-
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathShdrAdapter.cs
More file actions
1312 lines (1072 loc) · 48.6 KB
/
Copy pathShdrAdapter.cs
File metadata and controls
1312 lines (1072 loc) · 48.6 KB
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023 TrakHound Inc., All Rights Reserved.
// TrakHound Inc. licenses this file to you under the MIT license.
using MTConnect.Assets;
using MTConnect.Configurations;
using MTConnect.Devices;
using MTConnect.Input;
using MTConnect.Shdr;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MTConnect.Adapters
{
/// <summary>
/// An Adapter class for communicating with an MTConnect Agent using the SHDR protocol.
/// Supports multiple concurrent Agent connections.
/// Uses a queue to collect changes to Observations and Assets and sends the most recent changes at the specified interval.
/// </summary>
public class ShdrAdapter
{
private readonly IMTConnectAdapter _adapter;
private readonly AgentClientConnectionListener _connectionListener;
private readonly Dictionary<string, AgentClient> _clients = new Dictionary<string, AgentClient>();
private readonly object _lock = new object();
private CancellationTokenSource _stop;
/// <summary>Exposes the internal cancellation source to subclasses so they can hook custom shutdown work onto the same token used by the adapter listener and worker threads.</summary>
protected CancellationTokenSource StopToken => _stop;
/// <summary>The underlying <see cref="IMTConnectAdapter"/> that buffers SHDR observations and serialises them onto each connected agent's socket.</summary>
protected IMTConnectAdapter Adapter => _adapter;
/// <summary>
/// Get a unique identifier for the Adapter
/// </summary>
public string Id { get; }
/// <summary>
/// The Name or UUID of the Device to create a connection for
/// </summary>
public string DeviceKey { get; }
/// <summary>
/// The TCP Port used for communication
/// </summary>
public int Port { get; }
/// <summary>
/// The heartbeat used to maintain a connection between the Adapter and the Agent
/// </summary>
public int Heartbeat { get; }
/// <summary>
/// The amount of time (in milliseconds) to allow for a connection attempt to the Agent
/// </summary>
public int Timeout { get; set; }
/// <summary>
/// Use multiline Assets
/// </summary>
public bool MultilineAssets { get; set; }
/// <summary>
/// Use multiline Devices
/// </summary>
public bool MultilineDevices { get; set; }
/// <summary>
/// Determines whether to filter out duplicate data
/// </summary>
public bool FilterDuplicates { get; set; }
/// <summary>
/// Determines whether to output Timestamps for each SHDR line
/// </summary>
public bool OutputTimestamps { get; set; }
/// <summary>
/// Raised when a new Agent connection is established. Includes the AgentClient ID as an argument.
/// </summary>
public event EventHandler<string> AgentConnected;
/// <summary>
/// Raised when an existing Agent connection is disconnected. Includes the AgentClient ID as an argument.
/// </summary>
public event EventHandler<string> AgentDisconnected;
/// <summary>
/// Raised when an error occurs during an existing Agent connection. Includes the AgentClient ID as an argument.
/// </summary>
#pragma warning disable CS0067 // event is part of the public API surface, raised by subclasses
public event EventHandler<string> AgentConnectionError;
#pragma warning restore CS0067
/// <summary>
/// Raised when a Ping request message is received from an Agent. Includes the AgentClient ID as an argument.
/// </summary>
public event EventHandler<string> PingReceived;
/// <summary>
/// Raised when a Pong response message is sent to an Agent. Includes the AgentClient ID as an argument.
/// </summary>
public event EventHandler<string> PongSent;
/// <summary>
/// Raised when a new line is sent to the Agent. Includes the AgentClient ID and the Line sent as an argument.
/// </summary>
public event EventHandler<AdapterEventArgs<string>> LineSent;
/// <summary>
/// Raised when new data is sent to the Agent. Includes the AgentClient ID and the Line sent as an argument.
/// </summary>
#pragma warning disable CS0067 // event is part of the public API surface, raised by subclasses
public event EventHandler<AdapterEventArgs<string>> DataSent;
#pragma warning restore CS0067
/// <summary>
/// Raised when an error occurs when sending a new line to the Agent. Includes the AgentClient ID and the Error message as an argument.
/// </summary>
public event EventHandler<AdapterEventArgs<string>> SendError;
/// <summary>
/// Raised when an error a TCP connection error occurs
/// </summary>
public event EventHandler<AdapterEventArgs<Exception>> ConnectionError;
/// <summary>Creates an SHDR adapter that listens on <paramref name="port"/> with the supplied <paramref name="heartbeat"/> interval (milliseconds), no device-key scope, duplicate filtering enabled, and timestamps emitted on every line.</summary>
public ShdrAdapter(int port = 7878, int heartbeat = 10000)
{
FilterDuplicates = true;
OutputTimestamps = true;
Port = port;
Heartbeat = heartbeat;
Timeout = 5000;
var adapter = new MTConnectAdapter(null, false);
adapter.OutputTimestamps = OutputTimestamps;
adapter.WriteObservationsFunction = WriteObservations;
adapter.WriteAssetsFunction = WriteAssets;
adapter.WriteDevicesFunction = WriteDevices;
_adapter = adapter;
_connectionListener = new AgentClientConnectionListener(Port, heartbeat);
_connectionListener.ClientConnected += ClientConnected;
_connectionListener.ClientDisconnected += ClientDisconnected;
_connectionListener.ClientPingReceived += ClientPingReceived;
_connectionListener.ClientPongSent += ClientPongSent;
_connectionListener.ConnectionErrorReceived += ClientConnectionError;
}
/// <summary>Creates an SHDR adapter scoped to <paramref name="deviceKey"/>, listening on <paramref name="port"/> with the supplied <paramref name="heartbeat"/> interval; lines targeting other devices are skipped.</summary>
public ShdrAdapter(string deviceKey, int port = 7878, int heartbeat = 10000)
{
FilterDuplicates = true;
OutputTimestamps = true;
DeviceKey = deviceKey;
Port = port;
Heartbeat = heartbeat;
Timeout = 5000;
var adapter = new MTConnectAdapter(null, false);
adapter.OutputTimestamps = OutputTimestamps;
adapter.WriteObservationsFunction = WriteObservations;
adapter.WriteAssetsFunction = WriteAssets;
adapter.WriteDevicesFunction = WriteDevices;
_adapter = adapter;
_connectionListener = new AgentClientConnectionListener(Port, heartbeat);
_connectionListener.ClientConnected += ClientConnected;
_connectionListener.ClientDisconnected += ClientDisconnected;
_connectionListener.ClientPingReceived += ClientPingReceived;
_connectionListener.ClientPongSent += ClientPongSent;
_connectionListener.ConnectionErrorReceived += ClientConnectionError;
}
/// <summary>Creates an SHDR adapter from <paramref name="configuration"/>, pulling device key, port, heartbeat, and the <c>IgnoreTimestamps</c> flag from the configuration object.</summary>
public ShdrAdapter(ShdrAdapterClientConfiguration configuration)
{
FilterDuplicates = true;
OutputTimestamps = true;
if (configuration != null)
{
DeviceKey = configuration.DeviceKey;
Port = configuration.Port;
Heartbeat = configuration.Heartbeat;
Timeout = 5000;
var adapter = new MTConnectAdapter(null, false);
adapter.IgnoreTimestamps = configuration.IgnoreTimestamps;
adapter.OutputTimestamps = OutputTimestamps;
adapter.WriteObservationsFunction = WriteObservations;
adapter.WriteAssetsFunction = WriteAssets;
adapter.WriteDevicesFunction = WriteDevices;
_adapter = adapter;
_connectionListener = new AgentClientConnectionListener(Port, Heartbeat);
_connectionListener.ClientConnected += ClientConnected;
_connectionListener.ClientDisconnected += ClientDisconnected;
_connectionListener.ClientPingReceived += ClientPingReceived;
_connectionListener.ClientPongSent += ClientPongSent;
_connectionListener.ConnectionErrorReceived += ClientConnectionError;
}
}
/// <summary>Protected constructor used by interval and queue subclasses to wire the optional flush <paramref name="interval"/> (milliseconds) and to opt in to the queue-buffer mode via <paramref name="bufferEnabled"/>.</summary>
protected ShdrAdapter(int port = 7878, int heartbeat = 10000, int? interval = null, bool bufferEnabled = false)
{
FilterDuplicates = true;
OutputTimestamps = true;
Port = port;
Heartbeat = heartbeat;
Timeout = 5000;
var adapter = new MTConnectAdapter(interval, bufferEnabled);
adapter.OutputTimestamps = OutputTimestamps;
adapter.WriteObservationsFunction = WriteObservations;
adapter.WriteAssetsFunction = WriteAssets;
adapter.WriteDevicesFunction = WriteDevices;
_adapter = adapter;
_connectionListener = new AgentClientConnectionListener(Port, heartbeat);
_connectionListener.ClientConnected += ClientConnected;
_connectionListener.ClientDisconnected += ClientDisconnected;
_connectionListener.ClientPingReceived += ClientPingReceived;
_connectionListener.ClientPongSent += ClientPongSent;
_connectionListener.ConnectionErrorReceived += ClientConnectionError;
}
/// <summary>Protected device-keyed variant of the interval/queue constructor; see <see cref="ShdrAdapter(int, int, int?, bool)"/> for the <paramref name="interval"/> and <paramref name="bufferEnabled"/> semantics.</summary>
protected ShdrAdapter(string deviceKey, int port = 7878, int heartbeat = 10000, int? interval = null, bool bufferEnabled = false)
{
FilterDuplicates = true;
OutputTimestamps = true;
DeviceKey = deviceKey;
Port = port;
Heartbeat = heartbeat;
Timeout = 5000;
var adapter = new MTConnectAdapter(interval, bufferEnabled);
adapter.OutputTimestamps = OutputTimestamps;
adapter.WriteObservationsFunction = WriteObservations;
adapter.WriteAssetsFunction = WriteAssets;
adapter.WriteDevicesFunction = WriteDevices;
_adapter = adapter;
_connectionListener = new AgentClientConnectionListener(Port, heartbeat);
_connectionListener.ClientConnected += ClientConnected;
_connectionListener.ClientDisconnected += ClientDisconnected;
_connectionListener.ClientPingReceived += ClientPingReceived;
_connectionListener.ClientPongSent += ClientPongSent;
_connectionListener.ConnectionErrorReceived += ClientConnectionError;
}
/// <summary>Protected configuration-driven variant of the interval/queue constructor; see <see cref="ShdrAdapter(int, int, int?, bool)"/> for the <paramref name="interval"/> and <paramref name="bufferEnabled"/> semantics.</summary>
protected ShdrAdapter(ShdrAdapterClientConfiguration configuration, int? interval = null, bool bufferEnabled = false)
{
FilterDuplicates = true;
OutputTimestamps = true;
if (configuration != null)
{
DeviceKey = configuration.DeviceKey;
Port = configuration.Port;
Heartbeat = configuration.Heartbeat;
Timeout = 5000;
var adapter = new MTConnectAdapter(interval, bufferEnabled);
adapter.IgnoreTimestamps = configuration.IgnoreTimestamps;
adapter.WriteObservationsFunction = WriteObservations;
adapter.WriteAssetsFunction = WriteAssets;
adapter.WriteDevicesFunction = WriteDevices;
_adapter = adapter;
_connectionListener = new AgentClientConnectionListener(Port, Heartbeat);
_connectionListener.ClientConnected += ClientConnected;
_connectionListener.ClientDisconnected += ClientDisconnected;
_connectionListener.ClientPingReceived += ClientPingReceived;
_connectionListener.ClientPongSent += ClientPongSent;
_connectionListener.ConnectionErrorReceived += ClientConnectionError;
}
}
/// <summary>
/// Starts the Adapter to begins listening for Agent connections as well as starts the Queue for collecting and sending data to the Agent(s).
/// </summary>
public void Start()
{
_stop = new CancellationTokenSource();
_adapter.Start();
// Start Agent Connection Listener
_connectionListener.Start(_stop.Token);
// Call Overridable Method
OnStart();
}
/// <summary>
/// Stops the adapter which also stops listening for Agent connections, disconnects any existing Agent connections, and stops the Queue for sending data to the Agent(s).
/// </summary>
public void Stop()
{
if (_stop != null) _stop.Cancel();
_connectionListener.Stop();
_adapter.Stop();
// Call Overridable Method
OnStop();
}
/// <summary>Override-point invoked at the tail end of <see cref="Start"/>, after the listener and underlying adapter have been started.</summary>
protected virtual void OnStart() { }
/// <summary>Override-point invoked at the tail end of <see cref="Stop"/>, after the listener and underlying adapter have been signalled to stop.</summary>
protected virtual void OnStop() { }
/// <summary>
/// Set all items to Unavailable
/// </summary>
public void SetUnavailable(long timestamp = 0)
{
_adapter.SetUnavailable(timestamp);
}
#region "Event Handlers"
private void ClientConnected(string clientId, TcpClient client)
{
AddAgentClient(clientId, client);
AgentConnected.Raise(this, clientId, null);
SendLast(UnixDateTime.Now);
}
private void ClientDisconnected(string clientId)
{
RemoveAgentClient(clientId);
AgentDisconnected.Raise(this, clientId, null);
}
private void ClientPingReceived(string clientId)
{
PingReceived.Raise(this, clientId, null);
}
private void ClientPongSent(string clientId)
{
PongSent.Raise(this, clientId, null);
}
private void ClientConnectionError(string clientId, Exception exception)
{
ConnectionError.Raise(this, new AdapterEventArgs<Exception>(clientId, exception), null);
}
#endregion
#region "Clients"
private void AddAgentClient(string clientId, TcpClient tcpClient)
{
if (!string.IsNullOrEmpty(clientId) && tcpClient != null)
{
lock (_lock)
{
_clients.Remove(clientId);
_clients.Add(clientId, new AgentClient(clientId, tcpClient));
}
}
}
private AgentClient GetAgentClient(string clientId)
{
if (!string.IsNullOrEmpty(clientId))
{
lock (_lock)
{
if (_clients.TryGetValue(clientId, out AgentClient agentClient))
{
return agentClient;
}
}
}
return null;
}
private IEnumerable<AgentClient> GetAgentClients()
{
lock (_lock)
{
return _clients.Values;
}
}
private void RemoveAgentClient(string clientId)
{
if (!string.IsNullOrEmpty(clientId))
{
lock (_lock)
{
_clients.Remove(clientId);
}
}
}
#endregion
#region "Send"
/// <summary>
/// Sends all Items that have changed since last sent to the Agent
/// </summary>
public bool SendChanged()
{
return _adapter.SendChanged();
}
/// <summary>
/// Sends all of the last sent Items, Assets, and Devices to the Agent. This can be used upon reconnection to the Agent
/// </summary>
public bool SendLast(long timestamp = 0)
{
return _adapter.SendLast(timestamp);
}
/// <summary>Override-point invoked after <see cref="SendChanged"/> completes; subclasses can use it to record diagnostics or refresh derived state.</summary>
protected virtual void OnChangedSent() { }
/// <summary>Override-point invoked after <see cref="SendLast"/> completes (typically once per reconnect); subclasses can use it to clear sent flags or trigger follow-up publishes.</summary>
protected virtual void OnLastSent() { }
#endregion
#region "Write"
private bool WriteObservations(IEnumerable<IObservationInput> observations)
{
// DataItems
var dataItems = observations.Where(o => ShdrObservation.GetObservationType(o) == ShdrObservationType.DataItem);
if (!dataItems.IsNullOrEmpty())
{
var shdrDataItems = new List<ShdrDataItem>();
foreach (var x in dataItems) shdrDataItems.Add(new ShdrDataItem(x));
var shdrLine = ShdrDataItem.ToString(shdrDataItems, !OutputTimestamps);
if (!WriteLine(shdrLine)) return false;
}
// Messages
var messages = observations.Where(o => ShdrObservation.GetObservationType(o) == ShdrObservationType.Message);
if (!messages.IsNullOrEmpty())
{
foreach (var x in messages)
{
var shdrModel = new ShdrMessage(x);
var shdrLine = shdrModel.ToString();
if (!WriteLine(shdrLine)) return false;
}
}
// Conditions
var conditions = observations.Where(o => ShdrObservation.GetObservationType(o) == ShdrObservationType.Condition);
if (!conditions.IsNullOrEmpty())
{
foreach (var x in conditions)
{
var shdrModel = new ShdrFaultState(new ConditionFaultStateObservationInput(x));
var shdrLine = shdrModel.ToString();
if (!WriteLine(shdrLine)) return false;
}
}
// DataSets
var dataSets = observations.Where(o => ShdrObservation.GetObservationType(o) == ShdrObservationType.DataSet);
if (!dataSets.IsNullOrEmpty())
{
foreach (var x in dataSets)
{
var shdrModel = new ShdrDataSet(new DataSetObservationInput(x));
var shdrLine = shdrModel.ToString();
if (!WriteLine(shdrLine)) return false;
}
}
// Tables
var tables = observations.Where(o => ShdrObservation.GetObservationType(o) == ShdrObservationType.Table);
if (!tables.IsNullOrEmpty())
{
foreach (var x in tables)
{
var shdrModel = new ShdrTable(new TableObservationInput(x));
var shdrLine = shdrModel.ToString();
if (!WriteLine(shdrLine)) return false;
}
}
// TimeSeries
var timeSeries = observations.Where(o => ShdrObservation.GetObservationType(o) == ShdrObservationType.TimeSeries);
if (!timeSeries.IsNullOrEmpty())
{
foreach (var x in timeSeries)
{
var shdrModel = new ShdrTimeSeries(new TimeSeriesObservationInput(x));
var shdrLine = shdrModel.ToString();
if (!WriteLine(shdrLine)) return false;
}
}
return true;
}
private bool WriteAssets(IEnumerable<IAssetInput> assets)
{
foreach (var asset in assets)
{
var shdrModel = new ShdrAsset(asset.Asset);
var shdrLine = shdrModel.ToString(MultilineAssets);
if (!WriteLine(shdrLine)) return false;
}
return true;
}
private bool WriteDevices(IEnumerable<IDeviceInput> devices)
{
foreach (var device in devices)
{
var shdrModel = new ShdrDevice(device.Device);
var shdrLine = shdrModel.ToString(MultilineDevices);
if (!WriteLine(shdrLine)) return false;
}
return true;
}
/// <summary>Writes a fully-formatted SHDR <paramref name="line"/> (terminator included) to every connected agent and returns <c>true</c> when at least one write succeeded.</summary>
protected bool WriteLine(string line)
{
if (!string.IsNullOrEmpty(line))
{
try
{
// Write Line to each client in stored client list
var clients = GetAgentClients();
if (!clients.IsNullOrEmpty())
{
var success = true;
foreach (var client in clients)
{
if (!WriteLineToClient(client, line)) success = false;
}
return success;
}
}
catch { }
}
return false;
}
private bool WriteLineToClient(AgentClient client, string line)
{
if (client != null && !string.IsNullOrEmpty(line))
{
var lines = SplitLines(line);
if (!lines.IsNullOrEmpty())
{
foreach (var singleLine in lines)
{
try
{
// Convert string to ASCII bytes and add line terminator
var bytes = Encoding.ASCII.GetBytes(singleLine + "\n");
// Get the TcpClient Stream
var stream = client.TcpClient.GetStream();
stream.ReadTimeout = Timeout;
stream.WriteTimeout = Timeout;
// Write the line (in bytes) to the Stream
stream.Write(bytes, 0, bytes.Length);
LineSent.Raise(this, new AdapterEventArgs<string>(client.Id, singleLine), null);
}
catch (Exception ex)
{
SendError.Raise(this, new AdapterEventArgs<string>(client.Id, ex.Message), null);
return false;
}
}
return true;
}
}
return false;
}
private async Task<bool> WriteLineToClientAsync(AgentClient client, string line)
{
if (client != null)
{
try
{
// Convert string to ASCII bytes and add line terminator
var bytes = Encoding.ASCII.GetBytes(line + "\n");
// Get the TcpClient Stream
var stream = client.TcpClient.GetStream();
stream.ReadTimeout = Timeout;
stream.WriteTimeout = Timeout;
// Write the line (in bytes) to the Stream
await stream.WriteAsync(bytes, 0, bytes.Length);
LineSent.Raise(this, new AdapterEventArgs<string>(client.Id, line), null);
return true;
}
catch (Exception ex)
{
SendError.Raise(this, new AdapterEventArgs<string>(client.Id, ex.Message), null);
}
}
return false;
}
// Split Lines by \r\n
// Can't use string.Split(string, StringSplitOptions.TrimEntries since
// it isn't fully compatible with all of the target runtimes
private static IEnumerable<string> SplitLines(string line)
{
if (!string.IsNullOrEmpty(line))
{
var lines = new List<string>();
char cr = '\r';
char lf = '\n';
char prev = '$';
var s = 0;
var e = 0;
string l;
while (e < line.Length - 1)
{
// Look for \r\n
if (line[e] == lf && prev == cr)
{
// Add trimmed line to return list
l = line.Substring(s, (e - s) + 1).Trim('\r').Trim('\n');
if (!string.IsNullOrEmpty(l))
{
if (l.Length > 1 || (l.Length == 1 && l[0] != cr))
{
lines.Add(l);
}
}
s = e;
}
prev = line[e];
e++;
}
// Get Last Line
l = line.Substring(s, (e - s) + 1).Trim('\n');
if (!string.IsNullOrEmpty(l))
{
if (l.Length > 1 || (l.Length == 1 && l[0] != cr))
{
lines.Add(l);
}
}
return lines;
}
return null;
}
#endregion
#region "DataItems"
/// <summary>Override-point invoked when an SHDR data-item observation is added to the buffered queue; subclasses can use it to tap, log, or rewrite observations before they are flushed.</summary>
protected virtual void OnDataItemAdd(ShdrDataItem dataItem) { }
/// <summary>Adds a scalar Sample/Event observation for <paramref name="dataItemKey"/> with <paramref name="value"/> and the current Unix time as the timestamp.</summary>
public void AddDataItem(string dataItemKey, object value)
{
AddDataItem(dataItemKey, value, UnixDateTime.Now);
}
/// <summary>Adds a scalar Sample/Event observation with an explicit <paramref name="timestamp"/> (converted to Unix UTC time).</summary>
public void AddDataItem(string dataItemKey, object value, DateTime timestamp)
{
AddDataItem(dataItemKey, value, timestamp.ToUnixUtcTime());
}
/// <summary>Adds a scalar Sample/Event observation with an explicit Unix-time <paramref name="timestamp"/> (milliseconds since epoch).</summary>
public void AddDataItem(string dataItemKey, object value, long timestamp)
{
AddDataItem(new ShdrDataItem(dataItemKey, value, timestamp));
}
/// <summary>Adds a pre-built <see cref="ShdrDataItem"/> to the buffered queue.</summary>
public void AddDataItem(ShdrDataItem dataItem)
{
AddDataItem((IObservationInput)dataItem);
}
/// <summary>Adds a batch of <see cref="ShdrDataItem"/> objects to the buffered queue.</summary>
public void AddDataItems(IEnumerable<ShdrDataItem> dataItems)
{
if (!dataItems.IsNullOrEmpty())
{
foreach (var dataItem in dataItems)
{
AddDataItem(dataItem);
}
}
}
/// <summary>Adds an arbitrary <see cref="IObservationInput"/> to the buffered queue (used by SHDR data set/table/time-series observations that all flow through the same buffer).</summary>
public void AddDataItem(IObservationInput observation)
{
_adapter.AddObservation(observation);
}
/// <summary>Immediately writes a scalar Sample/Event observation to every connected agent and returns <c>true</c> when all writes succeeded.</summary>
public bool SendDataItem(string dataItemKey, object value)
{
return SendDataItem(dataItemKey, value, UnixDateTime.Now);
}
/// <summary>Sends a scalar Sample/Event observation with an explicit <paramref name="timestamp"/> (converted to Unix UTC time).</summary>
public bool SendDataItem(string dataItemKey, object value, DateTime timestamp)
{
return SendDataItem(dataItemKey, value, timestamp.ToUnixUtcTime());
}
/// <summary>Sends a scalar Sample/Event observation with an explicit Unix-time <paramref name="timestamp"/>.</summary>
public bool SendDataItem(string dataItemKey, object value, long timestamp)
{
return SendDataItem(new ShdrDataItem(dataItemKey, value, timestamp));
}
/// <summary>Sends a pre-built <see cref="ShdrDataItem"/> immediately.</summary>
public bool SendDataItem(ShdrDataItem dataItem)
{
return SendDataItem((IObservationInput)dataItem);
}
/// <summary>Sends a batch of <see cref="ShdrDataItem"/> objects immediately; returns <c>true</c> only when every observation was written successfully.</summary>
public bool SendDataItems(IEnumerable<ShdrDataItem> dataItems)
{
var success = true;
if (!dataItems.IsNullOrEmpty())
{
foreach (var dataItem in dataItems)
{
if (!SendDataItem(dataItem)) success = false;
}
return success;
}
return false;
}
/// <summary>Sends an arbitrary <see cref="IObservationInput"/> immediately; the common entry point used by the data-set/table/time-series send overloads.</summary>
public bool SendDataItem(IObservationInput observation)
{
return _adapter.SendObservation(observation);
}
#endregion
#region "Messages"
/// <summary>Override-point invoked when an SHDR Message event is added to the buffered queue.</summary>
protected virtual void OnMessageAdd(ShdrMessage message) { }
/// <summary>Adds a Message event for <paramref name="messageId"/> with the supplied text <paramref name="value"/> using the current Unix time.</summary>
public void AddMessage(string messageId, string value)
{
AddMessage(messageId, value, UnixDateTime.Now);
}
/// <summary>Adds a Message event with an explicit <paramref name="timestamp"/> (converted to Unix UTC time).</summary>
public void AddMessage(string messageId, string value, DateTime timestamp)
{
AddMessage(messageId, value, timestamp.ToUnixUtcTime());
}
/// <summary>Adds a Message event with an explicit Unix-time <paramref name="timestamp"/>.</summary>
public void AddMessage(string messageId, string value, long timestamp)
{
AddMessage(new ShdrMessage(messageId, value, timestamp));
}
/// <summary>Adds a Message event with a controller-supplied <paramref name="nativeCode"/> using the current Unix time.</summary>
public void AddMessage(string messageId, string value, string nativeCode)
{
AddMessage(messageId, value, nativeCode, UnixDateTime.Now);
}
/// <summary>Adds a Message event with native code and explicit <paramref name="timestamp"/> (converted to Unix UTC time).</summary>
public void AddMessage(string messageId, string value, string nativeCode, DateTime timestamp)
{
AddMessage(messageId, value, nativeCode, timestamp.ToUnixUtcTime());
}
/// <summary>Adds a Message event with native code and an explicit Unix-time <paramref name="timestamp"/>.</summary>
public void AddMessage(string messageId, string value, string nativeCode, long timestamp)
{
AddMessage(new ShdrMessage(messageId, value, nativeCode, timestamp));
}
/// <summary>Adds a pre-built <see cref="ShdrMessage"/> to the buffered queue.</summary>
public void AddMessage(ShdrMessage message)
{
_adapter.AddObservation(message);
}
/// <summary>Adds a batch of Message events to the buffered queue.</summary>
public void AddMessages(IEnumerable<ShdrMessage> messages)
{
if (!messages.IsNullOrEmpty())
{
foreach (var message in messages)
{
AddMessage(message);
}
}
}
/// <summary>Immediately writes a Message event using the current Unix time.</summary>
public bool SendMessage(string dataItemId, string value)
{
return SendMessage(dataItemId, value, UnixDateTime.Now);
}
/// <summary>Sends a Message event with an explicit <paramref name="timestamp"/>.</summary>
public bool SendMessage(string dataItemId, string value, DateTime timestamp)
{
return SendMessage(dataItemId, value, timestamp.ToUnixUtcTime());
}
/// <summary>Sends a Message event with an explicit Unix-time <paramref name="timestamp"/>.</summary>
public bool SendMessage(string dataItemId, string value, long timestamp)
{
return SendMessage(new ShdrMessage(dataItemId, value, timestamp));
}
/// <summary>Sends a Message event with a controller-supplied <paramref name="nativeCode"/> using the current Unix time.</summary>
public bool SendMessage(string dataItemId, string value, string nativeCode)
{
return SendMessage(dataItemId, value, nativeCode, UnixDateTime.Now);
}
/// <summary>Sends a Message event with native code and explicit <paramref name="timestamp"/>.</summary>
public bool SendMessage(string dataItemId, string value, string nativeCode, DateTime timestamp)
{
return SendMessage(dataItemId, value, nativeCode, timestamp.ToUnixUtcTime());
}
/// <summary>Sends a Message event with native code and an explicit Unix-time <paramref name="timestamp"/>.</summary>
public bool SendMessage(string dataItemId, string value, string nativeCode, long timestamp)
{
return SendMessage(new ShdrMessage(dataItemId, value, nativeCode, timestamp));
}
/// <summary>Sends a pre-built <see cref="ShdrMessage"/> immediately.</summary>
public bool SendMessage(ShdrMessage message)
{
return _adapter.SendObservation(message);
}
/// <summary>Sends a batch of Message events immediately; returns <c>true</c> when every message wrote successfully.</summary>
public bool SendMessages(IEnumerable<ShdrMessage> messages)
{
var success = true;
if (!messages.IsNullOrEmpty())
{
foreach (var message in messages)
{
if (!SendDataItem(message)) success = false;
}
return success;
}
return false;
}
#endregion
#region "Conditions"
/// <summary>Override-point invoked when an SHDR Condition is added to the buffered queue.</summary>
protected virtual void OnConditionAdd(ShdrCondition condition) { }
/// <summary>Adds every fault state of <paramref name="condition"/> to the buffered queue; the SHDR adapter emits one line per fault state so multi-state conditions remain individually addressable.</summary>
public void AddCondition(ShdrCondition condition)
{
if (condition != null && !condition.FaultStates.IsNullOrEmpty())
{
foreach (var faultState in condition.FaultStates)
{
_adapter.AddObservation(faultState);
}
}
}
/// <summary>Adds a batch of <see cref="ShdrCondition"/> objects, flattening each into its fault states.</summary>
public void AddConditions(IEnumerable<ShdrCondition> conditions)
{
if (!conditions.IsNullOrEmpty())
{
foreach (var condition in conditions)
{
AddCondition(condition);
}
}
}
/// <summary>Immediately writes the first fault state of <paramref name="condition"/> to every connected agent; the early-return behaviour exists to match the original send-on-first-state contract.</summary>
public bool SendCondition(ShdrCondition condition)
{
if (condition != null && !condition.FaultStates.IsNullOrEmpty())
{
foreach (var faultState in condition.FaultStates)
{
return _adapter.SendObservation(faultState);
}
}
return false;
}
/// <summary>Sends a batch of <see cref="ShdrCondition"/> objects immediately; returns <c>true</c> when every send succeeded.</summary>
public bool SendConditions(IEnumerable<ShdrCondition> conditions)
{
var success = true;
if (!conditions.IsNullOrEmpty())
{
foreach (var condition in conditions)
{
if (!SendCondition(condition)) success = false;
}
return success;
}
return false;
}
#endregion
#region "TimeSeries"
/// <summary>Override-point invoked when an SHDR TimeSeries observation is added to the buffered queue.</summary>
protected virtual void OnTimeSeriesAdd(ShdrTimeSeries timeSeries) { }
/// <summary>Adds a TimeSeries observation to the buffered queue.</summary>
public void AddTimeSeries(ShdrTimeSeries timeSeries)