[switch] Add trigger `on_state` (#10108)

This commit is contained in:
Edward Firmo 2025-08-09 13:09:40 +02:00 committed by GitHub
parent ff9ddb9d68
commit 2b9e1ce315
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 31 additions and 0 deletions

View File

@ -10,6 +10,7 @@ from esphome.const import (
CONF_ID,
CONF_INVERTED,
CONF_MQTT_ID,
CONF_ON_STATE,
CONF_ON_TURN_OFF,
CONF_ON_TURN_ON,
CONF_RESTORE_MODE,
@ -56,6 +57,9 @@ TurnOnAction = switch_ns.class_("TurnOnAction", automation.Action)
SwitchPublishAction = switch_ns.class_("SwitchPublishAction", automation.Action)
SwitchCondition = switch_ns.class_("SwitchCondition", Condition)
SwitchStateTrigger = switch_ns.class_(
"SwitchStateTrigger", automation.Trigger.template(bool)
)
SwitchTurnOnTrigger = switch_ns.class_(
"SwitchTurnOnTrigger", automation.Trigger.template()
)
@ -77,6 +81,11 @@ _SWITCH_SCHEMA = (
cv.Optional(CONF_RESTORE_MODE, default="ALWAYS_OFF"): cv.enum(
RESTORE_MODES, upper=True, space="_"
),
cv.Optional(CONF_ON_STATE): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SwitchStateTrigger),
}
),
cv.Optional(CONF_ON_TURN_ON): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SwitchTurnOnTrigger),
@ -140,6 +149,9 @@ async def setup_switch_core_(var, config):
if (inverted := config.get(CONF_INVERTED)) is not None:
cg.add(var.set_inverted(inverted))
for conf in config.get(CONF_ON_STATE, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [(bool, "x")], conf)
for conf in config.get(CONF_ON_TURN_ON, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)

View File

@ -64,6 +64,13 @@ template<typename... Ts> class SwitchCondition : public Condition<Ts...> {
bool state_;
};
class SwitchStateTrigger : public Trigger<bool> {
public:
SwitchStateTrigger(Switch *a_switch) {
a_switch->add_on_state_callback([this](bool state) { this->trigger(state); });
}
};
class SwitchTurnOnTrigger : public Trigger<> {
public:
SwitchTurnOnTrigger(Switch *a_switch) {

View File

@ -9,6 +9,18 @@ switch:
name: "Template Switch"
id: the_switch
optimistic: true
on_state:
- if:
condition:
- lambda: return x;
then:
- logger.log: "Switch turned ON"
else:
- logger.log: "Switch turned OFF"
on_turn_on:
- logger.log: "Switch is now ON"
on_turn_off:
- logger.log: "Switch is now OFF"
esphome:
on_boot: