re-connect mqtt

This commit is contained in:
Nicu Hodos 2022-10-16 20:50:31 +02:00
parent c20fb17f03
commit 16497456b2
2 changed files with 15 additions and 2 deletions

View File

@ -11,6 +11,9 @@ namespace Mqtt {
void publishConfig(); void publishConfig();
void publishCommand(); void publishCommand();
void publishBmp280(); void publishBmp280();
void connect();
void disconnect();
Task tReConnect(5 * TASK_MINUTE, TASK_FOREVER, connect, &ts);
Task tPublishConfig(TASK_IMMEDIATE, TASK_ONCE, publishConfig, &ts); Task tPublishConfig(TASK_IMMEDIATE, TASK_ONCE, publishConfig, &ts);
Task tPublishBmp(5 * TASK_MINUTE, TASK_FOREVER, publishBmp280, &ts); Task tPublishBmp(5 * TASK_MINUTE, TASK_FOREVER, publishBmp280, &ts);
Task tPublishCommand(TASK_SECOND, TASK_FOREVER, publishCommand, &ts); Task tPublishCommand(TASK_SECOND, TASK_FOREVER, publishCommand, &ts);
@ -33,6 +36,14 @@ namespace Mqtt {
const char* bmpTopic = "homeassistant/sensor/esp_clock/state"; const char* bmpTopic = "homeassistant/sensor/esp_clock/state";
void connect() {
client.connect();
}
void disconnect() {
client.disconnect();
}
void publishTempConfig() { void publishTempConfig() {
char message[JSON_SIZE]; char message[JSON_SIZE];
Ha::buildSensorConfig(message, Ha::TemperatureConfig{"Livingroom Temperature", "livingroom_temperature", bmpTopic}); Ha::buildSensorConfig(message, Ha::TemperatureConfig{"Livingroom Temperature", "livingroom_temperature", bmpTopic});
@ -86,9 +97,11 @@ namespace Mqtt {
tPublishConfig.enable(); tPublishConfig.enable();
tPublishBmp.enableIfNot(); tPublishBmp.enableIfNot();
tPublishCommand.enableDelayed(); tPublishCommand.enableDelayed();
tReConnect.disable();
Serial.println("Connected to MQTT"); Serial.println("Connected to MQTT");
}); });
client.onDisconnect([](AsyncMqttClientDisconnectReason reason) { client.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
tReConnect.enableDelayed();
tPublishCommand.disable(); tPublishCommand.disable();
tPublishBmp.disable(); tPublishBmp.disable();
Serial.println("Disconnected from MQTT"); Serial.println("Disconnected from MQTT");

View File

@ -48,7 +48,7 @@ void onWifiConnected() {
Wifi::printStatus(); Wifi::printStatus();
Ota::tLoop.enable(); Ota::tLoop.enable();
if (!Ir::avrOn) tCheckWifi.restartDelayed(); if (!Ir::avrOn) tCheckWifi.restartDelayed();
Mqtt::client.connect(); Mqtt::connect();
if (time_t newTime = Ntp::updateTime()) { if (time_t newTime = Ntp::updateTime()) {
Serial.println(asctime(localtime(&newTime))); Serial.println(asctime(localtime(&newTime)));
} }
@ -57,7 +57,7 @@ void onWifiConnected() {
void checkWifiCallback() { void checkWifiCallback() {
#if !WIFI_ALWAYS_ON #if !WIFI_ALWAYS_ON
Serial.println("Wifi connection timed out"); Serial.println("Wifi connection timed out");
Mqtt::client.disconnect(); Mqtt::disconnect();
Ota::tLoop.disable(); Ota::tLoop.disable();
Wifi::disconnect(); Wifi::disconnect();
#endif #endif