decouple mqtt:

- register onConnected and onDisconnected callbacks
- allow optional Scheduler
- publishInit is independent on Scheduler
This commit is contained in:
Nicu Hodos 2024-05-22 13:42:52 +02:00
parent 4b498d7afd
commit a4b1e78eef

View File

@ -2,27 +2,20 @@
#include <AsyncMqttClient.h> #include <AsyncMqttClient.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include "devices.h"
#define MAIN_TOPIC "homeassistant/+/" MAIN_DEVICE_ID "/#"
#define MQTT_HOST IPAddress(192, 168, 5, 11)
#define MQTT_PORT 1883
namespace Mqtt { namespace Mqtt {
AsyncMqttClient client; AsyncMqttClient client;
Task tReConnect(5 * TASK_MINUTE, TASK_FOREVER, []{ Task tReConnect(TASK_MINUTE, TASK_FOREVER, []{
Serial.println("Connecting to MQTT..."); Serial.println("Connecting to MQTT...");
client.connect(); client.connect();
}, &ts); });
void publishInit();
Task tPublishInit(TASK_IMMEDIATE, TASK_ONCE, publishInit, &ts);
const char* mainTopic = "homeassistant/+/rc-gateway/#";
void disconnect() { void disconnect() {
client.unsubscribe(mainTopic); client.unsubscribe(MAIN_TOPIC);
client.disconnect(); client.disconnect();
} }
@ -31,12 +24,12 @@ namespace Mqtt {
} }
void publishInit() { void publishInit() {
#if MQTT_CLEANUP static bool firstTime = true;
Ha::publisher = publish; if (firstTime) {
Component::components.forEach([](Component* c) { c->publishConfig(); }); Component::components.forEach([](Component* c) { c->publishConfig(); });
AbstractBuilder::deleteAll(); AbstractBuilder::deleteAll();
#endif firstTime = false;
ts.deleteTask(tPublishInit); }
} }
void publishCleanupConfig() { void publishCleanupConfig() {
@ -53,18 +46,20 @@ namespace Mqtt {
if (cmd) cmd->onCommand(msg); if (cmd) cmd->onCommand(msg);
} }
void setup() { void setup(Scheduler* ts = nullptr, void(*onConnected)() = nullptr, void(*onDisconnected)() = nullptr) {
client.onConnect([](bool sessionPresent) { if (ts) ts->addTask(tReConnect);
tPublishInit.enable(); Ha::publisher = publish;
client.subscribe(mainTopic, 0); client.onConnect([onConnected](bool sessionPresent) {
publishInit();
client.subscribe(MAIN_TOPIC, 0);
tReConnect.disable(); tReConnect.disable();
Serial.println("Connected to MQTT"); Serial.println("Connected to MQTT");
turnLed(BLUE_LED, false); if (onConnected) onConnected();
}); });
client.onDisconnect([](AsyncMqttClientDisconnectReason reason) { client.onDisconnect([onDisconnected](AsyncMqttClientDisconnectReason reason) {
tReConnect.enableDelayed(); tReConnect.enableDelayed();
Serial.println("Disconnected from MQTT"); Serial.println("Disconnected from MQTT");
turnLed(BLUE_LED); if (onDisconnected) onDisconnected();
}); });
client.onMessage(onMessage); client.onMessage(onMessage);
client.setServer(MQTT_HOST, MQTT_PORT); client.setServer(MQTT_HOST, MQTT_PORT);