diff --git a/include/mqtt.h b/include/mqtt.h index 5147799..f4adbce 100644 --- a/include/mqtt.h +++ b/include/mqtt.h @@ -11,6 +11,9 @@ namespace Mqtt { void publishConfig(); void publishCommand(); void publishBmp280(); + void connect(); + void disconnect(); + Task tReConnect(5 * TASK_MINUTE, TASK_FOREVER, connect, &ts); Task tPublishConfig(TASK_IMMEDIATE, TASK_ONCE, publishConfig, &ts); Task tPublishBmp(5 * TASK_MINUTE, TASK_FOREVER, publishBmp280, &ts); Task tPublishCommand(TASK_SECOND, TASK_FOREVER, publishCommand, &ts); @@ -33,6 +36,14 @@ namespace Mqtt { const char* bmpTopic = "homeassistant/sensor/esp_clock/state"; + void connect() { + client.connect(); + } + + void disconnect() { + client.disconnect(); + } + void publishTempConfig() { char message[JSON_SIZE]; Ha::buildSensorConfig(message, Ha::TemperatureConfig{"Livingroom Temperature", "livingroom_temperature", bmpTopic}); @@ -86,9 +97,11 @@ namespace Mqtt { tPublishConfig.enable(); tPublishBmp.enableIfNot(); tPublishCommand.enableDelayed(); + tReConnect.disable(); Serial.println("Connected to MQTT"); }); client.onDisconnect([](AsyncMqttClientDisconnectReason reason) { + tReConnect.enableDelayed(); tPublishCommand.disable(); tPublishBmp.disable(); Serial.println("Disconnected from MQTT"); diff --git a/src/esp_clock.cpp b/src/esp_clock.cpp index 6fb0bf5..368307d 100644 --- a/src/esp_clock.cpp +++ b/src/esp_clock.cpp @@ -48,7 +48,7 @@ void onWifiConnected() { Wifi::printStatus(); Ota::tLoop.enable(); if (!Ir::avrOn) tCheckWifi.restartDelayed(); - Mqtt::client.connect(); + Mqtt::connect(); if (time_t newTime = Ntp::updateTime()) { Serial.println(asctime(localtime(&newTime))); } @@ -57,7 +57,7 @@ void onWifiConnected() { void checkWifiCallback() { #if !WIFI_ALWAYS_ON Serial.println("Wifi connection timed out"); - Mqtt::client.disconnect(); + Mqtt::disconnect(); Ota::tLoop.disable(); Wifi::disconnect(); #endif