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.
This commit is contained in:
Yurii committed 2026-11-30 01:15:10 +03:00
1 parent 5fcf0af96d
commit d7554f2fa1
3 files changed
+59 -36

No files matched your search

+2 -1
View File
@@ -10,7 +10,8 @@ lib_deps = ESP32Async/AsyncTCP@^3.5.0
ESP32Async/ESPAsyncWebServer@^3.12.1 ESP32Async/ESPAsyncWebServer@^3.12.1
mathieucarbou/MycilaTaskManager@^5.0.0 mathieucarbou/MycilaTaskManager@^5.0.0
https://github.com/mathieucarbou/MycilaMQTT 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/MycilaWebSerial@^8.2.3
mathieucarbou/MycilaUtilities@^5.0.0 mathieucarbou/MycilaUtilities@^5.0.0
laxilef/ESP32OT@^1.0.0 laxilef/ESP32OT@^1.0.0
+56 -33
View File
@@ -1254,15 +1254,6 @@ static float mqttValueToMetric(std::string_view path, float value) {
} }
static void subscribe() { 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) { const auto onSettingCommand = [](const std::string& topic, const std::string_view& message) {
if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) { if (isMqttBlocked() || !settings.mqtt.enabled || mqttConfigureTask.scheduled() || mqttConfigureTask.active()) {
return; 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. // Update the local subscriptions; MQTT applies them when connected.
if (resubscribe) { if (mqttPrefix != settings.mqtt.prefix || !haDiscovery) {
for (const auto& topic : mqttClient->getSubscribedTopics()) { for (const auto& topic : mqttClient->getSubscribedTopics()) {
mqttClient->unsubscribe(topic.c_str()); mqttClient->unsubscribe(topic.c_str());
} }
@@ -1444,25 +1431,34 @@ static void connect() {
subscribe(); subscribe();
} }
// Recreate discovery to apply the current device metadata and MQTT prefix. // Apply the current device metadata and MQTT prefix.
haDiscovery = std::make_unique<HA::Discovery>( HA::Device haDevice{
HA::Device{ .id = mqttPrefix,
.id = mqttPrefix, .name = PROJECT_NAME,
.name = PROJECT_NAME, .version = BUILD_VERSION,
.version = BUILD_VERSION, .model = PROJECT_NAME,
.model = PROJECT_NAME, .manufacturer = PROJECT_REPO,
.manufacturer = PROJECT_REPO, .url = std::string("http://") + getNetworkIp().toString().c_str() + "/",
.url = std::string("http://") + getNetworkIp().toString().c_str() + "/", };
},
mqttPrefix, // Create or update existing discovery
[](const char* topic, const std::string& payload) { if (!haDiscovery) {
return mqttClient->publish(topic, payload, true) haDiscovery = std::make_unique<HA::Discovery>(
? HA::Error::SUCCESS std::move(haDevice),
: HA::Error::ERR_MQTT_PUBLISHER; mqttPrefix,
} [](const char* topic, const std::string& payload) {
); return mqttClient->publish(topic, payload, true)
haDiscovery->setDiscoveryTopic(settings.mqtt.homeAssistantDiscoveryPrefix); ? HA::Error::SUCCESS
haDiscovery->setWillTopic("~/status"); : 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. // Start the connection after configuring discovery and subscriptions.
mqttClient->begin({ mqttClient->begin({
@@ -1554,6 +1550,14 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) {
mqttHaRefreshRequested.store(true); 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) { if (unitSystem != settings.system.unitSystem) {
unitSystem = settings.system.unitSystem; unitSystem = settings.system.unitSystem;
mqttHaPendingEntities mqttHaPendingEntities
@@ -1639,6 +1643,21 @@ Task mqttConfigureTask("Configure MQTT", Task::Type::ONCE, [](void*) {
} }
if (mqttHaRefreshRequested.exchange(false)) { 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(); mqttHaPendingEntities.set();
mqttHaPendingSensors.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. // Rebuild sensor discovery and clear old readings in the same queue handler.
if (!mqttReconfigureSensorsTask) { if (!mqttReconfigureSensorsTask) {
auto* task = new Task("Reconfigure MQTT sensors", [](void*) { auto* task = new Task("Reconfigure MQTT sensors", [](void*) {
if (haDiscovery->getDiscoveryTopic() != settings.mqtt.homeAssistantDiscoveryPrefix) {
return;
}
std::unique_lock<std::mutex> lock(mqttSensorsMutex, std::try_to_lock); std::unique_lock<std::mutex> lock(mqttSensorsMutex, std::try_to_lock);
if (!lock.owns_lock() || mqttSensorChanges.empty()) { if (!lock.owns_lock() || mqttSensorChanges.empty()) {
return; return;
+1 -2
View File
@@ -595,8 +595,7 @@ static void restApi() {
strcmp(previousMqtt.server, settings.mqtt.server) != 0 || strcmp(previousMqtt.server, settings.mqtt.server) != 0 ||
strcmp(previousMqtt.user, settings.mqtt.user) != 0 || strcmp(previousMqtt.user, settings.mqtt.user) != 0 ||
strcmp(previousMqtt.password, settings.mqtt.password) != 0 || strcmp(previousMqtt.password, settings.mqtt.password) != 0 ||
strcmp(previousMqtt.prefix, settings.mqtt.prefix) != 0 || strcmp(previousMqtt.prefix, settings.mqtt.prefix) != 0;
strcmp(previousMqtt.homeAssistantDiscoveryPrefix, settings.mqtt.homeAssistantDiscoveryPrefix) != 0;
} else if (section == S_EMERGENCY) { } else if (section == S_EMERGENCY) {
result = fromJson(requestDoc, settings.emergency); result = fromJson(requestDoc, settings.emergency);