Compare commits

..
Author SHA1 Message Date
J. Nick Koston 4e82d88efe [cse7766] Name the error-frame warning, test it, and use ESP_LOGVV_HEX
Restores the direct helpers.h include, gives the warning for an error frame its own
message, adds tests that error frames keep the warning until a valid frame and that an
out-of-range power cycle does not set it, and logs the raw frame with ESP_LOGVV_HEX.
2026-11-17 15:56:06 -06:00
J. Nick Koston a7e64f4e88 [cse7766] Append the fixed log prefix with buf_append_str 2026-11-17 15:52:48 -06:00
J. Nick Koston 2dcd6128c0 [cse7766] Keep the warning for frames that report an error and tidy the parser
A frame that reports a calibration or circuit error now keeps the component warning instead
of clearing it. The idle loop returns before the receive timeout check, the per-byte modulo
and the read-back of the stored byte are gone, the energy and current paths drop two float
divisions per frame, and the 24-bit wrapper gives way to encode_uint24 and the nibble
helpers. The tests build all seven sensors with dict-style packages.
2026-11-17 15:49:28 -06:00
Andriy Malyshenko f2aadcf0b5 [pcm1863] Add PCM1863 stereo audio ADC component (#22794) 2026-11-17 15:18:48 -06:00
NonaSuomy d4d53aa965 [vl6180x] Add VL6180X I2C sensor component (#22689) 2026-11-17 15:16:22 -06:00
dependabot[bot] 735ba9c98a Bump smp from 4.2.0 to 4.3.0 (#22853) 2026-11-17 14:06:09 -06:00
tomaszduda23andClaude 141789d240 [debug] Fix the debug component on nRF54L boards (#22839)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 17:32:52 +01:00
Bascht74 c4df1b163c [uart] Fix undefined shift in the RP2 hardware UART pin check (#22841) 2026-11-17 09:54:29 -06:00
David WoodhouseandJ. Nick Koston 773afa0bb1 [mqtt] Don't start the broker lookup before the network is up (#22843)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-17 09:53:52 -06:00
tomaszduda23andClaude 9bf2bbc241 [nrf52] Store preferences in ZMS on nRF54L (#22840)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 18:21:54 +03:00
Mattheinrichs 84dea8078b [cst816] Ignore idle 0xFF touch frames and invalid coordinates (#22435) 2026-11-17 08:58:24 -06:00
Jacopo Labardi dbf6af2fd7 [logger] Qualify the host clock function (#22838) 2026-11-17 08:50:19 -06:00
David Woodhouse bc6fb7082f [climate] Don't fail on a platform entry that only holds nested climates (#22844) 2026-11-17 08:49:00 -06:00
tomaszduda23andClaude cfa27cea58 [npm1300] Fix the thermistor resistance error message (#22835)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 17:40:04 +03:00
rwrozelleandClaude Opus 5.5 5c061f9e1e [espidf] Hide the ccache binary in the forced-on, no-binary test (#22842)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:29:34 -05:00
Jesse Hills 34b24d0cf5 Merge branch 'beta' into dev 2026-11-17 22:25:16 +13:00
Jesse Hills e27614fda3 Merge pull request #22833 from esphome/bump-2026.11.0b6
2026.11.0b6
2026-11-17 22:24:55 +13:00
J. Nick Koston 8426d04138 [api] Make the event order backpressure test wait until the pipe is full (#22112) 2026-11-17 21:09:01 +13:00
641c8bedc9 [npm1300] Use datasheet defaults, require the thermistor setting for charging, fix charger status (#22769)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-17 09:00:10 +01:00
Jesse Hills 4a39ca1b71 Fix 2026-11-17 20:54:40 +13:00
Jesse Hills 4a218fdbd8 Remove extra test 2026-11-17 20:47:40 +13:00
Jesse Hills d8fc1cd214 Bump version to 2026.11.0b6 2026-11-17 18:54:23 +13:00
J. Nick Koston 1e030b7371 [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 18:54:20 +13:00
J. Nick Koston 3b113f2c39 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 18:54:20 +13:00
J. Nick Koston 73468592a9 [remote_base] Fix the Haier and Mirage remote_receiver binary sensors failing to compile 2026-11-17 18:54:06 +13:00
Jonathan Swoboda a1b456150d [esp32][libretiny] Make delay() wait at least the requested time (#22822) 2026-11-17 18:53:11 +13:00
J. Nick Koston 865a883abb [remote_base] Fix the canalsatld binary sensor and trigger build 2026-11-17 18:53:11 +13:00
J. Nick Koston 357a6717c8 [core] Release only the lwIP core lock a LwIPLock took (#22683) 2026-11-17 18:53:11 +13:00
J. Nick Koston bcb434e05e [esp32_ble] Stop Bluedroid re-running a failed queued MTU or execute write request (#22670) 2026-11-17 18:53:11 +13:00
J. Nick Koston fb65fcc5f6 [esp32_power_management] Clamp the tick step after light sleep so it cannot trip vTaskStepTick (#22637) 2026-11-17 18:53:11 +13:00
J. Nick Koston b5e379a9d4 [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog at 57600 baud (#22641) 2026-11-17 18:53:11 +13:00
J. Nick Kostonandpre-commit-ci-lite[bot] 05286dfd5d [api] Send queued entity states before DisconnectRequest on shutdown (#22625)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-17 18:53:11 +13:00
J. Nick Koston 36184f09aa [zephyr] Count micros() in microseconds and busy-wait in delayMicroseconds() (#22612) 2026-11-17 18:53:11 +13:00
Adam Matthews 449933891e [wifi] Clear the error flag when the adapter restart is skipped (#22797) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda a5bfa6dac3 [esp32_ble] Apply the Bluedroid workarounds to the ESP-IDF 6.1 releases that need them (#22806) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda 5aaa5b0552 [esp32_ble] Replace Bluedroid's sscanf callers on ESP-IDF 6 too (#22805) 2026-11-17 18:53:11 +13:00
J. Nick Koston 9ab090a818 [i2c] Refuse RP2040 writes larger than the Wire buffer instead of leaving the bus stuck (#22791) 2026-11-17 18:53:10 +13:00
J. Nick Koston 02d0bb56a6 [cc1101] Refuse begin_tx in packet mode (#22636) 2026-11-16 22:21:59 -06:00
Mark Mayo e12784543d [logger] Copy log lines that have no arguments instead of formatting them (#22644) 2026-11-16 22:16:47 -06:00
J. Nick Koston bc3e9c88f4 [select] Set a fixed option by index and look up a template lambda's option once (#22655) 2026-11-16 22:48:05 -05:00
luar123andCopilot Autofix powered by AI 7e3c2ebc10 [zigbee] refactor ZigbeeAttribute (#22765)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-11-16 22:31:05 -05:00
J. Nick Koston 3f6c0f35fe [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 16:23:11 +13:00
J. Nick Koston 200bf69035 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 16:23:06 +13:00
huangkongshengandhuangkongsheng 0054041d6a [core] Reject sign-padded bind key pairs (#22660)
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
Co-authored-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-11-16 22:15:45 -05:00
141 changed files with 3744 additions and 1370 deletions

No files matched your search

+2
View File
@@ -489,6 +489,7 @@ esphome/components/pca9505/* @ajfriesen @ssieb
esphome/components/pca9554/* @bdraco @clydebarrow @hwstar
esphome/components/pcf85063/* @brogon
esphome/components/pcf8563/* @KoenBreeman
esphome/components/pcm1863/* @anabolyc
esphome/components/pcm5122/* @remcom
esphome/components/pd_pioneer_ir/* @martinsah
esphome/components/pi4ioe5v6408/* @jesserockz
@@ -735,6 +736,7 @@ esphome/components/veml7700/* @latonita
esphome/components/version/* @esphome/core
esphome/components/vevor_dtx/* @Bofr5555
esphome/components/vl53l1x/* @will-tm
esphome/components/vl6180x/* @NonaSuomy
esphome/components/vnc/* @MindFreeze
esphome/components/voice_assistant/* @jesserockz @kahrendt
esphome/components/wake_on_lan/* @clydebarrow @willwill2will54
-9
View File
@@ -17,15 +17,6 @@ cap1188_ns = cg.esphome_ns.namespace("cap1188")
CONF_CAP1188_ID = "cap1188_id"
CAP1188Component = cap1188_ns.class_("CAP1188Component", cg.Component, i2c.I2CDevice)
# Publishes the channel binary sensors from the touch status read on each loop
CHANNELS_PUBLISHER = cg.HubFunction(
"channels",
cg.void,
[(cg.uint8, "touched")],
define="USE_CAP1188_CHANNELS_PUBLISHER",
)
TOUCHED = CHANNELS_PUBLISHER.param("touched")
MULTI_CONF = True
CONFIG_SCHEMA = (
cv.Schema(
+6 -6
View File
@@ -1,15 +1,15 @@
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import binary_sensor
import esphome.config_validation as cv
from esphome.const import CONF_CHANNEL
from esphome.types import ConfigType
from . import CHANNELS_PUBLISHER, CONF_CAP1188_ID, TOUCHED, CAP1188Component, cap1188_ns
from . import CONF_CAP1188_ID, CAP1188Component, cap1188_ns
DEPENDENCIES = ["cap1188"]
CAP1188Channel = cap1188_ns.class_("CAP1188Channel", binary_sensor.BinarySensor)
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(CAP1188Channel).extend(
{
cv.GenerateID(CONF_CAP1188_ID): cv.use_id(CAP1188Component),
cv.Required(CONF_CHANNEL): cv.int_range(min=0, max=7),
@@ -20,6 +20,6 @@ CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
hub = await cg.get_variable(config[CONF_CAP1188_ID])
CHANNELS_PUBLISHER.add(
hub, cap1188_ns.publish_channel(parent_ref(var), TOUCHED, config[CONF_CHANNEL])
)
cg.add(var.set_channel(config[CONF_CHANNEL]))
cg.add(hub.register_channel(var))
+3 -4
View File
@@ -79,10 +79,9 @@ void CAP1188Component::loop() {
if (touched)
this->update_register(CAP1188_MAIN, CAP1188_MAIN_INT, 0);
#ifdef USE_CAP1188_CHANNELS_PUBLISHER
if (this->channels_publisher_ != nullptr)
this->channels_publisher_(touched);
#endif
for (auto *channel : this->channels_) {
channel->process(touched);
}
}
} // namespace esphome::cap1188
+13 -8
View File
@@ -4,7 +4,9 @@
#include "esphome/core/hal.h"
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/output/binary_output.h"
#include "esphome/core/helpers.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include <vector>
namespace esphome::cap1188 {
@@ -24,16 +26,18 @@ enum {
CAP1188_SENSITIVITY = 0x1f,
};
// A template on the sensor type keeps binary_sensor.h out of this hub header
template<typename T> inline void publish_channel(T *sensor, uint8_t touched, uint8_t channel) {
sensor->publish_state((touched >> channel) & 1);
}
class CAP1188Channel final : public binary_sensor::BinarySensor {
public:
void set_channel(uint8_t channel) { channel_ = channel; }
void process(uint8_t data) { this->publish_state(static_cast<bool>(data & (1 << this->channel_))); }
protected:
uint8_t channel_{0};
};
class CAP1188Component final : public Component, public i2c::I2CDevice {
public:
#ifdef USE_CAP1188_CHANNELS_PUBLISHER
HUB_PUBLISHER(channels, uint8_t)
#endif
void register_channel(CAP1188Channel *channel) { this->channels_.push_back(channel); }
void set_touch_threshold(uint8_t touch_threshold) { this->touch_threshold_ = touch_threshold; };
void set_allow_multiple_touches(bool allow_multiple_touches) {
this->allow_multiple_touches_ = allow_multiple_touches ? 0x41 : 0x80;
@@ -46,6 +50,7 @@ class CAP1188Component final : public Component, public i2c::I2CDevice {
protected:
void finish_setup_();
std::vector<CAP1188Channel *> channels_{};
uint8_t touch_threshold_{0x20};
uint8_t allow_multiple_touches_{0x80};
+4 -10
View File
@@ -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
+83 -93
View File
@@ -10,121 +10,119 @@ ESPHOME_LOG_TAG(TAG, "cse7766");
// The chip only sends the time since the last pulse once a cycle is longer than 1 s (in us)
static constexpr uint32_t MIN_HELD_POWER_CYCLE = 1000000;
// A gap this long between bytes starts a new frame
static constexpr uint32_t RX_RESET_TIMEOUT_MS = 500;
// Datasheet: the smallest current the chip measures
static constexpr float MIN_CURRENT_A = 0.05f;
// Energy per CF pulse is the power coefficient in uW·s; this turns pulses × coefficient into Wh
static constexpr float PULSE_COEFF_TO_WH = 1.0f / (1000000.0f * 3600.0f);
static constexpr uint8_t HEADER_OK = 0x55;
static constexpr uint8_t HEADER_NOT_CALIBRATED = 0xAA;
static constexpr uint8_t HEADER_VOLTAGE_CYCLE_EXCEEDS = 1 << 3;
static constexpr uint8_t HEADER_CURRENT_CYCLE_EXCEEDS = 1 << 2;
static constexpr uint8_t HEADER_POWER_CYCLE_EXCEEDS = 1 << 1;
static constexpr uint8_t HEADER_COEFF_STORAGE_ABNORMAL = 1 << 0;
static constexpr uint8_t HEADER2 = 0x5A;
// Adjustment byte: which registers hold a new measurement
static constexpr uint8_t ADJ_POWER = 0x10;
static constexpr uint8_t ADJ_CURRENT = 0x20;
static constexpr uint8_t ADJ_VOLTAGE = 0x40;
void CSE7766Component::loop() {
const uint32_t now = App.get_loop_component_start_time();
if (now - this->last_transmission_ >= 500) {
// last transmission too long ago. Reset RX index.
this->raw_data_index_ = 0;
}
// Early return prevents updating last_transmission_ when no data is available.
size_t avail = this->available();
if (avail == 0) {
if (avail == 0)
return;
}
const uint32_t now = App.get_loop_component_start_time();
if (now - this->last_transmission_ >= RX_RESET_TIMEOUT_MS)
this->raw_data_index_ = 0;
this->last_transmission_ = now;
// Read all available bytes in batches to reduce UART call overhead.
// At 4800 baud (~480 bytes/sec) with ~122 Hz loop rate, typically ~4 bytes per call.
this->read_available<CSE7766_RAW_DATA_SIZE>(
// At 4800 baud (~480 bytes/sec) with ~122 Hz loop rate, typically ~4 bytes per call
this->read_available<RAW_DATA_SIZE>(
[this](uint8_t byte) {
this->raw_data_[this->raw_data_index_] = byte;
if (!this->check_byte_()) {
const uint8_t index = this->raw_data_index_;
this->raw_data_[index] = byte;
if (!this->check_byte_(index, byte)) {
this->raw_data_index_ = 0;
this->status_set_warning();
return;
}
if (this->raw_data_index_ == CSE7766_RAW_DATA_SIZE - 1) {
this->parse_data_();
this->status_clear_warning();
if (index == RAW_DATA_SIZE - 1) {
this->raw_data_index_ = 0;
this->status_comm_result(this->parse_data_(), LOG_STR("Chip reports an error"));
return;
}
this->raw_data_index_ = (this->raw_data_index_ + 1) % CSE7766_RAW_DATA_SIZE;
this->raw_data_index_ = index + 1;
},
avail);
}
bool CSE7766Component::check_byte_() {
uint8_t index = this->raw_data_index_;
uint8_t byte = this->raw_data_[index];
if (index == 0) {
return (byte == 0x55) || ((byte & 0xF0) == 0xF0) || (byte == 0xAA);
}
bool CSE7766Component::check_byte_(uint8_t index, uint8_t byte) const {
if (index == 0)
return byte == HEADER_OK || high_nibble(byte) == 0xF || byte == HEADER_NOT_CALIBRATED;
if (index == 1) {
if (byte != 0x5A) {
ESP_LOGV(TAG, "Invalid Header 2 Start: 0x%02X!", byte);
return false;
}
return true;
if (byte == HEADER2)
return true;
ESP_LOGV(TAG, "Invalid Header 2 Start: 0x%02X!", byte);
return false;
}
if (index == CSE7766_RAW_DATA_SIZE - 1) {
const uint8_t checksum = sum_bytes(this->raw_data_ + 2, CSE7766_RAW_DATA_SIZE - 3);
if (checksum != this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]) {
ESP_LOGW(TAG, "Invalid checksum from CSE7766: 0x%02X != 0x%02X", checksum,
this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]);
if (index == RAW_DATA_SIZE - 1) {
const uint8_t checksum = sum_bytes(this->raw_data_ + 2, RAW_DATA_SIZE - 3);
if (checksum != byte) {
ESP_LOGW(TAG, "Invalid checksum from CSE7766: 0x%02X != 0x%02X", checksum, byte);
return false;
}
return true;
}
return true;
}
void CSE7766Component::parse_data_() {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
{
char hex_buf[format_hex_pretty_size(CSE7766_RAW_DATA_SIZE)];
ESP_LOGVV(TAG, "Raw data: %s", format_hex_pretty_to(hex_buf, this->raw_data_, sizeof(this->raw_data_)));
}
#endif
// Parse header
uint8_t header1 = this->raw_data_[0];
bool CSE7766Component::parse_data_() {
ESP_LOGVV_HEX(TAG, this->raw_data_, RAW_DATA_SIZE, RAW_DATA_SIZE, "Raw data: %s");
if (header1 == 0xAA) {
const uint8_t header1 = this->raw_data_[0];
if (header1 == HEADER_NOT_CALIBRATED) {
ESP_LOGE(TAG, "CSE7766 not calibrated!");
return;
return false;
}
bool power_cycle_exceeds_range = false;
if ((header1 & 0xF0) == 0xF0) {
if (header1 & 0xD) {
// 0xFx: the low nibble holds error bits
if (high_nibble(header1) == 0xF) {
if (header1 & (HEADER_VOLTAGE_CYCLE_EXCEEDS | HEADER_CURRENT_CYCLE_EXCEEDS | HEADER_COEFF_STORAGE_ABNORMAL)) {
ESP_LOGE(TAG, "CSE7766 reports abnormal external circuit or chip damage: (0x%02X)", header1);
if (header1 & (1 << 3)) {
if (header1 & HEADER_VOLTAGE_CYCLE_EXCEEDS) {
ESP_LOGE(TAG, " Voltage cycle exceeds range.");
}
if (header1 & (1 << 2)) {
if (header1 & HEADER_CURRENT_CYCLE_EXCEEDS) {
ESP_LOGE(TAG, " Current cycle exceeds range.");
}
if (header1 & (1 << 0)) {
if (header1 & HEADER_COEFF_STORAGE_ABNORMAL) {
ESP_LOGE(TAG, " Coefficient storage area is abnormal.");
}
// Datasheet: voltage or current cycle exceeding range means invalid values
return;
return false;
}
power_cycle_exceeds_range = header1 & (1 << 1);
power_cycle_exceeds_range = header1 & HEADER_POWER_CYCLE_EXCEEDS;
}
// Parse data frame
uint32_t voltage_coeff = this->get_24_bit_uint_(2);
uint32_t voltage_cycle = this->get_24_bit_uint_(5);
uint32_t current_coeff = this->get_24_bit_uint_(8);
uint32_t current_cycle = this->get_24_bit_uint_(11);
uint32_t power_coeff = this->get_24_bit_uint_(14);
uint32_t power_cycle = this->get_24_bit_uint_(17);
uint8_t adj = this->raw_data_[20];
uint16_t cf_pulses = (this->raw_data_[21] << 8) + this->raw_data_[22];
const uint8_t *d = this->raw_data_;
uint32_t voltage_coeff = encode_uint24(d[2], d[3], d[4]);
uint32_t voltage_cycle = encode_uint24(d[5], d[6], d[7]);
uint32_t current_coeff = encode_uint24(d[8], d[9], d[10]);
uint32_t current_cycle = encode_uint24(d[11], d[12], d[13]);
uint32_t power_coeff = encode_uint24(d[14], d[15], d[16]);
uint32_t power_cycle = encode_uint24(d[17], d[18], d[19]);
uint8_t adj = d[20];
uint16_t cf_pulses = encode_uint16(d[21], d[22]);
bool have_power = adj & 0x10;
bool have_current = adj & 0x20;
bool have_voltage = adj & 0x40;
bool have_power = adj & ADJ_POWER;
bool have_current = adj & ADJ_CURRENT;
bool have_voltage = adj & ADJ_VOLTAGE;
float voltage = 0.0f;
if (have_voltage) {
@@ -132,7 +130,7 @@ void CSE7766Component::parse_data_() {
PUBLISH_STATE(this->voltage_sensor_, voltage);
}
float energy = 0.0;
float energy = 0.0f;
if (this->energy_sensor_ != nullptr) {
if (this->cf_pulses_last_ == 0 && !this->energy_sensor_->has_state()) {
this->cf_pulses_last_ = cf_pulses;
@@ -140,7 +138,7 @@ void CSE7766Component::parse_data_() {
uint16_t cf_diff = cf_pulses - this->cf_pulses_last_;
this->cf_pulses_total_ += cf_diff;
this->cf_pulses_last_ = cf_pulses;
energy = this->cf_pulses_total_ * float(power_coeff) / 1000000.0f / 3600.0f;
energy = this->cf_pulses_total_ * float(power_coeff) * PULSE_COEFF_TO_WH;
this->energy_sensor_->publish_state(energy);
}
@@ -149,37 +147,30 @@ void CSE7766Component::parse_data_() {
// Datasheet: power cycle exceeding range means active power is 0
have_power = true;
this->last_power_cycle_ = 0;
PUBLISH_STATE(this->power_sensor_, 0.0f);
} else if (have_power) {
power = power_coeff / float(power_cycle);
this->last_power_cycle_ = power_cycle;
PUBLISH_STATE(this->power_sensor_, power);
} else if (this->last_power_cycle_ > MIN_HELD_POWER_CYCLE && power_cycle <= 2 * this->last_power_cycle_) {
// No new measurement in this frame. With cycles over 1 s the register holds the last
// cycle or the time elapsed since the last pulse. While that time is within twice the
// last cycle, the next pulse is not overdue, so the last measurement still applies.
// Shorter cycles never get here in normal operation and keep the previous behaviour.
// Shorter cycles never get here in normal operation.
have_power = true;
power = power_coeff / float(this->last_power_cycle_);
PUBLISH_STATE(this->power_sensor_, power);
} else {
// The next pulse is overdue: the load has dropped, report 0 W. A load that drops to less
// than half also reads 0 W here until its first new pulse arrives.
this->last_power_cycle_ = 0;
PUBLISH_STATE(this->power_sensor_, 0.0f);
}
PUBLISH_STATE(this->power_sensor_, power);
// Without a power measurement the current is likely below the 50 mA the chip can measure;
// P > I_min·U is P/U > I_min without the division
const bool current_measurable = have_power && voltage > 1.0f && power > MIN_CURRENT_A * voltage;
float current = 0.0f;
float calculated_current = 0.0f;
if (have_current) {
// Assumption: if we don't have power measurement, then current is likely below 50mA
if (have_power && voltage > 1.0f) {
calculated_current = power / voltage;
}
// Datasheet: minimum measured current is 50mA
if (calculated_current > 0.05f) {
if (current_measurable)
current = current_coeff / float(current_cycle);
}
PUBLISH_STATE(this->current_sensor_, current);
}
@@ -196,7 +187,7 @@ void CSE7766Component::parse_data_() {
this->reactive_power_sensor_->publish_state(std::sqrt(q_squared));
}
}
if (this->power_factor_sensor_ != nullptr && (have_power || power_cycle_exceeds_range)) {
if (this->power_factor_sensor_ != nullptr && have_power) {
float pf = NAN;
if (apparent_power > 0) {
pf = power / apparent_power;
@@ -209,8 +200,7 @@ void CSE7766Component::parse_data_() {
} else if (apparent_power == 0 && power == 0) {
// No load, report ideal power factor
pf = 1.0f;
} else if (current == 0 && calculated_current <= 0.05f) {
// Datasheet: minimum measured current is 50mA
} else if (current == 0 && !current_measurable) {
ESP_LOGV(TAG, "Can't calculate power factor (current below minimum for CSE7766)");
} else {
ESP_LOGW(TAG, "Can't calculate power factor from P = %.4f W, S = %.4f VA", power, apparent_power);
@@ -221,10 +211,9 @@ void CSE7766Component::parse_data_() {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
{
// Buffer: 7 + 15 + 33 + 15 + 25 = 95 chars max + null, rounded to 128 for safety margin.
// Float sizes with %.4f can be up to 11 chars for large values (e.g., 999999.9999).
char buf[128];
size_t pos = buf_append_printf(buf, sizeof(buf), 0, "Parsed:");
const float calculated_current = have_power && voltage > 1.0f ? power / voltage : 0.0f;
char buf[128]; // five fields at %.4f fit with room to spare
size_t pos = buf_append_str(buf, sizeof(buf), 0, "Parsed:");
if (have_voltage) {
pos = buf_append_printf(buf, sizeof(buf), pos, " V=%.4fV", voltage);
}
@@ -241,6 +230,7 @@ void CSE7766Component::parse_data_() {
ESP_LOGVV(TAG, "%s", buf);
}
#endif
return true;
}
void CSE7766Component::dump_config() {
+6 -9
View File
@@ -7,8 +7,6 @@
namespace esphome::cse7766 {
static constexpr size_t CSE7766_RAW_DATA_SIZE = 24;
class CSE7766Component final : public Component, public uart::UARTDevice {
SUB_SENSOR(voltage)
SUB_SENSOR(current)
@@ -23,14 +21,13 @@ class CSE7766Component final : public Component, public uart::UARTDevice {
void dump_config() override;
protected:
bool check_byte_();
void parse_data_();
uint32_t get_24_bit_uint_(uint8_t start_index) const {
return encode_uint24(this->raw_data_[start_index], this->raw_data_[start_index + 1],
this->raw_data_[start_index + 2]);
}
static constexpr size_t RAW_DATA_SIZE = 24;
uint8_t raw_data_[CSE7766_RAW_DATA_SIZE];
bool check_byte_(uint8_t index, uint8_t byte) const;
/// Returns false when the frame reports an error instead of measurements.
bool parse_data_();
uint8_t raw_data_[RAW_DATA_SIZE];
uint8_t raw_data_index_{0};
uint16_t cf_pulses_last_{0};
uint32_t last_transmission_{0};
@@ -63,13 +63,25 @@ void CST816Touchscreen::update_touches() {
uint8_t data[13];
if (!this->status_comm_result(this->read_bytes(REG_STATUS, data, sizeof data)))
return;
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 3;
// The low nibble is the touch count. CST816/CST820 are single-touch;
// CST826/CST836 can report two points, but this driver only reads the first
// point. Some CST8xx controllers report an all-0xFF frame when idle or after
// disabling auto-sleep: the count lands above two and the coordinates are
// the 0xFFF sentinel, so both guards below reject it.
uint8_t num_of_touches = low_nibble(data[REG_TOUCH_NUM]);
if (num_of_touches == 0) {
return;
}
if (num_of_touches > 2) {
return;
}
uint16_t x = encode_uint16(low_nibble(data[REG_XPOS_HIGH]), data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(low_nibble(data[REG_YPOS_HIGH]), data[REG_YPOS_LOW]);
if (x == 0x0FFF || y == 0x0FFF) {
return;
}
ESP_LOGV(TAG, "Read touch %d/%d", x, y);
this->add_raw_touch_position_(0, x, y);
}
+2
View File
@@ -94,5 +94,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_platform(
PlatformFramework.LN882X_ARDUINO,
},
"debug_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf52.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf54l.cpp": {PlatformFramework.NRF52_ZEPHYR},
}
)
+380
View File
@@ -0,0 +1,380 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && !defined(NRF54L_SERIES)
#include <cinttypes>
#include <cstdint>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <hal/nrf_power.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")),
mac_pretty, NRF_FICR->INFO.PART, NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF,
NRF_FICR->INFO.VARIANT >> 8 & 0xFF, NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE),
NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? LOG_STR_LITERAL("") : LOG_STR_LITERAL("not ")));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
+113
View File
@@ -0,0 +1,113 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && defined(NRF54L_SERIES)
#include <cinttypes>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
// UARTE, SPIM, SPIS, TWIM and TWIS with the same number share one instance
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " UARTE00: %-3s| UARTE20: %-3s| UARTE21: %-3s| UARTE22: %-3s| UARTE30: %-3s", //
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE00), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE20),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE21), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE22),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE30));
ESP_LOGV(TAG, " SPIM00: %-3s| SPIM20: %-3s| SPIM21: %-3s| SPIM22: %-3s| SPIM30: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM00), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM20),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM21), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM22),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM30));
ESP_LOGV(TAG, " SPIS00: %-3s| SPIS20: %-3s| SPIS21: %-3s| SPIS22: %-3s| SPIS30: %-3s", //
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS00), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS20),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS21), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS22),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS30));
ESP_LOGV(TAG, " TWIM20: %-3s| TWIM21: %-3s| TWIM22: %-3s| TWIM30: %-3s", //
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM20), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM21),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM22), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM30));
ESP_LOGV(TAG, " TWIS20: %-3s| TWIS21: %-3s| TWIS22: %-3s| TWIS30: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS20), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS21),
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS22), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS30));
ESP_LOGV(TAG, " PWM20: %-3s| PWM21: %-3s| PWM22: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM20), NRF_PERIPH_ENABLED(PWM, NRF_PWM21), NRF_PERIPH_ENABLED(PWM, NRF_PWM22),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " PDM20: %-3s| PDM21: %-3s| QDEC20: %-3s| QDEC21: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM20), NRF_PERIPH_ENABLED(PDM, NRF_PDM21), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC20),
NRF_PERIPH_ENABLED(QDEC, NRF_QDEC21));
ESP_LOGV(TAG, " COMP: %-3s| LPCOMP: %-3s| AAR00: %-3s| CCM00: %-3s", //
NRF_PERIPH_ENABLED(COMP, NRF_COMP), NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP),
NRF_PERIPH_ENABLED(AAR, NRF_AAR00), NRF_PERIPH_ENABLED(CCM, NRF_CCM00));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF registers are MMIO at fixed addresses
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main regulator
const char *reg_type = (NRF_REGULATORS->VREGMAIN.DCDCEN & REGULATORS_VREGMAIN_DCDCEN_VAL_Msk) ==
(REGULATORS_VREGMAIN_DCDCEN_VAL_Enabled << REGULATORS_VREGMAIN_DCDCEN_VAL_Pos)
? "DC/DC"
: "LDO";
ESP_LOGD(TAG, "Main regulator: %s", reg_type);
pos = buf_append_str(buf, size, pos, "|Main regulator: ");
pos = buf_append_str(buf, size, pos, reg_type);
// Power-fail comparator, the threshold goes from 1.7V up in 0.1V steps
const uint32_t pofcon = NRF_REGULATORS->POFCON;
if ((pofcon & REGULATORS_POFCON_POF_Msk) == (REGULATORS_POFCON_POF_Enabled << REGULATORS_POFCON_POF_Pos)) {
const uint32_t decivolts = 17 + ((pofcon & REGULATORS_POFCON_THRESHOLD_Msk) >> REGULATORS_POFCON_THRESHOLD_Pos);
ESP_LOGD(TAG, "Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10, decivolts % 10);
pos = buf_append_printf(buf, size, pos, "|Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10,
decivolts % 10);
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
const uint32_t variant = NRF_FICR->INFO.VARIANT;
ESP_LOGD(TAG,
"nRF debug info:\n"
" Device id: 0x%08" PRIx32 "%08" PRIx32 "\n"
" Encryption root: 0x%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "%08" PRIx32 ", Identity Root: 0x%08" PRIx32
"%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "\n"
" Device address type: %s, address: %s\n"
" Part code: 0x%" PRIx32 ", version: %c%c%c%c, package: 0x%" PRIx32 "\n"
" RAM: %" PRIu32 "kB, RRAM: %" PRIu32 "kB",
NRF_FICR->INFO.DEVICEID[1], NRF_FICR->INFO.DEVICEID[0], NRF_FICR->ER[0], NRF_FICR->ER[1], NRF_FICR->ER[2],
NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2], NRF_FICR->IR[3],
(NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")), mac_pretty,
NRF_FICR->INFO.PART, static_cast<char>(variant >> 24 & 0xFF), static_cast<char>(variant >> 16 & 0xFF),
static_cast<char>(variant >> 8 & 0xFF), static_cast<char>(variant & 0xFF), NRF_FICR->INFO.PACKAGE,
NRF_FICR->INFO.RAM, NRF_FICR->INFO.RRAM);
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#endif
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
-364
View File
@@ -2,55 +2,14 @@
#ifdef USE_ZEPHYR
#include <cinttypes>
#include <climits>
#include "esphome/core/alloc_helpers.h"
#include "esphome/core/log.h"
#include <esphome/components/zephyr/reset_reason.h>
#include <zephyr/drivers/hwinfo.h>
#include <zephyr/kernel.h>
#include <hal/nrf_power.h>
#include <cstdint>
#include <zephyr/storage/flash_map.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
const char *DebugComponent::get_reset_reason_(std::span<char, RESET_REASON_BUFFER_SIZE> buffer) {
const char *buf = zephyr::get_reset_reason(buffer);
@@ -96,329 +55,6 @@ void DebugComponent::log_partition_info_() {
flash_area_foreach(fa_cb, nullptr);
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? "Random" : "Public"), mac_pretty, NRF_FICR->INFO.PART,
NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF, NRF_FICR->INFO.VARIANT >> 8 & 0xFF,
NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE), NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? "" : "not "));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// The Python side enables the statistics only for a verbose logger
#ifdef CONFIG_SCHED_THREAD_USAGE_ANALYSIS
static void log_thread_usage(const struct k_thread *thread, void *user_data) {
+3 -1
View File
@@ -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]:
+1 -1
View File
@@ -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])
+22 -1
View File
@@ -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--;
}
+53 -5
View File
@@ -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,
+22 -1
View File
@@ -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,
+1 -1
View File
@@ -9,7 +9,7 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
char buffer[TIMESTAMP_LEN + ESPHOME_LOGGER_TX_BUFFER_SIZE + HEADROOM];
time_t rawtime;
time(&rawtime);
::time(&rawtime);
struct tm timeinfo;
localtime_r(&rawtime, &timeinfo); // Thread-safe version
size_t pos = strftime(buffer, TIMESTAMP_LEN + 1, "[%H:%M:%S]", &timeinfo);
+1 -1
View File
@@ -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))
+32 -23
View File
@@ -56,7 +56,8 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
static constexpr uint32_t ATTACH_POLL_MS = 4000;
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
static constexpr uint32_t BAUD_PREF_HASH = 76007670UL;
static constexpr uint32_t PIN_PREF_HASH = 76007671UL;
@@ -670,22 +671,28 @@ ModemState ModemComponent::handle_state_enabling_() {
this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
// esp_modem keeps the last line before OK as the reply, which can be the echoed command
if (this->dce_->set_echo(false) != command_result::OK) {
ESP_LOGW(TAG, "Failed to disable command echo");
}
int radio_state = 0;
if (this->dce_->get_radio_state(radio_state) != command_result::OK) {
ESP_LOGW(TAG, "Failed to read the radio state; skipping the radio off step");
} else if (radio_state != RADIO_STATE_RF_OFF) {
// Drops a session left by a warm reboot; unlike CFUN=0, which powers the SIM down on the SIM7600, CFUN=4
// keeps the SIM readable for the PIN and the APN. A modem that refuses is used as it is.
if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK) {
ESP_LOGW(TAG, "Failed to turn the radio off");
}
// The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
// session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
esp_modem::PdpContext pdp(this->apn_);
this->apn_pending_ = this->dce_->set_radio_state(RADIO_STATE_MINIMUM) != command_result::OK ||
this->dce_->set_pdp_context(pdp) != command_result::OK;
if (this->apn_pending_) {
ESP_LOGW(TAG, "Failed to set the APN with the SIM powered down; setting it after the SIM check");
}
// CFUN=4 powers the SIM up with the radio still off; a modem without it needs CFUN=1 to bring the SIM back
if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK &&
this->dce_->set_radio_state(1) != command_result::OK) {
ESP_LOGW(TAG, "Failed to power the SIM up");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
this->modem_synced_ = true; // it answers, so a disable() still tears it down
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
if (this->baud_rate_ != 0 && this->baud_rate_ != this->current_baud_rate_) {
ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
@@ -752,7 +759,7 @@ ModemState ModemComponent::handle_state_connecting_() {
return ModemState::MODEM_STATE_ENABLING;
}
}
// ENABLING left the radio at CFUN=4, where the SIM answers but the modem cannot attach yet
// ENABLING powered the SIM up (CFUN=4, or CFUN=1 on a modem without it), so the SIM answers
switch (this->prepare_sim_()) {
case SimResult::SIM_RESULT_READY:
break;
@@ -769,13 +776,14 @@ ModemState ModemComponent::handle_state_connecting_() {
this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
return ModemState::MODEM_STATE_DISCONNECTING;
}
// The APN has to be in the PDP context before the radio comes on and the modem attaches; esp_modem only
// sends it when PPP starts
esp_modem::PdpContext pdp(this->apn_);
if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
ESP_LOGW(TAG, "Failed to set the APN");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
if (this->apn_pending_) {
esp_modem::PdpContext pdp(this->apn_);
if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
ESP_LOGW(TAG, "Failed to set the APN");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
this->apn_pending_ = false;
}
if (this->dce_->set_radio_state(1) != command_result::OK) {
ESP_LOGW(TAG, "Failed to turn the radio on");
@@ -862,11 +870,12 @@ ModemState ModemComponent::handle_state_disconnecting_() {
ESP_LOGW(TAG, "Failed to leave data mode");
this->set_teardown_fault_();
}
// Turn the radio off; waiting for the lost IP event could take up to 2 min. A reconnect keeps the SIM powered
// so it is not unlocked again; only disable() powers it down.
const bool reconnect = this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED;
if (this->dce_->set_radio_state(reconnect ? RADIO_STATE_RF_OFF : 0) == command_result::OK) {
// Turn the radio off; waiting for the lost IP event could take up to 2 min. The SIM is powered down as well, as
// ENABLING does anyway on a reconnect.
if (this->dce_->set_radio_state(RADIO_STATE_MINIMUM) == command_result::OK) {
ESP_LOGI(TAG, "Radio off");
} else if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) == command_result::OK) {
ESP_LOGW(TAG, "Radio off, but the SIM could not be powered down");
} else {
ESP_LOGW(TAG, "Radio off failed");
this->set_teardown_fault_();
@@ -299,6 +299,7 @@ class ModemComponent : public Component {
bool connect_timeout_armed_{false};
bool modem_synced_{false}; // a modem that never answered has nothing to tear down
bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
#ifdef USE_MODEM_SEND_AT
char at_command_[AT_COMMAND_SIZE];
#endif
+2 -12
View File
@@ -28,18 +28,6 @@ DOMAIN = "mpr121"
mpr121_ns = cg.esphome_ns.namespace("mpr121")
MPR121Component = mpr121_ns.class_("MPR121Component", cg.Component, i2c.I2CDevice)
# Both run only for channels: the thresholds once at setup, the states on each loop
THRESHOLDS_PUBLISHER = cg.HubFunction(
"thresholds", cg.void, [], define="USE_MPR121_CHANNEL_PUBLISHERS"
)
CHANNELS_PUBLISHER = cg.HubFunction(
"channels",
cg.void,
[(cg.uint16, "touched")],
define="USE_MPR121_CHANNEL_PUBLISHERS",
)
TOUCHED = CHANNELS_PUBLISHER.param("touched")
MPR121GPIOPin = mpr121_ns.class_(
"MPR121GPIOPin", cg.GPIOPin, cg.Parented.template(MPR121Component)
)
@@ -90,6 +78,8 @@ async def to_code(config: ConfigType) -> None:
var = cg.new_Pvariable(config[CONF_ID])
cg.add(var.set_touch_debounce(config[CONF_TOUCH_DEBOUNCE]))
cg.add(var.set_release_debounce(config[CONF_RELEASE_DEBOUNCE]))
cg.add(var.set_touch_threshold(config[CONF_TOUCH_THRESHOLD]))
cg.add(var.set_release_threshold(config[CONF_RELEASE_THRESHOLD]))
cg.add(var.set_max_touch_channel(config[CONF_MAX_TOUCH_CHANNEL]))
await cg.register_component(var, config)
await i2c.register_i2c_device(var, config)
@@ -1,25 +1,21 @@
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import binary_sensor
import esphome.config_validation as cv
from esphome.const import CONF_CHANNEL
import esphome.final_validate as fv
from esphome.types import ConfigType
from .. import (
CHANNELS_PUBLISHER,
CONF_MPR121_ID,
CONF_RELEASE_THRESHOLD,
CONF_TOUCH_THRESHOLD,
THRESHOLDS_PUBLISHER,
TOUCHED,
MPR121Component,
mpr121_ns,
)
DEPENDENCIES = ["mpr121"]
MPR121BinarySensor = mpr121_ns.class_("MPR121BinarySensor", binary_sensor.BinarySensor)
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(MPR121BinarySensor).extend(
{
cv.GenerateID(CONF_MPR121_ID): cv.use_id(MPR121Component),
cv.Required(CONF_CHANNEL): cv.int_range(min=0, max=11),
@@ -29,26 +25,13 @@ CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
)
def _final_validate(config: ConfigType) -> None:
"""Take the thresholds the channel does not set from its hub."""
hub = fv.get_declaring_config(config[CONF_MPR121_ID])
for key in (CONF_TOUCH_THRESHOLD, CONF_RELEASE_THRESHOLD):
config.setdefault(key, hub[key])
FINAL_VALIDATE_SCHEMA = _final_validate
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
hub = await cg.get_variable(config[CONF_MPR121_ID])
channel = config[CONF_CHANNEL]
THRESHOLDS_PUBLISHER.add(
hub,
hub.write_thresholds(
channel, config[CONF_TOUCH_THRESHOLD], config[CONF_RELEASE_THRESHOLD]
),
)
CHANNELS_PUBLISHER.add(
hub, mpr121_ns.publish_channel(parent_ref(var), TOUCHED, channel)
)
cg.add(var.set_channel(config[CONF_CHANNEL]))
await cg.register_parented(var, hub)
cg.add_optional(var.set_touch_threshold, config.get(CONF_TOUCH_THRESHOLD))
cg.add_optional(var.set_release_threshold, config.get(CONF_RELEASE_THRESHOLD))
cg.add(hub.register_channel(var))
@@ -0,0 +1,18 @@
#include "mpr121_binary_sensor.h"
namespace esphome::mpr121 {
void MPR121BinarySensor::setup() {
uint8_t touch_threshold = this->touch_threshold_.value_or(this->parent_->get_touch_threshold());
this->parent_->write_byte(MPR121_TOUCHTH_0 + 2 * this->channel_, touch_threshold);
uint8_t release_threshold = this->release_threshold_.value_or(this->parent_->get_release_threshold());
this->parent_->write_byte(MPR121_RELEASETH_0 + 2 * this->channel_, release_threshold);
}
void MPR121BinarySensor::process(uint16_t data) {
bool new_state = data & (1 << this->channel_);
this->publish_state(new_state);
}
} // namespace esphome::mpr121
@@ -0,0 +1,26 @@
#pragma once
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "../mpr121.h"
namespace esphome::mpr121 {
class MPR121BinarySensor final : public binary_sensor::BinarySensor,
public MPR121Channel,
public Parented<MPR121Component> {
public:
void set_channel(uint8_t channel) { this->channel_ = channel; }
void set_touch_threshold(uint8_t touch_threshold) { this->touch_threshold_ = touch_threshold; };
void set_release_threshold(uint8_t release_threshold) { this->release_threshold_ = release_threshold; };
void setup() override;
void process(uint16_t data) override;
protected:
uint8_t channel_{0};
optional<uint8_t> touch_threshold_{};
optional<uint8_t> release_threshold_{};
};
} // namespace esphome::mpr121
+9 -18
View File
@@ -17,10 +17,10 @@ void MPR121Component::setup() {
this->set_timeout(100, [this]() {
if (!this->setup_check(this->write_byte(MPR121_ECR, 0x0)))
return;
#ifdef USE_MPR121_CHANNEL_PUBLISHERS
if (this->thresholds_publisher_ != nullptr)
this->thresholds_publisher_();
#endif
// set touch sensitivity for all 12 channels
for (auto *channel : this->channels_) {
channel->setup();
}
this->write_byte(MPR121_MHDR, 0x01);
this->write_byte(MPR121_NHDR, 0x01);
this->write_byte(MPR121_NCLR, 0x0E);
@@ -65,25 +65,16 @@ void MPR121Component::set_release_debounce(uint8_t debounce) {
this->debounce_ |= mask;
};
#ifdef USE_MPR121_CHANNEL_PUBLISHERS
void MPR121Component::write_thresholds(uint8_t channel, uint8_t touch, uint8_t release) {
this->write_byte(MPR121_TOUCHTH_0 + 2 * channel, touch);
this->write_byte(MPR121_RELEASETH_0 + 2 * channel, release);
}
#endif
void MPR121Component::dump_config() {
ESP_LOGCONFIG(TAG, "MPR121:");
LOG_I2C_DEVICE(this);
}
void MPR121Component::loop() {
#ifdef USE_MPR121_CHANNEL_PUBLISHERS
if (this->channels_publisher_ != nullptr) {
uint16_t val = 0;
this->read_byte_16_le(MPR121_TOUCHSTATUS_L, &val);
this->channels_publisher_(val);
}
#endif
uint16_t val = 0;
this->read_byte_16_le(MPR121_TOUCHSTATUS_L, &val);
for (auto *channel : this->channels_)
channel->process(val);
this->read_byte(MPR121_GPIODATA, &this->gpio_input_);
}
+15 -10
View File
@@ -3,11 +3,12 @@
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/components/gpio_expander/expander_gpio_pin.h"
#include "esphome/components/i2c/i2c.h"
#include <vector>
namespace esphome::mpr121 {
enum {
@@ -51,20 +52,21 @@ enum {
MPR121_SOFTRESET = 0x80,
};
// A template on the sensor type keeps binary_sensor.h out of this hub header
template<typename T> inline void publish_channel(T *sensor, uint16_t touched, uint8_t channel) {
sensor->publish_state((touched >> channel) & 1);
}
class MPR121Channel {
public:
virtual void setup() = 0;
virtual void process(uint16_t data) = 0;
};
class MPR121Component final : public Component, public i2c::I2CDevice {
public:
#ifdef USE_MPR121_CHANNEL_PUBLISHERS
HUB_PUBLISHER(thresholds)
HUB_PUBLISHER(channels, uint16_t)
void write_thresholds(uint8_t channel, uint8_t touch, uint8_t release);
#endif
void register_channel(MPR121Channel *channel) { this->channels_.push_back(channel); }
void set_touch_debounce(uint8_t debounce);
void set_release_debounce(uint8_t debounce);
void set_touch_threshold(uint8_t touch_threshold) { this->touch_threshold_ = touch_threshold; };
void set_release_threshold(uint8_t release_threshold) { this->release_threshold_ = release_threshold; };
uint8_t get_touch_threshold() const { return this->touch_threshold_; };
uint8_t get_release_threshold() const { return this->release_threshold_; };
void setup() override;
void dump_config() override;
float get_setup_priority() const override { return setup_priority::IO; }
@@ -78,7 +80,10 @@ class MPR121Component final : public Component, public i2c::I2CDevice {
void pin_mode(uint8_t pin, gpio::Flags flags);
protected:
std::vector<MPR121Channel *> channels_{};
uint8_t debounce_{0};
uint8_t touch_threshold_{};
uint8_t release_threshold_{};
uint8_t max_touch_channel_{3};
bool flush_gpio_();
+12 -3
View File
@@ -323,12 +323,17 @@ bool MQTTClientComponent::can_proceed() {
}
void MQTTClientComponent::start_dnslookup_() {
this->status_set_warning();
// No lookup can start before the network is up: there is no DNS server to ask yet.
// Stay disconnected, and loop() calls this again.
if (!network::is_connected())
return;
for (auto &subscription : this->subscriptions_) {
subscription.subscribed = false;
subscription.resubscribe_timeout = 0;
}
this->status_set_warning();
this->dns_resolve_error_ = false;
this->dns_resolved_ = false;
ip_addr_t addr;
@@ -358,9 +363,13 @@ void MQTTClientComponent::start_dnslookup_() {
}
default:
case ERR_ARG: {
// error
// The lookup never started, so there is no answer to wait for; loop() tries again in 5 seconds
ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
break;
this->state_ = MQTT_CLIENT_DISCONNECTED;
this->disconnect_reason_ = MQTTClientDisconnectReason::DNS_RESOLVE_ERROR;
this->on_disconnect_.call(MQTTClientDisconnectReason::DNS_RESOLVE_ERROR);
this->connect_begin_ = millis();
return;
}
}
+117 -39
View File
@@ -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
@@ -101,14 +105,13 @@ def _one_of_units(
validator: Callable[[object], float],
allowed: list[int],
unit: str,
scale: float = 1000,
) -> Callable[[object], float]:
"""Validate a quantity with `validator` and accept only the listed values, given in units * `scale`."""
"""Validate a quantity with `validator` and accept only the listed values, given in thousandths of `unit`."""
def validate(value: object) -> float:
value = validator(value)
if round(value * scale) not in allowed:
options = ", ".join(f"{v / scale:g}{unit}" for v in allowed)
if _millis(value) not in allowed:
options = ", ".join(f"{v / 1000:g}{unit}" for v in allowed)
raise cv.Invalid(f"Must be one of {options}")
return value
@@ -135,6 +138,23 @@ def _stepped(
return validate
def _thermistor_resistance(value: object) -> float | str:
if isinstance(value, str) and value.lower() == THERMISTOR_NONE:
return THERMISTOR_NONE
value = cv.resistance(value)
if round(value) not in (kilohms * 1000 for kilohms in THERMISTOR_RESISTANCES):
options = ", ".join(f"{kilohms}kOhm" for kilohms in THERMISTOR_RESISTANCES)
raise cv.Invalid(f"Must be one of {options} or {THERMISTOR_NONE}")
return 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 +170,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 +232,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 +271,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 +287,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 +296,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 +323,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 +337,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),
)
+51 -34
View File
@@ -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
+13 -5
View File
@@ -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_;
+6 -5
View File
@@ -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)
+12 -4
View File
@@ -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],
)
+2 -6
View File
@@ -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,
+10 -3
View File
@@ -13,6 +13,7 @@ from esphome.build_helpers.ccache import resolve_ccache_path
import esphome.codegen as cg
from esphome.components import network
from esphome.components.zephyr import (
PreferenceStorage,
Section,
add_extra_script,
copy_files as zephyr_copy_files,
@@ -106,6 +107,7 @@ from .const import (
VARIANT_NRF52832,
VARIANT_NRF52840,
VARIANT_REGULATOR,
VARIANTS_NRF54L,
VARIANTS_WITHOUT_USB,
)
from .framework import (
@@ -536,6 +538,11 @@ def _final_validate(config):
FINAL_VALIDATE_SCHEMA = _final_validate
def _preferences_storage(variant: str) -> PreferenceStorage:
"""The storage for preferences: ZMS on the RRAM of the nRF54L, NVS on flash."""
return "ZMS" if variant in VARIANTS_NRF54L else "NVS"
@coroutine_with_priority(CoroPriority.PLATFORM)
async def to_code(config: ConfigType) -> None:
"""Convert the configuration to code."""
@@ -544,7 +551,7 @@ async def to_code(config: ConfigType) -> None:
variant = get_nrf52_variant()
cg.add_define("ESPHOME_VARIANT", variant)
cg.add_build_flag(f"-DUSE_NRF52_VARIANT_{variant}")
if variant in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if variant in VARIANTS_NRF54L:
# The entropy driver runs on the CRACEN crypto unit, which needs Nordic's PSA crypto
include_west_project("mbedtls")
include_west_project("oberon-psa-crypto")
@@ -612,11 +619,11 @@ async def to_code(config: ConfigType) -> None:
if config[KEY_BOOTLOADER] in ADAFRUIT_BOOTLOADERS:
cg.add_define("USE_BOOTLOADER_ADAFRUIT")
zephyr_setup_preferences()
zephyr_setup_preferences(_preferences_storage(variant))
zephyr_to_code(config)
# The nRF54L has RRAM (cpuapp_rram) and no flash0 node
if CORE.testing_mode and variant not in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if CORE.testing_mode and variant not in VARIANTS_NRF54L:
zephyr_add_overlay(
f"""
&flash0 {{
+2 -1
View File
@@ -17,6 +17,7 @@ from .const import (
VARIANT_NRF54LM20,
VARIANT_NRF52832,
VARIANT_NRF52840,
VARIANTS_NRF54L,
)
from .framework import (
check_and_install,
@@ -145,7 +146,7 @@ def upload_using_cmsis_dap(unique_id: str | None = None) -> None:
pyocd = [str(paths["python_executable"]), "-m", "pyocd"]
probe = ["-t", target] + (["-u", unique_id] if unique_id else [])
cmd = [*pyocd, "flash", "--no-wait", *probe, "-e", "sector"]
if variant in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
if variant in VARIANTS_NRF54L:
cmd += ["--script", str(_NRF54L_WATCHDOG_SCRIPT)]
cmd += [str(image) for image in images]
if not run_command_ok(cmd, env=env, stream_output=True):
+2
View File
@@ -41,6 +41,8 @@ VARIANT_I2C = {
VARIANT_NRF54LM20: VariantI2C("i2c21", (1, 3)),
}
VARIANTS_WITHOUT_USB = frozenset({VARIANT_NRF52832, VARIANT_NRF54L15})
# The nRF54L family: RRAM instead of flash, the CRACEN crypto unit and the wdt31 watchdog
VARIANTS_NRF54L = frozenset({VARIANT_NRF54L15, VARIANT_NRF54LM20})
# Devicetree label of the main regulator, reg1 on the others
VARIANT_REGULATOR = {VARIANT_NRF52832: "reg"}
VARIANT_FLASH_SIZE = {VARIANT_NRF52832: 0x80000, VARIANT_NRF52840: 0x100000}
+3
View File
@@ -0,0 +1,3 @@
"""PCM1863 audio ADC component."""
DOMAIN = "pcm1863"
+62
View File
@@ -0,0 +1,62 @@
import esphome.codegen as cg
from esphome.components import i2c
from esphome.components.audio_adc import AudioAdc
import esphome.config_validation as cv
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_INPUT, CONF_MIC_GAIN
from esphome.types import ConfigType
CODEOWNERS = ["@anabolyc"]
DEPENDENCIES = ["i2c"]
CONF_PCM1863_ID = "pcm1863_id"
# The PGA covers -12 dB to +40 dB in 0.5 dB steps
PCM1863_MIC_GAIN_MIN = -12.0
PCM1863_MIC_GAIN_MAX = 40.0
pcm1863_ns = cg.esphome_ns.namespace("pcm1863")
PCM1863 = pcm1863_ns.class_("PCM1863", AudioAdc, cg.Component, i2c.I2CDevice)
pcm1863_input = pcm1863_ns.enum("PCM1863Input")
# The declaration order is the select option order and the C++ enum value of each input
PCM1863_INPUT_ENUM = pcm1863_input.options(
"NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2", prefix="PCM1863_INPUT_"
)
pcm1863_bits_per_sample = pcm1863_ns.enum("PCM1863BitsPerSample")
PCM1863_BITS_PER_SAMPLE_ENUM = {
16: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_16,
20: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_20,
24: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_24,
32: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_32,
}
_validate_bits = cv.float_with_unit("bits", "bit")
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(PCM1863),
cv.Optional(CONF_BITS_PER_SAMPLE, default="24bit"): cv.All(
_validate_bits, cv.enum(PCM1863_BITS_PER_SAMPLE_ENUM)
),
cv.Optional(CONF_INPUT, default="VIN1"): cv.enum(
PCM1863_INPUT_ENUM, upper=True
),
cv.Optional(CONF_MIC_GAIN, default="0db"): cv.All(
cv.decibel,
cv.float_range(min=PCM1863_MIC_GAIN_MIN, max=PCM1863_MIC_GAIN_MAX),
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(i2c.i2c_device_schema(0x4A))
)
async def to_code(config: ConfigType) -> None:
var = await i2c.new_i2c_component(config)
cg.add(var.set_bits_per_sample(config[CONF_BITS_PER_SAMPLE]))
cg.add(var.set_input(config[CONF_INPUT]))
cg.add(var.set_mic_gain(config[CONF_MIC_GAIN]))
+96
View File
@@ -0,0 +1,96 @@
#include "pcm1863.h"
#include "pcm1863_const.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#include <cmath>
namespace esphome::pcm1863 {
ESPHOME_LOG_TAG(TAG, "pcm1863");
// Indexed by PCM1863BitsPerSample
PROGMEM_STRING_TABLE(BitsPerSampleStrings, "32", "24", "20", "16");
PROGMEM_STRING_TABLE(InputStrings, "NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2");
// Page select and power up: bits 2:0 clear is the run state, and the reserved bits 7:3
// must be written as 0b01110 or the analog section stops
static constexpr i2c::I2CRegValue PCM1863_INIT[] PROGMEM = {
{PCM1863_REG_PAGE, PCM1863_PAGE_0},
{PCM1863_REG_POWER_CTRL, PCM1863_PWR_CTRL_RSV},
};
void PCM1863::dump_config() {
ESP_LOGCONFIG(TAG,
"PCM1863 audio ADC:\n"
" Bits Per Sample: %s\n"
" Input: %s\n"
" Mic Gain: %.1f dB",
LOG_STR_ARG(BitsPerSampleStrings::get_log_str(this->bits_per_sample_, 0)),
LOG_STR_ARG(InputStrings::get_log_str(this->input_, 0)), this->mic_gain_);
#ifdef USE_PCM1863_SELECT
LOG_SELECT(" ", "Input", this->input_select_);
#endif
}
void PCM1863::setup() {
// Writing PCM1863_RESET to the page selector restores every register to its default
if (!this->setup_check(this->write_byte(PCM1863_REG_PAGE, PCM1863_RESET)))
return;
delay(2);
// The datasheet does not say which page the reset leaves selected, so select page 0 first
if (!this->setup_check(this->write_registers(PCM1863_INIT)))
return;
if (!this->setup_check(this->configure_i2s_format_() && this->configure_input_() && this->configure_mic_gain_()))
return;
this->setup_complete_ = true;
#ifdef USE_PCM1863_SELECT
// Show the input the ADC booted with, so the select does not start out blank
PUBLISH_STATE(this->input_select_, this->input_);
#endif
}
bool PCM1863::set_mic_gain(float mic_gain) {
// Nothing reaches the chip after a failed setup, so report the change as not applied
if (this->is_failed())
return false;
this->mic_gain_ = clamp<float>(mic_gain, PCM1863_MIC_GAIN_MIN, PCM1863_MIC_GAIN_MAX);
if (!this->setup_complete_)
return true;
return this->status_comm_result(this->configure_mic_gain_());
}
bool PCM1863::configure_mic_gain_() {
// The PGA gain registers take a two's complement value in 0.5 dB steps
const auto reg_val = static_cast<uint8_t>(lroundf(this->mic_gain_ / PCM1863_MIC_GAIN_STEP));
return this->write_byte(PCM1863_REG_PGA_VAL_CH1_L, reg_val) && this->write_byte(PCM1863_REG_PGA_VAL_CH1_R, reg_val);
}
bool PCM1863::set_input(PCM1863Input input) {
if (this->is_failed())
return false;
this->input_ = input;
if (!this->setup_complete_)
return true;
return this->status_comm_result(this->configure_input_());
}
bool PCM1863::configure_input_() {
// Bit 6 of both input select registers is reserved and must always be written as 1
const uint8_t mux = this->input_ == PCM1863_INPUT_NONE ? 0 : 1 << (this->input_ - 1);
const uint8_t reg_val = PCM1863_INPUT_SEL_RSV | mux;
return this->write_byte(PCM1863_REG_ADC1_INPUT_SEL_L, reg_val) &&
this->write_byte(PCM1863_REG_ADC1_INPUT_SEL_R, reg_val);
}
bool PCM1863::configure_i2s_format_() {
const uint8_t wlen = this->bits_per_sample_;
const uint8_t reg_val =
(wlen << PCM1863_PCM_CFG_RX_WLEN_SHIFT) | (wlen << PCM1863_PCM_CFG_TX_WLEN_SHIFT) | PCM1863_PCM_CFG_FMT_I2S;
return this->write_byte(PCM1863_REG_PCM_CFG, reg_val);
}
} // namespace esphome::pcm1863
+64
View File
@@ -0,0 +1,64 @@
#pragma once
#include "esphome/components/audio_adc/audio_adc.h"
#include "esphome/components/i2c/i2c.h"
#include "esphome/core/component.h"
#ifdef USE_PCM1863_SELECT
#include "esphome/components/select/select.h"
#endif
#include "pcm1863_const.h"
namespace esphome::pcm1863 {
// Positions of the select options, in the order audio_adc.py declares them
enum PCM1863Input : uint8_t {
PCM1863_INPUT_NONE,
PCM1863_INPUT_VIN1,
PCM1863_INPUT_VIN2,
PCM1863_INPUT_VIN3,
PCM1863_INPUT_VIN4,
PCM1863_INPUT_DIFF_1,
PCM1863_INPUT_DIFF_2,
};
// The word length code of PCM1863_REG_PCM_CFG
enum PCM1863BitsPerSample : uint8_t {
PCM1863_BITS_PER_SAMPLE_32,
PCM1863_BITS_PER_SAMPLE_24,
PCM1863_BITS_PER_SAMPLE_20,
PCM1863_BITS_PER_SAMPLE_16,
};
/// Texas Instruments PCM1863 stereo audio ADC for line and microphone input.
/// The register map and reset sequence follow the datasheet (SLAS831D) and the Linux
/// kernel driver in sound/soc/codecs/pcm186x.c.
class PCM1863 final : public audio_adc::AudioAdc, public Component, public i2c::I2CDevice {
#ifdef USE_PCM1863_SELECT
SUB_SELECT(input)
#endif
public:
void setup() override;
void dump_config() override;
void set_bits_per_sample(PCM1863BitsPerSample bits_per_sample) { this->bits_per_sample_ = bits_per_sample; }
/// Selects the analog input. Takes effect immediately once setup has run.
bool set_input(PCM1863Input input);
bool set_mic_gain(float mic_gain) override;
float mic_gain() override { return this->mic_gain_; }
protected:
bool configure_i2s_format_();
bool configure_mic_gain_();
bool configure_input_();
float mic_gain_{0};
bool setup_complete_{false};
PCM1863BitsPerSample bits_per_sample_{PCM1863_BITS_PER_SAMPLE_24};
PCM1863Input input_{PCM1863_INPUT_VIN1};
};
} // namespace esphome::pcm1863
@@ -0,0 +1,50 @@
#pragma once
#include <cstdint>
namespace esphome::pcm1863 {
// PCM1863 page 0 register addresses.
// Names and layout follow the Texas Instruments PCM186x family register map (SLAS831D).
static constexpr uint8_t PCM1863_REG_PAGE = 0x00; /* Page selector; writing 0xFE triggers a full reset */
static constexpr uint8_t PCM1863_REG_PGA_VAL_CH1_L = 0x01; /* ADC1 left PGA gain, 0.5 dB/LSB, two's complement */
static constexpr uint8_t PCM1863_REG_PGA_VAL_CH1_R = 0x02; /* ADC1 right PGA gain, 0.5 dB/LSB, two's complement */
static constexpr uint8_t PCM1863_REG_ADC1_INPUT_SEL_L = 0x06;
static constexpr uint8_t PCM1863_REG_ADC1_INPUT_SEL_R = 0x07;
static constexpr uint8_t PCM1863_REG_PCM_CFG = 0x0B; /* Word length and serial audio format */
static constexpr uint8_t PCM1863_REG_POWER_CTRL = 0x70; /* Power down, sleep and standby */
// PCM1863_REG_PAGE: the register holds the page number, and the two documented
// commands are selecting a page and resetting every register
static constexpr uint8_t PCM1863_PAGE_0 = 0x00;
static constexpr uint8_t PCM1863_RESET = 0xFE;
// PCM1863_REG_PCM_CFG: receive word length in bits 7:6, transmit word length in bits 3:2,
// serial audio format in bits 1:0. Bit 5 is reserved and bit 4 only applies to TDM; both
// are zero at reset and are written as zero here.
static constexpr uint8_t PCM1863_PCM_CFG_RX_WLEN_SHIFT = 6;
static constexpr uint8_t PCM1863_PCM_CFG_TX_WLEN_SHIFT = 2;
static constexpr uint8_t PCM1863_PCM_CFG_FMT_I2S = 0x00;
// PCM1863_REG_ADC1_INPUT_SEL_L / _R
// Bit 7 selects signal polarity, bit 6 is reserved and must always be written as 1,
// and bits 5:0 pick the analog input. See the PCM186x datasheet, "MUX, MIX, and
// Polarity Input Selection".
static constexpr uint8_t PCM1863_INPUT_SEL_RSV = 0x40; // bit 6, always write 1
// Bits 5:0 select one input: none, VIN1 to VIN4 single-ended (0x01 to 0x08), then the
// differential pairs VIN1/VIN2 (0x10) and VIN4/VIN3 (0x20)
// PCM1863_REG_POWER_CTRL
// Bits 2:0 are power down, sleep and standby; all three are clear in the run state.
// Bits 7:3 are reserved and the datasheet requires them to always be written as 0b01110,
// which is also their reset value. Writing them as zero stops the analog section.
static constexpr uint8_t PCM1863_PWR_CTRL_RSV = 0x70;
// The PGA gain registers hold a two's complement value in 0.5 dB steps,
// from -24 (-12 dB) to +80 (+40 dB)
static constexpr float PCM1863_MIC_GAIN_MIN = -12.0f;
static constexpr float PCM1863_MIC_GAIN_MAX = 40.0f;
static constexpr float PCM1863_MIC_GAIN_STEP = 0.5f;
} // namespace esphome::pcm1863
+32
View File
@@ -0,0 +1,32 @@
import esphome.codegen as cg
from esphome.components import select
import esphome.config_validation as cv
from esphome.const import ENTITY_CATEGORY_CONFIG, ICON_CHIP
from esphome.types import ConfigType
from .audio_adc import CONF_PCM1863_ID, PCM1863, PCM1863_INPUT_ENUM
PCM1863_INPUT_OPTIONS = list(PCM1863_INPUT_ENUM)
CONFIG_SCHEMA = select.select_schema(
select.ApplySelect,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_CHIP,
).extend(
{
cv.GenerateID(CONF_PCM1863_ID): cv.use_id(PCM1863),
}
)
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_PCM1863_SELECT")
hub = await cg.get_variable(config[CONF_PCM1863_ID])
# The ADC publishes the new option only once the I2C write went through
await select.sub_selects(config, parent=hub).create(
config,
hub.set_input_select,
options=PCM1863_INPUT_OPTIONS,
apply="set_input(static_cast<pcm1863::PCM1863Input>(index))",
publish="on_success",
)
-9
View File
@@ -13,15 +13,6 @@ MULTI_CONF = True
rdm6300_ns = cg.esphome_ns.namespace("rdm6300")
RDM6300Component = rdm6300_ns.class_("RDM6300Component", cg.Component, uart.UARTDevice)
# Publishes the card binary sensors for each tag read; returns whether one matched
CARDS_PUBLISHER = cg.HubFunction(
"cards",
cg.bool_,
[(cg.uint32, "tag")],
define="USE_RDM6300_CARDS_PUBLISHER",
)
TAG = CARDS_PUBLISHER.param("tag")
_AUTOMATION_LISTS = (
automation.AutomationList(CONF_ON_TAG, "RDM6300_ON_TAG_COUNT", [(cg.uint32, "x")]),
)
+8 -8
View File
@@ -1,19 +1,19 @@
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import binary_sensor, rdm6300
import esphome.config_validation as cv
from esphome.const import CONF_UID
from esphome.types import ConfigType
from . import CARDS_PUBLISHER, TAG, rdm6300_ns
from . import rdm6300_ns
DEPENDENCIES = ["rdm6300"]
CONF_RDM6300_ID = "rdm6300_id"
RDM6300BinarySensor = rdm6300_ns.class_(
"RDM6300BinarySensor", binary_sensor.BinarySensor
)
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(
binary_sensor.BinarySensorInitiallyOff
).extend(
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(RDM6300BinarySensor).extend(
{
cv.GenerateID(CONF_RDM6300_ID): cv.use_id(rdm6300.RDM6300Component),
cv.Required(CONF_UID): cv.uint32_t,
@@ -23,7 +23,7 @@ CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
hub = await cg.get_variable(config[CONF_RDM6300_ID])
CARDS_PUBLISHER.add(
hub, rdm6300_ns.publish_card(parent_ref(var), TAG, config[CONF_UID])
)
cg.add(hub.register_card(var))
cg.add(var.set_id(config[CONF_UID]))
+5 -4
View File
@@ -48,10 +48,11 @@ void rdm6300::RDM6300Component::loop() {
this->status_clear_warning();
const uint32_t result = encode_uint32(this->buffer_[1], this->buffer_[2], this->buffer_[3], this->buffer_[4]);
bool report = result != last_id_;
#ifdef USE_RDM6300_CARDS_PUBLISHER
if (this->cards_publisher_ != nullptr && this->cards_publisher_(result))
report = false;
#endif
for (auto *card : this->cards_) {
if (card->process(result)) {
report = false;
}
}
#ifdef RDM6300_ON_TAG_COUNT
this->tag_automations_.trigger(result);
#endif
+23 -14
View File
@@ -2,31 +2,21 @@
#include "esphome/core/component.h"
#include "esphome/core/automation.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "esphome/components/uart/uart.h"
#include <cinttypes>
#include <vector>
namespace esphome::rdm6300 {
// A template on the sensor type keeps binary_sensor.h out of this hub header
template<typename T> inline bool publish_card(T *sensor, uint32_t tag, uint32_t card) {
if (tag != card)
return false;
sensor->publish_state(true);
yield();
sensor->publish_state(false);
return true;
}
class RDM6300BinarySensor;
class RDM6300Component final : public Component, public uart::UARTDevice {
public:
void loop() override;
#ifdef USE_RDM6300_CARDS_PUBLISHER
HUB_PUBLISHER_RETURNING(bool, cards, uint32_t)
#endif
void register_card(RDM6300BinarySensor *obj) { this->cards_.push_back(obj); }
#ifdef RDM6300_ON_TAG_COUNT
void add_on_tag_automation(Automation<uint32_t> *automation) { this->tag_automations_.add(automation); }
#endif
@@ -34,10 +24,29 @@ class RDM6300Component final : public Component, public uart::UARTDevice {
protected:
int8_t read_state_{-1};
uint8_t buffer_[6]{};
std::vector<RDM6300BinarySensor *> cards_;
#ifdef RDM6300_ON_TAG_COUNT
AutomationList<RDM6300_ON_TAG_COUNT, uint32_t> tag_automations_;
#endif
uint32_t last_id_{0};
};
class RDM6300BinarySensor final : public binary_sensor::BinarySensorInitiallyOff {
public:
void set_id(uint32_t id) { id_ = id; }
bool process(uint32_t id) {
if (this->id_ == id) {
this->publish_state(true);
yield();
this->publish_state(false);
return true;
}
return false;
}
protected:
uint32_t id_;
};
} // namespace esphome::rdm6300
+73 -11
View File
@@ -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",
-9
View File
@@ -30,15 +30,6 @@ DOMAIN = "sx1509"
MULTI_CONF = True
sx1509_ns = cg.esphome_ns.namespace("sx1509")
# Publishes the keypad binary sensors from the key data read on each scan
KEYPAD_PUBLISHER = cg.HubFunction(
"keypad",
cg.void,
[(cg.uint16, "key_data")],
define="USE_SX1509_KEYPAD_PUBLISHER",
)
KEY_DATA = KEYPAD_PUBLISHER.param("key_data")
LedDriverFrequency = sx1509_ns.enum("LedDriverFrequency")
# The PWM frequency is shared by all output pins; the values are nominal (see sx1509.h).
@@ -1,16 +1,16 @@
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import binary_sensor
import esphome.config_validation as cv
from esphome.const import CONF_COL, CONF_ROW
from esphome.core import HexInt
from esphome.types import ConfigType
from .. import CONF_SX1509_ID, KEY_DATA, KEYPAD_PUBLISHER, SX1509Component, sx1509_ns
from .. import CONF_SX1509_ID, SX1509Component, sx1509_ns
DEPENDENCIES = ["sx1509"]
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
SX1509BinarySensor = sx1509_ns.class_("SX1509BinarySensor", binary_sensor.BinarySensor)
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(SX1509BinarySensor).extend(
{
cv.GenerateID(CONF_SX1509_ID): cv.use_id(SX1509Component),
cv.Required(CONF_ROW): cv.int_range(min=0, max=7),
@@ -22,6 +22,6 @@ CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
hub = await cg.get_variable(config[CONF_SX1509_ID])
# The key data has the column bit in the high byte and the row bit in the low byte
key = HexInt((1 << (config[CONF_COL] + 8)) | (1 << config[CONF_ROW]))
KEYPAD_PUBLISHER.add(hub, sx1509_ns.publish_key(parent_ref(var), KEY_DATA, key))
cg.add(var.set_row_col(config[CONF_ROW], config[CONF_COL]))
cg.add(hub.register_keypad_binary_sensor(var))
@@ -0,0 +1,17 @@
#pragma once
#include "esphome/components/sx1509/sx1509.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
namespace esphome::sx1509 {
class SX1509BinarySensor final : public sx1509::SX1509Processor, public binary_sensor::BinarySensor {
public:
void set_row_col(uint8_t row, uint8_t col) { this->key_ = (1 << (col + 8)) | (1 << row); }
void process(uint16_t data) override { this->publish_state(static_cast<bool>(data == key_)); }
protected:
uint16_t key_{0};
};
} // namespace esphome::sx1509
+2 -4
View File
@@ -40,10 +40,8 @@ void SX1509Component::loop() {
return;
this->last_loop_timestamp_ = millis();
uint16_t key_data = this->read_key_data();
#ifdef USE_SX1509_KEYPAD_PUBLISHER
if (this->keypad_publisher_ != nullptr)
this->keypad_publisher_(key_data);
#endif
for (auto *binary_sensor : this->keypad_binary_sensors_)
binary_sensor->process(key_data);
if (this->keys_ == nullptr)
return;
if (key_data == 0) {
+11 -8
View File
@@ -6,10 +6,11 @@
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/components/gpio_expander/expander_gpio_pin.h"
#include "sx1509_registers.h"
#include <vector>
namespace esphome::sx1509 {
// These are used for clock config:
@@ -35,10 +36,11 @@ const uint8_t REG_I_ON[16] = {REG_I_ON_0, REG_I_ON_1, REG_I_ON_2, REG_I_ON_3,
REG_I_ON_6, REG_I_ON_7, REG_I_ON_8, REG_I_ON_9, REG_I_ON_10, REG_I_ON_11,
REG_I_ON_12, REG_I_ON_13, REG_I_ON_14, REG_I_ON_15};
// A template on the sensor type keeps binary_sensor.h out of this hub header
template<typename T> inline void publish_key(T *sensor, uint16_t key_data, uint16_t key) {
sensor->publish_state(key_data == key);
}
// for all components that implement the process(uint16_t data )
class SX1509Processor {
public:
virtual void process(uint16_t data) {};
};
class SX1509Component final : public Component,
public i2c::I2CDevice,
@@ -65,9 +67,9 @@ class SX1509Component final : public Component,
void set_sleep_time(uint16_t sleep_time) { this->sleep_time_ = sleep_time; };
void set_scan_time(uint8_t scan_time) { this->scan_time_ = scan_time; };
void set_debounce_time(uint8_t debounce_time = 1) { this->debounce_time_ = debounce_time; };
#ifdef USE_SX1509_KEYPAD_PUBLISHER
HUB_PUBLISHER(keypad, uint16_t)
#endif
void register_keypad_binary_sensor(SX1509Processor *binary_sensor) {
this->keypad_binary_sensors_.push_back(binary_sensor);
}
#ifdef SX1509_ON_KEY_COUNT
void add_on_key_automation(Automation<uint8_t> *automation) { this->key_automations_.add(automation); }
#endif
@@ -93,6 +95,7 @@ class SX1509Component final : public Component,
uint8_t scan_time_ = 1;
uint8_t debounce_time_ = 1;
uint8_t last_key_ = 0;
std::vector<SX1509Processor *> keypad_binary_sensors_;
#ifdef SX1509_ON_KEY_COUNT
AutomationList<SX1509_ON_KEY_COUNT, uint8_t> key_automations_;
#endif
@@ -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_
@@ -12,15 +12,6 @@ ttp229_bsf_ns = cg.esphome_ns.namespace("ttp229_bsf")
TTP229BSFComponent = ttp229_bsf_ns.class_("TTP229BSFComponent", cg.Component)
# Publishes the channel binary sensors from the touch status read on each loop
CHANNELS_PUBLISHER = cg.HubFunction(
"channels",
cg.void,
[(cg.uint16, "touched")],
define="USE_TTP229_BSF_CHANNELS_PUBLISHER",
)
TOUCHED = CHANNELS_PUBLISHER.param("touched")
MULTI_CONF = True
CONFIG_SCHEMA = cv.Schema(
{
+6 -13
View File
@@ -1,21 +1,15 @@
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import binary_sensor
import esphome.config_validation as cv
from esphome.const import CONF_CHANNEL
from esphome.types import ConfigType
from . import (
CHANNELS_PUBLISHER,
CONF_TTP229_ID,
TOUCHED,
TTP229BSFComponent,
ttp229_bsf_ns,
)
from . import CONF_TTP229_ID, TTP229BSFComponent, ttp229_bsf_ns
DEPENDENCIES = ["ttp229_bsf"]
TTP229BSFChannel = ttp229_bsf_ns.class_("TTP229BSFChannel", binary_sensor.BinarySensor)
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(TTP229BSFChannel).extend(
{
cv.GenerateID(CONF_TTP229_ID): cv.use_id(TTP229BSFComponent),
cv.Required(CONF_CHANNEL): cv.int_range(min=0, max=15),
@@ -25,8 +19,7 @@ CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
cg.add(var.set_channel(config[CONF_CHANNEL]))
hub = await cg.get_variable(config[CONF_TTP229_ID])
CHANNELS_PUBLISHER.add(
hub,
ttp229_bsf_ns.publish_channel(parent_ref(var), TOUCHED, config[CONF_CHANNEL]),
)
cg.add(hub.register_channel(var))
+16 -12
View File
@@ -2,22 +2,26 @@
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include <vector>
namespace esphome::ttp229_bsf {
// A template on the sensor type keeps binary_sensor.h out of this hub header
template<typename T> inline void publish_channel(T *sensor, uint16_t touched, uint8_t channel) {
sensor->publish_state((touched >> channel) & 1);
}
class TTP229BSFChannel final : public binary_sensor::BinarySensor {
public:
void set_channel(uint8_t channel) { channel_ = channel; }
void process(uint16_t data) { this->publish_state(data & (1 << this->channel_)); }
protected:
uint8_t channel_;
};
class TTP229BSFComponent final : public Component {
public:
void set_sdo_pin(GPIOPin *sdo_pin) { sdo_pin_ = sdo_pin; }
void set_scl_pin(GPIOPin *scl_pin) { scl_pin_ = scl_pin; }
#ifdef USE_TTP229_BSF_CHANNELS_PUBLISHER
HUB_PUBLISHER(channels, uint16_t)
#endif
void register_channel(TTP229BSFChannel *channel) { this->channels_.push_back(channel); }
void setup() override;
void dump_config() override;
void loop() override {
@@ -35,15 +39,15 @@ class TTP229BSFComponent final : public Component {
touched |= uint16_t(bitval) << i;
}
#ifdef USE_TTP229_BSF_CHANNELS_PUBLISHER
if (this->channels_publisher_ != nullptr)
this->channels_publisher_(touched);
#endif
for (auto *channel : this->channels_) {
channel->process(touched);
}
}
protected:
GPIOPin *sdo_pin_;
GPIOPin *scl_pin_;
std::vector<TTP229BSFChannel *> channels_{};
};
} // namespace esphome::ttp229_bsf
@@ -14,15 +14,6 @@ TTP229LSFComponent = ttp229_lsf_ns.class_(
"TTP229LSFComponent", cg.Component, i2c.I2CDevice
)
# Publishes the channel binary sensors from the touch status read on each loop
CHANNELS_PUBLISHER = cg.HubFunction(
"channels",
cg.void,
[(cg.uint16, "touched")],
define="USE_TTP229_LSF_CHANNELS_PUBLISHER",
)
TOUCHED = CHANNELS_PUBLISHER.param("touched")
MULTI_CONF = True
CONFIG_SCHEMA = (
cv.Schema(
+6 -13
View File
@@ -1,21 +1,15 @@
from esphome.automation import parent_ref
import esphome.codegen as cg
from esphome.components import binary_sensor
import esphome.config_validation as cv
from esphome.const import CONF_CHANNEL
from esphome.types import ConfigType
from . import (
CHANNELS_PUBLISHER,
CONF_TTP229_ID,
TOUCHED,
TTP229LSFComponent,
ttp229_lsf_ns,
)
from . import CONF_TTP229_ID, TTP229LSFComponent, ttp229_lsf_ns
DEPENDENCIES = ["ttp229_lsf"]
TTP229Channel = ttp229_lsf_ns.class_("TTP229Channel", binary_sensor.BinarySensor)
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(TTP229Channel).extend(
{
cv.GenerateID(CONF_TTP229_ID): cv.use_id(TTP229LSFComponent),
cv.Required(CONF_CHANNEL): cv.int_range(min=0, max=15),
@@ -25,8 +19,7 @@ CONFIG_SCHEMA = binary_sensor.binary_sensor_schema().extend(
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
cg.add(var.set_channel(config[CONF_CHANNEL]))
hub = await cg.get_variable(config[CONF_TTP229_ID])
CHANNELS_PUBLISHER.add(
hub,
ttp229_lsf_ns.publish_channel(parent_ref(var), TOUCHED, config[CONF_CHANNEL]),
)
cg.add(hub.register_channel(var))
+3 -4
View File
@@ -20,10 +20,9 @@ void TTP229LSFComponent::loop() {
return;
touched = i2c::i2ctohs(touched);
touched = reverse_bits(touched);
#ifdef USE_TTP229_LSF_CHANNELS_PUBLISHER
if (this->channels_publisher_ != nullptr)
this->channels_publisher_(touched);
#endif
for (auto *channel : this->channels_) {
channel->process(touched);
}
}
} // namespace esphome::ttp229_lsf
+15 -8
View File
@@ -1,24 +1,31 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "esphome/components/i2c/i2c.h"
#include <vector>
namespace esphome::ttp229_lsf {
// A template on the sensor type keeps binary_sensor.h out of this hub header
template<typename T> inline void publish_channel(T *sensor, uint16_t touched, uint8_t channel) {
sensor->publish_state((touched >> channel) & 1);
}
class TTP229Channel final : public binary_sensor::BinarySensor {
public:
void set_channel(uint8_t channel) { channel_ = channel; }
void process(uint16_t data) { this->publish_state(data & (1 << this->channel_)); }
protected:
uint8_t channel_;
};
class TTP229LSFComponent final : public Component, public i2c::I2CDevice {
public:
#ifdef USE_TTP229_LSF_CHANNELS_PUBLISHER
HUB_PUBLISHER(channels, uint16_t)
#endif
void register_channel(TTP229Channel *channel) { this->channels_.push_back(channel); }
void setup() override;
void dump_config() override;
void loop() override;
protected:
std::vector<TTP229Channel *> channels_{};
};
} // namespace esphome::ttp229_lsf
+1 -1
View File
@@ -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])
@@ -15,6 +15,9 @@ namespace esphome::uart {
ESPHOME_LOG_TAG(TAG, "uart");
// GPIO32-47 (RP2350B) and GPIO64 (CYW43) are in no mask; a 32-bit shift by them is undefined.
static constexpr bool pin_in_mask(uint8_t pin, uint32_t mask) { return pin < 32 && (mask & (1U << pin)) != 0; }
uint16_t RP2UartComponent::get_config() {
uint16_t config = 0;
@@ -81,9 +84,9 @@ void RP2UartComponent::setup() {
if (this->tx_pin_->is_inverted()) {
ESP_LOGD(TAG, "An inverted TX pin %u can only be used with SerialPIO", this->tx_pin_->get_pin());
} else {
if (((1 << this->tx_pin_->get_pin()) & valid_tx_uart_0) != 0) {
if (pin_in_mask(this->tx_pin_->get_pin(), valid_tx_uart_0)) {
tx_hw = 0;
} else if (((1 << this->tx_pin_->get_pin()) & valid_tx_uart_1) != 0) {
} else if (pin_in_mask(this->tx_pin_->get_pin(), valid_tx_uart_1)) {
tx_hw = 1;
} else {
ESP_LOGD(TAG, "TX pin %u can only be used with SerialPIO", this->tx_pin_->get_pin());
@@ -95,9 +98,9 @@ void RP2UartComponent::setup() {
if (this->rx_pin_->is_inverted()) {
ESP_LOGD(TAG, "An inverted RX pin %u can only be used with SerialPIO", this->rx_pin_->get_pin());
} else {
if (((1 << this->rx_pin_->get_pin()) & valid_rx_uart_0) != 0) {
if (pin_in_mask(this->rx_pin_->get_pin(), valid_rx_uart_0)) {
rx_hw = 0;
} else if (((1 << this->rx_pin_->get_pin()) & valid_rx_uart_1) != 0) {
} else if (pin_in_mask(this->rx_pin_->get_pin(), valid_rx_uart_1)) {
rx_hw = 1;
} else {
ESP_LOGD(TAG, "RX pin %u can only be used with SerialPIO", this->rx_pin_->get_pin());
+88
View File
@@ -0,0 +1,88 @@
from esphome import pins
import esphome.codegen as cg
from esphome.components import i2c
from esphome.components.i2c import CONF_I2C_ID
import esphome.config_validation as cv
from esphome.const import CONF_ADDRESS, CONF_ENABLE_PIN
import esphome.final_validate as fv
from esphome.types import ConfigType
AUTO_LOAD = ["sensor"]
CODEOWNERS = ["@NonaSuomy"]
DEPENDENCIES = ["i2c"]
DOMAIN = "vl6180x"
MULTI_CONF = True
CONF_VL6180X_ID = "vl6180x_id"
vl6180x_ns = cg.esphome_ns.namespace("vl6180x")
VL6180XComponent = vl6180x_ns.class_(
"VL6180XComponent", cg.PollingComponent, i2c.I2CDevice
)
_request_enable_pin_slot = cg.slot_counter("VL6180X_ENABLE_PIN_COUNT")
DEFAULT_ADDRESS = 0x29
def _validate_address(config: ConfigType) -> ConfigType:
# The sensor always boots at 0x29; only an enable pin lets it move elsewhere
if config[CONF_ADDRESS] != DEFAULT_ADDRESS and CONF_ENABLE_PIN not in config:
raise cv.Invalid(
f"An address other than 0x{DEFAULT_ADDRESS:02X} needs an enable_pin"
)
return config
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(VL6180XComponent),
cv.Optional(CONF_ENABLE_PIN): pins.gpio_output_pin_schema,
}
)
.extend(cv.polling_component_schema("60s"))
.extend(i2c.i2c_device_schema(DEFAULT_ADDRESS)),
_validate_address,
)
def _final_validate(config: ConfigType) -> ConfigType:
# With several sensors on one bus each needs its own enable_pin so it can be held in reset
# while the others are re-addressed, and none may stay at 0x29, or a later sibling boots at
# the same address and the re-address write reaches both chips.
addresses = [
conf[CONF_ADDRESS]
for conf in fv.full_config.get()[DOMAIN]
if conf[CONF_I2C_ID] == config[CONF_I2C_ID]
]
if len(addresses) < 2:
return config
if CONF_ENABLE_PIN not in config:
raise cv.Invalid(
"Every VL6180X on a shared I2C bus needs an enable_pin",
path=[CONF_ENABLE_PIN],
)
address = config[CONF_ADDRESS]
if address == DEFAULT_ADDRESS:
raise cv.Invalid(
f"VL6180X sensors sharing an I2C bus must all be re-addressed away "
f"from 0x{DEFAULT_ADDRESS:02X}",
path=[CONF_ADDRESS],
)
if addresses.count(address) > 1:
raise cv.Invalid(
f"Address 0x{address:02X} is used by more than one VL6180X on this bus",
path=[CONF_ADDRESS],
)
return config
FINAL_VALIDATE_SCHEMA = _final_validate
async def to_code(config: ConfigType) -> None:
var = await i2c.new_i2c_component(config)
if pin := await cg.add_pin(var.set_enable_pin, config.get(CONF_ENABLE_PIN)):
_request_enable_pin_slot()
cg.add(var.register_enable_pin(pin))
+80
View File
@@ -0,0 +1,80 @@
import esphome.codegen as cg
from esphome.components import sensor
import esphome.config_validation as cv
from esphome.const import (
CONF_DISTANCE,
CONF_GAIN,
CONF_ILLUMINANCE,
CONF_INTEGRATION_TIME,
DEVICE_CLASS_DISTANCE,
DEVICE_CLASS_ILLUMINANCE,
STATE_CLASS_MEASUREMENT,
UNIT_LUX,
UNIT_MILLIMETER,
)
import esphome.final_validate as fv
from esphome.types import ConfigType
from . import CONF_VL6180X_ID, DOMAIN, VL6180XComponent
DEPENDENCIES = ["vl6180x"]
CONF_SCALER = "scaler"
# Gain factor to the SYSALS_ANALOGUE_GAIN code
ALS_GAINS = {1: 6, 1.25: 5, 1.67: 4, 2.5: 3, 5: 2, 10: 1, 20: 0, 40: 7}
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(CONF_VL6180X_ID): cv.use_id(VL6180XComponent),
cv.Optional(CONF_DISTANCE): sensor.sensor_schema(
unit_of_measurement=UNIT_MILLIMETER,
accuracy_decimals=0,
device_class=DEVICE_CLASS_DISTANCE,
state_class=STATE_CLASS_MEASUREMENT,
).extend(
{cv.Optional(CONF_SCALER, default=1): cv.one_of(1, 2, 3, int=True)}
),
cv.Optional(CONF_ILLUMINANCE): sensor.sensor_schema(
unit_of_measurement=UNIT_LUX,
accuracy_decimals=1,
device_class=DEVICE_CLASS_ILLUMINANCE,
state_class=STATE_CLASS_MEASUREMENT,
).extend(
{
cv.Optional(CONF_GAIN, default=1): cv.enum(ALS_GAINS),
cv.Optional(CONF_INTEGRATION_TIME, default="100ms"): cv.All(
cv.positive_time_period_milliseconds,
cv.Range(
min=cv.TimePeriod(milliseconds=1),
max=cv.TimePeriod(milliseconds=512),
),
),
}
),
}
),
cv.has_at_least_one_key(CONF_DISTANCE, CONF_ILLUMINANCE),
)
FINAL_VALIDATE_SCHEMA = fv.unique_platform_key(
domain=sensor.DOMAIN,
platform=DOMAIN,
keys=(CONF_VL6180X_ID,),
message="Only one VL6180X sensor platform entry is allowed per hub",
)
async def to_code(config: ConfigType) -> None:
hub = await cg.get_variable(config[CONF_VL6180X_ID])
sensors = sensor.sub_sensors(config)
if (distance_config := config.get(CONF_DISTANCE)) is not None:
await sensors(CONF_DISTANCE, hub.set_distance_sensor)
cg.add(hub.set_scaler(distance_config[CONF_SCALER]))
if (illuminance_config := config.get(CONF_ILLUMINANCE)) is not None:
await sensors(CONF_ILLUMINANCE, hub.set_illuminance_sensor)
gain = illuminance_config[CONF_GAIN]
time_ms = illuminance_config[CONF_INTEGRATION_TIME].total_milliseconds
# The datasheet scale is 0.32 lux per count at 1x gain and 100 ms
cg.add(hub.set_als(gain.enum_value, time_ms, 32.0 / (float(gain) * time_ms)))
+267
View File
@@ -0,0 +1,267 @@
#include "vl6180x.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
namespace esphome::vl6180x {
ESPHOME_LOG_TAG(TAG, "vl6180x");
static constexpr uint32_t MEASUREMENT_ID = 0;
static constexpr uint8_t DEFAULT_ADDRESS = 0x29;
static constexpr uint8_t MODEL_ID = 0xB4;
static constexpr uint16_t REG_IDENTIFICATION_MODEL_ID = 0x000;
static constexpr uint16_t REG_SYSTEM_INTERRUPT_CLEAR = 0x015;
static constexpr uint16_t REG_SYSTEM_FRESH_OUT_OF_RESET = 0x016;
static constexpr uint16_t REG_SYSRANGE_START = 0x018;
static constexpr uint16_t REG_SYSRANGE_CROSSTALK_VALID_HEIGHT = 0x021;
static constexpr uint16_t REG_SYSRANGE_PART_TO_PART_OFFSET = 0x024;
static constexpr uint16_t REG_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D;
static constexpr uint16_t REG_SYSALS_START = 0x038;
static constexpr uint16_t REG_SYSALS_ANALOGUE_GAIN = 0x03F;
static constexpr uint16_t REG_SYSALS_INTEGRATION_PERIOD = 0x040;
static constexpr uint16_t REG_RESULT_RANGE_STATUS = 0x04D;
static constexpr uint16_t REG_RESULT_ALS_STATUS = 0x04E;
static constexpr uint16_t REG_RESULT_RANGE_VAL = 0x062;
static constexpr uint16_t REG_RANGE_SCALING = 0x096;
static constexpr uint16_t REG_I2C_DEVICE_ADDRESS = 0x212;
// RESULT_INTERRUPT_STATUS_GPIO: a new range sample in bits 2:0, a new ALS sample in bits 5:3
static constexpr uint8_t RANGE_SAMPLE_READY = 0x04;
static constexpr uint8_t ALS_SAMPLE_READY = 0x04 << 3;
// Range conversion is at most the 50 ms convergence time set below plus readout
static constexpr uint32_t RANGE_TIME_MS = 70;
static constexpr uint32_t ALS_READOUT_MARGIN_MS = 400;
// Indexed by the range scaler, 1x to 3x (AN4545)
static constexpr uint16_t RANGE_SCALING_VALUES[] PROGMEM = {0, 253, 127, 84};
struct RegValue {
uint16_t reg;
uint8_t value;
};
// Private settings written once after a power-on reset (AN4545 table 7)
static constexpr RegValue MANDATORY_SETTINGS[] PROGMEM = {
{0x0207, 0x01},
{0x0208, 0x01},
{0x0096, 0x00},
{0x0097, 0xFD},
{0x00E3, 0x00},
{0x00E4, 0x04},
{0x00E5, 0x02},
{0x00E6, 0x01},
{0x00E7, 0x03},
{0x00F5, 0x02},
{0x00D9, 0x05},
{0x00DB, 0xCE},
{0x00DC, 0x03},
{0x00DD, 0xF8},
{0x009F, 0x00},
{0x00A3, 0x3C},
{0x00B7, 0x00},
{0x00BB, 0x3C},
{0x00B2, 0x09},
{0x00CA, 0x09},
{0x0198, 0x01},
{0x01B0, 0x17},
{0x01AD, 0x00},
{0x00FF, 0x05},
{0x0100, 0x05},
{0x0199, 0x05},
{0x01A6, 0x1B},
{0x01AC, 0x3E},
{0x01A7, 0x1F},
{0x0030, 0x00},
{REG_SYSTEM_FRESH_OUT_OF_RESET, 0x00},
};
// Recommended settings (AN4545 section 9), with GPIO1 left floating and new-sample interrupts flagged
static constexpr RegValue DEFAULT_SETTINGS[] PROGMEM = {
{0x010A, 0x30}, // averaging sample period
{0x0031, 0xFF}, // repeat temperature calibration every 255 range measurements
{0x002E, 0x01}, // run the first temperature calibration now
{0x001C, 0x32}, // 50 ms maximum convergence time
{0x0011, 0x20}, // GPIO1 off
{0x0014, RANGE_SAMPLE_READY | ALS_SAMPLE_READY},
{REG_SYSTEM_INTERRUPT_CLEAR, 0x07},
};
template<size_t N> static bool write_settings(i2c::I2CDevice *device, const RegValue (&table)[N]) {
for (const auto &entry : table) {
RegValue setting;
progmem_memcpy(&setting, &entry, sizeof(setting));
if (!device->write_byte_reg16(setting.reg, setting.value))
return false;
}
return true;
}
#ifdef VL6180X_ENABLE_PIN_COUNT
SlotList<GPIOPin *, VL6180X_ENABLE_PIN_COUNT> VL6180XComponent::enable_pins; // NOLINT
#endif
void VL6180XComponent::setup() {
#ifdef VL6180X_ENABLE_PIN_COUNT
// Every sensor boots at 0x29, so all are held in reset and then released one at a time
for (auto *pin : enable_pins) {
pin->setup();
pin->digital_write(false);
}
enable_pins.clear();
if (this->enable_pin_ != nullptr) {
this->enable_pin_->digital_write(true);
delay(10);
}
#endif
const uint8_t address = this->address_;
this->set_i2c_address(DEFAULT_ADDRESS);
uint8_t model_id = 0;
const bool read_ok = this->read_byte_reg16(REG_IDENTIFICATION_MODEL_ID, &model_id);
const bool ok = read_ok && model_id == MODEL_ID && this->init_() &&
(address == DEFAULT_ADDRESS || this->write_byte_reg16(REG_I2C_DEVICE_ADDRESS, address));
this->set_i2c_address(address);
if (ok)
return;
#ifdef VL6180X_ENABLE_PIN_COUNT
// A sensor left at 0x29 would answer for the next one released
if (this->enable_pin_ != nullptr)
this->enable_pin_->digital_write(false);
#endif
if (read_ok && model_id != MODEL_ID) {
ESP_LOGE(TAG, "Wrong model ID 0x%02X", model_id);
this->mark_failed(LOG_STR("Wrong model ID"));
return;
}
this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
}
bool VL6180XComponent::init_() {
uint8_t fresh;
uint8_t offset;
if (!this->read_byte_reg16(REG_SYSTEM_FRESH_OUT_OF_RESET, &fresh) ||
!this->read_byte_reg16(REG_SYSRANGE_PART_TO_PART_OFFSET, &offset))
return false;
// The factory offset is for 1x; a sensor that kept power through an MCU reboot already holds it divided by the
// scaler from the last setup
int16_t part_offset = static_cast<int8_t>(offset);
if (fresh & 0x01) {
if (!write_settings(this, MANDATORY_SETTINGS))
return false;
} else {
uint8_t scaling[2];
if (this->read_register16(REG_RANGE_SCALING, scaling, 2) != i2c::ERROR_OK)
return false;
const uint16_t value = encode_uint16(scaling[0], scaling[1]);
for (uint8_t scaler = 2; scaler <= 3; scaler++) {
if (value == progmem_read_uint16(&RANGE_SCALING_VALUES[scaler]))
part_offset *= scaler;
}
}
uint8_t period[2];
put_be16(period, this->als_integration_time_ms_ - 1);
uint8_t scaling[2];
put_be16(scaling, progmem_read_uint16(&RANGE_SCALING_VALUES[this->scaler_]));
return write_settings(this, DEFAULT_SETTINGS) &&
this->write_byte_reg16(REG_SYSALS_ANALOGUE_GAIN, 0x40 | this->als_gain_code_) &&
this->write_register16(REG_SYSALS_INTEGRATION_PERIOD, period, 2) == i2c::ERROR_OK &&
this->write_register16(REG_RANGE_SCALING, scaling, 2) == i2c::ERROR_OK &&
this->write_byte_reg16(REG_SYSRANGE_PART_TO_PART_OFFSET, static_cast<uint8_t>(part_offset / this->scaler_)) &&
this->write_byte_reg16(REG_SYSRANGE_CROSSTALK_VALID_HEIGHT, 20 / this->scaler_) &&
// SNR check, plus the early convergence estimate only at 1x, as in ST's API
this->write_byte_reg16(REG_SYSRANGE_RANGE_CHECK_ENABLES, 0x10 | (this->scaler_ == 1 ? 0x01 : 0x00));
}
void VL6180XComponent::update() {
// A measurement still running means the update interval is shorter than one cycle
if (this->measuring_)
return;
this->measuring_ = true;
if (this->distance_sensor_ != nullptr) {
this->start_range_();
} else {
this->start_als_();
}
}
void VL6180XComponent::start_range_() {
if (!this->status_comm_check(this->write_byte_reg16(REG_SYSRANGE_START, 0x01))) {
this->measuring_ = false;
return;
}
this->set_timeout(MEASUREMENT_ID, RANGE_TIME_MS, [this]() { this->read_range_(); });
}
void VL6180XComponent::read_range_() {
uint8_t status[3]; // range status, ALS status, interrupt status
uint8_t raw;
if (!this->status_comm_check(this->read_register16(REG_RESULT_RANGE_STATUS, status, 3) == i2c::ERROR_OK) ||
!this->status_comm_check((status[2] & 0x07) == RANGE_SAMPLE_READY) ||
!this->status_comm_check(this->read_byte_reg16(REG_RESULT_RANGE_VAL, &raw) &&
this->write_byte_reg16(REG_SYSTEM_INTERRUPT_CLEAR, 0x07))) {
this->measuring_ = false;
return;
}
const uint8_t error = status[0] >> 4;
// Codes 1 to 5 are self-test faults (VCSEL or PLL); a fault keeps the warning until a whole cycle works
if (error >= 1 && error <= 5) {
ESP_LOGW(TAG, "Range self-test fault %u", error);
PUBLISH_STATE(this->distance_sensor_, NAN);
this->status_set_warning();
this->measuring_ = false;
return;
}
// Other codes mean no target or out of range
if (error != 0) {
ESP_LOGV(TAG, "Range error code %u", error);
PUBLISH_STATE(this->distance_sensor_, NAN);
} else {
PUBLISH_STATE(this->distance_sensor_, static_cast<float>(raw * this->scaler_));
}
// With illuminance configured, read_als_() clears the warning once the whole cycle has worked
if (this->illuminance_sensor_ != nullptr) {
this->start_als_();
} else {
this->measuring_ = false;
this->status_clear_warning();
}
}
void VL6180XComponent::start_als_() {
if (!this->status_comm_check(this->write_byte_reg16(REG_SYSALS_START, 0x01))) {
this->measuring_ = false;
return;
}
this->set_timeout(MEASUREMENT_ID, this->als_integration_time_ms_ + ALS_READOUT_MARGIN_MS,
[this]() { this->read_als_(); });
}
void VL6180XComponent::read_als_() {
this->measuring_ = false;
uint8_t result[4]; // ALS status, interrupt status, ALS value
if (!this->status_comm_check(this->read_register16(REG_RESULT_ALS_STATUS, result, 4) == i2c::ERROR_OK) ||
!this->status_comm_check((result[1] & 0x38) == ALS_SAMPLE_READY) ||
!this->status_comm_result(this->write_byte_reg16(REG_SYSTEM_INTERRUPT_CLEAR, 0x07)))
return;
// An overflow in bright light is a reading, not a fault
if (result[0] >> 4) {
ESP_LOGV(TAG, "ALS error code %u", result[0] >> 4);
PUBLISH_STATE(this->illuminance_sensor_, NAN);
return;
}
PUBLISH_STATE(this->illuminance_sensor_, encode_uint16(result[2], result[3]) * this->lux_per_count_);
}
void VL6180XComponent::dump_config() {
ESP_LOGCONFIG(TAG, "VL6180X:");
LOG_I2C_DEVICE(this);
LOG_PIN(" Enable Pin: ", this->enable_pin_);
LOG_UPDATE_INTERVAL(this);
LOG_SENSOR(" ", "Distance", this->distance_sensor_);
LOG_SENSOR(" ", "Illuminance", this->illuminance_sensor_);
}
} // namespace esphome::vl6180x
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/component.h"
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
namespace esphome::vl6180x {
class VL6180XComponent final : public PollingComponent, public i2c::I2CDevice {
SUB_SENSOR(distance)
SUB_SENSOR(illuminance)
public:
void setup() override;
void update() override;
void dump_config() override;
void set_enable_pin(GPIOPin *pin) { this->enable_pin_ = pin; }
void set_scaler(uint8_t scaler) { this->scaler_ = scaler; }
/// @param gain_code SYSALS_ANALOGUE_GAIN code of the gain
/// @param integration_time_ms 1 to 512 ms
/// @param lux_per_count lux of one ALS count at this gain and integration time
void set_als(uint8_t gain_code, uint16_t integration_time_ms, float lux_per_count) {
this->als_gain_code_ = gain_code;
this->als_integration_time_ms_ = integration_time_ms;
this->lux_per_count_ = lux_per_count;
}
#ifdef VL6180X_ENABLE_PIN_COUNT
/// The first setup() holds every registered sensor in reset, so each can be moved off 0x29 alone.
static void register_enable_pin(GPIOPin *pin) { enable_pins.push_back(pin); }
#endif
protected:
bool init_();
void start_range_();
void read_range_();
void start_als_();
void read_als_();
#ifdef VL6180X_ENABLE_PIN_COUNT
static SlotList<GPIOPin *, VL6180X_ENABLE_PIN_COUNT> enable_pins; // NOLINT
#endif
GPIOPin *enable_pin_{nullptr};
float lux_per_count_{0.0f};
uint16_t als_integration_time_ms_{100};
uint8_t als_gain_code_{6};
uint8_t scaler_{1};
bool measuring_{false};
};
} // namespace esphome::vl6180x
+31 -21
View File
@@ -5,47 +5,57 @@
namespace esphome::wifi {
// Switching APs calls esp_wifi_disconnect(), which queues an association-leave event from the old AP. Remembers
// that AP so its leave event does not end the connection attempt started after it. Platform free for host tests.
/// Which expected leave a disconnect matched.
enum class ExpectedLeave : uint8_t {
EXPECTED_LEAVE_NONE,
EXPECTED_LEAVE_AP,
EXPECTED_LEAVE_ATTEMPT, ///< An attempt that never associated, so no BSSID
};
// Switching APs calls esp_wifi_disconnect(), which queues a leave event for the old AP, or with no BSSID for an
// attempt that never associated. Remembers it so that event does not end the next attempt. Platform free for tests.
class ExpectedDisconnect {
public:
void arm(const uint8_t *bssid) {
std::copy_n(bssid, this->bssid_.size(), this->bssid_.begin());
this->armed_ = true;
}
void clear() { this->armed_ = false; }
void arm(const uint8_t *bssid) { this->arm_(bssid, ExpectedLeave::EXPECTED_LEAVE_AP); }
void clear() { this->expected_ = ExpectedLeave::EXPECTED_LEAVE_NONE; }
/// Disconnects from the current AP and, once that succeeds, expects its leave event. read_bssid(uint8_t *out)
/// returns whether there was an AP and runs first, since the record is gone after the disconnect; disconnect()
/// returns whether it succeeded, which is also the result. Any earlier expectation is dropped.
/// Disconnects and, once that succeeds, expects the leave event. read_bssid(uint8_t *out) runs first, since the
/// record is gone after the disconnect, and writes the AP's BSSID only when it returns true; without an AP the
/// attempt's leave, with no BSSID, is expected. disconnect() returns whether it succeeded, which is the result.
template<typename ReadBssid, typename Disconnect>
bool disconnect_and_expect_leave(ReadBssid &&read_bssid, Disconnect &&disconnect) {
this->armed_ = false;
this->clear();
std::array<uint8_t, 6> bssid{};
const bool had_ap = read_bssid(bssid.data());
if (!disconnect())
return false;
if (had_ap)
this->arm(bssid.data());
this->arm_(bssid.data(), had_ap ? ExpectedLeave::EXPECTED_LEAVE_AP : ExpectedLeave::EXPECTED_LEAVE_ATTEMPT);
return true;
}
/// A connected event still queued from the previous AP; it keeps the expectation.
bool is_previous_ap(const uint8_t *bssid) const {
return this->armed_ && std::equal(this->bssid_.begin(), this->bssid_.end(), bssid);
return this->expected_ != ExpectedLeave::EXPECTED_LEAVE_NONE &&
std::equal(this->bssid_.begin(), this->bssid_.end(), bssid);
}
/// Whether a disconnect is the previous AP's leave. Every disconnect ends the expectation, so it matches at
/// most once; the caller handles roaming disconnects before this.
bool consume_disconnect(const uint8_t *bssid, bool assoc_leave) {
const bool expected = assoc_leave && this->is_previous_ap(bssid);
this->armed_ = false;
return expected;
/// Which expected leave a disconnect is. \p is_leave covers an AP's association leave (8) and the station leave
/// of an attempt that never associated (36). Every disconnect ends the expectation, so it matches at most once.
ExpectedLeave consume_disconnect(const uint8_t *bssid, bool is_leave) {
const ExpectedLeave matched =
is_leave && this->is_previous_ap(bssid) ? this->expected_ : ExpectedLeave::EXPECTED_LEAVE_NONE;
this->clear();
return matched;
}
protected:
void arm_(const uint8_t *bssid, ExpectedLeave expected) {
std::copy_n(bssid, this->bssid_.size(), this->bssid_.begin());
this->expected_ = expected;
}
std::array<uint8_t, 6> bssid_{};
bool armed_{false};
ExpectedLeave expected_{ExpectedLeave::EXPECTED_LEAVE_NONE};
};
} // namespace esphome::wifi
@@ -1158,10 +1158,12 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
ESP_LOGI(TAG, "Disconnected ssid='%.*s' reason='Station Roaming'", it.ssid_len, (const char *) it.ssid);
return;
}
const bool expected_disconnect =
s_expected_disconnect.consume_disconnect(it.bssid, it.reason == WIFI_REASON_ASSOC_LEAVE);
const ExpectedLeave expected = s_expected_disconnect.consume_disconnect(
it.bssid, it.reason == WIFI_REASON_ASSOC_LEAVE || it.reason == WIFI_REASON_STA_LEAVING);
const bool expected_disconnect = expected != ExpectedLeave::EXPECTED_LEAVE_NONE;
if (expected_disconnect) {
ESP_LOGD(TAG, "Expected disconnect from previous AP");
ESP_LOGD(TAG, "Expected leave of the previous %s",
expected == ExpectedLeave::EXPECTED_LEAVE_AP ? LOG_STR_LITERAL("AP") : LOG_STR_LITERAL("attempt"));
} else if (it.reason == WIFI_REASON_NO_AP_FOUND) {
ESP_LOGW(TAG, "Disconnected ssid='%.*s' reason='Probe Request Unsuccessful'", it.ssid_len,
(const char *) it.ssid);
@@ -1181,7 +1183,9 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
// Refresh is_connected() cache; the old session is no longer connected.
this->update_connected_state_();
#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
this->notify_disconnect_state_listeners_();
// An attempt that never associated ended no session listeners know of
if (expected != ExpectedLeave::EXPECTED_LEAVE_ATTEMPT)
this->notify_disconnect_state_listeners_();
#endif
#if defined(USE_WIFI_AP_WISP) && !defined(USE_WIFI_AP_WISP_STATIC_DNS)
+11 -3
View File
@@ -1,7 +1,7 @@
from collections.abc import Callable
from pathlib import Path
import textwrap
from typing import NamedTuple, TypedDict
from typing import Literal, NamedTuple, TypedDict
import esphome.codegen as cg
import esphome.config_validation as cv
@@ -212,10 +212,18 @@ async def _cdc_acm_to_code() -> None:
_cdc_acm_add_ports()
def zephyr_setup_preferences() -> None:
PreferenceStorage = Literal["NVS", "ZMS"]
def zephyr_setup_preferences(storage: PreferenceStorage = "NVS") -> None:
"""Store preferences through the settings subsystem.
`storage` picks the Zephyr storage backend: NVS for flash, ZMS for RRAM and MRAM.
"""
cg.add(zephyr_ns.setup_preferences())
zephyr_add_prj_conf("SETTINGS", True)
zephyr_add_prj_conf("NVS", True)
zephyr_add_prj_conf(storage, True)
zephyr_add_prj_conf(f"SETTINGS_{storage}", True)
zephyr_add_prj_conf("FLASH_MAP", True)
zephyr_add_prj_conf("FLASH", True)
@@ -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
+12 -8
View File
@@ -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) {
+5 -6
View File
@@ -1497,12 +1497,11 @@ class BindKeyValidator(SensitiveValidator):
if any(len(part) != 2 for part in parts):
raise Invalid(f"{self._name} must be format XX")
for part in parts:
try:
parts_int.append(int(part, 16))
except ValueError:
raise Invalid(
f"{self._name} must be hex values from 00 to FF"
) from None
# int() also accepts surrounding whitespace and a +/- sign, which
# would silently validate a key different from the one typed
if not re.fullmatch(r"[0-9A-Fa-f]{2}", part):
raise Invalid(f"{self._name} must be hex values from 00 to FF")
parts_int.append(int(part, 16))
return "".join(f"{part:02X}" for part in parts_int)
+2 -6
View File
@@ -70,7 +70,6 @@
#define USE_BUTTON
#define USE_CAMERA
#define USE_CANBUS_FD
#define USE_CAP1188_CHANNELS_PUBLISHER
#define USE_CC1101_LONG_PACKET
#define USE_CLIMATE
#define USE_CLIMATE_VISUAL_OVERRIDES
@@ -226,7 +225,6 @@
#define MODBUS_ON_REQUEST_COUNT 1
#define MODBUS_ON_RESPONSE_COUNT 1
#define USE_MOTION_DATA_PUBLISHER
#define USE_MPR121_CHANNEL_PUBLISHERS
#define NFC_TAG_LISTENER_COUNT 1
#define PN532_BINARY_SENSOR_COUNT 1
#define PN532_ON_TAG_REMOVED_TRIGGER_COUNT 1
@@ -240,10 +238,10 @@
#define RC522_ON_TAG_COUNT 1
#define RC522_ON_TAG_REMOVED_COUNT 1
#define RDM6300_ON_TAG_COUNT 1
#define USE_RDM6300_CARDS_PUBLISHER
#define REMOTE_BASE_DUMPER_COUNT 1
#define REMOTE_BASE_LISTENER_COUNT 1
#define SX1509_ON_KEY_COUNT 1
#define VL6180X_ENABLE_PIN_COUNT 2
#define WIEGAND_ON_KEY_COUNT 1
#define WIEGAND_ON_RAW_COUNT 1
#define WIEGAND_ON_TAG_COUNT 1
@@ -337,6 +335,7 @@
#define USE_PACKET_INTERFACE_HDLC
#define USE_PACKET_INTERFACE_XXTEA
#define USE_PCA9554_PCAL
#define USE_PCM1863_SELECT
#define USE_POWER_SUPPLY
// Only defined by key-lookup preference backends; the slot-based platforms
// (esp8266, rp2040) never set it in generated builds, and their preferences
@@ -368,7 +367,6 @@
#define USE_STATUS_SENSOR
#define USE_SWITCH
#define USE_SWITCH_STORAGE
#define USE_SX1509_KEYPAD_PUBLISHER
#define USE_SY6970_DATA_PUBLISHER
#define USE_TCA8418_KEY_PUBLISHER
#define USE_TEXT
@@ -384,8 +382,6 @@
#define USE_TMP102_TEXT_SENSOR
#define USE_TOSHIBA_RAS_25J2KVSG_ND
#define USE_TOUCHSCREEN
#define USE_TTP229_BSF_CHANNELS_PUBLISHER
#define USE_TTP229_LSF_CHANNELS_PUBLISHER
#define USE_TUYA_DUMP_PUBLISHER
#define USE_UART_DEBUGGER
#define USE_UART_WAKE_LOOP_ON_RX
+3 -1
View File
@@ -846,7 +846,9 @@ def convert_visual_temperatures(
that needs ``full_config`` is left for final validation, which runs this again with it."""
if (unit := entity_temperature_unit(config, full_config)) is None:
return config
visual = config[CONF_VISUAL]
# A platform entry that only holds nested entities has no visual section of its own
if (visual := config.get(CONF_VISUAL)) is None:
return config
convert_temperature_keys(visual, (CONF_MIN_TEMPERATURE, CONF_MAX_TEMPERATURE), unit)
section = visual if delta_section is None else visual.get(delta_section)
if section is not None:
+36
View File
@@ -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
+28
View File
@@ -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
View File
@@ -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
+1 -1
View File
@@ -28,7 +28,7 @@ bleak==3.1.0
smpclient==7.4.0
# smp 4.2+ needs cbor2 6+, which ships no Intel macOS wheels (arm64 only).
smp==4.3.0; platform_system != "Darwin" or platform_machine != "x86_64"
smp==4.2.0; platform_system == "Darwin" and platform_machine == "x86_64"
smp==4.3.0; platform_system == "Darwin" and platform_machine == "x86_64"
requests==2.34.2
py7zr==1.1.4
platformdirs==4.14.5 # native esp-idf toolchain global cache dir
Whitespace-only changes.
@@ -1,24 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
i2c:
sda: GPIO21
scl: GPIO22
cap1188:
- id: hub
- id: idle_hub
address: 0x28
binary_sensor:
- platform: cap1188
cap1188_id: hub
id: key0
channel: 0
- platform: cap1188
cap1188_id: hub
id: key7
channel: 7
@@ -1,21 +0,0 @@
"""Tests for the function that publishes the cap1188 channel binary sensors."""
from collections.abc import Callable
from pathlib import Path
def test_channels_publish_through_hub_function(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("hub_function.yaml"))
assert (
"static void esphome__hub__channels_fn(uint8_t esphome__arg_touched) {\n"
" cap1188::publish_channel(::key0, esphome__arg_touched, 0);\n"
" cap1188::publish_channel(::key7, esphome__arg_touched, 7);\n"
"}"
) in main_cpp
assert "hub->set_channels_publisher(esphome__hub__channels_fn);" in main_cpp
# A hub without channels keeps a null publisher
assert "idle_hub->set_channels_publisher" not in main_cpp
@@ -222,6 +222,20 @@ def test_a_resolved_unit_waits_for_the_full_config() -> None:
assert config[CONF_VISUAL][CONF_MIN_TEMPERATURE] == pytest.approx(59.0)
def test_final_validate_skips_a_platform_that_only_holds_nested_climates() -> None:
"""A hub platform may put each of its climates under a key of one platform entry."""
nested = climate_schema(climate_ns.class_("NestedClimate", Climate))
platform_schema = cv.Schema({cv.Optional("zone_1"): nested})
config = platform_schema(
{"zone_1": {CONF_NAME: "Zone 1", CONF_VISUAL: {CONF_MIN_TEMPERATURE: "50°F"}}}
)
# The platform entry itself is not a climate and has no visual section
assert CONF_VISUAL not in config
_final_validate([config])
# The nested climate was converted by its own schema
assert config["zone_1"][CONF_VISUAL][CONF_MIN_TEMPERATURE] == pytest.approx(10.0)
@pytest.mark.parametrize(
("use_fahrenheit", "cn105_lines"),
[
Whitespace-only changes.
@@ -1,27 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
i2c:
sda: GPIO21
scl: GPIO22
mpr121:
- id: hub
touch_threshold: 0x10
release_threshold: 0x08
- id: idle_hub
address: 0x5B
binary_sensor:
- platform: mpr121
mpr121_id: hub
id: key0
channel: 0
- platform: mpr121
mpr121_id: hub
id: key3
channel: 3
touch_threshold: 0x20
@@ -1,29 +0,0 @@
"""Tests for the function that publishes the mpr121 channel binary sensors."""
from collections.abc import Callable
from pathlib import Path
def test_channels_write_thresholds_and_publish_through_hub_functions(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("hub_function.yaml"))
# A channel without its own thresholds takes the hub's (16 and 8)
assert (
"static void esphome__hub__thresholds_fn() {\n"
" hub->write_thresholds(0, 16, 8);\n"
" hub->write_thresholds(3, 32, 8);\n"
"}"
) in main_cpp
assert (
"static void esphome__hub__channels_fn(uint16_t esphome__arg_touched) {\n"
" mpr121::publish_channel(::key0, esphome__arg_touched, 0);\n"
" mpr121::publish_channel(::key3, esphome__arg_touched, 3);\n"
"}"
) in main_cpp
assert "hub->set_thresholds_publisher(esphome__hub__thresholds_fn);" in main_cpp
assert "hub->set_channels_publisher(esphome__hub__channels_fn);" in main_cpp
assert "idle_hub->set_thresholds_publisher" not in main_cpp
assert "idle_hub->set_channels_publisher" not in main_cpp
+95 -2
View File
@@ -8,11 +8,16 @@ 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,
_thermistor_resistance,
_vbus_current_limit_code,
thermistor_beta,
)
from esphome.const import CONF_MODE, CONF_VOLTAGE
from esphome.cpp_generator import StructInitializer
@@ -54,10 +59,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 +142,66 @@ 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
@pytest.mark.parametrize(
("value", "result"),
[
("10kOhm", 10000.0),
("0.047MOhm", 47000.0),
("100000", 100000.0),
("None", "none"),
],
)
def test_thermistor_resistance(value: str, result: float | str) -> None:
assert _thermistor_resistance(value) == result
def test_thermistor_resistance_rejected() -> None:
with pytest.raises(cv.Invalid, match="10kOhm, 47kOhm, 100kOhm or none"):
_thermistor_resistance("22kOhm")
Whitespace-only changes.
@@ -1,29 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
uart:
- id: uart_reader
rx_pin: GPIO16
baud_rate: 9600
- id: uart_idle
rx_pin: GPIO17
baud_rate: 9600
rdm6300:
- id: reader
uart_id: uart_reader
- id: idle_reader
uart_id: uart_idle
binary_sensor:
- platform: rdm6300
rdm6300_id: reader
id: card_a
uid: 7616525
- platform: rdm6300
rdm6300_id: reader
id: card_b
uid: 4294967295
@@ -1,27 +0,0 @@
"""Tests for the function that publishes the rdm6300 card binary sensors."""
from collections.abc import Callable
from pathlib import Path
def test_cards_publish_through_hub_function(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("hub_function.yaml"))
# A bool function: every card is checked, and it returns whether one matched
assert (
"static bool esphome__reader__cards_fn(uint32_t esphome__arg_tag) {\n"
" bool esphome__found = false;\n"
" (esphome__found |= rdm6300::publish_card(::card_a, esphome__arg_tag, 7616525));\n"
" (esphome__found |= rdm6300::publish_card(::card_b, esphome__arg_tag, 4294967295UL));\n"
" return esphome__found;\n"
"}"
) in main_cpp
assert "reader->set_cards_publisher(esphome__reader__cards_fn);" in main_cpp
# Cards start OFF, as before; they only pulse ON when their tag is read
for card in ("card_a", "card_b"):
assert f"new({card}) binary_sensor::BinarySensorInitiallyOff();" in main_cpp
# A reader without cards keeps a null publisher
assert "idle_reader->set_cards_publisher" not in main_cpp
@@ -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
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more