From 106c1bfac262a16d977ca464fde2c18598e18b75 Mon Sep 17 00:00:00 2001 From: Javier Peletier Date: Thu, 1 Dec 2022 00:49:15 +0100 Subject: [PATCH] fix RESTORE_INVERTED switch:restore_mode (#4129) fixes https://github.com/esphome/esphome/pull/3648 --- esphome/components/switch/switch.cpp | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/esphome/components/switch/switch.cpp b/esphome/components/switch/switch.cpp index 99df5091c3..caa072b1ea 100644 --- a/esphome/components/switch/switch.cpp +++ b/esphome/components/switch/switch.cpp @@ -35,13 +35,14 @@ optional Switch::get_initial_state_with_restore_mode() { if (restore_mode & RESTORE_MODE_DISABLED_MASK) { return {}; } - bool initial_state = restore_mode & RESTORE_MODE_ON_MASK; - if (restore_mode & RESTORE_MODE_INVERTED_MASK) - initial_state = !initial_state; - if (restore_mode & RESTORE_MODE_PERSISTENT_MASK) { - initial_state = this->get_initial_state().value_or(initial_state); + bool initial_state = restore_mode & RESTORE_MODE_ON_MASK; // default value *_OFF or *_ON + if (restore_mode & RESTORE_MODE_PERSISTENT_MASK) { // For RESTORE_* + optional restored_state = this->get_initial_state(); + if (restored_state.has_value()) { + // Invert value if any of the *_INVERTED_* modes + initial_state = restore_mode & RESTORE_MODE_INVERTED_MASK ? !restored_state.value() : restored_state.value(); + } } - return initial_state; } void Switch::publish_state(bool state) { @@ -85,10 +86,14 @@ void log_switch(const char *tag, const char *prefix, const char *type, Switch *o if (!obj->get_device_class().empty()) { ESP_LOGCONFIG(tag, "%s Device Class: '%s'", prefix, obj->get_device_class().c_str()); } - const LogString *onoff = obj->restore_mode & RESTORE_MODE_ON_MASK ? LOG_STR("ON") : LOG_STR("OFF"); - const LogString *inverted = obj->restore_mode & RESTORE_MODE_INVERTED_MASK ? LOG_STR("inverted ") : LOG_STR(""); - const LogString *restore = - obj->restore_mode & RESTORE_MODE_PERSISTENT_MASK ? LOG_STR("restore defaults to") : LOG_STR("always"); + const LogString *onoff = LOG_STR(""), *inverted = onoff, *restore; + if (obj->restore_mode & RESTORE_MODE_DISABLED_MASK) { + restore = LOG_STR("disabled"); + } else { + onoff = obj->restore_mode & RESTORE_MODE_ON_MASK ? LOG_STR("ON") : LOG_STR("OFF"); + inverted = obj->restore_mode & RESTORE_MODE_INVERTED_MASK ? LOG_STR("inverted ") : LOG_STR(""); + restore = obj->restore_mode & RESTORE_MODE_PERSISTENT_MASK ? LOG_STR("restore defaults to") : LOG_STR("always"); + } ESP_LOGCONFIG(tag, "%s Restore Mode: %s%s %s", prefix, LOG_STR_ARG(inverted), LOG_STR_ARG(restore), LOG_STR_ARG(onoff));