ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
mqtt_client.cpp
Go to the documentation of this file.
1#include "mqtt_client.h"
2
3#ifdef USE_MQTT
4
5#include <utility>
10#include "esphome/core/log.h"
13#ifdef USE_LOGGER
15#endif
16#include "lwip/dns.h"
17#include "lwip/err.h"
18#include "mqtt_component.h"
19#include "mqtt_topic_match.h"
20
21#ifdef USE_API
23#endif
24#ifdef USE_MQTT_SESSION_PERSISTENCE
26#ifdef USE_ESP8266
28#elif defined(USE_ESP32)
29#include <esp_attr.h>
30#include <soc/soc_caps.h>
32#endif
33#endif
34#ifdef USE_DASHBOARD_IMPORT
36#endif
37
38namespace esphome::mqtt {
39
40ESPHOME_LOG_TAG(TAG, "mqtt");
41
42// Maximum number of MQTT component resends per loop iteration.
43// Limits work to avoid triggering the task watchdog on reconnect.
44static constexpr uint8_t MAX_RESENDS_PER_LOOP = 8;
45#ifdef USE_MQTT_SESSION_PERSISTENCE
46static constexpr uint32_t SESSION_FINGERPRINT_HASH = fnv1a_hash("mqtt_session_fingerprint");
47#ifdef USE_ESP8266
48// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
49static ESPPreferenceObject s_session_fingerprint_pref;
50#elif defined(USE_ESP32) && SOC_RTC_MEM_SUPPORTED
51#define USE_MQTT_SESSION_FINGERPRINT_RTC_NOINIT
52// Own 8 bytes rather than core's RTC preference pool, which would add 248 bytes of RTC RAM (usable memory on
53// variants with RTC fast memory only). The fingerprint and its checksum; power-on garbage fails the checksum.
54// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
55static RTC_NOINIT_ATTR uint32_t s_session_fingerprint[2];
56#endif
57
58// RTC memory where available; RAM only otherwise, so a reset resubscribes
59static void load_session_fingerprint([[maybe_unused]] uint32_t *fingerprint) {
60#ifdef USE_ESP8266
61 s_session_fingerprint_pref = global_preferences->make_preference<uint32_t>(SESSION_FINGERPRINT_HASH, false);
62 s_session_fingerprint_pref.load(fingerprint);
63#elif defined(USE_MQTT_SESSION_FINGERPRINT_RTC_NOINIT)
64 rtc_pref_decode(s_session_fingerprint, SESSION_FINGERPRINT_HASH, 1, reinterpret_cast<uint8_t *>(fingerprint),
65 sizeof(*fingerprint));
66#endif
67}
68
69static void store_session_fingerprint([[maybe_unused]] const uint32_t *fingerprint) {
70#ifdef USE_ESP8266
71 s_session_fingerprint_pref.save(fingerprint);
72#elif defined(USE_MQTT_SESSION_FINGERPRINT_RTC_NOINIT)
73 rtc_pref_encode(s_session_fingerprint, SESSION_FINGERPRINT_HASH, 1, reinterpret_cast<const uint8_t *>(fingerprint),
74 sizeof(*fingerprint));
75#endif
76}
77#endif
78
79// Disconnect reason strings indexed by MQTTClientDisconnectReason enum (0-8)
80PROGMEM_STRING_TABLE(MQTTDisconnectReasonStrings, "TCP disconnected", "Unacceptable Protocol Version",
81 "Identifier Rejected", "Server Unavailable", "Malformed Credentials", "Not Authorized",
82 "Not Enough Space", "TLS Bad Fingerprint", "DNS Resolve Error", "Unknown");
83
85 global_mqtt_client = this;
86 char mac_addr[MAC_ADDRESS_BUFFER_SIZE];
88 const StringRef &name = App.get_name();
89 char client_id[MAX_NAME_WITH_SUFFIX_SIZE];
90 size_t len = make_name_with_suffix_to(client_id, sizeof(client_id), name.c_str(), name.size(), '-', mac_addr,
91 MAC_ADDRESS_BUFFER_SIZE - 1);
92 this->credentials_.client_id.assign(client_id, len);
93}
94
95// Connection
96// Room for "esphome/<kind>/<name>" with the longest kind, "discover"
97static constexpr size_t ESPHOME_TOPIC_BUFFER_SIZE = sizeof("esphome/discover/") + ESPHOME_DEVICE_NAME_MAX_LEN;
98
99static void format_esphome_topic(char (&topic)[ESPHOME_TOPIC_BUFFER_SIZE], const char *kind) {
100 buf_append_printf(topic, sizeof(topic), 0, "esphome/%s/%s", kind, App.get_name().c_str());
101}
102
105 [this](const char *topic, const char *payload, size_t len, size_t index, size_t total) {
106 // total comes from the broker; reserving it unchecked can exhaust the heap
107 if (total > MQTT_MAX_PAYLOAD_SIZE) {
108 if (index == 0) {
109 ESP_LOGW(TAG, "Dropped %zu byte message on '%s' (max %d)", total, topic, MQTT_MAX_PAYLOAD_SIZE);
110 }
111 return;
112 }
113 if (index == 0) {
114 this->payload_buffer_.clear();
115 this->payload_buffer_.reserve(total);
116 }
117
118 // append new payload, may contain incomplete MQTT message
119 this->payload_buffer_.append(payload, len);
120
121 // MQTT fully received
122 if (len + index == total) {
123 this->on_message(topic, this->payload_buffer_);
124 this->payload_buffer_.clear();
125 }
126 });
128 if (this->state_ == MQTT_CLIENT_DISABLED)
129 return;
131 this->disconnect_reason_ = reason;
132 });
133#ifdef USE_MQTT_SESSION_PERSISTENCE
134 this->mqtt_backend_.set_on_connect([this](bool session_present) {
135 this->session_present_ = session_present;
136#ifndef USE_ESP32
137 // AsyncMqttClient delivers CONNACK and SUBACK in the same context, so the counter has one writer
138 this->subacks_.reset();
139#endif
140 });
141#ifndef USE_ESP32
142 this->mqtt_backend_.set_on_subscribe([this](uint16_t, uint8_t return_code) { this->subacks_.add(return_code); });
143#endif
144 load_session_fingerprint(&this->session_fingerprint_);
145#endif
146#ifdef USE_LOGGER
147 if (this->is_log_message_enabled() && logger::global_logger != nullptr) {
149 this, [](void *self, uint8_t level, const char *tag, const char *message, size_t message_len) {
150 static_cast<MQTTClientComponent *>(self)->on_log(level, tag, message, message_len);
151 });
152#ifdef USE_MQTT_CRASH_LOG
153 // `esphome logs` announces itself here, like an API client's log subscription, and the record stays
154 // loggable until the next boot, so the offer does too. A log topic that drops errors would swallow the
155 // replay, so it is not offered. The topic is rebuilt from the device name when needed, so nothing is
156 // stored for it.
157 this->crash_log_offered_ = logger::crash_log_pending() && this->log_level_ >= ESPHOME_LOG_LEVEL_ERROR;
158#endif
159 }
160#endif
161
162 if (this->is_discovery_ip_enabled()) {
163 this->subscribe(
164 static_topic("esphome/discover"),
165 [this](const std::string &topic, const std::string &payload) { this->send_device_info_(); }, 2);
166
167 static_assert(sizeof("esphome/ping/") + ESPHOME_DEVICE_NAME_MAX_LEN <= MQTT_DEFAULT_TOPIC_MAX_LEN);
168 MQTTTopicSource ping_topic{[](const void *, std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN> buf) {
169 size_t len = buf_append_printf(buf.data(), buf.size(), 0, "esphome/ping/%s",
170 App.get_name().c_str());
171 return StringRef(buf.data(), len);
172 },
173 nullptr};
174 this->subscribe(
175 ping_topic, [this](const std::string &topic, const std::string &payload) { this->send_device_info_(); }, 2);
176 }
177
178 if (this->enable_on_boot_) {
179 this->enable();
180 }
181}
182
184 if (!this->is_connected() or !this->is_discovery_ip_enabled()) {
185 return;
186 }
187 // Format topic on stack to avoid heap allocation
188 char topic[ESPHOME_TOPIC_BUFFER_SIZE];
189 format_esphome_topic(topic, "discover");
190
191 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
192 this->publish_json(
193 topic,
194 [](JsonObject root) {
195 uint8_t index = 0;
196 for (auto &ip : network::get_ip_addresses()) {
197 if (ip.is_set()) {
198 char key[8]; // "ip" + up to 3 digits + null
199 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
200 if (index == 0) {
201 key[0] = 'i';
202 key[1] = 'p';
203 key[2] = '\0';
204 } else {
205 buf_append_printf(key, sizeof(key), 0, "ip%u", index);
206 }
207 ip.str_to(ip_buf);
208 root[key] = ip_buf;
209 index++;
210 }
211 }
212 root[ESPHOME_F("name")] = App.get_name();
213 if (!App.get_friendly_name().empty()) {
214 root[ESPHOME_F("friendly_name")] = App.get_friendly_name();
215 }
216#ifdef USE_API
217 root[ESPHOME_F("port")] = api::global_api_server->get_port();
218#endif
219 root[ESPHOME_F("version")] = ESPHOME_VERSION;
220 char mac_buf[MAC_ADDRESS_BUFFER_SIZE];
222 root[ESPHOME_F("mac")] = mac_buf;
223
224#ifdef USE_ESP8266
225 root[ESPHOME_F("platform")] = ESPHOME_F("ESP8266");
226#endif
227#ifdef USE_ESP32
228 root[ESPHOME_F("platform")] = ESPHOME_F("ESP32");
229#endif
230#ifdef USE_LIBRETINY
231 root[ESPHOME_F("platform")] = lt_cpu_get_model_name();
232#endif
233
234 root[ESPHOME_F("board")] = ESPHOME_BOARD;
235#if defined(USE_WIFI)
236 root[ESPHOME_F("network")] = ESPHOME_F("wifi");
237#elif defined(USE_ETHERNET)
238 root[ESPHOME_F("network")] = ESPHOME_F("ethernet");
239#endif
240
241#ifdef ESPHOME_PROJECT_NAME
242 root[ESPHOME_F("project_name")] = ESPHOME_PROJECT_NAME;
243 root[ESPHOME_F("project_version")] = ESPHOME_PROJECT_VERSION;
244#endif // ESPHOME_PROJECT_NAME
245
246#ifdef USE_DASHBOARD_IMPORT
247 root[ESPHOME_F("package_import_url")] = dashboard_import::get_package_import_url();
248#endif
249
250#ifdef USE_API_NOISE
251 root[api::global_api_server->get_noise_ctx().has_psk() ? ESPHOME_F("api_encryption")
252 : ESPHOME_F("api_encryption_supported")] =
253 ESPHOME_F("Noise_NNpsk0_25519_ChaChaPoly_SHA256");
254#endif
255 },
256 2, this->discovery_info_.retain);
257 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
258}
259
260#ifdef USE_LOGGER
261void MQTTClientComponent::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
262 (void) tag;
263 if (level <= this->log_level_ && this->is_connected()) {
264 this->publish(this->log_message_.topic.c_str(), message, message_len, this->log_message_.qos,
265 this->log_message_.retain);
266 }
267}
268#endif
269
271 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
272 // clang-format off
273 ESP_LOGCONFIG(TAG,
274 "MQTT:\n"
275 " Server Address: %s:%u (%s)\n"
276 " Username: " LOG_SECRET("'%s'") "\n"
277 " Client ID: " LOG_SECRET("'%s'") "\n"
278 " Clean Session: %s",
279 this->credentials_.address.c_str(), this->credentials_.port, this->ip_.str_to(ip_buf),
280 this->credentials_.username.c_str(), this->credentials_.client_id.c_str(),
281 YESNO(this->credentials_.clean_session));
282 // clang-format on
283#ifdef USE_ESP32
284 if (const MQTTTransport transport = this->mqtt_backend_.get_transport();
286 ESP_LOGCONFIG(TAG,
287 " Transport: %s\n"
288 " WebSocket Path: '%s'",
289 transport == MQTTTransport::MQTT_TRANSPORT_WSS ? LOG_STR_LITERAL("wss") : LOG_STR_LITERAL("ws"),
290 this->mqtt_backend_.get_ws_path());
291 }
292#endif
293#if defined(USE_MQTT_CERT_BUNDLE)
294 ESP_LOGCONFIG(TAG, " TLS: certificate bundle");
295#elif defined(USE_MQTT_TLS_INSECURE)
296 ESP_LOGCONFIG(TAG, " TLS: no verification");
297#elif defined(USE_MQTT_TLS)
298 ESP_LOGCONFIG(TAG, " TLS: CA certificate");
299#endif
300 if (this->is_discovery_ip_enabled()) {
301 ESP_LOGCONFIG(TAG, " Discovery IP enabled");
302 }
303 if (!this->discovery_info_.prefix.empty()) {
304 ESP_LOGCONFIG(TAG,
305 " Discovery prefix: '%s'\n"
306 " Discovery retain: %s",
307 this->discovery_info_.prefix.c_str(), YESNO(this->discovery_info_.retain));
308 }
309 ESP_LOGCONFIG(TAG,
310 " Topic Prefix: '%s'\n"
311 " Max Payload Size: %d",
312 this->topic_prefix_.c_str(), MQTT_MAX_PAYLOAD_SIZE);
313 if (!this->log_message_.topic.empty()) {
314 ESP_LOGCONFIG(TAG, " Log Topic: '%s'", this->log_message_.topic.c_str());
315 }
316 if (!this->availability_.topic.empty()) {
317 ESP_LOGCONFIG(TAG, " Availability: '%s'", this->availability_.topic.c_str());
318 }
319}
321 return network::is_disabled() || this->state_ == MQTT_CLIENT_DISABLED || this->is_connected() ||
323}
324
326 for (auto &subscription : this->subscriptions_) {
327 subscription.subscribed = false;
328 subscription.resubscribe_timeout = 0;
329 }
330
331 this->status_set_warning();
332 this->dns_resolve_error_ = false;
333 this->dns_resolved_ = false;
334 ip_addr_t addr;
335 err_t err;
336 {
337 LwIPLock lock;
338#if USE_NETWORK_IPV6
339 err = dns_gethostbyname_addrtype(this->credentials_.address.c_str(), &addr, MQTTClientComponent::dns_found_callback,
340 this, LWIP_DNS_ADDRTYPE_IPV6_IPV4);
341#else
342 err = dns_gethostbyname_addrtype(this->credentials_.address.c_str(), &addr, MQTTClientComponent::dns_found_callback,
343 this, LWIP_DNS_ADDRTYPE_IPV4);
344#endif /* USE_NETWORK_IPV6 */
345 }
346 switch (err) {
347 case ERR_OK: {
348 // Got IP immediately
349 this->dns_resolved_ = true;
350 this->ip_ = network::IPAddress(&addr);
351 this->start_connect_();
352 return;
353 }
354 case ERR_INPROGRESS: {
355 // wait for callback
356 ESP_LOGD(TAG, "Resolving broker IP address");
357 break;
358 }
359 default:
360 case ERR_ARG: {
361 // error
362 ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
363 break;
364 }
365 }
366
368 this->connect_begin_ = millis();
369}
371 if (!this->dns_resolved_ && millis() - this->connect_begin_ > 20000) {
372 this->dns_resolve_error_ = true;
373 }
374
375 if (this->dns_resolve_error_) {
376 ESP_LOGW(TAG, "Couldn't resolve IP address for '%s'", this->credentials_.address.c_str());
380 return;
381 }
382
383 if (!this->dns_resolved_) {
384 return;
385 }
386
387 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
388 ESP_LOGD(TAG, "Resolved broker IP address to %s", this->ip_.str_to(ip_buf));
389 this->start_connect_();
390}
391#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
392void MQTTClientComponent::dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg) {
393#else
394void MQTTClientComponent::dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg) {
395#endif
396 auto *a_this = (MQTTClientComponent *) callback_arg;
397 if (ipaddr == nullptr) {
398 a_this->dns_resolve_error_ = true;
399 } else {
400 a_this->ip_ = network::IPAddress(ipaddr);
401 a_this->dns_resolved_ = true;
402 }
403}
404
407 return;
408
409 ESP_LOGI(TAG, "Connecting");
410 // Force disconnect first
412
415 const char *username = nullptr;
416 if (!this->credentials_.username.empty())
417 username = this->credentials_.username.c_str();
418 const char *password = nullptr;
419 if (!this->credentials_.password.empty())
420 password = this->credentials_.password.c_str();
421
422 this->mqtt_backend_.set_credentials(username, password);
423
424 this->mqtt_backend_.set_server(this->credentials_.address.c_str(), this->credentials_.port);
425 if (!this->last_will_.topic.empty()) {
426 this->mqtt_backend_.set_will(this->last_will_.topic.c_str(), this->last_will_.qos, this->last_will_.retain,
427 this->last_will_.payload.c_str());
428 }
429
430#ifdef USE_MQTT_SESSION_PERSISTENCE
431 this->session_present_ = false;
432#endif
433 this->mqtt_backend_.connect();
435 this->connect_begin_ = millis();
436}
438 return this->state_ == MQTT_CLIENT_CONNECTED && this->mqtt_backend_.connected();
439}
440
442 if (!this->mqtt_backend_.connected()) {
443 if (millis() - this->connect_begin_ > 60000) {
445 this->start_dnslookup_();
446 }
447 return;
448 }
449
451 this->sent_birth_message_ = false;
452 this->status_clear_warning();
453 ESP_LOGI(TAG, "Connected");
454 // MQTT Client needs some time to be fully set up.
455 delay(100); // NOLINT
456
457#ifdef USE_MQTT_SESSION_PERSISTENCE
458 this->subscribes_sent_ = 0;
459 const bool resumed =
461 this->subacks_settled_ = resumed;
462 if (resumed) {
463 for (auto &subscription : this->subscriptions_)
464 subscription.subscribed = true;
465 } else {
466 // Untrusted until all are acknowledged again, so a reset part way through does not trust a partial session;
467 // topics only an older firmware used stay subscribed in the session
468 this->set_session_fingerprint_(UNTRUSTED_SESSION_FINGERPRINT);
469 }
470#endif
472#ifdef USE_MQTT_CRASH_LOG
473#ifdef USE_MQTT_SESSION_PERSISTENCE
474 // Otherwise sent once the SUBACKs are in, so its own SUBACK is never counted
475 if (resumed) {
476 this->subscribe_crash_log_();
477 }
478#else
479 this->subscribe_crash_log_();
480#endif
481#endif
482 this->send_device_info_();
483
484 for (MQTTComponent *component : this->children_)
485 component->schedule_resend_state();
486}
487
489 // Call the backend loop first
491
492 if (this->disconnect_reason_.has_value()) {
493 const LogString *reason_s = MQTTDisconnectReasonStrings::get_log_str(
494 static_cast<uint8_t>(*this->disconnect_reason_), MQTTDisconnectReasonStrings::LAST_INDEX);
495 if (!network::is_connected()) {
496 reason_s = LOG_STR("WiFi disconnected");
497 }
498 ESP_LOGW(TAG, "Disconnected: %s", LOG_STR_ARG(reason_s));
499 this->disconnect_reason_.reset();
500 }
501
503
504 switch (this->state_) {
506 return; // Return to avoid a reboot when disabled
508 if (now - this->connect_begin_ > 5000) {
509 this->start_dnslookup_();
510 }
511 break;
513 this->check_dnslookup_();
514 break;
516 this->check_connected();
517 break;
519 if (!this->mqtt_backend_.connected()) {
521 ESP_LOGW(TAG, "Lost client connection");
522 this->start_dnslookup_();
523 } else {
524 this->last_connected_ = now;
525 const bool all_subscribed = this->resubscribe_subscriptions_();
526#ifdef USE_MQTT_SESSION_PERSISTENCE
527 if (all_subscribed && !this->subacks_settled_)
528 this->check_subacks_();
529#endif
530 // Online only once every paced SUBSCRIBE is out, so no command for an unsubscribed topic is lost
531 if (all_subscribed && !this->birth_message_.topic.empty() && !this->sent_birth_message_) {
532 this->sent_birth_message_ = this->publish(this->birth_message_);
533 }
534
535 // Process pending resends for all MQTT components centrally
536 // Limit work per loop iteration to avoid triggering task WDT on reconnect
537 {
538 uint8_t resend_count = 0;
539 for (MQTTComponent *component : this->children_) {
540 if (component->is_resend_pending()) {
541 component->process_resend();
542 if (++resend_count >= MAX_RESENDS_PER_LOOP)
543 break;
544 }
545 }
546 }
547 }
548 break;
549 }
550
551 if (millis() - this->last_connected_ > this->reboot_timeout_ && this->reboot_timeout_ != 0) {
552 ESP_LOGE(TAG, "Can't connect; restarting");
553 App.reboot();
554 }
555}
557
558// Subscribe
559bool MQTTClientComponent::subscribe_(const char *topic, uint8_t qos) {
560 if (!this->is_connected())
561 return false;
562
563 bool ret = this->mqtt_backend_.subscribe(topic, qos);
564 yield();
565
566 if (ret) {
567 ESP_LOGV(TAG, "subscribe(topic='%s')", topic);
568 } else {
569 delay(5);
570 ESP_LOGV(TAG, "Subscribe failed for topic='%s'. Will retry", topic);
571 this->status_momentary_warning(1000);
572 }
573 return ret != 0;
574}
575// Out of line so the topic buffer is not part of loop()'s stack frame
576__attribute__((noinline)) bool MQTTClientComponent::subscribe_topic_(const MQTTTopicSource &topic, uint8_t qos) {
577 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
578 return this->subscribe_(topic.build(buf).c_str(), qos);
579}
580
581void MQTTClientComponent::resubscribe_subscription_(MQTTSubscription *sub) {
582 if (sub->subscribed)
583 return;
584
585 const uint32_t now = millis();
586 bool do_resub = sub->resubscribe_timeout == 0 || now - sub->resubscribe_timeout > 1000;
587
588 // Paced so the connect burst fits the backend queue
589 if (do_resub && this->mqtt_backend_.can_subscribe()) {
590 sub->subscribed = this->subscribe_topic_(sub->topic, sub->qos);
591 sub->resubscribe_timeout = now;
592#ifdef USE_MQTT_SESSION_PERSISTENCE
593 // Only the subscriptions the fingerprint covers are counted
594 if (sub->subscribed)
595 this->subscribes_sent_++;
596#endif
597 }
598}
600 bool all_subscribed = true;
601 for (auto &subscription : this->subscriptions_) {
602 this->resubscribe_subscription_(&subscription);
603 all_subscribed &= subscription.subscribed;
604 }
605 return all_subscribed;
606}
607
608#ifdef USE_MQTT_SESSION_PERSISTENCE
609// Out of line so the topic buffer is not part of loop()'s stack frame
611 // Seeded with the config hash, so a new firmware config sends every subscription once
612 uint32_t fingerprint = App.get_config_hash();
613 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
614 for (const auto &subscription : this->subscriptions_)
615 fingerprint = add_subscription_fingerprint(fingerprint, subscription.topic.build(buf).c_str(), subscription.qos);
616 return fingerprint;
617}
618
620#ifdef USE_ESP32
621 const SubackTally tally = this->mqtt_backend_.get_subacks().tally(this->subscribes_sent_);
622#else
623 const SubackTally tally = this->subacks_.tally(this->subscribes_sent_);
624#endif
626 return;
627 this->subacks_settled_ = true;
628 // Trusted only once the broker granted every SUBSCRIBE, so a reset or a lost link before that sends them again,
629 // and a refused one is tried again at the next connect
632#ifdef USE_MQTT_CRASH_LOG
633 this->subscribe_crash_log_();
634#endif
635}
636
638 if (this->session_fingerprint_ == fingerprint)
639 return;
640 this->session_fingerprint_ = fingerprint;
641 store_session_fingerprint(&this->session_fingerprint_);
642}
643#endif
644
645#ifdef USE_MQTT_CRASH_LOG
647 // Best effort: a refused subscription is tried again at the next connection
648 if (!this->crash_log_offered_)
649 return;
650 char topic[ESPHOME_TOPIC_BUFFER_SIZE];
651 format_esphome_topic(topic, "logs");
652 this->subscribe_(topic, 0);
653}
654
655void MQTTClientComponent::handle_crash_log_request_(const std::string &topic, const std::string &payload) {
656 // Only the CLI's empty request counts: a log_topic pointing at this topic would otherwise replay the crash
657 // log for every line it logs
658 if (!this->crash_log_offered_ || !payload.empty())
659 return;
660 char logs_topic[ESPHOME_TOPIC_BUFFER_SIZE];
661 format_esphome_topic(logs_topic, "logs");
662 if (topic == logs_topic)
664}
665#endif
666
667static StringRef static_topic_builder(const void *context, std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN>) {
668 return StringRef(static_cast<const char *>(context));
669}
670// Same as static_topic_builder, but a distinct function so its address marks the topics to free
671static StringRef copied_topic_builder(const void *context, std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN>) {
672 return StringRef(static_cast<const char *>(context));
673}
674
675MQTTTopicSource static_topic(const char *topic) { return {static_topic_builder, topic}; }
676
677static_assert(MQTT_DEFAULT_TOPIC_MAX_LEN == 248, "update MQTT_DEFAULT_TOPIC_MAX_LEN in mqtt/__init__.py");
678
679#ifdef USE_ESP8266
680// mqtt/__init__.py picks this source only for topics that fit
681static StringRef progmem_topic_builder(const void *context, std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN> buf) {
682 size_t len = buf_append_str_p(buf.data(), buf.size(), 0, static_cast<const char *>(context));
683 return StringRef(buf.data(), len);
684}
685
686MQTTTopicSource progmem_topic(ProgmemStr topic) {
687 return {progmem_topic_builder, reinterpret_cast<const char *>(topic)};
688}
689#endif
690
691MQTTTopicSource MQTTClientComponent::copy_topic(StringRef topic) {
692 char *copy = new char[topic.size() + 1]; // NOLINT(cppcoreguidelines-owning-memory)
693 memcpy(copy, topic.c_str(), topic.size());
694 copy[topic.size()] = '\0';
695 return {copied_topic_builder, copy};
696}
697
698void MQTTClientComponent::add_subscription_(MQTTTopicSource topic, mqtt_subscription_callback_t callback, bool boxed,
699 uint8_t qos) {
700 auto &subscription = this->subscriptions_.emplace_back(MQTTSubscription{
701 .topic = topic,
702 .callback = callback,
703 .resubscribe_timeout = 0,
704 .qos = qos,
705 .subscribed = false,
706 .boxed = boxed,
707 .removed = false,
708 });
709 this->resubscribe_subscription_(&subscription);
710}
711
712// Out of line so the topic buffer is not part of unsubscribe()'s stack frame
713__attribute__((noinline)) static bool topic_equals(const MQTTTopicSource &source, const std::string &topic) {
714 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
715 return source.build(buf) == topic;
716}
717
718void MQTTClientComponent::unsubscribe(const std::string &topic) {
719#ifdef USE_MQTT_SESSION_PERSISTENCE
720 // Before the broker drops the topic, so a reset in between cannot leave a matching fingerprint
721 this->set_session_fingerprint_(UNTRUSTED_SESSION_FINGERPRINT);
722#endif
723 bool ret = this->mqtt_backend_.unsubscribe(topic.c_str());
724 yield();
725 if (ret) {
726 ESP_LOGV(TAG, "unsubscribe(topic='%s')", topic.c_str());
727 } else {
728 delay(5);
729 ESP_LOGV(TAG, "Unsubscribe failed for topic='%s'.", topic.c_str());
730 this->status_momentary_warning(1000);
731 }
732
733 for (auto &subscription : this->subscriptions_) {
734 if (topic_equals(subscription.topic, topic))
735 subscription.removed = true;
736 }
737 // A callback may be running; the outermost dispatch erases them once it returns.
738 if (this->dispatching_) {
739 this->removed_while_dispatching_ = true;
740 } else {
742 }
743}
744
746 auto it = this->subscriptions_.begin();
747 while (it != this->subscriptions_.end()) {
748 if (it->removed) {
749 if (it->boxed)
750 it->callback.free_boxed();
751 if (it->topic.builder == copied_topic_builder)
752 delete[] static_cast<const char *>(it->topic.context); // NOLINT(cppcoreguidelines-owning-memory)
753 it = this->subscriptions_.erase(it);
754 } else {
755 ++it;
756 }
757 }
758}
759
760// Publish
761bool MQTTClientComponent::publish(const std::string &topic, const std::string &payload, uint8_t qos, bool retain) {
762 return this->publish(topic, payload.data(), payload.size(), qos, retain);
763}
764
765bool MQTTClientComponent::publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos,
766 bool retain) {
767 return this->publish(topic.c_str(), payload, payload_length, qos, retain);
768}
769
770bool MQTTClientComponent::publish(const MQTTMessage &message) {
771 return this->publish(message.topic.c_str(), message.payload.c_str(), message.payload.length(), message.qos,
772 message.retain);
773}
774bool MQTTClientComponent::publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos,
775 bool retain) {
776 return this->publish_json(topic.c_str(), f, qos, retain);
777}
778
779bool MQTTClientComponent::publish(const char *topic, const char *payload, size_t payload_length, uint8_t qos,
780 bool retain) {
781 if (!this->is_connected()) {
782 return false;
783 }
784 size_t topic_len = strlen(topic);
785 bool logging_topic = (topic_len == this->log_message_.topic.size()) &&
786 (memcmp(this->log_message_.topic.c_str(), topic, topic_len) == 0);
787 bool ret = this->mqtt_backend_.publish(topic, payload, payload_length, qos, retain);
788 delay(0);
789 if (!ret && !logging_topic && this->is_connected()) {
790 delay(0);
791 ret = this->mqtt_backend_.publish(topic, payload, payload_length, qos, retain);
792 delay(0);
793 }
794
795 if (!logging_topic) {
796 if (ret) {
797 ESP_LOGV(TAG, "Publish(topic='%s' retain=%d qos=%d)", topic, retain, qos);
798 ESP_LOGVV(TAG, "Publish payload (len=%u): '%.*s'", payload_length, static_cast<int>(payload_length), payload);
799 } else {
800 ESP_LOGV(TAG, "Publish failed for topic='%s' (len=%u). Will retry", topic, payload_length);
801 this->status_momentary_warning(1000);
802 }
803 }
804 return ret != 0;
805}
806
807bool MQTTClientComponent::publish_json(const char *topic, const json::json_build_t &f, uint8_t qos, bool retain) {
808 auto message = json::build_json(f);
809 return this->publish(topic, message.c_str(), message.size(), qos, retain);
810}
811
813 if (this->state_ != MQTT_CLIENT_DISABLED)
814 return;
815 ESP_LOGD(TAG, "Enabling");
817 this->last_connected_ = millis();
818 this->start_dnslookup_();
819}
820
822 if (this->state_ == MQTT_CLIENT_DISABLED)
823 return;
824 ESP_LOGD(TAG, "Disabling");
827}
828
829// Out of line so the topic buffer is off the stack while the matched callback runs
830__attribute__((noinline)) static bool topic_matches(const char *message, const MQTTTopicSource &topic) {
831 char buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
832 return topic_match(message, topic.build(buf).c_str());
833}
834
835void MQTTClientComponent::on_message(const std::string &topic, const std::string &payload) {
836#ifdef USE_ESP8266
837 // IMPORTANT: This defer is REQUIRED to prevent stack overflow crashes on ESP8266.
838 //
839 // On ESP8266, this callback is invoked directly from the lwIP/AsyncTCP network stack
840 // which runs in the "sys" context with a very limited stack (~4KB). By the time we
841 // reach this function, the stack is already partially consumed by the network
842 // processing chain: tcp_input -> AsyncClient::_recv -> AsyncMqttClient::_onMessage -> here.
843 //
844 // MQTT subscription callbacks can trigger arbitrary user actions (automations, HTTP
845 // requests, sensor updates, etc.) which may have deep call stacks of their own.
846 // For example, an HTTP request action requires: DNS lookup -> TCP connect -> TLS
847 // handshake (if HTTPS) -> request formatting. This easily overflows the remaining
848 // system stack space, causing a LoadStoreAlignmentCause exception or silent corruption.
849 //
850 // By deferring to the main loop, we ensure callbacks execute with a fresh, full-size
851 // stack in the normal application context rather than the constrained network task.
852 //
853 // DO NOT REMOVE THIS DEFER without understanding the above. It may appear to work
854 // in simple tests but will cause crashes with complex automations.
855 this->defer([this, topic, payload]() {
856#endif
857#ifdef USE_MQTT_CRASH_LOG
858 this->handle_crash_log_request_(topic, payload);
859#endif
860 // Indexed with the count taken up front: a callback may subscribe, which can reallocate the
861 // vector, and the new entry waits for the next message.
862 // Only the outermost dispatch erases what was unsubscribed meanwhile.
863 const bool outermost = !this->dispatching_;
864 {
865 DispatchGuard dispatching(this->dispatching_);
866 const size_t count = this->subscriptions_.size();
867 for (size_t i = 0; i < count; i++) {
868 const auto &subscription = this->subscriptions_[i];
869 if (!subscription.removed && topic_matches(topic.c_str(), subscription.topic))
870 subscription.callback.call(topic, payload);
871 }
872 }
873 if (outermost && this->removed_while_dispatching_) {
874 this->removed_while_dispatching_ = false;
876 }
877#ifdef USE_ESP8266
878 });
879#endif
880}
881
882// Setters
884bool MQTTClientComponent::is_log_message_enabled() const { return !this->log_message_.topic.empty(); }
886void MQTTClientComponent::set_keep_alive(uint16_t keep_alive_s) { this->mqtt_backend_.set_keep_alive(keep_alive_s); }
887void MQTTClientComponent::set_log_message_template(MQTTMessage &&message) { this->log_message_ = std::move(message); }
888const MQTTDiscoveryInfo &MQTTClientComponent::get_discovery_info() const { return this->discovery_info_; }
889void MQTTClientComponent::set_topic_prefix(std::string topic_prefix) { this->topic_prefix_ = std::move(topic_prefix); }
890const std::string &MQTTClientComponent::get_topic_prefix() const { return this->topic_prefix_; }
892 this->birth_message_.topic = "";
894}
896 this->shutdown_message_.topic = "";
898}
899bool MQTTClientComponent::is_discovery_enabled() const { return !this->discovery_info_.prefix.empty(); }
901const Availability &MQTTClientComponent::get_availability() { return this->availability_; }
903 if (this->birth_message_.topic.empty() || this->birth_message_.topic != this->last_will_.topic) {
904 this->availability_.topic = "";
905 return;
906 }
910}
911
913 this->last_will_ = std::move(message);
915}
916
918 this->birth_message_ = std::move(message);
920}
921
922void MQTTClientComponent::set_shutdown_message(MQTTMessage &&message) { this->shutdown_message_ = std::move(message); }
923
924void MQTTClientComponent::set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
925 MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain,
926 bool discover_ip, bool clean) {
927 this->discovery_info_.prefix = std::move(prefix);
928 this->discovery_info_.discover_ip = discover_ip;
929 this->discovery_info_.unique_id_generator = unique_id_generator;
930 this->discovery_info_.object_id_generator = object_id_generator;
931 this->discovery_info_.retain = retain;
932 this->discovery_info_.clean = clean;
933}
934
936
938 this->discovery_info_ = MQTTDiscoveryInfo{
939 .prefix = "",
940 .retain = false,
941 .discover_ip = false,
942 .clean = false,
943 .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
944 .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
945 };
946}
948 // teardown() disconnects once the broker has confirmed the shutdown message
949 this->shutdown_message_sent_ = !this->shutdown_message_.topic.empty() && this->is_connected() &&
951}
952
954 // A disconnect drops a message the broker has not confirmed; the core's teardown timeout bounds the wait
955 if (this->shutdown_message_sent_ && this->mqtt_backend_.connected() && !this->mqtt_backend_.publish_acknowledged())
956 return false;
958 return true;
959}
960
962 this->mqtt_backend_.set_on_connect(std::forward<mqtt_on_connect_callback_t>(callback));
963}
964
966 auto callback_copy = callback;
967 this->mqtt_backend_.set_on_disconnect(std::forward<mqtt_on_disconnect_callback_t>(callback));
968 this->on_disconnect_.add(std::move(callback_copy));
969}
970
971MQTTClientComponent *global_mqtt_client = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
972
973} // namespace esphome::mqtt
974
975#endif // USE_MQTT
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
uint32_t get_config_hash()
Get the config hash as a 32-bit integer.
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void status_momentary_warning(uint32_t length=5000)
Set warning status flag and clear it after length ms.
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
void status_clear_warning()
Definition component.h:309
constexpr const char * c_str() const
Definition string_ref.h:78
constexpr bool empty() const
Definition string_ref.h:81
uint16_t get_port() const
Definition api_server.h:62
noise::NoiseContext & get_noise_ctx()
Definition api_server.h:92
void add_log_callback(void *instance, void(*fn)(void *, uint8_t, const char *, const char *, size_t))
Register a log callback to receive log messages.
Definition logger.h:203
void set_keep_alive(uint16_t keep_alive) final
void set_on_message(std::function< on_message_callback_t > &&callback) final
const SubackCounter & get_subacks() const
void set_client_id(const char *client_id) final
bool publish_tracked(const MQTTMessage &message) final
void set_on_connect(std::function< on_connect_callback_t > &&callback) final
void set_will(const char *topic, uint8_t qos, bool retain, const char *payload) final
bool subscribe(const char *topic, uint8_t qos) final
void set_server(network::IPAddress ip, uint16_t port) final
bool publish(const char *topic, const char *payload, size_t length, uint8_t qos, bool retain) final
void set_clean_session(bool clean_session) final
bool unsubscribe(const char *topic) final
void set_on_subscribe(std::function< on_subscribe_callback_t > &&callback) final
void set_on_disconnect(std::function< on_disconnect_callback_t > &&callback) final
void set_credentials(const char *username, const char *password) final
void set_birth_message(MQTTMessage &&message)
Set the birth message.
void start_connect_()
Reconnect to the MQTT broker if not already connected.
void setup() override
Setup the MQTT client, registering a bunch of callbacks and attempting to connect.
void disable_discovery()
Globally disable Home Assistant discovery.
void recalculate_availability_()
Re-calculate the availability property.
void subscribe(MQTTTopicSource topic, F &&callback, uint8_t qos=0)
Subscribe to an MQTT topic and call callback when a message is received.
void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator, MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip, bool clean=false)
Set the Home Assistant discovery info.
float get_setup_priority() const override
MQTT client setup priority.
void disable_log_message()
Get the topic used for logging. Defaults to "<topic_prefix>/debug" and the value is cached for speed.
const std::string & get_topic_prefix() const
Get the topic prefix of this device, using default if necessary.
uint16_t subscribes_sent_
SUBSCRIBEs sent on this connection for the subscriptions the fingerprint covers.
void register_mqtt_component(MQTTComponent *component)
bool resubscribe_subscriptions_()
Returns true when every subscription is subscribed.
void set_last_will(MQTTMessage &&message)
Set the last will testament message.
bool publish(const MQTTMessage &message)
Publish a MQTTMessage.
void set_topic_prefix(std::string topic_prefix)
Set the topic prefix that will be prepended to all topics together with "/".
const MQTTDiscoveryInfo & get_discovery_info() const
Get Home Assistant discovery info.
void disable_birth_message()
Remove the birth message.
static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg)
MQTTMessage last_will_
The last will message.
uint32_t session_fingerprint_
Fingerprint of the set the broker session is known to hold in full; 0 while a rebuild is in progress.
void set_shutdown_message(MQTTMessage &&message)
MQTTMessage birth_message_
The birth message (e.g.
std::vector< MQTTComponent * > children_
void add_subscription_(MQTTTopicSource topic, mqtt_subscription_callback_t callback, bool boxed, uint8_t qos)
void set_on_connect(mqtt_on_connect_callback_t &&callback)
void set_session_fingerprint_(uint32_t fingerprint)
optional< MQTTClientDisconnectReason > disconnect_reason_
static MQTTTopicSource copy_topic(StringRef topic)
A heap copy of topic, owned by the one subscription it is passed to and freed when that is erased.
bool subscribe_topic_(const MQTTTopicSource &topic, uint8_t qos)
void unsubscribe(const std::string &topic)
Unsubscribe from an MQTT topic.
void on_message(const std::string &topic, const std::string &payload)
void set_log_message_template(MQTTMessage &&message)
Manually set the topic used for logging.
bool subacks_settled_
Set once every SUBACK of this connection is in (or the session was resumed without subscribing)
void resubscribe_subscription_(MQTTSubscription *sub)
void set_on_disconnect(mqtt_on_disconnect_callback_t &&callback)
bool subscribe_(const char *topic, uint8_t qos)
void check_subacks_()
Once every SUBACK of this connection is in, saves the fingerprint if all were granted.
const Availability & get_availability()
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len)
std::vector< MQTTSubscription > subscriptions_
bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos=0, bool retain=false)
Construct and send a JSON MQTT message.
void disable_last_will()
Remove the last will testament message.
void set_keep_alive(uint16_t keep_alive_s)
Set the keep alive time in seconds, every 0.7*keep_alive a ping will be sent.
void loop() override
Reconnect if required.
MQTTDiscoveryInfo discovery_info_
The discovery info options for Home Assistant.
CallbackManager< MQTTBackend::on_disconnect_callback_t > on_disconnect_
void handle_crash_log_request_(const std::string &topic, const std::string &payload)
Availability availability_
Caches availability.
SubackTally tally(uint16_t sent) const
Compares the SUBACKs received with the number of SUBSCRIBEs sent on this connection.
const Component * component
Definition component.cpp:34
const LogString * message
Definition component.cpp:35
void yield(void)
const char * key
unsigned count
Definition gif.cpp:51
int ret
PROGMEM_STRING_TABLE(AlarmControlPanelStateStrings, "DISARMED", "ARMED_HOME", "ARMED_AWAY", "ARMED_NIGHT", "ARMED_VACATION", "ARMED_CUSTOM_BYPASS", "PENDING", "ARMING", "DISARMING", "TRIGGERED", "UNKNOWN")
ESPHOME_LOG_TAG(TAG, "alarm_control_panel")
APIServer * global_api_server
esphome::climate::Climate __attribute__
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition json_util.h:164
SerializationBuffer build_json(const json_build_t &f)
Build a JSON string with the provided json build function.
Definition json_util.cpp:19
bool crash_log_pending()
Whether a crash record from before this boot is waiting to be reported.
Logger * global_logger
Definition logger.cpp:396
void log_crash_to_client()
Log the previous crash for a client that just subscribed to the logs.
std::function< MQTTBackend::on_disconnect_callback_t > mqtt_on_disconnect_callback_t
Definition mqtt_client.h:56
MQTTDiscoveryObjectIdGenerator
available discovery object_id generators
@ MQTT_NONE_OBJECT_ID_GENERATOR
MQTTTopicSource progmem_topic(ProgmemStr topic)
A topic in flash, copied into the buffer when needed, so at most MQTT_DEFAULT_TOPIC_MAX_LEN - 1 chara...
bool topic_match(const char *message, const char *subscription)
True if the message topic matches the subscription, with + and # wildcards.
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
@ MQTT_LEGACY_UNIQUE_ID_GENERATOR
MQTTTransport
Transport for the broker connection; only the ESP-IDF backend supports WebSocket.
Callback< void(const std::string &, const std::string &)> mqtt_subscription_callback_t
Stored callback of an MQTT subscription: the topic, then the payload.
Definition mqtt_client.h:59
MQTTClientComponent * global_mqtt_client
@ MQTT_CLIENT_RESOLVING_ADDRESS
MQTTTopicSource static_topic(const char *topic)
A topic string that outlives the subscription, such as a literal; it is referenced,...
uint32_t add_subscription_fingerprint(uint32_t fingerprint, const char *topic, uint8_t qos)
Adds one subscription to a fingerprint of a set of subscriptions; the order they are added in does no...
std::function< MQTTBackend::on_connect_callback_t > mqtt_on_connect_callback_t
Callback for MQTT events.
Definition mqtt_client.h:55
constexpr bool session_has_subscriptions(bool session_present, uint32_t trusted, uint32_t current)
True when a resumed session holds in full the subscriptions it is trusted with, and they are the curr...
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
network::IPAddresses get_ip_addresses()
Definition util.cpp:98
bool is_disabled()
Return whether the network is disabled: every configured interface with a disable() lifecycle (modem,...
Definition util.cpp:42
constexpr float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.h:55
size_t buf_append_str_p(char *buf, size_t size, size_t pos, PGM_P str)
Safely append a PROGMEM string to buffer, returning new position (capped at size).
Definition helpers.h:1359
size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Format name + separator + suffix directly into buffer without heap allocation.
Definition helpers.cpp:277
const void size_t len
Definition hal.h:68
bool rtc_pref_decode(const uint32_t *buffer, uint32_t type, uint8_t length_words, uint8_t *data, size_t len)
Verify the checksum of a record held in buffer (length_words data words + 1 checksum word) and,...
ESPPreferences * global_preferences
void rtc_pref_encode(uint32_t *buffer, uint32_t type, uint8_t length_words, const uint8_t *data, size_t len)
Encode len data bytes into buffer (length_words data words + 1 trailing checksum word).
void get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Definition helpers.cpp:848
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:1018
const __FlashStringHelper * ProgmemStr
Definition progmem.h:31
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
std::string topic
Empty means disabled.
std::string address
The address of the server without port number.
Definition mqtt_client.h:99
bool clean_session
Whether the session will be cleaned or remembered between connects.
std::string client_id
The client ID. Will automatically be truncated to 23 characters.
MQTTDiscoveryUniqueIdGenerator unique_id_generator
bool discover_ip
Enable the Home Assistant device discovery.
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
MQTTDiscoveryObjectIdGenerator object_id_generator
bool retain
Whether to retain discovery messages.
char * str_to(char *buf) const
Definition ip_address.h:152
SemaphoreHandle_t lock