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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Aging.Infrastructure.Contracts;
using CanSimulator;
using log4net;
 
namespace Aging.Infrastructure.Drivers
{
    /// <summary>
    /// CAN 通讯驱动适配器。
    /// 封装 CanSimulator,实现统一的 IDeviceDriver 接口。
    /// 命令格式约定:
    ///   发送: "SEND:frameId:data"  如 "SEND:0x100:01 02 03 04"
    ///   查询:
    ///     "RECV"           - 获取接收邮箱中的下一帧
    ///     "RECV_ALL"       - 获取接收邮箱中的所有帧
    ///     "STATUS"         - 获取节点/总线状态
    ///     "FILTER:id:mask" - 设置接收滤波器
    ///     "FILTER_CLEAR"   - 清除所有滤波器
    ///     "PROMISCUOUS"    - 设置混杂模式(接收所有帧)
    ///     "LOG"            - 获取总线日志
    ///     "BUS_STATUS"     - 获取总线状态摘要
    /// </summary>
    public sealed class CanDriverAdapter : IDeviceDriver
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(CanDriverAdapter));
 
        /// <summary>
        /// 全局 CAN 总线模拟器实例(所有 CAN 驱动共享)
        /// </summary>
        private static readonly Dictionary<string, CanBusSimulator> _sharedBuses = new();
        private static readonly object _busLock = new();
 
        private readonly string _ip;      // 总线名称(用 ip 字段映射)
        private readonly int _port;       // 节点编号(用 port 字段映射)
        private CanBusSimulator? _bus;
        private CanNode? _node;
        private bool _disposed;
        private readonly Stopwatch _latencyStopwatch = new();
        private double _lastLatencyMs;
        private string _lastError = string.Empty;
        private DateTime? _lastErrorTime;
        private int _reconnectCount;
 
        /// <summary>
        /// 接收到的帧缓存(用于 RECV 查询)
        /// </summary>
        private readonly Queue<CanFrame> _recvBuffer = new();
 
        /// <inheritdoc/>
        public string DeviceId { get; }
 
        /// <inheritdoc/>
        public bool IsConnected => _node != null && _node.IsActive;
 
        /// <inheritdoc/>
        public event EventHandler<DeviceConnectionEventArgs>? ConnectionChanged;
 
        /// <summary>
        /// 初始化 CAN 驱动适配器
        /// </summary>
        /// <param name="deviceId">设备唯一标识符</param>
        /// <param name="busName">总线名称(如 CAN_BUS_1)</param>
        /// <param name="nodeIndex">节点编号(用于区分同一总线上的不同设备)</param>
        public CanDriverAdapter(string deviceId, string busName, int nodeIndex)
        {
            DeviceId = deviceId ?? throw new ArgumentNullException(nameof(deviceId));
            _ip = busName ?? "CAN_BUS_1";
            _port = nodeIndex;
        }
 
        /// <summary>
        /// 获取或创建共享总线
        /// </summary>
        private CanBusSimulator GetOrCreateBus(string busName)
        {
            lock (_busLock)
            {
                if (!_sharedBuses.TryGetValue(busName, out var bus))
                {
                    bus = new CanBusSimulator(busName);
                    _sharedBuses[busName] = bus;
                    Log.Info($"[CAN] 创建新的虚拟总线: {busName}");
                }
                return bus;
            }
        }
 
        /// <inheritdoc/>
        public Task ConnectAsync(CancellationToken ct)
        {
            ThrowIfDisposed();
            Log.Info($"[CAN] 设备 {DeviceId} 正在连接到总线 {_ip} (节点: {_port})...");
 
            try
            {
                // 获取或创建共享总线
                _bus = GetOrCreateBus(_ip);
 
                // 如果总线未启动,自动启动
                if (_bus.State != CanBusState.Running)
                {
                    _bus.Start();
                }
 
                // 注册节点
                string nodeId = $"{DeviceId}_node{_port}";
                _node = _bus.RegisterNode(nodeId, DeviceId);
 
                // 设置默认滤波器(接收所有帧)
                _node.SetPromiscuousMode();
 
                // 激活节点
                _node.Activate();
 
                // 订阅接收事件
                _node.FrameReceived += OnFrameReceived;
 
                _lastError = string.Empty;
                Log.Info($"[CAN] 设备 {DeviceId} 已成功连接到总线 {_ip} (节点: {_node.NodeId})");
                OnConnectionChanged(true, "连接成功");
            }
            catch (Exception ex)
            {
                _lastError = ex.Message;
                _lastErrorTime = DateTime.Now;
                Log.Error($"[CAN] 设备 {DeviceId} 连接异常: {ex.Message}", ex);
                _node?.Deactivate();
                _node = null;
                throw;
            }
 
            return Task.CompletedTask;
        }
 
        /// <inheritdoc/>
        public Task DisconnectAsync()
        {
            ThrowIfDisposed();
            Log.Info($"[CAN] 设备 {DeviceId} 正在断开连接...");
 
            try
            {
                if (_node != null)
                {
                    _node.FrameReceived -= OnFrameReceived;
                    _node.Deactivate();
                    _bus?.UnregisterNode(_node.NodeId);
                    _node = null;
                }
 
                Log.Info($"[CAN] 设备 {DeviceId} 已断开连接");
                OnConnectionChanged(false, "主动断开");
            }
            catch (Exception ex)
            {
                _lastError = ex.Message;
                _lastErrorTime = DateTime.Now;
                Log.Error($"[CAN] 设备 {DeviceId} 断开连接异常: {ex.Message}", ex);
                _node = null;
            }
 
            return Task.CompletedTask;
        }
 
        /// <inheritdoc/>
        public Task<string> SendCommandAsync(string command, CancellationToken ct)
        {
            ThrowIfDisposed();
            if (!IsConnected) throw new InvalidOperationException("[CAN] 设备未连接");
 
            _latencyStopwatch.Restart();
            try
            {
                Log.Debug($"[CAN] 设备 {DeviceId} 发送命令: {command}");
 
                // 解析命令格式: "SEND:frameId:data"
                string[] parts = command.Split(':');
                if (parts.Length < 3)
                {
                    throw new ArgumentException($"[CAN] 命令格式错误,应为 SEND:frameId:data,实际: {command}");
                }
 
                string operation = parts[0].ToUpper();
                if (operation != "SEND")
                {
                    throw new ArgumentException($"[CAN] 不支持的操作类型: {operation},应为 SEND");
                }
 
                // 解析帧 ID
                string frameIdStr = parts[1];
                uint frameId = CanFrame.ParseFrameId(frameIdStr);
 
                // 解析数据
                string dataStr = parts[2];
                byte[] data = CanFrame.ParseData(dataStr);
 
                // 验证数据长度
                if (data.Length > 8)
                {
                    throw new ArgumentException($"[CAN] 数据长度超限: {data.Length} 字节(最大 8 字节)");
                }
 
                // 创建并发送帧
                var frame = new CanFrame
                {
                    FrameId = frameId,
                    Format = frameId > 0x7FF ? CanFrameFormat.Extended : CanFrameFormat.Standard,
                    Type = CanFrameType.Data,
                    Data = data
                };
 
                _node!.SendFrame(frame);
 
                _latencyStopwatch.Stop();
                _lastLatencyMs = _latencyStopwatch.Elapsed.TotalMilliseconds;
 
                string response = $"OK:TX:{frame.FrameIdHex}:{frame.Dlc}";
                Log.Debug($"[CAN] 设备 {DeviceId} 发送成功 (延迟 {_lastLatencyMs:F2}ms): {response}");
                return Task.FromResult(response);
            }
            catch (Exception ex)
            {
                _latencyStopwatch.Stop();
                _lastLatencyMs = _latencyStopwatch.Elapsed.TotalMilliseconds;
                _lastError = ex.Message;
                _lastErrorTime = DateTime.Now;
                Log.Error($"[CAN] 设备 {DeviceId} 发送命令失败: {ex.Message}", ex);
                throw;
            }
        }
 
        /// <inheritdoc/>
        public Task<string> QueryAsync(string query, CancellationToken ct)
        {
            ThrowIfDisposed();
            if (!IsConnected) throw new InvalidOperationException("[CAN] 设备未连接");
 
            _latencyStopwatch.Restart();
            try
            {
                Log.Debug($"[CAN] 设备 {DeviceId} 查询: {query}");
 
                string[] parts = query.Split(':');
                string operation = parts[0].ToUpper();
 
                string response;
                switch (operation)
                {
                    case "RECV":
                        response = HandleRecv();
                        break;
 
                    case "RECV_ALL":
                        response = HandleRecvAll();
                        break;
 
                    case "STATUS":
                        response = HandleStatus();
                        break;
 
                    case "FILTER":
                        response = HandleFilter(parts);
                        break;
 
                    case "FILTER_CLEAR":
                        _node!.ClearFilters();
                        response = "OK:滤波器已清除";
                        break;
 
                    case "PROMISCUOUS":
                        _node!.SetPromiscuousMode();
                        response = "OK:混杂模式已启用";
                        break;
 
                    case "AUTO_RESPONSE":
                        response = HandleAutoResponse(parts);
                        break;
 
                    case "RESPONSE_DELAY":
                        response = HandleResponseDelay(parts);
                        break;
 
                    case "LOG":
                        response = HandleLog();
                        break;
 
                    case "BUS_STATUS":
                        response = _bus?.GetStatusSummary() ?? "总线未初始化";
                        break;
 
                    default:
                        throw new ArgumentException($"[CAN] 不支持的查询类型: {operation}");
                }
 
                _latencyStopwatch.Stop();
                _lastLatencyMs = _latencyStopwatch.Elapsed.TotalMilliseconds;
                Log.Debug($"[CAN] 设备 {DeviceId} 查询响应: {response} (延迟 {_lastLatencyMs:F2}ms)");
                return Task.FromResult(response);
            }
            catch (Exception ex)
            {
                _latencyStopwatch.Stop();
                _lastLatencyMs = _latencyStopwatch.Elapsed.TotalMilliseconds;
                _lastError = ex.Message;
                _lastErrorTime = DateTime.Now;
                Log.Error($"[CAN] 设备 {DeviceId} 查询失败: {ex.Message}", ex);
                throw;
            }
        }
 
        /// <summary>
        /// 处理 RECV 查询 - 获取下一帧
        /// </summary>
        private string HandleRecv()
        {
            // 先从缓冲区取
            if (_recvBuffer.Count > 0)
            {
                var frame = _recvBuffer.Dequeue();
                return $"RECV:{frame.FrameIdHex}:{frame.DataHex}:{frame.Timestamp:HH:mm:ss.fff}";
            }
 
            // 从节点邮箱取
            if (_node!.TryDequeueReceived(out var frame2))
            {
                return $"RECV:{frame2!.FrameIdHex}:{frame2.DataHex}:{frame2.Timestamp:HH:mm:ss.fff}";
            }
 
            return "RECV:EMPTY";
        }
 
        /// <summary>
        /// 处理 RECV_ALL 查询 - 获取所有帧
        /// </summary>
        private string HandleRecvAll()
        {
            var frames = new List<string>();
 
            // 先取缓冲区
            while (_recvBuffer.Count > 0)
            {
                var f = _recvBuffer.Dequeue();
                frames.Add($"{f.FrameIdHex}:{f.DataHex}");
            }
 
            // 再取节点邮箱
            var mailbox = _node!.PeekReceiveMailbox();
            _node.ClearReceiveMailbox();
            foreach (var f in mailbox)
            {
                frames.Add($"{f.FrameIdHex}:{f.DataHex}:{f.Timestamp:HH:mm:ss.fff}");
            }
 
            return frames.Count > 0 ? $"RECV_ALL:{frames.Count}:{string.Join("|", frames)}" : "RECV_ALL:0";
        }
 
        /// <summary>
        /// 处理 STATUS 查询
        /// </summary>
        private string HandleStatus()
        {
            var nodeStatus = _node?.GetStatusSummary() ?? "节点未初始化";
            var busStatus = _bus?.GetStatusSummary() ?? "总线未初始化";
            return $"STATUS:{nodeStatus}|{busStatus}";
        }
 
        /// <summary>
        /// 处理 FILTER 设置
        /// </summary>
        private string HandleFilter(string[] parts)
        {
            if (parts.Length < 3)
            {
                throw new ArgumentException("[CAN] FILTER 命令格式错误,应为 FILTER:id:mask");
            }
 
            uint filterId = CanFrame.ParseFrameId(parts[1]);
            uint mask = CanFrame.ParseFrameId(parts[2]);
 
            _node!.AddFilter(new AcceptanceFilter
            {
                FilterId = filterId,
                Mask = mask,
                IsExtended = filterId > 0x7FF
            });
 
            return $"OK:滤波器已添加 ID=0x{filterId:X3}, Mask=0x{mask:X3}";
        }
 
        /// <summary>
        /// 处理 AUTO_RESPONSE 命令
        /// 格式: AUTO_RESPONSE:on|off
        /// </summary>
        private string HandleAutoResponse(string[] parts)
        {
            if (parts.Length < 2)
            {
                // 查询当前状态
                bool current = _node!.AutoResponseEnabled;
                return $"AUTO_RESPONSE:{(current ? "ON" : "OFF")}";
            }
 
            string mode = parts[1].Trim().ToUpper();
            switch (mode)
            {
                case "ON":
                case "1":
                case "TRUE":
                case "ENABLE":
                    _node!.AutoResponseEnabled = true;
                    Log.Info($"[CAN] 设备 {DeviceId} 启用自动响应模式");
                    return "OK:自动响应模式已启用";
 
                case "OFF":
                case "0":
                case "FALSE":
                case "DISABLE":
                    _node!.AutoResponseEnabled = false;
                    Log.Info($"[CAN] 设备 {DeviceId} 禁用自动响应模式");
                    return "OK:自动响应模式已禁用";
 
                default:
                    throw new ArgumentException($"[CAN] AUTO_RESPONSE 参数错误: {mode},应为 on/off");
            }
        }
 
        /// <summary>
        /// 处理 RESPONSE_DELAY 命令
        /// 格式: RESPONSE_DELAY:毫秒数
        /// </summary>
        private string HandleResponseDelay(string[] parts)
        {
            if (parts.Length < 2)
            {
                // 查询当前延迟
                return $"RESPONSE_DELAY:{_node!.AutoResponseDelayMs}ms";
            }
 
            if (!int.TryParse(parts[1].Trim(), out int delayMs) || delayMs < 0)
            {
                throw new ArgumentException($"[CAN] RESPONSE_DELAY 参数错误: {parts[1]},应为非负整数(毫秒)");
            }
 
            _node!.AutoResponseDelayMs = delayMs;
            Log.Info($"[CAN] 设备 {DeviceId} 设置响应延迟: {delayMs}ms");
            return $"OK:响应延迟已设置为 {delayMs}ms";
        }
 
        /// <summary>
        /// 处理 LOG 查询
        /// </summary>
        private string HandleLog()
        {
            var log = _bus?.GetBusLog(50) ?? new List<CanFrame>();
            if (log.Count == 0) return "LOG:EMPTY";
 
            var entries = log.Select(f =>
                $"[{f.Timestamp:HH:mm:ss.fff}]{f.SourceNodeId}>{f.FrameIdHex}:{f.DataHex}");
            return $"LOG:{log.Count}:{string.Join("|", entries)}";
        }
 
        /// <summary>
        /// 帧接收事件(公开给外部订阅)
        /// </summary>
        public event EventHandler<CanFrame>? DriverFrameReceived;
 
        /// <summary>
        /// 帧接收事件处理
        /// </summary>
        private void OnFrameReceived(object? sender, CanFrame frame)
        {
            // 放入接收缓冲区(用于 RECV/RECV_ALL 查询)
            while (_recvBuffer.Count >= 1000)
            {
                _recvBuffer.Dequeue();
            }
            _recvBuffer.Enqueue(frame);
 
            // 触发公开事件(用于即时显示)
            DriverFrameReceived?.Invoke(this, frame);
        }
 
        /// <inheritdoc/>
        public DeviceDriverStatus GetStatus()
        {
            return new DeviceDriverStatus
            {
                IsConnected = IsConnected,
                IsHealthy = IsConnected && string.IsNullOrEmpty(_lastError),
                LastError = _lastError,
                LastErrorTime = _lastErrorTime,
                LatencyMs = _lastLatencyMs,
                ReconnectCount = _reconnectCount
            };
        }
 
        /// <inheritdoc/>
        public void Dispose()
        {
            if (_disposed) return;
            _disposed = true;
 
            try
            {
                if (_node != null)
                {
                    _node.FrameReceived -= OnFrameReceived;
                    _node.Deactivate();
                    _bus?.UnregisterNode(_node.NodeId);
                }
            }
            catch (Exception ex)
            {
                Log.Error($"[CAN] 设备 {DeviceId} 释放资源异常: {ex.Message}", ex);
            }
        }
 
        /// <summary>
        /// 触发所有总线和节点(用于测试清理)
        /// </summary>
        public static void ResetAllBuses()
        {
            lock (_busLock)
            {
                foreach (var bus in _sharedBuses.Values)
                {
                    bus.Dispose();
                }
                _sharedBuses.Clear();
                Log.Info("[CAN] 所有虚拟总线已重置");
            }
        }
 
        /// <summary>
        /// 触发所有总线实例(供外部查询)
        /// </summary>
        public static IReadOnlyDictionary<string, CanBusSimulator> GetAllBuses()
        {
            lock (_busLock)
            {
                return new Dictionary<string, CanBusSimulator>(_sharedBuses);
            }
        }
 
        /// <summary>
        /// 触发连接状态变化事件
        /// </summary>
        private void OnConnectionChanged(bool isConnected, string reason)
        {
            ConnectionChanged?.Invoke(this, new DeviceConnectionEventArgs
            {
                DeviceId = DeviceId,
                IsConnected = isConnected,
                Reason = reason
            });
 
            if (!isConnected)
            {
                _reconnectCount++;
            }
        }
 
        /// <summary>
        /// 检查是否已释放
        /// </summary>
        private void ThrowIfDisposed()
        {
            if (_disposed) throw new ObjectDisposedException(nameof(CanDriverAdapter));
        }
    }
}