forked from ela-compil/BACnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBACnetClient.cs
More file actions
2474 lines (2151 loc) · 125 KB
/
BACnetClient.cs
File metadata and controls
2474 lines (2151 loc) · 125 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
/**************************************************************************
* MIT License
*
* Copyright (C) 2014 Morten Kvistgaard <mk@pch-engineering.dk>
*
* 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.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
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 byte _lastSequenceNumber;
/// <summary>
/// only used when 'DefaultSegmentationHandling' = true
/// </summary>
private readonly LinkedList<byte[]> _segments = new LinkedList<byte[]>();
private readonly LastSegmentAck _lastSegmentAck = new LastSegmentAck();
private uint _writepriority;
public const byte DEFAULT_HOP_COUNT = 0xFF;
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;
/// <summary>
/// Used as the number of tentatives
/// </summary>
public int Retries
{
get { return _retries; }
set { _retries = Math.Max(1, value); }
}
public uint WritePriority
{
get { return _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;
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)
{
}
#if XAMARIN
#else
public BacnetClient(string portName, int baudRate, int timeout = DEFAULT_TIMEOUT, int retries = DEFAULT_RETRIES)
: this(new BacnetMstpProtocolTransport(portName, baudRate), timeout, retries)
{
}
#endif
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;
Trace.TraceInformation("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, BacnetEventNotificationData eventData);
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;
protected void ProcessConfirmedServiceRequest(BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, byte invokeId, byte[] buffer, int offset, int length)
{
try
{
Trace.WriteLine("ConfirmedServiceRequest", null);
raw_buffer = buffer;
raw_length = length;
raw_offset = offset;
OnConfirmedServiceRequest?.Invoke(this, adr, 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)
{
BacnetObjectId objectId;
BacnetPropertyReference property;
if (Services.DecodeReadProperty(buffer, offset, length, out objectId, out property) >= 0)
OnReadPropertyRequest(this, adr, invokeId, objectId, property, maxSegments);
else
Trace.TraceWarning("Couldn't decode DecodeReadProperty");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY && OnWritePropertyRequest != null)
{
BacnetObjectId objectId;
BacnetPropertyValue value;
if (Services.DecodeWriteProperty(buffer, offset, length, out objectId, out value) >= 0)
OnWritePropertyRequest(this, adr, invokeId, objectId, value, maxSegments);
else
Trace.TraceWarning("Couldn't decode DecodeWriteProperty");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROP_MULTIPLE && OnReadPropertyMultipleRequest != null)
{
IList<BacnetReadAccessSpecification> properties;
if (Services.DecodeReadPropertyMultiple(buffer, offset, length, out properties) >= 0)
OnReadPropertyMultipleRequest(this, adr, invokeId, properties, maxSegments);
else
Trace.TraceWarning("Couldn't decode DecodeReadPropertyMultiple");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROP_MULTIPLE && OnWritePropertyMultipleRequest != null)
{
BacnetObjectId objectId;
ICollection<BacnetPropertyValue> values;
if (Services.DecodeWritePropertyMultiple(buffer, offset, length, out objectId, out values) >= 0)
OnWritePropertyMultipleRequest(this, adr, invokeId, objectId, values, maxSegments);
else
Trace.TraceWarning("Couldn't decode DecodeWritePropertyMultiple");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_COV_NOTIFICATION && OnCOVNotification != null)
{
uint subscriberProcessIdentifier;
BacnetObjectId initiatingDeviceIdentifier;
BacnetObjectId monitoredObjectIdentifier;
uint timeRemaining;
ICollection<BacnetPropertyValue> values;
if (Services.DecodeCOVNotifyUnconfirmed(buffer, offset, length, out subscriberProcessIdentifier, out initiatingDeviceIdentifier, out monitoredObjectIdentifier, out timeRemaining, out values) >= 0)
OnCOVNotification(this, adr, invokeId, subscriberProcessIdentifier, initiatingDeviceIdentifier, monitoredObjectIdentifier, timeRemaining, true, values, maxSegments);
else
Trace.TraceWarning("Couldn't decode COVNotify");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_ATOMIC_WRITE_FILE && OnAtomicWriteFileRequest != null)
{
bool isStream;
BacnetObjectId objectId;
int position;
uint blockCount;
byte[][] blocks;
int[] counts;
if (Services.DecodeAtomicWriteFile(buffer, offset, length, out isStream, out objectId, out position, out blockCount, out blocks, out counts) >= 0)
OnAtomicWriteFileRequest(this, adr, invokeId, isStream, objectId, position, blockCount, blocks, counts, maxSegments);
else
Trace.TraceWarning("Couldn't decode AtomicWriteFile");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_ATOMIC_READ_FILE && OnAtomicReadFileRequest != null)
{
bool isStream;
BacnetObjectId objectId;
int position;
uint count;
if (Services.DecodeAtomicReadFile(buffer, offset, length, out isStream, out objectId, out position, out count) >= 0)
OnAtomicReadFileRequest(this, adr, invokeId, isStream, objectId, position, count, maxSegments);
else
Trace.TraceWarning("Couldn't decode AtomicReadFile");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV && OnSubscribeCOV != null)
{
uint subscriberProcessIdentifier;
BacnetObjectId monitoredObjectIdentifier;
bool cancellationRequest;
bool issueConfirmedNotifications;
uint lifetime;
if (Services.DecodeSubscribeCOV(buffer, offset, length, out subscriberProcessIdentifier, out monitoredObjectIdentifier, out cancellationRequest, out issueConfirmedNotifications, out lifetime) >= 0)
OnSubscribeCOV(this, adr, invokeId, subscriberProcessIdentifier, monitoredObjectIdentifier, cancellationRequest, issueConfirmedNotifications, lifetime, maxSegments);
else
Trace.TraceWarning("Couldn't decode SubscribeCOV");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV_PROPERTY && OnSubscribeCOVProperty != null)
{
uint subscriberProcessIdentifier;
BacnetObjectId monitoredObjectIdentifier;
BacnetPropertyReference monitoredProperty;
bool cancellationRequest;
bool issueConfirmedNotifications;
uint lifetime;
float covIncrement;
if (Services.DecodeSubscribeProperty(buffer, offset, length, out subscriberProcessIdentifier, out monitoredObjectIdentifier, out monitoredProperty, out cancellationRequest, out issueConfirmedNotifications, out lifetime, out covIncrement) >= 0)
OnSubscribeCOVProperty(this, adr, invokeId, subscriberProcessIdentifier, monitoredObjectIdentifier, monitoredProperty, cancellationRequest, issueConfirmedNotifications, lifetime, covIncrement, maxSegments);
else
Trace.TraceWarning("Couldn't decode SubscribeCOVProperty");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_DEVICE_COMMUNICATION_CONTROL && OnDeviceCommunicationControl != null)
{
uint timeDuration;
uint enableDisable;
string password;
if (Services.DecodeDeviceCommunicationControl(buffer, offset, length, out timeDuration, out enableDisable, out password) >= 0)
OnDeviceCommunicationControl(this, adr, invokeId, timeDuration, enableDisable, password, maxSegments);
else
Trace.TraceWarning("Couldn't decode DeviceCommunicationControl");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_REINITIALIZE_DEVICE && OnReinitializedDevice != null)
{
BacnetReinitializedStates state;
string password;
if (Services.DecodeReinitializeDevice(buffer, offset, length, out state, out password) >= 0)
OnReinitializedDevice(this, adr, invokeId, state, password, maxSegments);
else
Trace.TraceWarning("Couldn't decode ReinitializeDevice");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_EVENT_NOTIFICATION && OnEventNotify != null) // F. Chaxel
{
BacnetEventNotificationData eventData;
if (Services.DecodeEventNotifyData(buffer, offset, length, out eventData) >= 0)
OnEventNotify(this, adr, eventData);
else
Trace.TraceWarning("Couldn't decode Event/Alarm Notification");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_READ_RANGE && OnReadRange != null)
{
BacnetObjectId objectId;
BacnetPropertyReference property;
BacnetReadRangeRequestTypes requestType;
uint position;
DateTime time;
int count;
if (Services.DecodeReadRange(buffer, offset, length, out objectId, out property, out requestType, out position, out time, out count) >= 0)
OnReadRange(this, adr, invokeId, objectId, property, requestType, position, time, count, maxSegments);
else
Trace.TraceWarning("Couldn't decode ReadRange");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_CREATE_OBJECT && OnCreateObjectRequest != null)
{
BacnetObjectId objectId;
ICollection<BacnetPropertyValue> values;
if (Services.DecodeCreateObject(buffer, offset, length, out objectId, out values) >= 0)
OnCreateObjectRequest(this, adr, invokeId, objectId, values, maxSegments);
else
Trace.TraceWarning("Couldn't decode CreateObject");
}
else if (service == BacnetConfirmedServices.SERVICE_CONFIRMED_DELETE_OBJECT && OnDeleteObjectRequest != null)
{
BacnetObjectId objectId;
if (Services.DecodeDeleteObject(buffer, offset, length, out objectId) >= 0)
OnDeleteObjectRequest(this, adr, invokeId, objectId, maxSegments);
else
Trace.TraceWarning("Couldn't decode DecodeDeleteObject");
}
else
{
Trace.TraceWarning($"Confirmed service not handled: {service}");
SendConfirmedServiceReject(adr, invokeId, BacnetRejectReasons.REJECT_REASON_UNRECOGNIZED_SERVICE);
}
}
catch (Exception ex)
{
Trace.TraceError($"Error in ProcessConfirmedServiceRequest: {ex.Message}");
}
}
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 adr, BacnetPduTypes type, BacnetUnconfirmedServices service, byte[] buffer, int offset, int length)
{
try
{
Trace.WriteLine("UnconfirmedServiceRequest", null);
OnUnconfirmedServiceRequest?.Invoke(this, adr, type, service, buffer, offset, length);
if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_I_AM && OnIam != null)
{
uint deviceId;
uint maxAdpu;
BacnetSegmentations segmentation;
ushort vendorId;
if (Services.DecodeIamBroadcast(buffer, offset, out deviceId, out maxAdpu, out segmentation, out vendorId) >= 0)
OnIam(this, adr, deviceId, maxAdpu, segmentation, vendorId);
else
Trace.TraceWarning("Couldn't decode IamBroadcast");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_WHO_IS && OnWhoIs != null)
{
int lowLimit;
int highLimit;
if (Services.DecodeWhoIsBroadcast(buffer, offset, length, out lowLimit, out highLimit) >= 0)
OnWhoIs(this, adr, lowLimit, highLimit);
else
Trace.TraceWarning("Couldn't decode WhoIsBroadcast");
}
// added by thamersalek
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_WHO_HAS && OnWhoHas != null)
{
int lowLimit;
int highLimit;
BacnetObjectId objId;
string objName;
if (Services.DecodeWhoHasBroadcast(buffer, offset, length, out lowLimit, out highLimit, out objId, out objName) >= 0)
OnWhoHas(this, adr, lowLimit, highLimit, objId, objName);
else
Trace.TraceWarning("Couldn't decode WhoHasBroadcast");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_COV_NOTIFICATION && OnCOVNotification != null)
{
uint subscriberProcessIdentifier;
BacnetObjectId initiatingDeviceIdentifier;
BacnetObjectId monitoredObjectIdentifier;
uint timeRemaining;
ICollection<BacnetPropertyValue> values;
if (Services.DecodeCOVNotifyUnconfirmed(buffer, offset, length, out subscriberProcessIdentifier, out initiatingDeviceIdentifier, out monitoredObjectIdentifier, out timeRemaining, out values) >= 0)
OnCOVNotification(this, adr, 0, subscriberProcessIdentifier, initiatingDeviceIdentifier, monitoredObjectIdentifier, timeRemaining, false, values, BacnetMaxSegments.MAX_SEG0);
else
Trace.TraceWarning("Couldn't decode COVNotifyUnconfirmed");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_TIME_SYNCHRONIZATION && OnTimeSynchronize != null)
{
DateTime dateTime;
if (Services.DecodeTimeSync(buffer, offset, length, out dateTime) >= 0)
OnTimeSynchronize(this, adr, dateTime, false);
else
Trace.TraceWarning("Couldn't decode TimeSynchronize");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_UTC_TIME_SYNCHRONIZATION && OnTimeSynchronize != null)
{
DateTime dateTime;
if (Services.DecodeTimeSync(buffer, offset, length, out dateTime) >= 0)
OnTimeSynchronize(this, adr, dateTime, true);
else
Trace.TraceWarning("Couldn't decode TimeSynchronize");
}
else if (service == BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_EVENT_NOTIFICATION && OnEventNotify!=null) // F. Chaxel
{
BacnetEventNotificationData eventData;
if (Services.DecodeEventNotifyData(buffer, offset, length, out eventData) >= 0)
OnEventNotify(this, adr, eventData);
else
Trace.TraceWarning("Couldn't decode Event/Alarm Notification");
}
else
{
Trace.TraceWarning($"Unconfirmed service not handled: {service}");
// SendUnConfirmedServiceReject(adr); ? exists ?
}
}
catch (Exception ex)
{
Trace.TraceError($"Error in ProcessUnconfirmedServiceRequest: {ex.Message}");
}
}
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
{
Trace.WriteLine("SimpleAck", null);
OnSimpleAck?.Invoke(this, adr, type, service, invokeId, buffer, offset, length);
}
catch (Exception ex)
{
Trace.TraceError($"Error in ProcessSimpleAck: {ex.Message}");
}
}
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
{
Trace.WriteLine("ComplexAck", null);
OnComplexAck?.Invoke(this, adr, type, service, invokeId, buffer, offset, length);
}
catch (Exception ex)
{
Trace.TraceError($"Error in ProcessComplexAck: {ex.Message}");
}
}
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
{
Trace.WriteLine("Error", null);
BacnetErrorClasses errorClass;
BacnetErrorCodes errorCode;
if (Services.DecodeError(buffer, offset, length, out errorClass, out errorCode) < 0)
Trace.TraceWarning("Couldn't decode Error");
OnError?.Invoke(this, adr, type, service, invokeId, errorClass, errorCode, buffer, offset, length);
}
catch (Exception ex)
{
Trace.TraceError($"Error in ProcessError: {ex.Message}");
}
}
public delegate void AbortHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, byte invokeId, byte reason, byte[] buffer, int offset, int length);
public event AbortHandler OnAbort;
protected void ProcessAbort(BacnetAddress adr, BacnetPduTypes type, byte invokeId, byte reason, byte[] buffer, int offset, int length)
{
try
{
Trace.WriteLine("Abort", null);
OnAbort?.Invoke(this, adr, type, invokeId, reason, buffer, offset, length);
}
catch (Exception ex)
{
Trace.TraceError($"Error in ProcessAbort: {ex.Message}");
}
}
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
{
Trace.WriteLine("SegmentAck", null);
OnSegmentAck?.Invoke(this, adr, type, originalInvokeId, sequenceNumber, actualWindowSize, buffer, offset, length);
}
catch (Exception ex)
{
Trace.TraceError($"Error in ProcessSegmentAck: {ex.Message}");
}
}
public delegate void SegmentHandler(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, byte sequenceNumber, bool first, bool moreFollows, byte[] buffer, int offset, int length);
public event SegmentHandler OnSegment;
private void ProcessSegment(BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invokeId, BacnetMaxSegments maxSegments, BacnetMaxAdpu maxAdpu, bool server, byte sequenceNumber, byte proposedWindowNumber, byte[] buffer, int offset, int length)
{
var first = false;
if (sequenceNumber == 0 && _lastSequenceNumber == 0)
{
first = true;
}
else
{
//send negative ack
if (sequenceNumber != _lastSequenceNumber + 1)
{
SegmentAckResponse(adr, true, server, invokeId, _lastSequenceNumber, proposedWindowNumber);
Trace.WriteLine("Segment sequence out of order", null);
return;
}
}
_lastSequenceNumber = sequenceNumber;
var moreFollows = (type & BacnetPduTypes.MORE_FOLLOWS) == BacnetPduTypes.MORE_FOLLOWS;
if (!moreFollows)
_lastSequenceNumber = 0; //reset last sequenceNumber
//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, first, moreFollows, 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, first, moreFollows, buffer, offset, length);
}
private byte[] AssembleSegments()
{
return _segments.Aggregate(new byte[0], (current, next) =>
current.Concat(next).ToArray());
}
/// <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, bool first, bool moreFollows, byte[] buffer, int offset, int length)
{
if (first)
{
//clear any leftover segments
_segments.Clear();
//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, 0, 0);
else
APDU.EncodeComplexAck(encodedBuffer, type, service, invokeId, 0, 0);
_segments.AddLast(copy); // doesn't include BVLC or NPDU
}
else
{
//copy only content part
_segments.AddLast(buffer.Skip(offset).Take(length).ToArray());
}
//process when finished
if (moreFollows)
return;
//assemble whole part
var apduBuffer = AssembleSegments();
_segments.Clear();
//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:
{
BacnetUnconfirmedServices service;
var apduHeaderLen = APDU.DecodeUnconfirmedServiceRequest(buffer, offset, out type, out service);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessUnconfirmedServiceRequest(adr, type, service, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_SIMPLE_ACK:
{
BacnetConfirmedServices service;
byte invokeId;
var apduHeaderLen = APDU.DecodeSimpleAck(buffer, offset, out type, out service, out invokeId);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessSimpleAck(adr, type, service, invokeId, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_COMPLEX_ACK:
{
BacnetConfirmedServices service;
byte invokeId;
byte sequenceNumber;
byte proposedWindowNumber;
var apduHeaderLen = APDU.DecodeComplexAck(buffer, offset, out type, out service, out invokeId, out sequenceNumber, out 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:
{
byte originalInvokeId;
byte sequenceNumber;
byte actualWindowSize;
var apduHeaderLen = APDU.DecodeSegmentAck(buffer, offset, out type, out originalInvokeId, out sequenceNumber, out 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:
{
BacnetConfirmedServices service;
byte invokeId;
var apduHeaderLen = APDU.DecodeError(buffer, offset, out type, out service, out invokeId);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessError(adr, type, service, invokeId, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_REJECT:
case BacnetPduTypes.PDU_TYPE_ABORT:
{
byte invokeId;
byte reason;
var apduHeaderLen = APDU.DecodeAbort(buffer, offset, out type, out invokeId, out reason);
offset += apduHeaderLen;
length -= apduHeaderLen;
ProcessAbort(adr, type, invokeId, reason, buffer, offset, length);
}
break;
case BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST:
{
BacnetConfirmedServices service;
BacnetMaxSegments maxSegments;
BacnetMaxAdpu maxAdpu;
byte invokeId;
byte sequenceNumber;
byte proposedWindowNumber;
var apduHeaderLen = APDU.DecodeConfirmedServiceRequest(buffer, offset, out type, out service, out maxSegments, out maxAdpu, out invokeId, out sequenceNumber, out 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:
Trace.TraceWarning($"Something else arrived: {type}");
break;
}
}
private void OnRecieve(IBacnetTransport sender, byte[] buffer, int offset, int msgLength, BacnetAddress remoteAddress)
{
try
{
if (Transport == null)
return; //we're disposed
if (msgLength <= 0)
return;
BacnetNpduControls npduFunction;
BacnetAddress destination, source;
byte hopCount;
BacnetNetworkMessageTypes nmt;
ushort vendorId;
// parse
var npduLen = NPDU.Decode(buffer, offset, out npduFunction, out destination, out source, out hopCount, out nmt, out vendorId);
// Modif FC
remoteAddress.RoutedSource = source;
if ((npduFunction & BacnetNpduControls.NetworkLayerMessage) == BacnetNpduControls.NetworkLayerMessage)
{
Trace.TraceInformation("Network Layer message received");
return; // Network Layer message discarded
}
if (npduLen <= 0)
return;
offset += npduLen;
msgLength -= npduLen;
if (msgLength <= 0)
return;
var apduType = APDU.GetDecodedType(buffer, offset);
ProcessApdu(remoteAddress, apduType, buffer, offset, msgLength);
}
catch (Exception ex)
{
Trace.TraceError($"Error in OnRecieve: {ex.Message}");
}
}
// Modif FC
public void RegisterAsForeignDevice(string bbmdIP, short ttl, int port = DEFAULT_UDP_PORT)
{
try
{
var ep = new IPEndPoint(IPAddress.Parse(bbmdIP), port);
// dynamic avoid reference to BacnetIpUdpProtocolTransport or BacnetIpV6UdpProtocolTransport classes
dynamic clientDyn = Transport;
bool sent = clientDyn.SendRegisterAsForeignDevice(ep, ttl);
if (sent)
Trace.WriteLine("Sending Register as a Foreign Device ... ", null);
else
Trace.TraceWarning("The given address do not match with the IP version");
}
catch (Exception ex)
{
Trace.TraceError($"Error on RegisterAsForeignDevice (Wrong Transport, not IP ?) {ex.Message}");
}
}
public void RemoteWhoIs(string bbmdIP, int port = DEFAULT_UDP_PORT, int lowLimit = -1, int highLimit = -1)
{
try
{
var ep = new IPEndPoint(IPAddress.Parse(bbmdIP), port);
var b = GetEncodeBuffer(Transport.HeaderLength);
var broadcast = Transport.GetBroadcastAddress();
NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, broadcast, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, VendorId);
APDU.EncodeUnconfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_UNCONFIRMED_SERVICE_REQUEST, BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_WHO_IS);
Services.EncodeWhoIsBroadcast(b, lowLimit, highLimit);
// dynamic avoid reference to BacnetIpUdpProtocolTransport or BacnetIpV6UdpProtocolTransport classes
dynamic clientDyn = Transport;
bool sent = clientDyn.SendRemoteWhois(b.buffer, ep, b.offset);
if (sent == false)
Trace.TraceWarning("The given address do not match with the IP version");
else
Trace.WriteLine("Sending Remote Whois ... ", null);
}
catch (Exception ex)
{
Trace.TraceError($"Error on Sending Whois to remote BBMD (Wrong Transport, not IP ?) {ex.Message}");
}
}
public void WhoIs(int lowLimit = -1, int highLimit = -1, BacnetAddress receiver = null)
{
Trace.WriteLine("Sending WhoIs ... ", null);
var b = GetEncodeBuffer(Transport.HeaderLength);
// _receiver could be an unicast @ : for direct acces
// usefull on BIP for a known IP:Port, unknown device Id
if (receiver == null)
receiver = Transport.GetBroadcastAddress();
NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, receiver, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, VendorId);
APDU.EncodeUnconfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_UNCONFIRMED_SERVICE_REQUEST, BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_WHO_IS);
Services.EncodeWhoIsBroadcast(b, lowLimit, highLimit);
Transport.Send(b.buffer, Transport.HeaderLength, b.offset - Transport.HeaderLength, receiver, false, 0);
}
public void Iam(uint deviceId, BacnetSegmentations segmentation)
{
Trace.WriteLine("Sending Iam ... ", null);
var b = GetEncodeBuffer(Transport.HeaderLength);
var broadcast=Transport.GetBroadcastAddress();
NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, broadcast, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, VendorId);
APDU.EncodeUnconfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_UNCONFIRMED_SERVICE_REQUEST, BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_I_AM);
Services.EncodeIamBroadcast(b, deviceId, (uint)GetMaxApdu(), segmentation, VendorId);
Transport.Send(b.buffer, Transport.HeaderLength, b.offset - Transport.HeaderLength, broadcast, false, 0);
}
// ReSharper disable once InconsistentNaming
public void IHave(BacnetObjectId deviceId, BacnetObjectId objId, string objName)
{
Trace.WriteLine("Sending IHave ... ", null);
var b = GetEncodeBuffer(Transport.HeaderLength);
var broadcast = Transport.GetBroadcastAddress();
NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, broadcast, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, VendorId);
APDU.EncodeUnconfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_UNCONFIRMED_SERVICE_REQUEST, BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_I_HAVE);
Services.EncodeIhaveBroadcast(b, deviceId, objId, objName);
Transport.Send(b.buffer, Transport.HeaderLength, b.offset - Transport.HeaderLength, broadcast, false, 0);
}
public void SendUnconfirmedEventNotification(BacnetAddress adr, BacnetEventNotificationData eventData)
{
Trace.WriteLine("Sending Event Notification ... ", null);
var b = GetEncodeBuffer(Transport.HeaderLength);
NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, VendorId);
APDU.EncodeUnconfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_UNCONFIRMED_SERVICE_REQUEST, BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_EVENT_NOTIFICATION);
Services.EncodeEventNotifyUnconfirmed(b, eventData);
Transport.Send(b.buffer, Transport.HeaderLength, b.offset - Transport.HeaderLength, adr, false, 0);
}
public void SendConfirmedServiceReject(BacnetAddress adr, byte invokeId, BacnetRejectReasons reason)
{
Trace.WriteLine("Sending Service reject ... ", null);
var b = GetEncodeBuffer(Transport.HeaderLength);
NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, VendorId);
APDU.EncodeError(b, BacnetPduTypes.PDU_TYPE_REJECT, (BacnetConfirmedServices)reason, invokeId);
Transport.Send(b.buffer, Transport.HeaderLength, b.offset - Transport.HeaderLength, adr, false, 0);
}
public void SynchronizeTime(BacnetAddress adr, DateTime dateTime, bool utc)
{
Trace.WriteLine("Sending Time Synchronize ... ", null);
var b = GetEncodeBuffer(Transport.HeaderLength);
NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, VendorId);
APDU.EncodeUnconfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_UNCONFIRMED_SERVICE_REQUEST, utc
? BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_UTC_TIME_SYNCHRONIZATION
: BacnetUnconfirmedServices.SERVICE_UNCONFIRMED_TIME_SYNCHRONIZATION);
Services.EncodeTimeSync(b, dateTime);
Transport.Send(b.buffer, Transport.HeaderLength, b.offset - Transport.HeaderLength, adr, false, 0);
}
public int GetMaxApdu()
{
int maxAPDU;
switch (Transport.MaxAdpuLength)
{
case BacnetMaxAdpu.MAX_APDU1476:
maxAPDU = 1476;
break;
case BacnetMaxAdpu.MAX_APDU1024:
maxAPDU = 1024;
break;
case BacnetMaxAdpu.MAX_APDU480:
maxAPDU = 480;
break;
case BacnetMaxAdpu.MAX_APDU206:
maxAPDU = 206;
break;
case BacnetMaxAdpu.MAX_APDU128:
maxAPDU = 128;
break;
case BacnetMaxAdpu.MAX_APDU50:
maxAPDU = 50;
break;
default:
throw new NotImplementedException();
}
//max udp payload IRL seems to differ from the expectations in BACnet
//so we have to adjust it. (In order to fulfill the standard)
const int maxNPDUHeaderLength = 4; //usually it's '2', but it can also be more than '4'. Beware!
return Math.Min(maxAPDU, Transport.MaxBufferLength - Transport.HeaderLength - maxNPDUHeaderLength);
}
public int GetFileBufferMaxSize()
{
//6 should be the max_apdu_header_length for Confirmed (with segmentation)
//12 should be the max_atomic_write_file
return GetMaxApdu() - 18;
}