diff --git a/esphome/components/light/automation.h b/esphome/components/light/automation.h index dfab780658..b240f84e8f 100644 --- a/esphome/components/light/automation.h +++ b/esphome/components/light/automation.h @@ -103,10 +103,14 @@ class LightTurnOnTrigger : public Trigger<> { LightTurnOnTrigger(LightState *a_light) { a_light->add_new_remote_values_callback([this, a_light]() { auto is_on = a_light->current_values.is_on(); - if (is_on && !last_on_) { + // only trigger when going from off to on + auto should_trigger = is_on && !last_on_; + // Set new state immediately so that trigger() doesn't devolve + // into infinite loop + last_on_ = is_on; + if (should_trigger) { this->trigger(); } - last_on_ = is_on; }); last_on_ = a_light->current_values.is_on(); } @@ -120,10 +124,14 @@ class LightTurnOffTrigger : public Trigger<> { LightTurnOffTrigger(LightState *a_light) { a_light->add_new_remote_values_callback([this, a_light]() { auto is_on = a_light->current_values.is_on(); - if (!is_on && last_on_) { + // only trigger when going from on to off + auto should_trigger = !is_on && last_on_; + // Set new state immediately so that trigger() doesn't devolve + // into infinite loop + last_on_ = is_on; + if (should_trigger) { this->trigger(); } - last_on_ = is_on; }); last_on_ = a_light->current_values.is_on(); }