ESPHome 2025.5.0
Loading...
Searching...
No Matches
tuya_select.cpp
Go to the documentation of this file.
1#include "esphome/core/log.h"
2#include "tuya_select.h"
3
4namespace esphome {
5namespace tuya {
6
7static 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
26void 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 if (this->is_int_) {
35 this->parent_->set_integer_datapoint_value(this->select_id_, mapping);
36 } else {
37 this->parent_->set_enum_datapoint_value(this->select_id_, mapping);
38 }
39 return;
40 }
41
42 ESP_LOGW(TAG, "Invalid value %s", value.c_str());
43}
44
46 LOG_SELECT("", "Tuya Select", this);
47 ESP_LOGCONFIG(TAG, " Select has datapoint ID %u", this->select_id_);
48 ESP_LOGCONFIG(TAG, " Data type: %s", this->is_int_ ? "int" : "enum");
49 ESP_LOGCONFIG(TAG, " Options are:");
50 auto options = this->traits.get_options();
51 for (auto i = 0; i < this->mappings_.size(); i++) {
52 ESP_LOGCONFIG(TAG, " %i: %s", this->mappings_.at(i), options.at(i).c_str());
53 }
54}
55
56} // namespace tuya
57} // namespace esphome
optional< size_t > index_of(const std::string &option) const
Find the (optional) index offset of the provided option value.
Definition select.cpp:35
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 publish_state(const std::string &state)
Definition select.cpp:9
std::vector< std::string > get_options() const
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value)
Definition tuya.cpp:581
void register_listener(uint8_t datapoint_id, const std::function< void(TuyaDatapoint)> &func)
Definition tuya.cpp:697
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value)
Definition tuya.cpp:573
void dump_config() override
void control(const std::string &value) override
std::vector< uint8_t > mappings_
Definition tuya_select.h:31
uint8_t options
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7