From ac8dd2c8073bec0d7c88a7c578f1b3f01a1637b6 Mon Sep 17 00:00:00 2001 From: Nicu Hodos Date: Mon, 24 Oct 2022 14:03:16 +0200 Subject: [PATCH] refactor into smaller functions --- gateway/src/gateway.cpp | 52 +++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/gateway/src/gateway.cpp b/gateway/src/gateway.cpp index b291c5a..c851470 100644 --- a/gateway/src/gateway.cpp +++ b/gateway/src/gateway.cpp @@ -105,37 +105,38 @@ void blink() { digitalWrite(LED_BUILTIN, LOW); } -void runJsonCommand(String cmd) { - StaticJsonDocument<256> jsonArray; +void runRcSwitchCommand(JsonVariant jsonDoc) { + JsonObject rcSwitch = jsonDoc["rcSwitch"]; + unsigned int protocol = rcSwitch["protocol"]; + if (protocol == 1) { + mySwitch.setProtocol(protocol); + char* group = rcSwitch["group"]; + int channel = rcSwitch["channel"]; + rcSwitch["state"] ? mySwitch.switchOn(group, channel) : mySwitch.switchOff(group, channel); + } else { + mySwitch.setProtocol(protocol); + mySwitch.send(rcSwitch["value"]); + // Serial.println((const char*)rcSwitch["value"]); + } + char output[256]; + serializeJson(jsonDoc, output); + Serial.println(output); + // blink(); + // delay(1000); +} + +void runJsonCommands(String cmd) { + StaticJsonDocument<512> jsonArray; DeserializationError err = deserializeJson(jsonArray, cmd); if (err == DeserializationError::Ok) { JsonArray array = jsonArray.as(); for (JsonVariant jsonDoc : array) { if (jsonDoc.containsKey("rcSwitch")) { - JsonObject rcSwitch = jsonDoc["rcSwitch"]; - unsigned int protocol = rcSwitch["protocol"]; - if (protocol == 1) { - mySwitch.setProtocol(protocol); - char* group = rcSwitch["group"]; - int channel = rcSwitch["channel"]; - if (rcSwitch["state"]) { - mySwitch.switchOn(group, channel); - } else { - mySwitch.switchOff(group, channel); - } - } else { - mySwitch.setProtocol(protocol); - mySwitch.send(rcSwitch["value"]); - // Serial.println((const char*)rcSwitch["value"]); - } - char output[256]; - serializeJson(jsonDoc, output); - Serial.println(output); - blink(); - } else { - Serial.println(err.c_str()); + runRcSwitchCommand(jsonDoc); } } + } else { + Serial.println(String(err.c_str()) + ": " + cmd); } } @@ -151,6 +152,7 @@ void readCommand() { if (cmd.endsWith(",")) { cmd = cmd.substring(0, cmd.lastIndexOf(',')); } - runJsonCommand("[" + cmd + "]"); + cmd = "[" + cmd + "]"; + runJsonCommands(cmd); } }