Created
November 19, 2024 22:21
-
-
Save blindguynar/a8a441a09b5404cee2b1907f37ce1f94 to your computer and use it in GitHub Desktop.
Script to run on Shelly Device to monitor HA endpoint to switch from detached mode to flipped mode upon inability to connect to HA.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let switchId = 1; | |
| let hookId = 5; | |
| let checkPeriod = 60 * 1000; // in ms | |
| let haUrl = 'http://192.168.0.248:8123'; | |
| let mode = "detached"; // Could be "detached", "flip", "follow" or "momentary". Use "detached" when HA is in control | |
| function updateConfig(oldConfig) { | |
| //Apply the new config only if the switch is not already working in the desired mode | |
| if (oldConfig.in_mode !== mode) { | |
| print("switching it up"); | |
| Shelly.call("Switch.SetConfig", { id: switchId, config: { in_mode: mode } }); | |
| if (mode === "detached") { | |
| print("set switch on and hooks off"); | |
| Shelly.call("Switch.Set", { id: switchId, on: true }); | |
| Shelly.call("Webhook.Update", { id: hookId, enable: false}); | |
| Shelly.call("Webhook.Update", { id: hookId+1, enable: false}); | |
| } else { | |
| print("set webhook on"); | |
| Shelly.call("Webhook.Update", { id: hookId, enable: true}); | |
| Shelly.call("Webhook.Update", { id: hookId+1, enable: true}); | |
| } | |
| } else { | |
| print("no change"); | |
| } | |
| } | |
| function setSwitchFromRespons(response) { | |
| print("response"); | |
| // If HA is accessible the response code is 200 update the current mode and the new configuration | |
| if (response === undefined) { | |
| mode = "flip"; | |
| print("default flip"); | |
| } else { | |
| if (response.code === 200) { | |
| mode = "detached"; | |
| print("detached"); | |
| } else { | |
| mode = "flip"; | |
| print("flip"); | |
| } | |
| } | |
| // Get the current output configuration and pass it to updateConfig | |
| print("update config"); | |
| Shelly.call("Switch.GetConfig", {id: switchId}, updateConfig); | |
| print("update config done") | |
| } | |
| function testHA() { | |
| // For RPC command HTTP.GET, both url and body are required. | |
| print("test ha"); | |
| Shelly.call("HTTP.GET", {url: haUrl, body:{}}, setSwitchFromRespons); | |
| } | |
| print("Starting HA Monitor"); | |
| // Timer.set(period_in_ms, reapeate_indefinitely, function) | |
| Timer.set(checkPeriod, true, testHA); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment