-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
563 lines (484 loc) · 17.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
/*** BaseModule Z-Way HA module *******************************************
Version: 1.11
(c) Maroš Kollár, 2015-2017
-----------------------------------------------------------------------------
Author: Maroš Kollár <[email protected]>
Description:
This module provides many helpful functions for zway automation module
developers.
******************************************************************************/
/*jshint -W058 */
function BaseModule (id, controller) {
// Call superconstructor first (AutomationModule)
BaseModule.super_.call(this, id, controller);
this.langFile = undefined;
}
inherits(BaseModule, AutomationModule);
_module = BaseModule;
// ----------------------------------------------------------------------------
// --- Module instance initialized
// ----------------------------------------------------------------------------
BaseModule.prototype.init = function (config) {
BaseModule.super_.prototype.init.call(this, config);
var self = this;
self.langFile = self.controller.loadModuleLang(self.constructor.name);
self.imagePath = '/ZAutomation/api/v1/load/modulemedia/'+self.constructor.name;
// Only for BaseModule instance
if (self.constructor.name === 'BaseModule') {
self.log('Init callbacks');
self.callbackBase = _.bind(self.handleLevelModification,self);
self.controller.devices.on('change:metrics:level',self.callbackBase);
}
};
BaseModule.prototype.stop = function () {
var self = this;
// Only for BaseModule instance
if (self.constructor.name === 'BaseModule') {
self.controller.devices.off('change:metrics:level',self.callbackBase);
self.callbackBase = undefined;
}
BaseModule.super_.prototype.stop.call(this);
};
// ----------------------------------------------------------------------------
// --- Module methods
// ----------------------------------------------------------------------------
BaseModule.prototype.presenceModes = ['home','night','away','vacation'];
BaseModule.prototype.handleLevelModification = function(vDev) {
var self = this;
var lastLevel = vDev.get('metrics:lastLevel');
var newLevel = vDev.get('metrics:level');
var deviceType = vDev.get('deviceType');
var lastUpdate = vDev.get('updateTime');
var modificationTime = Math.floor(new Date().getTime() / 1000);
// No lastlevel - set it for the first time
if (typeof(lastLevel) === 'undefined') {
vDev.set('metrics:modificationTime',modificationTime,{ silent: true });
vDev.set('metrics:lastLevel',newLevel,{ silent: true });
return;
}
// Not changed
if (lastLevel == newLevel) return;
// Warn on big level changes - TODO maybe deny too big changes
if (deviceType === 'sensorMultilevel') {
var diff = Math.abs(lastLevel-newLevel);
var probeType = vDev.get('metrics:probeType');
// Ignore diff for changes of more than 4 hours
if (modificationTime-lastUpdate > (4*60*60)) {
diff = 0;
}
if (
(probeType == 'luminosity' && (diff > 250 || newLevel > 1000 || newLevel < 0)) ||
(probeType == 'temperature' && (diff > 10 || newLevel > 50 || newLevel < -30)) ||
(probeType == 'humidity' && (diff > 20 || newLevel > 100 || newLevel < 5)) ||
(probeType == 'ultraviolet' && (diff > 4 || newLevel > 15 || newLevel < -1))
) {
self.error('Unlikely '+probeType+' level change from '+lastLevel+' to '+newLevel+' for '+vDev.id);
}
}
// Run delayed, in order not to delay current processing
setTimeout(function() {
// Set modificationTime
self.log('Set lastLevel to '+newLevel+' for '+vDev.id+' (was '+lastLevel+')');
vDev.set('metrics:modificationTime',modificationTime,{ silent: true });
vDev.set('metrics:lastLevel',newLevel,{ silent: true });
},1);
// Bind to modify:metrics:level to get real changes
self.controller.devices.emit('modify:metrics:level',vDev,'metrics:level');
vDev.emit('modify:metrics:level',vDev,'metrics:level');
};
/* Log helper functions */
BaseModule.prototype.log = function(message) {
if (undefined === message) return;
console.log('['+this.constructor.name+'-'+this.id+'] '+message);
};
BaseModule.prototype.error = function(message) {
if (undefined === message) message = 'An unknown error occured';
var error = new Error(message);
console.error('['+this.constructor.name+'_'+this.id+'] '+error.stack);
};
/* Presence helper functions */
BaseModule.prototype.getPresenceBoolean = function() {
var self = this;
var value = self.getDeviceValue([
['probeType','=','presence']
]);
if (typeof(value) === 'string' && value === 'on') {
return true;
} else if (typeof(value) === 'undefined') {
self.error('Could not find presence device');
return true; // Fallback
}
return false;
};
BaseModule.prototype.getPresenceMode = function() {
var self = this;
var value = self.getDeviceValue([
['probeType','=','presence']
],'metrics:mode');
if (typeof(value) === 'undefined') {
self.error('Could not find presence device');
return 'home'; // Fallback
}
return value;
};
/* Device helper functions */
BaseModule.prototype.processDeviceList = function(devices,callback) {
var self = this;
if (! _.isFunction(callback)) {
self.error('Invalid callback for processDeviceList');
return;
}
if (_.isUndefined(devices) === 'undefined') {
return;
} else if (! _.isArray(devices)) {
devices = [ devices ];
}
_.each(devices,function(device) {
var vDev;
if (_.isString(device)) {
vDev = self.controller.devices.get(device);
} else if (_.isObject(device)) {
vDev = device;
}
if (_.isNull(vDev) || _.isUndefined(vDev)) {
self.error('Device not found '+device);
return;
}
callback(vDev);
});
};
BaseModule.prototype.compareDevice = function(vDev,criterias) {
var self = this;
var match;
_.each(criterias,function(criteria) {
// Matched false - skip the rest
if (match === false) {
return;
// Device ID
} else if (_.isString(criteria)) {
if (criteria !== vDev.id) {
match = false;
}
// Comparison array
} else if (_.isArray(criteria)) {
// eg. ['metrics:level','=','on']
var matchKey = criteria[0];
var matchComparison = criteria[1];
var matchList = criteria[2];
var compareValue;
// Get value
if (matchKey === 'zwaveId') {
var result = vDev.id.match(/^ZWayVDev_zway_(\d+)-\d+-/m);
if (result === null) {
match = false;
return;
}
compareValue = parseInt(result[1],10);
} else {
compareValue = vDev.get(matchKey);
// Fall back for metrics:level if no target is set
if (matchKey === 'metrics:target'
&& (typeof(compareValue) === 'undefined' || compareValue === null)) {
compareValue = vDev.get('metrics:level');
}
}
if (typeof(compareValue) === 'undefined' || compareValue === null) {
return false;
}
if (!_.isArray(matchList)) {
matchList = [ matchList ];
}
var matchFirst = _.find(matchList,function(matchValue) {
// Comparison is array
if (_.isArray(compareValue)) {
var hasMatch = (compareValue.indexOf(matchValue) === -1) ? false:true;
return ((matchComparison === '!=' && !hasMatch) || (matchComparison === '=' && hasMatch)) ? true:false;
// Comparison is scalar
} else {
if (matchKey === 'metrics:level' || matchKey === 'metrics:target') {
if (vDev.get('deviceType') === 'switchBinary') {
if (typeof(matchValue) === 'number') {
compareValue = (compareValue === 'on' ? 255:0);
} else if (typeof(matchValue) === 'boolean') {
compareValue = (compareValue === 'on' ? true:false);
}
} else if (vDev.get('deviceType') === 'switchMultilevel') {
if (typeof(matchValue) === 'string') {
compareValue = (compareValue > 0 ? 'on':'off');
} else if (typeof(matchValue) === 'boolean') {
compareValue = (compareValue > 0 ? true:false);
}
}
}
return self.compare(compareValue,matchComparison,matchValue);
}
});
match = ! _.isUndefined(matchFirst);
} else {
self.error('Invalid device comparison');
}
});
if (typeof(match) === 'boolean') {
return match;
}
return false;
};
BaseModule.prototype.processDevices = function(criterias,callback) {
var self = this;
if (! _.isFunction(callback)) {
self.error('Invalid callback for processDevices');
return;
}
self.controller.devices.each(function(vDev) {
var match = self.compareDevice(vDev,criterias);
if(match === true) {
callback(vDev);
}
});
};
BaseModule.prototype.getDevices = function(criterias) {
var self = this;
var devices = [];
self.controller.devices.each(function(vDev) {
var match = self.compareDevice(vDev,criterias);
if(match === true) {
devices.push(vDev);
}
});
return devices;
};
BaseModule.prototype.getDevice = function(criterias) {
var self = this;
var device;
if (typeof(criterias) === 'string') {
device = self.controller.devices.get(criterias);
} else if (_.isArray(criterias)) {
self.controller.devices.each(function(vDev) {
if (typeof(device) === 'undefined') {
var match = self.compareDevice(vDev,criterias);
if(match === true) {
device = vDev;
}
}
});
}
if (device === null) {
return undefined;
} else {
return device;
}
};
BaseModule.prototype.getDeviceValue = function(criterias,key) {
var self = this;
key = key || 'metrics:level';
var device = self.getDevice(criterias);
if (typeof(device) === 'undefined') {
self.error('Could not find device');
} else {
return device.get(key);
}
};
BaseModule.prototype.performCommandDevices = function(criterias,command,args,auto) {
var self = this;
args = args || {};
var devices = [];
self.controller.devices.each(function(vDev) {
var match = self.compareDevice(vDev,criterias);
if(match === true) {
devices.push(vDev);
if (typeof(command) !== 'undefined') {
setTimeout(function() {
vDev.performCommand(command,args);
},1);
}
if (typeof(auto) === 'boolean') {
vDev.set('metrics:auto',auto);
}
}
});
return devices;
};
/* Time helper functions */
BaseModule.prototype.parseTime = function(timeString) {
if (typeof(timeString) === 'undefined') {
return;
}
var match = timeString.match(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?\s*(am|pm)?$/);
if (!match) {
this.log('Could not parse time: '+timeString);
return;
}
var hour = parseInt(match[1],10);
var minute = parseInt(match[2],10);
var second = parseInt(match[3] || 0,10);
var ampm = match[4];
if (ampm === 'pm' && hour < 12) {
hour = hour + 12;
}
var dateCalc = new Date();
dateCalc.setHours(hour, minute,second,0);
return dateCalc;
};
BaseModule.prototype.checkPeriod = function(timeFrom,timeTo) {
var self = this;
var dateNow = new Date();
// Check from/to time
if (typeof(timeFrom) === 'string') {
timeFrom = self.parseTime(timeFrom);
}
if (typeof(timeTo) === 'string') {
timeTo = self.parseTime(timeTo);
}
if (typeof(timeFrom) === 'undefined'
|| typeof(timeTo) === 'undefined') {
return true;
}
// Period over midnight
if (timeFrom >= timeTo) {
if (timeTo <= dateNow) {
var toHour = timeTo.getHours();
var toMinute = timeTo.getMinutes();
timeTo.setHours(toHour + 24);
// Now fix time jump on DST
timeTo.setHours(toHour,toMinute);
} else {
var fromHour = timeFrom.getHours();
var fromMinute = timeFrom.getMinutes();
timeFrom.setHours(fromHour - 24);
// Now fix time jump on DST
timeFrom.setHours(fromHour,fromMinute);
}
}
if (timeFrom > dateNow || dateNow > timeTo) {
return false;
}
self.log('Match '+timeFrom+'-'+timeTo);
return true;
};
BaseModule.prototype.compare = function (val1, op, val2) {
// match = self.compare(compareValue,matchComparison,matchValue);
if (op === "=") {
if (_.isRegExp(val2) && _.isString(val1)) {
return val1.match(val2) !== null;
} else {
return val1 === val2;
}
} else if (op === "!=") {
if (_.isRegExp(val2) && _.isString(val1)) {
return val1.match(val2) === null;
} else {
return val2 !== val1;
}
} else if (op === ">") {
return val1 > val2;
} else if (op === "<") {
return val1 < val2;
} else if (op === ">=") {
return val1 >= val2;
} else if (op === "<=") {
return val1 <= val2;
} else {
console.error('Invalid comparison operator '+op);
}
return null; // error!!
};
//----------------------------------------------------------------------------
//--- Timeout manager
//----------------------------------------------------------------------------
function TimeoutManager(scope) {
var self = this;
self.scope = scope;
self.timeouts = {};
}
TimeoutManager.prototype.timeouts = {};
TimeoutManager.prototype.running = function(id) {
var self = this;
if (typeof(self.timeouts[id]) === "undefined") {
return false;
}
return self.timeouts[id].cleared ? false:true;
};
TimeoutManager.prototype.add = function(id,fn,interval) {
var self = this;
// Do not overwrite existing timer
if (typeof(self.timeouts[id]) !== "undefined"
&& self.timeouts[id].cleared === false) {
throw('Timeout "'+id+'" is already active');
}
// Build args
var args = new Array(arguments.length - 1);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i+1];
}
args.unshift(self.scope,self.scope);
self.timeouts[id] = new(Function.prototype.bind.apply(Timeout,args));
return self.timeouts[id];
};
TimeoutManager.prototype.replace = function(id,fn,interval) {
var self = this;
// Clear existing timer
if (typeof(self.timeouts[id]) !== "undefined") {
self.timeouts[id].clear();
}
// Build args
var args = new Array(arguments.length - 1);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i+1];
}
args.unshift(self.scope,self.scope);
self.timeouts[id] = new(Function.prototype.bind.apply(Timeout,args));
return self.timeouts[id];
};
TimeoutManager.prototype.get = function(id) {
return this.timeouts[id];
};
TimeoutManager.prototype.clear = function(id) {
var self = this;
if (typeof(self.timeouts[id]) !== "undefined") {
self.timeouts[id].clear();
delete self.timeouts[id];
return true;
}
return false;
};
TimeoutManager.prototype.clearAll = function() {
var self = this;
for (var id in self.timeouts) {
if (self.timeouts.hasOwnProperty(id)
&& typeof(self.timeouts[id]) !== "undefined") {
self.timeouts[id].clear();
}
}
self.timeouts = {};
};
//----------------------------------------------------------------------------
//--- Timeout class
//----------------------------------------------------------------------------
function Timeout(scope,fn,interval) {
var self = this;
var args = new Array(arguments.length-3);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i+3];
}
args.unshift(scope);
fn = fn || function() {};
self.fn = Function.prototype.bind.apply(fn,args);
self.id = setTimeout(self.run.bind(self),interval);
self.cleared= false;
//Register timeout by name?
}
Timeout.prototype.id = undefined;
Timeout.prototype.cleared = false;
Timeout.prototype.fn = undefined;
Timeout.prototype.run = function() {
this.clear();
this.fn();
};
Timeout.prototype.clear = function() {
var self = this;
if (typeof(self.id) !== 'undefined' && self.cleared === false) {
clearTimeout(self.id);
}
self.cleared = true;
self.id = undefined;
};