From d7554f2fa17505887b22974aaf940175d9523737 Mon Sep 17 00:00:00 2001 From: Yurii Date: Mon, 30 Nov 2026 01:15:10 +0300 Subject: [PATCH] fix: synchronize Home Assistant discovery subscriptions Reuse Discovery through its device and base topic setters. Handle HA status subscriptions and prefix changes in the discovery task. --- platformio.ini | 3 +- src/mqtt.cpp | 89 +++++++++++++++++++++++++++++++------------------- src/portal.cpp | 3 +- 3 files changed, 59 insertions(+), 36 deletions(-) diff --git a/platformio.ini b/platformio.ini index 97dfc63..b9c48e1 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,7 +10,8 @@ lib_deps = ESP32Async/AsyncTCP@^3.5.0 ESP32Async/ESPAsyncWebServer@^3.12.1 mathieucarbou/MycilaTaskManager@^5.0.0 https://github.com/mathieucarbou/MycilaMQTT - https://github.com/mathieucarbou/MycilaHADiscovery + ;https://github.com/mathieucarbou/MycilaHADiscovery + https://github.com/Laxilef/MycilaHADiscovery#feature/discovery-setters mathieucarbou/MycilaWebSerial@^8.2.3 mathieucarbou/MycilaUtilities@^5.0.0 laxilef/ESP32OT@^1.0.0 diff --git a/src/mqtt.cpp b/src/mqtt.cpp index 0932f6b..3d17109 100644 --- a/src/mqtt.cpp +++ b/src/mqtt.cpp @@ -1254,15 +1254,6 @@ static float mqttValueToMetric(std::string_view path, float value) { } static void subscribe() { - mqttClient->subscribe( - std::string(settings.mqtt.homeAssistantDiscoveryPrefix) + "/status", - [](const std::string&, const std::string_view& message) { - if (message == "online") { - mqttHaRefreshRequested.store(true); - } - } - ); - const auto onSettingCommand = [](const std::string& topic, const std::string_view& message) { if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) { return; @@ -1430,12 +1421,8 @@ static void connect() { }); } - // Compare the applied prefixes before recreating discovery. - const bool resubscribe = mqttPrefix != settings.mqtt.prefix || !haDiscovery || - haDiscovery->getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix; - // Update the local subscriptions; MQTT applies them when connected. - if (resubscribe) { + if (mqttPrefix != settings.mqtt.prefix || !haDiscovery) { for (const auto& topic : mqttClient->getSubscribedTopics()) { mqttClient->unsubscribe(topic.c_str()); } @@ -1444,25 +1431,34 @@ static void connect() { subscribe(); } - // Recreate discovery to apply the current device metadata and MQTT prefix. - haDiscovery = std::make_unique( - HA::Device{ - .id = mqttPrefix, - .name = PROJECT_NAME, - .version = BUILD_VERSION, - .model = PROJECT_NAME, - .manufacturer = PROJECT_REPO, - .url = std::string("http://") + getNetworkIp().toString().c_str() + "/", - }, - mqttPrefix, - [](const char* topic, const std::string& payload) { - return mqttClient->publish(topic, payload, true) - ? HA::Error::SUCCESS - : HA::Error::ERR_MQTT_PUBLISHER; - } - ); - haDiscovery->setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix); - haDiscovery->setWillTopic("~/status"); + // Apply the current device metadata and MQTT prefix. + HA::Device haDevice{ + .id = mqttPrefix, + .name = PROJECT_NAME, + .version = BUILD_VERSION, + .model = PROJECT_NAME, + .manufacturer = PROJECT_REPO, + .url = std::string("http://") + getNetworkIp().toString().c_str() + "/", + }; + + // Create or update existing discovery + if (!haDiscovery) { + haDiscovery = std::make_unique( + std::move(haDevice), + mqttPrefix, + [](const char* topic, const std::string& payload) { + return mqttClient->publish(topic, payload, true) + ? HA::Error::SUCCESS + : HA::Error::ERR_MQTT_PUBLISHER; + } + ); + haDiscovery->setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix); + haDiscovery->setWillTopic("~/status"); + + } else { + haDiscovery->setDevice(std::move(haDevice)); + haDiscovery->setBaseTopic(mqttPrefix); + } // Start the connection after configuring discovery and subscriptions. mqttClient->begin({ @@ -1554,6 +1550,14 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) { mqttHaRefreshRequested.store(true); } + // Apply the new discovery prefix and request a full HA refresh. + if (haDiscovery->getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix) { + const auto statusTopic = haDiscovery->getDiscoveryTopic() + "/status"; + mqttClient->unsubscribe(statusTopic.c_str()); + haDiscovery->setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix); + mqttHaRefreshRequested.store(true); + } + if (unitSystem != settings.system.unitSystem) { unitSystem = settings.system.unitSystem; mqttHaPendingEntities @@ -1639,6 +1643,21 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) { } if (mqttHaRefreshRequested.exchange(false)) { + const auto statusTopic = haDiscovery->getDiscoveryTopic() + "/status"; + const auto topics = mqttClient->getSubscribedTopics(); + const bool subscribed = std::find(topics.begin(), topics.end(), statusTopic) != topics.end(); + + if (settings.mqtt.homeAssistantDiscovery && !subscribed) { + mqttClient->subscribe(statusTopic, [](const std::string&, const std::string_view& message) { + if (message == "online") { + mqttHaRefreshRequested.store(true); + } + }); + + } else if (!settings.mqtt.homeAssistantDiscovery && subscribed) { + mqttClient->unsubscribe(statusTopic.c_str()); + } + mqttHaPendingEntities.set(); mqttHaPendingSensors.set(); } @@ -1689,6 +1708,10 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) { // Rebuild sensor discovery and clear old readings in the same queue handler. if (!mqttReconfigureSensorsTask) { auto* task = new Task("Reconfigure MQTT sensors", [](void*) { + if (haDiscovery->getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix) { + return; + } + std::unique_lock lock(mqttSensorsMutex, std::try_to_lock); if (!lock.owns_lock() || mqttSensorChanges.empty()) { return; diff --git a/src/portal.cpp b/src/portal.cpp index f671258..e718964 100644 --- a/src/portal.cpp +++ b/src/portal.cpp @@ -595,8 +595,7 @@ static void restApi() { strcmp(previousMqtt.server, settings.mqtt.server) != 0 || strcmp(previousMqtt.user, settings.mqtt.user) != 0 || strcmp(previousMqtt.password, settings.mqtt.password) != 0 || - strcmp(previousMqtt.prefix, settings.mqtt.prefix) != 0 || - strcmp(previousMqtt.homeAssistantDiscoveryPrefix, settings.mqtt.homeAssistantDiscoveryPrefix) != 0; + strcmp(previousMqtt.prefix, settings.mqtt.prefix) != 0; } else if (section == S_EMERGENCY) { result = fromJson(requestDoc, settings.emergency);