ESPHome 2026.11.0b6
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 <span>
32#include <vector>
33
34// The crash log replay needs the logger, which mqtt does not depend on
35#if defined(USE_LOGGER) && defined(USE_CRASH_HANDLER)
36#define USE_MQTT_CRASH_LOG
37#endif
38
39namespace esphome::mqtt {
40
41// Max lengths for stack-based topic building.
42// These limits are enforced at Python config validation time in mqtt/__init__.py
43// using cv.Length() validators for topic_prefix.
44// This ensures the stack buffers are always large enough.
45static constexpr size_t MQTT_COMPONENT_TYPE_MAX_LEN = 20;
46static constexpr size_t MQTT_SUFFIX_MAX_LEN = 32;
47static constexpr size_t MQTT_TOPIC_PREFIX_MAX_LEN = 64; // Validated in Python: cv.Length(max=64)
48// Stack buffer size - safe because all inputs are length-validated at config time
49// Format: prefix + "/" + type + "/" + object_id + "/" + suffix + null
50static constexpr size_t MQTT_DEFAULT_TOPIC_MAX_LEN =
51 MQTT_TOPIC_PREFIX_MAX_LEN + 1 + MQTT_COMPONENT_TYPE_MAX_LEN + 1 + OBJECT_ID_MAX_LEN + 1 + MQTT_SUFFIX_MAX_LEN + 1;
52
55using mqtt_on_connect_callback_t = std::function<MQTTBackend::on_connect_callback_t>;
56using mqtt_on_disconnect_callback_t = std::function<MQTTBackend::on_disconnect_callback_t>;
57
59using mqtt_subscription_callback_t = Callback<void(const std::string &, const std::string &)>;
60
61// Remove before 2027.5.0
62using mqtt_callback_t ESPDEPRECATED("subscribe() takes any callable; pass the lambda directly. Removed in 2027.5.0",
63 "2026.11.0") = std::function<void(const std::string &, const std::string &)>;
64using mqtt_json_callback_t ESPDEPRECATED(
65 "subscribe_json() takes any callable; pass the lambda directly. Removed in 2027.5.0",
66 "2026.11.0") = std::function<void(const std::string &, JsonObject)>;
67
70using mqtt_topic_builder_t = StringRef (*)(const void *context, std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN> buf);
71
75 const void *context;
76 StringRef build(std::span<char, MQTT_DEFAULT_TOPIC_MAX_LEN> buf) const { return this->builder(this->context, buf); }
77};
78
80MQTTTopicSource static_topic(const char *topic);
81#ifdef USE_ESP8266
84#endif
85
91 uint8_t qos;
93 bool boxed; // made by create_boxed(), freed on unsubscribe
94 bool removed; // unsubscribed while a callback ran, erased once dispatch returns
95};
96
99 std::string address;
100 uint16_t port;
101 std::string username;
102 std::string password;
103 std::string client_id;
105};
106
109 std::string topic;
110 std::string payload_available;
112};
113
119
125
138
146
147class MQTTComponent;
148
149class MQTTClientComponent final : public Component {
150 public:
152
157
162
165
167 void set_keep_alive(uint16_t keep_alive_s);
168
177 void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
178 MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip,
179 bool clean = false);
186
187#if defined(USE_ESP32) && defined(USE_MQTT_TLS)
188 void set_ca_certificate(const char *cert) { this->mqtt_backend_.set_ca_certificate(cert); }
189 void set_cl_certificate(const char *cert) { this->mqtt_backend_.set_cl_certificate(cert); }
190 void set_cl_key(const char *key) { this->mqtt_backend_.set_cl_key(key); }
191 void set_skip_cert_cn_check(bool skip_check) { this->mqtt_backend_.set_skip_cert_cn_check(skip_check); }
192#endif
193#ifdef USE_ESP32
194 void set_transport(MQTTTransport transport) { this->mqtt_backend_.set_transport(transport); }
195 void set_ws_path(const char *path) { this->mqtt_backend_.set_ws_path(path); }
196#endif
198
207 void set_topic_prefix(std::string topic_prefix);
209 const std::string &get_topic_prefix() const;
210
213 void set_log_level(int level) { this->log_level_ = level; }
217
227 template<typename F> void subscribe(MQTTTopicSource topic, F &&callback, uint8_t qos = 0) {
228 constexpr bool boxed = !mqtt_subscription_callback_t::fits_inline<F>();
229 this->add_subscription_(topic,
230 boxed ? mqtt_subscription_callback_t::create_boxed(std::forward<F>(callback))
231 : mqtt_subscription_callback_t::create(std::forward<F>(callback)),
232 boxed, qos);
233 }
234
243 template<typename F> void subscribe(const std::string &topic, F &&callback, uint8_t qos = 0) {
244 this->subscribe(copy_topic(StringRef(topic)), std::forward<F>(callback), qos);
245 }
246
256 template<typename T, typename F> void subscribe_json(T &&topic, F &&callback, uint8_t qos = 0) {
257 static_assert(std::is_invocable_v<const std::decay_t<F> &, const std::string &, JsonObject>,
258 "subscribe_json() needs a callback that does not mutate its captures");
259 this->subscribe(
260 std::forward<T>(topic),
261 [cb = std::forward<F>(callback)](const std::string &topic, const std::string &payload) {
262 call_json(cb, topic, payload);
263 },
264 qos);
265 }
266
275 void unsubscribe(const std::string &topic);
276
282
289 bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false);
290
291 bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0,
292 bool retain = false);
293
295 bool publish(const char *topic, const char *payload, size_t payload_length, uint8_t qos = 0, bool retain = false);
296
303 bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false);
304
306 bool publish_json(const char *topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false);
307
309 void setup() override;
310 void dump_config() override;
312 void loop() override;
314 float get_setup_priority() const override;
315
316#ifdef USE_LOGGER
317 void on_log(uint8_t level, const char *tag, const char *message, size_t message_len);
318#endif
319
320 void on_message(const std::string &topic, const std::string &payload);
321
322 bool can_proceed() override;
323
325
326 void set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
327
329
331 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
332 void enable();
333 void disable();
334
335 void on_shutdown() override;
336 bool teardown() override;
337
338 void set_broker_address(const std::string &address) { this->credentials_.address = address; }
339 void set_broker_port(uint16_t port) { this->credentials_.port = port; }
340 void set_username(const std::string &username) { this->credentials_.username = username; }
341 void set_password(const std::string &password) { this->credentials_.password = password; }
342 void set_client_id(const std::string &client_id) { this->credentials_.client_id = client_id; }
343 void set_clean_session(const bool &clean_session) { this->credentials_.clean_session = clean_session; }
346
347 // Publish None state instead of NaN for Home Assistant
348 void set_publish_nan_as_none(bool publish_nan_as_none) { this->publish_nan_as_none_ = publish_nan_as_none; }
349 bool is_publish_nan_as_none() const { return this->publish_nan_as_none_; }
350
351 void set_wait_for_connection(bool wait_for_connection) { this->wait_for_connection_ = wait_for_connection; }
352
353 protected:
354 // For the lambda command topic, which is copied once
355 friend class MQTTComponent;
356
359
361
366#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
367 static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg);
368#else
369 static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg);
370#endif
371
374
375 bool subscribe_(const char *topic, uint8_t qos);
376 bool subscribe_topic_(const MQTTTopicSource &topic, uint8_t qos);
378 template<typename F> static void call_json(const F &callback, const std::string &topic, const std::string &payload) {
379 JsonDocument doc = json::parse_json(payload);
380 if (doc.overflowed() || doc.isNull())
381 return;
382 callback(topic, doc.as<JsonObject>());
383 }
385#ifdef USE_MQTT_CRASH_LOG
387 void handle_crash_log_request_(const std::string &topic, const std::string &payload);
388#endif
389 void add_subscription_(MQTTTopicSource topic, mqtt_subscription_callback_t callback, bool boxed, uint8_t qos);
392#ifdef USE_MQTT_SESSION_PERSISTENCE
397#endif
398
414 .prefix = "homeassistant",
415 .retain = true,
416 .discover_ip = true,
417 .clean = false,
418 .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
419 .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
420 };
421 std::string topic_prefix_{};
423 std::string payload_buffer_;
424 int log_level_{ESPHOME_LOG_LEVEL};
425
426 std::vector<MQTTSubscription> subscriptions_;
427#if defined(USE_ESP32)
429#elif defined(USE_ESP8266)
431#elif defined(USE_LIBRETINY)
433#endif
434
437 bool dns_resolved_{false};
439 bool enable_on_boot_{true};
440#ifdef USE_MQTT_CRASH_LOG
442#endif
443 std::vector<MQTTComponent *> children_;
447 optional<MQTTClientDisconnectReason> disconnect_reason_{};
449
452 bool dispatching_{false};
454#ifdef USE_MQTT_SESSION_PERSISTENCE
455 bool session_present_{false};
457 bool subacks_settled_{false};
459 uint16_t subscribes_sent_{0};
460#ifndef USE_ESP32
462#endif
465#endif
466};
467
468extern MQTTClientComponent *global_mqtt_client; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
469
470template<typename... Ts> class MQTTPublishJsonAction final : public Action<Ts...> {
471 public:
473 TEMPLATABLE_VALUE(std::string, topic)
474 TEMPLATABLE_VALUE(uint8_t, qos)
475 TEMPLATABLE_VALUE(bool, retain)
476
477 void set_payload(std::function<void(Ts..., JsonObject)> payload) { this->payload_ = payload; }
478
479 void play(const Ts &...x) override {
480 auto topic = this->topic_.value(x...);
481 auto qos = this->qos_.value(x...);
482 auto retain = this->retain_.value(x...);
483 this->parent_->publish_json(topic, [this, x...](JsonObject root) { this->payload_(x..., root); }, qos, retain);
484 }
485
486 protected:
487 std::function<void(Ts..., JsonObject)> payload_;
489};
490
491} // namespace esphome::mqtt
492
493#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.
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)
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)
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.
void set_shutdown_message(MQTTMessage &&message)
MQTTBackendLibreTiny mqtt_backend_
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_on_connect(mqtt_on_connect_callback_t &&callback)
void set_session_fingerprint_(uint32_t fingerprint)
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)
optional< MQTTClientDisconnectReason > disconnect_reason_
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)
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)
void set_on_disconnect(mqtt_on_disconnect_callback_t &&callback)
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.
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.
CallbackManager< MQTTBackend::on_disconnect_callback_t > on_disconnect_
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...
TEMPLATABLE_VALUE(std::string, topic) TEMPLATABLE_VALUE(uint8_t
MQTTPublishJsonAction(MQTTClientComponent *parent)
void play(const Ts &...x) override
std::function< void(Ts..., JsonObject)> payload_
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:164
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
std::function< MQTTBackend::on_disconnect_callback_t > mqtt_on_disconnect_callback_t
Definition mqtt_client.h:56
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< MQTTBackend::on_connect_callback_t > mqtt_on_connect_callback_t
Callback for MQTT events.
Definition mqtt_client.h:55
=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:70
STL namespace.
const __FlashStringHelper * ProgmemStr
Definition progmem.h:31
Simple data struct for Home Assistant component availability.
std::string topic
Empty means disabled.
internal struct for MQTT credentials.
Definition mqtt_client.h:98
uint16_t port
The port number of the server.
std::string address
The address of the server without port number.
Definition mqtt_client.h:99
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:87
mqtt_subscription_callback_t callback
Definition mqtt_client.h:89
Where a subscription's topic comes from. The topic is rebuilt whenever it is needed,...
Definition mqtt_client.h:73
StringRef build(std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) const
Definition mqtt_client.h:76
mqtt_topic_builder_t builder
Definition mqtt_client.h:74
uint16_t x
Definition tt21100.cpp:5