ESPHome 2025.5.0
Loading...
Searching...
No Matches
template_switch.cpp
Go to the documentation of this file.
1#include "template_switch.h"
2#include "esphome/core/log.h"
3
4namespace esphome {
5namespace template_ {
6
7static const char *const TAG = "template.switch";
8
9TemplateSwitch::TemplateSwitch() : turn_on_trigger_(new Trigger<>()), turn_off_trigger_(new Trigger<>()) {}
10
12 if (!this->f_.has_value())
13 return;
14 auto s = (*this->f_)();
15 if (!s.has_value())
16 return;
17
18 this->publish_state(*s);
19}
21 if (this->prev_trigger_ != nullptr) {
23 }
24
25 if (state) {
26 this->prev_trigger_ = this->turn_on_trigger_;
28 } else {
29 this->prev_trigger_ = this->turn_off_trigger_;
31 }
32
33 if (this->optimistic_)
34 this->publish_state(state);
35}
36void TemplateSwitch::set_optimistic(bool optimistic) { this->optimistic_ = optimistic; }
38void TemplateSwitch::set_state_lambda(std::function<optional<bool>()> &&f) { this->f_ = f; }
44
45 if (initial_state.has_value()) {
46 ESP_LOGD(TAG, " Restored state %s", ONOFF(initial_state.value()));
47 // if it has a value, restore_mode is not "DISABLED", therefore act on the switch:
48 if (initial_state.value()) {
49 this->turn_on();
50 } else {
51 this->turn_off();
52 }
53 }
54}
56 LOG_SWITCH("", "Template Switch", this);
57 ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_));
58}
60
61} // namespace template_
62} // namespace esphome
void stop_action()
Stop any action connected to this trigger.
Definition automation.h:104
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition automation.h:96
bool has_value() const
Definition optional.h:87
value_type const & value() const
Definition optional.h:89
void turn_on()
Turn this switch on.
Definition switch.cpp:11
void turn_off()
Turn this switch off.
Definition switch.cpp:15
void publish_state(bool state)
Publish a state to the front-end from the back-end.
Definition switch.cpp:47
optional< bool > get_initial_state_with_restore_mode()
Returns the initial state of the switch, after applying restore mode rules.
Definition switch.cpp:33
float get_setup_priority() const override
void write_state(bool state) override
void set_assumed_state(bool assumed_state)
optional< std::function< optional< bool >()> > f_
void set_state_lambda(std::function< optional< bool >()> &&f)
bool state
Definition fan.h:0
const float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.cpp:18
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7