ESPHome 2025.12.0-dev
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 {
5namespace template_ {
6
7static const char *const TAG = "template.select";
8
10 if (this->f_.has_value())
11 return;
12
13 size_t index = this->initial_option_index_;
14 if (this->restore_value_) {
16 size_t restored_index;
17 if (this->pref_.load(&restored_index) && this->has_index(restored_index)) {
18 index = restored_index;
19 ESP_LOGD(TAG, "State from restore: %s", this->option_at(index));
20 } else {
21 ESP_LOGD(TAG, "State from initial (could not load or invalid stored index): %s", this->option_at(index));
22 }
23 } else {
24 ESP_LOGD(TAG, "State from initial: %s", this->option_at(index));
25 }
26
27 this->publish_state(index);
28}
29
31 if (!this->f_.has_value())
32 return;
33
34 auto val = this->f_();
35 if (val.has_value()) {
36 if (!this->has_option(*val)) {
37 ESP_LOGE(TAG, "Lambda returned an invalid option: %s", (*val).c_str());
38 return;
39 }
40 this->publish_state(*val);
41 }
42}
43
44void TemplateSelect::control(size_t index) {
45 this->set_trigger_->trigger(std::string(this->option_at(index)));
46
47 if (this->optimistic_)
48 this->publish_state(index);
49
50 if (this->restore_value_)
51 this->pref_.save(&index);
52}
53
55 LOG_SELECT("", "Template Select", this);
56 LOG_UPDATE_INTERVAL(this);
57 if (this->f_.has_value())
58 return;
59 ESP_LOGCONFIG(TAG,
60 " Optimistic: %s\n"
61 " Initial Option: %s\n"
62 " Restore Value: %s",
63 YESNO(this->optimistic_), this->option_at(this->initial_option_index_), YESNO(this->restore_value_));
64}
65
66} // namespace template_
67} // namespace esphome
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:169
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:87
bool has_option(const std::string &option) const
Return whether this select component contains the provided option.
Definition select.cpp:49
void publish_state(const std::string &state)
Definition select.cpp:12
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
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
ESPPreferences * global_preferences