├── .gitignore ├── src ├── Constants.js ├── Util.js ├── homekit │ ├── accessories │ │ ├── HttpWebHookCarbonDioxideSensorAccessory.js │ │ ├── HttpWebHookSwitchAccessory.js │ │ ├── HttpWebHookPushButtonAccessory.js │ │ ├── HttpWebHookStatelessSwitchAccessory.js │ │ ├── HttpWebHookSecurityAccessory.js │ │ ├── HttpWebHookOutletAccessory.js │ │ ├── HttpWebHookValveAccessory.js │ │ ├── HttpWebHookLightBulbAccessory.js │ │ ├── HttpWebHookLockMechanismAccessory.js │ │ ├── HttpWebHookGarageDoorOpenerAccessory.js │ │ ├── HttpWebHookSensorAccessory.js │ │ ├── HttpWebHookThermostatAccessory.js │ │ ├── HttpWebHookWindowCoveringAccessory.js │ │ └── HttpWebHookFanv2Accessory.js │ └── HttpWebHooksPlatform.js └── Server.js ├── .project ├── package.json ├── index.js ├── CHANGELOG.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | npm-debug.log 2 | node_modules 3 | sampleHttps.js 4 | package-lock.json 5 | .cache 6 | .idea 7 | .DS_Store 8 | -------------------------------------------------------------------------------- /src/Constants.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | DEFAULT_REQUEST_TIMEOUT : 10000, 3 | DEFAULT_PORT : 51828, 4 | DEFAULT_SENSOR_TIMEOUT : 5000, 5 | DEFAULT_CACHE_DIR : "./.node-persist/storage", 6 | DEFAULT_LISTEN_HOST : "0.0.0.0", 7 | COVERS_REQUEST_TIMEOUT : 35000, 8 | CONTEXT_FROM_WEBHOOK : "fromHTTPWebhooks", 9 | CONTEXT_FROM_TIMEOUTCALL : "fromTimeoutCall", 10 | CERT_VERSION : 2, 11 | CERT_DAYS : 365 12 | }; -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | homebridge-http-webhooks 4 | 5 | 6 | 7 | 8 | 9 | com.eclipsesource.jshint.ui.builder 10 | 11 | 12 | 13 | 14 | 15 | org.nodeclipse.ui.NodeNature 16 | org.eclipse.wst.jsdt.core.jsNature 17 | tern.eclipse.ide.core.ternnature 18 | 19 | 20 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "homebridge-http-webhooks", 3 | "version": "0.1.18", 4 | "displayName": "Homebridge Webhooks", 5 | "description": "A http plugin with support of webhooks for Homebridge: https://github.com/nfarina/homebridge", 6 | "license": "GPL-3.0", 7 | "keywords": [ 8 | "homebridge-plugin", 9 | "homebridge", 10 | "plugin", 11 | "http", 12 | "webhook", 13 | "httpwebhooks", 14 | "http-webhooks", 15 | "http webhooks", 16 | "smart", 17 | "homekit", 18 | "siri" 19 | ], 20 | "repository": { 21 | "type": "git", 22 | "url": "git@github.com:benzman81/homebridge-http-webhooks.git" 23 | }, 24 | "bugs": { 25 | "url": "https://github.com/benzman81/homebridge-http-webhooks/issues" 26 | }, 27 | "engines": { 28 | "node": ">=9.11.2", 29 | "homebridge": ">=0.3.0" 30 | }, 31 | "dependencies": { 32 | "http-auth": "^3.2.4", 33 | "node-persist": "2.0.x", 34 | "request": "2.87.x", 35 | "selfsigned": "^1.10.7" 36 | }, 37 | "homepage": "https://github.com/benzman81/homebridge-http-webhooks#readme", 38 | "author": "benzman81" 39 | } 40 | -------------------------------------------------------------------------------- /src/Util.js: -------------------------------------------------------------------------------- 1 | const Constants = require('./Constants'); 2 | 3 | var request = require("request"); 4 | 5 | const callHttpApi = function(log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, rejectUnauthorized, homeKitCallback, context, onSuccessCallback, onFailureCallback, timeout) { 6 | if (urlToCall !== "" && context !== Constants.CONTEXT_FROM_WEBHOOK) { 7 | var theRequest = { 8 | method : urlMethod, 9 | url : urlToCall, 10 | timeout : timeout || Constants.DEFAULT_REQUEST_TIMEOUT, 11 | headers : JSON.parse(urlHeaders), 12 | rejectUnauthorized: rejectUnauthorized 13 | }; 14 | if (urlMethod === "POST" || urlMethod === "PUT" || urlMethod === "PATCH") { 15 | if (urlForm) { 16 | log("Adding Form " + urlForm); 17 | theRequest.form = JSON.parse(urlForm); 18 | } 19 | else if (urlBody) { 20 | log("Adding Body " + urlBody); 21 | theRequest.body = urlBody; 22 | } 23 | } 24 | request(theRequest, (function(err, response, body) { 25 | var statusCode = response && response.statusCode ? response.statusCode : -1; 26 | log("Request to '%s' finished with status code '%s' and body '%s'.", urlToCall, statusCode, body, err); 27 | if (!err && statusCode >= 200 && statusCode < 300) { 28 | if (onSuccessCallback) { 29 | onSuccessCallback(); 30 | } 31 | homeKitCallback(null); 32 | } 33 | else { 34 | if (onFailureCallback) { 35 | onFailureCallback(); 36 | } 37 | homeKitCallback(err || new Error("Request to '" + urlToCall + "' was not succesful.")); 38 | } 39 | }).bind(this)); 40 | } 41 | else { 42 | if (onSuccessCallback) { 43 | onSuccessCallback(); 44 | } 45 | homeKitCallback(null); 46 | } 47 | }; 48 | 49 | module.exports = { 50 | callHttpApi : callHttpApi 51 | }; -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var HttpWebHooksPlatform = require('./src/homekit/HttpWebHooksPlatform'); 2 | var HttpWebHookSensorAccessory = require('./src/homekit/accessories/HttpWebHookSensorAccessory'); 3 | var HttpWebHookSwitchAccessory = require('./src/homekit/accessories/HttpWebHookSwitchAccessory'); 4 | var HttpWebHookPushButtonAccessory = require('./src/homekit/accessories/HttpWebHookPushButtonAccessory'); 5 | var HttpWebHookLightBulbAccessory = require('./src/homekit/accessories/HttpWebHookLightBulbAccessory'); 6 | var HttpWebHookThermostatAccessory = require('./src/homekit/accessories/HttpWebHookThermostatAccessory'); 7 | var HttpWebHookOutletAccessory = require('./src/homekit/accessories/HttpWebHookOutletAccessory'); 8 | var HttpWebHookSecurityAccessory = require('./src/homekit/accessories/HttpWebHookSecurityAccessory'); 9 | var HttpWebHookGarageDoorOpenerAccessory = require('./src/homekit/accessories/HttpWebHookGarageDoorOpenerAccessory'); 10 | var HttpWebHookStatelessSwitchAccessory = require('./src/homekit/accessories/HttpWebHookStatelessSwitchAccessory'); 11 | var HttpWebHookLockMechanismAccessory = require('./src/homekit/accessories/HttpWebHookLockMechanismAccessory'); 12 | var HttpWebHookWindowCoveringAccessory = require('./src/homekit/accessories/HttpWebHookWindowCoveringAccessory'); 13 | var HttpWebHookFanv2Accessory = require('./src/homekit/accessories/HttpWebHookFanv2Accessory'); 14 | var HttpWebHookCarbonDioxideSensoryAccessory = require('./src/homekit/accessories/HttpWebHookCarbonDioxideSensorAccessory'); 15 | var HttpWebHookValveAccessory = require('./src/homekit/accessories/HttpWebHookValveAccessory'); 16 | 17 | module.exports = function(homebridge) { 18 | homebridge.registerPlatform("homebridge-http-webhooks", "HttpWebHooks", HttpWebHooksPlatform); 19 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookSensor", HttpWebHookSensorAccessory); 20 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookSwitch", HttpWebHookSwitchAccessory); 21 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookPushButton", HttpWebHookPushButtonAccessory); 22 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookLight", HttpWebHookLightBulbAccessory); 23 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookThermostat", HttpWebHookThermostatAccessory); 24 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookOutlet", HttpWebHookOutletAccessory); 25 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookSecurity", HttpWebHookSecurityAccessory); 26 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookGarageDoorOpener", HttpWebHookGarageDoorOpenerAccessory); 27 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookStatelessSwitch", HttpWebHookStatelessSwitchAccessory); 28 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookLockMechanism", HttpWebHookLockMechanismAccessory); 29 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookWindowCovering", HttpWebHookWindowCoveringAccessory); 30 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookFanv2", HttpWebHookFanv2Accessory); 31 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookCarbonDioxideSensor", HttpWebHookCarbonDioxideSensoryAccessory); 32 | homebridge.registerAccessory("homebridge-http-webhooks", "HttpWebHookValve", HttpWebHookValveAccessory); 33 | }; 34 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookCarbonDioxideSensorAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | 3 | function HttpWebHookCarbonDioxideSensorAccessory(ServiceParam, CharacteristicParam, platform, sensorConfig) { 4 | Service = ServiceParam; 5 | Characteristic = CharacteristicParam; 6 | 7 | this.platform = platform; 8 | this.log = platform.log; 9 | this.storage = platform.storage; 10 | 11 | this.id = sensorConfig["id"]; 12 | this.name = sensorConfig["name"]; 13 | this.type = "co2"; 14 | this.co2PeakLevel = sensorConfig["co2_peak_level"] || 1200; 15 | 16 | this.informationService = new Service.AccessoryInformation(); 17 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 18 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookCarbonDioxideSensorAccessory-" + this.name); 19 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookCarbonDioxideSensorAccessory-" + this.id); 20 | 21 | this.service = new Service.CarbonDioxideSensor(this.name); 22 | this.service.getCharacteristic(Characteristic.CarbonDioxideLevel).on('get', this.getCarbonDioxideLevel.bind(this)); 23 | this.service.getCharacteristic(Characteristic.CarbonDioxideDetected).on('get', this.getCarbonDioxideDetected.bind(this)); 24 | } 25 | 26 | HttpWebHookCarbonDioxideSensorAccessory.prototype.changeFromServer = function(urlParams) { 27 | var cached = this.storage.getItemSync("http-webhook-" + this.id) || 0; 28 | if (urlParams.value === undefined) { 29 | this.log.debug("No urlValue"); 30 | return { 31 | "success" : true, 32 | "state" : cached 33 | }; 34 | } 35 | var urlValue = urlParams.value; 36 | var co2Detected = urlValue > this.co2PeakLevel; 37 | this.log.debug("urlValue: "+ urlValue); 38 | this.log.debug("co2Detected: "+ co2Detected); 39 | this.storage.setItemSync("http-webhook-carbon-dioxide-level-" + this.id, urlValue); 40 | this.storage.setItemSync("http-webhook-carbon-dioxide-detected-" + this.id, co2Detected); 41 | this.log.debug("cached: "+ cached); 42 | this.log.debug("cached !== urlValue: "+ (cached !== urlValue)); 43 | if (cached !== urlValue) { 44 | this.log("Change HomeKit value for " + this.type + " sensor to '%s'.", urlValue); 45 | this.service.getCharacteristic(Characteristic.CarbonDioxideLevel).updateValue(urlValue, undefined, Constants.CONTEXT_FROM_WEBHOOK); 46 | this.service.getCharacteristic(Characteristic.CarbonDioxideDetected).updateValue(co2Detected ? Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL : Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL, undefined, Constants.CONTEXT_FROM_WEBHOOK); 47 | } 48 | return { 49 | "success" : true 50 | }; 51 | } 52 | 53 | HttpWebHookCarbonDioxideSensorAccessory.prototype.getCarbonDioxideLevel = function(callback) { 54 | this.log.debug("Getting carbon dioxide level for '%s'...", this.id); 55 | var temp = this.storage.getItemSync("http-webhook-carbon-dioxide-level-" + this.id); 56 | if (temp === undefined) { 57 | temp = 0; 58 | } 59 | callback(null, temp); 60 | }; 61 | 62 | HttpWebHookCarbonDioxideSensorAccessory.prototype.getCarbonDioxideDetected = function(callback) { 63 | this.log.debug("Getting carbon dioxide detected state for '%s'...", this.id); 64 | var state = this.storage.getItemSync("http-webhook-carbon-dioxide-detected-" + this.id); 65 | if (state === undefined) { 66 | state = false; 67 | } 68 | callback(null, state ? Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL : Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL); 69 | }; 70 | 71 | HttpWebHookCarbonDioxideSensorAccessory.prototype.getServices = function() { 72 | return [ this.service, this.informationService ]; 73 | }; 74 | 75 | module.exports = HttpWebHookCarbonDioxideSensorAccessory; 76 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookSwitchAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookSwitchAccessory(ServiceParam, CharacteristicParam, platform, switchConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = switchConfig["id"]; 13 | this.name = switchConfig["name"]; 14 | this.rejectUnauthorized = switchConfig["rejectUnauthorized"] === undefined ? true: switchConfig["rejectUnauthorized"] === true; 15 | this.onURL = switchConfig["on_url"] || ""; 16 | this.onMethod = switchConfig["on_method"] || "GET"; 17 | this.onBody = switchConfig["on_body"] || ""; 18 | this.onForm = switchConfig["on_form"] || ""; 19 | this.onHeaders = switchConfig["on_headers"] || "{}"; 20 | this.offURL = switchConfig["off_url"] || ""; 21 | this.offMethod = switchConfig["off_method"] || "GET"; 22 | this.offBody = switchConfig["off_body"] || ""; 23 | this.offForm = switchConfig["off_form"] || ""; 24 | this.offHeaders = switchConfig["off_headers"] || "{}"; 25 | 26 | this.informationService = new Service.AccessoryInformation(); 27 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 28 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookSwitchAccessory-" + this.name); 29 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookSwitchAccessory-" + this.id); 30 | 31 | this.service = new Service.Switch(this.name); 32 | this.service.getCharacteristic(Characteristic.On).on('get', this.getState.bind(this)).on('set', this.setState.bind(this)); 33 | } 34 | 35 | HttpWebHookSwitchAccessory.prototype.changeFromServer = function(urlParams) { 36 | var cachedState = this.storage.getItemSync("http-webhook-" + this.id); 37 | if (cachedState === undefined) { 38 | cachedState = false; 39 | } 40 | if (!urlParams.state) { 41 | return { 42 | "success" : true, 43 | "state" : cachedState 44 | }; 45 | } 46 | else { 47 | var state = urlParams.state; 48 | var stateBool = state === "true"; 49 | this.storage.setItemSync("http-webhook-" + this.id, stateBool); 50 | // this.log("[INFO Http WebHook Server] State change of '%s' 51 | // to '%s'.",accessory.id,stateBool); 52 | if (cachedState !== stateBool) { 53 | this.log("Change HomeKit state for switch to '%s'.", stateBool); 54 | this.service.getCharacteristic(Characteristic.On).updateValue(stateBool, undefined, Constants.CONTEXT_FROM_WEBHOOK); 55 | } 56 | return { 57 | "success" : true 58 | }; 59 | } 60 | } 61 | 62 | HttpWebHookSwitchAccessory.prototype.getState = function(callback) { 63 | this.log.debug("Getting current state for '%s'...", this.id); 64 | var state = this.storage.getItemSync("http-webhook-" + this.id); 65 | if (state === undefined) { 66 | state = false; 67 | } 68 | callback(null, state); 69 | }; 70 | 71 | HttpWebHookSwitchAccessory.prototype.setState = function(powerOn, callback, context) { 72 | this.log("Switch state for '%s'...", this.id); 73 | this.storage.setItemSync("http-webhook-" + this.id, powerOn); 74 | var urlToCall = this.onURL; 75 | var urlMethod = this.onMethod; 76 | var urlBody = this.onBody; 77 | var urlForm = this.onForm; 78 | var urlHeaders = this.onHeaders; 79 | 80 | if (!powerOn) { 81 | urlToCall = this.offURL; 82 | urlMethod = this.offMethod; 83 | urlBody = this.offBody; 84 | urlForm = this.offForm; 85 | urlHeaders = this.offHeaders; 86 | } 87 | 88 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 89 | }; 90 | 91 | HttpWebHookSwitchAccessory.prototype.getServices = function() { 92 | return [ this.service, this.informationService ]; 93 | }; 94 | 95 | module.exports = HttpWebHookSwitchAccessory; 96 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookPushButtonAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookPushButtonAccessory(ServiceParam, CharacteristicParam, platform, pushButtonConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = pushButtonConfig["id"]; 13 | this.type = "pushbutton"; 14 | this.name = pushButtonConfig["name"]; 15 | this.rejectUnauthorized = pushButtonConfig["rejectUnauthorized"] === undefined ? true: pushButtonConfig["rejectUnauthorized"] === true; 16 | this.pushURL = pushButtonConfig["push_url"] || ""; 17 | this.pushMethod = pushButtonConfig["push_method"] || "GET"; 18 | this.pushBody = pushButtonConfig["push_body"] || ""; 19 | this.pushForm = pushButtonConfig["push_form"] || ""; 20 | this.pushHeaders = pushButtonConfig["push_headers"] || "{}"; 21 | 22 | this.informationService = new Service.AccessoryInformation(); 23 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 24 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookPushButtonAccessory-" + this.name); 25 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookPushButtonAccessory-" + this.id); 26 | 27 | this.service = new Service.Switch(this.name); 28 | this.service.getCharacteristic(Characteristic.On).on('get', this.getState.bind(this)).on('set', this.setState.bind(this)); 29 | } 30 | 31 | HttpWebHookPushButtonAccessory.prototype.changeFromServer = function(urlParams) { 32 | if (!urlParams.state) { 33 | return { 34 | "success" : true 35 | }; 36 | } 37 | else { 38 | var state = urlParams.state; 39 | var stateBool = state === "true"; 40 | // this.log("[INFO Http WebHook Server] State change of '%s' 41 | // to '%s'.",accessory.id,stateBool); 42 | if (stateBool) { 43 | this.log("Change HomeKit state for push button to '%s'.", stateBool); 44 | this.service.getCharacteristic(Characteristic.On).updateValue(stateBool, undefined, Constants.CONTEXT_FROM_WEBHOOK); 45 | setTimeout(function() { 46 | this.service.getCharacteristic(Characteristic.On).updateValue(false, undefined, Constants.CONTEXT_FROM_TIMEOUTCALL); 47 | }.bind(this), 1000); 48 | } 49 | return { 50 | "success" : true 51 | }; 52 | } 53 | } 54 | 55 | HttpWebHookPushButtonAccessory.prototype.getState = function(callback) { 56 | this.log.debug("Getting current state for '%s'...", this.id); 57 | var state = false; 58 | callback(null, state); 59 | }; 60 | 61 | HttpWebHookPushButtonAccessory.prototype.setState = function(powerOn, callback, context) { 62 | this.log("Push buttons state change for '%s'...", this.id); 63 | if (!powerOn) { 64 | callback(null); 65 | } 66 | else if (this.pushURL === "" || context === Constants.CONTEXT_FROM_WEBHOOK) { 67 | callback(null); 68 | setTimeout(function() { 69 | this.service.getCharacteristic(Characteristic.On).updateValue(false, undefined, Constants.CONTEXT_FROM_TIMEOUTCALL); 70 | }.bind(this), 1000); 71 | } 72 | else { 73 | var urlToCall = this.pushURL; 74 | var urlMethod = this.pushMethod; 75 | var urlBody = this.pushBody; 76 | var urlForm = this.pushForm; 77 | var urlHeaders = this.pushHeaders; 78 | 79 | var onSuccessAndFailureCallback = (function() { 80 | setTimeout(function() { 81 | this.service.getCharacteristic(Characteristic.On).updateValue(false, undefined, Constants.CONTEXT_FROM_TIMEOUTCALL); 82 | }.bind(this), 1000); 83 | }).bind(this); 84 | 85 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context, onSuccessAndFailureCallback, onSuccessAndFailureCallback); 86 | } 87 | }; 88 | 89 | HttpWebHookPushButtonAccessory.prototype.getServices = function() { 90 | return [ this.service, this.informationService ]; 91 | }; 92 | 93 | module.exports = HttpWebHookPushButtonAccessory; 94 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookStatelessSwitchAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | 3 | function HttpWebHookStatelessSwitchAccessory(ServiceParam, CharacteristicParam, platform, statelessSwitchConfig) { 4 | Service = ServiceParam; 5 | Characteristic = CharacteristicParam; 6 | 7 | this.platform = platform; 8 | this.log = platform.log; 9 | this.storage = platform.storage; 10 | 11 | this.id = statelessSwitchConfig["id"]; 12 | this.type = "statelessswitch"; 13 | this.name = statelessSwitchConfig["name"]; 14 | this.buttons = statelessSwitchConfig["buttons"] || []; 15 | 16 | this.service = []; 17 | for (var index = 0; index < this.buttons.length; index++) { 18 | var single_press = this.buttons[index]["single_press"] === undefined ? true : this.buttons[index]["single_press"]; 19 | var double_press = this.buttons[index]["double_press"] === undefined ? true : this.buttons[index]["double_press"]; 20 | var long_press = this.buttons[index]["long_press"] === undefined ? true : this.buttons[index]["long_press"]; 21 | var button = new Service.StatelessProgrammableSwitch(this.buttons[index].name, '' + index); 22 | button.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps(GetStatelessSwitchProps(single_press, double_press, long_press)); 23 | button.getCharacteristic(Characteristic.ServiceLabelIndex).setValue(index + 1); 24 | this.service.push(button); 25 | } 26 | 27 | var informationService = new Service.AccessoryInformation(); 28 | informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 29 | informationService.setCharacteristic(Characteristic.Model, "HttpWebHookStatelessSwitchAccessory-" + this.name); 30 | informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookStatelessSwitchAccessory-" + this.id); 31 | this.service.push(informationService); 32 | }; 33 | 34 | HttpWebHookStatelessSwitchAccessory.prototype.changeFromServer = function(urlParams) { 35 | if (urlParams.event && urlParams.event) { 36 | for (var index = 0; index < this.service.length; index++) { 37 | var serviceName = this.service[index].getCharacteristic(Characteristic.Name).value; 38 | if (serviceName === urlParams.buttonName) { 39 | this.log("Pressing '%s' with event '%i'", urlParams.buttonName, urlParams.event) 40 | this.service[index].getCharacteristic(Characteristic.ProgrammableSwitchEvent).updateValue(urlParams.event, undefined, Constants.CONTEXT_FROM_WEBHOOK); 41 | } 42 | } 43 | } 44 | return { 45 | "success" : true 46 | }; 47 | } 48 | 49 | function GetStatelessSwitchProps(single_press, double_press, long_press) { 50 | var props; 51 | if (single_press && !double_press && !long_press) { 52 | props = { 53 | minValue : Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, 54 | maxValue : Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS 55 | }; 56 | } 57 | if (single_press && double_press && !long_press) { 58 | props = { 59 | minValue : Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, 60 | maxValue : Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS 61 | }; 62 | } 63 | if (single_press && !double_press && long_press) { 64 | props = { 65 | minValue : Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, 66 | maxValue : Characteristic.ProgrammableSwitchEvent.LONG_PRESS, 67 | validValues : [ Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, Characteristic.ProgrammableSwitchEvent.LONG_PRESS ] 68 | }; 69 | } 70 | if (!single_press && double_press && !long_press) { 71 | props = { 72 | minValue : Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS, 73 | maxValue : Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS 74 | }; 75 | } 76 | if (!single_press && double_press && long_press) { 77 | props = { 78 | minValue : Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS, 79 | maxValue : Characteristic.ProgrammableSwitchEvent.LONG_PRESS 80 | }; 81 | } 82 | if (!single_press && !double_press && long_press) { 83 | props = { 84 | minValue : Characteristic.ProgrammableSwitchEvent.LONG_PRESS, 85 | maxValue : Characteristic.ProgrammableSwitchEvent.LONG_PRESS 86 | }; 87 | } 88 | if (single_press && double_press && long_press) { 89 | props = { 90 | minValue : Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, 91 | maxValue : Characteristic.ProgrammableSwitchEvent.LONG_PRESS 92 | }; 93 | } 94 | return props; 95 | } 96 | 97 | HttpWebHookStatelessSwitchAccessory.prototype.getServices = function() { 98 | return this.service; 99 | }; 100 | 101 | module.exports = HttpWebHookStatelessSwitchAccessory; -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookSecurityAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookSecurityAccessory(ServiceParam, CharacteristicParam, platform, securityConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = securityConfig["id"]; 13 | this.name = securityConfig["name"]; 14 | this.type = "security"; 15 | this.rejectUnauthorized = securityConfig["rejectUnauthorized"] === undefined ? true: securityConfig["rejectUnauthorized"] === true; 16 | this.setStateURL = securityConfig["set_state_url"] || ""; 17 | this.setStateMethod = securityConfig["set_state_method"] || "GET"; 18 | this.setStateBody = securityConfig["set_state_body"] || ""; 19 | this.setStateForm = securityConfig["set_state_form"] || ""; 20 | this.setStateHeaders = securityConfig["set_state_headers"] || "{}"; 21 | 22 | this.informationService = new Service.AccessoryInformation(); 23 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 24 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookSecurityAccessory-" + this.name); 25 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookSecurityAccessory-" + this.id); 26 | 27 | this.service = new Service.SecuritySystem(this.name); 28 | this.service.getCharacteristic(Characteristic.SecuritySystemTargetState).on('get', this.getTargetSecurityState.bind(this)).on('set', this.setTargetSecurityState.bind(this)); 29 | this.service.getCharacteristic(Characteristic.SecuritySystemCurrentState).on('get', this.getCurrentSecurityState.bind(this)); 30 | } 31 | 32 | HttpWebHookSecurityAccessory.prototype.changeFromServer = function(urlParams) { 33 | var cachedCurrentState = this.storage.getItemSync("http-webhook-current-security-state-" + this.id); 34 | if (cachedCurrentState === undefined) { 35 | cachedCurrentState = Characteristic.SecuritySystemCurrentState.DISARMED; 36 | } 37 | if (!urlParams.currentstate && !urlParams.targetstate) { 38 | return { 39 | "success" : true, 40 | "currentState" : cachedCurrentState 41 | }; 42 | } 43 | 44 | if (urlParams.currentstate != null) { 45 | this.storage.setItemSync("http-webhook-current-security-state-" + this.id, urlParams.currentstate); 46 | if (cachedCurrentState !== urlParams.currentstate) { 47 | this.log("Change current state for security to '%d'.", urlParams.currentstate); 48 | this.service.getCharacteristic(Characteristic.SecuritySystemCurrentState).updateValue(urlParams.currentstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 49 | } 50 | } 51 | 52 | if (urlParams.targetstate != null) { 53 | var cachedState = this.storage.getItemSync("http-webhook-target-security-state-" + this.id); 54 | if (cachedState === undefined) { 55 | cachedState = Characteristic.SecuritySystemTargetState.DISARM; 56 | } 57 | this.storage.setItemSync("http-webhook-target-security-state-" + this.id, urlParams.targetstate); 58 | if (cachedState !== urlParams.targetstate) { 59 | this.log("Change target state for security to '%d'.", urlParams.targetstate); 60 | this.service.getCharacteristic(Characteristic.SecuritySystemTargetState).updateValue(urlParams.targetstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 61 | } 62 | } 63 | return { 64 | "success" : true 65 | }; 66 | } 67 | 68 | HttpWebHookSecurityAccessory.prototype.getTargetSecurityState = function(callback) { 69 | this.log.debug("Getting Target Security state for '%s'...", this.id); 70 | var state = this.storage.getItemSync("http-webhook-target-security-state-" + this.id); 71 | if (state === undefined) { 72 | state = Characteristic.SecuritySystemTargetState.DISARM; 73 | } 74 | callback(null, state); 75 | }; 76 | 77 | HttpWebHookSecurityAccessory.prototype.setTargetSecurityState = function(newState, callback, context) { 78 | this.log("Target Security state for '%s'...", this.id); 79 | this.storage.setItemSync("http-webhook-target-security-state-" + this.id, newState); 80 | this.storage.setItemSync("http-webhook-current-security-state-" + this.id, newState); 81 | var urlToCall = this.setStateURL.replace("%d", newState); 82 | var urlMethod = this.setStateMethod; 83 | var urlBody = this.setStateBody; 84 | var urlForm = this.setStateForm; 85 | var urlHeaders = this.setStateHeaders; 86 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context, (function() { 87 | this.service.getCharacteristic(Characteristic.SecuritySystemCurrentState).updateValue(newState, undefined, null); 88 | }).bind(this)); 89 | }; 90 | 91 | HttpWebHookSecurityAccessory.prototype.getCurrentSecurityState = function(callback) { 92 | this.log.debug("Getting Current Security state for '%s'...", this.id); 93 | var state = this.storage.getItemSync("http-webhook-current-security-state-" + this.id); 94 | if (state === undefined) { 95 | state = Characteristic.SecuritySystemCurrentState.DISARMED; 96 | } 97 | callback(null, state); 98 | }; 99 | 100 | HttpWebHookSecurityAccessory.prototype.getServices = function() { 101 | return [ this.service, this.informationService ]; 102 | }; 103 | 104 | module.exports = HttpWebHookSecurityAccessory; 105 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookOutletAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookOutletAccessory(ServiceParam, CharacteristicParam, platform, outletConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = outletConfig["id"]; 13 | this.name = outletConfig["name"]; 14 | this.type = "outlet"; 15 | this.rejectUnauthorized = outletConfig["rejectUnauthorized"] === undefined ? true: outletConfig["rejectUnauthorized"] === true; 16 | this.onURL = outletConfig["on_url"] || ""; 17 | this.onMethod = outletConfig["on_method"] || "GET"; 18 | this.onBody = outletConfig["on_body"] || ""; 19 | this.onForm = outletConfig["on_form"] || ""; 20 | this.onHeaders = outletConfig["on_headers"] || "{}"; 21 | this.offURL = outletConfig["off_url"] || ""; 22 | this.offMethod = outletConfig["off_method"] || "GET"; 23 | this.offBody = outletConfig["off_body"] || ""; 24 | this.offForm = outletConfig["off_form"] || ""; 25 | this.offHeaders = outletConfig["off_headers"] || "{}"; 26 | 27 | this.informationService = new Service.AccessoryInformation(); 28 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 29 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookOutletAccessory-" + this.name); 30 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookOutletAccessory-" + this.id); 31 | 32 | this.service = new Service.Outlet(this.name); 33 | this.service.getCharacteristic(Characteristic.On).on('get', this.getState.bind(this)).on('set', this.setState.bind(this)); 34 | this.service.getCharacteristic(Characteristic.OutletInUse).on('get', this.getStateInUse.bind(this)); 35 | } 36 | 37 | HttpWebHookOutletAccessory.prototype.changeFromServer = function(urlParams) { 38 | var cachedState = this.storage.getItemSync("http-webhook-" + this.id); 39 | if (cachedState === undefined) { 40 | cachedState = false; 41 | } 42 | var cachedStateInUse = this.storage.getItemSync("http-webhook-" + this.id + "-inUse"); 43 | if (cachedStateInUse === undefined) { 44 | cachedStateInUse = false; 45 | } 46 | if (!urlParams.state && !urlParams.stateOutletInUse) { 47 | return { 48 | "success" : true, 49 | "state" : cachedState, 50 | "stateOutletInUse" : cachedStateInUse 51 | }; 52 | } 53 | else { 54 | if (urlParams.state) { 55 | var state = urlParams.state; 56 | var stateBool = state === "true"; 57 | this.storage.setItemSync("http-webhook-" + this.id, stateBool); 58 | // this.log("[INFO Http WebHook Server] State change of 59 | // '%s' 60 | // to '%s'.",accessory.id,stateBool); 61 | if (cachedState !== stateBool) { 62 | this.log("Change HomeKit state for outlet to '%s'.", stateBool); 63 | this.service.getCharacteristic(Characteristic.On).updateValue(stateBool, undefined, Constants.CONTEXT_FROM_WEBHOOK); 64 | } 65 | } 66 | if (urlParams.stateOutletInUse) { 67 | var stateOutletInUse = urlParams.stateOutletInUse; 68 | var stateOutletInUseBool = stateOutletInUse === "true"; 69 | this.storage.setItemSync("http-webhook-" + this.id + "-inUse", stateOutletInUseBool); 70 | // this.log("[INFO Http WebHook Server] State change of 71 | // '%s' 72 | // to '%s'.",accessory.id,stateBool); 73 | if (cachedStateInUse !== stateOutletInUseBool) { 74 | this.log("Change HomeKit stateInUse for outlet to '%s'.", stateOutletInUseBool); 75 | this.service.getCharacteristic(Characteristic.OutletInUse).updateValue(stateOutletInUseBool, undefined, Constants.CONTEXT_FROM_WEBHOOK); 76 | } 77 | } 78 | return { 79 | "success" : true 80 | }; 81 | } 82 | } 83 | 84 | HttpWebHookOutletAccessory.prototype.getState = function(callback) { 85 | this.log.debug("Getting current state for '%s'...", this.id); 86 | var state = this.storage.getItemSync("http-webhook-" + this.id); 87 | if (state === undefined) { 88 | state = false; 89 | } 90 | callback(null, state); 91 | }; 92 | 93 | HttpWebHookOutletAccessory.prototype.getStateInUse = function(callback) { 94 | this.log.debug("Getting current state for '%s'...", this.id); 95 | var stateInUse = this.storage.getItemSync("http-webhook-" + this.id + "-inUse"); 96 | if (stateInUse === undefined) { 97 | stateInUse = false; 98 | } 99 | callback(null, stateInUse); 100 | }; 101 | 102 | HttpWebHookOutletAccessory.prototype.setState = function(powerOn, callback, context) { 103 | this.log("Switch outlet state for '%s'...", this.id); 104 | this.storage.setItemSync("http-webhook-" + this.id, powerOn); 105 | var urlToCall = this.onURL; 106 | var urlMethod = this.onMethod; 107 | var urlBody = this.onBody; 108 | var urlForm = this.onForm; 109 | var urlHeaders = this.onHeaders; 110 | if (!powerOn) { 111 | urlToCall = this.offURL; 112 | urlMethod = this.offMethod; 113 | urlBody = this.offBody; 114 | urlForm = this.offForm; 115 | urlHeaders = this.offHeaders; 116 | } 117 | 118 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 119 | }; 120 | 121 | HttpWebHookOutletAccessory.prototype.getServices = function() { 122 | return [ this.service, this.informationService ]; 123 | }; 124 | 125 | module.exports = HttpWebHookOutletAccessory; 126 | -------------------------------------------------------------------------------- /src/homekit/HttpWebHooksPlatform.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../Constants'); 2 | const Server = require('../Server'); 3 | 4 | var HttpWebHookSensorAccessory = require('./accessories/HttpWebHookSensorAccessory'); 5 | var HttpWebHookSwitchAccessory = require('./accessories/HttpWebHookSwitchAccessory'); 6 | var HttpWebHookPushButtonAccessory = require('./accessories/HttpWebHookPushButtonAccessory'); 7 | var HttpWebHookLightBulbAccessory = require('./accessories/HttpWebHookLightBulbAccessory'); 8 | var HttpWebHookThermostatAccessory = require('./accessories/HttpWebHookThermostatAccessory'); 9 | var HttpWebHookOutletAccessory = require('./accessories/HttpWebHookOutletAccessory'); 10 | var HttpWebHookSecurityAccessory = require('./accessories/HttpWebHookSecurityAccessory'); 11 | var HttpWebHookGarageDoorOpenerAccessory = require('./accessories/HttpWebHookGarageDoorOpenerAccessory'); 12 | var HttpWebHookStatelessSwitchAccessory = require('./accessories/HttpWebHookStatelessSwitchAccessory'); 13 | var HttpWebHookLockMechanismAccessory = require('./accessories/HttpWebHookLockMechanismAccessory'); 14 | var HttpWebHookWindowCoveringAccessory = require('./accessories/HttpWebHookWindowCoveringAccessory'); 15 | var HttpWebHookFanv2Accessory = require('./accessories/HttpWebHookFanv2Accessory'); 16 | var HttpWebHookCarbonDioxideSensoryAccessory = require('./accessories/HttpWebHookCarbonDioxideSensorAccessory'); 17 | var HttpWebHookValveAccessory = require('./accessories/HttpWebHookValveAccessory'); 18 | 19 | var Service, Characteristic; 20 | 21 | function HttpWebHooksPlatform(log, config, homebridge) { 22 | Service = homebridge.hap.Service; 23 | Characteristic = homebridge.hap.Characteristic; 24 | 25 | this.log = log; 26 | this.cacheDirectory = config["cache_directory"] || Constants.DEFAULT_CACHE_DIR; 27 | this.storage = require('node-persist'); 28 | this.storage.initSync({ 29 | dir : this.cacheDirectory 30 | }); 31 | 32 | this.sensors = config["sensors"] || []; 33 | this.switches = config["switches"] || []; 34 | this.pushButtons = config["pushbuttons"] || []; 35 | this.lights = config["lights"] || []; 36 | this.thermostats = config["thermostats"] || []; 37 | this.outlets = config["outlets"] || []; 38 | this.security = config["security"] || []; 39 | this.garageDoorOpeners = config["garagedooropeners"] || []; 40 | this.statelessSwitches = config["statelessswitches"] || []; 41 | this.windowCoverings = config["windowcoverings"] || []; 42 | this.lockMechanisms = config["lockmechanisms"] || []; 43 | this.fanv2s = config["fanv2s"] || []; 44 | this.co2sensors = config["co2sensors"] || []; 45 | this.valves = config["valves"] || []; 46 | 47 | this.server = new Server(Service, Characteristic, this, config); 48 | }; 49 | 50 | HttpWebHooksPlatform.prototype.accessories = function(callback) { 51 | var accessories = []; 52 | 53 | for (var i = 0; i < this.sensors.length; i++) { 54 | var sensor = new HttpWebHookSensorAccessory(Service, Characteristic, this, this.sensors[i]); 55 | accessories.push(sensor); 56 | } 57 | 58 | for (var i = 0; i < this.switches.length; i++) { 59 | var switchAccessory = new HttpWebHookSwitchAccessory(Service, Characteristic, this, this.switches[i]); 60 | accessories.push(switchAccessory); 61 | } 62 | 63 | for (var i = 0; i < this.pushButtons.length; i++) { 64 | var pushButtonsAccessory = new HttpWebHookPushButtonAccessory(Service, Characteristic, this, this.pushButtons[i]); 65 | accessories.push(pushButtonsAccessory); 66 | } 67 | 68 | for (var i = 0; i < this.lights.length; i++) { 69 | var lightAccessory = new HttpWebHookLightBulbAccessory(Service, Characteristic, this, this.lights[i]); 70 | accessories.push(lightAccessory); 71 | } 72 | 73 | for (var i = 0; i < this.thermostats.length; i++) { 74 | var thermostatAccessory = new HttpWebHookThermostatAccessory(Service, Characteristic, this, this.thermostats[i]); 75 | accessories.push(thermostatAccessory); 76 | } 77 | 78 | for (var i = 0; i < this.outlets.length; i++) { 79 | var outletAccessory = new HttpWebHookOutletAccessory(Service, Characteristic, this, this.outlets[i]); 80 | accessories.push(outletAccessory); 81 | } 82 | 83 | for (var i = 0; i < this.security.length; i++) { 84 | var securityAccessory = new HttpWebHookSecurityAccessory(Service, Characteristic, this, this.security[i]); 85 | accessories.push(securityAccessory); 86 | } 87 | 88 | for (var i = 0; i < this.garageDoorOpeners.length; i++) { 89 | var garageDoorOpenerAccessory = new HttpWebHookGarageDoorOpenerAccessory(Service, Characteristic, this, this.garageDoorOpeners[i]); 90 | accessories.push(garageDoorOpenerAccessory); 91 | } 92 | 93 | for (var i = 0; i < this.windowCoverings.length; i++) { 94 | var WindowCoveringAccessory = new HttpWebHookWindowCoveringAccessory(Service, Characteristic, this, this.windowCoverings[i]); 95 | accessories.push(WindowCoveringAccessory); 96 | } 97 | 98 | for (var i = 0; i < this.statelessSwitches.length; i++) { 99 | var statelessSwitchAccessory = new HttpWebHookStatelessSwitchAccessory(Service, Characteristic, this, this.statelessSwitches[i]); 100 | accessories.push(statelessSwitchAccessory); 101 | } 102 | 103 | for (var i = 0; i < this.lockMechanisms.length; i++) { 104 | var lockMechanismAccessory = new HttpWebHookLockMechanismAccessory(Service, Characteristic, this, this.lockMechanisms[i]); 105 | accessories.push(lockMechanismAccessory); 106 | } 107 | 108 | for (var i = 0; i < this.fanv2s.length; i++) { 109 | var fanv2Accessory = new HttpWebHookFanv2Accessory(Service, Characteristic, this, this.fanv2s[i]); 110 | accessories.push(fanv2Accessory); 111 | } 112 | 113 | for (var i = 0; i < this.co2sensors.length; i++) { 114 | var co2sensorAccessory = new HttpWebHookCarbonDioxideSensoryAccessory(Service, Characteristic, this, this.co2sensors[i]); 115 | accessories.push(co2sensorAccessory); 116 | } 117 | 118 | for (var i = 0; i < this.valves.length; i++) { 119 | var valveAccessory = new HttpWebHookValveAccessory(Service, Characteristic, this, this.valves[i]); 120 | accessories.push(valveAccessory); 121 | } 122 | 123 | this.server.setAccessories(accessories); 124 | this.server.start(); 125 | 126 | callback(accessories); 127 | }; 128 | 129 | module.exports = HttpWebHooksPlatform; 130 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookValveAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookValveAccessory(ServiceParam, CharacteristicParam, platform, valveConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = valveConfig["id"]; 13 | this.name = valveConfig["name"]; 14 | this.type = "valve"; 15 | this.rejectUnauthorized = valveConfig["rejectUnauthorized"] === undefined ? true: valveConfig["rejectUnauthorized"] === true; 16 | this.onURL = valveConfig["on_url"] || ""; 17 | this.onMethod = valveConfig["on_method"] || "GET"; 18 | this.onBody = valveConfig["on_body"] || ""; 19 | this.onForm = valveConfig["on_form"] || ""; 20 | this.onHeaders = valveConfig["on_headers"] || "{}"; 21 | this.offURL = valveConfig["off_url"] || ""; 22 | this.offMethod = valveConfig["off_method"] || "GET"; 23 | this.offBody = valveConfig["off_body"] || ""; 24 | this.offForm = valveConfig["off_form"] || ""; 25 | this.offHeaders = valveConfig["off_headers"] || "{}"; 26 | 27 | this.informationService = new Service.AccessoryInformation(); 28 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 29 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookValveAccessory-" + this.name); 30 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookValveAccessory-" + this.id); 31 | 32 | var valveType = 0; 33 | switch(valveConfig.type) { 34 | default: 35 | case "generic valve": 36 | valveType = 0; // ValveType.GENERIC_VALVE 37 | break; 38 | case "irrigation": 39 | valveType = 1; // ValveType.IRRIGATION 40 | break; 41 | case "shower head": 42 | valveType = 2; // ValveType.SHOWER_HEAD 43 | break; 44 | case "water faucet": 45 | valveType = 3; // ValveType.WATER_FAUCET 46 | break; 47 | } 48 | 49 | this.service = new Service.Valve(this.name); 50 | this.service.setCharacteristic(Characteristic.ValveType, valveType); 51 | this.service.getCharacteristic(Characteristic.Active).on('get', this.getState.bind(this)).on('set', this.setState.bind(this)); 52 | this.service.getCharacteristic(Characteristic.InUse).on('get', this.getState.bind(this)).on('set', this.setState.bind(this)); 53 | this.service.getCharacteristic(Characteristic.StatusFault).on('get', this.getStatusFault.bind(this)); 54 | 55 | this.category = 30; 56 | } 57 | 58 | HttpWebHookValveAccessory.prototype.changeFromServer = function(urlParams) { 59 | var cachedState = this.storage.getItemSync("http-webhook-" + this.id); 60 | if (cachedState === undefined) { 61 | cachedState = 0; 62 | } 63 | var cachedStatusFault = this.storage.getItemSync("http-webhook-" + this.id + "-statusFault"); 64 | if (cachedStatusFault === undefined) { 65 | cachedStatusFault = 0; 66 | } 67 | if (!urlParams.state && !urlParams.statusFault) { 68 | return { 69 | "success" : true, 70 | "state" : cachedState, 71 | "statusFault" : cachedStatusFault 72 | }; 73 | } 74 | else { 75 | if (urlParams.state) { 76 | var state = urlParams.state; 77 | var stateNumber = state === "true" ? 1 : 0; 78 | this.storage.setItemSync("http-webhook-" + this.id, stateNumber); 79 | this.log.info("Change HomeKit value for " + this.type + " state to '%s'.", stateNumber); 80 | 81 | if (cachedState !== stateNumber) { 82 | this.log("Change HomeKit state for valve to '%s'.", stateNumber); 83 | this.service.getCharacteristic(Characteristic.Active).updateValue(stateNumber, undefined, Constants.CONTEXT_FROM_WEBHOOK); 84 | this.service.getCharacteristic(Characteristic.InUse).updateValue(stateNumber, undefined, Constants.CONTEXT_FROM_WEBHOOK); 85 | } 86 | } 87 | if (urlParams.statusFault) { 88 | var statusFault = urlParams.statusFault; 89 | var statusFaultNumber = statusFault === "true" ? 1 : 0; 90 | this.storage.setItemSync("http-webhook-" + this.id + "-statusFault", statusFaultNumber); 91 | this.log.info("Change HomeKit value for " + this.type + " statusFault to '%s'.", statusFaultNumber); 92 | 93 | if (cachedStatusFault !== statusFaultNumber) { 94 | this.log("Change HomeKit statusFault for valve to '%s'.", statusFault); 95 | this.service.getCharacteristic(Characteristic.StatusFault).updateValue(statusFaultNumber, undefined, Constants.CONTEXT_FROM_WEBHOOK); 96 | } 97 | } 98 | return { 99 | "success" : true 100 | }; 101 | } 102 | }; 103 | 104 | HttpWebHookValveAccessory.prototype.getState = function(callback) { 105 | this.log.debug("Getting current state for", this.id); 106 | var state = this.storage.getItemSync("http-webhook-" + this.id); 107 | if (state === undefined) { 108 | state = 0; 109 | } 110 | 111 | callback(null, state); 112 | }; 113 | 114 | HttpWebHookValveAccessory.prototype.getStatusFault = function(callback) { 115 | this.log.debug("Getting status fault for", this.id); 116 | var statusFault = this.storage.getItemSync("http-webhook-" + this.id + "-statusFault"); 117 | if (statusFault === undefined) { 118 | statusFault = 0; 119 | } 120 | 121 | callback(null, statusFault); 122 | }; 123 | 124 | HttpWebHookValveAccessory.prototype.setState = function(active, callback, context) { 125 | this.log.info("Set valve state for", this.id, "to", active); 126 | this.storage.setItemSync("http-webhook-" + this.id, active); 127 | 128 | this.service.getCharacteristic(Characteristic.Active).updateValue(active, undefined, Constants.CONTEXT_FROM_WEBHOOK); 129 | this.service.getCharacteristic(Characteristic.InUse).updateValue(active, undefined, Constants.CONTEXT_FROM_WEBHOOK); 130 | 131 | var urlToCall = this.onURL; 132 | var urlMethod = this.onMethod; 133 | var urlBody = this.onBody; 134 | var urlForm = this.onForm; 135 | var urlHeaders = this.onHeaders; 136 | if (!active) { 137 | urlToCall = this.offURL; 138 | urlMethod = this.offMethod; 139 | urlBody = this.offBody; 140 | urlForm = this.offForm; 141 | urlHeaders = this.offHeaders; 142 | } 143 | 144 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 145 | }; 146 | 147 | HttpWebHookValveAccessory.prototype.getServices = function() { 148 | return [ this.service, this.informationService ]; 149 | }; 150 | 151 | module.exports = HttpWebHookValveAccessory; 152 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookLightBulbAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookLightBulbAccessory(ServiceParam, CharacteristicParam, platform, lightConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = lightConfig["id"]; 13 | this.type = "lightbulb"; 14 | this.name = lightConfig["name"]; 15 | this.rejectUnauthorized = lightConfig["rejectUnauthorized"] === undefined ? true: lightConfig["rejectUnauthorized"] === true; 16 | this.onURL = lightConfig["on_url"] || ""; 17 | this.onMethod = lightConfig["on_method"] || "GET"; 18 | this.onBody = lightConfig["on_body"] || ""; 19 | this.onForm = lightConfig["on_form"] || ""; 20 | this.onHeaders = lightConfig["on_headers"] || "{}"; 21 | this.offURL = lightConfig["off_url"] || ""; 22 | this.offMethod = lightConfig["off_method"] || "GET"; 23 | this.offBody = lightConfig["off_body"] || ""; 24 | this.offForm = lightConfig["off_form"] || ""; 25 | this.offHeaders = lightConfig["off_headers"] || "{}"; 26 | this.brightnessURL = lightConfig["brightness_url"] || ""; 27 | this.brightnessMethod = lightConfig["brightness_method"] || "GET"; 28 | this.brightnessBody = lightConfig["brightness_body"] || ""; 29 | this.brightnessForm = lightConfig["brightness_form"] || ""; 30 | this.brightnessHeaders = lightConfig["brightness_headers"] || "{}"; 31 | this.brightnessFactor = lightConfig["brightness_factor"] || 1; 32 | 33 | this.informationService = new Service.AccessoryInformation(); 34 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 35 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookLightAccessory-" + this.name); 36 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookLightAccessory-" + this.id); 37 | 38 | this.service = new Service.Lightbulb(this.name); 39 | this.service.getCharacteristic(Characteristic.On).on('get', this.getState.bind(this)).on('set', this.setState.bind(this)); 40 | this.service.getCharacteristic(Characteristic.Brightness).on('get', this.getBrightness.bind(this)).on('set', this.setBrightness.bind(this)); 41 | } 42 | 43 | HttpWebHookLightBulbAccessory.prototype.changeFromServer = function(urlParams) { 44 | var cachedState = this.storage.getItemSync("http-webhook-" + this.id); 45 | if (cachedState === undefined) { 46 | cachedState = false; 47 | } 48 | var cachedBrightness = this.storage.getItemSync("http-webhook-brightness-" + this.id); 49 | if (cachedBrightness === undefined) { 50 | cachedBrightness = -1; 51 | } 52 | if (!urlParams.state && !urlParams.value) { 53 | return { 54 | "success" : true, 55 | "brightness" : cachedBrightness, 56 | "state" : cachedState 57 | }; 58 | } 59 | else { 60 | var brightness = urlParams.value || cachedBrightness; 61 | var state = urlParams.state || cachedState; 62 | var stateBool = state === "true" || state === true; 63 | this.storage.setItemSync("http-webhook-" + this.id, stateBool); 64 | var brightnessInt = parseInt(brightness); 65 | this.storage.setItemSync("http-webhook-brightness-" + this.id, brightnessInt); 66 | if (cachedState !== stateBool || cachedBrightness != brightnessInt) { 67 | var brightnessToSet = Math.ceil(brightnessInt / this.brightnessFactor); 68 | this.log("Change HomeKit state for light to '%s'.", stateBool); 69 | this.log("Change HomeKit brightness for light to '%s'.", brightnessToSet); 70 | this.service.getCharacteristic(Characteristic.On).updateValue(stateBool, undefined, Constants.CONTEXT_FROM_WEBHOOK); 71 | this.service.getCharacteristic(Characteristic.Brightness).updateValue(brightnessToSet, undefined, Constants.CONTEXT_FROM_WEBHOOK); 72 | } 73 | return { 74 | "success" : true 75 | }; 76 | } 77 | }; 78 | 79 | HttpWebHookLightBulbAccessory.prototype.getState = function(callback) { 80 | this.log.debug("Getting current state for '%s'...", this.id); 81 | var state = this.storage.getItemSync("http-webhook-" + this.id); 82 | if (state === undefined) { 83 | state = false; 84 | } 85 | callback(null, state); 86 | }; 87 | 88 | HttpWebHookLightBulbAccessory.prototype.setState = function(powerOn, callback, context) { 89 | this.log("Light state for '%s'...", this.id); 90 | this.storage.setItemSync("http-webhook-" + this.id, powerOn); 91 | var urlToCall = this.onURL; 92 | var urlMethod = this.onMethod; 93 | var urlBody = this.onBody; 94 | var urlForm = this.onForm; 95 | var urlHeaders = this.onHeaders; 96 | if (!powerOn) { 97 | urlToCall = this.offURL; 98 | urlMethod = this.offMethod; 99 | urlBody = this.offBody; 100 | urlForm = this.offForm; 101 | urlHeaders = this.offHeaders; 102 | } 103 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 104 | }; 105 | 106 | HttpWebHookLightBulbAccessory.prototype.getBrightness = function(callback) { 107 | this.log.debug("Getting current brightness for '%s'...", this.id); 108 | var state = this.storage.getItemSync("http-webhook-" + this.id); 109 | if (state === undefined) { 110 | state = false; 111 | } 112 | var brightness = 0; 113 | if (state) { 114 | brightness = this.storage.getItemSync("http-webhook-brightness-" + this.id); 115 | if (brightness === undefined) { 116 | brightness = 100; 117 | } 118 | } 119 | callback(null, parseInt(brightness)); 120 | }; 121 | 122 | HttpWebHookLightBulbAccessory.prototype.setBrightness = function(brightness, callback, context) { 123 | this.log("Light brightness for '%s'...", this.id); 124 | var newState = brightness > 0; 125 | this.storage.setItemSync("http-webhook-" + this.id, newState); 126 | this.storage.setItemSync("http-webhook-brightness-" + this.id, brightness); 127 | var brightnessFactor = this.brightnessFactor; 128 | var brightnessToSet = Math.ceil(brightness * brightnessFactor); 129 | var urlToCall = this.replaceVariables(this.brightnessURL, newState, brightnessToSet); 130 | var urlMethod = this.brightnessMethod; 131 | var urlBody = this.brightnessBody; 132 | var urlForm = this.brightnessForm; 133 | var urlHeaders = this.brightnessHeaders; 134 | 135 | if (urlForm) { 136 | urlForm = this.replaceVariables(urlForm, newState, brightnessToSet); 137 | } 138 | else if (urlBody) { 139 | urlBody = this.replaceVariables(urlBody, newState, brightnessToSet); 140 | } 141 | 142 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 143 | }; 144 | 145 | HttpWebHookLightBulbAccessory.prototype.replaceVariables = function(text, state, brightness) { 146 | return text.replace("%statusPlaceholder", state).replace("%brightnessPlaceholder", brightness); 147 | }; 148 | 149 | HttpWebHookLightBulbAccessory.prototype.getServices = function() { 150 | return [ this.service, this.informationService ]; 151 | }; 152 | 153 | module.exports = HttpWebHookLightBulbAccessory; 154 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookLockMechanismAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookLockMechanismAccessory(ServiceParam, CharacteristicParam, platform, lockMechanismOpenerConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = lockMechanismOpenerConfig["id"]; 13 | this.name = lockMechanismOpenerConfig["name"]; 14 | this.type = "lockmechanism"; 15 | this.rejectUnauthorized = lockMechanismOpenerConfig["rejectUnauthorized"] === undefined ? true: lockMechanismOpenerConfig["rejectUnauthorized"] === true; 16 | this.setLockTargetStateOpenURL = lockMechanismOpenerConfig["open_url"] || ""; 17 | this.setLockTargetStateOpenMethod = lockMechanismOpenerConfig["open_method"] || "GET"; 18 | this.setLockTargetStateOpenBody = lockMechanismOpenerConfig["open_body"] || ""; 19 | this.setLockTargetStateOpenForm = lockMechanismOpenerConfig["open_form"] || ""; 20 | this.setLockTargetStateOpenHeaders = lockMechanismOpenerConfig["open_headers"] || "{}"; 21 | this.setLockTargetStateCloseURL = lockMechanismOpenerConfig["close_url"] || ""; 22 | this.setLockTargetStateCloseMethod = lockMechanismOpenerConfig["close_method"] || "GET"; 23 | this.setLockTargetStateCloseBody = lockMechanismOpenerConfig["close_body"] || ""; 24 | this.setLockTargetStateCloseForm = lockMechanismOpenerConfig["close_form"] || ""; 25 | this.setLockTargetStateCloseHeaders = lockMechanismOpenerConfig["close_headers"] || "{}"; 26 | 27 | this.informationService = new Service.AccessoryInformation(); 28 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 29 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookLockMechanismAccessory-" + this.name); 30 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookLockMechanismAccessory-" + this.id); 31 | 32 | this.service = new Service.LockMechanism(this.name); 33 | this.service.getCharacteristic(Characteristic.LockTargetState).on('get', this.getLockTargetState.bind(this)).on('set', this.setLockTargetState.bind(this)); 34 | this.service.getCharacteristic(Characteristic.LockCurrentState).on('get', this.getLockCurrentState.bind(this)); 35 | } 36 | 37 | HttpWebHookLockMechanismAccessory.prototype.changeFromServer = function(urlParams) { 38 | if (urlParams.lockcurrentstate != null) { 39 | var cachedLockCurrentState = this.storage.getItemSync("http-webhook-lock-current-state-" + this.id); 40 | if (cachedLockCurrentState === undefined) { 41 | cachedLockCurrentState = Characteristic.LockCurrentState.SECURED; 42 | } 43 | this.storage.setItemSync("http-webhook-lock-current-state-" + this.id, urlParams.lockcurrentstate); 44 | if (cachedLockCurrentState !== urlParams.lockcurrentstate) { 45 | if (urlParams.lockcurrentstate) { 46 | this.log("Change Current Lock State for locking to '%s'.", urlParams.lockcurrentstate); 47 | this.service.getCharacteristic(Characteristic.LockCurrentState).updateValue(urlParams.lockcurrentstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 48 | } 49 | } 50 | } 51 | if (urlParams.locktargetstate != null) { 52 | var cachedLockTargetState = this.storage.getItemSync("http-webhook-lock-target-state-" + this.id); 53 | if (cachedLockTargetState === undefined) { 54 | cachedLockTargetState = Characteristic.LockTargetState.SECURED; 55 | } 56 | this.storage.setItemSync("http-webhook-lock-target-state-" + this.id, urlParams.locktargetstate); 57 | if (cachedLockTargetState !== urlParams.locktargetstate) { 58 | if (urlParams.locktargetstate) { 59 | this.log("Change Target Lock State for locking to '%s'.", urlParams.locktargetstate); 60 | this.service.getCharacteristic(Characteristic.LockTargetState).updateValue(urlParams.locktargetstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 61 | } 62 | } 63 | } 64 | return { 65 | "success" : true, 66 | "currentState" : cachedLockCurrentState, 67 | "targetState" : cachedLockTargetState 68 | }; 69 | } 70 | 71 | HttpWebHookLockMechanismAccessory.prototype.getLockTargetState = function(callback) { 72 | this.log.debug("Getting current Target Lock State for '%s'...", this.id); 73 | var state = this.storage.getItemSync("http-webhook-lock-target-state-" + this.id); 74 | if (state === undefined) { 75 | state = Characteristic.LockTargetState.SECURED; 76 | } 77 | callback(null, state); 78 | }; 79 | 80 | HttpWebHookLockMechanismAccessory.prototype.setLockTargetState = function(homeKitState, callback, context) { 81 | var doLock = homeKitState === Characteristic.LockTargetState.SECURED; 82 | var newHomeKitState = doLock ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED; 83 | var newHomeKitStateTarget = doLock ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED; 84 | 85 | this.log("Target Lock State for '%s' to '%s'...", this.id, doLock); 86 | this.storage.setItemSync("http-webhook-lock-target-state-" + this.id, homeKitState); 87 | var urlToCall = this.setLockTargetStateCloseURL; 88 | var urlMethod = this.setLockTargetStateCloseMethod; 89 | var urlBody = this.setLockTargetStateCloseBody; 90 | var urlForm = this.setLockTargetStateCloseForm; 91 | var urlHeaders = this.setLockTargetStateCloseHeaders; 92 | 93 | if (!doLock) { 94 | urlToCall = this.setLockTargetStateOpenURL; 95 | urlMethod = this.setLockTargetStateOpenMethod; 96 | urlBody = this.setLockTargetStateOpenBody; 97 | urlForm = this.setLockTargetStateOpenForm; 98 | urlHeaders = this.setLockTargetStateOpenHeaders; 99 | } 100 | 101 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context, (function() { 102 | this.storage.setItemSync("http-webhook-lock-current-state-" + this.id, newHomeKitState); 103 | this.service.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, null); 104 | this.service.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitState, undefined, null); 105 | }).bind(this), (function() { 106 | this.storage.setItemSync("http-webhook-lock-current-state-" + this.id, Characteristic.LockCurrentState.UNKNOWN); 107 | this.service.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, null); 108 | this.service.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.UNKNOWN, undefined, null); 109 | }).bind(this)); 110 | }; 111 | 112 | HttpWebHookLockMechanismAccessory.prototype.getLockCurrentState = function(callback) { 113 | this.log.debug("Getting Current Lock State for '%s'...", this.id); 114 | var state = this.storage.getItemSync("http-webhook-lock-current-state-" + this.id); 115 | if (state === undefined) { 116 | state = Characteristic.LockCurrentState.SECURED; 117 | } 118 | callback(null, state); 119 | }; 120 | 121 | HttpWebHookLockMechanismAccessory.prototype.getServices = function() { 122 | return [ this.service, this.informationService ]; 123 | }; 124 | 125 | module.exports = HttpWebHookLockMechanismAccessory; 126 | -------------------------------------------------------------------------------- /src/Server.js: -------------------------------------------------------------------------------- 1 | const Constants = require('./Constants'); 2 | 3 | var request = require("request"); 4 | var http = require('http'); 5 | var https = require('https'); 6 | var url = require('url'); 7 | var auth = require('http-auth'); 8 | var fs = require('fs'); 9 | var Service, Characteristic; 10 | 11 | function Server(ServiceParam, CharacteristicParam, platform, platformConfig) { 12 | Service = ServiceParam; 13 | Characteristic = CharacteristicParam; 14 | 15 | this.platform = platform; 16 | this.log = platform.log; 17 | this.storage = platform.storage; 18 | 19 | this.webhookPort = platformConfig["webhook_port"] || Constants.DEFAULT_PORT; 20 | this.webhookListenHost = platformConfig["webhook_listen_host"] || Constants.DEFAULT_LISTEN_HOST; 21 | this.webhookEnableCORS = platformConfig["webhook_enable_cors"] || false; 22 | this.httpAuthUser = platformConfig["http_auth_user"] || null; 23 | this.httpAuthPass = platformConfig["http_auth_pass"] || null; 24 | this.https = platformConfig["https"] === true; 25 | this.httpsKeyFile = platformConfig["https_keyfile"]; 26 | this.httpsCertFile = platformConfig["https_certfile"]; 27 | } 28 | 29 | Server.prototype.setAccessories = function(accessories) { 30 | this.accessories = accessories; 31 | }; 32 | 33 | Server.prototype.createSSLCertificate = function() { 34 | this.log("Generating new ssl certificate."); 35 | var selfsigned = require('selfsigned'); 36 | var certAttrs = [{ name: 'homebridgeHttpWebhooks', value: 'homebridgeHttpWebhooks.com' , type: 'homebridgeHttpWebhooks'}]; 37 | var certOpts = { days: Constants.CERT_DAYS}; 38 | certOpts.extensions = [{ 39 | name: 'subjectAltName', 40 | altNames: [{ 41 | type: 2, 42 | value: 'homebridgeHttpWebhooks.com' 43 | }, { 44 | type: 2, 45 | value: 'localhost' 46 | }] 47 | }]; 48 | var pems = selfsigned.generate(certAttrs, certOpts); 49 | var cachedSSLCert = pems; 50 | cachedSSLCert.timestamp = Date.now(); 51 | cachedSSLCert.certVersion = Constants.CERT_VERSION; 52 | return cachedSSLCert; 53 | }; 54 | 55 | Server.prototype.getSSLServerOptions = function() { 56 | var sslServerOptions = {}; 57 | if(this.https) { 58 | if(!this.httpsKeyFile || !this.httpsCertFile) { 59 | this.log("Using automatic created ssl certificate."); 60 | var cachedSSLCert = this.storage.getItemSync("http-webhook-ssl-cert"); 61 | if(cachedSSLCert) { 62 | var certVersion = cachedSSLCert.certVersion; 63 | var timestamp = Date.now() - cachedSSLCert.timestamp; 64 | var diffInDays = timestamp/1000/60/60/24; 65 | if(diffInDays > Constants.CERT_DAYS - 1 || certVersion !== Constants.CERT_VERSION) { 66 | cachedSSLCert = null; 67 | } 68 | } 69 | if(!cachedSSLCert) { 70 | cachedSSLCert = this.createSSLCertificate(); 71 | this.storage.setItemSync("http-webhook-ssl-cert", cachedSSLCert); 72 | } 73 | 74 | sslServerOptions = { 75 | key: cachedSSLCert.private, 76 | cert: cachedSSLCert.cert 77 | }; 78 | } 79 | else { 80 | sslServerOptions = { 81 | key: fs.readFileSync(this.httpsKeyFile), 82 | cert: fs.readFileSync(this.httpsCertFile) 83 | }; 84 | } 85 | } 86 | return sslServerOptions; 87 | }; 88 | 89 | Server.prototype.createServerCallback = function() { 90 | return (function(request, response) { 91 | if(this.webhookEnableCORS) { 92 | // Based on https://gist.github.com/balupton/3696140 93 | response.setHeader('Access-Control-Allow-Origin', '*'); 94 | response.setHeader('Access-Control-Request-Method', '*'); 95 | response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST'); 96 | response.setHeader('Access-Control-Allow-Headers', '*'); 97 | if (request.method === 'OPTIONS') { 98 | response.writeHead(200); 99 | response.end(); 100 | return; 101 | } 102 | } 103 | var theUrl = request.url; 104 | var theUrlParts = url.parse(theUrl, true); 105 | var theUrlParams = theUrlParts.query; 106 | var body = []; 107 | request.on('error', (function(err) { 108 | this.log("[ERROR Http WebHook Server] Reason: %s.", err); 109 | }).bind(this)).on('data', function(chunk) { 110 | body.push(chunk); 111 | }).on('end', (function() { 112 | body = Buffer.concat(body).toString(); 113 | 114 | response.on('error', function(err) { 115 | this.log("[ERROR Http WebHook Server] Reason: %s.", err); 116 | }); 117 | 118 | response.statusCode = 200; 119 | response.setHeader('Content-Type', 'application/json'); 120 | 121 | if (!theUrlParams.accessoryId) { 122 | response.statusCode = 404; 123 | response.setHeader("Content-Type", "text/plain"); 124 | var errorText = "[ERROR Http WebHook Server] No accessoryId in request."; 125 | this.log(errorText); 126 | response.write(errorText); 127 | response.end(); 128 | } 129 | else { 130 | var responseBody = null; 131 | var accessoryId = theUrlParams.accessoryId; 132 | var found = false; 133 | for (var i = 0; i < this.accessories.length; i++) { 134 | var accessory = this.accessories[i]; 135 | if (accessory.id === accessoryId) { 136 | responseBody = accessory.changeFromServer(theUrlParams); 137 | found = true; 138 | break; 139 | } 140 | } 141 | if(responseBody) { 142 | response.write(JSON.stringify(responseBody)); 143 | response.end(); 144 | } 145 | else { 146 | response.statusCode = 404; 147 | response.setHeader("Content-Type", "text/plain"); 148 | var errorText = "[ERROR Http WebHook Server] AccessoryId '"+theUrlParams.accessoryId+"' did not return a response body from 'changeFromServer'."; 149 | if(!found) { 150 | errorText = "[ERROR Http WebHook Server] AccessoryId '"+theUrlParams.accessoryId+"' not found."; 151 | } 152 | this.log(errorText); 153 | response.write(errorText); 154 | response.end(); 155 | } 156 | } 157 | }).bind(this)); 158 | }).bind(this); 159 | }; 160 | 161 | Server.prototype.start = function() { 162 | var sslServerOptions = this.getSSLServerOptions(); 163 | 164 | var serverCallback = this.createServerCallback(); 165 | 166 | if (this.httpAuthUser && this.httpAuthPass) { 167 | var httpAuthUser = this.httpAuthUser; 168 | var httpAuthPass = this.httpAuthPass; 169 | basicAuth = auth.basic({ 170 | realm : "Auth required" 171 | }, function(username, password, callback) { 172 | callback(username === httpAuthUser && password === httpAuthPass); 173 | }); 174 | if(this.https) { 175 | https.createServer(basicAuth, sslServerOptions, serverCallback).listen(this.webhookPort, this.webhookListenHost); 176 | } 177 | else { 178 | http.createServer(basicAuth, serverCallback).listen(this.webhookPort, this.webhookListenHost); 179 | } 180 | } 181 | else { 182 | if(this.https) { 183 | https.createServer(sslServerOptions, serverCallback).listen(this.webhookPort, this.webhookListenHost); 184 | } 185 | else { 186 | http.createServer(serverCallback).listen(this.webhookPort, this.webhookListenHost); 187 | } 188 | } 189 | this.log("Started server for webhooks on port '%s' listening for host '%s'.", this.webhookPort, this.webhookListenHost); 190 | }; 191 | 192 | module.exports = Server; -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookGarageDoorOpenerAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookGarageDoorOpenerAccessory(ServiceParam, CharacteristicParam, platform, garageDoorOpenerConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = garageDoorOpenerConfig["id"]; 13 | this.name = garageDoorOpenerConfig["name"]; 14 | this.type = "garagedooropener"; 15 | this.rejectUnauthorized = garageDoorOpenerConfig["rejectUnauthorized"] === undefined ? true: garageDoorOpenerConfig["rejectUnauthorized"] === true; 16 | this.setTargetDoorStateOpenURL = garageDoorOpenerConfig["open_url"] || ""; 17 | this.setTargetDoorStateOpenMethod = garageDoorOpenerConfig["open_method"] || "GET"; 18 | this.setTargetDoorStateOpenBody = garageDoorOpenerConfig["open_body"] || ""; 19 | this.setTargetDoorStateOpenForm = garageDoorOpenerConfig["open_form"] || ""; 20 | this.setTargetDoorStateOpenHeaders = garageDoorOpenerConfig["open_headers"] || "{}"; 21 | this.setTargetDoorStateCloseURL = garageDoorOpenerConfig["close_url"] || ""; 22 | this.setTargetDoorStateCloseMethod = garageDoorOpenerConfig["close_method"] || "GET"; 23 | this.setTargetDoorStateCloseBody = garageDoorOpenerConfig["close_body"] || ""; 24 | this.setTargetDoorStateCloseForm = garageDoorOpenerConfig["close_form"] || ""; 25 | this.setTargetDoorStateCloseHeaders = garageDoorOpenerConfig["close_headers"] || "{}"; 26 | 27 | this.informationService = new Service.AccessoryInformation(); 28 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 29 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookGarageDoorOpenerAccessory-" + this.name); 30 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookGarageDoorOpenerAccessory-" + this.id); 31 | 32 | this.service = new Service.GarageDoorOpener(this.name); 33 | this.service.getCharacteristic(Characteristic.TargetDoorState).on('get', this.getTargetDoorState.bind(this)).on('set', this.setTargetDoorState.bind(this)); 34 | this.service.getCharacteristic(Characteristic.CurrentDoorState).on('get', this.getCurrentDoorState.bind(this)); 35 | this.service.getCharacteristic(Characteristic.ObstructionDetected).on('get', this.getObstructionDetected.bind(this)); 36 | } 37 | 38 | HttpWebHookGarageDoorOpenerAccessory.prototype.changeFromServer = function(urlParams) { 39 | if (urlParams.currentdoorstate != null) { 40 | var cachedCurrentDoorState = this.storage.getItemSync("http-webhook-current-door-state-" + this.id); 41 | if (cachedCurrentDoorState === undefined) { 42 | cachedCurrentDoorState = Characteristic.CurrentDoorState.CLOSED; 43 | } 44 | this.storage.setItemSync("http-webhook-current-door-state-" + this.id, urlParams.currentdoorstate); 45 | if (cachedCurrentDoorState !== urlParams.currentdoorstate) { 46 | if (urlParams.currentdoorstate) { 47 | this.log("Change Current Door State for garage door opener to '%s'.", urlParams.currentdoorstate); 48 | this.service.getCharacteristic(Characteristic.CurrentDoorState).updateValue(urlParams.currentdoorstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 49 | } 50 | } 51 | } 52 | if (urlParams.targetdoorstate != null) { 53 | var cachedTargetDoorState = this.storage.getItemSync("http-webhook-target-door-state-" + this.id); 54 | if (cachedTargetDoorState === undefined) { 55 | cachedTargetDoorState = Characteristic.TargetDoorState.CLOSED; 56 | } 57 | this.storage.setItemSync("http-webhook-target-door-state-" + this.id, urlParams.targetdoorstate); 58 | if (cachedTargetDoorState !== urlParams.targetdoorstate) { 59 | if (urlParams.targetdoorstate) { 60 | this.log("Change Target Door State for garage door opener to '%s'.", urlParams.targetdoorstate); 61 | this.service.getCharacteristic(Characteristic.TargetDoorState).updateValue(urlParams.targetdoorstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 62 | } 63 | } 64 | } 65 | if (urlParams.obstructiondetected != null) { 66 | var cachedObstructionDetected = this.storage.getItemSync("http-webhook-obstruction-detected-" + this.id); 67 | if (cachedObstructionDetected === undefined) { 68 | cachedObstructionDetected = false; 69 | } 70 | this.storage.setItemSync("http-webhook-obstruction-detected-" + this.id, urlParams.obstructiondetected); 71 | if (cachedObstructionDetected !== urlParams.obstructiondetected) { 72 | if (urlParams.obstructiondetected) { 73 | this.log("Change Obstruction Detected for garage door opener to '%s'.", urlParams.obstructiondetected); 74 | this.service.getCharacteristic(Characteristic.ObstructionDetected).updateValue(urlParams.obstructiondetected, undefined, Constants.CONTEXT_FROM_WEBHOOK); 75 | } 76 | } 77 | } 78 | return { 79 | "success" : true, 80 | "currentState" : cachedCurrentDoorState, 81 | "targetState" : cachedTargetDoorState, 82 | "obstruction" : cachedObstructionDetected 83 | }; 84 | } 85 | 86 | HttpWebHookGarageDoorOpenerAccessory.prototype.getTargetDoorState = function(callback) { 87 | this.log("Getting current Target Door State for '%s'...", this.id); 88 | var state = this.storage.getItemSync("http-webhook-target-door-state-" + this.id); 89 | if (state === undefined) { 90 | state = Characteristic.TargetDoorState.CLOSED; 91 | } 92 | callback(null, state); 93 | }; 94 | 95 | HttpWebHookGarageDoorOpenerAccessory.prototype.setTargetDoorState = function(newState, callback, context) { 96 | this.log("Target Door State for '%s'...", this.id); 97 | this.storage.setItemSync("http-webhook-target-door-state-" + this.id, newState); 98 | 99 | var doOpen = newState === Characteristic.TargetDoorState.OPEN; 100 | var newHomeKitState = doOpen ? Characteristic.CurrentDoorState.OPEN : Characteristic.CurrentDoorState.CLOSED; 101 | var newHomeKitStateTarget = doOpen ? Characteristic.TargetDoorState.OPEN : Characteristic.TargetDoorState.CLOSED; 102 | var urlToCall = this.setTargetDoorStateCloseURL; 103 | var urlMethod = this.setTargetDoorStateCloseMethod; 104 | var urlBody = this.setTargetDoorStateCloseBody; 105 | var urlForm = this.setTargetDoorStateCloseForm; 106 | var urlHeaders = this.setTargetDoorStateCloseHeaders; 107 | if (doOpen) { 108 | urlToCall = this.setTargetDoorStateOpenURL; 109 | urlMethod = this.setTargetDoorStateOpenMethod; 110 | urlBody = this.setTargetDoorStateOpenBody; 111 | urlForm = this.setTargetDoorStateOpenForm; 112 | urlHeaders = this.setTargetDoorStateOpenHeaders; 113 | } 114 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context, (function() { 115 | this.service.getCharacteristic(Characteristic.TargetDoorState).updateValue(newHomeKitStateTarget, undefined, null); 116 | this.service.getCharacteristic(Characteristic.CurrentDoorState).updateValue(newHomeKitState, undefined, null); 117 | }).bind(this)); 118 | }; 119 | 120 | HttpWebHookGarageDoorOpenerAccessory.prototype.getCurrentDoorState = function(callback) { 121 | this.log("Getting Current Door State for '%s'...", this.id); 122 | var state = this.storage.getItemSync("http-webhook-current-door-state-" + this.id); 123 | if (state === undefined) { 124 | state = Characteristic.CurrentDoorState.CLOSED; 125 | } 126 | callback(null, state); 127 | }; 128 | 129 | HttpWebHookGarageDoorOpenerAccessory.prototype.getObstructionDetected = function(callback) { 130 | this.log("Getting Obstruction Detected for '%s'...", this.id); 131 | var state = this.storage.getItemSync("http-webhook-obstruction-detected-" + this.id); 132 | if (state === undefined) { 133 | state = false; 134 | } 135 | callback(null, state); 136 | }; 137 | 138 | HttpWebHookGarageDoorOpenerAccessory.prototype.getServices = function() { 139 | return [ this.service, this.informationService ]; 140 | }; 141 | 142 | module.exports = HttpWebHookGarageDoorOpenerAccessory; -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookSensorAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | 3 | function HttpWebHookSensorAccessory(ServiceParam, CharacteristicParam, platform, sensorConfig) { 4 | Service = ServiceParam; 5 | Characteristic = CharacteristicParam; 6 | 7 | this.platform = platform; 8 | this.log = platform.log; 9 | this.storage = platform.storage; 10 | 11 | this.id = sensorConfig["id"]; 12 | this.name = sensorConfig["name"]; 13 | this.type = sensorConfig["type"]; 14 | this.autoRelease = sensorConfig["autoRelease"]; 15 | this.autoReleaseTime = sensorConfig["autoReleaseTime"] || Constants.DEFAULT_SENSOR_TIMEOUT; 16 | 17 | this.informationService = new Service.AccessoryInformation(); 18 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 19 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookSensorAccessory-" + this.name); 20 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookSensorAccessory-" + this.id); 21 | 22 | if (this.type === "contact") { 23 | this.service = new Service.ContactSensor(this.name); 24 | this.service.getCharacteristic(Characteristic.ContactSensorState).on('get', this.getState.bind(this)); 25 | } 26 | else if (this.type === "motion") { 27 | this.service = new Service.MotionSensor(this.name); 28 | this.service.getCharacteristic(Characteristic.MotionDetected).on('get', this.getState.bind(this)); 29 | } 30 | else if (this.type === "occupancy") { 31 | this.service = new Service.OccupancySensor(this.name); 32 | this.service.getCharacteristic(Characteristic.OccupancyDetected).on('get', this.getState.bind(this)); 33 | } 34 | else if (this.type === "smoke") { 35 | this.service = new Service.SmokeSensor(this.name); 36 | this.service.getCharacteristic(Characteristic.SmokeDetected).on('get', this.getState.bind(this)); 37 | } 38 | else if (this.type === "humidity") { 39 | this.service = new Service.HumiditySensor(this.name); 40 | this.service.getCharacteristic(Characteristic.CurrentRelativeHumidity).on('get', this.getState.bind(this)); 41 | } 42 | else if (this.type === "temperature") { 43 | this.service = new Service.TemperatureSensor(this.name); 44 | this.service.getCharacteristic(Characteristic.CurrentTemperature).setProps({ 45 | minValue : -100, 46 | maxValue : 140 47 | }).on('get', this.getState.bind(this)); 48 | } 49 | else if (this.type === "airquality") { 50 | this.service = new Service.AirQualitySensor(this.name); 51 | this.service.getCharacteristic(Characteristic.AirQuality).on('get', this.getState.bind(this)); 52 | } 53 | else if (this.type === "light") { 54 | this.service = new Service.LightSensor(this.name); 55 | this.service.getCharacteristic(Characteristic.CurrentAmbientLightLevel).on('get', this.getState.bind(this)); 56 | } 57 | else if (this.type === "leak") { 58 | this.service = new Service.LeakSensor(this.name); 59 | this.service.getCharacteristic(Characteristic.LeakDetected).on('get', this.getState.bind(this)); 60 | } 61 | } 62 | 63 | HttpWebHookSensorAccessory.prototype.changeFromServer = function(urlParams) { 64 | var cached = this.storage.getItemSync("http-webhook-" + this.id); 65 | var isNumberBased = this.type === "leak" || this.type === "humidity" || this.type === "temperature" || this.type === "airquality" || this.type === "light"; 66 | if (cached === undefined) { 67 | cached = isNumberBased ? 0 : false; 68 | } 69 | var noUrlValue = isNumberBased ? urlParams.value === undefined : urlParams.state === undefined; 70 | if (noUrlValue) { 71 | this.log.debug("No urlValue"); 72 | return { 73 | "success" : true, 74 | "state" : cached 75 | }; 76 | } 77 | var urlValue = isNumberBased ? urlParams.value : urlParams.state === "true"; 78 | this.log.debug("urlValue: "+ urlValue); 79 | this.storage.setItemSync("http-webhook-" + this.id, urlValue); 80 | this.log.debug("cached: "+ cached); 81 | this.log.debug("cached !== urlValue: "+ (cached !== urlValue)); 82 | if (cached !== urlValue) { 83 | this.log("Change HomeKit value for " + this.type + " sensor to '%s'.", urlValue); 84 | 85 | if (this.type === "contact") { 86 | this.service.getCharacteristic(Characteristic.ContactSensorState).updateValue(urlValue ? Characteristic.ContactSensorState.CONTACT_DETECTED : Characteristic.ContactSensorState.CONTACT_NOT_DETECTED, undefined, Constants.CONTEXT_FROM_WEBHOOK); 87 | if (this.autoRelease) { 88 | setTimeout(function() { 89 | this.storage.setItemSync("http-webhook-" + this.id, true); 90 | this.service.getCharacteristic(Characteristic.ContactSensorState).updateValue(Characteristic.ContactSensorState.CONTACT_DETECTED, undefined, Constants.CONTEXT_FROM_TIMEOUTCALL); 91 | }.bind(this), this.autoReleaseTime); 92 | } 93 | } 94 | else if (this.type === "motion") { 95 | this.service.getCharacteristic(Characteristic.MotionDetected).updateValue(urlValue, undefined, Constants.CONTEXT_FROM_WEBHOOK); 96 | if (this.autoRelease) { 97 | setTimeout(function() { 98 | this.storage.setItemSync("http-webhook-" + this.id, false); 99 | this.service.getCharacteristic(Characteristic.MotionDetected).updateValue(false, undefined, Constants.CONTEXT_FROM_TIMEOUTCALL); 100 | }.bind(this), this.autoReleaseTime); 101 | } 102 | } 103 | else if (this.type === "occupancy") { 104 | this.service.getCharacteristic(Characteristic.OccupancyDetected).updateValue(urlValue ? Characteristic.OccupancyDetected.OCCUPANCY_DETECTED : Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED, undefined, Constants.CONTEXT_FROM_WEBHOOK); 105 | if (this.autoRelease) { 106 | setTimeout(function() { 107 | this.storage.setItemSync("http-webhook-" + this.id, false); 108 | this.service.getCharacteristic(Characteristic.OccupancyDetected).updateValue(Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED, undefined, Constants.CONTEXT_FROM_TIMEOUTCALL); 109 | }.bind(this), this.autoReleaseTime); 110 | } 111 | } 112 | else if (this.type === "smoke") { 113 | this.service.getCharacteristic(Characteristic.SmokeDetected).updateValue(urlValue ? Characteristic.SmokeDetected.SMOKE_DETECTED : Characteristic.SmokeDetected.SMOKE_NOT_DETECTED, undefined, Constants.CONTEXT_FROM_WEBHOOK); 114 | } 115 | else if (this.type === "humidity") { 116 | this.service.getCharacteristic(Characteristic.CurrentRelativeHumidity).updateValue(urlValue, undefined, Constants.CONTEXT_FROM_WEBHOOK); 117 | } 118 | else if (this.type === "temperature") { 119 | this.service.getCharacteristic(Characteristic.CurrentTemperature).updateValue(urlValue, undefined, Constants.CONTEXT_FROM_WEBHOOK); 120 | } 121 | else if (this.type === "airquality") { 122 | this.service.getCharacteristic(Characteristic.AirQuality).updateValue(urlValue, undefined, Constants.CONTEXT_FROM_WEBHOOK); 123 | } 124 | else if (this.type === "light") { 125 | urlValue = parseFloat(urlValue) 126 | this.service.getCharacteristic(Characteristic.CurrentAmbientLightLevel).updateValue(urlValue, undefined, Constants.CONTEXT_FROM_WEBHOOK); 127 | } 128 | else if (this.type === "leak") { 129 | this.service.getCharacteristic(Characteristic.LeakDetected).updateValue(urlValue, undefined, Constants.CONTEXT_FROM_WEBHOOK); 130 | } 131 | 132 | } 133 | return { 134 | "success" : true 135 | }; 136 | }; 137 | 138 | HttpWebHookSensorAccessory.prototype.getState = function(callback) { 139 | this.log.debug("Getting current state for '%s'...", this.id); 140 | var state = this.storage.getItemSync("http-webhook-" + this.id); 141 | this.log.debug("State for '%s' is '%s'", this.id, state); 142 | if (state === undefined) { 143 | state = false; 144 | } 145 | if (this.type === "contact") { 146 | callback(null, state ? Characteristic.ContactSensorState.CONTACT_DETECTED : Characteristic.ContactSensorState.CONTACT_NOT_DETECTED); 147 | } 148 | else if (this.type === "smoke") { 149 | callback(null, state ? Characteristic.SmokeDetected.SMOKE_DETECTED : Characteristic.SmokeDetected.SMOKE_NOT_DETECTED); 150 | } 151 | else if (this.type === "occupancy") { 152 | callback(null, state ? Characteristic.OccupancyDetected.OCCUPANCY_DETECTED : Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED); 153 | } 154 | else if (this.type === "light") { 155 | callback(null, parseFloat(state)); 156 | } 157 | else { 158 | callback(null, state); 159 | } 160 | }; 161 | 162 | HttpWebHookSensorAccessory.prototype.getServices = function() { 163 | return [ this.service, this.informationService ]; 164 | }; 165 | 166 | module.exports = HttpWebHookSensorAccessory; 167 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookThermostatAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookThermostatAccessory(ServiceParam, CharacteristicParam, platform, thermostatConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = thermostatConfig["id"]; 13 | this.name = thermostatConfig["name"]; 14 | this.type = "thermostat"; 15 | this.minValue = thermostatConfig["minTemp"] || 15; 16 | this.maxValue = thermostatConfig["maxTemp"] || 30; 17 | this.minStep = thermostatConfig["minStep"] || 0.5; 18 | this.rejectUnauthorized = thermostatConfig["rejectUnauthorized"] === undefined ? true: thermostatConfig["rejectUnauthorized"] === true; 19 | this.setTargetTemperatureURL = thermostatConfig["set_target_temperature_url"] || ""; 20 | this.setTargetTemperatureMethod = thermostatConfig["set_target_temperature_method"] || "GET"; 21 | this.setTargetTemperatureBody = thermostatConfig["set_target_temperature_body"] || ""; 22 | this.setTargetTemperatureForm = thermostatConfig["set_target_temperature_form"] || ""; 23 | this.setTargetTemperatureHeaders = thermostatConfig["set_target_temperature_headers"] || "{}"; 24 | this.setTargetHeatingCoolingStateURL = thermostatConfig["set_target_heating_cooling_state_url"] || ""; 25 | this.setTargetHeatingCoolingStateMethod = thermostatConfig["set_target_heating_cooling_state_method"] || "GET"; 26 | this.setTargetHeatingCoolingStateBody = thermostatConfig["set_target_heating_cooling_state_body"] || ""; 27 | this.setTargetHeatingCoolingStateForm = thermostatConfig["set_target_heating_cooling_state_form"] || ""; 28 | this.setTargetHeatingCoolingStateHeaders = thermostatConfig["set_target_heating_cooling_state_headers"] || "{}"; 29 | 30 | this.informationService = new Service.AccessoryInformation(); 31 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 32 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookThermostatAccessory-" + this.name); 33 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookThermostatAccessory-" + this.id); 34 | 35 | this.service = new Service.Thermostat(this.name); 36 | this.service.getCharacteristic(Characteristic.TargetHeatingCoolingState).on('get', this.getTargetHeatingCoolingState.bind(this)).on('set', this.setTargetHeatingCoolingState.bind(this)); 37 | this.service.getCharacteristic(Characteristic.CurrentHeatingCoolingState).on('get', this.getCurrentHeatingCoolingState.bind(this)); 38 | this.service.getCharacteristic(Characteristic.TargetTemperature).on('get', this.getTargetTemperature.bind(this)).on('set', this.setTargetTemperature.bind(this)).setProps({ 39 | minValue: this.minValue, 40 | maxValue: this.maxValue, 41 | minStep: this.minStep 42 | }); 43 | this.service.getCharacteristic(Characteristic.CurrentTemperature).on('get', this.getCurrentTemperature.bind(this)); 44 | } 45 | 46 | HttpWebHookThermostatAccessory.prototype.changeFromServer = function(urlParams) { 47 | if (urlParams.currenttemperature != null) { 48 | var cachedCurTemp = this.storage.getItemSync("http-webhook-current-temperature-" + this.id); 49 | if (cachedCurTemp === undefined) { 50 | cachedCurTemp = 0; 51 | } 52 | this.storage.setItemSync("http-webhook-current-temperature-" + this.id, urlParams.currenttemperature); 53 | if (cachedCurTemp !== urlParams.currenttemperature) { 54 | this.log("Change current Temperature for thermostat to '%d'.", urlParams.currenttemperature); 55 | this.service.getCharacteristic(Characteristic.CurrentTemperature).updateValue(urlParams.currenttemperature, undefined, Constants.CONTEXT_FROM_WEBHOOK); 56 | } 57 | } 58 | if (urlParams.targettemperature != null) { 59 | var cachedCurTemp = this.storage.getItemSync("http-webhook-target-temperature-" + this.id); 60 | if (cachedCurTemp === undefined) { 61 | cachedCurTemp = 10; 62 | } 63 | this.storage.setItemSync("http-webhook-target-temperature-" + this.id, urlParams.targettemperature); 64 | if (cachedCurTemp !== urlParams.targettemperature) { 65 | this.log("Change target Temperature for thermostat to '%d'.", urlParams.targettemperature); 66 | this.service.getCharacteristic(Characteristic.TargetTemperature).updateValue(urlParams.targettemperature, undefined, Constants.CONTEXT_FROM_WEBHOOK); 67 | } 68 | } 69 | if (urlParams.currentstate != null) { 70 | var cachedState = this.storage.getItemSync("http-webhook-current-heating-cooling-state-" + this.id); 71 | if (cachedState === undefined) { 72 | cachedState = Characteristic.CurrentHeatingCoolingState.OFF; 73 | } 74 | this.storage.setItemSync("http-webhook-current-heating-cooling-state-" + this.id, urlParams.currentstate); 75 | if (cachedState !== urlParams.currentstate) { 76 | if (urlParams.currentstate) { 77 | this.log("Change Current Heating Cooling State for thermostat to '%s'.", urlParams.currentstate); 78 | this.service.getCharacteristic(Characteristic.CurrentHeatingCoolingState).updateValue(urlParams.currentstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 79 | } 80 | } 81 | } 82 | if (urlParams.targetstate != null) { 83 | var cachedState = this.storage.getItemSync("http-webhook-target-heating-cooling-state-" + this.id); 84 | if (cachedState === undefined) { 85 | cachedState = Characteristic.TargetHeatingCoolingState.OFF; 86 | } 87 | this.storage.setItemSync("http-webhook-target-heating-cooling-state-" + this.id, urlParams.targetstate); 88 | if (cachedState !== urlParams.targetstate) { 89 | if (urlParams.targetstate) { 90 | this.log("Change Target Heating Cooling State for thermostat to '%s'.", urlParams.targetstate); 91 | this.service.getCharacteristic(Characteristic.TargetHeatingCoolingState).updateValue(urlParams.targetstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 92 | } 93 | } 94 | } 95 | return { 96 | "success" : true 97 | }; 98 | } 99 | 100 | HttpWebHookThermostatAccessory.prototype.getTargetTemperature = function(callback) { 101 | this.log.debug("Getting target temperature for '%s'...", this.id); 102 | var temp = this.storage.getItemSync("http-webhook-target-temperature-" + this.id); 103 | if (temp === undefined) { 104 | temp = 20; 105 | } 106 | callback(null, temp); 107 | }; 108 | 109 | HttpWebHookThermostatAccessory.prototype.setTargetTemperature = function(temp, callback, context) { 110 | this.log("Target temperature for '%s'...", this.id); 111 | this.storage.setItemSync("http-webhook-target-temperature-" + this.id, temp); 112 | var urlToCall = this.setTargetTemperatureURL.replace("%f", temp); 113 | var urlMethod = this.setTargetTemperatureMethod; 114 | var urlBody = this.setTargetTemperatureBody; 115 | var urlForm = this.setTargetTemperatureForm; 116 | var urlHeaders = this.setTargetTemperatureHeaders; 117 | 118 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 119 | }; 120 | 121 | HttpWebHookThermostatAccessory.prototype.getCurrentTemperature = function(callback) { 122 | this.log.debug("Getting current temperature for '%s'...", this.id); 123 | var temp = this.storage.getItemSync("http-webhook-current-temperature-" + this.id); 124 | if (temp === undefined) { 125 | temp = 20; 126 | } 127 | callback(null, temp); 128 | }; 129 | 130 | HttpWebHookThermostatAccessory.prototype.getTargetHeatingCoolingState = function(callback) { 131 | this.log.debug("Getting current Target Heating Cooling state for '%s'...", this.id); 132 | var state = this.storage.getItemSync("http-webhook-target-heating-cooling-state-" + this.id); 133 | if (state === undefined) { 134 | state = Characteristic.TargetHeatingCoolingState.OFF; 135 | } 136 | callback(null, state); 137 | }; 138 | 139 | HttpWebHookThermostatAccessory.prototype.setTargetHeatingCoolingState = function(newState, callback, context) { 140 | this.log("Target Heating Cooling state for '%s'...", this.id); 141 | this.storage.setItemSync("http-webhook-target-heating-cooling-state-" + this.id, newState); 142 | var urlToCall = this.setTargetHeatingCoolingStateURL.replace("%b", newState); 143 | var urlMethod = this.setTargetHeatingCoolingStateMethod; 144 | var urlBody = this.setTargetHeatingCoolingStateBody; 145 | var urlForm = this.setTargetHeatingCoolingStateForm; 146 | var urlHeaders = this.setTargetHeatingCoolingStateHeaders; 147 | 148 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 149 | }; 150 | 151 | HttpWebHookThermostatAccessory.prototype.getCurrentHeatingCoolingState = function(callback) { 152 | this.log.debug("Getting current Target Heating Cooling state for '%s'...", this.id); 153 | var state = this.storage.getItemSync("http-webhook-current-heating-cooling-state-" + this.id); 154 | if (state === undefined) { 155 | state = Characteristic.CurrentHeatingCoolingState.OFF; 156 | } 157 | callback(null, state); 158 | }; 159 | 160 | HttpWebHookThermostatAccessory.prototype.getServices = function() { 161 | return [ this.service, this.informationService ]; 162 | }; 163 | 164 | module.exports = HttpWebHookThermostatAccessory; 165 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### 0.1.18 2 | 3 | Bugfix: 4 | 5 | - fixed "nan" log when using fanv2 (thanks to shirnschall). 6 | 7 | ### 0.1.17 8 | 9 | Breaking change: 10 | - Thermostat parameter was wrong. Documentation stated "maxTemp" but was "maxValue". Now changed "maxValue" to "maxTemp" according to documentation (thanks to mgoeppl) 11 | 12 | ### 0.1.16 13 | 14 | New features: 15 | - Added value support (thanks to emptygalaxy) 16 | 17 | ### 0.1.15 18 | 19 | New features: 20 | - Support minValue, maxValue and minStep for thermostats (thanks to NikDevx) 21 | 22 | ### 0.1.14 23 | 24 | New features: 25 | - Support http method PATCH (thanks to supermamon) 26 | 27 | ### 0.1.13 28 | 29 | New features: 30 | 31 | - Added CO2 sensor (thanks to jwktje) 32 | 33 | ### 0.1.12 34 | 35 | New features: 36 | 37 | - Added Fanv2 (thanks to p-x9) 38 | 39 | ### 0.1.11 40 | 41 | Bugfix: 42 | 43 | - Reduced some more log messages by using debug (thanks to jsiegenthaler). 44 | 45 | ### 0.1.10 46 | 47 | New features: 48 | 49 | - You can now set "rejectUnauthorized" to false on each accessory to allow calls via https on using unsecure certificate. 50 | 51 | Bugfix: 52 | 53 | - Reduced some log messages by using debug (thanks to jsiegenthaler). 54 | 55 | ### 0.1.9 56 | 57 | Bugfix: 58 | 59 | - Sensors now return cached value if state and value is not provided in URL (thanks to tritter). 60 | 61 | ### 0.1.8 62 | 63 | Bugfix: 64 | 65 | - Stateless switch web hook did not return a response. 66 | 67 | 68 | ### 0.1.7 69 | 70 | Bugfix: 71 | 72 | - Missed to add "webhook_enable_cors" and "auto_set_current_position" to config.schema.json for Config UI X. 73 | 74 | ### 0.1.6 75 | 76 | New features: 77 | 78 | - You can now set "webhook_enable_cors" to true to enable cors for webhook server (thanks to konstantinkobs). 79 | 80 | ### 0.1.5 81 | 82 | New features: 83 | 84 | - You can now set "auto_set_current_position" in for window coverings to true if you dont use callbacks to let your covering give feedback of current position back to homekit. 85 | 86 | ### 0.1.4 87 | 88 | Bugfix: 89 | 90 | - Fixed bug as pushbutton does not have a cached state. 91 | 92 | ### 0.1.3 93 | 94 | Bugfix: 95 | 96 | - Fixed bug if no url is called and no success callback is set. 97 | 98 | ### 0.1.2 99 | 100 | New features: 101 | 102 | - Support Config UI X (thanks to donavanbecker). 103 | 104 | ### 0.1.1 105 | 106 | New features: 107 | 108 | - You can now query the state of security system by avoiding currentstate and targetstate parameter. 109 | 110 | Bugfix: 111 | 112 | - Fixed bug that success callback is not called if no url is called. 113 | - Fixed bug, that security system shows correct status after restart. 114 | 115 | ### 0.1.0 116 | 117 | Major restructuring for better maintainance. I tried best to not break anything. If I did, please report issue and I will fix it. 118 | 119 | New features: 120 | 121 | - "on_form"/"off_form" now supported for outlets 122 | 123 | ### 0.0.62 124 | 125 | New features: 126 | 127 | - You can now change the host to listen to. Default is "0.0.0.0". For ipv6 you can use "::". 128 | 129 | ### 0.0.61 130 | 131 | Bugfix: 132 | 133 | - Now all http status codes >= 200 && < 300 are treated as success. 134 | 135 | ### 0.0.60 136 | 137 | New features: 138 | 139 | - Added brightness to light. 140 | 141 | ### 0.0.59 142 | 143 | New features: 144 | 145 | - Added Leak Sensor (thanks to RamSet) 146 | 147 | ### 0.0.58 148 | 149 | New features: 150 | 151 | - Set Manufacturer, Model and SerialNumber to address issue with Eve App v4.2+ (https://github.com/homebridge/homebridge/issues/2503) 152 | 153 | ### 0.0.57 154 | 155 | New features: 156 | 157 | - Added subjectAltName to generated SSL cert. 158 | - Support SSL certificate update if code changes by using a version number. 159 | - Support own SSL certificates using properties httpsKeyFile and httpsCertFile. 160 | 161 | ### 0.0.56 162 | 163 | Bugfix: 164 | 165 | - Webhooks didn't work anymore. Please update. 166 | 167 | ### 0.0.55 168 | 169 | New features: 170 | 171 | - You can now secure the webhook server using a self signed ssl certificate (beta state). 172 | 173 | ### 0.0.54 174 | 175 | Bugfix: 176 | 177 | - Added ReadMe about cache directory. 178 | 179 | ### 0.0.52 180 | 181 | New features: 182 | 183 | - Added auto release for contact sensor. Added auto release time to contact, motion, and occupancy sensor. 184 | 185 | ### 0.0.51 186 | 187 | Bugfix: 188 | 189 | - Return valid Json in webhook (thanks to mshulman) 190 | 191 | ### 0.0.50 192 | 193 | New features: 194 | 195 | - You can now set body, form and custom headers for switches, pushbuttons, lights, thermostats, garage door openers, window coverings, lock mechanism & security system. (by EddyK69) 196 | 197 | ### 0.0.49 198 | 199 | New features: 200 | 201 | - You can now set custom headers for switches. 202 | - You can now set body and custom headers for outlets. 203 | 204 | ### 0.0.48 205 | 206 | Bugfix: 207 | 208 | - Fixed security system spinning wheel in homekit after action. 209 | 210 | ### 0.0.47 211 | 212 | Bugfix: 213 | 214 | - Fixed garage door spinning wheel visiable in homekit after action. 215 | 216 | ### 0.0.46 217 | 218 | New features: 219 | 220 | - Added window coverings. (thanks to kaowiec) 221 | 222 | ### 0.0.45 223 | 224 | Bugfix: 225 | 226 | - Fixed lock mechanism. 227 | 228 | ### 0.0.44 229 | 230 | Bugfix: 231 | 232 | - Now a temperature sensor can handle negative values. 233 | 234 | ### 0.0.43 235 | 236 | New features: 237 | 238 | - Added light sensor. (thanks to gorootde) 239 | 240 | Bugfix: 241 | 242 | - Fixed auto release for motion and occupancy sensor. (thanks to kovalev-sergey) 243 | 244 | ### 0.0.42 245 | 246 | New features: 247 | 248 | - Updated dependency to request. 249 | 250 | ### 0.0.41 251 | 252 | New features: 253 | 254 | - Added lock mechanism. (thanks to kaowiec). 255 | 256 | ### 0.0.40 257 | 258 | New features: 259 | 260 | - Added stateless switches. (thanks to BetoRn). 261 | - Added request body support for POST and PUT request for switches. (thanks to BetoRn). 262 | - Added auto release for motion and occupancy sensor. (thanks to BetoRn). 263 | 264 | ### 0.0.39 265 | 266 | New features: 267 | 268 | - Added Garage Door Opener accessory. (thanks to FlyingLemming). 269 | 270 | ### 0.0.38 271 | 272 | New features: 273 | 274 | - Added a new accessory to support security system. (thanks to jcbriones). 275 | 276 | ## 0.0.37 277 | 278 | Bugfix: 279 | 280 | - Listen to Ipv4. 281 | 282 | ### 0.0.36 283 | 284 | New features: 285 | 286 | - Added air quality as sensor (thanks to tansuka). 287 | 288 | ### 0.0.35 289 | 290 | New features: 291 | 292 | - Added http authentication if desired (thanks to paolotremadio). 293 | 294 | ### 0.0.34 295 | 296 | Bugfix: 297 | 298 | - Last fix wasn't correct. Removed cache handling for push button as state is always false. 299 | 300 | ### 0.0.33 301 | 302 | Bugfix: 303 | 304 | - Fix issue where push button doesn't change its cache state back to false. 305 | 306 | ### 0.0.32 307 | 308 | New features: 309 | 310 | - Added support for outlet. 311 | 312 | ### 0.0.31 313 | 314 | New features: 315 | 316 | - Added support for temperature, humidity and thermostats (thanks to iEns). 317 | 318 | ### 0.0.30 319 | 320 | New features: 321 | 322 | - Support setting the request method. Only GET and PUT are tested. Default is still GET. 323 | 324 | # 0.0.29 325 | 326 | Bugfix: 327 | 328 | - Use correct type to update smoke sensor state via webhook. 329 | - Switch back pushbutton correctly using timeout if it was updated to state = true via webhook. 330 | 331 | ## 0.0.28 332 | 333 | Bugfix: 334 | 335 | - Now uses updateValue instead of setValue to update iOS correctly. 336 | 337 | ## 0.0.27 338 | 339 | New features: 340 | 341 | - Webhooks no longer call the on/off/push url as in most cases the webhook gets called from an external smart home system that already knows the new state as it send the webhook call. 342 | 343 | ## 0.0.26 344 | 345 | New features: 346 | 347 | - Added light. Currently just on/off is supported. 348 | 349 | ## 0.0.25 350 | 351 | Bugfix: 352 | 353 | - Now Uses the Characteristic's Enumeration for Value Reporting. 354 | - Now a webhook call only triggers homekit change if the state is not the same as in the cache. This fixed an issue where a homekit change was triggered twice, once by homekit and once by the resulting webhook call of an external system that also reacts on changes. 355 | 356 | ## 0.0.24 357 | 358 | Bugfix: 359 | 360 | - Push buttons without url do now switch state back correctly. 361 | 362 | ## 0.0.23 363 | 364 | New features: 365 | 366 | - Added push buttons. The button will be released automatically. 367 | 368 | ## 0.0.22 369 | 370 | Bugfix: 371 | 372 | - Switches without on or off url do now switch state correctly. 373 | 374 | ## 0.0.21 375 | 376 | New features: 377 | 378 | - You can now call the webhook URL without the state parameter to get the current state of the accessory. 379 | 380 | ## 0.0.20 381 | 382 | New features: 383 | 384 | - Added occupancy sensor (thanks to wr). 385 | 386 | ## 0.0.19 387 | 388 | Bugfix: 389 | 390 | - Removed some logging. 391 | 392 | ## 0.0.18 393 | 394 | Bugfix: 395 | 396 | - Added context to setValue call. 397 | 398 | ## 0.0.17 399 | 400 | Bugfix: 401 | 402 | - Fixed infinite loop for switches. 403 | 404 | ## 0.0.16 405 | 406 | Bugfix: 407 | 408 | - Fixed switches one more time. 409 | 410 | ## 0.0.15 411 | 412 | Bugfix: 413 | 414 | - Fixed switches. 415 | 416 | ## 0.0.14 417 | 418 | New features: 419 | 420 | - Added switch. 421 | 422 | ## 0.0.13 423 | 424 | New features: 425 | 426 | - Added smoke sensor. 427 | 428 | ## 0.0.12 429 | 430 | Bugfix: 431 | 432 | - Fixed readme. 433 | 434 | ## 0.0.11 435 | 436 | Bugfix: 437 | 438 | - Fixed state values. 439 | 440 | ## 0.0.10 441 | 442 | Bugfix: 443 | 444 | - Fixed context. 445 | 446 | ## 0.0.9 447 | 448 | Bugfix: 449 | 450 | - Fixed variable. 451 | 452 | ## 0.0.8 453 | 454 | Bugfix: 455 | 456 | - Implemented getState. 457 | 458 | ## 0.0.7 459 | 460 | Bugfix: 461 | 462 | - Added missing dot. 463 | 464 | ## 0.0.6 465 | 466 | New features: 467 | 468 | - Added some logging. 469 | 470 | ## 0.0.5 471 | 472 | Bugfix: 473 | 474 | - Fix another copy and paste error. 475 | 476 | ## 0.0.4 477 | 478 | Bugfix: 479 | 480 | - Fix copy and paste error. 481 | 482 | ## 0.0.3 483 | 484 | Bugfix: 485 | 486 | - Fix context. 487 | 488 | ## 0.0.2 489 | 490 | Bugfix: 491 | 492 | - Removed unexpected ';'. 493 | 494 | ## 0.0.1 495 | 496 | Initial release version. 497 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookWindowCoveringAccessory.js: -------------------------------------------------------------------------------- 1 | const Constants = require('../../Constants'); 2 | const Util = require('../../Util'); 3 | 4 | function HttpWebHookWindowCoveringAccessory(ServiceParam, CharacteristicParam, platform, windowcoveringConfig) { 5 | Service = ServiceParam; 6 | Characteristic = CharacteristicParam; 7 | 8 | this.platform = platform; 9 | this.log = platform.log; 10 | this.storage = platform.storage; 11 | 12 | this.id = windowcoveringConfig["id"]; 13 | this.name = windowcoveringConfig["name"]; 14 | this.type = "windowcovering"; 15 | this.rejectUnauthorized = windowcoveringConfig["rejectUnauthorized"] === undefined ? true: windowcoveringConfig["rejectUnauthorized"] === true; 16 | this.setTargetPositionOpenURL = windowcoveringConfig["open_url"] || ""; 17 | this.setTargetPositionOpenMethod = windowcoveringConfig["open_method"] || "GET"; 18 | this.setTargetPositionOpenBody = windowcoveringConfig["open_body"] || ""; 19 | this.setTargetPositionOpenForm = windowcoveringConfig["open_form"] || ""; 20 | this.setTargetPositionOpenHeaders = windowcoveringConfig["open_headers"] || "{}"; 21 | this.setTargetPositionOpen20URL = windowcoveringConfig["open_20_url"] || ""; 22 | this.setTargetPositionOpen20Method = windowcoveringConfig["open_20_method"] || "GET"; 23 | this.setTargetPositionOpen20Body = windowcoveringConfig["open_20_body"] || ""; 24 | this.setTargetPositionOpen20Form = windowcoveringConfig["open_20_form"] || ""; 25 | this.setTargetPositionOpen20Headers = windowcoveringConfig["open_20_headers"] || "{}"; 26 | this.setTargetPositionOpen40URL = windowcoveringConfig["open_40_url"] || ""; 27 | this.setTargetPositionOpen40Method = windowcoveringConfig["open_40_method"] || "GET"; 28 | this.setTargetPositionOpen40Body = windowcoveringConfig["open_40_body"] || ""; 29 | this.setTargetPositionOpen40Form = windowcoveringConfig["open_40_form"] || ""; 30 | this.setTargetPositionOpen40Headers = windowcoveringConfig["open_40_headers"] || "{}"; 31 | this.setTargetPositionOpen60URL = windowcoveringConfig["open_60_url"] || ""; 32 | this.setTargetPositionOpen60Method = windowcoveringConfig["open_60_method"] || "GET"; 33 | this.setTargetPositionOpen60Body = windowcoveringConfig["open_60_body"] || ""; 34 | this.setTargetPositionOpen60Form = windowcoveringConfig["open_60_form"] || ""; 35 | this.setTargetPositionOpen60Headers = windowcoveringConfig["open_60_headers"] || "{}"; 36 | this.setTargetPositionOpen80URL = windowcoveringConfig["open_80_url"] || ""; 37 | this.setTargetPositionOpen80Method = windowcoveringConfig["open_80_method"] || "GET"; 38 | this.setTargetPositionOpen80Body = windowcoveringConfig["open_80_body"] || ""; 39 | this.setTargetPositionOpen80Form = windowcoveringConfig["open_80_form"] || ""; 40 | this.setTargetPositionOpen80Headers = windowcoveringConfig["open_80_headers"] || "{}"; 41 | this.setTargetPositionCloseURL = windowcoveringConfig["close_url"] || ""; 42 | this.setTargetPositionCloseMethod = windowcoveringConfig["close_method"] || "GET"; 43 | this.setTargetPositionCloseBody = windowcoveringConfig["close_body"] || ""; 44 | this.setTargetPositionCloseForm = windowcoveringConfig["close_form"] || ""; 45 | this.setTargetPositionCloseHeaders = windowcoveringConfig["close_headers"] || "{}"; 46 | this.autoSetCurrentPosition = windowcoveringConfig["auto_set_current_position"] || false; 47 | 48 | this.informationService = new Service.AccessoryInformation(); 49 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 50 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookWindowCoveringAccessory-" + this.name); 51 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookWindowCoveringAccessory-" + this.id); 52 | 53 | this.service = new Service.WindowCovering(this.name); 54 | this.service.getCharacteristic(Characteristic.TargetPosition).on('get', this.getTargetPosition.bind(this)).on('set', this.setTargetPosition.bind(this)); 55 | this.service.getCharacteristic(Characteristic.CurrentPosition).on('get', this.getCurrentPosition.bind(this)); 56 | this.service.getCharacteristic(Characteristic.PositionState).on('get', this.getPositionState.bind(this)); 57 | } 58 | 59 | HttpWebHookWindowCoveringAccessory.prototype.changeFromServer = function(urlParams) { 60 | if (urlParams.currentposition != null) { 61 | var cachedCurrentPosition = this.storage.getItemSync("http-webhook-current-position-" + this.id); 62 | if (cachedCurrentPosition === undefined) { 63 | cachedCurrentPosition = 100; 64 | } 65 | this.storage.setItemSync("http-webhook-current-position-" + this.id, urlParams.currentposition); 66 | if (cachedCurrentPosition !== urlParams.currentposition) { 67 | this.log("Change Current Window Covering for covers to '%s'.", urlParams.currentposition); 68 | this.service.getCharacteristic(Characteristic.CurrentPosition).updateValue(urlParams.currentposition, undefined, Constants.CONTEXT_FROM_WEBHOOK); 69 | } 70 | } 71 | 72 | if (urlParams.targetposition != null) { 73 | var cachedTargetPosition = this.storage.getItemSync("http-webhook-target-position-" + this.id); 74 | if (cachedTargetPosition === undefined) { 75 | cachedTargetPosition = 100; 76 | } 77 | this.storage.setItemSync("http-webhook-target-position-" + this.id, urlParams.targetposition); 78 | if (cachedTargetPosition !== urlParams.targetposition) { 79 | if (urlParams.targetposition) { 80 | this.log("Change Target Position for covers to '%s'.", urlParams.targetposition); 81 | this.service.getCharacteristic(Characteristic.TargetPosition).updateValue(urlParams.targetposition, undefined, Constants.CONTEXT_FROM_WEBHOOK); 82 | } 83 | } 84 | } 85 | if (urlParams.positionstate != null) { 86 | var cachedPositionState = this.storage.getItemSync("http-webhook-position-state-" + this.id); 87 | if (cachedPositionState === undefined) { 88 | cachedPositionState = false; 89 | } 90 | this.storage.setItemSync("http-webhook-position-state-" + this.id, urlParams.positionstate); 91 | if (cachedPositionState !== urlParams.positionstate) { 92 | if (urlParams.positionstate) { 93 | this.log("Change Position State for covers to '%s'.", urlParams.positionstate); 94 | this.service.getCharacteristic(Characteristic.PositionState).updateValue(urlParams.positionstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 95 | } 96 | } 97 | } 98 | return { 99 | "success" : true, 100 | "CurrentPosition" : cachedCurrentPosition, 101 | "TargetPosition" : cachedTargetPosition, 102 | "PositionState" : cachedPositionState 103 | }; 104 | } 105 | 106 | HttpWebHookWindowCoveringAccessory.prototype.getTargetPosition = function(callback) { 107 | this.log.debug("Getting current Target Position for '%s'...", this.id); 108 | var state = this.storage.getItemSync("http-webhook-target-position-" + this.id); 109 | if (state === undefined) { 110 | state = 100; 111 | } 112 | callback(null, state); 113 | }; 114 | 115 | HttpWebHookWindowCoveringAccessory.prototype.setTargetPosition = function(newState, callback, context) { 116 | this.log("Target Position State for '%s'...", this.id); 117 | this.log("New target state is: " + newState); 118 | this.storage.setItemSync("http-webhook-target-position-" + this.id, newState); 119 | if(this.autoSetCurrentPosition) { 120 | this.storage.setItemSync("http-webhook-current-position-" + this.id, newState); 121 | } 122 | var urlToCall = this.setTargetPositionCloseURL; 123 | var urlMethod = this.setTargetPositionCloseMethod; 124 | var urlBody = this.setTargetPositionCloseBody; 125 | var urlForm = this.setTargetPositionCloseForm; 126 | var urlHeaders = this.setTargetPositionCloseHeaders; 127 | if (newState === 0) { 128 | urlToCall = this.setTargetPositionOpenURL; 129 | urlMethod = this.setTargetPositionOpenMethod; 130 | urlBody = this.setTargetPositionOpenBody; 131 | urlForm = this.setTargetPositionOpenForm; 132 | urlHeaders = this.setTargetPositionOpenHeaders; 133 | } 134 | if (newState >= 1 && newState <= 25) { 135 | urlToCall = this.setTargetPositionOpen20URL; 136 | urlMethod = this.setTargetPositionOpen20Method; 137 | urlBody = this.setTargetPositionOpen20Body; 138 | urlForm = this.setTargetPositionOpen20Form; 139 | urlHeaders = this.setTargetPositionOpen20Headers; 140 | } 141 | if (newState >= 26 && newState <= 45) { 142 | urlToCall = this.setTargetPositionOpen40URL; 143 | urlMethod = this.setTargetPositionOpen40Method; 144 | urlBody = this.setTargetPositionOpen40Body; 145 | urlForm = this.setTargetPositionOpen40Form; 146 | urlHeaders = this.setTargetPositionOpen40Headers; 147 | } 148 | if (newState >= 46 && newState <= 65) { 149 | urlToCall = this.setTargetPositionOpen60URL; 150 | urlMethod = this.setTargetPositionOpen60Method; 151 | urlBody = this.setTargetPositionOpen60Body; 152 | urlForm = this.setTargetPositionOpen60Form; 153 | urlHeaders = this.setTargetPositionOpen60Headers; 154 | } 155 | if (newState >= 66 && newState <= 94) { 156 | urlToCall = this.setTargetPositionOpen80URL; 157 | urlMethod = this.setTargetPositionOpen80Method; 158 | urlBody = this.setTargetPositionOpen80Body; 159 | urlForm = this.setTargetPositionOpen80Form; 160 | urlHeaders = this.setTargetPositionOpen80Headers; 161 | } 162 | if (newState >= 95) { 163 | urlToCall = this.setTargetPositionCloseURL; 164 | urlMethod = this.setTargetPositionCloseMethod; 165 | urlBody = this.setTargetPositionCloseBody; 166 | urlForm = this.setTargetPositionCloseForm; 167 | urlHeaders = this.setTargetPositionCloseHeaders; 168 | } 169 | 170 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context, (function() { 171 | this.service.getCharacteristic(Characteristic.TargetPosition).updateValue(newState, undefined, null); 172 | if(this.autoSetCurrentPosition) { 173 | this.log("New current state is: " + newState); 174 | setTimeout(function() { 175 | this.service.getCharacteristic(Characteristic.CurrentPosition).updateValue(newState, undefined, null); 176 | }.bind(this), 1000); 177 | } 178 | }).bind(this), null, Constants.COVERS_REQUEST_TIMEOUT); 179 | }; 180 | 181 | HttpWebHookWindowCoveringAccessory.prototype.getCurrentPosition = function(callback) { 182 | this.log.debug("Getting Current Position for '%s'...", this.id); 183 | var state = this.storage.getItemSync("http-webhook-current-position-" + this.id); 184 | if (state === undefined) { 185 | state = 100; 186 | } 187 | callback(null, state); 188 | }; 189 | 190 | HttpWebHookWindowCoveringAccessory.prototype.getPositionState = function(callback) { 191 | this.log.debug("Getting position state for '%s'...", this.id); 192 | var state = this.storage.getItemSync("http-webhook-position-state-" + this.id); 193 | if (state === undefined) { 194 | state = Characteristic.PositionState.STOPPED; 195 | } 196 | callback(null, state); 197 | }; 198 | 199 | HttpWebHookWindowCoveringAccessory.prototype.getServices = function() { 200 | return [ this.service, this.informationService ]; 201 | }; 202 | 203 | module.exports = HttpWebHookWindowCoveringAccessory; 204 | -------------------------------------------------------------------------------- /src/homekit/accessories/HttpWebHookFanv2Accessory.js: -------------------------------------------------------------------------------- 1 | const { parse } = require('node-persist'); 2 | const Constants = require('../../Constants'); 3 | const Util = require('../../Util'); 4 | 5 | function HttpWebHookFanv2Accessory(ServiceParam, CharacteristicParam, platform, fanv2Config) { 6 | Service = ServiceParam; 7 | Characteristic = CharacteristicParam; 8 | 9 | this.platform = platform; 10 | this.log = platform.log; 11 | this.storage = platform.storage; 12 | 13 | this.id = fanv2Config["id"]; 14 | this.type = "fanv2"; 15 | this.name = fanv2Config["name"]; 16 | this.rejectUnauthorized = fanv2Config["rejectUnauthorized"] === undefined ? true : 17 | fanv2Config["rejectUnauthorized"] === true; 18 | 19 | this.onURL = fanv2Config["on_url"] || ""; 20 | this.onMethod = fanv2Config["on_method"] || "GET"; 21 | this.onBody = fanv2Config["on_body"] || ""; 22 | this.onForm = fanv2Config["on_form"] || ""; 23 | this.onHeaders = fanv2Config["on_headers"] || "{}"; 24 | this.offURL = fanv2Config["off_url"] || ""; 25 | this.offMethod = fanv2Config["off_method"] || "GET"; 26 | this.offBody = fanv2Config["off_body"] || ""; 27 | this.offForm = fanv2Config["off_form"] || ""; 28 | this.offHeaders = fanv2Config["off_headers"] || "{}"; 29 | this.speedURL = fanv2Config["speed_url"] || ""; 30 | this.speedMethod = fanv2Config["speed_method"] || "GET"; 31 | this.speedBody = fanv2Config["speed_body"] || ""; 32 | this.speedForm = fanv2Config["speed_form"] || ""; 33 | this.speedHeaders = fanv2Config["speed_headers"] || "{}"; 34 | this.speedFactor = fanv2Config["speed_factor"] || 1; 35 | 36 | this.enableLockPhysicalControls = fanv2Config["enableLockPhysicalControls"] || false; 37 | this.lockURL = fanv2Config["lock_url"] || ""; 38 | this.lockMethod = fanv2Config["lock_method"] || "GET"; 39 | this.lockBody = fanv2Config["lock_body"] || ""; 40 | this.lockForm = fanv2Config["lock_form"] || ""; 41 | this.lockHeaders = fanv2Config["lock_headers"] || "{}"; 42 | this.unlockURL = fanv2Config["unlock_url"] || ""; 43 | this.unlockMethod = fanv2Config["unlock_method"] || "GET"; 44 | this.unlockBody = fanv2Config["unlock_body"] || ""; 45 | this.unlockForm = fanv2Config["unlock_form"] || ""; 46 | this.unlockHeaders = fanv2Config["unlock_headers"] || "{}"; 47 | 48 | this.enableTargetStateControls = fanv2Config["enableTargetStateControls"] || false; 49 | this.targetStateURL = fanv2Config["target_state_url"] || ""; 50 | this.targetStateMethod = fanv2Config["target_state_method"] || "GET"; 51 | this.targetStateBody = fanv2Config["target_state_body"] || ""; 52 | this.targetStateForm = fanv2Config["target_state_form"] || ""; 53 | this.targetStateHeaders = fanv2Config["target_state_headers"] || "{}"; 54 | 55 | this.enableSwingModeControls = fanv2Config["enableSwingModeControls"] || false; 56 | this.swingModeURL = fanv2Config["swing_mode_url"] || ""; 57 | this.swingModeMethod = fanv2Config["swing_mode_method"] || "GET"; 58 | this.swingModeBody = fanv2Config["swing_mode_body"] || ""; 59 | this.swingModeForm = fanv2Config["swing_mode_form"] || ""; 60 | this.swingModeHeaders = fanv2Config["swing_mode_headers"] || "{}"; 61 | 62 | this.rotationDirectionURL = fanv2Config["rotation_direction_url"] || ""; 63 | this.rotationDirectionMethod = fanv2Config["rotation_direction_method"] || "GET"; 64 | this.rotationDirectionBody = fanv2Config["rotation_direction_body"] || ""; 65 | this.rotationDirectionForm = fanv2Config["rotation_direction_form"] || ""; 66 | this.rotationDirectionHeaders = fanv2Config["rotation_direction_headers"] || "{}"; 67 | 68 | this.informationService = new Service.AccessoryInformation(); 69 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "HttpWebHooksPlatform"); 70 | this.informationService.setCharacteristic(Characteristic.Model, "HttpWebHookFanv2Accessory-" + this.name); 71 | this.informationService.setCharacteristic(Characteristic.SerialNumber, "HttpWebHookFanv2Accessory-" + this.id); 72 | 73 | this.service = new Service.Fanv2(this.name); 74 | this.service.getCharacteristic(Characteristic.Active).on('get', this.getState.bind(this)).on('set', this.setState.bind(this)); 75 | this.service.getCharacteristic(Characteristic.RotationSpeed).on('get', this.getSpeed.bind(this)).on('set', this.setSpeed.bind(this)); 76 | this.service.getCharacteristic(Characteristic.RotationDirection).on('get', this.getRotationDirection.bind(this)).on('set', this.setRotationDirection.bind(this)); 77 | 78 | if (this.enableLockPhysicalControls) { 79 | this.service.getCharacteristic(Characteristic.LockPhysicalControls).on('get', this.getLockState.bind(this)).on('set', this.setLockState.bind(this)); 80 | } 81 | 82 | if (this.enableTargetStateControls) { 83 | this.service.getCharacteristic(Characteristic.TargetFanState).on('get', this.getTargetState.bind(this)).on('set', this.setTargetState.bind(this)); 84 | } 85 | 86 | if (this.enableSwingModeControls) { 87 | this.service.getCharacteristic(Characteristic.SwingMode).on('get', this.getSwingMode.bind(this)).on('set', this.setSwingMode.bind(this)); 88 | } 89 | } 90 | 91 | HttpWebHookFanv2Accessory.prototype.changeFromServer = function (urlParams) { 92 | var cachedState = this.storage.getItemSync("http-webhook-" + this.id); 93 | if (cachedState === undefined) { 94 | cachedState = false; 95 | } 96 | var state = urlParams.state || cachedState; 97 | var stateBool = state === "true" || state === true; 98 | if (urlParams.state != cachedState) { 99 | this.log("Change state for fanv2 to '%s'.", stateBool); 100 | this.service.getCharacteristic(Characteristic.Active).updateValue((urlParams.state == "true"), undefined, Constants.CONTEXT_FROM_WEBHOOK); 101 | } 102 | if (urlParams.speed != null) { 103 | var cachedSpeed = this.storage.getItemSync("http-webhook-speed-" + this.id); 104 | var speed = parseInt(urlParams.speed); 105 | if (cachedSpeed != speed) { 106 | this.log("Change speed for fanv2 to '%d'.", speed); 107 | this.service.getCharacteristic(Characteristic.RotationSpeed).updateValue(speed, undefined, Constants.CONTEXT_FROM_WEBHOOK); 108 | } 109 | } 110 | if (urlParams.swingMode != null && this.enableSwingModeControls) { 111 | var cachedSwingMode = this.storage.getItemSync("http-webhook-swingmode-" + this.id); 112 | var swingMode = parseInt(urlParams.swingMode); 113 | if (cachedSwingMode != swingMode) { 114 | this.log("Change swing mode for fanv2 to '%d'.", swingMode); 115 | this.service.getCharacteristic(Characteristic.SwingMode).updateValue(swingMode, undefined, Constants.CONTEXT_FROM_WEBHOOK); 116 | } 117 | } 118 | if (urlParams.rotationDirection != null) { 119 | var cachedRotationDirection = this.storage.getItemSync("http-webhook-rotationdirection-" + this.id); 120 | var rotationDirection = parseInt(urlParams.rotationDirection); 121 | if (cachedRotationDirection != rotationDirection) { 122 | this.log("Change rotation direction for fanv2 to '%d'.", rotationDirection); 123 | this.service.getCharacteristic(Characteristic.RotationDirection).updateValue(rotationDirection, undefined, Constants.CONTEXT_FROM_WEBHOOK); 124 | } 125 | } 126 | if (urlParams.lockstate != null && this.enableLockPhysicalControls) { 127 | var cachedLockstate = this.storage.getItemSync("http-webhook-lockstate-" + this.id); 128 | var lockstate = parseInt(urlParams.lockState); 129 | if (cachedLockstate != lockstate) { 130 | this.log("Change lock state for fanv2 to '%d'.", lockstate); 131 | this.service.getCharacteristic(Characteristic.LockPhysicalControls).updateValue(lockstate, undefined, Constants.CONTEXT_FROM_WEBHOOK); 132 | } 133 | } 134 | if (urlParams.targetState != null && this.enableTargetStateControls) { 135 | var cachedTargetstate = this.storage.getItemSync("http-webhook-targetstate-" + this.id); 136 | var targetState = parseInt(urlParams.targetState); 137 | if (cachedTargetstate != targetState) { 138 | this.log("Change target state for fanv2 to '%d'.", targetState); 139 | this.service.getCharacteristic(Characteristic.TargetFanState).updateValue(targetState, undefined, Constants.CONTEXT_FROM_WEBHOOK); 140 | } 141 | } 142 | return { 143 | "success": true 144 | }; 145 | } 146 | 147 | HttpWebHookFanv2Accessory.prototype.getState = function (callback) { 148 | this.log.debug("Getting current state for '%s'...", this.id); 149 | var state = this.storage.getItemSync("http-webhook-" + this.id); 150 | if (state === undefined) { 151 | state = false; 152 | } 153 | callback(null, state); 154 | }; 155 | 156 | HttpWebHookFanv2Accessory.prototype.setState = function (powerOn, callback, context) { 157 | this.log("Fanv2 state for '%s'...", this.id); 158 | this.storage.setItemSync("http-webhook-" + this.id, powerOn); 159 | var urlToCall = this.onURL; 160 | var urlMethod = this.onMethod; 161 | var urlBody = this.onBody; 162 | var urlForm = this.onForm; 163 | var urlHeaders = this.onHeaders; 164 | if (!powerOn) { 165 | urlToCall = this.offURL; 166 | urlMethod = this.offMethod; 167 | urlBody = this.offBody; 168 | urlForm = this.offForm; 169 | urlHeaders = this.offHeaders; 170 | } 171 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 172 | }; 173 | 174 | HttpWebHookFanv2Accessory.prototype.getSpeed = function (callback) { 175 | this.log.debug("Getting current speed for '%s'...", this.id); 176 | var state = this.storage.getItemSync("http-webhook-" + this.id); 177 | if (state === undefined) { 178 | state = false; 179 | } 180 | var speed = 0; 181 | if (state) { 182 | speed = this.storage.getItemSync("http-webhook-speed-" + this.id); 183 | if (speed === undefined) { 184 | speed = 100; 185 | } 186 | } 187 | callback(null, parseInt(speed)); 188 | }; 189 | 190 | HttpWebHookFanv2Accessory.prototype.setSpeed = function (speed, callback, context) { 191 | this.log("Fanv2 rotation speed for '%s'...", this.id); 192 | var newState = speed > 0; 193 | this.storage.setItemSync("http-webhook-" + this.id, newState); 194 | this.storage.setItemSync("http-webhook-speed-" + this.id, speed); 195 | var speedFactor = this.speedFactor; 196 | var speedToSet = Math.ceil(speed * speedFactor); 197 | var urlToCall = this.replaceVariables(this.speedURL, newState, speedToSet); 198 | var urlMethod = this.speedMethod; 199 | var urlBody = this.speedBody; 200 | var urlForm = this.speedForm; 201 | var urlHeaders = this.speedHeaders; 202 | 203 | if (urlForm) { 204 | urlForm = this.replaceVariables(urlForm, newState, speedToSet); 205 | } 206 | else if (urlBody) { 207 | urlBody = this.replaceVariables(urlBody, newState, speedToSet); 208 | } 209 | 210 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 211 | }; 212 | 213 | HttpWebHookFanv2Accessory.prototype.getLockState = function (callback) { 214 | this.log.debug("Getting current lock state for '%s'...", this.id); 215 | var lockstate = this.storage.getItemSync("http-webhook-lockstate-" + this.id); 216 | if (lockstate === undefined) { 217 | lockstate = false; 218 | } 219 | callback(null, lockstate); 220 | }; 221 | 222 | HttpWebHookFanv2Accessory.prototype.setLockState = function (lockState, callback, context) { 223 | this.log("Fanv2 lock state for '%s'...", this.id); 224 | this.storage.setItemSync("http-webhook-lockstate-" + this.id, lockState); 225 | var urlToCall = this.lockURL; 226 | var urlMethod = this.lockMethod; 227 | var urlBody = this.lockBody; 228 | var urlForm = this.lockForm; 229 | var urlHeaders = this.lockHeaders; 230 | if (!lockState) { 231 | urlToCall = this.unlockURL; 232 | urlMethod = this.unlockMethod; 233 | urlBody = this.unlockBody; 234 | urlForm = this.unlockForm; 235 | urlHeaders = this.unlockHeaders; 236 | } 237 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 238 | }; 239 | 240 | HttpWebHookFanv2Accessory.prototype.getTargetState = function (callback) { 241 | this.log.debug("Getting current target state for '%s'...", this.id); 242 | var targetState = this.storage.getItemSync("http-webhook-targetstate-" + this.id); 243 | if (targetState === undefined) { 244 | targetState = false; 245 | } 246 | callback(null, targetState); 247 | }; 248 | 249 | HttpWebHookFanv2Accessory.prototype.setTargetState = function (targetState, callback, context) { 250 | this.log("Fanv2 target state for '%s'...", this.id); 251 | this.storage.setItemSync("http-webhook-targetstate-" + this.id, targetState); 252 | var state = this.storage.getItemSync("http-webhook-" + this.id); 253 | if (state === undefined) { 254 | state = false; 255 | } 256 | var urlToCall = this.targetStateURL.replace("%targetState", targetState); 257 | var urlMethod = this.targetStateMethod; 258 | var urlBody = this.targetStateBody.replace("%targetState", targetState);; 259 | var urlForm = this.targetStateForm; 260 | var urlHeaders = this.targetStateHeaders; 261 | 262 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 263 | }; 264 | 265 | HttpWebHookFanv2Accessory.prototype.getSwingMode = function (callback) { 266 | this.log.debug("Getting current swing mode for '%s'...", this.id); 267 | var swingMode = this.storage.getItemSync("http-webhook-swingmode-" + this.id); 268 | if (swingMode === undefined) { 269 | swingMode = false; 270 | } 271 | callback(null, swingMode); 272 | }; 273 | 274 | HttpWebHookFanv2Accessory.prototype.setSwingMode = function (swingMode, callback, context) { 275 | this.log("Fanv2 swing mode for '%s'...", this.id); 276 | this.storage.setItemSync("http-webhook-swingmode-" + this.id, swingMode); 277 | var state = this.storage.getItemSync("http-webhook-" + this.id); 278 | if (state === undefined) { 279 | state = false; 280 | } 281 | var urlToCall = this.swingModeURL.replace("%swingMode", swingMode); 282 | var urlMethod = this.swingModeMethod; 283 | var urlBody = this.swingModeBody.replace("%swingMode", swingMode);; 284 | var urlForm = this.swingModeForm; 285 | var urlHeaders = this.swingModeHeaders; 286 | 287 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 288 | }; 289 | 290 | HttpWebHookFanv2Accessory.prototype.getRotationDirection = function (callback) { 291 | this.log.debug("Getting current rotation direction for '%s'...", this.id); 292 | var rotationDirection = this.storage.getItemSync("http-webhook-rotationdirection-" + this.id); 293 | if (rotationDirection === undefined) { 294 | rotationDirection = false; 295 | } 296 | callback(null, rotationDirection); 297 | }; 298 | 299 | HttpWebHookFanv2Accessory.prototype.setRotationDirection = function (rotationDirection, callback, context) { 300 | this.log("Fanv2 rotation direction for '%s'...", this.id); 301 | this.storage.setItemSync("http-webhook-rotationdirection-" + this.id, rotationDirection); 302 | var urlToCall = this.rotationDirectionURL.replace("%rotationDirection", rotationDirection); 303 | var urlMethod = this.rotationDirectionMethod; 304 | var urlBody = this.rotationDirectionBody.replace("%rotationDirection", rotationDirection);; 305 | var urlForm = this.rotationDirectionForm; 306 | var urlHeaders = this.rotationDirectionHeaders; 307 | 308 | Util.callHttpApi(this.log, urlToCall, urlMethod, urlBody, urlForm, urlHeaders, this.rejectUnauthorized, callback, context); 309 | }; 310 | 311 | HttpWebHookFanv2Accessory.prototype.replaceVariables = function (text, state, speed) { 312 | return text.replace("%statusPlaceholder", state).replace("%speedPlaceholder", speed); 313 | }; 314 | 315 | 316 | HttpWebHookFanv2Accessory.prototype.getServices = function () { 317 | return [this.service, this.informationService]; 318 | }; 319 | 320 | module.exports = HttpWebHookFanv2Accessory; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # homebridge-http-webhooks 2 | A http plugin with support of webhooks for [Homebridge](https://github.com/nfarina/homebridge). 3 | 4 | The plugin gets its states from any system that is calling the url to trigger a state change. 5 | 6 | Currently supports contact, motion, occupancy, smoke sensors, switches, push buttons, lights (only on/off and brightness), temperature sensors, humidity sensors, thermostats, CO2 sensors and leak sensors. 7 | 8 | # Installation 9 | 1. Install homebridge using: `npm install -g homebridge` 10 | 2. Install this plugin using: `npm install -g homebridge-http-webhooks` 11 | 3. Update your configuration file. See sample-config.json snippet below. 12 | 13 | # Retrieve state 14 | To retrieve the current state you need to call the url `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToTrigger` 15 | The returned JSON format is: 16 | ``` 17 | { 18 | "success": true, 19 | "state": cachedState 20 | } 21 | ``` 22 | 23 | # Trigger change for boolean accessory 24 | To trigger a change of a boolean accessory you need to call the url `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToTrigger&state=NEWSTATE` 25 | 26 | ## Contact sensor 27 | For contact sensors the value for `NEWSTATE` is either `true` for contact or `false` for no contact. If `autoRelease` is used, than the state will be released after `autoReleaseTime`, if not set 5 seconds. 28 | 29 | ## Motion sensor 30 | For motion sensors the value for `NEWSTATE` is either `true` for motion detection or `false` for no motion. If `autoRelease` is used, than the state will be released `autoReleaseTime`, if not set 5 seconds. 31 | 32 | ## Occupancy sensor 33 | For occupancy sensors the value for `NEWSTATE` is either `true` for occupancy detection or 'false' for no occupancy. If `autoRelease` is used, than the state will be released `autoReleaseTime`, if not set 5 seconds. 34 | 35 | ## Smoke sensor 36 | For smoke sensors the value for `NEWSTATE` is either `true` for smoke detection or `false` for no smoke. 37 | 38 | ## Switch 39 | For switches the value for `NEWSTATE` is either `true` for on or `false` for off. 40 | 41 | ## Push button 42 | For push buttons the value for `NEWSTATE` is `true`. The button will be released automatically. 43 | 44 | ## Light 45 | For lights the value for `NEWSTATE` is either `true` for on or `false` for off. 46 | 47 | ## Outlet 48 | For outlets the value for `NEWSTATE` is either `true` for on or `false` for off. 49 | 50 | ### Outlet in use 51 | For outlets the additional state `stateOutletInUse` is available. The value for `NEWSTATE` is either `true` for on or `false` for off and 52 | can be changed by calling the url `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToTrigger&stateOutletInUse=NEWSTATE` 53 | 54 | ## Fanv2 55 | For fanv2 the value for `NEWSTATE` is either `true` for on or `false` for off. 56 | 57 | ## Valve 58 | For valves/faucets the value for `NEWSTATE` is either `true` for on or `false` for off. 59 | 60 | ### Valve fault state 61 | For valves the additional state `statusFault` is available. The value for `NEWSTATE` is either `true` for on or `false` for off and 62 | can be changed by calling the url `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToTrigger&statusFault=NEWSTATE` 63 | 64 | # Trigger action 65 | 66 | ## Switch 67 | For switches you can call the url from any system to switch the switch on or off. 68 | 69 | ## Push button 70 | For push buttons you can call the url from any system to push the button. The button will be released automatically. 71 | 72 | ## Light 73 | For lights you can call the url from any system to switch the light on or off. 74 | 75 | ## Outlet 76 | For outlets you can call the url from any system to switch the outlet on or off. 77 | 78 | ## Fanv2 79 | For fanv2 you can call the url from any system to switch the fanv2 on or off. 80 | 81 | # Update a numeric accessory 82 | To update a numeric accessory you need to call the url `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&value=NEWVALUE` 83 | 84 | ## Temperature sensor 85 | For temperature sensors the value for `NEWVALUE` is the new temperature reading. 86 | 87 | ## Light sensor 88 | For light sensors the value for `NEWVALUE` is the new light intensity in lux (as float). 89 | 90 | ## Humidity sensor 91 | For humidity sensors the value for `NEWVALUE` is the new relative humidity percentage reading. 92 | 93 | ## Air Quality sensor 94 | For air quality sensors the value for `NEWVALUE` is the new air quality value (Between 1-5, 1 Excellent). 95 | 96 | ## CO2 Sensor 97 | For a CO2 sensor the value for `NEWVALUE` is the new PPM reading. 98 | 99 | ## Leak sensor 100 | For leak sensors the value for `NEWVALUE` is the new leak state value (1 for leak, 0 for dry). 101 | 102 | ## Light (brightness) 103 | For light brightness the value for `NEWVALUE` is the new light brightness (as integer, between 0 and 100 with respect to brightness factor). 104 | 105 | # Thermostat 106 | To update a thermostat you can update four different values: 107 | * Current temperature reading: `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate¤ttemperature=NEWVALUE` 108 | * Target temperature: `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&targettemperature=NEWVALUE` 109 | * Current state (Off=0 / Heating=1 / Cooling=2): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate¤tstate=NEWVALUE` 110 | * Target state (Off=0 / Heat=1 / Cool=2 / Auto=3): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&targetstate=NEWVALUE` 111 | 112 | # Security System 113 | To update the state of security, you can update two different values: 114 | * Current state (Stay=0 / Away=1 / Night=2 / Disarmed=3 / Triggered=4): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate¤tstate=NEWVALUE` 115 | * Target state (Stay=0 / Away=1 / Night=2 / Disarm=3): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&targetstate=NEWVALUE` 116 | 117 | # Garage Door opener 118 | To update a garage door opener you can update three different values: 119 | * Current door state (Open=0 / Closed=1 / Opening=2 / Closing=3 / Stopped=4): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate¤tdoorstate=NEWVALUE` 120 | * Target door state (Open=0 / Closed=1): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&targetdoorstate=NEWVALUE` 121 | * Obstruction detected (No=0 / Yes=1): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&obstructiondetected=NEWVALUE` 122 | 123 | # Stateless switch 124 | Stateless switches requires 3 parameters accessoryId, buttonName and the event to trigger: 125 | * Single press = 0 126 | * Double press = 1 127 | * Long press = 2 128 | 129 | `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&buttonName=theButtonName&event=EVENT` 130 | 131 | # Lock mechanism 132 | To update a lock mechanism you can update two different values: 133 | 134 | * Current lock state (unsecured=0 / secured=1 / jammed=2 / unknown=3): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&lockcurrentstate=NEWVALUE` 135 | * Target lock state (unsecured=0 / secured=1): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&locktargetstate=NEWVALUE` 136 | 137 | # Window Coverings 138 | To update a window coverings you can update three different values: 139 | * Current position (%): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate¤tposition=%s` (%s is replaced by corresponding current position) 140 | * Target position (%): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&targetposition=%s` (%s is replaced by corresponding target position) 141 | Setting of target position you can realize by send link to: open, 20%, 40%, 60% 80% and close 142 | * Position State (Decreasing=0 / Increasing=1 / Stopped=2): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&positionstate=0 (1 or 2)` (position state is not mandatory and not fully tested yet) 143 | 144 | If you dont use callbacks to let your covering give feedback of current position back to homekit you can set "auto_set_current_position" to true. 145 | 146 | # Fanv2 147 | To update a fanv2 you can update five different values: 148 | * Rotation Speed (%): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&speed=%s` (%s is replaced by fan's rotation speed) 149 | * Swing Mode (DISABLED=0 / ENABLED=1): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&swingMode=0 (or 1)` (To use this feature, "enableSwingModeControls" in confing must be set to true.) 150 | * Rotation Direction (CLOCKWISE=0 / COUNTER_CLOCKWISE=1): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&rotationDirection=0 (or 1)` 151 | * Lock Physical Controls (DISABLED=0 / ENABLED=1): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&lockstate=0 (or 1)` (To use this feature, "enableLockPhysicalControls" in confing must be set to true.) 152 | * Target Fan State (MANUAL=0 / AUTO=1): `http://yourHomebridgeServerIp:webhook_port/?accessoryId=theAccessoryIdToUpdate&targetState=0 (or 1)`(To use this feature, "enableTargetStateControls" in confing must be set to true.) 153 | 154 | ## Valves 155 | For valves/faucets you can call the url from any system to switch the valve on or off. 156 | 157 | # Configuration 158 | Example config.json: 159 | ``` 160 | { 161 | "platforms": [ 162 | { 163 | "platform": "HttpWebHooks", 164 | "webhook_port": "51828", 165 | "webhook_listen_host": "::", // (optional, default: "0.0.0.0") 166 | "webhook_enable_cors": true, // (optional, default: false) 167 | "cache_directory": "./.node-persist/storage", // (optional, default: "./.node-persist/storage") 168 | "http_auth_user": "test", // (optional, only if you like to secure your api) 169 | "http_auth_pass": "test", // (optional, only if you like to secure your api) 170 | "https": true, // (beta state, optional, only if you like to secure your api using ssl certificate) 171 | "https_keyfile": "/pathToKeyFile/server.key", // (beta state, optional, only if you like to secure your api using ssl certificate) 172 | "https_certfile": "/pathToKeyFile/server.cert", // (beta state, optional, only if you like to secure your api using ssl certificate) 173 | "sensors": [ 174 | { 175 | "id": "sensor1", 176 | "name": "Sensor name 1", 177 | "type": "contact", 178 | "autoRelease": false, // (optional) 179 | "autoReleaseTime": 7500 // (optional, in ms) 180 | }, 181 | { 182 | "id": "sensor2", 183 | "name": "Sensor name 2", 184 | "type": "motion", 185 | "autoRelease": false, // (optional) 186 | "autoReleaseTime": 7500 // (optional, in ms) 187 | }, 188 | { 189 | "id": "sensor3", 190 | "name": "Sensor name 3", 191 | "type": "occupancy", 192 | "autoRelease": false, // (optional) 193 | "autoReleaseTime": 7500 // (optional, in ms) 194 | }, 195 | { 196 | "id": "sensor4", 197 | "name": "Sensor name 4", 198 | "type": "smoke" 199 | }, 200 | { 201 | "id": "sensor5", 202 | "name": "Sensor name 5", 203 | "type": "temperature" 204 | }, 205 | { 206 | "id": "sensor6", 207 | "name": "Sensor name 6", 208 | "type": "humidity" 209 | }, 210 | { 211 | "id": "sensor7", 212 | "name": "Sensor name 7", 213 | "type": "airquality" 214 | }, 215 | { 216 | "id": "sensor8", 217 | "name": "Sensor name 8", 218 | "type": "light" 219 | }, 220 | { 221 | "id": "sensor9", 222 | "name": "Sensor name 9", 223 | "type": "leak" 224 | } 225 | ], 226 | "switches": [ 227 | { 228 | "id": "switch1", 229 | "name": "Switch name 1", 230 | "rejectUnauthorized": false, // (optional) 231 | "on_url": "your url to switch the switch on", // (optional) 232 | "on_method": "GET", // (optional) 233 | "on_body": "{ \"on\" : true }", // (optional only for POST, PUT and PATCH; use "on_form" for x-www-form-urlencoded JSON) 234 | "on_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 235 | "off_url": "your url to switch the switch off", // (optional) 236 | "off_method": "GET", // (optional) 237 | "off_body": "{ \"on\": false }", // (optional only for POST, PUT and PATCH; use "off_form" for x-www-form-urlencoded JSON) 238 | "off_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" // (optional) 239 | } 240 | ], 241 | "pushbuttons": [ 242 | { 243 | "id": "pushbutton1", 244 | "name": "Push button name 1", 245 | "rejectUnauthorized": false, // (optional) 246 | "push_url": "your url to be called on push", // (optional) 247 | "push_method": "GET", // (optional) 248 | "push_body": "{ \"push\": true }", // (optional only for POST, PUT and PATCH; use "push_form" for x-www-form-urlencoded JSON) 249 | "push_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" // (optional) 250 | } 251 | ], 252 | "lights": [ 253 | { 254 | "id": "light1", 255 | "name": "Light name 1", 256 | "rejectUnauthorized": false, // (optional) 257 | "on_url": "your url to switch the light on", // (optional) 258 | "on_method": "GET", // (optional) 259 | "on_body": "{ \"on\" : true }", // (optional only for POST, PUT and PATCH; use "on_form" for x-www-form-urlencoded JSON) 260 | "on_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 261 | "off_url": "your url to switch the light off", // (optional) 262 | "off_method": "GET", // (optional) 263 | "off_body": "{ \"on\": false }", // (optional only for POST, PUT and PATCH; use "off_form" for x-www-form-urlencoded JSON) 264 | "off_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 265 | "brightness_url": "your url to change the light brightness", // (optional) 266 | "brightness_method": "GET", // (optional) 267 | "brightness_body": "{ \"on\" : %statusPlaceholder, \"bri\" : %brightnessPlaceholder}", // (optional only for POST, PUT and PATCH; use "brightness_form" for x-www-form-urlencoded JSON, variables are replaced on the fly) 268 | "brightness_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 269 | "brightness_factor": 2.55 // (optional to convert homekit brightness to target system brightness) 270 | } 271 | ], 272 | "thermostats": [ 273 | { 274 | "id": "thermostat1", 275 | "name": "Thermostat name 1", 276 | "minTemp": 15, // (optional) 277 | "maxTemp": 30, // (optional) 278 | "minStep": 0.5, // (optional) 279 | "rejectUnauthorized": false, // (optional) 280 | "set_target_temperature_url": "http://127.0.0.1/thermostatscript.php?targettemperature=%f", // %f is replaced by the target temperature 281 | "set_target_temperature_method": "GET", // (optional) 282 | "set_target_temperature_body": "{ \"on\" : true }", // (optional only for POST, PUT and PATCH; use "set_target_temperature_form" for x-www-form-urlencoded JSON) 283 | "set_target_temperature_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 284 | "set_target_heating_cooling_state_url": "http://127.0.0.1/thermostatscript.php?targetstate=%b", // %b is replaced by the target state 285 | "set_target_heating_cooling_state_method": "GET", // (optional) 286 | "set_target_heating_cooling_state_body": "{ \"on\" : true }", // (optional only for POST, PUT and PATCH; use "set_target_heating_cooling_state_form" for x-www-form-urlencoded JSON) 287 | "set_target_heating_cooling_state_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" // (optional) 288 | } 289 | ], 290 | "co2sensors" : [ 291 | { 292 | "id": "co2sensor1", 293 | "name": "CO2 sensor name 1", 294 | "co2_peak_level": 1200 295 | } 296 | ], 297 | "outlets": [ 298 | { 299 | "id": "outlet1", 300 | "name": "Outlet name 1", 301 | "rejectUnauthorized": false, // (optional) 302 | "on_url": "your url to switch the outlet on", // (optional) 303 | "on_method": "GET", // (optional) 304 | "on_body": "{ \"on\" : true }", // (optional only for POST, PUT and PATCH; use "on_form" for x-www-form-urlencoded JSON) 305 | "on_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 306 | "off_url": "your url to switch the outlet off", // (optional) 307 | "off_method": "GET", // (optional) 308 | "off_body": "{ \"on\": false }", // (optional only for POST, PUT and PATCH; use "off_form" for x-www-form-urlencoded JSON) 309 | "off_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" // (optional) 310 | } 311 | ], 312 | "security": [ 313 | { 314 | "id": "security1", 315 | "name": "Security System", 316 | "rejectUnauthorized": false, // (optional) 317 | "set_state_url": "http://localhost/security/mode/%d", // %d is replaced by the target state 318 | "set_state_method": "GET", // (optional) 319 | "set_state_body": "{ \"on\": true }", // (optional only for POST, PUT and PATCH; use "set_state_form" for x-www-form-urlencoded JSON) 320 | "set_state_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" // (optional) 321 | } 322 | ], 323 | "garagedooropeners": [ 324 | { 325 | "id": "garagedooropener1", 326 | "name": "Garage Door Opener name 1", 327 | "rejectUnauthorized": false, // (optional) 328 | "open_url" : "your url to open the garage door", // (optional) 329 | "open_method" : "GET", // (optional) 330 | "open_body": "{ \"open\": true }", // (optional only for POST, PUT and PATCH; use "open_form" for x-www-form-urlencoded JSON) 331 | "open_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 332 | "close_url" : "your url to close the garage door", // (optional) 333 | "close_method" : "GET", // (optional) 334 | "close_body": "{ \"open\": false }", // (optional only for POST, PUT and PATCH; use "close_form" for x-www-form-urlencoded JSON) 335 | "close_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" // (optional) 336 | } 337 | ], 338 | "statelessswitches": [ 339 | { 340 | "id": "statelessswitch1", 341 | "name": "Stateless Switch 1", 342 | "buttons": [//the buttons of the switch 343 | { 344 | "name": "Button1" // (The name does not appear in Home app but appear in Eve app) 345 | }, 346 | { 347 | "name": "Button2", // (The name does not appear in Home app but appear in Eve app) 348 | "double_press": false, // (you can disable a type of action) 349 | "long_press": false 350 | } 351 | ] 352 | } 353 | ], 354 | "windowcoverings": [ 355 | { 356 | "id": "windowcovering1", 357 | "name": "Some Window Cover", 358 | "rejectUnauthorized": false, // (optional) 359 | "open_url" : "http://your.url/to/open", 360 | "open_method" : "GET", // (optional) 361 | "open_body": "{ \"open\": true }", // (optional only for POST, PUT and PATCH; use "open_form" for x-www-form-urlencoded JSON) 362 | "open_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 363 | "open_80_url" : "http://your.url/to/open80%", 364 | "open_80_method" : "GET", // (optional) 365 | "open_80_body": "{ \"open\": true }", // (optional only for POST, PUT and PATCH; use "open_80_form" for x-www-form-urlencoded JSON) 366 | "open_80_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 367 | "open_60_url" : "http://your.url/to/open60%", 368 | "open_60_method" : "GET", // (optional) 369 | "open_60_body": "{ \"open\": true }", // (optional only for POST, PUT and PATCH; use "open_60_form" for x-www-form-urlencoded JSON) 370 | "open_60_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 371 | "open_40_url" : "http://your.url/to/open40%", 372 | "open_40_method" : "GET", // (optional) 373 | "open_40_body": "{ \"open\": true }", // (optional only for POST, PUT and PATCH; use "open_40_form" for x-www-form-urlencoded JSON) 374 | "open_40_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 375 | "open_20_url" : "http://your.url/to/open20%", 376 | "open_20_method" : "GET", // (optional) 377 | "open_20_body": "{ \"open\": true }", // (optional only for POST, PUT and PATCH; use "open_20_form" for x-www-form-urlencoded JSON) 378 | "open_20_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 379 | "close_url" : "http://your.url/to/close", 380 | "close_method" : "GET", // (optional) 381 | "close_body": "{ \"open\": false }", // (optional only for POST, PUT and PATCH; use "close_form" for x-www-form-urlencoded JSON) 382 | "close_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 383 | "auto_set_current_position": true // (optional, default: false) 384 | } 385 | ], 386 | "lockmechanisms": [ 387 | { 388 | "id": "doorlock1", 389 | "name": "Door", 390 | "rejectUnauthorized": false, // (optional) 391 | "open_url" : "your url to open the garage door", // (optional) 392 | "open_method" : "GET",// (optional) 393 | "open_body": "{ \"open\": true }", // (optional only for POST, PUT and PATCH; use "open_form" for x-www-form-urlencoded JSON) 394 | "open_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 395 | "close_url" : "your url to close the garage door", // (optional) 396 | "close_method" : "GET", // (optional) 397 | "close_body": "{ \"open\": false }", // (optional only for POST, PUT and PATCH; use "close_form" for x-www-form-urlencoded JSON) 398 | "close_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" // (optional) 399 | } 400 | ], 401 | "fanv2s": [ 402 | { 403 | "id": "fanv2-1", 404 | "name": "Fanv2-1", 405 | "rejectUnauthorized": true, // (optional) 406 | "on_url": "your url to switch the fanv2 on", 407 | "on_method": "GET", 408 | "on_body": "{ \"on\" : true }", 409 | "on_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", 410 | "off_url": "your url to switch the fanv2 off", 411 | "off_method": "GET", 412 | "off_body": "{ \"off\" : true }", 413 | "off_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", 414 | "speed_url": "your url to change the fanv2 rotation speed", 415 | "speed_method": "GET", 416 | "speed_body": "{ \"on\" : %statusPlaceholder, \"speed\" : %speedPlaceholder}", 417 | "speed_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", 418 | "speed_factor":2.55, 419 | "enableLockPhysicalControls": true, 420 | "lock_url": "your url to lock the fanv2's physical controls", 421 | "lock_method": "GET", 422 | "lock_body": "{ \"physicalLock\": true }", 423 | "lock_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", 424 | "unlock_url": "your url to unlock the fanv2's physical controls", 425 | "unlock_method": "GET", 426 | "unlock_body": "{ \"physicalLock\": false }", 427 | "unlock_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", 428 | "enableTargetStateControls": true, 429 | "target_state_url": "your url to change the fanv2's target state", 430 | "target_state_method": "GET", 431 | "target_state_body": "{ \"mode\": %targetState }", 432 | "target_state_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", 433 | "enableSwingModeControls": true, 434 | "swing_mode_url": "your url to change the fanv2's swing mode", 435 | "swing_mode_method": "GET", 436 | "swing_mode_body": "{ \"swing_mode\": %swingMode }", 437 | "swing_mode_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", 438 | "rotation_direction_url": "your url to change the fanv2's rotation direction", 439 | "rotation_direction_method": "GET", 440 | "rotation_direction_body": "{ \"rotation_direction\": %rotationDirection }", 441 | "rotation_direction_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" 442 | } 443 | ], 444 | "valves": [ 445 | { 446 | "id": "valve1", 447 | "name": "Valve name 1", 448 | "type": "generic valve", // (optional) 449 | "rejectUnauthorized": false, // (optional) 450 | "on_url": "your url to switch the valve on", // (optional) 451 | "on_method": "GET", // (optional) 452 | "on_body": "{ \"on\" : true }", // (optional only for POST, PUT and PATCH; use "on_form" for x-www-form-urlencoded JSON) 453 | "on_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}", // (optional) 454 | "off_url": "your url to switch the valve off", // (optional) 455 | "off_method": "GET", // (optional) 456 | "off_body": "{ \"on\": false }", // (optional only for POST, PUT and PATCH; use "off_form" for x-www-form-urlencoded JSON) 457 | "off_headers": "{\"Authorization\": \"Bearer ABCDEFGH\", \"Content-Type\": \"application/json\"}" // (optional) 458 | } 459 | ] 460 | } 461 | ] 462 | } 463 | ``` 464 | 465 | ## Cache directory storage (cache_directory) 466 | The cache directory is used to cache the state of the accessories. It must point to a **valid** and **empty** directory and the user that runs homebridge must have **write access**. 467 | 468 | ## HTTPS 469 | If you want to create a secure connection for the webhooks you need to enable it by setting *https* to true. Then a self signed 470 | ssl certificate will be created automatically and a secure connection will be used. If you want to use your own generated ssl 471 | certificate you can do this by setting the values for *https_keyfile* and *https_certfile* to the corresponding file paths. 472 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------