ESPHome  2023.8.3
mqtt_component.cpp
Go to the documentation of this file.
1 #include "mqtt_component.h"
2 
3 #ifdef USE_MQTT
4 
5 #include "esphome/core/log.h"
7 #include "esphome/core/helpers.h"
8 #include "esphome/core/version.h"
9 
10 #include "mqtt_const.h"
11 
12 namespace esphome {
13 namespace mqtt {
14 
15 static const char *const TAG = "mqtt.component";
16 
17 void MQTTComponent::set_retain(bool retain) { this->retain_ = retain; }
18 
19 std::string MQTTComponent::get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const {
20  std::string sanitized_name = str_sanitize(App.get_name());
21  return discovery_info.prefix + "/" + this->component_type() + "/" + sanitized_name + "/" +
22  this->get_default_object_id_() + "/config";
23 }
24 
25 std::string MQTTComponent::get_default_topic_for_(const std::string &suffix) const {
26  return global_mqtt_client->get_topic_prefix() + "/" + this->component_type() + "/" + this->get_default_object_id_() +
27  "/" + suffix;
28 }
29 
30 std::string MQTTComponent::get_state_topic_() const {
31  if (this->custom_state_topic_.empty())
32  return this->get_default_topic_for_("state");
33  return this->custom_state_topic_;
34 }
35 
36 std::string MQTTComponent::get_command_topic_() const {
37  if (this->custom_command_topic_.empty())
38  return this->get_default_topic_for_("command");
39  return this->custom_command_topic_;
40 }
41 
42 bool MQTTComponent::publish(const std::string &topic, const std::string &payload) {
43  if (topic.empty())
44  return false;
45  return global_mqtt_client->publish(topic, payload, 0, this->retain_);
46 }
47 
48 bool MQTTComponent::publish_json(const std::string &topic, const json::json_build_t &f) {
49  if (topic.empty())
50  return false;
51  return global_mqtt_client->publish_json(topic, f, 0, this->retain_);
52 }
53 
55  const MQTTDiscoveryInfo &discovery_info = global_mqtt_client->get_discovery_info();
56 
57  if (discovery_info.clean) {
58  ESP_LOGV(TAG, "'%s': Cleaning discovery...", this->friendly_name().c_str());
59  return global_mqtt_client->publish(this->get_discovery_topic_(discovery_info), "", 0, 0, true);
60  }
61 
62  ESP_LOGV(TAG, "'%s': Sending discovery...", this->friendly_name().c_str());
63 
65  this->get_discovery_topic_(discovery_info),
66  [this](JsonObject root) {
67  SendDiscoveryConfig config;
68  config.state_topic = true;
69  config.command_topic = true;
70 
71  this->send_discovery(root, config);
72 
73  // Fields from EntityBase
74  root[MQTT_NAME] = this->friendly_name();
75  if (this->is_disabled_by_default())
76  root[MQTT_ENABLED_BY_DEFAULT] = false;
77  if (!this->get_icon().empty())
78  root[MQTT_ICON] = this->get_icon();
79 
80  switch (this->get_entity()->get_entity_category()) {
82  break;
84  root[MQTT_ENTITY_CATEGORY] = "config";
85  break;
87  root[MQTT_ENTITY_CATEGORY] = "diagnostic";
88  break;
89  }
90 
91  if (config.state_topic)
92  root[MQTT_STATE_TOPIC] = this->get_state_topic_();
93  if (config.command_topic)
94  root[MQTT_COMMAND_TOPIC] = this->get_command_topic_();
95  if (this->command_retain_)
96  root[MQTT_COMMAND_RETAIN] = true;
97 
98  if (this->availability_ == nullptr) {
99  if (!global_mqtt_client->get_availability().topic.empty()) {
105  }
106  } else if (!this->availability_->topic.empty()) {
107  root[MQTT_AVAILABILITY_TOPIC] = this->availability_->topic;
108  if (this->availability_->payload_available != "online")
109  root[MQTT_PAYLOAD_AVAILABLE] = this->availability_->payload_available;
110  if (this->availability_->payload_not_available != "offline")
111  root[MQTT_PAYLOAD_NOT_AVAILABLE] = this->availability_->payload_not_available;
112  }
113 
114  std::string unique_id = this->unique_id();
115  const MQTTDiscoveryInfo &discovery_info = global_mqtt_client->get_discovery_info();
116  if (!unique_id.empty()) {
117  root[MQTT_UNIQUE_ID] = unique_id;
118  } else {
120  char friendly_name_hash[9];
121  sprintf(friendly_name_hash, "%08" PRIx32, fnv1_hash(this->friendly_name()));
122  friendly_name_hash[8] = 0; // ensure the hash-string ends with null
123  root[MQTT_UNIQUE_ID] = get_mac_address() + "-" + this->component_type() + "-" + friendly_name_hash;
124  } else {
125  // default to almost-unique ID. It's a hack but the only way to get that
126  // gorgeous device registry view.
127  root[MQTT_UNIQUE_ID] = "ESP" + this->component_type() + this->get_default_object_id_();
128  }
129  }
130 
131  const std::string &node_name = App.get_name();
133  root[MQTT_OBJECT_ID] = node_name + "_" + this->get_default_object_id_();
134 
135  std::string node_friendly_name = App.get_friendly_name();
136  if (node_friendly_name.empty()) {
137  node_friendly_name = node_name;
138  }
139 
140  JsonObject device_info = root.createNestedObject(MQTT_DEVICE);
141  device_info[MQTT_DEVICE_IDENTIFIERS] = get_mac_address();
142  device_info[MQTT_DEVICE_NAME] = node_friendly_name;
143  device_info[MQTT_DEVICE_SW_VERSION] = "esphome v" ESPHOME_VERSION " " + App.get_compilation_time();
144  device_info[MQTT_DEVICE_MODEL] = ESPHOME_BOARD;
145  device_info[MQTT_DEVICE_MANUFACTURER] = "espressif";
146  },
147  0, discovery_info.retain);
148 }
149 
150 bool MQTTComponent::get_retain() const { return this->retain_; }
151 
154 }
155 
157  return str_sanitize(str_snake_case(this->friendly_name()));
158 }
159 
160 void MQTTComponent::subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos) {
161  global_mqtt_client->subscribe(topic, std::move(callback), qos);
162 }
163 
164 void MQTTComponent::subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos) {
165  global_mqtt_client->subscribe_json(topic, callback, qos);
166 }
167 
168 MQTTComponent::MQTTComponent() = default;
169 
172 void MQTTComponent::set_custom_state_topic(const std::string &custom_state_topic) {
173  this->custom_state_topic_ = custom_state_topic;
174 }
175 void MQTTComponent::set_custom_command_topic(const std::string &custom_command_topic) {
176  this->custom_command_topic_ = custom_command_topic;
177 }
178 void MQTTComponent::set_command_retain(bool command_retain) { this->command_retain_ = command_retain; }
179 
180 void MQTTComponent::set_availability(std::string topic, std::string payload_available,
181  std::string payload_not_available) {
182  this->availability_ = make_unique<Availability>();
183  this->availability_->topic = std::move(topic);
184  this->availability_->payload_available = std::move(payload_available);
185  this->availability_->payload_not_available = std::move(payload_not_available);
186 }
189  if (this->is_internal())
190  return;
191 
192  this->setup();
193 
195 
196  if (!this->is_connected_())
197  return;
198 
199  if (this->is_discovery_enabled()) {
200  if (!this->send_discovery_()) {
201  this->schedule_resend_state();
202  }
203  }
204  if (!this->send_initial_state()) {
205  this->schedule_resend_state();
206  }
207 }
208 
210  if (this->is_internal())
211  return;
212 
213  this->loop();
214 
215  if (!this->resend_state_ || !this->is_connected_()) {
216  return;
217  }
218 
219  this->resend_state_ = false;
220  if (this->is_discovery_enabled()) {
221  if (!this->send_discovery_()) {
222  this->schedule_resend_state();
223  }
224  }
225  if (!this->send_initial_state()) {
226  this->schedule_resend_state();
227  }
228 }
230  if (this->is_internal())
231  return;
232 
233  this->dump_config();
234 }
236 std::string MQTTComponent::unique_id() { return ""; }
238 
239 // Pull these properties from EntityBase if not overridden
240 std::string MQTTComponent::friendly_name() const { return this->get_entity()->get_name(); }
241 std::string MQTTComponent::get_icon() const { return this->get_entity()->get_icon(); }
243 bool MQTTComponent::is_internal() { return this->get_entity()->is_internal(); }
244 
245 } // namespace mqtt
246 } // namespace esphome
247 
248 #endif // USE_MQTT
float get_setup_priority() const override
MQTT_COMPONENT setup priority.
const Availability & get_availability()
std::string str_snake_case(const std::string &str)
Convert the string to snake case (lowercase with underscores).
Definition: helpers.cpp:264
void set_custom_command_topic(const std::string &custom_command_topic)
Set a custom command topic. Set to "" for default behavior.
virtual void loop()
This method will be called repeatedly.
Definition: component.cpp:49
std::string get_default_topic_for_(const std::string &suffix) const
Get this components state/command/...
constexpr const char *const MQTT_DEVICE_SW_VERSION
Definition: mqtt_const.h:261
const float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
Definition: component.cpp:26
constexpr const char *const MQTT_DEVICE_MODEL
Definition: mqtt_const.h:260
constexpr const char *const MQTT_NAME
Definition: mqtt_const.h:109
std::string topic
Empty means disabled.
Definition: mqtt_client.h:56
MQTTDiscoveryUniqueIdGenerator unique_id_generator
Definition: mqtt_client.h:81
Internal struct for MQTT Home Assistant discovery.
Definition: mqtt_client.h:77
std::function< void(const std::string &, const std::string &)> mqtt_callback_t
Callback for MQTT subscriptions.
Definition: mqtt_client.h:33
constexpr const char *const MQTT_ENTITY_CATEGORY
Definition: mqtt_const.h:520
bool state_topic
If the state topic should be included. Defaults to true.
constexpr const char *const MQTT_PAYLOAD_AVAILABLE
Definition: mqtt_const.h:129
const std::string & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
Definition: application.h:155
constexpr const char *const MQTT_PAYLOAD_NOT_AVAILABLE
Definition: mqtt_const.h:139
void disable_discovery()
Disable discovery. Sets friendly name to "".
constexpr const char *const MQTT_DEVICE_IDENTIFIERS
Definition: mqtt_const.h:257
std::string prefix
The Home Assistant discovery prefix. Empty means disabled.
Definition: mqtt_client.h:78
bool publish_json(const std::string &topic, const json::json_build_t &f)
Construct and send a JSON MQTT message.
const std::string & get_topic_prefix() const
Get the topic prefix of this device, using default if necessary.
virtual void dump_config()
Definition: component.cpp:163
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.
bool command_topic
If the command topic should be included. Default to true.
bool publish(const std::string &topic, const std::string &payload)
Send a MQTT message.
virtual void send_discovery(JsonObject root, SendDiscoveryConfig &config)=0
Send discovery info the Home Assistant, override this.
MQTTClientComponent * global_mqtt_client
std::string get_icon() const
Definition: entity_base.cpp:30
constexpr const char *const MQTT_STATE_TOPIC
Definition: mqtt_const.h:208
void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos=0)
Subscribe to a MQTT topic.
void set_retain(bool retain)
Set whether state message should be retained.
constexpr const char *const MQTT_DEVICE_NAME
Definition: mqtt_const.h:258
void set_availability(std::string topic, std::string payload_available, std::string payload_not_available)
Set the Home Assistant availability data.
virtual void setup()
Where the component&#39;s initialization should happen.
Definition: component.cpp:47
virtual const EntityBase * get_entity() const =0
Gets the Entity served by this MQTT component.
virtual std::string component_type() const =0
Override this method to return the component type (e.g. "light", "sensor", ...)
void register_mqtt_component(MQTTComponent *component)
bool publish(const MQTTMessage &message)
Publish a MQTTMessage.
std::string get_mac_address()
Get the device MAC address as a string, in lowercase hex notation.
Definition: helpers.cpp:560
constexpr const char *const MQTT_COMMAND_TOPIC
Definition: mqtt_const.h:47
bool is_internal() const
Definition: entity_base.cpp:22
Simple Helper struct used for Home Assistant MQTT send_discovery().
virtual bool send_initial_state()=0
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition: json_util.h:20
Application App
Global storage of Application pointer - only one Application can exist.
const std::string & get_name() const
Get the name of this Application set by pre_setup().
Definition: application.h:152
constexpr const char *const MQTT_DEVICE_MANUFACTURER
Definition: mqtt_const.h:259
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.
constexpr const char *const MQTT_COMMAND_RETAIN
Definition: mqtt_const.h:48
const MQTTDiscoveryInfo & get_discovery_info() const
Get Home Assistant discovery info.
void call_setup() override
Override setup_ so that we can call send_discovery() when needed.
std::string str_sanitize(const std::string &str)
Sanitizes the input string by removing all characters but alphanumerics, dashes and underscores...
Definition: helpers.cpp:271
MQTTComponent()
Constructs a MQTTComponent.
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:172
void set_custom_state_topic(const std::string &custom_state_topic)
Set a custom state topic. Set to "" for default behavior.
virtual std::string get_icon() const
Get the icon field of this component.
virtual bool is_disabled_by_default() const
Get whether the underlying Entity is disabled by default.
constexpr const char *const MQTT_ICON
Definition: mqtt_const.h:85
std::unique_ptr< Availability > availability_
virtual std::string friendly_name() const
Get the friendly name of this MQTT component.
constexpr const char *const MQTT_OBJECT_ID
Definition: mqtt_const.h:110
std::string payload_not_available
Definition: mqtt_client.h:58
MQTTDiscoveryObjectIdGenerator object_id_generator
Definition: mqtt_client.h:82
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.
constexpr const char *const MQTT_ENABLED_BY_DEFAULT
Definition: mqtt_const.h:58
constexpr const char *const MQTT_UNIQUE_ID
Definition: mqtt_const.h:243
constexpr const char *const MQTT_AVAILABILITY_TOPIC
Definition: mqtt_const.h:20
std::string get_state_topic_() const
Get the MQTT topic that new states will be shared to.
virtual std::string unique_id()
A unique ID for this MQTT component, empty for no unique id.
void set_command_retain(bool command_retain)
Set whether command message should be retained.
std::string get_compilation_time() const
Definition: application.h:161
std::string get_default_object_id_() const
Generate the Home Assistant MQTT discovery object id by automatically transforming the friendly name...
std::string get_command_topic_() const
Get the MQTT topic for listening to commands.
bool is_disabled_by_default() const
Definition: entity_base.cpp:26
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.
constexpr const char *const MQTT_DEVICE
Definition: mqtt_const.h:54
const StringRef & get_name() const
Definition: entity_base.cpp:10
std::string get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const
Helper method to get the discovery topic for this component.
bool retain
Whether to retain discovery messages.
Definition: mqtt_client.h:79
bool send_discovery_()
Internal method to start sending discovery info, this will call send_discovery(). ...
std::function< void(const std::string &, JsonObject)> mqtt_json_callback_t
Definition: mqtt_client.h:34
void schedule_resend_state()
Internal method for the MQTT client base to schedule a resend of the state on reconnect.