-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathplugwise.js
executable file
·649 lines (501 loc) · 22.5 KB
/
plugwise.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
/*********************************************************************************
*
* Plugwise API for nodejs
*
* Exposes the basic commands to control and read plugwise circles through nodejs
*
* Written by Camilo Tapia, http://www.onezerozeroone.com/
*
*********************************************************************************/
var serialport = require('serialport');
var crc = require('crc');
var SerialPort = serialport.SerialPort; // localize object constructor
var colors = require('./colors').colors;
var protocolCommands = require('./plugwise-commands').protocolCommands;
var moment = require('moment');
var commandResponses = {};
for(var key in protocolCommands) {
var protocolCommandInfo = protocolCommands[key];
commandResponses[protocolCommandInfo.response] = {
infoSplit: protocolCommandInfo.infoSplit,
name: protocolCommandInfo.name,
color: protocolCommandInfo.color
};
}
function parseResponse(responseCodeParts, data) {
var infoData = {};
var cursor = 4;
for(var key in responseCodeParts) {
infoData[key] = {value: data.substr(cursor, responseCodeParts[key].length), name: responseCodeParts[key].name};
cursor += responseCodeParts[key].length;
}
var parsed = {};
parsed.mac = infoData.mac.value;
parsed.relay = infoData.relayStatus.value == "01";
parsed.hertz = infoData.hertz.value == "85" ? 50 : 60;
infoData.parsed = parsed;
return infoData;
}
// the actual class
function plugwise(options) {
var commandStack = [];
var commandQueue = [];
var responsesCounter = 0;
var opened = false;
var initiated = false;
// connect to the serial port of the 'stick'
var sp = new SerialPort(options.serialport, {
baudrate: 115200,
parser: serialport.parsers.readline('\n')
});
sp.on('open', function() {
opened = true;
init();
});
// read incoming data
sp.on("data", readData);
var ackumulation = [];
var commandCallbackReference = {};
var ackCounter = 0;
function readData(data) {
var result = data;
if (options.log > 2) {
console.log("RAW DATA:", data);
}
// strip strange character in the begining of the string
while(data.charCodeAt(0) < 48 || data.charCodeAt(0) > 89) {
data = data.substring(1);
}
// parse the data and split into meaningful pairs, if we mapped them
var responseCode = data.substr(0, 4);
var commandInfo = commandResponses[responseCode];
if (commandInfo && commandInfo.infoSplit) {
var splitedData = [];
var index = 0;
for(var i = 0, ii = commandInfo.infoSplit.length; i < ii; i++) {
splitedData.push(data.substr(index, commandInfo.infoSplit[i]));
index += commandInfo.infoSplit[i];
}
if (splitedData[0] === protocolCommands.ack.response && options.log > 1) {
console.log(commandInfo.color + "READ ", commandInfo.name + ':\t' + splitedData.join('\t') + colors.reset);
}
else if (splitedData[0] !== protocolCommands.ack.response && options.log > 0) {
console.log(commandInfo.color + "READ ", commandInfo.name + ':\t' + splitedData.join('\t') + colors.reset);
}
var isAck = false;
// here we check for the imidate reponse and the response count
if (splitedData[0] == protocolCommands.ack.response) {
isAck = true;
ackCounter += 1;
if (ackCounter > 0) ackCounter = 0;
if (splitedData[2] == '00C1') {
ackumulation.push(splitedData[1]);
var ref = commandStack[ackumulation.length - 1];
ref.ack = splitedData[1];
commandCallbackReference[ref.ack] = ref;
//console.log(colors.white , "0", data, colors.reset);
}
else if (splitedData[2] == '00C2') {
var last;
for(var ack in commandCallbackReference) {
last = commandCallbackReference[ack];
}
if (last && last.command.request !== '000A') {
var mac = last.mac;
if (last.callback) {
last.callback.call(plugwiseObject(mac), {error: true});
}
}
}
else if (splitedData[2] =='00E1') {
// what is this?
if (options.log > 0) {
console.log(colors.red + "Error?" + colors.reset);
}
var ack = splitedData[1];
var responseInfo = commandCallbackReference[ack];
if (responseInfo) {
delete commandCallbackReference[ack];
var mac = responseInfo.mac;
//console.log("ack:", responseInfo);
if (responseInfo.callback) {
var parsedData = {};
var result = {error: true};
var pw = plugwiseObject(mac);
responseInfo.callback.call(pw, result);
}
}
if (responsesCounter == 1) {
sendQueue();
}
}
// this happens when the response is a result of a command that doesnt expect
// data in return
else {
var ack = splitedData[1];
var responseInfo = commandCallbackReference[ack];
if (responseInfo) {
delete commandCallbackReference[ack];
var mac = responseInfo.mac;
//console.log("ack:", responseInfo);
if (responseInfo.callback) {
var parsedData = {};
var result = null;
var pw = plugwiseObject(mac);
//if (responseInfo.command.parseInfo) {
//parsedData = parseResponse(responseInfo.command.parseInfo, data);
//result = parsedData.parsed;
//}
//console.log("data:", data);
if (responseInfo.command.parseFunction) {
result = responseInfo.command.parseFunction(pw, splitedData);
}
responseInfo.callback.call(pw, result);
//commandCallbackReference[ack].callback(parsedData.parsed);
}
}
else {
//console.log(colors.white ,"1", data, colors.reset);
//console.log("No callback for ack:", ack, data);
}
if (responsesCounter == 1) {
sendQueue();
}
}
//console.log(commandStack);
}
else {
var ack = splitedData[1];
var mac = splitedData[2];
var responseInfo = commandCallbackReference[ack];
if (responseInfo && responseInfo.callback) {
var parsedData = {};
var result = null;
var pw = plugwiseObject(mac);
//if (responseInfo.command.parseInfo) {
//parsedData = parseResponse(responseInfo.command.parseInfo, data);
//result = parsedData.parsed;
//}
if (responseInfo.command.parseFunction) {
result = responseInfo.command.parseFunction(pw, splitedData);
}
responseInfo.callback.call(pw, result);
}
else {
//console.log(colors.white ,"2", data, colors.reset);
}
if (responsesCounter == 1) {
sendQueue();
}
}
}
else {
//console.log(colors.white ,"3", data, colors.reset);
}
if (responsesCounter == 1) {
//sendQueue();
}
else {
responsesCounter++;
}
}
// builds the command string and sends it
function sendCommand(command, mac, params, callback, scope) {
var commandParts = [];
// check for callback instead of params
if (typeof params == 'function') {
callback = params;
params = '';
scope = callback;
}
var completeCommand = '';
completeCommand += command.request;
commandParts.push(command.request);
if (mac) {
commandParts.push(mac);
completeCommand += mac;
}
if (params) {
commandParts.push(params);
completeCommand += params;
}
var crcChecksum = crc.crc16(completeCommand).toString(16).toUpperCase();
if (crcChecksum.length < 2) {
crcChecksum = "000" + crcChecksum;
}
else if (crcChecksum.length < 3) {
crcChecksum = "00" + crcChecksum;
}
else if (crcChecksum.length < 4) {
crcChecksum = "0" + crcChecksum;
}
commandParts.push(crcChecksum);
completeCommand = protocolCommands.frames.start + commandParts.join("") + protocolCommands.frames.end;
commandStack.push({mac: mac,command: command, ack:'', callback: callback, scope: scope});
if (options.log > 0) {
console.log('---');
console.log(command.color + "SEND " , command.name + ":\t" + commandParts.join("\t") + colors.reset);
}
sp.write(completeCommand);
// we use a counter to know how many ack we are up in compared to commands
ackCounter -= 1;
return completeCommand;
}
function addCallback(command, callback) {
commandStack[command.response] = callback;
}
// init
function init(){
if (opened && !initiated) {
initiated = true;
sendCommand(protocolCommands.init);
}
}
function sendQueue() {
//console.log("ackCounter = ", ackCounter);
if (opened && responsesCounter == 1 && ackCounter >= 0) {
var command = commandQueue.shift();
if (command && command.f) {
//(function(command) {
//setTimeout(function() {
command.f.call(command.scope);
//}, 500);
//})(command);
}
}
}
var listOfAppliances = {};
// the actual object
var plugwiseObject = function(mac) {
if (listOfAppliances[mac]) {
return listOfAppliances[mac];
}
var internal = new (function(mac){
var self = this;
// reserved for internal data
self.data = {};
self.data.relay = null; // holds the status of the relay
self.mac = mac;
//console.log("MAC:", mac);
// All commands return this to be able to chain.
// All callbacks are scoped with 'this' as the plugwise instance
self.poweron = function(callback) {
(function(mac, callback, pw){
commandQueue.push({f:function() {
sendCommand(protocolCommands.switch, mac, '01', callback, pw);
}, scope: pw});
})(mac, callback, self);
sendQueue();
return self;
}
self.poweroff = function(callback) {
(function(mac, callback, pw){
commandQueue.push({f: function() {
sendCommand(protocolCommands.switch, mac, '00', callback, pw);
}, scope: pw});
})(mac, callback, self);
sendQueue();
return self;
}
self.setclock = function(date, callback) {
(function(mac, date, callback, pw){
var year = addZeros((date.getYear() + 1900 - 2000).toString(16), 2);
var month = addZeros((date.getMonth() + 1).toString(16), 2);
var fullMinutes = addZeros((date.getDate() * 24 * 60 + date.getHours() * 60 + date.getMinutes()).toString(16), 4);
var hours = addZeros((date.getHours()).toString(16), 2);
var minutes = addZeros((date.getMinutes()).toString(16), 2);
var seconds = addZeros((date.getSeconds()).toString(16), 2);
var day = addZeros((date.getDay()).toString(16), 2);
var tempLog = "FFFFFFFF";
var dateHex = year + month + fullMinutes + tempLog + hours + minutes + seconds + day;
dateHex = dateHex.toUpperCase();
//console.log(dateHex, parseInt(fullMinutes, 16));
//console.log(year, month,fullMinutes, hours, minutes, seconds, day);
commandQueue.push({f: function() {
sendCommand(protocolCommands.setclock, mac, dateHex, callback, pw);
}, scope: pw});
})(mac, date, callback, self);
sendQueue();
return self;
}
self.info = function(callback) {
(function(mac, callback, pw){
commandQueue.push({f: function() {
sendCommand(protocolCommands.info, mac, callback, pw);
}, scope: pw});
})(mac, callback, self);
sendQueue();
return self;
}
self.powerinfo = function(callback) {
// if we want to read the power from an appliance, we have to know if its on or off
//if (true || self.data.relay) {
(function(mac, callback, pw){
// if we havent asked for calibarion data, lets do it now
if (!pw.data.calibration) {
pw.calibration(function(){})
};
commandQueue.push({f: function() {
sendCommand(protocolCommands.powerinfo, mac, callback, pw);
}, scope: pw});
})(mac, callback, self);
sendQueue();
/*}
else {
// check if we dont know if the relay is on or off
if (self.data.relay !== false) {
//console.log("check relay");
self.info(function(result) {
//console.log("relay info recieved", result);
self.powerinfo(callback);
});
}
else {
callback.call(self, {error: true, message: 'relay off'});
}
}
*/
return self;
}
self._powerInfoBufferBase = function(logAddress, callback) {
/*
if (typeof offset == "function") {
callback = offset;
offset = 0;
}
*/
(function(mac, callback, logAddress, pw){
commandQueue.push({f: function() {
sendCommand(protocolCommands.powerbufferinfo, mac, logAddress, callback, pw);
}, scope: pw});
})(mac, callback, logAddress, self);
sendQueue();
return self;
};
self.powerbufferinfo = self.powerBufferInfo = function(when, callback) {
self.powerinfo(function(deviceInfo) {
var startDate = new Date(1974, 0, 1);
var endDate = new Date();
var amount = 4;
if (typeof when == "function") {
callback = when;
delete when;
// The default value is today
var now = new Date();
var nowDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
when = nowDay;
}
if (typeof when == "number") {
// This is when we just get how many hours back in time we want
amount = when;
} else if (when.constructor == Array && when.length == 2 && when[0].constructor == Date && when[1].constructor == Date && when[0].getTime() <= when[1].getTime()) {
// This is when we get an interval of dates as an array
// it should be an array of two date when the first is older than the second
startDate = when[0];
var now = new Date();
var nowDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var delta = nowDay.getTime() - when[0].getTime();
var hours = Math.ceil(delta / (1000 * 60 * 60)) + 24;
endDate = new Date(when[1].getTime() + 1000 * 60 * 60 * 24 - 1);
//console.log("%s - %s - %s - %sh", nowDay, startDate, endDate, hours);
amount = hours;
} else if (when.constructor == Date) {
// This is when we a single date
// Get a start date and end date and calculate how much back in time we need to go to get those dates
startDate = when;
var now = new Date();
var nowDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var delta = nowDay.getTime() - when.getTime();
var hours = Math.ceil(delta / (1000 * 60 * 60)) + 24;
endDate = new Date(startDate.getTime() + 1000 * 60 * 60 * 24 - 1);
//console.log("%s - %s - %s - %sh", nowDay, startDate, endDate, hours);
amount = hours;
}
var logAddress = parseInt(self.data.logAddressHex, 16) - 8 * amount;
var buffer = [];
var counter = 0;
function getNext(logAddress) {
var logAddressHex = logAddress.toString(16).toUpperCase();
logAddressHex = addZeros(logAddressHex, 8);
//console.log("%s. %s", counter, logAddressHex);
self._powerInfoBufferBase(logAddressHex, function(powerInfo) {
//console.log(powerInfo);
for(var i = 0, ii = powerInfo.length; i < ii; i++){
if (powerInfo[i].date.getTime() >= startDate.getTime() && powerInfo[i].date.getTime() <= endDate.getTime()) {
buffer.push(powerInfo[i]);
}
}
var lastEntry = powerInfo[powerInfo.length - 1];
if (lastEntry && lastEntry.date.getTime() <= endDate.getTime()){
getNext(logAddress + 8 * 4);
} else {
callback(buffer);
}
});
}
getNext(logAddress);
/*
self._powerInfoBufferBase(logAddressHex, function(powerInfo) {
//console.log(powerInfo);
var firstDate = powerInfo.length > 0 ? powerInfo[0].date : new Date();
var dateToCheck = new Date();
console.log(firstDate);
console.log(dateToCheck);
var hoursDelta = Math.floor(( dateToCheck.getTime() - firstDate.getTime() ) / (1000 * 60 * 60));
console.log(hoursDelta);
//var offset = Math.ceil(hoursDelta / 4) - 7;
var logAddress = (parseInt(self.data.logAddressHex, 16) + 278528 ) * 32 + 8 * hoursDelta;
var logAddressHex = logAddress.toString(16).toUpperCase();
logAddressHex = addZeros(logAddressHex, 8);
console.log(logAddressHex);
self._powerInfoBufferBase(logAddressHex, function(info) {
callback(info);
process.exit();
});
});
*/
});
return self;
};
self.calibration = function(callback) {
(function(mac, callback, pw){
commandQueue.push({f: function() {
sendCommand(protocolCommands.calibration, mac, callback, pw);
}, scope: pw});
})(mac, callback, self);
sendQueue();
return self;
}
this.init = init;
//this.calibration(function(){});
})(mac);
listOfAppliances[mac] = internal;
//console.log(mac);
//internal.calibration(function(){});
// return to be able to chain
return internal;
};
return plugwiseObject;
}
function addZeros(value, length) {
for(var i = value.length + 1, ii = length; i <= ii; i++){
value = "0" + value;
}
return value;
}
var hasBeenInitiated = false;
var listOfDevices = {};
exports.init = function(options, callback) {
if (listOfDevices[options.serialport]) {
return listOfDevices[options.serialport];
}
else {
var instance = plugwise(options);
instance().init();
if (typeof callback == 'function') {
callback.call(instance);
}
listOfDevices[options.serialport] = instance;
return instance;
}
}