ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
mqtt_client.h
Go to the documentation of this file.
1#pragma once
2
4
5#ifdef USE_MQTT
6
13#include "esphome/core/log.h"
16#ifdef USE_LOGGER
18#endif
19#if defined(USE_ESP32)
20#include "mqtt_backend_esp32.h"
21#elif defined(USE_ESP8266)
23#elif defined(USE_LIBRETINY)
25#endif
26#if defined(USE_MQTT_SESSION_PERSISTENCE) && !defined(USE_ESP32)
28#endif
29#include "lwip/ip_addr.h"
30
31#include <atomic>
32#include <span>
33#include <vector>
34
35// The crash log replay needs the logger, which mqtt does not depend on
36#if defined(USE_LOGGER) && defined(USE_CRASH_HANDLER)
37#define USE_MQTT_CRASH_LOG
38#endif
39
40namespace esphome::mqtt {
41
42#if defined(USE_ESP8266) && ASYNC_TCP_SSL_ENABLED
43extern const uint8_t SSL_FINGERPRINT[] PROGMEM;
44#endif
45
46// Max lengths for stack-based topic building.
47// These limits are enforced at Python config validation time in mqtt/__init__.py
48// using cv.Length() validators for topic_prefix.
49// This ensures the stack buffers are always large enough.
50static constexpr size_t MQTT_COMPONENT_TYPE_MAX_LEN = 20;
51static constexpr size_t MQTT_SUFFIX_MAX_LEN = 32;
52static constexpr size_t MQTT_TOPIC_PREFIX_MAX_LEN = 64; // Validated in Python: cv.Length(max=64)
53// Stack buffer size - safe because all inputs are length-validated at config time
54// Format: prefix + "/" + type + "/" + object_id + "/" + suffix + null
55static constexpr size_t MQTT_DEFAULT_TOPIC_MAX_LEN =
56 MQTT_TOPIC_PREFIX_MAX_LEN + 1 + MQTT_COMPONENT_TYPE_MAX_LEN + 1 + OBJECT_ID_MAX_LEN + 1 + MQTT_SUFFIX_MAX_LEN + 1;
57
59using mqtt_subscription_callback_t = Callback<void(const std::string &, const std::string &)>;
60
61// Remove before 2027.6.0
62using mqtt_on_connect_callback_t ESPDEPRECATED(
63 "set_on_connect() takes any callable; pass the lambda directly. Removed in 2027.6.0",
64 "2026.12.0") = std::function<MQTTBackend::on_connect_callback_t>;
65using mqtt_on_disconnect_callback_t ESPDEPRECATED(
66 "set_on_disconnect() takes any callable; pass the lambda directly. Removed in 2027.6.0",
67 "2026.12.0") = std::function<MQTTBackend::on_disconnect_callback_t>;
68
69// Remove before 2027.5.0
70using mqtt_callback_t ESPDEPRECATED("subscribe() takes any callable; pass the lambda directly. Removed in 2027.5.0",
71 "2026.11.0") = std::function<void(const std::string &, const std::string &)>;
72using mqtt_json_callback_t ESPDEPRECATED(
73 "subscribe_json() takes any callable; pass the lambda directly. Removed in 2027.5.0",
74 "2026.11.0") = std::function<void(const std::string &, JsonObject)>;
75
78using mqtt_topic_builder_t = StringRef (*)(const void *context, std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN> buf);
79
83 const void *context;
84 StringRef build(std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN> buf) const { return this->builder(this->context, buf); }
85};
86
88MQTTTopicSource static_topic(const char *topic);
89#ifdef USE_ESP8266
92#endif
93
99 uint8_t qos;
101 bool boxed; // made by create_boxed(), freed on unsubscribe
102 bool removed; // unsubscribed while a callback ran, erased once dispatch returns
103};
104
107 std::string address;
108 uint16_t port;
109 std::string username;
110 std::string password;
111 std::string client_id;
113};
114
117 std::string topic;
118 std::string payload_available;
120};
121
127
133
146
154
155class MQTTComponent;
156
157class MQTTClientComponent final : public Component {
158 public:
160
165
170
173
175 void set_keep_alive(uint16_t keep_alive_s);
176
185 void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
186 MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip,
187 bool clean = false);
194
195#if defined(USE_ESP32) && defined(USE_MQTT_TLS)
196 void set_ca_certificate(const char *cert) { this->mqtt_backend_.set_ca_certificate(cert); }
197 void set_cl_certificate(const char *cert) { this->mqtt_backend_.set_cl_certificate(cert); }
198 void set_cl_key(const char *key) { this->mqtt_backend_.set_cl_key(key); }
199 void set_skip_cert_cn_check(bool skip_check) { this->mqtt_backend_.set_skip_cert_cn_check(skip_check); }
200#endif
201#if defined(USE_ESP8266) && ASYNC_TCP_SSL_ENABLED
202 // The broker's certificate SHA1, generated as SSL_FINGERPRINT in flash; the library keeps its own copy
204 uint8_t fingerprint[20];
205 progmem_memcpy(fingerprint, SSL_FINGERPRINT, sizeof(fingerprint));
206 this->mqtt_backend_.set_server_fingerprint(fingerprint);
207 }
208#endif
209#ifdef USE_ESP32
210 void set_transport(MQTTTransport transport) { this->mqtt_backend_.set_transport(transport); }
211 void set_ws_path(const char *path) { this->mqtt_backend_.set_ws_path(path); }
212#endif
214
223 void set_topic_prefix(std::string topic_prefix) { this->topic_prefix_ = std::move(topic_prefix); }
225 const std::string &get_topic_prefix() const;
226
229 void set_log_level(int level) { this->log_level_ = level; }
233
243 template<typename F> void subscribe(MQTTTopicSource topic, F &&callback, uint8_t qos = 0) {
244 constexpr bool boxed = !mqtt_subscription_callback_t::fits_inline<F>();
245 this->add_subscription_(topic,
246 boxed ? mqtt_subscription_callback_t::create_boxed(std::forward<F>(callback))
247 : mqtt_subscription_callback_t::create(std::forward<F>(callback)),
248 boxed, qos);
249 }
250
259 template<typename F> void subscribe(const std::string &topic, F &&callback, uint8_t qos = 0) {
260 this->subscribe(copy_topic(StringRef(topic)), std::forward<F>(callback), qos);
261 }
262
272 template<typename T, typename F> void subscribe_json(T &&topic, F &&callback, uint8_t qos = 0) {
273 static_assert(std::is_invocable_v<const std::decay_t<F> &, const std::string &, JsonObject>,
274 "subscribe_json() needs a callback that does not mutate its captures");
275 this->subscribe(
276 std::forward<T>(topic),
277 [cb = std::forward<F>(callback)](const std::string &topic, const std::string &payload) {
278 call_json(cb, topic, payload);
279 },
280 qos);
281 }
282
291 void unsubscribe(const std::string &topic);
292
298
305 bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false);
306
307 bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0,
308 bool retain = false);
309
311 bool publish(const char *topic, const char *payload, size_t payload_length, uint8_t qos = 0, bool retain = false);
312
319 bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false) {
320 return this->publish_json(topic.c_str(), json::json_build_ref(f), qos, retain);
321 }
322 template<json::JsonBuildCallable F>
323 bool publish_json(const std::string &topic, F &&f, uint8_t qos = 0, bool retain = false) {
324 return this->publish_json(topic.c_str(), json::json_build_ref(f), qos, retain);
325 }
326
328 bool publish_json(const char *topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false) {
329 return this->publish_json(topic, json::json_build_ref(f), qos, retain);
330 }
332 template<json::JsonBuildCallable F>
333 bool publish_json(const char *topic, F &&f, uint8_t qos = 0, bool retain = false) {
334 return this->publish_json(topic, json::json_build_ref(f), qos, retain);
335 }
336 bool publish_json(const char *topic, json::JsonBuildRef f, uint8_t qos = 0, bool retain = false);
337
339 void setup() override;
340 void dump_config() override;
342 void loop() override;
344 float get_setup_priority() const override;
345
346#ifdef USE_LOGGER
347 void on_log(uint8_t level, const char *tag, const char *message, size_t message_len);
348#endif
349
350 void on_message(const std::string &topic, const std::string &payload);
351
352 bool can_proceed() override;
353
355
356 void set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
357
359
361 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
362 void enable();
363 void disable();
364
365 void on_shutdown() override;
366 bool teardown() override;
367#ifdef USE_ESP8266
368 void on_powerdown() override;
369#endif
370
371 void set_broker_address(const std::string &address) { this->credentials_.address = address; }
372 void set_broker_port(uint16_t port) { this->credentials_.port = port; }
373 void set_username(const std::string &username) { this->credentials_.username = username; }
374 void set_password(const std::string &password) { this->credentials_.password = password; }
375 void set_client_id(const std::string &client_id) { this->credentials_.client_id = client_id; }
376 void set_clean_session(const bool &clean_session) { this->credentials_.clean_session = clean_session; }
377 template<typename F> void set_on_connect(F &&callback) { this->on_connect_.add(std::forward<F>(callback)); }
378 template<typename F> void set_on_disconnect(F &&callback) { this->on_disconnect_.add(std::forward<F>(callback)); }
379
380 // Publish None state instead of NaN for Home Assistant
381 void set_publish_nan_as_none(bool publish_nan_as_none) { this->publish_nan_as_none_ = publish_nan_as_none; }
382 bool is_publish_nan_as_none() const { return this->publish_nan_as_none_; }
383
384 void set_wait_for_connection(bool wait_for_connection) { this->wait_for_connection_ = wait_for_connection; }
385
386 protected:
387 // For the lambda command topic, which is copied once
388 friend class MQTTComponent;
389
392
394
399#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
400 static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg);
401#else
402 static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg);
403#endif
404
407
408 bool subscribe_(const char *topic, uint8_t qos);
409 bool subscribe_topic_(const MQTTTopicSource &topic, uint8_t qos);
411 template<typename F> static void call_json(const F &callback, const std::string &topic, const std::string &payload) {
412 JsonDocument doc = json::parse_json(payload);
413 if (doc.overflowed() || doc.isNull())
414 return;
415 callback(topic, doc.as<JsonObject>());
416 }
418#ifdef USE_MQTT_CRASH_LOG
420 void handle_crash_log_request_(const std::string &topic, const std::string &payload);
421#endif
422 void add_subscription_(MQTTTopicSource topic, mqtt_subscription_callback_t callback, bool boxed, uint8_t qos);
425#ifdef USE_MQTT_SESSION_PERSISTENCE
430#endif
431
447 .prefix = "homeassistant",
448 .retain = true,
449 .discover_ip = true,
450 .clean = false,
451 .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
452 .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
453 };
454 std::string topic_prefix_{};
456 std::string payload_buffer_;
457 int log_level_{ESPHOME_LOG_LEVEL};
458
459 std::vector<MQTTSubscription> subscriptions_;
460#if defined(USE_ESP32)
462#elif defined(USE_ESP8266)
464#elif defined(USE_LIBRETINY)
466#endif
467
470 bool dns_resolved_{false};
474 bool enable_on_boot_{true};
475#ifdef USE_MQTT_CRASH_LOG
477#endif
478 std::vector<MQTTComponent *> children_;
482 // Reason for loop() to report, or NO_DISCONNECT; written from the backend's network context
483 static constexpr int8_t NO_DISCONNECT = -1;
484 std::atomic<int8_t> disconnect_reason_{NO_DISCONNECT};
485 bool session_present_{false};
488
491 bool dispatching_{false};
493#ifdef USE_MQTT_SESSION_PERSISTENCE
495 bool subacks_settled_{false};
497 uint16_t subscribes_sent_{0};
498#ifndef USE_ESP32
500#endif
503#endif
504};
505
506extern MQTTClientComponent *global_mqtt_client; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
507
508} // namespace esphome::mqtt
509
510#endif // USE_MQTT
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
void set_ca_certificate(const char *cert)
void set_transport(MQTTTransport transport)
void set_skip_cert_cn_check(bool skip_check)
void set_cl_certificate(const char *cert)
void set_birth_message(MQTTMessage &&message)
Set the birth message.
void start_connect_()
Reconnect to the MQTT broker if not already connected.
void set_ws_path(const char *path)
void setup() override
Setup the MQTT client, registering a bunch of callbacks and attempting to connect.
void set_password(const std::string &password)
void set_clean_session(const bool &clean_session)
void disable_discovery()
Globally disable Home Assistant discovery.
void recalculate_availability_()
Re-calculate the availability property.
void subscribe(MQTTTopicSource topic, F &&callback, uint8_t qos=0)
Subscribe to an MQTT topic and call callback when a message is received.
void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator, MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip, bool clean=false)
Set the Home Assistant discovery info.
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(T &&topic, F &&callback, uint8_t qos=0)
Subscribe to a MQTT topic and automatically parse JSON payload.
LazyCallbackManager< MQTTBackend::on_connect_callback_t > on_connect_
void set_cl_certificate(const char *cert)
uint16_t subscribes_sent_
SUBSCRIBEs sent on this connection for the subscriptions the fingerprint covers.
void register_mqtt_component(MQTTComponent *component)
void set_on_disconnect(F &&callback)
bool resubscribe_subscriptions_()
Returns true when every subscription is subscribed.
void set_last_will(MQTTMessage &&message)
Set the last will testament message.
void set_skip_cert_cn_check(bool skip_check)
bool publish(const MQTTMessage &message)
Publish a MQTTMessage.
void set_topic_prefix(std::string topic_prefix)
Set the topic prefix that will be prepended to all topics together with "/".
const MQTTDiscoveryInfo & get_discovery_info() const
Get Home Assistant discovery info.
void disable_birth_message()
Remove the birth message.
static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg)
bool waiting_for_network_
The last start_dnslookup_() found no network, so no attempt was made and there is nothing to back off...
void set_broker_address(const std::string &address)
MQTTMessage last_will_
The last will message.
uint32_t session_fingerprint_
Fingerprint of the set the broker session is known to hold in full; 0 while a rebuild is in progress.
std::atomic< int8_t > disconnect_reason_
void set_shutdown_message(MQTTMessage &&message)
MQTTBackendLibreTiny mqtt_backend_
static constexpr int8_t NO_DISCONNECT
MQTTMessage birth_message_
The birth message (e.g.
std::vector< MQTTComponent * > children_
void add_subscription_(MQTTTopicSource topic, mqtt_subscription_callback_t callback, bool boxed, uint8_t qos)
void set_session_fingerprint_(uint32_t fingerprint)
LazyCallbackManager< MQTTBackend::on_disconnect_callback_t > on_disconnect_
static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg)
void set_ca_certificate(const char *cert)
bool publish(const std::string &topic, const std::string &payload, uint8_t qos=0, bool retain=false)
Publish a MQTT message.
void set_enable_on_boot(bool enable_on_boot)
void set_cl_key(const char *key)
void set_wait_for_connection(bool wait_for_connection)
void set_username(const std::string &username)
static MQTTTopicSource copy_topic(StringRef topic)
A heap copy of topic, owned by the one subscription it is passed to and freed when that is erased.
bool subscribe_topic_(const MQTTTopicSource &topic, uint8_t qos)
void unsubscribe(const std::string &topic)
Unsubscribe from an MQTT topic.
void subscribe(const std::string &topic, F &&callback, uint8_t qos=0)
Subscribe to an MQTT topic and call callback when a message is received.
bool publish_json(const char *topic, const json::json_build_t &f, uint8_t qos=0, bool retain=false)
Publish JSON directly without heap allocation for topic.
void set_publish_nan_as_none(bool publish_nan_as_none)
bool publish_json(const std::string &topic, F &&f, uint8_t qos=0, bool retain=false)
bool publish_json(const char *topic, F &&f, uint8_t qos=0, bool retain=false)
A JsonBuildCallable; it is not copied, so its captures never allocate.
void on_message(const std::string &topic, const std::string &payload)
void set_log_message_template(MQTTMessage &&message)
Manually set the topic used for logging.
bool subacks_settled_
Set once every SUBACK of this connection is in (or the session was resumed without subscribing)
void resubscribe_subscription_(MQTTSubscription *sub)
bool publish(const char *topic, const char *payload, size_t payload_length, uint8_t qos=0, bool retain=false)
Publish directly without creating MQTTMessage (avoids heap allocation for topic)
bool subscribe_(const char *topic, uint8_t qos)
void set_broker_port(uint16_t port)
void check_subacks_()
Once every SUBACK of this connection is in, saves the fingerprint if all were granted.
const Availability & get_availability()
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len)
std::vector< MQTTSubscription > subscriptions_
bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos=0, bool retain=false)
Construct and send a JSON MQTT message.
bool publish_json(const char *topic, json::JsonBuildRef f, uint8_t qos=0, bool retain=false)
static void call_json(const F &callback, const std::string &topic, const std::string &payload)
void set_client_id(const std::string &client_id)
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.
void handle_crash_log_request_(const std::string &topic, const std::string &payload)
void set_transport(MQTTTransport transport)
Availability availability_
Caches availability.
bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos=0, bool retain=false)
MQTTComponent is the base class for all components that interact with MQTT to expose certain function...
SUBACKs received on the current connection.
const Component * component
Definition component.cpp:34
const LogString * message
Definition component.cpp:35
const char * key
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition json_util.h:171
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
JsonBuildRef json_build_ref(F &f)
Wrap f without copying it; f must outlive the returned reference.
Definition json_util.h:188
constexpr ColorMode COLOR_MODE_LOOKUP[] PROGMEM
Definition color_mode.h:114
MQTTDiscoveryObjectIdGenerator
available discovery object_id generators
@ MQTT_DEVICE_NAME_OBJECT_ID_GENERATOR
@ MQTT_NONE_OBJECT_ID_GENERATOR
MQTTTopicSource progmem_topic(ProgmemStr topic)
A topic in flash, copied into the buffer when needed, so at most MQTT_DEFAULT_TOPIC_MAX_LEN - 1 chara...
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
@ MQTT_MAC_ADDRESS_UNIQUE_ID_GENERATOR
@ MQTT_LEGACY_UNIQUE_ID_GENERATOR
MQTTTransport
Transport for the broker connection; only the ESP-IDF backend supports WebSocket.
MQTTClientComponent * global_mqtt_client
@ MQTT_CLIENT_RESOLVING_ADDRESS
MQTTTopicSource static_topic(const char *topic)
A topic string that outlives the subscription, such as a literal; it is referenced,...
=std::function< void(const std::string &, JsonObject)> StringRef(*)(const void *context, std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) mqtt_topic_builder_t
Returns a subscription's topic, written into buf or referring to storage that outlives the subscripti...
Definition mqtt_client.h:78
void progmem_memcpy(void *dst, const void *src, size_t len)
Definition hal.h:56
void const char * tag
Definition log.h:110
const __FlashStringHelper * ProgmemStr
Definition progmem.h:33
Non-owning reference to a JSON build callable, valid only for the call it is passed to.
Definition json_util.h:175
Simple data struct for Home Assistant component availability.
std::string topic
Empty means disabled.
internal struct for MQTT credentials.
uint16_t port
The port number of the server.
std::string address
The address of the server without port number.
bool clean_session
Whether the session will be cleaned or remembered between connects.
std::string client_id
The client ID. Will automatically be truncated to 23 characters.
Internal struct for MQTT Home Assistant discovery.
MQTTDiscoveryUniqueIdGenerator unique_id_generator
bool discover_ip
Enable the Home Assistant device discovery.
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
MQTTDiscoveryObjectIdGenerator object_id_generator
bool retain
Whether to retain discovery messages.
internal struct for MQTT messages.
internal struct for MQTT subscriptions.
Definition mqtt_client.h:95
mqtt_subscription_callback_t callback
Definition mqtt_client.h:97
Where a subscription's topic comes from. The topic is rebuilt whenever it is needed,...
Definition mqtt_client.h:81
StringRef build(std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) const
Definition mqtt_client.h:84
mqtt_topic_builder_t builder
Definition mqtt_client.h:82