ESPHome 2025.8.0b1
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#if defined(USE_ESP32)
14#include "mqtt_backend_esp32.h"
15#elif defined(USE_ESP8266)
17#elif defined(USE_LIBRETINY)
19#endif
20#include "lwip/ip_addr.h"
21
22#include <vector>
23
24namespace esphome {
25namespace mqtt {
26
29using mqtt_on_connect_callback_t = std::function<MQTTBackend::on_connect_callback_t>;
30using mqtt_on_disconnect_callback_t = std::function<MQTTBackend::on_disconnect_callback_t>;
31
36using mqtt_callback_t = std::function<void(const std::string &, const std::string &)>;
37using mqtt_json_callback_t = std::function<void(const std::string &, JsonObject)>;
38
47
50 std::string address;
51 uint16_t port;
52 std::string username;
53 std::string password;
54 std::string client_id;
56};
57
60 std::string topic;
61 std::string payload_available;
63};
64
70
76
89
97
98class MQTTComponent;
99
101 public:
103
105 void set_last_will(MQTTMessage &&message);
108
113
116
118 void set_keep_alive(uint16_t keep_alive_s);
119
128 void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
129 MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip,
130 bool clean = false);
137
138#if ASYNC_TCP_SSL_ENABLED
151 void add_ssl_fingerprint(const std::array<uint8_t, SHA1_SIZE> &fingerprint);
152#endif
153#ifdef USE_ESP32
154 void set_ca_certificate(const char *cert) { this->mqtt_backend_.set_ca_certificate(cert); }
155 void set_cl_certificate(const char *cert) { this->mqtt_backend_.set_cl_certificate(cert); }
156 void set_cl_key(const char *key) { this->mqtt_backend_.set_cl_key(key); }
157 void set_skip_cert_cn_check(bool skip_check) { this->mqtt_backend_.set_skip_cert_cn_check(skip_check); }
158#endif
160
169 void set_topic_prefix(const std::string &topic_prefix, const std::string &check_topic_prefix);
171 const std::string &get_topic_prefix() const;
172
175 void set_log_level(int level);
179
186 void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos = 0);
187
197 void subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos = 0);
198
206 void unsubscribe(const std::string &topic);
207
212 bool publish(const MQTTMessage &message);
213
220 bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false);
221
222 bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0,
223 bool retain = false);
224
231 bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false);
232
234 void setup() override;
235 void dump_config() override;
237 void loop() override;
239 float get_setup_priority() const override;
240
241 void on_message(const std::string &topic, const std::string &payload);
242
243 bool can_proceed() override;
244
246
247 void set_reboot_timeout(uint32_t reboot_timeout);
248
250
252 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
253 void enable();
254 void disable();
255
256 void on_shutdown() override;
257
258 void set_broker_address(const std::string &address) { this->credentials_.address = address; }
259 void set_broker_port(uint16_t port) { this->credentials_.port = port; }
260 void set_username(const std::string &username) { this->credentials_.username = username; }
261 void set_password(const std::string &password) { this->credentials_.password = password; }
262 void set_client_id(const std::string &client_id) { this->credentials_.client_id = client_id; }
263 void set_clean_session(const bool &clean_session) { this->credentials_.clean_session = clean_session; }
266
267 // Publish None state instead of NaN for Home Assistant
268 void set_publish_nan_as_none(bool publish_nan_as_none);
270
271 void set_wait_for_connection(bool wait_for_connection) { this->wait_for_connection_ = wait_for_connection; }
272
273 protected:
275
280#if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
281 static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg);
282#else
283 static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg);
284#endif
285
288
289 bool subscribe_(const char *topic, uint8_t qos);
292
307 .prefix = "homeassistant",
308 .retain = true,
309 .discover_ip = true,
310 .clean = false,
311 .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
312 .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
313 };
314 std::string topic_prefix_{};
316 std::string payload_buffer_;
317 int log_level_{ESPHOME_LOG_LEVEL};
318
319 std::vector<MQTTSubscription> subscriptions_;
320#if defined(USE_ESP32)
322#elif defined(USE_ESP8266)
324#elif defined(USE_LIBRETINY)
326#endif
327
330 bool dns_resolved_{false};
332 bool enable_on_boot_{true};
333 std::vector<MQTTComponent *> children_;
339
342};
343
344extern MQTTClientComponent *global_mqtt_client; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
345
346class MQTTMessageTrigger : public Trigger<std::string>, public Component {
347 public:
348 explicit MQTTMessageTrigger(std::string topic);
349
350 void set_qos(uint8_t qos);
351 void set_payload(const std::string &payload);
352 void setup() override;
353 void dump_config() override;
354 float get_setup_priority() const override;
355
356 protected:
357 std::string topic_;
358 uint8_t qos_{0};
360};
361
362class MQTTJsonMessageTrigger : public Trigger<JsonObjectConst> {
363 public:
364 explicit MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos) {
366 topic, [this](const std::string &topic, JsonObject root) { this->trigger(root); }, qos);
367 }
368};
369
370class MQTTConnectTrigger : public Trigger<> {
371 public:
373 client->set_on_connect([this](bool session_present) { this->trigger(); });
374 }
375};
376
378 public:
380 client->set_on_disconnect([this](MQTTClientDisconnectReason reason) { this->trigger(); });
381 }
382};
383
384template<typename... Ts> class MQTTPublishAction : public Action<Ts...> {
385 public:
386 MQTTPublishAction(MQTTClientComponent *parent) : parent_(parent) {}
387 TEMPLATABLE_VALUE(std::string, topic)
388 TEMPLATABLE_VALUE(std::string, payload)
389 TEMPLATABLE_VALUE(uint8_t, qos)
390 TEMPLATABLE_VALUE(bool, retain)
391
392 void play(Ts... x) override {
393 this->parent_->publish(this->topic_.value(x...), this->payload_.value(x...), this->qos_.value(x...),
394 this->retain_.value(x...));
395 }
396
397 protected:
398 MQTTClientComponent *parent_;
399};
400
401template<typename... Ts> class MQTTPublishJsonAction : public Action<Ts...> {
402 public:
404 TEMPLATABLE_VALUE(std::string, topic)
405 TEMPLATABLE_VALUE(uint8_t, qos)
406 TEMPLATABLE_VALUE(bool, retain)
407
408 void set_payload(std::function<void(Ts..., JsonObject)> payload) { this->payload_ = payload; }
409
410 void play(Ts... x) override {
411 auto f = std::bind(&MQTTPublishJsonAction<Ts...>::encode_, this, x..., std::placeholders::_1);
412 auto topic = this->topic_.value(x...);
413 auto qos = this->qos_.value(x...);
414 auto retain = this->retain_.value(x...);
415 this->parent_->publish_json(topic, f, qos, retain);
416 }
417
418 protected:
419 void encode_(Ts... x, JsonObject root) { this->payload_(x..., root); }
420 std::function<void(Ts..., JsonObject)> payload_;
422};
423
424template<typename... Ts> class MQTTConnectedCondition : public Condition<Ts...> {
425 public:
427 bool check(Ts... x) override { return this->parent_->is_connected(); }
428
429 protected:
431};
432
433template<typename... Ts> class MQTTEnableAction : public Action<Ts...> {
434 public:
436
437 void play(Ts... x) override { this->parent_->enable(); }
438
439 protected:
441};
442
443template<typename... Ts> class MQTTDisableAction : public Action<Ts...> {
444 public:
446
447 void play(Ts... x) override { this->parent_->disable(); }
448
449 protected:
451};
452
453} // namespace mqtt
454} // namespace esphome
455
456#endif // USE_MQTT
uint8_t address
Definition bl0906.h:4
virtual void play(Ts... x)=0
Base class for all automation conditions.
Definition automation.h:124
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 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)
MQTTConnectedCondition(MQTTClientComponent *parent)
MQTTDisableAction(MQTTClientComponent *parent)
void play(Ts... x) override
MQTTClientComponent * parent_
MQTTDisconnectTrigger(MQTTClientComponent *&client)
MQTTEnableAction(MQTTClientComponent *parent)
MQTTClientComponent * parent_
void play(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)
std::function< void(Ts..., JsonObject)> payload_
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:20
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_DEVICE_NAME_OBJECT_ID_GENERATOR
Definition mqtt_client.h:74
@ MQTT_NONE_OBJECT_ID_GENERATOR
Definition mqtt_client.h:73
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
Definition mqtt_client.h:66
@ MQTT_MAC_ADDRESS_UNIQUE_ID_GENERATOR
Definition mqtt_client.h:68
@ 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
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:59
std::string payload_not_available
Definition mqtt_client.h:62
std::string topic
Empty means disabled.
Definition mqtt_client.h:60
internal struct for MQTT credentials.
Definition mqtt_client.h:49
uint16_t port
The port number of the server.
Definition mqtt_client.h:51
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
Internal struct for MQTT Home Assistant discovery.
Definition mqtt_client.h:81
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
internal struct for MQTT messages.
internal struct for MQTT subscriptions.
Definition mqtt_client.h:40
uint16_t x
Definition tt21100.cpp:5