-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1206 lines (1000 loc) · 44.4 KB
/
index.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 usb = require('usb')
const serialport = require('serialport');
const Readline = serialport.parsers.Readline;
const Joi = require('joi');
const cache = require('memory-cache-ttl');
const moment = require('moment');
const roundTo = require('round-to');
const conectricUsbGateway = {
macAddress: undefined,
parser: undefined,
serialPort: undefined,
contikiVersion: undefined,
conectricVersion: undefined,
nodeModuleVersion: require('./package.json').version,
BROADCAST_LOCAL_ADDRESS: 'ffff',
BROADCAST_ALL_ADDRESS: '0000',
PARITY_NONE: 'none',
PARITY_ODD: 'odd',
PARTITY_EVEN: 'even',
STANDARD_HEADER: 0,
EXTENDED_HEADER: 128,
MESSAGE_TYPES: {
'30': 'tempHumidity',
'31': 'switch',
'32': 'motion',
'36': 'rs485Request',
'37': 'rs485Response',
'38': 'rs485ChunkRequest',
'39': 'rs485ChunkResponse',
'40': 'pulse',
'41': 'echoStatus',
'42': 'rs485ChunkEnvelopeResponse',
'43': 'rs485Status',
'44': 'moisture',
'45': 'tempHumidityLight',
'46': 'tempHumidityAdc',
'60': 'boot',
'61': 'text',
'70': 'rs485Config'
},
TRACKABLE_MESSAGES: [
'37', // rs485Response
'39', // rs485ChunkResponse
'42' // r485ChunkEnvelopeResponse
],
BROADCAST_MESSAGE_TYPES: [
'30',
'31',
'32',
'37',
'39',
'40',
'41',
'42',
'43',
'44',
'45',
'46',
'60',
'61'
],
TX_LED_DEFAULT_COLOR: '02', // Red
RX_LED_DEFAULT_COLOR: '01', // Green
ACTIVITY_LED_DEFAULT_COLOR: '04', // Yellow
MOISTURE_ENABLE_ALL_EVENTS: '00',
MOISTURE_DISABLE_BECOMES_WET_EVENT: '01',
MOISTURE_DISABLE_BECOMES_DRY_EVENT: '02',
MOISTURE_DISABLE_ALL_EVENTS: '03',
MOTION_ENABLE_ALL_EVENTS: '00',
MOTION_DISABLE_ALL_EVENTS: '01',
PULSE_ENABLE_ALL_EVENTS: '00',
PULSE_DISABLE_ALL_EVENTS: '01',
SWITCH_ENABLE_ALL_EVENTS: '00',
SWITCH_DISABLE_CLOSE_EVENT: '01',
SWITCH_DISABLE_OPEN_EVENT: '02',
SWITCH_DISABLE_ALL_EVENTS: '03',
TEMP_HUMIDITY_EVENT_CONFIG: '00',
PARAM_SCHEMA: Joi.object().keys({
onSensorMessage: Joi.func().required(),
onGatewayReady: Joi.func().optional(),
sendAdcWithLux: Joi.boolean().optional(),
sendRawData: Joi.boolean().optional(),
sendRawLux: Joi.boolean().optional(),
sendBootMessages: Joi.boolean().optional(),
sendStatusMessages: Joi.boolean().optional(),
sendDecodedPayload: Joi.boolean().optional(),
sendEventCount: Joi.boolean().optional(),
useFahrenheitTemps: Joi.boolean().optional(),
useMillisecondTimestamps: Joi.boolean().optional(),
switchOpenValue: Joi.boolean().optional(),
deDuplicateBursts: Joi.boolean().optional(),
decodeTextMessages: Joi.boolean().optional(),
debugMode: Joi.boolean().optional(),
sendHopData: Joi.boolean().optional(),
useTrackingId: Joi.boolean().optional(),
}).required().options({
allowUnknown: false
}),
TEXT_MESSAGE_SCHEMA: Joi.object().keys({
message: Joi.string().min(1).max(250).required(),
destination: Joi.string().length(4).required()
}).required().options({
allowUnknown: false
}),
RS485_MESSAGE_SCHEMA: Joi.object().keys({
message: Joi.string().min(1).max(250).required(),
destination: Joi.string().length(4).required(),
hexEncodePayload: Joi.boolean().optional(),
trackingId: Joi.string().length(4).regex(/([A-Fa-f0-9]{4})/gi).optional()
}).required().options({
allowUnknown: false
}),
RS485_CHUNKED_MESSAGE_SCHEMA: Joi.object().keys({
chunkNumber: Joi.number().integer().min(0).required(),
chunkSize: Joi.number().integer().min(1).required(),
destination: Joi.string().length(4).required(),
trackingId: Joi.string().length(4).regex(/([A-Fa-f0-9]{4})/gi).optional()
}).required().options({
allowUnknown: false
}),
RS485_CONFIG_MESSAGE_SCHEMA: Joi.object().keys({
baudRate: Joi.number().valid(
2400,
4800,
9600,
19200
),
parity: Joi.string().valid(
'none',
'odd',
'even'
),
stopBits: Joi.number().valid(
1,
2
),
bitMask: Joi.number().valid(
7,
8
),
destination: Joi.string().length(4).required()
}).required().options({
allowUnknown: false
}),
EVENT_CONFIG_MESSAGE_SCHEMA: Joi.object().keys({
sensorType: Joi.string().valid(
'moisture',
'motion',
'pulse',
'switch',
'tempHumidity',
'tempHumidityLight'
).required(),
sleepTime: Joi.number().integer().min(2).max(60).required(),
reportEvery: Joi.number().integer().min(1).max(1440).required(),
eventConfig: Joi.string().valid('00', '01', '02', '03').required(), // TODO constrain by value of sensorType.
moistureWetReportEvery: Joi.number().integer().min(1).optional(), // TODO required for moisture sensorType otherwise must not be present.
deploymentLifetime: Joi.number().integer().min(0).required()
}).required().options({
allowUnknown: false
}),
LED_CONFIG_MESSAGE_SCHEMA: Joi.object().keys({
destination: Joi.string().length(4).required(),
sensorType: Joi.string().valid(
'moisture',
'motion',
'pulse',
'switch',
'tempHumidity',
'tempHumidityLight'
).required(),
leds: Joi.object().keys({
tx: Joi.boolean().required(),
rx: Joi.boolean().required(),
activity: Joi.boolean().required()
}).required().options({
allowUnknown: false
}),
deploymentLifetime: Joi.number().integer().min(0).required()
}).required().options({
allowUnknown: false
}),
IGNORABLE_MESSAGE_TYPES: [ '33', '34', '35' ],
KNOWN_COMMANDS: [ 'DP', 'MR', 'SS', 'VER' ],
runGateway: async function(params) {
const validationResult = Joi.validate(params, conectricUsbGateway.PARAM_SCHEMA);
if (validationResult.error) {
console.error(validationResult.error.message);
return;
}
// sendBootMessages is on by default
if (! params.hasOwnProperty('sendBootMessages')) {
params.sendBootMessages = true;
}
// sendDecodedPayload is on by default
if (! params.hasOwnProperty('sendDecodedPayload')) {
params.sendDecodedPayload = true;
}
// deDuplicateBursts is on by default
if (! params.hasOwnProperty('deDuplicateBursts')) {
params.deDuplicateBursts = true;
}
// decodeTextMessages is on by default
if (! params.hasOwnProperty('decodeTextMessages')) {
params.decodeTextMessages = true;
}
// Establish cache if needed.
if (params.deDuplicateBursts) {
cache.init({ ttl: 30, interval: 3, randomize: false });
}
conectricUsbGateway.params = params;
conectricUsbGateway.handleUSBEvents();
conectricUsbGateway.startGateway();
},
handleUSBEvents: () => {
usb.on('attach', function(device) {
if (conectricUsbGateway.isConectricRouter(device)) {
console.log('USB Router device attached.');
setTimeout(conectricUsbGateway.startGateway, 200);
}
});
usb.on('detach', function(device) {
if (conectricUsbGateway.isConectricRouter(device)) {
console.log('USB Router device removed.');
setTimeout(conectricUsbGateway.startGateway, 100);
}
});
},
startGateway: async function () {
console.log(`Gateway node module version ${conectricUsbGateway.nodeModuleVersion}.`);
try {
await conectricUsbGateway.findRouterDevice();
console.log(`Found USB router device at ${conectricUsbGateway.comName}.`);
} catch(e) {
console.log('Waiting for USB router device.');
conectricUsbGateway.macAddress = undefined;
conectricUsbGateway.parser = undefined;
conectricUsbGateway.serialPort = undefined;
conectricUsbGateway.conectricVersion = undefined;
conectricUsbGateway.contikiVersion = undefined;
return;
}
conectricUsbGateway.startSerial();
conectricUsbGateway.parser = new Readline();
conectricUsbGateway.serialPort.pipe(conectricUsbGateway.parser);
conectricUsbGateway.serialPort.on('open', function() {
console.log('Gateway opened.');
});
conectricUsbGateway.serialPort.on('close', function() {
console.log('Gateway closed.');
});
conectricUsbGateway.parser.on('data', function(data) {
if (data.startsWith('>') && conectricUsbGateway.conectricVersion && conectricUsbGateway.contikiVersion && conectricUsbGateway.macAddress) {
// Found a message and we have started up properly.
conectricUsbGateway.parseMessage(`${data.substring(1)}`);
} else if (data.startsWith('MR:')) {
// Found mac address.
conectricUsbGateway.macAddress = `${data.substring(3)}`;
console.log(`USB router mac address is ${conectricUsbGateway.macAddress}.`);
} else if (data === 'DP:Ok') {
// Dump buffer was acknowledged OK.
console.log('Switched gateway to dump payload mode.');
} else if (data === 'SS:Ok') {
// Sink was acknowledged OK.
console.log('Switched gateway to sink mode.');
// Notify caller gateway is ready, if interested.
if (conectricUsbGateway.params.onGatewayReady) {
conectricUsbGateway.params.onGatewayReady();
}
} else if (data.toLowerCase().startsWith('ver:contiki')) {
conectricUsbGateway.contikiVersion = data.substring(12);
console.log(`USB router Contiki version: ${conectricUsbGateway.contikiVersion}`);
} else if (data.toLowerCase().startsWith('ver:conectric-v')) {
conectricUsbGateway.conectricVersion = data.substring(15);
console.log(`USB router Conectric version: ${conectricUsbGateway.conectricVersion}`);
} else {
if (! conectricUsbGateway.KNOWN_COMMANDS.includes(data)) {
if (conectricUsbGateway.params.debugMode) {
console.log(`Unprocessed: ${data}`);
}
}
}
});
setTimeout(function() {
conectricUsbGateway.serialPort.write('DP\n');
setTimeout(function() {
conectricUsbGateway.serialPort.write('V');
conectricUsbGateway.serialPort.write('E');
conectricUsbGateway.serialPort.write('R\n');
setTimeout(function() {
conectricUsbGateway.serialPort.write('MR\n');
setTimeout(function() {
conectricUsbGateway.serialPort.write('SS\n');
}, 500);
}, 500);
}, 500);
// Original:
//conectricUsbGateway.serialPort.write('DP\nMR\nVER\nSS\n');
}, 1500);
},
isConectricRouter: (device) => {
const descriptor = device.deviceDescriptor;
if (descriptor) {
return (descriptor.idVendor && descriptor.idVendor === 1027 && descriptor.idProduct && descriptor.idProduct === 24597);
}
return false;
},
isBroadcastMessageType: (messageType) => {
return conectricUsbGateway.BROADCAST_MESSAGE_TYPES.includes(messageType);
},
findRouterDevice: () => {
return new Promise((resolve, reject) => {
serialport.list((err, ports) => {
for (let n = 0; n < ports.length; n++) {
const port = ports[n];
const lowerPortName = port.comName.toLowerCase();
if (port.manufacturer && port.manufacturer === 'FTDI' && (
lowerPortName.indexOf('usbserial-') !== -1 ||
lowerPortName.indexOf('ttyusb') !== -1 ||
lowerPortName.indexOf('com') !== -1)
) {
conectricUsbGateway.comName = port.comName;
return resolve(port.comName);
}
}
// No suitable port found.
conectricUsbGateway.comName = null;
return reject();
});
});
},
startSerial: () => {
conectricUsbGateway.serialPort = new serialport(conectricUsbGateway.comName, {
baudRate: 230400
});
return conectricUsbGateway.serialPort;
},
hexEncode: (message) => {
let encodedMessage = '';
for (let n = 0; n < message.length; n++) {
let encodedChar = message.charCodeAt(n).toString(16);
if (encodedChar.length === 1) {
encodedChar = `0${encodedChar}`;
}
encodedMessage = `${encodedMessage}${encodedChar}`;
}
return encodedMessage;
},
hexDecode: (message) => {
let decodedMessage = '';
for (let n = 0; n < message.length; n += 2) {
decodedMessage = `${decodedMessage}${String.fromCharCode(parseInt(message.substr(n, 2), 16))}`;
}
return decodedMessage;
},
calculateTemperature: (tempRaw) => {
const temperature = roundTo((-46.85 + ((parseInt(tempRaw, 16) / 65536) * 175.72)), 2); // C
if (conectricUsbGateway.params.useFahrenheitTemps) {
return {
temperature: roundTo(((temperature * (9 / 5)) + 32), 2), // F
temperatureUnit: 'F'
}
} else {
return {
temperature,
temperatureUnit: 'C'
}
message.payload.temperatureUnit = 'C';
}
},
calculateHumidity: (humidityRaw) => {
return roundTo((-6 + (125 * (parseInt(humidityRaw, 16) / 65536))), 2); // percentage
},
sendTextMessage: (params) => {
const validationResult = Joi.validate(params, conectricUsbGateway.TEXT_MESSAGE_SCHEMA);
if (validationResult.error) {
console.error(validationResult.error.message);
return false;
}
let encodedPayload = conectricUsbGateway.hexEncode(params.message);
// length:
// 1 for the message type
// 1 for the length
// 2 for the destination
// 1 for the reserved part
// 1 for each letter in the message
let msgLen = 5 + params.message.length;
let hexLen = msgLen.toString(16);
if (hexLen.length === 1) {
hexLen = `0${hexLen}`;
}
let outboundMessage = `<${hexLen}61${params.destination}01${encodedPayload}`;
if (conectricUsbGateway.params.debugMode) {
console.log(`Outbound text message: ${outboundMessage}`);
}
conectricUsbGateway.serialPort.write(`${outboundMessage}\n`);
return true;
},
_sendRS485Message: (params) => {
// hexEncodePayload is on by default
if (! params.hasOwnProperty('hexEncodePayload')) {
params.hexEncodePayload = true;
}
let encodedPayload;
if (params.hexEncodePayload) {
if (conectricUsbGateway.params.debugMode) {
console.log('Hex encoding outbound RS485 request message.');
}
encodedPayload = conectricUsbGateway.hexEncode(params.message);
} else {
encodedPayload = params.message;
}
// length:
// 1 for the message type
// 1 for the length
// 2 for the destination
// 1 for the reserved part
// 1 for each letter in the message if encoding
let msgLen = 5 + (params.hexEncodePayload ? params.message.length : params.message.length / 2);
// Add another 2 if trackingId is set.
if (params.trackingId) {
msgLen += 2;
}
let hexLen = msgLen.toString(16);
if (hexLen.length === 1) {
hexLen = `0${hexLen}`;
}
let outboundMessage = `<${hexLen}${params.msgCode}${params.destination}01${encodedPayload}`;
if (params.trackingId) {
outboundMessage = `${outboundMessage}${params.trackingId}`;
}
if (conectricUsbGateway.params.debugMode) {
console.log(`Outbound RS485 request: ${outboundMessage}`);
}
conectricUsbGateway.serialPort.write(`${outboundMessage}\n`);
return true;
},
sendRS485ChunkRequest: (params) => {
const validationResult = Joi.validate(params, conectricUsbGateway.RS485_CHUNKED_MESSAGE_SCHEMA);
if (validationResult.error) {
console.error(validationResult.error.message);
return false;
}
params.msgCode = 38;
let chunkNumberHex = params.chunkNumber.toString(16);
if (chunkNumberHex.length === 1) {
chunkNumberHex = `0${chunkNumberHex}`;
}
let chunkSizeHex = params.chunkSize.toString(16);
if (chunkSizeHex.length === 1) {
chunkSizeHex = `0${chunkSizeHex}`;
}
params.message = `${chunkNumberHex}${chunkSizeHex}`;
params.hexEncodePayload = false;
return conectricUsbGateway._sendRS485Message(params);
},
getSensorCodeFromType: (sensorType) => {
let r = '';
switch (sensorType) {
case 'moisture':
r = '59';
break;
case 'motion':
r = '04';
break;
case 'pulse':
r = '3d';
break;
case 'switch':
r = '05';
break;
case 'tempHumidity':
r = '29';
break;
case 'tempHumidityLight':
r = '5a';
break;
}
return r;
},
convertToLittleEndianHex: (valueToConvert) => {
let working = valueToConvert.toString(16);
// Pad out to 2 hex bytes
while (working.length < 4) {
working = `0${working}`;
}
// Swap the bytes as reportEvery is little endian
return `${working.substring(2)}${working.substring(0, 2)}`;
},
sendEventConfigMessage: (params) => {
const validationResult = Joi.validate(params, conectricUsbGateway.EVENT_CONFIG_MESSAGE_SCHEMA);
if (validationResult.error) {
console.error(validationResult.error.message);
return false;
}
params.msgCode = '1c';
const destinationSensorType = conectricUsbGateway.getSensorCodeFromType(params.sensorType);
let deploymentLifetime = params.deploymentLifetime.toString(16);
if (deploymentLifetime.length < 2) {
deploymentLifetime = `0${deploymentLifetime}`;
}
const sleepTime = conectricUsbGateway.convertToLittleEndianHex(params.sleepTime);
let reportEvery = conectricUsbGateway.convertToLittleEndianHex(params.reportEvery);
let moistureWetReportEvery = '0000';
if (params.sensorType === 'moisture') {
moistureWetReportEvery = conectricUsbGateway.convertToLittleEndianHex(params.moistureWetReportEvery);
}
let msg = `${params.msgCode}000001${deploymentLifetime}c208${destinationSensorType}${sleepTime}${params.eventConfig}00${reportEvery}${moistureWetReportEvery}`
let msgLen = Math.round(1 + (msg.length / 2)); // 1 is the length byte.
let hexLen = msgLen.toString(16);
if (hexLen.length === 1) {
hexLen = `0${hexLen}`;
}
let outboundMessage = `<${hexLen}${msg}`;
if (conectricUsbGateway.params.debugMode) {
console.log(`Outbound interval config message: ${outboundMessage}`);
}
conectricUsbGateway.serialPort.write(`${outboundMessage}\n`);
return true;
},
sendLEDConfigMessage: (params) => {
const validationResult = Joi.validate(params, conectricUsbGateway.LED_CONFIG_MESSAGE_SCHEMA);
if (validationResult.error) {
console.error(validationResult.error.message);
return false;
}
params.msgCode = '1c'; // set here
const destinationSensorType = conectricUsbGateway.getSensorCodeFromType(params.sensorType);
const txLED = params.leds.tx === true ? conectricUsbGateway.TX_LED_DEFAULT_COLOR : '00';
const rxLED = params.leds.rx === true ? conectricUsbGateway.RX_LED_DEFAULT_COLOR : '00';
const activityLED = params.leds.activity === true ? conectricUsbGateway.ACTIVITY_LED_DEFAULT_COLOR : '00';
let deploymentLifetime = params.deploymentLifetime.toString(16);
if (deploymentLifetime.length < 2) {
deploymentLifetime = `0${deploymentLifetime}`;
}
let msg = `${params.msgCode}${params.destination}01${deploymentLifetime}c108${destinationSensorType}07010204${txLED}${rxLED}${activityLED}00`
let msgLen = Math.round(1 + (msg.length / 2)); // 1 is the length byte.
let hexLen = msgLen.toString(16);
if (hexLen.length === 1) {
hexLen = `0${hexLen}`;
}
let outboundMessage = `<${hexLen}${msg}`;
if (conectricUsbGateway.params.debugMode) {
console.log(`Outbound LED config message: ${outboundMessage}`);
}
conectricUsbGateway.serialPort.write(`${outboundMessage}\n`);
return true;
},
sendRS485Request: (params) => {
const validationResult = Joi.validate(params, conectricUsbGateway.RS485_MESSAGE_SCHEMA);
if (validationResult.error) {
console.error(validationResult.error.message);
return false;
}
params.msgCode = 36;
return conectricUsbGateway._sendRS485Message(params);
},
sendRS485ConfigMessage: (params) => {
const validationResult = Joi.validate(params, conectricUsbGateway.RS485_CONFIG_MESSAGE_SCHEMA);
if (validationResult.error) {
console.error(validationResult.error.message);
return false;
}
let baudRate;
switch (params.baudRate) {
case 2400:
baudRate = '00';
break;
case 4800:
baudRate = '01';
break;
case 9600:
baudRate = '02';
break;
case 19200:
baudRate = '03';
break;
}
let parity;
switch (params.parity) {
case conectricUsbGateway.PARITY_NONE:
parity = '00';
break;
case conectricUsbGateway.PARITY_ODD:
parity = '01';
break;
case conectricUsbGateway.PARITY_EVEN:
parity = '02';
break;
}
const stopBits = (params.stopBits === 1 ? '00' : '01');
const bitMask = (params.bitMask === 8 ? '00' : '01');
let outboundMessage = `<0970${params.destination}01${baudRate}${parity}${stopBits}${bitMask}`;
if (conectricUsbGateway.params.debugMode) {
console.log(`Outbound RS485 config message: ${outboundMessage}`);
}
conectricUsbGateway.serialPort.write(`${outboundMessage}\n`);
return true;
},
parseMessage: (data) => {
const fullMessage = data;
let trackingId;
if (conectricUsbGateway.params.debugMode) {
console.log(fullMessage);
}
if (conectricUsbGateway.params.useTrackingId) {
trackingId = data.substring(data.length - 4);
}
// Chop off the last 4 which are CRC.
data = data.substring(0, data.length - 4);
if (conectricUsbGateway.params.debugMode) {
console.log(`Removed tracking ID from data, leaving: ${data}`);
}
// Get to the message type value first so we can drop message
// types that are not intended for the end user.
const hexHeader = parseInt(data.substring(0, 2), 16);
const headerLength = (hexHeader & 31); // 0x1F
const headerType = (hexHeader & 128); // 0x80
const payloadType = (hexHeader & 96); // 0x60
// Right now we don't support the extended header, and
// we only support the simple payload.
if (headerType !== 0) {
if (conectricUsbGateway.params.debugMode) {
console.log(`Dropping message "${fullMessage}" as messages with extended headers are unsupported in this version.`);
}
return;
}
if (payloadType !== 32) {
if (conectricUsbGateway.params.debugMode) {
console.log(`Dropping message "${fullMessage}" as this payload type is unsupported in this version.`);
}
return;
}
const messageType = data.substring(2 + (headerLength * 2), 4 + (headerLength * 2));
if (conectricUsbGateway.IGNORABLE_MESSAGE_TYPES.includes(messageType)) {
// Drop this message and do no more work on it.
if (conectricUsbGateway.params.debugMode) {
console.log(`Dropping message "${fullMessage}" as it is ignorable.`);
}
return;
}
const messageTypeString = conectricUsbGateway.MESSAGE_TYPES[messageType];
if (! messageTypeString || messageTypeString.length === 0) {
if (conectricUsbGateway.params.debugMode) {
console.log(`Ignoring unknown message type "${messageType}".`);
}
return;
}
const sourceAddr = data.substring(8, 12);
const sequenceNumber = parseInt(data.substring(2, 4), 16);
const payloadLength = parseInt(data.substring(0 + (headerLength * 2), 2 + (headerLength * 2)), 16);
const battery = parseInt(data.substring(4 + (headerLength * 2), 6 + (headerLength * 2)), 16) / 10;
const messageData = data.substring(6 + (headerLength * 2));
// Check if we have cached this message before
if (conectricUsbGateway.params.deDuplicateBursts) {
const cacheKey = `${sourceAddr}${sequenceNumber}${messageData}`;
if (! cache.get(cacheKey)) {
// We have not dealt with this burst before.
cache.set(cacheKey, true);
} else {
// We have seen this recently and processed it so drop it.
if (conectricUsbGateway.params.debugMode) {
console.log(`Dropping message "${data}", already processed message from this burst.`);
}
return;
}
}
const message = {
type: messageTypeString,
payload: {},
sensorId: sourceAddr,
sequenceNumber
};
message.timestamp= (conectricUsbGateway.params.useMillisecondTimestamps ? moment().valueOf() : moment().unix());
if (conectricUsbGateway.params.useTrackingId && conectricUsbGateway.TRACKABLE_MESSAGES.includes(messageType)) {
message.trackingId = trackingId;
}
if (conectricUsbGateway.isBroadcastMessageType(messageType)) {
// Broadcast message detected add extra fields.
if (conectricUsbGateway.params.debugMode) {
console.log(`Message type "${messageType}" is a broadcast message type.`);
}
if (conectricUsbGateway.params.sendHopData) {
message.numHops = parseInt(data.substring(4, 6), 16);
message.maxHops = parseInt(data.substring(6, 8), 16);
}
} else if (conectricUsbGateway.params.debugMode) {
console.log(`Message type "${messageType}" is not a broadcast message type.`);
}
if (conectricUsbGateway.params.sendRawData) {
message.rawData = fullMessage;
}
if (! conectricUsbGateway.params.sendDecodedPayload) {
delete(message.payload);
} else {
switch (messageTypeString) {
case 'tempHumidity':
let tempRaw
let humidityRaw
if (messageData.length === 8) {
// Older style
tempRaw = messageData.substring(0, 4);
humidityRaw = messageData.substring(4);
} else {
// Newer style
tempRaw = messageData.substring(10, 14);
humidityRaw = messageData.substring(14);
if (conectricUsbGateway.params.sendEventCount) {
message.payload.eventCount = parseInt(messageData.substring(2, 10), 16)
}
}
message.payload = {
...message.payload,
battery,
...conectricUsbGateway.calculateTemperature(tempRaw),
humidity: conectricUsbGateway.calculateHumidity(humidityRaw)
};
break;
case 'tempHumidityAdc':
{
message.payload.battery = battery;
if (conectricUsbGateway.params.sendEventCount) {
message.payload.eventCount = parseInt(messageData.substring(2, 10), 16)
}
const rawTemp = messageData.substring(10, 14);
const rawHumidity = messageData.substring(14, 18);
const rawAdcMax = messageData.substring(22, 26);
const rawAdcIn = messageData.substring(26);
message.payload = {
...message.payload,
...conectricUsbGateway.calculateTemperature(rawTemp),
humidity: conectricUsbGateway.calculateHumidity(rawHumidity),
adcIn: rawAdcIn,
adcMax: rawAdcMax
}
if (conectricUsbGateway.params.debugMode) {
console.log(`Raw adc in: ${rawAdcIn}`);
console.log(`Raw adc max: ${rawAdcMax}`);
console.log(`Raw battery: ${messageData.substring(18, 22)}`);
}
} break;
case 'tempHumidityLight':
{
message.payload.battery = battery;
if (conectricUsbGateway.params.sendEventCount) {
message.payload.eventCount = parseInt(messageData.substring(2, 10), 16);
}
const rawTemp = messageData.substring(10, 14);
const rawHumidity = messageData.substring(14, 18);
const rawAdcMax = messageData.substring(22, 26);
const rawAdcIn = messageData.substring(26);
const lux = roundTo(0.003 * Math.pow(parseInt(rawAdcIn, 16), (1.89 - (3.7 - battery) / 25)), 0);
let bucketedLux = Math.round(lux / 100);
if (bucketedLux > 15) {
bucketedLux = 15;
}
message.payload = {
...message.payload,
...conectricUsbGateway.calculateTemperature(rawTemp),
humidity: conectricUsbGateway.calculateHumidity(rawHumidity),
bucketedLux
};
if (conectricUsbGateway.params.sendRawLux) {
message.payload.lux = lux;
}
if (conectricUsbGateway.params.sendAdcWithLux) {
message.payload.adcIn = rawAdcIn;
message.payload.adcMax = rawAdcMax;
}
if (conectricUsbGateway.params.debugMode) {
console.log(`Raw adc in: ${rawAdcIn}`);
console.log(`Raw adc max: ${rawAdcMax}`);
console.log(`Raw battery: ${messageData.substring(18, 22)}`);
}
} break;
case 'moisture':
message.payload.battery = battery;
// This is a new protocol only sensor, so event count
// data will always be present...
if (messageData.startsWith('21') || messageData.startsWith('22')) {
// This is a status report not an actual event.
if (! conectricUsbGateway.params.sendStatusMessages) {
// Not sending status message to callback.
return;
}
message.type = 'moistureStatus';
message.payload = {
...message.payload,
moisture: messageData.startsWith('21'),
...conectricUsbGateway.calculateTemperature(messageData.substring(10, 14)),
humidity: conectricUsbGateway.calculateHumidity(messageData.substring(14))
};
} else {
// 81 = event caused because now wet where was dry.
// 82 = event caused because now dry where was wet.
message.payload.moisture = messageData.startsWith('81');
}
if (conectricUsbGateway.params.sendEventCount) {
message.payload.eventCount = parseInt(messageData.substring(2, 10), 16)
}
break;
case 'echoStatus':
case 'rs485Status':
message.payload.battery = battery;
if (! conectricUsbGateway.params.sendStatusMessages) {
// Not sending status message to callback.
return;
}
// Add eventCount for messages that have it.
if (messageData.length === 10 && conectricUsbGateway.params.sendEventCount) {
message.payload.eventCount = parseInt(messageData.substring(2), 16)
}
break;
case 'motion':
message.payload.battery = battery;
if (messageData.startsWith('20')) {
// This is a status report not an actual event.
if (! conectricUsbGateway.params.sendStatusMessages) {