ESPHome 2026.1.4
Loading...
Searching...
No Matches
mqtt_component.h
Go to the documentation of this file.
1#pragma once
2
4
5#ifdef USE_MQTT
6
7#include <memory>
8
13#include "mqtt_client.h"
14
15namespace esphome::mqtt {
16
19 bool state_topic{true};
20 bool command_topic{true};
21};
22
23// Max lengths for stack-based topic building (must match mqtt_component.cpp)
24static constexpr size_t MQTT_COMPONENT_TYPE_MAX_LEN = 20;
25static constexpr size_t MQTT_SUFFIX_MAX_LEN = 32;
26
27#define LOG_MQTT_COMPONENT(state_topic, command_topic) \
28 if (state_topic) { \
29 ESP_LOGCONFIG(TAG, " State Topic: '%s'", this->get_state_topic_().c_str()); \
30 } \
31 if (command_topic) { \
32 ESP_LOGCONFIG(TAG, " Command Topic: '%s'", this->get_command_topic_().c_str()); \
33 }
34
35// Macro to define component_type() with compile-time length verification
36// Usage: MQTT_COMPONENT_TYPE(MQTTSensorComponent, "sensor")
37#define MQTT_COMPONENT_TYPE(class_name, type_str) \
38 const char *class_name::component_type() const { return type_str; } \
39 static_assert(sizeof(type_str) - 1 <= MQTT_COMPONENT_TYPE_MAX_LEN, \
40 #class_name "::component_type() exceeds MQTT_COMPONENT_TYPE_MAX_LEN");
41
42// Macro to define custom topic getter/setter with compile-time suffix length verification
43#define MQTT_COMPONENT_CUSTOM_TOPIC_(name, type) \
44 static_assert(sizeof(#name "/" #type) - 1 <= MQTT_SUFFIX_MAX_LEN, \
45 "topic suffix " #name "/" #type " exceeds MQTT_SUFFIX_MAX_LEN"); \
46\
47 protected: \
48 std::string custom_##name##_##type##_topic_{}; \
49\
50 public: \
51 void set_custom_##name##_##type##_topic(const std::string &topic) { this->custom_##name##_##type##_topic_ = topic; } \
52 std::string get_##name##_##type##_topic() const { \
53 if (this->custom_##name##_##type##_topic_.empty()) \
54 return this->get_default_topic_for_(#name "/" #type); \
55 return this->custom_##name##_##type##_topic_; \
56 }
57
58#define MQTT_COMPONENT_CUSTOM_TOPIC(name, type) MQTT_COMPONENT_CUSTOM_TOPIC_(name, type)
59
76class MQTTComponent : public Component {
77 public:
79 explicit MQTTComponent();
80
82 void call_setup() override;
83
84 void call_loop() override;
85
86 void call_dump_config() override;
87
89 virtual void send_discovery(JsonObject root, SendDiscoveryConfig &config) = 0;
90
91 virtual bool send_initial_state() = 0;
92
93 virtual bool is_internal();
94
96 void set_qos(uint8_t qos);
97 uint8_t get_qos() const;
98
100 void set_retain(bool retain);
101 bool get_retain() const;
102
104 void disable_discovery();
105 bool is_discovery_enabled() const;
106
108 void set_subscribe_qos(uint8_t qos);
109
111 virtual const char *component_type() const = 0;
112
114 template<typename T> void set_custom_state_topic(T &&custom_state_topic) {
115 this->custom_state_topic_ = std::forward<T>(custom_state_topic);
116 }
117 template<typename T> void set_custom_command_topic(T &&custom_command_topic) {
118 this->custom_command_topic_ = std::forward<T>(custom_command_topic);
119 }
121 void set_command_retain(bool command_retain);
122
124 float get_setup_priority() const override;
125
130 void set_availability(std::string topic, std::string payload_available, std::string payload_not_available);
132
135
141 bool publish(const std::string &topic, const std::string &payload);
142
149 bool publish(const std::string &topic, const char *payload, size_t payload_length);
150
156 bool publish_json(const std::string &topic, const json::json_build_t &f);
157
164 void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos = 0);
165
175 void subscribe_json(const std::string &topic, const mqtt_json_callback_t &callback, uint8_t qos = 0);
176
177 protected:
179 std::string get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const;
180
186 std::string get_default_topic_for_(const std::string &suffix) const;
187
191 virtual const EntityBase *get_entity() const = 0;
192
194 std::string friendly_name_() const;
195
197 StringRef get_icon_ref_() const;
198
200 bool is_disabled_by_default_() const;
201
203 std::string get_state_topic_() const;
204
206 std::string get_command_topic_() const;
207
208 bool is_connected_() const;
209
211 bool send_discovery_();
212
213 // ========== INTERNAL METHODS ==========
214 // (In most use cases you won't need these)
216 StringRef get_default_object_id_to_(std::span<char, OBJECT_ID_MAX_LEN> buf) const;
217
220
221 std::unique_ptr<Availability> availability_;
222
223 bool command_retain_{false};
224 bool retain_{true};
225 uint8_t qos_{0};
226 uint8_t subscribe_qos_{0};
228 bool resend_state_{false};
229};
230
231} // namespace esphome::mqtt
232
233#endif // USE_MQTt
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
MQTTComponent is the base class for all components that interact with MQTT to expose certain function...
TemplatableValue< std::string > custom_state_topic_
TemplatableValue< std::string > custom_command_topic_
std::unique_ptr< Availability > availability_
bool is_disabled_by_default_() const
Get whether the underlying Entity is disabled by default.
MQTTComponent()
Constructs a MQTTComponent.
void set_custom_command_topic(T &&custom_command_topic)
void set_qos(uint8_t qos)
Set QOS for state messages.
void schedule_resend_state()
Internal method for the MQTT client base to schedule a resend of the state on reconnect.
bool publish(const std::string &topic, const std::string &payload)
Send a MQTT message.
void set_command_retain(bool command_retain)
Set whether command message should be retained.
bool send_discovery_()
Internal method to start sending discovery info, this will call send_discovery().
void set_subscribe_qos(uint8_t qos)
Set the QOS for subscribe messages (used in discovery).
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 call_setup() override
Override setup_ so that we can call send_discovery() when needed.
bool publish_json(const std::string &topic, const json::json_build_t &f)
Construct and send a JSON MQTT message.
std::string get_discovery_topic_(const MQTTDiscoveryInfo &discovery_info) const
Helper method to get the discovery topic for this component.
std::string get_default_topic_for_(const std::string &suffix) const
Get this components state/command/... topic.
StringRef get_default_object_id_to_(std::span< char, OBJECT_ID_MAX_LEN > buf) const
Get the object ID for this MQTT component, writing to the provided buffer.
void set_retain(bool retain)
Set whether state message should be retained.
virtual const EntityBase * get_entity() const =0
Gets the Entity served by this MQTT component.
std::string get_state_topic_() const
Get the MQTT topic that new states will be shared to.
virtual void send_discovery(JsonObject root, SendDiscoveryConfig &config)=0
Send discovery info the Home Assistant, override this.
std::string friendly_name_() const
Get the friendly name of this MQTT component.
void set_custom_state_topic(T &&custom_state_topic)
Set a custom state topic. Do not set for default behavior.
virtual bool send_initial_state()=0
void disable_discovery()
Disable discovery. Sets friendly name to "".
float get_setup_priority() const override
MQTT_COMPONENT setup priority.
void set_availability(std::string topic, std::string payload_available, std::string payload_not_available)
Set the Home Assistant availability data.
std::string get_command_topic_() const
Get the MQTT topic for listening to commands.
void subscribe(const std::string &topic, mqtt_callback_t callback, uint8_t qos=0)
Subscribe to a MQTT topic.
virtual const char * component_type() const =0
Override this method to return the component type (e.g. "light", "sensor", ...)
StringRef get_icon_ref_() const
Get the icon field of this component as StringRef.
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition json_util.h:46
std::function< void(const std::string &, JsonObject)> mqtt_json_callback_t
Definition mqtt_client.h:39
std::function< void(const std::string &, const std::string &)> mqtt_callback_t
Callback for MQTT subscriptions.
Definition mqtt_client.h:38
Internal struct for MQTT Home Assistant discovery.
Definition mqtt_client.h:83
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.
bool state_topic
If the state topic should be included. Defaults to true.