wenxiangchao
4 天以前 559890c482f5973f06aafdfec9550fee5ba3c7f2
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
using System;
using System.Configuration;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using CanSimulator;
using log4net;
 
namespace Aging.Infrastructure.Drivers
{
    /// <summary>
    /// Local 传输后端:TCP 直连 CanSimulatorServer,握手 HELLO 挂载 (bus,nodeIndex),
    /// 命令串经 TransceiveAsync 一问一答,接收帧由服务端 EV:RECV 主动推送触发 FramePushed。
    /// </summary>
    internal sealed class NodeChannelTransport : ICanTransport
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(NodeChannelTransport));
 
        private readonly string _host;
        private readonly int _port;
        private readonly string _clientTag;
 
        private TcpClient _socket;
        private Stream _stream;
        private CancellationTokenSource _cts;
        private Task _readLoop;
 
        // 一问一答:同一时刻仅一个在途请求
        private readonly SemaphoreSlim _requestLock = new(1, 1);
        private TaskCompletionSource<string> _pending;
 
        private volatile bool _connected;
        private bool _disposed;
        private string _busName;
        private int _nodeIndex = -1;
 
        public bool IsConnected => _connected;
        public event Action<string> FramePushed;
        public event Action TransportBroken;
 
        public NodeChannelTransport(string hostOverride, int? portOverride, string clientTag)
        {
            _host = hostOverride ?? ReadCfg("CanSimulator.Host", "127.0.0.1");
            _port = portOverride ?? ReadIntCfg("CanSimulator.Port", 9000);
            _clientTag = clientTag ?? $"{Environment.MachineName}/{System.Diagnostics.Process.GetCurrentProcess().Id}";
        }
 
        private static string ReadCfg(string key, string def)
        {
            try { var v = ConfigurationManager.AppSettings[key]; return string.IsNullOrWhiteSpace(v) ? def : v; }
            catch { return def; }
        }
        private static int ReadIntCfg(string key, int def)
            => int.TryParse(ReadCfg(key, null), out int v) ? v : def;
 
        public async Task ConnectAsync(string busName, int nodeIndex, CancellationToken ct)
        {
            if (_disposed) throw new ObjectDisposedException(nameof(NodeChannelTransport));
            _busName = busName;
            _nodeIndex = nodeIndex;
 
            try
            {
                _socket = new TcpClient();
                await _socket.ConnectAsync(_host, _port).ConfigureAwait(false);
                _socket.NoDelay = true;
                _stream = _socket.GetStream();
                _cts = new CancellationTokenSource();
 
                // HELLO 握手:读循环启动前同步直读一行响应(此时无并发推送)
                string ack = await HandshakeAsync(
                    $"HELLO:{busName}:{nodeIndex}:{_clientTag}", ct).ConfigureAwait(false);
 
                if (ack == "ERR:NODE_BUSY")
                    throw new InvalidOperationException(
                        $"模拟器总线 {busName} 上节点编号 {nodeIndex} 已被占用,请修改设备端点的节点编号");
                if (!ack.StartsWith("OK:HELLO", StringComparison.Ordinal))
                    throw new InvalidOperationException($"模拟器握手失败: {ack}");
 
                _connected = true;
                _readLoop = Task.Run(() => ReadLoopAsync(_cts.Token));
                Log.Info($"[CAN-TCP] 已挂载 {busName}:N{nodeIndex} @ {_host}:{_port}");
            }
            catch (SocketException ex)
            {
                SafeCleanupSocket();
                throw new InvalidOperationException(
                    $"无法连接 CAN 模拟器服务 {_host}:{_port}({ex.Message})。请先启动 CanSimulatorServer.exe", ex);
            }
        }
 
        public async Task DisconnectAsync()
        {
            if (!_connected) return;
            try { await RequestLineAsync("DISCONNECT", CancellationToken.None).ConfigureAwait(false); }
            catch { /* 断开尽力而为 */ }
            Teardown();
        }
 
        public async Task<string> TransceiveAsync(string line, CancellationToken ct)
        {
            if (_disposed) throw new ObjectDisposedException(nameof(NodeChannelTransport));
            if (!_connected) throw new InvalidOperationException("CAN 通道未连接");
            try
            {
                return await RequestLineAsync(line, ct).ConfigureAwait(false);
            }
            catch (IOException ex)
            {
                OnBroken();
                throw new InvalidOperationException("CAN 模拟器连接已中断: " + ex.Message, ex);
            }
        }
 
        /// <summary>握手专用:写 HELLO 后直接同步读取一行响应(读循环尚未启动,无并发)。</summary>
        private async Task<string> HandshakeAsync(string helloLine, CancellationToken ct)
        {
            byte[] frame = SimulatorFraming.Encode(helloLine);
            await _stream.WriteAsync(frame, 0, frame.Length, ct).ConfigureAwait(false);
            await _stream.FlushAsync(ct).ConfigureAwait(false);
            string resp = await SimulatorFraming.ReadFrameAsync(_stream, ct).ConfigureAwait(false);
            return resp ?? "<EOF>";
        }
 
        /// <summary>发送一行并等待其响应行;EV:RECV 推送在此过程中被分流出去,不计为响应。</summary>
        private async Task<string> RequestLineAsync(string line, CancellationToken ct)
        {
            await _requestLock.WaitAsync(ct).ConfigureAwait(false);
            try
            {
                var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
                _pending = tcs;
 
                byte[] frame = SimulatorFraming.Encode(line);
                await _stream.WriteAsync(frame, 0, frame.Length, ct).ConfigureAwait(false);
                await _stream.FlushAsync(ct).ConfigureAwait(false);
 
                // deadline:默认 5s,超时视为结果未知(上层禁止假定未执行)
                var timeoutTask = Task.Delay(TimeSpan.FromSeconds(5), ct);
                var done = await Task.WhenAny(tcs.Task, timeoutTask).ConfigureAwait(false);
                if (done != tcs.Task)
                {
                    _pending = null;
                    throw new TimeoutException($"CAN 模拟器命令超时: {line}");
                }
                _pending = null;
                ct.ThrowIfCancellationRequested();
                return await tcs.Task.ConfigureAwait(false);
            }
            finally
            {
                _requestLock.Release();
            }
        }
 
        private async Task ReadLoopAsync(CancellationToken ct)
        {
            try
            {
                while (!ct.IsCancellationRequested)
                {
                    string resp = await SimulatorFraming.ReadFrameAsync(_stream, ct).ConfigureAwait(false);
                    if (resp == null) break; // EOF
 
                    if (resp.StartsWith("EV:", StringComparison.Ordinal))
                    {
                        FramePushed?.Invoke(resp);
                        continue;
                    }
 
                    // 普通响应:交给在途请求
                    _pending?.TrySetResult(resp);
                }
            }
            catch (IOException) { }
            catch (InvalidDataException) { }
            catch (OperationCanceledException) { }
            catch (Exception ex) { Log.Warn($"[CAN-TCP] 读循环异常: {ex.Message}"); }
            finally
            {
                if (!_disposed) OnBroken();
            }
        }
 
        private void OnBroken()
        {
            if (!_connected && _pending == null) return;
            _connected = false;
            _pending?.TrySetException(new IOException("CAN 模拟器通道已断开"));
            TransportBroken?.Invoke();
        }
 
        private void Teardown()
        {
            _connected = false;
            try { _cts?.Cancel(); } catch { }
            SafeCleanupSocket();
        }
 
        private void SafeCleanupSocket()
        {
            try { _stream?.Dispose(); } catch { }
            try { _socket?.Close(); } catch { }
            _stream = null;
            _socket = null;
        }
 
        public void Dispose()
        {
            if (_disposed) return;
            _disposed = true;
            Teardown();
            try { _readLoop?.Wait(200); } catch { }
            _requestLock.Dispose();
            _cts?.Dispose();
        }
    }
}