FIX: Unnecessary flash writes by ModbusSwitch component (#3648)

This commit is contained in:
Javier Peletier
2022-11-30 10:05:40 +13:00
committed by GitHub
parent a59ce7bfa2
commit c55e01ff3f
11 changed files with 114 additions and 144 deletions
+44 -1
View File
@@ -22,18 +22,36 @@ void Switch::toggle() {
this->write_state(this->inverted_ == this->state);
}
optional<bool> Switch::get_initial_state() {
if (!(restore_mode & RESTORE_MODE_PERSISTENT_MASK))
return {};
this->rtc_ = global_preferences->make_preference<bool>(this->get_object_id_hash());
bool initial_state;
if (!this->rtc_.load(&initial_state))
return {};
return initial_state;
}
optional<bool> 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);
}
return initial_state;
}
void Switch::publish_state(bool state) {
if (!this->publish_dedup_.next(state))
return;
this->state = state != this->inverted_;
this->rtc_.save(&this->state);
if (restore_mode & RESTORE_MODE_PERSISTENT_MASK)
this->rtc_.save(&this->state);
ESP_LOGD(TAG, "'%s': Sending state %s", this->name_.c_str(), ONOFF(this->state));
this->state_callback_.call(this->state);
}
@@ -52,5 +70,30 @@ std::string Switch::get_device_class() {
}
void Switch::set_device_class(const std::string &device_class) { this->device_class_ = device_class; }
void log_switch(const char *tag, const char *prefix, const char *type, Switch *obj) {
if (obj != nullptr) {
ESP_LOGCONFIG(tag, "%s%s '%s'", prefix, type, obj->get_name().c_str());
if (!obj->get_icon().empty()) {
ESP_LOGCONFIG(tag, "%s Icon: '%s'", prefix, obj->get_icon().c_str());
}
if (obj->assumed_state()) {
ESP_LOGCONFIG(tag, "%s Assumed State: YES", prefix);
}
if (obj->is_inverted()) {
ESP_LOGCONFIG(tag, "%s Inverted: YES", prefix);
}
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");
ESP_LOGCONFIG(tag, "%s Restore Mode: %s%s %s", prefix, LOG_STR_ARG(inverted), LOG_STR_ARG(restore),
LOG_STR_ARG(onoff));
}
}
} // namespace switch_
} // namespace esphome