diff --git a/esphome/components/mqtt/mqtt_client.cpp b/esphome/components/mqtt/mqtt_client.cpp index 6a7d91a02ab3..1cdf704d8394 100644 --- a/esphome/components/mqtt/mqtt_client.cpp +++ b/esphome/components/mqtt/mqtt_client.cpp @@ -723,6 +723,11 @@ void MQTTClientComponent::set_discovery_info(std::string &&prefix, MQTTDiscovery this->discovery_info_.object_id_generator = object_id_generator; this->discovery_info_.retain = retain; this->discovery_info_.clean = clean; + this->discovery_prefix_configured_ = this->discovery_info_.prefix; +} + +void MQTTClientComponent::set_discovery_enabled(bool enabled) { + this->discovery_info_.prefix = enabled ? this->discovery_prefix_configured_ : ""; } void MQTTClientComponent::disable_last_will() { @@ -739,6 +744,7 @@ void MQTTClientComponent::disable_discovery() { .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR, .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR, }; + this->discovery_prefix_configured_ = ""; } void MQTTClientComponent::on_shutdown() { if (!this->shutdown_message_.topic.empty()) { diff --git a/esphome/components/mqtt/mqtt_client.h b/esphome/components/mqtt/mqtt_client.h index fe8f42b0cdec..88d8acb5dc5a 100644 --- a/esphome/components/mqtt/mqtt_client.h +++ b/esphome/components/mqtt/mqtt_client.h @@ -132,6 +132,8 @@ class MQTTClientComponent : public Component { const MQTTDiscoveryInfo &get_discovery_info() const; /// Globally disable Home Assistant discovery. void disable_discovery(); + /// Flip discovery at run time; off keeps the configured prefix so a later on can restore it. + void set_discovery_enabled(bool enabled); bool is_discovery_enabled() const; bool is_discovery_ip_enabled() const; @@ -314,6 +316,8 @@ class MQTTClientComponent : public Component { .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR, .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR, }; + /// What set_discovery_enabled(true) restores; empty once discovery is off at build time. + std::string discovery_prefix_configured_{"homeassistant"}; std::string topic_prefix_{}; bool topic_prefix_auto_{true}; bool birth_message_auto_{true};