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