From f53de2fc5d3c563c6e07c06caa794ae6e2f9ee44 Mon Sep 17 00:00:00 2001 From: Philipp Date: Mon, 7 Nov 2022 18:19:38 +0000 Subject: [PATCH] =?UTF-8?q?F=C3=BCge=20tats=C3=A4chlich=20erste=20Version?= =?UTF-8?q?=20hinzu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- switch.js | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/switch.js b/switch.js index e69de29..941906e 100644 --- a/switch.js +++ b/switch.js @@ -0,0 +1,74 @@ +function initialize() { + Shelly.call("Switch.GetStatus", + { id: CONFIG.switchId }, + function (res, error_code, error_msg, ud) { + print("Initializing... current switch state is:", res.output) + switchIsOpen = res.output; + runLoop(); + }, + null + ); +} + +function runLoop() { + let alertTimer = Timer.set( + CONFIG.pollingInterval, + true, // Run periodically + function (ud) { + Shelly.call("HTTP.REQUEST", + { method: "POST", url: CONFIG.pollingUrl, body: '{"801":{"170":null}}', timeout: 10 }, + function (res, error_code, error_msg, ud) { + print("errors-http-post:", error_code, error_msg); + if (error_code === 0) { + let parsedBody = JSON.parse(res.body); + let production = parsedBody["801"]["170"]["101"]; + let consumption = parsedBody["801"]["170"]["110"]; + print("read production and consumption", production, consumption) + let threshold; + if (switchIsOpen) { + threshold = consumption; + } else { + threshold = consumption + CONFIG.chargingConsumption; + } + // print(threshold); + if (production > threshold) { + if (!switchIsOpen) { + setSwitch(true); + } + } else { + if (switchIsOpen) { + setSwitch(false); + } + } + } + }, + null + ); + }, + null + ); +} + +function setSwitch(on) { + Shelly.call("Switch.Set", + { id: CONFIG.switchId, on: on }, + function (res, error_code, error_msg, ud) { + print("errors-switch-set:", error_code, error_msg); + let newSwitchState = !res["was_on"]; + switchIsOpen = newSwitchState; + print("Changed switch state to:", newSwitchState); + }, + null + ); +} + +let CONFIG = { + pollingInterval: 60 * 1000, + pollingUrl: "192.168.178.101/getjp", + switchId: 0, + chargingConsumption: 2100, +}; + +let switchIsOpen; + +initialize();