-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxbee.js
2021 lines (1580 loc) · 63.7 KB
/
xbee.js
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
const SerialPort = require('serialport');
const xbee_api = require('xbee-api');
const clone = require('rfdc')();
const motionTimeoutSec = 180;
const batteryMinVoltage = 2.0;
const batteryMaxVoltage = 3.28;
let serialport;
let xbeeAPI;
const addr64List = [ null, null ];
// Zigbee addressing
// const BROADCAST_LONG = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF ];
// const BROADCAST_SHORT = [ 0xFF, 0xFE ];
// Zigbee profile IDs
const PROFILE_ID_ALERTME = 'c216'; // AlertMe device profile
const PROFILE_ID_HA = '0104'; // HA device profile
const PROFILE_ID_LL = 'c05e'; // Light link Profile
const PROFILE_ID_ZDP = '0000'; // Zigbee device profile
// Zigbee endpoints
const ENDPOINT_ALERTME = '02'; // AlertMe/Iris endpoint
const ENDPOINT_ZDO = '00'; // Zigbee device objects endpoint
const endpointList = [ ENDPOINT_ZDO, ENDPOINT_ALERTME ];
// ZDP status
const ZDP_STATUS = {
OK : 0x00,
INVALID : 0x80,
NOT_FOUND : 0x81,
};
// Cluster IDs
const CLUSTER_ID = {
// AlertMe cluster IDs
// http://www.desert-home.com/2015/06/hacking-into-iris-door-sensor-part-4.html
AM : {
ATTRIBUTE : '00c0', // Attribute
BUTTON : '00f3', // Button/keyfob
DISCOVERY : '00f6', // Device discovery
POWER : '00ef', // Power information
SECURITY : '0500', // Security
STATUS : '00f0', // Device status
SWITCH : '00ee', // SmartPlug switch
TAMPER : '00f2', // Device tamper
}, // AM
// ZDO cluster IDs
// http://ftp1.digi.com/support/images/APP_NOTE_XBee_Zigbee_Device_Profile.pdf
ZDO : {
ACTIVE_ENDPOINT : {
REQUEST : '0005', // Active endpoint request
RESPONSE : '8005', // Active endpoint response
},
END_DEVICE_ANNOUNCE : '0013', // End device announce
MANAGEMENT_ROUTING : {
REQUEST : '0032', // Management routing request
RESPONSE : '8032', // Management routing response
},
MATCH_DESCRIPTOR : {
REQUEST : '0006', // Match descriptor request
RESPONSE : '8006', // Match descriptor response
},
NETWORK_ADDRESS : {
REQUEST : '0000', // Network address (16-bit) request
RESPONSE : '8000', // Network address (16-bit) response
},
PERMIT_JOINING : {
REQUEST : '0036', // Permit joining request
RESPONSE : '8036', // Permit joining response
},
SIMPLE_DESC_REQ : '0004', // Simple descriptor request
}, // ZDO
}; // CLUSTER_ID
// Cluster commands
const CLUSTER_CMD = {
// AlertMe
AM : {
// Security IasZoneCluster commands cluster 0x500 = 1280
SEC_ENROLL_REQ : '01',
SEC_STATUS_CHANGE : '00', // Security event (sensors)
// AmGeneralCluster commands cluster [ 0x00, 0xF0 ] : 240
LIFESIGN_CMD : 'fb', // LIFESIGN_CMD : 251
RTC_CMD_REQ : '80', // REQUEST_RTC_CMD : 128
SET_MODE_CMD : 'fa', // SET_MODE_CMD : 250
SET_RTC_CMD : '00', // SET_RTC_CMD : 0
STOP_POLLING_CMD : 'fd', // STOP_POLLING_CMD : 253
// AmPowerCtrlCluster commands cluster [ 0x00, 0xEE ] : 238
STATE_REQ : '01', // CMD_SET_OPERATING_MODE : 1 // State request (SmartPlug)
STATE_CHANGE : '02', // CMD_SET_RELAY_STATE : 2 // State change request (SmartPlug)
STATE_REPORT_REQ : '03', // CMD_REQUEST_REPORT : 3
STATE_RESP : '80', // CMD_STATUS_REPORT : 128 // switch status update
// AmPowerMonCluster commands cluster [ 0x00, 0xEF ] : 239
POWER_SET_REPT_PARAMS : '00', // CMD_SET_REPT_PARAMS : 0
POWER_REQUEST_REPORT : '03', // CMD_REQUEST_REPORT : 3
POWER_SET_REPORT_RATE : '04', // CMD_SET_REPORT_RATE : 4
POWER_DEMAND : '81', // CMD_POWER_REPORT : 129 // Power demand update
POWER_CONSUMPTION : '82', // CMD_ENERGY_REPORT : 130 // Power consumption & uptime update
PWD_BATCH_POWER_REPORT : '84', // CMD_BATCH_POWER_REPORT : 132
PWD_BATCH_ENERGY_REPORT : '85', // CMD_BATCH_ENERGY_REPORT : 133
PWD_POWER_ENERGY_REPORT : '86', // CMD_POWER_ENERGY_REPORT : 134
PWD_BATCH_POWER_ENERGY_REPORT : '87', // CMD_BATCH_POWER_ENERGY_REPORT : 135
POWER_UNKNOWN : '86', // Unknown British Gas power meter update
// AmMaintenanceCluster commands cluster [ 0x00, 0xF6 ] : 246
MAINT_HELLO_REQ : 'fc', // HELLO_WORLD_REQ : 252
MAINT_HELLO_RESP : 'fe', // HELLO_WORLD_RESP : 254
MAINT_RANGE_TEST_REQ : 'fd', // RANGE_TEST_SEND_CMD : 253
MAINT_RANGE_TEST_RESP : 'fd', // RANGE_TEST_RECV_CMD : 253
MODE_REQ : 'fa', // Mode change request
STATUS : 'fb', // Status update
VERSION_REQ : 'fc', // Version information request
RSSI : 'fd', // RSSI range test update
VERSION_RESP : 'fe', // Version information response
}, // AM
}; // CLUSTER_CMD
// AlertMe device modes
const DEVICE_MODE = {
IDLE : 0x04,
LOCKED : 0x02,
NORMAL_OPS : 0x00,
OPT_CLEAR_HNF : 0x02,
OPT_NONE : 0x00,
OPT_SET_HNF : 0x01,
QUIESCENT : 0x05,
RANGE_TEST : 0x01,
SEEKING : 0x03,
SILENT : 0x03,
TEST : 0x02,
};
// Utilized by generateMessage()
const messages = {
activeEndpointRequest : {
name : 'Active endpoint request',
frame : {
profileId : PROFILE_ID_ZDP,
clusterId : CLUSTER_ID.ZDO.ACTIVE_ENDPOINT.REQUEST,
sourceEndpoint : ENDPOINT_ZDO,
destinationEndpoint : ENDPOINT_ZDO,
dataGenerate : (params) => generateActiveEndpointRequest(params),
data : [ ],
},
},
matchDescriptorRequest : {
name : 'Match descriptor request',
frame : {
profileId : PROFILE_ID_ZDP,
clusterId : CLUSTER_ID.ZDO.MATCH_DESCRIPTOR.REQUEST,
sourceEndpoint : ENDPOINT_ZDO,
destinationEndpoint : ENDPOINT_ZDO,
dataGenerate : (params) => generateMatchDescriptorRequest(params),
data : [ ],
},
},
matchDescriptorResponse : {
name : 'Match descriptor response',
frame : {
profileId : PROFILE_ID_ZDP,
clusterId : CLUSTER_ID.ZDO.MATCH_DESCRIPTOR.RESPONSE,
sourceEndpoint : ENDPOINT_ZDO,
destinationEndpoint : ENDPOINT_ZDO,
dataGenerate : (params) => generateMatchDescriptorResponse(params),
data : [ ],
},
},
modeChangeRequest : {
name : 'Mode change request',
frame : {
profileId : PROFILE_ID_ALERTME,
clusterId : CLUSTER_ID.AM.STATUS,
sourceEndpoint : ENDPOINT_ALERTME,
destinationEndpoint : ENDPOINT_ALERTME,
dataGenerate : (params) => generateModeChangeRequest(params),
data : [ ],
},
},
permitJoinRequest : {
name : 'Management permit join request',
frame : {
profileId : PROFILE_ID_ZDP,
clusterId : CLUSTER_ID.ZDO.PERMIT_JOINING.REQUEST,
sourceEndpoint : ENDPOINT_ZDO,
destinationEndpoint : ENDPOINT_ZDO,
data : [ 0xFF, 0x00 ],
},
},
routingTableRequest : {
name : 'Management routing table request',
frame : {
profileId : PROFILE_ID_ZDP,
clusterId : CLUSTER_ID.ZDO.MANAGEMENT_ROUTING.REQUEST,
sourceEndpoint : ENDPOINT_ZDO,
destinationEndpoint : ENDPOINT_ZDO,
data : [ 0x12, 0x01 ],
},
},
securityInit : {
name : 'Security initialization',
frame : {
profileId : PROFILE_ID_ALERTME,
clusterId : CLUSTER_ID.AM.SECURITY,
sourceEndpoint : ENDPOINT_ALERTME,
destinationEndpoint : ENDPOINT_ALERTME,
dataGenerate : () => generateSecurityInit(),
data : [ ],
},
},
switchStateRequest : {
name : 'Switch state request',
frame : {
profileId : PROFILE_ID_ALERTME,
clusterId : CLUSTER_ID.AM.SWITCH,
sourceEndpoint : ENDPOINT_ZDO,
destinationEndpoint : ENDPOINT_ALERTME,
dataGenerate : (params) => generateSwitchStateRequest(params),
data : [ ],
},
},
versionInfoRequest : {
name : 'Version info request',
frame : {
profileId : PROFILE_ID_ALERTME,
clusterId : CLUSTER_ID.AM.DISCOVERY,
sourceEndpoint : ENDPOINT_ZDO,
destinationEndpoint : ENDPOINT_ALERTME,
dataGenerate : (params) => generateVersionInfoRequest(params),
data : [ ],
},
},
}; // messages
// Issue AT commands to find addresses of connected XBee device
async function readAddresses() {
await sendATCommand('MY');
await sendATCommand('SH');
await sendATCommand('SL');
} // async readAddresses()
function generateActiveEndpointRequest(params) {
// The active endpoint request needs the short address of the device in the payload
//
// It needs to be little endian (backwards)
//
// The first byte in the payload is simply a number to identify the message
// The response will have the same number in it
// Field name Size Description
// ---------- ---- -----------
// Sequence 1 Frame sequence
// Network address 2 16-bit address of a device in the network whose active endpoint list being requested
// :param params:
// :return: Message data
// Example: [ 0xAA, 0x9F, 0x88 ]
// TODO
const netAddr = [ Buffer.from(params.remote16, 'hex')[0], Buffer.from(params.remote16, 'hex')[1] ];
const data = [ params.zdoSequenceNumber ].concat(netAddr);
log.msg('generateActiveEndpointRequest()', { params, netAddr, data });
return data;
} // generateActiveEndpointRequest(params)
function generateMatchDescriptorRequest(params) {
log.msg('generateMatchDescriptorRequest()', params);
// params:
// - inClusters
// - outClusters
// - profileId
// - remote16
// - zdoSequenceNumber
// Broadcast or unicast transmission used to discover the device(s) that supports a specified profile ID and/or clusters
// Field name Size Description
// ---------- ---- -----------
// Sequence 1 Frame sequence
// Network address 2 16-bit address of a device in the network whose power descriptor is being requested
// Profile ID 2 Profile ID to be matched at the destination
// Number of input clusters 1 The number of input clusters in the in cluster list for matching. Set to 0 if no clusters supplied
// Input cluster list 2* List of input cluster IDs to be used for matching
// Number of output clusters 1 The number of output clusters in the output cluster list for matching. Set to 0 if no clusters supplied
// Output cluster list 2* List of output cluster IDs to be used for matching
// * Number of Input Clusters
// Example: [ 0x01, 0xFD, 0xFF, 0x16, 0xC2, 0x00, 0x01, 0xF0, 0x00 ]
// :param params:
// :return: Message data
const netAddr = [ Buffer.from(params.remote16, 'hex')[0], Buffer.from(params.remote16, 'hex')[1] ]; // 0xFD, 0xFF
const profileId = [ Buffer.from(params.profileId, 'hex')[1], Buffer.from(params.profileId, 'hex')[0] ]; // 0x16, 0xC2 PROFILE_ID_ALERTME (reversed)
// TODO: Finish this off! At the moment this does not support multiple clusters, it just supports one!
const data = [ params.zdoSequenceNumber ].concat(netAddr).concat(profileId).concat(params.inClusters.length).concat(params.inClusters).concat(params.outClusters.length).concat(params.outClusters[1]).concat(params.outClusters[0]);
return data;
} // generateMatchDescriptorRequest(params)
function generateMatchDescriptorResponse(params) {
// If a descriptor match is found on the device, this response contains a list of endpoints that support the request criteria
//
// Field Name Size Description
// ---------- ---- -----------
// Sequence 1 Frame sequence
// Status 1 Response status
// Network Address 2 Indicates the 16-bit address of the responding device
// Length 1 The number of endpoints on the remote device that match the request criteria
// Match List Variable List of endpoints on the remote that match the request criteria
//
// Example: [ 0x01, 0x00, 0x00, 0xE1, 0x02, 0x00, 0x02 ]
//
// :param params:
// :return: Message data
// params:
// - remote16
// - zdoSequenceNumber
const responseStatus = ZDP_STATUS.OK; // 0x00
// TODO
const netAddr = [ Buffer.from(params.remote16, 'hex')[0], Buffer.from(params.remote16, 'hex')[1] ];
const matchList = [ Buffer.from(endpointList[0], 'hex')[0], Buffer.from(endpointList[1], 'hex')[0] ];
// const data = [ params.zdoSequenceNumber ].concat(responseStatus).concat(netAddr).concat(matchList.length).concat(matchList);
const data = [ params.zdoSequenceNumber, responseStatus, 0x00, 0x00, 0x01, 0x02 ];
log.msg('generateMatchDescriptorResponse()', {
params,
responseStatus,
netAddr,
matchList,
data,
});
return data;
} // generateMatchDescriptorResponse(params)
function generateModeChangeRequest(params = null) {
// Available modes:
// idle
// locked
// normal
// rangeTest
// silent
// Field name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC
// Cluster command 1 Cluster command - mode change request ([ 0xFA ])
// Mode 2 Requested mode (1: Normal, 257: Range Test, 513: Locked, 769: Silent)
// :param params: Object of requested mode
// :return: Message data
const preamble = [ 0x11, 0x00 ];
// const preamble = [ 0x19, 0x41 ];
const clusterCmd = Buffer.from(CLUSTER_CMD.AM.MODE_REQ, 'hex')[0]; // TODO: Flip this around so there's one Buffer.from() in parseMessage
// Default normal if no mode
let mode = 'normal';
let payload = DEVICE_MODE.NORMAL_OPS;
if (typeof params === 'object' && typeof params.mode === 'string') {
mode = params.mode;
}
switch (mode) {
case 'idle' : payload = DEVICE_MODE.IDLE; break;
case 'locked' : payload = DEVICE_MODE.LOCKED; break;
case 'normal' : payload = DEVICE_MODE.NORMAL_OPS; break;
case 'rangeTest' : payload = DEVICE_MODE.RANGE_TEST; break;
case 'silent' : payload = DEVICE_MODE.SILENT; break;
default : {
log.error('generateModeChangeRequest(): invalid mode', mode);
return [];
}
}
const data = preamble.concat(clusterCmd).concat([ payload, 0x01 ]);
log.msg('generateModeChangeRequest()', { params, data });
return data;
} // generateModeChangeRequest(params)
function generateSecurityInit() {
// Keeps security devices joined?
// Field name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC ([ 0x11, 0x80 ])
// Cluster command 1 Cluster command - Security event ([ 0x00 ])
// Unknown 2 ??? ([ 0x00, 0x05 ])
// :param params: Object (none required)
// :return: Message data
const preamble = [ 0x11, 0x80 ];
const clusterCmd = Buffer.from(CLUSTER_CMD.AM.SEC_STATUS_CHANGE, 'hex')[0]; // TODO: Flip this around so there's one Buffer.from() in parseMessage
const payload = [ 0x00, 0x05 ];
const data = preamble.concat(clusterCmd).concat(payload);
log.msg('generateSecurityInit()', { data });
return data;
} // generateSecurityInit()
function generateSwitchStateRequest(params = { switchState : 'check' }) {
log.msg('generateSwitchStateRequest()', { params });
// This message is sent FROM the Hub TO the SmartPlug requesting state change
// Field name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC
// Cluster command 1 Cluster command - Change state (SmartPlug) ([ 0x01 ] / [ 0x02 ])
// Requested relay state 2* [ 0x01 ] = Check Only, [ 0x01, 0x01 ] = On, [ 0x00, 0x01 ] = Off
// * Size = 1 if check only
// :param params: Object of switch relay state
// :return: Message data
const preamble = [ 0x11, 0x00 ];
let clusterCmd;
let payload;
if (typeof params.switchState === 'undefined') params.switchState = 'check';
if (params.switchState === null) params.switchState = 'check';
if (params.switchState === '') params.switchState = 'check';
switch (params.switchState.toString().toLowerCase()) {
case '1' :
case 'active' :
case 'activate' :
case 'on' :
case 'poweron' :
case 'switchon' :
case 'true' :
params.switchState = 1;
clusterCmd = CLUSTER_CMD.AM.STATE_CHANGE;
payload = [ 0x01, 0x01 ]; // On
break;
case '0' :
case 'inactive' :
case 'deactivate' :
case 'off' :
case 'poweroff' :
case 'switchoff' :
case 'false' :
params.switchState = 0;
clusterCmd = CLUSTER_CMD.AM.STATE_CHANGE;
payload = [ 0x00, 0x01 ]; // Off
break;
default :
// Check only
params.switchState = 'check';
clusterCmd = CLUSTER_CMD.AM.STATE_REQ;
payload = [ 0x01 ];
}
clusterCmd = Buffer.from(clusterCmd, 'hex')[0]; // TODO: Flip this around so there's one Buffer.from() in parseMessage
const data = preamble.concat(clusterCmd).concat(payload);
log.msg('generateSwitchStateRequest()', { data });
return data;
} // generateSwitchStateRequest(params)
function generateVersionInfoRequest() {
// This message is sent FROM the Hub TO the SmartPlug requesting version information
// Field name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC
// Cluster command 1 Cluster command - version information request ([ 0xFC ])
// :return: Message data
const preamble = [ 0x11, 0x00 ];
const clusterCmd = Buffer.from(CLUSTER_CMD.AM.VERSION_REQ, 'hex')[0]; // TODO: Flip this around so there's one Buffer.from() in parseMessage
const data = preamble.concat(clusterCmd);
return data;
} // generateVersionInfoRequest()
function parseActiveEndpointResponse(data, remote64, nodeName) {
const activeEndpointResponseState = {};
log.msg('parseActiveEndpointResponse()', { remote64, nodeName, data, activeEndpointResponseState, error : 'none' });
return activeEndpointResponseState;
} // parseActiveEndpointResponse(data, remote64, nodeName)
function parseATCommandResponse(frame) {
switch (frame.command) {
case 'MY' : update.status('xbee.self.addr16', frame.commandData.toString('hex')); break;
case 'SH' : addr64List[0] = frame.commandData.toString('hex'); break;
case 'SL' : addr64List[1] = frame.commandData.toString('hex'); break;
} // switch (frame.command)
if (typeof addr64List[0] === 'string' && typeof addr64List[1] === 'string') {
update.status('xbee.self.addr64', addr64List[0] + addr64List[1]);
}
} // parseATCommandResponse(frame)
// Messages labeled "attribute" in arcus, sent from Keypad device
function parseAttribute(data) {
// constants alertme.KeyPad {
// const u8 DEVICE_TYPE = 0x1C;
//
// const u8 ATTR_STATE = 0x20;
// const u8 ATTR_PIN = 0x21;
// const u8 ATTR_ACTION_KEY_PRESS = 0x22;
// const u8 ATTR_ACTION_KEY_RELEASE = 0x23;
// const u8 ATTR_HUB_POLL_RATE = 0x24;
// const u8 ATTR_SOUNDS_MASK = 0x25;
// const u8 ATTR_SOUND_ID = 0x26;
// const u8 ATTR_CUSTOM_SOUND = 0x27;
// const u8 ATTR_UNSUCCESSFUL_STATE_CHANGE = 0x27;
//
// const u8 KEYPAD_STATE_UNKNOWN = 0x00;
// const u8 KEYPAD_STATE_HOME = 0x01;
// const u8 KEYPAD_STATE_ARMED = 0x02;
// const u8 KEYPAD_STATE_NIGHT = 0x03;
// const u8 KEYPAD_STATE_PANIC = 0x04;
// const u8 KEYPAD_STATE_ARMING = 0x05;
// const u8 KEYPAD_STATE_ALARMING = 0x06;
// const u8 KEYPAD_STATE_NIGHT_ARMING = 0x07;
// const u8 KEYPAD_STATE_NIGHT_ALARMING = 0x08;
//
// const u8 KEYPAD_STATE_LOCKED_MASK = 0x80;
//
// const u8 ACTION_KEY_POUND = 0x23; // '#'
// const u8 ACTION_KEY_HOME = 0x48; // 'H'
// const u8 ACTION_KEY_AWAY = 0x41; // 'A'
// const u8 ACTION_KEY_NIGHT = 0x4E; // 'N'
// const u8 ACTION_KEY_PANIC = 0x50; // 'P'
//
// const u8 SOUND_CUSTOM = 0x00;
// const u8 SOUND_KEYCLICK = 0x01;
// const u8 SOUND_LOSTHUB = 0x02;
// const u8 SOUND_ARMING = 0x03;
// const u8 SOUND_ARMED = 0x04;
// const u8 SOUND_HOME = 0x05;
// const u8 SOUND_NIGHT = 0x06;
// const u8 SOUND_ALARM = 0x07;
// const u8 SOUND_PANIC = 0x08;
// const u8 SOUND_BADPIN = 0x09;
// const u8 SOUND_OPENDOOR = 0x0A;
// const u8 SOUND_LOCKED = 0x0B;
// }
// PIN length seems to be limited to 15 digits in hardware
//
// Examples from logs
//
// Periodic messages
// <Buffer 08 33 0a 22 00 09 00 48 23 00 09 00 48>
// <Buffer 08 34 0a 23 00 09 00 48>
// <Buffer 08 4a 00 20 00>
// Pressing 'OFF' button
// <Buffer 08 60 00 20 00>
// <Buffer 08 34 0a 23 00 09 00 48 23 00 09 00 48>
// <Buffer 08 00 0a 23 00 09 00 48 23 00 09 00 48>
// Pressing 'ON' button
// <Buffer 08 34 0a 22 00 09 00 41>
// <Buffer 08 00 0a 23 00 09 00 41 23 00 09 00 41>
// Pressing 'PARTIAL' button
// <Buffer 08 34 0a 22 00 09 00 4e>
// <Buffer 08 33 0a 22 00 09 00 4e 23 00 09 00 4e>
// Pressing 'PANIC' button
// <Buffer 08 34 0a 22 00 09 00 50>
// <Buffer 08 33 0a 22 00 09 00 50 23 00 09 00 50>
// Entering 5 4 3 2 1 in succession
// <Buffer 08 34 0a 21 00 42 05 35 34 33 32 31>
//
// Entering 5 6 0 8 5 in succession
// <Buffer 08 6c 0a 21 00 42 05 35 36 30 38 35>
//
// Entering 1 2 3 1 2 3 in succession
// <Buffer 08 34 0a 21 00 42 06 31 32 33 31 32 33>
//
// Entering 16 or more digits on keypad
// <Buffer 08 34 0a 21 00 42 10 39 34 35 36 31 32 33 34 35 36 37 38 39 39 39 79>
//
// Entering 20 digits on keypad (entered 51340722145134072214)
// [ xbee ] [ MESSAGE ] parseAttribute() {
// data: <Buffer 08 34 0a 21 00 42 10 30 37 32 32 31 34 35 31 33 34 30 30 30 30 30 79>,
// attributeData: {
// pinLength: 15,
// pinBuffer: <Buffer 30 37 32 32 31 34 35 31 33 34 30 30 30 30 30>,
// pinString: '072214513400000'
// }
// }
let attributeName = 'unknown';
const attributeData = {};
switch (data[2]) {
case 0x0A : {
switch (data[3]) {
case 0x21 : { // ATTR_PIN
attributeName = 'pinEntry';
let pinLength = data[6];
if (pinLength > 15) pinLength = 15;
const pinBuffer = data.slice(7, (7 + pinLength));
const pinString = pinBuffer.toString();
// attributeData[attributeName] = {};
// attributeData[attributeName].pinLength = pinLength;
// attributeData[attributeName].pinBuffer = pinBuffer.toJSON().data;
// attributeData[attributeName].pinString = pinString;
attributeData[attributeName] = pinString;
break;
}
case 0x22 : { // ATTR_ACTION_KEY_PRESS
attributeName = 'actionKeyPress';
let keyName = 'unknown';
switch (data[7]) {
case 0x2A : keyName = '*'; break;
case 0x23 : keyName = '#'; break;
case 0x48 : keyName = 'on'; break; // ACTION_KEY_HOME = 0x48; // 'H'
case 0x41 : keyName = 'off'; break; // ACTION_KEY_AWAY = 0x41; // 'A'
case 0x4E : keyName = 'partial'; break; // ACTION_KEY_NIGHT = 0x4E; // 'N'
case 0x50 : keyName = 'panic'; break; // ACTION_KEY_PANIC = 0x50; // 'P'
}
attributeData[attributeName] = keyName;
break;
}
case 0x23 : { // ATTR_ACTION_KEY_RELEASE
attributeName = 'actionKeyRelease';
let keyName = 'unknown';
switch (data[7]) {
case 0x2A : keyName = '*'; break;
case 0x23 : keyName = '#'; break;
case 0x48 : keyName = 'on'; break; // ACTION_KEY_HOME = 0x48; // 'H'
case 0x41 : keyName = 'off'; break; // ACTION_KEY_AWAY = 0x41; // 'A'
case 0x4E : keyName = 'partial'; break; // ACTION_KEY_NIGHT = 0x4E; // 'N'
case 0x50 : keyName = 'panic'; break; // ACTION_KEY_PANIC = 0x50; // 'P'
}
attributeData[attributeName] = keyName;
break;
}
// ATTR_HUB_POLL_RATE = 0x24;
// ATTR_SOUNDS_MASK = 0x25;
// ATTR_SOUND_ID = 0x26;
// ATTR_CUSTOM_SOUND = 0x27;
// ATTR_UNSUCCESSFUL_STATE_CHANGE = 0x27;
}
hass.fireKeypadEvent(attributeData);
break;
}
}
log.msg('parseAttribute()', { data, attributeData });
return attributeData;
} // parseAttribute(data)
function parseButtonPress(data) {
log.msg('parseButtonPress()', data);
// Process message, parse for button press status
// Field name Size Description
// ---------- ---- -----------
// Preamble 1 Unknown preamble TBC ([ 0x09 ])
// Cluster command 1 Cluster command - Security event ([ 0x00 ])
// Button state 1 Button state ([ 0x01 ] = On, [ 0x00 ] = Off)
// Unknown 1 ??? ([ 0x00 ])
// Unknown 1 ??? ([ 0x01 ], [ 0x02 ])
// Counter 2 Counter (milliseconds) ([ 0xBF, 0xC3, 0x12, 0xCA ])
// Unknown 2 ??? ([ 0x00, 0x00 ])
// Examples:
// [ 0x09, 0x00, 0x00, 0x00, 0x02, 0xBF, 0xC3, 0x00, 0x00 ] { state : 0, counter : 50111 }
// [ 0x09, 0x00, 0x01, 0x00, 0x01, 0x12, 0xCA, 0x00, 0x00 ] { state : 1, counter : 51730 }
const attributes = {
buttonState : Boolean(data[2]),
// TODO
// counter : struct.unpack('<H', data[5:7])[0],
};
return attributes;
} // parseButtonPress(data)
// function parseModeChangeRequest(data) {
// const modeCmd = data[3];
//
// const attributes = {
// mode : 'unknown',
// };
//
// if (data[4] !== 0x01) return attributes;
//
// switch (modeCmd) {
// case 0x00 : attributes.mode = 'normal'; break; // 0x11, 0x00, 0xFA, 0x00, 0x01
// case 0x01 : attributes.mode = 'range'; break; // 0x11, 0x00, 0xFA, 0x01, 0x01
// case 0x02 : attributes.mode = 'locked'; break; // 0x11, 0x00, 0xFA, 0x02, 0x01
// case 0x03 : attributes.mode = 'silent'; break; // 0x11, 0x00, 0xFA, 0x03, 0x01
// }
//
// return attributes;
// } // parseModeChangeRequest(data)
function parsePowerConsumption(data) {
// Process message, parse for power consumption value
// Field name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC
// Cluster command 1 Cluster command - power consumption & uptime update (0x82)
// Power value 4 Power consumption value (kWh)
// Up Time 4 Up Time value (seconds)
// Unknown 1 ???
// Examples
// [ 0x09, 0x77, 0x82, 0x2C, 0x4D, 0x4C, 0x00, 0x84, 0xDA, 0x0A, 0x00, 0x00 ]
// [ 0x09, 0x77, 0x82, 0xA1, 0x0B, 0x4B, 0x00, 0x48, 0xDA, 0x0A, 0x00, 0x00 ]
//
// [ 0x09, 0x77, 0x82, 0xBF, 0x0F, 0x0C, 0x00, 0x28, 0xDC, 0x0A, 0x00, 0x00 ]
// [ 0x09, 0x77, 0x82, 0xBF, 0x0F, 0x0C, 0x00, 0xEC, 0xDB, 0x0A, 0x00, 0x00 ]
const attributes = {
kWh : data.readUInt32LE(3),
uptime : data.readUInt32LE(7),
};
// const attributes = dict(zip(('clusterCmd', 'power_consumption', 'up_time'), struct.unpack('< 2x s I I 1x', data)));
log.msg('parsePowerConsumption()', data, attributes);
return attributes;
} // parsePowerConsumption(data)
function parseActivePower(data) {
// log.msg('parseActivePower()', data);
// Process message, parse for power demand value
// Field name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC
// Cluster command 1 Cluster command - Power Demand Update ([ 0x81 ])
// Power value 2 Power Demand value (kW)
// Examples:
// [ 0x09, 0x6A, 0x81, 0x00, 0x00 ] { activePower : 0 }
// [ 0x09, 0x6A, 0x81, 0x16, 0x00 ] { activePower : 22 }
// [ 0x09, 0x6A, 0x81, 0x00 ] { activePower : 37 }
const attributes = {
// activePower : parseFloat(`${data[3]}.${data[4]}`),
activePower : data.readUInt16LE(3),
};
log.msg('parseActivePower()', data.toJSON().data, attributes);
return attributes;
} // parseActivePower(data)
function parsePowerUnknown(data) {
log.msg('parsePowerUnknown()', data);
// Parse unknown power message seen from British Gas (AlertMe) power monitor
// Could this be the same or merged with parseActivePower() or parsePowerConsumption()?
// Field name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC ([ 0x09, 0x00 ])
// Cluster command 1 Cluster command - unknown power ([ 0x86 ])
// Unknown 11 TODO Work out what power values this message contains
// Examples:
// [ 0x09, 0x00, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 = 0
// [ 0x09, 0x00, 0x86, 0x91, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 = ?
// [ 0x09, 0x00, 0x86, 0x01, 0xC9, 0x02, 0x07, 0x02, 0x00, 0x00, 0x00 = ?
// TODO
// let value = struct.unpack('<H', data[3:5])[0] // TBC
const value = null;
return { activePower : value };
} // parsePowerUnknown(data)
function parseRangeInfoUpdate(data) {
log.msg('parseRangeInfoUpdate()', data);
// Process message, parse for RSSI range test value
// Field name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC
// Cluster command 1 Cluster command - RSSI range test update ([ 0xFD ])
// RSSI value 1 RSSI range test value
// Unknown 1 ???
const rssi = data[3];
return { rssi };
} // parseRangeInfoUpdate(data)
// TODO
function parseVersionInfoUpdate(data) {
log.msg('parseVersionInfoUpdate()', data.toString('hex'));
// Process message, parse for version information:
// Version, Type, Manufacturer, Date
// Field Name Size Description
// ---------- ---- -----------
// Preamble 2 Unknown preamble TBC
// Cluster command 1 Cluster Command - Version Information Response (0xFE)
// NodeID 2 unsigned short (H)
// EUI64Str 8 8x Char (8s)
// mfgID 2 unsigned short (H)
// DeviceType 2 unsigned short (H)
// AppRelease 1 unsigned inter (B)
// AppVersion 1 unsigned inter (B)
// HWMinor 1 unsigned inter (B)
// HWMajor 1 unsigned inter (B)
// Type Info Variable Type Information ('AlertMe.com\nSmartPlug\n2013-09-26')
const attributes = {};
// TODO
// attributes['nodeId'],
// Eui64str,
// attributes['mfgId'],
// attributes['deviceType'],
// attributes['appRelease'],
// attributes['appVersion'],
// attributes['hwMinorVersion'],
// attributes['hwMajorVersion']
// = struct.unpack('<H8sHHBBBB', data[3:21])
const stringOffsets = {
make : data.slice(21, 22)[0],
model : null,
buildDate : null,
};
stringOffsets.model = data.slice((21 + stringOffsets.make + 1), (22 + stringOffsets.make + 1))[0];
stringOffsets.buildDate = data.slice((21 + stringOffsets.make + 1 + stringOffsets.model + 1), (22 + stringOffsets.make + 1 + stringOffsets.model + 1))[0];
attributes.make = data.slice(22, (22 + stringOffsets.make)).toString();
attributes.model = data.slice((22 + stringOffsets.make + 1), (22 + stringOffsets.make + stringOffsets.model + 1)).toString();
attributes.buildDate = data.slice((22 + stringOffsets.make + 1 + stringOffsets.model + 1), (22 + stringOffsets.make + stringOffsets.model + 1 + stringOffsets.buildDate + 1)).toString();
return attributes;
} // parseVersionInfoUpdate(data)
function parseSecurityState(data, remote64, nodeName = null) {
// Process message, parse for security state
// TODO: Is this the SAME AS parseTamperState!?!
// Field name Size Description
// ---------- ---- -----------
// Preamble 1 Unknown preamble TBC ([ 0x09 ])
// Cluster command 1 Cluster command - Security event ([ 0x00 ])
// Unknown 1 ??? ([ 0x00 ])
// Button state 1 Security states bitmask ([ 0x00, 0x01, 0x04, 0x05 ])
// Unknown 2 ??? ([ 0x00, 0x00 ])
// Examples:
// [ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00 ] { triggerState : 0, tamperState : 0 }
// [ 0x09, 0x00, 0x00, 0x01, 0x00, 0x00 ] { triggerState : 1, tamperState : 0 }
// [ 0x09, 0x00, 0x00, 0x04, 0x00, 0x00 ] { triggerState : 0, tamperState : 1 }
// [ 0x09, 0x00, 0x00, 0x05, 0x00, 0x00 ] { triggerState : 1, tamperState : 1 }
const securityState = {};
// Old info
// 1 = Open
// 2 = Closed
// From PIR motion sensor
// data: <Buffer 09 00 01 0d 00 39 10>
// data: <Buffer 09 c7 01 0d 00 39 10>
// data: <Buffer 09 e6 01 0d 00 39 10>
//
// Oddball:
// data: <Buffer 09 01 01 0d 00 39 10> ( 0.39)
// data: <Buffer 09 6e 01 0d 00 39 10> (43.14)
// const stateBits = bitmask.check(securityState.securityStateId);
// const tamperState = stateBits.mask.bit2;
// securityState.triggerState = stateBits.mask.bit0;
// The security states are in byte [3] and is a bitfield:
// bit 0 is the magnetic reed switch state
// bit 3 is the tamper switch state
securityState.securityStateId = data[3];
for (let i = 0; i < data.length; i++) {
securityState['securityStateValue' + i] = data[i];
}
if (typeof status.xbee.nodes64[remote64].model === 'undefined' || status.xbee.nodes64[remote64].model === null) {
log.msg('parseSecurityState()', { remote64, nodeName, data, securityState, error : 'Missing model name' });
return securityState;
}
if (data[0] !== 0x09) {
log.msg('parseSecurityState()', { remote64, nodeName, data, securityState, error : 'data[0] !== 0x09' });
return securityState;
}
switch (status.xbee.nodes64[remote64].model) {
case 'Button Device' : {
// When a contact sensor broadcasts a state change for the reed switch, data[1] is 0x6E
const stateBits = bitmask.check(data[3]);
securityState.tamperState = Boolean(!stateBits.mask.bit2);
break;
}
case 'Contact Sensor Device' : {
// When a contact sensor broadcasts a state change for the reed switch, data[1] is 0x6E
const stateBits = bitmask.check(data[3]);
securityState.contactState = Boolean(stateBits.mask.bit0);
securityState.tamperState = Boolean(!stateBits.mask.bit2);
break;
}