From aae63a7ff3b64054860384a461314dea31a22e80 Mon Sep 17 00:00:00 2001 From: "Sergey V. DUDANOV" Date: Sat, 13 Nov 2021 18:42:15 +0400 Subject: [PATCH] Add climate on_state trigger (#2707) --- esphome/components/climate/__init__.py | 12 ++++++++++++ esphome/components/climate/automation.h | 7 +++++++ tests/test1.yaml | 2 ++ 3 files changed, 21 insertions(+) diff --git a/esphome/components/climate/__init__.py b/esphome/components/climate/__init__.py index 7ff769e5cb..b0f9146012 100644 --- a/esphome/components/climate/__init__.py +++ b/esphome/components/climate/__init__.py @@ -20,6 +20,7 @@ from esphome.const import ( CONF_MODE, CONF_MODE_COMMAND_TOPIC, CONF_MODE_STATE_TOPIC, + CONF_ON_STATE, CONF_PRESET, CONF_SWING_MODE, CONF_SWING_MODE_COMMAND_TOPIC, @@ -34,6 +35,7 @@ from esphome.const import ( CONF_TARGET_TEMPERATURE_LOW_COMMAND_TOPIC, CONF_TARGET_TEMPERATURE_LOW_STATE_TOPIC, CONF_TEMPERATURE_STEP, + CONF_TRIGGER_ID, CONF_VISUAL, CONF_MQTT_ID, ) @@ -101,6 +103,7 @@ validate_climate_swing_mode = cv.enum(CLIMATE_SWING_MODES, upper=True) # Actions ControlAction = climate_ns.class_("ControlAction", automation.Action) +StateTrigger = climate_ns.class_("StateTrigger", automation.Trigger.template()) CLIMATE_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA).extend( { @@ -161,6 +164,11 @@ CLIMATE_SCHEMA = cv.ENTITY_BASE_SCHEMA.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA). cv.Optional(CONF_TARGET_TEMPERATURE_LOW_STATE_TOPIC): cv.All( cv.requires_component("mqtt"), cv.publish_topic ), + cv.Optional(CONF_ON_STATE): automation.validate_automation( + { + cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(StateTrigger), + } + ), } ) @@ -256,6 +264,10 @@ async def setup_climate_core_(var, config): ) ) + for conf in config.get(CONF_ON_STATE, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) + await automation.build_automation(trigger, [], conf) + async def register_climate(var, config): if not CORE.has_id(config[CONF_ID]): diff --git a/esphome/components/climate/automation.h b/esphome/components/climate/automation.h index 49a87027f2..3145358dab 100644 --- a/esphome/components/climate/automation.h +++ b/esphome/components/climate/automation.h @@ -42,5 +42,12 @@ template class ControlAction : public Action { Climate *climate_; }; +class StateTrigger : public Trigger<> { + public: + StateTrigger(Climate *climate) { + climate->add_on_state_callback([this]() { this->trigger(); }); + } +}; + } // namespace climate } // namespace esphome diff --git a/tests/test1.yaml b/tests/test1.yaml index 04d928e1b8..f10922a7b9 100644 --- a/tests/test1.yaml +++ b/tests/test1.yaml @@ -1707,6 +1707,8 @@ climate: min_temperature: 18 max_temperature: 30 - platform: midea + on_state: + logger.log: "State changed!" id: midea_unit uart_id: uart0 name: Midea Climate