ESPHome  2022.6.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_ESP_IDF)
13 #include "mqtt_backend_idf.h"
14 #elif defined(USE_ARDUINO)
15 #include "mqtt_backend_arduino.h"
16 #endif
17 #include "lwip/ip_addr.h"
18 
19 namespace esphome {
20 namespace mqtt {
21 
24 using mqtt_on_connect_callback_t = std::function<MQTTBackend::on_connect_callback_t>;
25 using mqtt_on_disconnect_callback_t = std::function<MQTTBackend::on_disconnect_callback_t>;
26 
31 using mqtt_callback_t = std::function<void(const std::string &, const std::string &)>;
32 using mqtt_json_callback_t = std::function<void(const std::string &, JsonObject)>;
33 
36  std::string topic;
37  uint8_t qos;
39  bool subscribed;
41 };
42 
45  std::string address;
46  uint16_t port;
47  std::string username;
48  std::string password;
49  std::string client_id;
50 };
51 
53 struct Availability {
54  std::string topic;
55  std::string payload_available;
56  std::string payload_not_available;
57 };
58 
63 };
64 
69 };
70 
76  std::string prefix;
77  bool retain;
78  bool clean;
81 };
82 
88 };
89 
90 class MQTTComponent;
91 
93  public:
95 
97  void set_last_will(MQTTMessage &&message);
99  void disable_last_will();
100 
102  void set_birth_message(MQTTMessage &&message);
104  void disable_birth_message();
105 
106  void set_shutdown_message(MQTTMessage &&message);
107  void disable_shutdown_message();
108 
110  void set_keep_alive(uint16_t keep_alive_s);
111 
120  void set_discovery_info(std::string &&prefix, MQTTDiscoveryUniqueIdGenerator unique_id_generator,
121  MQTTDiscoveryObjectIdGenerator object_id_generator, bool retain, bool clean = false);
123  const MQTTDiscoveryInfo &get_discovery_info() const;
125  void disable_discovery();
126  bool is_discovery_enabled() const;
127 
128 #if ASYNC_TCP_SSL_ENABLED
129 
141  void add_ssl_fingerprint(const std::array<uint8_t, SHA1_SIZE> &fingerprint);
142 #endif
143 #ifdef USE_ESP_IDF
144  void set_ca_certificate(const char *cert) { this->mqtt_backend_.set_ca_certificate(cert); }
145  void set_skip_cert_cn_check(bool skip_check) { this->mqtt_backend_.set_skip_cert_cn_check(skip_check); }
146 #endif
147  const Availability &get_availability();
148 
157  void set_topic_prefix(const std::string &topic_prefix);
159  const std::string &get_topic_prefix() const;
160 
162  void set_log_message_template(MQTTMessage &&message);
163  void set_log_level(int level);
165  void disable_log_message();
166  bool is_log_message_enabled() const;
167 
174  void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos = 0);
175 
185  void subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos = 0);
186 
194  void unsubscribe(const std::string &topic);
195 
200  bool publish(const MQTTMessage &message);
201 
208  bool publish(const std::string &topic, const std::string &payload, uint8_t qos = 0, bool retain = false);
209 
210  bool publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos = 0,
211  bool retain = false);
212 
219  bool publish_json(const std::string &topic, const json::json_build_t &f, uint8_t qos = 0, bool retain = false);
220 
222  void setup() override;
223  void dump_config() override;
225  void loop() override;
227  float get_setup_priority() const override;
228 
229  void on_message(const std::string &topic, const std::string &payload);
230 
231  bool can_proceed() override;
232 
233  void check_connected();
234 
235  void set_reboot_timeout(uint32_t reboot_timeout);
236 
237  void register_mqtt_component(MQTTComponent *component);
238 
239  bool is_connected();
240 
241  void on_shutdown() override;
242 
243  void set_broker_address(const std::string &address) { this->credentials_.address = address; }
244  void set_broker_port(uint16_t port) { this->credentials_.port = port; }
245  void set_username(const std::string &username) { this->credentials_.username = username; }
246  void set_password(const std::string &password) { this->credentials_.password = password; }
247  void set_client_id(const std::string &client_id) { this->credentials_.client_id = client_id; }
248  void set_on_connect(mqtt_on_connect_callback_t &&callback);
249  void set_on_disconnect(mqtt_on_disconnect_callback_t &&callback);
250 
251  protected:
253  void start_connect_();
254  void start_dnslookup_();
255  void check_dnslookup_();
256 #if defined(USE_ESP8266) && LWIP_VERSION_MAJOR == 1
257  static void dns_found_callback(const char *name, ip_addr_t *ipaddr, void *callback_arg);
258 #else
259  static void dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg);
260 #endif
261 
263  void recalculate_availability_();
264 
265  bool subscribe_(const char *topic, uint8_t qos);
266  void resubscribe_subscription_(MQTTSubscription *sub);
267  void resubscribe_subscriptions_();
268 
276  bool sent_birth_message_{false};
279  Availability availability_{};
282  MQTTDiscoveryInfo discovery_info_{
283  .prefix = "homeassistant",
284  .retain = true,
285  .clean = false,
286  .unique_id_generator = MQTT_LEGACY_UNIQUE_ID_GENERATOR,
287  .object_id_generator = MQTT_NONE_OBJECT_ID_GENERATOR,
288  };
289  std::string topic_prefix_{};
291  std::string payload_buffer_;
292  int log_level_{ESPHOME_LOG_LEVEL};
293 
294  std::vector<MQTTSubscription> subscriptions_;
295 #if defined(USE_ESP_IDF)
297 #elif defined(USE_ARDUINO)
299 #endif
300 
303  bool dns_resolved_{false};
304  bool dns_resolve_error_{false};
305  std::vector<MQTTComponent *> children_;
306  uint32_t reboot_timeout_{300000};
307  uint32_t connect_begin_;
308  uint32_t last_connected_{0};
310 };
311 
312 extern MQTTClientComponent *global_mqtt_client; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
313 
314 class MQTTMessageTrigger : public Trigger<std::string>, public Component {
315  public:
316  explicit MQTTMessageTrigger(std::string topic);
317 
318  void set_qos(uint8_t qos);
319  void set_payload(const std::string &payload);
320  void setup() override;
321  void dump_config() override;
322  float get_setup_priority() const override;
323 
324  protected:
325  std::string topic_;
326  uint8_t qos_{0};
328 };
329 
330 class MQTTJsonMessageTrigger : public Trigger<JsonObjectConst> {
331  public:
332  explicit MQTTJsonMessageTrigger(const std::string &topic, uint8_t qos) {
333  global_mqtt_client->subscribe_json(
334  topic, [this](const std::string &topic, JsonObject root) { this->trigger(root); }, qos);
335  }
336 };
337 
338 class MQTTConnectTrigger : public Trigger<> {
339  public:
341  client->set_on_connect([this](bool session_present) { this->trigger(); });
342  }
343 };
344 
345 class MQTTDisconnectTrigger : public Trigger<> {
346  public:
348  client->set_on_disconnect([this](MQTTClientDisconnectReason reason) { this->trigger(); });
349  }
350 };
351 
352 template<typename... Ts> class MQTTPublishAction : public Action<Ts...> {
353  public:
354  MQTTPublishAction(MQTTClientComponent *parent) : parent_(parent) {}
355  TEMPLATABLE_VALUE(std::string, topic)
356  TEMPLATABLE_VALUE(std::string, payload)
357  TEMPLATABLE_VALUE(uint8_t, qos)
358  TEMPLATABLE_VALUE(bool, retain)
359 
360  void play(Ts... x) override {
361  this->parent_->publish(this->topic_.value(x...), this->payload_.value(x...), this->qos_.value(x...),
362  this->retain_.value(x...));
363  }
364 
365  protected:
366  MQTTClientComponent *parent_;
367 };
368 
369 template<typename... Ts> class MQTTPublishJsonAction : public Action<Ts...> {
370  public:
371  MQTTPublishJsonAction(MQTTClientComponent *parent) : parent_(parent) {}
372  TEMPLATABLE_VALUE(std::string, topic)
373  TEMPLATABLE_VALUE(uint8_t, qos)
374  TEMPLATABLE_VALUE(bool, retain)
375 
376  void set_payload(std::function<void(Ts..., JsonObject)> payload) { this->payload_ = payload; }
377 
378  void play(Ts... x) override {
379  auto f = std::bind(&MQTTPublishJsonAction<Ts...>::encode_, this, x..., std::placeholders::_1);
380  auto topic = this->topic_.value(x...);
381  auto qos = this->qos_.value(x...);
382  auto retain = this->retain_.value(x...);
383  this->parent_->publish_json(topic, f, qos, retain);
384  }
385 
386  protected:
387  void encode_(Ts... x, JsonObject root) { this->payload_(x..., root); }
388  std::function<void(Ts..., JsonObject)> payload_;
390 };
391 
392 template<typename... Ts> class MQTTConnectedCondition : public Condition<Ts...> {
393  public:
394  MQTTConnectedCondition(MQTTClientComponent *parent) : parent_(parent) {}
395  bool check(Ts... x) override { return this->parent_->is_connected(); }
396 
397  protected:
399 };
400 
401 } // namespace mqtt
402 } // namespace esphome
403 
404 #endif // USE_MQTT
void setup()
MQTTConnectedCondition(MQTTClientComponent *parent)
Definition: mqtt_client.h:394
const char * name
Definition: stm32flash.h:78
void loop()
std::function< void(Ts..., JsonObject)> payload_
Definition: mqtt_client.h:388
optional< std::string > payload_
Definition: mqtt_client.h:327
void set_client_id(const std::string &client_id)
Definition: mqtt_client.h:247
MQTTPublishAction(MQTTClientComponent *parent)
Definition: mqtt_client.h:354
std::string topic
Empty means disabled.
Definition: mqtt_client.h:54
MQTTDiscoveryUniqueIdGenerator unique_id_generator
Definition: mqtt_client.h:79
Internal struct for MQTT Home Assistant discovery.
Definition: mqtt_client.h:75
std::function< void(const std::string &, const std::string &)> mqtt_callback_t
Callback for MQTT subscriptions.
Definition: mqtt_client.h:31
std::string client_id
The client ID. Will automatically be truncated to 23 characters.
Definition: mqtt_client.h:49
void set_broker_port(uint16_t port)
Definition: mqtt_client.h:244
internal struct for MQTT messages.
Definition: mqtt_backend.h:23
std::vector< MQTTComponent * > children_
Definition: mqtt_client.h:305
void encode_(Ts... x, JsonObject root)
Definition: mqtt_client.h:387
STL namespace.
MQTTMessage last_will_
The last will message.
Definition: mqtt_client.h:272
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
Definition: mqtt_client.h:76
std::function< MQTTBackend::on_connect_callback_t > mqtt_on_connect_callback_t
Callback for MQTT events.
Definition: mqtt_client.h:24
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:145
void set_on_connect(mqtt_on_connect_callback_t &&callback)
void set_password(const std::string &password)
Definition: mqtt_client.h:246
void set_broker_address(const std::string &address)
Definition: mqtt_client.h:243
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:332
uint16_t port
The port number of the server.
Definition: mqtt_client.h:46
MQTTDiscoveryUniqueIdGenerator
available discovery unique_id generators
Definition: mqtt_client.h:60
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:371
void set_ca_certificate(const char *cert)
Definition: mqtt_client.h:144
MQTTDiscoveryObjectIdGenerator
available discovery object_id generators
Definition: mqtt_client.h:66
internal struct for MQTT subscriptions.
Definition: mqtt_client.h:35
std::string address
The address of the server without port number.
Definition: mqtt_client.h:45
Simple data struct for Home Assistant component availability.
Definition: mqtt_client.h:53
std::function< MQTTBackend::on_disconnect_callback_t > mqtt_on_disconnect_callback_t
Definition: mqtt_client.h:25
MQTTMessage birth_message_
The birth message (e.g.
Definition: mqtt_client.h:275
Definition: a4988.cpp:4
std::string payload_not_available
Definition: mqtt_client.h:56
MQTTConnectTrigger(MQTTClientComponent *&client)
Definition: mqtt_client.h:340
std::vector< MQTTSubscription > subscriptions_
Definition: mqtt_client.h:294
MQTTDiscoveryObjectIdGenerator object_id_generator
Definition: mqtt_client.h:80
void set_username(const std::string &username)
Definition: mqtt_client.h:245
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:44
MQTTDisconnectTrigger(MQTTClientComponent *&client)
Definition: mqtt_client.h:347
MQTTBackendArduino mqtt_backend_
Definition: mqtt_client.h:298
void set_on_disconnect(mqtt_on_disconnect_callback_t &&callback)
bool retain
Whether to retain discovery messages.
Definition: mqtt_client.h:77
std::function< void(const std::string &, JsonObject)> mqtt_json_callback_t
Definition: mqtt_client.h:32
MQTTComponent is the base class for all components that interact with MQTT to expose certain function...