diff --git a/gateway/include/Protocol.h b/gateway/include/Protocol.h index 16da3bf..9d966c9 100644 --- a/gateway/include/Protocol.h +++ b/gateway/include/Protocol.h @@ -10,6 +10,7 @@ public: Protocol(unsigned int protocol) { this->protocol = protocol; } + virtual ~Protocol() {} virtual void fromJson(JsonObjectConst& rcSwitch, RCSwitch& rcDevice) { unsigned int protocol = rcSwitch["protocol"]; diff --git a/gateway/include/Protocol_1.h b/gateway/include/Protocol_1.h index 1a50917..cde4517 100644 --- a/gateway/include/Protocol_1.h +++ b/gateway/include/Protocol_1.h @@ -64,5 +64,5 @@ private: } } }; -} protocol_1; +}; diff --git a/gateway/include/Protocol_2.h b/gateway/include/Protocol_2.h index 4820c09..34cfad6 100644 --- a/gateway/include/Protocol_2.h +++ b/gateway/include/Protocol_2.h @@ -64,4 +64,4 @@ private: return true; } -} protocol_2; \ No newline at end of file +}; \ No newline at end of file diff --git a/gateway/src/gateway.cpp b/gateway/src/gateway.cpp index c77a1b8..49228f4 100644 --- a/gateway/src/gateway.cpp +++ b/gateway/src/gateway.cpp @@ -27,14 +27,20 @@ void setup() { delay(1000); } -Protocol findProtocol(unsigned int protocol) { +void blink() { + digitalWrite(LED_BUILTIN, HIGH); + delay(200); + digitalWrite(LED_BUILTIN, LOW); +} + +Protocol* findProtocol(unsigned int protocol) { switch (protocol) { case 1: - return protocol_1; + return new Protocol_1(); case 2: - return protocol_2; + return new Protocol_2(); default: - return Protocol(protocol); + return new Protocol(protocol); } } @@ -44,7 +50,9 @@ void readRcSwitch() { mySwitch.resetAvailable(); StaticJsonDocument<200> jsonDoc; - findProtocol(mySwitch.getReceivedProtocol()).toJson(value, jsonDoc); + Protocol* p = findProtocol(mySwitch.getReceivedProtocol()); + p->toJson(value, jsonDoc); + delete p; if (!jsonDoc.isNull()) { serializeJson(jsonDoc, Serial); Serial.println(); @@ -52,12 +60,6 @@ void readRcSwitch() { } } -void blink() { - digitalWrite(LED_BUILTIN, HIGH); - delay(200); - digitalWrite(LED_BUILTIN, LOW); -} - void runJsonCommands(const char* cmd) { String origCmd = String(cmd); StaticJsonDocument<512> jsonArray; @@ -67,7 +69,9 @@ void runJsonCommands(const char* cmd) { for (JsonVariant jsonDoc : array) { if (jsonDoc.containsKey("rcSwitch")) { JsonObjectConst rcSwitch = jsonDoc["rcSwitch"]; - findProtocol(rcSwitch["protocol"]).fromJson(rcSwitch, mySwitch); + Protocol* p = findProtocol(rcSwitch["protocol"]); + p->fromJson(rcSwitch, mySwitch); + delete p; serializeJson(jsonDoc, Serial); Serial.println(); } @@ -91,8 +95,9 @@ void readCommand() { if (cmd.endsWith(",")) { cmd = cmd.substring(0, cmd.lastIndexOf(',')); } - cmd = "[" + cmd + "]"; - runJsonCommands(cmd.c_str()); + char buffer[cmd.length()+2]; + sprintf(buffer, "[%s]", cmd.c_str()); + runJsonCommands(buffer); } }