forked from ela-compil/BACnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BACnetClient.cs
2949 lines (2577 loc) · 151 KB
/
BACnetClient.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
/**************************************************************************
* MIT License
*
* Copyright (C) 2014 Morten Kvistgaard <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*********************************************************************/
using System.Collections.Generic;
using System.IO.BACnet.Serialize;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
namespace System.IO.BACnet
{
public delegate void MessageRecievedHandler(IBacnetTransport sender, byte[] buffer, int offset, int msgLength, BacnetAddress remoteAddress);
/// <summary>
/// BACnet network client or server
/// </summary>
public class BacnetClient : IDisposable
{
private int _retries;
private byte _invokeId;
private readonly LastSegmentAck _lastSegmentAck = new LastSegmentAck();
private uint _writepriority;
/// <summary>
/// Dictionary of List of Tuples with sequence-number and byte[] per invoke-id
/// TODO: invoke-id should be PER (remote) DEVICE!
/// </summary>
private Dictionary<byte, List<Tuple<byte, byte[]>>> _segmentsPerInvokeId = new Dictionary<byte, List<Tuple<byte, byte[]>>>();
private Dictionary<byte, object> _locksPerInvokeId = new Dictionary<byte, object>();
private Dictionary<byte, byte> _expectedSegmentsPerInvokeId = new Dictionary<byte, byte>();
public const int DEFAULT_UDP_PORT = 0xBAC0;
public const int DEFAULT_TIMEOUT = 1000;
public const int DEFAULT_RETRIES = 3;
public IBacnetTransport Transport { get; }
public ushort VendorId { get; set; } = 260;
public int Timeout { get; set; }
public int TransmitTimeout { get; set; } = 30000;
public BacnetMaxSegments MaxSegments { get; set; } = BacnetMaxSegments.MAX_SEG0;
public byte ProposedWindowSize { get; set; } = 10;
public bool ForceWindowSize { get; set; }
public bool DefaultSegmentationHandling { get; set; } = true;
public ILog Log { get; set; } = LogManager.GetLogger<BacnetClient>();
/// <summary>
/// Used as the number of tentatives
/// </summary>
public int Retries
{
get => _retries;
set => _retries = Math.Max(1, value);
}
public uint WritePriority
{
get => _writepriority;
set { if (value < 17) _writepriority = value; }
}
// These members allows to access undecoded buffer by the application
// layer, when the basic undecoding process is not really able to do the job
// in particular with application_specific_encoding values
public byte[] raw_buffer;
public int raw_offset, raw_length;
public class Segmentation
{
// ReSharper disable InconsistentNaming
// was public before refactor so can't change this
public EncodeBuffer buffer;
public byte sequence_number;
public byte window_size;
public byte max_segments;
// ReSharper restore InconsistentNaming
}
private class LastSegmentAck
{
private readonly ManualResetEvent _wait = new ManualResetEvent(false);
private readonly object _lockObject = new object();
private BacnetAddress _address;
private byte _invokeId;
public byte SequenceNumber;
public byte WindowSize;
public void Set(BacnetAddress adr, byte invokeId, byte sequenceNumber, byte windowSize)
{
lock (_lockObject)
{
_address = adr;
_invokeId = invokeId;
SequenceNumber = sequenceNumber;
WindowSize = windowSize;
_wait.Set();
}
}
public bool Wait(BacnetAddress adr, byte invokeId, int timeout)
{
Monitor.Enter(_lockObject);
while (!adr.Equals(this._address) || this._invokeId != invokeId)
{
_wait.Reset();
Monitor.Exit(_lockObject);
if (!_wait.WaitOne(timeout)) return false;
Monitor.Enter(_lockObject);
}
Monitor.Exit(_lockObject);
_address = null;
return true;
}
}
public BacnetClient(int port = DEFAULT_UDP_PORT, int timeout = DEFAULT_TIMEOUT, int retries = DEFAULT_RETRIES)
: this(new BacnetIpUdpProtocolTransport(port), timeout, retries)
{
}
public BacnetClient(IBacnetTransport transport, int timeout = DEFAULT_TIMEOUT, int retries = DEFAULT_RETRIES)
{
Transport = transport;
Timeout = timeout;
Retries = retries;
}
public override bool Equals(object obj)
{
return Transport.Equals((obj as BacnetClient)?.Transport);
}
public override int GetHashCode()
{
return Transport.GetHashCode();
}
public override string ToString()
{
return Transport.ToString();
}
public EncodeBuffer GetEncodeBuffer(int startOffset)
{
return new EncodeBuffer(new byte[Transport.MaxBufferLength], startOffset);
}
public void Start()
{
Transport.Start();
Transport.MessageRecieved += OnRecieve;
Log.Info("Started communication");
}
public delegate void ConfirmedServiceRequestHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, byte invokeId, byte[] buffer, int offset, int length);
public event ConfirmedServiceRequestHandler OnConfirmedServiceRequest;
public delegate void ReadPropertyRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, BacnetObjectId objectId, BacnetPropertyReference property, BacnetMaxSegments maxSegments);
public event ReadPropertyRequestHandler OnReadPropertyRequest;
public delegate void ReadPropertyMultipleRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, IList<BacnetReadAccessSpecification> properties, BacnetMaxSegments maxSegments);
public event ReadPropertyMultipleRequestHandler OnReadPropertyMultipleRequest;
public delegate void WritePropertyRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, BacnetObjectId objectId, BacnetPropertyValue value, BacnetMaxSegments maxSegments);
public event WritePropertyRequestHandler OnWritePropertyRequest;
public delegate void WritePropertyMultipleRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, BacnetObjectId objectId, ICollection<BacnetPropertyValue> values, BacnetMaxSegments maxSegments);
public event WritePropertyMultipleRequestHandler OnWritePropertyMultipleRequest;
public delegate void AtomicWriteFileRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, bool isStream, BacnetObjectId objectId, int position, uint blockCount, byte[][] blocks, int[] counts, BacnetMaxSegments maxSegments);
public event AtomicWriteFileRequestHandler OnAtomicWriteFileRequest;
public delegate void AtomicReadFileRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, bool isStream, BacnetObjectId objectId, int position, uint count, BacnetMaxSegments maxSegments);
public event AtomicReadFileRequestHandler OnAtomicReadFileRequest;
public delegate void SubscribeCOVRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, uint subscriberProcessIdentifier, BacnetObjectId monitoredObjectIdentifier, bool cancellationRequest, bool issueConfirmedNotifications, uint lifetime, BacnetMaxSegments maxSegments);
public event SubscribeCOVRequestHandler OnSubscribeCOV;
public delegate void EventNotificationCallbackHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, BacnetEventNotificationData eventData, bool needConfirm);
public event EventNotificationCallbackHandler OnEventNotify;
public delegate void SubscribeCOVPropertyRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, uint subscriberProcessIdentifier, BacnetObjectId monitoredObjectIdentifier, BacnetPropertyReference monitoredProperty, bool cancellationRequest, bool issueConfirmedNotifications, uint lifetime, float covIncrement, BacnetMaxSegments maxSegments);
public event SubscribeCOVPropertyRequestHandler OnSubscribeCOVProperty;
public delegate void DeviceCommunicationControlRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, uint timeDuration, uint enableDisable, string password, BacnetMaxSegments maxSegments);
public event DeviceCommunicationControlRequestHandler OnDeviceCommunicationControl;
public delegate void ReinitializedRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, BacnetReinitializedStates state, string password, BacnetMaxSegments maxSegments);
public event ReinitializedRequestHandler OnReinitializedDevice;
public delegate void ReadRangeHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, BacnetObjectId objectId, BacnetPropertyReference property, BacnetReadRangeRequestTypes requestType, uint position, DateTime time, int count, BacnetMaxSegments maxSegments);
public event ReadRangeHandler OnReadRange;
public delegate void CreateObjectRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, BacnetObjectId objectId, ICollection<BacnetPropertyValue> values, BacnetMaxSegments maxSegments);
public event CreateObjectRequestHandler OnCreateObjectRequest;
public delegate void DeleteObjectRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, BacnetObjectId objectId, BacnetMaxSegments maxSegments);
public event DeleteObjectRequestHandler OnDeleteObjectRequest;
public delegate void GetAlarmSummaryOrEventInformationRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, bool getEvent, BacnetObjectId objectId, BacnetMaxAdpu maxApdu, BacnetMaxSegments max_segments);
public event GetAlarmSummaryOrEventInformationRequestHandler OnGetAlarmSummaryOrEventInformation;
public delegate void AlarmAcknowledgeRequestHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, uint ackProcessIdentifier, BacnetObjectId eventObjectIdentifier, uint eventStateAcked, string ackSource, BacnetGenericTime eventTimeStamp, BacnetGenericTime ackTimeStamp);
public event AlarmAcknowledgeRequestHandler OnAlarmAcknowledge;
protected void ProcessConfirmedServiceRequest(BacnetAddress address, BacnetPduTypes type, BacnetConfirmedServices service, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, byte invokeId, byte[] buffer, int offset, int length)
{
try
{
Log.Debug($"ConfirmedServiceRequest {service}");
raw_buffer = buffer;
raw_length = length;
raw_offset = offset;
OnConfirmedServiceRequest?.Invoke(this, address, type, service, maxSegments, maxAdpu, invokeId, buffer, offset, length);
//don't send segmented messages, if client don't want it
if ((type & BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED) == 0)
maxSegments = BacnetMaxSegments.MAX_SEG0;
if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY && OnReadPropertyRequest != null)
{
int thsRejectReason;
if ((thsRejectReason = Services.DecodeReadProperty(buffer, offset, length, out var objectId, out var property)) >= 0)
{
OnReadPropertyRequest(this, address, invokeId, objectId, property, maxSegments);
}
else
{
switch (thsRejectReason)
{
case -1:
SendConfirmedServiceReject(address, invokeId, BacnetRejectReason.MISSING_REQUIRED_PARAMETER);
break;
case -2:
SendConfirmedServiceReject(address, invokeId, BacnetRejectReason.INVALID_TAG);
break;
case -3:
SendConfirmedServiceReject(address, invokeId, BacnetRejectReason.TOO_MANY_ARGUMENTS);
break;
}
Log.Warn("Couldn't decode DecodeReadProperty");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY && OnWritePropertyRequest != null)
{
if (Services.DecodeWriteProperty(address, buffer, offset, length, out var objectId, out var value) >= 0)
OnWritePropertyRequest(this, address, invokeId, objectId, value, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
//SendConfirmedServiceReject(adr, invokeId, BacnetRejectReason.OTHER);
Log.Warn("Couldn't decode DecodeWriteProperty");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROP_MULTIPLE && OnReadPropertyMultipleRequest != null)
{
if (Services.DecodeReadPropertyMultiple(buffer, offset, length, out var properties) >= 0)
OnReadPropertyMultipleRequest(this, address, invokeId, properties, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode DecodeReadPropertyMultiple");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROP_MULTIPLE && OnWritePropertyMultipleRequest != null)
{
if (Services.DecodeWritePropertyMultiple(address, buffer, offset, length, out var objectId, out var values) >= 0)
OnWritePropertyMultipleRequest(this, address, invokeId, objectId, values, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode DecodeWritePropertyMultiple");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_COV_NOTIFICATION && OnCOVNotification != null)
{
if (Services.DecodeCOVNotifyUnconfirmed(address, buffer, offset, length, out var subscriberProcessIdentifier, out var initiatingDeviceIdentifier, out var monitoredObjectIdentifier, out var timeRemaining, out var values) >= 0)
OnCOVNotification(this, address, invokeId, subscriberProcessIdentifier, initiatingDeviceIdentifier, monitoredObjectIdentifier, timeRemaining, true, values, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode COVNotify");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_ATOMIC_WRITE_FILE && OnAtomicWriteFileRequest != null)
{
if (Services.DecodeAtomicWriteFile(buffer, offset, length, out var isStream, out var objectId, out var position, out var blockCount, out var blocks, out var counts) >= 0)
OnAtomicWriteFileRequest(this, address, invokeId, isStream, objectId, position, blockCount, blocks, counts, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode AtomicWriteFile");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_ATOMIC_READ_FILE && OnAtomicReadFileRequest != null)
{
if (Services.DecodeAtomicReadFile(buffer, offset, length, out var isStream, out var objectId, out var position, out var count) >= 0)
OnAtomicReadFileRequest(this, address, invokeId, isStream, objectId, position, count, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode AtomicReadFile");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV && OnSubscribeCOV != null)
{
if (Services.DecodeSubscribeCOV(buffer, offset, length, out var subscriberProcessIdentifier, out var monitoredObjectIdentifier, out var cancellationRequest, out var issueConfirmedNotifications, out var lifetime) >= 0)
OnSubscribeCOV(this, address, invokeId, subscriberProcessIdentifier, monitoredObjectIdentifier, cancellationRequest, issueConfirmedNotifications, lifetime, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode SubscribeCOV");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV_PROPERTY && OnSubscribeCOVProperty != null)
{
if (Services.DecodeSubscribeProperty(buffer, offset, length, out var subscriberProcessIdentifier, out var monitoredObjectIdentifier, out var monitoredProperty, out var cancellationRequest, out var issueConfirmedNotifications, out var lifetime, out var covIncrement) >= 0)
OnSubscribeCOVProperty(this, address, invokeId, subscriberProcessIdentifier, monitoredObjectIdentifier, monitoredProperty, cancellationRequest, issueConfirmedNotifications, lifetime, covIncrement, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode SubscribeCOVProperty");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_DEVICE_COMMUNICATION_CONTROL && OnDeviceCommunicationControl != null)
{
// DAL
if (Services.DecodeDeviceCommunicationControl(buffer, offset, length, out var timeDuration, out var enableDisable, out var password) >= 0)
OnDeviceCommunicationControl(this, address, invokeId, timeDuration, enableDisable, password, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode DeviceCommunicationControl");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_REINITIALIZE_DEVICE && OnReinitializedDevice != null)
{
// DAL
if (Services.DecodeReinitializeDevice(buffer, offset, length, out var state, out var password) >= 0)
OnReinitializedDevice(this, address, invokeId, state, password, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode ReinitializeDevice");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_EVENT_NOTIFICATION && OnEventNotify != null) // F. Chaxel
{
if (Services.DecodeEventNotifyData(buffer, offset, length, out var eventData) >= 0)
{
OnEventNotify(this, address, invokeId, eventData, true);
}
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode Event/Alarm Notification");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_READ_RANGE && OnReadRange != null)
{
if (Services.DecodeReadRange(buffer, offset, length, out var objectId, out var property, out var requestType, out var position, out var time, out var count) >= 0)
OnReadRange(this, address, invokeId, objectId, property, requestType, position, time, count, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode ReadRange");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_CREATE_OBJECT && OnCreateObjectRequest != null)
{
if (Services.DecodeCreateObject(address, buffer, offset, length, out var objectId, out var values) >= 0)
OnCreateObjectRequest(this, address, invokeId, objectId, values, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode CreateObject");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_DELETE_OBJECT && OnDeleteObjectRequest != null)
{
if (Services.DecodeDeleteObject(buffer, offset, length, out var objectId) >= 0)
OnDeleteObjectRequest(this, address, invokeId, objectId, maxSegments);
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode DecodeDeleteObject");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_GET_ALARM_SUMMARY && OnGetAlarmSummaryOrEventInformation != null)
{
// DAL -- added the core code required but since I couldn't test it we just reject this service
// rejecting it shouldn't be too bad a thing since GetAlarmSummary has been retired anyway...
// if someone needs it they can uncomment the related code and test.
#if false
BacnetObjectId objectId = default(BacnetObjectId);
objectId.Type = BacnetObjectTypes.MAX_BACNET_OBJECT_TYPE;
if (Services.DecodeAlarmSummaryOrEventRequest(buffer, offset, length, false, ref objectId) >= 0)
{
OnGetAlarmSummaryOrEventInformation(this, address, invokeId, false, objectId, maxAdpu, maxSegments);
}
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode GetAlarmSummary");
}
#else
SendConfirmedServiceReject(address, invokeId, BacnetRejectReason.RECOGNIZED_SERVICE); // should be unrecognized but this is the way it was spelled..
#endif
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_GET_EVENT_INFORMATION && OnGetAlarmSummaryOrEventInformation != null)
{
// DAL
BacnetObjectId objectId = default(BacnetObjectId);
objectId.Type = BacnetObjectTypes.MAX_BACNET_OBJECT_TYPE;
if (Services.DecodeAlarmSummaryOrEventRequest(buffer, offset, length, true, ref objectId) >= 0)
{
OnGetAlarmSummaryOrEventInformation(this, address, invokeId, true, objectId, maxAdpu, maxSegments);
}
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode GetEventInformation");
}
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_ACKNOWLEDGE_ALARM && OnAlarmAcknowledge != null)
{
// DAL
if (Services.DecodeAlarmAcknowledge(buffer, offset, length, out uint ackProcessIdentifier, out BacnetObjectId eventObjectIdentifier, out uint eventStateAcked, out string ackSource, out BacnetGenericTime eventTimeStamp, out BacnetGenericTime ackTimeStamp) >= 0)
{
OnAlarmAcknowledge(this, address, invokeId, ackProcessIdentifier, eventObjectIdentifier, eventStateAcked, ackSource, eventTimeStamp, ackTimeStamp);
}
else
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Warn("Couldn't decode AlarmAcknowledge");
}
}
else
{
// DAL
SendConfirmedServiceReject(address, invokeId, BacnetRejectReason.RECOGNIZED_SERVICE); // should be unrecognized but this is the way it was spelled..
Log.Warn($"Confirmed service not handled: {service}");
}
}
catch (Exception ex)
{
// DAL
SendAbort(address, invokeId, BacnetAbortReason.OTHER);
//ErrorResponse(address, service, invokeId, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_ABORT_OTHER);
Log.Error("Error in ProcessConfirmedServiceRequest", ex);
}
}
public delegate void UnconfirmedServiceRequestHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetUnconfirmedServices service, byte[] buffer, int offset, int length);
public event UnconfirmedServiceRequestHandler OnUnconfirmedServiceRequest;
public delegate void WhoHasHandler(BacnetClient sender, BacnetAddress adr, int lowLimit, int highLimit, BacnetObjectId? objId, string objName);
public event WhoHasHandler OnWhoHas;
public delegate void IamHandler(BacnetClient sender, BacnetAddress adr, uint deviceId, uint maxAPDU, BacnetSegmentations segmentation, ushort vendorId);
public event IamHandler OnIam;
public delegate void WhoIsHandler(BacnetClient sender, BacnetAddress adr, int lowLimit, int highLimit);
public event WhoIsHandler OnWhoIs;
public delegate void TimeSynchronizeHandler(BacnetClient sender, BacnetAddress adr, DateTime dateTime, bool utc);
public event TimeSynchronizeHandler OnTimeSynchronize;
//used by both 'confirmed' and 'unconfirmed' notify
public delegate void COVNotificationHandler(BacnetClient sender, BacnetAddress adr, byte invokeId, uint subscriberProcessIdentifier, BacnetObjectId initiatingDeviceIdentifier, BacnetObjectId monitoredObjectIdentifier, uint timeRemaining, bool needConfirm, ICollection<BacnetPropertyValue> values, BacnetMaxSegments maxSegments);
public event COVNotificationHandler OnCOVNotification;
protected void ProcessUnconfirmedServiceRequest(BacnetAddress address, BacnetPduTypes type, BacnetUnconfirmedServices service, byte[] buffer, int offset, int length)
{
try
{
Log.Debug("UnconfirmedServiceRequest");
OnUnconfirmedServiceRequest?.Invoke(this, address, type, service, buffer, offset, length);
if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_I_AM && OnIam != null)
{
if (Services.DecodeIamBroadcast(buffer, offset, out var deviceId, out var maxAdpu, out var segmentation, out var vendorId) >= 0)
OnIam(this, address, deviceId, maxAdpu, segmentation, vendorId);
else
Log.Warn("Couldn't decode IamBroadcast");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_WHO_IS && OnWhoIs != null)
{
if (Services.DecodeWhoIsBroadcast(buffer, offset, length, out var lowLimit, out var highLimit) >= 0)
OnWhoIs(this, address, lowLimit, highLimit);
else
Log.Warn("Couldn't decode WhoIsBroadcast");
}
// added by thamersalek
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_WHO_HAS && OnWhoHas != null)
{
if (Services.DecodeWhoHasBroadcast(buffer, offset, length, out var lowLimit, out var highLimit, out var objId, out var objName) >= 0)
OnWhoHas(this, address, lowLimit, highLimit, objId, objName);
else
Log.Warn("Couldn't decode WhoHasBroadcast");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_COV_NOTIFICATION && OnCOVNotification != null)
{
if (Services.DecodeCOVNotifyUnconfirmed(address, buffer, offset, length, out var subscriberProcessIdentifier, out var initiatingDeviceIdentifier, out var monitoredObjectIdentifier, out var timeRemaining, out var values) >= 0)
OnCOVNotification(this, address, 0, subscriberProcessIdentifier, initiatingDeviceIdentifier, monitoredObjectIdentifier, timeRemaining, false, values, BacnetMaxSegments.MAX_SEG0);
else
Log.Warn("Couldn't decode COVNotifyUnconfirmed");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_TIME_SYNCHRONIZATION && OnTimeSynchronize != null)
{
if (Services.DecodeTimeSync(buffer, offset, length, out var dateTime) >= 0)
OnTimeSynchronize(this, address, dateTime, false);
else
Log.Warn("Couldn't decode TimeSynchronize");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_UTC_TIME_SYNCHRONIZATION && OnTimeSynchronize != null)
{
if (Services.DecodeTimeSync(buffer, offset, length, out var dateTime) >= 0)
OnTimeSynchronize(this, address, dateTime, true);
else
Log.Warn("Couldn't decode TimeSynchronize");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_EVENT_NOTIFICATION && OnEventNotify != null) // F. Chaxel
{
if (Services.DecodeEventNotifyData(buffer, offset, length, out var eventData) >= 0)
OnEventNotify(this, address, 0, eventData, false);
else
Log.Warn("Couldn't decode Event/Alarm Notification");
}
else
{
Log.Warn($"Unconfirmed service not handled: {service}");
// SendUnConfirmedServiceReject(adr); ? exists ?
}
}
catch (Exception ex)
{
Log.Error("Error in ProcessUnconfirmedServiceRequest", ex);
}
}
public delegate void SimpleAckHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, byte[] data, int dataOffset, int dataLength);
public event SimpleAckHandler OnSimpleAck;
protected void ProcessSimpleAck(BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, byte[] buffer, int offset, int length)
{
try
{
Log.Debug($"Received SimpleAck for {service}");
OnSimpleAck?.Invoke(this, adr, type, service, invokeId, buffer, offset, length);
}
catch (Exception ex)
{
Log.Error("Error in ProcessSimpleAck", ex);
}
}
public delegate void ComplexAckHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, byte[] buffer, int offset, int length);
public event ComplexAckHandler OnComplexAck;
protected void ProcessComplexAck(BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, byte[] buffer, int offset, int length)
{
try
{
Log.Debug($"Received ComplexAck for {service}");
OnComplexAck?.Invoke(this, adr, type, service, invokeId, buffer, offset, length);
}
catch (Exception ex)
{
Log.Error($"Error in {nameof(ProcessComplexAck)}", ex);
}
}
public delegate void ErrorHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, BacnetErrorClasses errorClass, BacnetErrorCodes errorCode, byte[] buffer, int offset, int length);
public event ErrorHandler OnError;
protected void ProcessError(BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, byte[] buffer, int offset, int length)
{
try
{
if (Services.DecodeError(buffer, offset, length, out var errorClass, out var errorCode) < 0)
Log.Warn("Couldn't decode received Error");
Log.Debug($"Received Error {errorClass} {errorCode}");
OnError?.Invoke(this, adr, type, service, invokeId, errorClass, errorCode, buffer, offset, length);
}
catch (Exception ex)
{
Log.Error($"Error in {nameof(ProcessError)}", ex);
}
}
public delegate void AbortHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, byte invokeId, BacnetAbortReason reason, byte[] buffer, int offset, int length);
public event AbortHandler OnAbort;
protected void ProcessAbort(BacnetAddress adr, BacnetPduTypes type, byte invokeId, BacnetAbortReason reason, byte[] buffer, int offset, int length)
{
try
{
Log.Debug($"Received Abort, reason: {reason}");
OnAbort?.Invoke(this, adr, type, invokeId, reason, buffer, offset, length);
}
catch (Exception ex)
{
Log.Error("Error in ProcessAbort", ex);
}
}
public delegate void RejectHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, byte invokeId, BacnetRejectReason reason, byte[] buffer, int offset, int length);
public event RejectHandler OnReject;
protected void ProcessReject(BacnetAddress adr, BacnetPduTypes type, byte invokeId, BacnetRejectReason reason, byte[] buffer, int offset, int length)
{
try
{
Log.Debug($"Received Reject, reason: {reason}");
OnReject?.Invoke(this, adr, type, invokeId, reason, buffer, offset, length);
}
catch (Exception ex)
{
Log.Error("Error in ProcessReject", ex);
}
}
public delegate void SegmentAckHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, byte originalInvokeId, byte sequenceNumber, byte actualWindowSize, byte[] buffer, int offset, int length);
public event SegmentAckHandler OnSegmentAck;
protected void ProcessSegmentAck(BacnetAddress adr, BacnetPduTypes type, byte originalInvokeId, byte sequenceNumber, byte actualWindowSize, byte[] buffer, int offset, int length)
{
try
{
Log.Debug("Received SegmentAck");
OnSegmentAck?.Invoke(this, adr, type, originalInvokeId, sequenceNumber, actualWindowSize, buffer, offset, length);
}
catch (Exception ex)
{
Log.Error("Error in ProcessSegmentAck", ex);
}
}
public delegate void SegmentHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, byte sequenceNumber, byte[] buffer, int offset, int length);
public event SegmentHandler OnSegment;
private void ProcessSegment(BacnetAddress address, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, bool server, byte sequenceNumber, byte proposedWindowNumber, byte[] buffer, int offset, int length)
{
if (!_locksPerInvokeId.TryGetValue(invokeId, out var lockObj))
{
lockObj = new object();
_locksPerInvokeId[invokeId] = lockObj;
}
lock (lockObj)
{
ProcessSegmentLocked(address, type, service, invokeId, maxSegments, maxAdpu, server, sequenceNumber,
proposedWindowNumber, buffer, offset, length);
}
}
private void ProcessSegmentLocked(BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service,
byte invokeId, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, bool server, byte sequenceNumber,
byte proposedWindowNumber, byte[] buffer, int offset, int length)
{
Log.Trace($@"Processing Segment #{sequenceNumber} of invoke-id #{invokeId}");
if (!_segmentsPerInvokeId.ContainsKey(invokeId))
_segmentsPerInvokeId[invokeId] = new List<Tuple<byte, byte[]>>();
if (!_expectedSegmentsPerInvokeId.ContainsKey(invokeId))
_expectedSegmentsPerInvokeId[invokeId] = byte.MaxValue;
var moreFollows = (type & BacnetPduTypes.MORE_FOLLOWS) == BacnetPduTypes.MORE_FOLLOWS;
if (!moreFollows)
_expectedSegmentsPerInvokeId[invokeId] = (byte)(sequenceNumber + 1);
//send ACK
if (sequenceNumber % proposedWindowNumber == 0 || !moreFollows)
{
if (ForceWindowSize)
proposedWindowNumber = ProposedWindowSize;
SegmentAckResponse(adr, false, server, invokeId, sequenceNumber, proposedWindowNumber);
}
//Send on
OnSegment?.Invoke(this, adr, type, service, invokeId, maxSegments, maxAdpu, sequenceNumber, buffer, offset, length);
//default segment assembly. We run this seperately from the above handler, to make sure that it comes after!
if (DefaultSegmentationHandling)
PerformDefaultSegmentHandling(adr, type, service, invokeId, maxSegments, maxAdpu, sequenceNumber, buffer, offset, length);
}
/// <summary>
/// This is a simple handling that stores all segments in memory and assembles them when done
/// </summary>
private void PerformDefaultSegmentHandling(BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, byte sequenceNumber, byte[] buffer, int offset, int length)
{
var segments = _segmentsPerInvokeId[invokeId];
if (sequenceNumber == 0)
{
//copy buffer + encode new adpu header
type &= ~BacnetPduTypes.SEGMENTED_MESSAGE;
var confirmedServiceRequest = (type & BacnetPduTypes.PDU_TYPE_MASK) == BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST;
var adpuHeaderLen = confirmedServiceRequest ? 4 : 3;
var copy = new byte[length + adpuHeaderLen];
Array.Copy(buffer, offset, copy, adpuHeaderLen, length);
var encodedBuffer = new EncodeBuffer(copy, 0);
if (confirmedServiceRequest)
APDU.EncodeConfirmedServiceRequest(encodedBuffer, type, service, maxSegments, maxAdpu, invokeId);
else
APDU.EncodeComplexAck(encodedBuffer, type, service, invokeId);
segments.Add(Tuple.Create(sequenceNumber, copy)); // doesn't include BVLC or NPDU
}
else
{
//copy only content part
segments.Add(Tuple.Create(sequenceNumber, buffer.Skip(offset).Take(length).ToArray()));
}
//process when finished
if (segments.Count < _expectedSegmentsPerInvokeId[invokeId])
return;
//assemble whole part
var apduBuffer = segments.OrderBy(s => s.Item1).SelectMany(s => s.Item2).ToArray();
segments.Clear();
_expectedSegmentsPerInvokeId[invokeId] = byte.MaxValue;
//process
ProcessApdu(adr, type, apduBuffer, 0, apduBuffer.Length);
}
private void ProcessApdu(BacnetAddress adr, BacnetPduTypes type, byte[] buffer, int offset, int length)
{
switch (type & BacnetPduTypes.PDU_TYPE_MASK)
{
case BacnetPduTypes.PDU_TYPE_UNCONFIRMED_SERVICE_REQUEST:
{
var apduHeaderLen = APDU.DecodeUnconfirmedServiceRequest(buffer, offset, out type, out var service);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessUnconfirmedServiceRequest(adr, type, service, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_SIMPLE_ACK:
{
var apduHeaderLen = APDU.DecodeSimpleAck(buffer, offset, out type, out var service, out var invokeId);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessSimpleAck(adr, type, service, invokeId, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_COMPLEX_ACK:
{
var apduHeaderLen = APDU.DecodeComplexAck(buffer, offset, out type, out var service, out var invokeId,
out var sequenceNumber, out var proposedWindowNumber);
offset += apduHeaderLen;
length -= apduHeaderLen;
if ((type & BacnetPduTypes.SEGMENTED_MESSAGE) == 0) //don't process segmented messages here
{
ProcessComplexAck(adr, type, service, invokeId, buffer, offset, length);
}
else
{
ProcessSegment(adr, type, service, invokeId, BacnetMaxSegments.MAX_SEG0, BacnetMaxAdpu.MAX_APDU50, false,
sequenceNumber, proposedWindowNumber, buffer, offset, length);
}
}
break;
case BacnetPduTypes.PDU_TYPE_SEGMENT_ACK:
{
var apduHeaderLen = APDU.DecodeSegmentAck(buffer, offset, out type, out var originalInvokeId,
out var sequenceNumber, out var actualWindowSize);
offset += apduHeaderLen;
length -= apduHeaderLen;
_lastSegmentAck.Set(adr, originalInvokeId, sequenceNumber, actualWindowSize);
ProcessSegmentAck(adr, type, originalInvokeId, sequenceNumber, actualWindowSize, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_ERROR:
{
var apduHeaderLen = APDU.DecodeError(buffer, offset, out type, out var service, out var invokeId);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessError(adr, type, service, invokeId, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_ABORT:
{
var apduHeaderLen = APDU.DecodeAbort(buffer, offset, out type, out var invokeId, out var reason);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessAbort(adr, type, invokeId, reason, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_REJECT:
{
var apduHeaderLen = APDU.DecodeReject(buffer, offset, out type, out var invokeId, out var reason);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessReject(adr, type, invokeId, reason, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST:
{
var apduHeaderLen = APDU.DecodeConfirmedServiceRequest(buffer, offset, out type, out var service,
out var maxSegments, out var maxAdpu, out var invokeId, out var sequenceNumber, out var proposedWindowNumber);
offset += apduHeaderLen;
length -= apduHeaderLen;
if ((type & BacnetPduTypes.SEGMENTED_MESSAGE) == 0) //don't process segmented messages here
{
ProcessConfirmedServiceRequest(adr, type, service, maxSegments, maxAdpu, invokeId, buffer, offset, length);
}
else
{
ProcessSegment(adr, type, service, invokeId, maxSegments, maxAdpu, true, sequenceNumber, proposedWindowNumber, buffer, offset, length);
}
}
break;
default:
Log.Warn($"Something else arrived: {type}");
break;
}
}
// DAL
public void SendNetworkMessage(BacnetAddress adr, byte[] buffer, int bufLen, BacnetNetworkMessageTypes messageType, ushort vendorId = 0)
{
if (adr == null)
{
adr = Transport.GetBroadcastAddress();
}
var b = GetEncodeBuffer(Transport.HeaderLength);
NPDU.Encode(b, BacnetNpduControls.NetworkLayerMessage, adr, null, 255, messageType, vendorId);
b.Add(buffer, bufLen);
Transport.Send(b.buffer, Transport.HeaderLength, b.offset - Transport.HeaderLength, adr, false, 0);
}
public void SendIAmRouterToNetwork(ushort[] networks)
{
var b = GetEncodeBuffer(0);
for (int i = 0; i < networks.Length; i++)
{
ASN1.encode_unsigned16(b, networks[i]);
}
SendNetworkMessage(null, b.buffer, b.offset, BacnetNetworkMessageTypes.NETWORK_MESSAGE_I_AM_ROUTER_TO_NETWORK);
}
public void SendInitializeRoutingTableAck(BacnetAddress adr, ushort[] networks)
{
var b = GetEncodeBuffer(0);
if (networks != null)
{
for (int i = 0; i < networks.Length; i++)
{
ASN1.encode_unsigned16(b, networks[i]);
}
}
SendNetworkMessage(adr, b.buffer, b.offset, BacnetNetworkMessageTypes.NETWORK_MESSAGE_INIT_RT_TABLE_ACK);
}
public void SendRejectToNetwork(BacnetAddress adr, ushort[] networks)
{
var b = GetEncodeBuffer(0);
/* Sending our DNET doesn't make a lot of sense, does it? */
for (int i = 0; i < networks.Length; i++)
{
ASN1.encode_unsigned16(b, networks[i]);
}
SendNetworkMessage(adr, b.buffer, b.offset, BacnetNetworkMessageTypes.NETWORK_MESSAGE_REJECT_MESSAGE_TO_NETWORK);
}
public delegate void NetworkMessageHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, BacnetNetworkMessageTypes npduMessageType, byte[] buffer, int offset, int messageLength);
public event NetworkMessageHandler OnNetworkMessage;
public delegate void WhoIsRouterToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event WhoIsRouterToNetworkHandler OnWhoIsRouterToNetworkMessage;
public delegate void IAmRouterToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event IAmRouterToNetworkHandler OnIAmRouterToNetworkMessage;
public delegate void ICouldBeRouterToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event ICouldBeRouterToNetworkHandler OnICouldBeRouterToNetworkMessage;
public delegate void RejectMessageToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event RejectMessageToNetworkHandler OnRejectMessageToNetworkMessage;
public delegate void RouterBusyToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event RouterBusyToNetworkHandler OnRouterBusyToNetworkMessage;
public delegate void RouterAvailableToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event RouterAvailableToNetworkHandler OnRouterAvailableToNetworkMessage;
public delegate void InitRtTableToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event InitRtTableToNetworkHandler OnInitRtTableToNetworkMessage;
public delegate void InitRtTableAckToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event InitRtTableAckToNetworkHandler OnInitRtTableAckToNetworkMessage;
public delegate void EstablishConnectionToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event EstablishConnectionToNetworkHandler OnEstablishConnectionToNetworkMessage;
public delegate void DisconnectConnectionToNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event DisconnectConnectionToNetworkHandler OnDisconnectConnectionToNetworkMessage;
public delegate void UnrecognizedNetworkHandler(BacnetClient sender, BacnetAddress adr, BacnetNpduControls npduFunction, byte[] buffer, int offset, int messageLength);
public event UnrecognizedNetworkHandler OnUnrecognizedNetworkMessage;
private void ProcessNetworkMessage(BacnetAddress adr, BacnetNpduControls npduFunction, BacnetNetworkMessageTypes npduMessageType, byte[] buffer, int offset, int messageLength)
{
// DAL I don't want to make a generic router, but I do want to put in enough infrastructure
// that I can build on it to route multiple devices in the normal bacnet way.
OnNetworkMessage?.Invoke(this, adr, npduFunction, npduMessageType, buffer, offset, messageLength);
switch (npduMessageType)
{
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK:
OnWhoIsRouterToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_I_AM_ROUTER_TO_NETWORK:
OnIAmRouterToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_I_COULD_BE_ROUTER_TO_NETWORK:
OnICouldBeRouterToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_REJECT_MESSAGE_TO_NETWORK:
OnRejectMessageToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_ROUTER_BUSY_TO_NETWORK:
OnRouterBusyToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_ROUTER_AVAILABLE_TO_NETWORK:
OnRouterAvailableToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_INIT_RT_TABLE:
OnInitRtTableToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_INIT_RT_TABLE_ACK:
OnInitRtTableAckToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_ESTABLISH_CONNECTION_TO_NETWORK:
OnEstablishConnectionToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
case BacnetNetworkMessageTypes.NETWORK_MESSAGE_DISCONNECT_CONNECTION_TO_NETWORK:
OnDisconnectConnectionToNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
default:
/* An unrecognized message is bad; send an error response. */
OnUnrecognizedNetworkMessage?.Invoke(this, adr, npduFunction, buffer, offset, messageLength);
break;
}
}
private void OnRecieve(IBacnetTransport sender, byte[] buffer, int offset, int msgLength, BacnetAddress remoteAddress)
{
try
{