ESPHome 2025.9.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>
9#include "esphome/core/log.h"
11#ifdef USE_LOGGER
13#endif
14#include "lwip/dns.h"
15#include "lwip/err.h"
16#include "mqtt_component.h"
17
18#ifdef USE_API
20#endif
21#ifdef USE_DASHBOARD_IMPORT
23#endif
24
25namespace esphome {
26namespace mqtt {
27
28static const char *const TAG = "mqtt";
29
31 global_mqtt_client = this;
33}
34
35// Connection
38 [this](const char *topic, const char *payload, size_t len, size_t index, size_t total) {
39 if (index == 0)
40 this->payload_buffer_.reserve(total);
41
42 // append new payload, may contain incomplete MQTT message
43 this->payload_buffer_.append(payload, len);
44
45 // MQTT fully received
46 if (len + index == total) {
47 this->on_message(topic, this->payload_buffer_);
48 this->payload_buffer_.clear();
49 }
50 });
52 if (this->state_ == MQTT_CLIENT_DISABLED)
53 return;
55 this->disconnect_reason_ = reason;
56 });
57#ifdef USE_LOGGER
58 if (this->is_log_message_enabled() && logger::global_logger != nullptr) {
60 [this](int level, const char *tag, const char *message, size_t message_len) {
61 if (level <= this->log_level_ && this->is_connected()) {
62 this->publish({.topic = this->log_message_.topic,
63 .payload = std::string(message, message_len),
64 .qos = this->log_message_.qos,
65 .retain = this->log_message_.retain});
66 }
67 });
68 }
69#endif
70
71 if (this->is_discovery_ip_enabled()) {
72 this->subscribe(
73 "esphome/discover", [this](const std::string &topic, const std::string &payload) { this->send_device_info_(); },
74 2);
75
76 std::string topic = "esphome/ping/";
77 topic.append(App.get_name());
78 this->subscribe(
79 topic, [this](const std::string &topic, const std::string &payload) { this->send_device_info_(); }, 2);
80 }
81
82 if (this->enable_on_boot_) {
83 this->enable();
84 }
85}
86
88 if (!this->is_connected() or !this->is_discovery_ip_enabled()) {
89 return;
90 }
91 std::string topic = "esphome/discover/";
92 topic.append(App.get_name());
93
94 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
95 this->publish_json(
96 topic,
97 [](JsonObject root) {
98 uint8_t index = 0;
99 for (auto &ip : network::get_ip_addresses()) {
100 if (ip.is_set()) {
101 root["ip" + (index == 0 ? "" : esphome::to_string(index))] = ip.str();
102 index++;
103 }
104 }
105 root["name"] = App.get_name();
106 if (!App.get_friendly_name().empty()) {
107 root["friendly_name"] = App.get_friendly_name();
108 }
109#ifdef USE_API
110 root["port"] = api::global_api_server->get_port();
111#endif
112 root["version"] = ESPHOME_VERSION;
113 root["mac"] = get_mac_address();
114
115#ifdef USE_ESP8266
116 root["platform"] = "ESP8266";
117#endif
118#ifdef USE_ESP32
119 root["platform"] = "ESP32";
120#endif
121#ifdef USE_LIBRETINY
122 root["platform"] = lt_cpu_get_model_name();
123#endif
124
125 root["board"] = ESPHOME_BOARD;
126#if defined(USE_WIFI)
127 root["network"] = "wifi";
128#elif defined(USE_ETHERNET)
129 root["network"] = "ethernet";
130#endif
131
132#ifdef ESPHOME_PROJECT_NAME
133 root["project_name"] = ESPHOME_PROJECT_NAME;
134 root["project_version"] = ESPHOME_PROJECT_VERSION;
135#endif // ESPHOME_PROJECT_NAME
136
137#ifdef USE_DASHBOARD_IMPORT
138 root["package_import_url"] = dashboard_import::get_package_import_url();
139#endif
140
141#ifdef USE_API_NOISE
142 if (api::global_api_server->get_noise_ctx()->has_psk()) {
143 root["api_encryption"] = "Noise_NNpsk0_25519_ChaChaPoly_SHA256";
144 } else {
145 root["api_encryption_supported"] = "Noise_NNpsk0_25519_ChaChaPoly_SHA256";
146 }
147#endif
148 },
149 2, this->discovery_info_.retain);
150 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
151}
152
154 ESP_LOGCONFIG(TAG,
155 "MQTT:\n"
156 " Server Address: %s:%u (%s)\n"
157 " Username: " LOG_SECRET("'%s'") "\n"
158 " Client ID: " LOG_SECRET("'%s'") "\n"
159 " Clean Session: %s",
160 this->credentials_.address.c_str(), this->credentials_.port, this->ip_.str().c_str(),
161 this->credentials_.username.c_str(), this->credentials_.client_id.c_str(),
162 YESNO(this->credentials_.clean_session));
163 if (this->is_discovery_ip_enabled()) {
164 ESP_LOGCONFIG(TAG, " Discovery IP enabled");
165 }
166 if (!this->discovery_info_.prefix.empty()) {
167 ESP_LOGCONFIG(TAG,
168 " Discovery prefix: '%s'\n"
169 " Discovery retain: %s",
170 this->discovery_info_.prefix.c_str(), YESNO(this->discovery_info_.retain));
171 }
172 ESP_LOGCONFIG(TAG, " Topic Prefix: '%s'", this->topic_prefix_.c_str());
173 if (!this->log_message_.topic.empty()) {
174 ESP_LOGCONFIG(TAG, " Log Topic: '%s'", this->log_message_.topic.c_str());
175 }
176 if (!this->availability_.topic.empty()) {
177 ESP_LOGCONFIG(TAG, " Availability: '%s'", this->availability_.topic.c_str());
178 }
179}
181 return network::is_disabled() || this->state_ == MQTT_CLIENT_DISABLED || this->is_connected() ||
183}
184
186 for (auto &subscription : this->subscriptions_) {
187 subscription.subscribed = false;
188 subscription.resubscribe_timeout = 0;
189 }
190
191 this->status_set_warning();
192 this->dns_resolve_error_ = false;
193 this->dns_resolved_ = false;
194 ip_addr_t addr;
195 err_t err;
196 {
197 LwIPLock lock;
198#if USE_NETWORK_IPV6
199 err = dns_gethostbyname_addrtype(this->credentials_.address.c_str(), &addr, MQTTClientComponent::dns_found_callback,
200 this, LWIP_DNS_ADDRTYPE_IPV6_IPV4);
201#else
202 err = dns_gethostbyname_addrtype(this->credentials_.address.c_str(), &addr, MQTTClientComponent::dns_found_callback,
203 this, LWIP_DNS_ADDRTYPE_IPV4);
204#endif /* USE_NETWORK_IPV6 */
205 }
206 switch (err) {
207 case ERR_OK: {
208 // Got IP immediately
209 this->dns_resolved_ = true;
210 this->ip_ = network::IPAddress(&addr);
211 this->start_connect_();
212 return;
213 }
214 case ERR_INPROGRESS: {
215 // wait for callback
216 ESP_LOGD(TAG, "Resolving broker IP address");
217 break;
218 }
219 default:
220 case ERR_ARG: {
221 // error
222 ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
223 break;
224 }
225 }
226
228 this->connect_begin_ = millis();
229}
231 if (!this->dns_resolved_ && millis() - this->connect_begin_ > 20000) {
232 this->dns_resolve_error_ = true;
233 }
234
235 if (this->dns_resolve_error_) {
236 ESP_LOGW(TAG, "Couldn't resolve IP address for '%s'", this->credentials_.address.c_str());
240 return;
241 }
242
243 if (!this->dns_resolved_) {
244 return;
245 }
246
247 ESP_LOGD(TAG, "Resolved broker IP address to %s", this->ip_.str().c_str());
248 this->start_connect_();
249}
250#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
251void MQTTClientComponent::dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg) {
252#else
253void MQTTClientComponent::dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg) {
254#endif
255 auto *a_this = (MQTTClientComponent *) callback_arg;
256 if (ipaddr == nullptr) {
257 a_this->dns_resolve_error_ = true;
258 } else {
259 a_this->ip_ = network::IPAddress(ipaddr);
260 a_this->dns_resolved_ = true;
261 }
262}
263
266 return;
267
268 ESP_LOGI(TAG, "Connecting");
269 // Force disconnect first
271
274 const char *username = nullptr;
275 if (!this->credentials_.username.empty())
276 username = this->credentials_.username.c_str();
277 const char *password = nullptr;
278 if (!this->credentials_.password.empty())
279 password = this->credentials_.password.c_str();
280
281 this->mqtt_backend_.set_credentials(username, password);
282
283 this->mqtt_backend_.set_server(this->credentials_.address.c_str(), this->credentials_.port);
284 if (!this->last_will_.topic.empty()) {
285 this->mqtt_backend_.set_will(this->last_will_.topic.c_str(), this->last_will_.qos, this->last_will_.retain,
286 this->last_will_.payload.c_str());
287 }
288
289 this->mqtt_backend_.connect();
291 this->connect_begin_ = millis();
292}
294 return this->state_ == MQTT_CLIENT_CONNECTED && this->mqtt_backend_.connected();
295}
296
298 if (!this->mqtt_backend_.connected()) {
299 if (millis() - this->connect_begin_ > 60000) {
301 this->start_dnslookup_();
302 }
303 return;
304 }
305
307 this->sent_birth_message_ = false;
308 this->status_clear_warning();
309 ESP_LOGI(TAG, "Connected");
310 // MQTT Client needs some time to be fully set up.
311 delay(100); // NOLINT
312
314 this->send_device_info_();
315
316 for (MQTTComponent *component : this->children_)
317 component->schedule_resend_state();
318}
319
321 // Call the backend loop first
323
324 if (this->disconnect_reason_.has_value()) {
325 const LogString *reason_s;
326 switch (*this->disconnect_reason_) {
328 reason_s = LOG_STR("TCP disconnected");
329 break;
331 reason_s = LOG_STR("Unacceptable Protocol Version");
332 break;
334 reason_s = LOG_STR("Identifier Rejected");
335 break;
337 reason_s = LOG_STR("Server Unavailable");
338 break;
340 reason_s = LOG_STR("Malformed Credentials");
341 break;
343 reason_s = LOG_STR("Not Authorized");
344 break;
346 reason_s = LOG_STR("Not Enough Space");
347 break;
349 reason_s = LOG_STR("TLS Bad Fingerprint");
350 break;
351 default:
352 reason_s = LOG_STR("Unknown");
353 break;
354 }
355 if (!network::is_connected()) {
356 reason_s = LOG_STR("WiFi disconnected");
357 }
358 ESP_LOGW(TAG, "Disconnected: %s", LOG_STR_ARG(reason_s));
360 }
361
363
364 switch (this->state_) {
366 return; // Return to avoid a reboot when disabled
368 if (now - this->connect_begin_ > 5000) {
369 this->start_dnslookup_();
370 }
371 break;
373 this->check_dnslookup_();
374 break;
376 this->check_connected();
377 break;
379 if (!this->mqtt_backend_.connected()) {
381 ESP_LOGW(TAG, "Lost client connection");
382 this->start_dnslookup_();
383 } else {
384 if (!this->birth_message_.topic.empty() && !this->sent_birth_message_) {
385 this->sent_birth_message_ = this->publish(this->birth_message_);
386 }
387
388 this->last_connected_ = now;
390 }
391 break;
392 }
393
394 if (millis() - this->last_connected_ > this->reboot_timeout_ && this->reboot_timeout_ != 0) {
395 ESP_LOGE(TAG, "Can't connect; restarting");
396 App.reboot();
397 }
398}
400
401// Subscribe
402bool MQTTClientComponent::subscribe_(const char *topic, uint8_t qos) {
403 if (!this->is_connected())
404 return false;
405
406 bool ret = this->mqtt_backend_.subscribe(topic, qos);
407 yield();
408
409 if (ret) {
410 ESP_LOGV(TAG, "subscribe(topic='%s')", topic);
411 } else {
412 delay(5);
413 ESP_LOGV(TAG, "Subscribe failed for topic='%s'. Will retry", topic);
414 this->status_momentary_warning("subscribe", 1000);
415 }
416 return ret != 0;
417}
418void MQTTClientComponent::resubscribe_subscription_(MQTTSubscription *sub) {
419 if (sub->subscribed)
420 return;
421
422 const uint32_t now = millis();
423 bool do_resub = sub->resubscribe_timeout == 0 || now - sub->resubscribe_timeout > 1000;
424
425 if (do_resub) {
426 sub->subscribed = this->subscribe_(sub->topic.c_str(), sub->qos);
427 sub->resubscribe_timeout = now;
428 }
429}
431 for (auto &subscription : this->subscriptions_) {
432 this->resubscribe_subscription_(&subscription);
433 }
434}
435
436void MQTTClientComponent::subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos) {
437 MQTTSubscription subscription{
438 .topic = topic,
439 .qos = qos,
440 .callback = std::move(callback),
441 .subscribed = false,
442 .resubscribe_timeout = 0,
443 };
444 this->resubscribe_subscription_(&subscription);
445 this->subscriptions_.push_back(subscription);
446}
447
448void MQTTClientComponent::subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos) {
449 auto f = [callback](const std::string &topic, const std::string &payload) {
450 json::parse_json(payload, [topic, callback](JsonObject root) -> bool {
451 callback(topic, root);
452 return true;
453 });
454 };
455 MQTTSubscription subscription{
456 .topic = topic,
457 .qos = qos,
458 .callback = f,
459 .subscribed = false,
460 .resubscribe_timeout = 0,
461 };
462 this->resubscribe_subscription_(&subscription);
463 this->subscriptions_.push_back(subscription);
464}
465
466void MQTTClientComponent::unsubscribe(const std::string &topic) {
467 bool ret = this->mqtt_backend_.unsubscribe(topic.c_str());
468 yield();
469 if (ret) {
470 ESP_LOGV(TAG, "unsubscribe(topic='%s')", topic.c_str());
471 } else {
472 delay(5);
473 ESP_LOGV(TAG, "Unsubscribe failed for topic='%s'.", topic.c_str());
474 this->status_momentary_warning("unsubscribe", 1000);
475 }
476
477 auto it = subscriptions_.begin();
478 while (it != subscriptions_.end()) {
479 if (it->topic == topic) {
480 it = subscriptions_.erase(it);
481 } else {
482 ++it;
483 }
484 }
485}
486
487// Publish
488bool MQTTClientComponent::publish(const std::string &topic, const std::string &payload, uint8_t qos, bool retain) {
489 return this->publish(topic, payload.data(), payload.size(), qos, retain);
490}
491
492bool MQTTClientComponent::publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos,
493 bool retain) {
494 return publish({.topic = topic, .payload = payload, .qos = qos, .retain = retain});
495}
496
497bool MQTTClientComponent::publish(const MQTTMessage &message) {
498 if (!this->is_connected()) {
499 // critical components will re-transmit their messages
500 return false;
501 }
502 bool logging_topic = this->log_message_.topic == message.topic;
503 bool ret = this->mqtt_backend_.publish(message);
504 delay(0);
505 if (!ret && !logging_topic && this->is_connected()) {
506 delay(0);
507 ret = this->mqtt_backend_.publish(message);
508 delay(0);
509 }
510
511 if (!logging_topic) {
512 if (ret) {
513 ESP_LOGV(TAG, "Publish(topic='%s' payload='%s' retain=%d qos=%d)", message.topic.c_str(), message.payload.c_str(),
514 message.retain, message.qos);
515 } else {
516 ESP_LOGV(TAG, "Publish failed for topic='%s' (len=%u). Will retry", message.topic.c_str(),
517 message.payload.length());
518 this->status_momentary_warning("publish", 1000);
519 }
520 }
521 return ret != 0;
522}
523bool MQTTClientComponent::publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos,
524 bool retain) {
525 std::string message = json::build_json(f);
526 return this->publish(topic, message, qos, retain);
527}
528
530 if (this->state_ != MQTT_CLIENT_DISABLED)
531 return;
532 ESP_LOGD(TAG, "Enabling");
534 this->last_connected_ = millis();
535 this->start_dnslookup_();
536}
537
539 if (this->state_ == MQTT_CLIENT_DISABLED)
540 return;
541 ESP_LOGD(TAG, "Disabling");
543 this->on_shutdown();
544}
545
557static bool topic_match(const char *message, const char *subscription, bool is_normal, bool past_separator) {
558 // Reached end of both strings at the same time, this means we have a successful match
559 if (*message == '\0' && *subscription == '\0')
560 return true;
561
562 // Either the message or the subscribe are at the end. This means they don't match.
563 if (*message == '\0' || *subscription == '\0')
564 return false;
565
566 bool do_wildcards = is_normal || past_separator;
567
568 if (*subscription == '+' && do_wildcards) {
569 // single level wildcard
570 // consume + from subscription
571 subscription++;
572 // consume everything from message until '/' found or end of string
573 while (*message != '\0' && *message != '/') {
574 message++;
575 }
576 // after this, both pointers will point to a '/' or to the end of the string
577
578 return topic_match(message, subscription, is_normal, true);
579 }
580
581 if (*subscription == '#' && do_wildcards) {
582 // multilevel wildcard - MQTT mandates that this must be at end of subscribe topic
583 return true;
584 }
585
586 // this handles '/' and normal characters at the same time.
587 if (*message != *subscription)
588 return false;
589
590 past_separator = past_separator || *subscription == '/';
591
592 // consume characters
593 subscription++;
594 message++;
595
596 return topic_match(message, subscription, is_normal, past_separator);
597}
598
599static bool topic_match(const char *message, const char *subscription) {
600 return topic_match(message, subscription, *message != '\0' && *message != '$', false);
601}
602
603void MQTTClientComponent::on_message(const std::string &topic, const std::string &payload) {
604#ifdef USE_ESP8266
605 // on ESP8266, this is called in lwIP/AsyncTCP task; some components do not like running
606 // from a different task.
607 this->defer([this, topic, payload]() {
608#endif
609 for (auto &subscription : this->subscriptions_) {
610 if (topic_match(topic.c_str(), subscription.topic.c_str()))
611 subscription.callback(topic, payload);
612 }
613#ifdef USE_ESP8266
614 });
615#endif
616}
617
618// Setters
620bool MQTTClientComponent::is_log_message_enabled() const { return !this->log_message_.topic.empty(); }
621void MQTTClientComponent::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
622void MQTTClientComponent::register_mqtt_component(MQTTComponent *component) { this->children_.push_back(component); }
623void MQTTClientComponent::set_log_level(int level) { this->log_level_ = level; }
624void MQTTClientComponent::set_keep_alive(uint16_t keep_alive_s) { this->mqtt_backend_.set_keep_alive(keep_alive_s); }
625void MQTTClientComponent::set_log_message_template(MQTTMessage &&message) { this->log_message_ = std::move(message); }
626const MQTTDiscoveryInfo &MQTTClientComponent::get_discovery_info() const { return this->discovery_info_; }
627void MQTTClientComponent::set_topic_prefix(const std::string &topic_prefix, const std::string &check_topic_prefix) {
628 if (App.is_name_add_mac_suffix_enabled() && (topic_prefix == check_topic_prefix)) {
630 } else {
631 this->topic_prefix_ = topic_prefix;
632 }
633}
634const std::string &MQTTClientComponent::get_topic_prefix() const { return this->topic_prefix_; }
635void MQTTClientComponent::set_publish_nan_as_none(bool publish_nan_as_none) {
636 this->publish_nan_as_none_ = publish_nan_as_none;
637}
640 this->birth_message_.topic = "";
642}
644 this->shutdown_message_.topic = "";
646}
647bool MQTTClientComponent::is_discovery_enabled() const { return !this->discovery_info_.prefix.empty(); }
649const Availability &MQTTClientComponent::get_availability() { return this->availability_; }
651 if (this->birth_message_.topic.empty() || this->birth_message_.topic != this->last_will_.topic) {
652 this->availability_.topic = "";
653 return;
654 }
658}
659
660void MQTTClientComponent::set_last_will(MQTTMessage &&message) {
661 this->last_will_ = std::move(message);
663}
664
665void MQTTClientComponent::set_birth_message(MQTTMessage &&message) {
666 this->birth_message_ = std::move(message);
668}
669
670void MQTTClientComponent::set_shutdown_message(MQTTMessage &&message) { this->shutdown_message_ = std::move(message); }
671
672void MQTTClientComponent::set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
673 MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain,
674 bool discover_ip, bool clean) {
675 this->discovery_info_.prefix = std::move(prefix);
676 this->discovery_info_.discover_ip = discover_ip;
677 this->discovery_info_.unique_id_generator = unique_id_generator;
678 this->discovery_info_.object_id_generator = object_id_generator;
679 this->discovery_info_.retain = retain;
680 this->discovery_info_.clean = clean;
681}
682
684
686 this->discovery_info_ = MQTTDiscoveryInfo{
687 .prefix = "",
688 .retain = false,
689 .discover_ip = false,
690 .clean = false,
691 .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
692 .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
693 };
694}
696 if (!this->shutdown_message_.topic.empty()) {
697 yield();
698 this->publish(this->shutdown_message_);
699 yield();
700 }
702}
703
705 this->mqtt_backend_.set_on_connect(std::forward<mqtt_on_connect_callback_t>(callback));
706}
707
709 auto callback_copy = callback;
710 this->mqtt_backend_.set_on_disconnect(std::forward<mqtt_on_disconnect_callback_t>(callback));
711 this->on_disconnect_.add(std::move(callback_copy));
712}
713
714#if ASYNC_TCP_SSL_ENABLED
715void MQTTClientComponent::add_ssl_fingerprint(const std::array<uint8_t, SHA1_SIZE> &fingerprint) {
716 this->mqtt_backend_.setSecure(true);
717 this->mqtt_backend_.addServerFingerprint(fingerprint.data());
718}
719#endif
720
721MQTTClientComponent *global_mqtt_client = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
722
723// MQTTMessageTrigger
724MQTTMessageTrigger::MQTTMessageTrigger(std::string topic) : topic_(std::move(topic)) {}
725void MQTTMessageTrigger::set_qos(uint8_t qos) { this->qos_ = qos; }
726void MQTTMessageTrigger::set_payload(const std::string &payload) { this->payload_ = payload; }
727void MQTTMessageTrigger::setup() {
729 this->topic_,
730 [this](const std::string &topic, const std::string &payload) {
731 if (this->payload_.has_value() && payload != *this->payload_) {
732 return;
733 }
734
735 this->trigger(payload);
736 },
737 this->qos_);
738}
739void MQTTMessageTrigger::dump_config() {
740 ESP_LOGCONFIG(TAG,
741 "MQTT Message Trigger:\n"
742 " Topic: '%s'\n"
743 " QoS: %u",
744 this->topic_.c_str(), this->qos_);
745}
746float MQTTMessageTrigger::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
747
748} // namespace mqtt
749} // namespace esphome
750
751#endif // USE_MQTT
const std::string & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
bool is_name_add_mac_suffix_enabled() const
const std::string & get_name() const
Get the name of this Application set by pre_setup().
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void status_set_warning(const char *message=nullptr)
void status_momentary_warning(const std::string &name, uint32_t length=5000)
void defer(const std::string &name, std::function< void()> &&f)
Defer a callback to the next loop() call.
void status_clear_warning()
uint16_t get_port() const
void add_on_log_callback(std::function< void(uint8_t, const char *, const char *, size_t)> &&callback)
Register a callback that will be called for every log message sent.
Definition logger.cpp:245
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 add_ssl_fingerprint(const std::array< uint8_t, SHA1_SIZE > &fingerprint)
Add a SSL fingerprint to use for TCP SSL connections to the MQTT broker.
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()
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)
bool has_value() const
Definition optional.h:92
in_addr ip_addr_t
Definition ip_address.h:22
APIServer * global_api_server
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition json_util.h:20
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:53
std::string build_json(const json_build_t &f)
Build a JSON string with the provided json build function.
Definition json_util.cpp:33
Logger * global_logger
Definition logger.cpp:283
std::function< MQTTBackend::on_disconnect_callback_t > mqtt_on_disconnect_callback_t
Definition mqtt_client.h:30
MQTTDiscoveryObjectIdGenerator
available discovery object_id generators
Definition mqtt_client.h:72
@ MQTT_NONE_OBJECT_ID_GENERATOR
Definition mqtt_client.h:73
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
Definition mqtt_client.h:66
@ MQTT_LEGACY_UNIQUE_ID_GENERATOR
Definition mqtt_client.h:67
std::function< void(const std::string &, JsonObject)> mqtt_json_callback_t
Definition mqtt_client.h:37
std::function< void(const std::string &, const std::string &)> mqtt_callback_t
Callback for MQTT subscriptions.
Definition mqtt_client.h:36
MQTTClientComponent * global_mqtt_client
@ MQTT_CLIENT_DISCONNECTED
Definition mqtt_client.h:92
@ MQTT_CLIENT_RESOLVING_ADDRESS
Definition mqtt_client.h:93
std::function< MQTTBackend::on_connect_callback_t > mqtt_on_connect_callback_t
Callback for MQTT events.
Definition mqtt_client.h:29
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.cpp:26
network::IPAddresses get_ip_addresses()
Definition util.cpp:66
bool is_disabled()
Return whether the network is disabled (only wifi for now)
Definition util.cpp:53
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.cpp:57
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores.
Definition helpers.cpp:184
std::string size_t len
Definition helpers.h:279
void IRAM_ATTR HOT yield()
Definition core.cpp:27
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition helpers.cpp:578
Application App
Global storage of Application pointer - only one Application can exist.
std::string payload_not_available
Definition mqtt_client.h:62
std::string topic
Empty means disabled.
Definition mqtt_client.h:60
std::string address
The address of the server without port number.
Definition mqtt_client.h:50
bool clean_session
Whether the session will be cleaned or remembered between connects.
Definition mqtt_client.h:55
std::string client_id
The client ID. Will automatically be truncated to 23 characters.
Definition mqtt_client.h:54
MQTTDiscoveryUniqueIdGenerator unique_id_generator
Definition mqtt_client.h:86
bool discover_ip
Enable the Home Assistant device discovery.
Definition mqtt_client.h:84
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
Definition mqtt_client.h:82
MQTTDiscoveryObjectIdGenerator object_id_generator
Definition mqtt_client.h:87
bool retain
Whether to retain discovery messages.
Definition mqtt_client.h:83
uint8_t qos
QoS. Only for last will testaments.
std::string str() const
Definition ip_address.h:52