ESPHome 2025.12.0-dev
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 auto s = this->f_();
13 if (s.has_value()) {
14 this->publish_state(*s);
15 }
16}
18 if (this->prev_trigger_ != nullptr) {
20 }
21
22 if (state) {
23 this->prev_trigger_ = this->turn_on_trigger_;
25 } else {
26 this->prev_trigger_ = this->turn_off_trigger_;
28 }
29
30 if (this->optimistic_)
31 this->publish_state(state);
32}
33void TemplateSwitch::set_optimistic(bool optimistic) { this->optimistic_ = optimistic; }
39 if (!this->f_.has_value())
40 this->disable_loop();
41
43
44 if (initial_state.has_value()) {
45 ESP_LOGD(TAG, " Restored state %s", ONOFF(initial_state.value()));
46 // if it has a value, restore_mode is not "DISABLED", therefore act on the switch:
47 if (initial_state.value()) {
48 this->turn_on();
49 } else {
50 this->turn_off();
51 }
52 }
53}
55 LOG_SWITCH("", "Template Switch", this);
56 ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_));
57}
59
60} // namespace template_
61} // namespace esphome
void disable_loop()
Disable this component's loop.
bool has_value() const
Check if a lambda is set.
void trigger(const Ts &...x)
Inform the parent automation that the event has triggered.
Definition automation.h:169
void stop_action()
Stop any action connected to this trigger.
Definition automation.h:177
bool has_value() const
Definition optional.h:92
value_type const & value() const
Definition optional.h:94
void turn_on()
Turn this switch on.
Definition switch.cpp:21
void turn_off()
Turn this switch off.
Definition switch.cpp:25
void publish_state(bool state)
Publish a state to the front-end from the back-end.
Definition switch.cpp:57
optional< bool > get_initial_state_with_restore_mode()
Returns the initial state of the switch, after applying restore mode rules.
Definition switch.cpp:43
float get_setup_priority() const override
void write_state(bool state) override
void set_assumed_state(bool assumed_state)
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:58
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7