forked from WebThingsIO/zwave-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zwave-adapter.js
453 lines (398 loc) · 13.1 KB
/
zwave-adapter.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
/**
*
* ZWaveAdapter - Adapter which manages ZWave nodes
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.*
*/
'use strict';
const path = require('path');
const fs = require('fs');
const ZWaveNode = require('./zwave-node');
const SerialPort = require('serialport');
const zwaveClassifier = require('./zwave-classifier');
let Adapter;
try {
Adapter = require('../adapter');
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
Adapter = require('gateway-addon').Adapter;
}
let ZWaveModule;
const DEBUG = false;
class ZWaveAdapter extends Adapter {
constructor(addonManager, packageName, port) {
// The ZWave adapter supports multiple dongles and
// will create an adapter object for each dongle.
// We don't know the actual adapter id until we
// retrieve the home id from the dongle. So we set the
// adapter id to zwave-unknown here and fix things up
// later just before we call addAdapter.
super(addonManager, 'zwave-unknown', packageName);
this.ready = false;
this.named = false;
this.port = port;
this.nodes = {};
this.nodesBeingAdded = {};
// Use debugFlow if you need to debug the flow of the program. This causes
// prints at the beginning of many functions to print some info.
this.debugFlow = false;
// Default to current directory.
let logDir = '.';
if (process.env.hasOwnProperty('MOZIOT_HOME')) {
// Check user profile directory.
const profileDir = path.join(process.env.MOZIOT_HOME, 'log');
if (fs.existsSync(profileDir) &&
fs.lstatSync(profileDir).isDirectory()) {
logDir = profileDir;
}
}
this.zwave = new ZWaveModule({
SaveConfiguration: true,
ConsoleOutput: false,
UserPath: logDir,
});
this.zwave.on('controller command', this.controllerCommand.bind(this));
this.zwave.on('driver ready', this.driverReady.bind(this));
this.zwave.on('driver failed', this.driverFailed.bind(this));
this.zwave.on('scan complete', this.scanComplete.bind(this));
this.zwave.on('node added', this.nodeAdded.bind(this));
this.zwave.on('node naming', this.nodeNaming.bind(this));
this.zwave.on('node removed', this.nodeRemoved.bind(this));
this.zwave.on('node event', this.nodeEvent.bind(this));
this.zwave.on('node ready', this.nodeReady.bind(this));
this.zwave.on('notification', this.nodeNotification.bind(this));
this.zwave.on('value added', this.valueAdded.bind(this));
this.zwave.on('value changed', this.valueChanged.bind(this));
this.zwave.on('value removed', this.valueRemoved.bind(this));
this.zwave.on('scene event', this.sceneEvent.bind(this));
this.zwave.connect(port.comName);
}
asDict() {
const dict = super.asDict();
const node1 = this.nodes[1];
if (node1) {
this.node1 = node1.asDict();
}
return dict;
}
dump() {
console.log(this.oneLineSummary());
console.log(ZWaveNode.oneLineHeader(0));
console.log(ZWaveNode.oneLineHeader(1));
for (const nodeId in this.nodes) {
const node = this.nodes[nodeId];
console.log(node.oneLineSummary());
}
console.log('----');
}
controllerCommand(nodeId, retVal, state, msg) {
console.log('Controller Command feedback: %s node%d retVal:%d ' +
'state:%d', msg, nodeId, retVal, state);
}
driverReady(homeId) {
console.log('Driver Ready: HomeId:', homeId.toString(16));
this.id = `zwave-${homeId.toString(16)}`;
this.manager.addAdapter(this);
}
driverFailed() {
console.log('failed to start driver');
this.zwave.disconnect(this.port.comName);
}
handleDeviceAdded(node) {
if (this.debugFlow) {
console.log('handleDeviceAdded:', node.nodeId);
}
delete this.nodesBeingAdded[node.zwInfo.nodeId];
if (node.nodeId > 1) {
zwaveClassifier.classify(node);
super.handleDeviceAdded(node);
}
}
handleDeviceRemoved(node) {
if (this.debugFlow) {
console.log('handleDeviceRemoved:', node.nodeId);
}
delete this.nodes[node.zwInfo.nodeId];
delete this.nodesBeingAdded[node.zwInfo.nodeId];
super.handleDeviceRemoved(node);
}
scanComplete() {
// Add any nodes which otherwise aren't responding. This typically
// corresponds to devices which are sleeping and only check in periodically.
for (const nodeId in this.nodesBeingAdded) {
const node = this.nodesBeingAdded[nodeId];
if (node.lastStatus !== 'dead') {
this.handleDeviceAdded(node);
}
}
console.log('Scan complete');
this.ready = true;
this.zwave.requestAllConfigParams(3);
this.dump();
}
nodeAdded(nodeId) {
if (DEBUG) {
console.log('node%d added', nodeId);
}
// Pass in the empty string as a name here. Once the node is initialized
// (i.e. nodeReady) then if the user has assigned a name, we'll get
// that name.
const node = new ZWaveNode(this, nodeId, '');
this.nodes[nodeId] = node;
this.nodesBeingAdded[nodeId] = node;
node.lastStatus = 'added';
}
nodeNaming(nodeId, nodeInfo) {
const node = this.nodes[nodeId];
if (node) {
node.lastStatus = 'named';
const zwInfo = node.zwInfo;
zwInfo.location = nodeInfo.loc;
zwInfo.manufacturer = nodeInfo.manufacturer;
zwInfo.manufacturerId = nodeInfo.manufacturerid;
zwInfo.product = nodeInfo.product;
zwInfo.productType = nodeInfo.producttype;
zwInfo.productId = nodeInfo.productid;
zwInfo.type = nodeInfo.type;
if (zwInfo.product.startsWith('Unknown: ')) {
zwInfo.product = `${zwInfo.manufacturer} ${zwInfo.product}`;
}
if (nodeInfo.name) {
// Use the assigned name, if it exists
node.name = nodeInfo.name;
} else if (node.defaultName) {
// Otherwise use the constructed name
node.name = node.defaultName;
} else if (nodeId > 1) {
// We don't have anything else, use the id
node.name = node.id;
}
if (DEBUG || !node.named) {
console.log(
'node%d: Named',
nodeId,
zwInfo.manufacturer ?
zwInfo.manufacturer :
`id=${zwInfo.manufacturerId}`,
zwInfo.product ?
zwInfo.product :
`product=${zwInfo.productId}, type=${zwInfo.productType}`);
console.log('node%d: name="%s", type="%s", location="%s"',
zwInfo.nodeId, node.name, zwInfo.type, zwInfo.location);
}
node.named = true;
if (DEBUG) {
for (const comClass in node.zwClasses) {
const zwClass = node.zwClasses[comClass];
console.log('node%d: class %d', nodeId, comClass);
for (const idx in zwClass) {
console.log('node%d: %s=%s',
nodeId, zwClass[idx].label, zwClass[idx].value);
}
}
}
}
}
nodeRemoved(nodeId) {
if (DEBUG) {
console.log('node%d removed', nodeId);
}
const node = this.nodes[nodeId];
if (node) {
node.lastStatus = 'removed';
this.handleDeviceRemoved(node);
}
}
nodeEvent(nodeId, data) {
console.log('node%d event: Basic set %d', nodeId, data);
}
// eslint-disable-next-line no-unused-vars
nodeReady(nodeId, nodeInfo) {
const node = this.nodes[nodeId];
if (node) {
node.lastStatus = 'ready';
node.ready = true;
for (const comClass in node.zwClasses) {
switch (comClass) {
case 0x25: // COMMAND_CLASS_SWITCH_BINARY
case 0x26: // COMMAND_CLASS_SWITCH_MULTILEVEL
this.zwave.enablePoll(nodeId, comClass);
break;
}
}
if (nodeId in this.nodesBeingAdded) {
this.handleDeviceAdded(node);
}
}
}
// eslint-disable-next-line no-unused-vars
nodeNotification(nodeId, notif, help) {
const node = this.nodes[nodeId];
let lastStatus;
switch (notif) {
case 0:
console.log('node%d: message complete', nodeId);
lastStatus = 'msgCmplt';
break;
case 1:
console.log('node%d: timeout', nodeId);
lastStatus = 'timeout';
break;
case 2:
if (DEBUG) {
console.log('node%d: nop', nodeId);
}
lastStatus = 'nop';
break;
case 3:
console.log('node%d: node awake', nodeId);
lastStatus = 'awake';
break;
case 4:
console.log('node%d: node sleep', nodeId);
lastStatus = 'sleeping';
break;
case 5:
console.log('node%d: node dead', nodeId);
lastStatus = 'dead';
break;
case 6:
console.log('node%d: node alive', nodeId);
lastStatus = 'alive';
break;
}
if (node && lastStatus) {
node.lastStatus = lastStatus;
}
}
oneLineSummary() {
return `Controller: ${this.id} Path: ${this.port.comName}`;
}
sceneEvent(nodeId, sceneId) {
console.log('scene event: nodeId:', nodeId, 'sceneId', sceneId);
}
valueAdded(nodeId, comClass, value) {
const node = this.nodes[nodeId];
if (node) {
node.zwValueAdded(comClass, value);
}
}
valueChanged(nodeId, comClass, value) {
const node = this.nodes[nodeId];
if (node) {
node.zwValueChanged(comClass, value);
}
}
valueRemoved(nodeId, comClass, valueInstance, valueIndex) {
const node = this.nodes[nodeId];
if (node) {
node.zwValueRemoved(comClass, valueInstance, valueIndex);
}
}
// eslint-disable-next-line no-unused-vars
startPairing(timeoutSeconds) {
console.log('===============================================');
console.log('Press the Inclusion button on the device to add');
console.log('===============================================');
this.zwave.addNode();
}
cancelPairing() {
console.log('Cancelling pairing mode');
this.zwave.cancelControllerCommand();
}
/**
* Remove a device.
*
* @param {Object} device The device to remove.
* @return {Promise} which resolves to the device removed.
*/
removeThing(device) {
// ZWave can't really remove a particular thing.
console.log('==================================================');
console.log('Press the Exclusion button on the device to remove');
console.log('==================================================');
this.zwave.removeNode();
return new Promise((resolve, reject) => {
if (this.devices.hasOwnProperty(device.id)) {
this.handleDeviceRemoved(device);
resolve(device);
} else {
reject(`Device: ${device.id} not found.`);
}
});
}
// eslint-disable-next-line no-unused-vars
cancelRemoveThing(node) {
console.log('Cancelling remove mode');
this.zwave.cancelControllerCommand();
}
unload() {
// Wrap in setTimeout to resolve issues with disconnect() hanging.
// See: https://github.com/OpenZWave/node-openzwave-shared/issues/182
setTimeout(() => {
this.zwave.disconnect(this.port.comName);
}).ref();
return super.unload();
}
}
function isZWavePort(port) {
return ((port.vendorId == '0658' &&
port.productId == '0200') || // Aeotec Z-Stick Gen-5
(port.vendorId == '0658' &&
port.productId == '0280') || // UZB1
(port.vendorId == '10c4' &&
port.productId == 'ea60') || // Aeotec Z-Stick S2
(port.vendorId == '10c4' &&
port.productId == '8a2a')); // Nortek Security & Control HUSBZB-1
}
// Scan the serial ports looking for an OpenZWave adapter.
//
// callback(error, port)
// Upon success, callback is invoked as callback(null, port) where `port`
// is the port object from SerialPort.list().
// Upon failure, callback is invoked as callback(err) instead.
//
function findZWavePort(callback) {
SerialPort.list(function listPortsCallback(error, ports) {
if (error) {
callback(error);
}
for (const port of ports) {
// Under OSX, SerialPort.list returns the /dev/tty.usbXXX instead
// /dev/cu.usbXXX. tty.usbXXX requires DCD to be asserted which
// isn't necessarily the case for ZWave dongles. The cu.usbXXX
// doesn't care about DCD.
if (port.comName.startsWith('/dev/tty.usb')) {
port.comName = port.comName.replace('/dev/tty', '/dev/cu');
}
if (isZWavePort(port)) {
callback(null, port);
return;
}
}
callback('No ZWave port found');
});
}
function loadZWaveAdapters(addonManager, manifest, errorCallback) {
try {
ZWaveModule = require('openzwave-shared');
} catch (err) {
errorCallback(manifest.name, `Failed to load openzwave-shared: ${err}`);
return;
}
findZWavePort(function(error, port) {
if (error) {
errorCallback(manifest.name, 'Unable to find ZWave adapter');
return;
}
console.log('Found ZWave port @', port.comName);
new ZWaveAdapter(addonManager, manifest.name, port);
// The zwave adapter will be added when it's driverReady method is called.
// Prior to that we don't know what the homeID of the adapter is.
});
}
module.exports = loadZWaveAdapters;