-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathSensorClient.cs
1335 lines (1129 loc) · 49.8 KB
/
SensorClient.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
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
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Waher.Content;
using Waher.Content.Xml;
using Waher.Networking.XMPP.Events;
using Waher.Things;
using Waher.Things.SensorData;
namespace Waher.Networking.XMPP.Sensor
{
/// <summary>
/// Implements an XMPP sensor client interface.
///
/// The interface is defined in the Neuro-Foundation XMPP IoT extensions:
/// https://neuro-foundation.io
/// </summary>
public class SensorClient : XmppExtension
{
/// <summary>
/// urn:ieee:iot:sd:1.0
/// </summary>
public const string NamespaceSensorDataIeeeV1 = "urn:ieee:iot:sd:1.0";
/// <summary>
/// urn:nf:iot:sd:1.0
/// </summary>
public const string NamespaceSensorDataNeuroFoundationV1 = "urn:nf:iot:sd:1.0";
/// <summary>
/// Current namespace for sensor data.
/// </summary>
public const string NamespaceSensorDataCurrent = NamespaceSensorDataNeuroFoundationV1;
/// <summary>
/// Supported sensor-data namespaces.
/// </summary>
public static readonly string[] NamespacesSensorData = new string[]
{
NamespaceSensorDataNeuroFoundationV1,
NamespaceSensorDataIeeeV1
};
/// <summary>
/// urn:ieee:iot:events:1.0
/// </summary>
public const string NamespaceSensorEventsIeeeV1 = "urn:ieee:iot:events:1.0";
/// <summary>
/// urn:nf:iot:events:1.0
/// </summary>
public const string NamespaceSensorEventsNeuroFoundationV1 = "urn:nf:iot:events:1.0";
/// <summary>
/// Current namespace for sensor data events.
/// </summary>
public const string NamespaceSensorEventsCurrent = NamespaceSensorEventsNeuroFoundationV1;
/// <summary>
/// Supported sensor event namespaces.
/// </summary>
public static readonly string[] NamespacesSensorEvents = new string[]
{
NamespaceSensorEventsNeuroFoundationV1,
NamespaceSensorEventsIeeeV1
};
private readonly Dictionary<string, SensorDataClientRequest> requests = new Dictionary<string, SensorDataClientRequest>();
private readonly object synchObj = new object();
/// <summary>
/// Implements an XMPP sensor client interface.
///
/// The interface is defined in the Neuro-Foundation XMPP IoT extensions:
/// https://neuro-foundation.io
/// </summary>
/// <param name="Client">XMPP Client</param>
public SensorClient(XmppClient Client)
: base(Client)
{
#region Neuro-Foundation V1
this.client.RegisterMessageHandler("started", NamespaceSensorDataNeuroFoundationV1, this.StartedHandler, false);
this.client.RegisterMessageHandler("done", NamespaceSensorDataNeuroFoundationV1, this.DoneHandler, false);
this.client.RegisterMessageHandler("resp", NamespaceSensorDataNeuroFoundationV1, this.FieldsHandler, false);
#endregion
#region IEEE V1
this.client.RegisterMessageHandler("started", NamespaceSensorDataIeeeV1, this.StartedHandler, false);
this.client.RegisterMessageHandler("done", NamespaceSensorDataIeeeV1, this.DoneHandler, false);
this.client.RegisterMessageHandler("resp", NamespaceSensorDataIeeeV1, this.FieldsHandler, false);
#endregion
}
/// <inheritdoc/>
public override void Dispose()
{
base.Dispose();
#region Neuro-Foundation V1
this.client.UnregisterMessageHandler("started", NamespaceSensorDataNeuroFoundationV1, this.StartedHandler, false);
this.client.UnregisterMessageHandler("done", NamespaceSensorDataNeuroFoundationV1, this.DoneHandler, false);
this.client.UnregisterMessageHandler("resp", NamespaceSensorDataNeuroFoundationV1, this.FieldsHandler, false);
#endregion
#region IEEE V1
this.client.UnregisterMessageHandler("started", NamespaceSensorDataIeeeV1, this.StartedHandler, false);
this.client.UnregisterMessageHandler("done", NamespaceSensorDataIeeeV1, this.DoneHandler, false);
this.client.UnregisterMessageHandler("resp", NamespaceSensorDataIeeeV1, this.FieldsHandler, false);
#endregion
}
/// <summary>
/// Implemented extensions.
/// </summary>
public override string[] Extensions => new string[] { "XEP-0323" };
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor to read.</param>
/// <param name="Types">Field Types to read.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, FieldType Types)
{
return this.RequestReadout(Destination, null, Types, null, DateTime.MinValue, DateTime.MaxValue, DateTime.MinValue, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor to read.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, string[] Fields, FieldType Types)
{
return this.RequestReadout(Destination, null, Types, Fields, DateTime.MinValue, DateTime.MaxValue, DateTime.MinValue, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor to read.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <param name="From">From what time readout is to be made. Use <see cref="DateTime.MinValue"/> to specify no lower limit.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, FieldType Types, string[] Fields, DateTime From)
{
return this.RequestReadout(Destination, null, Types, Fields, From, DateTime.MaxValue, DateTime.MinValue, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor to read.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <param name="From">From what time readout is to be made. Use <see cref="DateTime.MinValue"/> to specify no lower limit.</param>
/// <param name="To">To what time readout is to be made. Use <see cref="DateTime.MaxValue"/> to specify no upper limit.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, FieldType Types, string[] Fields, DateTime From, DateTime To)
{
return this.RequestReadout(Destination, null, Types, Fields, From, To, DateTime.MinValue, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor to read.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <param name="From">From what time readout is to be made. Use <see cref="DateTime.MinValue"/> to specify no lower limit.</param>
/// <param name="To">To what time readout is to be made. Use <see cref="DateTime.MaxValue"/> to specify no upper limit.</param>
/// <param name="When">When the readout is to be made. Use <see cref="DateTime.MinValue"/> to start the readout immediately.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, FieldType Types, string[] Fields, DateTime From, DateTime To, DateTime When)
{
return this.RequestReadout(Destination, null, Types, Fields, From, To, When, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor to read.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <param name="From">From what time readout is to be made. Use <see cref="DateTime.MinValue"/> to specify no lower limit.</param>
/// <param name="To">To what time readout is to be made. Use <see cref="DateTime.MaxValue"/> to specify no upper limit.</param>
/// <param name="When">When the readout is to be made. Use <see cref="DateTime.MinValue"/> to start the readout immediately.</param>
/// <param name="ServiceToken">Optional service token.</param>
/// <param name="DeviceToken">Optional device token.</param>
/// <param name="UserToken">Optional user token.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, FieldType Types, string[] Fields, DateTime From, DateTime To, DateTime When,
string ServiceToken, string DeviceToken, string UserToken)
{
return this.RequestReadout(Destination, null, Types, Fields, From, To, When, ServiceToken, DeviceToken, UserToken);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to read.</param>
/// <param name="Nodes">Array of nodes to read. Can be null or empty, if reading a sensor that is not a concentrator.</param>
/// <param name="Types">Field Types to read.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, ThingReference[] Nodes, FieldType Types)
{
return this.RequestReadout(Destination, Nodes, Types, null, DateTime.MinValue, DateTime.MaxValue, DateTime.MinValue, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to read.</param>
/// <param name="Nodes">Array of nodes to read. Can be null or empty, if reading a sensor that is not a concentrator.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, ThingReference[] Nodes, string[] Fields, FieldType Types)
{
return this.RequestReadout(Destination, Nodes, Types, Fields, DateTime.MinValue, DateTime.MaxValue, DateTime.MinValue, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to read.</param>
/// <param name="Nodes">Array of nodes to read. Can be null or empty, if reading a sensor that is not a concentrator.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <param name="From">From what time readout is to be made. Use <see cref="DateTime.MinValue"/> to specify no lower limit.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, ThingReference[] Nodes, FieldType Types, string[] Fields, DateTime From)
{
return this.RequestReadout(Destination, Nodes, Types, Fields, From, DateTime.MaxValue, DateTime.MinValue, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to read.</param>
/// <param name="Nodes">Array of nodes to read. Can be null or empty, if reading a sensor that is not a concentrator.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <param name="From">From what time readout is to be made. Use <see cref="DateTime.MinValue"/> to specify no lower limit.</param>
/// <param name="To">To what time readout is to be made. Use <see cref="DateTime.MaxValue"/> to specify no upper limit.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, ThingReference[] Nodes, FieldType Types, string[] Fields, DateTime From, DateTime To)
{
return this.RequestReadout(Destination, Nodes, Types, Fields, From, To, DateTime.MinValue, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to read.</param>
/// <param name="Nodes">Array of nodes to read. Can be null or empty, if reading a sensor that is not a concentrator.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <param name="From">From what time readout is to be made. Use <see cref="DateTime.MinValue"/> to specify no lower limit.</param>
/// <param name="To">To what time readout is to be made. Use <see cref="DateTime.MaxValue"/> to specify no upper limit.</param>
/// <param name="When">When the readout is to be made. Use <see cref="DateTime.MinValue"/> to start the readout immediately.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public Task<SensorDataClientRequest> RequestReadout(string Destination, ThingReference[] Nodes, FieldType Types, string[] Fields, DateTime From, DateTime To, DateTime When)
{
return this.RequestReadout(Destination, Nodes, Types, Fields, From, To, When, string.Empty, string.Empty, string.Empty);
}
/// <summary>
/// Requests a sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to read.</param>
/// <param name="Nodes">Array of nodes to read. Can be null or empty, if reading a sensor that is not a concentrator.</param>
/// <param name="Types">Field Types to read.</param>
/// <param name="Fields">Fields to read.</param>
/// <param name="From">From what time readout is to be made. Use <see cref="DateTime.MinValue"/> to specify no lower limit.</param>
/// <param name="To">To what time readout is to be made. Use <see cref="DateTime.MaxValue"/> to specify no upper limit.</param>
/// <param name="When">When the readout is to be made. Use <see cref="DateTime.MinValue"/> to start the readout immediately.</param>
/// <param name="ServiceToken">Optional service token.</param>
/// <param name="DeviceToken">Optional device token.</param>
/// <param name="UserToken">Optional user token.</param>
/// <returns>Request object maintaining the current status of the request.</returns>
public async Task<SensorDataClientRequest> RequestReadout(string Destination, IThingReference[] Nodes, FieldType Types, string[] Fields, DateTime From, DateTime To, DateTime When,
string ServiceToken, string DeviceToken, string UserToken)
{
StringBuilder Xml = new StringBuilder();
string Id = this.GetNewId();
Xml.Append("<req xmlns='");
Xml.Append(NamespaceSensorDataCurrent);
Xml.Append("' id='");
Xml.Append(XML.Encode(Id));
if ((Types & FieldType.All) == FieldType.All)
Xml.Append("' all='true");
else
{
if (Types.HasFlag(FieldType.Momentary))
Xml.Append("' m='true");
if (Types.HasFlag(FieldType.Peak))
Xml.Append("' p='true");
if (Types.HasFlag(FieldType.Status))
Xml.Append("' s='true");
if (Types.HasFlag(FieldType.Computed))
Xml.Append("' c='true");
if (Types.HasFlag(FieldType.Identity))
Xml.Append("' i='true");
if (Types.HasFlag(FieldType.Historical))
Xml.Append("' h='true");
}
if (From != DateTime.MinValue)
{
Xml.Append("' from='");
Xml.Append(XML.Encode(From));
}
if (To != DateTime.MaxValue)
{
Xml.Append("' to='");
Xml.Append(XML.Encode(To));
}
if (When != DateTime.MinValue)
{
Xml.Append("' when='");
Xml.Append(XML.Encode(When));
}
if (!string.IsNullOrEmpty(ServiceToken))
{
Xml.Append("' st='");
Xml.Append(ServiceToken);
}
if (!string.IsNullOrEmpty(DeviceToken))
{
Xml.Append("' dt='");
Xml.Append(DeviceToken);
}
if (!string.IsNullOrEmpty(UserToken))
{
Xml.Append("' ut='");
Xml.Append(UserToken);
}
Xml.Append("'>");
if (!(Nodes is null))
{
foreach (IThingReference Node in Nodes)
{
Xml.Append("<nd id='");
Xml.Append(XML.Encode(Node.NodeId));
if (!string.IsNullOrEmpty(Node.SourceId))
{
Xml.Append("' src='");
Xml.Append(XML.Encode(Node.SourceId));
}
if (!string.IsNullOrEmpty(Node.Partition))
{
Xml.Append("' pt='");
Xml.Append(XML.Encode(Node.Partition));
}
Xml.Append("'/>");
}
}
if (!(Fields is null))
{
foreach (string Field in Fields)
{
Xml.Append("<f n='");
Xml.Append(XML.Encode(Field));
Xml.Append("'/>");
}
}
Xml.Append("</req>");
SensorDataClientRequest Request = new SensorDataClientRequest(Id, this, Destination, Destination, Nodes, Types, Fields, From, To, When,
ServiceToken, DeviceToken, UserToken);
lock (this.requests)
{
this.requests[Id] = Request;
}
await this.client.SendIqGet(Destination, Xml.ToString(), this.RequestResponse, Request);
return Request;
}
private string GetNewId()
{
string Id;
lock (this.synchObj)
{
do
{
Id = Guid.NewGuid().ToString().Replace("-", string.Empty);
}
while (this.requests.ContainsKey(Id));
this.requests[Id] = null;
}
return Id;
}
private async Task RequestResponse(object Sender, IqResultEventArgs e)
{
SensorDataClientRequest Request = (SensorDataClientRequest)e.State;
if (e.Ok)
{
foreach (XmlNode N in e.Response.ChildNodes)
{
switch (N.LocalName)
{
case "accepted":
XmlElement E = (XmlElement)N;
string Id = XML.Attribute(E, "id");
bool Queued = XML.Attribute(E, "queued", false);
if (Id == Request.Id)
await Request.Accept(Queued);
else
await Request.Fail("Request identity mismatch.");
return;
case "started":
E = (XmlElement)N;
Id = XML.Attribute(E, "id");
if (Id == Request.Id)
{
await Request.Accept(false);
await Request.Started();
}
else
await Request.Fail("Request identity mismatch.");
return;
case "resp":
E = (XmlElement)N;
Id = XML.Attribute(E, "id");
if (Id == Request.Id)
await this.ProcessFields(E, Request);
else
await Request.Fail("Request identity mismatch.");
return;
}
}
await Request.Fail("Invalid response to request.");
}
else
await Request.Fail(e.ErrorText);
}
private async Task StartedHandler(object Sender, MessageEventArgs e)
{
SensorDataClientRequest Request;
string Id = XML.Attribute(e.Content, "id");
lock (this.requests)
{
if (!this.requests.TryGetValue(Id, out Request))
return;
}
await Request.Started();
}
private async Task DoneHandler(object Sender, MessageEventArgs e)
{
SensorDataClientRequest Request;
string Id = XML.Attribute(e.Content, "id");
lock (this.requests)
{
if (!this.requests.TryGetValue(Id, out Request))
return;
if (!Request.MaintainSubscription)
this.requests.Remove(Id);
}
await Request.Done();
if (Request.MaintainSubscription)
Request.Clear();
}
private async Task AssertReceiving(SensorDataClientRequest Request)
{
switch (Request.State)
{
case SensorDataReadoutState.Requested:
await Request.SetState(SensorDataReadoutState.Accepted);
await Request.SetState(SensorDataReadoutState.Started);
await Request.SetState(SensorDataReadoutState.Receiving);
break;
case SensorDataReadoutState.Accepted:
await Request.SetState(SensorDataReadoutState.Started);
await Request.SetState(SensorDataReadoutState.Receiving);
break;
case SensorDataReadoutState.Started:
await Request.SetState(SensorDataReadoutState.Receiving);
break;
case SensorDataReadoutState.Failure:
case SensorDataReadoutState.Done:
Request.Clear();
await Request.SetState(SensorDataReadoutState.Receiving);
break;
}
}
private async Task FieldsHandler(object Sender, MessageEventArgs e)
{
SensorDataClientRequest Request;
string Id = XML.Attribute(e.Content, "id");
lock (this.requests)
{
if (!this.requests.TryGetValue(Id, out Request))
return;
}
await this.ProcessFields(e.Content, Request);
}
private async Task ProcessFields(XmlElement Content, SensorDataClientRequest Request)
{
await this.AssertReceiving(Request);
Tuple<List<Field>, List<ThingError>> Response = ParseFields(Content, out bool Done);
if (!(Response.Item1 is null))
await Request.LogFields(Response.Item1);
if (!(Response.Item2 is null))
await Request.LogErrors(Response.Item2);
if (Done)
{
await Request.Done();
if (Request.MaintainSubscription)
Request.Clear();
else
{
lock (this.requests)
{
this.requests.Remove(Request.Id);
}
}
}
}
/// <summary>
/// Parses sensor data field definitions.
/// </summary>
/// <param name="Content">Fields element containing sensor data as defined in neuro-foundation.io.</param>
/// <returns>Parsed fields.</returns>
public static SensorData ParseFields(XmlElement Content)
{
Tuple<List<Field>, List<ThingError>> Response = ParseFields(Content, out bool Done, out string Id);
return new SensorData()
{
Done = Done,
Errors = Response.Item2,
Fields = Response.Item1,
Id = Id
};
}
/// <summary>
/// Parses sensor data field definitions.
/// </summary>
/// <param name="Content">Fields element containing sensor data as defined in the neuro-foundation.io.</param>
/// <param name="Done">If sensor data readout is done.</param>
/// <returns>Parsed fields.</returns>
public static Tuple<List<Field>, List<ThingError>> ParseFields(XmlElement Content, out bool Done)
{
return ParseFields(Content, out Done, out string _);
}
/// <summary>
/// Parses sensor data field definitions.
/// </summary>
/// <param name="Content">Fields element containing sensor data as defined in the neuro-foundation.io.</param>
/// <param name="Done">If sensor data readout is done.</param>
/// <param name="Id">Readout identity.</param>
/// <returns>Parsed fields.</returns>
public static Tuple<List<Field>, List<ThingError>> ParseFields(XmlElement Content, out bool Done, out string Id)
{
List<ThingError> Errors = null;
List<Field> Fields = null;
Done = !XML.Attribute(Content, "more", false);
Id = XML.Attribute(Content, "id");
foreach (XmlNode N in Content.ChildNodes)
{
if (!(N is XmlElement E))
continue;
switch (E.LocalName)
{
case "nd":
ParseNode(E, ref Fields, ref Errors);
break;
case "ts":
ParseTimespan(E, ThingReference.Empty, ref Fields, ref Errors);
break;
}
}
return new Tuple<List<Field>, List<ThingError>>(Fields, Errors);
}
private static void ParseNode(XmlElement E,
ref List<Field> Fields, ref List<ThingError> Errors)
{
string NodeId = XML.Attribute(E, "id");
string SourceId = XML.Attribute(E, "src");
string Partition = XML.Attribute(E, "pt");
ThingReference Thing = new ThingReference(NodeId, SourceId, Partition);
foreach (XmlNode N2 in E.ChildNodes)
{
if (!(N2 is XmlElement E2))
continue;
if (E2.LocalName == "ts")
ParseTimespan(E2, Thing, ref Fields, ref Errors);
}
}
private static void ParseTimespan(XmlElement E2, ThingReference Thing,
ref List<Field> Fields, ref List<ThingError> Errors)
{
DateTime Timestamp = XML.Attribute(E2, "v", DateTime.MinValue);
foreach (XmlNode N3 in E2.ChildNodes)
{
if (!(N3 is XmlElement E))
continue;
if (E.LocalName == "err")
{
if (Errors is null)
Errors = new List<ThingError>();
Errors.Add(new ThingError(Thing, Timestamp, E.InnerText));
}
else
{
FieldType FieldTypes = (FieldType)0;
FieldQoS FieldQoS = (FieldQoS)0;
string FieldName = string.Empty;
string Module = string.Empty;
string StringIds = string.Empty;
string ValueString = string.Empty;
string ValueType = string.Empty;
string Unit = string.Empty;
bool Writable = false;
if (Fields is null)
Fields = new List<Field>();
foreach (XmlAttribute Attr in E.Attributes)
{
switch (Attr.Name)
{
case "n":
FieldName = Attr.Value;
break;
case "lns":
Module = Attr.Value;
break;
case "loc":
StringIds = Attr.Value;
break;
case "ctr":
if (!CommonTypes.TryParse(Attr.Value, out Writable))
Writable = false;
break;
case "m":
if (CommonTypes.TryParse(Attr.Value, out bool b) && b)
FieldTypes |= FieldType.Momentary;
break;
case "p":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes |= FieldType.Peak;
break;
case "s":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes |= FieldType.Status;
break;
case "c":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes |= FieldType.Computed;
break;
case "i":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes |= FieldType.Identity;
break;
case "h":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldTypes |= FieldType.Historical;
break;
case "ms":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.Missing;
break;
case "pr":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.InProgress;
break;
case "ae":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.AutomaticEstimate;
break;
case "me":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.ManualEstimate;
break;
case "mr":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.ManualReadout;
break;
case "ar":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.AutomaticReadout;
break;
case "of":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.TimeOffset;
break;
case "w":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.Warning;
break;
case "er":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.Error;
break;
case "so":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.Signed;
break;
case "iv":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.Invoiced;
break;
case "eos":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.EndOfSeries;
break;
case "pf":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.PowerFailure;
break;
case "ic":
if (CommonTypes.TryParse(Attr.Value, out b) && b)
FieldQoS |= FieldQoS.InvoiceConfirmed;
break;
case "v":
ValueString = Attr.Value;
break;
case "u":
Unit = Attr.Value;
break;
case "t":
ValueType = Attr.Value;
break;
}
}
LocalizationStep[] LocalizationSteps;
if (string.IsNullOrEmpty(StringIds))
LocalizationSteps = null;
else
LocalizationSteps = ParseStringIds(StringIds);
switch (E.LocalName)
{
case "b":
if (CommonTypes.TryParse(ValueString, out bool b))
Fields.Add(new BooleanField(Thing, Timestamp, FieldName, b, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "d":
if (XML.TryParse(ValueString, out DateTime DT))
Fields.Add(new DateField(Thing, Timestamp, FieldName, DT, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "dt":
if (XML.TryParse(ValueString, out DT))
Fields.Add(new DateTimeField(Thing, Timestamp, FieldName, DT, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "dr":
if (Duration.TryParse(ValueString, out Duration D))
Fields.Add(new DurationField(Thing, Timestamp, FieldName, D, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "e":
Fields.Add(new EnumField(Thing, Timestamp, FieldName, ValueString, ValueType, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "i":
if (int.TryParse(ValueString, out int i))
Fields.Add(new Int32Field(Thing, Timestamp, FieldName, i, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "l":
if (long.TryParse(ValueString, out long l))
Fields.Add(new Int64Field(Thing, Timestamp, FieldName, l, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "q":
if (CommonTypes.TryParse(ValueString, out double d, out byte NrDec))
Fields.Add(new QuantityField(Thing, Timestamp, FieldName, d, NrDec, Unit, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "s":
Fields.Add(new StringField(Thing, Timestamp, FieldName, ValueString, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
case "t":
if (TimeSpan.TryParse(ValueString, out TimeSpan TS))
Fields.Add(new TimeField(Thing, Timestamp, FieldName, TS, FieldTypes, FieldQoS, Writable, Module, LocalizationSteps));
break;
}
}
}
}
private static LocalizationStep[] ParseStringIds(string StringIds)
{
if (string.IsNullOrEmpty(StringIds))
return null;
if (int.TryParse(StringIds, out int StringId))
return new LocalizationStep[1] { new LocalizationStep(StringId) };
string[] Steps = StringIds.Split(',');
string[] Parts;
string Module;
string Seed;
int i, d, c = Steps.Length;
LocalizationStep[] Result = new LocalizationStep[c];
for (i = 0; i < c; i++)
{
Parts = Steps[i].Split('|');
d = Parts.Length;
if (!int.TryParse(Parts[0], out StringId))
continue;
if (d > 1)
{
Module = Parts[1];
if (d > 2)
Seed = Parts[2];
else
Seed = string.Empty;
}
else
{
Module = string.Empty;
Seed = string.Empty;
}
Result[i] = new LocalizationStep(StringId, Module, Seed);
}
return Result;
}
/// <summary>
/// Subscribes to sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to subscribe to.</param>
/// <param name="Types">Field Types to subscribe to.</param>
/// <param name="Fields">Fields to subscribe to, and any applicable change rules to apply to the subscription.</param>
/// <param name="ImmediateReadout">If an immediate readout should be performed.</param>
/// <returns>Request object maintaining the current status of the subscription.</returns>
public Task<SensorDataSubscriptionRequest> Subscribe(string Destination, FieldType Types, FieldSubscriptionRule[] Fields,
bool ImmediateReadout)
{
return this.Subscribe(Destination, null, Types, Fields, null, null, null, string.Empty, string.Empty, string.Empty, ImmediateReadout);
}
/// <summary>
/// Subscribes to sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to subscribe to.</param>
/// <param name="Types">Field Types to subscribe to.</param>
/// <param name="MinInterval">Optional smallest acceptable event interval.</param>
/// <param name="MaxInterval">Optional largest desired event interval.</param>
/// <param name="ImmediateReadout">If an immediate readout should be performed.</param>
/// <returns>Request object maintaining the current status of the subscription.</returns>
public Task<SensorDataSubscriptionRequest> Subscribe(string Destination, FieldType Types,
Duration? MinInterval, Duration? MaxInterval, bool ImmediateReadout)
{
return this.Subscribe(Destination, null, Types, null, MinInterval, MaxInterval, null, string.Empty, string.Empty, string.Empty, ImmediateReadout);
}
/// <summary>
/// Subscribes to sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to subscribe to.</param>
/// <param name="Types">Field Types to subscribe to.</param>
/// <param name="Fields">Fields to subscribe to, and any applicable change rules to apply to the subscription.</param>
/// <param name="MinInterval">Optional smallest acceptable event interval.</param>
/// <param name="MaxInterval">Optional largest desired event interval.</param>
/// <param name="ImmediateReadout">If an immediate readout should be performed.</param>
/// <returns>Request object maintaining the current status of the subscription.</returns>
public Task<SensorDataSubscriptionRequest> Subscribe(string Destination, FieldType Types, FieldSubscriptionRule[] Fields,
Duration? MinInterval, Duration? MaxInterval, bool ImmediateReadout)
{
return this.Subscribe(Destination, null, Types, Fields, MinInterval, MaxInterval, null, string.Empty, string.Empty, string.Empty, ImmediateReadout);
}
/// <summary>
/// Subscribes to sensor data readout.
/// </summary>
/// <param name="Destination">JID of sensor or concentrator containing the thing(s) to subscribe to.</param>
/// <param name="Types">Field Types to subscribe to.</param>
/// <param name="MinInterval">Optional smallest acceptable event interval.</param>
/// <param name="MaxInterval">Optional largest desired event interval.</param>
/// <param name="MaxAge">Optional maximum age of historical data.</param>
/// <param name="ImmediateReadout">If an immediate readout should be performed.</param>
/// <returns>Request object maintaining the current status of the subscription.</returns>
public Task<SensorDataSubscriptionRequest> Subscribe(string Destination, FieldType Types,