mirror of
https://github.com/esphome/esphome.git
synced 2026-11-17 10:36:01 +00:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34b24d0cf5 | ||
|
|
e27614fda3 | ||
|
|
8426d04138 | ||
|
|
641c8bedc9 | ||
|
|
4a39ca1b71 | ||
|
|
4a218fdbd8 | ||
|
|
d8fc1cd214 | ||
|
|
1e030b7371 | ||
|
|
3b113f2c39 | ||
|
|
73468592a9 | ||
|
|
a1b456150d | ||
|
|
865a883abb | ||
|
|
357a6717c8 | ||
|
|
bcb434e05e | ||
|
|
fb65fcc5f6 | ||
|
|
b5e379a9d4 | ||
|
|
05286dfd5d | ||
|
|
36184f09aa | ||
|
|
449933891e | ||
|
|
a5bfa6dac3 | ||
|
|
5aaa5b0552 | ||
|
|
9ab090a818 | ||
|
|
02d0bb56a6 | ||
|
|
e12784543d | ||
|
|
bc3e9c88f4 | ||
|
|
7e3c2ebc10 |
No files matched your search
@@ -515,18 +515,12 @@ void CC1101Component::dump_config() {
|
||||
}
|
||||
|
||||
void CC1101Component::begin_tx() {
|
||||
this->wake_up();
|
||||
// Read the mode before the PKTCTRL0 write below overwrites it in state_
|
||||
const bool packet_mode = this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
|
||||
// Ensure Packet Format is 3 (Async Serial)
|
||||
this->write_(Register::PKTCTRL0, 0x32);
|
||||
if (this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
|
||||
ESP_LOGW(TAG, "begin_tx is for async serial mode; use send_packet in packet mode");
|
||||
return;
|
||||
}
|
||||
ESP_LOGV(TAG, "Beginning TX sequence");
|
||||
if (this->gdo0_pin_ != nullptr) {
|
||||
// setup() only attaches the interrupt in packet mode. In async serial mode the pin may be
|
||||
// shared with remote_receiver, and detaching here would remove the receiver's interrupt.
|
||||
if (packet_mode) {
|
||||
this->gdo0_pin_->detach_interrupt();
|
||||
}
|
||||
this->gdo0_pin_->pin_mode(gpio::FLAG_OUTPUT);
|
||||
}
|
||||
// Transition through IDLE to bypass CCA (Clear Channel Assessment) which can
|
||||
|
||||
@@ -605,7 +605,9 @@ async def to_code(config: ConfigType) -> None:
|
||||
cg.add(var.set_type(conf[CONF_TYPE]))
|
||||
|
||||
for conf in config[CONF_SELECTS]:
|
||||
var = await select.new_select(conf, options=conf[CONF_OPTIONS])
|
||||
var = await select.new_select(
|
||||
conf, options=conf[CONF_OPTIONS], fixed_options=True
|
||||
)
|
||||
await cg.register_component(var, conf)
|
||||
|
||||
for conf in config[CONF_SENSORS]:
|
||||
|
||||
@@ -41,5 +41,5 @@ CONFIG_SCHEMA = (
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await select.new_select(config, options=DUCO_MODE_OPTIONS)
|
||||
var = await select.new_select(config, options=DUCO_MODE_OPTIONS, fixed_options=True)
|
||||
await register_duco_device(var, config, config[CONF_DUCO_ID])
|
||||
@@ -114,6 +114,26 @@ struct LogBuffer {
|
||||
this->finalize_();
|
||||
}
|
||||
#endif
|
||||
// Writes a message that needs no formatting, truncated and stripped of trailing newlines as format_body() does
|
||||
void HOT write_unformatted_body(const char *text, size_t len) {
|
||||
if (!this->full_()) {
|
||||
const uint16_t limit = this->remaining_() - 1; // vsnprintf() keeps the last byte for the null terminator
|
||||
const uint16_t copy_len = (len < limit) ? static_cast<uint16_t>(len) : limit;
|
||||
memcpy(this->current_(), text, copy_len);
|
||||
this->pos += copy_len;
|
||||
this->strip_trailing_newlines_();
|
||||
}
|
||||
this->finalize_();
|
||||
}
|
||||
// write_unformatted_body() for a message in flash
|
||||
inline void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body_p(ESPHOME_PGM_P text) {
|
||||
if (!this->full_()) {
|
||||
char *const start = this->current_();
|
||||
this->pos = static_cast<uint16_t>(progmem_copy_str(start, start + this->remaining_() - 1, text) - this->data);
|
||||
this->strip_trailing_newlines_();
|
||||
}
|
||||
this->finalize_();
|
||||
}
|
||||
static constexpr uint16_t ANSI_COLOR_LEN = 7; // "\033[{bold};3{color}m" written by write_header for level != 0
|
||||
static constexpr uint16_t ANSI_RESET_LEN = 4; // "\033[0m"
|
||||
// Largest replay header: color plus "@4294967295ms "
|
||||
@@ -161,7 +181,8 @@ struct LogBuffer {
|
||||
this->pos += ANSI_RESET_LEN;
|
||||
}
|
||||
}
|
||||
void strip_trailing_newlines_() {
|
||||
// Forced inline: an outlined copy slows every formatted line
|
||||
inline void ESPHOME_ALWAYS_INLINE strip_trailing_newlines_() {
|
||||
while (this->pos > 0 && this->data[this->pos - 1] == '\n')
|
||||
this->pos--;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,15 @@ namespace esphome::logger {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "logger");
|
||||
|
||||
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
|
||||
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes to a socket would
|
||||
// take that lock again and deadlock, so such a line is queued for loop() instead. It can print after later inline
|
||||
// lines, and is lost if loop() never runs again (safe_reboot()).
|
||||
static inline bool HOT ESPHOME_ALWAYS_INLINE under_lwip_core_lock() {
|
||||
return sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(USE_ESP32) || defined(USE_HOST) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
|
||||
// Implementation for multi-threaded platforms (ESP32 with FreeRTOS, Host with pthreads, LibreTiny with FreeRTOS,
|
||||
// Zephyr) Main thread/task always uses direct buffer access for console output and callbacks
|
||||
@@ -51,11 +60,7 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
|
||||
// Pass nullptr for thread_name since we already know this is the main task
|
||||
if (is_main_task && !this->main_task_recursion_guard_) [[likely]] {
|
||||
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
|
||||
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes
|
||||
// to a socket would take that lock again and deadlock, so queue the message for loop() instead. Such lines
|
||||
// can print after later inline ones, and are lost if loop() never runs again (safe_reboot()).
|
||||
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED))
|
||||
[[unlikely]] {
|
||||
if (under_lwip_core_lock()) [[unlikely]] {
|
||||
this->log_vprintf_non_main_thread_(level, tag, line, format, args, nullptr);
|
||||
return;
|
||||
}
|
||||
@@ -159,6 +164,49 @@ void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __Flas
|
||||
}
|
||||
#endif // USE_ESP8266
|
||||
|
||||
// Not shared with log_message_to_buffer_and_send_(): sharing it slows formatted lines
|
||||
inline void HOT ESPHOME_ALWAYS_INLINE Logger::send_unformatted_line_(uint8_t level, const char *tag, LogBuffer &buf) {
|
||||
#ifdef USE_LOGGER_BOOT_LOG_BUFFER
|
||||
if (!this->boot_log_done_)
|
||||
this->boot_log_capture_(level, tag, buf);
|
||||
#endif
|
||||
this->notify_listeners_(level, tag, buf);
|
||||
this->write_log_buffer_to_console_(buf);
|
||||
}
|
||||
|
||||
bool HOT Logger::log_str_(uint8_t level, const char *tag, int line, const char *msg) {
|
||||
if (level > this->level_for(tag))
|
||||
return true;
|
||||
// Check the task first: the guard belongs to the main task and must not be read from other threads
|
||||
if (!this->is_main_task_())
|
||||
return false;
|
||||
if (this->main_task_recursion_guard_)
|
||||
return true;
|
||||
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
|
||||
// The formatting path queues it
|
||||
if (under_lwip_core_lock()) [[unlikely]]
|
||||
return false;
|
||||
#endif
|
||||
RecursionGuard guard(this->main_task_recursion_guard_);
|
||||
LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
|
||||
buf.write_header(level, tag, line, nullptr);
|
||||
buf.write_unformatted_body(msg, strlen(msg));
|
||||
this->send_unformatted_line_(level, tag, buf);
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
void Logger::log_str_(uint8_t level, const char *tag, int line, const __FlashStringHelper *msg) {
|
||||
if (level > this->level_for(tag) || this->main_task_recursion_guard_)
|
||||
return;
|
||||
RecursionGuard guard(this->main_task_recursion_guard_);
|
||||
LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
|
||||
buf.write_header(level, tag, line, nullptr);
|
||||
buf.write_unformatted_body_p(reinterpret_cast<PGM_P>(msg));
|
||||
this->send_unformatted_line_(level, tag, buf);
|
||||
}
|
||||
#endif // USE_ESP8266
|
||||
|
||||
#if defined(USE_LOGGER_RUNTIME_TAG_LEVELS) || defined(USE_LOGGER_BOOT_LOG_PER_TAG_LEVELS)
|
||||
// Level for tag from a per-tag map, or fallback when the tag has none; tags may live in flash
|
||||
static inline uint8_t tag_level(const std::map<const char *, uint8_t, CStrCompare> &levels, const char *tag,
|
||||
|
||||
@@ -223,6 +223,12 @@ class Logger final : public Component {
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
void log_vprintf_(uint8_t level, const char *tag, int line, const __FlashStringHelper *format, va_list args);
|
||||
#endif
|
||||
// Copies a line with no '%' without formatting; false means the caller must format it
|
||||
bool log_str_(uint8_t level, const char *tag, int line, const char *msg); // NOLINT
|
||||
#ifdef USE_ESP8266
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
void log_str_(uint8_t level, const char *tag, int line, const __FlashStringHelper *msg);
|
||||
#endif
|
||||
|
||||
protected:
|
||||
// RAII guard for recursion flags - sets flag on construction, clears on destruction
|
||||
@@ -292,7 +298,7 @@ class Logger final : public Component {
|
||||
}
|
||||
|
||||
// Helper to write log buffer to console if logging is enabled
|
||||
inline void HOT write_log_buffer_to_console_(LogBuffer &buf) {
|
||||
inline void HOT ESPHOME_ALWAYS_INLINE write_log_buffer_to_console_(LogBuffer &buf) {
|
||||
if (this->baud_rate_ > 0)
|
||||
this->write_to_console_(buf);
|
||||
}
|
||||
@@ -321,6 +327,21 @@ class Logger final : public Component {
|
||||
this->write_log_buffer_to_console_(buf);
|
||||
}
|
||||
|
||||
inline void send_unformatted_line_(uint8_t level, const char *tag, LogBuffer &buf);
|
||||
|
||||
// True on the task that runs the main loop, and always on single-task platforms
|
||||
inline bool HOT is_main_task_() const {
|
||||
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
|
||||
return xTaskGetCurrentTaskHandle() == this->main_task_;
|
||||
#elif defined(USE_ZEPHYR)
|
||||
return k_current_get() == this->main_task_;
|
||||
#elif defined(USE_HOST)
|
||||
return pthread_equal(pthread_self(), this->main_thread_);
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
|
||||
// Helper to format a pre-formatted message from the task log buffer and notify listeners
|
||||
inline void HOT format_buffered_message_and_notify_(uint8_t level, const char *tag, uint16_t line,
|
||||
|
||||
@@ -34,6 +34,6 @@ async def to_code(config: ConfigType) -> None:
|
||||
levels = list(LOG_LEVELS)
|
||||
index = levels.index(CORE.data[DOMAIN][CONF_LEVEL])
|
||||
levels = levels[: index + 1]
|
||||
var = await select.new_select(config, options=levels)
|
||||
var = await select.new_select(config, options=levels, fixed_options=True)
|
||||
await register_parented(var, parent)
|
||||
await register_component(var, config)
|
||||
@@ -103,7 +103,9 @@ async def to_code(config: ConfigType) -> None:
|
||||
)
|
||||
|
||||
await cg.register_component(var, config)
|
||||
await select.register_select(var, config, options=list(options_map.keys()))
|
||||
await select.register_select(
|
||||
var, config, options=list(options_map.keys()), fixed_options=True
|
||||
)
|
||||
|
||||
parent = await cg.get_variable(config[CONF_MODBUS_CONTROLLER_ID])
|
||||
cg.add(parent.add_sensor_item(var))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
import logging
|
||||
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
@@ -8,6 +9,8 @@ import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DURATION, CONF_ID, CONF_MODE, CONF_VOLTAGE
|
||||
from esphome.types import ConfigType
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CODEOWNERS = ["@tomaszduda23"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
DOMAIN = "npm1300"
|
||||
@@ -42,20 +45,18 @@ NPM1300_CHILD_SCHEMA = cv.Schema(
|
||||
{cv.GenerateID(CONF_NPM1300_ID): cv.use_id(NPM1300Component)}
|
||||
)
|
||||
|
||||
# Status registers read on each update: VBUSINSTATUS, BCHGCHARGESTATUS and BCHGERRREASON
|
||||
NPM1300Status = npm1300_ns.struct("NPM1300Status")
|
||||
# The status registers read on each update
|
||||
STATUS_PUBLISHER = cg.HubFunction(
|
||||
"status",
|
||||
cg.void,
|
||||
[
|
||||
(cg.uint8, "vbus_status"),
|
||||
(cg.uint8, "charge_status"),
|
||||
(cg.uint8, "error_reason"),
|
||||
],
|
||||
[(NPM1300Status.operator("const").operator("ref"), "status")],
|
||||
define="USE_NPM1300_STATUS_PUBLISHER",
|
||||
)
|
||||
VBUS_STATUS = STATUS_PUBLISHER.param("vbus_status")
|
||||
CHARGE_STATUS = STATUS_PUBLISHER.param("charge_status")
|
||||
ERROR_REASON = STATUS_PUBLISHER.param("error_reason")
|
||||
STATUS = STATUS_PUBLISHER.param("status")
|
||||
VBUS_STATUS = STATUS.vbus
|
||||
CHARGE_STATUS = STATUS.charge
|
||||
ERROR_REASON = STATUS.error_reason
|
||||
# The ADC results and the amperes per code of the battery current
|
||||
DATA_PUBLISHER = cg.HubFunction(
|
||||
"data",
|
||||
@@ -77,7 +78,10 @@ OUTPUTS = NPM1300Output.options(
|
||||
# Written for a field the YAML leaves out
|
||||
NPM1300_UNSET = 0xFF
|
||||
# ADCNTCRSEL codes, by kiloohms
|
||||
THERMISTOR_NONE = "none"
|
||||
THERMISTOR_RESISTANCES = {10: 1, 47: 2, 100: 3}
|
||||
# B25/50 of the thermistors the product specification lists for each resistance, by kiloohms
|
||||
THERMISTOR_BETAS = {10: 3380, 47: 4050, 100: 4250}
|
||||
LDO_MODES = {"load_switch": 0, "ldo": 1}
|
||||
TERMINATION_CURRENTS = {"10%": 0, "20%": 1}
|
||||
# BCHGVTRICKLESEL, by millivolts
|
||||
@@ -135,6 +139,24 @@ def _stepped(
|
||||
return validate
|
||||
|
||||
|
||||
_THERMISTOR_RESISTANCE = _one_of_units(
|
||||
cv.resistance, list(THERMISTOR_RESISTANCES), "kOhm", scale=0.001
|
||||
)
|
||||
|
||||
|
||||
def _thermistor_resistance(value: object) -> float | str:
|
||||
if isinstance(value, str) and value.lower() == THERMISTOR_NONE:
|
||||
return THERMISTOR_NONE
|
||||
return _THERMISTOR_RESISTANCE(value)
|
||||
|
||||
|
||||
def thermistor_beta(config: ConfigType) -> int:
|
||||
"""The B constant of the hub's thermistor: the configured one, or the one listed for its resistance."""
|
||||
if (beta := config.get(CONF_THERMISTOR_BETA)) is not None:
|
||||
return beta
|
||||
return THERMISTOR_BETAS[round(config[CONF_THERMISTOR_RESISTANCE] / 1000)]
|
||||
|
||||
|
||||
OUTPUT_VOLTAGE = _stepped(cv.voltage, 1000, 3300, 100, "V")
|
||||
VBUS_CURRENT_LIMIT = _stepped(cv.current, 100, 1500, 100, "A")
|
||||
|
||||
@@ -150,15 +172,58 @@ LDO_SCHEMA = BUCK_SCHEMA.extend(
|
||||
}
|
||||
)
|
||||
|
||||
CHARGER_SCHEMA = cv.Schema(
|
||||
WARM_TERMINATION_VOLTAGE_DEFAULT = 3.6
|
||||
|
||||
|
||||
def _warm_termination_default(config: ConfigType) -> ConfigType:
|
||||
"""Keep the default warm termination voltage at or below the termination voltage.
|
||||
|
||||
Warn when the default stays below a higher termination voltage.
|
||||
"""
|
||||
if (
|
||||
not isinstance(config, dict)
|
||||
or CONF_WARM_TERMINATION_VOLTAGE in config
|
||||
or CONF_TERMINATION_VOLTAGE not in config
|
||||
):
|
||||
return config
|
||||
try:
|
||||
termination = cv.voltage(config[CONF_TERMINATION_VOLTAGE])
|
||||
except cv.Invalid:
|
||||
# The schema reports it
|
||||
return config
|
||||
if termination < WARM_TERMINATION_VOLTAGE_DEFAULT - 0.001:
|
||||
# A warm battery is never charged higher than a cool one
|
||||
return {
|
||||
**config,
|
||||
CONF_WARM_TERMINATION_VOLTAGE: config[CONF_TERMINATION_VOLTAGE],
|
||||
}
|
||||
if termination > WARM_TERMINATION_VOLTAGE_DEFAULT + 0.001:
|
||||
_LOGGER.warning(
|
||||
"npm1300 '%s' is not set, so a warm battery (45 °C to 60 °C by default) stops "
|
||||
"charging at %.2fV instead of the %.2fV of '%s'. Set '%s' to the value your "
|
||||
"battery allows when warm",
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
WARM_TERMINATION_VOLTAGE_DEFAULT,
|
||||
termination,
|
||||
CONF_TERMINATION_VOLTAGE,
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
_CHARGER_SETTINGS_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_CHARGE_CURRENT): _stepped(cv.current, 32, 800, 2, "A"),
|
||||
cv.Optional(CONF_TERMINATION_VOLTAGE, default="4.2V"): _one_of_units(
|
||||
cv.voltage, TERMINATION_VOLTAGES, "V"
|
||||
# Defaults are the reset values of the product specification
|
||||
cv.Optional(CONF_CHARGE_CURRENT, default="32mA"): _stepped(
|
||||
cv.current, 32, 800, 2, "A"
|
||||
),
|
||||
cv.Optional(CONF_WARM_TERMINATION_VOLTAGE): _one_of_units(
|
||||
cv.Optional(CONF_TERMINATION_VOLTAGE, default="3.6V"): _one_of_units(
|
||||
cv.voltage, TERMINATION_VOLTAGES, "V"
|
||||
),
|
||||
cv.Optional(
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
default=f"{WARM_TERMINATION_VOLTAGE_DEFAULT}V",
|
||||
): _one_of_units(cv.voltage, TERMINATION_VOLTAGES, "V"),
|
||||
cv.Optional(CONF_TERMINATION_CURRENT, default="10%"): cv.enum(
|
||||
TERMINATION_CURRENTS
|
||||
),
|
||||
@@ -169,22 +234,37 @@ CHARGER_SCHEMA = cv.Schema(
|
||||
cv.current, list(DISCHARGE_CURRENT_LIMITS), "A"
|
||||
),
|
||||
cv.Optional(CONF_RECHARGE, default=True): cv.boolean,
|
||||
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
|
||||
cv.Optional(CONF_ENABLED, default=False): cv.boolean,
|
||||
}
|
||||
)
|
||||
CHARGER_SCHEMA = cv.All(_warm_termination_default, _CHARGER_SETTINGS_SCHEMA)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
def _check_thermistor(config: ConfigType) -> ConfigType:
|
||||
"""A wrong thermistor shifts the battery temperature the charger sees, so charging needs one chosen."""
|
||||
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
|
||||
if CONF_CHARGER in config and resistance is None:
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' is required with '{CONF_CHARGER}': set the nominal "
|
||||
f"resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
|
||||
path=[CONF_THERMISTOR_RESISTANCE],
|
||||
)
|
||||
if CONF_THERMISTOR_BETA in config and resistance in (None, THERMISTOR_NONE):
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_THERMISTOR_BETA}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
|
||||
"resistance of the thermistor",
|
||||
path=[CONF_THERMISTOR_BETA],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(NPM1300Component),
|
||||
cv.Optional(CONF_VBUS_CURRENT_LIMIT): VBUS_CURRENT_LIMIT,
|
||||
cv.Optional(CONF_THERMISTOR_RESISTANCE): _one_of_units(
|
||||
cv.resistance, list(THERMISTOR_RESISTANCES), "kOhm", scale=0.001
|
||||
),
|
||||
cv.Optional(CONF_THERMISTOR_BETA, default=3380): cv.int_range(
|
||||
min=1, max=65535
|
||||
),
|
||||
cv.Optional(CONF_THERMISTOR_RESISTANCE): _thermistor_resistance,
|
||||
cv.Optional(CONF_THERMISTOR_BETA): cv.int_range(min=1, max=65535),
|
||||
cv.Optional(CONF_CHARGER): CHARGER_SCHEMA,
|
||||
cv.Optional(CONF_BUCK1): BUCK_SCHEMA,
|
||||
cv.Optional(CONF_BUCK2): BUCK_SCHEMA,
|
||||
@@ -193,7 +273,8 @@ CONFIG_SCHEMA = (
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
.extend(i2c.i2c_device_schema(0x6B))
|
||||
.extend(i2c.i2c_device_schema(0x6B)),
|
||||
_check_thermistor,
|
||||
)
|
||||
|
||||
|
||||
@@ -208,7 +289,7 @@ def _vbus_current_limit_code(amps: float) -> int:
|
||||
|
||||
def _charger_config(config: ConfigType) -> cg.StructInitializer:
|
||||
termination = _termination_voltage_code(config[CONF_TERMINATION_VOLTAGE])
|
||||
warm = config.get(CONF_WARM_TERMINATION_VOLTAGE)
|
||||
warm = _termination_voltage_code(config[CONF_WARM_TERMINATION_VOLTAGE])
|
||||
return cg.StructInitializer(
|
||||
NPM1300ChargerConfig,
|
||||
("current", _millis(config[CONF_CHARGE_CURRENT]) // 2),
|
||||
@@ -217,10 +298,7 @@ def _charger_config(config: ConfigType) -> cg.StructInitializer:
|
||||
DISCHARGE_CURRENT_LIMITS[_millis(config[CONF_DISCHARGE_CURRENT_LIMIT])],
|
||||
),
|
||||
("termination_voltage", termination),
|
||||
(
|
||||
"warm_termination_voltage",
|
||||
termination if warm is None else _termination_voltage_code(warm),
|
||||
),
|
||||
("warm_termination_voltage", warm),
|
||||
("trickle_voltage", TRICKLE_VOLTAGES[_millis(config[CONF_TRICKLE_VOLTAGE])]),
|
||||
("termination_current", TERMINATION_CURRENTS[config[CONF_TERMINATION_CURRENT]]),
|
||||
("recharge", config[CONF_RECHARGE]),
|
||||
@@ -247,6 +325,13 @@ def _output_config(config: ConfigType | None) -> cg.StructInitializer:
|
||||
def _config(config: ConfigType) -> cg.StructInitializer:
|
||||
charger = config.get(CONF_CHARGER)
|
||||
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
|
||||
if resistance is None:
|
||||
thermistor, beta = NPM1300_UNSET, 0
|
||||
elif resistance == THERMISTOR_NONE:
|
||||
thermistor, beta = 0, 0
|
||||
else:
|
||||
thermistor = THERMISTOR_RESISTANCES[round(resistance / 1000)]
|
||||
beta = thermistor_beta(config)
|
||||
return cg.StructInitializer(
|
||||
NPM1300Config,
|
||||
(
|
||||
@@ -254,13 +339,8 @@ def _config(config: ConfigType) -> cg.StructInitializer:
|
||||
cg.ArrayInitializer(*(_output_config(config.get(key)) for key in OUTPUTS)),
|
||||
),
|
||||
("charger", None if charger is None else _charger_config(charger)),
|
||||
("thermistor_beta", config[CONF_THERMISTOR_BETA]),
|
||||
(
|
||||
"thermistor",
|
||||
NPM1300_UNSET
|
||||
if resistance is None
|
||||
else THERMISTOR_RESISTANCES[round(resistance / 1000)],
|
||||
),
|
||||
("thermistor_beta", beta),
|
||||
("thermistor", thermistor),
|
||||
("charger_configured", charger is not None),
|
||||
)
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ static constexpr uint16_t REG_BCHG_VTERM = 0x030C;
|
||||
static constexpr uint16_t REG_BCHG_VTERM_R = 0x030D;
|
||||
static constexpr uint16_t REG_BCHG_VTRICKLE_SEL = 0x030E;
|
||||
static constexpr uint16_t REG_BCHG_ITERM_SEL = 0x030F;
|
||||
static constexpr uint16_t REG_BCHG_NTC_STATUS = 0x0332;
|
||||
static constexpr uint16_t REG_BCHG_CHARGE_STATUS = 0x0334;
|
||||
static constexpr uint16_t REG_BCHG_ERR_REASON = 0x0336;
|
||||
static constexpr uint16_t REG_BUCK1_ENA_SET = 0x0400;
|
||||
@@ -53,6 +54,9 @@ static constexpr uint16_t REG_SHIP_TASK_SHIP_MODE = 0x0B02;
|
||||
|
||||
// VBUSINSTATUS
|
||||
static constexpr uint8_t VBUS_PRESENT = 0x01;
|
||||
// NTCSTATUS
|
||||
static constexpr uint8_t NTC_STATUS_COLD = 0x01;
|
||||
static constexpr uint8_t NTC_STATUS_HOT = 0x08;
|
||||
// BCHGCHARGESTATUS; bit 0 (battery detected) is reserved since C00 silicon
|
||||
static constexpr uint8_t CHARGE_STATUS_COMPLETED = 0x02;
|
||||
static constexpr uint8_t CHARGE_STATUS_TRICKLE = 0x04;
|
||||
@@ -107,26 +111,36 @@ float ntc_temperature(uint16_t code, float inv_beta) {
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Error", "Paused, Die Too Hot", "Charge Complete", "Trickle Charge",
|
||||
"Constant Current", "Constant Voltage", "Discharging", "Not Charging");
|
||||
// BCHGCHARGESTATUS bits in order of priority; bit i is reported as string i + 1
|
||||
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Discharging", "Error", "Disabled", "Paused, PMIC Too Hot",
|
||||
"Charge Complete", "Trickle Charge", "Constant Current", "Constant Voltage",
|
||||
"Paused, Battery Too Cold", "Paused, Battery Too Hot", "Not Charging");
|
||||
static constexpr uint8_t CHARGER_STATUS_FIRST_BIT = 3;
|
||||
// BCHGCHARGESTATUS bits in order of priority, reported from string CHARGER_STATUS_FIRST_BIT on
|
||||
static const uint8_t CHARGER_STATUS_BITS[] PROGMEM = {CHARGE_STATUS_DIE_TEMP_HIGH, CHARGE_STATUS_COMPLETED,
|
||||
CHARGE_STATUS_TRICKLE, CHARGE_STATUS_CONSTANT_CURRENT,
|
||||
CHARGE_STATUS_CONSTANT_VOLTAGE};
|
||||
|
||||
static uint8_t charger_status_index(uint8_t vbus_status, uint8_t charge_status, uint8_t error_reason) {
|
||||
if (error_reason != 0)
|
||||
static uint8_t charger_status_index(const NPM1300Status &status) {
|
||||
if ((status.vbus & VBUS_PRESENT) == 0)
|
||||
return 0;
|
||||
if (status.error_reason != 0)
|
||||
return 1;
|
||||
if ((status.charger_enable & 1) == 0)
|
||||
return 2;
|
||||
for (size_t i = 0; i < sizeof(CHARGER_STATUS_BITS); i++) {
|
||||
if ((charge_status & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
|
||||
return i + 1;
|
||||
if ((status.charge & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
|
||||
return CHARGER_STATUS_FIRST_BIT + i;
|
||||
}
|
||||
return (vbus_status & VBUS_PRESENT) == 0 ? 6 : 7;
|
||||
// The charger stops without an error outside the cold and hot limits of the battery temperature
|
||||
if ((status.ntc & NTC_STATUS_COLD) != 0)
|
||||
return 8;
|
||||
if ((status.ntc & NTC_STATUS_HOT) != 0)
|
||||
return 9;
|
||||
return 10;
|
||||
}
|
||||
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
|
||||
uint8_t error_reason) {
|
||||
const uint8_t index = charger_status_index(vbus_status, charge_status, error_reason);
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status) {
|
||||
const uint8_t index = charger_status_index(status);
|
||||
if (index == last)
|
||||
return;
|
||||
last = index;
|
||||
@@ -198,7 +212,7 @@ bool NPM1300Component::configure_charger_(const NPM1300Config &config) {
|
||||
split_9bit(charger.discharge_limit, discharge);
|
||||
uint8_t disable = charger.recharge ? 0 : CHARGER_DISABLE_RECHARGE;
|
||||
// Without a thermistor the charger reports an NTC error and does not charge
|
||||
if (config.thermistor == NPM1300_UNSET)
|
||||
if (config.thermistor == 0 || config.thermistor == NPM1300_UNSET)
|
||||
disable |= CHARGER_DISABLE_NTC;
|
||||
const uint8_t enable = (CHARGER_DISABLE_RECHARGE | CHARGER_DISABLE_NTC) & ~disable;
|
||||
if (this->write_register16(REG_BCHG_ISET_MSB, current, sizeof(current)) != i2c::ERROR_OK ||
|
||||
@@ -292,33 +306,40 @@ void NPM1300Component::hibernate(uint32_t duration_ms) {
|
||||
}
|
||||
|
||||
void NPM1300Component::update() {
|
||||
uint8_t vbus_status;
|
||||
uint8_t charge_status;
|
||||
uint8_t error_reason;
|
||||
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &vbus_status) &&
|
||||
this->read_byte_reg16(REG_BCHG_CHARGE_STATUS, &charge_status) &&
|
||||
this->read_byte_reg16(REG_BCHG_ERR_REASON, &error_reason)))
|
||||
NPM1300Status status;
|
||||
// NTCSTATUS, DIETEMPSTATUS and BCHGCHARGESTATUS
|
||||
uint8_t charger_status[3];
|
||||
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &status.vbus) &&
|
||||
this->read_byte_reg16(REG_BCHG_ENABLE_SET, &status.charger_enable) &&
|
||||
this->read_register16(REG_BCHG_NTC_STATUS, charger_status, sizeof(charger_status)) ==
|
||||
i2c::ERROR_OK &&
|
||||
this->read_byte_reg16(REG_BCHG_ERR_REASON, &status.error_reason)))
|
||||
return;
|
||||
status.ntc = charger_status[0];
|
||||
status.charge = charger_status[2];
|
||||
// Without a thermistor the NTC pin is grounded and can read as a hot battery
|
||||
if (progmem_read_byte(&this->config_->thermistor) == 0)
|
||||
status.ntc = 0;
|
||||
|
||||
// The chip goes back to its default VBUS current limit whenever VBUS is removed
|
||||
const bool vbus_present = (vbus_status & VBUS_PRESENT) != 0;
|
||||
const bool vbus_present = (status.vbus & VBUS_PRESENT) != 0;
|
||||
if (vbus_present && !this->vbus_present_ && this->vbus_current_limit_ != NPM1300_UNSET &&
|
||||
!this->status_comm_check(this->apply_vbus_current_limit_()))
|
||||
return;
|
||||
this->vbus_present_ = vbus_present;
|
||||
|
||||
if (error_reason != this->last_error_reason_) {
|
||||
this->last_error_reason_ = error_reason;
|
||||
if (error_reason != 0) {
|
||||
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", error_reason);
|
||||
if (status.error_reason != this->last_error_reason_) {
|
||||
this->last_error_reason_ = status.error_reason;
|
||||
if (status.error_reason != 0) {
|
||||
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", status.error_reason);
|
||||
}
|
||||
}
|
||||
#ifdef USE_NPM1300_STATUS_PUBLISHER
|
||||
if (this->status_publisher_ != nullptr)
|
||||
this->status_publisher_(vbus_status, charge_status, error_reason);
|
||||
this->status_publisher_(status);
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
if (!this->status_comm_check(this->publish_switches_()))
|
||||
if (!this->status_comm_check(this->publish_switches_(status)))
|
||||
return;
|
||||
#endif
|
||||
|
||||
@@ -348,16 +369,10 @@ void NPM1300Component::update() {
|
||||
}
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
bool NPM1300Component::publish_switches_() {
|
||||
bool NPM1300Component::publish_switches_(const NPM1300Status &status) {
|
||||
PUBLISH_STATE(this->charger_switch_, (status.charger_enable & 1) != 0);
|
||||
uint8_t value;
|
||||
bool ok = true;
|
||||
if (this->charger_switch_ != nullptr) {
|
||||
if (this->read_byte_reg16(REG_BCHG_ENABLE_SET, &value)) {
|
||||
this->charger_switch_->publish_state((value & 1) != 0);
|
||||
} else {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
switch_::Switch *const bucks[2] = {this->buck1_switch_, this->buck2_switch_};
|
||||
if (bucks[0] != nullptr || bucks[1] != nullptr) {
|
||||
if (this->read_byte_reg16(REG_BUCK_STATUS, &value)) {
|
||||
@@ -461,7 +476,9 @@ void NPM1300Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, " Enabled at boot: %s", YESNO(output.enabled != 0));
|
||||
}
|
||||
}
|
||||
if (config.thermistor != NPM1300_UNSET) {
|
||||
if (config.thermistor == 0) {
|
||||
ESP_LOGCONFIG(TAG, " Thermistor: none");
|
||||
} else if (config.thermistor != NPM1300_UNSET) {
|
||||
ESP_LOGCONFIG(TAG, " Thermistor B constant: %u", config.thermistor_beta);
|
||||
}
|
||||
#ifdef USE_SENSOR
|
||||
|
||||
@@ -54,10 +54,19 @@ struct NPM1300Config {
|
||||
NPM1300OutputConfig outputs[NPM1300_OUTPUT_COUNT];
|
||||
NPM1300ChargerConfig charger; // only applied when charger_configured
|
||||
uint16_t thermistor_beta;
|
||||
uint8_t thermistor; // ADCNTCRSEL code: 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
|
||||
uint8_t thermistor; // ADCNTCRSEL code: 0 for none, 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
|
||||
bool charger_configured;
|
||||
};
|
||||
|
||||
/// The status registers read on every update
|
||||
struct NPM1300Status {
|
||||
uint8_t vbus; // VBUSINSTATUS
|
||||
uint8_t charger_enable; // BCHGENABLESET
|
||||
uint8_t ntc; // NTCSTATUS
|
||||
uint8_t charge; // BCHGCHARGESTATUS
|
||||
uint8_t error_reason; // BCHGERRREASON
|
||||
};
|
||||
|
||||
#ifdef USE_NPM1300_DATA_PUBLISHER
|
||||
/// The 10-bit ADC result whose high 8 bits are adc[msb] and low 2 bits are at `shift` in adc[lsbs]
|
||||
inline uint16_t adc_code(const uint8_t *adc, uint8_t msb, uint8_t lsbs, uint8_t shift) {
|
||||
@@ -68,8 +77,7 @@ float ntc_temperature(uint16_t code, float inv_beta);
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
/// Publish the charger status text, only when it differs from `last`
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
|
||||
uint8_t error_reason);
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status);
|
||||
#endif
|
||||
|
||||
class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
@@ -95,7 +103,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
float get_setup_priority() const override { return setup_priority::BUS - 1.0f; }
|
||||
|
||||
#ifdef USE_NPM1300_STATUS_PUBLISHER
|
||||
HUB_PUBLISHER(status, uint8_t, uint8_t, uint8_t)
|
||||
HUB_PUBLISHER(status, const NPM1300Status &)
|
||||
#endif
|
||||
#ifdef USE_NPM1300_DATA_PUBLISHER
|
||||
HUB_PUBLISHER(data, const uint8_t *, float)
|
||||
@@ -128,7 +136,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
/// Returns false when a status read failed
|
||||
bool publish_switches_();
|
||||
bool publish_switches_(const NPM1300Status &status);
|
||||
#endif
|
||||
|
||||
const NPM1300Config *config_;
|
||||
|
||||
@@ -21,7 +21,6 @@ from esphome.types import ConfigType
|
||||
from . import (
|
||||
ADC,
|
||||
CONF_NPM1300_ID,
|
||||
CONF_THERMISTOR_BETA,
|
||||
CONF_THERMISTOR_RESISTANCE,
|
||||
CONF_VBUS_CURRENT_LIMIT,
|
||||
DATA_PUBLISHER,
|
||||
@@ -30,7 +29,9 @@ from . import (
|
||||
DUMP_TAG,
|
||||
IBAT_SCALE,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
THERMISTOR_NONE,
|
||||
npm1300_ns,
|
||||
thermistor_beta,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["npm1300"]
|
||||
@@ -109,10 +110,10 @@ def _final_validate(config: ConfigType) -> None:
|
||||
if CONF_BATTERY_TEMPERATURE not in config:
|
||||
return
|
||||
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
|
||||
if CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
if hub.get(CONF_THERMISTOR_RESISTANCE, THERMISTOR_NONE) == THERMISTOR_NONE:
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' "
|
||||
"set on the npm1300 component",
|
||||
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
|
||||
"nominal resistance of the battery thermistor on the npm1300 component",
|
||||
path=[CONF_BATTERY_TEMPERATURE],
|
||||
)
|
||||
|
||||
@@ -145,7 +146,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
if (var := await sensors(CONF_BATTERY_TEMPERATURE, None)) is not None:
|
||||
hub_config = next(c for c in CORE.config[DOMAIN] if c[CONF_ID] == hub_id)
|
||||
state = npm1300_ns.ntc_temperature(
|
||||
_adc(2, 5, 2), 1.0 / hub_config[CONF_THERMISTOR_BETA]
|
||||
_adc(2, 5, 2), 1.0 / thermistor_beta(hub_config)
|
||||
)
|
||||
_add_adc_sensor(hub, var, state, "Battery Temperature")
|
||||
await sensors(CONF_VBUS_CURRENT_LIMIT, hub.set_vbus_current_limit_sensor)
|
||||
@@ -15,6 +15,7 @@ from . import (
|
||||
CONF_THERMISTOR_RESISTANCE,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
OUTPUTS,
|
||||
THERMISTOR_NONE,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["npm1300"]
|
||||
@@ -44,11 +45,18 @@ def _final_validate(config: ConfigType) -> None:
|
||||
if CONF_CHARGER not in config:
|
||||
return
|
||||
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
|
||||
# Only the charger block turns off the NTC check, without which the charger never starts
|
||||
if CONF_CHARGER not in hub and CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
# A wrong thermistor shifts the battery temperature the charger sees
|
||||
if CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
raise cv.Invalid(
|
||||
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block or "
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' on the npm1300 component",
|
||||
f"The '{CONF_CHARGER}' switch needs '{CONF_THERMISTOR_RESISTANCE}' on the npm1300 "
|
||||
f"component: the nominal resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
|
||||
path=[CONF_CHARGER],
|
||||
)
|
||||
# Only the charger block turns off the NTC check, without which the charger never starts
|
||||
if CONF_CHARGER not in hub and hub[CONF_THERMISTOR_RESISTANCE] == THERMISTOR_NONE:
|
||||
raise cv.Invalid(
|
||||
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block when "
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' is '{THERMISTOR_NONE}'",
|
||||
path=[CONF_CHARGER],
|
||||
)
|
||||
|
||||
|
||||
@@ -11,14 +11,12 @@ from esphome.cpp_generator import (
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import (
|
||||
CHARGE_STATUS,
|
||||
CONF_NPM1300_ID,
|
||||
DUMP,
|
||||
DUMP_TAG,
|
||||
ERROR_REASON,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
STATUS,
|
||||
STATUS_PUBLISHER,
|
||||
VBUS_STATUS,
|
||||
npm1300_ns,
|
||||
)
|
||||
|
||||
@@ -48,9 +46,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
)
|
||||
STATUS_PUBLISHER.add(
|
||||
hub,
|
||||
npm1300_ns.publish_charger_status(
|
||||
parent_ref(var), last, VBUS_STATUS, CHARGE_STATUS, ERROR_REASON
|
||||
),
|
||||
npm1300_ns.publish_charger_status(parent_ref(var), last, STATUS),
|
||||
)
|
||||
DUMP.add(
|
||||
hub,
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
from dataclasses import dataclass, field
|
||||
import functools
|
||||
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
@@ -26,7 +29,7 @@ from esphome.core.entity_helpers import (
|
||||
)
|
||||
from esphome.cpp_generator import MockObj, MockObjClass, TemplateArguments
|
||||
from esphome.cpp_types import global_ns
|
||||
from esphome.types import ConfigType
|
||||
from esphome.types import ConfigType, TemplateArgsType
|
||||
|
||||
CODEOWNERS = ["@esphome/core"]
|
||||
DOMAIN = "select"
|
||||
@@ -47,6 +50,25 @@ SELECT_OPERATION_OPTIONS = SelectOperation.options(
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SelectData:
|
||||
# Options of each select whose option list never changes at run time, by id
|
||||
fixed_options: dict[str, list[str]] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _get_data() -> SelectData:
|
||||
if DOMAIN not in CORE.data:
|
||||
CORE.data[DOMAIN] = SelectData()
|
||||
return CORE.data[DOMAIN]
|
||||
|
||||
|
||||
def _record_options(
|
||||
config: ConfigType, options: list[str], fixed_options: bool
|
||||
) -> None:
|
||||
if fixed_options:
|
||||
_get_data().fixed_options[config[CONF_ID].id] = options
|
||||
|
||||
|
||||
_SELECT_SCHEMA = (
|
||||
cv.ENTITY_BASE_SCHEMA.extend(entity_helpers.WEBSERVER_SORTING_SCHEMA)
|
||||
.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA)
|
||||
@@ -105,7 +127,11 @@ async def setup_select_core_(var, config, *, options: list[str]):
|
||||
await entity_helpers.setup_entity_integrations(var, config)
|
||||
|
||||
|
||||
async def register_select(var, config, *, options: list[str]):
|
||||
async def register_select(
|
||||
var, config, *, options: list[str], fixed_options: bool = False
|
||||
):
|
||||
"""``fixed_options=True`` when the options never change at run time, so ``select.set`` can use the index."""
|
||||
_record_options(config, options, fixed_options)
|
||||
if not CORE.has_id(config[CONF_ID]):
|
||||
var = cg.Pvariable(config[CONF_ID], var)
|
||||
queue_entity_register("select", config)
|
||||
@@ -113,9 +139,9 @@ async def register_select(var, config, *, options: list[str]):
|
||||
await setup_select_core_(var, config, options=options)
|
||||
|
||||
|
||||
async def new_select(config, *args, options: list[str]):
|
||||
async def new_select(config, *args, options: list[str], fixed_options: bool = False):
|
||||
var = cg.new_Pvariable(config[CONF_ID], *args)
|
||||
await register_select(var, config, options=options)
|
||||
await register_select(var, config, options=options, fixed_options=fixed_options)
|
||||
return var
|
||||
|
||||
|
||||
@@ -131,7 +157,10 @@ def sub_selects(
|
||||
config: ConfigType, *, parent: MockObj | ID | None = None
|
||||
) -> SubEntities:
|
||||
"""Return a SubEntities bound to new_select; ``apply`` statements can use ``entity``, ``index`` and ``option``."""
|
||||
return SubEntities(new_select, config, parent, APPLY_ENTITY)
|
||||
# Hub selects get their options from code generation only
|
||||
return SubEntities(
|
||||
functools.partial(new_select, fixed_options=True), config, parent, APPLY_ENTITY
|
||||
)
|
||||
|
||||
|
||||
@coroutine_with_priority(CoroPriority.CORE)
|
||||
@@ -146,13 +175,20 @@ OPERATION_BASE_SCHEMA = cv.Schema(
|
||||
)
|
||||
|
||||
|
||||
automation.register_apply_action(
|
||||
_SELECT_SET_SCHEMA = OPERATION_BASE_SCHEMA.extend(
|
||||
{
|
||||
cv.Required(CONF_OPTION): cv.templatable(cv.string_strict),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _option_index(config: ConfigType, option: str) -> str:
|
||||
return str(_get_data().fixed_options[config[CONF_ID].id].index(option))
|
||||
|
||||
|
||||
_set_option_builder = automation.apply_action_builder(
|
||||
"select.set",
|
||||
OPERATION_BASE_SCHEMA.extend(
|
||||
{
|
||||
cv.Required(CONF_OPTION): cv.templatable(cv.string_strict),
|
||||
}
|
||||
),
|
||||
_SELECT_SET_SCHEMA,
|
||||
automation.ApplyField(
|
||||
CONF_OPTION,
|
||||
"set_option",
|
||||
@@ -161,6 +197,32 @@ automation.register_apply_action(
|
||||
),
|
||||
call="make_call",
|
||||
)
|
||||
_set_index_builder = automation.apply_action_builder(
|
||||
"select.set",
|
||||
_SELECT_SET_SCHEMA,
|
||||
automation.ApplyField(CONF_OPTION, "set_index", cg.size_t, const_fn=_option_index),
|
||||
call="make_call",
|
||||
)
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
"select.set", automation.ApplyAction, _SELECT_SET_SCHEMA, synchronous=True
|
||||
)
|
||||
async def select_set_to_code(
|
||||
config: ConfigType,
|
||||
action_id: ID,
|
||||
template_arg: TemplateArguments,
|
||||
args: TemplateArgsType,
|
||||
) -> MockObj:
|
||||
# A constant fixed option becomes its index
|
||||
await cg.get_variable(config[CONF_ID])
|
||||
option = config[CONF_OPTION]
|
||||
if not cg.is_template(option) and option in _get_data().fixed_options.get(
|
||||
config[CONF_ID].id, ()
|
||||
):
|
||||
return await _set_index_builder(config, action_id, template_arg, args)
|
||||
return await _set_option_builder(config, action_id, template_arg, args)
|
||||
|
||||
|
||||
automation.register_apply_action(
|
||||
"select.set_index",
|
||||
|
||||
@@ -113,7 +113,7 @@ async def to_code(config):
|
||||
milliseconds=SCHEDULER_DONT_RUN
|
||||
)
|
||||
await cg.register_component(var, component_config)
|
||||
await select.register_select(var, config, options=options)
|
||||
await select.register_select(var, config, options=options, fixed_options=True)
|
||||
|
||||
if CONF_LAMBDA in config:
|
||||
lambda_ = await cg.process_lambda(
|
||||
|
||||
@@ -36,13 +36,8 @@ void setup_with_restore(BaseTemplateSelect *sel_comp, ESPPreferenceObject &pref,
|
||||
}
|
||||
|
||||
void update_lambda(BaseTemplateSelect *sel_comp, const optional<std::string> &val) {
|
||||
if (val.has_value()) {
|
||||
if (!sel_comp->has_option(*val)) {
|
||||
ESP_LOGE(TAG, "Lambda returned an invalid option: %s", (*val).c_str());
|
||||
return;
|
||||
}
|
||||
if (val.has_value())
|
||||
sel_comp->publish_state(*val);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::template_
|
||||
@@ -115,7 +115,7 @@ async def to_code(config):
|
||||
options = list(options_map.values())
|
||||
mappings = list(options_map.keys())
|
||||
|
||||
var = await select.new_select(config, options=options)
|
||||
var = await select.new_select(config, options=options, fixed_options=True)
|
||||
if mappings:
|
||||
cg.add(var.set_select_mappings(mappings))
|
||||
hub = await cg.add_variable(var.set_tuya_parent, config[CONF_TUYA_ID])
|
||||
|
||||
@@ -8,18 +8,16 @@ namespace esphome::zigbee {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "zigbee.attribute");
|
||||
|
||||
void ZigbeeAttribute::set_attr_() {
|
||||
void ZigbeeAttribute::set_attr_internal() {
|
||||
if (!this->zb_->is_started()) {
|
||||
return;
|
||||
}
|
||||
if (esp_zigbee_lock_acquire(10 / portTICK_PERIOD_MS)) {
|
||||
ezb_zcl_status_t state = ezb_zcl_set_attr_value(this->endpoint_id_, this->cluster_id_, this->role_, this->attr_id_,
|
||||
EZB_ZCL_STD_MANUF_CODE, this->value_p_, false);
|
||||
// cleared before report_() so it can disable the loop
|
||||
// when the report has to wait for join
|
||||
this->set_attr_requested_ = false;
|
||||
if (this->force_report_) {
|
||||
this->report_(true);
|
||||
this->report_internal(true);
|
||||
}
|
||||
// Check for error
|
||||
if (state != EZB_ZCL_STATUS_SUCCESS) {
|
||||
@@ -30,15 +28,12 @@ void ZigbeeAttribute::set_attr_() {
|
||||
}
|
||||
}
|
||||
|
||||
void ZigbeeAttribute::report_(bool has_lock) {
|
||||
void ZigbeeAttribute::report_internal(bool has_lock) {
|
||||
if (!this->report_enabled) {
|
||||
return;
|
||||
}
|
||||
if (!this->zb_->is_joined()) {
|
||||
this->report_requested_ = true;
|
||||
if (!this->set_attr_requested_) {
|
||||
this->disable_loop();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (has_lock or esp_zigbee_lock_acquire(10 / portTICK_PERIOD_MS)) {
|
||||
@@ -61,43 +56,6 @@ void ZigbeeAttribute::report_(bool has_lock) {
|
||||
}
|
||||
}
|
||||
|
||||
void ZigbeeAttribute::set_report(ZigbeeReportT report) {
|
||||
if (report == ZigbeeReportT::ZIGBEE_REPORT_DEFAULT || report == ZigbeeReportT::ZIGBEE_REPORT_COORDINATOR) {
|
||||
return;
|
||||
}
|
||||
this->report_enabled = true;
|
||||
if (report == ZigbeeReportT::ZIGBEE_REPORT_FORCE) {
|
||||
this->force_report_ = true;
|
||||
}
|
||||
this->zb_->add_on_join_callback([this](bool) {
|
||||
if (this->report_requested_) {
|
||||
this->enable_loop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ZigbeeAttribute::report() {
|
||||
if (!this->report_enabled) {
|
||||
return;
|
||||
}
|
||||
this->report_requested_ = true;
|
||||
this->enable_loop();
|
||||
}
|
||||
|
||||
void ZigbeeAttribute::loop() {
|
||||
if (this->set_attr_requested_) {
|
||||
this->set_attr_();
|
||||
}
|
||||
|
||||
if (this->report_requested_) {
|
||||
this->report_(false);
|
||||
}
|
||||
|
||||
if (!this->report_requested_ && !this->set_attr_requested_) {
|
||||
this->disable_loop();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::zigbee
|
||||
|
||||
#endif
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "zigbee_entity_base_esp32.h"
|
||||
|
||||
#ifdef USE_ESP32
|
||||
#ifdef USE_ZIGBEE
|
||||
@@ -29,34 +28,22 @@
|
||||
|
||||
namespace esphome::zigbee {
|
||||
|
||||
enum ZigbeeReportT {
|
||||
ZIGBEE_REPORT_DEFAULT,
|
||||
ZIGBEE_REPORT_COORDINATOR,
|
||||
ZIGBEE_REPORT_ENABLE,
|
||||
ZIGBEE_REPORT_FORCE,
|
||||
};
|
||||
|
||||
class ZigbeeAttribute final : public Component {
|
||||
class ZigbeeAttribute final : public ZigbeeEntityBase {
|
||||
public:
|
||||
ZigbeeAttribute(ZigbeeComponent *parent, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id,
|
||||
uint8_t attr_type, float scale, uint8_t max_size)
|
||||
: zb_(parent),
|
||||
endpoint_id_(endpoint_id),
|
||||
: ZigbeeEntityBase(parent, endpoint_id),
|
||||
cluster_id_(cluster_id),
|
||||
role_(role),
|
||||
attr_id_(attr_id),
|
||||
attr_type_(attr_type),
|
||||
max_size_(max_size),
|
||||
scale_(scale) {}
|
||||
void loop() override;
|
||||
template<typename T> void add_attr(T value);
|
||||
template<typename T> void set_attr(const T &value);
|
||||
uint8_t attr_type() { return attr_type_; }
|
||||
void set_report(ZigbeeReportT report);
|
||||
void report();
|
||||
|
||||
template<typename F> void add_on_value_callback(F &&callback) { on_value_callback_.add(std::forward<F>(callback)); }
|
||||
void on_value(ezb_zcl_attribute_t attribute) {
|
||||
void on_value(ezb_zcl_attribute_t attribute) override {
|
||||
if (attribute.data.type == this->attr_type() && attribute.data.value) {
|
||||
this->on_value_callback_.call(attribute);
|
||||
}
|
||||
@@ -75,13 +62,10 @@ class ZigbeeAttribute final : public Component {
|
||||
#ifdef USE_NUMBER
|
||||
template<typename T> void connect(number::Number *device);
|
||||
#endif
|
||||
bool report_enabled = false;
|
||||
|
||||
protected:
|
||||
void set_attr_();
|
||||
void report_(bool has_lock);
|
||||
ZigbeeComponent *zb_;
|
||||
uint8_t endpoint_id_;
|
||||
void set_attr_internal() override;
|
||||
void report_internal(bool has_lock) override;
|
||||
uint16_t cluster_id_;
|
||||
uint8_t role_;
|
||||
uint16_t attr_id_;
|
||||
@@ -89,9 +73,6 @@ class ZigbeeAttribute final : public Component {
|
||||
uint8_t max_size_;
|
||||
float scale_;
|
||||
void *value_p_{nullptr};
|
||||
bool set_attr_requested_{false};
|
||||
bool report_requested_{false};
|
||||
bool force_report_{false};
|
||||
LazyCallbackManager<void(ezb_zcl_attribute_t attribute)> on_value_callback_{};
|
||||
template<typename T> T scale_value_(float value);
|
||||
template<typename T> T invalid_value_();
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#include "zigbee_entity_base_esp32.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#ifdef USE_ESP32
|
||||
#ifdef USE_ZIGBEE
|
||||
|
||||
namespace esphome::zigbee {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "zigbee.entity_base");
|
||||
|
||||
void ZigbeeEntityBase::set_report(ZigbeeReportT report) {
|
||||
if (report == ZigbeeReportT::ZIGBEE_REPORT_DEFAULT || report == ZigbeeReportT::ZIGBEE_REPORT_COORDINATOR) {
|
||||
return;
|
||||
}
|
||||
this->report_enabled = true;
|
||||
if (report == ZigbeeReportT::ZIGBEE_REPORT_FORCE) {
|
||||
this->force_report_ = true;
|
||||
}
|
||||
this->zb_->add_on_join_callback([this](bool) {
|
||||
if (this->report_requested_) {
|
||||
this->enable_loop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ZigbeeEntityBase::report() {
|
||||
if (!this->report_enabled) {
|
||||
return;
|
||||
}
|
||||
this->report_requested_ = true;
|
||||
this->enable_loop();
|
||||
}
|
||||
|
||||
void ZigbeeEntityBase::loop() {
|
||||
if (this->set_attr_requested_) {
|
||||
this->set_attr_internal();
|
||||
}
|
||||
|
||||
if (this->report_requested_ && this->zb_->is_joined()) {
|
||||
this->report_internal(false);
|
||||
}
|
||||
|
||||
if ((!this->report_requested_ || !this->zb_->is_joined()) && !this->set_attr_requested_) {
|
||||
this->disable_loop();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::zigbee
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/defines.h"
|
||||
|
||||
#ifdef USE_ESP32
|
||||
#ifdef USE_ZIGBEE
|
||||
|
||||
#include "esp_zigbee.h"
|
||||
#include "zigbee_esp32.h"
|
||||
|
||||
namespace esphome::zigbee {
|
||||
|
||||
enum ZigbeeReportT {
|
||||
ZIGBEE_REPORT_DEFAULT,
|
||||
ZIGBEE_REPORT_COORDINATOR,
|
||||
ZIGBEE_REPORT_ENABLE,
|
||||
ZIGBEE_REPORT_FORCE,
|
||||
};
|
||||
|
||||
class ZigbeeEntityBase : public Component, public ZigbeeAttributeInterface {
|
||||
public:
|
||||
void loop() override;
|
||||
void set_report(ZigbeeReportT report);
|
||||
void report() override;
|
||||
|
||||
bool report_enabled = false;
|
||||
|
||||
protected:
|
||||
ZigbeeEntityBase(ZigbeeComponent *parent, uint8_t endpoint_id) : zb_(parent), endpoint_id_(endpoint_id) {}
|
||||
/// Handle pending attribute writes and clear set_attr_requested_ when complete; leave it set to retry.
|
||||
virtual void set_attr_internal() = 0;
|
||||
/// Handle pending reports and clear report_requested_ when complete; leave it set to retry.
|
||||
/// Acquire/release the Zigbee lock only when has_lock is false; otherwise the caller owns it.
|
||||
virtual void report_internal(bool has_lock) = 0;
|
||||
ZigbeeComponent *zb_;
|
||||
uint8_t endpoint_id_;
|
||||
bool set_attr_requested_{false};
|
||||
bool report_requested_{false};
|
||||
bool force_report_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::zigbee
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -31,7 +31,11 @@ static constexpr uint8_t MAX_ZB_QUEUE_SIZE = 32;
|
||||
|
||||
uint8_t *get_zcl_string(const char *str, uint8_t max_size, bool use_max_size = false);
|
||||
|
||||
class ZigbeeAttribute;
|
||||
class ZigbeeAttributeInterface {
|
||||
public:
|
||||
virtual void on_value(ezb_zcl_attribute_t attribute) = 0;
|
||||
virtual void report() = 0;
|
||||
};
|
||||
|
||||
class ZigbeeComponent final : public Component {
|
||||
public:
|
||||
@@ -48,8 +52,8 @@ class ZigbeeComponent final : public Component {
|
||||
bool register_device();
|
||||
|
||||
template<typename T>
|
||||
void add_attr(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id,
|
||||
uint8_t max_size, T value);
|
||||
void add_attr(ZigbeeAttributeInterface *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
|
||||
uint16_t attr_id, uint8_t max_size, T value);
|
||||
|
||||
template<typename T>
|
||||
void add_attr(uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id, uint8_t max_size, T value);
|
||||
@@ -94,13 +98,13 @@ class ZigbeeComponent final : public Component {
|
||||
void end_parent_link_failures_(uint8_t seq);
|
||||
void reset_parent_link_failures_();
|
||||
template<typename T>
|
||||
void add_attr_(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id,
|
||||
T *value_p);
|
||||
void add_attr_(ZigbeeAttributeInterface *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
|
||||
uint16_t attr_id, T *value_p);
|
||||
void handle_attribute_(ezb_zcl_message_info_t info, ezb_zcl_attribute_t attribute);
|
||||
// attributes_ will be used during operation in zigbee callbacks to update the attribute values and trigger
|
||||
// automations
|
||||
// key tuple could be replaced by single 64 (48) bit int with bit fields for endpoint, cluster, role and attr_id
|
||||
std::map<std::tuple<uint8_t, uint16_t, uint8_t, uint16_t>, ZigbeeAttribute *> attributes_;
|
||||
std::map<std::tuple<uint8_t, uint16_t, uint8_t, uint16_t>, ZigbeeAttributeInterface *> attributes_;
|
||||
ezb_af_device_desc_t dev_desc_ = ezb_af_create_device_desc();
|
||||
CallbackManager<void(bool)> join_cb_{};
|
||||
template<typename... Args> friend void enqueue_zb_event(Args... args);
|
||||
@@ -133,7 +137,7 @@ void ZigbeeComponent::add_attr(uint8_t endpoint_id, uint16_t cluster_id, uint8_t
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ZigbeeComponent::add_attr(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
|
||||
void ZigbeeComponent::add_attr(ZigbeeAttributeInterface *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
|
||||
uint16_t attr_id, uint8_t max_size, T value) {
|
||||
// The size byte of the zcl_str must be set to the maximum value,
|
||||
// even though the initial string may be shorter.
|
||||
@@ -151,7 +155,7 @@ void ZigbeeComponent::add_attr(ZigbeeAttribute *attr, uint8_t endpoint_id, uint1
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ZigbeeComponent::add_attr_(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
|
||||
void ZigbeeComponent::add_attr_(ZigbeeAttributeInterface *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
|
||||
uint16_t attr_id, T *value_p) {
|
||||
ezb_af_ep_desc_t ep_desc = ezb_af_device_get_endpoint_desc(this->dev_desc_, endpoint_id);
|
||||
if (ep_desc == NULL) {
|
||||
|
||||
@@ -1472,6 +1472,42 @@ __attribute__((format(printf, 4, 5))) inline size_t buf_append_printf(char *buf,
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Copy a PROGMEM string to `dst`, stopping at its null terminator or at `end`, and return the new end of `dst`.
|
||||
/// No terminator is written. Flash only allows aligned 32-bit loads on ESP8266, so `src` is read a whole word at a
|
||||
/// time, including the bytes after its null in the last word; `src` must be readable up to the end of that word.
|
||||
inline char *ESPHOME_ALWAYS_INLINE progmem_copy_str(char *dst, const char *end, const char *src) {
|
||||
const uint32_t offset = reinterpret_cast<uintptr_t>(src) & 3;
|
||||
const uint32_t *word = reinterpret_cast<const uint32_t *>(src - offset);
|
||||
uint32_t bytes = *word++;
|
||||
// Enters the loop at the first byte of src; after that each word runs its four steps without another dispatch, and
|
||||
// one step per byte keeps each a single extract
|
||||
switch (offset) {
|
||||
for (;;) {
|
||||
bytes = *word++;
|
||||
[[fallthrough]];
|
||||
case 0:
|
||||
if (dst >= end || static_cast<char>(bytes) == '\0')
|
||||
return dst;
|
||||
*dst++ = static_cast<char>(bytes);
|
||||
[[fallthrough]];
|
||||
case 1:
|
||||
if (dst >= end || static_cast<char>(bytes >> 8) == '\0')
|
||||
return dst;
|
||||
*dst++ = static_cast<char>(bytes >> 8);
|
||||
[[fallthrough]];
|
||||
case 2:
|
||||
if (dst >= end || static_cast<char>(bytes >> 16) == '\0')
|
||||
return dst;
|
||||
*dst++ = static_cast<char>(bytes >> 16);
|
||||
[[fallthrough]];
|
||||
default:
|
||||
if (dst >= end || static_cast<char>(bytes >> 24) == '\0')
|
||||
return dst;
|
||||
*dst++ = static_cast<char>(bytes >> 24);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
/// Safely append a PROGMEM string to buffer, returning new position (capped at size).
|
||||
/// ESP8266 internal implementation — prefer the `buf_append_str` macro which wraps
|
||||
|
||||
@@ -48,6 +48,34 @@ void HOT esp_log_printf_(int level, const char *tag, int line, const __FlashStri
|
||||
}
|
||||
#endif
|
||||
|
||||
void HOT esp_log_str_(int level, const char *tag, int line, const char *format) { // NOLINT
|
||||
#ifdef USE_LOGGER
|
||||
#ifdef ESPHOME_DEBUG
|
||||
// Before Logger::pre_setup(), the formatting path below reports the early call
|
||||
if (logger::global_logger != nullptr)
|
||||
#endif
|
||||
{
|
||||
if (logger::global_logger->log_str_(static_cast<uint8_t>(level), tag, line, format))
|
||||
return;
|
||||
}
|
||||
// Formats the line log_str_() could not copy; it has no '%', so it is its own format
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wformat-security"
|
||||
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
|
||||
esp_log_printf_(level, tag, line, format);
|
||||
#pragma GCC diagnostic pop
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
void HOT esp_log_str_(int level, const char *tag, int line, const __FlashStringHelper *format) {
|
||||
#ifdef USE_LOGGER
|
||||
ESPHOME_DEBUG_ASSERT(logger::global_logger != nullptr);
|
||||
logger::global_logger->log_str_(static_cast<uint8_t>(level), tag, line, format);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
void HOT esp_log_vprintf_(int level, const char *tag, int line, const char *format, va_list args) { // NOLINT
|
||||
#ifdef USE_LOGGER
|
||||
#ifdef ESPHOME_DEBUG
|
||||
|
||||
+57
-14
@@ -67,6 +67,14 @@ void esp_log_printf_(int level, const char *tag, int line, const char *format, .
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
void esp_log_printf_(int level, const char *tag, int line, const __FlashStringHelper *format, ...);
|
||||
#endif
|
||||
// esp_log_printf_ for a line with no arguments and no '%': it is copied without formatting
|
||||
void esp_log_str_(int level, const char *tag, int line, const char *format); // NOLINT
|
||||
#ifdef USE_ESP8266
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
void esp_log_str_(int level, const char *tag, int line, const __FlashStringHelper *format);
|
||||
#endif
|
||||
// Never defined or called: the ESP_LOGx macros name it in dead code so a line without arguments has its format checked
|
||||
int esp_log_format_check_(const char *format, ...) __attribute__((format(printf, 1, 2))); // NOLINT
|
||||
void esp_log_vprintf_(int level, const char *tag, int line, const char *format, va_list args); // NOLINT
|
||||
#if defined(USE_ESP32)
|
||||
int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
|
||||
@@ -78,9 +86,50 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
|
||||
#define ESPHOME_LOG_FORMAT(format) format
|
||||
#endif
|
||||
|
||||
#define ESPHOME_LOG_ARGS_(level, tag, format, ...) \
|
||||
::esphome::esp_log_printf_(level, tag, __LINE__, ESPHOME_LOG_FORMAT(format), __VA_ARGS__)
|
||||
// The format check is a statement-level if (false), not sizeof: GCC 16 skips format checks in unevaluated or folded
|
||||
// expressions. __builtin_strchr folds on a literal, so only a line with '%' (such as "100%%") is formatted.
|
||||
#ifdef USE_ESP8266
|
||||
// F() only takes a literal, so using format more than once cannot repeat a side effect
|
||||
#define ESPHOME_LOG_NO_ARGS_(level, tag, format) \
|
||||
({ \
|
||||
if (false) \
|
||||
::esphome::esp_log_format_check_(format); \
|
||||
if (__builtin_strchr(format, '%') != nullptr) \
|
||||
::esphome::esp_log_printf_(level, tag, __LINE__, ESPHOME_LOG_FORMAT(format)); \
|
||||
else \
|
||||
::esphome::esp_log_str_(level, tag, __LINE__, ESPHOME_LOG_FORMAT(format)); \
|
||||
})
|
||||
#else
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wformat-security"
|
||||
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
|
||||
// A function argument, so format is evaluated once and a temporary such as std::string().c_str() outlives the call
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
inline void __attribute__((always_inline)) esp_log_no_args_(int level, const char *tag, int line, const char *format) {
|
||||
if (__builtin_strchr(format, '%') != nullptr) {
|
||||
esp_log_printf_(level, tag, line, format);
|
||||
} else {
|
||||
esp_log_str_(level, tag, line, format);
|
||||
}
|
||||
}
|
||||
#pragma GCC diagnostic pop
|
||||
#define ESPHOME_LOG_NO_ARGS_(level, tag, format) \
|
||||
({ \
|
||||
if (false) \
|
||||
::esphome::esp_log_format_check_(format); \
|
||||
::esphome::esp_log_no_args_(level, tag, __LINE__, format); \
|
||||
})
|
||||
#endif
|
||||
// ESPHOME_LOG_NO_ARGS_ when there are no arguments after the format, ESPHOME_LOG_ARGS_ otherwise
|
||||
#define ESPHOME_LOG_PICK_(skip, name, ...) name
|
||||
#define ESPHOME_LOG_(level, tag, format, ...) \
|
||||
ESPHOME_LOG_PICK_(__VA_OPT__(, ) ESPHOME_LOG_ARGS_, ESPHOME_LOG_NO_ARGS_)(level, tag, \
|
||||
format __VA_OPT__(, ) __VA_ARGS__)
|
||||
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
|
||||
#define esph_log_vv(tag, format, ...) \
|
||||
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_VERY_VERBOSE, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
|
||||
#define esph_log_vv(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_VERY_VERBOSE, tag, format, __VA_ARGS__)
|
||||
|
||||
#define ESPHOME_LOG_HAS_VERY_VERBOSE
|
||||
#else
|
||||
@@ -88,8 +137,7 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
|
||||
#endif
|
||||
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
|
||||
#define esph_log_v(tag, format, ...) \
|
||||
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_VERBOSE, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
|
||||
#define esph_log_v(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_VERBOSE, tag, format, __VA_ARGS__)
|
||||
|
||||
#define ESPHOME_LOG_HAS_VERBOSE
|
||||
#else
|
||||
@@ -97,10 +145,8 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
|
||||
#endif
|
||||
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
|
||||
#define esph_log_d(tag, format, ...) \
|
||||
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_DEBUG, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
|
||||
#define esph_log_config(tag, format, ...) \
|
||||
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_CONFIG, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
|
||||
#define esph_log_d(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_DEBUG, tag, format, __VA_ARGS__)
|
||||
#define esph_log_config(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_CONFIG, tag, format, __VA_ARGS__)
|
||||
|
||||
#define ESPHOME_LOG_HAS_DEBUG
|
||||
#define ESPHOME_LOG_HAS_CONFIG
|
||||
@@ -110,8 +156,7 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
|
||||
#endif
|
||||
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_INFO
|
||||
#define esph_log_i(tag, format, ...) \
|
||||
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_INFO, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
|
||||
#define esph_log_i(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_INFO, tag, format, __VA_ARGS__)
|
||||
|
||||
#define ESPHOME_LOG_HAS_INFO
|
||||
#else
|
||||
@@ -119,8 +164,7 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
|
||||
#endif
|
||||
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_WARN
|
||||
#define esph_log_w(tag, format, ...) \
|
||||
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_WARN, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
|
||||
#define esph_log_w(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_WARN, tag, format, __VA_ARGS__)
|
||||
|
||||
#define ESPHOME_LOG_HAS_WARN
|
||||
#else
|
||||
@@ -128,8 +172,7 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
|
||||
#endif
|
||||
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_ERROR
|
||||
#define esph_log_e(tag, format, ...) \
|
||||
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_ERROR, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
|
||||
#define esph_log_e(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_ERROR, tag, format, __VA_ARGS__)
|
||||
|
||||
#define ESPHOME_LOG_HAS_ERROR
|
||||
#else
|
||||
|
||||
@@ -8,11 +8,15 @@ from esphome.components.npm1300 import (
|
||||
CHARGER_SCHEMA,
|
||||
NPM1300_UNSET,
|
||||
OUTPUT_VOLTAGE,
|
||||
THERMISTOR_NONE,
|
||||
VBUS_CURRENT_LIMIT,
|
||||
_charger_config,
|
||||
_check_thermistor,
|
||||
_config,
|
||||
_output_config,
|
||||
_termination_voltage_code,
|
||||
_vbus_current_limit_code,
|
||||
thermistor_beta,
|
||||
)
|
||||
from esphome.const import CONF_MODE, CONF_VOLTAGE
|
||||
from esphome.cpp_generator import StructInitializer
|
||||
@@ -54,10 +58,35 @@ def test_termination_voltage_gap_rejected(voltage: str) -> None:
|
||||
CHARGER_SCHEMA({"charge_current": "100mA", "termination_voltage": voltage})
|
||||
|
||||
|
||||
def test_warm_termination_defaults_to_termination() -> None:
|
||||
def test_warm_termination_defaults_to_reset_value() -> None:
|
||||
fields = _charger({"charge_current": "100mA", "termination_voltage": "4.1V"})
|
||||
assert fields["termination_voltage"] == "6"
|
||||
assert fields["warm_termination_voltage"] == "6"
|
||||
assert fields["warm_termination_voltage"] == "2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config", "warns"),
|
||||
[
|
||||
({"termination_voltage": "4.2V"}, True),
|
||||
({"termination_voltage": "3.5V"}, False),
|
||||
({"termination_voltage": "3.6V"}, False),
|
||||
({}, False),
|
||||
({"termination_voltage": "4.2V", "warm_termination_voltage": "4.0V"}, False),
|
||||
],
|
||||
)
|
||||
def test_warm_termination_default_warning(
|
||||
config: ConfigType, warns: bool, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
CHARGER_SCHEMA(config)
|
||||
assert ("warm_termination_voltage" in caplog.text) is warns
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("termination", "code"), [("3.5V", "0"), ("3.55V", "1")])
|
||||
def test_warm_termination_default_not_above_termination(
|
||||
termination: str, code: str
|
||||
) -> None:
|
||||
fields = _charger({"termination_voltage": termination})
|
||||
assert fields["warm_termination_voltage"] == code
|
||||
|
||||
|
||||
def test_warm_termination_code() -> None:
|
||||
@@ -112,3 +141,48 @@ def test_vbus_current_limit_code(limit: str, code: int) -> None:
|
||||
def test_vbus_current_limit_rejected(limit: str) -> None:
|
||||
with pytest.raises(cv.Invalid):
|
||||
VBUS_CURRENT_LIMIT(limit)
|
||||
|
||||
|
||||
def test_charger_needs_thermistor() -> None:
|
||||
with pytest.raises(cv.Invalid, match="thermistor_resistance"):
|
||||
_check_thermistor({"charger": {}})
|
||||
config = {"charger": {}, "thermistor_resistance": THERMISTOR_NONE}
|
||||
assert _check_thermistor(config) is config
|
||||
|
||||
|
||||
@pytest.mark.parametrize("resistance", [None, THERMISTOR_NONE])
|
||||
def test_thermistor_beta_needs_resistance(resistance: str | None) -> None:
|
||||
config = {"thermistor_beta": 3380}
|
||||
if resistance is not None:
|
||||
config["thermistor_resistance"] = resistance
|
||||
with pytest.raises(cv.Invalid, match="thermistor_beta"):
|
||||
_check_thermistor(config)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("resistance", "beta"), [(10000.0, 3380), (47000.0, 4050), (100000.0, 4250)]
|
||||
)
|
||||
def test_thermistor_beta_default(resistance: float, beta: int) -> None:
|
||||
assert thermistor_beta({"thermistor_resistance": resistance}) == beta
|
||||
|
||||
|
||||
def test_thermistor_beta_configured() -> None:
|
||||
config = {"thermistor_resistance": 47000.0, "thermistor_beta": 3950}
|
||||
assert thermistor_beta(config) == 3950
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("resistance", "code", "beta"),
|
||||
[
|
||||
(None, str(NPM1300_UNSET), "0"),
|
||||
(THERMISTOR_NONE, "0", "0"),
|
||||
(100000.0, "3", "4250"),
|
||||
],
|
||||
)
|
||||
def test_config_thermistor(
|
||||
resistance: str | float | None, code: str, beta: str
|
||||
) -> None:
|
||||
config = {} if resistance is None else {"thermistor_resistance": resistance}
|
||||
fields = _fields(_config(config))
|
||||
assert fields["thermistor"] == code
|
||||
assert fields["thermistor_beta"] == beta
|
||||
@@ -0,0 +1,39 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp8266:
|
||||
board: esp01_1m
|
||||
|
||||
button:
|
||||
# Declared before the selects, so the action is generated before them
|
||||
- platform: template
|
||||
id: early
|
||||
name: Early
|
||||
on_press:
|
||||
- select.set:
|
||||
id: fan
|
||||
option: high
|
||||
- select.set:
|
||||
id: fan
|
||||
option: turbo
|
||||
- select.set:
|
||||
id: fan
|
||||
option: !lambda return "low";
|
||||
- select.set:
|
||||
id: fan_copy
|
||||
option: medium
|
||||
|
||||
select:
|
||||
- platform: template
|
||||
id: fan
|
||||
name: Fan
|
||||
optimistic: true
|
||||
options: [low, medium, high]
|
||||
on_value:
|
||||
- select.set:
|
||||
id: fan
|
||||
option: medium
|
||||
- platform: copy
|
||||
id: fan_copy
|
||||
name: Fan Copy
|
||||
source_id: fan
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
esphome:
|
||||
name: toshiba-test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
|
||||
remote_transmitter:
|
||||
pin: GPIO4
|
||||
carrier_duty_percent: 50%
|
||||
non_blocking: true
|
||||
|
||||
climate:
|
||||
- platform: toshiba
|
||||
id: ras
|
||||
name: RAS
|
||||
model: RAS-25J2KVSG-ND
|
||||
- platform: toshiba
|
||||
id: generic
|
||||
name: Generic
|
||||
|
||||
select:
|
||||
- platform: toshiba
|
||||
toshiba_id: ras
|
||||
power_selection:
|
||||
id: power
|
||||
name: Power selection
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
name: Set
|
||||
on_press:
|
||||
- select.set:
|
||||
id: power
|
||||
option: Silent 1
|
||||
@@ -0,0 +1,47 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
framework:
|
||||
type: esp-idf
|
||||
|
||||
spi:
|
||||
- id: spi_bus
|
||||
clk_pin: GPIO18
|
||||
mosi_pin: GPIO23
|
||||
|
||||
display:
|
||||
- platform: mipi_spi
|
||||
spi_id: spi_bus
|
||||
model: st7789v
|
||||
id: tft_display
|
||||
dimensions:
|
||||
width: 240
|
||||
height: 320
|
||||
cs_pin: GPIO22
|
||||
dc_pin: GPIO21
|
||||
auto_clear_enabled: false
|
||||
invert_colors: false
|
||||
update_interval: never
|
||||
|
||||
lvgl:
|
||||
displays: tft_display
|
||||
widgets:
|
||||
- dropdown:
|
||||
id: dropdown_widget
|
||||
options: [low, high]
|
||||
|
||||
select:
|
||||
- platform: lvgl
|
||||
id: lv_fan
|
||||
name: LVGL Fan
|
||||
widget: dropdown_widget
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
name: Set
|
||||
on_press:
|
||||
- select.set:
|
||||
id: lv_fan
|
||||
option: high
|
||||
@@ -0,0 +1,43 @@
|
||||
"""A constant select.set option of a select with a fixed option list becomes its index."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _call(select_id: str, statement: str) -> str:
|
||||
return f"auto apply_call = ::{select_id}->make_call();\n apply_call.{statement};"
|
||||
|
||||
|
||||
def test_select_set_constant_uses_index(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
main_cpp = generate_main(component_config_path("select_set.yaml"))
|
||||
|
||||
# Generated before the select, and from the select's own on_value
|
||||
assert _call("fan", "set_index(2)") in main_cpp
|
||||
assert _call("fan", "set_index(1)") in main_cpp
|
||||
assert 'set_option("high"' not in main_cpp
|
||||
# Not an option: the lookup by text still logs it at run time
|
||||
assert _call("fan", 'set_option("turbo", 5)') in main_cpp
|
||||
# A lambda's value is only known at run time
|
||||
assert _call("fan", 'set_option("low")') in main_cpp
|
||||
# A copy select gets its options at run time
|
||||
assert _call("fan_copy", 'set_option("medium", 6)') in main_cpp
|
||||
|
||||
|
||||
def test_select_set_lvgl_keeps_lookup_by_text(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
"""Lvgl dropdown options can be replaced at run time, so the index is not fixed."""
|
||||
main_cpp = generate_main(component_config_path("select_set_lvgl.yaml"))
|
||||
assert _call("lv_fan", 'set_option("high", 4)') in main_cpp
|
||||
|
||||
|
||||
def test_select_set_hub_select_uses_index(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
main_cpp = generate_main(component_config_path("select_set_hub.yaml"))
|
||||
assert _call("power", "set_index(3)") in main_cpp
|
||||
@@ -1,4 +1,5 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
@@ -271,6 +272,28 @@ TEST(BufAppendStrP, AppendsAndTruncates) {
|
||||
EXPECT_EQ(pos, 7u);
|
||||
}
|
||||
|
||||
// --- progmem_copy_str() ---
|
||||
|
||||
TEST(ProgmemCopyStr, CopiesUpToTheNullOrTheEndAtEveryAlignment) {
|
||||
static constexpr char TEXT[] = "0123456789abcdefghij";
|
||||
constexpr size_t len = sizeof(TEXT) - 1;
|
||||
for (size_t offset = 0; offset < 4; offset++) {
|
||||
// Reads whole aligned words, so the source is a zero padded copy
|
||||
alignas(4) char src[32] = {};
|
||||
memcpy(src + offset, TEXT, sizeof(TEXT));
|
||||
for (size_t room = 0; room <= len + 2; room++) {
|
||||
SCOPED_TRACE(::testing::Message() << "offset " << offset << " room " << room);
|
||||
char dst[32];
|
||||
memset(dst, '#', sizeof(dst));
|
||||
const char *const end = progmem_copy_str(dst, dst + room, src + offset);
|
||||
const size_t copied = std::min(room, len);
|
||||
EXPECT_EQ(end, dst + copied);
|
||||
EXPECT_EQ(memcmp(dst, TEXT, copied), 0);
|
||||
EXPECT_EQ(dst[copied], '#'); // No terminator written
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- base64 encode/decode ---
|
||||
|
||||
static const char BASE64_ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/components/logger/log_buffer.h"
|
||||
#include "esphome/components/logger/logger.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::logger::testing {
|
||||
|
||||
ESPHOME_LOG_TAG(PLAIN_TAG, "plain.test");
|
||||
|
||||
static void format_into(LogBuffer &buf, const char *format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
buf.format_body(format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
TEST(UnformattedLogTest, BodyMatchesFormattedBodyAtEverySize) {
|
||||
const std::string long_text(100, 'y');
|
||||
const char *texts[] = {"", "short", "ends with newlines\n\n", "\n", "a\nb", long_text.c_str()};
|
||||
constexpr uint16_t max_size = 48;
|
||||
for (uint16_t size = 1; size <= max_size; size++) {
|
||||
for (uint16_t start = 0; start <= size; start++) {
|
||||
for (const char *text : texts) {
|
||||
SCOPED_TRACE(::testing::Message() << "size " << size << " start " << start << " text '" << text << "'");
|
||||
char formatted[max_size], unformatted[max_size], flash[max_size];
|
||||
memset(formatted, '#', sizeof(formatted));
|
||||
memset(unformatted, '#', sizeof(unformatted));
|
||||
memset(flash, '#', sizeof(flash));
|
||||
LogBuffer a{formatted, size, start};
|
||||
LogBuffer b{unformatted, size, start};
|
||||
LogBuffer c{flash, size, start};
|
||||
format_into(a, "%s", text);
|
||||
b.write_unformatted_body(text, strlen(text));
|
||||
// The flash copy reads whole aligned words, so give it a zero padded copy
|
||||
alignas(4) char padded[128] = {};
|
||||
char *const in_flash = padded + (start & 3);
|
||||
memcpy(in_flash, text, strlen(text) + 1);
|
||||
c.write_unformatted_body_p(in_flash);
|
||||
ASSERT_EQ(a.pos, b.pos);
|
||||
ASSERT_EQ(a.pos, c.pos);
|
||||
// Up to and including the null terminator; vsnprintf() may leave bytes after it that nothing reads
|
||||
const size_t used = (a.pos < size) ? a.pos + 1 : size;
|
||||
ASSERT_EQ(memcmp(formatted, unformatted, used), 0);
|
||||
ASSERT_EQ(memcmp(formatted, flash, used), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PlainLine {
|
||||
uint8_t level;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
static void capture_plain(void *instance, uint8_t level, const char *tag, const char *message, size_t len) {
|
||||
static_cast<std::vector<PlainLine> *>(instance)->push_back({level, std::string(message, len)});
|
||||
}
|
||||
|
||||
class UnformattedLoggerTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
this->previous_ = global_logger;
|
||||
this->logger_.pre_setup();
|
||||
this->logger_.set_log_level(ESPHOME_LOG_LEVEL_DEBUG);
|
||||
this->logger_.add_log_callback(&this->lines_, capture_plain);
|
||||
}
|
||||
void TearDown() override { global_logger = this->previous_; }
|
||||
|
||||
Logger *previous_{nullptr};
|
||||
Logger logger_{0};
|
||||
std::vector<PlainLine> lines_;
|
||||
};
|
||||
|
||||
TEST_F(UnformattedLoggerTest, LineWithoutArgumentsMatchesFormattedLine) {
|
||||
esp_log_str_(ESPHOME_LOG_LEVEL_INFO, PLAIN_TAG, 7, "no arguments here\n");
|
||||
esp_log_printf_(ESPHOME_LOG_LEVEL_INFO, PLAIN_TAG, 7, "%s", "no arguments here\n");
|
||||
ASSERT_EQ(this->lines_.size(), 2u);
|
||||
EXPECT_EQ(this->lines_[0].level, ESPHOME_LOG_LEVEL_INFO);
|
||||
EXPECT_EQ(this->lines_[0].message, this->lines_[1].message);
|
||||
EXPECT_NE(this->lines_[0].message.find("[I][plain.test:007]: no arguments here\033[0m"), std::string::npos)
|
||||
<< this->lines_[0].message;
|
||||
}
|
||||
|
||||
TEST_F(UnformattedLoggerTest, PercentSignIsStillFormatted) {
|
||||
ESP_LOGW(PLAIN_TAG, "100%% done");
|
||||
ASSERT_EQ(this->lines_.size(), 1u);
|
||||
EXPECT_NE(this->lines_[0].message.find("]: 100% done"), std::string::npos) << this->lines_[0].message;
|
||||
}
|
||||
|
||||
TEST_F(UnformattedLoggerTest, FormatExpressionIsEvaluatedOnce) {
|
||||
const char *const messages[] = {"first", "second"};
|
||||
int index = 0;
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wformat-security"
|
||||
ESP_LOGW(PLAIN_TAG, messages[index++]);
|
||||
#pragma GCC diagnostic pop
|
||||
EXPECT_EQ(index, 1);
|
||||
ASSERT_EQ(this->lines_.size(), 1u);
|
||||
EXPECT_NE(this->lines_[0].message.find("]: first"), std::string::npos) << this->lines_[0].message;
|
||||
}
|
||||
|
||||
TEST_F(UnformattedLoggerTest, TemporaryFormatOutlivesTheCall) {
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wformat-security"
|
||||
ESP_LOGW(PLAIN_TAG, std::string(80, 'x').c_str());
|
||||
#pragma GCC diagnostic pop
|
||||
ASSERT_EQ(this->lines_.size(), 1u);
|
||||
EXPECT_NE(this->lines_[0].message.find("]: " + std::string(80, 'x')), std::string::npos) << this->lines_[0].message;
|
||||
}
|
||||
|
||||
TEST_F(UnformattedLoggerTest, LevelIsStillFiltered) {
|
||||
this->logger_.set_log_level(ESPHOME_LOG_LEVEL_WARN);
|
||||
ESP_LOGI(PLAIN_TAG, "hidden");
|
||||
ESP_LOGW(PLAIN_TAG, "shown");
|
||||
ASSERT_EQ(this->lines_.size(), 1u);
|
||||
EXPECT_EQ(this->lines_[0].level, ESPHOME_LOG_LEVEL_WARN);
|
||||
}
|
||||
|
||||
#ifdef USE_HOST
|
||||
TEST_F(UnformattedLoggerTest, WorkerThreadLineGoesThroughTaskBuffer) {
|
||||
this->logger_.create_pthread_key();
|
||||
std::thread worker([]() { esp_log_str_(ESPHOME_LOG_LEVEL_INFO, PLAIN_TAG, 7, "from a worker"); });
|
||||
worker.join();
|
||||
EXPECT_TRUE(this->lines_.empty());
|
||||
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
|
||||
this->logger_.loop();
|
||||
ASSERT_EQ(this->lines_.size(), 1u);
|
||||
EXPECT_NE(this->lines_[0].message.find("from a worker"), std::string::npos) << this->lines_[0].message;
|
||||
#endif
|
||||
}
|
||||
#endif // USE_HOST
|
||||
|
||||
} // namespace esphome::logger::testing
|
||||
@@ -1,29 +1,38 @@
|
||||
npm1300:
|
||||
id: pmic
|
||||
i2c_id: i2c_bus
|
||||
vbus_current_limit: 500mA
|
||||
thermistor_resistance: 10kOhm
|
||||
thermistor_beta: 3380
|
||||
charger:
|
||||
charge_current: 150mA
|
||||
termination_voltage: 4.2V
|
||||
warm_termination_voltage: 4.0V
|
||||
termination_current: 20%
|
||||
trickle_voltage: 2.5V
|
||||
discharge_current_limit: 1000mA
|
||||
recharge: true
|
||||
buck2:
|
||||
voltage: 3.3V
|
||||
ldo1:
|
||||
voltage: 3.3V
|
||||
mode: ldo
|
||||
enabled: true
|
||||
ldo2:
|
||||
mode: load_switch
|
||||
enabled: false
|
||||
- id: pmic
|
||||
i2c_id: i2c_bus
|
||||
vbus_current_limit: 500mA
|
||||
thermistor_resistance: 10kOhm
|
||||
thermistor_beta: 3380
|
||||
charger:
|
||||
charge_current: 150mA
|
||||
termination_voltage: 4.2V
|
||||
warm_termination_voltage: 4.0V
|
||||
termination_current: 20%
|
||||
trickle_voltage: 2.5V
|
||||
discharge_current_limit: 1000mA
|
||||
recharge: true
|
||||
buck2:
|
||||
voltage: 3.3V
|
||||
ldo1:
|
||||
voltage: 3.3V
|
||||
mode: ldo
|
||||
enabled: true
|
||||
ldo2:
|
||||
mode: load_switch
|
||||
enabled: false
|
||||
# A battery without a thermistor
|
||||
- id: pmic_no_ntc
|
||||
i2c_id: i2c_bus
|
||||
address: 0x6C
|
||||
thermistor_resistance: none
|
||||
charger:
|
||||
termination_voltage: 3.5V
|
||||
enabled: true
|
||||
|
||||
sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
battery_voltage:
|
||||
name: Battery Voltage
|
||||
battery_current:
|
||||
@@ -41,6 +50,7 @@ sensor:
|
||||
|
||||
binary_sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
vbus_present:
|
||||
name: VBUS Present
|
||||
vbus_current_limit_active:
|
||||
@@ -54,11 +64,13 @@ binary_sensor:
|
||||
|
||||
text_sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
charger_status:
|
||||
name: Charger Status
|
||||
|
||||
switch:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
charger:
|
||||
name: Charger
|
||||
buck1:
|
||||
@@ -67,6 +79,10 @@ switch:
|
||||
name: LDO1
|
||||
ldo2:
|
||||
name: LDO2
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic_no_ntc
|
||||
charger:
|
||||
name: Charger Without Thermistor
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
esphome:
|
||||
name: select-set-constant
|
||||
|
||||
host:
|
||||
api:
|
||||
logger:
|
||||
|
||||
globals:
|
||||
- id: next_option
|
||||
type: std::string
|
||||
initial_value: '"low"'
|
||||
|
||||
select:
|
||||
- platform: template
|
||||
name: "Fan"
|
||||
id: fan
|
||||
optimistic: true
|
||||
options: [low, medium, high]
|
||||
initial_option: low
|
||||
- platform: template
|
||||
name: "Picked"
|
||||
id: picked
|
||||
options: [low, medium, high]
|
||||
update_interval: never
|
||||
lambda: return id(next_option);
|
||||
set_action:
|
||||
- lambda: id(next_option) = std::string(x.c_str(), x.size());
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
name: "Set High"
|
||||
on_press:
|
||||
- select.set:
|
||||
id: fan
|
||||
option: high
|
||||
- platform: template
|
||||
name: "Set Medium"
|
||||
on_press:
|
||||
- select.set:
|
||||
id: fan
|
||||
option: medium
|
||||
- platform: template
|
||||
name: "Set Invalid"
|
||||
on_press:
|
||||
- select.set:
|
||||
id: fan
|
||||
option: turbo
|
||||
- platform: template
|
||||
name: "Pick High"
|
||||
on_press:
|
||||
- lambda: id(next_option) = "high";
|
||||
- component.update: picked
|
||||
- platform: template
|
||||
name: "Pick Invalid"
|
||||
on_press:
|
||||
- lambda: id(next_option) = "turbo";
|
||||
- component.update: picked
|
||||
- platform: template
|
||||
name: "Pick Medium"
|
||||
on_press:
|
||||
- lambda: id(next_option) = "medium";
|
||||
- component.update: picked
|
||||
@@ -0,0 +1,50 @@
|
||||
"""select.set with a constant option and a template select lambda, both set by index."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from aioesphomeapi import SelectInfo, SelectState
|
||||
import pytest
|
||||
|
||||
from .log_utils import LineWaiter
|
||||
from .state_utils import press_and_wait, require_entity, subscribe_after_initial_states
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
from .wait_utils import wait_or_fail
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_select_set_constant(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
waiter_log = LineWaiter()
|
||||
invalid_lambda = waiter_log.expect("'Picked': Invalid option turbo")
|
||||
# An unknown constant keeps the lookup by text and its warning, never a compiled index
|
||||
invalid_constant = waiter_log.expect("'Fan' - No option set")
|
||||
out_of_bounds = waiter_log.expect("out of bounds")
|
||||
async with (
|
||||
run_compiled(yaml_config, line_callback=waiter_log.callback),
|
||||
api_client_connected() as client,
|
||||
):
|
||||
entities, _ = await client.list_entities_services()
|
||||
fan = require_entity(entities, "fan", SelectInfo, exact=True)
|
||||
picked = require_entity(entities, "picked", SelectInfo, exact=True)
|
||||
sub = await subscribe_after_initial_states(client, entities)
|
||||
|
||||
async def press(button: str, key: int) -> str:
|
||||
state = await press_and_wait(
|
||||
client, entities, sub.waiter, button, SelectState, key=key
|
||||
)
|
||||
return state.state
|
||||
|
||||
assert await press("set_high", fan.key) == "high"
|
||||
# An option the select does not have changes nothing; the next press is the next state
|
||||
client.button_command(require_entity(entities, "set_invalid").key)
|
||||
assert await press("set_medium", fan.key) == "medium"
|
||||
await wait_or_fail(invalid_constant, 5.0, "invalid constant was not logged")
|
||||
assert not out_of_bounds.done()
|
||||
|
||||
assert await press("pick_high", picked.key) == "high"
|
||||
client.button_command(require_entity(entities, "pick_invalid").key)
|
||||
await wait_or_fail(invalid_lambda, 5.0, "invalid lambda option was not logged")
|
||||
assert await press("pick_medium", picked.key) == "medium"
|
||||
Reference in new issue
Block a user