├── ExecQueue.js ├── LICENSE ├── README.md ├── config.schema.json ├── index.js └── package.json /ExecQueue.js: -------------------------------------------------------------------------------- 1 | const { exec } = require("child_process"); 2 | 3 | const ExecQueue = function() { 4 | this.buffer = []; 5 | this.isRunning = false; 6 | } 7 | 8 | ExecQueue.prototype.add = function(cmd, arg1, arg2) { 9 | if (typeof arg1 === "function") { 10 | this.buffer.push({ cmd, callback: arg1 }); 11 | } else if (typeof arg2 === "function") { 12 | this.buffer.push({ cmd, options: arg1, callback: arg2 }); 13 | } 14 | if (!this.isRunning) { 15 | this.process(); 16 | } 17 | } 18 | 19 | ExecQueue.prototype.process = function() { 20 | if (this.buffer.length) { 21 | const self = this; 22 | const { cmd, options, callback } = this.buffer.shift(); 23 | this.isRunning = true; 24 | exec(cmd, options, function(){ 25 | callback.apply(null, arguments); 26 | self.process(); 27 | }); 28 | } else { 29 | this.isRunning = false; 30 | } 31 | } 32 | 33 | module.exports = ExecQueue; 34 | -------------------------------------------------------------------------------- /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-cmdswitch2 [![npm version](https://badge.fury.io/js/homebridge-cmdswitch2.svg)](https://badge.fury.io/js/homebridge-cmdswitch2) 2 | CMD Plugin for [HomeBridge](https://github.com/nfarina/homebridge) (API 2.0) 3 | 4 | Older version using API 1.0: [homebridge-cmdswitch](https://github.com/luisiam/homebridge-cmdswitch) (deprecated) 5 | 6 | ### Switching from homebridge-cmdswitch (API 1.0) 7 | Users switching from homebridge-cmdswitch will need to remove their old config in `config.json` and use the new config. Hence, switch will show up as brand new device. This is due to the fact that API 2.0 only supports platform plugins and homebridge-cmdswitch was implemented as an accessory plugin. This means any configurations, alarms, scenes, etc to which the switch was associated will need to be updated with the new switch device. 8 | 9 | ### What this plugin does 10 | This plugin allows you to run Command Line Interface (CLI) commands via HomeKit. This means you can run a simple commands such as `ping`, `shutdown`, or `wakeonlan` just by telling Siri to do so. An example usage for this plugin would be to turn on your PS4 or HTPC, check if it’s on, and even shut it down when finished. 11 | 12 | ### How this plugin works 13 | 1. `on_cmd`: This is the command issued when the switch is turned ON. 14 | 2. `off_cmd`: This is the command issued when the switch is turned OFF. 15 | 3. `state_cmd`: This is the command issued when HomeBridge checks the state of the switch. 16 | 1. If there is no error, HomeBridge is notified that the switch is ON. 17 | 2. If there is an error, HomeBridge is notified that the switch is OFF. 18 | 19 | ### Things to know about this plugin 20 | This plugin can only run CLI commands the same as you typing them yourself. In order to test if your `on_cmd`, `off_cmd`, or `state_cmd` are valid commands you need to run them from your CLI. Please keep in mind you will want to run these commands from the same user that runs (or owns) the HomeBridge service if different than your root user. 21 | 22 | # Installation 23 | 1. Install homebridge using `npm install -g homebridge`. 24 | 2. Install this plugin using `npm install -g homebridge-cmdswitch2`. 25 | 3. Update your configuration file. See configuration sample below. 26 | 27 | # Configuration 28 | Edit your `config.json` accordingly. Configuration sample: 29 | ``` 30 | "platforms": [{ 31 | "platform": "cmdSwitch2" 32 | }] 33 | ``` 34 | 35 | ### Advanced Configuration (Optional) 36 | This step is not required. HomeBridge with API 2.0 can handle configurations in the HomeKit app. 37 | ``` 38 | "platforms": [{ 39 | "platform": "cmdSwitch2", 40 | "name": "CMD Switch", 41 | "synchronous": true, 42 | "switches": [{ 43 | "name" : "HTPC", 44 | "on_cmd": "wakeonlan XX:XX:XX:XX:XX:XX", 45 | "off_cmd": "net rpc shutdown -I XXX.XXX.XXX.XXX -U user%password", 46 | "state_cmd": "ping -c 2 -W 1 XXX.XXX.XXX.XXX | grep -i '2 received'" 47 | }, { 48 | "name" : "Playstation 4", 49 | "on_cmd": "ps4-waker", 50 | "off_cmd": "ps4-waker standby", 51 | "state_cmd": "ps4-waker search | grep -i '200 Ok'", 52 | "polling": true, 53 | "interval": 5, 54 | "timeout": 2000, 55 | "manufacturer": "Sony Corporation", 56 | "model": "CUH-1001A", 57 | "serial": "XXXXXXXXXXX" 58 | }, { 59 | "name" : "My Dimmer", 60 | "on_cmd": "set-light on", 61 | "off_cmd": "set-light off", 62 | "state_cmd": "get-light dim | grep -E '\d+'", 63 | "dim_cmd": "set-light dim $HB_BRIGHTNESS", 64 | "manufacturer": "Custom dimmer" 65 | }] 66 | }] 67 | ``` 68 | 69 | 70 | | Fields | Description | Required | 71 | |--------------------|-------------------------------------------------------|----------| 72 | | platform | Must always be `cmdSwitch2`. | Yes | 73 | | name | For logging purposes. | No | 74 | | synchronous | No parallell execution. | No | 75 | | switches | Array of switch config (multiple switches supported). | Yes | 76 | | \|- name\* | Name of your device. | Yes | 77 | | \|- on_cmd | Command to turn on your device. | No | 78 | | \|- off_cmd | Command to turn off your device. | No | 79 | | \|- state_cmd | Command to detect an ON state of your device. Should return a number if used as state for dim_cmd | No | 80 | | \|- dim_cmd\*\* | Command to detect an ON state of your device. | No | 81 | | \|- polling | State polling (Default false). | No | 82 | | \|- interval | Polling interval in `s` (Default 1s). | No | 83 | | \|- timeout\*\*\* | Commands execution timeout in `s` (Default 1s). | No | 84 | | \|- manufacturer | Manufacturer of your device. | No | 85 | | \|- model | Model of your device. | No | 86 | | \|- serial | Serial number of your device. | No | 87 | 88 | \*Changing the switch `name` in `config.json` will create a new switch instead of renaming the existing one in HomeKit. It's strongly recommended that you rename the switch using a HomeKit app only. 89 | 90 | \*\*Adding/removing this command will change accessory type form Light Bulb to Switch. 91 | 92 | \*\*\*Command execution is assumed 'Successful' if timeout occures. 93 | -------------------------------------------------------------------------------- /config.schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "pluginAlias": "cmdSwitch2", 3 | "pluginType": "platform", 4 | "footerDisplay": "For help please see the [README](https://github.com/luisiam/homebridge-cmdswitch2).", 5 | "schema": { 6 | "name": { 7 | "title": "Name", 8 | "type": "string", 9 | "default": "homebridge-cmdswitch2", 10 | "required": false 11 | }, 12 | "switches": { 13 | "type": "array", 14 | "items": { 15 | "title": "Switch Config", 16 | "type": "object", 17 | "properties": { 18 | "name":{ 19 | "title": "Name", 20 | "type": "string", 21 | "required": true 22 | }, 23 | "on_cmd":{ 24 | "title": "On Command", 25 | "type": "string", 26 | "required": false 27 | }, 28 | "off_cmd":{ 29 | "title": "Off Command", 30 | "type": "string", 31 | "required": false 32 | }, 33 | "state_cmd":{ 34 | "title": "State Command", 35 | "type": "string", 36 | "required": false 37 | }, 38 | "polling":{ 39 | "title": "Polling?", 40 | "type": "boolean", 41 | "required": false 42 | }, 43 | "interval":{ 44 | "title": "Poll interval (s)", 45 | "type": "number", 46 | "required": false 47 | }, 48 | "timeout":{ 49 | "title": "Poll timout (s)", 50 | "type": "number", 51 | "required": false 52 | }, 53 | "manufacturer":{ 54 | "title": "Manufacturer", 55 | "type": "string", 56 | "required": false 57 | }, 58 | "model":{ 59 | "title": "Model", 60 | "type": "string", 61 | "required": false 62 | }, 63 | "serial":{ 64 | "title": "Serial", 65 | "type": "string", 66 | "required": false 67 | } 68 | } 69 | } 70 | } 71 | }, 72 | "form": [ 73 | "name", 74 | { 75 | "key":"switches", 76 | "items":[ 77 | "switches[].name", 78 | "switches[].on_cmd", 79 | "switches[].off_cmd", 80 | "switches[].state_cmd", 81 | "switches[].polling", 82 | "switches[].interval", 83 | "switches[].timeout", 84 | "switches[].manufacturer", 85 | "switches[].model", 86 | "switches[].serial" 87 | ] 88 | } 89 | ] 90 | } 91 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const { exec } = require("child_process"); 2 | const ExecQueue = require('./ExecQueue'); 3 | var Accessory, Service, Characteristic, UUIDGen; 4 | 5 | const execQueue = new ExecQueue(); 6 | 7 | module.exports = function (homebridge) { 8 | Accessory = homebridge.platformAccessory; 9 | Service = homebridge.hap.Service; 10 | Characteristic = homebridge.hap.Characteristic; 11 | UUIDGen = homebridge.hap.uuid; 12 | 13 | homebridge.registerPlatform("homebridge-cmdswitch2", "cmdSwitch2", cmdSwitchPlatform, true); 14 | } 15 | 16 | function cmdSwitchPlatform(log, config, api) { 17 | this.log = log; 18 | this.config = config || {"platform": "cmdSwitch2"}; 19 | this.switches = this.config.switches || []; 20 | const { synchronous = false } = this.config; 21 | if (synchronous) { 22 | this.exec = function() {execQueue.add.apply(execQueue, arguments)} 23 | } else { 24 | this.exec = exec; 25 | } 26 | 27 | this.accessories = {}; 28 | this.polling = {}; 29 | 30 | if (api) { 31 | this.api = api; 32 | this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this)); 33 | } 34 | } 35 | 36 | // Method to restore accessories from cache 37 | cmdSwitchPlatform.prototype.configureAccessory = function (accessory) { 38 | this.setService(accessory); 39 | this.accessories[accessory.context.name] = accessory; 40 | } 41 | 42 | // Method to setup accesories from config.json 43 | cmdSwitchPlatform.prototype.didFinishLaunching = function () { 44 | // Add or update accessories defined in config.json 45 | for (var i in this.switches) this.addAccessory(this.switches[i]); 46 | 47 | // Remove extra accessories in cache 48 | for (var name in this.accessories) { 49 | var accessory = this.accessories[name]; 50 | if (!accessory.reachable) this.removeAccessory(accessory); 51 | } 52 | } 53 | 54 | // Method to add and update HomeKit accessories 55 | cmdSwitchPlatform.prototype.addAccessory = function (data) { 56 | this.log("Initializing platform accessory '" + data.name + "'..."); 57 | 58 | // Retrieve accessory from cache 59 | var accessory = this.accessories[data.name]; 60 | 61 | if (accessory) { 62 | const isLightbulb = !!accessory.getService(Service.Lightbulb); 63 | const isUpdated = !!data.dim_cmd !== isLightbulb; 64 | if (isUpdated) { 65 | this.log(`${accessory.context.name} has changed.`); 66 | this.removeAccessory(accessory); 67 | accessory = undefined; 68 | } 69 | } 70 | 71 | if (!accessory) { 72 | var uuid = UUIDGen.generate(data.name); 73 | const { dim_cmd } = data; 74 | if (dim_cmd) { 75 | // Setup accessory as LIGHTBULB (5) category. 76 | accessory = new Accessory(data.name, uuid, 5); 77 | // Setup HomeKit switch service 78 | accessory.addService(Service.Lightbulb, data.name); 79 | } else { 80 | // Setup accessory as SWITCH (8) category. 81 | accessory = new Accessory(data.name, uuid, 8); 82 | // Setup HomeKit switch service 83 | accessory.addService(Service.Switch, data.name); 84 | } 85 | 86 | // New accessory is always reachable 87 | accessory.reachable = true; 88 | 89 | // Setup listeners for different switch events 90 | this.setService(accessory); 91 | 92 | // Register new accessory in HomeKit 93 | this.api.registerPlatformAccessories("homebridge-cmdswitch2", "cmdSwitch2", [accessory]); 94 | 95 | // Store accessory in cache 96 | this.accessories[data.name] = accessory; 97 | } 98 | 99 | // Confirm variable type 100 | data.polling = data.polling === true; 101 | data.interval = parseInt(data.interval, 10) || 1; 102 | data.timeout = parseInt(data.timeout, 10) || 1; 103 | if (data.manufacturer) data.manufacturer = data.manufacturer.toString(); 104 | if (data.model) data.model = data.model.toString(); 105 | if (data.serial) data.serial = data.serial.toString(); 106 | 107 | // Store and initialize variables into context 108 | var cache = accessory.context; 109 | cache.name = data.name; 110 | cache.on_cmd = data.on_cmd; 111 | cache.off_cmd = data.off_cmd; 112 | cache.dim_cmd = data.dim_cmd; 113 | cache.state_cmd = data.state_cmd; 114 | cache.polling = data.polling; 115 | cache.interval = data.interval; 116 | cache.timeout = data.timeout; 117 | cache.manufacturer = data.manufacturer; 118 | cache.model = data.model; 119 | cache.serial = data.serial; 120 | cache.brightness = data.brightness || 0; 121 | if (cache.state === undefined) { 122 | cache.state = false; 123 | if (data.off_cmd && !data.on_cmd) cache.state = true; 124 | } 125 | 126 | // Retrieve initial state 127 | this.getInitState(accessory); 128 | 129 | // Configure state polling 130 | if (data.polling && data.state_cmd) this.statePolling(data.name); 131 | } 132 | 133 | // Method to remove accessories from HomeKit 134 | cmdSwitchPlatform.prototype.removeAccessory = function (accessory) { 135 | if (accessory) { 136 | var name = accessory.context.name; 137 | this.log(name + " is removed from HomeBridge."); 138 | this.api.unregisterPlatformAccessories("homebridge-cmdswitch2", "cmdSwitch2", [accessory]); 139 | delete this.accessories[name]; 140 | } 141 | } 142 | 143 | // Method to setup listeners for different events 144 | cmdSwitchPlatform.prototype.setService = function (accessory) { 145 | const isLightbulb = !!accessory.getService(Service.Lightbulb); 146 | if (isLightbulb) { 147 | accessory.getService(Service.Lightbulb) 148 | .getCharacteristic(Characteristic.On) 149 | .on('get', this.getPowerState.bind(this, accessory.context)) 150 | .on('set', this.setBrightness.bind(this, accessory.context)); 151 | 152 | accessory.getService(Service.Lightbulb) 153 | .getCharacteristic(Characteristic.Brightness) 154 | .on('get', this.getBrightness.bind(this, accessory.context)) 155 | .on('set', this.setBrightness.bind(this, accessory.context)); 156 | } else { 157 | accessory.getService(Service.Switch) 158 | .getCharacteristic(Characteristic.On) 159 | .on('get', this.getPowerState.bind(this, accessory.context)) 160 | .on('set', this.setPowerState.bind(this, accessory.context)); 161 | } 162 | 163 | accessory.on('identify', this.identify.bind(this, accessory.context)); 164 | } 165 | 166 | // Method to retrieve initial state 167 | cmdSwitchPlatform.prototype.getInitState = function (accessory) { 168 | var manufacturer = accessory.context.manufacturer || "Default-Manufacturer"; 169 | var model = accessory.context.model || "Default-Model"; 170 | var serial = accessory.context.serial || "Default-SerialNumber"; 171 | 172 | const isLightbulb = !!accessory.getService(Service.Lightbulb); 173 | 174 | // Update HomeKit accessory information 175 | accessory.getService(Service.AccessoryInformation) 176 | .setCharacteristic(Characteristic.Manufacturer, manufacturer) 177 | .setCharacteristic(Characteristic.Model, model) 178 | .setCharacteristic(Characteristic.SerialNumber, serial); 179 | 180 | // Retrieve initial state if polling is disabled 181 | if (!accessory.context.polling) { 182 | if (isLightbulb) { 183 | accessory.getService(Service.Lightbulb) 184 | .getCharacteristic(Characteristic.Brightness) 185 | .getValue(); 186 | } else { 187 | accessory.getService(Service.Switch) 188 | .getCharacteristic(Characteristic.On) 189 | .getValue(); 190 | } 191 | } 192 | 193 | // Configured accessory is reachable 194 | accessory.updateReachability(true); 195 | } 196 | 197 | // Method to determine current state 198 | cmdSwitchPlatform.prototype.getState = function (thisSwitch, callback) { 199 | var self = this; 200 | 201 | // Return cached state if no state_cmd provided 202 | if (thisSwitch.state_cmd === undefined) { 203 | callback(null, thisSwitch.state); 204 | return; 205 | } 206 | 207 | // Execute command to detect state 208 | this.exec(thisSwitch.state_cmd, function (error, stdout, stderr) { 209 | var state = error ? false : true; 210 | 211 | // Error detection 212 | if (stderr) { 213 | self.log("Failed to determine " + thisSwitch.name + " state."); 214 | self.log(stderr); 215 | } 216 | 217 | callback(stderr, state); 218 | }); 219 | } 220 | 221 | // Method to determine current state 222 | cmdSwitchPlatform.prototype.statePolling = function (name) { 223 | var accessory = this.accessories[name]; 224 | var thisSwitch = accessory.context; 225 | 226 | // Clear polling 227 | clearTimeout(this.polling[name]); 228 | 229 | this.getState(thisSwitch, function (error, state) { 230 | // Update state if there's no error 231 | if (!error && state !== thisSwitch.state) { 232 | thisSwitch.state = state; 233 | accessory.getService(Service.Switch) 234 | .getCharacteristic(Characteristic.On) 235 | .getValue(); 236 | } 237 | }); 238 | 239 | // Setup for next polling 240 | this.polling[name] = setTimeout(this.statePolling.bind(this, name), thisSwitch.interval * 1000); 241 | } 242 | 243 | // Method to determine current state 244 | cmdSwitchPlatform.prototype.getPowerState = function (thisSwitch, callback) { 245 | var self = this; 246 | 247 | if (thisSwitch.polling) { 248 | // Get state directly from cache if polling is enabled 249 | this.log(thisSwitch.name + " is " + (thisSwitch.state ? "on." : "off.")); 250 | callback(null, thisSwitch.state); 251 | } else { 252 | // Check state if polling is disabled 253 | this.getState(thisSwitch, function (error, state) { 254 | // Update state if command exists 255 | if (thisSwitch.state_cmd) thisSwitch.state = state; 256 | if (!error) self.log(thisSwitch.name + " is " + (thisSwitch.state ? "on." : "off.")); 257 | callback(error, thisSwitch.state); 258 | }); 259 | } 260 | } 261 | 262 | // Method to determine current state 263 | cmdSwitchPlatform.prototype.getBrightness = function (thisSwitch, callback) { 264 | this.exec(thisSwitch.state_cmd, function (error, stdout, stderr) { 265 | const matches = stdout.toString().match(/\d+/g) || []; 266 | if (matches.length > 0) { 267 | const [dimValue] = matches; 268 | const value = parseInt(dimValue, 10); 269 | thisSwitch.brightness = value; 270 | callback(stderr, value); 271 | } else { 272 | callback(stderr, thisSwitch.brightness); 273 | } 274 | }); 275 | } 276 | 277 | cmdSwitchPlatform.prototype.setBrightness = function (thisSwitch, brightness, callback) { 278 | const self = this; 279 | const didTurnOn = typeof brightness === 'boolean' && !!brightness && !thisSwitch.state; 280 | const didTurnOff = typeof brightness === 'boolean' && !brightness; 281 | let newBrightness; 282 | if (didTurnOff) { 283 | this.setPowerState(thisSwitch, false, callback); 284 | return; 285 | } else if (didTurnOn) { 286 | thisSwitch.state = true; 287 | newBrightness = thisSwitch.brightness; 288 | } else if (typeof brightness !== 'boolean'){ 289 | newBrightness = brightness; 290 | } else { 291 | callback(); 292 | return; 293 | } 294 | thisSwitch.brightness = newBrightness; 295 | this.exec(thisSwitch.dim_cmd, {env: {HB_BRIGHTNESS: thisSwitch.brightness}}, function (error, stdout, stderr) { 296 | self.log(`${thisSwitch.name} dimmed to ${thisSwitch.brightness}`); 297 | callback(error); 298 | }); 299 | } 300 | 301 | // Method to set state 302 | cmdSwitchPlatform.prototype.setPowerState = function (thisSwitch, state, callback) { 303 | var self = this; 304 | 305 | var cmd = state ? thisSwitch.on_cmd : thisSwitch.off_cmd; 306 | var notCmd = state ? thisSwitch.off_cmd : thisSwitch.on_cmd; 307 | var tout = null; 308 | 309 | // Execute command to set state 310 | this.exec(cmd, function (error, stdout, stderr) { 311 | // Error detection 312 | if (error && (state !== thisSwitch.state)) { 313 | self.log("Failed to turn " + (state ? "on " : "off ") + thisSwitch.name); 314 | self.log(stderr); 315 | } else { 316 | if (cmd) self.log(thisSwitch.name + " is turned " + (state ? "on." : "off.")); 317 | thisSwitch.state = state; 318 | error = null; 319 | } 320 | 321 | // Restore switch after 1s if only one command exists 322 | if (!notCmd && !thisSwitch.state_cmd) { 323 | setTimeout(function () { 324 | self.accessories[thisSwitch.name].getService(Service.Switch) 325 | .setCharacteristic(Characteristic.On, !state); 326 | }, 1000); 327 | } 328 | 329 | if (tout) { 330 | clearTimeout(tout); 331 | callback(error); 332 | } 333 | }); 334 | 335 | // Allow 1s to set state but otherwise assumes success 336 | tout = setTimeout(function () { 337 | tout = null; 338 | self.log("Turning " + (state ? "on " : "off ") + thisSwitch.name + " took too long [" + thisSwitch.timeout + "s], assuming success." ); 339 | callback(); 340 | }, thisSwitch.timeout * 1000); 341 | } 342 | 343 | // Method to handle identify request 344 | cmdSwitchPlatform.prototype.identify = function (thisSwitch, paired, callback) { 345 | this.log(thisSwitch.name + " identify requested!"); 346 | callback(); 347 | } 348 | 349 | // Method to handle plugin configuration in HomeKit app 350 | cmdSwitchPlatform.prototype.configurationRequestHandler = function (context, request, callback) { 351 | if (request && request.type === "Terminate") { 352 | return; 353 | } 354 | 355 | // Instruction 356 | if (!context.step) { 357 | var instructionResp = { 358 | "type": "Interface", 359 | "interface": "instruction", 360 | "title": "Before You Start...", 361 | "detail": "Please make sure homebridge is running with elevated privileges.", 362 | "showNextButton": true 363 | } 364 | 365 | context.step = 1; 366 | callback(instructionResp); 367 | } else { 368 | switch (context.step) { 369 | case 1: 370 | // Operation choices 371 | var respDict = { 372 | "type": "Interface", 373 | "interface": "list", 374 | "title": "What do you want to do?", 375 | "items": [ 376 | "Add New Switch", 377 | "Modify Existing Switch", 378 | "Remove Existing Switch" 379 | ] 380 | } 381 | 382 | context.step = 2; 383 | callback(respDict); 384 | break; 385 | case 2: 386 | var selection = request.response.selections[0]; 387 | if (selection === 0) { 388 | // Info for new accessory 389 | var respDict = { 390 | "type": "Interface", 391 | "interface": "input", 392 | "title": "New Switch", 393 | "items": [{ 394 | "id": "name", 395 | "title": "Name (Required)", 396 | "placeholder": "HTPC" 397 | }] 398 | }; 399 | 400 | context.operation = 0; 401 | context.step = 3; 402 | callback(respDict); 403 | } else { 404 | var names = Object.keys(this.accessories); 405 | 406 | if (names.length > 0) { 407 | // Select existing accessory for modification or removal 408 | if (selection === 1) { 409 | var title = "Witch switch do you want to modify?"; 410 | context.operation = 1; 411 | context.step = 3; 412 | } else { 413 | var title = "Witch switch do you want to remove?"; 414 | context.step = 5; 415 | } 416 | 417 | var respDict = { 418 | "type": "Interface", 419 | "interface": "list", 420 | "title": title, 421 | "items": names 422 | }; 423 | 424 | context.list = names; 425 | } else { 426 | // Error if not switch is configured 427 | var respDict = { 428 | "type": "Interface", 429 | "interface": "instruction", 430 | "title": "Unavailable", 431 | "detail": "No switch is configured.", 432 | "showNextButton": true 433 | }; 434 | 435 | context.step = 1; 436 | } 437 | callback(respDict); 438 | } 439 | break; 440 | case 3: 441 | if (context.operation === 0) { 442 | var data = request.response.inputs; 443 | } else if (context.operation === 1) { 444 | var selection = context.list[request.response.selections[0]]; 445 | var data = this.accessories[selection].context; 446 | } 447 | 448 | if (data.name) { 449 | // Add/Modify info of selected accessory 450 | var respDict = { 451 | "type": "Interface", 452 | "interface": "input", 453 | "title": data.name, 454 | "items": [{ 455 | "id": "on_cmd", 456 | "title": "CMD to Turn On", 457 | "placeholder": context.operation ? "Leave blank if unchanged" : "wakeonlan XX:XX:XX:XX:XX:XX" 458 | }, { 459 | "id": "off_cmd", 460 | "title": "CMD to Turn Off", 461 | "placeholder": context.operation ? "Leave blank if unchanged" : "net rpc shutdown -I XXX.XXX.XXX.XXX -U user%password" 462 | }, { 463 | "id": "state_cmd", 464 | "title": "CMD to Check ON State", 465 | "placeholder": context.operation ? "Leave blank if unchanged" : "ping -c 2 -W 1 XXX.XXX.XXX.XXX | grep -i '2 received'" 466 | }, { 467 | "id": "polling", 468 | "title": "Enable Polling (true/false)", 469 | "placeholder": context.operation ? "Leave blank if unchanged" : "false" 470 | }, { 471 | "id": "interval", 472 | "title": "Polling Interval (s)", 473 | "placeholder": context.operation ? "Leave blank if unchanged" : "1" 474 | }, 475 | { 476 | "id": "timeout", 477 | "title": "On/Off command execution timeout (s)", 478 | "placeholder": context.operation ? "Leave blank if unchanged" : "1" 479 | }, { 480 | "id": "manufacturer", 481 | "title": "Manufacturer", 482 | "placeholder": context.operation ? "Leave blank if unchanged" : "Default-Manufacturer" 483 | }, { 484 | "id": "model", 485 | "title": "Model", 486 | "placeholder": context.operation ? "Leave blank if unchanged" : "Default-Model" 487 | }, { 488 | "id": "serial", 489 | "title": "Serial", 490 | "placeholder": context.operation ? "Leave blank if unchanged" : "Default-SerialNumber" 491 | }] 492 | }; 493 | 494 | context.name = data.name; 495 | context.step = 4; 496 | } else { 497 | // Error if required info is missing 498 | var respDict = { 499 | "type": "Interface", 500 | "interface": "instruction", 501 | "title": "Error", 502 | "detail": "Name of the switch is missing.", 503 | "showNextButton": true 504 | }; 505 | 506 | context.step = 1; 507 | } 508 | 509 | delete context.list; 510 | delete context.operation; 511 | callback(respDict); 512 | break; 513 | case 4: 514 | var userInputs = request.response.inputs; 515 | var newSwitch = {}; 516 | 517 | // Clone context if switch exists 518 | if (this.accessories[context.name]) { 519 | newSwitch = JSON.parse(JSON.stringify(this.accessories[context.name].context)); 520 | } 521 | 522 | // Setup input for addAccessory 523 | newSwitch.name = context.name; 524 | newSwitch.on_cmd = userInputs.on_cmd || newSwitch.on_cmd; 525 | newSwitch.off_cmd = userInputs.off_cmd || newSwitch.off_cmd; 526 | newSwitch.state_cmd = userInputs.state_cmd || newSwitch.state_cmd; 527 | newSwitch.dim_cmd = userInputs.dim_cmd || newSwitch.dim_cmd; 528 | if (userInputs.polling.toUpperCase() === "TRUE") { 529 | newSwitch.polling = true; 530 | } else if (userInputs.polling.toUpperCase() === "FALSE") { 531 | newSwitch.polling = false; 532 | } 533 | newSwitch.interval = userInputs.interval || newSwitch.interval; 534 | newSwitch.timeout = userInputs.timeout || newSwitch.timeout; 535 | newSwitch.manufacturer = userInputs.manufacturer; 536 | newSwitch.model = userInputs.model; 537 | newSwitch.serial = userInputs.serial; 538 | 539 | // Register or update accessory in HomeKit 540 | this.addAccessory(newSwitch); 541 | var respDict = { 542 | "type": "Interface", 543 | "interface": "instruction", 544 | "title": "Success", 545 | "detail": "The new switch is now updated.", 546 | "showNextButton": true 547 | }; 548 | 549 | context.step = 6; 550 | callback(respDict); 551 | break; 552 | case 5: 553 | // Remove selected accessory from HomeKit 554 | var selection = context.list[request.response.selections[0]]; 555 | var accessory = this.accessories[selection]; 556 | 557 | this.removeAccessory(accessory); 558 | var respDict = { 559 | "type": "Interface", 560 | "interface": "instruction", 561 | "title": "Success", 562 | "detail": "The switch is now removed.", 563 | "showNextButton": true 564 | }; 565 | 566 | delete context.list; 567 | context.step = 6; 568 | callback(respDict); 569 | break; 570 | case 6: 571 | // Update config.json accordingly 572 | var self = this; 573 | delete context.step; 574 | var newConfig = this.config; 575 | 576 | // Create config for each switch 577 | var newSwitches = Object.keys(this.accessories).map(function (k) { 578 | var accessory = self.accessories[k]; 579 | var data = { 580 | 'name': accessory.context.name, 581 | 'on_cmd': accessory.context.on_cmd, 582 | 'off_cmd': accessory.context.off_cmd, 583 | 'state_cmd': accessory.context.state_cmd, 584 | 'dim_cmd': accessory.context.dim_cmd, 585 | 'brightness': accessory.context.brightness, 586 | 'polling': accessory.context.polling, 587 | 'interval': accessory.context.interval, 588 | 'timeout': accessory.context.timeout, 589 | 'manufacturer': accessory.context.manufacturer, 590 | 'model': accessory.context.model, 591 | 'serial': accessory.context.serial 592 | }; 593 | return data; 594 | }); 595 | 596 | newConfig.switches = newSwitches; 597 | callback(null, "platform", true, newConfig); 598 | break; 599 | } 600 | } 601 | } 602 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "homebridge-cmdswitch2", 3 | "version": "0.2.10", 4 | "description": "CMD plugin for HomeBridge (API 2.0): https://github.com/nfarina/homebridge", 5 | "repository": { 6 | "type": "git", 7 | "url": "git://github.com/luisiam/homebridge-cmdswitch2.git" 8 | }, 9 | "keywords": [ 10 | "homebridge-plugin" 11 | ], 12 | "author": "Luis Iam", 13 | "license": "ISC", 14 | "bugs": { 15 | "url": "https://github.com/luisiam/homebridge-cmdswitch2/issues" 16 | }, 17 | "homepage": "https://github.com/luisiam/homebridge-cmdswitch2#readme", 18 | "engines": { 19 | "node": ">=0.12.0", 20 | "homebridge": ">=0.3.0" 21 | } 22 | } 23 | --------------------------------------------------------------------------------