mirror of
https://github.com/esphome/esphome.git
synced 2025-08-08 11:27:47 +00:00
[switch] Add control()
method to API (#10118)
This commit is contained in:
parent
7e4d09dbd8
commit
676c51ffa0
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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_);
|
||||
|
@ -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.
|
||||
|
Loading…
x
Reference in New Issue
Block a user