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

+56 -33
View File
@@ -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::Discovery>(
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<HA::Discovery>(
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<std::mutex> lock(mqttSensorsMutex, std::try_to_lock);
if (!lock.owns_lock() || mqttSensorChanges.empty()) {
return;