fix RESTORE_INVERTED switch:restore_mode (#4129)

fixes https://github.com/esphome/esphome/pull/3648
This commit is contained in:
Javier Peletier 2022-12-01 00:49:15 +01:00 committed by GitHub
parent eb2a0f45db
commit 106c1bfac2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -35,13 +35,14 @@ optional<bool> Switch::get_initial_state_with_restore_mode() {
if (restore_mode & RESTORE_MODE_DISABLED_MASK) { if (restore_mode & RESTORE_MODE_DISABLED_MASK) {
return {}; return {};
} }
bool initial_state = restore_mode & RESTORE_MODE_ON_MASK; bool initial_state = restore_mode & RESTORE_MODE_ON_MASK; // default value *_OFF or *_ON
if (restore_mode & RESTORE_MODE_INVERTED_MASK) if (restore_mode & RESTORE_MODE_PERSISTENT_MASK) { // For RESTORE_*
initial_state = !initial_state; optional<bool> restored_state = this->get_initial_state();
if (restore_mode & RESTORE_MODE_PERSISTENT_MASK) { if (restored_state.has_value()) {
initial_state = this->get_initial_state().value_or(initial_state); // 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; return initial_state;
} }
void Switch::publish_state(bool 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()) { if (!obj->get_device_class().empty()) {
ESP_LOGCONFIG(tag, "%s Device Class: '%s'", prefix, obj->get_device_class().c_str()); 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 *onoff = LOG_STR(""), *inverted = onoff, *restore;
const LogString *inverted = obj->restore_mode & RESTORE_MODE_INVERTED_MASK ? LOG_STR("inverted ") : LOG_STR(""); if (obj->restore_mode & RESTORE_MODE_DISABLED_MASK) {
const LogString *restore = restore = LOG_STR("disabled");
obj->restore_mode & RESTORE_MODE_PERSISTENT_MASK ? LOG_STR("restore defaults to") : LOG_STR("always"); } 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), ESP_LOGCONFIG(tag, "%s Restore Mode: %s%s %s", prefix, LOG_STR_ARG(inverted), LOG_STR_ARG(restore),
LOG_STR_ARG(onoff)); LOG_STR_ARG(onoff));