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