-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
2175 lines (1874 loc) · 54.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
'use strict';
require('../assign'); // Object.assign polyfill
var net = require('net');
var util = require('util');
var events = require('events');
var Q = require('q');
var SerialPort;
/* istanbul ignore next */
try {
SerialPort = require('serialport');
} catch (e) {
SerialPort = 0;
}
var https = require('https');
var querystring = require('querystring');
var EventSource = require('eventsource');
var debug = require('debug')('home-controller:insteon');
var utils = require('./utils');
var toByte = utils.toByte;
var DEV_CAT_NAMES = utils.DEV_CAT_NAMES;
var DEDUP_TIMER = 5000; // 5 seconds
// responses
var MESSAGE_PROCESSED = 1; // signals the caller that a message was consumed.
var INSUFFICIENT_DATA = 2; // signals the caller that insufficient data is there to proceed.
var MESSAGE_SKIPPED = 3; // signals the caller that we skipped a message. Temporary.
var Light = require('./Light');
var Thermostat = require('./Thermostat');
var Motion = require('./Motion');
var Door = require('./Door');
var Leak = require('./Leak');
var Meter = require('./Meter');
var IO = require('./IO'); // EZIO
var IOLinc = require('./IOLinc');
var GarageDoor = require('./GarageDoor');
var X10 = require('./X10');
var Insteon = function () {
this.queue = [];
this.buffer = '';
this.commandTimeout = 5000; // default 5 second timeout
this.nakTimeout = 10;
this.commandRetries = 1;
this.defaultTempUnits = Insteon.defaultTempUnits;
this.devices = {};
this.emitDuplicates = false;
this.emitSelfAck = false;
// Clone the dispatchers to allow clients to override/customize if desired
this.dispatchers = Object.assign({}, DISPATCHERS);
// allow it to be overridden in tests
this.SerialPort = SerialPort;
};
util.inherits(Insteon, events.EventEmitter);
Insteon.prototype.connect = function (host, port, connectListener) {
var that = this;
if (typeof port !== 'number') {
connectListener = port;
port = 9761;
}
this.host = host;
this.port = port || 9761;
debug('connecting', this.port, this.host);
var socket = this.socket = new net.Socket();
socket.setEncoding('hex');
socket.setKeepAlive(true, 30000);
socket.on('connect', function () {
debug('connected');
that.emit('connect');
});
socket.on('data', function (data) {
debug('Rcvd:', data);
that.buffer = that.buffer + data;
that.checkStatus();
});
socket.on('error', function (err) {
that.emit('error', err);
});
socket.on('close', function (had_error) {
that.emit('close', had_error);
});
this.write = function (raw) {
return this.socket.write(raw, 'hex');
};
this.close = this.socket.destroy.bind(this.socket);
return new Promise((resolve) => {
that.socket.connect(that.port, that.host, function () {
resolve();
});
}).then(connectListener);
};
Insteon.prototype.serial = function (comName, options, connectListener) {
/* istanbul ignore next */
if (!this.SerialPort) {
throw (new Error('serial is Unsupported on this platform'));
}
var that = this;
if (typeof options === 'function') {
connectListener = options;
options = null;
}
if (!options) {
options = {};
}
if (typeof options.baudRate === 'undefined') {
options.baudRate = 19200;
}
if (typeof options.dataBits === 'undefined') {
options.dataBits = 8;
}
if (typeof options.parity === 'undefined') {
options.parity = 'none';
}
if (typeof options.stopBits === 'undefined') {
options.stopBits = 1;
}
options.autoOpen = false;
this.comName = comName;
this.options = options;
debug('connecting', this.comName);
this.socket = new this.SerialPort(comName, this.options)
.on('open', function () {
debug('connected');
that.emit('connect');
if (!!connectListener) {
connectListener(that.comName);
}
})
.on('data', function (data) {
data = data.toString('hex');
debug('Rcvd:', data);
that.buffer = that.buffer + data;
that.checkStatus();
})
.on('error', function (err) {
that.emit('error', err);
})
.on('close', function (had_error) {
that.emit('close', had_error);
});
this.write = function (raw) {
return that.socket.write(Buffer.from(raw, 'hex'));
};
this.close = this.socket.close.bind(this.socket);
this.socket.open();
};
Insteon.prototype.spark = function (sparkId, token, reconnectInterval) {
var that = this;
var eventUrl = 'https://api.spark.io/v1/devices/' +
sparkId +
'/events/insteon?access_token=' +
token;
debug('Spark event url', eventUrl);
var es = new EventSource(eventUrl);
es.reconnectInterval = reconnectInterval || 5000;
es.addEventListener('insteon', function (event) {
debug('Spark Rcvd:', Date.now(), event);
try {
var eventData = JSON.parse(event.data);
that.buffer = that.buffer + eventData.data;
that.checkStatus();
} catch (err) {
debug('Spark Rcvd error - ignoring', err);
}
});
es.onerror = function (err) {
debug('Spark Error', err, es.readyState);
setTimeout(function () {
if (es.readyState === EventSource.CLOSED) {
that.emit('error', err);
that.close(true);
}
}, 100);
};
es.onopen = function () {
debug('Spark connected');
that.emit('connect');
};
this.write = function (raw) {
var postData = querystring.stringify({
'args': raw,
'access_token': token
});
var options = {
hostname: 'api.spark.io',
port: 443,
path: '/v1/devices/' + sparkId + '/insteon',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, function (res) {
debug('Spark resp', raw, res);
res.setEncoding('utf8');
res.on('data', function (data) {
debug('Spark wrote', raw, data);
});
});
req.on('error', function (err) {
debug('Spark write error:', err);
that.emit('error', err);
});
// write data to request body
req.write(postData);
req.end();
};
this.close = function (had_error) {
try {
es.close();
} catch (err) {
debug('Error closing spark', err);
} finally {
es = null;
that.write = null;
}
that.emit('close', had_error);
};
};
Insteon.prototype.httpClient = function (options, connectListener) {
require('./httpClient')(this, options, connectListener);
};
/**************************************************************************
* Command Functions
**************************************************************************/
Insteon.prototype.sendCommand = function (cmd, timeout, next) {
if (typeof timeout === 'function') {
next = timeout;
timeout = null;
}
if (typeof cmd === 'string') {
cmd = {
raw: '02' + cmd,
type: cmd
};
}
timeout = timeout || this.commandTimeout;
var deferred = Q.defer();
var status = {
command: cmd,
deferred: deferred,
timeout: timeout,
nakTimeout: this.nakTimeout
};
sendCommand(this, status);
return deferred.promise.nodeify(next);
};
function sendCommand(gw, status) {
if (!status) {
return;
}
if (gw.status) {
debug('Already running a command - queuing command: %j', status.command);
return gw.queue.push(status);
}
var timeout = status.timeout;
gw.status = status;
debug('Send: %j', status);
setTimeout(function () { // slowing down writes reduces errors
try {
gw.emit('sendCommand', status.command);
if (gw.write) {
gw.write(status.command.raw);
}
} catch (err) {
debug('Error writing to socket', err);
status.deferred.reject(err);
delete gw.timeout;
delete gw.status;
return sendCommand(gw, gw.queue.shift());
}
gw.timeout = setTimeout(function () {
sendCommandTimout(gw, timeout, gw.commandRetries);
}, timeout);
}, 10);
}
function sendCommandTimout(gw, timeout, retries) {
var status = gw.status;
debug('sendCommandTimout - status: %j', status);
if (!status || !status.command) {
debug('missing status');
return sendCommand(gw, gw.queue.shift());
}
var resp = status.command.response;
if (retries-- <= 0 || (resp && resp.standard && status.command.waitForExtended)) { // don't retry if we got a standard response
delete gw.timeout;
delete gw.status;
status.deferred.resolve(status);
sendCommand(gw, gw.queue.shift());
} else {
debug('Resend: %j', status);
try {
gw.emit('sendCommand', status.command);
if (gw.write) {
gw.write(status.command.raw);
}
} catch (err) {
debug('Error writing to socket', err);
status.deferred.reject(err);
delete gw.timeout;
delete gw.status;
return sendCommand(gw, gw.queue.shift());
}
gw.timeout = setTimeout(function () {
sendCommandTimout(gw, timeout, retries);
}, timeout);
}
}
Insteon.prototype.cancelInprogress = function () {
if (this.status) {
this.status.deferred.reject(new Error('Cancelled!'));
if (this.timeout) {
clearTimeout(this.timeout);
}
delete this.timeout;
delete this.status;
return sendCommand(this, this.queue.shift());
}
return false;
};
Insteon.prototype.cancelPending = function (cmdMatch) {
if (cmdMatch === null || cmdMatch === undefined) {
cmdMatch = /.*/;
}
if (typeof cmdMatch === 'string') {
var id = cmdMatch.trim().replace(/\./g, '');
if (!/^[0-9a-fA-F]{6}$/.test(id)) {
throw new Error('Invalid Insteon ID');
}
cmdMatch = new RegExp('^....' + id + '.*');
}
if (!(cmdMatch instanceof RegExp)) {
throw new Error('Invalid cmdMatch');
}
cmdMatch = new RegExp(cmdMatch.source, 'i');
debug('canceling - match: %s', cmdMatch);
this.queue = this.queue.filter(function (status) {
if (cmdMatch.test(status.command.raw)) {
debug('canceling - cmd: %s', status.command.raw);
status.deferred.reject(new Error('Canceled'));
return false;
}
return true;
});
};
Insteon.prototype.directCommand = function (id, cmd, param, timeout, next) {
if (typeof param === 'function') {
next = param;
param = '00';
} else if (typeof timeout === 'function') {
next = timeout;
timeout = null;
}
if (typeof param === 'number') {
timeout = param;
param = '00';
}
if (!param) {
param = '00';
}
if (typeof cmd === 'string') {
cmd = {
cmd1: cmd,
cmd2: param
};
}
id = id || '';
id = id.trim().replace(/\./g, '');
if (!/^[0-9a-fA-F]{6}$/.test(id)) {
var msg = 'Invalid Insteon ID - ' + id;
debug(msg);
return Q.reject(new Error(msg)).nodeify(next);
}
var type = cmd.type = '62';
var userData = '';
var flags = '0F'; // standard command
if (cmd.extended) {
flags = '1F';
var pad = '0000000000000000000000000000';
userData = (cmd.userData ? cmd.userData.join('') : '');
userData = userData.substring(0, pad.length);
userData = userData + pad.substring(0, pad.length - userData.length);
// create checksum for i2cs devices
var fullCmd = cmd.cmd1 + cmd.cmd2 + userData;
if (cmd.crc) {
userData = userData.substring(0, pad.length - 4) + genCrc(fullCmd);
} else {
var checksum = 0;
fullCmd.match(/.{1,2}/g).forEach(function (b) {
checksum += parseInt(b, 16);
});
checksum = ((~checksum) + 1) & 255;
cmd.checksum = checksum;
userData = userData.substring(0, pad.length - 2) + toByte(checksum);
}
}
cmd.raw = '02' + type + id + flags + cmd.cmd1 + cmd.cmd2 + userData;
cmd.id = id;
return this.sendCommand(cmd, timeout, next);
};
function genCrc(cmd) {
var crc = 0;
cmd.substring(0, 28).match(/.{1,2}/g).forEach(function (byte) {
byte = parseInt(byte, 16);
for (var bit = 0; bit < 8; bit++) {
var fb = byte & 1;
fb = (crc & 0x8000) ? fb ^ 1 : fb;
fb = (crc & 0x4000) ? fb ^ 1 : fb;
fb = (crc & 0x1000) ? fb ^ 1 : fb;
fb = (crc & 0x0008) ? fb ^ 1 : fb;
crc = (crc << 1) & 0xFFFF | fb;
byte = byte >> 1;
}
});
return toByte(crc, 2);
}
Insteon.prototype.handleCommand = function (device, cmd) {
if (!cmd || !cmd.standard) {
debug('Ignoring invalid command or not from this device (%s) : ', device.id, cmd);
return;
}
var directCmd;
if (cmd.standard.messageType === 0) {
directCmd = {
command1: cmd.standard.command1,
command2: parseInt(cmd.standard.command2, 16)
};
}
if (directCmd && device.handleDirect) {
var lastDirectCmd = device.lastCmd;
if (
!this.emitDuplicates &&
!!lastDirectCmd &&
lastDirectCmd.command1 === directCmd.command1 &&
lastDirectCmd.command2 === directCmd.command2 &&
Date.now() - lastDirectCmd.timestamp < DEDUP_TIMER) {
device.lastCmd.timestamp = Date.now();
return;
}
device.lastCmd = directCmd;
device.lastCmd.timestamp = Date.now();
return device.handleDirect(directCmd.command1, directCmd.command2);
}
var broadcastCmd;
// Standard ALL-link Broadcast
if (cmd.standard.messageType === 6 && cmd.standard.command1 !== '06') {
broadcastCmd = {
group: parseInt(cmd.standard.gatewayId, 16),
command1: cmd.standard.command1,
command2: cmd.standard.command2
};
} else if (cmd.standard.messageType === 6) { // I2CS ALL-link Success Broadcast
broadcastCmd = {
group: parseInt(cmd.standard.gatewayId.substr(4), 16),
command1: cmd.standard.gatewayId.substr(0, 2),
command2: cmd.standard.gatewayId.substr(2, 2)
};
} else if (cmd.standard.messageType === 2 || cmd.standard.messageType === 3) { // ALL-link Clean Up and ACK of ALL-Link Cleanup Message
broadcastCmd = {
group: parseInt(cmd.standard.command2, 16),
command1: cmd.standard.command1,
command2: '00'
};
}
if (broadcastCmd && device.handleAllLinkBroadcast) {
var lastCmd = device.lastCmd;
if (
!this.emitDuplicates &&
lastCmd &&
lastCmd.group === broadcastCmd.group &&
lastCmd.command1 === broadcastCmd.command1 &&
Date.now() - lastCmd.timestamp < DEDUP_TIMER) {
device.lastCmd.timestamp = Date.now();
return;
}
device.lastCmd = broadcastCmd;
device.lastCmd.timestamp = Date.now();
return device.handleAllLinkBroadcast(broadcastCmd.group, broadcastCmd.command1, broadcastCmd.command2);
}
// if Ack
if (cmd.standard.messageType === 1) {
var status = this.status;
var isSelfAck = status && status.command && status.command.id &&
status.command.id.toUpperCase() === device.id;
var handleAck = !!device.handleAck && (this.emitSelfAck || !isSelfAck);
// Handle Ack
if (handleAck) {
return device.handleAck(cmd.standard.command1, cmd.standard.command2);
}
return;
}
debug('No event for command message type for device (%s) : ', device.id, cmd);
};
Insteon.prototype.checkStatus = function () {
var that = this;
var result = this._checkStatus();
switch (result) {
case INSUFFICIENT_DATA:
debug('parsing - insufficient data to continue - %d', this.buffer.length);
break;
case MESSAGE_PROCESSED:
case MESSAGE_SKIPPED:
// If a message was consumed or skipped
debug('parsing - message %s', ((result === MESSAGE_PROCESSED) ? 'consumed' : 'skipped'));
if (this.buffer) {
// Run this again, but allow the message loop a chance to wake up.
setTimeout(function () {
that.checkStatus();
}, 0);
}
break;
default:
debug('parsing - unknown result %s', result);
}
};
Insteon.prototype._checkStatus = function () {
var result; // Just trying to be careful and suss out every single path
var raw = this.buffer;
debug('checkStatus - buffer: %s', raw);
var status = this.status;
debug('checkStatus - status: %j', status);
// check for gateway NAK
if (raw.substr(0, 2) === '15' && this.status && this.timeout) {
// Got a PLM NAK; retry our command, if applicable
var gw = this;
var nakTimeout = this.status.nakTimeout;
this.status.nakTimeout *= 2; // Exponential backoff
clearTimeout(this.timeout);
this.timeout = setTimeout(function () {
sendCommandTimout(gw, gw.status.timeout, gw.commandRetries);
}, nakTimeout);
this.buffer = raw.substr(2);
return MESSAGE_PROCESSED;
}
// check for enough data
if (raw.length <= 4) {
return INSUFFICIENT_DATA; // buffering
}
var nextCmdAt = raw.search(/02(5[0-8]|6[0-9a-f]|7[0-3])/i);
if (nextCmdAt > 0) {
this.buffer = raw = raw.substr(nextCmdAt);
}
var type = raw.substr(0, 4);
// Dispatcher-style handling
var dispatcher = this.dispatchers[type.toUpperCase()];
if (dispatcher) {
var rawMsg = dispatcher.checkSize.call(this, raw);
if (rawMsg === false) {
return INSUFFICIENT_DATA;
}
debug('checkStatus - dispatcher - %s', dispatcher.name);
result = dispatcher.handler.call(this, rawMsg, status);
if (result !== MESSAGE_SKIPPED) {
this.trailer();
}
return result;
} else {
if (this.buffer.length > 4) {
this.buffer = this.buffer.substr(4);
} else {
this.buffer = '';
}
return MESSAGE_SKIPPED;
}
};
var DISPATCHERS = {};
// A closure factory to build the checkSize function for most of our handlers
function _defaultCheckSize(size) {
return function (raw) {
if (raw.length < size) {
return false;
}
this.buffer = raw.substr(size);
return raw.substr(0, size);
};
}
function setupDispatcher(dispatcher) {
if (!dispatcher.checkSize) {
if (!dispatcher.size) {
throw new Error('Dispatcher missing checkSize and size');
}
dispatcher.checkSize = _defaultCheckSize(dispatcher.size);
}
DISPATCHERS[dispatcher.id] = dispatcher;
}
// 0251 is a Standard Message that came on the wire and was not a direct response to a command.
setupDispatcher({
id: '0250',
name: 'Standard Command',
size: 22,
handler: function (raw, status) {
var cmd = {
standard: parseMessageReceived(raw)
};
this.emit('recvCommand', cmd);
debug('Parsed command: %j', cmd);
debug('Status: %j', status);
var id = cmd.standard.id.toUpperCase();
debug('Devices: %j', Object.keys(this.devices));
if (this.devices[id]) {
debug('Handle Command for device: %s', id);
this.handleCommand(this.devices[id], cmd);
}
if (!status || !status.command || !status.command.id ||
(status.command.id.toUpperCase() !== id)) { // command isn't a response for a command we sent
this.emit('command', cmd);
return MESSAGE_SKIPPED;
}
if (!status.response) {
status.response = {};
}
var responseCount = status.command.responseCount;
if (responseCount) {
status.response.standard = status.response.standard || [];
status.response.standard.push(cmd.standard);
status.success = status.response.standard.length === responseCount;
} else {
status.response.standard = cmd.standard;
status.success = cmd.standard !== undefined && cmd.standard !== null &&
(!status.command.extended || !!status.command.isStandardResponse) &&
!status.command.waitForExtended && !status.command.waitForLinking;
}
return MESSAGE_PROCESSED;
}
});
// 0251 is an Extended message that came on the wire and was not a direct response to a command.
setupDispatcher({
id: '0251',
name: 'Extended Command',
size: 50,
handler: function (raw, status) {
var cmd = {
extended: parseMessageReceived(raw)
};
// Calculate if CRC is valid (not use by most commands)
var fullCmd = cmd.extended.command1 + cmd.extended.command2;
fullCmd = fullCmd + cmd.extended.userData.slice(0, 12).join('');
var rspCrc = cmd.extended.userData.slice(12).join('').toLowerCase();
var crc = genCrc(fullCmd).toLowerCase();
cmd.extended.crc = rspCrc === crc;
this.emit('recvCommand', cmd);
debug('Parsed command: %j', cmd);
debug('Status: %j', status);
var id = cmd.extended.id.toUpperCase();
if (this.devices[id]) {
this.handleCommand(this.devices[id], cmd);
}
if (!status || !status.command || !status.command.id ||
status.command.id.toUpperCase() !== id) { // command isn't a response for a command we sent
this.emit('command', cmd);
return MESSAGE_PROCESSED;
}
if (!status.response) {
status.response = {};
}
status.response.extended = cmd.extended;
status.success = cmd.extended !== undefined && cmd.extended !== null;
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0253',
name: 'Link Command',
size: 20,
handler: function (raw, status) {
var cmd = {
link: parseLinkingComplete(raw)
};
this.emit('recvCommand', cmd);
if (!status) {
this.emit('command', cmd);
return MESSAGE_PROCESSED;
}
if (!status.response) {
status.response = {};
}
status.response.link = cmd.link;
status.success = cmd.link !== undefined && cmd.link !== null;
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0257',
name: 'Link Record Command',
size: 20,
handler: function (raw, status) {
if (!status) {
return MESSAGE_SKIPPED;
}
status.response = {};
status.response.raw = raw;
status.response.type = raw.substr(2, 2);
status.response.link = parseLinkRecord(raw.substr(4, 16));
this.emit('recvCommand', status.response);
status.success = true;
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0258',
name: 'All-Link Cleanup Status Report',
size: 6,
handler: function (raw, status) {
if (!status) {
return MESSAGE_SKIPPED;
}
status.report = {
completed: raw.substr(4, 2) === '06',
aborted: raw.substr(4, 2) === '15'
};
this.emit('recvCommand', {
type: '58',
raw: raw.substr(0, 6),
report: status.report
});
status.success = true;
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0260',
name: 'Get IM Info Response',
size: 18,
handler: function (raw, status) {
if (!status) {
return MESSAGE_SKIPPED;
}
status.ack = raw.substr(16, 2) === '06';
status.nack = raw.substr(16, 2) === '15';
status.response = parseGetInfo(raw.substr(0, 16));
this.emit('recvCommand', status.response);
status.success = true;
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0261',
name: 'All-Link Command Response',
size: 12,
handler: function (raw, status) {
this.emit('recvCommand', {
type: '61',
raw: raw.substr(0, 12)
});
if (!status) {
return MESSAGE_SKIPPED; // TODO: this.emit('command', parsedCmd);
}
status.ack = raw.substr(10, 2) === '06';
status.nack = raw.substr(10, 2) === '15';
return MESSAGE_PROCESSED;
}
});
// Response to a standard or extended message, usually direct
setupDispatcher({
id: '0262',
name: 'Direct Command Response',
checkSize: function (raw) {
// Under 12 characters, we don't have the flags byte, so we need more.
if (raw.length < 12) {
return false;
}
// The interesting thing about an 0262 is it's a variable length response.
// So unlike the other responses, we need to get to the message flags byte to know
// whether it's a standard (18 hex chars) or extended (46 hex chars) response.
var flags = parseInt(raw.substr(10, 2), 16);
var isExtended = (flags & 0x10) !== 0;
var expectedLength = isExtended ? 46 : 18;
if (raw.length < expectedLength) {
return false;
}
this.buffer = raw.substr(expectedLength);
return raw.substr(0, expectedLength);
},
handler: function (raw, status) {
if (!this.status) {
return MESSAGE_SKIPPED;
}
this.emit('recvCommand', {
type: '62',
raw: raw.substr(0, status.command.raw.length + 2)
});
status.ack = raw.substr(status.command.raw.length, 2) === '06';
status.nack = raw.substr(status.command.raw.length, 2) === '15';
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0263', // X10 response
name: 'X10 Response',
size: 10,
handler: function (raw, status) {
if (!status) {
// If we get here, we got an X10 response without sending a request. Probably nowhere to route it.
return MESSAGE_SKIPPED;
}
debug('checkStatus - X10 Command');
this.emit('recvCommand', {
type: '63',
raw: raw.substr(0, status.command.raw.length + 2)
});
status.ack = raw.substr(status.command.raw.length, 2) === '06';
status.nack = raw.substr(status.command.raw.length, 2) === '15';
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0264',
name: 'All-Link Start Response',
size: 10,
handler: function (raw, status) {
if (!status) {
return MESSAGE_SKIPPED;
}
this.emit('recvCommand', {
type: '64',
raw: raw.substr(0, 10)
});
status.ack = raw.substr(8, 2) === '06';
status.nack = raw.substr(8, 2) === '15';
status.success = !status.command.waitForLinking;
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0265',
name: 'ALL-Link Cancel Response',
size: 6,
handler: function (raw, status) {
if (!status) {
return MESSAGE_SKIPPED;
}
this.emit('recvCommand', {
type: '65',
raw: raw.substr(0, 6)
});
status.ack = raw.substr(4, 2) === '06';
status.nack = raw.substr(4, 2) === '15';
status.success = true;
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '0269',
name: 'Get First ALL-Link Record',
size: 6,
handler: function (raw, status) {
if (!status) {
return MESSAGE_SKIPPED;
}
this.emit('recvCommand', {
type: raw.substr(2, 2),
raw: raw.substr(0, 6)
});
status.ack = raw.substr(4, 2) === '06';
status.nack = raw.substr(4, 2) === '15';
return MESSAGE_PROCESSED;
}
});
setupDispatcher({
id: '026A',
name: 'Get Next ALL-Link Record',
size: 6,