decouple mqtt:
- register onConnected and onDisconnected callbacks - allow optional Scheduler - publishInit is independent on Scheduler
This commit is contained in:
parent
4b498d7afd
commit
a4b1e78eef
@ -2,27 +2,20 @@
|
||||
|
||||
#include <AsyncMqttClient.h>
|
||||
#include <ArduinoJson.h>
|
||||
#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);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user