mirror of
https://github.com/Threnklyn/esphome-dev.git
synced 2026-05-21 05:23:27 +02:00
Select enhancement (#3423)
Co-authored-by: Maurice Makaay <mmakaay1@xs4all.net>
This commit is contained in:
@@ -6,37 +6,53 @@ namespace select {
|
||||
|
||||
static const char *const TAG = "select";
|
||||
|
||||
void SelectCall::perform() {
|
||||
ESP_LOGD(TAG, "'%s' - Setting", this->parent_->get_name().c_str());
|
||||
if (!this->option_.has_value()) {
|
||||
ESP_LOGW(TAG, "No value set for SelectCall");
|
||||
return;
|
||||
}
|
||||
|
||||
const auto &traits = this->parent_->traits;
|
||||
auto value = *this->option_;
|
||||
auto options = traits.get_options();
|
||||
|
||||
if (std::find(options.begin(), options.end(), value) == options.end()) {
|
||||
ESP_LOGW(TAG, " Option %s is not a valid option.", value.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, " Option: %s", (*this->option_).c_str());
|
||||
this->parent_->control(*this->option_);
|
||||
}
|
||||
|
||||
void Select::publish_state(const std::string &state) {
|
||||
this->has_state_ = true;
|
||||
this->state = state;
|
||||
ESP_LOGD(TAG, "'%s': Sending state %s", this->get_name().c_str(), state.c_str());
|
||||
this->state_callback_.call(state);
|
||||
auto index = this->index_of(state);
|
||||
const auto *name = this->get_name().c_str();
|
||||
if (index.has_value()) {
|
||||
this->has_state_ = true;
|
||||
this->state = state;
|
||||
ESP_LOGD(TAG, "'%s': Sending state %s (index %d)", name, state.c_str(), index.value());
|
||||
this->state_callback_.call(state, index.value());
|
||||
} else {
|
||||
ESP_LOGE(TAG, "'%s': invalid state for publish_state(): %s", name, state.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void Select::add_on_state_callback(std::function<void(std::string)> &&callback) {
|
||||
void Select::add_on_state_callback(std::function<void(std::string, size_t)> &&callback) {
|
||||
this->state_callback_.add(std::move(callback));
|
||||
}
|
||||
|
||||
size_t Select::size() const {
|
||||
auto options = traits.get_options();
|
||||
return options.size();
|
||||
}
|
||||
|
||||
optional<size_t> Select::index_of(const std::string &option) const {
|
||||
auto options = traits.get_options();
|
||||
auto it = std::find(options.begin(), options.end(), option);
|
||||
if (it == options.end()) {
|
||||
return {};
|
||||
}
|
||||
return std::distance(options.begin(), it);
|
||||
}
|
||||
|
||||
optional<size_t> Select::active_index() const {
|
||||
if (this->has_state()) {
|
||||
return this->index_of(this->state);
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
optional<std::string> Select::at(size_t index) const {
|
||||
auto options = traits.get_options();
|
||||
if (index >= options.size()) {
|
||||
return {};
|
||||
}
|
||||
return options.at(index);
|
||||
}
|
||||
|
||||
uint32_t Select::hash_base() { return 2812997003UL; }
|
||||
|
||||
} // namespace select
|
||||
|
||||
Reference in New Issue
Block a user