diff --git a/switch.js b/switch.js index bba226a..34e824d 100644 --- a/switch.js +++ b/switch.js @@ -1,51 +1,57 @@ +function processHttpResponse(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); + } + } + } +} + +function processTick(ud) { + Shelly.call("HTTP.REQUEST", + { method: "POST", url: CONFIG.pollingUrl, body: '{"801":{"170":null}}', timeout: 10 }, + processHttpResponse, + 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 - ); - }, + processTick, null ); } +function processSwitchSet(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); +} + 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); - }, + processSwitchSet, null ); }