From 6dabf24bf35681e98fe01950dd9c77bd28fe4c81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=5Bp=CA=B2=C9=B5s=5D?= Date: Mon, 16 May 2022 05:35:27 +0200 Subject: [PATCH] MQTT cover: send state even if position is available (#3473) --- esphome/components/mqtt/mqtt_cover.cpp | 28 +++++++++++--------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/esphome/components/mqtt/mqtt_cover.cpp b/esphome/components/mqtt/mqtt_cover.cpp index e5525bc0f7..0718a24828 100644 --- a/esphome/components/mqtt/mqtt_cover.cpp +++ b/esphome/components/mqtt/mqtt_cover.cpp @@ -51,10 +51,9 @@ void MQTTCoverComponent::setup() { void MQTTCoverComponent::dump_config() { ESP_LOGCONFIG(TAG, "MQTT cover '%s':", this->cover_->get_name().c_str()); auto traits = this->cover_->get_traits(); - // no state topic for position - bool state_topic = !traits.get_supports_position(); - LOG_MQTT_COMPONENT(state_topic, true) - if (!state_topic) { + bool has_command_topic = traits.get_supports_position() || !traits.get_supports_tilt(); + LOG_MQTT_COMPONENT(true, has_command_topic) + if (traits.get_supports_position()) { ESP_LOGCONFIG(TAG, " Position State Topic: '%s'", this->get_position_state_topic().c_str()); ESP_LOGCONFIG(TAG, " Position Command Topic: '%s'", this->get_position_command_topic().c_str()); } @@ -72,7 +71,6 @@ void MQTTCoverComponent::send_discovery(JsonObject root, mqtt::SendDiscoveryConf root[MQTT_OPTIMISTIC] = true; } if (traits.get_supports_position()) { - config.state_topic = false; root[MQTT_POSITION_TOPIC] = this->get_position_state_topic(); root[MQTT_SET_POSITION_TOPIC] = this->get_position_command_topic(); } @@ -92,17 +90,7 @@ bool MQTTCoverComponent::send_initial_state() { return this->publish_state(); } bool MQTTCoverComponent::publish_state() { auto traits = this->cover_->get_traits(); bool success = true; - if (!traits.get_supports_position()) { - const char *state_s = "unknown"; - if (this->cover_->position == COVER_OPEN) { - state_s = "open"; - } else if (this->cover_->position == COVER_CLOSED) { - state_s = "closed"; - } - - if (!this->publish(this->get_state_topic_(), state_s)) - success = false; - } else { + if (traits.get_supports_position()) { std::string pos = value_accuracy_to_string(roundf(this->cover_->position * 100), 0); if (!this->publish(this->get_position_state_topic(), pos)) success = false; @@ -112,6 +100,14 @@ bool MQTTCoverComponent::publish_state() { if (!this->publish(this->get_tilt_state_topic(), pos)) success = false; } + const char *state_s = this->cover_->current_operation == COVER_OPERATION_OPENING ? "opening" + : this->cover_->current_operation == COVER_OPERATION_CLOSING ? "closing" + : this->cover_->position == COVER_CLOSED ? "closed" + : this->cover_->position == COVER_OPEN ? "open" + : traits.get_supports_position() ? "open" + : "unknown"; + if (!this->publish(this->get_state_topic_(), state_s)) + success = false; return success; }