ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
template_text.cpp
Go to the documentation of this file.
1#include "template_text.h"
2#include "esphome/core/log.h"
3
4namespace esphome::template_ {
5
6static const char *const TAG = "template.text";
7
9 if (this->f_.has_value())
10 return;
11
12 if (this->pref_ == nullptr) {
13 // No restore - use const char* directly, no heap allocation needed
14 if (this->initial_value_ != nullptr && this->initial_value_[0] != '\0') {
15 ESP_LOGD(TAG, "State from initial: %s", this->initial_value_);
16 this->publish_state(this->initial_value_);
17 }
18 return;
19 }
20
21 // Need std::string for pref_->setup() to fill from flash
22 std::string value{this->initial_value_ != nullptr ? this->initial_value_ : ""};
23 // For future hash migration: use migrate_entity_preference_() with:
24 // old_key = get_preference_hash() + extra
25 // new_key = get_preference_hash_v2() + extra
26 // See: https://github.com/esphome/backlog/issues/85
27#pragma GCC diagnostic push
28#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
29 uint32_t key = this->get_preference_hash();
30#pragma GCC diagnostic pop
31 key += this->traits.get_min_length() << 2;
32 key += this->traits.get_max_length() << 4;
33 key += fnv1_hash(this->traits.get_pattern_c_str()) << 6;
34 this->pref_->setup(key, value);
35 if (!value.empty())
36 this->publish_state(value);
37}
38
40 if (!this->f_.has_value())
41 return;
42
43 auto val = this->f_();
44 if (val.has_value()) {
45 this->publish_state(*val);
46 }
47}
48
49void TemplateText::control(const std::string &value) {
50 this->set_trigger_.trigger(value);
51
52 if (this->optimistic_)
53 this->publish_state(value);
54
55 if (this->pref_) {
56 if (!this->pref_->save(value)) {
57 ESP_LOGW(TAG, "Text value too long to save");
58 }
59 }
60}
62 LOG_TEXT("", "Template Text Input", this);
63 ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_));
64 LOG_UPDATE_INTERVAL(this);
65}
66
67} // namespace esphome::template_
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:325
Trigger< std::string > set_trigger_
TemplateLambda< std::string > f_
TemplateTextSaverBase * pref_
void control(const std::string &value) override
virtual bool save(const std::string &value)
virtual void setup(uint32_t id, std::string &value)
void publish_state(const std::string &state)
Definition text.cpp:11
TextTraits traits
Definition text.h:24
const char * get_pattern_c_str() const
Definition text_traits.h:25
mopeka_std_values val[4]
const char *const TAG
Definition spi.cpp:7
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:148