From 36e4a8b444d5b4aa7c367d98cc164218d9f1cdf6 Mon Sep 17 00:00:00 2001 From: Emil Hesslow Date: Wed, 29 Jul 2020 00:13:51 -0700 Subject: [PATCH] Stop infinite loop in light on_turn_on (#1219) Co-authored-by: Otto Winter --- esphome/components/light/automation.h | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) 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(); }