-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathrfxcom.js
More file actions
2009 lines (1893 loc) · 73.6 KB
/
Copy pathrfxcom.js
File metadata and controls
2009 lines (1893 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const
{ SerialPort } = require("serialport"),
rfxcom = require("./index"),
EventEmitter = require("events"),
Queue = require("queue"),
defines = require("./defines"),
util = require("util"),
dateFormat = require("date-format"),
Transform = require("stream").Transform;
class RFXParser extends Transform {
// This is a buffering parser which accumulates message bytes until it receives the number of bytes specified by the
// first byte of the message + 1. It relies on a flushed buffer, to ensure it starts with the length byte of the
// first message. The 'data' message emitted contains all the message bytes. Messages may be split across multiple
// buffers, or a single buffer may contain multiple messages. If a length byte is outside the valid range (less than 4)
// it is assumed synchronisation has been lost and all received data is discarded. The parser attempts to resynchronise
// at the start of the next buffer.
constructor(rfxtrx) {
super({readableObjectMode: true});
this.data = [];
this.requiredBytes = 0;
this.rfxtrx = rfxtrx;
}
// noinspection JSUnusedGlobalSymbols
_transform(buffer, encoding, callback) {
if (this.rfxtrx.receiving) {
this.data.push.apply(this.data, buffer);
while (this.data.length >= this.requiredBytes) {
if (this.requiredBytes > 0) { // There is a message in the buffer - push it
this.push(this.data.slice(0, this.requiredBytes));
this.data = this.data.slice(this.requiredBytes);
}
if (this.data.length > 0 && this.data[0] >= 4) { // data[0] is the length byte of the next message
this.requiredBytes = this.data[0] + 1;
} else { // lost synch - flush & try again
this.requiredBytes = 0;
this.data = [];
break;
}
}
}
callback();
}
}
class RfxCom extends EventEmitter {
constructor(device, options) {
super();
const self = this;
// Store the device to use
this.device = device;
this.options = options || {};
// Allow for faking out the SerialPort
if (typeof this.options.port !== "undefined") {
this.serialport = options.port;
}
this.firmwareVersion = 0;
// Device-specific parmeters for packet hndlers
this.deviceParameters = this.options.deviceParameters || {};
// Packet handlers
this.handlers = {
0x01: "statusMessageHandler",
0x02: "transmitCommandResponseHandler",
0x10: "lighting1Handler",
0x11: "lighting2Handler",
0x13: "lighting4Handler",
0x14: "lighting5Handler",
0x15: "lighting6Handler",
0x16: "chimeHandler",
0x17: "fanHandler",
0x19: "blinds1Handler",
0x1c: "edisioHandler",
0x1d: "activLinkHandler",
0x1e: "funkbusHandler",
0x1f: "hunterfanHandler",
0x20: "security1Handler",
0x28: "camera1Handler",
0x30: "remoteHandler",
0x31: "blinds2Handler",
0x40: "thermostat1Handler",
0x42: "thermostat3Handler",
0x4e: "bbqHandler",
0x4f: "temprainHandler",
0x50: "tempHandler",
0x51: "humidityHandler",
0x52: "temphumidityHandler",
0x54: "temphumbaroHandler",
0x55: "rainHandler",
0x56: "windHandler",
0x57: "uvHandler",
0x58: "dateTimeHandler",
0x59: "elec1Handler",
0x5a: "elec23Handler",
0x5b: "elec4Handler",
0x5c: "elec5Handler",
0x5d: "weightHandler",
0x60: "cartelectronicHandler",
0x70: "rfxsensorHandler",
0x71: "rfxmeterHandler",
0x73: "waterlevelHandler",
0x74: "lightningHandler",
0x76: "weatherHandler",
0x77: "solarHandler"
};
// Human-readable names for packets & devices
this.deviceNames = rfxcom.deviceNames;
this.packetNames = rfxcom.packetNames;
// This is how long a caller must wait between initialisation attempts
// It is long enough for the 'ready' event to have been emitted if the
// previous call to initialise() succeeded
this.initialiseWaitTime = 6000;
// Running counter for command message sequence numbers.
this._seqnbr = 0;
// The transmit message queue
// The transmission timeout is set to 12s to allow time for 40 Rfy remotes to be reported in response
// to an Rfy.listRemotes() call. I measured this at 10.1s on a fast system, with no other packets present
this.TxQ = Queue({concurrency: self.options.concurrency || 3,
timeout: self.options.timeout || 12000});
this.TxQ.on("timeout", function (next, transmission) {
if (transmission.sender._timeoutHandler.call(transmission.sender, transmission.buffer, transmission.seqnbr) === false) {
self.debugLog("Error : Command message " + RfxCom.dumpHex([transmission.seqnbr]) +
", timed out waiting for response");
self.emit("response", "Timed out waiting for response", transmission.seqnbr, rfxcom.responseCode.TIMEOUT);
}
next();
});
// Holds the command acknowledgement callbacks for the transmit queue
this.acknowledge = new Array(256);
for (let idx = 0; idx < this.acknowledge.length; idx++) {
this.acknowledge[idx] = null;
}
// Create the parser and listen for data events from it (the parser will be applied to the serialport once the
// port has been created)
this.parser = new RFXParser(this);
this.parser.on("data", function(data) {
const
length = data[0] + 1,
packetType = data[1],
handler = self.handlers[packetType];
self.debugLog("Received: " + RfxCom.dumpHex(data));
// Always emit a "receive" event, even if we don't have a handler for the packet type
self.emit("receive", data);
// Avoid calling a handler with the wrong length packet, and catch any Error a handler may throw
if (data.length !== length) {
self.debugLog("Wrong packet length: " + data.length + " bytes, should be " + length)
} else {
if (typeof handler !== "undefined") {
try {
self[handler](data.slice(2), packetType);
} catch (e) {
if (e instanceof Error) {
self.debugLog("Packet type " + RfxCom.dumpHex([packetType]) +
" handler threw exception " + e.name + ": " + e.message);
}
}
} else {
self.debugLog("Unhandled packet type = " + RfxCom.dumpHex([packetType]));
}
}
});
// Send the initial handshake sequence once the serialport is open & handle errors
this.on("ready", function () {
self.resetRFX(function (err) {
if (err) {
self.close();
self.emit("disconnect", err);
} else {
setTimeout(function () {
// TODO - test that flush() now works correctly on Windows
if (process.platform === "win32") {
self.receiving = true;
self.getRFXStatus(function (err) {
if (err) {
self.close();
self.emit("disconnect", err);
}
});
} else {
self.flush(function (err) {
if (err) {
self.close();
self.emit("disconnect", err);
} else {
self.receiving = true;
self.getRFXStatus(function (err) {
if (err) {
self.close();
self.emit("disconnect", err);
}
});
}
});
}
}, 500);
// 30-second timeout in case we are not connected to an RFX device at all
/*
TODO - this isn't quite right: it's only needed if the previous timeout hasn't connected
setTimeout(function () {
self.close();
self.emit("disconnect", "Timeout waiting for response")
}, 30000);
*/
}
});
});
// Initial state
this.portEventHandlersInstalled = false;
this.connected = false;
this.initialising = false;
this.receiving = false;
this.startReceiverRequired = true;
this.transmitters = {};
this.readyCallback = null;
this.receiverTypeCode = 0x00;
this.transmitterPower = +10; // dBm;
};
debugLog(message) {
if (this.options.debug) {
console.log(dateFormat("yyyy-MM-dd hh:mm:ss.SSS", new Date(Date.now())) + " [rfxcom] on " + this.device + " - " + message);
}
};
/*
* These methods allow an arbitrary name/value pair {parameter, value} to be set for a particular device
* "subtype/Id" and a specified packet type.
*
* This allows event handlers to access device-specified configuration data, e.g. for RAIN8 (Davis) gauges, which can
* have Metric or US Customary buckets {cartridgeVolume: 0.2} or {cartridgeVolume: 0.01}
*
* The setter uses names, but the getter uses numbers, as these are more easily accessed by the packet data handlers.
*/
setDeviceParameter(packetName, subtypeName, id, parameter, value) {
let key = subtypeName + "/0x" + Number(id).toString(16).toUpperCase();
this.deviceParameters[rfxcom.packetNames[packetName]] = {};
this.deviceParameters[rfxcom.packetNames[packetName]][key] = {};
this.deviceParameters[rfxcom.packetNames[packetName]][key][parameter] = value;
}
getDeviceParameter(packetType, subtype, id, parameter, defaultValue) {
let value = defaultValue;
let packetTypeParameters = this.deviceParameters[packetType];
if (packetTypeParameters) {
let deviceParameters = packetTypeParameters[rfxcom[this.packetNames[packetType]][subtype] + "/" + id];
if (deviceParameters) {
value = deviceParameters[parameter];
}
}
return value;
}
nextMessageSequenceNumber() {
// Fetches a "command message sequence number" for identifying requests sent to the device.
if (this._seqnbr > 255) {
this._seqnbr = 0;
}
return this._seqnbr++;
};
// The 'proper' way to start up the RFXtrx. If supplied, the callback will be called after the device is ready and
// the handshake sequence has completed - no corresponding event is emitted, so this is the only way to take action
// on this condition
initialise(callback) {
if (this.initialising === false) {
this.initialising = true;
this.readyCallback = callback || null;
this.open();
}
};
// Attempt to establish communication with the RFXtrx
open() {
const self = this;
// If we weren't supplied a serialport in the constructor, create one
if (typeof self.serialport === "undefined") {
// Delay opening the serialport until after the event handlers are installed
self.serialport = new SerialPort({
path: self.device,
baudRate: 38400,
lock: false,
autoOpen: false
});
}
// Make sure all data is piped to the parser (also for faked serialports)
if (typeof self.serialport.pipe === "function") {
self.serialport.pipe(self.parser);
}
// Important: only ever install the handlers once, no matter how many times open() is called!
if (self.portEventHandlersInstalled === false) {
self.serialport.on("open", self.openHandler.bind(self));
self.serialport.on("error", self.errorHandler.bind(self));
self.serialport.on("close", self.closeHandler.bind(self));
self.portEventHandlersInstalled = true;
}
// Now everything is set up, open the serialport - the "open" event handler starts the handshake
if (typeof self.serialport.open === "function") {
self.serialport.open();
}
};
// Called to clear all state when the RFXtrx is disconnected, or we want to force a disconnection
close() {
// Cancel all messages in the queue
this.TxQ.end();
this.debugLog("Cleared command message queue");
for (let idx = 0; idx < this.acknowledge.length; idx++) {
this.acknowledge[idx] = null;
}
this._seqnbr = 0;
// Close the serialport if necessary - should only happen if this function is called from user code
if (this.serialport && this.serialport.isOpen) {
this.serialport.close(null, null);
}
this.connected = false;
this.initialising = false;
this.receiving = false;
};
// If the RFXTRX has just been connected, we must wait for at least 5s before any
// attempt to communicate with it, or it will enter the flash bootloader.
// We can't know how long it has been connected, so we must always wait!
openHandler() {
const self = this;
this.connected = true;
this.emit("connecting");
setTimeout(function () {
self.emit("ready")
}, this.initialiseWaitTime - 500);
};
disconnectHandler(err) {
// Call close() to clear the transmit queue and reset our state, then emit the
// appropriate event
const wasConnected = this.connected;
this.close();
if (wasConnected) {
this.emit("disconnect", err.message);
} else {
this.emit("connectfailed", err.message);
}
};
errorHandler(err) {
this.debugLog(err.message);
// If the port open fails, handle as a disconnect
if (err.message.startsWith("Error: No such file or directory, cannot open")) {
this.disconnectHandler(err);
}
};
closeHandler(err) {
// Handle a disconnect when one occurs
if (err && err.disconnected === true) {
this.debugLog("RFXtrx433 disconnected from " + this.device);
this.disconnectHandler(err);
}
};
/*
*
* Calls flush on the underlying SerialPort.
*
*/
flush(callback) {
if (typeof this.serialport.flush === "function") {
this.serialport.flush(callback);
}
};
queueMessage(sender, buffer, seqnbr, callback) {
// External function for queueing messages for later transmission
const self = this;
if (self.connected) {
self.debugLog("Queued : " + RfxCom.dumpHex(buffer));
self.TxQ.push(function () {
let transmission = function (cb) {
self.acknowledge[seqnbr] = cb;
self.transmit(buffer, seqnbr, callback);
};
transmission.buffer = buffer;
transmission.seqnbr = seqnbr;
transmission.sender = sender;
return transmission;
}()
);
if (self.initialising === false) {
self.TxQ.start();
}
}
};
_sendMessage(type, subtype, cmd, extra, callback) {
// Internal function for sending messages to the device, bypassing the transmit queue
const
seqnbr = this.nextMessageSequenceNumber(),
byteCount = extra.length + 4;
let buffer = [byteCount, type, subtype, seqnbr, cmd];
buffer = buffer.concat(extra);
this.transmit(buffer, seqnbr, callback);
return seqnbr;
};
/*
* Send bytes to the serialport - called either directly from _sendMessage or from the transmit queue job
* Log the transmitted bytes to console if debug enabled
*/
transmit(buffer, seqnbr, callback) {
const self = this;
if (self.serialport && typeof self.serialport.write === "function") {
if (self.serialport.isOpen) {
self.serialport.write(buffer, function (err, response) {
self.debugLog("Sent : " + RfxCom.dumpHex(buffer));
if (callback && typeof callback === "function") {
return callback(err, response, seqnbr);
}
});
} else {
self.debugLog("Serial port was closed unexpectedly");
self.debugLog("Dropped : " + RfxCom.dumpHex(buffer));
}
}
};
/*
*
* Writes the resetRFX sequence to the RFxtrx433.
*
*/
resetRFX(callback) {
return this._sendMessage(0, 0, 0, [0, 0, 0, 0, 0, 0, 0, 0, 0], callback);
};
/*
* Sends the get status bytes to the interface.
*/
getRFXStatus(callback) {
return this._sendMessage(0, 0, 2, [0, 0, 0, 0, 0, 0, 0, 0, 0], callback);
};
/*
* Sends the start receiver bytes to the interface.
*/
startRFXReceiver(callback) {
return this._sendMessage(0, 0, 7, [0, 0, 0, 0, 0, 0, 0, 0, 0], callback);
};
/*
* Enables reception of different protocols - now just a compatibilty shim around configureRFX()
*/
enableRFXProtocols(protocols, callback) {
this.configureRFX(0, 0, protocols, callback);
};
/*
* Set receiver frequency & transmitter power (where these are configurable) and the set of
* enabled protocols to receive. Frequency units are MHz, power units dBm
*/
configureRFX(rxFrequency, txPower, protocols, callback) {
const
seqnbr = this.nextMessageSequenceNumber(),
header = [0x0D, 0x00, 0x00, seqnbr, 0x03];
let msg = [this.receiverTypeCode, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
rxFrequency = Number(rxFrequency);
// noinspection FallThroughInSwitchStatementJS
switch (this.receiverTypeCode) {
case 0x50:
case 0x51:
// RFXtrx315
if (rxFrequency === 310) {
msg[0] = 0x50;
} else if (rxFrequency === 315) {
msg[0] = 0x51;
}
break;
case 0x53:
case 0x54:
case 0x5f:
// RFXtrx433, RFXtrx433E, RFXtrx433Pro
if (rxFrequency === 433.92) {
msg[0] = 0x53;
} else if (rxFrequency === 433.42) {
msg[0] = 0x54;
} else if (rxFrequency === 434.50) {
msg[0] = 0x5F;
}
break;
case 0x5C:
case 0x5D:
// RFXtrxIOT
if (rxFrequency === 433 || rxFrequency === 434) {
msg[0] = 0x5C;
} else if (rxFrequency === 868) {
msg[0] = 0x5D;
}
case 0x55:
case 0x56:
case 0x57:
case 0x58:
case 0x59:
case 0x5A:
case 0x5B:
// RFXtrx868
if (txPower >= -18 && txPower <= +13) {
this.transmitterPower = Math.round(txPower);
msg[1] = this.transmitterPower + 0x12;
}
break;
}
this.receiverTypeCode = msg[0];
if (Array.isArray(protocols) === false) {
protocols = [protocols];
}
protocols.forEach(function(protocol) {
if (typeof msg[protocol.msg] === "undefined") {
msg[protocol.msg - 1] = protocol.bit;
} else {
msg[protocol.msg - 1] |= protocol.bit;
}
});
return this.queueMessage(this, header.concat(msg), seqnbr, callback);
};
/*
* Save the enabled protocols of the receiver/transceiver in non-volatile memory
*
* Important: Do not send the saveRFXProtocols command very often because there is a
* maximum of 10,000 write cycles to non-volatile memory!
*/
saveRFXProtocols(callback) {
const msg = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
return this._sendMessage(0, 0, 0x06, msg, callback);
};
//------------------------------------------
// INTERFACE CONTROL MESSAGE HANDLERS
//------------------------------------------
/*
*
* Called by the data event handler when an Interface Response Message arrives
* from the device.
*
*/
statusMessageHandler(data) {
const
self = this,
receiverTypes = {
0x50: "310MHz",
0x51: "315MHz",
0x52: "433.92MHz receiver only",
0x53: "433.92MHz transceiver",
0x54: "433.42MHz transceiver",
0x55: "868.00MHz",
0x56: "868.00MHz FSK", // Obsolete
0x57: "868.30MHz", // Obsolete
0x58: "868.30MHz FSK", // Obsolete
0x59: "868.35MHz", // Obsolete
0x5A: "868.35MHz FSK", // Obsolete
0x5B: "868.95MHz", // Obsolete
0x5C: "433.92MHz RFXtrxIOT",
0x5D: "868.00MHz RFXtrxIOT",
0x5F: "434.50MHz transceiver"
},
firmwareTypes = {0x00: "Type 1 RO", 0x01: "Type 1", 0x02: "Type 2", 0x03: "Ext", 0x04: "Ext 2",
0x05: "Pro 1", 0x06: "Pro 2", 0x10: "ProXL 1", 0x13: "ProXL 2", 0x14: "RFX433",
0x15: "RFX868", 0x16: "ProXL 95", 0x18: "RFX310"},
subtype = data[0],
seqnbr = data[1],
cmnd = data[2];
let transmitterPower = 10, msg, hardwareVersion, firmwareVersion, firmwareType, protocols, copyrightText;
if (subtype === 0xFF) { // Message not understood!
if (self.acknowledge[seqnbr] !== undefined && typeof self.acknowledge[seqnbr] === "function") {
self.acknowledge[seqnbr]();
self.acknowledge[seqnbr] = null;
}
// Handle early firmware versions that don't understand command 0x07 - "start receiver"
if (self.initialising) {
self.initialising = false;
self.TxQ.start();
self.debugLog("Started command message queue");
} else {
self.debugLog("Response: Command message " + RfxCom.dumpHex([seqnbr]) +
", command unknown or not supported by this device");
self.emit("response", "Command unknown or not supported by this device",
seqnbr, rfxcom.responseCode.UNKNOWN_COMMAND);
}
} else if (subtype === 0x07) { // Start receiver response (should return copyright message)
if (self.acknowledge[seqnbr] !== undefined && typeof self.acknowledge[seqnbr] === "function") {
self.acknowledge[seqnbr]();
self.acknowledge[seqnbr] = null;
}
copyrightText = String.fromCharCode.apply(String, data.slice(3, 19));
self.emit("receiverstarted", copyrightText);
if (copyrightText === "Copyright RFXCOM") {
self.debugLog(copyrightText);
if (self.initialising) {
self.initialising = false;
self.TxQ.start();
self.debugLog("Started command message queue");
if (typeof self.readyCallback === "function") {
self.readyCallback();
}
}
} else {
throw new Error("[rfxcom] on " + self.device + " - Invalid response '" + copyrightText +"'");
}
} else if (subtype === 0x04 || subtype === 0x03) { // Handle RFY/ASA list remotes status response
const params = {
remoteNumber: data[3],
remoteType: subtype === 0x03 ? "RFY" : "ASA",
deviceId: "0x" + RfxCom.dumpHex(data.slice(4, 7)).join("") + "/" + data[7],
idBytes: [data[4], data[5], data[6]],
unitCode: data[7],
randomCode: data[8],
rollingCode: 256*data[9] + data[10]
};
self.rfyRemotesList.push(params);
} else if (subtype === 0x01) { // Unknown RFY remote
if (self.acknowledge[seqnbr] !== undefined && typeof self.acknowledge[seqnbr] === "function") {
self.acknowledge[seqnbr]();
self.acknowledge[seqnbr] = null;
}
self.debugLog("Response: Command message " + RfxCom.dumpHex([seqnbr]) + ", unknown RFY remote ID");
self.emit("response", "Unknown RFY remote ID", seqnbr, rfxcom.responseCode.UNKNOWN_REMOTE_ID);
} else if (subtype === 0x00) { // Mode command response
if (self.acknowledge[seqnbr] !== undefined && typeof self.acknowledge[seqnbr] === "function") {
self.acknowledge[seqnbr]();
self.acknowledge[seqnbr] = null;
}
// Firmware version decoding supplied by Bert Weijenberg
if (data.length > 12) {
self.startReceiverRequired = true; // New firmware versions require the command
msg = data.slice(2, 19);
firmwareType = msg[10];
// 'Next-generation' non-FTDI chip devices are now using 2000 series firmware version numbers
if (firmwareType === 0x14 || firmwareType === 0x15 || firmwareType === 0x18) {
firmwareVersion = msg[2] + 2000;
} else {
firmwareVersion = msg[2] + 1000;
}
transmitterPower = msg[9] - 18;
} else {
self.startReceiverRequired = false; // Old firmware versions dont support the command
msg = data.slice(2, 12);
firmwareVersion = msg[2];
if (msg[1] === 0x52 && firmwareVersion < 162) {
firmwareType = 0;
} else if (msg[1] === 0x53 && firmwareVersion < 162) {
firmwareType = 1;
if (firmwareVersion >= 89) {
transmitterPower = msg[9] - 18;
}
} else if (msg[1] === 0x53 && firmwareVersion >= 162 && firmwareVersion < 225) {
firmwareType = 2;
if (firmwareVersion >= 189) {
transmitterPower = msg[9] - 18;
}
} else {
firmwareType = 3;
if (firmwareVersion >= 243) {
transmitterPower = msg[9] - 18;
}
}
}
self.firmwareVersion = firmwareVersion;
self.receiverTypeCode = msg[1];
if (transmitterPower > 13.0) {
transmitterPower = 10.0;
}
self.transmitterPower = self.receiverTypeCode === 0x52 ? -99 : transmitterPower;
hardwareVersion = msg[7] + "." + msg[8];
// Check which protocols are enabled
protocols = [];
if (typeof rfxcom.protocols[self.receiverTypeCode] == "object") {
for (let key in rfxcom.protocols[self.receiverTypeCode]) {
if (rfxcom.protocols[self.receiverTypeCode].hasOwnProperty(key)) {
const value = rfxcom.protocols[self.receiverTypeCode][key];
// Bytes msg7 & msg8 are displaced in the Interface Response Message
// See SDK section 10.3.1
if (value.msg >= 7) {
value.msg += 8;
}
// noinspection JSBitwiseOperatorUsage
if (msg[value.msg] & value.bit) {
protocols.push(key);
}
}
}
}
// Now we are ready to go
const evt = {
subtype: subtype,
seqnbr: seqnbr,
cmnd: cmnd,
receiverTypeCode: self.receiverTypeCode,
receiverType: receiverTypes[self.receiverTypeCode] || "Unknown device",
hardwareVersion: hardwareVersion,
firmwareVersion: firmwareVersion,
firmwareType: firmwareTypes[firmwareType] || "Unknown firmware",
enabledProtocols: protocols
};
if (firmwareType !== 0) {
evt.transmitterPower = transmitterPower;
}
if (firmwareType >= 5) { // PRO firmware only
// TODO - noise level calibration to give dBm?
evt.noiseLevel = msg[11];
}
self.emit("status", evt);
// Send the start receiver command if required by this firmware version
if (self.startReceiverRequired) {
self.startRFXReceiver(function (err) {
if (err) {
self.close();
self.emit("disconnect", err);
}
});
} else if (self.initialising) {
self.initialising = false;
self.TxQ.start();
self.debugLog("Started command message queue");
if (typeof self.readyCallback === "function") {
self.readyCallback();
}
}
}
};
transmitCommandResponseHandler(data) {
const
seqnbr = data[1],
responses = {
0: "ACK - transmit OK",
1: "ACK - transmit delayed",
2: "NAK - transmitter did not lock onto frequency",
3: "NAK - AC address not allowed"
},
message = data[2];
if (this.acknowledge[seqnbr] !== undefined && typeof this.acknowledge[seqnbr] === "function") {
this.acknowledge[seqnbr]();
this.acknowledge[seqnbr] = null;
}
this.debugLog("Response: Command message " + RfxCom.dumpHex([seqnbr]) + ", " + responses[message]);
this.emit("response", responses[message], seqnbr, message);
};
//------------------------------------------
// DATA PACKET HANDLERS
//------------------------------------------
/*
*
* Called by the data event handler when data arrives from a Lighting1
* light control device (packet type 0x10).
*
*/
lighting1Handler(data, packetType) {
const
subtype = data[0],
evt = {
id: "0x" + RfxCom.dumpHex(data.slice(2, 4), false).join(""), // Redundant?
subtype: subtype,
seqnbr: data[1],
houseCode: String.fromCharCode(data[2]).toUpperCase(),
unitCode: data[3],
commandNumber: data[4],
command: rfxcom.commandName(packetType, subtype, data[4]),
rssi: (data[5] >> 4) & 0xf
};
this.emit("lighting1", evt, packetType);
};
/*
*
* Called by the data event handler when data arrives from a HomeEasy
* light control device (packet type 0x11).
*
*/
lighting2Handler(data, packetType) {
let idBytes = data.slice(2, 6);
idBytes[0] &= ~0xfc; // "id1 : 2"
const
subtype = data[0],
evt = {
seqnbr: data[1],
subtype: subtype,
id: "0x" + RfxCom.dumpHex(idBytes, false).join(""),
unitCode: data[6],
commandNumber: data[7],
command: rfxcom.commandName(packetType, subtype, data[7]),
level: data[8],
rssi: (data[9] >> 4) & 0xf
};
this.emit("lighting2", evt, packetType);
};
/*
*
* Called by the data event handler when data arrives from a device using the PT2262 chip (paket type 0x13)
* This always has a commandNumber of 0, corresponding to the sole supported command 'Data'
* The actual data encoded by the chip is returned as a hex string in 'data'
*
*/
lighting4Handler(data, packetType) {
const
evt = {
subtype: data[0],
seqnbr: data[1],
data: "0x" + RfxCom.dumpHex(data.slice(2, 5), false).join(""),
commandNumber: 0,
command: "Data",
pulseWidth: (256*data[5] + data[6]),
rssi: (data[7] >> 4) & 0xf
};
this.emit("lighting4", evt, packetType);
};
/*
*
* Called by the data event handler when data arrives from a LightwaveRF/Siemens
* light control device (packet type 0x14).
*
*/
lighting5Handler(data, packetType) {
const
subtype = data[0],
evt = {
subtype: subtype,
id: "0x" + RfxCom.dumpHex(data.slice(2, 5), false).join(""),
unitCode: data[5],
commandNumber: data[6],
command: rfxcom.commandName(packetType, subtype, data[6]),
seqnbr: data[1],
level: data[7],
rssi: (data[8] >> 4) & 0xf
};
this.emit("lighting5", evt, packetType);
};
/*
*
* Called by the data event handler when data arrives from a Blyss
* light control device (packet type 0x15)
*
*/
lighting6Handler(data, packetType) {
const
subtype = data[0],
evt = {
subtype: subtype,
seqnbr: data[1],
id: "0x" + RfxCom.dumpHex(data.slice(2, 4), false).join(""),
groupCode: String.fromCharCode(data[4]).toUpperCase(),
unitCode: data[5],
commandNumber: data[6],
command: rfxcom.commandName(packetType, subtype, data[6]),
rssi: (data[9] >> 4) & 0xf
};
this.emit("lighting6", evt, packetType);
};
/*
*
* Called by the data event handler when data arrives from various doorbell pushbuttons
* (packet type 0x16)
*
*/
chimeHandler(data, packetType) {
// Chime packets changed length in version 1045, to add the id4 byte
const
subtype = data[0],
evt = {
subtype: subtype,
seqnbr: data[1],
rssi: (data[data.length - 1] >> 4) & 0xf
};
if (evt.subtype === 0) {
evt.id = "0x" + RfxCom.dumpHex(data.slice(3, 4), false).join("");
evt.commandNumber = data[4];
evt.command = rfxcom.commandName(packetType, subtype, data[4]);
} else if (evt.subtype === 1) {
// noinspection JSBitwiseOperatorUsage
evt.id = (data[2] & 0x40 ? "0" : "1") + (data[2] & 0x10 ? "0" : "1") +
(data[2] & 0x04 ? "0" : "1") + (data[2] & 0x01 ? "0" : "1") +
(data[3] & 0x40 ? "0" : "1") + (data[3] & 0x10 ? "0" : "1");
} else if (evt.subtype === 3) {
evt.id = "0x" + RfxCom.dumpHex([(data[4] & 0x80) >> 7, data[2], data[3]], false).join("");
evt.commandNumber = data[4] & 0x7f;
evt.command = "";
} else if (data.length > 6 && (evt.subtype === 6 || evt.subtype === 7)) {
evt.id = "0x" + RfxCom.dumpHex(data.slice(2, 6), false).join("");
} else {
evt.id = "0x" + RfxCom.dumpHex(data.slice(2, 5), false).join("");
}
this.emit("chime1", evt, packetType);
};
/*
*
* Called by the data event handler when data arrives from fan remote controls
* (packet type 0x17)
*
*/
fanHandler(data, packetType) {
const
subtype = data[0],
evt = {
subtype: subtype,
seqnbr: data[1],
rssi: (data[6] >> 4) & 0xf,
commandNumber: data[5]
};
switch (subtype){
case 1:
case 10:
evt.id = "0x" + RfxCom.dumpHex(data.slice(2, 5), false).join("");
break;
case 0:
case 7:
evt.id = "0x" + RfxCom.dumpHex(data.slice(3, 5), false).join("");
break;
case 2:
case 4:
case 5:
case 6:
case 8:
case 9:
case 11:
evt.id = "0x" + RfxCom.dumpHex(data.slice(4, 5), false).join("");
break;
case 3:
evt.id = ((data[2] & 0x80) >> 7).toString(2) + "/" +
RfxCom.zeroPad(((data[2] & 0x60) >> 5), 2, 2)+ "/" +
RfxCom.zeroPad((data[3]*8 + ((data[4] & 0xe0) >> 5)), 10, 2) + "/0x" +
(data[4] && 0x1f).toString(16);
break;
case 12:
evt.id = "0x" + RfxCom.dumpHex(data.slice(2, 5), false).join("");
if (data.length === 16) {
} else if (data.length === 41) {
switch (evt.commandNumber) {
case 0x0b:
evt.state = -1;
break;
case 0x0c:
break;
case 0x0d:
evt.co2 = data[7]*256 + data[8];
break;
case 0x0e:
break;
case 0x0f:
break;
case 0x10:
break;
case 0x12:
break;
}
}
break;
case 13:
evt.id = "0x" + RfxCom.dumpHex(data.slice(2, 5), false).join("");
break;
}
evt.command = rfxcom.commandName(packetType, subtype, data[5]);