├── .gitignore ├── LICENSE ├── README.md ├── index.js ├── lib ├── accessory.js ├── utils.js └── websocket.js └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Mac 3 | .DS_Store 4 | 5 | # Node 6 | node_modules/ 7 | npm-debug.log 8 | .node-version 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # homebridge-websocket 2 | 3 | [![NPM version][npm-image]][npm-url] 4 | 5 | [npm-image]: http://img.shields.io/npm/v/homebridge-websocket.svg 6 | [npm-url]: https://npmjs.org/package/homebridge-websocket 7 | 8 | Homebridge-websocket is a Plugin for Homebridge. The Websocket-API supports the main homebridge functions. This allows you to add and control accessories from a "Bridge" or "Gateway" with a Websocket API. [Node-RED](http://nodered.org/) is the perfect platform to use with homebridge-websocket. 9 | 10 | Note-RED is a visual tool for wiring together hardware devices, APIs and online services. 11 | 12 | Please note that you can only get the accessories which are added via this homebridge-websocket plugin. 13 | The same applies to the homebridge-mqtt plugin. See comments [here](https://github.com/cflurin/homebridge-mqtt/issues/8) 14 | 15 | ### Installation 16 | 17 | If you are new to Homebridge, please first read the [documentation](https://github.com/nfarina/homebridge) to install Homebridge. 18 | 19 | Install homebridge-websocket: 20 | ```sh 21 | sudo npm install -g homebridge-websocket 22 | ``` 23 | 24 | ### Configuration 25 | Add the websocket-platform in config.json in your home directory inside `.homebridge`. 26 | 27 | ```sh 28 | { 29 | "platform" : "websocket", 30 | "name" : "websocket", 31 | "port": 4050 32 | } 33 | ``` 34 | 35 | ### Websocket Uri 36 | 37 | The homebridge-websocket is listen on: 38 | 39 | ```sh 40 | ws://127.0.0.1:4050 41 | ``` 42 | 43 | Replace `127.0.0.1` with your `ip-address`. The port `4050` can be changed in config.json. 44 | The websocket-client (e.g. Node-RED) has to connect to homebridge-websocket. 45 | 46 | ### Websocket API 47 | 48 | The data is sent/received in a JSON format with this structure: 49 | 50 | ```sh 51 | {"topic": , "payload": {}} 52 | ``` 53 | 54 | function | input / output 55 | -------- | --------- 56 | add | output 57 | remove | output 58 | get | output 59 | setValue | output 60 | set | input 61 | get | input 62 | response | input 63 | callback | output 64 | 65 | 66 | ```sh 67 | input: the websocket-client receives a message from the homebridge-websocket. 68 | output: the websocket-client sends a message to the homebridge-websocket. 69 | ``` 70 | 71 | **Howto examples:** 72 | 73 | **add (output)** 74 | 75 | ```sh 76 | {"topic": "add", "payload": {"name": "flex_lamp", "service": "Switch"}} 77 | ``` 78 | 79 | or with the additional accessory informations 80 | ```sh 81 | {"topic": "add", "payload": {"name": "flex_lamp", "service": "Switch", "manufacturer": "lamp_manu", "model": "flex_007", "serialnumber": "4711", "firmwarerevision": "1.0.0"}} 82 | ``` 83 | 84 | After the new accessory is added homebridge-websocket sends an acknowledge message: 85 | 86 | ```sh 87 | {"topic":"response", "payload": {"ack": true, "message": "accessory 'flex_lamp' is added."}} 88 | ``` 89 | 90 | **remove (output)** 91 | 92 | ```sh 93 | {"topic": "remove", "payload": {"name": "flex_lamp"}} 94 | ``` 95 | 96 | After the accessory is removed homebridge sends an acknowledge message: 97 | 98 | ```sh 99 | {"topic":"response", "payload": {"ack": true, "message": "accessory 'flex_lamp' is removed."}} 100 | ``` 101 | 102 | **get (output)** 103 | 104 | ```sh 105 | {"topic": "get", "payload": {"name": "all"}} 106 | ``` 107 | 108 | homebridge sends an accessories list: 109 | 110 | ```sh 111 | {"topic": "accessories", "payload": { 112 | "node_switch":{"service":"Switch","characteristics":{"On":true}}, 113 | "office_lamp":{"service":"Lightbulb","characteristics":{"On":"blank","Brightness":65}}, 114 | "at_home":{"service":"OccupancySensor","characteristics":{"OccupancyDetected":1}} 115 | } 116 | } 117 | ``` 118 | 119 | ```sh 120 | {"topic": "get", "payload": {"name": "temp_outdoor"}} 121 | ``` 122 | 123 | homebridge sends the accessory JSON object: 124 | 125 | ```sh 126 | {"topic": "accessories", "payload": { 127 | "temp_outdoor": {"service": "TemperatureSensor", "characteristics": {"CurrentTemperature": "13.4"}} 128 | } 129 | } 130 | ``` 131 | 132 | **setValue (output)** 133 | 134 | ```sh 135 | {"topic": "setValue", "payload": {"name": "flex_lamp", "characteristic": "On", "value": true}} 136 | ``` 137 | 138 | **set (input)** 139 | 140 | ```sh 141 | {"topic": "set", "payload": {"name": "flex_lamp", "characteristic": "On", "value": true}} 142 | ``` 143 | 144 | **get (input)** 145 | 146 | ```sh 147 | {"topic": "get", "payload": {"name": "flex_lamp", "characteristic": "On"}} 148 | ``` 149 | 150 | When homebridge-websocket sends a `get` topic it expects a callback with the value within 1 second. 151 | 152 | **callback (output)** 153 | 154 | ```sh 155 | {"topic": "callback", "payload": {"name": "flex_lamp", "characteristic": "On", "value": true}} 156 | ``` 157 | 158 | The required characteristics are added with the default properties. If you need to change the default, define the characteristic-name with the properties. e.g.: 159 | 160 | ```sh 161 | {"topic": "add", 162 | "payload": 163 | { 164 | "name": "temp_living", 165 | "service": "TemperatureSensor", 166 | "CurrentTemperature": {"minValue": -20, "maxValue": 60,"minStep": 1} 167 | } 168 | } 169 | ``` 170 | 171 | To add an optional charachteristic define the characteristic-name with "default" or with the properties. e.g.: 172 | 173 | ```sh 174 | {"topic": "add", "payload": {"name": "living_lamp", "service": "Lightbulb", "Brightness": "default"}} 175 | ``` 176 | 177 | ```sh 178 | {"topic": "add", 179 | "payload": 180 | { 181 | "name": "bathroom_blind", 182 | "service": "WindowCovering", 183 | "CurrentPosition": {"minStep": 5}, 184 | "TargetPosition": {"minStep": 5}, 185 | "CurrentHorizontalTiltAngle": {"minValue": 0, "minStep": 5}, 186 | "TargetHorizontalTiltAngle": {"minValue": 0, "minStep": 5} 187 | } 188 | } 189 | ``` 190 | 191 | [HomeKitTypes.js](https://github.com/KhaosT/HAP-NodeJS/blob/master/lib/gen/HomeKitTypes.js) describes all the predifined Services and Characteristcs. 192 | 193 | ### Websocket client (node-RED) 194 | 195 | Here's an example flow. It shows how to add an accessory (office_lamp) and how to set the value on/off. 196 | The messages sent from the homebridge-websocket are displayed on the debug tap. 197 | 198 | node-RED websocket settings: 199 | 200 | ```sh 201 | Type: Connect to 202 | URL: ws://127.0.0.1:4050 203 | option: Send/Receice intery message 204 | ``` 205 | 206 | ![node-RED](https://cloud.githubusercontent.com/assets/5056710/14761441/fee01054-0961-11e6-81e0-73f59603089c.jpeg) 207 | 208 | Take a look at [collection/homebridge-websocket](https://github.com/cflurin/collection/tree/master/homebridge-websocket) 209 | for the `example-flow.json` which you can import into node-RED. 210 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var util = require('util'); 4 | var Utils = require('./lib/utils.js').Utils; 5 | var WebsocketAccessory = require('./lib/accessory.js').Accessory; 6 | var Websocket = require('./lib/websocket.js').Websocket; 7 | 8 | var Accessory, Service, Characteristic, UUIDGen; 9 | var cachedAccessories = 0; 10 | 11 | var platform_name = "websocket"; 12 | var plugin_name = "homebridge-" + platform_name; 13 | var storagePath; 14 | 15 | module.exports = function(homebridge) { 16 | console.log("homebridge API version: " + homebridge.version); 17 | 18 | Accessory = homebridge.platformAccessory; 19 | 20 | Service = homebridge.hap.Service; 21 | Characteristic = homebridge.hap.Characteristic; 22 | UUIDGen = homebridge.hap.uuid; // Universally Unique IDentifier 23 | 24 | storagePath = homebridge.user.storagePath(); 25 | 26 | homebridge.registerPlatform(plugin_name, platform_name, WebsocketPlatform, true); 27 | } 28 | 29 | function WebsocketPlatform(log, config, api) { 30 | 31 | this.log = log; 32 | this.accessories = {}; 33 | this.hap_accessories = {}; 34 | 35 | this.log.debug("storagePath = %s", storagePath); 36 | this.log.debug("config = %s", JSON.stringify(config)); 37 | 38 | if (typeof(config) !== "undefined" && config !== null) { 39 | this.port = config.port || {"port": 4050}; 40 | } else { 41 | this.log.error("config undefined or null!"); 42 | this.log("storagePath = %s", storagePath); 43 | process.exit(1); 44 | } 45 | 46 | var plugin_version = Utils.readPluginVersion(); 47 | this.log("%s v%s", plugin_name, plugin_version); 48 | 49 | var params = { 50 | "log": this.log, 51 | "plugin_name": plugin_name, 52 | "port": this.port, 53 | "accessories": this.accessories, 54 | "Characteristic": Characteristic, 55 | "addAccessory": this.addAccessory.bind(this), 56 | "removeAccessory": this.removeAccessory.bind(this), 57 | "getAccessories": this.getAccessories.bind(this) 58 | } 59 | this.Websocket = new Websocket(params); 60 | 61 | Utils.read_npmVersion(plugin_name, function(npm_version) { 62 | if (npm_version > plugin_version) { 63 | this.log("A new version %s is avaiable", npm_version); 64 | } 65 | }.bind(this)); 66 | 67 | if (api) { 68 | this.api = api; 69 | 70 | this.api.on('didFinishLaunching', function() { 71 | this.log("Plugin - DidFinishLaunching"); 72 | 73 | this.Websocket.startServer(); 74 | 75 | this.log.debug("Number of cached Accessories: %s", cachedAccessories); 76 | this.log("Number of Accessories: %s", Object.keys(this.accessories).length); 77 | 78 | }.bind(this)); 79 | //this.log.debug("WebsocketPlatform %s", JSON.stringify(this.accessories)); 80 | } 81 | } 82 | 83 | WebsocketPlatform.prototype.addAccessory = function(accessoryDef) { 84 | 85 | var name = accessoryDef.name; 86 | var ack, message; 87 | var isValid; 88 | var service_type = accessoryDef.service; 89 | var manufacturer = accessoryDef.manufacturer; 90 | var model = accessoryDef.model; 91 | var serialnumber = accessoryDef.serialnumber; 92 | var firmwarerevision = accessoryDef.firmwarerevision; 93 | var service_name; 94 | 95 | if (!this.accessories[name]) { 96 | var uuid = UUIDGen.generate(name); 97 | 98 | var newAccessory = new Accessory(name, uuid); 99 | newAccessory.reachable = true; 100 | newAccessory.context.service_name = accessoryDef.service; 101 | 102 | //this.log.debug("addAccessory UUID = %s", newAccessory.UUID); 103 | 104 | var i_accessory = new WebsocketAccessory(this.buildParams(accessoryDef)); 105 | isValid = i_accessory.addService(newAccessory); 106 | if (isValid) { 107 | i_accessory.configureAccessory(newAccessory); 108 | 109 | this.accessories[name] = i_accessory; 110 | this.hap_accessories[name] = newAccessory; 111 | this.api.registerPlatformAccessories(plugin_name, platform_name, [newAccessory]); 112 | 113 | ack = true; 114 | message = "accessory '" + name + "' is added."; 115 | } else { 116 | ack = false; 117 | message = "service '" + accessoryDef.service + "' undefined."; 118 | } 119 | } else { 120 | ack = false; 121 | message = "name '" + name + "' is already used."; 122 | } 123 | this.log("addAccessory %s", message); 124 | this.Websocket.sendAck(ack, message); 125 | if (ack) { 126 | var now = new Date().toISOString().slice(0,16); 127 | var plugin_version = Utils.readPluginVersion(); 128 | var plugin_v = "v" + plugin_version; 129 | if (typeof manufacturer === "undefined") { 130 | manufacturer = plugin_name; 131 | } 132 | if (typeof model === "undefined") { 133 | model = plugin_v; 134 | } 135 | if (typeof serialnumber === "undefined") { 136 | serialnumber = now; 137 | } 138 | if (typeof firmwarerevision === "undefined") { 139 | firmwarerevision = plugin_version; 140 | } 141 | this.setAccessoryInformation({"name":name,"manufacturer":manufacturer,"model":model,"serialnumber":serialnumber,"firmwarerevision":firmwarerevision}, false); 142 | } 143 | } 144 | 145 | WebsocketPlatform.prototype.setAccessoryInformation = function(accessory) { 146 | 147 | this.log.debug("WebsocketPlatform.setAccessoryInformation %s", JSON.stringify(accessory)); 148 | var message; 149 | var ack; 150 | var name = accessory.name; 151 | 152 | if (typeof this.hap_accessories[name] === "undefined") { 153 | ack = false; message = "accessory '" + name + "' undefined."; 154 | } else { 155 | var service = this.hap_accessories[name].getService(Service.AccessoryInformation); 156 | 157 | if (typeof accessory.manufacturer !== "undefined") { 158 | service.setCharacteristic(Characteristic.Manufacturer, accessory.manufacturer); 159 | ack = true; 160 | } 161 | if (typeof accessory.model !== "undefined") { 162 | service.setCharacteristic(Characteristic.Model, accessory.model); 163 | ack = true; 164 | } 165 | if (typeof accessory.serialnumber !== "undefined") { 166 | service.setCharacteristic(Characteristic.SerialNumber, accessory.serialnumber); 167 | ack = true; 168 | } 169 | if (typeof accessory.firmwarerevision !== "undefined") { 170 | service.setCharacteristic(Characteristic.FirmwareRevision, accessory.firmwarerevision); 171 | ack = true; 172 | } 173 | 174 | if (ack) { 175 | message = "accessory '" + name + "', accessoryinformation is set."; 176 | } else { 177 | message = "accessory '" + name + "', accessoryinforrmation properties undefined."; 178 | } 179 | } 180 | this.Websocket.sendAck(ack, message); 181 | } 182 | 183 | WebsocketPlatform.prototype.configureAccessory = function(accessory) { 184 | 185 | //this.log.debug("configureAccessory %s", JSON.stringify(accessory.services, null, 2)); 186 | 187 | cachedAccessories++; 188 | var name = accessory.displayName; 189 | var uuid = accessory.UUID; 190 | 191 | var accessoryDef = {}; 192 | accessoryDef.name = name; 193 | accessoryDef.service = accessory.context.service_name; 194 | 195 | if (this.accessories[name]) { 196 | this.log.error("configureAccessory %s UUID %s already used.", name, uuid); 197 | process.exit(1); 198 | } 199 | 200 | accessory.reachable = true; 201 | 202 | var i_accessory = new WebsocketAccessory(this.buildParams(accessoryDef)); 203 | i_accessory.configureAccessory(accessory); 204 | 205 | this.accessories[name] = i_accessory; 206 | this.hap_accessories[name] = accessory; 207 | } 208 | 209 | WebsocketPlatform.prototype.removeAccessory = function(name) { 210 | 211 | var ack, message; 212 | 213 | if (typeof(this.accessories[name]) !== "undefined") { 214 | this.log.debug("removeAccessory '%s'", name); 215 | 216 | this.api.unregisterPlatformAccessories(plugin_name, platform_name, [this.hap_accessories[name]]); 217 | delete this.accessories[name]; 218 | delete this.hap_accessories[name]; 219 | ack = true; 220 | message = "accessory '" + name + "' is removed."; 221 | } else { 222 | ack = false; 223 | message = "accessory '" + name + "' not found."; 224 | } 225 | this.log("removeAccessory %s", message); 226 | this.Websocket.sendAck(ack, message); 227 | } 228 | 229 | WebsocketPlatform.prototype.getAccessories = function(name) { 230 | 231 | var accessories = {}; 232 | var def = {}; 233 | var service, characteristics; 234 | 235 | switch (name) { 236 | case "all": 237 | for (var k in this.accessories) { 238 | //this.log("getAccessories %s", JSON.stringify(this.accessories[k], null, 2)); 239 | service = this.accessories[k].service_name; 240 | characteristics = this.accessories[k].i_value; 241 | def = {"service": service, "characteristics": characteristics}; 242 | accessories[k] = def; 243 | } 244 | break; 245 | 246 | default: 247 | service = this.accessories[name].service_name; 248 | characteristics = this.accessories[name].i_value; 249 | def = {"service": service, "characteristics": characteristics}; 250 | accessories[name] = def; 251 | } 252 | 253 | //this.log("getAccessory %s", JSON.stringify(accessories, null, 2)); 254 | this.Websocket.sendAccessories(accessories); 255 | } 256 | 257 | WebsocketPlatform.prototype.buildParams = function (accessoryDef) { 258 | 259 | var params = { 260 | "accessoryDef": accessoryDef, 261 | "log": this.log, 262 | "Service": Service, 263 | "Characteristic": Characteristic, 264 | "Websocket": this.Websocket 265 | } 266 | //this.log.debug("configureAccessories %s", JSON.stringify(params.accessory_config)); 267 | return params; 268 | } 269 | 270 | -------------------------------------------------------------------------------- /lib/accessory.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var Utils = require('./utils.js').Utils; 4 | var Service, Characteristic, Websocket; 5 | 6 | Number.prototype.pad = function (len) { 7 | return (new Array(len+1).join("0") + this).slice(-len); 8 | } 9 | 10 | module.exports = { 11 | Accessory: Accessory 12 | } 13 | 14 | function Accessory(params) { 15 | 16 | this.accessoryDef = params.accessoryDef; 17 | this.log = params.log; 18 | Service = params.Service; 19 | Characteristic = params.Characteristic; 20 | Websocket = params.Websocket; 21 | 22 | this.name = this.accessoryDef.name; 23 | this.service_name = this.accessoryDef.service; 24 | 25 | this.i_value = {}; 26 | this.i_label = {}; 27 | this.i_props = {}; 28 | 29 | this.service; 30 | } 31 | 32 | Accessory.prototype.save_and_setValue = function (trigger, c, value) { 33 | 34 | //this.log.debug("Accessory.save_and_setValue %s %s %s", trigger, c, value); 35 | 36 | var result = {}; 37 | 38 | result = this.parseValue(c, value); 39 | 40 | if (result.isValid) { 41 | this.i_value[c] = result.value; 42 | this.setLabel(trigger, c); 43 | 44 | var context = this.i_label[c]; 45 | //context is also used by the hap-server ('get' and 'set' event) - "context": {"keepalive":true, ... 46 | //this.log.debug("Accessory.save_and_setValue %s %s %s %s %s ", trigger, this.name, c, result.value, JSON.stringify(context)); 47 | 48 | if (typeof(context) !== "undefined") { 49 | this.service.getCharacteristic(Characteristic[c]).setValue(result.value, null, context); 50 | } 51 | else { 52 | this.service.getCharacteristic(Characteristic[c]).setValue(result.value); 53 | } 54 | } 55 | } 56 | 57 | Accessory.prototype.saveValue = function (c, value) { 58 | 59 | var result = {}; 60 | 61 | result = this.parseValue(c, value); 62 | 63 | if (result.isValid) { 64 | this.i_value[c] = result.value; 65 | } 66 | } 67 | 68 | Accessory.prototype.parseValue = function(c, value) { 69 | 70 | var isValid = true; 71 | 72 | var sc = this.service.getCharacteristic(Characteristic[c]); 73 | 74 | switch (sc.props.format) { 75 | case "bool": 76 | value = (value == 0 || value == false) ? false : true; 77 | break; 78 | 79 | case "int": 80 | case "uint8": 81 | case "uint16": 82 | case "uint32": 83 | value = parseInt(value); 84 | if (value < sc.props.minValue || value > sc.props.maxalue) { 85 | this.log.error("Accessory.parse %s %s value '%s' outside range.", this.name, c, value); 86 | isValid = false; 87 | } 88 | break; 89 | 90 | case "float": 91 | value = parseFloat(value); 92 | if (value < sc.props.minValue || value > sc.props.maxalue) { 93 | this.log.error("Accessory.parse %s %s value '%s' outside range.", this.name, c, value); 94 | isValid = false 95 | } 96 | break; 97 | 98 | default: 99 | // string, tlv8, 100 | value = undefined; 101 | this.log.warn("Accessory.parseValue %s %s %s %s", name, c, value, JSON.stringify(sc.props)); 102 | } 103 | return {isValid: isValid, value: value}; 104 | } 105 | 106 | Accessory.prototype.setLabel = function(trigger, c) { 107 | 108 | var now = new Date(); 109 | var timestamp = now.getHours().pad(2)+":"+now.getMinutes().pad(2)+":"+now.getSeconds().pad(2); 110 | // +","+now.getMilliseconds(); 111 | 112 | this.i_label[c] = { 113 | "timestamp": timestamp, 114 | "trigger": trigger 115 | }; 116 | } 117 | 118 | Accessory.prototype.addService = function(newAccessory) { 119 | 120 | var isValid; 121 | 122 | if (typeof(Service[this.service_name]) !== "undefined") { 123 | var service = newAccessory.addService(Service[this.service_name], this.name); 124 | isValid = true; 125 | //this.log.debug("Accessory.addService %s", JSON.stringify(service, null, 2)); 126 | 127 | } else { 128 | //this.log.debug("Accessory.addService service '%s' undefined.", this.service_name); 129 | isValid = false; 130 | } 131 | return isValid; 132 | } 133 | 134 | Accessory.prototype.configureAccessory = function(accessory) { 135 | 136 | accessory.on('identify', function(paired, callback) {this.identify(paired, callback)}.bind(this)); 137 | 138 | //this.service = accessory.getService(Service[this.service_name]); 139 | this.service = accessory.getService(this.name); 140 | 141 | //this.log.debug("Accessory.configureAccessory %s %s %s\n", this.name, this.service_name, JSON.stringify(this.service.characteristics)); 142 | 143 | this.log.debug("Accessory.configureAccessory Def %s", JSON.stringify(this.accessoryDef)); 144 | 145 | var c; 146 | for (var k in this.service.characteristics) { 147 | 148 | c = this.service.characteristics[k].displayName.replace(/\s/g, ""); 149 | //this.log.debug("Accessory.configureAccessory %s %s %s", this.name, this.service_name, c); 150 | 151 | if (c != "Name") { 152 | this.allocate(c); 153 | this.setProps(c); 154 | this.i_value[c] = "blank"; 155 | this.i_props[c] = JSON.parse(JSON.stringify(this.service.getCharacteristic(Characteristic[c]).props)); 156 | //this.log.debug("Accessory.configureAccessory %s %s %s %s", this.name, this.service_name, c, JSON.stringify(this.i_props)); 157 | } 158 | } 159 | 160 | // note: if the accessories are restored from cachedAccessories, the optionalCharacteristics are stored in characteristics. 161 | for (var k in this.service.optionalCharacteristics) { 162 | 163 | c = this.service.optionalCharacteristics[k].displayName.replace(/\s/g, ""); 164 | 165 | if (typeof(this.accessoryDef[c]) !== "undefined") { 166 | this.log.debug("Accessory.configureAccessory %s %s optional %s", this.name, this.service_name, c); 167 | 168 | if (c != "Name") { 169 | this.allocate(c); 170 | this.setProps(c); 171 | this.i_value[c] = "blank"; 172 | this.i_props[c] = JSON.parse(JSON.stringify(this.service.getCharacteristic(Characteristic[c]).props)); 173 | } 174 | } 175 | } 176 | } 177 | 178 | Accessory.prototype.allocate = function(c) { 179 | 180 | var self = this; 181 | var sc = this.service.getCharacteristic(Characteristic[c]); 182 | 183 | sc.on('get', function(callback, context) {self.get(callback, context, this.displayName)}); 184 | if (sc.props.perms.indexOf("pw") > -1) { 185 | //this.log.debug("Accessory.allocate 'set' event %s %s", this.name, c); 186 | sc.on('set', function(value, callback, context) {self.set(value, callback, context, this.displayName)}); 187 | } 188 | } 189 | 190 | Accessory.prototype.setProps = function(c) { 191 | 192 | if (typeof(this.accessoryDef[c]) !== "undefined") { 193 | if (this.accessoryDef[c] != "default") { 194 | this.service.getCharacteristic(Characteristic[c]).setProps(this.accessoryDef[c]); 195 | } 196 | //this.log.debug("Accessory.setProps %s %s", this.name, c, this.accessoryDef[c]); 197 | //this.log.debug("Accessory.setProps %s %s", this.name, c, Characteristic[c]); 198 | } 199 | } 200 | 201 | Accessory.prototype.get = function(callback, context, displayName) { 202 | 203 | var c = displayName.replace(/\s/g, ""); 204 | //this.log.debug("Accessory.get %s %s", this.name, c); 205 | 206 | Websocket.get(this.name, c, callback); 207 | 208 | var value; 209 | if (typeof(this.i_value[c]) !== "undefined" && this.i_value[c] !== "blank") { 210 | value = this.i_value[c]; 211 | } else { 212 | value = null; 213 | } 214 | this.log.debug("Accessory.get %s %s %s", this.name, c, value); 215 | callback(null, value); 216 | } 217 | 218 | Accessory.prototype.set = function(value, callback, context, displayName) { 219 | 220 | var c = displayName.replace(/\s/g, ""); 221 | //this.log.debug("Accessory.set %s %s %s %s", this.name, c, value, JSON.stringify(context)); 222 | 223 | if (c == "On") value = (value == 0 || value == false) ? false : true; 224 | this.i_value[c] = value; 225 | 226 | if (typeof(context) !== "undefined" && typeof(context.trigger) === "undefined") { 227 | this.setLabel("homekit", c); 228 | } 229 | 230 | if (typeof(context) !== "undefined" && typeof(context.trigger) !== "undefined" && context.trigger.match(/websocket/g)) { 231 | //this.log.debug("Accessory.set %s %s %s - websocket", this.name, c, value); 232 | callback(); 233 | } else { 234 | Websocket.set(this.name, c, value, callback); 235 | } 236 | } 237 | 238 | Accessory.prototype.identify = function (paired, callback) { 239 | 240 | this.log("Accessory.identify %s", this.name); 241 | // todo 242 | callback(); 243 | } 244 | 245 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var path = require('path'); 4 | var fs = require('fs'); 5 | var request = require('request'); 6 | 7 | var plugins_name = "plugins"; 8 | var package_json = "../package.json"; 9 | var plugin_version; 10 | var github_version; 11 | var npm_version; 12 | 13 | module.exports = { 14 | Utils: Utils 15 | } 16 | 17 | function Utils() { 18 | } 19 | 20 | Utils.loadConfig = function(storage_path, plugin_name, config_name) { 21 | 22 | var plugin_storage_path = path.join(storage_path, plugins_name, plugin_name); 23 | var config_path = path.join(plugin_storage_path, config_name); 24 | 25 | // Complain and exit if config_name doesn't exist yet 26 | if (!fs.existsSync(config_path)) { 27 | console.log("Couldn't find a %s file at %s.", config_name, plugin_storage_path); 28 | process.exit(1); 29 | } 30 | 31 | // Load up the configuration file 32 | var config; 33 | try { 34 | //console.log("Utils.loadConfig"); 35 | config = JSON.parse(fs.readFileSync(config_path)); 36 | } 37 | catch (err) { 38 | console.log("There was a problem reading your %s file.", config_name); 39 | console.log("Please try pasting your %s file here to validate it: http://jsonlint.com", config_name); 40 | console.log(""); 41 | throw err; 42 | } 43 | return config; 44 | } 45 | 46 | Utils.saveConfig = function(storage_path, plugin_name, config_name, data) { 47 | 48 | var plugin_storage_path = path.join(storage_path, plugins_name, plugin_name); 49 | var config_path = path.join(plugin_storage_path, config_name); // "config_test.json"); 50 | 51 | try { 52 | //console.log("Utils.saveConfig %s", data); 53 | fs.writeFileSync(config_path, JSON.stringify(data, null, 2)); 54 | } 55 | catch (err) { 56 | console.log("There was a problem writing your %s file.", config_name); 57 | throw err; 58 | } 59 | } 60 | 61 | Utils.getPluginVersion = function() { 62 | return plugin_version; 63 | } 64 | 65 | Utils.get_npmVersion = function(pkg) { 66 | // Update version for the next call 67 | this.read_npmVersion(pkg, function(version) { 68 | npm_version = version; 69 | }); 70 | return npm_version; 71 | } 72 | 73 | Utils.n2b = function (number) { 74 | return (number == 0 || number == false) ? false : true; 75 | } 76 | 77 | Utils.getGitHubVersion = function(pkg, github_url) { 78 | this.read_GitHubVersion(pkg, github_url); 79 | return github_version; 80 | } 81 | 82 | Utils.readPluginVersion = function() { 83 | 84 | var packageJSONPath = path.join(__dirname, package_json); 85 | var packageJSON = JSON.parse(fs.readFileSync(packageJSONPath)); 86 | plugin_version = packageJSON.version; 87 | return plugin_version; 88 | } 89 | 90 | Utils.read_npmVersion = function(pck, callback) { 91 | var exec = require('child_process').exec; 92 | var cmd = 'npm view '+pck+' version'; 93 | exec(cmd, function(error, stdout, stderr) { 94 | npm_version = stdout.trim(); 95 | //npm_version = stdout.replace(/(\r\n|\n|\r)/gm,""); 96 | callback(npm_version); 97 | //console.log("npm_version %s", npm_version); 98 | }); 99 | } 100 | 101 | Utils.readGitHubVersion = function (pkg, url) { 102 | 103 | request.get({url: url}, function(err, response, body) { 104 | 105 | if (!err && response.statusCode == 200) { 106 | var package_json = body.trim(); 107 | //console.log("package.json %s", JSON.stringify(package)); 108 | var packageJSON = JSON.parse(package_json); 109 | github_version = packageJSON.version; 110 | if (github_version > plugin_version) { 111 | console.log("%s a new version %s is avaiable", pkg, github_version); 112 | } 113 | } 114 | else { 115 | console.log(err); 116 | if (response) console.log("statusCode: %s Message: %s", response.statusCode, response.statusMessage); 117 | } 118 | }); 119 | } 120 | 121 | /** 122 | * Converts an HSV color value to RGB. Conversion formula 123 | * adapted from https://en.wikipedia.org/wiki/HSL_and_HSV 124 | * Assumes h, s, and v are contained in the set [0, 1] and 125 | * returns rgb (FFFFFF) 126 | * 127 | * @param Number h The hue 128 | * @param Number s The saturation 129 | * @param Number v The value (brigthness) 130 | * @return HexNumber The RGB representation 131 | */ 132 | 133 | Utils.hsv2rgb = function (h, s, v) { 134 | 135 | //console.log("h: %s s: %s v: %s", h, s, v); 136 | var r, g, b; 137 | 138 | if( s == 0 ) { 139 | r = v; g = v; b = v; 140 | } 141 | else { 142 | var i = Math.floor(h * 6); 143 | var f = h * 6 - i; 144 | var p = v * (1 - s); 145 | var q = v * (1 - f * s); 146 | var t = v * (1 - (1 - f) * s); 147 | 148 | switch(i % 6){ 149 | case 0: r = v; g = t; b = p; break; 150 | case 1: r = q; g = v; b = p; break; 151 | case 2: r = p; g = v; b = t; break; 152 | case 3: r = p; g = q; b = v; break; 153 | case 4: r = t; g = p; b = v; break; 154 | case 5: r = v; g = p; b = q; break; 155 | } 156 | } 157 | r = Math.round(r*255); 158 | g = Math.round(g*255); 159 | b = Math.round(b*255); 160 | //console.log("r: %s g: %s b: %s", r, g, b); 161 | return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1).toUpperCase(); 162 | } 163 | 164 | /** 165 | * Converts an RGB color value to HSV. Conversion formula 166 | * adapted from https://en.wikipedia.org/wiki/HSL_and_HSV 167 | * Assumes r, g, and b are contained in the set [0, 255] and 168 | * returns h, s, and v in the set [0, 1]. 169 | * 170 | * @param Number r The red color value 171 | * @param Number g The green color value 172 | * @param Number b The blue color value 173 | * @return Array The HSV representation 174 | */ 175 | 176 | Utils.rgb2hsv = function(r, g, b) { 177 | 178 | r = r/255, g = g/255, b = b/255; 179 | var max = Math.max(r, g, b), min = Math.min(r, g, b); 180 | var h, s, v = max; 181 | 182 | var d = max - min; 183 | s = max == 0 ? 0 : d / max; 184 | 185 | if(max == min){ 186 | h = 0; // achromatic 187 | } else { 188 | switch(max){ 189 | case r: h = (g - b) / d + (g < b ? 6 : 0); break; 190 | case g: h = (b - r) / d + 2; break; 191 | case b: h = (r - g) / d + 4; break; 192 | } 193 | h /= 6; 194 | } 195 | 196 | return [h, s, v]; 197 | } -------------------------------------------------------------------------------- /lib/websocket.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var util = require('util'); 4 | var path = require('path'); 5 | var Utils = require('./utils.js').Utils; 6 | var port, plugin_name, accessories, Characteristic, addAccessory, removeAccessory, getAccessories; 7 | var latest, get_timeout, set_timeout, pre_name, pre_c; 8 | 9 | var WebSocketServer = require('ws').Server, 10 | http = require('http'), 11 | express = require('express'), 12 | app = express(); 13 | 14 | module.exports = { 15 | Websocket: Websocket 16 | } 17 | 18 | function Websocket(params) { 19 | 20 | this.log = params.log; 21 | port = params.port; 22 | plugin_name = params.plugin_name; 23 | accessories = params.accessories; 24 | Characteristic = params.Characteristic; 25 | addAccessory = params.addAccessory; 26 | removeAccessory = params.removeAccessory; 27 | getAccessories = params.getAccessories; 28 | 29 | this.ws; 30 | } 31 | 32 | Websocket.prototype.startServer = function() { 33 | 34 | var server = http.createServer(app); 35 | server.listen(port, function() { 36 | this.log("url %j", server.address()); 37 | }.bind(this)); 38 | 39 | var wsServer = new WebSocketServer({server: server}); 40 | 41 | wsServer.on('connection', function(ws, req) { 42 | 43 | this.ws = ws; 44 | 45 | this.ws.on('open', function open() { // no event ? 46 | this.log.debug("on.open"); 47 | }.bind(this)); 48 | 49 | this.ws.on('message', function message(data) { 50 | this.log.debug("on.message: %s", data); 51 | this.onMessage(data); 52 | }.bind(this)); 53 | 54 | this.ws.on('close', function close() { 55 | this.log("on.close client ip %s disconnected", req.connection.remoteAddress); 56 | }.bind(this)); 57 | 58 | this.ws.on('error', function error(e) { 59 | this.log.error("on.error %s", e.message); 60 | }.bind(this)) 61 | 62 | set_timeout = setTimeout(function() { 63 | this.log("client ip %s connected", req.connection.remoteAddress); 64 | }.bind(this), 500); 65 | 66 | }.bind(this)); 67 | } 68 | 69 | Websocket.prototype.onMessage = function(data) { 70 | 71 | var msg = JSON.parse(data); 72 | var topic = msg.topic; 73 | var accessory = msg.payload; 74 | var result = {}; 75 | 76 | switch (topic) { 77 | case "add": 78 | case "addAccessory": 79 | this.log.debug("onMessage add %s", JSON.stringify(accessory, null, 2)); 80 | addAccessory(accessory); 81 | break; 82 | 83 | case "remove": 84 | case "removeAccessory": 85 | removeAccessory(accessory.name); 86 | break; 87 | 88 | case "set": 89 | case "setValue": 90 | //this.log.debug("onMessage setValue %s", JSON.stringify(accessory)); 91 | this.log.debug("setValue %s", JSON.stringify(accessory)); 92 | result = this.validate(accessory); 93 | 94 | if (result.isValid) { 95 | accessories[accessory.name].save_and_setValue("websocket", accessory.characteristic, result.value); 96 | } else { 97 | this.log.warn("setValue %s", result.message); 98 | this.sendAck(false, result.message); 99 | } 100 | break; 101 | 102 | case "callback": 103 | this.log.debug("callback %s", JSON.stringify(accessory)); 104 | 105 | result = this.validate(accessory); 106 | 107 | if (result.isValid) { 108 | accessories[accessory.name].saveValue(accessory.characteristic, result.value); 109 | } else { 110 | this.log.error("onMessage %s", result.message); 111 | this.sendAck(false, result.message); 112 | } 113 | break; 114 | 115 | case "getAccessories": 116 | case "getAccessory": 117 | case "get": 118 | var name; 119 | this.log.debug("onMessage get %s", JSON.stringify(accessory)); 120 | 121 | if (typeof(accessory.name) !== "undefined") { 122 | name = accessory.name; 123 | } else { 124 | name = "all"; 125 | } 126 | 127 | if (typeof(accessories[name]) !== "undefined" || name === "all") { 128 | getAccessories(name); 129 | } else { 130 | var message = "name '" + name + "' undefined."; 131 | this.log.warn("onMessage.get %s", message); 132 | this.sendAck(false, message); 133 | } 134 | break; 135 | 136 | default: 137 | var message = "topic '" + topic + "' unknown."; 138 | this.log.warn("onMessage topic %s", message); 139 | this.sendAck(false, message); 140 | } 141 | } 142 | 143 | Websocket.prototype.validate = function(accessory) { 144 | 145 | var name = accessory.name; 146 | var c = accessory.characteristic; 147 | var value = accessory.value; 148 | 149 | var isValid = false; 150 | var message = ""; 151 | 152 | if(typeof(accessories[name]) === "undefined") { 153 | message = "name '" + name + "' undefined."; 154 | } else if (typeof(Characteristic[c]) !== "function") { 155 | message = "characteristic '" + c + "' undefined."; 156 | } else if (typeof(accessory.value) === "undefined" || accessory.value === null) { 157 | message = "name '" + name + "' value undefined."; 158 | } else if (typeof(accessories[name].service.getCharacteristic(Characteristic[c])) === "undefined"){ 159 | message = "name '" + name + "' characteristic do not match."; 160 | } else { 161 | var result = {}; 162 | result = accessories[name].parseValue(c, value); 163 | isValid = result.isValid; 164 | value = result.value; 165 | if (!isValid) { 166 | message = "value '" + value + "' outside range"; 167 | } else { 168 | message = "name '" + name + "' is valid."; 169 | } 170 | } 171 | 172 | return {isValid: isValid, message: message, value: value}; 173 | } 174 | 175 | Websocket.prototype.get = function(name, c, callback) { 176 | // callback not used 177 | 178 | // this.log.debug("get %s %s", name, c); 179 | 180 | if (typeof(this.ws) !== "undefined" && this.ws.OPEN) { 181 | var data = {"topic": "get", "payload": {"name": name, "characteristic": c}}; 182 | this.sendData(data); 183 | } else { 184 | this.log.debug("get client disconnected."); 185 | } 186 | } 187 | 188 | Websocket.prototype.set = function(name, c, value, callback) { 189 | 190 | if (typeof(this.ws) !== "undefined" && this.ws.OPEN) { 191 | 192 | if (c === "On") { 193 | value = (value == 0 || value == false) ? false : true; 194 | } 195 | 196 | var data = {"topic": "set", "payload": {"name": name, "characteristic": c, "value": value}}; 197 | 198 | switch (c) { 199 | case "Brightness": 200 | case "TargetPosition": 201 | case "TargetHorizontalTiltAngle": 202 | case "TargetVerticalTiltAngle": 203 | case "TargetRelativeHumidity": 204 | case "TargetTemperature": 205 | if (set_timeout && name === pre_name && c === pre_c) { 206 | clearTimeout(set_timeout); 207 | } 208 | set_timeout = setTimeout(function() { 209 | this.log.debug("set %s %s %s", name, c, value); 210 | this.sendData(data); 211 | }.bind(this), 300); 212 | pre_name = name; 213 | pre_c = c; 214 | break; 215 | 216 | default: 217 | this.log.debug("set %s %s %s", name, c, value); 218 | this.sendData(data); 219 | } 220 | callback(); // todo error handling 221 | } else { 222 | this.log.debug("get client disconnected."); 223 | callback("disconnected"); 224 | } 225 | } 226 | 227 | Websocket.prototype.sendAccessories = function (accessories) { 228 | 229 | if (typeof(this.ws) !== "undefined" && this.ws.OPEN) { 230 | var data = {"topic": "accessories", "payload": accessories}; 231 | this.sendData(data); 232 | } else { 233 | this.log.error("sendAck client disconnected."); 234 | } 235 | } 236 | 237 | Websocket.prototype.sendAck = function (ack, message) { 238 | 239 | if (typeof(this.ws) !== "undefined" && this.ws.OPEN) { 240 | var data = {"topic":"response", "payload": {"ack": ack, "message": message}}; 241 | this.sendData(data); 242 | } else { 243 | this.log.error("sendAck client disconnected."); 244 | } 245 | } 246 | 247 | Websocket.prototype.sendData = function(data) { 248 | 249 | if (typeof(this.ws) !== "undefined" && this.ws.OPEN) { 250 | var j_data = JSON.stringify(data); 251 | 252 | this.log.debug("sendData %s", JSON.stringify(data)); // JSON.stringify(data, null, 2)); 253 | 254 | this.ws.send(j_data, function ack(error) { 255 | if (error) this.log("sendData %s", error); 256 | }.bind(this)); 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "homebridge-websocket", 3 | "version": "0.2.2", 4 | "description": "Websocket Plugin for Homebridge", 5 | "license": "ISC", 6 | "author": { 7 | "name": "flurin" 8 | }, 9 | "keywords": [ 10 | "homebridge", 11 | "homebridge-plugin", 12 | "homekit", 13 | "siri", 14 | "websocket", 15 | "node-RED" 16 | ], 17 | "repository": { 18 | "type": "git", 19 | "url": "https://github.com/cflurin/homebridge-websocket.git" 20 | }, 21 | "bugs": { 22 | "url": "http://github.com/cflurin/homebridge-websocket/issues" 23 | }, 24 | "engines": { 25 | "node": ">=4.3.2", 26 | "homebridge": ">=0.4.6" 27 | }, 28 | "dependencies": { 29 | "request": "^2.65.0", 30 | "express": "^4.13.3", 31 | "ws": "^6.1.2" 32 | } 33 | } 34 | --------------------------------------------------------------------------------