diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7386211 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*~ +node_modules +build diff --git a/10-zwave.html b/10-zwave.html index 2ce2df3..11337c5 100644 --- a/10-zwave.html +++ b/10-zwave.html @@ -22,19 +22,40 @@ + +
+ +
- - + +
- - + + + +
+
+ +
+
@@ -74,8 +95,145 @@
+ + + + + + + + diff --git a/10-zwave.js b/10-zwave.js index 45b54a6..2145c44 100644 --- a/10-zwave.js +++ b/10-zwave.js @@ -2,8 +2,9 @@ OpenZWave nodes for IBM's Node-Red https://github.com/ekarak/node-red-contrib-openzwave - (c) 2014-2015, Elias Karakoulakis - + (c) 2014-2017, Elias Karakoulakis + (c) 2017 Sebastian Barwe + Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at @@ -18,6 +19,7 @@ */ + var UUIDPREFIX = "_macaddr_"; var HOMENAME = "_homename_"; require('getmac').getMac(function (err, macAddress) { @@ -25,18 +27,27 @@ require('getmac').getMac(function (err, macAddress) { UUIDPREFIX = macAddress.replace(/:/gi, ''); }); -/* set this to true to get some incomprehensible Klingon text in your console */ -var debug = true; -if (debug) console.log("booting up node-red-contrib-openzwave"); module.exports = function (RED) { - var serialp = require("serialport"); - var OpenZWave = require('openzwave-shared'); + const serialp = require("serialport"); + const util = require('util'); + const path = require('path'); + const fs = require('fs'); + + var ozwsharedpath = path.dirname(path.dirname(require.resolve('openzwave-shared'))); + var ozwsharedpackage = JSON.parse(fs.readFileSync(ozwsharedpath+"/package.json")); + var thispackage = JSON.parse(fs.readFileSync(__dirname+'/package.json')); + RED.log.info('openzwave-shared: ' + ozwsharedpackage.version); + RED.log.info('node-red-contrib-openzwave: ' + thispackage.version); + + const OpenZWave = require('openzwave-shared'); var ozwConfig = {}; var ozwDriver = null; var ozwConnected = false; var driverReadyStatus = false; + var allowunreadyupdates = false; + // array of all zwave nodes with internal hashmaps for their properties and their values var zwnodes = {}; // Provide context.global access to node info. @@ -52,7 +63,7 @@ module.exports = function (RED) { function zwsubscribe(nrNode, event, callback) { if (!(event in nrNodeSubscriptions)) nrNodeSubscriptions[event] = {}; - if (debug) console.log('subscribing %s(%s) to event %s', nrNode.type, nrNode.id, event); + RED.log.trace(util.format('subscribing %s(%s) to event %s', nrNode.type, nrNode.id, event)); nrNodeSubscriptions[event][nrNode.id] = callback; } @@ -60,7 +71,7 @@ module.exports = function (RED) { function zwunsubscribe(nrNode) { for (var event in nrNodeSubscriptions) { if (nrNodeSubscriptions.hasOwnProperty(event)) { - if (debug) console.log('unsubscribing %s(%s) from %s', nrNode.type, nrNode.id, event); + RED.log.trace(util.format('unsubscribing %s(%s) from %s', nrNode.type, nrNode.id, event)); delete nrNodeSubscriptions[event][nrNode.id]; } } @@ -71,7 +82,7 @@ module.exports = function (RED) { * ============================================================================ **/ function zwcallback(event, arghash) { - if (debug) console.log("zwcallback(event: %s, args: %j)", event, arghash); + RED.log.trace(util.format("zwcallback(event: %s, args: %j)", event, arghash)); // Add uuid if (arghash.nodeid !== undefined && HOMENAME !== undefined) arghash.uuid = UUIDPREFIX + '-' + @@ -84,7 +95,7 @@ module.exports = function (RED) { for (var nrnid in nrNodes) { if (nrNodes.hasOwnProperty(nrnid)) { var nrNode = RED.nodes.getNode(nrnid); - if (debug) console.log("zwcallback => %j, %s, args %j", nrNode, event, arghash); + RED.log.trace(util.format("zwcallback => %j, %s, args %j", nrNode, event, arghash)); nrNodes[nrnid].call(nrNode, event, arghash); updateNodeRedStatus(nrNode); } @@ -93,9 +104,9 @@ module.exports = function (RED) { } // update the NR node's status indicator - function updateNodeRedStatus(nrNode) { + function updateNodeRedStatus(nrNode, options) { // update NR node status - nrNode.status({ + nrNode.status(options || { fill: driverReadyStatus ? "green" : "red", text: driverReadyStatus ? "connected" : "disconnected", shape: "ring" @@ -108,7 +119,7 @@ module.exports = function (RED) { var homeHex = '0x' + homeid.toString(16); HOMENAME = homeHex; ozwConfig.name = homeHex; - if (debug) console.log('scanning Zwave network with homeid %s...', homeHex); + RED.log.info(util.format('scanning Zwave network with homeid %s...', homeHex)); zwcallback('driver ready', ozwConfig); } @@ -160,12 +171,11 @@ module.exports = function (RED) { function valueChanged(nodeid, comclass, valueId) { // valueId: OpenZWave ValueID (struct) - not just a boolean var oldst; - if (zwnodes[nodeid].ready) { + if (zwnodes[nodeid].ready || allowunreadyupdates) { oldst = zwnodes[nodeid]['classes'][comclass][valueId.instance][valueId.index].value; - if (debug) { - console.log('node%d: changed: %d:%s:%s->%s', nodeid, comclass, valueId['label'], oldst, valueId['value']); - console.log('node%d: value=%s', nodeid, JSON.stringify(valueId)); - } + RED.log.trace(util.format('node%d: changed: %d:%s:%s->%s', nodeid, comclass, valueId['label'], oldst, valueId['value'])); + RED.log.trace(util.format('node%d: value=%s', nodeid, JSON.stringify(valueId))); + // tell NR only if the node is marked as ready zwcallback('value changed', { "nodeid": nodeid, "cmdclass": comclass, "instance": valueId.instance, "cmdidx": valueId.index, @@ -205,9 +215,10 @@ module.exports = function (RED) { zwnodes[nodeid][attrname] = nodeinfo[attrname]; } } + RED.log.info(util.format("node%d: node ready (%s %s)", nodeid, nodeinfo.manufacturer || "", nodeinfo.product || "")); zwnodes[nodeid].ready = true; // - for (comclass in zwnodes[nodeid]['classes']) { + for (var comclass in zwnodes[nodeid]['classes']) { switch (comclass) { case 0x25: // COMMAND_CLASS_SWITCH_BINARY case 0x26: // COMMAND_CLASS_SWITCH_MULTILEVEL @@ -219,11 +230,10 @@ module.exports = function (RED) { } var values = zwnodes[nodeid]['classes'][comclass]; - if (debug) { - console.log('node%d: class %d', nodeid, comclass); - for (idx in values) - console.log('node%d: %s=%s', nodeid, values[idx]['label'], values[idx]['value']); - } + RED.log.trace(util.format('node%d: class %d', nodeid, comclass)); + for (var idx in values) + RED.log.trace(util.format('node%d: %s=%s', nodeid, values[idx]['label'], values[idx]['value'])); + } // zwcallback('node ready', {nodeid: nodeid, nodeinfo: nodeinfo}); @@ -239,28 +249,35 @@ module.exports = function (RED) { zwcallback('node available', {nodeid: nodeid, nodeinfo: nodeinfo}); } - function nodeEvent(nodeid, evtcode, valueId, help) { + function nodeEvent(nodeid, evt, help) { + RED.log.trace(util.format('node%d: %s', nodeid, help)); zwcallback('node event', { - "nodeid": nodeid, "event": evtcode, - "cmdclass": valueId.comclass, "cmdidx": valueId.index, "instance": valueId.instance, - "msg": msg + "nodeid": nodeid, + "event": evt, + "help": help }); } function notification(nodeid, notif, help) { - if (debug) console.log('node%d: %s', nodeid, help); + RED.log.trace(util.format('node%d: %s', nodeid, help)); zwcallback('notification', {nodeid: nodeid, notification: notif, help: help}); } function scanComplete() { - if (debug) console.log('ZWave network scan complete.'); + RED.log.info('ZWave network scan complete.'); zwcallback('scan complete', {}); } function controllerCommand(nodeid, state, errcode, help) { - if (debug) console.log('ZWave controller command feedback received'); + RED.log.trace('ZWave controller command feedback received'); zwcallback('controller command', {nodeid: nodeid, state: state, errcode: errcode, help: help}); } + + function sceneEvent(nodeid, sceneid) { + RED.log.trace(util.format('node%d: scende event %d', nodeid, sceneid)); + zwcallback('scene event', { + "nodeid": nodeid, "sceneid": sceneid}); + } // list of events emitted by OpenZWave and redirected to Node flows by the mapped function var ozwEvents = { @@ -277,39 +294,59 @@ module.exports = function (RED) { 'value removed': valueRemoved, 'notification': notification, 'scan complete': scanComplete, - 'controller command': controllerCommand + 'controller command': controllerCommand, + 'scene event': sceneEvent } // ========================== - function ZWaveController(n) { - // ========================== - RED.nodes.createNode(this, n); - this.name = n.port; - this.port = n.port; - this.driverattempts = n.driverattempts; - this.pollinterval = n.pollinterval; + function ZWaveController(config) { + // ========================== + RED.nodes.createNode(this, config); + this.name = config.port; + this.port = config.port; + this.driverattempts = config.driverattempts || 3; + this.pollinterval = config.pollinterval || 10000; + this.allowunreadyupdates = config.allowunreadyupdates; + this.logging = config.logging || 0; var node = this; // initialize OpenZWave upon boot or fetch it from the global reference // (used across Node-Red deployments which recreate all the nodes) // so we only get to initialise one single OZW driver (a lengthy process) + // see options.xml in the node's directory for basic options. + // these options are overrided by the following initialization options + // see https://github.com/OpenZWave/open-zwave/wiki/Config-Options for a description of the available parmeters. if (!ozwDriver) { ozwDriver = new OpenZWave({ - Logging: debug, - ConsoleOutput: debug, - QueueLogLevel: 6 + UserPath: RED.settings.userDir, // save ozw data in nodered user dir + //ConfigPath: RED.settings.userDir, // path must containt the zwave configuration library from ozw + LogFileName: "ozw.log", // TODO: append homeid to filename + Interface: node.port, // the serial port to use + Logging: true, // enable logging to OZW_Log.txt + ConsoleOutput: true, // copy logging to the console + SaveConfig: false, // write an XML network layout + SaveConfiguration: true, + DriverAttempts: node.driverattempts,// try this many times before giving up + PollInterval: node.pollinterval, // interval between polls in milliseconds + SuppressRefresh: false, // use refreshes to update alive timestamp + QueueLogLevel: node.logging, + NotifyTransactions: true, // Notifications when transaction complete is reported. + + //NetworkKey: "0xd2,0x58,0x85,0x11,0xa2,0x50,0xbc,0xd9,0xf4,0xa5,0x85,0x48,0x3f,0x9f,0xf8,0x06" }); + + /* =============== OpenZWave events ================== */ + Object.keys(ozwEvents).forEach(function (evt) { + RED.log.trace(node.name + ' addListener ' + evt); + ozwDriver.on(evt, ozwEvents[evt]); + }); } - /* =============== OpenZWave events ================== */ - Object.keys(ozwEvents).forEach(function (evt) { - if (debug) console.log(node.name + ' addListener ' + evt); - ozwDriver.on(evt, ozwEvents[evt]); - }) + /* =============== Node-Red events ================== */ this.on("close", function () { - if (debug) console.log('zwave-controller: close'); + RED.log.trace('zwave-controller: close'); // controller should also unbind from the C++ addon if (ozwDriver) { ozwDriver.removeAllListeners() @@ -330,17 +367,36 @@ module.exports = function (RED) { }); + zwsubscribe(node, 'scan complete', function(event, data) { + ozwDriver.setPollInterval(node.pollinterval); + allowunreadyupdates = node.allowunreadyupdates; + }); + zwsubscribe(node, 'driver failed', function (event, data) { - console.log('failed to start ZWave driver, is there a ZWave stick attached to %s ?', n.port); + RED.log.error(util.format('failed to start ZWave driver, is there a ZWave stick attached to %s ?', node.port)); }); /* time to connect */ if (!ozwConnected) { - if (debug) console.log('ZWave Driver: connecting to %s', n.port); - ozwDriver.connect(n.port); + RED.log.trace(util.format('ZWave Driver: connecting to %s', config.port)); + ozwDriver.connect(config.port); ozwConnected = true; + + function exitHandler(options, err) { + if (ozwDriver && ozwConnected) { + RED.log.info('disconnecting ZWave driver on '+node.port); + ozwDriver.disconnect(node.port); + } + + if (options.cleanup) RED.log.trace('clean shutdown'); + if (err) RED.log.trace(util.format("%j", err.stack)); + } + //do something when app is closing + process.on('exit', exitHandler.bind(null,{cleanup:true})); } - } + + + } // RED.nodes.registerType("zwave-controller", ZWaveController); @@ -356,7 +412,7 @@ module.exports = function (RED) { var zwaveController = RED.nodes.getNode(config.controller); if (!zwaveController) { - node.err('no ZWave controller class defined!'); + node.error('no ZWave controller class defined!'); return; } /* =============== Node-Red events ================== */ @@ -365,7 +421,7 @@ module.exports = function (RED) { node.status({fill: "red", shape: "ring", text: "disconnected"}); // remove all event subscriptions for this node zwunsubscribe(this); - if (debug) console.log('zwave-in: close'); + node.info('zwave-in: close'); }); this.on("error", function () { // what? there are no errors. there never were. @@ -377,7 +433,7 @@ module.exports = function (RED) { zwsubscribe(node, key, function (event, data) { var msg = {'topic': 'zwave: ' + event}; if (data) msg.payload = data; - if (debug) console.log('===> ZWAVE-IN injecting: %j', msg); + RED.log.trace(util.format('===> ZWAVE-IN injecting: %j', msg)); node.send(msg); }); }); @@ -394,19 +450,21 @@ module.exports = function (RED) { // ========================= RED.nodes.createNode(this, config); this.name = config.name; + this.topic = config.topic || null; + // var node = this; var zwaveController = RED.nodes.getNode(config.controller); if (!zwaveController) { - node.err('no ZWave controller class defined!'); + node.error('no ZWave controller class defined!'); return; } /* =============== Node-Red events ================== */ // this.on("input", function (msg) { - if (debug) console.log("ZWaveOut#input: %j", msg); + RED.log.trace(util.format("ZWaveOut#input: %j", msg)); var payload; try { payload = (typeof(msg.payload) === "string") ? @@ -432,7 +490,7 @@ module.exports = function (RED) { // setValue: for everything else case /setValue/.test(msg.topic): - if (debug) console.log("ZWaveOut.setValue payload: %j", payload); + RED.log.trace(util.format("ZWaveOut.setValue payload: %j", payload)); ozwDriver.setValue( payload.nodeid, (payload.cmdclass || 37),// default cmdclass: on-off @@ -443,7 +501,7 @@ module.exports = function (RED) { break; case /setConfigParam/.test(msg.topic): - if (debug) console.log("ZWaveOut.setConfigParam payload: %j", payload); + RED.log.trace(util.format("ZWaveOut.setConfigParam payload: %j", payload)); ozwDriver.setConfigParam( payload.nodeid, payload.paramId, @@ -451,36 +509,61 @@ module.exports = function (RED) { ); break; case /requestConfigParam/.test(msg.topic): - if (debug) console.log("ZWaveOut.requestConfigParam payload: %j", payload); + RED.log.trace(util.format("ZWaveOut.requestConfigParam payload: %j", payload)); ozwDriver.requestConfigParam( payload.nodeid, payload.paramId ); break; case /requestAllConfigParams/.test(msg.topic): - if (debug) console.log("ZWaveOut.requestAllConfigParams payload: %j", payload); + RED.log.trace(util.format("ZWaveOut.requestAllConfigParams payload: %j", payload)); ozwDriver.requestAllConfigParams(payload.nodeid); break; case /refreshNodeInfo/.test(msg.topic): - if (debug) console.log("ZWaveOut.refreshNodeInfo payload: %j", payload); + RED.log.trace(util.format("ZWaveOut.refreshNodeInfo payload: %j", payload)); ozwDriver.refreshNodeInfo(payload.nodeid); break; - /* EXPERIMENTAL: send basically every available command down - * to OpenZWave, just name the function in the message topic - * and pass in the payload the function's args as an array: - * {"topic": "someOpenZWaveCommand", "payload": [1, 2, 3]} - * */ + /* EXPERIMENTAL: send basically every available command down + * to OpenZWave, just name the function in the message topic + * and pass in the arguments as "payload.args" as an array: + * {"topic": "someOpenZWaveCommand", "payload": {"args": [1, 2, 3]}} + * If the command needs the HomeID as the 1st arg, use "payload.prependHomeId" + * */ + //TODO: move this to special zwave-cmd-node code default: - if (/*ozwDriver.hasOwnProperty(msg.topic) &&*/ - typeof ozwDriver[msg.topic] === 'function' && - payload.constructor.name === 'Array' - ) { - console.log('attempting direct call to OpenZWave API: %s(%s)', msg.topic, payload); + + var topic; + if (msg.topic !== undefined && msg.topic !== "") { + topic = msg.topic; + } else { + topic = node.topic; + } + if (topic in ozwDriver && + typeof ozwDriver[topic] === 'function' && + payload + ){ + RED.log.trace(util.format('attempting direct call to OpenZWave API: %s(%s)', topic, payload)); try { - ozwDriver[msg.topic](payload.args); + var args = payload.args || []; + if (payload.prependHomeId) + args.unshift(ozwConfig.homeid); + var retval = ozwDriver[topic].apply(ozwDriver, args); + + + if ((typeof result != 'undefined') && !retval) { + RED.log.trace('Got return value, sending as payload'); + } else { + RED.log.trace('No return value but call successful, sending empty array'); + } + //TODO: move below so that error case is handled + msg.topic = topic; + msg.payload.args = args; + msg.payload.result = retval || []; + //TODO: this is only for the cmdnode + node.send(msg); } catch (err) { - node.warn('direct OpenZWave call to ' + msg.topic + ' failed: ' + err); + node.warn('direct OpenZWave call to ' + topic + ' failed: ' + err); } } ; @@ -497,8 +580,8 @@ module.exports = function (RED) { }); this.on("error", function () { - // there are. no. russians. in afghanistan. node.status({fill: "yellow", shape: "ring", text: "error"}); + node.log('zwave-out: error'); }); /* =============== OpenZWave events ================== */ @@ -512,9 +595,15 @@ module.exports = function (RED) { updateNodeRedStatus(node); } + + // RED.nodes.registerType("zwave-out", ZWaveOut); - // + + //TODO: create ZWaveCmd instead of ZWaveOut + RED.nodes.registerType("zwave-cmd", ZWaveOut); + + // create API endpoints for configuration node RED.httpAdmin.post("/openzwave/:id/:command", RED.auth.needsPermission("openzwave.write"), function (req, res) { var node = RED.nodes.getNode(req.params.id); try { @@ -525,24 +614,28 @@ module.exports = function (RED) { ozwDriver.addNode(false); else ozwDriver.beginControllerCommand('AddDevice', false); - res.send(200); + res.sendStatus(200); break; case 'remove_spec_node': - res.send(200); + res.sendStatus(200); break; case 'remove': case 'delete': - ozwDriver.beginControllerCommand('RemoveDevice', true); - res.send(200); + ozwDriver.removeNode(); + // ozwDriver.beginControllerCommand('RemoveDevice', true); + res.sendStatus(200); break; case 'remove_dead': case 'delete_failed': ozwDriver.beginControllerCommand('RemoveFailedNode', true); - res.send(200); + res.sendStatus(200); break; case 'cancel': ozwDriver.cancelControllerCommand(true); - res.send(200); + // TODO: handle asynchronisytoy here + if (ozwDriver.addNode) + ozwDriver.addNode(true); + res.sendStatus(200); break; case 'list_nodes': res.status(200).json(zwnodes); @@ -552,18 +645,18 @@ module.exports = function (RED) { break; case 'soft_reset': ozwDriver.softReset(); - res.send(200); + res.sendStatus(200); break; case 'heal_network': ozwDriver.healNetwork(); - res.send(200); + res.sendStatus(200); break; default: - res.send(404); + res.sendStatus(404); } } catch (err) { - res.send(500); - console.log(err); + res.sendStatus(500); + RED.log.error(err); node.error(RED._("openzwave.failed", {error: err.toString()})); } }); diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 72f8a86..0000000 --- a/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -One may find full license text here: https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode - -You are free to: - -Share - copy and redistribute the material in any medium or format -Adapt - remix, transform, and build upon the material -The licensor cannot revoke these freedoms as long as you follow the license terms. - -Under the following terms: - -Attribution - You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. -NonCommercial - You may not use the material for commercial purposes. -ShareAlike - If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. -No additional restrictions - You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. - -Notices: - -You do not have to comply with the license for elements of the material in the public domain or where your use is permitted by an applicable exception or limitation. -No warranties are given. The license may not give you all of the permissions necessary for your intended use. For example, other rights such as publicity, privacy, or moral rights may limit how you use the material. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..ec99d84 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,226 @@ +## License + +Copyright (c) 2015 Elias Karakoulakis + +This software follows Node-Red's licencing scheme, Apache-2.0, which +is copied verbatim: + +### Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + +### node-openzwave-shared + +node-openzwave-shared (aka openzwave-shared) is licensed under the ISC license: + + Copyright (c) 2013 Jonathan Perkin + Copyright (c) 2015 Elias Karakoulakis + + Permission to use, copy, modify, and distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +### OpenZWave + + Copyright (c) 2010 Mal Lansell + + SOFTWARE NOTICE AND LICENSE + + OpenZWave is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + OpenZWave is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with OpenZWave. If not, see . + +You can find full copies of the GPL licenses under OpenZWave's +installation directory. diff --git a/README.md b/README.md index aa708c7..19be3b3 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,19 @@ ### Decription -*OpenZWave* nodes for Node-Red ( ). Uses the *shared* OpenZWave addon for Node.js ( ). +*OpenZWave* nodes for Node-Red ( ). Uses the *shared* OpenZWave addon for Node.js ( ). Integrating this node onto your Node-Red installation enables you to have **bidirectional integration with ZWave networks**, ie you can: - *send commands* to ZWave devices by sending special command messages in Node-Red flows - *have ZWave devices report their status* as messages injected into Node-Red flows as feedback -#### Nodes in this package +#### Nodes added to Node-Red by this package -- *zwave-controller* : a unique CONFIG node that holds configuration for initializing OpenZWave and will act as the encapsulator for OZW access. As a node-red 'config' node, it cannot be added to a graph, but it acts as a singleton object that gets created in the the background when you add 'zwave-in' or 'zwave-out' nodes and configure them to point to a ZWave USB controller (usually /dev/ttyUSB0). It also holds the state for the openZWave library which is useful across flow edits (you surely don't want to wait for OpenZWave to reinitialise when you change your flows!) +##### - *zwave-controller* -- *zwave-out* : use this to send arbitrary commands to the ZWave appliances. For the moment there are four commands supported, namely: +a unique CONFIG node that holds configuration for initializing OpenZWave and will act as the encapsulator for OZW access. As a node-red 'config' node, it cannot be added to a graph, but it acts as a singleton object that gets created in the the background when you add 'zwave-in' or 'zwave-out' nodes and configure them to point to a ZWave USB controller (usually /dev/ttyUSB0). It also holds the state for the openZWave library which is useful across flow edits (you surely don't want to wait for OpenZWave to reinitialise when you change your flows!) + +##### - *zwave-out* + +Use this node to send arbitrary commands to the ZWave appliances. For the moment there are four commands supported, namely: - `{topic: 'switchOn', payload: {"nodeid":2}}` ==> to switch on basic switch on ZWave node #2 @@ -24,17 +28,33 @@ Integrating this node onto your Node-Red installation enables you to have **bidi - `{topic: 'setValue', payload: {"nodeid":8, "instance":1, "value":1}}` ==> switch on the 2nd relay of multiswitch #8 For a full list of ZWave command classes, see - - - **(New since version 1.1.0)** Experimental support for the *full OpenZWave API*: - You can try passing ANY of the commands accepted by openzwave-shared (which - should be `properlyCamelCased` (convention is that `Manager::HealNetwork` - would be called as `healNetwork'), followed by a `payload` whose contents - is simply a JSON array of the command arguments **in the correct order**. - - - For example, to enable polling for ZWave node #5 for the on-off command class (0x25 == decimal 37): - - `{"topic": "enablePoll", "payload": [5, 37]}` - -- *zwave-in* : a node that emits ZWave events as they are emitted from the ZWave controller. Use this node to get status feedback about what is happening in real time in your ZWave network. For example, the following message is injected into the NR flow when ZWave node #9, a binary switch, is turned on: + +### Support for the **full OpenZWave API**: + + You can invoke ANY of the OpenZWave::Manager commands that are accepted by openzwave-shared (see [this source file for a list of supported commands](https://github.com/OpenZWave/node-openzwave-shared/blob/master/src/openzwave.cc#L59)). You should also consult the [official OpenZWave::Manager class documentation.](http://www.openzwave.com/dev/classOpenZWave_1_1Manager.html) + + The Node-Red message payload should contain an array of the command arguments **in the correct order**. For example: + + * to **add a new ZWave node** to your network, you need to prepend the ZWave Home ID to the `addNode()` management call as follows: + + `{"topic": "addNode", "payload": {"prependHomeId": true}}` + + * to **enable polling** for ZWave node #5 for the on-off command class (0x25 == decimal 37). Notice that the [EnablePoll() command](http://www.openzwave.com/dev/classOpenZWave_1_1Manager.html#a50d795cb20a0bea55ecfd4a02c9777f3) does **not** need a HomeId as an argument, hence we don't need to add `prependHomeId` to the message payload: + + `{"topic": "enablePoll", "payload": {"args": [5, 37]}}` + + * to get **a node's statistics** by using the `getNodeStatistics()` call: + + `{"topic": "getNodeStatistics", "payload": {"args": [2]}}` + +Most of the API calls in OpenZWave are *asynchronous*. This means that you don't get an immediate result value from the call itself, but you'll get notifications from their activity on the zwave-in input node. However, there are some direct API calls which *do return a value* (eg the `getNodeStatistics` is returning an object populated with the node's statistics: number of packets sent/received, transmission error counts etc). + +In this case, the result is appended to the message payload and forwarded to the output of the ZWave-out node. This is the *only* message that the output node is emitting. + + +##### - *zwave-in* + +A node that emits ZWave events as they are emitted from the ZWave controller. Use this node to get status feedback about what is happening in real time in your ZWave network. For example, the following message is injected into the NR flow when ZWave node #9, a binary switch, is turned on: `{"topic":"zwave: value changed","payload":{"nodeid":9,"cmdclass":37,"instance":1,"cmdidx":0,"oldState":false,"currState":true}}` @@ -49,4 +69,4 @@ This package has one sole dependency: [node-openzwave-shared](https://github.com Here's an example flow, that uses its sibling KNX for Node-Red project ( ) to bind KNX and ZWave together as one happy home automation network: -![openzwave example](https://lh6.googleusercontent.com/-g4i3cJ_Anp8/VCG4uThDUQI/AAAAAAAAAvw/EoOagZZ8u34/s1600/teaser.png) +![openzwave example](https://lh6.googleusercontent.com/-g4i3cJ_Anp8/VCG4uThDUQI/AAAAAAAAAvw/EoOagZZ8u34/s1600/teaser.png) \ No newline at end of file diff --git a/package.json b/package.json index b9e6830..0199602 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,19 @@ { "name": "node-red-contrib-openzwave", - "version": "1.2.0", + "version": "1.2.7", "description": "ZWave for node-red through OpenZWave, the open source ZWave library", "dependencies": { - "openzwave-shared": "1.1.2", + "openzwave-shared": "1.2.7", "getmac": ">= 1.0.0", - "serialport": "1.7.*" + "serialport": "4.0.*" + }, + "engines": { + "node": ">=4", + "npm": "=2.*" }, "repository": { "type": "git", - "url": "git://github.com/ekarak/node-red-contrib-openzwave.git#master" + "url": "https://github.com/OpenZWave/node-red-contrib-openzwave.git#master" }, "author": "Elias Karakoulakis ", "keywords": [ @@ -23,7 +27,7 @@ } }, "bugs": { - "url": "https://github.com/ekarak/node-red-contrib-openzwave.git#master/issues" + "url": "https://github.com/OpenZWave/node-red-contrib-openzwave.git#master/issues" }, "main": "10-zwave.js", "scripts": {