ESPHome  2024.2.1
tuya_select.cpp
Go to the documentation of this file.
1 #include "esphome/core/log.h"
2 #include "tuya_select.h"
3 
4 namespace esphome {
5 namespace tuya {
6 
7 static const char *const TAG = "tuya.select";
8 
10  this->parent_->register_listener(this->select_id_, [this](const TuyaDatapoint &datapoint) {
11  uint8_t enum_value = datapoint.value_enum;
12  ESP_LOGV(TAG, "MCU reported select %u value %u", this->select_id_, enum_value);
13  auto options = this->traits.get_options();
14  auto mappings = this->mappings_;
15  auto it = std::find(mappings.cbegin(), mappings.cend(), enum_value);
16  if (it == mappings.end()) {
17  ESP_LOGW(TAG, "Invalid value %u", enum_value);
18  return;
19  }
20  size_t mapping_idx = std::distance(mappings.cbegin(), it);
21  auto value = this->at(mapping_idx);
22  this->publish_state(value.value());
23  });
24 }
25 
26 void TuyaSelect::control(const std::string &value) {
27  if (this->optimistic_)
28  this->publish_state(value);
29 
30  auto idx = this->index_of(value);
31  if (idx.has_value()) {
32  uint8_t mapping = this->mappings_.at(idx.value());
33  ESP_LOGV(TAG, "Setting %u datapoint value to %u:%s", this->select_id_, mapping, value.c_str());
34  this->parent_->set_enum_datapoint_value(this->select_id_, mapping);
35  return;
36  }
37 
38  ESP_LOGW(TAG, "Invalid value %s", value.c_str());
39 }
40 
42  LOG_SELECT("", "Tuya Select", this);
43  ESP_LOGCONFIG(TAG, " Select has datapoint ID %u", this->select_id_);
44  ESP_LOGCONFIG(TAG, " Options are:");
45  auto options = this->traits.get_options();
46  for (auto i = 0; i < this->mappings_.size(); i++) {
47  ESP_LOGCONFIG(TAG, " %i: %s", this->mappings_.at(i), options.at(i).c_str());
48  }
49 }
50 
51 } // namespace tuya
52 } // namespace esphome
void dump_config() override
Definition: tuya_select.cpp:41
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value)
Definition: tuya.cpp:551
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 register_listener(uint8_t datapoint_id, const std::function< void(TuyaDatapoint)> &func)
Definition: tuya.cpp:667
void control(const std::string &value) override
Definition: tuya_select.cpp:26
std::vector< uint8_t > mappings_
Definition: tuya_select.h:28
const char *const TAG
Definition: spi.cpp:8
std::vector< std::string > get_options() const
uint8_t options
void setup() override
Definition: tuya_select.cpp:9
void publish_state(const std::string &state)
Definition: select.cpp:9
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
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