-
Notifications
You must be signed in to change notification settings - Fork 310
/
buffaloZdo.ts
2275 lines (1938 loc) · 81.3 KB
/
buffaloZdo.ts
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
import Buffalo from '../../buffalo/buffalo';
import {logger} from '../../utils/logger';
import {DEFAULT_ENCRYPTION_KEY_SIZE, EUI64_SIZE, EXTENDED_PAN_ID_SIZE, PAN_ID_SIZE} from '../consts';
import {ClusterId, EUI64, NodeId, ProfileId} from '../tstypes';
import * as ZSpecUtils from '../utils';
import {ClusterId as ZdoClusterId} from './definition/clusters';
import {ZDO_MESSAGE_OVERHEAD, UNICAST_BINDING, MULTICAST_BINDING, CHALLENGE_VALUE_SIZE, CURVE_PUBLIC_POINT_SIZE} from './definition/consts';
import {LeaveRequestFlags, GlobalTLV} from './definition/enums';
import {Status} from './definition/status';
import {
ActiveEndpointsResponse,
BindingTableResponse,
EndDeviceAnnounce,
IEEEAddressResponse,
LQITableResponse,
MatchDescriptorsResponse,
NetworkAddressResponse,
NodeDescriptorResponse,
ParentAnnounceResponse,
PowerDescriptorResponse,
RoutingTableResponse,
SimpleDescriptorResponse,
SystemServerDiscoveryResponse,
LQITableEntry,
RoutingTableEntry,
BindingTableEntry,
NwkUpdateResponse,
NwkEnhancedUpdateResponse,
NwkIEEEJoiningListResponse,
NwkUnsolicitedEnhancedUpdateResponse,
NwkBeaconSurveyResponse,
StartKeyNegotiationResponse,
RetrieveAuthenticationTokenResponse,
GetAuthenticationLevelResponse,
SetConfigurationResponse,
GetConfigurationResponse,
ChallengeResponse,
APSFrameCounterChallengeTLV,
AuthenticationTokenIdTLV,
Curve25519PublicPointTLV,
FragmentationParametersGlobalTLV,
SelectedKeyNegotiationMethodTLV,
PotentialParentsTLV,
ClearAllBindingsReqEUI64TLV,
BeaconAppendixEncapsulationGlobalTLV,
TargetIEEEAddressTLV,
NextPanIdChangeGlobalTLV,
NextChannelChangeGlobalTLV,
ConfigurationParametersGlobalTLV,
DeviceEUI64ListTLV,
BeaconSurveyResultsTLV,
DeviceAuthenticationLevelTLV,
ProcessingStatusTLV,
APSFrameCounterResponseTLV,
BeaconSurveyConfigurationTLV,
ManufacturerSpecificGlobalTLV,
SupportedKeyNegotiationMethodsGlobalTLV,
PanIdConflictReportGlobalTLV,
SymmetricPassphraseGlobalTLV,
RouterInformationGlobalTLV,
JoinerEncapsulationGlobalTLV,
DeviceCapabilityExtensionGlobalTLV,
TLV,
LocalTLVReader,
ServerMask,
} from './definition/tstypes';
import * as Utils from './utils';
import {ZdoStatusError} from './zdoStatusError';
const NS = 'zh:zdo:buffalo';
const MAX_BUFFER_SIZE = 255;
export class BuffaloZdo extends Buffalo {
/**
* Set the position of the internal position tracker.
* TODO: move to base `Buffalo` class
* @param position
*/
public setPosition(position: number): void {
this.position = position;
}
/**
* Set the byte at given position without affecting the internal position tracker.
* TODO: move to base `Buffalo` class
* @param position
* @param value
*/
public setByte(position: number, value: number): void {
this.buffer.writeUInt8(value, position);
}
/**
* Get the byte at given position without affecting the internal position tracker.
* TODO: move to base `Buffalo` class
* @param position
* @returns
*/
public getByte(position: number): number {
return this.buffer.readUInt8(position);
}
/**
* Check if internal buffer has enough bytes to satisfy: (current position + given count).
* TODO: move to base `Buffalo` class
* @param count
* @returns True if has given more bytes
*/
public isMoreBy(count: number): boolean {
return this.position + count <= this.buffer.length;
}
//-- GLOBAL TLVS
private writeManufacturerSpecificGlobalTLV(tlv: ManufacturerSpecificGlobalTLV): void {
this.writeUInt16(tlv.zigbeeManufacturerId);
this.writeBuffer(tlv.additionalData, tlv.additionalData.length);
}
private readManufacturerSpecificGlobalTLV(length: number): ManufacturerSpecificGlobalTLV {
logger.debug(`readManufacturerSpecificGlobalTLV with length=${length}`, NS);
if (length < 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 2.`);
}
const zigbeeManufacturerId = this.readUInt16();
const additionalData = this.readBuffer(length - 2);
return {
zigbeeManufacturerId,
additionalData,
};
}
private writeSupportedKeyNegotiationMethodsGlobalTLV(tlv: SupportedKeyNegotiationMethodsGlobalTLV): void {
this.writeUInt8(tlv.keyNegotiationProtocolsBitmask);
this.writeUInt8(tlv.preSharedSecretsBitmask);
if (tlv.sourceDeviceEui64) {
this.writeIeeeAddr(tlv.sourceDeviceEui64);
}
}
private readSupportedKeyNegotiationMethodsGlobalTLV(length: number): SupportedKeyNegotiationMethodsGlobalTLV {
logger.debug(`readSupportedKeyNegotiationMethodsGlobalTLV with length=${length}`, NS);
if (length < 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 2.`);
}
const keyNegotiationProtocolsBitmask = this.readUInt8();
const preSharedSecretsBitmask = this.readUInt8();
let sourceDeviceEui64: EUI64;
if (length >= 2 + EUI64_SIZE) {
sourceDeviceEui64 = this.readIeeeAddr();
}
return {
keyNegotiationProtocolsBitmask,
preSharedSecretsBitmask,
sourceDeviceEui64,
};
}
private writePanIdConflictReportGlobalTLV(tlv: PanIdConflictReportGlobalTLV): void {
this.writeUInt16(tlv.nwkPanIdConflictCount);
}
private readPanIdConflictReportGlobalTLV(length: number): PanIdConflictReportGlobalTLV {
logger.debug(`readPanIdConflictReportGlobalTLV with length=${length}`, NS);
if (length < 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 2.`);
}
const nwkPanIdConflictCount = this.readUInt16();
return {
nwkPanIdConflictCount,
};
}
private writeNextPanIdChangeGlobalTLV(tlv: NextPanIdChangeGlobalTLV): void {
this.writeUInt16(tlv.panId);
}
private readNextPanIdChangeGlobalTLV(length: number): NextPanIdChangeGlobalTLV {
logger.debug(`readNextPanIdChangeGlobalTLV with length=${length}`, NS);
if (length < PAN_ID_SIZE) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least ${PAN_ID_SIZE}.`);
}
const panId = this.readUInt16();
return {
panId,
};
}
private writeNextChannelChangeGlobalTLV(tlv: NextChannelChangeGlobalTLV): void {
this.writeUInt32(tlv.channel);
}
private readNextChannelChangeGlobalTLV(length: number): NextChannelChangeGlobalTLV {
logger.debug(`readNextChannelChangeGlobalTLV with length=${length}`, NS);
if (length < 4) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 4.`);
}
const channel = this.readUInt32();
return {
channel,
};
}
private writeSymmetricPassphraseGlobalTLV(tlv: SymmetricPassphraseGlobalTLV): void {
this.writeBuffer(tlv.passphrase, DEFAULT_ENCRYPTION_KEY_SIZE);
}
private readSymmetricPassphraseGlobalTLV(length: number): SymmetricPassphraseGlobalTLV {
logger.debug(`readSymmetricPassphraseGlobalTLV with length=${length}`, NS);
if (length < DEFAULT_ENCRYPTION_KEY_SIZE) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least ${DEFAULT_ENCRYPTION_KEY_SIZE}.`);
}
const passphrase = this.readBuffer(DEFAULT_ENCRYPTION_KEY_SIZE);
return {
passphrase,
};
}
private writeRouterInformationGlobalTLV(tlv: RouterInformationGlobalTLV): void {
this.writeUInt16(tlv.bitmask);
}
private readRouterInformationGlobalTLV(length: number): RouterInformationGlobalTLV {
logger.debug(`readRouterInformationGlobalTLV with length=${length}`, NS);
if (length < 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 2.`);
}
const bitmask = this.readUInt16();
return {
bitmask,
};
}
private writeFragmentationParametersGlobalTLV(tlv: FragmentationParametersGlobalTLV): void {
this.writeUInt16(tlv.nwkAddress);
if (tlv.fragmentationOptions != undefined) {
this.writeUInt8(tlv.fragmentationOptions);
}
if (tlv.maxIncomingTransferUnit != undefined) {
this.writeUInt16(tlv.maxIncomingTransferUnit);
}
}
private readFragmentationParametersGlobalTLV(length: number): FragmentationParametersGlobalTLV {
logger.debug(`readFragmentationParametersGlobalTLV with length=${length}`, NS);
if (length < 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 2.`);
}
const nwkAddress = this.readUInt16();
let fragmentationOptions: number;
let maxIncomingTransferUnit: number;
if (length >= 3) {
fragmentationOptions = this.readUInt8();
}
if (length >= 5) {
maxIncomingTransferUnit = this.readUInt16();
}
return {
nwkAddress,
fragmentationOptions,
maxIncomingTransferUnit,
};
}
private writeJoinerEncapsulationGlobalTLV(encapsulationTLV: JoinerEncapsulationGlobalTLV): void {
this.writeGlobalTLVs(encapsulationTLV.additionalTLVs);
}
private readJoinerEncapsulationGlobalTLV(length: number): JoinerEncapsulationGlobalTLV {
logger.debug(`readJoinerEncapsulationGlobalTLV with length=${length}`, NS);
// at least the length of tagId+length for first encapsulated tlv, doesn't make sense otherwise
if (length < 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 2.`);
}
const encapsulationBuffalo = new BuffaloZdo(this.readBuffer(length));
const additionalTLVs = encapsulationBuffalo.readTLVs(null, true);
return {
additionalTLVs,
};
}
private writeBeaconAppendixEncapsulationGlobalTLV(encapsulationTLV: BeaconAppendixEncapsulationGlobalTLV): void {
this.writeGlobalTLVs(encapsulationTLV.additionalTLVs);
}
private readBeaconAppendixEncapsulationGlobalTLV(length: number): BeaconAppendixEncapsulationGlobalTLV {
logger.debug(`readBeaconAppendixEncapsulationGlobalTLV with length=${length}`, NS);
// at least the length of tagId+length for first encapsulated tlv, doesn't make sense otherwise
if (length < 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 2.`);
}
const encapsulationBuffalo = new BuffaloZdo(this.readBuffer(length));
// Global: SupportedKeyNegotiationMethodsGlobalTLV
// Global: FragmentationParametersGlobalTLV
const additionalTLVs = encapsulationBuffalo.readTLVs(null, true);
return {
additionalTLVs,
};
}
private writeConfigurationParametersGlobalTLV(configurationParameters: ConfigurationParametersGlobalTLV): void {
this.writeUInt16(configurationParameters.configurationParameters);
}
private readConfigurationParametersGlobalTLV(length: number): ConfigurationParametersGlobalTLV {
logger.debug(`readConfigurationParametersGlobalTLV with length=${length}`, NS);
if (length < 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 2.`);
}
const configurationParameters = this.readUInt16();
return {
configurationParameters,
};
}
private writeDeviceCapabilityExtensionGlobalTLV(tlv: DeviceCapabilityExtensionGlobalTLV): void {
this.writeBuffer(tlv.data, tlv.data.length);
}
private readDeviceCapabilityExtensionGlobalTLV(length: number): DeviceCapabilityExtensionGlobalTLV {
logger.debug(`readDeviceCapabilityExtensionGlobalTLV with length=${length}`, NS);
const data = this.readBuffer(length);
return {
data,
};
}
public writeGlobalTLV(tlv: TLV): void {
this.writeUInt8(tlv.tagId);
this.writeUInt8(tlv.length - 1); // remove offset (spec quirk...)
switch (tlv.tagId) {
case GlobalTLV.MANUFACTURER_SPECIFIC: {
this.writeManufacturerSpecificGlobalTLV(tlv.tlv as ManufacturerSpecificGlobalTLV);
break;
}
case GlobalTLV.SUPPORTED_KEY_NEGOTIATION_METHODS: {
this.writeSupportedKeyNegotiationMethodsGlobalTLV(tlv.tlv as SupportedKeyNegotiationMethodsGlobalTLV);
break;
}
case GlobalTLV.PAN_ID_CONFLICT_REPORT: {
this.writePanIdConflictReportGlobalTLV(tlv.tlv as PanIdConflictReportGlobalTLV);
break;
}
case GlobalTLV.NEXT_PAN_ID_CHANGE: {
this.writeNextPanIdChangeGlobalTLV(tlv.tlv as NextPanIdChangeGlobalTLV);
break;
}
case GlobalTLV.NEXT_CHANNEL_CHANGE: {
this.writeNextChannelChangeGlobalTLV(tlv.tlv as NextChannelChangeGlobalTLV);
break;
}
case GlobalTLV.SYMMETRIC_PASSPHRASE: {
this.writeSymmetricPassphraseGlobalTLV(tlv.tlv as SymmetricPassphraseGlobalTLV);
break;
}
case GlobalTLV.ROUTER_INFORMATION: {
this.writeRouterInformationGlobalTLV(tlv.tlv as RouterInformationGlobalTLV);
break;
}
case GlobalTLV.FRAGMENTATION_PARAMETERS: {
this.writeFragmentationParametersGlobalTLV(tlv.tlv as FragmentationParametersGlobalTLV);
break;
}
case GlobalTLV.JOINER_ENCAPSULATION: {
this.writeJoinerEncapsulationGlobalTLV(tlv.tlv as JoinerEncapsulationGlobalTLV);
break;
}
case GlobalTLV.BEACON_APPENDIX_ENCAPSULATION: {
this.writeBeaconAppendixEncapsulationGlobalTLV(tlv.tlv as BeaconAppendixEncapsulationGlobalTLV);
break;
}
case GlobalTLV.CONFIGURATION_PARAMETERS: {
this.writeConfigurationParametersGlobalTLV(tlv.tlv as ConfigurationParametersGlobalTLV);
break;
}
case GlobalTLV.DEVICE_CAPABILITY_EXTENSION: {
this.writeDeviceCapabilityExtensionGlobalTLV(tlv.tlv as DeviceCapabilityExtensionGlobalTLV);
break;
}
default: {
throw new ZdoStatusError(Status.NOT_SUPPORTED);
}
}
}
public readGlobalTLV(tagId: number, length: number): TLV['tlv'] {
switch (tagId) {
case GlobalTLV.MANUFACTURER_SPECIFIC: {
return this.readManufacturerSpecificGlobalTLV(length);
}
case GlobalTLV.SUPPORTED_KEY_NEGOTIATION_METHODS: {
return this.readSupportedKeyNegotiationMethodsGlobalTLV(length);
}
case GlobalTLV.PAN_ID_CONFLICT_REPORT: {
return this.readPanIdConflictReportGlobalTLV(length);
}
case GlobalTLV.NEXT_PAN_ID_CHANGE: {
return this.readNextPanIdChangeGlobalTLV(length);
}
case GlobalTLV.NEXT_CHANNEL_CHANGE: {
return this.readNextChannelChangeGlobalTLV(length);
}
case GlobalTLV.SYMMETRIC_PASSPHRASE: {
return this.readSymmetricPassphraseGlobalTLV(length);
}
case GlobalTLV.ROUTER_INFORMATION: {
return this.readRouterInformationGlobalTLV(length);
}
case GlobalTLV.FRAGMENTATION_PARAMETERS: {
return this.readFragmentationParametersGlobalTLV(length);
}
case GlobalTLV.JOINER_ENCAPSULATION: {
return this.readJoinerEncapsulationGlobalTLV(length);
}
case GlobalTLV.BEACON_APPENDIX_ENCAPSULATION: {
return this.readBeaconAppendixEncapsulationGlobalTLV(length);
}
case GlobalTLV.CONFIGURATION_PARAMETERS: {
return this.readConfigurationParametersGlobalTLV(length);
}
case GlobalTLV.DEVICE_CAPABILITY_EXTENSION: {
return this.readDeviceCapabilityExtensionGlobalTLV(length);
}
default: {
// validation: unknown tag shall be ignored
return null;
}
}
}
public writeGlobalTLVs(tlvs: TLV[]): void {
for (const tlv of tlvs) {
this.writeGlobalTLV(tlv);
}
}
//-- LOCAL TLVS
// write only
// private readBeaconSurveyConfigurationTLV(length: number): BeaconSurveyConfigurationTLV {
// logger.debug(`readBeaconSurveyConfigurationTLV with length=${length}`, NS);
// const count = this.readUInt8();
// /* istanbul ignore else */
// if (length !== (1 + (count * 4) + 1)) {
// throw new Error(`Malformed TLV. Invalid length '${length}', expected ${(1 + (count * 4) + 1)}.`);
// }
// const scanChannelList = this.readListUInt32(count);
// const configurationBitmask = this.readUInt8();
// return {
// scanChannelList,
// configurationBitmask,
// };
// }
private readCurve25519PublicPointTLV(length: number): Curve25519PublicPointTLV {
logger.debug(`readCurve25519PublicPointTLV with length=${length}`, NS);
if (length !== EUI64_SIZE + CURVE_PUBLIC_POINT_SIZE) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected ${EUI64_SIZE + CURVE_PUBLIC_POINT_SIZE}.`);
}
const eui64 = this.readIeeeAddr();
const publicPoint = this.readBuffer(CURVE_PUBLIC_POINT_SIZE);
return {
eui64,
publicPoint,
};
}
// write only
// private readTargetIEEEAddressTLV(length: number): TargetIEEEAddressTLV {
// logger.debug(`readTargetIEEEAddressTLV with length=${length}`, NS);
// /* istanbul ignore else */
// if (length !== EUI64_SIZE) {
// throw new Error(`Malformed TLV. Invalid length '${length}', expected ${EUI64_SIZE}.`);
// }
// const ieee = this.readIeeeAddr();
// return {
// ieee,
// };
// }
// write only
// private readSelectedKeyNegotiationMethodTLV(length: number): SelectedKeyNegotiationMethodTLV {
// logger.debug(`readSelectedKeyNegotiationMethodTLV with length=${length}`, NS);
// /* istanbul ignore else */
// if (length !== 10) {
// throw new Error(`Malformed TLV. Invalid length '${length}', expected 10.`);
// }
// const protocol = this.readUInt8();
// const presharedSecret = this.readUInt8();
// const sendingDeviceEui64 = this.readIeeeAddr();
// return {
// protocol,
// presharedSecret,
// sendingDeviceEui64,
// };
// }
// write only
// private readDeviceEUI64ListTLV(length: number): DeviceEUI64ListTLV {
// logger.debug(`readDeviceEUI64ListTLV with length=${length}`, NS);
// const count = this.readUInt8();
// /* istanbul ignore else */
// if (length !== (1 + (count * EUI64_SIZE))) {
// throw new Error(`Malformed TLV. Invalid length '${length}', expected ${(1 + (count * EUI64_SIZE))}.`);
// }
// const eui64List: DeviceEUI64ListTLV['eui64List'] = [];
// for (let i = 0; i < count; i++) {
// const eui64 = this.readIeeeAddr();
// eui64List.push(eui64);
// }
// return {
// eui64List,
// };
// }
private readAPSFrameCounterResponseTLV(length: number): APSFrameCounterResponseTLV {
logger.debug(`readAPSFrameCounterResponseTLV with length=${length}`, NS);
if (length !== 32) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected 32.`);
}
const responderEui64 = this.readIeeeAddr();
const receivedChallengeValue = this.readBuffer(CHALLENGE_VALUE_SIZE);
const apsFrameCounter = this.readUInt32();
const challengeSecurityFrameCounter = this.readUInt32();
const mic = this.readBuffer(8);
return {
responderEui64,
receivedChallengeValue,
apsFrameCounter,
challengeSecurityFrameCounter,
mic,
};
}
private readBeaconSurveyResultsTLV(length: number): BeaconSurveyResultsTLV {
logger.debug(`readBeaconSurveyResultsTLV with length=${length}`, NS);
if (length !== 4) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected 4.`);
}
const totalBeaconsReceived = this.readUInt8();
const onNetworkBeacons = this.readUInt8();
const potentialParentBeacons = this.readUInt8();
const otherNetworkBeacons = this.readUInt8();
return {
totalBeaconsReceived,
onNetworkBeacons,
potentialParentBeacons,
otherNetworkBeacons,
};
}
private readPotentialParentsTLV(length: number): PotentialParentsTLV {
logger.debug(`readPotentialParentsTLV with length=${length}`, NS);
if (length < 4) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected at least 4.`);
}
const currentParentNwkAddress = this.readUInt16();
const currentParentLQA = this.readUInt8();
// [0x00 - 0x05]
const entryCount = this.readUInt8();
if (length !== 4 + entryCount * 3) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected ${4 + entryCount * 3}.`);
}
const potentialParents: PotentialParentsTLV['potentialParents'] = [];
for (let i = 0; i < entryCount; i++) {
const nwkAddress = this.readUInt16();
const lqa = this.readUInt8();
potentialParents.push({
nwkAddress,
lqa,
});
}
return {
currentParentNwkAddress,
currentParentLQA,
entryCount,
potentialParents,
};
}
private readDeviceAuthenticationLevelTLV(length: number): DeviceAuthenticationLevelTLV {
logger.debug(`readDeviceAuthenticationLevelTLV with length=${length}`, NS);
if (length !== 10) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected 10.`);
}
const remoteNodeIeee = this.readIeeeAddr();
const initialJoinMethod = this.readUInt8();
const activeLinkKeyType = this.readUInt8();
return {
remoteNodeIeee,
initialJoinMethod,
activeLinkKeyType,
};
}
private readProcessingStatusTLV(length: number): ProcessingStatusTLV {
logger.debug(`readProcessingStatusTLV with length=${length}`, NS);
const count = this.readUInt8();
if (length !== 1 + count * 2) {
throw new Error(`Malformed TLV. Invalid length '${length}', expected ${1 + count * 2}.`);
}
const tlvs: ProcessingStatusTLV['tlvs'] = [];
for (let i = 0; i < count; i++) {
const tagId = this.readUInt8();
const processingStatus = this.readUInt8();
tlvs.push({
tagId,
processingStatus,
});
}
return {
count,
tlvs,
};
}
/**
* ANNEX I ZIGBEE TLV DEFINITIONS AND FORMAT
*
* Unknown tags => TLV ignored
* Duplicate tags => reject message except for MANUFACTURER_SPECIFIC_GLOBAL_TLV
* Malformed TLVs => reject message
*
* @param localTLVReaders Mapping of tagID to local TLV reader function
* @param encapsulated Default false. If true, this is reading inside an encapsuled TLV (excludes further encapsulation)
* @returns
*/
public readTLVs(localTLVReaders: Map<number, LocalTLVReader> = null, encapsulated: boolean = false): TLV[] {
const tlvs: TLV[] = [];
while (this.isMore()) {
const tagId = this.readUInt8();
// validation: cannot have duplicate tagId, except MANUFACTURER_SPECIFIC_GLOBAL_TLV
if (tagId !== GlobalTLV.MANUFACTURER_SPECIFIC && tlvs.findIndex((tlv) => tlv.tagId === tagId) !== -1) {
throw new Error(`Duplicate tag. Cannot have more than one of tagId=${tagId}.`);
}
// validation: encapsulation TLV cannot contain another encapsulation TLV, outer considered malformed, reject message
if (encapsulated && (tagId === GlobalTLV.BEACON_APPENDIX_ENCAPSULATION || tagId === GlobalTLV.JOINER_ENCAPSULATION)) {
throw new Error(`Invalid nested encapsulation for tagId=${tagId}.`);
}
const length = this.readUInt8() + 1; // add offset (spec quirk...)
console.log(this.position, length);
// validation: invalid if not at least ${length} bytes to read
if (!this.isMoreBy(length)) {
throw new Error(`Malformed TLV. Invalid data length for tagId=${tagId}, expected ${length}.`);
}
const nextTLVStart = this.getPosition() + length;
// null == unknown tag
let tlv: TLV['tlv'] = null;
if (tagId < GlobalTLV.MANUFACTURER_SPECIFIC) {
/* istanbul ignore else */
if (localTLVReaders) {
const localTLVReader = localTLVReaders.get(tagId);
/* istanbul ignore else */
if (localTLVReader) {
tlv = localTLVReader.call(this, length);
} else {
logger.debug(`Local TLV found tagId=${tagId} but no reader given for it. Ignoring it.`, NS);
}
} else {
logger.debug(`Local TLV found tagId=${tagId} but no reader available. Ignoring it.`, NS);
}
} else {
tlv = this.readGlobalTLV(tagId, length);
}
// validation: unknown tag shall be ignored
/* istanbul ignore else */
if (tlv != null) {
tlvs.push({
tagId,
length,
tlv,
});
} else {
logger.debug(`Unknown TLV tagId=${tagId}. Ignoring it.`, NS);
}
// ensure we're at the right position as dictated by the tlv length field, and not the tlv reader (should be the same if proper)
this.setPosition(nextTLVStart);
}
return tlvs;
}
//-- REQUESTS
/**
* @see ClusterId.NETWORK_ADDRESS_REQUEST
* @param target IEEE address for the request
* @param reportKids True to request that the target list their children in the response. [request type = 0x01]
* @param childStartIndex The index of the first child to list in the response. Ignored if reportKids is false.
*/
public static buildNetworkAddressRequest(target: EUI64, reportKids: boolean, childStartIndex: number): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeIeeeAddr(target);
buffalo.writeUInt8(reportKids ? 1 : 0);
buffalo.writeUInt8(childStartIndex);
return buffalo.getWritten();
}
/**
* @see ClusterId.IEEE_ADDRESS_REQUEST
* Can be sent to target, or to another node that will send to target.
* @param target NWK address for the request
* @param reportKids True to request that the target list their children in the response. [request type = 0x01]
* @param childStartIndex The index of the first child to list in the response. Ignored if reportKids is false.
*/
public static buildIeeeAddressRequest(target: NodeId, reportKids: boolean, childStartIndex: number): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeUInt16(target);
buffalo.writeUInt8(reportKids ? 1 : 0);
buffalo.writeUInt8(childStartIndex);
return buffalo.getWritten();
}
/**
* @see ClusterId.NODE_DESCRIPTOR_REQUEST
* @param target NWK address for the request
*/
public static buildNodeDescriptorRequest(target: NodeId, fragmentationParameters?: FragmentationParametersGlobalTLV): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeUInt16(target);
if (fragmentationParameters) {
let length = 2;
/* istanbul ignore else */
if (fragmentationParameters.fragmentationOptions) {
length += 1;
}
/* istanbul ignore else */
if (fragmentationParameters.maxIncomingTransferUnit) {
length += 2;
}
buffalo.writeGlobalTLV({tagId: GlobalTLV.FRAGMENTATION_PARAMETERS, length, tlv: fragmentationParameters});
}
return buffalo.getWritten();
}
/**
* @see ClusterId.POWER_DESCRIPTOR_REQUEST
* @param target NWK address for the request
*/
public static buildPowerDescriptorRequest(target: NodeId): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeUInt16(target);
return buffalo.getWritten();
}
/**
* @see ClusterId.SIMPLE_DESCRIPTOR_REQUEST
* @param target NWK address for the request
* @param targetEndpoint The endpoint on the destination
*/
public static buildSimpleDescriptorRequest(target: NodeId, targetEndpoint: number): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeUInt16(target);
buffalo.writeUInt8(targetEndpoint);
return buffalo.getWritten();
}
/**
* @see ClusterId.ACTIVE_ENDPOINTS_REQUEST
* @param target NWK address for the request
*/
public static buildActiveEndpointsRequest(target: NodeId): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeUInt16(target);
return buffalo.getWritten();
}
/**
* @see ClusterId.MATCH_DESCRIPTORS_REQUEST
* @param target NWK address for the request
* @param profileId Profile ID to be matched at the destination
* @param inClusterList List of Input ClusterIDs to be used for matching
* @param outClusterList List of Output ClusterIDs to be used for matching
*/
public static buildMatchDescriptorRequest(target: NodeId, profileId: ProfileId, inClusterList: ClusterId[], outClusterList: ClusterId[]): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeUInt16(target);
buffalo.writeUInt16(profileId);
buffalo.writeUInt8(inClusterList.length);
buffalo.writeListUInt16(inClusterList);
buffalo.writeUInt8(outClusterList.length);
buffalo.writeListUInt16(outClusterList);
return buffalo.getWritten();
}
/**
* @see ClusterId.SYSTEM_SERVER_DISCOVERY_REQUEST
* @param serverMask See Table 2-34 for bit assignments.
*/
public static buildSystemServiceDiscoveryRequest(serverMask: ServerMask): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeUInt16(Utils.createServerMask(serverMask));
return buffalo.getWritten();
}
/**
* @see ClusterId.PARENT_ANNOUNCE
* @param children The IEEE addresses of the children bound to the parent.
*/
public static buildParentAnnounce(children: EUI64[]): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeUInt8(children.length);
for (const child of children) {
buffalo.writeIeeeAddr(child);
}
return buffalo.getWritten();
}
/**
* @see ClusterId.BIND_REQUEST
*
* @param source The IEEE address for the source.
* @param sourceEndpoint The source endpoint for the binding entry.
* @param clusterId The identifier of the cluster on the source device that is bound to the destination.
* @param type The addressing mode for the destination address used in this command, either ::UNICAST_BINDING, ::MULTICAST_BINDING.
* @param destination The destination address for the binding entry. IEEE for ::UNICAST_BINDING.
* @param groupAddress The destination address for the binding entry. Group ID for ::MULTICAST_BINDING.
* @param destinationEndpoint The destination endpoint for the binding entry. Only if ::UNICAST_BINDING.
*/
public static buildBindRequest(
source: EUI64,
sourceEndpoint: number,
clusterId: ClusterId,
type: number,
destination: EUI64,
groupAddress: number,
destinationEndpoint: number,
): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeIeeeAddr(source);
buffalo.writeUInt8(sourceEndpoint);
buffalo.writeUInt16(clusterId);
buffalo.writeUInt8(type);
switch (type) {
case UNICAST_BINDING: {
buffalo.writeIeeeAddr(destination);
buffalo.writeUInt8(destinationEndpoint);
break;
}
case MULTICAST_BINDING: {
buffalo.writeUInt16(groupAddress);
break;
}
default:
throw new ZdoStatusError(Status.NOT_SUPPORTED);
}
return buffalo.getWritten();
}
/**
* @see ClusterId.UNBIND_REQUEST
*
* @param source The IEEE address for the source.
* @param sourceEndpoint The source endpoint for the binding entry.
* @param clusterId The identifier of the cluster on the source device that is bound to the destination.
* @param type The addressing mode for the destination address used in this command, either ::UNICAST_BINDING, ::MULTICAST_BINDING.
* @param destination The destination address for the binding entry. IEEE for ::UNICAST_BINDING.
* @param groupAddress The destination address for the binding entry. Group ID for ::MULTICAST_BINDING.
* @param destinationEndpoint The destination endpoint for the binding entry. Only if ::UNICAST_BINDING.
*/
public static buildUnbindRequest(
source: EUI64,
sourceEndpoint: number,
clusterId: ClusterId,
type: ClusterId,
destination: EUI64,
groupAddress: number,
destinationEndpoint: number,
): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
buffalo.writeIeeeAddr(source);
buffalo.writeUInt8(sourceEndpoint);
buffalo.writeUInt16(clusterId);
buffalo.writeUInt8(type);
switch (type) {
case UNICAST_BINDING: {
buffalo.writeIeeeAddr(destination);
buffalo.writeUInt8(destinationEndpoint);
break;
}
case MULTICAST_BINDING: {
buffalo.writeUInt16(groupAddress);
break;
}
default:
throw new ZdoStatusError(Status.NOT_SUPPORTED);
}
return buffalo.getWritten();
}
/**
* @see ClusterId.CLEAR_ALL_BINDINGS_REQUEST
*/
public static buildClearAllBindingsRequest(tlv: ClearAllBindingsReqEUI64TLV): Buffer {
const buffalo = new BuffaloZdo(Buffer.alloc(MAX_BUFFER_SIZE), ZDO_MESSAGE_OVERHEAD);
// ClearAllBindingsReqEUI64TLV: Local: ID: 0x00
buffalo.writeUInt8(0x00);
buffalo.writeUInt8(tlv.eui64List.length * EUI64_SIZE + 1 - 1);