ESPHome  2022.9.2
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, "%08x", 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  JsonObject device_info = root.createNestedObject(MQTT_DEVICE);
136  device_info[MQTT_DEVICE_IDENTIFIERS] = get_mac_address();
137  device_info[MQTT_DEVICE_NAME] = node_name;
138  device_info[MQTT_DEVICE_SW_VERSION] = "esphome v" ESPHOME_VERSION " " + App.get_compilation_time();
139  device_info[MQTT_DEVICE_MODEL] = ESPHOME_BOARD;
140  device_info[MQTT_DEVICE_MANUFACTURER] = "espressif";
141  },
142  0, discovery_info.retain);
143 }
144 
145 bool MQTTComponent::get_retain() const { return this->retain_; }
146 
149 }
150 
152  return str_sanitize(str_snake_case(this->friendly_name()));
153 }
154 
155 void MQTTComponent::subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos) {
156  global_mqtt_client->subscribe(topic, std::move(callback), qos);
157 }
158 
159 void MQTTComponent::subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos) {
160  global_mqtt_client->subscribe_json(topic, callback, qos);
161 }
162 
163 MQTTComponent::MQTTComponent() = default;
164 
167 void MQTTComponent::set_custom_state_topic(const std::string &custom_state_topic) {
168  this->custom_state_topic_ = custom_state_topic;
169 }
170 void MQTTComponent::set_custom_command_topic(const std::string &custom_command_topic) {
171  this->custom_command_topic_ = custom_command_topic;
172 }
173 void MQTTComponent::set_command_retain(bool command_retain) { this->command_retain_ = command_retain; }
174 
175 void MQTTComponent::set_availability(std::string topic, std::string payload_available,
176  std::string payload_not_available) {
177  this->availability_ = make_unique<Availability>();
178  this->availability_->topic = std::move(topic);
179  this->availability_->payload_available = std::move(payload_available);
180  this->availability_->payload_not_available = std::move(payload_not_available);
181 }
184  if (this->is_internal())
185  return;
186 
187  this->setup();
188 
190 
191  if (!this->is_connected_())
192  return;
193 
194  if (this->is_discovery_enabled()) {
195  if (!this->send_discovery_()) {
196  this->schedule_resend_state();
197  }
198  }
199  if (!this->send_initial_state()) {
200  this->schedule_resend_state();
201  }
202 }
203 
205  if (this->is_internal())
206  return;
207 
208  this->loop();
209 
210  if (!this->resend_state_ || !this->is_connected_()) {
211  return;
212  }
213 
214  this->resend_state_ = false;
215  if (this->is_discovery_enabled()) {
216  if (!this->send_discovery_()) {
217  this->schedule_resend_state();
218  }
219  }
220  if (!this->send_initial_state()) {
221  this->schedule_resend_state();
222  }
223 }
225  if (this->is_internal())
226  return;
227 
228  this->dump_config();
229 }
231 std::string MQTTComponent::unique_id() { return ""; }
233 
234 // Pull these properties from EntityBase if not overridden
235 std::string MQTTComponent::friendly_name() const { return this->get_entity()->get_name(); }
236 std::string MQTTComponent::get_icon() const { return this->get_entity()->get_icon(); }
238 bool MQTTComponent::is_internal() { return this->get_entity()->is_internal(); }
239 
240 } // namespace mqtt
241 } // namespace esphome
242 
243 #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:137
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:48
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:25
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: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
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_name() const
Definition: entity_base.cpp:11
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:76
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:158
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
constexpr const char *const MQTT_STATE_TOPIC
Definition: mqtt_const.h:208
const std::string & get_icon() const
Definition: entity_base.cpp:26
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:46
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:414
constexpr const char *const MQTT_COMMAND_TOPIC
Definition: mqtt_const.h:47
bool is_internal() const
Definition: entity_base.cpp:18
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 set_name().
Definition: application.h:135
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.
const std::string & get_compilation_time() const
Definition: application.h:139
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:144
MQTTComponent()
Constructs a MQTTComponent.
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:80
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
Definition: a4988.cpp:4
std::string payload_not_available
Definition: mqtt_client.h:56
MQTTDiscoveryObjectIdGenerator object_id_generator
Definition: mqtt_client.h:80
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_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:22
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
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:77
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:32
void schedule_resend_state()
Internal method for the MQTT client base to schedule a resend of the state on reconnect.