Keep the mqtt_subscribe topic copy and note when custom topics must be set

This commit is contained in:
J. Nick Koston
2026-10-14 09:33:35 -10:00
parent d220f9c395
commit d8d4c2f121
3 changed files with 7 additions and 4 deletions
+4 -1
View File
@@ -40,7 +40,9 @@ void log_mqtt_component(const char *tag, MQTTComponent *obj, bool state_topic, b
static_assert(sizeof(type_str) - 1 <= MQTT_COMPONENT_TYPE_MAX_LEN, \
#class_name "::component_type() exceeds MQTT_COMPONENT_TYPE_MAX_LEN");
// Macro to define custom topic getter/setter with compile-time suffix length verification
// Macro to define custom topic getter/setter with compile-time suffix length verification.
// Set the topic before setup(): subscriptions rebuild it when needed, so a later change only reaches the broker
// after a reconnect.
#define MQTT_COMPONENT_CUSTOM_TOPIC_(name, type) \
static_assert(sizeof(#name "/" #type) - 1 <= MQTT_SUFFIX_MAX_LEN, \
"topic suffix " #name "/" #type " exceeds MQTT_SUFFIX_MAX_LEN"); \
@@ -123,6 +125,7 @@ class MQTTComponent : public Component {
template<typename T> void set_custom_state_topic(T &&custom_state_topic) {
this->custom_state_topic_ = std::forward<T>(custom_state_topic);
}
/// Set a custom command topic before setup(); a later change only reaches the broker after a reconnect.
template<typename T> void set_custom_command_topic(T &&custom_command_topic) {
this->custom_command_topic_ = std::forward<T>(custom_command_topic);
}
@@ -10,7 +10,7 @@ ESPHOME_LOG_TAG(TAG, "mqtt_subscribe.sensor");
void MQTTSubscribeSensor::setup() {
mqtt::global_mqtt_client->subscribe(
mqtt::static_topic(this->topic_.c_str()),
this->topic_,
[this](const std::string &topic, const std::string &payload) {
auto val = parse_number<float>(payload);
if (!val.has_value()) {
@@ -11,8 +11,8 @@ ESPHOME_LOG_TAG(TAG, "mqtt_subscribe.text_sensor");
void MQTTSubscribeTextSensor::setup() {
this->parent_->subscribe(
mqtt::static_topic(this->topic_.c_str()),
[this](const std::string &topic, const std::string &payload) { this->publish_state(payload); }, this->qos_);
this->topic_, [this](const std::string &topic, const std::string &payload) { this->publish_state(payload); },
this->qos_);
}
float MQTTSubscribeTextSensor::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void MQTTSubscribeTextSensor::dump_config() {