diff --git a/gateway/include/ha.h b/gateway/include/ha.h index 904f254..2337936 100644 --- a/gateway/include/ha.h +++ b/gateway/include/ha.h @@ -139,10 +139,22 @@ namespace Ha { } }; + typedef void (*onMessage)(const char* msg); struct Command : Component { char commandTopic[TOPIC_SIZE]; + onMessage f; + static unordered_map mapCommands; - Command(const char* name, const char* id, const char* type) : Component(name, id, type) { + Command(const char* name, const char* id, const char* type, onMessage f) : Component(name, id, type), f(f) { + buildCommandTopic(); + mapCommands.insert({ string(commandTopic), this }); + } + + virtual void onCommand(const char* msg) { + if (f) f(msg); + } + + virtual void buildCommandTopic() { sprintf(commandTopic, "homeassistant/%s/%s/%s", type, MAIN_DEVICE_ID, id); } @@ -156,12 +168,11 @@ namespace Ha { } }; + unordered_map Command::mapCommands; - typedef void (*onMessage)(const char* msg); struct Button : Command { - onMessage f; - Button(const char* name, const char* id, onMessage f = nullptr) : Command(name, id, "button"), f(f) {} + Button(const char* name, const char* id, onMessage f = nullptr) : Command(name, id, "button", f) {} }; @@ -177,9 +188,9 @@ namespace Ha { struct Switch : Command, StateConfig { - virtual void onCommand(const char* msg){} + Switch(const char* name, const char* id, onMessage f = nullptr) : Command(name, id, "switch", f) {} - Switch(const char* name, const char* id) : Command(name, id, "switch") { + void buildCommandTopic() override { sprintf(commandTopic, "homeassistant/%s/%s/%s/set", type, MAIN_DEVICE_ID, id); } diff --git a/gateway/include/mqtt.h b/gateway/include/mqtt.h index 998add7..6698770 100644 --- a/gateway/include/mqtt.h +++ b/gateway/include/mqtt.h @@ -31,21 +31,18 @@ namespace Mqtt { return client.publish(topic, 0, true, message); } - Button* buttons[] = { + Command* commands[] = { Builder