diff --git a/esphome/components/climate/climate.cpp b/esphome/components/climate/climate.cpp index 756051d6ce..dc83189692 100644 --- a/esphome/components/climate/climate.cpp +++ b/esphome/components/climate/climate.cpp @@ -197,13 +197,12 @@ ClimateCall &ClimateCall::set_fan_mode(const char *custom_fan_mode) { } } // Find the matching pointer from traits - const auto &supported = this->parent_->get_traits().get_supported_custom_fan_modes(); - for (const char *mode : supported) { - if (strcmp(mode, custom_fan_mode) == 0) { - this->custom_fan_mode_ = mode; - this->fan_mode_.reset(); - return *this; - } + auto traits = this->parent_->get_traits(); + const char *mode_ptr = traits.find_custom_fan_mode(custom_fan_mode); + if (mode_ptr != nullptr) { + this->custom_fan_mode_ = mode_ptr; + this->fan_mode_.reset(); + return *this; } ESP_LOGW(TAG, "'%s' - Unrecognized fan mode %s", this->parent_->get_name().c_str(), custom_fan_mode); return *this; diff --git a/esphome/components/climate/climate_traits.h b/esphome/components/climate/climate_traits.h index 1d4d8b6097..e5171867d5 100644 --- a/esphome/components/climate/climate_traits.h +++ b/esphome/components/climate/climate_traits.h @@ -151,6 +151,14 @@ class ClimateTraits { bool supports_custom_fan_mode(const std::string &custom_fan_mode) const { return this->supports_custom_fan_mode(custom_fan_mode.c_str()); } + /// Find and return the matching custom fan mode pointer from supported modes, or nullptr if not found + const char *find_custom_fan_mode(const char *custom_fan_mode) const { + for (const char *mode : this->supported_custom_fan_modes_) { + if (strcmp(mode, custom_fan_mode) == 0) + return mode; + } + return nullptr; + } void set_supported_presets(ClimatePresetMask presets) { this->supported_presets_ = presets; } void add_supported_preset(ClimatePreset preset) { this->supported_presets_.insert(preset); } @@ -174,6 +182,14 @@ class ClimateTraits { bool supports_custom_preset(const std::string &custom_preset) const { return this->supports_custom_preset(custom_preset.c_str()); } + /// Find and return the matching custom preset pointer from supported presets, or nullptr if not found + const char *find_custom_preset(const char *custom_preset) const { + for (const char *preset : this->supported_custom_presets_) { + if (strcmp(preset, custom_preset) == 0) + return preset; + } + return nullptr; + } void set_supported_swing_modes(ClimateSwingModeMask modes) { this->supported_swing_modes_ = modes; } void add_supported_swing_mode(ClimateSwingMode mode) { this->supported_swing_modes_.insert(mode); }