-
Notifications
You must be signed in to change notification settings - Fork 189
/
HsmsConnection.cs
571 lines (519 loc) · 19.4 KB
/
HsmsConnection.cs
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
using CommunityToolkit.HighPerformance.Buffers;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using PooledAwait;
using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
namespace Secs4Net;
#if NET
[UnsupportedOSPlatform("browser")]
#endif
public sealed class HsmsConnection : BackgroundService, ISecsConnection, IAsyncDisposable
{
public event EventHandler<ConnectionState>? ConnectionChanged;
public int T5 { get; }
public int T6 { get; }
public int T7 { get; }
public int T8 { get; }
public int LinkTestInterval { get; }
public bool LinkTestEnabled
{
get => _linkTestEnable;
set
{
if (_linkTestEnable == value)
{
return;
}
_linkTestEnable = value;
if (_linkTestEnable)
{
_timerLinkTest.Change(0, LinkTestInterval);
}
else
{
_timerLinkTest.Change(Timeout.Infinite, Timeout.Infinite);
}
}
}
private bool _linkTestEnable;
public ConnectionState State { get; private set; }
public bool IsActive { get; }
public IPAddress IpAddress { get; }
public int Port { get; }
public string DeviceIpAddress
=> IsActive
? IpAddress.ToString()
: ((IPEndPoint?)_socket?.RemoteEndPoint)?.Address?.ToString() ?? "NA";
private Socket? _socket;
private const int DisposalNotStarted = 0;
private const int DisposalComplete = 1;
private int _disposeStage;
public bool IsDisposed
=> Interlocked.CompareExchange(ref _disposeStage, DisposalComplete, DisposalComplete) == DisposalComplete;
private readonly Func<CancellationToken, Task> _startImpl;
private readonly Action _stopImpl;
private readonly Timer _timer7;
private readonly Timer _timer8;
private readonly Timer _timerLinkTest;
private readonly ConcurrentDictionary<int, ValueTaskCompletionSource<MessageType>> _replyExpectedMsgs = new();
private readonly int _socketReceiveBufferSize;
#if NETSTANDARD
private readonly byte[] _socketReceiveBuffer;
#endif
private readonly ISecsGemLogger _logger;
private readonly PipeDecoder _pipeDecoder;
private readonly Pipe _pipe;
private readonly SemaphoreSlim _sendLock = new(initialCount: 1);
private CancellationToken _stoppingToken;
private CancellationTokenSource? _cancellationTokenSourceForPipeDecoder;
private readonly CancellationTokenSource _cancellationSourceForControlMessageProcessing = new();
public HsmsConnection(IOptions<SecsGemOptions> secsGemOptions, ISecsGemLogger logger)
{
var pipe = new Pipe(new PipeOptions(useSynchronizationContext: true));
_pipeDecoder = new PipeDecoder(pipe.Reader, pipe.Writer);
_pipe = pipe;
_logger = logger;
var options = secsGemOptions.Value;
T5 = options.T5;
T6 = options.T6;
T7 = options.T7;
T8 = options.T8;
LinkTestInterval = options.LinkTestInterval;
IpAddress = IPAddress.Parse(options.IpAddress);
Port = options.Port;
IsActive = options.IsActive;
_socketReceiveBufferSize = options.SocketReceiveBufferSize;
#if NETSTANDARD
_socketReceiveBuffer = new byte[_socketReceiveBufferSize];
#endif
Task.Run(() => HandleControlMessagesAsync(_cancellationSourceForControlMessageProcessing.Token), _cancellationSourceForControlMessageProcessing.Token);
_timer7 = new Timer(delegate
{
_logger.Error($"T7 Timeout: {T7 / 1000} sec.");
CommunicationStateChanging(ConnectionState.Retry);
}, null, Timeout.Infinite, Timeout.Infinite);
_timer8 = new Timer(delegate
{
_logger.Error($"T8 Timeout: {T8 / 1000} sec.");
CommunicationStateChanging(ConnectionState.Retry);
}, null, Timeout.Infinite, Timeout.Infinite);
_timerLinkTest = new Timer(delegate
{
#if !DISABLE_TIMER
if (State == ConnectionState.Selected)
{
_ = SendLinkTestAsync();
}
async FireAndForget SendLinkTestAsync() => await SendControlMessage(MessageType.LinkTestRequest, MessageIdGenerator.NewId()).ConfigureAwait(false);
#endif
}, null, Timeout.Infinite, Timeout.Infinite);
if (IsActive)
{
_startImpl = async cancellation =>
{
var connected = false;
do
{
if (IsDisposed)
{
return;
}
CommunicationStateChanging(ConnectionState.Connecting);
try
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
Blocking = false,
ReceiveBufferSize = _socketReceiveBufferSize,
};
#if NET
await socket.ConnectAsync(IpAddress, Port, cancellation).ConfigureAwait(false);
#else
await socket.ConnectAsync(IpAddress, Port).WithCancellation(cancellation).ConfigureAwait(false);
#endif
_socket = socket;
CommunicationStateChanging(ConnectionState.Connected);
connected = true;
}
catch (Exception ex) when (!IsDisposed)
{
_logger.Error(ex.Message);
_logger.Info($"Start T5 Timer: {T5 / 1000} sec.");
await Task.Delay(T5, cancellation).ConfigureAwait(false);
}
} while (!connected);
await SendControlMessage(MessageType.SelectRequest, MessageIdGenerator.NewId(), cancellation).ConfigureAwait(false);
};
_stopImpl = delegate { };
}
else
{
var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
Blocking = false,
};
server.Bind(new IPEndPoint(IpAddress, Port));
server.Listen(0);
_startImpl = async cancellation =>
{
var connected = false;
do
{
if (IsDisposed)
{
return;
}
CommunicationStateChanging(ConnectionState.Connecting);
try
{
#if NET6_0
_socket = await server.AcceptAsync(cancellation).ConfigureAwait(false);
#else
_socket = await server.AcceptAsync().WithCancellation(cancellation).ConfigureAwait(false);
#endif
_socket.Blocking = false;
_socket.ReceiveBufferSize = _socketReceiveBufferSize;
CommunicationStateChanging(ConnectionState.Connected);
connected = true;
}
catch (Exception ex) when (!IsDisposed)
{
_logger.Error(ex.Message);
await Task.Delay(2000, cancellation).ConfigureAwait(false);
}
} while (!connected);
};
_stopImpl = delegate
{
if (IsDisposed)
{
server.Dispose();
}
};
}
}
private void Disconnect()
{
_timer7.Change(Timeout.Infinite, Timeout.Infinite);
_timer8.Change(Timeout.Infinite, Timeout.Infinite);
_timerLinkTest.Change(Timeout.Infinite, Timeout.Infinite);
StopPipeDecoder(ref _cancellationTokenSourceForPipeDecoder);
_stopImpl.Invoke();
if (_socket is null)
{
return;
}
if (_socket.Connected)
{
_socket.Shutdown(SocketShutdown.Both);
}
_socket.Dispose();
_socket = null;
}
protected sealed override Task ExecuteAsync(CancellationToken stoppingToken)
{
_stoppingToken = stoppingToken;
Start(_stoppingToken);
return Task.CompletedTask;
}
private void Start(CancellationToken cancellation)
=> Task.Run(() => _startImpl(cancellation), cancellation);
private async Task StartPipeDecoderConsumerAsync(CancellationToken cancellation)
{
try
{
await _pipeDecoder.StartAsync(cancellation).ConfigureAwait(false);
}
catch (Exception ex)
{
if (cancellation.IsCancellationRequested)
{
return;
}
_logger.Error("Unexpected exception on StartAsyncStreamDecoderAsync", ex);
Reconnect();
}
}
private async Task StartPipeDecoderProducerAsync(CancellationToken cancellation)
{
var decoderInput = _pipeDecoder.Input;
try
{
while (true)
{
#if DEBUG
Debug.Assert(_socket != null);
#endif
#if NET
var memory = decoderInput.GetMemory(_socketReceiveBufferSize);
var count = await _socket!.ReceiveAsync(memory, SocketFlags.None, cancellation).ConfigureAwait(false);
decoderInput.Advance(count);
await decoderInput.FlushAsync(cancellation).ConfigureAwait(false);
#else
var count = await _socket!.ReceiveAsync(new ArraySegment<byte>(_socketReceiveBuffer), SocketFlags.None).WithCancellation(cancellation).ConfigureAwait(false); ;
await decoderInput.WriteAsync(_socketReceiveBuffer.AsMemory()[..count], cancellation).ConfigureAwait(false);
#endif
}
}
catch (Exception ex)
{
if (cancellation.IsCancellationRequested)
{
return;
}
_logger.Error("Unhandled exception occurred on PipeDecoder producer", ex);
Reconnect();
}
}
private void StopPipeDecoder(ref CancellationTokenSource? cancellationTokenSource)
{
if (cancellationTokenSource is { IsCancellationRequested: false })
{
cancellationTokenSource.Cancel();
cancellationTokenSource.Dispose();
cancellationTokenSource = null;
_pipe.Reader.Complete();
_pipe.Writer.Complete();
_pipe.Reset();
}
}
public void Reconnect()
=> CommunicationStateChanging(ConnectionState.Retry);
private void CommunicationStateChanging(ConnectionState newState)
{
State = newState;
ConnectionChanged?.Invoke(this, State);
switch (State)
{
case ConnectionState.Selected:
#if !DISABLE_TIMER
_timer7.Change(Timeout.Infinite, Timeout.Infinite);
_logger.Info("Stop T7 Timer");
#endif
break;
case ConnectionState.Connected:
#if !DISABLE_TIMER
_cancellationTokenSourceForPipeDecoder = new CancellationTokenSource();
Task.Run(() => StartPipeDecoderConsumerAsync(_cancellationTokenSourceForPipeDecoder.Token));
Task.Run(() => StartPipeDecoderProducerAsync(_cancellationTokenSourceForPipeDecoder.Token));
_logger.Info($"Start T7 Timer: {T7 / 1000} sec.");
_timer7.Change(T7, Timeout.Infinite);
#endif
break;
case ConnectionState.Retry:
if (IsDisposed)
{
return;
}
Disconnect();
Start(_stoppingToken);
break;
}
}
private async Task HandleControlMessagesAsync(CancellationToken cancellation)
{
try
{
await _pipeDecoder.GetControlMessages(cancellation)
.ForEachAwaitWithCancellationAsync(ProcessControlMessageAsync, cancellation).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { }
}
private async Task ProcessControlMessageAsync(MessageHeader header, CancellationToken cancellation)
{
try
{
if ((byte)header.MessageType % 2 == 0)
{
if (_replyExpectedMsgs.TryGetValue(header.Id, out var ar))
{
ar.TrySetResult(header.MessageType);
}
else
{
_logger.Warning("Received Unexpected Control Message: " + header.MessageType);
return;
}
}
_logger.Info("Receive Control message: " + header.MessageType);
switch (header.MessageType)
{
case MessageType.SelectRequest:
await SendControlMessage(MessageType.SelectResponse, header.Id, cancellation).ConfigureAwait(false);
CommunicationStateChanging(ConnectionState.Selected);
break;
case MessageType.SelectResponse:
switch (header.F)
{
case 0:
CommunicationStateChanging(ConnectionState.Selected);
break;
case 1:
_logger.Error("Communication Already Active.");
break;
case 2:
_logger.Error("Connection Not Ready.");
break;
case 3:
_logger.Error("Connection Exhaust.");
break;
default:
_logger.Error("Connection Status Is Unknown.");
break;
}
break;
case MessageType.LinkTestRequest:
await SendControlMessage(MessageType.LinkTestResponse, header.Id, cancellation).ConfigureAwait(false);
break;
case MessageType.SeperateRequest:
CommunicationStateChanging(ConnectionState.Retry);
break;
}
}
catch (Exception ex)
{
_logger.Error("Unhandled exception occurred when processing control message: " + header.ToString(), ex);
}
}
private static readonly ReadOnlyMemory<byte> ControlMessageLengthBytes = new byte[] { 0, 0, 0, 10 };
private async Task SendControlMessage(MessageType msgType, int id, CancellationToken cancellation = default)
{
var token = ValueTaskCompletionSource<MessageType>.Create();
if ((byte)msgType % 2 == 1 && msgType != MessageType.SeperateRequest)
{
_replyExpectedMsgs[id] = token;
}
try
{
var buffer = EncodeControlMessage(msgType, id);
await Unsafe.As<ISecsConnection>(this)!.SendAsync(buffer, cancellation).ConfigureAwait(false);
_logger.Info("Sent Control Message: " + msgType);
if (_replyExpectedMsgs.ContainsKey(id))
{
#if NET6_0
await token.Task.WaitAsync(TimeSpan.FromMilliseconds(T6), cancellation).ConfigureAwait(false);
#else
if (await Task.WhenAny(token.Task, Task.Delay(T6, cancellation)).ConfigureAwait(false) != token.Task)
{
_logger.Error($"T6 Timeout[id=0x{id:X8}]: {T6 / 1000} sec.");
CommunicationStateChanging(ConnectionState.Retry);
}
#endif
}
}
#if NET6_0
catch (TimeoutException)
{
_logger.Error($"T6 Timeout[id=0x{id:X8}]: {T6 / 1000} sec.");
CommunicationStateChanging(ConnectionState.Retry);
}
#endif
catch (Exception ex)
{
_logger.Error($"Unknown exception occurred when send control messages", ex);
CommunicationStateChanging(ConnectionState.Retry);
}
finally
{
_replyExpectedMsgs.TryRemove(id, out _);
}
static ReadOnlyMemory<byte> EncodeControlMessage(MessageType msgType, int id)
{
var buffer = new MemoryBufferWriter<byte>(new byte[14]);
buffer.Write(ControlMessageLengthBytes.Span);
new MessageHeader
{
DeviceId = 0xFFFF,
MessageType = msgType,
Id = id
}.EncodeTo(buffer);
return buffer.WrittenMemory;
}
}
private void StopT8Timer()
{
_logger.Debug($"Stop T8 Timer: {T8 / 1000} sec.");
_timer8.Change(Timeout.Infinite, Timeout.Infinite);
}
private void StartT8Timer()
{
_logger.Debug($"Start T8 Timer: {T8 / 1000} sec.");
_timer8.Change(T8, Timeout.Infinite);
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposeStage, DisposalComplete) != DisposalNotStarted)
{
return;
}
ConnectionChanged = null;
if (State == ConnectionState.Selected)
{
await SendControlMessage(MessageType.SeperateRequest, MessageIdGenerator.NewId()).ConfigureAwait(false);
}
Disconnect();
_cancellationSourceForControlMessageProcessing.Cancel();
_cancellationSourceForControlMessageProcessing.Dispose();
_timer7.Dispose();
_timer8.Dispose();
_timerLinkTest.Dispose();
}
Task ISecsConnection.SendAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellation)
=> SendAsync(buffer, cancellation);
#if NET
private async Task SendAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellation)
{
await _sendLock.WaitAsync(cancellation).ConfigureAwait(false);
try
{
do
{
#if DEBUG
Debug.Assert(_socket != null);
#endif
var length = await _socket!.SendAsync(buffer, SocketFlags.None, cancellation).ConfigureAwait(false);
//Trace.WriteLine($"Socket sent {length} bytes.");
buffer = buffer[length..];
} while (!buffer.IsEmpty);
}
finally
{
_sendLock.Release();
}
}
#else
private async Task SendAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellation)
{
if (!System.Runtime.InteropServices.MemoryMarshal.TryGetArray(buffer, out var arr))
{
throw new InvalidOperationException();
}
await _sendLock.WaitAsync(cancellation).ConfigureAwait(false);
try
{
do
{
#if DEBUG
Debug.Assert(_socket != null);
#endif
var length = await _socket!.SendAsync(arr, SocketFlags.None).WithCancellation(cancellation).ConfigureAwait(false);
arr = new ArraySegment<byte>(arr.Array, arr.Offset + length, arr.Count - length);
//Trace.WriteLine($"Socket sent {length} bytes.");
} while (arr.Count > 0);
}
finally
{
_sendLock.Release();
}
}
#endif
IAsyncEnumerable<(MessageHeader header, Item? rootItem)> ISecsConnection.GetDataMessages(CancellationToken cancellation)
=> _pipeDecoder.GetDataMessages(cancellation);
}