ESPHome 2026.3.0
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
20#ifdef USE_API
22#endif
23#ifdef USE_DASHBOARD_IMPORT
25#endif
26
27namespace esphome::mqtt {
28
29static const char *const TAG = "mqtt";
30
31// Disconnect reason strings indexed by MQTTClientDisconnectReason enum (0-8)
32PROGMEM_STRING_TABLE(MQTTDisconnectReasonStrings, "TCP disconnected", "Unacceptable Protocol Version",
33 "Identifier Rejected", "Server Unavailable", "Malformed Credentials", "Not Authorized",
34 "Not Enough Space", "TLS Bad Fingerprint", "DNS Resolve Error", "Unknown");
35
37 global_mqtt_client = this;
38 char mac_addr[MAC_ADDRESS_BUFFER_SIZE];
40 this->credentials_.client_id = make_name_with_suffix(App.get_name(), '-', mac_addr, MAC_ADDRESS_BUFFER_SIZE - 1);
41}
42
43// Connection
46 [this](const char *topic, const char *payload, size_t len, size_t index, size_t total) {
47 if (index == 0) {
48 this->payload_buffer_.clear();
49 this->payload_buffer_.reserve(total);
50 }
51
52 // append new payload, may contain incomplete MQTT message
53 this->payload_buffer_.append(payload, len);
54
55 // MQTT fully received
56 if (len + index == total) {
57 this->on_message(topic, this->payload_buffer_);
58 this->payload_buffer_.clear();
59 }
60 });
62 if (this->state_ == MQTT_CLIENT_DISABLED)
63 return;
65 this->disconnect_reason_ = reason;
66 });
67#ifdef USE_LOGGER
68 if (this->is_log_message_enabled() && logger::global_logger != nullptr) {
70 this, [](void *self, uint8_t level, const char *tag, const char *message, size_t message_len) {
71 static_cast<MQTTClientComponent *>(self)->on_log(level, tag, message, message_len);
72 });
73 }
74#endif
75
76 if (this->is_discovery_ip_enabled()) {
77 this->subscribe(
78 "esphome/discover", [this](const std::string &topic, const std::string &payload) { this->send_device_info_(); },
79 2);
80
81 // Format topic on stack - subscribe() copies it
82 // "esphome/ping/" (13) + name (ESPHOME_DEVICE_NAME_MAX_LEN) + null (1)
83 constexpr size_t ping_topic_buffer_size = 13 + ESPHOME_DEVICE_NAME_MAX_LEN + 1;
84 char ping_topic[ping_topic_buffer_size];
85 buf_append_printf(ping_topic, sizeof(ping_topic), 0, "esphome/ping/%s", App.get_name().c_str());
86 this->subscribe(
87 ping_topic, [this](const std::string &topic, const std::string &payload) { this->send_device_info_(); }, 2);
88 }
89
90 if (this->enable_on_boot_) {
91 this->enable();
92 }
93}
94
96 if (!this->is_connected() or !this->is_discovery_ip_enabled()) {
97 return;
98 }
99 // Format topic on stack to avoid heap allocation
100 // "esphome/discover/" (17) + name (ESPHOME_DEVICE_NAME_MAX_LEN) + null (1)
101 constexpr size_t topic_buffer_size = 17 + ESPHOME_DEVICE_NAME_MAX_LEN + 1;
102 char topic[topic_buffer_size];
103 buf_append_printf(topic, sizeof(topic), 0, "esphome/discover/%s", App.get_name().c_str());
104
105 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
106 this->publish_json(
107 topic,
108 [](JsonObject root) {
109 uint8_t index = 0;
110 for (auto &ip : network::get_ip_addresses()) {
111 if (ip.is_set()) {
112 char key[8]; // "ip" + up to 3 digits + null
113 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
114 if (index == 0) {
115 key[0] = 'i';
116 key[1] = 'p';
117 key[2] = '\0';
118 } else {
119 buf_append_printf(key, sizeof(key), 0, "ip%u", index);
120 }
121 ip.str_to(ip_buf);
122 root[key] = ip_buf;
123 index++;
124 }
125 }
126 root[ESPHOME_F("name")] = App.get_name();
127 if (!App.get_friendly_name().empty()) {
128 root[ESPHOME_F("friendly_name")] = App.get_friendly_name();
129 }
130#ifdef USE_API
131 root[ESPHOME_F("port")] = api::global_api_server->get_port();
132#endif
133 root[ESPHOME_F("version")] = ESPHOME_VERSION;
134 char mac_buf[MAC_ADDRESS_BUFFER_SIZE];
136 root[ESPHOME_F("mac")] = mac_buf;
137
138#ifdef USE_ESP8266
139 root[ESPHOME_F("platform")] = ESPHOME_F("ESP8266");
140#endif
141#ifdef USE_ESP32
142 root[ESPHOME_F("platform")] = ESPHOME_F("ESP32");
143#endif
144#ifdef USE_LIBRETINY
145 root[ESPHOME_F("platform")] = lt_cpu_get_model_name();
146#endif
147
148 root[ESPHOME_F("board")] = ESPHOME_BOARD;
149#if defined(USE_WIFI)
150 root[ESPHOME_F("network")] = ESPHOME_F("wifi");
151#elif defined(USE_ETHERNET)
152 root[ESPHOME_F("network")] = ESPHOME_F("ethernet");
153#endif
154
155#ifdef ESPHOME_PROJECT_NAME
156 root[ESPHOME_F("project_name")] = ESPHOME_PROJECT_NAME;
157 root[ESPHOME_F("project_version")] = ESPHOME_PROJECT_VERSION;
158#endif // ESPHOME_PROJECT_NAME
159
160#ifdef USE_DASHBOARD_IMPORT
161 root[ESPHOME_F("package_import_url")] = dashboard_import::get_package_import_url();
162#endif
163
164#ifdef USE_API_NOISE
165 root[api::global_api_server->get_noise_ctx().has_psk() ? ESPHOME_F("api_encryption")
166 : ESPHOME_F("api_encryption_supported")] =
167 ESPHOME_F("Noise_NNpsk0_25519_ChaChaPoly_SHA256");
168#endif
169 },
170 2, this->discovery_info_.retain);
171 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
172}
173
174#ifdef USE_LOGGER
175void MQTTClientComponent::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) {
176 (void) tag;
177 if (level <= this->log_level_ && this->is_connected()) {
178 this->publish(this->log_message_.topic.c_str(), message, message_len, this->log_message_.qos,
179 this->log_message_.retain);
180 }
181}
182#endif
183
185 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
186 // clang-format off
187 ESP_LOGCONFIG(TAG,
188 "MQTT:\n"
189 " Server Address: %s:%u (%s)\n"
190 " Username: " LOG_SECRET("'%s'") "\n"
191 " Client ID: " LOG_SECRET("'%s'") "\n"
192 " Clean Session: %s",
193 this->credentials_.address.c_str(), this->credentials_.port, this->ip_.str_to(ip_buf),
194 this->credentials_.username.c_str(), this->credentials_.client_id.c_str(),
195 YESNO(this->credentials_.clean_session));
196 // clang-format on
197 if (this->is_discovery_ip_enabled()) {
198 ESP_LOGCONFIG(TAG, " Discovery IP enabled");
199 }
200 if (!this->discovery_info_.prefix.empty()) {
201 ESP_LOGCONFIG(TAG,
202 " Discovery prefix: '%s'\n"
203 " Discovery retain: %s",
204 this->discovery_info_.prefix.c_str(), YESNO(this->discovery_info_.retain));
205 }
206 ESP_LOGCONFIG(TAG, " Topic Prefix: '%s'", this->topic_prefix_.c_str());
207 if (!this->log_message_.topic.empty()) {
208 ESP_LOGCONFIG(TAG, " Log Topic: '%s'", this->log_message_.topic.c_str());
209 }
210 if (!this->availability_.topic.empty()) {
211 ESP_LOGCONFIG(TAG, " Availability: '%s'", this->availability_.topic.c_str());
212 }
213}
215 return network::is_disabled() || this->state_ == MQTT_CLIENT_DISABLED || this->is_connected() ||
217}
218
220 for (auto &subscription : this->subscriptions_) {
221 subscription.subscribed = false;
222 subscription.resubscribe_timeout = 0;
223 }
224
225 this->status_set_warning();
226 this->dns_resolve_error_ = false;
227 this->dns_resolved_ = false;
228 ip_addr_t addr;
229 err_t err;
230 {
231 LwIPLock lock;
232#if USE_NETWORK_IPV6
233 err = dns_gethostbyname_addrtype(this->credentials_.address.c_str(), &addr, MQTTClientComponent::dns_found_callback,
234 this, LWIP_DNS_ADDRTYPE_IPV6_IPV4);
235#else
236 err = dns_gethostbyname_addrtype(this->credentials_.address.c_str(), &addr, MQTTClientComponent::dns_found_callback,
237 this, LWIP_DNS_ADDRTYPE_IPV4);
238#endif /* USE_NETWORK_IPV6 */
239 }
240 switch (err) {
241 case ERR_OK: {
242 // Got IP immediately
243 this->dns_resolved_ = true;
244 this->ip_ = network::IPAddress(&addr);
245 this->start_connect_();
246 return;
247 }
248 case ERR_INPROGRESS: {
249 // wait for callback
250 ESP_LOGD(TAG, "Resolving broker IP address");
251 break;
252 }
253 default:
254 case ERR_ARG: {
255 // error
256 ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
257 break;
258 }
259 }
260
262 this->connect_begin_ = millis();
263}
265 if (!this->dns_resolved_ && millis() - this->connect_begin_ > 20000) {
266 this->dns_resolve_error_ = true;
267 }
268
269 if (this->dns_resolve_error_) {
270 ESP_LOGW(TAG, "Couldn't resolve IP address for '%s'", this->credentials_.address.c_str());
274 return;
275 }
276
277 if (!this->dns_resolved_) {
278 return;
279 }
280
281 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
282 ESP_LOGD(TAG, "Resolved broker IP address to %s", this->ip_.str_to(ip_buf));
283 this->start_connect_();
284}
285#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
286void MQTTClientComponent::dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg) {
287#else
288void MQTTClientComponent::dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg) {
289#endif
290 auto *a_this = (MQTTClientComponent *) callback_arg;
291 if (ipaddr == nullptr) {
292 a_this->dns_resolve_error_ = true;
293 } else {
294 a_this->ip_ = network::IPAddress(ipaddr);
295 a_this->dns_resolved_ = true;
296 }
297}
298
301 return;
302
303 ESP_LOGI(TAG, "Connecting");
304 // Force disconnect first
306
309 const char *username = nullptr;
310 if (!this->credentials_.username.empty())
311 username = this->credentials_.username.c_str();
312 const char *password = nullptr;
313 if (!this->credentials_.password.empty())
314 password = this->credentials_.password.c_str();
315
316 this->mqtt_backend_.set_credentials(username, password);
317
318 this->mqtt_backend_.set_server(this->credentials_.address.c_str(), this->credentials_.port);
319 if (!this->last_will_.topic.empty()) {
320 this->mqtt_backend_.set_will(this->last_will_.topic.c_str(), this->last_will_.qos, this->last_will_.retain,
321 this->last_will_.payload.c_str());
322 }
323
324 this->mqtt_backend_.connect();
326 this->connect_begin_ = millis();
327}
329 return this->state_ == MQTT_CLIENT_CONNECTED && this->mqtt_backend_.connected();
330}
331
333 if (!this->mqtt_backend_.connected()) {
334 if (millis() - this->connect_begin_ > 60000) {
336 this->start_dnslookup_();
337 }
338 return;
339 }
340
342 this->sent_birth_message_ = false;
343 this->status_clear_warning();
344 ESP_LOGI(TAG, "Connected");
345 // MQTT Client needs some time to be fully set up.
346 delay(100); // NOLINT
347
349 this->send_device_info_();
350
351 for (MQTTComponent *component : this->children_)
352 component->schedule_resend_state();
353}
354
356 // Call the backend loop first
358
359 if (this->disconnect_reason_.has_value()) {
360 const LogString *reason_s = MQTTDisconnectReasonStrings::get_log_str(
361 static_cast<uint8_t>(*this->disconnect_reason_), MQTTDisconnectReasonStrings::LAST_INDEX);
362 if (!network::is_connected()) {
363 reason_s = LOG_STR("WiFi disconnected");
364 }
365 ESP_LOGW(TAG, "Disconnected: %s", LOG_STR_ARG(reason_s));
366 this->disconnect_reason_.reset();
367 }
368
370
371 switch (this->state_) {
373 return; // Return to avoid a reboot when disabled
375 if (now - this->connect_begin_ > 5000) {
376 this->start_dnslookup_();
377 }
378 break;
380 this->check_dnslookup_();
381 break;
383 this->check_connected();
384 break;
386 if (!this->mqtt_backend_.connected()) {
388 ESP_LOGW(TAG, "Lost client connection");
389 this->start_dnslookup_();
390 } else {
391 if (!this->birth_message_.topic.empty() && !this->sent_birth_message_) {
392 this->sent_birth_message_ = this->publish(this->birth_message_);
393 }
394
395 this->last_connected_ = now;
397
398 // Process pending resends for all MQTT components centrally
399 // This is more efficient than each component polling in its own loop
400 for (MQTTComponent *component : this->children_) {
401 component->process_resend();
402 }
403 }
404 break;
405 }
406
407 if (millis() - this->last_connected_ > this->reboot_timeout_ && this->reboot_timeout_ != 0) {
408 ESP_LOGE(TAG, "Can't connect; restarting");
409 App.reboot();
410 }
411}
413
414// Subscribe
415bool MQTTClientComponent::subscribe_(const char *topic, uint8_t qos) {
416 if (!this->is_connected())
417 return false;
418
419 bool ret = this->mqtt_backend_.subscribe(topic, qos);
420 yield();
421
422 if (ret) {
423 ESP_LOGV(TAG, "subscribe(topic='%s')", topic);
424 } else {
425 delay(5);
426 ESP_LOGV(TAG, "Subscribe failed for topic='%s'. Will retry", topic);
427 this->status_momentary_warning("subscribe", 1000);
428 }
429 return ret != 0;
430}
431void MQTTClientComponent::resubscribe_subscription_(MQTTSubscription *sub) {
432 if (sub->subscribed)
433 return;
434
435 const uint32_t now = millis();
436 bool do_resub = sub->resubscribe_timeout == 0 || now - sub->resubscribe_timeout > 1000;
437
438 if (do_resub) {
439 sub->subscribed = this->subscribe_(sub->topic.c_str(), sub->qos);
440 sub->resubscribe_timeout = now;
441 }
442}
444 for (auto &subscription : this->subscriptions_) {
445 this->resubscribe_subscription_(&subscription);
446 }
447}
448
449void MQTTClientComponent::subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos) {
450 MQTTSubscription subscription{
451 .topic = topic,
452 .qos = qos,
453 .callback = std::move(callback),
454 .subscribed = false,
455 .resubscribe_timeout = 0,
456 };
457 this->resubscribe_subscription_(&subscription);
458 this->subscriptions_.push_back(subscription);
459}
460
461void MQTTClientComponent::subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos) {
462 auto f = [callback](const std::string &topic, const std::string &payload) {
463 json::parse_json(payload, [topic, callback](JsonObject root) -> bool {
464 callback(topic, root);
465 return true;
466 });
467 };
468 MQTTSubscription subscription{
469 .topic = topic,
470 .qos = qos,
471 .callback = f,
472 .subscribed = false,
473 .resubscribe_timeout = 0,
474 };
475 this->resubscribe_subscription_(&subscription);
476 this->subscriptions_.push_back(subscription);
477}
478
479void MQTTClientComponent::unsubscribe(const std::string &topic) {
480 bool ret = this->mqtt_backend_.unsubscribe(topic.c_str());
481 yield();
482 if (ret) {
483 ESP_LOGV(TAG, "unsubscribe(topic='%s')", topic.c_str());
484 } else {
485 delay(5);
486 ESP_LOGV(TAG, "Unsubscribe failed for topic='%s'.", topic.c_str());
487 this->status_momentary_warning("unsubscribe", 1000);
488 }
489
490 auto it = subscriptions_.begin();
491 while (it != subscriptions_.end()) {
492 if (it->topic == topic) {
493 it = subscriptions_.erase(it);
494 } else {
495 ++it;
496 }
497 }
498}
499
500// Publish
501bool MQTTClientComponent::publish(const std::string &topic, const std::string &payload, uint8_t qos, bool retain) {
502 return this->publish(topic, payload.data(), payload.size(), qos, retain);
503}
504
505bool MQTTClientComponent::publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos,
506 bool retain) {
507 return this->publish(topic.c_str(), payload, payload_length, qos, retain);
508}
509
510bool MQTTClientComponent::publish(const MQTTMessage &message) {
511 return this->publish(message.topic.c_str(), message.payload.c_str(), message.payload.length(), message.qos,
512 message.retain);
513}
514bool MQTTClientComponent::publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos,
515 bool retain) {
516 return this->publish_json(topic.c_str(), f, qos, retain);
517}
518
519bool MQTTClientComponent::publish(const char *topic, const char *payload, size_t payload_length, uint8_t qos,
520 bool retain) {
521 if (!this->is_connected()) {
522 return false;
523 }
524 size_t topic_len = strlen(topic);
525 bool logging_topic = (topic_len == this->log_message_.topic.size()) &&
526 (memcmp(this->log_message_.topic.c_str(), topic, topic_len) == 0);
527 bool ret = this->mqtt_backend_.publish(topic, payload, payload_length, qos, retain);
528 delay(0);
529 if (!ret && !logging_topic && this->is_connected()) {
530 delay(0);
531 ret = this->mqtt_backend_.publish(topic, payload, payload_length, qos, retain);
532 delay(0);
533 }
534
535 if (!logging_topic) {
536 if (ret) {
537 ESP_LOGV(TAG, "Publish(topic='%s' retain=%d qos=%d)", topic, retain, qos);
538 ESP_LOGVV(TAG, "Publish payload (len=%u): '%.*s'", payload_length, static_cast<int>(payload_length), payload);
539 } else {
540 ESP_LOGV(TAG, "Publish failed for topic='%s' (len=%u). Will retry", topic, payload_length);
541 this->status_momentary_warning("publish", 1000);
542 }
543 }
544 return ret != 0;
545}
546
547bool MQTTClientComponent::publish_json(const char *topic, const json::json_build_t &f, uint8_t qos, bool retain) {
548 auto message = json::build_json(f);
549 return this->publish(topic, message.c_str(), message.size(), qos, retain);
550}
551
553 if (this->state_ != MQTT_CLIENT_DISABLED)
554 return;
555 ESP_LOGD(TAG, "Enabling");
557 this->last_connected_ = millis();
558 this->start_dnslookup_();
559}
560
562 if (this->state_ == MQTT_CLIENT_DISABLED)
563 return;
564 ESP_LOGD(TAG, "Disabling");
566 this->on_shutdown();
567}
568
580static bool topic_match(const char *message, const char *subscription, bool is_normal, bool past_separator) {
581 // Reached end of both strings at the same time, this means we have a successful match
582 if (*message == '\0' && *subscription == '\0')
583 return true;
584
585 // Either the message or the subscribe are at the end. This means they don't match.
586 if (*message == '\0' || *subscription == '\0')
587 return false;
588
589 bool do_wildcards = is_normal || past_separator;
590
591 if (*subscription == '+' && do_wildcards) {
592 // single level wildcard
593 // consume + from subscription
594 subscription++;
595 // consume everything from message until '/' found or end of string
596 while (*message != '\0' && *message != '/') {
597 message++;
598 }
599 // after this, both pointers will point to a '/' or to the end of the string
600
601 return topic_match(message, subscription, is_normal, true);
602 }
603
604 if (*subscription == '#' && do_wildcards) {
605 // multilevel wildcard - MQTT mandates that this must be at end of subscribe topic
606 return true;
607 }
608
609 // this handles '/' and normal characters at the same time.
610 if (*message != *subscription)
611 return false;
612
613 past_separator = past_separator || *subscription == '/';
614
615 // consume characters
616 subscription++;
617 message++;
618
619 return topic_match(message, subscription, is_normal, past_separator);
620}
621
622static bool topic_match(const char *message, const char *subscription) {
623 return topic_match(message, subscription, *message != '\0' && *message != '$', false);
624}
625
626void MQTTClientComponent::on_message(const std::string &topic, const std::string &payload) {
627#ifdef USE_ESP8266
628 // IMPORTANT: This defer is REQUIRED to prevent stack overflow crashes on ESP8266.
629 //
630 // On ESP8266, this callback is invoked directly from the lwIP/AsyncTCP network stack
631 // which runs in the "sys" context with a very limited stack (~4KB). By the time we
632 // reach this function, the stack is already partially consumed by the network
633 // processing chain: tcp_input -> AsyncClient::_recv -> AsyncMqttClient::_onMessage -> here.
634 //
635 // MQTT subscription callbacks can trigger arbitrary user actions (automations, HTTP
636 // requests, sensor updates, etc.) which may have deep call stacks of their own.
637 // For example, an HTTP request action requires: DNS lookup -> TCP connect -> TLS
638 // handshake (if HTTPS) -> request formatting. This easily overflows the remaining
639 // system stack space, causing a LoadStoreAlignmentCause exception or silent corruption.
640 //
641 // By deferring to the main loop, we ensure callbacks execute with a fresh, full-size
642 // stack in the normal application context rather than the constrained network task.
643 //
644 // DO NOT REMOVE THIS DEFER without understanding the above. It may appear to work
645 // in simple tests but will cause crashes with complex automations.
646 this->defer([this, topic, payload]() {
647#endif
648 for (auto &subscription : this->subscriptions_) {
649 if (topic_match(topic.c_str(), subscription.topic.c_str()))
650 subscription.callback(topic, payload);
651 }
652#ifdef USE_ESP8266
653 });
654#endif
655}
656
657// Setters
659bool MQTTClientComponent::is_log_message_enabled() const { return !this->log_message_.topic.empty(); }
660void MQTTClientComponent::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
661void MQTTClientComponent::register_mqtt_component(MQTTComponent *component) { this->children_.push_back(component); }
662void MQTTClientComponent::set_log_level(int level) { this->log_level_ = level; }
663void MQTTClientComponent::set_keep_alive(uint16_t keep_alive_s) { this->mqtt_backend_.set_keep_alive(keep_alive_s); }
664void MQTTClientComponent::set_log_message_template(MQTTMessage &&message) { this->log_message_ = std::move(message); }
665const MQTTDiscoveryInfo &MQTTClientComponent::get_discovery_info() const { return this->discovery_info_; }
666void MQTTClientComponent::set_topic_prefix(const std::string &topic_prefix, const std::string &check_topic_prefix) {
667 if (App.is_name_add_mac_suffix_enabled() && (topic_prefix == check_topic_prefix)) {
668 char buf[ESPHOME_DEVICE_NAME_MAX_LEN + 1];
670 } else {
671 this->topic_prefix_ = topic_prefix;
672 }
673}
674const std::string &MQTTClientComponent::get_topic_prefix() const { return this->topic_prefix_; }
675void MQTTClientComponent::set_publish_nan_as_none(bool publish_nan_as_none) {
676 this->publish_nan_as_none_ = publish_nan_as_none;
677}
680 this->birth_message_.topic = "";
682}
684 this->shutdown_message_.topic = "";
686}
687bool MQTTClientComponent::is_discovery_enabled() const { return !this->discovery_info_.prefix.empty(); }
689const Availability &MQTTClientComponent::get_availability() { return this->availability_; }
691 if (this->birth_message_.topic.empty() || this->birth_message_.topic != this->last_will_.topic) {
692 this->availability_.topic = "";
693 return;
694 }
698}
699
701 this->last_will_ = std::move(message);
703}
704
706 this->birth_message_ = std::move(message);
708}
709
710void MQTTClientComponent::set_shutdown_message(MQTTMessage &&message) { this->shutdown_message_ = std::move(message); }
711
712void MQTTClientComponent::set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
713 MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain,
714 bool discover_ip, bool clean) {
715 this->discovery_info_.prefix = std::move(prefix);
716 this->discovery_info_.discover_ip = discover_ip;
717 this->discovery_info_.unique_id_generator = unique_id_generator;
718 this->discovery_info_.object_id_generator = object_id_generator;
719 this->discovery_info_.retain = retain;
720 this->discovery_info_.clean = clean;
721}
722
724
726 this->discovery_info_ = MQTTDiscoveryInfo{
727 .prefix = "",
728 .retain = false,
729 .discover_ip = false,
730 .clean = false,
731 .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
732 .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
733 };
734}
736 if (!this->shutdown_message_.topic.empty()) {
737 yield();
738 this->publish(this->shutdown_message_);
739 yield();
740 }
742}
743
745 this->mqtt_backend_.set_on_connect(std::forward<mqtt_on_connect_callback_t>(callback));
746}
747
749 auto callback_copy = callback;
750 this->mqtt_backend_.set_on_disconnect(std::forward<mqtt_on_disconnect_callback_t>(callback));
751 this->on_disconnect_.add(std::move(callback_copy));
752}
753
754MQTTClientComponent *global_mqtt_client = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
755
756// MQTTMessageTrigger
757MQTTMessageTrigger::MQTTMessageTrigger(std::string topic) : topic_(std::move(topic)) {}
758void MQTTMessageTrigger::set_qos(uint8_t qos) { this->qos_ = qos; }
759void MQTTMessageTrigger::set_payload(const std::string &payload) { this->payload_ = payload; }
760void MQTTMessageTrigger::setup() {
762 this->topic_,
763 [this](const std::string &topic, const std::string &payload) {
764 if (this->payload_.has_value() && payload != *this->payload_) {
765 return;
766 }
767
768 this->trigger(payload);
769 },
770 this->qos_);
771}
772void MQTTMessageTrigger::dump_config() {
773 ESP_LOGCONFIG(TAG,
774 "MQTT Message Trigger:\n"
775 " Topic: '%s'\n"
776 " QoS: %u",
777 this->topic_.c_str(), this->qos_);
778}
779float MQTTMessageTrigger::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
780
781} // namespace esphome::mqtt
782
783#endif // USE_MQTT
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
bool is_name_add_mac_suffix_enabled() const
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.
ESPDEPRECATED("Use const char* overload instead. Removed in 2026.7.0", "2026.1.0") void defer(const std voi defer)(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call.
Definition component.h:501
void status_set_warning(const char *message=nullptr)
void status_momentary_warning(const char *name, uint32_t length=5000)
Set warning status flag and automatically clear it after a timeout.
ESPDEPRECATED("set_retry is deprecated and will be removed in 2026.8.0. Use set_timeout or set_interval instead.", "2026.2.0") void set_retry(const std uint32_t uint8_t std::function< RetryResult(uint8_t)> && f
Definition component.h:395
void status_clear_warning()
Definition component.h:254
constexpr const char * c_str() const
Definition string_ref.h:73
constexpr bool empty() const
Definition string_ref.h:76
APINoiseContext & get_noise_ctx()
Definition api_server.h:75
uint16_t get_port() const
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:190
void set_keep_alive(uint16_t keep_alive) final
void set_on_message(std::function< on_message_callback_t > &&callback) final
void set_client_id(const char *client_id) 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_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 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.
void set_reboot_timeout(uint32_t reboot_timeout)
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.
void subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos=0)
Subscribe to a MQTT topic and automatically parse JSON payload.
void register_mqtt_component(MQTTComponent *component)
void set_last_will(MQTTMessage &&message)
Set the last will testament message.
bool publish(const MQTTMessage &message)
Publish a MQTTMessage.
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)
void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos=0)
Subscribe to an MQTT topic and call callback when a message is received.
MQTTMessage last_will_
The last will message.
void set_topic_prefix(const std::string &topic_prefix, const std::string &check_topic_prefix)
Set the topic prefix that will be prepended to all topics together with "/".
void set_shutdown_message(MQTTMessage &&message)
MQTTMessage birth_message_
The birth message (e.g.
std::vector< MQTTComponent * > children_
void set_on_connect(mqtt_on_connect_callback_t &&callback)
optional< MQTTClientDisconnectReason > disconnect_reason_
void unsubscribe(const std::string &topic)
Unsubscribe from an MQTT topic.
void set_publish_nan_as_none(bool publish_nan_as_none)
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.
void resubscribe_subscription_(MQTTSubscription *sub)
void set_on_disconnect(mqtt_on_disconnect_callback_t &&callback)
bool subscribe_(const char *topic, uint8_t qos)
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_
Availability availability_
Caches availability.
MQTTMessageTrigger(std::string topic)
const Component * component
Definition component.cpp:37
const char * message
Definition component.cpp:38
in_addr ip_addr_t
Definition ip_address.h:22
PROGMEM_STRING_TABLE(AlarmControlPanelStateStrings, "DISARMED", "ARMED_HOME", "ARMED_AWAY", "ARMED_NIGHT", "ARMED_VACATION", "ARMED_CUSTOM_BYPASS", "PENDING", "ARMING", "DISARMING", "TRIGGERED", "UNKNOWN")
APIServer * global_api_server
const char * get_package_import_url()
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition json_util.h:151
bool parse_json(const std::string &data, const json_parse_t &f)
Parse a JSON string and run the provided json parse function if it's valid.
Definition json_util.cpp:27
SerializationBuffer build_json(const json_build_t &f)
Build a JSON string with the provided json build function.
Definition json_util.cpp:18
Logger * global_logger
Definition logger.cpp:278
std::function< MQTTBackend::on_disconnect_callback_t > mqtt_on_disconnect_callback_t
Definition mqtt_client.h:32
MQTTDiscoveryObjectIdGenerator
available discovery object_id generators
Definition mqtt_client.h:74
@ MQTT_NONE_OBJECT_ID_GENERATOR
Definition mqtt_client.h:75
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
Definition mqtt_client.h:68
@ MQTT_LEGACY_UNIQUE_ID_GENERATOR
Definition mqtt_client.h:69
std::function< void(const std::string &, JsonObject)> mqtt_json_callback_t
Definition mqtt_client.h:39
std::function< void(const std::string &, const std::string &)> mqtt_callback_t
Callback for MQTT subscriptions.
Definition mqtt_client.h:38
MQTTClientComponent * global_mqtt_client
@ MQTT_CLIENT_DISCONNECTED
Definition mqtt_client.h:94
@ MQTT_CLIENT_RESOLVING_ADDRESS
Definition mqtt_client.h:95
std::function< MQTTBackend::on_connect_callback_t > mqtt_on_connect_callback_t
Callback for MQTT events.
Definition mqtt_client.h:31
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:27
network::IPAddresses get_ip_addresses()
Definition util.cpp:23
bool is_disabled()
Return whether the network is disabled (only wifi for now)
Definition util.cpp:10
constexpr float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.h:41
const char *const TAG
Definition spi.cpp:7
const char * tag
Definition log.h:74
std::string size_t len
Definition helpers.h:892
void HOT yield()
Definition core.cpp:25
char * str_sanitize_to(char *buffer, size_t buffer_size, const char *str)
Sanitize a string to buffer, keeping only alphanumerics, dashes, and underscores.
Definition helpers.cpp:210
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:811
void HOT delay(uint32_t ms)
Definition core.cpp:28
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:26
Application App
Global storage of Application pointer - only one Application can exist.
std::string make_name_with_suffix(const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Optimized string concatenation: name + separator + suffix (const char* overload) Uses a fixed stack b...
Definition helpers.cpp:281
std::string payload_not_available
Definition mqtt_client.h:64
std::string topic
Empty means disabled.
Definition mqtt_client.h:62
std::string address
The address of the server without port number.
Definition mqtt_client.h:52
bool clean_session
Whether the session will be cleaned or remembered between connects.
Definition mqtt_client.h:57
std::string client_id
The client ID. Will automatically be truncated to 23 characters.
Definition mqtt_client.h:56
MQTTDiscoveryUniqueIdGenerator unique_id_generator
Definition mqtt_client.h:88
bool discover_ip
Enable the Home Assistant device discovery.
Definition mqtt_client.h:86
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
Definition mqtt_client.h:84
MQTTDiscoveryObjectIdGenerator object_id_generator
Definition mqtt_client.h:89
bool retain
Whether to retain discovery messages.
Definition mqtt_client.h:85