ESPHome  2024.12.2
template_text.cpp
Go to the documentation of this file.
1 #include "template_text.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace template_ {
6 
7 static const char *const TAG = "template.text";
8 
10  if (!(this->f_ == nullptr)) {
11  if (this->f_.has_value())
12  return;
13  }
14 
15  std::string value;
16  ESP_LOGD(TAG, "Setting up Template Text Input");
17  value = this->initial_value_;
18  if (!this->pref_) {
19  ESP_LOGD(TAG, "State from initial: %s", value.c_str());
20  } else {
21  uint32_t key = this->get_object_id_hash();
22  key += this->traits.get_min_length() << 2;
23  key += this->traits.get_max_length() << 4;
24  key += fnv1_hash(this->traits.get_pattern()) << 6;
25  this->pref_->setup(key, value);
26  }
27  if (!value.empty())
28  this->publish_state(value);
29 }
30 
32  if (this->f_ == nullptr)
33  return;
34 
35  if (!this->f_.has_value())
36  return;
37 
38  auto val = (*this->f_)();
39  if (!val.has_value())
40  return;
41 
42  this->publish_state(*val);
43 }
44 
45 void TemplateText::control(const std::string &value) {
46  this->set_trigger_->trigger(value);
47 
48  if (this->optimistic_)
49  this->publish_state(value);
50 
51  if (this->pref_) {
52  if (!this->pref_->save(value)) {
53  ESP_LOGW(TAG, "Text value too long to save");
54  }
55  }
56 }
58  LOG_TEXT("", "Template Text Input", this);
59  ESP_LOGCONFIG(TAG, " Optimistic: %s", YESNO(this->optimistic_));
60  LOG_UPDATE_INTERVAL(this);
61 }
62 
63 } // namespace template_
64 } // namespace esphome
void control(const std::string &value) override
virtual void setup(uint32_t id, std::string &value)
Definition: template_text.h:17
TextTraits traits
Definition: text.h:27
mopeka_std_values val[4]
int get_max_length() const
Definition: text_traits.h:21
Trigger< std::string > * set_trigger_
Definition: template_text.h:80
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition: automation.h:95
optional< std::function< optional< std::string >)> > f_
Definition: template_text.h:81
const char *const TAG
Definition: spi.cpp:8
void publish_state(const std::string &state)
Definition: text.cpp:9
virtual bool save(const std::string &value)
Definition: template_text.h:15
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition: helpers.cpp:183
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
int get_min_length() const
Definition: text_traits.h:19
TemplateTextSaverBase * pref_
Definition: template_text.h:83
uint32_t get_object_id_hash()
Definition: entity_base.cpp:76
std::string get_pattern() const
Definition: text_traits.h:25