ESPHome 2025.12.2
Loading...
Searching...
No Matches
template_select.cpp
Go to the documentation of this file.
1#include "template_select.h"
2#include "esphome/core/log.h"
3
4namespace esphome::template_ {
5
6static const char *const TAG = "template.select";
7
9 if (this->f_.has_value())
10 return;
11
12 size_t index = this->initial_option_index_;
13 if (this->restore_value_) {
15 size_t restored_index;
16 if (this->pref_.load(&restored_index) && this->has_index(restored_index)) {
17 index = restored_index;
18 ESP_LOGD(TAG, "State from restore: %s", this->option_at(index));
19 } else {
20 ESP_LOGD(TAG, "State from initial (could not load or invalid stored index): %s", this->option_at(index));
21 }
22 } else {
23 ESP_LOGD(TAG, "State from initial: %s", this->option_at(index));
24 }
25
26 this->publish_state(index);
27}
28
30 if (!this->f_.has_value())
31 return;
32
33 auto val = this->f_();
34 if (val.has_value()) {
35 if (!this->has_option(*val)) {
36 ESP_LOGE(TAG, "Lambda returned an invalid option: %s", (*val).c_str());
37 return;
38 }
39 this->publish_state(*val);
40 }
41}
42
43void TemplateSelect::control(size_t index) {
44 this->set_trigger_->trigger(std::string(this->option_at(index)));
45
46 if (this->optimistic_)
47 this->publish_state(index);
48
49 if (this->restore_value_)
50 this->pref_.save(&index);
51}
52
54 LOG_SELECT("", "Template Select", this);
55 LOG_UPDATE_INTERVAL(this);
56 if (this->f_.has_value())
57 return;
58 ESP_LOGCONFIG(TAG,
59 " Optimistic: %s\n"
60 " Initial Option: %s\n"
61 " Restore Value: %s",
62 YESNO(this->optimistic_), this->option_at(this->initial_option_index_), YESNO(this->restore_value_));
63}
64
65} // namespace esphome::template_
bool save(const T *src)
Definition preferences.h:21
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
uint32_t get_preference_hash()
Get a unique hash for storing preferences/settings for this entity.
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
const char * option_at(size_t index) const
Return the option value at the provided index offset (as const char* from flash).
Definition select.cpp:84
bool has_option(const std::string &option) const
Return whether this select component contains the provided option.
Definition select.cpp:48
void publish_state(const std::string &state)
Definition select.cpp:11
Trigger< std::string > * set_trigger_
void control(size_t index) override
TemplateLambda< std::string > f_
mopeka_std_values val[4]
const char *const TAG
Definition spi.cpp:8
ESPPreferences * global_preferences