mirror of
https://github.com/esphome/esphome.git
synced 2026-07-10 08:55:36 +00:00
Merge branch 'devirtualize-api-dispatch' into devirtualize-decode
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/components/binary_sensor/binary_sensor.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "crash_handler.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "preferences.h"
|
||||
@@ -15,7 +16,6 @@
|
||||
#include <freertos/task.h>
|
||||
|
||||
void setup(); // NOLINT(readability-redundant-declaration)
|
||||
void loop(); // NOLINT(readability-redundant-declaration)
|
||||
|
||||
// Weak stub for initArduino - overridden when the Arduino component is present
|
||||
extern "C" __attribute__((weak)) void initArduino() {}
|
||||
@@ -65,7 +65,7 @@ TaskHandle_t loop_task_handle = nullptr; // NOLINT(cppcoreguidelines-avoid-non-
|
||||
void loop_task(void *pv_params) {
|
||||
setup();
|
||||
while (true) {
|
||||
loop();
|
||||
App.loop();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,11 @@ def esp32_validate_gpio_pin(value: int) -> int:
|
||||
raise cv.Invalid(f"Invalid pin number: {value} (must be 0-39)")
|
||||
if value in _ESP_SDIO_PINS:
|
||||
raise cv.Invalid(
|
||||
f"This pin cannot be used on ESP32s and is already used by the flash interface (function: {_ESP_SDIO_PINS[value]})"
|
||||
f"This pin cannot be used on ESP32s and is already used by the flash interface"
|
||||
f" (function: {_ESP_SDIO_PINS[value]})."
|
||||
f" If you are using an ESP32 module that uses a different flash pin"
|
||||
f" configuration (e.g. ESP32-PICO-V3-02), you can set"
|
||||
f" 'ignore_pin_validation_error: true' to bypass this check."
|
||||
)
|
||||
if 9 <= value <= 10:
|
||||
_LOGGER.warning(
|
||||
|
||||
@@ -9,11 +9,14 @@
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/portmacro.h>
|
||||
#include "esphome/core/log.h"
|
||||
#include "esp_random.h"
|
||||
#include "esp_system.h"
|
||||
|
||||
namespace esphome {
|
||||
|
||||
static const char *const TAG = "esp32";
|
||||
|
||||
bool random_bytes(uint8_t *data, size_t len) {
|
||||
esp_fill_random(data, len);
|
||||
return true;
|
||||
@@ -63,22 +66,43 @@ LwIPLock::~LwIPLock() {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Read MAC and validate both the return code and content.
|
||||
static bool read_valid_mac(uint8_t *mac, esp_err_t err) { return err == ESP_OK && mac_address_is_valid(mac); }
|
||||
|
||||
static constexpr size_t MAC_ADDRESS_SIZE_BITS = MAC_ADDRESS_SIZE * 8; // 48 bits
|
||||
|
||||
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
|
||||
#if defined(CONFIG_SOC_IEEE802154_SUPPORTED)
|
||||
// When CONFIG_SOC_IEEE802154_SUPPORTED is defined, esp_efuse_mac_get_default
|
||||
// returns the 802.15.4 EUI-64 address, so we read directly from eFuse instead.
|
||||
if (has_custom_mac_address()) {
|
||||
esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48);
|
||||
} else {
|
||||
esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, 48);
|
||||
// Both paths already read raw eFuse bytes, so there is no CRC-bypass fallback
|
||||
// (unlike the non-IEEE802154 path where esp_efuse_mac_get_default does CRC checks).
|
||||
if (has_custom_mac_address() &&
|
||||
read_valid_mac(mac, esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, MAC_ADDRESS_SIZE_BITS))) {
|
||||
return;
|
||||
}
|
||||
if (read_valid_mac(mac, esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, MAC_ADDRESS_SIZE_BITS))) {
|
||||
return;
|
||||
}
|
||||
#else
|
||||
if (has_custom_mac_address()) {
|
||||
esp_efuse_mac_get_custom(mac);
|
||||
} else {
|
||||
esp_efuse_mac_get_default(mac);
|
||||
if (has_custom_mac_address() && read_valid_mac(mac, esp_efuse_mac_get_custom(mac))) {
|
||||
return;
|
||||
}
|
||||
if (read_valid_mac(mac, esp_efuse_mac_get_default(mac))) {
|
||||
return;
|
||||
}
|
||||
// Default MAC read failed (e.g., eFuse CRC error) - try reading raw eFuse bytes
|
||||
// directly, bypassing CRC validation. A MAC that passes mac_address_is_valid()
|
||||
// (non-zero, non-broadcast, unicast) is almost certainly the real factory MAC
|
||||
// with a corrupted CRC byte, which is far better than returning garbage or zeros.
|
||||
if (read_valid_mac(mac, esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, MAC_ADDRESS_SIZE_BITS))) {
|
||||
ESP_LOGW(TAG, "eFuse MAC CRC failed but raw bytes appear valid - using raw eFuse MAC");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
// All methods failed - zero the MAC rather than returning garbage
|
||||
ESP_LOGE(TAG, "Failed to read a valid MAC address from eFuse");
|
||||
memset(mac, 0, MAC_ADDRESS_SIZE);
|
||||
}
|
||||
|
||||
void set_mac_address(uint8_t *mac) { esp_base_mac_addr_set(mac); }
|
||||
@@ -88,9 +112,11 @@ bool has_custom_mac_address() {
|
||||
uint8_t mac[6];
|
||||
// do not use 'esp_efuse_mac_get_custom(mac)' because it drops an error in the logs whenever it fails
|
||||
#ifndef USE_ESP32_VARIANT_ESP32
|
||||
return (esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac);
|
||||
return (esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, MAC_ADDRESS_SIZE_BITS) == ESP_OK) &&
|
||||
mac_address_is_valid(mac);
|
||||
#else
|
||||
return (esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac);
|
||||
return (esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, MAC_ADDRESS_SIZE_BITS) == ESP_OK) &&
|
||||
mac_address_is_valid(mac);
|
||||
#endif
|
||||
#else
|
||||
return false;
|
||||
|
||||
@@ -81,18 +81,32 @@ def _get_data() -> LightData:
|
||||
return CORE.data[DOMAIN]
|
||||
|
||||
|
||||
def generate_gamma_table(gamma_correct: float) -> list[HexInt]:
|
||||
"""Generate a 256-entry uint16 gamma lookup table.
|
||||
|
||||
For gamma > 0, non-zero indices are clamped to a minimum of 1 to preserve
|
||||
the invariant that non-zero input always produces non-zero output. Without
|
||||
this, small brightness values (e.g. 1%) get quantized to exactly 0.0,
|
||||
which breaks zero_means_zero logic in FloatOutput.
|
||||
"""
|
||||
if gamma_correct > 0:
|
||||
return [
|
||||
HexInt(
|
||||
max(1, min(65535, int(round((i / 255.0) ** gamma_correct * 65535))))
|
||||
if i > 0
|
||||
else HexInt(0)
|
||||
)
|
||||
for i in range(256)
|
||||
]
|
||||
return [HexInt(int(round(i / 255.0 * 65535))) for i in range(256)]
|
||||
|
||||
|
||||
def _get_or_create_gamma_table(gamma_correct):
|
||||
data = _get_data()
|
||||
if gamma_correct in data.gamma_tables:
|
||||
return data.gamma_tables[gamma_correct]
|
||||
|
||||
if gamma_correct > 0:
|
||||
forward = [
|
||||
HexInt(min(65535, int(round((i / 255.0) ** gamma_correct * 65535))))
|
||||
for i in range(256)
|
||||
]
|
||||
else:
|
||||
forward = [HexInt(int(round(i / 255.0 * 65535))) for i in range(256)]
|
||||
forward = generate_gamma_table(gamma_correct)
|
||||
|
||||
gamma_str = f"{gamma_correct}".replace(".", "_")
|
||||
fwd_id = ID(f"gamma_{gamma_str}_fwd", is_declaration=True, type=cg.uint16)
|
||||
|
||||
@@ -154,6 +154,16 @@ class LightColorValues {
|
||||
}
|
||||
|
||||
/// Convert these light color values to an CWWW representation with the given parameters.
|
||||
///
|
||||
/// Note on gamma and constant_brightness: This method operates on the raw/internal channel
|
||||
/// values stored in this object. For cold_white_ and warm_white_ specifically, these
|
||||
/// may already be gamma-uncorrected when derived from a color_temperature value.
|
||||
/// For constant_brightness=false, additional gamma for the output can be applied after
|
||||
/// this method since gamma commutes with simple multiplication. For constant_brightness=true,
|
||||
/// the caller (LightState::current_values_as_cwww) must apply gamma to the individual
|
||||
/// channel values BEFORE the balancing formula, because the nonlinear max/sum ratio does
|
||||
/// not commute with gamma. See LightState::current_values_as_cwww() for the correct
|
||||
/// implementation.
|
||||
void as_cwww(float *cold_white, float *warm_white, bool constant_brightness = false) const {
|
||||
if (this->color_mode_ & ColorCapability::COLD_WARM_WHITE) {
|
||||
const float cw_level = this->cold_white_;
|
||||
|
||||
@@ -223,12 +223,11 @@ void LightState::current_values_as_rgbw(float *red, float *green, float *blue, f
|
||||
}
|
||||
void LightState::current_values_as_rgbww(float *red, float *green, float *blue, float *cold_white, float *warm_white,
|
||||
bool constant_brightness) {
|
||||
this->current_values.as_rgbww(red, green, blue, cold_white, warm_white, constant_brightness);
|
||||
this->current_values.as_rgb(red, green, blue);
|
||||
*red = this->gamma_correct_lut(*red);
|
||||
*green = this->gamma_correct_lut(*green);
|
||||
*blue = this->gamma_correct_lut(*blue);
|
||||
*cold_white = this->gamma_correct_lut(*cold_white);
|
||||
*warm_white = this->gamma_correct_lut(*warm_white);
|
||||
this->current_values_as_cwww(cold_white, warm_white, constant_brightness);
|
||||
}
|
||||
void LightState::current_values_as_rgbct(float *red, float *green, float *blue, float *color_temperature,
|
||||
float *white_brightness) {
|
||||
@@ -241,9 +240,45 @@ void LightState::current_values_as_rgbct(float *red, float *green, float *blue,
|
||||
*white_brightness = this->gamma_correct_lut(*white_brightness);
|
||||
}
|
||||
void LightState::current_values_as_cwww(float *cold_white, float *warm_white, bool constant_brightness) {
|
||||
this->current_values.as_cwww(cold_white, warm_white, constant_brightness);
|
||||
*cold_white = this->gamma_correct_lut(*cold_white);
|
||||
*warm_white = this->gamma_correct_lut(*warm_white);
|
||||
if (!constant_brightness) {
|
||||
// Without constant_brightness, gamma commutes with simple multiplication:
|
||||
// gamma(white_level * cw) = gamma(white_level) * gamma(cw)
|
||||
// (since gamma(a*b) = (a*b)^g = a^g * b^g = gamma(a) * gamma(b))
|
||||
// so applying gamma after is mathematically equivalent and simpler.
|
||||
this->current_values.as_cwww(cold_white, warm_white, false);
|
||||
*cold_white = this->gamma_correct_lut(*cold_white);
|
||||
*warm_white = this->gamma_correct_lut(*warm_white);
|
||||
return;
|
||||
}
|
||||
|
||||
// For constant_brightness mode, gamma MUST be applied to the individual
|
||||
// channel values BEFORE the balancing formula (max/sum ratio), not after.
|
||||
//
|
||||
// Why: The cold_white_ and warm_white_ values stored in LightColorValues
|
||||
// are gamma-uncorrected (see transform_parameters_() which applies
|
||||
// gamma_uncorrect to the linear CW/WW fractions derived from color
|
||||
// temperature). Applying gamma_correct here recovers the original linear
|
||||
// fractions, which the constant_brightness formula then uses to distribute
|
||||
// power evenly. The max/sum formula ensures cold+warm PWM output sums to
|
||||
// a constant, keeping total power (and perceived brightness) the same
|
||||
// across all color temperatures.
|
||||
//
|
||||
// Applying gamma AFTER the formula would be incorrect because gamma is
|
||||
// nonlinear: gamma(a/b) != gamma(a)/gamma(b), so the carefully balanced
|
||||
// ratio would be distorted, causing a severe brightness dip at mid-range
|
||||
// color temperatures.
|
||||
const auto &v = this->current_values;
|
||||
if (!(v.get_color_mode() & ColorCapability::COLD_WARM_WHITE)) {
|
||||
*cold_white = *warm_white = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const float cw_level = this->gamma_correct_lut(v.get_cold_white());
|
||||
const float ww_level = this->gamma_correct_lut(v.get_warm_white());
|
||||
const float white_level = this->gamma_correct_lut(v.get_state() * v.get_brightness());
|
||||
const float sum = cw_level > 0 || ww_level > 0 ? cw_level + ww_level : 1; // Don't divide by zero.
|
||||
*cold_white = white_level * std::max(cw_level, ww_level) * cw_level / sum;
|
||||
*warm_white = white_level * std::max(cw_level, ww_level) * ww_level / sum;
|
||||
}
|
||||
void LightState::current_values_as_ct(float *color_temperature, float *white_brightness) {
|
||||
auto traits = this->get_traits();
|
||||
|
||||
@@ -331,11 +331,27 @@ async def to_code(config: ConfigType) -> None:
|
||||
CORE.data.setdefault(CONF_LOGGER, {})[CONF_LEVEL] = level
|
||||
tx_buffer_size = config[CONF_TX_BUFFER_SIZE]
|
||||
cg.add_define("ESPHOME_LOGGER_TX_BUFFER_SIZE", tx_buffer_size)
|
||||
log = cg.new_Pvariable(
|
||||
config[CONF_ID],
|
||||
baud_rate,
|
||||
)
|
||||
if CORE.is_esp32:
|
||||
# Determine task log buffer size and define USE_ESPHOME_TASK_LOG_BUFFER early
|
||||
# so the constructor can allocate the buffer immediately, preventing a race
|
||||
# where another task logs before the buffer is initialized.
|
||||
task_log_buffer_size = 0
|
||||
if CORE.is_esp32 or CORE.is_libretiny or CORE.is_nrf52:
|
||||
task_log_buffer_size = config[CONF_TASK_LOG_BUFFER_SIZE]
|
||||
elif CORE.is_host:
|
||||
task_log_buffer_size = 64 # Fixed 64 slots for host
|
||||
if task_log_buffer_size > 0:
|
||||
cg.add_define("USE_ESPHOME_TASK_LOG_BUFFER")
|
||||
log = cg.new_Pvariable(
|
||||
config[CONF_ID],
|
||||
baud_rate,
|
||||
task_log_buffer_size,
|
||||
)
|
||||
else:
|
||||
log = cg.new_Pvariable(
|
||||
config[CONF_ID],
|
||||
baud_rate,
|
||||
)
|
||||
if CORE.is_esp32 or CORE.is_host:
|
||||
cg.add(log.create_pthread_key())
|
||||
# set_uart_selection() must be called before pre_setup() because
|
||||
# pre_setup() switches on uart_ to decide which hardware to initialize
|
||||
@@ -364,17 +380,10 @@ async def _late_logger_init(config: ConfigType) -> None:
|
||||
log = await cg.get_variable(config[CONF_ID])
|
||||
level = config[CONF_LEVEL]
|
||||
baud_rate: int = config[CONF_BAUD_RATE]
|
||||
if CORE.is_esp32 or CORE.is_libretiny or CORE.is_nrf52:
|
||||
task_log_buffer_size = config[CONF_TASK_LOG_BUFFER_SIZE]
|
||||
if CORE.using_zephyr:
|
||||
task_log_buffer_size = config.get(CONF_TASK_LOG_BUFFER_SIZE, 0)
|
||||
if task_log_buffer_size > 0:
|
||||
cg.add_define("USE_ESPHOME_TASK_LOG_BUFFER")
|
||||
cg.add(log.init_log_buffer(task_log_buffer_size))
|
||||
if CORE.using_zephyr:
|
||||
zephyr_add_prj_conf("MPSC_PBUF", True)
|
||||
elif CORE.is_host:
|
||||
cg.add(log.create_pthread_key())
|
||||
cg.add_define("USE_ESPHOME_TASK_LOG_BUFFER")
|
||||
cg.add(log.init_log_buffer(64)) # Fixed 64 slots for host
|
||||
zephyr_add_prj_conf("MPSC_PBUF", True)
|
||||
|
||||
# Enable runtime tag levels if logs are configured or explicitly enabled
|
||||
logs_config = config[CONF_LOGS]
|
||||
@@ -605,6 +614,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_platform(
|
||||
PlatformFramework.RTL87XX_ARDUINO,
|
||||
PlatformFramework.LN882X_ARDUINO,
|
||||
},
|
||||
"task_log_buffer_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
@@ -8,8 +9,8 @@ namespace esphome::logger {
|
||||
// Maximum header size: 35 bytes fixed + 32 bytes tag + 16 bytes thread name = 83 bytes (45 byte safety margin)
|
||||
static constexpr uint16_t MAX_HEADER_SIZE = 128;
|
||||
|
||||
// ANSI color code last digit (30-38 range, store only last digit to save RAM)
|
||||
static constexpr char LOG_LEVEL_COLOR_DIGIT[] = {
|
||||
// ANSI color code last digit (30-38 range, store only last digit to save RAM on ESP8266)
|
||||
static const char LOG_LEVEL_COLOR_DIGIT[] PROGMEM = {
|
||||
'\0', // NONE
|
||||
'1', // ERROR (31 = red)
|
||||
'3', // WARNING (33 = yellow)
|
||||
@@ -20,7 +21,7 @@ static constexpr char LOG_LEVEL_COLOR_DIGIT[] = {
|
||||
'8', // VERY_VERBOSE (38 = white)
|
||||
};
|
||||
|
||||
static constexpr char LOG_LEVEL_LETTER_CHARS[] = {
|
||||
static const char LOG_LEVEL_LETTER_CHARS[] PROGMEM = {
|
||||
'\0', // NONE
|
||||
'E', // ERROR
|
||||
'W', // WARNING
|
||||
@@ -64,7 +65,7 @@ struct LogBuffer {
|
||||
*p++ = 'V'; // VERY_VERBOSE = "VV"
|
||||
*p++ = 'V';
|
||||
} else {
|
||||
*p++ = LOG_LEVEL_LETTER_CHARS[level];
|
||||
*p++ = static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&LOG_LEVEL_LETTER_CHARS[level])));
|
||||
}
|
||||
}
|
||||
*p++ = ']';
|
||||
@@ -184,7 +185,7 @@ struct LogBuffer {
|
||||
*p++ = (level == 1) ? '1' : '0'; // Only ERROR is bold
|
||||
*p++ = ';';
|
||||
*p++ = '3';
|
||||
*p++ = LOG_LEVEL_COLOR_DIGIT[level];
|
||||
*p++ = static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&LOG_LEVEL_COLOR_DIGIT[level])));
|
||||
*p++ = 'm';
|
||||
}
|
||||
// Copy string without null terminator, updates pointer in place
|
||||
|
||||
@@ -152,29 +152,25 @@ inline uint8_t Logger::level_for(const char *tag) {
|
||||
return this->current_level_;
|
||||
}
|
||||
|
||||
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
|
||||
Logger::Logger(uint32_t baud_rate, size_t task_log_buffer_size) : baud_rate_(baud_rate) {
|
||||
#else
|
||||
Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
|
||||
#endif
|
||||
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
|
||||
this->main_task_ = xTaskGetCurrentTaskHandle();
|
||||
#elif defined(USE_ZEPHYR)
|
||||
this->main_task_ = k_current_get();
|
||||
#elif defined(USE_HOST)
|
||||
this->main_thread_ = pthread_self();
|
||||
this->main_thread_ = pthread_self();
|
||||
#endif
|
||||
}
|
||||
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
|
||||
void Logger::init_log_buffer(size_t total_buffer_size) {
|
||||
// Host uses slot count instead of byte size
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - allocated once, never freed
|
||||
this->log_buffer_ = new logger::TaskLogBuffer(total_buffer_size);
|
||||
|
||||
#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
|
||||
// Start with loop disabled when using task buffer
|
||||
// The loop will be enabled automatically when messages arrive
|
||||
// Zephyr with USB CDC needs loop active to poll port readiness via cdc_loop_()
|
||||
this->disable_loop_when_buffer_empty_();
|
||||
this->log_buffer_ = new logger::TaskLogBuffer(task_log_buffer_size);
|
||||
// Note: we don't disable loop here because the component isn't registered with App yet.
|
||||
// The loop self-disables on its first iteration when it finds no messages to process.
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
|
||||
void Logger::loop() {
|
||||
|
||||
@@ -143,9 +143,10 @@ enum UARTSelection : uint8_t {
|
||||
*/
|
||||
class Logger final : public Component {
|
||||
public:
|
||||
explicit Logger(uint32_t baud_rate);
|
||||
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
|
||||
void init_log_buffer(size_t total_buffer_size);
|
||||
explicit Logger(uint32_t baud_rate, size_t task_log_buffer_size);
|
||||
#else
|
||||
explicit Logger(uint32_t baud_rate);
|
||||
#endif
|
||||
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
|
||||
void loop() override;
|
||||
|
||||
@@ -280,7 +280,7 @@ SWIPE_TRIGGERS = tuple(
|
||||
|
||||
|
||||
LV_ANIM = LvConstant(
|
||||
"LV_SCR_LOAD_ANIM_",
|
||||
"LV_SCREEN_LOAD_ANIM_",
|
||||
"NONE",
|
||||
"OVER_LEFT",
|
||||
"OVER_RIGHT",
|
||||
|
||||
@@ -176,7 +176,11 @@ void LvglComponent::show_page(size_t index, lv_scr_load_anim_t anim, uint32_t ti
|
||||
if (index >= this->pages_.size())
|
||||
return;
|
||||
this->current_page_ = index;
|
||||
lv_scr_load_anim(this->pages_[this->current_page_]->obj, anim, time, 0, false);
|
||||
if (anim == LV_SCREEN_LOAD_ANIM_NONE) {
|
||||
lv_scr_load(this->pages_[this->current_page_]->obj);
|
||||
} else {
|
||||
lv_scr_load_anim(this->pages_[this->current_page_]->obj, anim, time, 0, false);
|
||||
}
|
||||
}
|
||||
|
||||
void LvglComponent::show_next_page(lv_scr_load_anim_t anim, uint32_t time) {
|
||||
@@ -262,8 +266,8 @@ void LvglComponent::flush_cb_(lv_display_t *disp_drv, const lv_area_t *area, uin
|
||||
if (!this->is_paused()) {
|
||||
auto now = millis();
|
||||
this->draw_buffer_(area, reinterpret_cast<lv_color_data *>(color_p));
|
||||
ESP_LOGV(TAG, "flush_cb, area=%d/%d, %d/%d took %dms", area->x1, area->y1, lv_area_get_width(area),
|
||||
lv_area_get_height(area), (int) (millis() - now));
|
||||
ESP_LOGV(TAG, "flush_cb, area=%d/%d, %d/%d took %dms", (int) area->x1, (int) area->y1,
|
||||
(int) lv_area_get_width(area), (int) lv_area_get_height(area), (int) (millis() - now));
|
||||
}
|
||||
lv_display_flush_ready(disp_drv);
|
||||
}
|
||||
@@ -619,7 +623,7 @@ void LvglComponent::setup() {
|
||||
// Rotation will be handled by our drawing function, so reset the display rotation.
|
||||
for (auto *disp : this->displays_)
|
||||
disp->set_rotation(display::DISPLAY_ROTATION_0_DEGREES);
|
||||
this->show_page(0, LV_SCR_LOAD_ANIM_NONE, 0);
|
||||
this->show_page(0, LV_SCREEN_LOAD_ANIM_NONE, 0);
|
||||
lv_display_trigger_activity(this->disp_);
|
||||
}
|
||||
|
||||
@@ -667,9 +671,10 @@ void LvglComponent::static_flush_cb(lv_display_t *disp_drv, const lv_area_t *are
|
||||
* @param e The event data
|
||||
* @param color_start The color to apply to the first tick
|
||||
* @param color_end The color to apply to the last tick
|
||||
* @param width
|
||||
*/
|
||||
void lv_scale_draw_event_cb(lv_event_t *e, uint16_t range_start, uint16_t range_end, lv_color_t color_start,
|
||||
lv_color_t color_end, bool local) {
|
||||
lv_color_t color_end, int width, bool local) {
|
||||
auto *scale = static_cast<lv_obj_t *>(lv_event_get_target(e));
|
||||
lv_draw_task_t *task = lv_event_get_draw_task(e);
|
||||
|
||||
@@ -687,6 +692,7 @@ void lv_scale_draw_event_cb(lv_event_t *e, uint16_t range_start, uint16_t range_
|
||||
range = 1;
|
||||
auto ratio = (tick * 255) / range;
|
||||
line_dsc->color = lv_color_mix(color_end, color_start, ratio);
|
||||
line_dsc->width += width;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ extern std::string lv_event_code_name_for(lv_event_t *event);
|
||||
lv_obj_t *lv_container_create(lv_obj_t *parent);
|
||||
#ifdef USE_LVGL_SCALE
|
||||
void lv_scale_draw_event_cb(lv_event_t *e, uint16_t range_start, uint16_t range_end, lv_color_t color_start,
|
||||
lv_color_t color_end, bool local);
|
||||
lv_color_t color_end, int width, bool local);
|
||||
#endif
|
||||
#if LV_COLOR_DEPTH == 16
|
||||
static const display::ColorBitness LV_BITNESS = display::ColorBitness::COLOR_BITNESS_565;
|
||||
|
||||
@@ -177,7 +177,7 @@ INDICATOR_ARC_SCHEMA = cv.Schema(
|
||||
cv.Optional(CONF_VALUE): lv_float,
|
||||
cv.Optional(CONF_START_VALUE): lv_float,
|
||||
cv.Optional(CONF_END_VALUE): lv_float,
|
||||
cv.Optional(CONF_OPA): opacity,
|
||||
cv.Optional(CONF_OPA, default=1.0): opacity,
|
||||
}
|
||||
).add_extra(cv.has_at_most_one_key(CONF_VALUE, CONF_START_VALUE))
|
||||
|
||||
@@ -247,7 +247,7 @@ SCALE_SCHEMA = cv.Schema(
|
||||
cv.Optional(CONF_RANGE_FROM, default=0.0): lv_int,
|
||||
cv.Optional(CONF_RANGE_TO, default=100.0): lv_int,
|
||||
cv.Optional(CONF_ANGLE_RANGE, default=270): lv_angle_degrees,
|
||||
cv.Optional(CONF_ROTATION, default=0): lv_angle_degrees,
|
||||
cv.Optional(CONF_ROTATION): lv_angle_degrees,
|
||||
cv.Optional(CONF_INDICATORS): cv.ensure_list(INDICATOR_SCHEMA),
|
||||
cv.Optional(CONF_DRAW_TICKS_ON_TOP, default=True): bool,
|
||||
}
|
||||
@@ -329,7 +329,7 @@ class MeterType(WidgetType):
|
||||
)
|
||||
|
||||
def get_uses(self):
|
||||
return CONF_SCALE, CONF_LINE
|
||||
return CONF_SCALE, CONF_LINE, CONF_IMAGE
|
||||
|
||||
def validate(self, value):
|
||||
return cv.has_at_most_one_key(CONF_INDICATOR, CONF_PIVOT)(value)
|
||||
@@ -366,16 +366,17 @@ class MeterType(WidgetType):
|
||||
lv.scale_set_range(scale_var, range_from, range_to)
|
||||
|
||||
angle_range = await lv_angle_degrees.process(scale_conf[CONF_ANGLE_RANGE])
|
||||
rotation = await lv_angle_degrees.process(scale_conf[CONF_ROTATION])
|
||||
if (rotation := scale_conf.get(CONF_ROTATION)) is not None:
|
||||
rotation = await lv_angle_degrees.process(rotation)
|
||||
else:
|
||||
rotation = 90 + (360 - angle_range) // 2
|
||||
|
||||
# Set angle range
|
||||
lv.scale_set_angle_range(
|
||||
scale_var,
|
||||
angle_range,
|
||||
)
|
||||
|
||||
# Set rotation if specified
|
||||
if rotation:
|
||||
lv.scale_set_rotation(scale_var, rotation)
|
||||
lv.scale_set_rotation(scale_var, rotation)
|
||||
|
||||
# Handle indicators as sections
|
||||
for indicator in scale_conf.get(CONF_INDICATORS, ()):
|
||||
@@ -393,10 +394,9 @@ class MeterType(WidgetType):
|
||||
props = {
|
||||
"arc_width": v[CONF_WIDTH],
|
||||
"arc_color": v[CONF_COLOR],
|
||||
"arc_opa": v[CONF_OPA],
|
||||
"arc_rounded": v.get("arc_rounded", False),
|
||||
}
|
||||
if (opa := v.get(CONF_OPA)) is not None:
|
||||
props["arc_opa"] = opa
|
||||
if CONF_R_MOD in v:
|
||||
get_warnings().add(
|
||||
"The 'r_mod' indicator property is not supported in LVGL 9.x and will be ignored."
|
||||
@@ -424,6 +424,7 @@ class MeterType(WidgetType):
|
||||
end_value,
|
||||
color_start,
|
||||
color_end,
|
||||
v[CONF_WIDTH],
|
||||
local,
|
||||
)
|
||||
lv_obj.add_event_cb(
|
||||
|
||||
@@ -28,6 +28,10 @@ namespace esphome::mqtt {
|
||||
|
||||
static const char *const TAG = "mqtt";
|
||||
|
||||
// Maximum number of MQTT component resends per loop iteration.
|
||||
// Limits work to avoid triggering the task watchdog on reconnect.
|
||||
static constexpr uint8_t MAX_RESENDS_PER_LOOP = 8;
|
||||
|
||||
// Disconnect reason strings indexed by MQTTClientDisconnectReason enum (0-8)
|
||||
PROGMEM_STRING_TABLE(MQTTDisconnectReasonStrings, "TCP disconnected", "Unacceptable Protocol Version",
|
||||
"Identifier Rejected", "Server Unavailable", "Malformed Credentials", "Not Authorized",
|
||||
@@ -396,9 +400,16 @@ void MQTTClientComponent::loop() {
|
||||
this->resubscribe_subscriptions_();
|
||||
|
||||
// Process pending resends for all MQTT components centrally
|
||||
// This is more efficient than each component polling in its own loop
|
||||
for (MQTTComponent *component : this->children_) {
|
||||
component->process_resend();
|
||||
// Limit work per loop iteration to avoid triggering task WDT on reconnect
|
||||
{
|
||||
uint8_t resend_count = 0;
|
||||
for (MQTTComponent *component : this->children_) {
|
||||
if (component->is_resend_pending()) {
|
||||
component->process_resend();
|
||||
if (++resend_count >= MAX_RESENDS_PER_LOOP)
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -147,6 +147,9 @@ class MQTTComponent : public Component {
|
||||
/// Internal method for the MQTT client base to schedule a resend of the state on reconnect.
|
||||
void schedule_resend_state();
|
||||
|
||||
/// Check if a resend is pending (called by MQTTClientComponent to rate-limit work)
|
||||
bool is_resend_pending() const { return this->resend_state_; }
|
||||
|
||||
/// Process pending resend if needed (called by MQTTClientComponent)
|
||||
void process_resend();
|
||||
|
||||
|
||||
@@ -177,13 +177,19 @@ async def register_packet_transport(var, config):
|
||||
cg.add(var.set_provider_encryption(name, hash_encryption_key(encryption)))
|
||||
|
||||
is_provider = False
|
||||
for sens_conf in config.get(CONF_SENSORS, ()):
|
||||
sensors = config.get(CONF_SENSORS, ())
|
||||
binary_sensors = config.get(CONF_BINARY_SENSORS, ())
|
||||
if sensors:
|
||||
cg.add(var.set_sensor_count(len(sensors)))
|
||||
if binary_sensors:
|
||||
cg.add(var.set_binary_sensor_count(len(binary_sensors)))
|
||||
for sens_conf in sensors:
|
||||
is_provider = True
|
||||
sens_id = sens_conf[CONF_ID]
|
||||
sensor = await cg.get_variable(sens_id)
|
||||
bcst_id = sens_conf.get(CONF_BROADCAST_ID, sens_id.id)
|
||||
cg.add(var.add_sensor(bcst_id, sensor))
|
||||
for sens_conf in config.get(CONF_BINARY_SENSORS, ()):
|
||||
for sens_conf in binary_sensors:
|
||||
is_provider = True
|
||||
sens_id = sens_conf[CONF_ID]
|
||||
sensor = await cg.get_variable(sens_id)
|
||||
|
||||
@@ -221,16 +221,20 @@ void PacketTransport::setup() {
|
||||
}
|
||||
#ifdef USE_SENSOR
|
||||
for (auto &sensor : this->sensors_) {
|
||||
sensor.sensor->add_on_state_callback([this, &sensor](float x) {
|
||||
this->updated_ = true;
|
||||
// [&sensor] is safe: sensor refers to a FixedVector element that never reallocates,
|
||||
// so the reference remains valid for the component's lifetime.
|
||||
sensor.sensor->add_on_state_callback([&sensor](float x) {
|
||||
sensor.parent->updated_ = true;
|
||||
sensor.updated = true;
|
||||
});
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
for (auto &sensor : this->binary_sensors_) {
|
||||
sensor.sensor->add_on_state_callback([this, &sensor](bool value) {
|
||||
this->updated_ = true;
|
||||
// [&sensor] is safe: sensor refers to a FixedVector element that never reallocates,
|
||||
// so the reference remains valid for the component's lifetime.
|
||||
sensor.sensor->add_on_state_callback([&sensor](bool value) {
|
||||
sensor.parent->updated_ = true;
|
||||
sensor.updated = true;
|
||||
});
|
||||
}
|
||||
@@ -548,11 +552,11 @@ void PacketTransport::dump_config() {
|
||||
" Ping-pong: %s",
|
||||
this->platform_name_, YESNO(this->is_encrypted_()), YESNO(this->ping_pong_enable_));
|
||||
#ifdef USE_SENSOR
|
||||
for (auto sensor : this->sensors_)
|
||||
for (const auto &sensor : this->sensors_)
|
||||
ESP_LOGCONFIG(TAG, " Sensor: %s", sensor.id);
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
for (auto sensor : this->binary_sensors_)
|
||||
for (const auto &sensor : this->binary_sensors_)
|
||||
ESP_LOGCONFIG(TAG, " Binary Sensor: %s", sensor.id);
|
||||
#endif
|
||||
for (const auto &host : this->providers_) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
#ifdef USE_SENSOR
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
@@ -37,11 +38,14 @@ struct Provider {
|
||||
#endif
|
||||
};
|
||||
|
||||
class PacketTransport;
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
struct Sensor {
|
||||
sensor::Sensor *sensor;
|
||||
const char *id;
|
||||
bool updated;
|
||||
PacketTransport *parent;
|
||||
};
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
@@ -49,6 +53,7 @@ struct BinarySensor {
|
||||
binary_sensor::BinarySensor *sensor;
|
||||
const char *id;
|
||||
bool updated;
|
||||
PacketTransport *parent;
|
||||
};
|
||||
#endif
|
||||
|
||||
@@ -60,8 +65,9 @@ class PacketTransport : public PollingComponent {
|
||||
void dump_config() override;
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
void set_sensor_count(size_t count) { this->sensors_.init(count); }
|
||||
void add_sensor(const char *id, sensor::Sensor *sensor) {
|
||||
Sensor st{sensor, id, true};
|
||||
Sensor st{sensor, id, true, this};
|
||||
this->sensors_.push_back(st);
|
||||
}
|
||||
void add_remote_sensor(const char *hostname, const char *remote_id, sensor::Sensor *sensor) {
|
||||
@@ -70,8 +76,9 @@ class PacketTransport : public PollingComponent {
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
void set_binary_sensor_count(size_t count) { this->binary_sensors_.init(count); }
|
||||
void add_binary_sensor(const char *id, binary_sensor::BinarySensor *sensor) {
|
||||
BinarySensor st{sensor, id, true};
|
||||
BinarySensor st{sensor, id, true, this};
|
||||
this->binary_sensors_.push_back(st);
|
||||
}
|
||||
|
||||
@@ -141,11 +148,11 @@ class PacketTransport : public PollingComponent {
|
||||
std::vector<uint8_t> encryption_key_{};
|
||||
|
||||
#ifdef USE_SENSOR
|
||||
std::vector<Sensor> sensors_{};
|
||||
FixedVector<Sensor> sensors_{};
|
||||
string_map_t<string_map_t<sensor::Sensor *>> remote_sensors_{};
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
std::vector<BinarySensor> binary_sensors_{};
|
||||
FixedVector<BinarySensor> binary_sensors_{};
|
||||
string_map_t<string_map_t<binary_sensor::BinarySensor *>> remote_binary_sensors_{};
|
||||
#endif
|
||||
|
||||
|
||||
@@ -95,10 +95,6 @@ void PMSX003Component::loop() {
|
||||
// Just go ahead and read stuff
|
||||
break;
|
||||
}
|
||||
} else if (now - this->last_update_ < this->update_interval_) {
|
||||
// Otherwise just leave the sensor powered up and come back when we hit the update
|
||||
// time
|
||||
return;
|
||||
}
|
||||
|
||||
if (now - this->last_transmission_ >= 500) {
|
||||
@@ -114,10 +110,11 @@ void PMSX003Component::loop() {
|
||||
this->read_byte(&this->data_[this->data_index_]);
|
||||
auto check = this->check_byte_();
|
||||
if (!check.has_value()) {
|
||||
// finished
|
||||
this->parse_data_();
|
||||
if (this->update_interval_ > STABILISING_MS || now - this->last_update_ >= this->update_interval_) {
|
||||
this->parse_data_();
|
||||
this->last_update_ = now;
|
||||
}
|
||||
this->data_index_ = 0;
|
||||
this->last_update_ = now;
|
||||
} else if (!*check) {
|
||||
// wrong data
|
||||
this->data_index_ = 0;
|
||||
@@ -138,7 +135,7 @@ optional<bool> PMSX003Component::check_byte_() {
|
||||
return true;
|
||||
}
|
||||
|
||||
ESP_LOGW(TAG, "Start character %u mismatch: 0x%02X != 0x%02X", index + 1, byte, START_CHARACTER_1);
|
||||
ESP_LOGW(TAG, "Start character %u mismatch: 0x%02X != 0x%02X", index + 1, byte, start_char);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "sht4x.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -9,14 +10,12 @@ static const char *const TAG = "sht4x";
|
||||
static const uint8_t MEASURECOMMANDS[] = {0xFD, 0xF6, 0xE0};
|
||||
static const uint8_t SERIAL_NUMBER_COMMAND = 0x89;
|
||||
|
||||
void SHT4XComponent::start_heater_() {
|
||||
uint8_t cmd[] = {this->heater_command_};
|
||||
|
||||
ESP_LOGD(TAG, "Heater turning on");
|
||||
if (this->write(cmd, 1) != i2c::ERROR_OK) {
|
||||
this->status_set_error(LOG_STR("Failed to turn on heater"));
|
||||
}
|
||||
}
|
||||
// Conversion constants from SHT4x datasheet
|
||||
static constexpr float TEMPERATURE_OFFSET = -45.0f;
|
||||
static constexpr float TEMPERATURE_SPAN = 175.0f;
|
||||
static constexpr float HUMIDITY_OFFSET = -6.0f;
|
||||
static constexpr float HUMIDITY_SPAN = 125.0f;
|
||||
static constexpr float RAW_MAX = 65535.0f;
|
||||
|
||||
void SHT4XComponent::read_serial_number_() {
|
||||
uint16_t buffer[2];
|
||||
@@ -39,8 +38,8 @@ void SHT4XComponent::setup() {
|
||||
this->read_serial_number_();
|
||||
|
||||
if (std::isfinite(this->duty_cycle_) && this->duty_cycle_ > 0.0f) {
|
||||
uint32_t heater_interval = static_cast<uint32_t>(static_cast<uint16_t>(this->heater_time_) / this->duty_cycle_);
|
||||
ESP_LOGD(TAG, "Heater interval: %" PRIu32, heater_interval);
|
||||
this->heater_interval_ = static_cast<uint32_t>(static_cast<uint16_t>(this->heater_time_) / this->duty_cycle_);
|
||||
ESP_LOGD(TAG, "Heater interval: %" PRIu32, this->heater_interval_);
|
||||
|
||||
if (this->heater_power_ == SHT4X_HEATERPOWER_HIGH) {
|
||||
if (this->heater_time_ == SHT4X_HEATERTIME_LONG) {
|
||||
@@ -62,8 +61,6 @@ void SHT4XComponent::setup() {
|
||||
}
|
||||
}
|
||||
ESP_LOGD(TAG, "Heater command: %x", this->heater_command_);
|
||||
|
||||
this->set_interval(heater_interval, [this]() { this->start_heater_(); });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,19 +103,27 @@ void SHT4XComponent::update() {
|
||||
// Evaluate and publish measurements
|
||||
if (this->temp_sensor_ != nullptr) {
|
||||
// Temp is contained in the first result word
|
||||
float sensor_value_temp = buffer[0];
|
||||
float temp = -45 + 175 * sensor_value_temp / 65535;
|
||||
|
||||
float temp = TEMPERATURE_OFFSET + TEMPERATURE_SPAN * static_cast<float>(buffer[0]) / RAW_MAX;
|
||||
this->temp_sensor_->publish_state(temp);
|
||||
}
|
||||
|
||||
if (this->humidity_sensor_ != nullptr) {
|
||||
// Relative humidity is in the second result word
|
||||
float sensor_value_rh = buffer[1];
|
||||
float rh = -6 + 125 * sensor_value_rh / 65535;
|
||||
|
||||
float rh = HUMIDITY_OFFSET + HUMIDITY_SPAN * static_cast<float>(buffer[1]) / RAW_MAX;
|
||||
this->humidity_sensor_->publish_state(rh);
|
||||
}
|
||||
|
||||
// Fire heater after measurement to maximize cooldown time before the next reading.
|
||||
// The heater command produces a measurement that we don't need (datasheet 4.9).
|
||||
if (this->heater_interval_ > 0) {
|
||||
uint32_t now = millis();
|
||||
if (now - this->last_heater_millis_ >= this->heater_interval_) {
|
||||
ESP_LOGD(TAG, "Heater turning on");
|
||||
if (this->write_command(this->heater_command_)) {
|
||||
this->last_heater_millis_ = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -35,9 +35,10 @@ class SHT4XComponent : public PollingComponent, public sensirion_common::Sensiri
|
||||
SHT4XHEATERTIME heater_time_;
|
||||
float duty_cycle_;
|
||||
|
||||
void start_heater_();
|
||||
void read_serial_number_();
|
||||
uint8_t heater_command_;
|
||||
uint32_t heater_interval_{0};
|
||||
uint32_t last_heater_millis_{0};
|
||||
uint32_t serial_number_;
|
||||
|
||||
sensor::Sensor *temp_sensor_{nullptr};
|
||||
|
||||
@@ -125,7 +125,7 @@ size_t format_sockaddr_to(const struct sockaddr *addr_ptr, socklen_t len, std::s
|
||||
/// On ESP8266, uses esp_delay() with a callback that checks socket activity.
|
||||
/// On RP2040, uses __wfe() (Wait For Event) to truly sleep until an interrupt
|
||||
/// (for example, CYW43 GPIO or a timer alarm) fires and wakes the CPU.
|
||||
void socket_delay(uint32_t ms);
|
||||
void socket_delay(uint32_t ms); // NOLINT(readability-redundant-declaration)
|
||||
|
||||
/// Signal socket/IO activity and wake the main loop early.
|
||||
/// On ESP8266: sets flag + esp_schedule().
|
||||
|
||||
@@ -30,12 +30,17 @@ enum UARTDirection {
|
||||
const LogString *parity_to_str(UARTParityOptions parity);
|
||||
|
||||
/// Result of a flush() call.
|
||||
// Some vendor SDKs (e.g., Realtek) define SUCCESS as a macro.
|
||||
// Save and restore around the enum to avoid collisions with our scoped enum value.
|
||||
#pragma push_macro("SUCCESS")
|
||||
#undef SUCCESS
|
||||
enum class FlushResult {
|
||||
SUCCESS, ///< Confirmed: all bytes left the TX FIFO.
|
||||
TIMEOUT, ///< Confirmed: timed out before TX completed.
|
||||
FAILED, ///< Confirmed: driver or hardware error.
|
||||
ASSUMED_SUCCESS, ///< Platform cannot report result; success is assumed.
|
||||
};
|
||||
#pragma pop_macro("SUCCESS")
|
||||
|
||||
class UARTComponent {
|
||||
public:
|
||||
|
||||
@@ -6,11 +6,17 @@ namespace esphome::ultrasonic {
|
||||
|
||||
static const char *const TAG = "ultrasonic.sensor";
|
||||
|
||||
static constexpr uint32_t DEBOUNCE_US = 50; // Ignore edges within 50us of each other (noise filtering)
|
||||
static constexpr uint32_t START_DELAY_US = 100; // Ignore edges within 100us of trigger (filters bleed-through)
|
||||
static constexpr uint32_t START_TIMEOUT_US = 40000; // Maximum time to wait for echo pulse to start
|
||||
|
||||
void IRAM_ATTR UltrasonicSensorStore::gpio_intr(UltrasonicSensorStore *arg) {
|
||||
uint32_t now = micros();
|
||||
if (arg->echo_pin_isr.digital_read()) {
|
||||
// Ignore edges after measurement complete or too soon after trigger pulse
|
||||
if (arg->echo_end || (now - arg->measurement_start_us) <= START_DELAY_US) {
|
||||
return;
|
||||
}
|
||||
if (!arg->echo_start || (now - arg->echo_start_us) <= DEBOUNCE_US) {
|
||||
arg->echo_start_us = now;
|
||||
arg->echo_start = true;
|
||||
} else {
|
||||
@@ -21,15 +27,14 @@ void IRAM_ATTR UltrasonicSensorStore::gpio_intr(UltrasonicSensorStore *arg) {
|
||||
|
||||
void IRAM_ATTR UltrasonicSensorComponent::send_trigger_pulse_() {
|
||||
InterruptLock lock;
|
||||
this->store_.echo_start_us = 0;
|
||||
this->store_.echo_end_us = 0;
|
||||
this->store_.echo_start = false;
|
||||
this->store_.echo_end = false;
|
||||
this->store_.measurement_start_us = micros();
|
||||
this->trigger_pin_isr_.digital_write(true);
|
||||
delayMicroseconds(this->pulse_time_us_);
|
||||
this->trigger_pin_isr_.digital_write(false);
|
||||
this->measurement_pending_ = true;
|
||||
this->measurement_start_us_ = micros();
|
||||
this->measurement_start_us_ = this->store_.measurement_start_us;
|
||||
}
|
||||
|
||||
void UltrasonicSensorComponent::setup() {
|
||||
@@ -37,7 +42,6 @@ void UltrasonicSensorComponent::setup() {
|
||||
this->trigger_pin_->digital_write(false);
|
||||
this->trigger_pin_isr_ = this->trigger_pin_->to_isr();
|
||||
this->echo_pin_->setup();
|
||||
this->store_.echo_pin_isr = this->echo_pin_->to_isr();
|
||||
this->echo_pin_->attach_interrupt(UltrasonicSensorStore::gpio_intr, &this->store_, gpio::INTERRUPT_ANY_EDGE);
|
||||
}
|
||||
|
||||
@@ -77,17 +81,10 @@ void UltrasonicSensorComponent::loop() {
|
||||
}
|
||||
|
||||
if (this->store_.echo_end) {
|
||||
float result;
|
||||
if (this->store_.echo_start) {
|
||||
uint32_t pulse_duration = this->store_.echo_end_us - this->store_.echo_start_us;
|
||||
ESP_LOGV(TAG, "pulse start took %" PRIu32 "us, echo took %" PRIu32 "us",
|
||||
this->store_.echo_start_us - this->measurement_start_us_, pulse_duration);
|
||||
result = UltrasonicSensorComponent::us_to_m(pulse_duration);
|
||||
ESP_LOGD(TAG, "'%s' - Got distance: %.3f m", this->name_.c_str(), result);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "'%s' - pulse end before pulse start, does the echo pin need to be inverted?", this->name_.c_str());
|
||||
result = NAN;
|
||||
}
|
||||
uint32_t pulse_duration = this->store_.echo_end_us - this->store_.echo_start_us;
|
||||
ESP_LOGV(TAG, "Echo took %" PRIu32 "us", pulse_duration);
|
||||
float result = UltrasonicSensorComponent::us_to_m(pulse_duration);
|
||||
ESP_LOGD(TAG, "'%s' - Got distance: %.3f m", this->name_.c_str(), result);
|
||||
this->publish_state(result);
|
||||
this->measurement_pending_ = false;
|
||||
return;
|
||||
|
||||
@@ -11,8 +11,7 @@ namespace esphome::ultrasonic {
|
||||
struct UltrasonicSensorStore {
|
||||
static void gpio_intr(UltrasonicSensorStore *arg);
|
||||
|
||||
ISRInternalGPIOPin echo_pin_isr;
|
||||
volatile uint32_t wait_start_us{0};
|
||||
volatile uint32_t measurement_start_us{0};
|
||||
volatile uint32_t echo_start_us{0};
|
||||
volatile uint32_t echo_end_us{0};
|
||||
volatile bool echo_start{false};
|
||||
|
||||
@@ -262,19 +262,6 @@ StringRef AsyncWebServerRequest::url_to(std::span<char, URL_BUF_SIZE> buffer) co
|
||||
return StringRef(buffer.data(), decoded_len);
|
||||
}
|
||||
|
||||
void AsyncWebServerRequest::send(AsyncWebServerResponse *response) {
|
||||
httpd_resp_send(*this, response->get_content_data(), response->get_content_size());
|
||||
}
|
||||
|
||||
void AsyncWebServerRequest::send(int code, const char *content_type, const char *content) {
|
||||
this->init_response_(nullptr, code, content_type);
|
||||
if (content) {
|
||||
httpd_resp_send(*this, content, HTTPD_RESP_USE_STRLEN);
|
||||
} else {
|
||||
httpd_resp_send(*this, nullptr, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncWebServerRequest::redirect(const std::string &url) {
|
||||
httpd_resp_set_status(*this, "302 Found");
|
||||
httpd_resp_set_hdr(*this, "Location", url.c_str());
|
||||
|
||||
@@ -134,8 +134,17 @@ class AsyncWebServerRequest {
|
||||
|
||||
void redirect(const std::string &url);
|
||||
|
||||
void send(AsyncWebServerResponse *response);
|
||||
void send(int code, const char *content_type = nullptr, const char *content = nullptr);
|
||||
inline void ESPHOME_ALWAYS_INLINE send(AsyncWebServerResponse *response) {
|
||||
httpd_resp_send(*this, response->get_content_data(), response->get_content_size());
|
||||
}
|
||||
inline void ESPHOME_ALWAYS_INLINE send(int code, const char *content_type = nullptr, const char *content = nullptr) {
|
||||
this->init_response_(nullptr, code, content_type);
|
||||
if (content) {
|
||||
httpd_resp_send(*this, content, HTTPD_RESP_USE_STRLEN);
|
||||
} else {
|
||||
httpd_resp_send(*this, nullptr, 0);
|
||||
}
|
||||
}
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
AsyncWebServerResponse *beginResponse(int code, const char *content_type) {
|
||||
auto *res = new AsyncWebServerResponseEmpty(this); // NOLINT(cppcoreguidelines-owning-memory)
|
||||
|
||||
@@ -871,9 +871,6 @@ void WiFiComponent::loop() {
|
||||
|
||||
WiFiComponent::WiFiComponent() { global_wifi_component = this; }
|
||||
|
||||
bool WiFiComponent::has_ap() const { return this->has_ap_; }
|
||||
bool WiFiComponent::is_ap_active() const { return this->ap_started_; }
|
||||
bool WiFiComponent::has_sta() const { return !this->sta_.empty(); }
|
||||
#ifdef USE_WIFI_11KV_SUPPORT
|
||||
void WiFiComponent::set_btm(bool btm) { this->btm_ = btm; }
|
||||
void WiFiComponent::set_rrm(bool rrm) { this->rrm_ = rrm; }
|
||||
@@ -2250,8 +2247,6 @@ bool WiFiAP::has_bssid() const { return this->bssid_ != bssid_t{}; }
|
||||
#ifdef USE_WIFI_WPA2_EAP
|
||||
const optional<EAPAuth> &WiFiAP::get_eap() const { return this->eap_; }
|
||||
#endif
|
||||
uint8_t WiFiAP::get_channel() const { return this->channel_; }
|
||||
bool WiFiAP::has_channel() const { return this->channel_ != 0; }
|
||||
#ifdef USE_WIFI_MANUAL_IP
|
||||
const optional<ManualIP> &WiFiAP::get_manual_ip() const { return this->manual_ip_; }
|
||||
#endif
|
||||
|
||||
@@ -263,8 +263,8 @@ class WiFiAP {
|
||||
#ifdef USE_WIFI_WPA2_EAP
|
||||
const optional<EAPAuth> &get_eap() const;
|
||||
#endif // USE_WIFI_WPA2_EAP
|
||||
uint8_t get_channel() const;
|
||||
bool has_channel() const;
|
||||
uint8_t get_channel() const { return this->channel_; }
|
||||
bool has_channel() const { return this->channel_ != 0; }
|
||||
int8_t get_priority() const { return priority_; }
|
||||
#ifdef USE_WIFI_MANUAL_IP
|
||||
const optional<ManualIP> &get_manual_ip() const;
|
||||
@@ -470,9 +470,9 @@ class WiFiComponent final : public Component {
|
||||
/// Reconnect WiFi if required.
|
||||
void loop() override;
|
||||
|
||||
bool has_sta() const;
|
||||
bool has_ap() const;
|
||||
bool is_ap_active() const;
|
||||
bool has_sta() const { return !this->sta_.empty(); }
|
||||
bool has_ap() const { return this->has_ap_; }
|
||||
bool is_ap_active() const { return this->ap_started_; }
|
||||
|
||||
#ifdef USE_WIFI_11KV_SUPPORT
|
||||
void set_btm(bool btm);
|
||||
|
||||
@@ -12,21 +12,11 @@
|
||||
#endif
|
||||
#ifdef USE_LWIP_FAST_SELECT
|
||||
#include "esphome/core/lwip_fast_select.h"
|
||||
#ifdef USE_ESP32
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#else
|
||||
#include <FreeRTOS.h>
|
||||
#include <task.h>
|
||||
#endif
|
||||
#endif // USE_LWIP_FAST_SELECT
|
||||
#include "esphome/core/version.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include <algorithm>
|
||||
#include <ranges>
|
||||
#ifdef USE_RUNTIME_STATS
|
||||
#include "esphome/components/runtime_stats/runtime_stats.h"
|
||||
#endif
|
||||
|
||||
#ifdef USE_STATUS_LED
|
||||
#include "esphome/components/status_led/status_led.h"
|
||||
@@ -163,66 +153,6 @@ void Application::setup() {
|
||||
|
||||
this->schedule_dump_config();
|
||||
}
|
||||
void Application::loop() {
|
||||
uint8_t new_app_state = 0;
|
||||
|
||||
// Get the initial loop time at the start
|
||||
uint32_t last_op_end_time = millis();
|
||||
|
||||
this->before_loop_tasks_(last_op_end_time);
|
||||
|
||||
for (this->current_loop_index_ = 0; this->current_loop_index_ < this->looping_components_active_end_;
|
||||
this->current_loop_index_++) {
|
||||
Component *component = this->looping_components_[this->current_loop_index_];
|
||||
|
||||
// Update the cached time before each component runs
|
||||
this->loop_component_start_time_ = last_op_end_time;
|
||||
|
||||
{
|
||||
this->set_current_component(component);
|
||||
WarnIfComponentBlockingGuard guard{component, last_op_end_time};
|
||||
component->loop();
|
||||
// Use the finish method to get the current time as the end time
|
||||
last_op_end_time = guard.finish();
|
||||
}
|
||||
new_app_state |= component->get_component_state();
|
||||
this->app_state_ |= new_app_state;
|
||||
this->feed_wdt(last_op_end_time);
|
||||
}
|
||||
|
||||
this->after_loop_tasks_();
|
||||
this->app_state_ = new_app_state;
|
||||
|
||||
#ifdef USE_RUNTIME_STATS
|
||||
// Process any pending runtime stats printing after all components have run
|
||||
// This ensures stats printing doesn't affect component timing measurements
|
||||
if (global_runtime_stats != nullptr) {
|
||||
global_runtime_stats->process_pending_stats(last_op_end_time);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Use the last component's end time instead of calling millis() again
|
||||
auto elapsed = last_op_end_time - this->last_loop_;
|
||||
if (elapsed >= this->loop_interval_ || HighFrequencyLoopRequester::is_high_frequency()) {
|
||||
// Even if we overran the loop interval, we still need to select()
|
||||
// to know if any sockets have data ready
|
||||
this->yield_with_select_(0);
|
||||
} else {
|
||||
uint32_t delay_time = this->loop_interval_ - elapsed;
|
||||
uint32_t next_schedule = this->scheduler.next_schedule_in(last_op_end_time).value_or(delay_time);
|
||||
// next_schedule is max 0.5*delay_time
|
||||
// otherwise interval=0 schedules result in constant looping with almost no sleep
|
||||
next_schedule = std::max(next_schedule, delay_time / 2);
|
||||
delay_time = std::min(next_schedule, delay_time);
|
||||
|
||||
this->yield_with_select_(delay_time);
|
||||
}
|
||||
this->last_loop_ = last_op_end_time;
|
||||
|
||||
if (this->dump_config_at_ < this->components_.size()) {
|
||||
this->process_dump_config_();
|
||||
}
|
||||
}
|
||||
|
||||
void Application::process_dump_config_() {
|
||||
if (this->dump_config_at_ == 0) {
|
||||
@@ -509,41 +439,6 @@ void Application::enable_pending_loops_() {
|
||||
}
|
||||
}
|
||||
|
||||
void Application::before_loop_tasks_(uint32_t loop_start_time) {
|
||||
#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE) && !defined(USE_LWIP_FAST_SELECT)
|
||||
// Drain wake notifications first to clear socket for next wake
|
||||
this->drain_wake_notifications_();
|
||||
#endif
|
||||
|
||||
// Process scheduled tasks
|
||||
this->scheduler.call(loop_start_time);
|
||||
|
||||
// Feed the watchdog timer
|
||||
this->feed_wdt(loop_start_time);
|
||||
|
||||
// Process any pending enable_loop requests from ISRs
|
||||
// This must be done before marking in_loop_ = true to avoid race conditions
|
||||
if (this->has_pending_enable_loop_requests_) {
|
||||
// Clear flag BEFORE processing to avoid race condition
|
||||
// If ISR sets it during processing, we'll catch it next loop iteration
|
||||
// This is safe because:
|
||||
// 1. Each component has its own pending_enable_loop_ flag that we check
|
||||
// 2. If we can't process a component (wrong state), enable_pending_loops_()
|
||||
// will set this flag back to true
|
||||
// 3. Any new ISR requests during processing will set the flag again
|
||||
this->has_pending_enable_loop_requests_ = false;
|
||||
this->enable_pending_loops_();
|
||||
}
|
||||
|
||||
// Mark that we're in the loop for safe reentrant modifications
|
||||
this->in_loop_ = true;
|
||||
}
|
||||
|
||||
void Application::after_loop_tasks_() {
|
||||
// Clear the in_loop_ flag to indicate we're done processing components
|
||||
this->in_loop_ = false;
|
||||
}
|
||||
|
||||
#ifdef USE_LWIP_FAST_SELECT
|
||||
bool Application::register_socket(struct lwip_sock *sock) {
|
||||
// It modifies monitored_sockets_ without locking — must only be called from the main loop.
|
||||
@@ -625,36 +520,10 @@ void Application::unregister_socket_fd(int fd) {
|
||||
|
||||
#endif
|
||||
|
||||
// Only the select() fallback path remains in the .cpp — all other paths are inlined in application.h
|
||||
#if defined(USE_SOCKET_SELECT_SUPPORT) && !defined(USE_LWIP_FAST_SELECT)
|
||||
void Application::yield_with_select_(uint32_t delay_ms) {
|
||||
// Delay while monitoring sockets. When delay_ms is 0, always yield() to ensure other tasks run.
|
||||
#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_LWIP_FAST_SELECT)
|
||||
// Fast path (ESP32/LibreTiny): reads rcvevent directly from cached lwip_sock pointers.
|
||||
// Safe because this runs on the main loop which owns socket lifetime (create, read, close).
|
||||
if (delay_ms == 0) [[unlikely]] {
|
||||
yield();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if any socket already has pending data before sleeping.
|
||||
// If a socket still has unread data (rcvevent > 0) but the task notification was already
|
||||
// consumed, ulTaskNotifyTake would block until timeout — adding up to delay_ms latency.
|
||||
// This scan preserves select() semantics: return immediately when any fd is ready.
|
||||
for (struct lwip_sock *sock : this->monitored_sockets_) {
|
||||
if (esphome_lwip_socket_has_data(sock)) {
|
||||
yield();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep with instant wake via FreeRTOS task notification.
|
||||
// Woken by: callback wrapper (socket data arrives), wake_loop_threadsafe() (other tasks), or timeout.
|
||||
// Without USE_WAKE_LOOP_THREADSAFE, only hooked socket callbacks wake the task —
|
||||
// background tasks won't call wake, so this degrades to a pure timeout (same as old select path).
|
||||
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(delay_ms));
|
||||
|
||||
#elif defined(USE_SOCKET_SELECT_SUPPORT)
|
||||
// Fallback select() path (host platform and any future platforms without fast select).
|
||||
// ESP32 and LibreTiny are excluded by the #if above — they use the fast path.
|
||||
if (!this->socket_fds_.empty()) [[likely]] {
|
||||
// Update fd_set if socket list has changed
|
||||
if (this->socket_fds_changed_) [[unlikely]] {
|
||||
@@ -701,16 +570,8 @@ void Application::yield_with_select_(uint32_t delay_ms) {
|
||||
}
|
||||
// No sockets registered or select() failed - use regular delay
|
||||
delay(delay_ms);
|
||||
#elif (defined(USE_ESP8266) || defined(USE_RP2040)) && defined(USE_SOCKET_IMPL_LWIP_TCP)
|
||||
// No select support but can wake on socket activity
|
||||
// ESP8266: via esp_schedule()
|
||||
// RP2040: via __sev()/__wfe() hardware sleep/wake
|
||||
socket::socket_delay(delay_ms);
|
||||
#else
|
||||
// No select support, use regular delay
|
||||
delay(delay_ms);
|
||||
#endif
|
||||
}
|
||||
#endif // defined(USE_SOCKET_SELECT_SUPPORT) && !defined(USE_LWIP_FAST_SELECT)
|
||||
|
||||
// App storage — asm label shares the linker symbol with "extern Application App".
|
||||
// char[] is trivially destructible, so no __cxa_atexit or destructor chain is emitted.
|
||||
|
||||
+150
-4
@@ -27,6 +27,13 @@
|
||||
#ifdef USE_SOCKET_SELECT_SUPPORT
|
||||
#ifdef USE_LWIP_FAST_SELECT
|
||||
#include "esphome/core/lwip_fast_select.h"
|
||||
#ifdef USE_ESP32
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#else
|
||||
#include <FreeRTOS.h>
|
||||
#include <task.h>
|
||||
#endif
|
||||
#else
|
||||
#include <sys/select.h>
|
||||
#ifdef USE_WAKE_LOOP_THREADSAFE
|
||||
@@ -34,9 +41,13 @@
|
||||
#endif
|
||||
#endif
|
||||
#endif // USE_SOCKET_SELECT_SUPPORT
|
||||
#ifdef USE_RUNTIME_STATS
|
||||
#include "esphome/components/runtime_stats/runtime_stats.h"
|
||||
#endif
|
||||
#if (defined(USE_ESP8266) || defined(USE_RP2040)) && defined(USE_SOCKET_IMPL_LWIP_TCP)
|
||||
namespace esphome::socket {
|
||||
void socket_wake(); // NOLINT(readability-redundant-declaration)
|
||||
void socket_wake(); // NOLINT(readability-redundant-declaration)
|
||||
void socket_delay(uint32_t ms); // NOLINT(readability-redundant-declaration)
|
||||
} // namespace esphome::socket
|
||||
#endif
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
@@ -293,7 +304,7 @@ class Application {
|
||||
void setup();
|
||||
|
||||
/// Make a loop iteration. Call this in your loop() function.
|
||||
void loop();
|
||||
inline void ESPHOME_ALWAYS_INLINE loop();
|
||||
|
||||
/// Get the name of this Application set by pre_setup().
|
||||
const StringRef &get_name() const { return this->name_; }
|
||||
@@ -617,8 +628,8 @@ class Application {
|
||||
void enable_component_loop_(Component *component);
|
||||
void enable_pending_loops_();
|
||||
void activate_looping_component_(uint16_t index);
|
||||
void before_loop_tasks_(uint32_t loop_start_time);
|
||||
void after_loop_tasks_();
|
||||
inline void ESPHOME_ALWAYS_INLINE before_loop_tasks_(uint32_t loop_start_time);
|
||||
inline void ESPHOME_ALWAYS_INLINE after_loop_tasks_() { this->in_loop_ = false; }
|
||||
|
||||
/// Process dump_config output one component per loop iteration.
|
||||
/// Extracted from loop() to keep cold startup/reconnect logging out of the hot path.
|
||||
@@ -628,7 +639,12 @@ class Application {
|
||||
void feed_wdt_arch_();
|
||||
|
||||
/// Perform a delay while also monitoring socket file descriptors for readiness
|
||||
#if defined(USE_SOCKET_SELECT_SUPPORT) && !defined(USE_LWIP_FAST_SELECT)
|
||||
// select() fallback path is too complex to inline (host platform)
|
||||
void yield_with_select_(uint32_t delay_ms);
|
||||
#else
|
||||
inline void ESPHOME_ALWAYS_INLINE yield_with_select_(uint32_t delay_ms);
|
||||
#endif
|
||||
|
||||
#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE) && !defined(USE_LWIP_FAST_SELECT)
|
||||
void setup_wake_loop_threadsafe_(); // Create wake notification socket
|
||||
@@ -814,4 +830,134 @@ inline void Application::drain_wake_notifications_() {
|
||||
}
|
||||
#endif // defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE) && !defined(USE_LWIP_FAST_SELECT)
|
||||
|
||||
inline void ESPHOME_ALWAYS_INLINE Application::before_loop_tasks_(uint32_t loop_start_time) {
|
||||
#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE) && !defined(USE_LWIP_FAST_SELECT)
|
||||
// Drain wake notifications first to clear socket for next wake
|
||||
this->drain_wake_notifications_();
|
||||
#endif
|
||||
|
||||
// Process scheduled tasks
|
||||
this->scheduler.call(loop_start_time);
|
||||
|
||||
// Feed the watchdog timer
|
||||
this->feed_wdt(loop_start_time);
|
||||
|
||||
// Process any pending enable_loop requests from ISRs
|
||||
// This must be done before marking in_loop_ = true to avoid race conditions
|
||||
if (this->has_pending_enable_loop_requests_) {
|
||||
// Clear flag BEFORE processing to avoid race condition
|
||||
// If ISR sets it during processing, we'll catch it next loop iteration
|
||||
// This is safe because:
|
||||
// 1. Each component has its own pending_enable_loop_ flag that we check
|
||||
// 2. If we can't process a component (wrong state), enable_pending_loops_()
|
||||
// will set this flag back to true
|
||||
// 3. Any new ISR requests during processing will set the flag again
|
||||
this->has_pending_enable_loop_requests_ = false;
|
||||
this->enable_pending_loops_();
|
||||
}
|
||||
|
||||
// Mark that we're in the loop for safe reentrant modifications
|
||||
this->in_loop_ = true;
|
||||
}
|
||||
|
||||
inline void ESPHOME_ALWAYS_INLINE Application::loop() {
|
||||
uint8_t new_app_state = 0;
|
||||
|
||||
// Get the initial loop time at the start
|
||||
uint32_t last_op_end_time = millis();
|
||||
|
||||
this->before_loop_tasks_(last_op_end_time);
|
||||
|
||||
for (this->current_loop_index_ = 0; this->current_loop_index_ < this->looping_components_active_end_;
|
||||
this->current_loop_index_++) {
|
||||
Component *component = this->looping_components_[this->current_loop_index_];
|
||||
|
||||
// Update the cached time before each component runs
|
||||
this->loop_component_start_time_ = last_op_end_time;
|
||||
|
||||
{
|
||||
this->set_current_component(component);
|
||||
WarnIfComponentBlockingGuard guard{component, last_op_end_time};
|
||||
component->loop();
|
||||
// Use the finish method to get the current time as the end time
|
||||
last_op_end_time = guard.finish();
|
||||
}
|
||||
new_app_state |= component->get_component_state();
|
||||
this->app_state_ |= new_app_state;
|
||||
this->feed_wdt(last_op_end_time);
|
||||
}
|
||||
|
||||
this->after_loop_tasks_();
|
||||
this->app_state_ = new_app_state;
|
||||
|
||||
#ifdef USE_RUNTIME_STATS
|
||||
// Process any pending runtime stats printing after all components have run
|
||||
// This ensures stats printing doesn't affect component timing measurements
|
||||
if (global_runtime_stats != nullptr) {
|
||||
global_runtime_stats->process_pending_stats(last_op_end_time);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Use the last component's end time instead of calling millis() again
|
||||
auto elapsed = last_op_end_time - this->last_loop_;
|
||||
if (elapsed >= this->loop_interval_ || HighFrequencyLoopRequester::is_high_frequency()) {
|
||||
// Even if we overran the loop interval, we still need to select()
|
||||
// to know if any sockets have data ready
|
||||
this->yield_with_select_(0);
|
||||
} else {
|
||||
uint32_t delay_time = this->loop_interval_ - elapsed;
|
||||
uint32_t next_schedule = this->scheduler.next_schedule_in(last_op_end_time).value_or(delay_time);
|
||||
// next_schedule is max 0.5*delay_time
|
||||
// otherwise interval=0 schedules result in constant looping with almost no sleep
|
||||
next_schedule = std::max(next_schedule, delay_time / 2);
|
||||
delay_time = std::min(next_schedule, delay_time);
|
||||
|
||||
this->yield_with_select_(delay_time);
|
||||
}
|
||||
this->last_loop_ = last_op_end_time;
|
||||
|
||||
if (this->dump_config_at_ < this->components_.size()) {
|
||||
this->process_dump_config_();
|
||||
}
|
||||
}
|
||||
|
||||
// Inline yield_with_select_ for all paths except the select() fallback
|
||||
#if !defined(USE_SOCKET_SELECT_SUPPORT) || defined(USE_LWIP_FAST_SELECT)
|
||||
inline void ESPHOME_ALWAYS_INLINE Application::yield_with_select_(uint32_t delay_ms) {
|
||||
#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_LWIP_FAST_SELECT)
|
||||
// Fast path (ESP32/LibreTiny): reads rcvevent directly from cached lwip_sock pointers.
|
||||
// Safe because this runs on the main loop which owns socket lifetime (create, read, close).
|
||||
if (delay_ms == 0) [[unlikely]] {
|
||||
yield();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if any socket already has pending data before sleeping.
|
||||
// If a socket still has unread data (rcvevent > 0) but the task notification was already
|
||||
// consumed, ulTaskNotifyTake would block until timeout — adding up to delay_ms latency.
|
||||
// This scan preserves select() semantics: return immediately when any fd is ready.
|
||||
for (struct lwip_sock *sock : this->monitored_sockets_) {
|
||||
if (esphome_lwip_socket_has_data(sock)) {
|
||||
yield();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep with instant wake via FreeRTOS task notification.
|
||||
// Woken by: callback wrapper (socket data arrives), wake_loop_threadsafe() (other tasks), or timeout.
|
||||
// Without USE_WAKE_LOOP_THREADSAFE, only hooked socket callbacks wake the task —
|
||||
// background tasks won't call wake, so this degrades to a pure timeout (same as old select path).
|
||||
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(delay_ms));
|
||||
#elif (defined(USE_ESP8266) || defined(USE_RP2040)) && defined(USE_SOCKET_IMPL_LWIP_TCP)
|
||||
// No select support but can wake on socket activity
|
||||
// ESP8266: via esp_schedule()
|
||||
// RP2040: via __sev()/__wfe() hardware sleep/wake
|
||||
socket::socket_delay(delay_ms);
|
||||
#else
|
||||
// No select support, use regular delay
|
||||
delay(delay_ms);
|
||||
#endif
|
||||
}
|
||||
#endif // !defined(USE_SOCKET_SELECT_SUPPORT) || defined(USE_LWIP_FAST_SELECT)
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
@@ -322,7 +322,9 @@ template<typename... Ts> class Automation;
|
||||
template<typename... Ts> class Trigger {
|
||||
public:
|
||||
/// Inform the parent automation that the event has triggered.
|
||||
void trigger(const Ts &...x) {
|
||||
// Force-inline: collapses the Trigger→Automation→ActionList forwarding
|
||||
// chain into a single frame, reducing automation call stack depth.
|
||||
inline void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE {
|
||||
if (this->automation_parent_ == nullptr)
|
||||
return;
|
||||
this->automation_parent_->trigger(x...);
|
||||
@@ -429,7 +431,9 @@ template<typename... Ts> class ActionList {
|
||||
this->add_action(action);
|
||||
}
|
||||
}
|
||||
void play(const Ts &...x) {
|
||||
// Force-inline: part of the Trigger→Automation→ActionList forwarding
|
||||
// chain collapsed to reduce automation call stack depth.
|
||||
inline void play(const Ts &...x) ESPHOME_ALWAYS_INLINE {
|
||||
if (this->actions_begin_ != nullptr)
|
||||
this->actions_begin_->play_complex(x...);
|
||||
}
|
||||
@@ -473,7 +477,9 @@ template<typename... Ts> class Automation {
|
||||
|
||||
void stop() { this->actions_.stop(); }
|
||||
|
||||
void trigger(const Ts &...x) { this->actions_.play(x...); }
|
||||
// Force-inline: part of the Trigger→Automation→ActionList forwarding
|
||||
// chain collapsed to reduce automation call stack depth.
|
||||
inline void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE { this->actions_.play(x...); }
|
||||
|
||||
bool is_running() { return this->actions_.is_running(); }
|
||||
|
||||
|
||||
@@ -272,9 +272,6 @@ void Component::call() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
const LogString *Component::get_component_log_str() const {
|
||||
return this->component_source_ == nullptr ? LOG_STR("<unknown>") : this->component_source_;
|
||||
}
|
||||
bool Component::should_warn_of_blocking(uint32_t blocking_time) {
|
||||
if (blocking_time > this->warn_if_blocking_over_) {
|
||||
// Prevent overflow when adding increment - if we're about to overflow, just max out
|
||||
|
||||
@@ -294,7 +294,9 @@ class Component {
|
||||
*
|
||||
* Returns LOG_STR("<unknown>") if source not set
|
||||
*/
|
||||
const LogString *get_component_log_str() const;
|
||||
const LogString *get_component_log_str() const {
|
||||
return this->component_source_ == nullptr ? LOG_STR("<unknown>") : this->component_source_;
|
||||
}
|
||||
|
||||
bool should_warn_of_blocking(uint32_t blocking_time);
|
||||
|
||||
|
||||
@@ -863,7 +863,16 @@ bool mac_address_is_valid(const uint8_t *mac) {
|
||||
is_all_ones = false;
|
||||
}
|
||||
}
|
||||
return !(is_all_zeros || is_all_ones);
|
||||
if (is_all_zeros || is_all_ones) {
|
||||
return false;
|
||||
}
|
||||
// Reject multicast MACs (bit 0 of first byte set) - device MACs must be unicast.
|
||||
// This catches garbage data from corrupted eFuse custom MAC areas, which often
|
||||
// has random values that would otherwise pass the all-zeros/all-ones check.
|
||||
if (mac[0] & 0x01) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void IRAM_ATTR HOT delay_microseconds_safe(uint32_t us) {
|
||||
|
||||
@@ -1762,7 +1762,10 @@ template<typename... Ts> struct Callback<void(Ts...)> {
|
||||
// Safe under C++20 (P0593R6): byte copy into aligned storage implicitly
|
||||
// creates objects of implicit-lifetime types (trivially copyable qualifies).
|
||||
Callback cb; // fn and ctx are zero-initialized by default
|
||||
__builtin_memcpy(&cb.ctx_, &callable, sizeof(DecayF));
|
||||
// Decay callable to a local variable first. When F is a function reference
|
||||
// (e.g. void(&)(int)), &callable would point at machine code, not a pointer variable.
|
||||
DecayF decayed = std::forward<F>(callable);
|
||||
__builtin_memcpy(&cb.ctx_, &decayed, sizeof(DecayF));
|
||||
cb.fn_ = [](void *c, Ts... args) {
|
||||
alignas(DecayF) char buf[sizeof(DecayF)];
|
||||
__builtin_memcpy(buf, &c, sizeof(DecayF));
|
||||
|
||||
@@ -579,10 +579,41 @@ def Pvariable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj":
|
||||
obj = MockObj(id_, "->")
|
||||
if type_ is not None:
|
||||
id_.type = type_
|
||||
decl = VariableDeclarationExpression(id_.type, "*", id_, static=True)
|
||||
CORE.add_global(decl)
|
||||
assignment = AssignmentExpression(None, None, id_, rhs)
|
||||
CORE.add(assignment)
|
||||
|
||||
if isinstance(rhs, MockObj) and rhs.is_new_expr:
|
||||
# For 'new' allocations, use placement new into static storage
|
||||
# to avoid heap fragmentation on embedded devices.
|
||||
the_type = id_.type
|
||||
storage_name = f"{id_.id}__pstorage"
|
||||
|
||||
# Declare aligned byte array for the object storage
|
||||
CORE.add_global(
|
||||
RawStatement(
|
||||
f"alignas({the_type}) static unsigned char {storage_name}[sizeof({the_type})];"
|
||||
)
|
||||
)
|
||||
CORE.add_global(
|
||||
AssignmentExpression(
|
||||
f"static {the_type}",
|
||||
"*const ",
|
||||
id_,
|
||||
MockObj(f"reinterpret_cast<{the_type} *>({storage_name})"),
|
||||
)
|
||||
)
|
||||
# Extract args from the CallExpression and rebuild as placement new.
|
||||
# Template args are already encoded in the_type (e.g. GlobalsComponent<int>),
|
||||
# so we only pass the constructor args, not template_args.
|
||||
call_expr = rhs.base
|
||||
assert isinstance(call_expr, CallExpression), (
|
||||
f"Expected CallExpression for placement new, got {type(call_expr)}"
|
||||
)
|
||||
placement_new = CallExpression(f"new({id_.id}) {the_type}", *call_expr.args)
|
||||
CORE.add(ExpressionStatement(placement_new))
|
||||
else:
|
||||
decl = VariableDeclarationExpression(id_.type, "*", id_, static=True)
|
||||
CORE.add_global(decl)
|
||||
CORE.add(AssignmentExpression(None, None, id_, rhs))
|
||||
|
||||
CORE.register_variable(id_, obj)
|
||||
return obj
|
||||
|
||||
@@ -799,11 +830,12 @@ class MockObj(Expression):
|
||||
Mostly consists of magic methods that allow ESPHome's codegen syntax.
|
||||
"""
|
||||
|
||||
__slots__ = ("base", "op")
|
||||
__slots__ = ("base", "op", "is_new_expr")
|
||||
|
||||
def __init__(self, base, op="."):
|
||||
def __init__(self, base, op=".", is_new_expr=False) -> None:
|
||||
self.base = base
|
||||
self.op = op
|
||||
self.is_new_expr = is_new_expr
|
||||
|
||||
def __getattr__(self, attr: str) -> "MockObj":
|
||||
# prevent python dunder methods being replaced by mock objects
|
||||
@@ -818,7 +850,7 @@ class MockObj(Expression):
|
||||
|
||||
def __call__(self, *args: SafeExpType) -> "MockObj":
|
||||
call = CallExpression(self.base, *args)
|
||||
return MockObj(call, self.op)
|
||||
return MockObj(call, self.op, is_new_expr=self.is_new_expr)
|
||||
|
||||
def __str__(self):
|
||||
return str(self.base)
|
||||
@@ -832,7 +864,7 @@ class MockObj(Expression):
|
||||
|
||||
@property
|
||||
def new(self) -> "MockObj":
|
||||
return MockObj(f"new {self.base}", "->")
|
||||
return MockObj(f"new {self.base}", "->", is_new_expr=True)
|
||||
|
||||
def template(self, *args: SafeExpType) -> "MockObj":
|
||||
"""Apply template parameters to this object."""
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ platformio==6.1.19
|
||||
esptool==5.2.0
|
||||
click==8.3.1
|
||||
esphome-dashboard==20260210.0
|
||||
aioesphomeapi==44.6.2
|
||||
aioesphomeapi==44.7.0
|
||||
zeroconf==0.148.0
|
||||
puremagic==1.30
|
||||
ruamel.yaml==0.19.1 # dashboard_import
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
#include "esphome/core/defines.h"
|
||||
#ifdef USE_API_PLAINTEXT
|
||||
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <fcntl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "esphome/components/api/api_frame_helper_plaintext.h"
|
||||
#include "esphome/components/api/api_pb2.h"
|
||||
#include "esphome/components/api/api_buffer.h"
|
||||
|
||||
namespace esphome::api::benchmarks {
|
||||
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// Helper to drain accumulated data from the read side of a socket
|
||||
// to prevent the write side from blocking.
|
||||
static void drain_socket(int fd) {
|
||||
char buf[65536];
|
||||
while (::read(fd, buf, sizeof(buf)) > 0) {
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to create a TCP loopback connection with an APIPlaintextFrameHelper
|
||||
// on the write end. Returns the helper and the read-side fd.
|
||||
// Uses real TCP sockets so TCP_NODELAY succeeds during init().
|
||||
static std::pair<std::unique_ptr<APIPlaintextFrameHelper>, int> create_plaintext_helper() {
|
||||
// Create a TCP listener on loopback
|
||||
int listen_fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int opt = 1;
|
||||
::setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
|
||||
|
||||
struct sockaddr_in addr {};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0; // OS-assigned port
|
||||
::bind(listen_fd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr));
|
||||
::listen(listen_fd, 1);
|
||||
|
||||
// Get the assigned port
|
||||
socklen_t addr_len = sizeof(addr);
|
||||
::getsockname(listen_fd, reinterpret_cast<struct sockaddr *>(&addr), &addr_len);
|
||||
|
||||
// Connect from client side
|
||||
int write_fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
::connect(write_fd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr));
|
||||
|
||||
// Accept on server side (this is our read fd)
|
||||
int read_fd = ::accept(listen_fd, nullptr, nullptr);
|
||||
::close(listen_fd);
|
||||
|
||||
// Make both ends non-blocking
|
||||
int flags = ::fcntl(write_fd, F_GETFL, 0);
|
||||
::fcntl(write_fd, F_SETFL, flags | O_NONBLOCK);
|
||||
flags = ::fcntl(read_fd, F_GETFL, 0);
|
||||
::fcntl(read_fd, F_SETFL, flags | O_NONBLOCK);
|
||||
|
||||
// Increase socket buffer sizes to reduce drain frequency
|
||||
int bufsize = 1024 * 1024;
|
||||
::setsockopt(write_fd, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
|
||||
::setsockopt(read_fd, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
|
||||
|
||||
auto sock = std::make_unique<socket::Socket>(write_fd);
|
||||
auto helper = std::make_unique<APIPlaintextFrameHelper>(std::move(sock));
|
||||
helper->init();
|
||||
|
||||
return {std::move(helper), read_fd};
|
||||
}
|
||||
|
||||
// --- Write a single SensorStateResponse through plaintext framing ---
|
||||
// Measures the full write path: header construction, varint encoding,
|
||||
// iovec assembly, and socket write.
|
||||
|
||||
static void PlaintextFrame_WriteSensorState(benchmark::State &state) {
|
||||
auto [helper, read_fd] = create_plaintext_helper();
|
||||
uint8_t padding = helper->frame_header_padding();
|
||||
|
||||
// Pre-init buffer to typical TCP MSS size to avoid benchmarking
|
||||
// heap allocation — in real use the buffer is reused across writes.
|
||||
APIBuffer buffer;
|
||||
buffer.reserve(1460);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
buffer.clear();
|
||||
SensorStateResponse msg;
|
||||
msg.key = 0x12345678;
|
||||
msg.state = 23.5f;
|
||||
msg.missing_state = false;
|
||||
|
||||
uint32_t size = msg.calculate_size();
|
||||
buffer.resize(padding + size);
|
||||
ProtoWriteBuffer writer(&buffer, padding);
|
||||
msg.encode(writer);
|
||||
|
||||
helper->write_protobuf_packet(SensorStateResponse::MESSAGE_TYPE, writer);
|
||||
|
||||
if ((i & 0xFF) == 0)
|
||||
drain_socket(read_fd);
|
||||
}
|
||||
drain_socket(read_fd);
|
||||
benchmark::DoNotOptimize(helper.get());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
|
||||
::close(read_fd);
|
||||
}
|
||||
BENCHMARK(PlaintextFrame_WriteSensorState);
|
||||
|
||||
// --- Write a batch of 5 SensorStateResponses in one call ---
|
||||
// Measures batched write: multiple messages assembled into one writev.
|
||||
|
||||
static void PlaintextFrame_WriteBatch5(benchmark::State &state) {
|
||||
auto [helper, read_fd] = create_plaintext_helper();
|
||||
uint8_t padding = helper->frame_header_padding();
|
||||
uint8_t footer = helper->frame_footer_size();
|
||||
|
||||
// Pre-init buffer to typical TCP MSS size to avoid benchmarking
|
||||
// heap allocation — in real use the buffer is reused across writes.
|
||||
APIBuffer buffer;
|
||||
buffer.reserve(1460);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
buffer.clear();
|
||||
MessageInfo messages[5] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
|
||||
|
||||
for (int j = 0; j < 5; j++) {
|
||||
uint16_t offset = buffer.size();
|
||||
SensorStateResponse msg;
|
||||
msg.key = static_cast<uint32_t>(j);
|
||||
msg.state = 23.5f + static_cast<float>(j);
|
||||
msg.missing_state = false;
|
||||
|
||||
uint32_t size = msg.calculate_size();
|
||||
buffer.resize(offset + padding + size + footer);
|
||||
ProtoWriteBuffer writer(&buffer, offset + padding);
|
||||
msg.encode(writer);
|
||||
|
||||
messages[j] = MessageInfo(SensorStateResponse::MESSAGE_TYPE, offset, size);
|
||||
}
|
||||
|
||||
helper->write_protobuf_messages(ProtoWriteBuffer(&buffer, 0), std::span<const MessageInfo>(messages, 5));
|
||||
|
||||
if ((i & 0xFF) == 0)
|
||||
drain_socket(read_fd);
|
||||
}
|
||||
drain_socket(read_fd);
|
||||
benchmark::DoNotOptimize(helper.get());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
|
||||
::close(read_fd);
|
||||
}
|
||||
BENCHMARK(PlaintextFrame_WriteBatch5);
|
||||
|
||||
} // namespace esphome::api::benchmarks
|
||||
|
||||
#endif // USE_API_PLAINTEXT
|
||||
@@ -26,7 +26,7 @@ void setup() {
|
||||
|
||||
// Log functions call global_logger->log_vprintf_() without a null check,
|
||||
// so we must set up a Logger before any test that triggers logging.
|
||||
static esphome::logger::Logger test_logger(0);
|
||||
static esphome::logger::Logger test_logger(0, 64);
|
||||
test_logger.set_log_level(ESPHOME_LOG_LEVEL);
|
||||
test_logger.pre_setup();
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ def test_binary_sensor_is_setup(generate_main):
|
||||
)
|
||||
|
||||
# Then
|
||||
assert "new gpio::GPIOBinarySensor();" in main_cpp
|
||||
assert "static gpio::GPIOBinarySensor *const" in main_cpp
|
||||
assert "App.register_binary_sensor" in main_cpp
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ def test_button_is_setup(generate_main):
|
||||
main_cpp = generate_main("tests/component_tests/button/test_button.yaml")
|
||||
|
||||
# Then
|
||||
assert "new wake_on_lan::WakeOnLanButton();" in main_cpp
|
||||
assert "static wake_on_lan::WakeOnLanButton *const" in main_cpp
|
||||
assert ") wake_on_lan::WakeOnLanButton();" in main_cpp
|
||||
assert "App.register_button" in main_cpp
|
||||
assert "App.register_component" in main_cpp
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ def generate_main() -> Generator[Callable[[str | Path], str]]:
|
||||
CORE.config_path = Path(path)
|
||||
CORE.config = read_config({})
|
||||
generate_cpp_contents(CORE.config)
|
||||
return CORE.cpp_main_section
|
||||
return CORE.cpp_global_section + CORE.cpp_main_section
|
||||
|
||||
yield generator
|
||||
|
||||
|
||||
@@ -7,7 +7,11 @@ def test_deep_sleep_setup(generate_main):
|
||||
"""
|
||||
main_cpp = generate_main("tests/component_tests/deep_sleep/test_deep_sleep1.yaml")
|
||||
|
||||
assert "deepsleep = new deep_sleep::DeepSleepComponent();" in main_cpp
|
||||
assert (
|
||||
"static deep_sleep::DeepSleepComponent *const deepsleep = reinterpret_cast<deep_sleep::DeepSleepComponent *>(deepsleep__pstorage);"
|
||||
in main_cpp
|
||||
)
|
||||
assert "new(deepsleep) deep_sleep::DeepSleepComponent();" in main_cpp
|
||||
assert "App.register_component_(deepsleep);" in main_cpp
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
|
||||
globals:
|
||||
- id: my_global_int
|
||||
type: int
|
||||
initial_value: "42"
|
||||
- id: my_global_float
|
||||
type: float
|
||||
initial_value: "1.5"
|
||||
- id: my_global_bool
|
||||
type: bool
|
||||
initial_value: "true"
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Tests for the globals component."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_globals_placement_new_with_template_args(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
"""Test that globals uses placement new with template arguments preserved."""
|
||||
main_cpp = generate_main(component_config_path("globals_test.yaml"))
|
||||
|
||||
# Globals uses Pvariable with Type.new(template_args, initial_value)
|
||||
# which exercises the template_args preservation in placement new.
|
||||
assert "static globals::GlobalsComponent<int> *const my_global_int" in main_cpp
|
||||
assert "sizeof(globals::GlobalsComponent<int>)" in main_cpp
|
||||
assert "new(my_global_int) globals::GlobalsComponent<int>" in main_cpp
|
||||
|
||||
# Verify initial value is passed as constructor arg
|
||||
assert "42" in main_cpp
|
||||
|
||||
# Check other globals are also generated
|
||||
assert "sizeof(globals::GlobalsComponent<float>)" in main_cpp
|
||||
assert "sizeof(globals::GlobalsComponent<bool>)" in main_cpp
|
||||
@@ -16,7 +16,8 @@ def test_gpio_binary_sensor_basic_setup(
|
||||
"""
|
||||
main_cpp = generate_main("tests/component_tests/gpio/test_gpio_binary_sensor.yaml")
|
||||
|
||||
assert "new gpio::GPIOBinarySensor();" in main_cpp
|
||||
assert "static gpio::GPIOBinarySensor *const" in main_cpp
|
||||
assert ") gpio::GPIOBinarySensor();" in main_cpp
|
||||
assert "App.register_binary_sensor" in main_cpp
|
||||
# set_use_interrupt(true) should NOT be generated (uses C++ default)
|
||||
assert "bs_gpio->set_use_interrupt(true);" not in main_cpp
|
||||
|
||||
@@ -242,7 +242,15 @@ def test_image_generation(
|
||||
main_cpp = generate_main(component_config_path("image_test.yaml"))
|
||||
assert "uint8_t_id[] PROGMEM = {0x24, 0x21, 0x24, 0x21" in main_cpp
|
||||
assert (
|
||||
"cat_img = new image::Image(uint8_t_id, 32, 24, image::IMAGE_TYPE_RGB565, image::TRANSPARENCY_OPAQUE);"
|
||||
"alignas(image::Image) static unsigned char cat_img__pstorage[sizeof(image::Image)];"
|
||||
in main_cpp
|
||||
)
|
||||
assert (
|
||||
"static image::Image *const cat_img = reinterpret_cast<image::Image *>(cat_img__pstorage);"
|
||||
in main_cpp
|
||||
)
|
||||
assert (
|
||||
"new(cat_img) image::Image(uint8_t_id, 32, 24, image::IMAGE_TYPE_RGB565, image::TRANSPARENCY_OPAQUE);"
|
||||
in main_cpp
|
||||
)
|
||||
|
||||
|
||||
@@ -22,6 +22,10 @@ def test_logger_pre_setup_before_other_components(generate_main):
|
||||
|
||||
# Find all "new " allocations (component creation)
|
||||
new_allocations = list(re.finditer(r"\bnew [\w:]+", main_cpp))
|
||||
# Find all "new(" allocations (component creation) and combine them
|
||||
new_allocations.extend(re.finditer(r"\bnew\([^)]+\) [\w:]+", main_cpp))
|
||||
# Sort allocations by position in the file
|
||||
new_allocations.sort(key=lambda m: m.start())
|
||||
assert len(new_allocations) > 0, "No component allocations found"
|
||||
|
||||
# Separate logger and non-logger allocations
|
||||
|
||||
@@ -119,7 +119,15 @@ def test_code_generation(
|
||||
|
||||
main_cpp = generate_main(component_fixture_path("mipi_dsi.yaml"))
|
||||
assert (
|
||||
"p4_nano = new mipi_dsi::MIPI_DSI(800, 1280, display::COLOR_BITNESS_565, 16);"
|
||||
"alignas(mipi_dsi::MIPI_DSI) static unsigned char p4_nano__pstorage[sizeof(mipi_dsi::MIPI_DSI)];"
|
||||
in main_cpp
|
||||
)
|
||||
assert (
|
||||
"static mipi_dsi::MIPI_DSI *const p4_nano = reinterpret_cast<mipi_dsi::MIPI_DSI *>(p4_nano__pstorage);"
|
||||
in main_cpp
|
||||
)
|
||||
assert (
|
||||
"new(p4_nano) mipi_dsi::MIPI_DSI(800, 1280, display::COLOR_BITNESS_565, 16);"
|
||||
in main_cpp
|
||||
)
|
||||
assert "set_init_sequence({224, 1, 0, 225, 1, 147, 226, 1," in main_cpp
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
|
||||
status_led:
|
||||
pin: GPIO2
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Tests for status_led."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_status_led_generation(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
"""Test status_led generation."""
|
||||
main_cpp = generate_main(component_config_path("status_led_test.yaml"))
|
||||
assert (
|
||||
"alignas(status_led::StatusLED) static unsigned char status_led_statusled_id__pstorage[sizeof(status_led::StatusLED)];"
|
||||
in main_cpp
|
||||
)
|
||||
assert (
|
||||
"static status_led::StatusLED *const status_led_statusled_id = reinterpret_cast<status_led::StatusLED *>(status_led_statusled_id__pstorage);"
|
||||
in main_cpp
|
||||
)
|
||||
assert "new(status_led_statusled_id) status_led::StatusLED(" in main_cpp
|
||||
@@ -13,7 +13,8 @@ def test_text_is_setup(generate_main):
|
||||
main_cpp = generate_main("tests/component_tests/text/test_text.yaml")
|
||||
|
||||
# Then
|
||||
assert "new template_::TemplateText();" in main_cpp
|
||||
assert "static template_::TemplateText *const" in main_cpp
|
||||
assert ") template_::TemplateText();" in main_cpp
|
||||
assert "App.register_text" in main_cpp
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ def test_text_sensor_is_setup(generate_main):
|
||||
main_cpp = generate_main("tests/component_tests/text_sensor/test_text_sensor.yaml")
|
||||
|
||||
# Then
|
||||
assert "new template_::TemplateTextSensor();" in main_cpp
|
||||
assert "static template_::TemplateTextSensor *const" in main_cpp
|
||||
assert ") template_::TemplateTextSensor();" in main_cpp
|
||||
assert "App.register_text_sensor" in main_cpp
|
||||
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ void original_setup() {
|
||||
void setup() {
|
||||
// Log functions call global_logger->log_vprintf_() without a null check,
|
||||
// so we must set up a Logger before any test that triggers logging.
|
||||
static esphome::logger::Logger test_logger(0);
|
||||
static esphome::logger::Logger test_logger(0, 64);
|
||||
test_logger.set_log_level(ESPHOME_LOG_LEVEL);
|
||||
test_logger.pre_setup();
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace esphome::packet_transport::testing {
|
||||
TEST(PacketTransportBinarySensorTest, AddBinarySensor) {
|
||||
TestablePacketTransport transport;
|
||||
binary_sensor::BinarySensor bs;
|
||||
transport.set_binary_sensor_count(1);
|
||||
transport.add_binary_sensor("motion", &bs);
|
||||
ASSERT_EQ(transport.binary_sensors_.size(), 1u);
|
||||
EXPECT_STREQ(transport.binary_sensors_[0].id, "motion");
|
||||
@@ -24,6 +25,7 @@ TEST(PacketTransportBinarySensorTest, UnencryptedBinarySensorRoundTrip) {
|
||||
encoder.init_for_test("sender");
|
||||
binary_sensor::BinarySensor local_bs;
|
||||
local_bs.state = true;
|
||||
encoder.set_binary_sensor_count(1);
|
||||
encoder.add_binary_sensor("motion", &local_bs);
|
||||
|
||||
encoder.send_data_(true);
|
||||
@@ -46,11 +48,13 @@ TEST(PacketTransportBinarySensorTest, MultipleSensorsRoundTrip) {
|
||||
sensor::Sensor s1, s2;
|
||||
s1.state = 10.0f;
|
||||
s2.state = 20.0f;
|
||||
encoder.set_sensor_count(2);
|
||||
encoder.add_sensor("s1", &s1);
|
||||
encoder.add_sensor("s2", &s2);
|
||||
|
||||
binary_sensor::BinarySensor bs1;
|
||||
bs1.state = true;
|
||||
encoder.set_binary_sensor_count(1);
|
||||
encoder.add_binary_sensor("bs1", &bs1);
|
||||
|
||||
encoder.send_data_(true);
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace esphome::packet_transport::testing {
|
||||
TEST(PacketTransportSensorTest, AddSensor) {
|
||||
TestablePacketTransport transport;
|
||||
sensor::Sensor s;
|
||||
transport.set_sensor_count(1);
|
||||
transport.add_sensor("temp", &s);
|
||||
ASSERT_EQ(transport.sensors_.size(), 1u);
|
||||
EXPECT_STREQ(transport.sensors_[0].id, "temp");
|
||||
@@ -26,6 +27,7 @@ TEST(PacketTransportSensorTest, UnencryptedSensorRoundTrip) {
|
||||
encoder.init_for_test("sender");
|
||||
sensor::Sensor local_sensor;
|
||||
local_sensor.state = 42.5f;
|
||||
encoder.set_sensor_count(1);
|
||||
encoder.add_sensor("temp", &local_sensor);
|
||||
|
||||
encoder.send_data_(true);
|
||||
@@ -53,6 +55,7 @@ TEST(PacketTransportSensorTest, EncryptedSensorRoundTrip) {
|
||||
encoder.set_encryption_key(key);
|
||||
sensor::Sensor local_sensor;
|
||||
local_sensor.state = 99.9f;
|
||||
encoder.set_sensor_count(1);
|
||||
encoder.add_sensor("temp", &local_sensor);
|
||||
|
||||
encoder.send_data_(true);
|
||||
@@ -77,6 +80,7 @@ TEST(PacketTransportSensorTest, SendDataOnlyUpdated) {
|
||||
sensor::Sensor s1, s2;
|
||||
s1.state = 1.0f;
|
||||
s2.state = 2.0f;
|
||||
encoder.set_sensor_count(2);
|
||||
encoder.add_sensor("s1", &s1);
|
||||
encoder.add_sensor("s2", &s2);
|
||||
|
||||
@@ -111,6 +115,7 @@ TEST(PacketTransportSensorTest, PingKeyIncludedInTransmittedPacket) {
|
||||
responder.set_encryption_key(key);
|
||||
sensor::Sensor local_sensor;
|
||||
local_sensor.state = 77.7f;
|
||||
responder.set_sensor_count(1);
|
||||
responder.add_sensor("temp", &local_sensor);
|
||||
|
||||
// Requester sends a MAGIC_PING that the responder processes
|
||||
@@ -148,6 +153,7 @@ TEST(PacketTransportSensorTest, MissingPingKeyBlocksSensorData) {
|
||||
responder.set_encryption_key(key);
|
||||
sensor::Sensor local_sensor;
|
||||
local_sensor.state = 77.7f;
|
||||
responder.set_sensor_count(1);
|
||||
responder.add_sensor("temp", &local_sensor);
|
||||
responder.send_data_(true);
|
||||
ASSERT_EQ(responder.sent_packets.size(), 1u);
|
||||
|
||||
@@ -6,4 +6,8 @@ sensor:
|
||||
humidity:
|
||||
name: SHT4X Humidity
|
||||
address: 0x44
|
||||
precision: High
|
||||
heater_max_duty: 0.02
|
||||
heater_power: High
|
||||
heater_time: Long
|
||||
update_interval: 15s
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
uart:
|
||||
- id: uart_id
|
||||
tx_pin: PA23
|
||||
rx_pin: PA18
|
||||
baud_rate: 9600
|
||||
data_bits: 8
|
||||
parity: NONE
|
||||
stop_bits: 1
|
||||
|
||||
switch:
|
||||
- platform: uart
|
||||
name: "UART Switch"
|
||||
uart_id: uart_id
|
||||
data: [0x01, 0x02, 0x03]
|
||||
@@ -15,7 +15,7 @@ void setup() {
|
||||
static char name[] = "livingroom";
|
||||
static char friendly_name[] = "LivingRoom";
|
||||
App.pre_setup(name, sizeof(name) - 1, friendly_name, sizeof(friendly_name) - 1);
|
||||
auto *log = new logger::Logger(115200); // NOLINT
|
||||
auto *log = new logger::Logger(115200, 512); // NOLINT
|
||||
log->pre_setup();
|
||||
log->set_uart_selection(logger::UART_SELECTION_UART0);
|
||||
App.register_component_(log);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
esphome:
|
||||
name: light-cb-test
|
||||
host:
|
||||
api: # Port will be automatically injected
|
||||
logger:
|
||||
level: DEBUG
|
||||
|
||||
output:
|
||||
- platform: template
|
||||
id: cb_cold_white_output
|
||||
type: float
|
||||
write_action:
|
||||
- logger.log:
|
||||
format: "CB_CW_OUTPUT:%.6f"
|
||||
args: [state]
|
||||
- platform: template
|
||||
id: cb_warm_white_output
|
||||
type: float
|
||||
write_action:
|
||||
- logger.log:
|
||||
format: "CB_WW_OUTPUT:%.6f"
|
||||
args: [state]
|
||||
- platform: template
|
||||
id: ncb_cold_white_output
|
||||
type: float
|
||||
write_action:
|
||||
- logger.log:
|
||||
format: "NCB_CW_OUTPUT:%.6f"
|
||||
args: [state]
|
||||
- platform: template
|
||||
id: ncb_warm_white_output
|
||||
type: float
|
||||
write_action:
|
||||
- logger.log:
|
||||
format: "NCB_WW_OUTPUT:%.6f"
|
||||
args: [state]
|
||||
|
||||
light:
|
||||
- platform: cwww
|
||||
name: "Test CB Light"
|
||||
id: test_cb_light
|
||||
cold_white: cb_cold_white_output
|
||||
warm_white: cb_warm_white_output
|
||||
cold_white_color_temperature: 6536 K
|
||||
warm_white_color_temperature: 2000 K
|
||||
constant_brightness: true
|
||||
gamma_correct: 2.8
|
||||
|
||||
- platform: cwww
|
||||
name: "Test NCB Light"
|
||||
id: test_ncb_light
|
||||
cold_white: ncb_cold_white_output
|
||||
warm_white: ncb_warm_white_output
|
||||
cold_white_color_temperature: 6536 K
|
||||
warm_white_color_temperature: 2000 K
|
||||
constant_brightness: false
|
||||
gamma_correct: 2.8
|
||||
@@ -3,6 +3,7 @@ esphome:
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ esphome:
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ esphome:
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ esphome:
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ esphome:
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ esphome:
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ esphome:
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ esphome:
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""Integration test for constant_brightness with gamma correction.
|
||||
|
||||
Tests both constant_brightness: true and false cwww lights with gamma
|
||||
correction in a single compilation to verify:
|
||||
- constant_brightness: true maintains constant total CW+WW power output
|
||||
- constant_brightness: false correctly varies total power across color temps
|
||||
|
||||
This is a regression test for https://github.com/esphome/esphome/issues/15040
|
||||
where the gamma LUT refactor (#14123) broke constant_brightness by applying
|
||||
gamma after the balancing formula instead of before it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from aioesphomeapi import EntityState, LightInfo, LightState
|
||||
import pytest
|
||||
|
||||
from .state_utils import InitialStateHelper
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_light_constant_brightness(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""Test constant_brightness true and false behavior with gamma correction."""
|
||||
# Track output values for both lights from log lines
|
||||
cb_cw_pattern = re.compile(r"(?<!N)CB_CW_OUTPUT:([\d.]+)")
|
||||
cb_ww_pattern = re.compile(r"(?<!N)CB_WW_OUTPUT:([\d.]+)")
|
||||
ncb_cw_pattern = re.compile(r"NCB_CW_OUTPUT:([\d.]+)")
|
||||
ncb_ww_pattern = re.compile(r"NCB_WW_OUTPUT:([\d.]+)")
|
||||
|
||||
latest: dict[str, float] = {
|
||||
"cb_cw": 0.0,
|
||||
"cb_ww": 0.0,
|
||||
"ncb_cw": 0.0,
|
||||
"ncb_ww": 0.0,
|
||||
}
|
||||
|
||||
def on_log_line(line: str) -> None:
|
||||
for pattern, key in [
|
||||
(cb_cw_pattern, "cb_cw"),
|
||||
(cb_ww_pattern, "cb_ww"),
|
||||
(ncb_cw_pattern, "ncb_cw"),
|
||||
(ncb_ww_pattern, "ncb_ww"),
|
||||
]:
|
||||
match = pattern.search(line)
|
||||
if match:
|
||||
latest[key] = float(match.group(1))
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
async with (
|
||||
run_compiled(yaml_config, line_callback=on_log_line),
|
||||
api_client_connected() as client,
|
||||
):
|
||||
entities, _ = await client.list_entities_services()
|
||||
lights = [e for e in entities if isinstance(e, LightInfo)]
|
||||
cb_light = next(e for e in lights if e.object_id.endswith("cb_light"))
|
||||
ncb_light = next(e for e in lights if e.object_id.endswith("ncb_light"))
|
||||
|
||||
# Use InitialStateHelper to wait for initial state broadcast
|
||||
initial_state_helper = InitialStateHelper(entities)
|
||||
|
||||
# Track state changes per light key
|
||||
state_futures: dict[int, asyncio.Future[EntityState]] = {}
|
||||
|
||||
def on_state(state: EntityState) -> None:
|
||||
if isinstance(state, LightState) and state.key in state_futures:
|
||||
future = state_futures[state.key]
|
||||
if not future.done():
|
||||
future.set_result(state)
|
||||
|
||||
client.subscribe_states(initial_state_helper.on_state_wrapper(on_state))
|
||||
|
||||
try:
|
||||
await initial_state_helper.wait_for_initial_states()
|
||||
except TimeoutError:
|
||||
pytest.fail("Timeout waiting for initial states")
|
||||
|
||||
async def send_and_wait(
|
||||
light_key: int, timeout: float = 5.0, **kwargs: Any
|
||||
) -> LightState:
|
||||
"""Send a light command and wait for the state response."""
|
||||
state_futures[light_key] = loop.create_future()
|
||||
client.light_command(key=light_key, **kwargs)
|
||||
try:
|
||||
return await asyncio.wait_for(state_futures[light_key], timeout=timeout)
|
||||
except TimeoutError:
|
||||
pytest.fail(f"Timeout waiting for light state after command: {kwargs}")
|
||||
|
||||
# --- Test constant_brightness: true ---
|
||||
|
||||
# Turn on CB light at full brightness
|
||||
await send_and_wait(
|
||||
cb_light.key,
|
||||
state=True,
|
||||
brightness=1.0,
|
||||
color_temperature=153.0,
|
||||
transition_length=0,
|
||||
)
|
||||
|
||||
test_mireds = [
|
||||
153.0, # Pure cold white
|
||||
200.0, # Mostly cold
|
||||
280.0, # Mixed
|
||||
326.5, # Midpoint
|
||||
400.0, # Mostly warm
|
||||
500.0, # Pure warm white
|
||||
]
|
||||
|
||||
cb_totals: list[tuple[float, float, float]] = []
|
||||
for mireds in test_mireds:
|
||||
await send_and_wait(
|
||||
cb_light.key, color_temperature=mireds, transition_length=0
|
||||
)
|
||||
cb_totals.append((mireds, latest["cb_cw"], latest["cb_ww"]))
|
||||
|
||||
# All totals should be approximately equal (constant brightness)
|
||||
reference_total = next((cw + ww for _, cw, ww in cb_totals if cw + ww > 0), 0)
|
||||
assert reference_total > 0, (
|
||||
f"Reference total power is zero, CB light outputs not working. "
|
||||
f"Values: {cb_totals}"
|
||||
)
|
||||
|
||||
for mireds, cw, ww in cb_totals:
|
||||
total = cw + ww
|
||||
assert total == pytest.approx(reference_total, rel=0.05), (
|
||||
f"constant_brightness: Total power at {mireds} mireds "
|
||||
f"({total:.4f}) differs from reference ({reference_total:.4f}) "
|
||||
f"by more than 5%. CW={cw:.4f}, WW={ww:.4f}. "
|
||||
f"All values: {cb_totals}"
|
||||
)
|
||||
|
||||
# --- Test constant_brightness: false ---
|
||||
|
||||
# Turn on NCB light at full brightness
|
||||
await send_and_wait(
|
||||
ncb_light.key,
|
||||
state=True,
|
||||
brightness=1.0,
|
||||
color_temperature=153.0,
|
||||
transition_length=0,
|
||||
)
|
||||
|
||||
ncb_totals: list[tuple[float, float, float]] = []
|
||||
for mireds in test_mireds:
|
||||
await send_and_wait(
|
||||
ncb_light.key, color_temperature=mireds, transition_length=0
|
||||
)
|
||||
ncb_totals.append((mireds, latest["ncb_cw"], latest["ncb_ww"]))
|
||||
|
||||
extreme_cw = ncb_totals[0] # 153 mireds - pure cold
|
||||
extreme_ww = ncb_totals[-1] # 500 mireds - pure warm
|
||||
midpoint = ncb_totals[3] # 326.5 mireds - midpoint
|
||||
|
||||
# At pure cold white, WW should be ~0
|
||||
assert extreme_cw[2] == pytest.approx(0.0, abs=0.01), (
|
||||
f"Pure cold white should have WW~0, got WW={extreme_cw[2]:.4f}"
|
||||
)
|
||||
# At pure warm white, CW should be ~0
|
||||
assert extreme_ww[1] == pytest.approx(0.0, abs=0.01), (
|
||||
f"Pure warm white should have CW~0, got CW={extreme_ww[1]:.4f}"
|
||||
)
|
||||
|
||||
# At midpoint, both channels should be non-zero
|
||||
assert midpoint[1] > 0.05, f"Midpoint CW should be >0.05, got {midpoint[1]:.4f}"
|
||||
assert midpoint[2] > 0.05, f"Midpoint WW should be >0.05, got {midpoint[2]:.4f}"
|
||||
|
||||
# Total power at midpoint should be higher than at the extremes
|
||||
midpoint_total = midpoint[1] + midpoint[2]
|
||||
extreme_cw_total = extreme_cw[1] + extreme_cw[2]
|
||||
extreme_ww_total = extreme_ww[1] + extreme_ww[2]
|
||||
|
||||
assert midpoint_total > extreme_cw_total, (
|
||||
f"Midpoint total ({midpoint_total:.4f}) should be > pure CW total "
|
||||
f"({extreme_cw_total:.4f}). All values: {ncb_totals}"
|
||||
)
|
||||
assert midpoint_total > extreme_ww_total, (
|
||||
f"Midpoint total ({midpoint_total:.4f}) should be > pure WW total "
|
||||
f"({extreme_ww_total:.4f}). All values: {ncb_totals}"
|
||||
)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Tests for the gamma LUT table generation."""
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.light import generate_gamma_table
|
||||
|
||||
|
||||
def _simulate_gamma_correct_lut(table: list[int], value: float) -> float:
|
||||
"""Simulate the C++ gamma_correct_lut interpolation from light_state.cpp."""
|
||||
if value <= 0.0:
|
||||
return 0.0
|
||||
if value >= 1.0:
|
||||
return 1.0
|
||||
scaled = value * 255.0
|
||||
idx = int(scaled)
|
||||
if idx >= 255:
|
||||
return table[255] / 65535.0
|
||||
frac = scaled - idx
|
||||
a = float(table[idx])
|
||||
b = float(table[idx + 1])
|
||||
return (a + frac * (b - a)) / 65535.0
|
||||
|
||||
|
||||
def test_table_length() -> None:
|
||||
"""Table must always have exactly 256 entries."""
|
||||
table = generate_gamma_table(2.8)
|
||||
assert len(table) == 256
|
||||
|
||||
|
||||
def test_index_zero_is_zero() -> None:
|
||||
"""Index 0 must be 0 so true off remains off."""
|
||||
for gamma in (1.0, 2.0, 2.2, 2.8, 3.0):
|
||||
table = generate_gamma_table(gamma)
|
||||
assert table[0] == 0, f"gamma={gamma}"
|
||||
|
||||
|
||||
def test_index_255_is_max() -> None:
|
||||
"""Index 255 must be 65535 (full on)."""
|
||||
for gamma in (1.0, 2.0, 2.2, 2.8, 3.0):
|
||||
table = generate_gamma_table(gamma)
|
||||
assert table[255] == 65535, f"gamma={gamma}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gamma", [1.0, 2.0, 2.2, 2.8, 3.0])
|
||||
def test_nonzero_indices_are_nonzero(gamma: float) -> None:
|
||||
"""All indices > 0 must produce non-zero values.
|
||||
|
||||
This prevents zero_means_zero breakage: non-zero input must always
|
||||
produce non-zero output so FloatOutput applies min_power scaling.
|
||||
"""
|
||||
table = generate_gamma_table(gamma)
|
||||
for i in range(1, 256):
|
||||
assert table[i] >= 1, f"gamma={gamma}, index {i}: got {table[i]}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gamma", [1.0, 2.0, 2.2, 2.8, 3.0])
|
||||
def test_table_monotonically_nondecreasing(gamma: float) -> None:
|
||||
"""The gamma table must be monotonically non-decreasing."""
|
||||
table = generate_gamma_table(gamma)
|
||||
for i in range(1, 256):
|
||||
assert table[i] >= table[i - 1], (
|
||||
f"gamma={gamma}: table[{i}]={table[i]} < table[{i - 1}]={table[i - 1]}"
|
||||
)
|
||||
|
||||
|
||||
def test_linear_gamma() -> None:
|
||||
"""With gamma=0 (linear), table should be evenly spaced."""
|
||||
table = generate_gamma_table(0)
|
||||
assert table[0] == 0
|
||||
assert table[128] == round(128 / 255.0 * 65535)
|
||||
assert table[255] == 65535
|
||||
|
||||
|
||||
@pytest.mark.parametrize("brightness", [0.01, 0.005, 0.001, 1 / 255])
|
||||
def test_small_brightness_nonzero_after_lut(brightness: float) -> None:
|
||||
"""Small but non-zero brightness must produce non-zero output through the LUT.
|
||||
|
||||
Regression test for #15055: with zero_means_zero=true, a gamma-corrected
|
||||
value of exactly 0.0 causes FloatOutput to skip min_power scaling, turning
|
||||
the LED off instead of to minimum brightness.
|
||||
"""
|
||||
table = generate_gamma_table(2.8)
|
||||
result = _simulate_gamma_correct_lut(table, brightness)
|
||||
assert result > 0.0, (
|
||||
f"brightness={brightness}: gamma LUT returned 0.0, would break zero_means_zero"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gamma", [1.0, 2.0, 2.2, 2.8, 3.0])
|
||||
def test_small_brightness_nonzero_all_gammas(gamma: float) -> None:
|
||||
"""1% brightness must be non-zero for all common gamma values."""
|
||||
table = generate_gamma_table(gamma)
|
||||
result = _simulate_gamma_correct_lut(table, 0.01)
|
||||
assert result > 0.0, f"gamma={gamma}: 1% brightness returned 0.0"
|
||||
|
||||
|
||||
def test_lut_zero_returns_zero() -> None:
|
||||
"""LUT with input 0.0 must return 0.0."""
|
||||
table = generate_gamma_table(2.8)
|
||||
assert _simulate_gamma_correct_lut(table, 0.0) == 0.0
|
||||
|
||||
|
||||
def test_lut_one_returns_one() -> None:
|
||||
"""LUT with input 1.0 must return 1.0."""
|
||||
table = generate_gamma_table(2.8)
|
||||
assert _simulate_gamma_correct_lut(table, 1.0) == 1.0
|
||||
|
||||
|
||||
def test_lut_output_monotonically_nondecreasing() -> None:
|
||||
"""LUT output must be monotonically non-decreasing across the full range."""
|
||||
table = generate_gamma_table(2.8)
|
||||
prev = 0.0
|
||||
for i in range(1001):
|
||||
value = i / 1000.0
|
||||
result = _simulate_gamma_correct_lut(table, value)
|
||||
assert result >= prev, f"value={value}: result {result} < previous {prev}"
|
||||
prev = result
|
||||
Reference in New Issue
Block a user