mirror of
https://github.com/esphome/esphome.git
synced 2026-01-17 23:44:52 -07:00
Compare commits
39 Commits
mapping_de
...
string_ref
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5e7aa41b1 | ||
|
|
caa86a4701 | ||
|
|
05dbc0035b | ||
|
|
36e9febba1 | ||
|
|
1dc4a5432f | ||
|
|
451447b0fc | ||
|
|
3cfca5228c | ||
|
|
620667f9d8 | ||
|
|
f3226b108f | ||
|
|
83d164c213 | ||
|
|
1550a6af72 | ||
|
|
18c3dd8af7 | ||
|
|
65cdb97f06 | ||
|
|
37025d62e0 | ||
|
|
798d3bd956 | ||
|
|
77df3933db | ||
|
|
19514ccdf4 | ||
|
|
2947642ca5 | ||
|
|
60e333db08 | ||
|
|
d8463f4813 | ||
|
|
e1800d2fe2 | ||
|
|
50aa4b1992 | ||
|
|
edb303e495 | ||
|
|
973fc4c5dc | ||
|
|
f88e8fc43b | ||
|
|
d830787c71 | ||
|
|
c4c31a2e8e | ||
|
|
e6790f0042 | ||
|
|
ec7f72e280 | ||
|
|
6f29dbd6f1 | ||
|
|
9caf78aa7e | ||
|
|
1f4221abfa | ||
|
|
92808a09c7 | ||
|
|
e54d5ee898 | ||
|
|
bbe1155518 | ||
|
|
69d7b6e921 | ||
|
|
510c874061 | ||
|
|
f7ad324d81 | ||
|
|
58a9e30017 |
@@ -69,6 +69,7 @@ from esphome.cpp_types import ( # noqa: F401
|
||||
JsonObjectConst,
|
||||
Parented,
|
||||
PollingComponent,
|
||||
StringRef,
|
||||
arduino_json_ns,
|
||||
bool_,
|
||||
const_char_ptr,
|
||||
|
||||
@@ -48,14 +48,14 @@ uint32_t ProtoDecodableMessage::count_repeated_field(const uint8_t *buffer, size
|
||||
}
|
||||
uint32_t field_length = res->as_uint32();
|
||||
ptr += consumed;
|
||||
if (ptr + field_length > end) {
|
||||
if (field_length > static_cast<size_t>(end - ptr)) {
|
||||
return count; // Out of bounds
|
||||
}
|
||||
ptr += field_length;
|
||||
break;
|
||||
}
|
||||
case WIRE_TYPE_FIXED32: { // 32-bit - skip 4 bytes
|
||||
if (ptr + 4 > end) {
|
||||
if (end - ptr < 4) {
|
||||
return count;
|
||||
}
|
||||
ptr += 4;
|
||||
@@ -110,7 +110,7 @@ void ProtoDecodableMessage::decode(const uint8_t *buffer, size_t length) {
|
||||
}
|
||||
uint32_t field_length = res->as_uint32();
|
||||
ptr += consumed;
|
||||
if (ptr + field_length > end) {
|
||||
if (field_length > static_cast<size_t>(end - ptr)) {
|
||||
ESP_LOGV(TAG, "Out-of-bounds Length Delimited at offset %ld", (long) (ptr - buffer));
|
||||
return;
|
||||
}
|
||||
@@ -121,7 +121,7 @@ void ProtoDecodableMessage::decode(const uint8_t *buffer, size_t length) {
|
||||
break;
|
||||
}
|
||||
case WIRE_TYPE_FIXED32: { // 32-bit
|
||||
if (ptr + 4 > end) {
|
||||
if (end - ptr < 4) {
|
||||
ESP_LOGV(TAG, "Out-of-bounds Fixed32-bit at offset %ld", (long) (ptr - buffer));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ FanSpeedSetTrigger = fan_ns.class_(
|
||||
"FanSpeedSetTrigger", automation.Trigger.template(cg.int_)
|
||||
)
|
||||
FanPresetSetTrigger = fan_ns.class_(
|
||||
"FanPresetSetTrigger", automation.Trigger.template(cg.std_string)
|
||||
"FanPresetSetTrigger", automation.Trigger.template(cg.StringRef)
|
||||
)
|
||||
|
||||
FanIsOnCondition = fan_ns.class_("FanIsOnCondition", automation.Condition.template())
|
||||
@@ -287,7 +287,7 @@ async def setup_fan_core_(var, config):
|
||||
await automation.build_automation(trigger, [(cg.int_, "x")], conf)
|
||||
for conf in config.get(CONF_ON_PRESET_SET, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(trigger, [(cg.std_string, "x")], conf)
|
||||
await automation.build_automation(trigger, [(cg.StringRef, "x")], conf)
|
||||
|
||||
|
||||
async def register_fan(var, config):
|
||||
|
||||
@@ -208,7 +208,7 @@ class FanSpeedSetTrigger : public Trigger<int> {
|
||||
int last_speed_;
|
||||
};
|
||||
|
||||
class FanPresetSetTrigger : public Trigger<std::string> {
|
||||
class FanPresetSetTrigger : public Trigger<StringRef> {
|
||||
public:
|
||||
FanPresetSetTrigger(Fan *state) {
|
||||
state->add_on_state_callback([this, state]() {
|
||||
@@ -216,7 +216,7 @@ class FanPresetSetTrigger : public Trigger<std::string> {
|
||||
auto should_trigger = preset_mode != this->last_preset_mode_;
|
||||
this->last_preset_mode_ = preset_mode;
|
||||
if (should_trigger) {
|
||||
this->trigger(std::string(preset_mode));
|
||||
this->trigger(preset_mode);
|
||||
}
|
||||
});
|
||||
this->last_preset_mode_ = state->get_preset_mode();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include "hmac_sha256.h"
|
||||
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2040) || defined(USE_LIBRETINY) || defined(USE_HOST)
|
||||
@@ -26,9 +25,7 @@ void HmacSHA256::calculate() { mbedtls_md_hmac_finish(&this->ctx_, this->digest_
|
||||
void HmacSHA256::get_bytes(uint8_t *output) { memcpy(output, this->digest_, SHA256_DIGEST_SIZE); }
|
||||
|
||||
void HmacSHA256::get_hex(char *output) {
|
||||
for (size_t i = 0; i < SHA256_DIGEST_SIZE; i++) {
|
||||
sprintf(output + (i * 2), "%02x", this->digest_[i]);
|
||||
}
|
||||
format_hex_to(output, SHA256_DIGEST_SIZE * 2 + 1, this->digest_, SHA256_DIGEST_SIZE);
|
||||
}
|
||||
|
||||
bool HmacSHA256::equals_bytes(const uint8_t *expected) {
|
||||
|
||||
@@ -242,9 +242,7 @@ template<typename... Ts> class HttpRequestSendAction : public Action<Ts...> {
|
||||
return;
|
||||
}
|
||||
|
||||
size_t content_length = container->content_length;
|
||||
size_t max_length = std::min(content_length, this->max_response_buffer_size_);
|
||||
|
||||
size_t max_length = this->max_response_buffer_size_;
|
||||
#ifdef USE_HTTP_REQUEST_RESPONSE
|
||||
if (this->capture_response_.value(x...)) {
|
||||
std::string response_body;
|
||||
|
||||
@@ -213,18 +213,12 @@ int HttpContainerIDF::read(uint8_t *buf, size_t max_len) {
|
||||
const uint32_t start = millis();
|
||||
watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
|
||||
|
||||
int bufsize = std::min(max_len, this->content_length - this->bytes_read_);
|
||||
|
||||
if (bufsize == 0) {
|
||||
this->duration_ms += (millis() - start);
|
||||
return 0;
|
||||
this->feed_wdt();
|
||||
int read_len = esp_http_client_read(this->client_, (char *) buf, max_len);
|
||||
this->feed_wdt();
|
||||
if (read_len > 0) {
|
||||
this->bytes_read_ += read_len;
|
||||
}
|
||||
|
||||
this->feed_wdt();
|
||||
int read_len = esp_http_client_read(this->client_, (char *) buf, bufsize);
|
||||
this->feed_wdt();
|
||||
this->bytes_read_ += read_len;
|
||||
|
||||
this->duration_ms += (millis() - start);
|
||||
|
||||
return read_len;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from esphome import automation, pins
|
||||
@@ -18,13 +19,16 @@ from esphome.const import (
|
||||
CONF_ROTATION,
|
||||
CONF_UPDATE_INTERVAL,
|
||||
)
|
||||
from esphome.core import ID
|
||||
from esphome.core import ID, EnumValue
|
||||
from esphome.cpp_generator import MockObj, TemplateArgsType
|
||||
import esphome.final_validate as fv
|
||||
from esphome.helpers import add_class_to_obj
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import boards, hub75_ns
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEPENDENCIES = ["esp32"]
|
||||
CODEOWNERS = ["@stuartparmenter"]
|
||||
|
||||
@@ -120,13 +124,51 @@ PANEL_LAYOUTS = {
|
||||
}
|
||||
|
||||
Hub75ScanWiring = cg.global_ns.enum("Hub75ScanWiring", is_class=True)
|
||||
SCAN_PATTERNS = {
|
||||
SCAN_WIRINGS = {
|
||||
"STANDARD_TWO_SCAN": Hub75ScanWiring.STANDARD_TWO_SCAN,
|
||||
"FOUR_SCAN_16PX_HIGH": Hub75ScanWiring.FOUR_SCAN_16PX_HIGH,
|
||||
"FOUR_SCAN_32PX_HIGH": Hub75ScanWiring.FOUR_SCAN_32PX_HIGH,
|
||||
"FOUR_SCAN_64PX_HIGH": Hub75ScanWiring.FOUR_SCAN_64PX_HIGH,
|
||||
"SCAN_1_4_16PX_HIGH": Hub75ScanWiring.SCAN_1_4_16PX_HIGH,
|
||||
"SCAN_1_8_32PX_HIGH": Hub75ScanWiring.SCAN_1_8_32PX_HIGH,
|
||||
"SCAN_1_8_40PX_HIGH": Hub75ScanWiring.SCAN_1_8_40PX_HIGH,
|
||||
"SCAN_1_8_64PX_HIGH": Hub75ScanWiring.SCAN_1_8_64PX_HIGH,
|
||||
}
|
||||
|
||||
# Deprecated scan wiring names - mapped to new names
|
||||
DEPRECATED_SCAN_WIRINGS = {
|
||||
"FOUR_SCAN_16PX_HIGH": "SCAN_1_4_16PX_HIGH",
|
||||
"FOUR_SCAN_32PX_HIGH": "SCAN_1_8_32PX_HIGH",
|
||||
"FOUR_SCAN_64PX_HIGH": "SCAN_1_8_64PX_HIGH",
|
||||
}
|
||||
|
||||
|
||||
def _validate_scan_wiring(value):
|
||||
"""Validate scan_wiring with deprecation warnings for old names."""
|
||||
value = cv.string(value).upper().replace(" ", "_")
|
||||
|
||||
# Check if using deprecated name
|
||||
# Remove deprecated names in 2026.7.0
|
||||
if value in DEPRECATED_SCAN_WIRINGS:
|
||||
new_name = DEPRECATED_SCAN_WIRINGS[value]
|
||||
_LOGGER.warning(
|
||||
"Scan wiring '%s' is deprecated and will be removed in ESPHome 2026.7.0. "
|
||||
"Please use '%s' instead.",
|
||||
value,
|
||||
new_name,
|
||||
)
|
||||
value = new_name
|
||||
|
||||
# Validate against allowed values
|
||||
if value not in SCAN_WIRINGS:
|
||||
raise cv.Invalid(
|
||||
f"Unknown scan wiring '{value}'. "
|
||||
f"Valid options are: {', '.join(sorted(SCAN_WIRINGS.keys()))}"
|
||||
)
|
||||
|
||||
# Return as EnumValue like cv.enum does
|
||||
result = add_class_to_obj(value, EnumValue)
|
||||
result.enum_value = SCAN_WIRINGS[value]
|
||||
return result
|
||||
|
||||
|
||||
Hub75ClockSpeed = cg.global_ns.enum("Hub75ClockSpeed", is_class=True)
|
||||
CLOCK_SPEEDS = {
|
||||
"8MHZ": Hub75ClockSpeed.HZ_8M,
|
||||
@@ -382,9 +424,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.Optional(CONF_LAYOUT_COLS): cv.positive_int,
|
||||
cv.Optional(CONF_LAYOUT): cv.enum(PANEL_LAYOUTS, upper=True, space="_"),
|
||||
# Panel hardware configuration
|
||||
cv.Optional(CONF_SCAN_WIRING): cv.enum(
|
||||
SCAN_PATTERNS, upper=True, space="_"
|
||||
),
|
||||
cv.Optional(CONF_SCAN_WIRING): _validate_scan_wiring,
|
||||
cv.Optional(CONF_SHIFT_DRIVER): cv.enum(SHIFT_DRIVERS, upper=True),
|
||||
# Display configuration
|
||||
cv.Optional(CONF_DOUBLE_BUFFER): cv.boolean,
|
||||
@@ -547,7 +587,7 @@ def _build_config_struct(
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
add_idf_component(
|
||||
name="esphome/esp-hub75",
|
||||
ref="0.2.2",
|
||||
ref="0.3.0",
|
||||
)
|
||||
|
||||
# Set compile-time configuration via build flags (so external library sees them)
|
||||
|
||||
@@ -19,12 +19,12 @@ InfraredCall &InfraredCall::set_carrier_frequency(uint32_t frequency) {
|
||||
InfraredCall &InfraredCall::set_raw_timings(const std::vector<int32_t> &timings) {
|
||||
this->raw_timings_ = &timings;
|
||||
this->packed_data_ = nullptr;
|
||||
this->base85_ptr_ = nullptr;
|
||||
this->base64url_ptr_ = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
InfraredCall &InfraredCall::set_raw_timings_base85(const std::string &base85) {
|
||||
this->base85_ptr_ = &base85;
|
||||
InfraredCall &InfraredCall::set_raw_timings_base64url(const std::string &base64url) {
|
||||
this->base64url_ptr_ = &base64url;
|
||||
this->raw_timings_ = nullptr;
|
||||
this->packed_data_ = nullptr;
|
||||
return *this;
|
||||
@@ -35,7 +35,7 @@ InfraredCall &InfraredCall::set_raw_timings_packed(const uint8_t *data, uint16_t
|
||||
this->packed_length_ = length;
|
||||
this->packed_count_ = count;
|
||||
this->raw_timings_ = nullptr;
|
||||
this->base85_ptr_ = nullptr;
|
||||
this->base64url_ptr_ = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -101,13 +101,22 @@ void Infrared::control(const InfraredCall &call) {
|
||||
call.get_packed_count());
|
||||
ESP_LOGD(TAG, "Transmitting packed raw timings: count=%u, repeat=%u", call.get_packed_count(),
|
||||
call.get_repeat_count());
|
||||
} else if (call.is_base85()) {
|
||||
// Decode base85 directly into transmit buffer (zero heap allocations)
|
||||
if (!transmit_data->set_data_from_base85(call.get_base85_data())) {
|
||||
ESP_LOGE(TAG, "Invalid base85 data");
|
||||
} else if (call.is_base64url()) {
|
||||
// Decode base64url (URL-safe) into transmit buffer
|
||||
if (!transmit_data->set_data_from_base64url(call.get_base64url_data())) {
|
||||
ESP_LOGE(TAG, "Invalid base64url data");
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "Transmitting base85 raw timings: count=%zu, repeat=%u", transmit_data->get_data().size(),
|
||||
// Sanity check: validate timing values are within reasonable bounds
|
||||
constexpr int32_t max_timing_us = 500000; // 500ms absolute max
|
||||
for (int32_t timing : transmit_data->get_data()) {
|
||||
int32_t abs_timing = timing < 0 ? -timing : timing;
|
||||
if (abs_timing > max_timing_us) {
|
||||
ESP_LOGE(TAG, "Invalid timing value: %d µs (max %d)", timing, max_timing_us);
|
||||
return;
|
||||
}
|
||||
}
|
||||
ESP_LOGD(TAG, "Transmitting base64url raw timings: count=%zu, repeat=%u", transmit_data->get_data().size(),
|
||||
call.get_repeat_count());
|
||||
} else {
|
||||
// From vector (lambdas/automations)
|
||||
|
||||
@@ -40,11 +40,11 @@ class InfraredCall {
|
||||
/// @note Usage: Primarily for lambdas/automations where the vector is in scope.
|
||||
InfraredCall &set_raw_timings(const std::vector<int32_t> &timings);
|
||||
|
||||
/// Set the raw timings from base85-encoded int32 data
|
||||
/// Set the raw timings from base64url-encoded little-endian int32 data
|
||||
/// @note Lifetime: Stores a pointer to the string. The string must outlive perform().
|
||||
/// @note Usage: For web_server where the encoded string is on the stack.
|
||||
/// @note Usage: For web_server - base64url is fully URL-safe (uses '-' and '_').
|
||||
/// @note Decoding happens at perform() time, directly into the transmit buffer.
|
||||
InfraredCall &set_raw_timings_base85(const std::string &base85);
|
||||
InfraredCall &set_raw_timings_base64url(const std::string &base64url);
|
||||
|
||||
/// Set the raw timings from packed protobuf sint32 data (zigzag + varint encoded)
|
||||
/// @note Lifetime: Stores a pointer to the buffer. The buffer must outlive perform().
|
||||
@@ -59,18 +59,18 @@ class InfraredCall {
|
||||
|
||||
/// Get the carrier frequency
|
||||
const optional<uint32_t> &get_carrier_frequency() const { return this->carrier_frequency_; }
|
||||
/// Get the raw timings (only valid if set via set_raw_timings, not packed or base85)
|
||||
/// Get the raw timings (only valid if set via set_raw_timings)
|
||||
const std::vector<int32_t> &get_raw_timings() const { return *this->raw_timings_; }
|
||||
/// Check if raw timings have been set (vector, packed, or base85)
|
||||
/// Check if raw timings have been set (any format)
|
||||
bool has_raw_timings() const {
|
||||
return this->raw_timings_ != nullptr || this->packed_data_ != nullptr || this->base85_ptr_ != nullptr;
|
||||
return this->raw_timings_ != nullptr || this->packed_data_ != nullptr || this->base64url_ptr_ != nullptr;
|
||||
}
|
||||
/// Check if using packed data format
|
||||
bool is_packed() const { return this->packed_data_ != nullptr; }
|
||||
/// Check if using base85 data format
|
||||
bool is_base85() const { return this->base85_ptr_ != nullptr; }
|
||||
/// Get the base85 data string
|
||||
const std::string &get_base85_data() const { return *this->base85_ptr_; }
|
||||
/// Check if using base64url data format
|
||||
bool is_base64url() const { return this->base64url_ptr_ != nullptr; }
|
||||
/// Get the base64url data string
|
||||
const std::string &get_base64url_data() const { return *this->base64url_ptr_; }
|
||||
/// Get packed data (only valid if set via set_raw_timings_packed)
|
||||
const uint8_t *get_packed_data() const { return this->packed_data_; }
|
||||
uint16_t get_packed_length() const { return this->packed_length_; }
|
||||
@@ -84,8 +84,8 @@ class InfraredCall {
|
||||
optional<uint32_t> carrier_frequency_;
|
||||
// Pointer to vector-based timings (caller-owned, must outlive perform())
|
||||
const std::vector<int32_t> *raw_timings_{nullptr};
|
||||
// Pointer to base85-encoded string (caller-owned, must outlive perform())
|
||||
const std::string *base85_ptr_{nullptr};
|
||||
// Pointer to base64url-encoded string (caller-owned, must outlive perform())
|
||||
const std::string *base64url_ptr_{nullptr};
|
||||
// Pointer to packed protobuf buffer (caller-owned, must outlive perform())
|
||||
const uint8_t *packed_data_{nullptr};
|
||||
uint16_t packed_length_{0};
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <cinttypes>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
@@ -44,17 +43,8 @@ template<typename K, typename V> class Mapping {
|
||||
esph_log_e(TAG, "Key '%p' not found in mapping", key);
|
||||
} else if constexpr (std::is_same_v<K, std::string>) {
|
||||
esph_log_e(TAG, "Key '%s' not found in mapping", key.c_str());
|
||||
} else if constexpr (std::is_integral_v<K>) {
|
||||
char buf[24]; // enough for 64-bit integer
|
||||
if constexpr (std::is_unsigned_v<K>) {
|
||||
buf_append_printf(buf, sizeof(buf), 0, "%" PRIu64, static_cast<uint64_t>(key));
|
||||
} else {
|
||||
buf_append_printf(buf, sizeof(buf), 0, "%" PRId64, static_cast<int64_t>(key));
|
||||
}
|
||||
esph_log_e(TAG, "Key '%s' not found in mapping", buf);
|
||||
} else {
|
||||
// All supported key types are handled above - this should never be reached
|
||||
static_assert(sizeof(K) == 0, "Unsupported key type for Mapping error logging");
|
||||
esph_log_e(TAG, "Key '%s' not found in mapping", to_string(key).c_str());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
#include <cinttypes>
|
||||
|
||||
namespace esphome {
|
||||
namespace remote_base {
|
||||
|
||||
@@ -160,8 +158,8 @@ void RemoteTransmitData::set_data_from_packed_sint32(const uint8_t *data, size_t
|
||||
}
|
||||
}
|
||||
|
||||
bool RemoteTransmitData::set_data_from_base85(const std::string &base85) {
|
||||
return base85_decode_int32_vector(base85, this->data_);
|
||||
bool RemoteTransmitData::set_data_from_base64url(const std::string &base64url) {
|
||||
return base64_decode_int32_vector(base64url, this->data_);
|
||||
}
|
||||
|
||||
/* RemoteTransmitterBase */
|
||||
|
||||
@@ -36,11 +36,11 @@ class RemoteTransmitData {
|
||||
/// @param len Length of the buffer in bytes
|
||||
/// @param count Number of values (for reserve optimization)
|
||||
void set_data_from_packed_sint32(const uint8_t *data, size_t len, size_t count);
|
||||
/// Set data from base85-encoded int32 values
|
||||
/// Decodes directly into internal buffer (zero heap allocations)
|
||||
/// @param base85 Base85-encoded string (5 chars per int32 value)
|
||||
/// Set data from base64url-encoded little-endian int32 values
|
||||
/// Base64url is URL-safe: uses '-' instead of '+', '_' instead of '/'
|
||||
/// @param base64url Base64url-encoded string of little-endian int32 values
|
||||
/// @return true if successful, false if decode failed or invalid size
|
||||
bool set_data_from_base85(const std::string &base85);
|
||||
bool set_data_from_base64url(const std::string &base64url);
|
||||
void reset() {
|
||||
this->data_.clear();
|
||||
this->carrier_frequency_ = 0;
|
||||
|
||||
@@ -33,7 +33,7 @@ SelectPtr = Select.operator("ptr")
|
||||
# Triggers
|
||||
SelectStateTrigger = select_ns.class_(
|
||||
"SelectStateTrigger",
|
||||
automation.Trigger.template(cg.std_string, cg.size_t),
|
||||
automation.Trigger.template(cg.StringRef, cg.size_t),
|
||||
)
|
||||
|
||||
# Actions
|
||||
@@ -100,7 +100,7 @@ async def setup_select_core_(var, config, *, options: list[str]):
|
||||
for conf in config.get(CONF_ON_VALUE, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
await automation.build_automation(
|
||||
trigger, [(cg.std_string, "x"), (cg.size_t, "i")], conf
|
||||
trigger, [(cg.StringRef, "x"), (cg.size_t, "i")], conf
|
||||
)
|
||||
|
||||
if (mqtt_id := config.get(CONF_MQTT_ID)) is not None:
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
|
||||
namespace esphome::select {
|
||||
|
||||
class SelectStateTrigger : public Trigger<std::string, size_t> {
|
||||
class SelectStateTrigger : public Trigger<StringRef, size_t> {
|
||||
public:
|
||||
explicit SelectStateTrigger(Select *parent) : parent_(parent) {
|
||||
parent->add_on_state_callback(
|
||||
[this](size_t index) { this->trigger(std::string(this->parent_->option_at(index)), index); });
|
||||
[this](size_t index) { this->trigger(StringRef(this->parent_->option_at(index)), index); });
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
@@ -658,6 +658,24 @@ std::string WebServer::text_sensor_json_(text_sensor::TextSensor *obj, const std
|
||||
#endif
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
enum SwitchAction : uint8_t { SWITCH_ACTION_NONE, SWITCH_ACTION_TOGGLE, SWITCH_ACTION_TURN_ON, SWITCH_ACTION_TURN_OFF };
|
||||
|
||||
static void execute_switch_action(switch_::Switch *obj, SwitchAction action) {
|
||||
switch (action) {
|
||||
case SWITCH_ACTION_TOGGLE:
|
||||
obj->toggle();
|
||||
break;
|
||||
case SWITCH_ACTION_TURN_ON:
|
||||
obj->turn_on();
|
||||
break;
|
||||
case SWITCH_ACTION_TURN_OFF:
|
||||
obj->turn_off();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void WebServer::on_switch_update(switch_::Switch *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
@@ -676,34 +694,22 @@ void WebServer::handle_switch_request(AsyncWebServerRequest *request, const UrlM
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle action methods with single defer and response
|
||||
enum SwitchAction { NONE, TOGGLE, TURN_ON, TURN_OFF };
|
||||
SwitchAction action = NONE;
|
||||
SwitchAction action = SWITCH_ACTION_NONE;
|
||||
|
||||
if (match.method_equals(ESPHOME_F("toggle"))) {
|
||||
action = TOGGLE;
|
||||
action = SWITCH_ACTION_TOGGLE;
|
||||
} else if (match.method_equals(ESPHOME_F("turn_on"))) {
|
||||
action = TURN_ON;
|
||||
action = SWITCH_ACTION_TURN_ON;
|
||||
} else if (match.method_equals(ESPHOME_F("turn_off"))) {
|
||||
action = TURN_OFF;
|
||||
action = SWITCH_ACTION_TURN_OFF;
|
||||
}
|
||||
|
||||
if (action != NONE) {
|
||||
this->defer([obj, action]() {
|
||||
switch (action) {
|
||||
case TOGGLE:
|
||||
obj->toggle();
|
||||
break;
|
||||
case TURN_ON:
|
||||
obj->turn_on();
|
||||
break;
|
||||
case TURN_OFF:
|
||||
obj->turn_off();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
if (action != SWITCH_ACTION_NONE) {
|
||||
#ifdef USE_ESP8266
|
||||
execute_switch_action(obj, action);
|
||||
#else
|
||||
this->defer([obj, action]() { execute_switch_action(obj, action); });
|
||||
#endif
|
||||
request->send(200);
|
||||
} else {
|
||||
request->send(404);
|
||||
@@ -743,7 +749,7 @@ void WebServer::handle_button_request(AsyncWebServerRequest *request, const UrlM
|
||||
std::string data = this->button_json_(obj, detail);
|
||||
request->send(200, "application/json", data.c_str());
|
||||
} else if (match.method_equals(ESPHOME_F("press"))) {
|
||||
this->defer([obj]() { obj->press(); });
|
||||
DEFER_ACTION(obj, obj->press());
|
||||
request->send(200);
|
||||
return;
|
||||
} else {
|
||||
@@ -828,7 +834,7 @@ void WebServer::handle_fan_request(AsyncWebServerRequest *request, const UrlMatc
|
||||
std::string data = this->fan_json_(obj, detail);
|
||||
request->send(200, "application/json", data.c_str());
|
||||
} else if (match.method_equals(ESPHOME_F("toggle"))) {
|
||||
this->defer([obj]() { obj->toggle().perform(); });
|
||||
DEFER_ACTION(obj, obj->toggle().perform());
|
||||
request->send(200);
|
||||
} else {
|
||||
bool is_on = match.method_equals(ESPHOME_F("turn_on"));
|
||||
@@ -859,7 +865,7 @@ void WebServer::handle_fan_request(AsyncWebServerRequest *request, const UrlMatc
|
||||
return;
|
||||
}
|
||||
}
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
}
|
||||
return;
|
||||
@@ -909,7 +915,7 @@ void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMa
|
||||
std::string data = this->light_json_(obj, detail);
|
||||
request->send(200, "application/json", data.c_str());
|
||||
} else if (match.method_equals(ESPHOME_F("toggle"))) {
|
||||
this->defer([obj]() { obj->toggle().perform(); });
|
||||
DEFER_ACTION(obj, obj->toggle().perform());
|
||||
request->send(200);
|
||||
} else {
|
||||
bool is_on = match.method_equals(ESPHOME_F("turn_on"));
|
||||
@@ -938,7 +944,7 @@ void WebServer::handle_light_request(AsyncWebServerRequest *request, const UrlMa
|
||||
parse_string_param_(request, ESPHOME_F("effect"), call, &decltype(call)::set_effect);
|
||||
}
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
}
|
||||
return;
|
||||
@@ -1027,7 +1033,7 @@ void WebServer::handle_cover_request(AsyncWebServerRequest *request, const UrlMa
|
||||
parse_float_param_(request, ESPHOME_F("position"), call, &decltype(call)::set_position);
|
||||
parse_float_param_(request, ESPHOME_F("tilt"), call, &decltype(call)::set_tilt);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1086,7 +1092,7 @@ void WebServer::handle_number_request(AsyncWebServerRequest *request, const UrlM
|
||||
auto call = obj->make_call();
|
||||
parse_float_param_(request, ESPHOME_F("value"), call, &decltype(call)::set_value);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1159,7 +1165,7 @@ void WebServer::handle_date_request(AsyncWebServerRequest *request, const UrlMat
|
||||
|
||||
parse_string_param_(request, ESPHOME_F("value"), call, &decltype(call)::set_date);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1223,7 +1229,7 @@ void WebServer::handle_time_request(AsyncWebServerRequest *request, const UrlMat
|
||||
|
||||
parse_string_param_(request, ESPHOME_F("value"), call, &decltype(call)::set_time);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1286,7 +1292,7 @@ void WebServer::handle_datetime_request(AsyncWebServerRequest *request, const Ur
|
||||
|
||||
parse_string_param_(request, ESPHOME_F("value"), call, &decltype(call)::set_datetime);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1346,7 +1352,7 @@ void WebServer::handle_text_request(AsyncWebServerRequest *request, const UrlMat
|
||||
auto call = obj->make_call();
|
||||
parse_string_param_(request, ESPHOME_F("value"), call, &decltype(call)::set_value);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1404,7 +1410,7 @@ void WebServer::handle_select_request(AsyncWebServerRequest *request, const UrlM
|
||||
auto call = obj->make_call();
|
||||
parse_string_param_(request, ESPHOME_F("option"), call, &decltype(call)::set_option);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1473,7 +1479,7 @@ void WebServer::handle_climate_request(AsyncWebServerRequest *request, const Url
|
||||
parse_float_param_(request, ESPHOME_F("target_temperature_low"), call, &decltype(call)::set_target_temperature_low);
|
||||
parse_float_param_(request, ESPHOME_F("target_temperature"), call, &decltype(call)::set_target_temperature);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1589,6 +1595,24 @@ std::string WebServer::climate_json_(climate::Climate *obj, JsonDetail start_con
|
||||
#endif
|
||||
|
||||
#ifdef USE_LOCK
|
||||
enum LockAction : uint8_t { LOCK_ACTION_NONE, LOCK_ACTION_LOCK, LOCK_ACTION_UNLOCK, LOCK_ACTION_OPEN };
|
||||
|
||||
static void execute_lock_action(lock::Lock *obj, LockAction action) {
|
||||
switch (action) {
|
||||
case LOCK_ACTION_LOCK:
|
||||
obj->lock();
|
||||
break;
|
||||
case LOCK_ACTION_UNLOCK:
|
||||
obj->unlock();
|
||||
break;
|
||||
case LOCK_ACTION_OPEN:
|
||||
obj->open();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void WebServer::on_lock_update(lock::Lock *obj) {
|
||||
if (!this->include_internal_ && obj->is_internal())
|
||||
return;
|
||||
@@ -1607,34 +1631,22 @@ void WebServer::handle_lock_request(AsyncWebServerRequest *request, const UrlMat
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle action methods with single defer and response
|
||||
enum LockAction { NONE, LOCK, UNLOCK, OPEN };
|
||||
LockAction action = NONE;
|
||||
LockAction action = LOCK_ACTION_NONE;
|
||||
|
||||
if (match.method_equals(ESPHOME_F("lock"))) {
|
||||
action = LOCK;
|
||||
action = LOCK_ACTION_LOCK;
|
||||
} else if (match.method_equals(ESPHOME_F("unlock"))) {
|
||||
action = UNLOCK;
|
||||
action = LOCK_ACTION_UNLOCK;
|
||||
} else if (match.method_equals(ESPHOME_F("open"))) {
|
||||
action = OPEN;
|
||||
action = LOCK_ACTION_OPEN;
|
||||
}
|
||||
|
||||
if (action != NONE) {
|
||||
this->defer([obj, action]() {
|
||||
switch (action) {
|
||||
case LOCK:
|
||||
obj->lock();
|
||||
break;
|
||||
case UNLOCK:
|
||||
obj->unlock();
|
||||
break;
|
||||
case OPEN:
|
||||
obj->open();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
if (action != LOCK_ACTION_NONE) {
|
||||
#ifdef USE_ESP8266
|
||||
execute_lock_action(obj, action);
|
||||
#else
|
||||
this->defer([obj, action]() { execute_lock_action(obj, action); });
|
||||
#endif
|
||||
request->send(200);
|
||||
} else {
|
||||
request->send(404);
|
||||
@@ -1717,7 +1729,7 @@ void WebServer::handle_valve_request(AsyncWebServerRequest *request, const UrlMa
|
||||
|
||||
parse_float_param_(request, ESPHOME_F("position"), call, &decltype(call)::set_position);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1796,7 +1808,7 @@ void WebServer::handle_alarm_control_panel_request(AsyncWebServerRequest *reques
|
||||
return;
|
||||
}
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -1872,7 +1884,7 @@ void WebServer::handle_water_heater_request(AsyncWebServerRequest *request, cons
|
||||
// Parse on/off parameter
|
||||
parse_bool_param_(request, ESPHOME_F("is_on"), base_call, &water_heater::WaterHeaterCall::set_on);
|
||||
|
||||
this->defer([call]() mutable { call.perform(); });
|
||||
DEFER_ACTION(call, call.perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
@@ -2032,7 +2044,7 @@ void WebServer::handle_update_request(AsyncWebServerRequest *request, const UrlM
|
||||
return;
|
||||
}
|
||||
|
||||
this->defer([obj]() mutable { obj->perform(); });
|
||||
DEFER_ACTION(obj, obj->perform());
|
||||
request->send(200);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -42,6 +42,14 @@ using ParamNameType = const __FlashStringHelper *;
|
||||
using ParamNameType = const char *;
|
||||
#endif
|
||||
|
||||
// ESP8266 is single-threaded, so actions can execute directly in request context.
|
||||
// Multi-core platforms need to defer to main loop thread for thread safety.
|
||||
#ifdef USE_ESP8266
|
||||
#define DEFER_ACTION(capture, action) action
|
||||
#else
|
||||
#define DEFER_ACTION(capture, action) this->defer([capture]() mutable { action; })
|
||||
#endif
|
||||
|
||||
/// Result of matching a URL against an entity
|
||||
struct EntityMatchResult {
|
||||
bool matched; ///< True if entity matched the URL
|
||||
|
||||
@@ -624,53 +624,44 @@ std::vector<uint8_t> base64_decode(const std::string &encoded_string) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// Encode int32 to 5 base85 characters + null terminator
|
||||
/// Standard ASCII85 alphabet: '!' (33) = 0 through 'u' (117) = 84
|
||||
inline void base85_encode_int32(int32_t value, std::span<char, BASE85_INT32_ENCODED_SIZE> output) {
|
||||
uint32_t v = static_cast<uint32_t>(value);
|
||||
// Encode least significant digit first, then reverse
|
||||
for (int i = 4; i >= 0; i--) {
|
||||
output[i] = static_cast<char>('!' + (v % 85));
|
||||
v /= 85;
|
||||
}
|
||||
output[5] = '\0';
|
||||
}
|
||||
|
||||
/// Decode 5 base85 characters to int32
|
||||
inline bool base85_decode_int32(const char *input, int32_t &out) {
|
||||
uint8_t c0 = static_cast<uint8_t>(input[0] - '!');
|
||||
uint8_t c1 = static_cast<uint8_t>(input[1] - '!');
|
||||
uint8_t c2 = static_cast<uint8_t>(input[2] - '!');
|
||||
uint8_t c3 = static_cast<uint8_t>(input[3] - '!');
|
||||
uint8_t c4 = static_cast<uint8_t>(input[4] - '!');
|
||||
|
||||
// Each digit must be 0-84. Since uint8_t wraps, chars below '!' become > 84
|
||||
if (c0 > 84 || c1 > 84 || c2 > 84 || c3 > 84 || c4 > 84)
|
||||
return false;
|
||||
|
||||
// 85^4 = 52200625, 85^3 = 614125, 85^2 = 7225, 85^1 = 85
|
||||
out = static_cast<int32_t>(c0 * 52200625u + c1 * 614125u + c2 * 7225u + c3 * 85u + c4);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Decode base85 string directly into vector (no intermediate buffer)
|
||||
bool base85_decode_int32_vector(const std::string &base85, std::vector<int32_t> &out) {
|
||||
size_t len = base85.size();
|
||||
if (len % 5 != 0)
|
||||
return false;
|
||||
/// Decode base64/base64url string directly into vector of little-endian int32 values
|
||||
/// @param base64 Base64 or base64url encoded string (both +/ and -_ accepted)
|
||||
/// @param out Output vector (cleared and filled with decoded int32 values)
|
||||
/// @return true if successful, false if decode failed or invalid size
|
||||
bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out) {
|
||||
// Decode in chunks to minimize stack usage
|
||||
constexpr size_t chunk_bytes = 48; // 12 int32 values
|
||||
constexpr size_t chunk_chars = 64; // 48 * 4/3 = 64 chars
|
||||
uint8_t chunk[chunk_bytes];
|
||||
|
||||
out.clear();
|
||||
const char *ptr = base85.data();
|
||||
const char *end = ptr + len;
|
||||
|
||||
while (ptr < end) {
|
||||
int32_t value;
|
||||
if (!base85_decode_int32(ptr, value))
|
||||
const uint8_t *input = reinterpret_cast<const uint8_t *>(base64.data());
|
||||
size_t remaining = base64.size();
|
||||
size_t pos = 0;
|
||||
|
||||
while (remaining > 0) {
|
||||
size_t chars_to_decode = std::min(remaining, chunk_chars);
|
||||
size_t decoded_len = base64_decode(input + pos, chars_to_decode, chunk, chunk_bytes);
|
||||
|
||||
if (decoded_len == 0)
|
||||
return false;
|
||||
out.push_back(value);
|
||||
ptr += 5;
|
||||
|
||||
// Parse little-endian int32 values
|
||||
for (size_t i = 0; i + 3 < decoded_len; i += 4) {
|
||||
int32_t timing = static_cast<int32_t>(encode_uint32(chunk[i + 3], chunk[i + 2], chunk[i + 1], chunk[i]));
|
||||
out.push_back(timing);
|
||||
}
|
||||
|
||||
// Check for incomplete int32 in last chunk
|
||||
if (remaining <= chunk_chars && (decoded_len % 4) != 0)
|
||||
return false;
|
||||
|
||||
pos += chars_to_decode;
|
||||
remaining -= chars_to_decode;
|
||||
}
|
||||
return true;
|
||||
|
||||
return !out.empty();
|
||||
}
|
||||
|
||||
// Colors
|
||||
|
||||
@@ -1137,13 +1137,11 @@ std::vector<uint8_t> base64_decode(const std::string &encoded_string);
|
||||
size_t base64_decode(std::string const &encoded_string, uint8_t *buf, size_t buf_len);
|
||||
size_t base64_decode(const uint8_t *encoded_data, size_t encoded_len, uint8_t *buf, size_t buf_len);
|
||||
|
||||
/// Size of buffer needed for base85 encoded int32 (5 chars + null terminator)
|
||||
static constexpr size_t BASE85_INT32_ENCODED_SIZE = 6;
|
||||
|
||||
void base85_encode_int32(int32_t value, std::span<char, BASE85_INT32_ENCODED_SIZE> output);
|
||||
|
||||
bool base85_decode_int32(const char *input, int32_t &out);
|
||||
bool base85_decode_int32_vector(const std::string &base85, std::vector<int32_t> &out);
|
||||
/// Decode base64/base64url string directly into vector of little-endian int32 values
|
||||
/// @param base64 Base64 or base64url encoded string (both +/ and -_ accepted)
|
||||
/// @param out Output vector (cleared and filled with decoded int32 values)
|
||||
/// @return true if successful, false if decode failed or invalid size
|
||||
bool base64_decode_int32_vector(const std::string &base64, std::vector<int32_t> &out);
|
||||
|
||||
///@}
|
||||
|
||||
|
||||
@@ -72,6 +72,7 @@ class StringRef {
|
||||
|
||||
constexpr const char *c_str() const { return base_; }
|
||||
constexpr size_type size() const { return len_; }
|
||||
constexpr size_type length() const { return len_; }
|
||||
constexpr bool empty() const { return len_ == 0; }
|
||||
constexpr const_reference operator[](size_type pos) const { return *(base_ + pos); }
|
||||
|
||||
@@ -80,6 +81,32 @@ class StringRef {
|
||||
|
||||
operator std::string() const { return str(); }
|
||||
|
||||
/// Find first occurrence of substring, returns std::string::npos if not found.
|
||||
/// Note: Requires the underlying string to be null-terminated.
|
||||
size_type find(const char *s, size_type pos = 0) const {
|
||||
if (pos >= len_)
|
||||
return std::string::npos;
|
||||
const char *result = std::strstr(base_ + pos, s);
|
||||
// Verify entire match is within bounds (strstr searches to null terminator)
|
||||
if (result && result + std::strlen(s) <= base_ + len_)
|
||||
return static_cast<size_type>(result - base_);
|
||||
return std::string::npos;
|
||||
}
|
||||
size_type find(char c, size_type pos = 0) const {
|
||||
if (pos >= len_)
|
||||
return std::string::npos;
|
||||
const void *result = std::memchr(base_ + pos, static_cast<unsigned char>(c), len_ - pos);
|
||||
return result ? static_cast<size_type>(static_cast<const char *>(result) - base_) : std::string::npos;
|
||||
}
|
||||
|
||||
/// Return substring as std::string
|
||||
std::string substr(size_type pos = 0, size_type count = std::string::npos) const {
|
||||
if (pos >= len_)
|
||||
return std::string();
|
||||
size_type actual_count = (count == std::string::npos || pos + count > len_) ? len_ - pos : count;
|
||||
return std::string(base_ + pos, actual_count);
|
||||
}
|
||||
|
||||
private:
|
||||
const char *base_;
|
||||
size_type len_;
|
||||
@@ -160,6 +187,43 @@ inline std::string operator+(const std::string &lhs, const StringRef &rhs) {
|
||||
str.append(rhs.c_str(), rhs.size());
|
||||
return str;
|
||||
}
|
||||
// String conversion functions for ADL compatibility (allows stoi(x) where x is StringRef)
|
||||
// Must be in esphome namespace for ADL to find them. Uses strtol/strtod directly to avoid heap allocation.
|
||||
namespace internal {
|
||||
// NOLINTBEGIN(google-runtime-int)
|
||||
template<typename R, typename F> inline R parse_number(const StringRef &str, size_t *pos, F conv) {
|
||||
char *end;
|
||||
R result = conv(str.c_str(), &end);
|
||||
// Set pos to 0 on conversion failure (when no characters consumed), otherwise index after number
|
||||
if (pos)
|
||||
*pos = (end == str.c_str()) ? 0 : static_cast<size_t>(end - str.c_str());
|
||||
return result;
|
||||
}
|
||||
template<typename R, typename F> inline R parse_number(const StringRef &str, size_t *pos, int base, F conv) {
|
||||
char *end;
|
||||
R result = conv(str.c_str(), &end, base);
|
||||
// Set pos to 0 on conversion failure (when no characters consumed), otherwise index after number
|
||||
if (pos)
|
||||
*pos = (end == str.c_str()) ? 0 : static_cast<size_t>(end - str.c_str());
|
||||
return result;
|
||||
}
|
||||
// NOLINTEND(google-runtime-int)
|
||||
} // namespace internal
|
||||
// NOLINTBEGIN(readability-identifier-naming,google-runtime-int)
|
||||
inline int stoi(const StringRef &str, size_t *pos = nullptr, int base = 10) {
|
||||
return static_cast<int>(internal::parse_number<long>(str, pos, base, std::strtol));
|
||||
}
|
||||
inline long stol(const StringRef &str, size_t *pos = nullptr, int base = 10) {
|
||||
return internal::parse_number<long>(str, pos, base, std::strtol);
|
||||
}
|
||||
inline float stof(const StringRef &str, size_t *pos = nullptr) {
|
||||
return internal::parse_number<float>(str, pos, std::strtof);
|
||||
}
|
||||
inline double stod(const StringRef &str, size_t *pos = nullptr) {
|
||||
return internal::parse_number<double>(str, pos, std::strtod);
|
||||
}
|
||||
// NOLINTEND(readability-identifier-naming,google-runtime-int)
|
||||
|
||||
#ifdef USE_JSON
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
inline void convertToJson(const StringRef &src, JsonVariant dst) { dst.set(src.c_str()); }
|
||||
|
||||
@@ -44,3 +44,4 @@ gpio_Flags = gpio_ns.enum("Flags", is_class=True)
|
||||
EntityCategory = esphome_ns.enum("EntityCategory")
|
||||
Parented = esphome_ns.class_("Parented")
|
||||
ESPTime = esphome_ns.struct("ESPTime")
|
||||
StringRef = esphome_ns.class_("StringRef")
|
||||
|
||||
@@ -28,8 +28,8 @@ dependencies:
|
||||
rules:
|
||||
- if: "target in [esp32s2, esp32s3, esp32p4]"
|
||||
esphome/esp-hub75:
|
||||
version: 0.2.2
|
||||
version: 0.3.0
|
||||
rules:
|
||||
- if: "target in [esp32, esp32s2, esp32s3, esp32p4]"
|
||||
- if: "target in [esp32, esp32s2, esp32s3, esp32c6, esp32p4]"
|
||||
esp32async/asynctcp:
|
||||
version: 3.4.91
|
||||
|
||||
85
tests/integration/fixtures/select_stringref_trigger.yaml
Normal file
85
tests/integration/fixtures/select_stringref_trigger.yaml
Normal file
@@ -0,0 +1,85 @@
|
||||
esphome:
|
||||
name: select-stringref-test
|
||||
friendly_name: Select StringRef Test
|
||||
|
||||
host:
|
||||
|
||||
logger:
|
||||
level: DEBUG
|
||||
|
||||
api:
|
||||
|
||||
select:
|
||||
- platform: template
|
||||
name: "Test Select"
|
||||
id: test_select
|
||||
optimistic: true
|
||||
options:
|
||||
- "Option A"
|
||||
- "Option B"
|
||||
- "Option C"
|
||||
initial_option: "Option A"
|
||||
on_value:
|
||||
then:
|
||||
# Test 1: Log the value directly (StringRef -> const char* via c_str())
|
||||
- logger.log:
|
||||
format: "Select value: %s"
|
||||
args: ['x.c_str()']
|
||||
# Test 2: String concatenation (StringRef + const char* -> std::string)
|
||||
- lambda: |-
|
||||
std::string with_suffix = x + " selected";
|
||||
ESP_LOGI("test", "Concatenated: %s", with_suffix.c_str());
|
||||
# Test 3: Comparison (StringRef == const char*)
|
||||
- lambda: |-
|
||||
if (x == "Option B") {
|
||||
ESP_LOGI("test", "Option B was selected");
|
||||
}
|
||||
# Test 4: Use index parameter (variable name is 'i')
|
||||
- lambda: |-
|
||||
ESP_LOGI("test", "Select index: %d", (int)i);
|
||||
# Test 5: StringRef.length() method
|
||||
- lambda: |-
|
||||
ESP_LOGI("test", "Length: %d", (int)x.length());
|
||||
# Test 6: StringRef.find() method with substring
|
||||
- lambda: |-
|
||||
if (x.find("Option") != std::string::npos) {
|
||||
ESP_LOGI("test", "Found 'Option' in value");
|
||||
}
|
||||
# Test 7: StringRef.find() method with character
|
||||
- lambda: |-
|
||||
size_t space_pos = x.find(' ');
|
||||
if (space_pos != std::string::npos) {
|
||||
ESP_LOGI("test", "Space at position: %d", (int)space_pos);
|
||||
}
|
||||
# Test 8: StringRef.substr() method
|
||||
- lambda: |-
|
||||
std::string prefix = x.substr(0, 6);
|
||||
ESP_LOGI("test", "Substr prefix: %s", prefix.c_str());
|
||||
|
||||
# Second select with numeric options to test ADL functions
|
||||
- platform: template
|
||||
name: "Baud Rate"
|
||||
id: baud_select
|
||||
optimistic: true
|
||||
options:
|
||||
- "9600"
|
||||
- "115200"
|
||||
initial_option: "9600"
|
||||
on_value:
|
||||
then:
|
||||
# Test 9: stoi via ADL
|
||||
- lambda: |-
|
||||
int baud = stoi(x);
|
||||
ESP_LOGI("test", "stoi result: %d", baud);
|
||||
# Test 10: stol via ADL
|
||||
- lambda: |-
|
||||
long baud_long = stol(x);
|
||||
ESP_LOGI("test", "stol result: %ld", baud_long);
|
||||
# Test 11: stof via ADL
|
||||
- lambda: |-
|
||||
float baud_float = stof(x);
|
||||
ESP_LOGI("test", "stof result: %.0f", baud_float);
|
||||
# Test 12: stod via ADL
|
||||
- lambda: |-
|
||||
double baud_double = stod(x);
|
||||
ESP_LOGI("test", "stod result: %.0f", baud_double);
|
||||
143
tests/integration/test_select_stringref_trigger.py
Normal file
143
tests/integration/test_select_stringref_trigger.py
Normal file
@@ -0,0 +1,143 @@
|
||||
"""Integration test for select on_value trigger with StringRef parameter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_select_stringref_trigger(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""Test select on_value trigger passes StringRef that works with string operations."""
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
# Track log messages to verify StringRef operations work
|
||||
value_logged_future = loop.create_future()
|
||||
concatenated_future = loop.create_future()
|
||||
comparison_future = loop.create_future()
|
||||
index_logged_future = loop.create_future()
|
||||
length_future = loop.create_future()
|
||||
find_substr_future = loop.create_future()
|
||||
find_char_future = loop.create_future()
|
||||
substr_future = loop.create_future()
|
||||
# ADL functions
|
||||
stoi_future = loop.create_future()
|
||||
stol_future = loop.create_future()
|
||||
stof_future = loop.create_future()
|
||||
stod_future = loop.create_future()
|
||||
|
||||
# Patterns to match in logs
|
||||
value_pattern = re.compile(r"Select value: Option B")
|
||||
concatenated_pattern = re.compile(r"Concatenated: Option B selected")
|
||||
comparison_pattern = re.compile(r"Option B was selected")
|
||||
index_pattern = re.compile(r"Select index: 1")
|
||||
length_pattern = re.compile(r"Length: 8") # "Option B" is 8 chars
|
||||
find_substr_pattern = re.compile(r"Found 'Option' in value")
|
||||
find_char_pattern = re.compile(r"Space at position: 6") # space at index 6
|
||||
substr_pattern = re.compile(r"Substr prefix: Option")
|
||||
# ADL function patterns (115200 from baud rate select)
|
||||
stoi_pattern = re.compile(r"stoi result: 115200")
|
||||
stol_pattern = re.compile(r"stol result: 115200")
|
||||
stof_pattern = re.compile(r"stof result: 115200")
|
||||
stod_pattern = re.compile(r"stod result: 115200")
|
||||
|
||||
def check_output(line: str) -> None:
|
||||
"""Check log output for expected messages."""
|
||||
if not value_logged_future.done() and value_pattern.search(line):
|
||||
value_logged_future.set_result(True)
|
||||
if not concatenated_future.done() and concatenated_pattern.search(line):
|
||||
concatenated_future.set_result(True)
|
||||
if not comparison_future.done() and comparison_pattern.search(line):
|
||||
comparison_future.set_result(True)
|
||||
if not index_logged_future.done() and index_pattern.search(line):
|
||||
index_logged_future.set_result(True)
|
||||
if not length_future.done() and length_pattern.search(line):
|
||||
length_future.set_result(True)
|
||||
if not find_substr_future.done() and find_substr_pattern.search(line):
|
||||
find_substr_future.set_result(True)
|
||||
if not find_char_future.done() and find_char_pattern.search(line):
|
||||
find_char_future.set_result(True)
|
||||
if not substr_future.done() and substr_pattern.search(line):
|
||||
substr_future.set_result(True)
|
||||
# ADL functions
|
||||
if not stoi_future.done() and stoi_pattern.search(line):
|
||||
stoi_future.set_result(True)
|
||||
if not stol_future.done() and stol_pattern.search(line):
|
||||
stol_future.set_result(True)
|
||||
if not stof_future.done() and stof_pattern.search(line):
|
||||
stof_future.set_result(True)
|
||||
if not stod_future.done() and stod_pattern.search(line):
|
||||
stod_future.set_result(True)
|
||||
|
||||
async with (
|
||||
run_compiled(yaml_config, line_callback=check_output),
|
||||
api_client_connected() as client,
|
||||
):
|
||||
# Verify device info
|
||||
device_info = await client.device_info()
|
||||
assert device_info is not None
|
||||
assert device_info.name == "select-stringref-test"
|
||||
|
||||
# List entities to find our select
|
||||
entities, _ = await client.list_entities_services()
|
||||
|
||||
select_entity = next(
|
||||
(e for e in entities if hasattr(e, "options") and e.name == "Test Select"),
|
||||
None,
|
||||
)
|
||||
assert select_entity is not None, "Test Select entity not found"
|
||||
|
||||
baud_entity = next(
|
||||
(e for e in entities if hasattr(e, "options") and e.name == "Baud Rate"),
|
||||
None,
|
||||
)
|
||||
assert baud_entity is not None, "Baud Rate entity not found"
|
||||
|
||||
# Change select to Option B - this should trigger on_value with StringRef
|
||||
client.select_command(select_entity.key, "Option B")
|
||||
# Change baud to 115200 - this tests ADL functions (stoi, stol, stof, stod)
|
||||
client.select_command(baud_entity.key, "115200")
|
||||
|
||||
# Wait for all log messages confirming StringRef operations work
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.gather(
|
||||
value_logged_future,
|
||||
concatenated_future,
|
||||
comparison_future,
|
||||
index_logged_future,
|
||||
length_future,
|
||||
find_substr_future,
|
||||
find_char_future,
|
||||
substr_future,
|
||||
stoi_future,
|
||||
stol_future,
|
||||
stof_future,
|
||||
stod_future,
|
||||
),
|
||||
timeout=5.0,
|
||||
)
|
||||
except TimeoutError:
|
||||
results = {
|
||||
"value_logged": value_logged_future.done(),
|
||||
"concatenated": concatenated_future.done(),
|
||||
"comparison": comparison_future.done(),
|
||||
"index_logged": index_logged_future.done(),
|
||||
"length": length_future.done(),
|
||||
"find_substr": find_substr_future.done(),
|
||||
"find_char": find_char_future.done(),
|
||||
"substr": substr_future.done(),
|
||||
"stoi": stoi_future.done(),
|
||||
"stol": stol_future.done(),
|
||||
"stof": stof_future.done(),
|
||||
"stod": stod_future.done(),
|
||||
}
|
||||
pytest.fail(f"StringRef operations failed - received: {results}")
|
||||
Reference in New Issue
Block a user