[switch] Add control() method to API (#10118)

This commit is contained in:
Edward Firmo 2025-08-08 07:51:19 +02:00 committed by GitHub
parent 7e4d09dbd8
commit 676c51ffa0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 17 additions and 5 deletions

View File

@ -46,11 +46,7 @@ template<typename... Ts> class ControlAction : public Action<Ts...> {
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);
}
}

View File

@ -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_);

View File

@ -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.