ESPHome 2026.1.4
Loading...
Searching...
No Matches
mqtt_client.h
Go to the documentation of this file.
1#pragma once
2
4
5#ifdef USE_MQTT
6
12#include "esphome/core/log.h"
13#ifdef USE_LOGGER
15#endif
16#if defined(USE_ESP32)
17#include "mqtt_backend_esp32.h"
18#elif defined(USE_ESP8266)
20#elif defined(USE_LIBRETINY)
22#endif
23#include "lwip/ip_addr.h"
24
25#include <vector>
26
27namespace esphome::mqtt {
28
31using mqtt_on_connect_callback_t = std::function<MQTTBackend::on_connect_callback_t>;
32using mqtt_on_disconnect_callback_t = std::function<MQTTBackend::on_disconnect_callback_t>;
33
38using mqtt_callback_t = std::function<void(const std::string &, const std::string &)>;
39using mqtt_json_callback_t = std::function<void(const std::string &, JsonObject)>;
40
49
52 std::string address;
53 uint16_t port;
54 std::string username;
55 std::string password;
56 std::string client_id;
58};
59
62 std::string topic;
63 std::string payload_available;
65};
66
72
78
91
99
100class MQTTComponent;
101
103#ifdef USE_LOGGER
104 ,
106#endif
107{
108 public:
110
115
120
123
125 void set_keep_alive(uint16_t keep_alive_s);
126
135 void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
136 MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip,
137 bool clean = false);
144
145#if ASYNC_TCP_SSL_ENABLED
158 void add_ssl_fingerprint(const std::array<uint8_t, SHA1_SIZE> &fingerprint);
159#endif
160#ifdef USE_ESP32
161 void set_ca_certificate(const char *cert) { this->mqtt_backend_.set_ca_certificate(cert); }
162 void set_cl_certificate(const char *cert) { this->mqtt_backend_.set_cl_certificate(cert); }
163 void set_cl_key(const char *key) { this->mqtt_backend_.set_cl_key(key); }
164 void set_skip_cert_cn_check(bool skip_check) { this->mqtt_backend_.set_skip_cert_cn_check(skip_check); }
165#endif
167
176 void set_topic_prefix(const std::string &topic_prefix, const std::string &check_topic_prefix);
178 const std::string &get_topic_prefix() const;
179
182 void set_log_level(int level);
186
193 void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos = 0);
194
204 void subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos = 0);
205
213 void unsubscribe(const std::string &topic);
214
220
227 bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false);
228
229 bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0,
230 bool retain = false);
231
238 bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false);
239
241 void setup() override;
242 void dump_config() override;
244 void loop() override;
246 float get_setup_priority() const override;
247
248#ifdef USE_LOGGER
249 void on_log(uint8_t level, const char *tag, const char *message, size_t message_len) override;
250#endif
251
252 void on_message(const std::string &topic, const std::string &payload);
253
254 bool can_proceed() override;
255
257
258 void set_reboot_timeout(uint32_t reboot_timeout);
259
261
263 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
264 void enable();
265 void disable();
266
267 void on_shutdown() override;
268
269 void set_broker_address(const std::string &address) { this->credentials_.address = address; }
270 void set_broker_port(uint16_t port) { this->credentials_.port = port; }
271 void set_username(const std::string &username) { this->credentials_.username = username; }
272 void set_password(const std::string &password) { this->credentials_.password = password; }
273 void set_client_id(const std::string &client_id) { this->credentials_.client_id = client_id; }
274 void set_clean_session(const bool &clean_session) { this->credentials_.clean_session = clean_session; }
277
278 // Publish None state instead of NaN for Home Assistant
279 void set_publish_nan_as_none(bool publish_nan_as_none);
281
282 void set_wait_for_connection(bool wait_for_connection) { this->wait_for_connection_ = wait_for_connection; }
283
284 protected:
286
291#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
292 static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg);
293#else
294 static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg);
295#endif
296
299
300 bool subscribe_(const char *topic, uint8_t qos);
303
318 .prefix = "homeassistant",
319 .retain = true,
320 .discover_ip = true,
321 .clean = false,
322 .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
323 .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
324 };
325 std::string topic_prefix_{};
327 std::string payload_buffer_;
328 int log_level_{ESPHOME_LOG_LEVEL};
329
330 std::vector<MQTTSubscription> subscriptions_;
331#if defined(USE_ESP32)
333#elif defined(USE_ESP8266)
335#elif defined(USE_LIBRETINY)
337#endif
338
341 bool dns_resolved_{false};
343 bool enable_on_boot_{true};
344 std::vector<MQTTComponent *> children_;
350
353};
354
355extern MQTTClientComponent *global_mqtt_client; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
356
357class MQTTMessageTrigger : public Trigger<std::string>, public Component {
358 public:
359 explicit MQTTMessageTrigger(std::string topic);
360
361 void set_qos(uint8_t qos);
362 void set_payload(const std::string &payload);
363 void setup() override;
364 void dump_config() override;
365 float get_setup_priority() const override;
366
367 protected:
368 std::string topic_;
369 uint8_t qos_{0};
371};
372
373class MQTTJsonMessageTrigger : public Trigger<JsonObjectConst> {
374 public:
375 explicit MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos) {
377 topic, [this](const std::string &topic, JsonObject root) { this->trigger(root); }, qos);
378 }
379};
380
381class MQTTConnectTrigger : public Trigger<bool> {
382 public:
384 client->set_on_connect([this](bool session_present) { this->trigger(session_present); });
385 }
386};
387
388class MQTTDisconnectTrigger : public Trigger<MQTTClientDisconnectReason> {
389 public:
391 client->set_on_disconnect([this](MQTTClientDisconnectReason reason) { this->trigger(reason); });
392 }
393};
394
395template<typename... Ts> class MQTTPublishAction : public Action<Ts...> {
396 public:
397 MQTTPublishAction(MQTTClientComponent *parent) : parent_(parent) {}
398 TEMPLATABLE_VALUE(std::string, topic)
399 TEMPLATABLE_VALUE(std::string, payload)
400 TEMPLATABLE_VALUE(uint8_t, qos)
401 TEMPLATABLE_VALUE(bool, retain)
402
403 void play(const Ts &...x) override {
404 this->parent_->publish(this->topic_.value(x...), this->payload_.value(x...), this->qos_.value(x...),
405 this->retain_.value(x...));
406 }
407
408 protected:
409 MQTTClientComponent *parent_;
410};
411
412template<typename... Ts> class MQTTPublishJsonAction : public Action<Ts...> {
413 public:
415 TEMPLATABLE_VALUE(std::string, topic)
416 TEMPLATABLE_VALUE(uint8_t, qos)
417 TEMPLATABLE_VALUE(bool, retain)
418
419 void set_payload(std::function<void(Ts..., JsonObject)> payload) { this->payload_ = payload; }
420
421 void play(const Ts &...x) override {
422 auto f = std::bind(&MQTTPublishJsonAction<Ts...>::encode_, this, x..., std::placeholders::_1);
423 auto topic = this->topic_.value(x...);
424 auto qos = this->qos_.value(x...);
425 auto retain = this->retain_.value(x...);
426 this->parent_->publish_json(topic, f, qos, retain);
427 }
428
429 protected:
430 void encode_(Ts... x, JsonObject root) { this->payload_(x..., root); }
431 std::function<void(Ts..., JsonObject)> payload_;
433};
434
435template<typename... Ts> class MQTTConnectedCondition : public Condition<Ts...> {
436 public:
438 bool check(const Ts &...x) override { return this->parent_->is_connected(); }
439
440 protected:
442};
443
444template<typename... Ts> class MQTTEnableAction : public Action<Ts...> {
445 public:
447
448 void play(const Ts &...x) override { this->parent_->enable(); }
449
450 protected:
452};
453
454template<typename... Ts> class MQTTDisableAction : public Action<Ts...> {
455 public:
457
458 void play(const Ts &...x) override { this->parent_->disable(); }
459
460 protected:
462};
463
464} // namespace esphome::mqtt
465
466#endif // USE_MQTT
uint8_t address
Definition bl0906.h:4
virtual void play(const Ts &...x)=0
Base class for all automation conditions.
Definition automation.h:217
Interface for receiving log messages without std::function overhead.
Definition logger.h:62
void set_ca_certificate(const std::string &cert)
void set_cl_key(const std::string &key)
void set_cl_certificate(const std::string &cert)
void set_skip_cert_cn_check(bool skip_check)
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 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 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 set_cl_certificate(const char *cert)
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.
void set_skip_cert_cn_check(bool skip_check)
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.
void set_broker_address(const std::string &address)
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)
MQTTBackendLibreTiny mqtt_backend_
MQTTMessage birth_message_
The birth message (e.g.
std::vector< MQTTComponent * > children_
void set_on_connect(mqtt_on_connect_callback_t &&callback)
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)
void unsubscribe(const std::string &topic)
Unsubscribe from an MQTT topic.
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len) override
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)
void set_broker_port(uint16_t port)
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 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_
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...
MQTTConnectTrigger(MQTTClientComponent *&client)
bool check(const Ts &...x) override
MQTTConnectedCondition(MQTTClientComponent *parent)
MQTTDisableAction(MQTTClientComponent *parent)
void play(const Ts &...x) override
MQTTClientComponent * parent_
MQTTDisconnectTrigger(MQTTClientComponent *&client)
MQTTEnableAction(MQTTClientComponent *parent)
MQTTClientComponent * parent_
void play(const Ts &...x) override
MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos)
MQTTMessageTrigger(std::string topic)
float get_setup_priority() const override
void set_payload(const std::string &payload)
optional< std::string > payload_
MQTTPublishAction(MQTTClientComponent *parent)
TEMPLATABLE_VALUE(std::string, topic) TEMPLATABLE_VALUE(uint8_t
MQTTPublishJsonAction(MQTTClientComponent *parent)
void encode_(Ts... x, JsonObject root)
void play(const Ts &...x) override
std::function< void(Ts..., JsonObject)> payload_
const Component * component
Definition component.cpp:37
const char * message
Definition component.cpp:38
in_addr ip_addr_t
Definition ip_address.h:22
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition json_util.h:46
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_DEVICE_NAME_OBJECT_ID_GENERATOR
Definition mqtt_client.h:76
@ MQTT_NONE_OBJECT_ID_GENERATOR
Definition mqtt_client.h:75
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
Definition mqtt_client.h:68
@ MQTT_MAC_ADDRESS_UNIQUE_ID_GENERATOR
Definition mqtt_client.h:70
@ 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
Simple data struct for Home Assistant component availability.
Definition mqtt_client.h:61
std::string payload_not_available
Definition mqtt_client.h:64
std::string topic
Empty means disabled.
Definition mqtt_client.h:62
internal struct for MQTT credentials.
Definition mqtt_client.h:51
uint16_t port
The port number of the server.
Definition mqtt_client.h:53
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
Internal struct for MQTT Home Assistant discovery.
Definition mqtt_client.h:83
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
internal struct for MQTT messages.
internal struct for MQTT subscriptions.
Definition mqtt_client.h:42
uint16_t x
Definition tt21100.cpp:5