ESPHome 2025.12.5
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 {
28namespace mqtt {
29
32using mqtt_on_connect_callback_t = std::function<MQTTBackend::on_connect_callback_t>;
33using mqtt_on_disconnect_callback_t = std::function<MQTTBackend::on_disconnect_callback_t>;
34
39using mqtt_callback_t = std::function<void(const std::string &, const std::string &)>;
40using mqtt_json_callback_t = std::function<void(const std::string &, JsonObject)>;
41
50
53 std::string address;
54 uint16_t port;
55 std::string username;
56 std::string password;
57 std::string client_id;
59};
60
63 std::string topic;
64 std::string payload_available;
66};
67
73
79
92
100
101class MQTTComponent;
102
104#ifdef USE_LOGGER
105 ,
107#endif
108{
109 public:
111
116
121
124
126 void set_keep_alive(uint16_t keep_alive_s);
127
136 void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
137 MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip,
138 bool clean = false);
145
146#if ASYNC_TCP_SSL_ENABLED
159 void add_ssl_fingerprint(const std::array<uint8_t, SHA1_SIZE> &fingerprint);
160#endif
161#ifdef USE_ESP32
162 void set_ca_certificate(const char *cert) { this->mqtt_backend_.set_ca_certificate(cert); }
163 void set_cl_certificate(const char *cert) { this->mqtt_backend_.set_cl_certificate(cert); }
164 void set_cl_key(const char *key) { this->mqtt_backend_.set_cl_key(key); }
165 void set_skip_cert_cn_check(bool skip_check) { this->mqtt_backend_.set_skip_cert_cn_check(skip_check); }
166#endif
168
177 void set_topic_prefix(const std::string &topic_prefix, const std::string &check_topic_prefix);
179 const std::string &get_topic_prefix() const;
180
183 void set_log_level(int level);
187
194 void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos = 0);
195
205 void subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos = 0);
206
214 void unsubscribe(const std::string &topic);
215
221
228 bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false);
229
230 bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0,
231 bool retain = false);
232
239 bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false);
240
242 void setup() override;
243 void dump_config() override;
245 void loop() override;
247 float get_setup_priority() const override;
248
249#ifdef USE_LOGGER
250 void on_log(uint8_t level, const char *tag, const char *message, size_t message_len) override;
251#endif
252
253 void on_message(const std::string &topic, const std::string &payload);
254
255 bool can_proceed() override;
256
258
259 void set_reboot_timeout(uint32_t reboot_timeout);
260
262
264 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
265 void enable();
266 void disable();
267
268 void on_shutdown() override;
269
270 void set_broker_address(const std::string &address) { this->credentials_.address = address; }
271 void set_broker_port(uint16_t port) { this->credentials_.port = port; }
272 void set_username(const std::string &username) { this->credentials_.username = username; }
273 void set_password(const std::string &password) { this->credentials_.password = password; }
274 void set_client_id(const std::string &client_id) { this->credentials_.client_id = client_id; }
275 void set_clean_session(const bool &clean_session) { this->credentials_.clean_session = clean_session; }
278
279 // Publish None state instead of NaN for Home Assistant
280 void set_publish_nan_as_none(bool publish_nan_as_none);
282
283 void set_wait_for_connection(bool wait_for_connection) { this->wait_for_connection_ = wait_for_connection; }
284
285 protected:
287
292#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
293 static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg);
294#else
295 static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg);
296#endif
297
300
301 bool subscribe_(const char *topic, uint8_t qos);
304
319 .prefix = "homeassistant",
320 .retain = true,
321 .discover_ip = true,
322 .clean = false,
323 .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
324 .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
325 };
326 std::string topic_prefix_{};
328 std::string payload_buffer_;
329 int log_level_{ESPHOME_LOG_LEVEL};
330
331 std::vector<MQTTSubscription> subscriptions_;
332#if defined(USE_ESP32)
334#elif defined(USE_ESP8266)
336#elif defined(USE_LIBRETINY)
338#endif
339
342 bool dns_resolved_{false};
344 bool enable_on_boot_{true};
345 std::vector<MQTTComponent *> children_;
351
354};
355
356extern MQTTClientComponent *global_mqtt_client; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
357
358class MQTTMessageTrigger : public Trigger<std::string>, public Component {
359 public:
360 explicit MQTTMessageTrigger(std::string topic);
361
362 void set_qos(uint8_t qos);
363 void set_payload(const std::string &payload);
364 void setup() override;
365 void dump_config() override;
366 float get_setup_priority() const override;
367
368 protected:
369 std::string topic_;
370 uint8_t qos_{0};
372};
373
374class MQTTJsonMessageTrigger : public Trigger<JsonObjectConst> {
375 public:
376 explicit MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos) {
378 topic, [this](const std::string &topic, JsonObject root) { this->trigger(root); }, qos);
379 }
380};
381
382class MQTTConnectTrigger : public Trigger<> {
383 public:
385 client->set_on_connect([this](bool session_present) { this->trigger(); });
386 }
387};
388
390 public:
392 client->set_on_disconnect([this](MQTTClientDisconnectReason reason) { this->trigger(); });
393 }
394};
395
396template<typename... Ts> class MQTTPublishAction : public Action<Ts...> {
397 public:
398 MQTTPublishAction(MQTTClientComponent *parent) : parent_(parent) {}
399 TEMPLATABLE_VALUE(std::string, topic)
400 TEMPLATABLE_VALUE(std::string, payload)
401 TEMPLATABLE_VALUE(uint8_t, qos)
402 TEMPLATABLE_VALUE(bool, retain)
403
404 void play(const Ts &...x) override {
405 this->parent_->publish(this->topic_.value(x...), this->payload_.value(x...), this->qos_.value(x...),
406 this->retain_.value(x...));
407 }
408
409 protected:
410 MQTTClientComponent *parent_;
411};
412
413template<typename... Ts> class MQTTPublishJsonAction : public Action<Ts...> {
414 public:
416 TEMPLATABLE_VALUE(std::string, topic)
417 TEMPLATABLE_VALUE(uint8_t, qos)
418 TEMPLATABLE_VALUE(bool, retain)
419
420 void set_payload(std::function<void(Ts..., JsonObject)> payload) { this->payload_ = payload; }
421
422 void play(const Ts &...x) override {
423 auto f = std::bind(&MQTTPublishJsonAction<Ts...>::encode_, this, x..., std::placeholders::_1);
424 auto topic = this->topic_.value(x...);
425 auto qos = this->qos_.value(x...);
426 auto retain = this->retain_.value(x...);
427 this->parent_->publish_json(topic, f, qos, retain);
428 }
429
430 protected:
431 void encode_(Ts... x, JsonObject root) { this->payload_(x..., root); }
432 std::function<void(Ts..., JsonObject)> payload_;
434};
435
436template<typename... Ts> class MQTTConnectedCondition : public Condition<Ts...> {
437 public:
439 bool check(const Ts &...x) override { return this->parent_->is_connected(); }
440
441 protected:
443};
444
445template<typename... Ts> class MQTTEnableAction : public Action<Ts...> {
446 public:
448
449 void play(const Ts &...x) override { this->parent_->enable(); }
450
451 protected:
453};
454
455template<typename... Ts> class MQTTDisableAction : public Action<Ts...> {
456 public:
458
459 void play(const Ts &...x) override { this->parent_->disable(); }
460
461 protected:
463};
464
465} // namespace mqtt
466} // namespace esphome
467
468#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:183
Interface for receiving log messages without std::function overhead.
Definition logger.h:56
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:33
MQTTDiscoveryObjectIdGenerator
available discovery object_id generators
Definition mqtt_client.h:75
@ MQTT_DEVICE_NAME_OBJECT_ID_GENERATOR
Definition mqtt_client.h:77
@ MQTT_NONE_OBJECT_ID_GENERATOR
Definition mqtt_client.h:76
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
Definition mqtt_client.h:69
@ MQTT_MAC_ADDRESS_UNIQUE_ID_GENERATOR
Definition mqtt_client.h:71
@ MQTT_LEGACY_UNIQUE_ID_GENERATOR
Definition mqtt_client.h:70
std::function< void(const std::string &, JsonObject)> mqtt_json_callback_t
Definition mqtt_client.h:40
std::function< void(const std::string &, const std::string &)> mqtt_callback_t
Callback for MQTT subscriptions.
Definition mqtt_client.h:39
MQTTClientComponent * global_mqtt_client
@ MQTT_CLIENT_DISCONNECTED
Definition mqtt_client.h:95
@ MQTT_CLIENT_RESOLVING_ADDRESS
Definition mqtt_client.h:96
std::function< MQTTBackend::on_connect_callback_t > mqtt_on_connect_callback_t
Callback for MQTT events.
Definition mqtt_client.h:32
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
Simple data struct for Home Assistant component availability.
Definition mqtt_client.h:62
std::string payload_not_available
Definition mqtt_client.h:65
std::string topic
Empty means disabled.
Definition mqtt_client.h:63
internal struct for MQTT credentials.
Definition mqtt_client.h:52
uint16_t port
The port number of the server.
Definition mqtt_client.h:54
std::string address
The address of the server without port number.
Definition mqtt_client.h:53
bool clean_session
Whether the session will be cleaned or remembered between connects.
Definition mqtt_client.h:58
std::string client_id
The client ID. Will automatically be truncated to 23 characters.
Definition mqtt_client.h:57
Internal struct for MQTT Home Assistant discovery.
Definition mqtt_client.h:84
MQTTDiscoveryUniqueIdGenerator unique_id_generator
Definition mqtt_client.h:89
bool discover_ip
Enable the Home Assistant device discovery.
Definition mqtt_client.h:87
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
Definition mqtt_client.h:85
MQTTDiscoveryObjectIdGenerator object_id_generator
Definition mqtt_client.h:90
bool retain
Whether to retain discovery messages.
Definition mqtt_client.h:86
internal struct for MQTT messages.
internal struct for MQTT subscriptions.
Definition mqtt_client.h:43
uint16_t x
Definition tt21100.cpp:5