wenxiangchao
4 天以前 2e889843b4c171f2d6ad8e0d53084040703d11f6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
using System.Collections.Concurrent;
using Aging.Infrastructure.Contracts;
using log4net;
 
namespace Aging.Infrastructure.Core
{
    /// <summary>
    /// 设备管理实现。
    /// 提供设备驱动的注册、连接管理和状态查询功能。
    /// 使用 ConcurrentDictionary 管理驱动实例和缓存状态。
    /// </summary>
    public sealed class DeviceManager : IDeviceManager
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(DeviceManager));
 
        /// <summary>
        /// 设备驱动字典(key = deviceId)
        /// </summary>
        private readonly ConcurrentDictionary<string, IDeviceDriver> _drivers = new();
 
        /// <summary>
        /// 设备状态缓存字典(key = deviceId)
        /// </summary>
        private readonly ConcurrentDictionary<string, DeviceDriverStatus> _statusCache = new();
 
        /// <inheritdoc/>
        public void RegisterDriver(string deviceId, IDeviceDriver driver)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
                throw new ArgumentException("设备ID不能为空", nameof(deviceId));
            if (driver == null) throw new ArgumentNullException(nameof(driver));
 
            if (_drivers.ContainsKey(deviceId))
            {
                Log.Warn($"[DeviceManager] 设备 {deviceId} 已注册,将覆盖现有驱动");
                UnregisterDriver(deviceId);
            }
 
            _drivers[deviceId] = driver;
 
            // 初始化状态缓存
            var initialStatus = driver.GetStatus();
            _statusCache[deviceId] = initialStatus;
 
            // 订阅连接状态变化事件
            driver.ConnectionChanged += OnConnectionChanged;
 
            Log.Info($"[DeviceManager] 设备 {deviceId} 驱动注册成功,当前连接状态: {initialStatus.IsConnected}");
        }
 
        /// <inheritdoc/>
        public void UnregisterDriver(string deviceId)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
                throw new ArgumentException("设备ID不能为空", nameof(deviceId));
 
            if (_drivers.TryRemove(deviceId, out var driver))
            {
                // 取消事件订阅
                driver.ConnectionChanged -= OnConnectionChanged;
 
                // 清理状态缓存
                _statusCache.TryRemove(deviceId, out _);
 
                Log.Info($"[DeviceManager] 设备 {deviceId} 驱动已注销");
            }
            else
            {
                Log.Warn($"[DeviceManager] 尝试注销不存在的设备: {deviceId}");
            }
        }
 
        /// <inheritdoc/>
        public IDeviceDriver? GetDriver(string deviceId)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
                throw new ArgumentException("设备ID不能为空", nameof(deviceId));
 
            _drivers.TryGetValue(deviceId, out var driver);
            return driver;
        }
 
        /// <inheritdoc/>
        public DeviceDriverStatus GetStatus(string deviceId)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
                throw new ArgumentException("设备ID不能为空", nameof(deviceId));
 
            if (_statusCache.TryGetValue(deviceId, out var status))
            {
                return status;
            }
 
            // 如果缓存中没有,返回默认状态
            Log.Warn($"[DeviceManager] 设备 {deviceId} 状态缓存不存在,返回默认状态");
            return new DeviceDriverStatus
            {
                IsConnected = false,
                IsHealthy = false,
                LastError = "设备未注册或状态未初始化"
            };
        }
 
        /// <inheritdoc/>
        public async Task ConnectAsync(string deviceId, CancellationToken ct)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
                throw new ArgumentException("设备ID不能为空", nameof(deviceId));
 
            if (!_drivers.TryGetValue(deviceId, out var driver))
            {
                throw new InvalidOperationException($"设备 {deviceId} 未注册驱动");
            }
 
            try
            {
                Log.Info($"[DeviceManager] 正在连接设备: {deviceId}");
                await driver.ConnectAsync(ct).ConfigureAwait(false);
 
                // 更新状态缓存
                _statusCache[deviceId] = driver.GetStatus();
 
                Log.Info($"[DeviceManager] 设备 {deviceId} 连接成功");
            }
            catch (Exception ex)
            {
                // 更新错误状态
                if (_statusCache.TryGetValue(deviceId, out var status))
                {
                    status.IsConnected = false;
                    status.IsHealthy = false;
                    status.LastError = ex.Message;
                    status.LastErrorTime = DateTime.UtcNow;
                    _statusCache[deviceId] = status;
                }
 
                Log.Error($"[DeviceManager] 设备 {deviceId} 连接失败: {ex.Message}", ex);
                throw;
            }
        }
 
        /// <inheritdoc/>
        public async Task DisconnectAsync(string deviceId)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
                throw new ArgumentException("设备ID不能为空", nameof(deviceId));
 
            if (!_drivers.TryGetValue(deviceId, out var driver))
            {
                Log.Warn($"[DeviceManager] 尝试断开未注册的设备: {deviceId}");
                return;
            }
 
            try
            {
                Log.Info($"[DeviceManager] 正在断开设备: {deviceId}");
                await driver.DisconnectAsync().ConfigureAwait(false);
 
                // 更新状态缓存
                _statusCache[deviceId] = driver.GetStatus();
 
                Log.Info($"[DeviceManager] 设备 {deviceId} 已断开连接");
            }
            catch (Exception ex)
            {
                Log.Error($"[DeviceManager] 设备 {deviceId} 断开连接失败: {ex.Message}", ex);
                throw;
            }
        }
 
        /// <inheritdoc/>
        public IReadOnlyList<string> GetRegisteredDevices()
        {
            return _drivers.Keys.ToList().AsReadOnly();
        }
 
        /// <inheritdoc/>
        public bool IsDeviceRegistered(string deviceId)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
                return false;
 
            return _drivers.ContainsKey(deviceId);
        }
 
        /// <summary>
        /// 处理设备连接状态变化事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void OnConnectionChanged(object? sender, DeviceConnectionEventArgs e)
        {
            var deviceId = e.DeviceId;
 
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                Log.Warn("[DeviceManager] 收到连接变化事件但 DeviceId 为空");
                return;
            }
 
            if (_statusCache.TryGetValue(deviceId, out var status))
            {
                status.IsConnected = e.IsConnected;
                if (!e.IsConnected)
                {
                    status.IsHealthy = false;
                    if (!string.IsNullOrEmpty(e.Reason))
                    {
                        status.LastError = e.Reason;
                        status.LastErrorTime = DateTime.UtcNow;
                    }
                }
                else
                {
                    status.IsHealthy = true;
                    status.LastError = "";
                }
 
                _statusCache[deviceId] = status;
 
                Log.Info($"[DeviceManager] 设备 {deviceId} 连接状态变化: {(e.IsConnected ? "已连接" : "已断开")}" +
                        (string.IsNullOrEmpty(e.Reason) ? "" : $", 原因: {e.Reason}"));
            }
        }
    }
}