ESPHome  2022.6.2
template_number.cpp
Go to the documentation of this file.
1 #include "template_number.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace template_ {
6 
7 static const char *const TAG = "template.number";
8 
10  if (this->f_.has_value())
11  return;
12 
13  float value;
14  if (!this->restore_value_) {
15  value = this->initial_value_;
16  } else {
18  if (!this->pref_.load(&value)) {
19  if (!std::isnan(this->initial_value_)) {
20  value = this->initial_value_;
21  } else {
22  value = this->traits.get_min_value();
23  }
24  }
25  }
26  this->publish_state(value);
27 }
28 
30  if (!this->f_.has_value())
31  return;
32 
33  auto val = (*this->f_)();
34  if (!val.has_value())
35  return;
36 
37  this->publish_state(*val);
38 }
39 
40 void TemplateNumber::control(float value) {
41  this->set_trigger_->trigger(value);
42 
43  if (this->optimistic_)
44  this->publish_state(value);
45 
46  if (this->restore_value_)
47  this->pref_.save(&value);
48 }
50  LOG_NUMBER("", "Template Number", this);
51  ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_));
52  LOG_UPDATE_INTERVAL(this);
53 }
54 
55 } // namespace template_
56 } // namespace esphome
void publish_state(float state)
Definition: number.cpp:9
optional< std::function< optional< float >)> > f_
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition: automation.h:95
bool save(const T *src)
Definition: preferences.h:21
ESPPreferences * global_preferences
NumberTraits traits
Definition: number.h:39
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
Definition: a4988.cpp:4
uint32_t val
Definition: datatypes.h:85
void control(float value) override
uint32_t get_object_id_hash()
Definition: entity_base.cpp:42