ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
mqtt_cover.cpp
Go to the documentation of this file.
1#include "mqtt_cover.h"
2#include "esphome/core/log.h"
4
5#include "mqtt_const.h"
6
7#ifdef USE_MQTT
8#ifdef USE_COVER
9
10namespace esphome::mqtt {
11
12ESPHOME_LOG_TAG(TAG, "mqtt.cover");
13
14using namespace esphome::cover;
15
16static ProgmemStr cover_state_to_mqtt_str(CoverOperation operation, float position, bool supports_position) {
17 if (operation == COVER_OPERATION_OPENING)
18 return ESPHOME_F("opening");
19 if (operation == COVER_OPERATION_CLOSING)
20 return ESPHOME_F("closing");
21 if (position == COVER_CLOSED)
22 return ESPHOME_F("closed");
23 if (position == COVER_OPEN)
24 return ESPHOME_F("open");
25 if (supports_position)
26 return ESPHOME_F("open");
27 return ESPHOME_F("unknown");
28}
29
32 auto traits = this->cover_->get_traits();
33 this->cover_->add_on_state_callback([this]() { this->publish_state(); });
34 this->subscribe(this->command_topic_source_(), [this](const std::string &topic, const std::string &payload) {
35 auto call = this->cover_->make_call();
36 call.set_command(payload.c_str());
37 call.perform();
38 });
39 if (traits.get_supports_position()) {
40 this->subscribe(this->get_position_command_topic_source(),
41 [this](const std::string &topic, const std::string &payload) {
42 auto value = parse_number<float>(payload);
43 if (!value.has_value()) {
44 ESP_LOGW(TAG, "Invalid position value: '%s'", payload.c_str());
45 return;
46 }
47 auto call = this->cover_->make_call();
48 call.set_position(*value / 100.0f);
49 call.perform();
50 });
51 }
52 if (traits.get_supports_tilt()) {
53 this->subscribe(this->get_tilt_command_topic_source(),
54 [this](const std::string &topic, const std::string &payload) {
55 if (ESPHOME_strcasecmp_P(payload.c_str(), ESPHOME_PSTR("STOP")) == 0) {
57 return;
58 }
59 auto value = parse_number<float>(payload);
60 if (!value.has_value()) {
61 ESP_LOGW(TAG, "Invalid tilt value: '%s'", payload.c_str());
62 return;
63 }
64 auto call = this->cover_->make_call();
65 call.set_tilt(*value / 100.0f);
66 call.perform();
67 });
68 }
69}
70
72 auto traits = this->cover_->get_traits();
73 bool has_command_topic = traits.get_supports_position() || !traits.get_supports_tilt();
74 LOG_MQTT_COMPONENT(true, has_command_topic);
75 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
76#ifdef USE_MQTT_COVER_JSON
77 if (this->use_json_format_) {
78 ESP_LOGCONFIG(TAG, " JSON State Payload: YES");
79 } else {
80#endif
81 if (traits.get_supports_position()) {
82 ESP_LOGCONFIG(TAG, " Position State Topic: '%s'", this->get_position_state_topic_to(topic_buf).c_str());
83 }
84 if (traits.get_supports_tilt()) {
85 ESP_LOGCONFIG(TAG, " Tilt State Topic: '%s'", this->get_tilt_state_topic_to(topic_buf).c_str());
86 }
87#ifdef USE_MQTT_COVER_JSON
88 }
89#endif
90 if (traits.get_supports_position()) {
91 ESP_LOGCONFIG(TAG, " Position Command Topic: '%s'", this->get_position_command_topic_to(topic_buf).c_str());
92 }
93 if (traits.get_supports_tilt()) {
94 ESP_LOGCONFIG(TAG, " Tilt Command Topic: '%s'", this->get_tilt_command_topic_to(topic_buf).c_str());
95 }
96}
98 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
99 auto traits = this->cover_->get_traits();
100 if (traits.get_is_assumed_state()) {
101 root[MQTT_OPTIMISTIC] = true;
102 }
103 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
104#ifdef USE_MQTT_COVER_JSON
105 if (this->use_json_format_) {
106 // JSON mode: all state published to state_topic as JSON, use templates to extract
107 root[MQTT_VALUE_TEMPLATE] = ESPHOME_F("{{ value_json.state }}");
108 if (traits.get_supports_position()) {
109 root[MQTT_POSITION_TOPIC] = this->get_state_topic_to_(topic_buf);
110 root[MQTT_POSITION_TEMPLATE] = ESPHOME_F("{{ value_json.position }}");
111 root[MQTT_SET_POSITION_TOPIC] = this->get_position_command_topic_to(topic_buf);
112 }
113 if (traits.get_supports_tilt()) {
114 root[MQTT_TILT_STATUS_TOPIC] = this->get_state_topic_to_(topic_buf);
115 root[MQTT_TILT_STATUS_TEMPLATE] = ESPHOME_F("{{ value_json.tilt }}");
116 root[MQTT_TILT_COMMAND_TOPIC] = this->get_tilt_command_topic_to(topic_buf);
117 }
118 } else
119#endif
120 {
121 // Standard mode: separate topics for position and tilt
122 if (traits.get_supports_position()) {
123 root[MQTT_POSITION_TOPIC] = this->get_position_state_topic_to(topic_buf);
124 root[MQTT_SET_POSITION_TOPIC] = this->get_position_command_topic_to(topic_buf);
125 }
126 if (traits.get_supports_tilt()) {
127 root[MQTT_TILT_STATUS_TOPIC] = this->get_tilt_state_topic_to(topic_buf);
128 root[MQTT_TILT_COMMAND_TOPIC] = this->get_tilt_command_topic_to(topic_buf);
129 }
130 }
131 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
132 if (traits.get_supports_tilt() && !traits.get_supports_position()) {
133 config.command_topic = false;
134 }
135}
136
138const EntityBase *MQTTCoverComponent::get_entity() const { return this->cover_; }
139
142 auto traits = this->cover_->get_traits();
143 char topic_buf[MQTT_DEFAULT_TOPIC_MAX_LEN];
144#ifdef USE_MQTT_COVER_JSON
145 if (this->use_json_format_) {
146 return this->publish_json(this->get_state_topic_to_(topic_buf), [this, traits](JsonObject root) {
147 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
148 root[ESPHOME_F("state")] = cover_state_to_mqtt_str(this->cover_->current_operation, this->cover_->position,
149 traits.get_supports_position());
150 if (traits.get_supports_position()) {
151 root[ESPHOME_F("position")] = static_cast<int>(roundf(this->cover_->position * 100));
152 }
153 if (traits.get_supports_tilt()) {
154 root[ESPHOME_F("tilt")] = static_cast<int>(roundf(this->cover_->tilt * 100));
155 }
156 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
157 });
158 }
159#endif
160 bool success = true;
161 if (traits.get_supports_position()) {
162 char pos[VALUE_ACCURACY_MAX_LEN];
163 size_t len = value_accuracy_to_buf(pos, roundf(this->cover_->position * 100), 0);
164 if (!this->publish(this->get_position_state_topic_to(topic_buf), pos, len))
165 success = false;
166 }
167 if (traits.get_supports_tilt()) {
168 char pos[VALUE_ACCURACY_MAX_LEN];
169 size_t len = value_accuracy_to_buf(pos, roundf(this->cover_->tilt * 100), 0);
170 if (!this->publish(this->get_tilt_state_topic_to(topic_buf), pos, len))
171 success = false;
172 }
173 if (!this->publish(this->get_state_topic_to_(topic_buf),
174 cover_state_to_mqtt_str(this->cover_->current_operation, this->cover_->position,
175 traits.get_supports_position())))
176 success = false;
177 return success;
178}
179
180} // namespace esphome::mqtt
181
182#endif
183#endif // USE_MQTT
CoverCall & set_command(const char *command)
Set the command as a string, "STOP", "OPEN", "CLOSE", "TOGGLE".
Definition cover.cpp:32
void perform()
Perform the cover call.
Definition cover.cpp:74
CoverCall & set_position(float position)
Set the call to a certain target position.
Definition cover.cpp:66
CoverCall & set_command_stop_tilt()
Set the command to stop the cover tilt.
Definition cover.cpp:58
CoverCall & set_tilt(float tilt)
Set the call to a certain target tilt.
Definition cover.cpp:70
Base class for all cover devices.
Definition cover.h:115
CoverOperation current_operation
The current operation of the cover (idle, opening, closing).
Definition cover.h:120
void add_on_state_callback(F &&f)
Definition cover.h:133
CoverCall make_call()
Construct a new cover call used to control the cover.
Definition cover.h:131
float tilt
The current tilt value of the cover from 0.0 to 1.0.
Definition cover.h:128
float position
The position of the cover from 0.0 (fully closed) to 1.0 (fully open).
Definition cover.h:126
virtual CoverTraits get_traits()=0
bool get_supports_position() const
void subscribe(T &&topic, F &&callback, uint8_t qos=0)
Subscribe to a MQTT topic.
MQTTTopicSource command_topic_source_() const
The command topic as a subscription source. A lambda topic is read once and copied,...
bool publish(const std::string &topic, const std::string &payload)
Send a MQTT message.
bool publish_json(const std::string &topic, const json::json_build_t &f)
Construct and send a JSON MQTT message.
StringRef get_state_topic_to_(std::span< char, MQTT_DEFAULT_TOPIC_MAX_LEN > buf) const
Get the MQTT state topic into a buffer (no heap allocation for non-lambda custom topics).
void send_discovery(JsonObject root, mqtt::SendDiscoveryConfig &config) override
state state bool send_initial_state() override
MQTTCoverComponent(cover::Cover *cover)
float position
Definition cover.h:0
ESPHOME_LOG_TAG(TAG, "alarm_control_panel")
CoverOperation
Enum encoding the current operation of a cover.
Definition cover.h:84
@ COVER_OPERATION_OPENING
The cover is currently opening.
Definition cover.h:88
@ COVER_OPERATION_CLOSING
The cover is currently closing.
Definition cover.h:90
MQTT_COMPONENT_TYPE(MQTTAlarmControlPanelComponent, "alarm_control_panel") const EntityBase *MQTTAlarmControlPanelComponent
size_t value_accuracy_to_buf(std::span< char, VALUE_ACCURACY_MAX_LEN > buf, float value, int8_t accuracy_decimals)
Format value with accuracy to buffer, returns chars written (excluding null)
Definition helpers.cpp:625
const void size_t len
Definition hal.h:68
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1352
size_t size_t pos
Definition helpers.h:1255
const __FlashStringHelper * ProgmemStr
Definition progmem.h:31
Simple Helper struct used for Home Assistant MQTT send_discovery().
bool command_topic
If the command topic should be included. Default to true.