diff --git a/esphome/components/select/select.cpp b/esphome/components/select/select.cpp index fae485709e..aabd68f420 100644 --- a/esphome/components/select/select.cpp +++ b/esphome/components/select/select.cpp @@ -35,7 +35,12 @@ void Select::publish_state(size_t index) { this->state_callback_.call(std::string(option), index); } -const char *Select::current_option() const { return this->option_at(this->active_index_); } +const char *Select::current_option() const { + if (!this->has_state() || !this->has_index(this->active_index_)) { + return ""; + } + return this->option_at(this->active_index_); +} void Select::add_on_state_callback(std::function &&callback) { this->state_callback_.add(std::move(callback)); diff --git a/esphome/components/select/select.h b/esphome/components/select/select.h index 030646c1ad..1598784c9c 100644 --- a/esphome/components/select/select.h +++ b/esphome/components/select/select.h @@ -77,6 +77,11 @@ class Select : public EntityBase { void add_on_state_callback(std::function &&callback); + protected: + friend class SelectCall; + + size_t active_index_{0}; + /** Set the value of the select by index, this is an optional virtual method. * * This method is called by the SelectCall when the index is already known. @@ -87,11 +92,6 @@ class Select : public EntityBase { */ virtual void control(size_t index) { this->control(this->option_at(index)); } - protected: - friend class SelectCall; - - size_t active_index_{0}; - /** Set the value of the select, this is a virtual method that each select integration can implement. * * This method is called by control(size_t) when not overridden, or directly by external code.