ESPHome 2026.1.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::template_ {
5
6static const char *const TAG = "template.switch";
7
8TemplateSwitch::TemplateSwitch() : turn_on_trigger_(new Trigger<>()), turn_off_trigger_(new Trigger<>()) {}
9
11 auto s = this->f_();
12 if (s.has_value()) {
13 this->publish_state(*s);
14 }
15}
17 if (this->prev_trigger_ != nullptr) {
19 }
20
21 if (state) {
22 this->prev_trigger_ = this->turn_on_trigger_;
24 } else {
25 this->prev_trigger_ = this->turn_off_trigger_;
27 }
28
29 if (this->optimistic_)
30 this->publish_state(state);
31}
32void TemplateSwitch::set_optimistic(bool optimistic) { this->optimistic_ = optimistic; }
38 if (!this->f_.has_value())
39 this->disable_loop();
40
42
43 if (initial_state.has_value()) {
44 ESP_LOGD(TAG, " Restored state %s", ONOFF(initial_state.value()));
45 // if it has a value, restore_mode is not "DISABLED", therefore act on the switch:
46 if (initial_state.value()) {
47 this->turn_on();
48 } else {
49 this->turn_off();
50 }
51 }
52}
54 LOG_SWITCH("", "Template Switch", this);
55 ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_));
56}
58
59} // namespace esphome::template_
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:204
void stop_action()
Stop any action connected to this trigger.
Definition automation.h:212
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:80
const char *const TAG
Definition spi.cpp:7