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) { // do this so that during timeout no crash 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();