ESPHome  2024.9.0
lvgl_select.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <utility>
4 
9 
10 namespace esphome {
11 namespace lvgl {
12 
13 static std::vector<std::string> split_string(const std::string &str) {
14  std::vector<std::string> strings;
15  auto delimiter = std::string("\n");
16 
17  std::string::size_type pos;
18  std::string::size_type prev = 0;
19  while ((pos = str.find(delimiter, prev)) != std::string::npos) {
20  strings.push_back(str.substr(prev, pos - prev));
21  prev = pos + delimiter.size();
22  }
23 
24  // To get the last substring (or only, if delimiter is not found)
25  strings.push_back(str.substr(prev));
26 
27  return strings;
28 }
29 
30 class LVGLSelect : public select::Select {
31  public:
32  void set_control_lambda(std::function<void(size_t)> lambda) {
33  this->control_lambda_ = std::move(lambda);
34  if (this->initial_state_.has_value()) {
35  this->control(this->initial_state_.value());
36  this->initial_state_.reset();
37  }
38  }
39 
40  void publish_index(size_t index) {
41  auto value = this->at(index);
42  if (value)
43  this->publish_state(value.value());
44  }
45 
46  void set_options(const char *str) { this->traits.set_options(split_string(str)); }
47 
48  protected:
49  void control(const std::string &value) override {
50  if (this->control_lambda_ != nullptr) {
51  auto index = index_of(value);
52  if (index)
53  this->control_lambda_(index.value());
54  } else {
55  this->initial_state_ = value.c_str();
56  }
57  }
58 
59  std::function<void(size_t)> control_lambda_{};
61 };
62 
63 } // namespace lvgl
64 } // namespace esphome
value_type const & value() const
Definition: optional.h:89
optional< const char * > initial_state_
Definition: lvgl_select.h:60
optional< std::string > at(size_t index) const
Return the (optional) option value at the provided index offset.
Definition: select.cpp:52
SelectTraits traits
Definition: select.h:34
void set_options(const char *str)
Definition: lvgl_select.h:46
bool has_value() const
Definition: optional.h:87
void set_options(std::vector< std::string > options)
void publish_index(size_t index)
Definition: lvgl_select.h:40
std::function< void(size_t)> control_lambda_
Definition: lvgl_select.h:59
void set_control_lambda(std::function< void(size_t)> lambda)
Definition: lvgl_select.h:32
void publish_state(const std::string &state)
Definition: select.cpp:9
Base-class for all selects.
Definition: select.h:31
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
optional< size_t > index_of(const std::string &option) const
Find the (optional) index offset of the provided option value.
Definition: select.cpp:35
void control(const std::string &value) override
Definition: lvgl_select.h:49