ESPHome  2024.8.3
mqtt_client.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include "esphome/core/defines.h"
4 
5 #ifdef USE_MQTT
6 
9 #include "esphome/core/log.h"
12 #if defined(USE_ESP32)
13 #include "mqtt_backend_esp32.h"
14 #elif defined(USE_ESP8266)
15 #include "mqtt_backend_esp8266.h"
16 #elif defined(USE_LIBRETINY)
17 #include "mqtt_backend_libretiny.h"
18 #endif
19 #include "lwip/ip_addr.h"
20 
21 #include <vector>
22 
23 namespace esphome {
24 namespace mqtt {
25 
28 using mqtt_on_connect_callback_t = std::function<MQTTBackend::on_connect_callback_t>;
29 using mqtt_on_disconnect_callback_t = std::function<MQTTBackend::on_disconnect_callback_t>;
30 
35 using mqtt_callback_t = std::function<void(const std::string &, const std::string &)>;
36 using mqtt_json_callback_t = std::function<void(const std::string &, JsonObject)>;
37 
40  std::string topic;
41  uint8_t qos;
43  bool subscribed;
45 };
46 
49  std::string address;
50  uint16_t port;
51  std::string username;
52  std::string password;
53  std::string client_id;
54 };
55 
57 struct Availability {
58  std::string topic;
59  std::string payload_available;
60  std::string payload_not_available;
61 };
62 
67 };
68 
73 };
74 
80  std::string prefix;
81  bool retain;
82  bool discover_ip;
83  bool clean;
86 };
87 
93 };
94 
95 class MQTTComponent;
96 
98  public:
100 
102  void set_last_will(MQTTMessage &&message);
104  void disable_last_will();
105 
107  void set_birth_message(MQTTMessage &&message);
109  void disable_birth_message();
110 
111  void set_shutdown_message(MQTTMessage &&message);
112  void disable_shutdown_message();
113 
115  void set_keep_alive(uint16_t keep_alive_s);
116 
125  void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
126  MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool discover_ip,
127  bool clean = false);
129  const MQTTDiscoveryInfo &get_discovery_info() const;
131  void disable_discovery();
132  bool is_discovery_enabled() const;
133  bool is_discovery_ip_enabled() const;
134 
135 #if ASYNC_TCP_SSL_ENABLED
136 
148  void add_ssl_fingerprint(const std::array<uint8_t, SHA1_SIZE> &fingerprint);
149 #endif
150 #ifdef USE_ESP32
151  void set_ca_certificate(const char *cert) { this->mqtt_backend_.set_ca_certificate(cert); }
152  void set_cl_certificate(const char *cert) { this->mqtt_backend_.set_cl_certificate(cert); }
153  void set_cl_key(const char *key) { this->mqtt_backend_.set_cl_key(key); }
154  void set_skip_cert_cn_check(bool skip_check) { this->mqtt_backend_.set_skip_cert_cn_check(skip_check); }
155 #endif
156  const Availability &get_availability();
157 
166  void set_topic_prefix(const std::string &topic_prefix);
168  const std::string &get_topic_prefix() const;
169 
171  void set_log_message_template(MQTTMessage &&message);
172  void set_log_level(int level);
174  void disable_log_message();
175  bool is_log_message_enabled() const;
176 
183  void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos = 0);
184 
194  void subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos = 0);
195 
203  void unsubscribe(const std::string &topic);
204 
209  bool publish(const MQTTMessage &message);
210 
217  bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false);
218 
219  bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0,
220  bool retain = false);
221 
228  bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false);
229 
231  void setup() override;
232  void dump_config() override;
234  void loop() override;
236  float get_setup_priority() const override;
237 
238  void on_message(const std::string &topic, const std::string &payload);
239 
240  bool can_proceed() override;
241 
242  void check_connected();
243 
244  void set_reboot_timeout(uint32_t reboot_timeout);
245 
246  void register_mqtt_component(MQTTComponent *component);
247 
248  bool is_connected();
249 
250  void on_shutdown() override;
251 
252  void set_broker_address(const std::string &address) { this->credentials_.address = address; }
253  void set_broker_port(uint16_t port) { this->credentials_.port = port; }
254  void set_username(const std::string &username) { this->credentials_.username = username; }
255  void set_password(const std::string &password) { this->credentials_.password = password; }
256  void set_client_id(const std::string &client_id) { this->credentials_.client_id = client_id; }
257  void set_on_connect(mqtt_on_connect_callback_t &&callback);
258  void set_on_disconnect(mqtt_on_disconnect_callback_t &&callback);
259 
260  protected:
261  void send_device_info_();
262 
264  void start_connect_();
265  void start_dnslookup_();
266  void check_dnslookup_();
267 #if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
268  static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg);
269 #else
270  static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg);
271 #endif
272 
274  void recalculate_availability_();
275 
276  bool subscribe_(const char *topic, uint8_t qos);
277  void resubscribe_subscription_(MQTTSubscription *sub);
278  void resubscribe_subscriptions_();
279 
287  bool sent_birth_message_{false};
290  Availability availability_{};
293  MQTTDiscoveryInfo discovery_info_{
294  .prefix = "homeassistant",
295  .retain = true,
296  .discover_ip = true,
297  .clean = false,
298  .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
299  .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
300  };
301  std::string topic_prefix_{};
303  std::string payload_buffer_;
304  int log_level_{ESPHOME_LOG_LEVEL};
305 
306  std::vector<MQTTSubscription> subscriptions_;
307 #if defined(USE_ESP32)
309 #elif defined(USE_ESP8266)
311 #elif defined(USE_LIBRETINY)
313 #endif
314 
317  bool dns_resolved_{false};
318  bool dns_resolve_error_{false};
319  std::vector<MQTTComponent *> children_;
320  uint32_t reboot_timeout_{300000};
321  uint32_t connect_begin_;
322  uint32_t last_connected_{0};
324 };
325 
326 extern MQTTClientComponent *global_mqtt_client; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
327 
328 class MQTTMessageTrigger : public Trigger<std::string>, public Component {
329  public:
330  explicit MQTTMessageTrigger(std::string topic);
331 
332  void set_qos(uint8_t qos);
333  void set_payload(const std::string &payload);
334  void setup() override;
335  void dump_config() override;
336  float get_setup_priority() const override;
337 
338  protected:
339  std::string topic_;
340  uint8_t qos_{0};
342 };
343 
344 class MQTTJsonMessageTrigger : public Trigger<JsonObjectConst> {
345  public:
346  explicit MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos) {
347  global_mqtt_client->subscribe_json(
348  topic, [this](const std::string &topic, JsonObject root) { this->trigger(root); }, qos);
349  }
350 };
351 
352 class MQTTConnectTrigger : public Trigger<> {
353  public:
355  client->set_on_connect([this](bool session_present) { this->trigger(); });
356  }
357 };
358 
359 class MQTTDisconnectTrigger : public Trigger<> {
360  public:
362  client->set_on_disconnect([this](MQTTClientDisconnectReason reason) { this->trigger(); });
363  }
364 };
365 
366 template<typename... Ts> class MQTTPublishAction : public Action<Ts...> {
367  public:
368  MQTTPublishAction(MQTTClientComponent *parent) : parent_(parent) {}
369  TEMPLATABLE_VALUE(std::string, topic)
370  TEMPLATABLE_VALUE(std::string, payload)
371  TEMPLATABLE_VALUE(uint8_t, qos)
372  TEMPLATABLE_VALUE(bool, retain)
373 
374  void play(Ts... x) override {
375  this->parent_->publish(this->topic_.value(x...), this->payload_.value(x...), this->qos_.value(x...),
376  this->retain_.value(x...));
377  }
378 
379  protected:
380  MQTTClientComponent *parent_;
381 };
382 
383 template<typename... Ts> class MQTTPublishJsonAction : public Action<Ts...> {
384  public:
385  MQTTPublishJsonAction(MQTTClientComponent *parent) : parent_(parent) {}
386  TEMPLATABLE_VALUE(std::string, topic)
387  TEMPLATABLE_VALUE(uint8_t, qos)
388  TEMPLATABLE_VALUE(bool, retain)
389 
390  void set_payload(std::function<void(Ts..., JsonObject)> payload) { this->payload_ = payload; }
391 
392  void play(Ts... x) override {
393  auto f = std::bind(&MQTTPublishJsonAction<Ts...>::encode_, this, x..., std::placeholders::_1);
394  auto topic = this->topic_.value(x...);
395  auto qos = this->qos_.value(x...);
396  auto retain = this->retain_.value(x...);
397  this->parent_->publish_json(topic, f, qos, retain);
398  }
399 
400  protected:
401  void encode_(Ts... x, JsonObject root) { this->payload_(x..., root); }
402  std::function<void(Ts..., JsonObject)> payload_;
404 };
405 
406 template<typename... Ts> class MQTTConnectedCondition : public Condition<Ts...> {
407  public:
408  MQTTConnectedCondition(MQTTClientComponent *parent) : parent_(parent) {}
409  bool check(Ts... x) override { return this->parent_->is_connected(); }
410 
411  protected:
413 };
414 
415 } // namespace mqtt
416 } // namespace esphome
417 
418 #endif // USE_MQTT
void setup()
MQTTConnectedCondition(MQTTClientComponent *parent)
Definition: mqtt_client.h:408
const char * name
Definition: stm32flash.h:78
void loop()
std::function< void(Ts..., JsonObject)> payload_
Definition: mqtt_client.h:402
optional< std::string > payload_
Definition: mqtt_client.h:341
void set_client_id(const std::string &client_id)
Definition: mqtt_client.h:256
MQTTPublishAction(MQTTClientComponent *parent)
Definition: mqtt_client.h:368
std::string topic
Empty means disabled.
Definition: mqtt_client.h:58
MQTTDiscoveryUniqueIdGenerator unique_id_generator
Definition: mqtt_client.h:84
Internal struct for MQTT Home Assistant discovery.
Definition: mqtt_client.h:79
void set_cl_certificate(const char *cert)
Definition: mqtt_client.h:152
std::function< void(const std::string &, const std::string &)> mqtt_callback_t
Callback for MQTT subscriptions.
Definition: mqtt_client.h:35
std::string client_id
The client ID. Will automatically be truncated to 23 characters.
Definition: mqtt_client.h:53
void set_broker_port(uint16_t port)
Definition: mqtt_client.h:253
uint16_t x
Definition: tt21100.cpp:17
internal struct for MQTT messages.
Definition: mqtt_backend.h:24
std::vector< MQTTComponent * > children_
Definition: mqtt_client.h:319
void encode_(Ts... x, JsonObject root)
Definition: mqtt_client.h:401
STL namespace.
MQTTMessage last_will_
The last will message.
Definition: mqtt_client.h:283
bool discover_ip
Enable the Home Assistant device discovery.
Definition: mqtt_client.h:82
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
Definition: mqtt_client.h:80
std::function< MQTTBackend::on_connect_callback_t > mqtt_on_connect_callback_t
Callback for MQTT events.
Definition: mqtt_client.h:28
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition: util.cpp:15
void set_skip_cert_cn_check(bool skip_check)
Definition: mqtt_client.h:154
void set_on_connect(mqtt_on_connect_callback_t &&callback)
void set_password(const std::string &password)
Definition: mqtt_client.h:255
void set_broker_address(const std::string &address)
Definition: mqtt_client.h:252
MQTTClientComponent * global_mqtt_client
Base class for all automation conditions.
Definition: automation.h:74
MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos)
Definition: mqtt_client.h:346
MQTTBackendESP8266 mqtt_backend_
Definition: mqtt_client.h:310
uint16_t port
The port number of the server.
Definition: mqtt_client.h:50
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
Definition: mqtt_client.h:64
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition: json_util.h:20
MQTTPublishJsonAction(MQTTClientComponent *parent)
Definition: mqtt_client.h:385
void set_ca_certificate(const char *cert)
Definition: mqtt_client.h:151
MQTTDiscoveryObjectIdGenerator
available discovery object_id generators
Definition: mqtt_client.h:70
internal struct for MQTT subscriptions.
Definition: mqtt_client.h:39
MQTTBackendLibreTiny mqtt_backend_
Definition: mqtt_client.h:312
std::string address
The address of the server without port number.
Definition: mqtt_client.h:49
Simple data struct for Home Assistant component availability.
Definition: mqtt_client.h:57
std::function< MQTTBackend::on_disconnect_callback_t > mqtt_on_disconnect_callback_t
Definition: mqtt_client.h:29
MQTTMessage birth_message_
The birth message (e.g.
Definition: mqtt_client.h:286
in_addr ip_addr_t
Definition: ip_address.h:22
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
std::string payload_not_available
Definition: mqtt_client.h:60
MQTTConnectTrigger(MQTTClientComponent *&client)
Definition: mqtt_client.h:354
std::vector< MQTTSubscription > subscriptions_
Definition: mqtt_client.h:306
MQTTDiscoveryObjectIdGenerator object_id_generator
Definition: mqtt_client.h:85
void set_cl_key(const char *key)
Definition: mqtt_client.h:153
void set_username(const std::string &username)
Definition: mqtt_client.h:254
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.
internal struct for MQTT credentials.
Definition: mqtt_client.h:48
MQTTDisconnectTrigger(MQTTClientComponent *&client)
Definition: mqtt_client.h:361
void set_on_disconnect(mqtt_on_disconnect_callback_t &&callback)
bool retain
Whether to retain discovery messages.
Definition: mqtt_client.h:81
std::function< void(const std::string &, JsonObject)> mqtt_json_callback_t
Definition: mqtt_client.h:36
MQTTComponent is the base class for all components that interact with MQTT to expose certain function...