diff --git a/esphome/components/mdns/__init__.py b/esphome/components/mdns/__init__.py index 7625b28408..6e148092fe 100644 --- a/esphome/components/mdns/__init__.py +++ b/esphome/components/mdns/__init__.py @@ -126,9 +126,11 @@ async def to_code(config): if cg.is_template(txt_value): # It's a lambda - evaluate and store using helper templated_value = await cg.templatable(txt_value, [], cg.std_string) + safe_key = cg.safe_exp(txt_key) + dynamic_call = f"{var}->add_dynamic_txt_value(({templated_value})())" txt_records.append( cg.RawExpression( - f"{{MDNS_STR({cg.safe_exp(txt_key)}), MDNS_STR({var}->add_dynamic_txt_value(({templated_value})()))}}" + f"{{MDNS_STR({safe_key}), MDNS_STR({dynamic_call})}}" ) ) else: diff --git a/esphome/components/mdns/mdns_component.cpp b/esphome/components/mdns/mdns_component.cpp index d1fc28eee6..8ab14fa935 100644 --- a/esphome/components/mdns/mdns_component.cpp +++ b/esphome/components/mdns/mdns_component.cpp @@ -132,9 +132,9 @@ void MDNSComponent::compile_records_() { #ifdef USE_API_NOISE MDNS_STATIC_CONST_CHAR(NOISE_ENCRYPTION, "Noise_NNpsk0_25519_ChaChaPoly_SHA256"); - txt_records.push_back({MDNS_STR(api::global_api_server->get_noise_ctx()->has_psk() ? TXT_API_ENCRYPTION - : TXT_API_ENCRYPTION_SUPPORTED), - MDNS_STR(NOISE_ENCRYPTION)}); + bool has_psk = api::global_api_server->get_noise_ctx()->has_psk(); + const char *encryption_key = has_psk ? TXT_API_ENCRYPTION : TXT_API_ENCRYPTION_SUPPORTED; + txt_records.push_back({MDNS_STR(encryption_key), MDNS_STR(NOISE_ENCRYPTION)}); #endif #ifdef ESPHOME_PROJECT_NAME diff --git a/esphome/core/defines.h b/esphome/core/defines.h index 2317c0ed32..0f1d1bcf28 100644 --- a/esphome/core/defines.h +++ b/esphome/core/defines.h @@ -84,6 +84,7 @@ #define USE_LVGL_TOUCHSCREEN #define USE_MDNS #define MDNS_SERVICE_COUNT 3 +#define MDNS_DYNAMIC_TXT_COUNT 3 #define USE_MEDIA_PLAYER #define USE_NEXTION_TFT_UPLOAD #define USE_NUMBER diff --git a/esphome/core/helpers.h b/esphome/core/helpers.h index cbb71134fd..c36ecf6f5d 100644 --- a/esphome/core/helpers.h +++ b/esphome/core/helpers.h @@ -149,8 +149,14 @@ template class StaticVector { T &operator[](size_t i) { return data_[i]; } const T &operator[](size_t i) const { return data_[i]; } - T &back() { return data_[count_ - 1]; } - const T &back() const { return data_[count_ - 1]; } + T &back() { + assert(count_ > 0 && "back() called on empty StaticVector"); + return data_[count_ - 1]; + } + const T &back() const { + assert(count_ > 0 && "back() called on empty StaticVector"); + return data_[count_ - 1]; + } // For range-based for loops iterator begin() { return data_.begin(); }