From a4b1e78eef627ad61ced4dc3a30b0bb8b349de06 Mon Sep 17 00:00:00 2001 From: Nicu Hodos Date: Wed, 22 May 2024 13:42:52 +0200 Subject: [PATCH] decouple mqtt: - register onConnected and onDisconnected callbacks - allow optional Scheduler - publishInit is independent on Scheduler --- gateway/include/mqtt.h | 43 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/gateway/include/mqtt.h b/gateway/include/mqtt.h index 840372e..93df1c9 100644 --- a/gateway/include/mqtt.h +++ b/gateway/include/mqtt.h @@ -2,27 +2,20 @@ #include #include -#include "devices.h" - -#define MQTT_HOST IPAddress(192, 168, 5, 11) -#define MQTT_PORT 1883 +#define MAIN_TOPIC "homeassistant/+/" MAIN_DEVICE_ID "/#" namespace Mqtt { AsyncMqttClient client; - Task tReConnect(5 * TASK_MINUTE, TASK_FOREVER, []{ + Task tReConnect(TASK_MINUTE, TASK_FOREVER, []{ Serial.println("Connecting to MQTT..."); client.connect(); - }, &ts); - void publishInit(); - Task tPublishInit(TASK_IMMEDIATE, TASK_ONCE, publishInit, &ts); - - const char* mainTopic = "homeassistant/+/rc-gateway/#"; + }); void disconnect() { - client.unsubscribe(mainTopic); + client.unsubscribe(MAIN_TOPIC); client.disconnect(); } @@ -31,12 +24,12 @@ namespace Mqtt { } void publishInit() { -#if MQTT_CLEANUP - Ha::publisher = publish; - Component::components.forEach([](Component* c) { c->publishConfig(); }); - AbstractBuilder::deleteAll(); -#endif - ts.deleteTask(tPublishInit); + static bool firstTime = true; + if (firstTime) { + Component::components.forEach([](Component* c) { c->publishConfig(); }); + AbstractBuilder::deleteAll(); + firstTime = false; + } } void publishCleanupConfig() { @@ -53,18 +46,20 @@ namespace Mqtt { if (cmd) cmd->onCommand(msg); } - void setup() { - client.onConnect([](bool sessionPresent) { - tPublishInit.enable(); - client.subscribe(mainTopic, 0); + void setup(Scheduler* ts = nullptr, void(*onConnected)() = nullptr, void(*onDisconnected)() = nullptr) { + if (ts) ts->addTask(tReConnect); + Ha::publisher = publish; + client.onConnect([onConnected](bool sessionPresent) { + publishInit(); + client.subscribe(MAIN_TOPIC, 0); tReConnect.disable(); Serial.println("Connected to MQTT"); - turnLed(BLUE_LED, false); + if (onConnected) onConnected(); }); - client.onDisconnect([](AsyncMqttClientDisconnectReason reason) { + client.onDisconnect([onDisconnected](AsyncMqttClientDisconnectReason reason) { tReConnect.enableDelayed(); Serial.println("Disconnected from MQTT"); - turnLed(BLUE_LED); + if (onDisconnected) onDisconnected(); }); client.onMessage(onMessage); client.setServer(MQTT_HOST, MQTT_PORT);