diff --git a/esphome/components/switch/automation.h b/esphome/components/switch/automation.h index 51ac5d7a3a..66818a80be 100644 --- a/esphome/components/switch/automation.h +++ b/esphome/components/switch/automation.h @@ -46,11 +46,7 @@ template class ControlAction : public Action { void play(Ts... x) override { auto state = this->state_.optional_value(x...); if (state.has_value()) { - if (*state) { - this->switch_->turn_on(); - } else { - this->switch_->turn_off(); - } + this->switch_->control(*state); } } diff --git a/esphome/components/switch/switch.cpp b/esphome/components/switch/switch.cpp index c204895755..13c12c1213 100644 --- a/esphome/components/switch/switch.cpp +++ b/esphome/components/switch/switch.cpp @@ -8,6 +8,14 @@ static const char *const TAG = "switch"; Switch::Switch() : state(false) {} +void Switch::control(bool target_state) { + ESP_LOGV(TAG, "'%s' Control: %s", this->get_name().c_str(), ONOFF(target_state)); + if (target_state) { + this->turn_on(); + } else { + this->turn_off(); + } +} void Switch::turn_on() { ESP_LOGD(TAG, "'%s' Turning ON.", this->get_name().c_str()); this->write_state(!this->inverted_); diff --git a/esphome/components/switch/switch.h b/esphome/components/switch/switch.h index b999296564..6371e35292 100644 --- a/esphome/components/switch/switch.h +++ b/esphome/components/switch/switch.h @@ -55,6 +55,14 @@ class Switch : public EntityBase, public EntityBase_DeviceClass { /// The current reported state of the binary sensor. bool state; + /** Control this switch using a boolean state value. + * + * This method provides a unified interface for setting the switch state based on a boolean parameter. + * It automatically calls turn_on() when state is true or turn_off() when state is false. + * + * @param target_state The desired state: true to turn the switch ON, false to turn it OFF. + */ + void control(bool target_state); /** Turn this switch on. This is called by the front-end. * * For implementing switches, please override write_state.