ESPHome  2024.11.0
template_switch.cpp
Go to the documentation of this file.
1 #include "template_switch.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace template_ {
6 
7 static const char *const TAG = "template.switch";
8 
9 TemplateSwitch::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) {
22  this->prev_trigger_->stop_action();
23  }
24 
25  if (state) {
26  this->prev_trigger_ = this->turn_on_trigger_;
27  this->turn_on_trigger_->trigger();
28  } else {
29  this->prev_trigger_ = this->turn_off_trigger_;
30  this->turn_off_trigger_->trigger();
31  }
32 
33  if (this->optimistic_)
34  this->publish_state(state);
35 }
36 void TemplateSwitch::set_optimistic(bool optimistic) { this->optimistic_ = optimistic; }
38 void 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
value_type const & value() const
Definition: optional.h:89
void set_state_lambda(std::function< optional< bool >()> &&f)
void set_optimistic(bool optimistic)
void write_state(bool state) override
bool has_value() const
Definition: optional.h:87
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition: automation.h:95
optional< std::function< optional< bool >)> > f_
const char *const TAG
Definition: spi.cpp:8
optional< bool > get_initial_state_with_restore_mode()
Returns the initial state of the switch, after applying restore mode rules.
Definition: switch.cpp:33
void turn_on()
Turn this switch on.
Definition: switch.cpp:11
const float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition: component.cpp:18
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void set_assumed_state(bool assumed_state)
float get_setup_priority() const override
void publish_state(bool state)
Publish a state to the front-end from the back-end.
Definition: switch.cpp:47
bool state
The current reported state of the binary sensor.
Definition: switch.h:53
void stop_action()
Stop any action connected to this trigger.
Definition: automation.h:103
void turn_off()
Turn this switch off.
Definition: switch.cpp:15