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
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using log4net;
 
namespace CanSimulator
{
    /// <summary>
    /// CAN 总线状态
    /// </summary>
    public enum CanBusState
    {
        /// <summary>停止状态</summary>
        Stopped,
        /// <summary>运行中</summary>
        Running,
        /// <summary>暂停</summary>
        Paused,
        /// <summary>错误</summary>
        Error
    }
 
    /// <summary>
    /// CAN 总线模拟器事件参数
    /// </summary>
    public sealed class CanBusFrameEventArgs : EventArgs
    {
        public CanFrame Frame { get; }
        public string SourceNodeId { get; }
 
        public CanBusFrameEventArgs(CanFrame frame, string sourceNodeId)
        {
            Frame = frame;
            SourceNodeId = sourceNodeId;
        }
    }
 
    /// <summary>
    /// CAN 总线模拟器
    /// 模拟一条虚拟 CAN 总线,多个虚拟节点可以挂载到总线上进行通讯
    /// </summary>
    public sealed class CanBusSimulator : IDisposable
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(CanBusSimulator));
 
        /// <summary>
        /// 总线名称
        /// </summary>
        public string BusName { get; }
 
        /// <summary>
        /// 总线状态
        /// </summary>
        public CanBusState State { get; private set; } = CanBusState.Stopped;
 
        /// <summary>
        /// 波特率(仅用于模拟显示,不影响实际逻辑)
        /// </summary>
        public int BaudRate { get; set; } = 500000; // 默认 500kbps
 
        /// <summary>
        /// 模拟延迟(毫秒)- 模拟真实总线传输延迟
        /// </summary>
        public int SimulatedLatencyMs { get; set; } = 0;
 
        /// <summary>
        /// 已注册的节点
        /// </summary>
        private readonly ConcurrentDictionary<string, CanNode> _nodes = new();
 
        /// <summary>
        /// 总线日志(最近 N 条帧)
        /// </summary>
        private readonly ConcurrentQueue<CanFrame> _busLog = new();
        private int _maxLogSize = 5000;
 
        /// <summary>
        /// 总线统计
        /// </summary>
        public long TotalFramesTransmitted { get; private set; }
        public long TotalFramesReceived { get; private set; }
        public DateTime? LastActivityTime { get; private set; }
 
        /// <summary>
        /// 帧在总线上传输事件(可用于监控/日志)
        /// </summary>
        public event EventHandler<CanBusFrameEventArgs>? FrameTransmitted;
 
        /// <summary>
        /// 总线状态变化事件
        /// </summary>
        public event EventHandler<CanBusState>? StateChanged;
 
        public CanBusSimulator(string busName = "CAN_BUS_1")
        {
            BusName = busName ?? throw new ArgumentNullException(nameof(busName));
        }
 
        /// <summary>
        /// 启动总线
        /// </summary>
        public void Start()
        {
            if (State == CanBusState.Running)
            {
                Log.Warn($"[CanBus] 总线 {BusName} 已在运行中");
                return;
            }
 
            State = CanBusState.Running;
            Log.Info($"[CanBus] 总线 {BusName} 已启动 (波特率: {BaudRate}bps)");
            StateChanged?.Invoke(this, State);
        }
 
        /// <summary>
        /// 停止总线
        /// </summary>
        public void Stop()
        {
            if (State == CanBusState.Stopped) return;
 
            State = CanBusState.Stopped;
            Log.Info($"[CanBus] 总线 {BusName} 已停止");
            StateChanged?.Invoke(this, State);
        }
 
        /// <summary>
        /// 暂停总线(帧仍在保留但不路由)
        /// </summary>
        public void Pause()
        {
            if (State != CanBusState.Running) return;
 
            State = CanBusState.Paused;
            Log.Info($"[CanBus] 总线 {BusName} 已暂停");
            StateChanged?.Invoke(this, State);
        }
 
        /// <summary>
        /// 恢复总线
        /// </summary>
        public void Resume()
        {
            if (State != CanBusState.Paused) return;
 
            State = CanBusState.Running;
            Log.Info($"[CanBus] 总线 {BusName} 已恢复");
            StateChanged?.Invoke(this, State);
        }
 
        /// <summary>
        /// 注册节点到总线
        /// </summary>
        public CanNode RegisterNode(string nodeId, string? name = null)
        {
            if (string.IsNullOrWhiteSpace(nodeId))
                throw new ArgumentException("节点 ID 不能为空", nameof(nodeId));
 
            var node = new CanNode(nodeId, name);
            node.FrameSent += OnNodeFrameSent;
 
            if (!_nodes.TryAdd(nodeId, node))
            {
                Log.Warn($"[CanBus] 节点 {nodeId} 已存在,将被替换");
                _nodes.TryRemove(nodeId, out var oldNode);
                oldNode?.Deactivate();
                _nodes.TryAdd(nodeId, node);
            }
 
            // 如果总线已运行,自动激活节点
            if (State == CanBusState.Running)
            {
                node.Activate();
            }
 
            Log.Info($"[CanBus] 节点 {nodeId} ({name ?? nodeId}) 已注册到总线 {BusName}");
            return node;
        }
 
        /// <summary>
        /// 注销节点
        /// </summary>
        public bool UnregisterNode(string nodeId)
        {
            if (_nodes.TryRemove(nodeId, out var node))
            {
                node.FrameSent -= OnNodeFrameSent;
                node.Deactivate();
                Log.Info($"[CanBus] 节点 {nodeId} 已从总线 {BusName} 注销");
                return true;
            }
            return false;
        }
 
        /// <summary>
        /// 获取节点
        /// </summary>
        public CanNode? GetNode(string nodeId)
        {
            _nodes.TryGetValue(nodeId, out var node);
            return node;
        }
 
        /// <summary>
        /// 获取所有已注册节点
        /// </summary>
        public IReadOnlyList<CanNode> GetAllNodes()
        {
            return _nodes.Values.ToList();
        }
 
        /// <summary>
        /// 向总线发送帧(由节点发送,总线负责路由)
        /// </summary>
        private void OnNodeFrameSent(object? sender, CanFrame frame)
        {
            if (State != CanBusState.Running) return;
 
            // 模拟延迟
            if (SimulatedLatencyMs > 0)
            {
                Thread.Sleep(SimulatedLatencyMs);
            }
 
            // 记录到总线日志
            while (_busLog.Count >= _maxLogSize)
            {
                _busLog.TryDequeue(out _);
            }
            _busLog.Enqueue(frame);
            TotalFramesTransmitted++;
            LastActivityTime = DateTime.Now;
 
            // 路由到所有其他节点
            int routed = 0;
            foreach (var kvp in _nodes)
            {
                if (kvp.Key == frame.SourceNodeId) continue; // 不路由回源节点
 
                try
                {
                    kvp.Value.ReceiveFrame(frame);
                    routed++;
                    TotalFramesReceived++;
                }
                catch (Exception ex)
                {
                    Log.Error($"[CanBus] 路由帧到节点 {kvp.Key} 失败: {ex.Message}");
                }
            }
 
            // 检查源节点是否启用自动响应模式
            if (_nodes.TryGetValue(frame.SourceNodeId, out var sourceNode) && sourceNode.AutoResponseEnabled)
            {
                try
                {
                    // 模拟响应延迟
                    if (sourceNode.AutoResponseDelayMs > 0)
                    {
                        Thread.Sleep(sourceNode.AutoResponseDelayMs);
                    }
 
                    // 创建响应帧(复制原始帧数据,来源为源节点)
                    var responseFrame = new CanFrame
                    {
                        FrameId = frame.FrameId,
                        Format = frame.Format,
                        Type = frame.Type,
                        Data = (byte[])frame.Data.Clone(),
                        SourceNodeId = sourceNode.NodeId,
                        Timestamp = DateTime.Now
                    };
 
                    // 将响应帧路由到所有其他节点(不包括响应源自身)
                    foreach (var kvp in _nodes)
                    {
                        if (kvp.Key == sourceNode.NodeId) continue;
                        try
                        {
                            kvp.Value.ReceiveFrame(responseFrame);
                            TotalFramesReceived++;
                        }
                        catch (Exception ex)
                        {
                            Log.Error($"[CanBus] 路由响应帧到节点 {kvp.Key} 失败: {ex.Message}");
                        }
                    }
 
                    // 将响应帧送入源节点的接收邮箱(让源节点能看到自己的响应)
                    sourceNode.ReceiveFrame(responseFrame);
                    TotalFramesReceived++;
 
                    // 记录响应帧到总线日志
                    _busLog.Enqueue(responseFrame);
                    TotalFramesTransmitted++;
 
                    Log.Debug($"[CanBus] 节点 {sourceNode.NodeId} 自动响应帧 {responseFrame.FrameIdHex}");
                }
                catch (Exception ex)
                {
                    Log.Error($"[CanBus] 源节点自动响应失败: {ex.Message}");
                }
            }
 
            Log.Debug($"[CanBus] 帧 {frame.FrameIdHex} 从 {frame.SourceNodeId} 路由到 {routed} 个节点");
            FrameTransmitted?.Invoke(this, new CanBusFrameEventArgs(frame, frame.SourceNodeId));
        }
 
        /// <summary>
        /// 直接注入帧到总线(用于模拟外部设备发送)
        /// </summary>
        public void InjectFrame(CanFrame frame)
        {
            if (State != CanBusState.Running)
            {
                Log.Warn($"[CanBus] 总线未运行,无法注入帧");
                return;
            }
 
            frame.Timestamp = DateTime.Now;
 
            // 记录到日志
            while (_busLog.Count >= _maxLogSize)
            {
                _busLog.TryDequeue(out _);
            }
            _busLog.Enqueue(frame);
            TotalFramesTransmitted++;
            LastActivityTime = DateTime.Now;
 
            // 路由到所有节点
            foreach (var kvp in _nodes)
            {
                try
                {
                    kvp.Value.ReceiveFrame(frame);
                    TotalFramesReceived++;
                }
                catch (Exception ex)
                {
                    Log.Error($"[CanBus] 注入帧路由到节点 {kvp.Key} 失败: {ex.Message}");
                }
            }
 
            FrameTransmitted?.Invoke(this, new CanBusFrameEventArgs(frame, frame.SourceNodeId));
            Log.Debug($"[CanBus] 注入帧 {frame.FrameIdHex} 到总线");
        }
 
        /// <summary>
        /// 获取总线日志
        /// </summary>
        public List<CanFrame> GetBusLog(int maxCount = 100)
        {
            var all = _busLog.ToList();
            if (all.Count <= maxCount) return all;
            return all.Skip(all.Count - maxCount).ToList();
        }
 
        /// <summary>
        /// 清空总线日志
        /// </summary>
        public void ClearBusLog()
        {
            while (_busLog.TryDequeue(out _)) { }
        }
 
        /// <summary>
        /// 重置所有统计
        /// </summary>
        public void ResetStatistics()
        {
            TotalFramesTransmitted = 0;
            TotalFramesReceived = 0;
            LastActivityTime = null;
            foreach (var node in _nodes.Values)
            {
                node.ResetCounters();
            }
        }
 
        /// <summary>
        /// 获取总线状态摘要
        /// </summary>
        public string GetStatusSummary()
        {
            return $"Bus={BusName}, State={State}, BaudRate={BaudRate}, Nodes={_nodes.Count}, " +
                   $"Tx={TotalFramesTransmitted}, Rx={TotalFramesReceived}, " +
                   $"LastActivity={LastActivityTime?.ToString("HH:mm:ss") ?? "N/A"}";
        }
 
        public void Dispose()
        {
            Stop();
            foreach (var node in _nodes.Values)
            {
                node.Deactivate();
            }
            _nodes.Clear();
        }
    }
}