ESPHome  2022.11.3
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; }
43  if (!this->restore_state_)
44  return;
45 
46  auto restored = this->get_initial_state();
47  if (!restored.has_value())
48  return;
49 
50  ESP_LOGD(TAG, " Restored state %s", ONOFF(*restored));
51  if (*restored) {
52  this->turn_on();
53  } else {
54  this->turn_off();
55  }
56 }
58  LOG_SWITCH("", "Template Switch", this);
59  ESP_LOGCONFIG(TAG, " Restore State: %s", YESNO(this->restore_state_));
60  ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_));
61 }
62 void TemplateSwitch::set_restore_state(bool restore_state) { this->restore_state_ = restore_state; }
64 
65 } // namespace template_
66 } // namespace esphome
void set_restore_state(bool restore_state)
void set_state_lambda(std::function< optional< bool >()> &&f)
void set_optimistic(bool optimistic)
void write_state(bool state) override
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition: automation.h:95
optional< std::function< optional< bool >)> > f_
optional< bool > get_initial_state()
Definition: switch.cpp:24
void turn_on()
Turn this switch on.
Definition: switch.cpp:12
const float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition: component.cpp:17
Definition: a4988.cpp:4
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:31
bool state
The current reported state of the binary sensor.
Definition: switch.h:48
void stop_action()
Stop any action connected to this trigger.
Definition: automation.h:103
void turn_off()
Turn this switch off.
Definition: switch.cpp:16