Compare commits

..
Author SHA1 Message Date
J. Nick Koston ebc9807ffe Test register writes through the port frequency paths 2026-11-16 17:55:38 -06:00
J. Nick Koston 49a6f7133f Record the upstream calls without std::to_string 2026-11-16 17:52:00 -06:00
J. Nick Koston c20c445188 [tca9548a] Forward register writes to the upstream bus in two parts 2026-11-16 17:48:05 -06:00
J. Nick Koston ca6cfc6469 Merge remote-tracking branch 'upstream/dev' into i2c-write-register-gather
# Conflicts:
#	esphome/components/i2c/i2c.cpp
2026-11-16 17:33:14 -06:00
J. Nick Koston 3c8940bfef [i2c] Keep register writes of up to 18 data bytes on the stack (#22717) 2026-11-16 18:30:39 -05:00
J. Nick Koston 4886238892 [opentherm] Drop the Component base from OpenthermOutput (#22723) 2026-11-16 18:29:05 -05:00
J. Nick Koston d611d9a3ca [cc1101] Wait for the CRC when a received packet fills the RX FIFO (#22635) 2026-11-16 18:27:56 -05:00
Jonathan Swoboda aa2a31647d [esp32][libretiny] Make delay() wait at least the requested time (#22822) 2026-11-16 18:17:25 -05:00
J. Nick Koston f18de29d20 [remote_base] Fix the canalsatld binary sensor and trigger build (#22716) 2026-11-16 16:46:13 -06:00
J. Nick Koston 4eb24d78b0 [core] Release only the lwIP core lock a LwIPLock took (#22683) 2026-11-16 16:46:02 -06:00
J. Nick Koston 1658efa9e7 [esp32_ble] Stop Bluedroid re-running a failed queued MTU or execute write request (#22670) 2026-11-17 11:30:07 +13:00
J. Nick Koston feebc28853 [esp32_power_management] Clamp the tick step after light sleep so it cannot trip vTaskStepTick (#22637) 2026-11-17 11:30:00 +13:00
J. Nick Koston 86385ea2fe [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog at 57600 baud (#22641) 2026-11-17 11:28:34 +13:00
J. Nick Kostonandpre-commit-ci-lite[bot] 9bee9629c6 [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 11:27:26 +13:00
J. Nick Koston 422ba0662e [zephyr] Count micros() in microseconds and busy-wait in delayMicroseconds() (#22612) 2026-11-17 11:22:58 +13:00
J. Nick Koston 4b4d787884 [esphome] Load sha256 for OTA only when a password is configured (#22777) 2026-11-16 17:18:58 -05:00
J. Nick Koston 34d68a0fa0 [logger] Keep the log header write pointer in a register (#22820) 2026-11-16 16:15:35 -06:00
J. Nick Koston 7caa7de696 [ci] Build the two LVGL render tests from one shared fixture (#22793) 2026-11-16 16:50:48 -05:00
J. Nick Koston 0f90578733 Merge remote-tracking branch 'upstream/dev' into i2c-write-register-gather 2026-11-16 15:48:55 -06:00
J. Nick Koston 9b23184e10 [host][zephyr] Remove the ISR pin_mode copies the beta merge duplicated (#22823) 2026-11-16 15:41:53 -06:00
J. Nick Koston f7eb1c811e Merge remote-tracking branch 'upstream/dev' into i2c-write-register-gather
# Conflicts:
#	esphome/components/i2c/i2c_bus_arduino.cpp
2026-11-16 15:37:22 -06:00
Jesse Hills 2f9abefe3f Merge branch 'beta' into dev 2026-11-17 10:27:56 +13:00
Jesse Hills 84079c07e2 Merge pull request #22804 from esphome/bump-2026.11.0b5
2026.11.0b5
2026-11-17 10:27:35 +13:00
J. Nick Koston 110f854246 [ci] Run the benchmarks when logger changes (#22821) 2026-11-16 16:27:15 -05:00
J. Nick Koston b7dbf17469 [core] Brace the fast loop check in the unit test main (#22640) 2026-11-17 09:54:53 +13:00
Jesse Hills b91750c325 [tests] Add RawApiClient.read_frame for the serial proxy backpressure test
The serial proxy test from #22687 calls RawApiClient.read_frame, which was
added on dev as part of the store_yaml feature (#16445) and is not on this
release branch. Take tests/integration/raw_api_client.py from that PR so the
test can run; no firmware code changes.
2026-11-17 09:33:39 +13:00
Adam Matthews 6c5bdd9251 [wifi] Clear the error flag when the adapter restart is skipped (#22797) 2026-11-16 14:14:22 -06:00
J. Nick Koston 92d2a457fa [epaper_spi] Stop the fast loop after the fill tests (#22638) 2026-11-17 09:00:52 +13:00
dependabot[bot] be41bc41e4 Bump puremagic from 2.2.0 to 2.2.1 (#22812)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-16 19:45:14 +00:00
dependabot[bot] c0cf8f6b19 Bump smp from 4.2.0 to 4.3.0 (#22809)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-16 13:37:30 -06:00
dependabot[bot] 49d1f61df7 Bump pytest-asyncio from 1.4.1.post1 to 1.5.0 (#22813)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-16 13:37:07 -06:00
dependabot[bot]andesphome[bot] 95c67a5523 Bump ruff from 0.17.4 to 0.17.5 (#22810)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: esphome[bot] <115708604+esphome[bot]@users.noreply.github.com>
2026-11-16 13:35:59 -06:00
Jonathan Swoboda 8045a11909 [esp32_ble] Apply the Bluedroid workarounds to the ESP-IDF 6.1 releases that need them (#22806) 2026-11-16 14:34:54 -05:00
esphome[bot] 208d0021a9 Bump aioesphomeapi from 46.30.0 to 46.30.1 (#22807)
Co-authored-by: esphome[bot] <115708604+esphome[bot]@users.noreply.github.com>
2026-11-16 19:34:07 +00:00
Jonathan Swoboda 1da90be339 [esp32] Pin the vasprintf stub tests to a newlib ESP-IDF (#22808) 2026-11-16 14:28:00 -05:00
Jonathan Swoboda 4b48ff0255 [esp32_ble] Replace Bluedroid's sscanf callers on ESP-IDF 6 too (#22805) 2026-11-16 14:12:05 -05:00
Jonathan Swoboda fed2b2995e [esp32] Replace arduino-esp32's libsodium through the manifest overrides field (#22799) 2026-11-16 14:10:15 -05:00
J. Nick Koston ae48c7ab4c [logger] Share the per-platform copies and drop dead code (#22595) 2026-11-16 13:07:28 -06:00
J. Nick Koston 6f6e34ca40 [remote_base] Add decode and dump: all benchmarks (#22753) 2026-11-16 13:45:38 -05:00
J. Nick Koston 0561d90334 [i2c] Refuse RP2040 writes larger than the Wire buffer instead of leaving the bus stuck (#22791) 2026-11-16 13:41:43 -05:00
J. Nick Koston 78ef1fd104 [ci] Share the integration builds of fixtures that are identical (#22795) 2026-11-16 13:41:10 -05:00
J. Nick Koston a6bca49020 [ci] Leave deleted integration test files out of the test buckets (#22802) 2026-11-16 18:36:09 +00:00
Jonathan Swoboda 2e68c56908 [mlx90393] Enable the Wire library on ESP32 Arduino (#22801) 2026-11-16 13:30:46 -05:00
Jesse Hills a1fecebb09 Bump version to 2026.11.0b5 2026-11-17 07:30:12 +13:00
J. Nick Koston 32b9d4cbe7 [web_server_base] Bump ESPAsyncWebServer to 3.12.1 (#22682) 2026-11-17 07:30:09 +13:00
Chris c53401a28d [ethernet] Notify IP state listeners from the main loop (#22657) 2026-11-17 07:30:09 +13:00
Miguel Angel Nubla 6b7d17c762 [wifi] Leave the AP before restarting on ESP32 (#22715) 2026-11-17 07:30:09 +13:00
J. Nick Koston 93a3306d82 [libretiny] Free closed TCP connections after about 1 s instead of 120 s (#22696) 2026-11-17 07:30:09 +13:00
J. Nick Koston 54d3477240 [bluetooth_connection] Keep the top half of 32-bit GATT UUIDs on RP2 (#22679) 2026-11-17 07:30:09 +13:00
J. Nick Koston 5f9d83d293 [async_tcp] Use the esphome-libs RPAsyncTCP fork so SSE streams do not stall on RP2040 (#22686) 2026-11-17 07:30:09 +13:00
J. Nick Koston 43864283b4 [web_server_base] Check Basic auth without linking the library's Digest code (#22684) 2026-11-17 07:30:09 +13:00
J. Nick Koston 4efbb38b86 [core] Lock the scheduler against lwIP callbacks on RP2 (#22688) 2026-11-17 07:30:09 +13:00
Keith Burzinski 045374965f [serial_proxy] Keep received bytes when the client's connection is blocked (#22687) 2026-11-17 07:30:09 +13:00
Craig Andrews 39a939720f [epaper_spi] Point the UC8279 gate-count error at the height (#22628) 2026-11-17 07:30:09 +13:00
esphome[bot] a79e51e784 Bump bundled esphome-device-builder to 1.28.1 (#22630)
Co-authored-by: esphome[bot] <115708604+esphome[bot]@users.noreply.github.com>
2026-11-17 07:29:59 +13:00
Chris 517f0d6d48 [usb_host] Respect explicit control transfer size (#22629) 2026-11-17 07:29:14 +13:00
Craig Andrews 1327d0ddc5 [epaper_spi] Mark the frame drawn after fill() (#21505) 2026-11-17 07:29:14 +13:00
J. Nick Koston 2adb544e7a [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog above 19200 baud (#22603) 2026-11-17 07:29:14 +13:00
J. Nick Koston 48905beb96 [zephyr] Add ISR pin_mode so dht links on nRF52 2026-11-17 07:29:14 +13:00
J. Nick Koston ed401814bf [dht] Negate sign-and-magnitude negative temperatures instead of inverting them (#22615) 2026-11-17 07:29:14 +13:00
J. Nick Koston 0245db6285 [host] Add the empty ISRInternalGPIOPin::pin_mode (#22616) 2026-11-17 07:29:14 +13:00
J. Nick Koston 07ee0f9f04 [logger] Fix LibreTiny task log messages landing unaligned and out of step (#22594) 2026-11-17 07:29:14 +13:00
Jesse HillsandJ. Nick Koston 3d34ad572b [api] Send the platform of each wizard entity (#22580)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-17 07:29:13 +13:00
Jonathan Swoboda 5c9033e04d [neopixelbus] Remove ESP32 support (#22796) 2026-11-16 13:11:50 -05:00
Jonathan Swoboda e91934e4bd [ethernet] Return espressif/w5500 to 1.0.1 (#22792) 2026-11-16 11:27:13 -05:00
esphome[bot] 602cbff184 [ci] Refresh integration test durations (#22783)
Co-authored-by: esphome[bot] <115708604+esphome[bot]@users.noreply.github.com>
2026-11-16 09:44:39 -06:00
w1ll14m da274f92d3 [duco] Extend text_sensor with version, error, uptime and node type queries (#22560) 2026-11-16 08:57:52 -06:00
c6f330458a [tcp] Add TCP packet interface link (#21119)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-16 04:36:50 +00:00
J. Nick Koston 8e95c9b0a6 Skip the prefix memcpy for an empty prefix in the default write_prefixed 2026-11-15 21:21:38 -06:00
Clyde StubbsandJ. Nick Koston dbb4ba769a [sx126x][sx127x] Packet interface links for SX126x and SX127x (#21110)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-16 14:19:19 +11:00
J. Nick Kostonandclydebarrow 0eb4a09935 [sx127x] Write multi-byte settings in one SPI burst (#22776)
Co-authored-by: clydebarrow <2366188+clydebarrow@users.noreply.github.com>
2026-11-16 14:16:55 +11:00
J. Nick Koston c09d677ed2 Force the ESP-IDF write job helper inline 2026-11-15 21:14:54 -06:00
J. Nick Koston b6d5777876 Merge the ESP-IDF probe branch, skip the empty prefix write and use memcpy in the fallback 2026-11-15 21:12:00 -06:00
J. Nick Koston b59e822cda Write I2C register writes without copying them into a heap buffer 2026-11-15 21:02:22 -06:00
Clyde Stubbs ed9e5cff58 [sx127x] Set rx_floor in the unit test radio (#22779) 2026-11-15 20:31:44 -06:00
J. Nick Koston 7acd023079 [web_server_base] Bump ESPAsyncWebServer to 3.12.1 (#22682) 2026-11-16 13:43:15 +13:00
Clyde Stubbs 5623a5d511 [sx127x] Add async sends and failure recovery (#22733) 2026-11-15 23:52:31 +00:00
J. Nick Koston 4f8c2239dd [components] Use put_be16 and the other byte helpers in more drivers (#22771) 2026-11-15 23:32:08 +00:00
Mark Mayo 07bbad4061 [esp32] Import the SBOM writer only when generating the build (#22702) 2026-11-15 16:50:14 -06:00
Mark Mayo 1cd99ce6d6 [core] Import url2pathname only where a file URL is converted (#22703) 2026-11-15 16:50:04 -06:00
Mark Mayo 91db9d86d0 [debug] Import the nrf52 helper only when building for Zephyr (#22701) 2026-11-15 16:42:23 -06:00
Tanguy Pruvot 2f900f23d7 [cst3240] Add the Hynitron CST3240 touchscreen (#22601) 2026-11-15 12:20:54 -06:00
373224c141 [npm1300] Add the Nordic nPM1300 PMIC component (#22661)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-15 12:52:15 +01:00
Hajo Noerenberg 1dff22f578 [cc1101] Add long packet support, plus a lambda packet_length for unknown-length packets (#17578) 2026-11-14 21:43:21 -06:00
Vinicius FortunaandClyde Stubbs c2eb540b37 [sx126x] Refactor/sx126x radio lifecycle (#22197)
Co-authored-by: Clyde Stubbs <2366188+clydebarrow@users.noreply.github.com>
2026-11-15 13:17:23 +11:00
J. Nick Kostonandclydebarrow fad21e3f14 [cstxxx] Share the Hynitron 16-bit register touchscreen code (#22718)
Co-authored-by: clydebarrow <2366188+clydebarrow@users.noreply.github.com>
2026-11-15 02:11:09 +00:00
Rodrigoah 904f0df920 [whirlpool] Add the Hitachi HCRA31NEWH model (#22704) 2026-11-14 14:23:51 -06:00
Chris 7128d22f07 [ethernet] Notify IP state listeners from the main loop (#22657) 2026-11-14 13:22:11 -06:00
Miguel Angel Nubla 825e2c3dd0 [wifi] Leave the AP before restarting on ESP32 (#22715) 2026-11-14 18:05:42 +00:00
324 changed files with 13970 additions and 2873 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ ci:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.17.4
rev: v0.17.5
hooks:
# Run the linter.
- id: ruff
+8 -1
View File
@@ -146,9 +146,11 @@ esphome/components/cover/* @esphome/core
esphome/components/cs5460a/* @balrog-kun
esphome/components/cse7761/* @berfenger
esphome/components/cst226/* @clydebarrow
esphome/components/cst3240/* @tpruvot
esphome/components/cst328/* @latonita
esphome/components/cst816/* @clydebarrow
esphome/components/cst9220/* @clydebarrow
esphome/components/cstxxx/* @clydebarrow @latonita
esphome/components/ct_clamp/* @jesserockz
esphome/components/current_based/* @djwmarcx
esphome/components/cw2017/* @exciton
@@ -466,6 +468,7 @@ esphome/components/nfc/* @jesserockz @kbx81
esphome/components/noblex/* @AGalfra
esphome/components/noise/* @esphome/core
esphome/components/npi19/* @bakerkj
esphome/components/npm1300/* @tomaszduda23
esphome/components/nrf52/* @tomaszduda23
esphome/components/ns2009/* @tchilov
esphome/components/ns2009/touchscreen/* @tchilov
@@ -648,7 +651,9 @@ esphome/components/sun_gtil2/* @Mat931
esphome/components/switch/* @esphome/core
esphome/components/switch/binary_sensor/* @ssieb
esphome/components/sx126x/* @swoboda1337
esphome/components/sx126x/packet_interface/* @clydebarrow
esphome/components/sx127x/* @swoboda1337
esphome/components/sx127x/packet_interface/* @clydebarrow
esphome/components/sy6970/* @linkedupbits
esphome/components/syslog/* @clydebarrow
esphome/components/systa_bus/* @Mat931
@@ -660,6 +665,8 @@ esphome/components/tca8418/* @zebble
esphome/components/tca9548a/* @andreashergert1984
esphome/components/tca9555/* @mobrembski
esphome/components/tcl112/* @glmnet
esphome/components/tcp/* @clydebarrow
esphome/components/tcp/packet_interface/* @clydebarrow
esphome/components/tcp_uart/* @Bascht74
esphome/components/tee501/* @Stock-M
esphome/components/teleinfo/* @0hax @FredM67
@@ -741,7 +748,7 @@ esphome/components/web_server_idf/* @dentra
esphome/components/weikai/* @DrCoolZic
esphome/components/weikai_i2c/* @DrCoolZic
esphome/components/weikai_spi/* @DrCoolZic
esphome/components/whirlpool/* @arpena @glmnet
esphome/components/whirlpool/* @arpena @glmnet @Rodrigoah
esphome/components/whynter/* @aeonsablaze
esphome/components/wiegand/* @ssieb
esphome/components/wireguard/* @droscy @lhoracek @thomas0bernard
+2 -1
View File
@@ -802,8 +802,9 @@ class APIConnection final : public APIServerConnectionBase {
}
// Helper function to schedule a high priority message at the front of the batch
// Out-of-line: callers (on_shutdown, check_keepalive_) are cold paths
// Out-of-line: callers (send_shutdown_disconnect_, check_keepalive_) are cold paths
bool schedule_message_front_(EntityBase *entity, uint16_t message_type, uint8_t estimated_size);
void send_shutdown_disconnect_();
// Helper function to log client messages with name and peername
void log_client_(int level, const LogString *message);
@@ -278,10 +278,9 @@ APIError APINoiseFrameHelper::state_action_client_hello_() {
state_ = State::FAILED;
return APIError::OUT_OF_MEMORY;
}
dst[0] = (uint8_t) (rx_size >> 8);
dst[1] = (uint8_t) rx_size;
uint8_t *payload = put_be16(dst, rx_size);
if (rx_size > 0) {
std::memcpy(dst + 2, this->rx_buf_.data(), rx_size);
std::memcpy(payload, this->rx_buf_.data(), rx_size);
}
#ifdef USE_API_OUTGOING_CONNECTION
@@ -464,10 +463,8 @@ APIError APINoiseFrameHelper::encrypt_noise_message_(uint8_t *buf_start, uint16_
// Write message header (to be encrypted)
constexpr uint8_t msg_offset = noise::FRAME_HEADER_SIZE;
buf_start[msg_offset] = static_cast<uint8_t>(message_type >> 8); // type high byte
buf_start[msg_offset + 1] = static_cast<uint8_t>(message_type); // type low byte
buf_start[msg_offset + 2] = static_cast<uint8_t>(payload_size >> 8); // data_len high byte
buf_start[msg_offset + 3] = static_cast<uint8_t>(payload_size); // data_len low byte
put_be16(buf_start + msg_offset, message_type);
put_be16(buf_start + msg_offset + 2, payload_size);
// payload data is already in the buffer starting at offset + 7
// Encrypt the message in place
@@ -1,6 +1,7 @@
#include "api_overflow_buffer.h"
#ifdef USE_API
#include <cstring>
#include "esphome/core/helpers.h"
namespace esphome::api {
@@ -17,7 +18,7 @@ ssize_t APIOverflowBuffer::try_drain(socket::Socket *socket) {
while (this->count_ > 0) {
uint8_t *msg = this->buf_.data() + this->head_;
size_t len = msg[0] | (msg[1] << 8);
size_t len = encode_value_le<uint16_t>(msg);
ssize_t sent = socket->write(msg + LEN_PREFIX, len);
if (sent <= 0)
+28 -9
View File
@@ -4,6 +4,7 @@
#include <cinttypes>
#include <cstring>
#include "api_connection.h"
#include "api_connection_buffer.h"
#include "esphome/components/network/util.h"
#include "esphome/core/application.h"
#include "esphome/core/defines.h"
@@ -806,6 +807,31 @@ void APIServer::on_camera_image(const std::shared_ptr<camera::CameraImage> &imag
}
#endif
// Kept out of api_connection.cpp so GCC inlines its send path as before
void APIConnection::send_shutdown_disconnect_() {
#ifndef USE_DEEP_SLEEP
// Queued states first: Home Assistant mishandles states after DisconnectRequest (#22610).
// Not with deep sleep: its entities stay available, and the disconnect must not wait on a slow link
this->flags_.state_subscription = false;
this->destroy_active_iterator_();
// process_batch_ first flushes any overflow without blocking; stop once the queue stops shrinking
for (size_t left = this->deferred_batch_.size(); left != 0;) {
this->process_batch_();
const size_t now_left = this->deferred_batch_.size();
if (now_left >= left)
break;
left = now_left;
}
#endif
DisconnectRequest req;
if (!this->send_message(req)) {
// tx buffer full: first in the queue, so a slow link still delivers it before the teardown timeout.
// Due at once: teardown does not advance the cached loop time the batch_delay gate reads
this->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
this->make_batch_due_now_();
}
}
void APIServer::on_shutdown() {
this->shutting_down_ = true;
@@ -818,15 +844,8 @@ void APIServer::on_shutdown() {
// Change batch delay to 5ms for quick flushing during shutdown
this->batch_delay_ = 5;
// Send disconnect requests to all connected clients
for (auto &c : this->active_clients()) {
DisconnectRequest req;
if (!c->send_message(req)) {
// If we can't send the disconnect request directly (tx_buffer full),
// schedule it at the front of the batch so it will be sent with priority
c->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
}
}
for (auto &c : this->active_clients())
c->send_shutdown_disconnect_();
}
bool APIServer::teardown() {
+5 -1
View File
@@ -35,7 +35,11 @@ async def to_code(config: ConfigType) -> None:
add_idf_component(name="esp32async/asynctcp", ref="3.4.91")
elif CORE.is_libretiny:
# https://github.com/ESP32Async/AsyncTCP
cg.add_library("ESP32Async/AsyncTCP", "3.4.5")
cg.add_library("ESP32Async/AsyncTCP", "3.5.0")
# AsyncTCP 3.5.0 debug logs call xPortGetCoreID(), which LibreTiny (single core) lacks; they are compiled
# in by LibreTiny's debug level or CONFIG_ASYNC_TCP_DEBUG, so the call always expands to int(), which is 0
# (a function-like -D does not survive PlatformIO's build flags)
cg.add_build_flag("-DxPortGetCoreID=int")
elif CORE.is_esp8266:
# https://github.com/ESP32Async/ESPAsyncTCP
cg.add_library("ESP32Async/ESPAsyncTCP", "2.0.0")
+1 -5
View File
@@ -35,13 +35,9 @@ BEDJET_CLIENT_SCHEMA = cv.Schema(
)
_register_child = cg.slot_list("BEDJET_CHILD_COUNT", "register_child", DOMAIN)
async def register_bedjet_child(var: MockObj, config: ConfigType) -> None:
parent = await cg.get_variable(config[CONF_BEDJET_ID])
await cg.register_parented(var, parent)
cg.add(_register_child(parent, var))
cg.add(parent.register_child(var))
async def to_code(config: ConfigType) -> None:
+5
View File
@@ -547,6 +547,11 @@ void BedJetHub::dispatch_status_() {
}
}
void BedJetHub::register_child(BedJetClient *obj) {
this->children_.push_back(obj);
obj->set_parent(this);
}
} // namespace esphome::bedjet
#endif
+5 -2
View File
@@ -6,10 +6,11 @@
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "bedjet_child.h"
#include "bedjet_codec.h"
#include <vector>
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
#include "esphome/core/time.h"
@@ -91,7 +92,8 @@ class BedJetHub final : public esphome::ble_client::BLEClientNode, public Pollin
bool has_status() { return this->codec_->has_status(); }
const BedjetStatusPacket *get_status_packet() const { return this->codec_->get_status_packet(); }
SLOT_LIST(BedJetClient, children_, register_child, BEDJET_CHILD_COUNT)
/** Register a `BedJetClient` child component. */
void register_child(BedJetClient *obj);
/** Set the status timeout.
*
@@ -125,6 +127,7 @@ class BedJetHub final : public esphome::ble_client::BLEClientNode, public Pollin
esp_ble_gattc_cb_param_t *param) override;
protected:
std::vector<BedJetClient *> children_;
void dispatch_status_();
void dispatch_state_(bool is_ready);
@@ -2,6 +2,7 @@
#include <algorithm>
#include <cstring>
#include "esphome/core/helpers.h"
namespace esphome::ble_device_base {
@@ -163,8 +164,7 @@ bool aes_ccm_auth_decrypt(const uint8_t key[16], const uint8_t *nonce, size_t no
if (aad_len > 0) {
// Only the < 2^16-2^8 encoding is needed for BLE-sized AAD.
uint8_t blk[16] = {0};
blk[0] = static_cast<uint8_t>((aad_len >> 8) & 0xff);
blk[1] = static_cast<uint8_t>(aad_len & 0xff);
put_be16(blk, aad_len);
size_t ai = 0;
size_t pos = 2;
while (pos < 16 && ai < aad_len)
+42 -7
View File
@@ -1,3 +1,5 @@
from typing import Any
from esphome import automation, pins
from esphome.automation import maybe_simple_id
import esphome.codegen as cg
@@ -13,6 +15,7 @@ from esphome.const import (
CONF_VALUE,
CONF_WAIT_TIME,
)
from esphome.types import ConfigType
CODEOWNERS = ["@lygris", "@gabest11"]
DEPENDENCIES = ["spi"]
@@ -22,6 +25,8 @@ MULTI_CONF = True
ns = cg.esphome_ns.namespace("cc1101")
CC1101Component = ns.class_("CC1101Component", cg.Component, spi.SPIDevice)
CC1101Listener = ns.class_("CC1101Listener")
PACKET_TYPE = cg.std_vector.template(cg.uint8)
RX_FIFO_SIZE = 64
# Config keys
CONF_RX_ATTENUATION = "rx_attenuation"
@@ -241,20 +246,34 @@ CONFIG_MAP = {
cv.Optional(CONF_BS_POST_KI): cv.enum(BS_POST_KI, upper=False),
cv.Optional(CONF_BS_POST_KP): cv.enum(BS_POST_KP, upper=False),
cv.Optional(CONF_PACKET_MODE, default=False): cv.boolean,
cv.Optional(CONF_PACKET_LENGTH): cv.uint8_t,
cv.Optional(CONF_CRC_ENABLE, default=False): cv.boolean,
cv.Optional(CONF_WHITENING, default=False): cv.boolean,
}
def _validate_packet_mode(config):
if config.get(CONF_PACKET_MODE, False):
def _is_long_packet(packet_length: Any) -> bool:
"""A packet_length that does not fit the RX FIFO, or is a lambda."""
return cg.is_template(packet_length) or (packet_length or 0) > RX_FIFO_SIZE
def _validate_packet_mode(config: ConfigType) -> ConfigType:
packet_mode = config.get(CONF_PACKET_MODE, False)
packet_length = config.get(CONF_PACKET_LENGTH)
if packet_mode:
if CONF_GDO0_PIN not in config:
raise cv.Invalid("gdo0_pin is required when packet_mode is enabled")
if CONF_PACKET_LENGTH not in config:
if packet_length is None:
raise cv.Invalid("packet_length is required when packet_mode is enabled")
if config[CONF_PACKET_LENGTH] > 64:
raise cv.Invalid("packet_length must be <= 64 (FIFO size)")
elif cg.is_template(packet_length):
raise cv.Invalid("packet_mode is required when packet_length is a lambda")
if (
packet_mode
and _is_long_packet(packet_length)
and config.get(CONF_CRC_ENABLE, False)
):
raise cv.Invalid(
"crc_enable is not supported with packet_length > 64 or a lambda"
)
return config
@@ -263,6 +282,9 @@ CONFIG_SCHEMA = cv.All(
{
cv.GenerateID(): cv.declare_id(CC1101Component),
cv.Optional(CONF_GDO0_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_PACKET_LENGTH): cv.templatable(
cv.int_range(min=0, max=1024)
),
cv.Optional(CONF_ON_PACKET): automation.validate_automation(single=True),
}
)
@@ -282,11 +304,24 @@ async def to_code(config):
cg.add(getattr(var, f"set_{key}")(config[key]))
await cg.add_pin(var.set_gdo0_pin, config.get(CONF_GDO0_PIN))
if (packet_length := config.get(CONF_PACKET_LENGTH)) is not None:
# packet_mode can also be switched on at run time, so this does not check it
if _is_long_packet(packet_length):
cg.add_define("USE_CC1101_LONG_PACKET")
if cg.is_template(packet_length):
lambda_ = await cg.process_lambda(
packet_length,
[(PACKET_TYPE.operator("ref").operator("const"), "x")],
return_type=cg.int32,
)
cg.add(var.set_packet_length_lambda(lambda_))
else:
cg.add(var.set_packet_length(packet_length))
if CONF_ON_PACKET in config:
await automation.build_automation(
var.get_packet_trigger(),
[
(cg.std_vector.template(cg.uint8), "x"),
(PACKET_TYPE, "x"),
(cg.float_, "freq_offset"),
(cg.float_, "rssi"),
(cg.uint8, "lqi"),
+361 -33
View File
@@ -1,8 +1,10 @@
#include "cc1101.h"
#include "cc1101pa.h"
#include "esphome/core/application.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#include <algorithm>
#include <cmath>
#include <cstring>
@@ -14,9 +16,15 @@ namespace esphome::cc1101 {
ESPHOME_LOG_TAG(TAG, "cc1101");
static constexpr size_t TX_FIFO_SIZE = 64;
static constexpr size_t RX_FIFO_SIZE = 64;
// RX FIFO threshold for FIFO_THR = 7 in long packet mode
static constexpr uint8_t RX_FIFO_THRESHOLD = 32;
// The crystal takes about 150 us to start after CSn goes low
static constexpr uint32_t WAKEUP_DELAY_US = 200;
static float freq_offset_hz(uint8_t freqest) { return static_cast<int8_t>(freqest) * (XTAL_FREQUENCY / (1 << 14)); }
static float rssi_dbm(int8_t rssi) { return (rssi * RSSI_STEP) - RSSI_OFFSET; }
// MDMCFG2 MOD_FORMAT values
PROGMEM_STRING_TABLE(ModulationStrings, "2-FSK", "GFSK", "UNUSED", "ASK/OOK", "4-FSK", "UNUSED", "UNUSED", "MSK");
@@ -114,8 +122,6 @@ CC1101Component::CC1101Component() {
memset(this->pa_table_, 0, sizeof(this->pa_table_));
}
void IRAM_ATTR CC1101Component::gpio_intr(CC1101Component *arg) { arg->enable_loop_soon_any_context(); }
void CC1101Component::setup() {
this->spi_setup();
@@ -193,7 +199,220 @@ void CC1101Component::call_listeners_(const std::vector<uint8_t> &packet, float
this->packet_trigger_.trigger(packet, freq_offset, rssi, lqi);
}
float CC1101Component::symbol_rate_() const {
return (((256.0f + this->state_.DRATE_M) * (1 << this->state_.DRATE_E)) / (1 << 28)) * XTAL_FREQUENCY;
}
#ifdef USE_CC1101_LONG_PACKET
bool CC1101Component::is_long_packet_mode_() const {
return this->packet_mode_ && (this->packet_length_ > RX_FIFO_SIZE || this->packet_length_func_ != nullptr);
}
void CC1101Component::arm_length_(uint16_t length) {
// Over 255 bytes or unknown starts in infinite mode (datasheet section 15.2.2). PKTLEN must not be 0, so a
// multiple of 256 stays in infinite mode and ends on the MCU byte count alone.
this->packet_expected_length_ = length;
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(length > 0 && length < 256 ? LengthConfig::LENGTH_CONFIG_FIXED
: LengthConfig::LENGTH_CONFIG_INFINITE);
this->state_.PKTLEN = length % 256 == 0 ? 0xFF : static_cast<uint8_t>(length % 256);
}
void CC1101Component::reset_long_packet_rx_() {
this->packet_.clear();
this->packet_last_byte_ms_ = 0;
this->high_freq_.stop();
this->arm_length_(this->packet_length_func_ != nullptr ? 0 : this->packet_length_);
}
void CC1101Component::restart_long_packet_rx_() {
this->enter_idle_();
this->enter_rx_();
this->disable_loop();
}
void CC1101Component::maybe_switch_long_packet_to_fixed_() {
const uint16_t expected = this->packet_expected_length_;
if (this->state_.LENGTH_CONFIG == static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED) || expected == 0 ||
expected % 256 == 0) {
return;
}
const uint16_t received = this->packet_.size();
if (expected - received >= 256) {
return;
}
// PKTLEN keeps the (length % 256) set at the start, as in TI Design Note DN500 section 2.3
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED);
this->write_(Register::PKTCTRL0);
ESP_LOGVV(TAG, "Switched long packet RX to fixed mode: received=%u expected=%u pktlen=%u", received, expected,
this->state_.PKTLEN);
}
void CC1101Component::finish_long_packet_() {
this->packet_.resize(this->packet_expected_length_);
this->read_(Register::FREQEST);
this->read_(Register::LQI);
const float freq_offset = freq_offset_hz(this->state_.FREQEST);
const uint8_t lqi = this->state_.LQI & STATUS_LQI_MASK;
// No CRC check: crc_enable is rejected for long packets, CRC_OK is only set after the last payload byte.
// Restart RX before dispatching so a callback may change settings; swapping back keeps the reserved capacity
// unless a callback reserved a larger buffer.
std::vector<uint8_t> packet;
packet.swap(this->packet_);
this->restart_long_packet_rx_();
this->call_listeners_(packet, freq_offset, rssi_dbm(this->long_packet_rssi_), lqi);
if (packet.capacity() > this->packet_.capacity()) {
packet.clear();
this->packet_.swap(packet);
}
}
void CC1101Component::handle_long_packet_(uint8_t rx_bytes) {
// Leave one byte in the FIFO unless it holds the rest of the packet (datasheet section 20)
uint16_t to_read = rx_bytes > 0 ? rx_bytes - 1 : 0;
if (this->packet_expected_length_ > 0) {
const uint16_t remaining = this->packet_expected_length_ - this->packet_.size();
if (remaining <= rx_bytes) {
to_read = remaining;
}
}
if (to_read == 0) {
if (this->packet_.empty()) {
return;
}
// Discard a packet when no byte arrived for the air time of PACKET_IDLE_TIMEOUT_BYTES
const uint32_t timeout_ms =
std::max(static_cast<uint32_t>(std::ceil((8.0f * PACKET_IDLE_TIMEOUT_BYTES * 1000.0f) / this->symbol_rate_())),
PACKET_IDLE_TIMEOUT_MIN_MS);
if (App.get_loop_component_start_time() - this->packet_last_byte_ms_ > timeout_ms) {
ESP_LOGW(TAG, "Packet receive timeout, discarding packet: received=%u expected=%u fifo=%u",
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
this->restart_long_packet_rx_();
}
return;
}
const size_t old_size = this->packet_.size();
if (old_size == 0) {
// The RSSI register follows the live signal; sample it while the packet is still on air
this->read_(Register::RSSI);
this->long_packet_rssi_ = this->state_.RSSI;
// The FIFO threshold signal does not fire for the bytes after the last threshold crossing; poll until done
this->high_freq_.start();
}
// Read through an aligned buffer: for an unaligned target the ESP32 SPI driver allocates a bounce buffer
alignas(4) uint8_t staged[RX_FIFO_SIZE];
this->read_(Register::FIFO, staged, to_read);
this->packet_.resize(old_size + to_read);
std::memcpy(this->packet_.data() + old_size, staged, to_read);
this->packet_last_byte_ms_ = App.get_loop_component_start_time();
ESP_LOGVV(TAG, "Drained RX FIFO: read=%u received=%u expected=%u fifo=%u", to_read,
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
if (this->packet_expected_length_ == 0 && this->packet_length_func_ != nullptr) {
const int32_t length = this->packet_length_func_(this->packet_);
if (length < 0) {
ESP_LOGVV(TAG, "Packet length lambda discarded packet: received=%u", static_cast<uint16_t>(this->packet_.size()));
this->restart_long_packet_rx_();
return;
}
if (length > MAX_PACKET_LENGTH) {
ESP_LOGW(TAG, "Packet length exceeds maximum, discarding packet: length=%" PRId32 " max=%u", length,
MAX_PACKET_LENGTH);
this->restart_long_packet_rx_();
return;
}
if (length > 0) {
this->arm_length_(static_cast<uint16_t>(length));
// A packet shorter than the first FIFO drain is already complete; finish_long_packet_() truncates it
if (this->packet_expected_length_ <= this->packet_.size()) {
this->finish_long_packet_();
return;
}
this->write_(Register::PKTLEN);
this->write_(Register::PKTCTRL0);
ESP_LOGVV(TAG, "Resolved packet length: received=%u expected=%u pktlen=%u",
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, this->state_.PKTLEN);
}
}
// Only reachable while the length is still unknown; a known length caps every read
if (this->packet_.size() > MAX_PACKET_LENGTH) {
ESP_LOGW(TAG, "Packet length exceeds maximum, discarding packet: length=%u max=%u",
static_cast<uint16_t>(this->packet_.size()), MAX_PACKET_LENGTH);
this->restart_long_packet_rx_();
return;
}
this->maybe_switch_long_packet_to_fixed_();
if (this->packet_expected_length_ > 0 && this->packet_.size() >= this->packet_expected_length_) {
this->finish_long_packet_();
}
}
void CC1101Component::loop_long_packet_() {
if (this->sleeping_ || this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO) ||
this->gdo0_pin_ == nullptr) {
this->high_freq_.stop();
this->disable_loop();
return;
}
// While GDO0 (RX FIFO threshold) is high, the FIFO holds at least RX_FIFO_THRESHOLD bytes, so drain without
// reading RXBYTES. At high data rates RXBYTES changes between two reads, so waiting for two reads that agree
// and retrying on the next loop pass lets the FIFO overflow. MARCSTATE does not change during RX.
for (uint8_t i = 0; i < RX_FIFO_SIZE / RX_FIFO_THRESHOLD + 2 && this->gdo0_pin_->digital_read(); i++) {
this->read_(Register::MARCSTATE);
if (static_cast<State>(this->state_.MARC_STATE) == State::RXFIFO_OVERFLOW) {
ESP_LOGW(TAG, "RX FIFO overflow, discarding packet: received=%u expected=%u",
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_);
this->restart_long_packet_rx_();
return;
}
this->handle_long_packet_(RX_FIFO_THRESHOLD);
if (this->packet_.empty()) {
return; // finished or discarded
}
}
// Below the threshold the next crossing raises GDO0 again, and after the packet the count no longer changes,
// so retrying on the next loop pass is safe here. RXBYTES can be misread while bytes arrive (TI SWRZ020), so
// only trust two consecutive reads that agree.
this->read_(Register::RXBYTES);
uint8_t rx_bytes = this->state_.RXBYTES;
bool stable = false;
for (uint8_t retries = RXBYTES_STABLE_RETRIES; retries > 0 && !stable; retries--) {
const uint8_t previous = rx_bytes;
this->read_(Register::RXBYTES);
rx_bytes = this->state_.RXBYTES;
stable = rx_bytes == previous;
}
if (!stable) {
return;
}
rx_bytes = this->state_.NUM_RXBYTES;
// More than the FIFO holds can only be a misread; the staged drain buffer is FIFO sized
if (this->state_.RXFIFO_OVERFLOW || rx_bytes > RX_FIFO_SIZE) {
ESP_LOGW(TAG, "RX FIFO overflow, discarding packet: received=%u expected=%u fifo=%u",
static_cast<uint16_t>(this->packet_.size()), this->packet_expected_length_, rx_bytes);
this->restart_long_packet_rx_();
return;
}
if (rx_bytes == 0 && this->packet_.empty() && !this->gdo0_pin_->digital_read()) {
this->disable_loop();
return;
}
this->handle_long_packet_(rx_bytes);
}
#endif
void CC1101Component::loop() {
#ifdef USE_CC1101_LONG_PACKET
if (this->is_long_packet_mode_()) {
this->loop_long_packet_();
return;
}
#endif
this->disable_loop();
if (this->sleeping_ || this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO) ||
this->gdo0_pin_ == nullptr || !this->gdo0_pin_->digital_read()) {
@@ -211,6 +430,14 @@ void CC1101Component::loop() {
this->enter_rx_();
return;
}
// GDO0 also rises when the FIFO fills, which for a 64 byte packet is before the CRC has arrived
if (rx_bytes == RX_FIFO_SIZE) {
this->read_(Register::MARCSTATE);
if (static_cast<State>(this->state_.MARC_STATE) == State::RX) {
this->enable_loop();
return;
}
}
// Read packet
uint8_t payload_length, expected_rx;
@@ -221,7 +448,7 @@ void CC1101Component::loop() {
payload_length = this->state_.PKTLEN;
expected_rx = payload_length;
}
if (payload_length == 0 || payload_length > 64 || rx_bytes != expected_rx) {
if (payload_length == 0 || payload_length > RX_FIFO_SIZE || rx_bytes != expected_rx) {
ESP_LOGW(TAG, "Invalid packet: rx_bytes %u, payload_length %u", rx_bytes, payload_length);
this->enter_idle_();
this->strobe_(Command::FRX);
@@ -235,8 +462,8 @@ void CC1101Component::loop() {
this->read_(Register::FREQEST);
this->read_(Register::RSSI);
this->read_(Register::LQI);
float freq_offset = static_cast<int8_t>(this->state_.FREQEST) * (XTAL_FREQUENCY / (1 << 14));
float rssi = (this->state_.RSSI * RSSI_STEP) - RSSI_OFFSET;
float freq_offset = freq_offset_hz(this->state_.FREQEST);
float rssi = rssi_dbm(this->state_.RSSI);
bool crc_ok = (this->state_.LQI & STATUS_CRC_OK_MASK) != 0;
uint8_t lqi = this->state_.LQI & STATUS_LQI_MASK;
if (this->state_.CRC_EN == 0 || crc_ok) {
@@ -256,7 +483,7 @@ void CC1101Component::loop() {
void CC1101Component::dump_config() {
int32_t freq = static_cast<int32_t>(this->state_.FREQ2 << 16 | this->state_.FREQ1 << 8 | this->state_.FREQ0) *
XTAL_FREQUENCY / (1 << 16);
float symbol_rate = (((256.0f + this->state_.DRATE_M) * (1 << this->state_.DRATE_E)) / (1 << 28)) * XTAL_FREQUENCY;
float symbol_rate = this->symbol_rate_();
float bw = XTAL_FREQUENCY / (8.0f * (4 + this->state_.CHANBW_M) * (1 << this->state_.CHANBW_E));
ESP_LOGCONFIG(TAG,
"CC1101:\n"
@@ -271,6 +498,20 @@ void CC1101Component::dump_config() {
LOG_STR_ARG(ModulationStrings::get_log_str(this->state_.MOD_FORMAT & 0x07, 0)), symbol_rate, bw,
this->output_power_effective_);
LOG_PIN(" CS Pin: ", this->cs_);
LOG_PIN(" GDO0 Pin: ", this->gdo0_pin_);
if (this->packet_mode_) {
#ifdef USE_CC1101_LONG_PACKET
if (this->packet_length_func_ != nullptr) {
ESP_LOGCONFIG(TAG, " Packet Length: lambda");
} else
#endif
if (this->packet_length_ == 0) {
ESP_LOGCONFIG(TAG, " Packet Length: variable");
} else {
ESP_LOGCONFIG(TAG, " Packet Length: %u", this->packet_length_);
}
}
}
void CC1101Component::begin_tx() {
@@ -316,6 +557,14 @@ void CC1101Component::reset() {
void CC1101Component::set_idle() {
ESP_LOGV(TAG, "Setting IDLE state");
this->enter_idle_();
#ifdef USE_CC1101_LONG_PACKET
if (this->is_long_packet_mode_()) {
// Drop a partial packet so a pending loop pass cannot finish it and re-enter RX
this->strobe_(Command::FRX);
this->reset_long_packet_rx_();
this->disable_loop();
}
#endif
}
void CC1101Component::power_down() {
@@ -393,7 +642,18 @@ void CC1101Component::enter_idle_() {
}
}
bool CC1101Component::enter_rx_() { return this->enter_calibrated_(State::RX, Command::RX); }
bool CC1101Component::enter_rx_() {
#ifdef USE_CC1101_LONG_PACKET
if (this->is_long_packet_mode_()) {
// Every RX entry starts a fresh long packet; callers leave the chip in IDLE, where SFRX is allowed
this->strobe_(Command::FRX);
this->reset_long_packet_rx_();
this->write_(Register::PKTLEN);
this->write_(Register::PKTCTRL0);
}
#endif
return this->enter_calibrated_(State::RX, Command::RX);
}
bool CC1101Component::enter_tx_() { return this->enter_calibrated_(State::TX, Command::TX); }
@@ -456,12 +716,22 @@ void CC1101Component::read_(Register reg, uint8_t *buffer, size_t length) {
CC1101Error CC1101Component::transmit_packet(const uint8_t *data, size_t len) {
if (this->state_.PKT_FORMAT != static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
ESP_LOGW(TAG, "Cannot transmit packet: packet mode is not FIFO");
return CC1101Error::PARAMS;
}
#ifdef USE_CC1101_LONG_PACKET
// Long packet TX needs chunked FIFO refills and is not implemented
if (this->is_long_packet_mode_()) {
ESP_LOGW(TAG, "Cannot transmit packet: long packet mode is RX-only");
return CC1101Error::PARAMS;
}
#endif
const bool variable = this->state_.LENGTH_CONFIG == static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE);
// In variable length mode the FIFO also holds the length byte
if (len + (variable ? 1 : 0) > TX_FIFO_SIZE) {
ESP_LOGE(TAG, "Packet of %u bytes does not fit the TX FIFO", static_cast<unsigned>(len));
ESP_LOGW(TAG,
"Cannot transmit packet: long packet TX is not implemented, payload length %u exceeds TX FIFO limit %u",
static_cast<unsigned>(len), static_cast<unsigned>(TX_FIFO_SIZE));
return CC1101Error::PARAMS;
}
@@ -834,19 +1104,60 @@ void CC1101Component::set_bs_post_kp(BsPostKp value) {
}
}
void CC1101Component::set_packet_mode(bool value) {
this->state_.PKT_FORMAT =
static_cast<uint8_t>(value ? PacketFormat::PACKET_FORMAT_FIFO : PacketFormat::PACKET_FORMAT_ASYNC_SERIAL);
if (value) {
// Configure GDO0 for FIFO status (asserts on RX FIFO threshold or end of packet)
this->state_.GDO0_CFG = 0x01;
// Set max RX FIFO threshold to ensure we only trigger on end-of-packet
this->state_.FIFO_THR = 15;
// Don't append status bytes to FIFO - we read from registers instead
this->state_.APPEND_STATUS = 0;
} else {
// Configure GDO0 for serial data (async serial mode)
void CC1101Component::configure_packet_mode_() {
#ifdef USE_CC1101_LONG_PACKET
// Ends a long reception in progress, also when switching to a short packet mode
this->high_freq_.stop();
this->packet_.clear();
#endif
if (!this->packet_mode_) {
this->state_.PKT_FORMAT = static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_ASYNC_SERIAL);
this->state_.GDO0_CFG = 0x0D;
} else {
this->state_.PKT_FORMAT = static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
this->state_.APPEND_STATUS = 0;
#ifdef USE_CC1101_LONG_PACKET
if (this->is_long_packet_mode_()) {
// Threshold-only signal, reasserts after each partial FIFO drain
this->state_.GDO0_CFG = 0x00;
this->state_.FIFO_THR = 7;
// Reserve once so receiving never allocates; a lambda may read one FIFO drain past MAX_PACKET_LENGTH
this->packet_.reserve(this->packet_length_func_ != nullptr ? MAX_PACKET_LENGTH + RX_FIFO_SIZE
: this->packet_length_);
this->reset_long_packet_rx_();
} else
#endif
{
this->state_.GDO0_CFG = 0x01;
this->state_.FIFO_THR = 15;
if (this->packet_length_ == 0) {
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE);
} else {
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED);
this->state_.PKTLEN = static_cast<uint8_t>(this->packet_length_);
}
}
}
if (this->initialized_) {
this->write_(Register::PKTCTRL0);
this->write_(Register::PKTCTRL1);
this->write_(Register::PKTLEN);
this->write_(Register::IOCFG0);
this->write_(Register::FIFOTHR);
}
}
void CC1101Component::set_packet_mode(bool value) {
this->packet_mode_ = value;
#ifdef USE_CC1101_LONG_PACKET
// Long packet RX must drop the FIFO along with a partial packet, so go through IDLE and restart RX
if (this->initialized_ && this->is_long_packet_mode_()) {
this->reconfigure_packet_length_();
} else
#endif
{
this->configure_packet_mode_();
}
if (this->initialized_) {
if (this->gdo0_pin_ != nullptr) {
@@ -856,24 +1167,41 @@ void CC1101Component::set_packet_mode(bool value) {
this->gdo0_pin_->detach_interrupt();
}
}
this->write_(Register::PKTCTRL0);
this->write_(Register::PKTCTRL1);
this->write_(Register::IOCFG0);
this->write_(Register::FIFOTHR);
}
}
void CC1101Component::set_packet_length(uint8_t value) {
if (value == 0) {
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_VARIABLE);
} else {
this->state_.LENGTH_CONFIG = static_cast<uint8_t>(LengthConfig::LENGTH_CONFIG_FIXED);
this->state_.PKTLEN = value;
void CC1101Component::set_packet_length(uint16_t value) {
#ifndef USE_CC1101_LONG_PACKET
if (value > RX_FIFO_SIZE) {
ESP_LOGW(TAG, "Packet length %u needs a configured packet_length above %u", value,
static_cast<unsigned>(RX_FIFO_SIZE));
return;
}
if (this->initialized_) {
this->write_(Register::PKTCTRL0);
this->write_(Register::PKTLEN);
#else
this->packet_length_func_ = nullptr;
#endif
this->packet_length_ = value;
this->reconfigure_packet_length_();
}
#ifdef USE_CC1101_LONG_PACKET
void CC1101Component::set_packet_length_lambda(packet_length_func_t func) {
this->packet_length_func_ = func;
this->reconfigure_packet_length_();
}
#endif
void CC1101Component::reconfigure_packet_length_() {
// While asleep the writes wait for wake_up() and the radio stays asleep, like set_frequency()
if (!this->initialized_ || this->sleeping_) {
this->configure_packet_mode_();
return;
}
// Like the other runtime setters: go through IDLE, and flush bytes of a reception in progress
this->enter_idle_();
this->strobe_(Command::FRX);
this->configure_packet_mode_();
this->enter_rx_();
}
void CC1101Component::set_crc_enable(bool value) {
+33 -2
View File
@@ -2,6 +2,7 @@
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/components/spi/spi.h"
#include "esphome/core/automation.h"
#include "cc1101defs.h"
@@ -10,6 +11,7 @@
namespace esphome::cc1101 {
enum class CC1101Error { NONE = 0, TIMEOUT, PARAMS, CRC_ERROR, FIFO_OVERFLOW, PLL_LOCK };
using packet_length_func_t = int32_t (*)(const std::vector<uint8_t> &);
class CC1101Listener {
public:
@@ -86,7 +88,10 @@ class CC1101Component final : public Component,
// Packet mode settings
void set_packet_mode(bool value);
void set_packet_length(uint8_t value);
void set_packet_length(uint16_t value);
#ifdef USE_CC1101_LONG_PACKET
void set_packet_length_lambda(packet_length_func_t func);
#endif
void set_crc_enable(bool value);
void set_whitening(bool value);
@@ -101,6 +106,7 @@ class CC1101Component final : public Component,
protected:
uint16_t chip_id_{0};
bool initialized_{false};
bool packet_mode_{false};
bool sleeping_{false};
bool registers_dirty_{false};
@@ -112,13 +118,38 @@ class CC1101Component final : public Component,
// GDO pin for packet reception
InternalGPIOPin *gdo0_pin_{nullptr};
static void gpio_intr(CC1101Component *arg);
// Inline like App.get_loop_component_start_time(): on RP2040 an out-of-line IRAM_ATTR function in the same
// file as that inline one fails with a section type conflict
static void IRAM_ATTR gpio_intr(CC1101Component *arg) { arg->enable_loop_soon_any_context(); }
// Packet handling
void call_listeners_(const std::vector<uint8_t> &packet, float freq_offset, float rssi, uint8_t lqi);
void configure_packet_mode_();
void reconfigure_packet_length_();
float symbol_rate_() const;
#ifdef USE_CC1101_LONG_PACKET
bool is_long_packet_mode_() const;
void arm_length_(uint16_t length);
void reset_long_packet_rx_();
void restart_long_packet_rx_();
void loop_long_packet_();
void handle_long_packet_(uint8_t rx_bytes);
void finish_long_packet_();
void maybe_switch_long_packet_to_fixed_();
#endif
Trigger<std::vector<uint8_t>, float, float, uint8_t> packet_trigger_;
std::vector<uint8_t> packet_;
std::vector<CC1101Listener *> listeners_;
#ifdef USE_CC1101_LONG_PACKET
packet_length_func_t packet_length_func_{nullptr};
uint32_t packet_last_byte_ms_{0};
#endif
uint16_t packet_length_{0};
#ifdef USE_CC1101_LONG_PACKET
uint16_t packet_expected_length_{0};
int8_t long_packet_rssi_{0}; // raw RSSI register
HighFrequencyLoopRequester high_freq_;
#endif
// Low-level Helpers
uint8_t strobe_(Command cmd);
+5
View File
@@ -15,6 +15,11 @@ static constexpr uint8_t PLL_LOCK_RETRIES = 3;
static constexpr uint8_t STATUS_CRC_OK_MASK = 0x80;
static constexpr uint8_t STATUS_LQI_MASK = 0x7F;
static constexpr uint16_t MAX_PACKET_LENGTH = 1024;
static constexpr uint16_t PACKET_IDLE_TIMEOUT_BYTES = 64;
static constexpr uint32_t PACKET_IDLE_TIMEOUT_MIN_MS = 5;
static constexpr uint8_t RXBYTES_STABLE_RETRIES = 4;
static constexpr uint8_t BUS_BURST = 0x40;
static constexpr uint8_t BUS_READ = 0x80;
static constexpr uint8_t BUS_WRITE = 0x00;
+2 -2
View File
@@ -1,6 +1,7 @@
#include "cse7761.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome::cse7761 {
@@ -104,8 +105,7 @@ void CSE7761Component::write_(uint8_t reg, uint16_t data) {
buffer[2] = data & 0xFF;
len = 3;
} else {
buffer[2] = (data >> 8) & 0xFF;
buffer[3] = data & 0xFF;
put_be16(buffer + 2, data);
len = 4;
}
buffer[len] = ~sum_bytes(buffer, len);
@@ -1,36 +1,15 @@
from esphome import pins
import esphome.codegen as cg
from esphome.components import i2c, touchscreen
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
from esphome.components import cstxxx
from esphome.types import ConfigType
from .. import cst226_ns
CST226Touchscreen = cst226_ns.class_(
"CST226Touchscreen",
touchscreen.Touchscreen,
i2c.I2CDevice,
)
AUTO_LOAD = ["cstxxx"]
CST226Touchscreen = cst226_ns.class_("CST226Touchscreen", cstxxx.CSTTouchscreen)
CST226ButtonListener = cst226_ns.class_("CST226ButtonListener")
CONFIG_SCHEMA = (
touchscreen.touchscreen_schema("100ms")
.extend(
{
cv.GenerateID(): cv.declare_id(CST226Touchscreen),
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
}
)
.extend(i2c.i2c_device_schema(0x5A))
)
CONFIG_SCHEMA = cstxxx.cst_touchscreen_schema(CST226Touchscreen, 0x5A)
async def to_code(config: ConfigType) -> None:
var = cg.new_Pvariable(config[CONF_ID])
await touchscreen.register_touchscreen(var, config)
await i2c.register_i2c_device(var, config)
await cg.add_pin(var.set_interrupt_pin, config.get(CONF_INTERRUPT_PIN))
await cg.add_pin(var.set_reset_pin, config.get(CONF_RESET_PIN))
await cstxxx.new_cst_touchscreen(config)
@@ -14,6 +14,10 @@ void CST226Touchscreen::setup() {
}
void CST226Touchscreen::update_touches() {
if (!this->setup_complete_) {
this->skip_update_ = true;
return;
}
uint8_t data[28];
if (!this->status_comm_result(this->read_bytes(CST226_REG_STATUS, data, sizeof data))) {
this->skip_update_ = true;
@@ -24,56 +28,39 @@ void CST226Touchscreen::update_touches() {
return;
}
this->update_button_state_(false);
if (data[6] != 0xAB || data[0] == 0xAB || data[5] == 0x80) {
if (data[cstxxx::SYNC_IDX] != cstxxx::SYNC_BYTE || data[0] == cstxxx::SYNC_BYTE ||
data[cstxxx::FINGER_COUNT_IDX] == 0x80) {
this->skip_update_ = true;
return;
}
uint8_t num_of_touches = data[5] & 0x7F;
uint8_t num_of_touches = data[cstxxx::FINGER_COUNT_IDX] & 0x7F;
if (num_of_touches == 0 || num_of_touches > 5) {
this->write_byte(0, 0xAB);
this->write_byte(CST226_REG_STATUS, cstxxx::SYNC_BYTE);
return;
}
size_t index = 0;
for (uint8_t i = 0; i != num_of_touches; i++) {
uint8_t id = data[index] >> 4;
int16_t x = (data[index + 1] << 4) | ((data[index + 3] >> 4) & 0x0F);
int16_t y = (data[index + 2] << 4) | (data[index + 3] & 0x0F);
int16_t z = data[index + 4];
this->add_raw_touch_position_(id, x, y, z);
ESP_LOGV(TAG, "Read touch %d: %d/%d", id, x, y);
index += 5;
if (i == 0)
index += 2;
auto touch = cstxxx::decode_touch(data, i);
this->add_raw_touch_position_(touch.id, touch.x, touch.y, touch.z);
ESP_LOGV(TAG, "Read touch %d: %d/%d", touch.id, touch.x, touch.y);
}
}
bool CST226Touchscreen::read16_(uint16_t addr, uint8_t *data, size_t len) {
if (this->read_register16(addr, data, len) != i2c::ERROR_OK) {
ESP_LOGE(TAG, "Read data from 0x%04X failed", addr);
this->mark_failed();
return false;
}
return true;
}
void CST226Touchscreen::continue_setup_() {
uint8_t buffer[8];
if (this->interrupt_pin_ != nullptr) {
this->interrupt_pin_->setup();
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
}
if (!this->setup_check(this->write_byte_reg16(0xD1, 0xD1), LOG_STR("Write byte to 0xD1 failed")))
this->setup_interrupt_pin_(gpio::INTERRUPT_FALLING_EDGE);
if (!this->enter_command_mode_())
return;
delay(10);
if (this->read16_(0xD204, buffer, 4)) {
uint16_t chip_id = buffer[2] + (buffer[3] << 8);
uint16_t project_id = buffer[0] + (buffer[1] << 8);
ESP_LOGCONFIG(TAG, "Chip ID %X, project ID %x", chip_id, project_id);
}
if (!this->check_firmware_())
return;
if (!this->setup_check(this->read_words_(cstxxx::REG_CHIP_INFO, this->project_id_, this->chip_id_),
LOG_STR("Failed to read chip ID")))
return;
if (this->x_raw_max_ == 0 || this->y_raw_max_ == 0) {
if (this->read16_(0xD1F8, buffer, 4)) {
this->x_raw_max_ = buffer[0] + (buffer[1] << 8);
this->y_raw_max_ = buffer[2] + (buffer[3] << 8);
uint16_t x_max, y_max;
if (this->read_words_(cstxxx::REG_RESOLUTION, x_max, y_max)) {
this->x_raw_max_ = x_max;
this->y_raw_max_ = y_max;
if (this->swap_x_y_)
std::swap(this->x_raw_max_, this->y_raw_max_);
} else {
@@ -81,8 +68,10 @@ void CST226Touchscreen::continue_setup_() {
this->y_raw_max_ = this->display_->get_native_height();
}
}
this->status_comm_check(this->write_register16(cstxxx::REG_NORMAL_MODE, nullptr, 0) == i2c::ERROR_OK);
this->setup_complete_ = true;
}
void CST226Touchscreen::update_button_state_(bool state) {
if (this->button_touched_ == state)
return;
@@ -96,6 +85,10 @@ void CST226Touchscreen::dump_config() {
LOG_I2C_DEVICE(this);
LOG_PIN(" Interrupt Pin: ", this->interrupt_pin_);
LOG_PIN(" Reset Pin: ", this->reset_pin_);
ESP_LOGCONFIG(TAG,
" Chip ID: 0x%04X, Project ID: 0x%04X\n"
" X/Y raw max: %d/%d",
this->chip_id_, this->project_id_, this->x_raw_max_, this->y_raw_max_);
}
} // namespace esphome::cst226
@@ -1,11 +1,12 @@
#pragma once
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/touchscreen/touchscreen.h"
#include "esphome/components/cstxxx/cstxxx.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include <vector>
namespace esphome::cst226 {
static const uint8_t CST226_REG_STATUS = 0x00;
@@ -15,28 +16,23 @@ class CST226ButtonListener {
virtual void update_button(bool state) = 0;
};
class CST226Touchscreen final : public touchscreen::Touchscreen, public i2c::I2CDevice {
class CST226Touchscreen final : public cstxxx::CSTTouchscreen {
public:
void setup() override;
void update_touches() override;
void dump_config() override;
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
bool can_proceed() override { return this->setup_complete_ || this->is_failed(); }
void register_button_listener(CST226ButtonListener *listener) { this->button_listeners_.push_back(listener); }
protected:
bool read16_(uint16_t addr, uint8_t *data, size_t len);
void continue_setup_();
void update_button_state_(bool state);
InternalGPIOPin *interrupt_pin_{};
GPIOPin *reset_pin_{};
uint8_t chip_id_{};
bool setup_complete_{};
std::vector<CST226ButtonListener *> button_listeners_;
bool button_touched_{};
uint16_t chip_id_{};
uint16_t project_id_{};
std::vector<CST226ButtonListener *> button_listeners_;
};
} // namespace esphome::cst226
+7
View File
@@ -0,0 +1,7 @@
import esphome.codegen as cg
CODEOWNERS = ["@tpruvot"]
DEPENDENCIES = ["i2c"]
DOMAIN = "cst3240"
cst3240_ns = cg.esphome_ns.namespace("cst3240")
@@ -0,0 +1,14 @@
from esphome.components import cstxxx
from esphome.types import ConfigType
from .. import cst3240_ns
AUTO_LOAD = ["cstxxx"]
CST3240Touchscreen = cst3240_ns.class_("CST3240Touchscreen", cstxxx.CSTTouchscreen)
CONFIG_SCHEMA = cstxxx.cst_touchscreen_schema(CST3240Touchscreen, 0x5A)
async def to_code(config: ConfigType) -> None:
await cstxxx.new_cst_touchscreen(config)
@@ -0,0 +1,112 @@
#include "cst3240_touchscreen.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <utility>
namespace esphome::cst3240 {
ESPHOME_LOG_TAG(TAG, "cst3240.touchscreen");
void CST3240Touchscreen::setup() {
if (this->reset_pin_ == nullptr) {
this->continue_setup_();
return;
}
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 5});
this->set_timeout(30, [this] { this->continue_setup_(); });
}
void CST3240Touchscreen::continue_setup_() {
if (!this->enter_command_mode_())
return;
if (!this->setup_check(this->read_words_(cstxxx::REG_CHIP_INFO, this->project_id_, this->chip_id_),
LOG_STR("Failed to read chip ID")))
return;
// Only warn: the chip ID has not been confirmed on enough boards to fail setup on it
if (this->chip_id_ != CST3240_CHIP_ID) {
ESP_LOGW(TAG, "Unexpected chip ID 0x%04X", this->chip_id_);
}
this->read_words_(cstxxx::REG_FW_VERSION, this->fw_build_, this->fw_version_);
if (this->x_raw_max_ == this->x_raw_min_ || this->y_raw_max_ == this->y_raw_min_) {
uint16_t x_max, y_max;
if (this->read_words_(cstxxx::REG_RESOLUTION, x_max, y_max)) {
this->x_raw_max_ = x_max;
this->y_raw_max_ = y_max;
if (this->swap_x_y_)
std::swap(this->x_raw_max_, this->y_raw_max_);
} else {
this->x_raw_max_ = this->display_->get_native_width();
this->y_raw_max_ = this->display_->get_native_height();
}
}
this->status_comm_check(this->write_register16(cstxxx::REG_NORMAL_MODE, nullptr, 0) == i2c::ERROR_OK);
this->setup_interrupt_pin_(gpio::INTERRUPT_RISING_EDGE);
this->setup_complete_ = true;
}
void CST3240Touchscreen::update_touches() {
if (!this->setup_complete_) {
this->skip_update_ = true;
return;
}
uint8_t data[CST3240_REPORT_SIZE];
if (!this->status_comm_result(this->read_register16(cstxxx::REG_TOUCH_DATA, data, sizeof(data)) == i2c::ERROR_OK)) {
this->skip_update_ = true;
return;
}
const uint8_t sync = data[cstxxx::SYNC_IDX];
if (sync != cstxxx::SYNC_BYTE) {
this->skip_update_ = true;
if (sync != 0) {
ESP_LOGV(TAG, "Skipping report, sync byte 0x%02X", sync);
this->clear_report_();
}
return;
}
const uint8_t count = data[cstxxx::FINGER_COUNT_IDX] & 0x0F;
if (count <= CST3240_MAX_TOUCHES) {
for (uint8_t i = 0; i < count; i++) {
auto touch = cstxxx::decode_touch(data, i);
// A released finger is still listed once, with both press bits clear
if ((touch.event & TOUCH_EVENT_PRESSED) == 0)
continue;
this->add_raw_touch_position_(touch.id, touch.x, touch.y, touch.z);
}
}
if (this->interrupt_pin_ == nullptr) {
this->clear_report_();
} else if (!this->write_byte_reg16(cstxxx::REG_FINGER_COUNT, 0) ||
!this->write_byte_reg16(cstxxx::REG_TOUCH_DATA, cstxxx::SYNC_BYTE)) {
ESP_LOGW(TAG, "Failed to acknowledge the report");
}
}
void CST3240Touchscreen::clear_report_() {
// Built on the stack: write_register16() heap allocates a frame this long
uint8_t frame[2 + CST3240_REPORT_SIZE]{};
put_be16(frame, cstxxx::REG_TOUCH_DATA);
if (this->write(frame, sizeof(frame)) != i2c::ERROR_OK) {
ESP_LOGW(TAG, "Failed to clear the report");
}
}
void CST3240Touchscreen::dump_config() {
ESP_LOGCONFIG(TAG,
"CST3240 Touchscreen:\n"
" Chip ID: 0x%04X, Project ID: 0x%04X\n"
" FW version: %d.%d.%d\n"
" X/Y resolution: %d/%d",
this->chip_id_, this->project_id_, this->fw_version_ >> 8, this->fw_version_ & 0xFF, this->fw_build_,
this->x_raw_max_, this->y_raw_max_);
LOG_I2C_DEVICE(this);
LOG_PIN(" Interrupt Pin: ", this->interrupt_pin_);
LOG_PIN(" Reset Pin: ", this->reset_pin_);
}
} // namespace esphome::cst3240
@@ -0,0 +1,31 @@
#pragma once
#include "esphome/components/cstxxx/cstxxx.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
namespace esphome::cst3240 {
static constexpr uint16_t CST3240_CHIP_ID = 0x3240;
static constexpr uint8_t CST3240_MAX_TOUCHES = 5;
static constexpr uint8_t CST3240_REPORT_SIZE = cstxxx::report_size(CST3240_MAX_TOUCHES);
static constexpr uint8_t TOUCH_EVENT_PRESSED = 0x06;
class CST3240Touchscreen : public cstxxx::CSTTouchscreen {
public:
void setup() override;
void dump_config() override;
protected:
void update_touches() override;
void continue_setup_();
/// Zeroes the touch report block, which polling relies on to tell new reports from old.
void clear_report_();
uint16_t chip_id_{};
uint16_t project_id_{};
uint16_t fw_version_{};
uint16_t fw_build_{};
};
} // namespace esphome::cst3240
@@ -1,37 +1,15 @@
from esphome import pins
import esphome.codegen as cg
from esphome.components import i2c, touchscreen
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
from esphome.components import cstxxx
from esphome.types import ConfigType
from .. import cst328_ns
CST328Touchscreen = cst328_ns.class_(
"CST328Touchscreen",
touchscreen.Touchscreen,
i2c.I2CDevice,
)
AUTO_LOAD = ["cstxxx"]
CST328Touchscreen = cst328_ns.class_("CST328Touchscreen", cstxxx.CSTTouchscreen)
CST328ButtonListener = cst328_ns.class_("CST328ButtonListener")
CONFIG_SCHEMA = (
touchscreen.touchscreen_schema("100ms")
.extend(
{
cv.GenerateID(): cv.declare_id(CST328Touchscreen),
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
}
)
.extend(i2c.i2c_device_schema(0x1A))
)
CONFIG_SCHEMA = cstxxx.cst_touchscreen_schema(CST328Touchscreen, 0x1A)
async def to_code(config: ConfigType) -> None:
var = cg.new_Pvariable(config[CONF_ID])
await touchscreen.register_touchscreen(var, config)
await i2c.register_i2c_device(var, config)
await cg.add_pin(var.set_interrupt_pin, config.get(CONF_INTERRUPT_PIN))
await cg.add_pin(var.set_reset_pin, config.get(CONF_RESET_PIN))
await cstxxx.new_cst_touchscreen(config)
@@ -5,31 +5,8 @@ namespace esphome::cst328 {
ESPHOME_LOG_TAG(TAG, "cst328.touchscreen");
static const uint32_t CST328_BEFORE_RESET_TIMEOUT = 50; // 50 ms from datasheet
static const uint32_t CST328_TRANSITION_TIMEOUT = 300; // 200 ms from datasheet, but typically much less
static const uint16_t CST328_FW_CRC = 0xCACA; // Expected firmware CRC value
static const uint8_t CST328_SYNC_BYTE = 0xAB; // Sync byte used in communication
static const uint8_t ZERO_BYTE = 0;
#define I2C_WARN_ON_ERROR(x, log_tag, format, ...) \
do { \
i2c::ErrorCode err_rc_ = (x); \
if (err_rc_ != i2c::ERROR_OK) { \
ESP_LOGW(log_tag, "%s(%d): [error %d] " format, __FUNCTION__, __LINE__, err_rc_, ##__VA_ARGS__); \
this->status_set_warning(format); \
} \
} while (0)
#define I2C_FAIL_ON_ERROR(x, log_tag, format, ...) \
do { \
i2c::ErrorCode err_rc_ = (x); \
if (err_rc_ != i2c::ERROR_OK) { \
ESP_LOGE(log_tag, "%s(%d): [error %d] " format, __FUNCTION__, __LINE__, err_rc_, ##__VA_ARGS__); \
this->mark_failed(); \
return; \
} \
} while (0)
static constexpr uint32_t CST328_BEFORE_RESET_TIMEOUT = 50; // 50 ms from datasheet
static constexpr uint32_t CST328_TRANSITION_TIMEOUT = 300; // 200 ms from datasheet, but typically much less
void CST328Touchscreen::setup() {
ESP_LOGCONFIG(TAG, "Setting up CST328 Touchscreen...");
@@ -50,50 +27,36 @@ void CST328Touchscreen::reset_device_() {
void CST328Touchscreen::continue_setup_() {
ESP_LOGV(TAG, "Continuing CST328 setup...");
uint8_t data_byte{0};
uint8_t buf[24]{};
I2C_FAIL_ON_ERROR(this->write_register16(CST_WM_DEBUG_INFO, buf, 0), TAG, "Failed to enter debug/info mode");
I2C_FAIL_ON_ERROR(this->read_register16(CST_REG_FW_CRC_AND_BOOT_TIME, buf, 4), TAG,
"Failed to read FW CRC and boot time");
uint16_t fw_crc = buf[2] + (buf[3] << 8);
if (fw_crc != CST328_FW_CRC) {
ESP_LOGE(TAG, "Error: Firmware CRC mismatch, expected 0x%04X but got 0x%04X", CST328_FW_CRC, fw_crc);
this->mark_failed();
if (!this->enter_command_mode_() || !this->check_firmware_())
return;
if (!this->setup_check(this->read_words_(cstxxx::REG_CHIP_INFO, this->project_id_, this->chip_id_),
LOG_STR("Failed to read chip and project ID")))
return;
}
I2C_FAIL_ON_ERROR(this->read_register16(CST_REG_CHIP_TYPE_AND_PROJECT_ID, buf, 4), TAG,
"Failed to read chip and project ID");
this->chip_id_ = buf[2] + (buf[3] << 8);
this->project_id_ = buf[0] + (buf[1] << 8);
ESP_LOGD(TAG, "Chip ID %X, project ID %X", this->chip_id_, this->project_id_);
I2C_FAIL_ON_ERROR(this->read_register16(CST_REG_FW_REVISION, buf, 4), TAG, "Failed to read FW version");
this->fw_ver_major_ = buf[3];
this->fw_ver_minor_ = buf[2];
this->fw_build_ = buf[0] + (buf[1] << 8);
uint16_t fw_version;
if (!this->setup_check(this->read_words_(cstxxx::REG_FW_VERSION, this->fw_build_, fw_version),
LOG_STR("Failed to read FW version")))
return;
this->fw_ver_major_ = fw_version >> 8;
this->fw_ver_minor_ = fw_version & 0xFF;
ESP_LOGV(TAG, "FW version %d.%d.%d", this->fw_ver_major_, this->fw_ver_minor_, this->fw_build_);
if (i2c::ERROR_OK == this->read_register16(CST_REG_X_Y_RESOLUTION, buf, 4)) {
this->x_raw_max_ = buf[0] + (buf[1] << 8);
this->y_raw_max_ = buf[2] + (buf[3] << 8);
uint16_t x_max, y_max;
if (this->read_words_(cstxxx::REG_RESOLUTION, x_max, y_max)) {
this->x_raw_max_ = x_max;
this->y_raw_max_ = y_max;
} else {
this->x_raw_max_ = this->display_->get_native_width();
this->y_raw_max_ = this->display_->get_native_height();
}
I2C_WARN_ON_ERROR(this->write_register16(CST_WM_NORMAL, buf, 0), TAG, "Failed to enter normal mode");
I2C_WARN_ON_ERROR(this->read_register16(CST_REG_TOUCH_INFORMATION, &data_byte, 1), TAG, "Failed to read sync");
I2C_WARN_ON_ERROR(this->write_register16(CST_REG_TOUCH_INFORMATION, &CST328_SYNC_BYTE, 1), TAG,
"Failed to write sync");
uint8_t sync;
bool ok = this->write_register16(cstxxx::REG_NORMAL_MODE, nullptr, 0) == i2c::ERROR_OK;
ok &= this->read_byte_reg16(cstxxx::REG_TOUCH_DATA, &sync);
ok &= this->write_byte_reg16(cstxxx::REG_TOUCH_DATA, cstxxx::SYNC_BYTE);
this->status_comm_check(ok);
if (this->interrupt_pin_ != nullptr) {
this->interrupt_pin_->setup();
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
}
this->setup_interrupt_pin_(gpio::INTERRUPT_FALLING_EDGE);
this->setup_complete_ = true;
ESP_LOGV(TAG, "CST328 setup complete");
@@ -142,21 +105,15 @@ void CST328Touchscreen::update_touches() {
} else {
this->update_button_state_(true);
uint8_t data_idx = 0;
for (uint8_t i = 0; i < touch_cnt; i++) {
uint8_t id = touch_data[data_idx] >> 4;
int16_t x = (touch_data[data_idx + 1] << 4) | ((touch_data[data_idx + 3] >> 4) & 0x0F);
int16_t y = (touch_data[data_idx + 2] << 4) | (touch_data[data_idx + 3] & 0x0F);
int16_t z = touch_data[data_idx + 4];
this->add_raw_touch_position_(id, x, y, z);
data_idx += (i == 0) ? 7 : 5;
auto touch = cstxxx::decode_touch(touch_data, i);
this->add_raw_touch_position_(touch.id, touch.x, touch.y, touch.z);
}
}
bool cleanup_error = false;
cleanup_error |= !this->write_byte_reg16(CST_REG_TOUCH_FINGER_NUMBER, ZERO_BYTE);
cleanup_error |= !this->write_byte_reg16(CST_REG_TOUCH_INFORMATION, CST328_SYNC_BYTE);
cleanup_error |= !this->write_byte_reg16(cstxxx::REG_FINGER_COUNT, 0);
cleanup_error |= !this->write_byte_reg16(cstxxx::REG_TOUCH_DATA, cstxxx::SYNC_BYTE);
if (cleanup_error) {
ESP_LOGW(TAG, "Failed to clean up touch registers");
@@ -1,61 +1,45 @@
#pragma once
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/touchscreen/touchscreen.h"
#include "esphome/components/cstxxx/cstxxx.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include <vector>
namespace esphome::cst328 {
static const uint8_t CST328_TOUCH_MAX_POINTS = 5;
static const uint8_t CST328_TOUCH_DATA_SIZE = CST328_TOUCH_MAX_POINTS * 5 + 2;
static constexpr uint8_t CST328_TOUCH_MAX_POINTS = 5;
static constexpr uint8_t CST328_TOUCH_DATA_SIZE = cstxxx::report_size(CST328_TOUCH_MAX_POINTS);
static const uint16_t CST_REG_TOUCH_INFORMATION = 0xD000;
static const uint16_t CST_REG_TOUCH_FINGER_NUMBER = 0xD005;
static const uint16_t CST_REG_FINGER_COUNT_IDX = CST_REG_TOUCH_FINGER_NUMBER - CST_REG_TOUCH_INFORMATION;
static const uint16_t CST_REG_X_Y_RESOLUTION = 0xD1F8;
static const uint16_t CST_REG_FW_CRC_AND_BOOT_TIME = 0xD1FC;
static const uint16_t CST_REG_CHIP_TYPE_AND_PROJECT_ID = 0xD204;
static const uint16_t CST_REG_FW_REVISION = 0xD208;
static const uint16_t CST_WM_DEBUG_INFO = 0xD101;
static const uint16_t CST_WM_NORMAL = 0xD109;
static constexpr uint16_t CST_REG_TOUCH_INFORMATION = cstxxx::REG_TOUCH_DATA;
static constexpr uint16_t CST_REG_FINGER_COUNT_IDX = cstxxx::FINGER_COUNT_IDX;
static constexpr uint16_t CST_REG_X_Y_RESOLUTION = cstxxx::REG_RESOLUTION;
static constexpr uint16_t CST_REG_FW_CRC_AND_BOOT_TIME = cstxxx::REG_FW_CHECK_CODE;
class CST328ButtonListener {
public:
virtual void update_button(bool state) = 0;
};
class CST328Touchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
class CST328Touchscreen : public cstxxx::CSTTouchscreen {
public:
void setup() override;
void register_button_listener(CST328ButtonListener *listener) { this->button_listeners_.push_back(listener); }
void dump_config() override;
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
protected:
void update_touches() override;
void reset_device_();
void continue_setup_();
void update_button_state_(bool state);
InternalGPIOPin *interrupt_pin_{};
GPIOPin *reset_pin_{};
std::vector<CST328ButtonListener *> button_listeners_;
bool button_touched_{};
uint16_t chip_id_{};
uint16_t project_id_{};
uint8_t fw_ver_major_{};
uint8_t fw_ver_minor_{};
std::vector<CST328ButtonListener *> button_listeners_;
uint16_t chip_id_{};
uint16_t project_id_{};
uint16_t fw_build_{};
bool setup_complete_{};
};
} // namespace esphome::cst328
@@ -1,35 +1,14 @@
from esphome import pins
import esphome.codegen as cg
from esphome.components import i2c, touchscreen
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
from esphome.components import cstxxx
from esphome.types import ConfigType
from .. import cst9220_ns
CST9220Touchscreen = cst9220_ns.class_(
"CST9220Touchscreen",
touchscreen.Touchscreen,
i2c.I2CDevice,
)
AUTO_LOAD = ["cstxxx"]
CONFIG_SCHEMA = (
touchscreen.touchscreen_schema("100ms")
.extend(
{
cv.GenerateID(): cv.declare_id(CST9220Touchscreen),
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
}
)
.extend(i2c.i2c_device_schema(0x5A))
)
CST9220Touchscreen = cst9220_ns.class_("CST9220Touchscreen", cstxxx.CSTTouchscreen)
CONFIG_SCHEMA = cstxxx.cst_touchscreen_schema(CST9220Touchscreen, 0x5A)
async def to_code(config: ConfigType) -> None:
var = cg.new_Pvariable(config[CONF_ID])
await touchscreen.register_touchscreen(var, config)
await i2c.register_i2c_device(var, config)
await cg.add_pin(var.set_interrupt_pin, config.get(CONF_INTERRUPT_PIN))
await cg.add_pin(var.set_reset_pin, config.get(CONF_RESET_PIN))
await cstxxx.new_cst_touchscreen(config)
@@ -1,7 +1,4 @@
#include "cst9220_touchscreen.h"
#include "esphome/core/helpers.h"
#include <cinttypes>
namespace esphome::cst9220 {
@@ -16,55 +13,29 @@ void CST9220Touchscreen::setup() {
}
void CST9220Touchscreen::continue_setup_() {
uint8_t buffer[4];
this->setup_interrupt_pin_(gpio::INTERRUPT_FALLING_EDGE);
if (this->interrupt_pin_ != nullptr) {
this->interrupt_pin_->setup();
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
}
// Enter command mode so the configuration registers can be read.
if (this->write_register16(REG_CMD_MODE, buffer, 0) != i2c::ERROR_OK) {
this->status_set_error(LOG_STR("Failed to enter command mode"));
this->mark_failed();
if (!this->enter_command_mode_())
return;
}
delay(10);
// The firmware check code confirms that valid firmware is loaded.
if (this->read_register16(REG_CHECKCODE, buffer, 4) != i2c::ERROR_OK) {
this->status_set_error(LOG_STR("Failed to read check code"));
this->mark_failed();
if (!this->check_firmware_())
return;
}
uint32_t checkcode = encode_uint32(buffer[3], buffer[2], buffer[1], buffer[0]);
if ((checkcode & 0xFFFF0000) != 0xCACA0000) {
ESP_LOGE(TAG, "Invalid firmware check code: 0x%08" PRIX32, checkcode);
this->status_set_error(LOG_STR("Invalid firmware check code"));
this->mark_failed();
return;
}
// Read the panel resolution unless the user supplied calibration values.
if (this->read_register16(REG_RESOLUTION, buffer, 4) == i2c::ERROR_OK) {
uint16_t x_max, y_max;
if (this->read_words_(cstxxx::REG_RESOLUTION, x_max, y_max)) {
if (this->x_raw_max_ == this->x_raw_min_)
this->x_raw_max_ = encode_value_le<uint16_t>(buffer);
this->x_raw_max_ = x_max;
if (this->y_raw_max_ == this->y_raw_min_)
this->y_raw_max_ = encode_value_le<uint16_t>(&buffer[2]);
this->y_raw_max_ = y_max;
}
// Read the chip type and project id and validate the controller.
if (this->read_register16(REG_CHIP_INFO, buffer, 4) != i2c::ERROR_OK) {
this->status_set_error(LOG_STR("Failed to read chip ID"));
this->mark_failed();
if (!this->setup_check(this->read_words_(cstxxx::REG_CHIP_INFO, this->project_id_, this->chip_id_),
LOG_STR("Failed to read chip ID")))
return;
}
this->chip_id_ = encode_value_le<uint16_t>(&buffer[2]);
this->project_id_ = encode_value_le<uint16_t>(buffer);
if (this->chip_id_ != CST9220_CHIP_ID && this->chip_id_ != CST9217_CHIP_ID) {
ESP_LOGE(TAG, "Unknown chip ID: 0x%04X", this->chip_id_);
this->status_set_error(LOG_STR("Unknown chip ID"));
this->mark_failed();
this->mark_failed(LOG_STR("Unknown chip ID"));
return;
}
@@ -84,7 +55,7 @@ void CST9220Touchscreen::update_touches() {
// Only an actual I2C failure should skip the update; a successful read with no
// touches is a real "all fingers lifted" state that must flow through so the
// base class can generate the release event.
if (!this->status_comm_result(this->read_register16(REG_TOUCH_DATA, data, sizeof(data)) == i2c::ERROR_OK)) {
if (!this->status_comm_result(this->read_register16(cstxxx::REG_TOUCH_DATA, data, sizeof(data)) == i2c::ERROR_OK)) {
this->skip_update_ = true;
return;
}
@@ -92,30 +63,23 @@ void CST9220Touchscreen::update_touches() {
// A valid report carries the marker at offset 6. Writing an acknowledge back makes the controller return
// invalid frames during a long press, so none is written. An invalid frame keeps the previous points; while
// a finger is down, read again shortly so a lost release frame does not leave the touch held.
if (data[6] != TOUCH_ACK) {
if (data[cstxxx::SYNC_IDX] != cstxxx::SYNC_BYTE) {
this->skip_update_ = true;
if (!this->touches_.empty())
this->set_timeout(REREAD_TIMEOUT_ID, REREAD_DELAY_MS, [this] { this->store_.touched = true; });
return;
}
uint8_t num_touches = data[5] & 0x7F;
uint8_t num_touches = data[cstxxx::FINGER_COUNT_IDX] & 0x7F;
if (num_touches > CST9220_MAX_TOUCHES)
num_touches = CST9220_MAX_TOUCHES;
for (uint8_t i = 0; i < num_touches; i++) {
// The first point starts at offset 0; subsequent points are offset by the
// two status bytes that follow it.
const uint8_t *p = data + i * 5 + (i == 0 ? 0 : 2);
uint8_t id = p[0] >> 4;
uint8_t event = p[0] & 0x0F;
if (event != TOUCH_EVENT_DOWN)
auto touch = cstxxx::decode_touch(data, i);
if (touch.event != TOUCH_EVENT_DOWN)
continue;
// p[3] is shared: high nibble holds the X LSBs, low nibble the Y LSBs.
uint16_t x = (p[1] << 4) | (p[3] >> 4);
uint16_t y = (p[2] << 4) | (p[3] & 0x0F);
ESP_LOGV(TAG, "Read touch %d: %d/%d", id, x, y);
this->add_raw_touch_position_(id, x, y);
ESP_LOGV(TAG, "Read touch %d: %d/%d", touch.id, touch.x, touch.y);
this->add_raw_touch_position_(touch.id, touch.x, touch.y);
}
}
@@ -1,7 +1,6 @@
#pragma once
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/touchscreen/touchscreen.h"
#include "esphome/components/cstxxx/cstxxx.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
@@ -10,41 +9,26 @@ namespace esphome::cst9220 {
ESPHOME_LOG_TAG(TAG, "cst9220.touchscreen");
// The CST92xx family uses 16-bit (big-endian) register addresses.
static const uint16_t REG_TOUCH_DATA = 0xD000; // touch report
static const uint16_t REG_CMD_MODE = 0xD101; // enter command mode
static const uint16_t REG_CHECKCODE = 0xD1FC; // firmware check code
static const uint16_t REG_RESOLUTION = 0xD1F8; // panel resolution
static const uint16_t REG_CHIP_INFO = 0xD204; // chip type + project id
static constexpr uint8_t TOUCH_EVENT_DOWN = 0x06;
static const uint8_t TOUCH_ACK = 0xAB;
static const uint8_t TOUCH_EVENT_DOWN = 0x06;
static constexpr uint16_t CST9220_CHIP_ID = 0x9220;
static constexpr uint16_t CST9217_CHIP_ID = 0x9217;
static const uint16_t CST9220_CHIP_ID = 0x9220;
static const uint16_t CST9217_CHIP_ID = 0x9217;
// Maximum simultaneous touch points reported by the family.
static const uint8_t CST9220_MAX_TOUCHES = 5;
static constexpr uint8_t CST9220_MAX_TOUCHES = 5;
// Report layout: 5 bytes per touch point plus 5 bytes of status/ack overhead.
static const size_t CST9220_DATA_LENGTH = CST9220_MAX_TOUCHES * 5 + 5;
static constexpr size_t CST9220_DATA_LENGTH = CST9220_MAX_TOUCHES * 5 + 5;
class CST9220Touchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
class CST9220Touchscreen : public cstxxx::CSTTouchscreen {
public:
void setup() override;
void dump_config() override;
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
protected:
void update_touches() override;
void continue_setup_();
InternalGPIOPin *interrupt_pin_{};
GPIOPin *reset_pin_{};
uint16_t chip_id_{};
uint16_t project_id_{};
bool setup_complete_{};
};
} // namespace esphome::cst9220
+42
View File
@@ -0,0 +1,42 @@
from esphome import pins
import esphome.codegen as cg
from esphome.components import i2c, touchscreen
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_INTERRUPT_PIN, CONF_RESET_PIN
from esphome.cpp_generator import MockObj, MockObjClass
from esphome.types import ConfigType
CODEOWNERS = ["@clydebarrow", "@latonita"]
DEPENDENCIES = ["i2c", "touchscreen"]
DOMAIN = "cstxxx"
cstxxx_ns = cg.esphome_ns.namespace("cstxxx")
CSTTouchscreen = cstxxx_ns.class_(
"CSTTouchscreen", touchscreen.Touchscreen, i2c.I2CDevice
)
def cst_touchscreen_schema(touchscreen_class: MockObjClass, address: int) -> cv.Schema:
"""Return the touchscreen schema of a Hynitron driver."""
return (
touchscreen.touchscreen_schema("100ms")
.extend(
{
cv.GenerateID(): cv.declare_id(touchscreen_class),
cv.Optional(CONF_INTERRUPT_PIN): pins.internal_gpio_input_pin_schema,
cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
}
)
.extend(i2c.i2c_device_schema(address))
)
async def new_cst_touchscreen(config: ConfigType) -> MockObj:
"""Create a Hynitron touchscreen and set its pins."""
var = cg.new_Pvariable(config[CONF_ID])
await touchscreen.register_touchscreen(var, config)
await i2c.register_i2c_device(var, config)
await cg.add_pin(var.set_interrupt_pin, config.get(CONF_INTERRUPT_PIN))
await cg.add_pin(var.set_reset_pin, config.get(CONF_RESET_PIN))
return var
+13
View File
@@ -0,0 +1,13 @@
#include "cstxxx.h"
#include "esphome/core/log.h"
namespace esphome::cstxxx {
ESPHOME_LOG_TAG(TAG, "cstxxx");
void CSTTouchscreen::fail_check_code_(uint16_t check_code) {
ESP_LOGE(TAG, "Firmware check code 0x%04X", check_code);
this->mark_failed(LOG_STR("Invalid firmware check code"));
}
} // namespace esphome::cstxxx
+92
View File
@@ -0,0 +1,92 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include "esphome/components/i2c/i2c.h"
#include "esphome/components/touchscreen/touchscreen.h"
#include "esphome/core/gpio.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::cstxxx {
static constexpr uint16_t REG_TOUCH_DATA = 0xD000;
static constexpr uint16_t REG_FINGER_COUNT = 0xD005;
static constexpr uint16_t REG_COMMAND_MODE = 0xD101;
static constexpr uint16_t REG_NORMAL_MODE = 0xD109;
static constexpr uint16_t REG_RESOLUTION = 0xD1F8;
static constexpr uint16_t REG_FW_CHECK_CODE = 0xD1FC;
static constexpr uint16_t REG_CHIP_INFO = 0xD204;
static constexpr uint16_t REG_FW_VERSION = 0xD208;
static constexpr uint8_t FINGER_COUNT_IDX = REG_FINGER_COUNT - REG_TOUCH_DATA;
static constexpr uint8_t SYNC_IDX = FINGER_COUNT_IDX + 1;
static constexpr uint8_t SYNC_BYTE = 0xAB;
static constexpr uint16_t FW_CHECK_CODE = 0xCACA;
/// Bytes of a touch report holding `points` records; two status bytes follow the first record.
constexpr size_t report_size(uint8_t points) { return points * 5 + 2; }
struct TouchRecord {
uint8_t id;
uint8_t event;
uint16_t x;
uint16_t y;
uint8_t z;
};
/// Decodes record `index` of a touch report.
inline TouchRecord decode_touch(const uint8_t *report, uint8_t index) {
const uint8_t *r = report + index * 5 + (index == 0 ? 0 : 2);
return {static_cast<uint8_t>(r[0] >> 4), static_cast<uint8_t>(r[0] & 0x0F),
static_cast<uint16_t>(r[1] << 4 | r[3] >> 4), static_cast<uint16_t>(r[2] << 4 | (r[3] & 0x0F)), r[4]};
}
class CSTTouchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
public:
void set_interrupt_pin(InternalGPIOPin *pin) { this->interrupt_pin_ = pin; }
void set_reset_pin(GPIOPin *pin) { this->reset_pin_ = pin; }
protected:
/// Sets up the interrupt pin, if configured, to fire on `type`.
void setup_interrupt_pin_(gpio::InterruptType type) {
if (this->interrupt_pin_ == nullptr)
return;
this->interrupt_pin_->setup();
this->attach_interrupt_(this->interrupt_pin_, type);
}
/// Reads two little-endian words starting at `reg`.
bool ESPHOME_ALWAYS_INLINE read_words_(uint16_t reg, uint16_t &low, uint16_t &high) {
uint16_t words[2];
if (this->read_register16(reg, reinterpret_cast<uint8_t *>(words), sizeof(words)) != i2c::ERROR_OK)
return false;
low = convert_little_endian(words[0]);
high = convert_little_endian(words[1]);
return true;
}
/// Enters command mode, marking the component failed if the write fails.
bool enter_command_mode_() {
return this->setup_check(this->write_register16(REG_COMMAND_MODE, nullptr, 0) == i2c::ERROR_OK,
LOG_STR("Failed to enter command mode"));
}
/// Checks the firmware check code, marking the component failed if it is unreadable or wrong.
bool check_firmware_() {
uint16_t boot_time, check_code;
if (!this->setup_check(this->read_words_(REG_FW_CHECK_CODE, boot_time, check_code)))
return false;
if (check_code == FW_CHECK_CODE)
return true;
this->fail_check_code_(check_code);
return false;
}
/// Logs a wrong firmware check code and marks the component failed.
void fail_check_code_(uint16_t check_code);
InternalGPIOPin *interrupt_pin_{};
GPIOPin *reset_pin_{};
bool setup_complete_{};
};
} // namespace esphome::cstxxx
+3 -1
View File
@@ -1,6 +1,5 @@
import esphome.codegen as cg
from esphome.components import logger
from esphome.components.nrf52.framework import include_west_project
from esphome.components.zephyr import zephyr_add_prj_conf
from esphome.config_helpers import filter_source_files_from_platform
import esphome.config_validation as cv
@@ -53,6 +52,9 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config: ConfigType) -> None:
if CORE.using_zephyr:
# Imported here so configs for other platforms do not load the nrf52 package
from esphome.components.nrf52.framework import include_west_project
zephyr_add_prj_conf("HWINFO", True)
# gdb thread support
zephyr_add_prj_conf("DEBUG_THREAD_INFO", True)
+1 -1
View File
@@ -173,7 +173,7 @@ void DFPlayer::loop() {
}
// Parse valid received command
uint8_t cmd = this->read_buffer_[3];
uint16_t argument = (this->read_buffer_[5] << 8) | this->read_buffer_[6];
uint16_t argument = encode_uint16(this->read_buffer_[5], this->read_buffer_[6]);
ESP_LOGV(TAG, "Received message cmd: %#02x arg %#04x", cmd, argument);
+9 -7
View File
@@ -56,7 +56,7 @@ void Duco::close_request(DucoDevice *device) {
bool Duco::parse_byte_(uint8_t byte) {
const size_t at = this->rx_size_;
if (at >= MAX_FRAME_SIZE) {
ESP_LOGV(TAG, "Message longer than %u bytes dropped", static_cast<unsigned>(MAX_FRAME_SIZE));
ESP_LOGW(TAG, "Message longer than %u bytes dropped", static_cast<unsigned>(MAX_FRAME_SIZE));
return false;
}
const uint8_t prev = at > 0 ? this->rx_buffer_[at - 1] : 0;
@@ -178,16 +178,17 @@ void Duco::send(DucoDevice *device, uint8_t function, std::initializer_list<uint
ESP_LOGV_HEX(TAG, frame + 2, size + 5, sizeof(frame), "Sent %s");
}
static const LogString *node_type_name(uint8_t type) {
switch (type) {
const LogString *node_type_name(uint8_t type) {
const bool bs = (type & NODE_TYPE_BS) != 0;
switch (type & ~NODE_TYPE_BS) {
case 8:
return LOG_STR("UCBAT");
case 9:
return LOG_STR("UC");
case 10:
return LOG_STR("UCRH");
return bs ? LOG_STR("BSRH") : LOG_STR("UCRH");
case 12:
return LOG_STR("UCCO2");
return bs ? LOG_STR("BSCO2") : LOG_STR("UCCO2");
case 13:
return LOG_STR("VLV");
case 17:
@@ -230,8 +231,9 @@ void DucoDiscovery::receive_response(const DucoMessage &message) {
if (message.size >= 1 && this->next_node_ < NODE_COUNT) {
if (message.data[0] != 0) {
ESP_LOGV(TAG, "Found node %u: type %u", this->next_node_, message.data[0]);
this->node_types_[this->next_node_] = node_type_byte(message);
}
this->node_types_[this->next_node_++] = message.data[0];
this->next_node_++;
this->attempts_ = 0;
}
}
@@ -241,7 +243,7 @@ void DucoDiscovery::dump_config() {
for (uint8_t node = 0; node < NODE_COUNT; node++) {
const uint8_t type = this->node_types_[node];
if (type != 0) {
ESP_LOGCONFIG(TAG, " Node %u: type %u (%s)", node, type, LOG_STR_ARG(node_type_name(type)));
ESP_LOGCONFIG(TAG, " Node %u: type %u (%s)", node, type & ~NODE_TYPE_BS, LOG_STR_ARG(node_type_name(type)));
}
}
if (this->next_node_ < NODE_COUNT) {
+17 -3
View File
@@ -6,6 +6,7 @@
#include "esphome/components/uart/uart.h"
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
@@ -17,6 +18,13 @@ namespace esphome::duco {
static constexpr uint8_t FUNCTION_NODE = 0x0c; // discovery, status and mode of a node
static constexpr uint8_t FUNCTION_NODE_DATA = 0x10; // a block of a node's data (sensors, serial number)
static constexpr uint8_t FUNCTION_PARAMETER = 0x24; // read or write a box parameter, set the clock
static constexpr uint8_t FUNCTION_ERRORS = 0x30; // the active errors of a node
/// Set in a node type byte for a node on network type 3 (BS); the node type codes stay below it.
static constexpr uint8_t NODE_TYPE_BS = 0x80;
/// The name of a node type byte.
const LogString *node_type_name(uint8_t type);
/// A received message; data points into the receive buffer and is valid only during the callback.
struct DucoMessage {
@@ -25,6 +33,11 @@ struct DucoMessage {
uint8_t size;
};
/// The node type byte of a non-empty node answer; a one-byte answer has no network type.
inline uint8_t node_type_byte(const DucoMessage &message) {
return message.data[0] | (message.size >= 2 && message.data[1] == 3 ? NODE_TYPE_BS : 0);
}
class DucoDevice;
/// The open request of one device: the answer to it is function + 2 with the same message id.
@@ -53,8 +66,9 @@ class Duco : public uart::UARTDevice, public Component {
void send(DucoDevice *device, uint8_t function, std::initializer_list<uint8_t> data);
protected:
// The longest answer to a request sent here is 25 bytes (node status), the longest request 9
static constexpr size_t MAX_FRAME_SIZE = 32;
// The longest answer to a request sent here is 39 bytes (box serial number), the longest request 9.
// An error answer is 1 + 5 bytes per error, so one with more than eight errors is dropped.
static constexpr size_t MAX_FRAME_SIZE = 48;
static constexpr size_t MAX_REQUEST_DATA = 9;
bool parse_byte_(uint8_t byte);
@@ -89,7 +103,7 @@ class DucoDiscovery : public DucoDevice {
protected:
static constexpr uint8_t NODE_COUNT = 0x45;
std::array<uint8_t, NODE_COUNT> node_types_{}; // 0 when no node answered at that address
std::array<uint8_t, NODE_COUNT> node_types_{}; // node type bytes, 0 when no node answered at that address
uint8_t next_node_{0};
uint8_t attempts_{0};
};
@@ -1,5 +1,8 @@
import esphome.codegen as cg
from esphome.components import text_sensor
from esphome.components.const import CONF_SERIAL_NUMBER
import esphome.config_validation as cv
from esphome.const import CONF_ADDRESS, CONF_VERSION
from esphome.types import ConfigType
from .. import (
@@ -13,15 +16,71 @@ from .. import (
DEPENDENCIES = ["duco"]
CODEOWNERS = ["@kokx"]
DucoSerial = duco_ns.class_("DucoSerial", DucoDevice, text_sensor.TextSensor)
DucoTextSensor = duco_ns.class_("DucoTextSensor", DucoDevice, text_sensor.TextSensor)
DucoTextReading = duco_ns.enum("DucoTextReading", is_class=True)
CONFIG_SCHEMA = (
text_sensor.text_sensor_schema(DucoSerial)
.extend(cv.polling_component_schema("300s"))
.extend(DUCO_COMPONENT_SCHEMA)
CONF_ERROR = "error"
CONF_UPTIME = "uptime"
CONF_NODE_TYPE = "node_type"
# key: (what is read, lowest address, update interval); address 0 of a serial number is the box itself
TEXT_SENSORS = {
CONF_SERIAL_NUMBER: (DucoTextReading.DUCO_TEXT_READING_SERIAL_NUMBER, 0, "300s"),
CONF_VERSION: (DucoTextReading.DUCO_TEXT_READING_VERSION, 1, "300s"),
CONF_ERROR: (DucoTextReading.DUCO_TEXT_READING_ERROR, 1, "60s"),
CONF_UPTIME: (DucoTextReading.DUCO_TEXT_READING_UPTIME, 1, "60s"),
CONF_NODE_TYPE: (DucoTextReading.DUCO_TEXT_READING_NODE_TYPE, 1, "300s"),
}
def _schema(min_address: int, update_interval: str) -> cv.Schema:
return (
text_sensor.text_sensor_schema(DucoTextSensor)
.extend(
{
cv.Optional(CONF_ADDRESS, default=min_address): cv.int_range(
min=min_address, max=0x44
),
}
)
.extend(cv.polling_component_schema(update_interval))
)
_SCHEMAS = {
key: _schema(min_address, update_interval)
for key, (_, min_address, update_interval) in TEXT_SENSORS.items()
}
CONFIG_SCHEMA = cv.Any(
_SCHEMAS[CONF_SERIAL_NUMBER].extend(DUCO_COMPONENT_SCHEMA),
cv.All(
DUCO_COMPONENT_SCHEMA.extend(
{
cv.Optional(key): cv.ensure_list(schema)
for key, schema in _SCHEMAS.items()
}
),
cv.has_at_least_one_key(*TEXT_SENSORS),
),
)
async def to_code(config: ConfigType) -> None:
var = await text_sensor.new_text_sensor(config)
await register_duco_device(var, config, config[CONF_DUCO_ID])
if CONF_ADDRESS in config:
var = await text_sensor.new_text_sensor(
config,
TEXT_SENSORS[CONF_SERIAL_NUMBER][0],
config[CONF_ADDRESS],
)
await register_duco_device(var, config, config[CONF_DUCO_ID])
return
if config.get(CONF_ERROR):
cg.add_define("USE_DUCO_ERROR_TEXT_SENSOR")
for key, (reading, _, _) in TEXT_SENSORS.items():
for entity_config in config.get(key, []):
var = await text_sensor.new_text_sensor(
entity_config, reading, entity_config[CONF_ADDRESS]
)
await register_duco_device(var, entity_config, config[CONF_DUCO_ID])
@@ -1,17 +0,0 @@
#include "serial.h"
#include <cstring>
namespace esphome::duco {
void DucoSerial::update() { this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, 0x01, 0x00, 0x1a, 0x10}); }
void DucoSerial::receive_response(const DucoMessage &message) {
if (message.size > 2) {
// The serial number starts at byte 2 and is padded with zeros
const char *serial = reinterpret_cast<const char *>(message.data + 2);
this->publish_state(serial, strnlen(serial, message.size - 2));
}
}
} // namespace esphome::duco
@@ -1,15 +0,0 @@
#pragma once
#include "esphome/components/text_sensor/text_sensor.h"
#include "../duco.h"
namespace esphome::duco {
class DucoSerial : public DucoDevice, public text_sensor::TextSensor {
public:
void update() override;
void receive_response(const DucoMessage &message) override;
};
} // namespace esphome::duco
@@ -0,0 +1,187 @@
#include "text_sensor.h"
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
namespace esphome::duco {
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
// Only built when an error text sensor is configured; the tables are about 3 kB of flash
ESPHOME_LOG_TAG(TAG, "duco.text_sensor");
static constexpr size_t MAX_ERROR_TEXT_LENGTH = 255;
PROGMEM_STRING_TABLE(ErrorCodes, "E01.04.01", "E03.01.01", "E03.01.02", "E03.01.03", "E03.01.04", "E03.01.05",
"E03.01.06", "E04.01.01", "E04.01.02", "E04.01.03", "E04.01.04", "E04.01.05", "E04.01.06",
"E06.01.01", "E06.01.02", "E06.01.03", "E06.01.04", "E06.01.05", "E06.01.06", "E16.01.01",
"E16.01.02", "E16.01.03", "E16.01.04", "E16.01.05", "E16.01.06", "E28.04.01", "E29.01.01",
"E29.01.02", "E29.01.03", "E29.01.04", "E29.01.05", "E29.01.06", "E30.01.01", "E30.01.02",
"E30.01.03", "E30.01.04", "E30.01.05", "E30.01.06", "E31.19.01", "E32.10.01", "E33.10.01",
"E35.17.01", "E35.17.02", "E35.17.03", "E36.24.01", "E36.24.02", "E37.17.01", "E37.17.02",
"E37.17.03", "E40.17.01", "E40.17.02", "E40.17.03", "E42.22.01", "E42.22.02", "E43.23.01",
"E43.23.02", "E44.06.01", "E44.06.02");
PROGMEM_STRING_TABLE(
ErrorDescriptions, "No response from the extractor fan.", "ODA temperature sensor value is too low.",
"ODA temperature sensor value is too high.", "ODA temperature sensor cannot be read.",
"ODA temperature sensor value is unchanged for too long.", "ODA temperature sensor is short-circuited.",
"ODA temperature sensor has a bad connection.", "ETA temperature sensor value is too low.",
"ETA temperature sensor value is too high.", "ETA temperature sensor cannot be read.",
"ETA temperature sensor value is unchanged for too long.", "ETA temperature sensor is short-circuited.",
"ETA temperature sensor has a bad connection.", "EHA temperature sensor value is too low.",
"EHA temperature sensor value is too high.", "EHA temperature sensor cannot be read.",
"EHA temperature sensor value is unchanged for too long.", "EHA temperature sensor is short-circuited.",
"EHA temperature sensor has a bad connection.", "Extract air pressure sensor value is too low.",
"Extract air pressure sensor value is too high.", "Extract air pressure sensor cannot be read.",
"Extract air pressure sensor value is unchanged for too long.", "Extract air pressure sensor is short-circuited.",
"Extract air pressure sensor has a bad connection.", "No response from the supply fan.",
"Supply air pressure sensor value is too low.", "Supply air pressure sensor value is too high.",
"Supply air pressure sensor cannot be read.", "Supply air pressure sensor value is unchanged for too long.",
"Supply air pressure sensor is short-circuited.", "Supply air pressure sensor has a bad connection.",
"SUP temperature sensor value is too low.", "SUP temperature sensor value is too high.",
"SUP temperature sensor cannot be read.", "SUP temperature sensor value is unchanged for too long.",
"SUP temperature sensor is short-circuited.", "SUP temperature sensor has a bad connection.",
"Filters need replacement.", "Outdoor temperature is too low; ventilation is off for 8 hours.",
"Outdoor temperature is too low; ventilation is permanently off.", "Temperature sensor value is too low.",
"Temperature sensor value is too high.", "Temperature sensor cannot be read.",
"Connection to the weather station has been lost.", "Connection to the outdoor temperature sensor has been lost.",
"CO2 sensor value is too low.", "CO2 sensor value is too high.", "CO2 sensor cannot be read.",
"Humidity sensor value is too low.", "Humidity sensor value is too high.", "Humidity sensor cannot be read.",
"Too many valves are connected.", "Too few valves are connected; at least two are required.",
"Flow adjustment has not happened or failed.", "The requested flow rate cannot be achieved.",
"No connection to the Duco Pre-Heater.", "A Duco Pre-Heater is connected but not configured.",
"Unknown DUCO error");
static_assert(ErrorCodes::COUNT + 1 == ErrorDescriptions::COUNT);
// One line per error, with its description or only its code. Returns the text length, or 0 if it does not fit
// in MAX_ERROR_TEXT_LENGTH; text holds one byte more than that so a cut off text is told apart from a full one.
static size_t format_errors(const uint8_t *records, uint8_t count, char *text, size_t size, bool descriptions) {
size_t pos = 0;
for (uint8_t index = 0; index < count; index++) {
const uint8_t *record = records + index * 5;
const size_t code_start = pos;
pos = buf_append_printf(text, size, pos, "E%02u.%02u.%02u", record[1], record[2], record[3]);
if (descriptions && pos < size) {
const int16_t description_index = progmem_string_table_find<ErrorCodes>(text + code_start, pos - code_start);
pos = buf_append_str(text, size, pos, " ");
pos = buf_append_str_p(text, size, pos,
reinterpret_cast<ESPHOME_PGM_P>(
ErrorDescriptions::get_progmem_str(description_index, ErrorDescriptions::LAST_INDEX)));
}
pos = buf_append_str(text, size, pos, "\n");
}
return pos <= MAX_ERROR_TEXT_LENGTH ? pos : 0;
}
#endif
void DucoTextSensor::update() {
switch (this->reading_) {
case DucoTextReading::DUCO_TEXT_READING_SERIAL_NUMBER:
// Address 0 selects the separate box serial; nodes use a different data block (main board is node 1)
if (this->address_ == 0) {
this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, 0x01, 0x00, 0x1a, 0x10});
} else {
this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, this->address_, 0x00, 0x08, 0x06});
}
break;
case DucoTextReading::DUCO_TEXT_READING_VERSION:
this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, this->address_, 0x00, 0x00, 0x04});
break;
case DucoTextReading::DUCO_TEXT_READING_ERROR:
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
this->parent_->send(this, FUNCTION_ERRORS, {this->address_, 0x00, 0x00, 0x04});
#endif
break;
case DucoTextReading::DUCO_TEXT_READING_UPTIME:
this->parent_->send(this, FUNCTION_NODE_DATA, {0x01, this->address_, 0x00, 0x49, 0x04});
break;
case DucoTextReading::DUCO_TEXT_READING_NODE_TYPE:
this->parent_->send(this, FUNCTION_NODE, {0x01, this->address_});
break;
}
}
void DucoTextSensor::receive_response(const DucoMessage &message) {
switch (this->reading_) {
case DucoTextReading::DUCO_TEXT_READING_SERIAL_NUMBER:
this->publish_serial_number_(message);
break;
case DucoTextReading::DUCO_TEXT_READING_VERSION:
this->publish_version_(message);
break;
case DucoTextReading::DUCO_TEXT_READING_ERROR:
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
this->publish_errors_(message);
#endif
break;
case DucoTextReading::DUCO_TEXT_READING_UPTIME:
this->publish_uptime_(message);
break;
case DucoTextReading::DUCO_TEXT_READING_NODE_TYPE:
if (message.size >= 1)
this->publish_state(reinterpret_cast<ProgmemStr>(node_type_name(node_type_byte(message))));
break;
}
}
void DucoTextSensor::publish_serial_number_(const DucoMessage &message) {
if (message.size <= 2)
return;
// The serial number starts at byte 2 and is padded with zeros
const char *serial = reinterpret_cast<const char *>(message.data + 2);
const auto serial_length = strnlen(serial, message.size - 2);
if (serial_length == 0 || !std::all_of(serial, serial + serial_length, [](char character) {
return std::isprint(static_cast<unsigned char>(character));
})) {
return;
}
this->publish_state(serial, serial_length);
}
void DucoTextSensor::publish_version_(const DucoMessage &message) {
if (message.size < 7)
return;
const unsigned major = encode_uint16(message.data[3], message.data[2]);
const unsigned minor = message.data[4], patch = message.data[6], build = message.data[5];
char version[20];
snprintf(version, sizeof(version), "%u.%u.%u.%u", major, minor, patch, build);
this->publish_state(version);
}
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
void DucoTextSensor::publish_errors_(const DucoMessage &message) {
if (message.size == 0 || message.data[0] == 0) {
this->publish_state("No errors");
return;
}
const uint8_t error_count = message.data[0];
if (message.size < 1 + static_cast<size_t>(error_count) * 5) {
ESP_LOGW(TAG, "Error answer for %u errors has only %u bytes", error_count, message.size);
return;
}
char text[MAX_ERROR_TEXT_LENGTH + 2];
size_t length = format_errors(message.data + 1, error_count, text, sizeof(text), true);
if (length == 0) // the descriptions do not fit, the codes always do
length = format_errors(message.data + 1, error_count, text, sizeof(text), false);
this->publish_state(text, length);
}
#endif
void DucoTextSensor::publish_uptime_(const DucoMessage &message) {
if (message.size < 10)
return;
const unsigned uptime_minutes = encode_uint16(message.data[9], message.data[8]);
const unsigned days = uptime_minutes / 1440;
const unsigned hours = uptime_minutes % 1440 / 60;
const unsigned minutes = uptime_minutes % 60;
char formatted[24];
snprintf(formatted, sizeof(formatted), "%ud %uh %um", days, hours, minutes);
this->publish_state(formatted);
}
} // namespace esphome::duco
@@ -0,0 +1,38 @@
#pragma once
#include "esphome/components/text_sensor/text_sensor.h"
#include "../duco.h"
namespace esphome::duco {
/// What a text sensor reads.
enum class DucoTextReading : uint8_t {
DUCO_TEXT_READING_SERIAL_NUMBER,
DUCO_TEXT_READING_VERSION,
DUCO_TEXT_READING_ERROR,
DUCO_TEXT_READING_UPTIME,
DUCO_TEXT_READING_NODE_TYPE,
};
class DucoTextSensor : public DucoDevice, public text_sensor::TextSensor {
public:
/// address is the node address; a serial number at address 0 is the box itself.
DucoTextSensor(DucoTextReading reading, uint8_t address) : reading_(reading), address_(address) {}
void update() override;
void receive_response(const DucoMessage &message) override;
protected:
void publish_serial_number_(const DucoMessage &message);
void publish_version_(const DucoMessage &message);
#ifdef USE_DUCO_ERROR_TEXT_SENSOR
void publish_errors_(const DucoMessage &message);
#endif
void publish_uptime_(const DucoMessage &message);
DucoTextReading reading_;
uint8_t address_;
};
} // namespace esphome::duco
+1 -1
View File
@@ -22,7 +22,7 @@ void EE895Component::setup() {
uint8_t serial_number[20];
this->read(serial_number, 20);
crc16_check = (serial_number[19] << 8) + serial_number[18];
crc16_check = encode_value_le<uint16_t>(serial_number + 18);
if (!this->setup_check(crc16_check == calc_crc16_(serial_number, 18), LOG_STR("CRC check failed")))
return;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
@@ -10,7 +10,7 @@ from esphome.components.const import CONF_PROVIDER, CONF_REMOTE_ID
from esphome.components.packet_interface import (
CONF_PACKET_INTERFACE,
final_validate_interface,
interface_layers,
interface_has_layer,
interface_packet_size,
)
from esphome.components.packet_interface.layers import CONF_SESSION
@@ -103,11 +103,13 @@ CONFIG_SCHEMA = cv.Schema(
def _final_validate(config: ConfigType) -> ConfigType:
"""With a session layer, which clears the states when the peer is lost, nothing would refresh an unchanged state."""
layers = interface_layers(config[CONF_PACKET_INTERFACE])
if CONF_TIMEOUT in config and CONF_SESSION in layers:
if CONF_TIMEOUT in config and interface_has_layer(
config[CONF_PACKET_INTERFACE], CONF_SESSION
):
raise cv.Invalid(
f"Not allowed with a '{CONF_SESSION}' layer, which already clears the states when the other device "
"cannot be reached; unchanged states may never be sent again, so they would time out on a working link",
f"Not allowed with a '{CONF_SESSION}' layer, or a link that does its job, which already clears the "
"states when the other device cannot be reached; unchanged states may never be sent again, so they "
"would time out on a working link",
path=[CONF_TIMEOUT],
)
return config
@@ -4,6 +4,7 @@
#include <cstring>
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome::entity_transport {
@@ -373,8 +374,7 @@ size_t EntityTransport::write_record_(const LocalEntity &entity, uint8_t *record
#endif
uint16_t tag =
entity.number | (type << TAG_TYPE_SHIFT) | (payload << TAG_PAYLOAD_SHIFT) | (value ? TAG_VALUE_BIT : 0);
record[0] = tag;
record[1] = tag >> 8;
put_le16(record, tag);
return size;
}
+39 -25
View File
@@ -56,7 +56,6 @@ from esphome.const import (
from esphome.core import CORE, EsphomeError, HexInt
from esphome.core.config import BOARD_MAX_LENGTH
from esphome.coroutine import CoroPriority, coroutine_with_priority
from esphome.espidf import sbom
from esphome.espidf.component import IDFComponent, generate_idf_components
import esphome.final_validate as fv
from esphome.helpers import copy_file_if_changed, rmtree, write_file_if_changed
@@ -331,32 +330,25 @@ ARDUINO_EXCLUDED_IDF_COMPONENTS = (
"joltwallet__littlefs", # LittleFS - ESPHome doesn't use filesystem
)
# Entries arduino-esp32 only declares below the given IDF version; stubbing one past
# it clashes with ESPHome's own managed component of the same short name.
ARDUINO_EXCLUDED_IDF_COMPONENTS_MAX_IDF: dict[str, cv.Version] = {
"espressif__libsodium": cv.Version(6, 0, 0),
# arduino-esp32 dependencies that ESPHome replaces with its own component when a
# build uses it, through the manifest "overrides" field. IDF cannot hold two
# components of the same short name, so a stub would clash with the replacement.
ARDUINO_OVERRIDDEN_IDF_COMPONENTS: dict[str, str] = {
"espressif/libsodium": "esphome/libsodium",
}
def manifest_overrides_supported() -> bool:
"""Whether the IDF component manager reads the manifest "overrides" field.
pioarduino pins idf-component-manager 2.4 for ESP-IDF 5, which predates it.
"""
return CORE.using_toolchain_esp_idf or idf_version() >= cv.Version(6, 0, 0)
def arduino_bundles_libsodium() -> bool:
"""arduino-esp32 ships its own libsodium below IDF 6.0."""
return (
CORE.using_arduino
and idf_version()
< ARDUINO_EXCLUDED_IDF_COMPONENTS_MAX_IDF["espressif__libsodium"]
)
def arduino_excluded_idf_components() -> set[str]:
"""The arduino-bundled components to stub for this build's IDF version."""
version = idf_version()
return {
component
for component in ARDUINO_EXCLUDED_IDF_COMPONENTS
if (max_version := ARDUINO_EXCLUDED_IDF_COMPONENTS_MAX_IDF.get(component))
is None
or version < max_version
}
"""arduino-esp32's own libsodium is in the build and cannot be replaced."""
return CORE.using_arduino and not manifest_overrides_supported()
# Mapping of Arduino libraries to IDF managed components they require
@@ -3914,6 +3906,15 @@ def _write_idf_component_yml():
# on path order. Such a stub points at the converted library instead.
converted_by_name = {component.path.name: component for component in converted}
overridden: dict[str, str] = {}
if CORE.using_arduino and manifest_overrides_supported():
managed_components = CORE.data[KEY_ESP32].get(KEY_COMPONENTS, {})
overridden = {
target: replacement
for target, replacement in ARDUINO_OVERRIDDEN_IDF_COMPONENTS.items()
if replacement in managed_components
}
# For Arduino builds, override unused managed components from the Arduino framework
# by pointing them to empty stub directories using override_path
# This prevents the IDF component manager from downloading the real components
@@ -3927,7 +3928,9 @@ def _write_idf_component_yml():
}
# Only stub components that are not required by any enabled Arduino library
components_to_stub = arduino_excluded_idf_components() - required_idf_components
components_to_stub = (
set(ARDUINO_EXCLUDED_IDF_COMPONENTS) - required_idf_components
)
stubs_dir = CORE.relative_build_path("component_stubs")
stubs_dir.mkdir(exist_ok=True)
@@ -3939,6 +3942,8 @@ def _write_idf_component_yml():
for component_name in sorted(components_to_stub):
stub_name = _idf_component_stub_name(component_name)
stub_path = stubs_dir / stub_name
if _idf_component_dep_name(component_name) in overridden:
continue
if (component := converted_by_name.get(stub_name)) is not None:
if stub_path.exists():
rmtree(stub_path)
@@ -4006,7 +4011,13 @@ def _write_idf_component_yml():
dependency["path"] = component[KEY_PATH]
dependencies[name] = dependency
contents = yaml_util.dump({"dependencies": dependencies}) if dependencies else ""
manifest: dict[str, Any] = {"dependencies": dependencies}
if overridden:
manifest["overrides"] = [
{target: {"with": {replacement: dependencies[replacement]}}}
for target, replacement in overridden.items()
]
contents = yaml_util.dump(manifest) if dependencies else ""
if write_file_if_changed(yml_path, contents):
dependencies_lock = CORE.relative_build_path("dependencies.lock")
if dependencies_lock.is_file():
@@ -4033,6 +4044,9 @@ def copy_files():
CORE.relative_build_path("version.txt"),
__version__,
)
# Imported here: sbom loads git and urllib helpers that config validation does not need
from esphome.espidf import sbom
sbom.write_manifests()
# Remote extra build files are fetched into the shared download cache in
+4 -1
View File
@@ -37,7 +37,10 @@ __attribute__((always_inline)) inline bool is_main_loop_thread() {
return xTaskGetCurrentTaskHandle() == esphome_main_task_handle;
}
__attribute__((always_inline)) inline void yield() { vPortYield(); }
__attribute__((always_inline)) inline void delay(uint32_t ms) { vTaskDelay(ms / portTICK_PERIOD_MS); }
// vTaskDelay() counts the partial tick, so one more tick makes the wait at least ms
__attribute__((always_inline)) inline void delay(uint32_t ms) {
vTaskDelay(ms == 0 ? 0 : (ms + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS + 1);
}
__attribute__((always_inline)) inline uint32_t micros() { return static_cast<uint32_t>(esp_timer_get_time()); }
uint32_t millis();
__attribute__((always_inline)) inline uint64_t millis_64() {
+4 -20
View File
@@ -33,34 +33,18 @@ IRAM_ATTR InterruptLock::~InterruptLock() { portENABLE_INTERRUPTS(); }
LwIPLock::LwIPLock() {
#ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING
// When CONFIG_LWIP_TCPIP_CORE_LOCKING is enabled, lwIP uses a global mutex to protect
// its internal state. Any thread can take this lock to safely access lwIP APIs.
//
// sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) returns true if the current thread
// already holds the lwIP core lock. This prevents recursive locking attempts and
// allows nested LwIPLock instances to work correctly.
//
// If we don't already hold the lock, acquire it. This will block until the lock
// is available if another thread currently holds it.
// A thread that already holds the core lock (lwIP took it for a tcpip_api_call or netif callback, or an
// outer LwIPLock did) must not take it again, and must not release it when this nested guard ends.
if (!sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) {
LOCK_TCPIP_CORE();
this->locked_ = true;
}
#endif
}
LwIPLock::~LwIPLock() {
#ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING
// Only release the lwIP core lock if this thread currently holds it.
//
// sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) queries lwIP's internal lock
// ownership tracking. It returns true only if the current thread is registered
// as the lock holder.
//
// This check is essential because:
// 1. We may not have acquired the lock in the constructor (if we already held it)
// 2. The lock might have been released by other means between constructor and destructor
// 3. Calling UNLOCK_TCPIP_CORE() without holding the lock causes undefined behavior
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) {
if (this->locked_) {
UNLOCK_TCPIP_CORE();
}
#endif
+42 -13
View File
@@ -567,30 +567,46 @@ async def to_code(config: ConfigType) -> None:
request_bluetooth()
# Replace Bluedroid's only two sscanf callers so newlib's scanf engine is not
# linked; see bluedroid_hex_wraps.cpp. IDF 6.0+ uses picolibc, not newlib.
if (
not CORE.using_arduino
and idf_version() < cv.Version(6, 0, 0)
and get_esp32_variant() not in ROM_SSCANF_VARIANTS
# Replace Bluedroid's only two sscanf callers so the C library's scanf engine is
# not linked; see bluedroid_hex_wraps.cpp. The ROM only provides sscanf for newlib,
# which IDF 6.0 replaced with picolibc.
if not CORE.using_arduino and (
idf_version() >= cv.Version(6, 0, 0)
or get_esp32_variant() not in ROM_SSCANF_VARIANTS
):
cg.add_define("USE_ESP32_BLE_BLUEDROID_HEX_WRAPS")
_wrap_bluedroid_symbols("btc_config_get_bin", "string_to_bdaddr")
# The headers only feed bluedroid_hex_wraps.cpp's ESP-IDF drift checks
add_src_cmake(bluedroid_headers_cmake("bluedroid_hex_wraps.cpp"))
# ESP-IDF 5.5.6 drops bond keys on re-encryption (see bluedroid_bond_keys.c). Needs the
# native toolchain for Bluedroid's private headers; Windows response files lose them.
# ESP-IDF 5.5.6 and 6.1.1 drop bond keys on re-encryption (see bluedroid_bond_keys.c). Needs
# the native toolchain for Bluedroid's private headers; Windows response files lose them.
if (
CORE.using_toolchain_esp_idf
and not IS_WINDOWS
and cv.Version(5, 5, 6) <= idf_version() < cv.Version(6, 0, 0)
and _drops_bond_keys(idf_version())
):
cg.add_define("USE_ESP32_BLE_BLUEDROID_BOND_KEYS")
_wrap_bluedroid_symbols("smp_check_auth_req", "btm_sec_clear_ble_keys")
add_src_cmake(bluedroid_headers_cmake("bluedroid_bond_keys.c"))
# ESP-IDF 5.5.6 and 6.0.3 end GATT discovery on a response listing handles out of order
# Bluedroid runs a queued MTU or execute write request that fails at once again until the BTU task stack
# overflows (see bluedroid_gattc_queue.c); every ESP-IDF release so far. Private headers, as above.
if (
CORE.using_toolchain_esp_idf
and not IS_WINDOWS
and _has_gatt_client(CORE.config)
):
cg.add_define("USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE")
_wrap_bluedroid_symbols(
"bta_gattc_cfg_mtu",
"bta_gattc_execute",
"GATTC_ConfigureMTU",
"GATTC_ExecuteWrite",
)
add_src_cmake(bluedroid_headers_cmake("bluedroid_gattc_queue.c"))
# ESP-IDF 5.5.6, 6.0.3 and 6.1.1 end GATT discovery on a response listing handles out of order
# (see bluedroid_gattc_order.cpp). It needs no Bluedroid headers, so any toolchain works.
if _has_gatt_client(CORE.config) and _has_strict_handle_order(idf_version()):
cg.add_define("USE_ESP32_BLE_GATTC_HANDLE_ORDER")
@@ -667,11 +683,23 @@ def _has_gatt_client(config: ConfigType) -> bool:
return "esp32_ble_tracker" in config or "esp32_ble_client" in config
def _has_strict_handle_order(version: cv.Version) -> bool:
"""Whether this ESP-IDF rejects discovery responses whose handles are out of order."""
def _drops_bond_keys(version: cv.Version) -> bool:
"""Whether this ESP-IDF clears a bonded device's keys when it re-encrypts."""
return cv.Version(5, 5, 6) <= version < cv.Version(
6, 0, 0
) or version >= cv.Version(6, 0, 3)
) or version >= cv.Version(6, 1, 1)
def _has_strict_handle_order(version: cv.Version) -> bool:
"""Whether this ESP-IDF rejects discovery responses whose handles are out of order.
ESP-IDF 6.1.0 was released before the check reached the 6.1 line.
"""
return (
cv.Version(5, 5, 6) <= version < cv.Version(6, 0, 0)
or cv.Version(6, 0, 3) <= version < cv.Version(6, 1, 0)
or version >= cv.Version(6, 1, 1)
)
# ble_advertising.cpp is fully #ifdef'd on USE_ESP32_BLE_ADVERTISING, set
@@ -681,6 +709,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_defines(
"ble_advertising.cpp": "USE_ESP32_BLE_ADVERTISING",
"bluedroid_hex_wraps.cpp": "USE_ESP32_BLE_BLUEDROID_HEX_WRAPS",
"bluedroid_bond_keys.c": "USE_ESP32_BLE_BLUEDROID_BOND_KEYS",
"bluedroid_gattc_queue.c": "USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE",
"bluedroid_gattc_order.cpp": "USE_ESP32_BLE_GATTC_HANDLE_ORDER",
}
)
@@ -1,4 +1,4 @@
// Linker wraps that keep a bonded device's keys when it re-encrypts without pairing again (ESP-IDF 5.5.6).
// Linker wraps that keep a bonded device's keys when it re-encrypts without pairing again (ESP-IDF 5.5.6, 6.1.1).
// Same guard as espressif/esp-idf#19322; drop once ESPHome uses an ESP-IDF release that contains it.
// C, because Bluedroid's btm_ble_int.h does not close its extern "C" block.
@@ -1,5 +1,5 @@
// Linker wrap that puts a GATT discovery response back in handle order before Bluedroid parses it.
// ESP-IDF 5.5.6 and 6.0.3 end the whole discovery when a peer lists handles out of order (esphome#22518), which
// ESP-IDF 5.5.6, 6.0.3 and 6.1.1 end the whole discovery when a peer lists handles out of order (esphome#22518), which
// earlier releases, Android and BlueZ accept.
#include "esphome/core/defines.h"
@@ -0,0 +1,67 @@
// Linker wraps that stop Bluedroid running a failed queued MTU or execute write request again until the BTU task
// stack overflows (esphome#17954). The same fix as removing the command from p_cmd_list in bta_gattc_act.c before
// the failure path pops the queue; drop once an ESP-IDF release has it.
// Compiled only with Bluedroid's private headers (bluedroid_headers_cmake); static analysis skips it
#ifdef USE_ESP32_BLE_BLUEDROID_HEADERS
#include <stddef.h>
#include "bta_gattc_int.h"
#include "osi/list.h"
// The command bta_gattc_cfg_mtu() or bta_gattc_execute() is running, NULL outside them
static tBTA_GATTC_CLCB *running_clcb = NULL;
static tBTA_GATTC_DATA *running_cmd = NULL;
void __real_bta_gattc_cfg_mtu(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data);
void __real_bta_gattc_execute(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data);
tGATT_STATUS __real_GATTC_ConfigureMTU(UINT16 conn_id);
tGATT_STATUS __real_GATTC_ExecuteWrite(UINT16 conn_id, BOOLEAN is_execute);
// Runs on the Bluetooth host task; the failure path pops the queue again, so this nests
static void run_command(void (*real)(tBTA_GATTC_CLCB *, tBTA_GATTC_DATA *), tBTA_GATTC_CLCB *p_clcb,
tBTA_GATTC_DATA *p_data) {
tBTA_GATTC_CLCB *const outer_clcb = running_clcb;
tBTA_GATTC_DATA *const outer_cmd = running_cmd;
running_clcb = p_clcb;
running_cmd = p_data;
real(p_clcb, p_data);
running_clcb = outer_clcb;
running_cmd = outer_cmd;
}
// The send failed, so the caller clears p_q_cmd and pops the queue. A command popped from p_cmd_list is still its
// head and would run again; remove (and free) it first. A command not from the queue is not in it: a no-op.
static void drop_failed_command(void) {
if (running_clcb != NULL && running_clcb->p_cmd_list != NULL && running_clcb->p_q_cmd == running_cmd) {
list_remove(running_clcb->p_cmd_list, running_cmd);
}
}
void __wrap_bta_gattc_cfg_mtu(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data) {
run_command(__real_bta_gattc_cfg_mtu, p_clcb, p_data);
}
void __wrap_bta_gattc_execute(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data) {
run_command(__real_bta_gattc_execute, p_clcb, p_data);
}
// The failure checks are the ones bta_gattc_cfg_mtu() and bta_gattc_execute() make
tGATT_STATUS __wrap_GATTC_ConfigureMTU(UINT16 conn_id) {
const tGATT_STATUS status = __real_GATTC_ConfigureMTU(conn_id);
if (status != GATT_SUCCESS && status != GATT_CMD_STARTED) {
drop_failed_command();
}
return status;
}
tGATT_STATUS __wrap_GATTC_ExecuteWrite(UINT16 conn_id, BOOLEAN is_execute) {
const tGATT_STATUS status = __real_GATTC_ExecuteWrite(conn_id, is_execute);
if (status != BTA_GATT_OK) {
drop_failed_command();
}
return status;
}
#endif // USE_ESP32_BLE_BLUEDROID_HEADERS
@@ -1,4 +1,5 @@
// Linker wraps for the only two sscanf callers in Bluedroid, so newlib's scanf engine (~16 KB) is not linked.
// Linker wraps for the only two sscanf callers in Bluedroid, so the C library's scanf engine is not linked
// (~16 KB with newlib, ~4 KB with picolibc).
// Same parsing as espressif/esp-idf#19235; drop once ESPHome uses an ESP-IDF release that contains it.
#include "esphome/core/defines.h"
@@ -18,10 +18,12 @@ from esphome.components.esp32 import (
VARIANT_ESP32S31,
add_idf_sdkconfig_option,
get_esp32_variant,
idf_version,
)
from esphome.components.openthread.const import CONF_POLL_PERIOD
from esphome.components.psram import DOMAIN as PSRAM_DOMAIN
from esphome.components.zigbee import DOMAIN as ZIGBEE_DOMAIN
from esphome.config_helpers import filter_source_files_from_defines
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_OPENTHREAD
from esphome.core import CORE
@@ -32,6 +34,10 @@ from . import DOMAIN
_LOGGER = logging.getLogger(__name__)
FILTER_SOURCE_FILES = filter_source_files_from_defines(
{"tick_overflow_guard.cpp": "USE_ESP32_PM_TICK_OVERFLOW_GUARD"}
)
CODEOWNERS = ["@rwrozelle"]
DEPENDENCIES = ["esp32"]
@@ -187,6 +193,15 @@ async def to_code(config: ConfigType) -> None:
add_idf_sdkconfig_option(
"CONFIG_FREERTOS_IDLE_TIME_BEFORE_SLEEP", config[CONF_IDLE_TIME_BEFORE_SLEEP]
)
# Stop vTaskStepTick asserting on a tick overshoot after light sleep; built into
# IDF 6.0.1, backported by tick_overflow_guard.cpp before that.
if idf_version() >= cv.Version(6, 0, 1):
add_idf_sdkconfig_option("CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_PROTECTION", True)
else:
cg.add_define("USE_ESP32_PM_TICK_OVERFLOW_GUARD")
for symbol in ("vApplicationSleep", "vTaskStepTick"):
cg.add_build_flag(f"-Wl,--wrap={symbol}")
cg.add_build_flag(f"-Wl,--undefined=__wrap_{symbol}")
if config[CONF_POWER_DOWN_PERIPHERALS]:
add_idf_sdkconfig_option("CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP", True)
if config[CONF_POWER_DOWN_FLASH]:
@@ -0,0 +1,42 @@
#include "esphome/core/defines.h"
#ifdef USE_ESP32_PM_TICK_OVERFLOW_GUARD
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
namespace esphome::esp32_power_management {}
// IDF drops tickless idle on chips without light sleep support (ESP32-H4 and -H21 on 5.5), and then
// vApplicationSleep() does not exist
#if CONFIG_FREERTOS_USE_TICKLESS_IDLE
// Backport of IDF 6.0.1 CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_PROTECTION: clamp a small tick overshoot
// after light sleep so vTaskStepTick() does not assert.
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming,cppcoreguidelines-avoid-non-const-global-variables)
extern "C" {
void __real_vApplicationSleep(TickType_t expected_idle_time);
void __real_vTaskStepTick(TickType_t ticks_to_jump);
// Same default as IDF's CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_TOLERANCE; a larger overshoot still asserts
static constexpr TickType_t TICK_OVERFLOW_TOLERANCE = 2;
static TickType_t expected_idle_time[portNUM_PROCESSORS];
void __wrap_vApplicationSleep(TickType_t expected) {
expected_idle_time[xPortGetCoreID()] = expected;
__real_vApplicationSleep(expected);
}
// Only pm_impl.c calls vTaskStepTick(), from inside vApplicationSleep() on the same core
void __wrap_vTaskStepTick(TickType_t ticks) {
const TickType_t expected = expected_idle_time[xPortGetCoreID()];
if (ticks > expected && ticks <= expected + TICK_OVERFLOW_TOLERANCE)
ticks = expected;
__real_vTaskStepTick(ticks);
}
} // extern "C"
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming,cppcoreguidelines-avoid-non-const-global-variables)
#endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
#endif // USE_ESP32_PM_TICK_OVERFLOW_GUARD
@@ -185,9 +185,6 @@ EFFECTIVE_HIGH_VOLTAGE = {
}
register_touch_pad = cg.slot_list("ESP32_TOUCH_PAD_COUNT", "register_touch_pad", DOMAIN)
def validate_touch_pad(value: Any) -> int:
value = gpio.gpio_pin_number_validator(value)
variant = get_esp32_variant()
@@ -4,12 +4,7 @@ import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_PIN, CONF_THRESHOLD
from esphome.types import ConfigType
from . import (
ESP32TouchComponent,
esp32_touch_ns,
register_touch_pad,
validate_touch_pad,
)
from . import ESP32TouchComponent, esp32_touch_ns, validate_touch_pad
DEPENDENCIES = ["esp32_touch", "esp32"]
@@ -39,4 +34,4 @@ async def to_code(config: ConfigType) -> None:
config[CONF_WAKEUP_THRESHOLD],
)
await binary_sensor.register_binary_sensor(var, config)
cg.add(register_touch_pad(hub, var))
cg.add(hub.register_touch_pad(var))
+4 -2
View File
@@ -3,9 +3,10 @@
#ifdef USE_ESP32
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include <vector>
#include <driver/touch_sens.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
@@ -27,7 +28,7 @@ class ESP32TouchBinarySensor;
class ESP32TouchComponent final : public Component {
public:
SLOT_LIST(ESP32TouchBinarySensor, children_, register_touch_pad, ESP32_TOUCH_PAD_COUNT)
void register_touch_pad(ESP32TouchBinarySensor *pad) { this->children_.push_back(pad); }
void set_setup_mode(bool setup_mode) { this->setup_mode_ = setup_mode; }
void set_meas_interval_us(float meas_interval_us) { this->meas_interval_us_ = meas_interval_us; }
@@ -117,6 +118,7 @@ class ESP32TouchComponent final : public Component {
static bool on_inactive_cb(touch_sensor_handle_t handle, const touch_inactive_event_data_t *event, void *ctx);
// Common members
std::vector<ESP32TouchBinarySensor *> children_;
bool setup_mode_{false};
uint32_t setup_mode_last_log_print_{0};
+11 -5
View File
@@ -56,12 +56,18 @@ DEPENDENCIES = ["network"]
def AUTO_LOAD(config: ConfigType) -> list[str]:
"""Auto-load noise only when encryption is configured; the api key offer
inherits it from the api component."""
base = ["sha256", "socket"]
"""Auto-load sha256 only for password auth and noise only when encryption is
configured; the api key offer inherits noise from the api component."""
# A falsy config is a tooling probe for the maximal set
if not config or CONF_ENCRYPTION in config:
return base + ["noise"]
if not config:
return ["sha256", "socket", "noise"]
base = ["socket"]
# Keyed on the password alone, not password without encryption as USE_OTA_PASSWORD is:
# final validation can merge ota blocks, and a merged block must not lack sha256
if CONF_PASSWORD in config:
base.append("sha256")
if CONF_ENCRYPTION in config:
base.append("noise")
return base
+1 -1
View File
@@ -181,7 +181,7 @@ _IDF6_ETHERNET_COMPONENTS: dict[str, IDFRegistryComponent] = {
"IP101": IDFRegistryComponent("espressif/ip101", "1.1.0"),
"KSZ8081": IDFRegistryComponent("espressif/ksz80xx", "1.1.0"),
"KSZ8081RNA": IDFRegistryComponent("espressif/ksz80xx", "1.1.0"),
"W5500": IDFRegistryComponent("espressif/w5500", "2.0.1"),
"W5500": IDFRegistryComponent("espressif/w5500", "1.0.1"),
"DM9051": IDFRegistryComponent("espressif/dm9051", "1.1.1"),
"ENC28J60": IDFRegistryComponent("espressif/enc28j60", "1.1.0"),
"LAN8670": IDFRegistryComponent("espressif/lan867x", "2.1.0"),
@@ -7,6 +7,8 @@
#include "esphome/core/automation.h"
#include "esphome/components/network/ip_address.h"
#include <atomic>
#ifdef USE_ETHERNET
#ifdef USE_ESP32
@@ -366,6 +368,9 @@ class EthernetComponent final : public Component {
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
StaticVector<EthernetIPStateListener *, ESPHOME_ETHERNET_IP_STATE_LISTENERS> ip_state_listeners_;
#ifdef USE_ESP32
std::atomic<uint8_t> ip_state_pending_{0};
#endif
#endif
#ifdef USE_ETHERNET_CONNECT_TRIGGER
@@ -129,6 +129,14 @@ void EthernetComponent::log_error_and_mark_failed_(esp_err_t err, const char *me
void EthernetComponent::loop() {
const uint32_t now = App.get_loop_component_start_time();
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
// The IP events arrive on the event task; the listeners publish states, so notify them here
if (this->ip_state_pending_.load(std::memory_order_acquire) != 0) {
this->ip_state_pending_.store(0, std::memory_order_relaxed);
this->notify_ip_state_listeners_();
}
#endif
switch (this->state_) {
case EthernetComponentState::STOPPED:
if (this->started_) {
@@ -278,16 +286,9 @@ void EthernetComponent::ethernet_lazy_init_() {
#endif
#if defined(USE_ETHERNET_W5500)
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
w5500_config.base.int_gpio_num = this->interrupt_pin_;
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
w5500_config.base.poll_period_ms = this->polling_interval_;
#endif
#else
w5500_config.int_gpio_num = this->interrupt_pin_;
#ifdef USE_ETHERNET_SPI_POLLING_SUPPORT
w5500_config.poll_period_ms = this->polling_interval_;
#endif
#endif
// Install the custom SPI driver that offloads the bulk RX/TX frame transfers off the busy-wait
// path. w5500_config (and the devcfg it references) outlives esp_eth_mac_new_w5500() below, which
@@ -770,7 +771,8 @@ void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base
event_name = "ETH connected";
// For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
#if defined(USE_ETHERNET_IP_STATE_LISTENERS) && defined(USE_ETHERNET_MANUAL_IP)
global_eth_component->notify_ip_state_listeners_();
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
global_eth_component->enable_loop_soon_any_context();
#endif
#if USE_NETWORK_IPV6
// Start SLAAC on link-up, not after the DHCPv4 lease. This also restores the
@@ -798,6 +800,9 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
const esp_netif_ip_info_t *ip_info = &event->ip_info;
ESP_LOGV(TAG, "[Ethernet event] ETH Got IP " IPSTR, IP2STR(&ip_info->ip));
global_eth_component->got_ipv4_address_ = true;
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
#endif
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
global_eth_component->connected_ = global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT;
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
@@ -805,9 +810,6 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
global_eth_component->connected_ = true;
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
#endif /* USE_NETWORK_IPV6 */
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
global_eth_component->notify_ip_state_listeners_();
#endif
}
#if USE_NETWORK_IPV6
@@ -819,6 +821,9 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
// after a link flap fires another event for the same address.
struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
global_eth_component->ipv6_count_ = esp_netif_get_all_ip6(global_eth_component->eth_netif_, if_ip6s);
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
#endif
#if (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
global_eth_component->connected_ =
global_eth_component->got_ipv4_address_ && (global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
@@ -827,9 +832,6 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
global_eth_component->connected_ = global_eth_component->got_ipv4_address_;
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
#endif
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
global_eth_component->notify_ip_state_listeners_();
#endif
}
#endif /* USE_NETWORK_IPV6 */
@@ -32,16 +32,10 @@ void *w5500_custom_spi_init(const void *spi_config) {
auto *ctx = &w5500_context;
// The W5500 SPI frame carries the 16-bit address in the command phase and the 8-bit control
// byte in the address phase; mirror what the stock driver configures.
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
spi_device_interface_config_t devcfg = *config->base.spi_devcfg;
const spi_host_device_t spi_host_id = config->base.spi_host_id;
#else
spi_device_interface_config_t devcfg = *config->spi_devcfg;
const spi_host_device_t spi_host_id = config->spi_host_id;
#endif
devcfg.command_bits = 16;
devcfg.address_bits = 8;
if (spi_bus_add_device(spi_host_id, &devcfg, &ctx->handle) != ESP_OK) {
if (spi_bus_add_device(config->spi_host_id, &devcfg, &ctx->handle) != ESP_OK) {
ctx->handle = nullptr;
return nullptr;
}
@@ -113,19 +107,11 @@ void install_w5500_async_spi(eth_w5500_config_t &config) {
// Point the custom driver's config at the W5500 config itself; init() reads spi_host_id and
// spi_devcfg back out of it. The self-reference is valid because both the config and the
// spi_devcfg it points at outlive the esp_eth_mac_new_w5500() call that runs init().
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
config.base.custom_spi_driver.config = &config;
config.base.custom_spi_driver.init = w5500_custom_spi_init;
config.base.custom_spi_driver.deinit = w5500_custom_spi_deinit;
config.base.custom_spi_driver.read = w5500_custom_spi_read;
config.base.custom_spi_driver.write = w5500_custom_spi_write;
#else
config.custom_spi_driver.config = &config;
config.custom_spi_driver.init = w5500_custom_spi_init;
config.custom_spi_driver.deinit = w5500_custom_spi_deinit;
config.custom_spi_driver.read = w5500_custom_spi_read;
config.custom_spi_driver.write = w5500_custom_spi_write;
#endif
}
} // namespace esphome::ethernet
+1 -4
View File
@@ -143,9 +143,6 @@ CONFIG_SCHEMA = cv.All(
)
_add_trace = cg.slot_list("GRAPH_TRACE_COUNT", "add_trace", DOMAIN)
async def to_code(config: ConfigType) -> None:
var = cg.new_Pvariable(config[CONF_ID])
cg.add(var.set_duration(config[CONF_DURATION]))
@@ -182,7 +179,7 @@ async def to_code(config: ConfigType) -> None:
await cg.add_variable(tr.set_line_color, trace.get(CONF_COLOR))
if CONF_CONTINUOUS in trace:
cg.add(tr.set_continuous(trace[CONF_CONTINUOUS]))
cg.add(_add_trace(var, tr))
cg.add(var.add_trace(tr))
# Add legend
if CONF_LEGEND in config:
lgd = config[CONF_LEGEND]
+3 -2
View File
@@ -1,9 +1,9 @@
#pragma once
#include <cstdint>
#include <span>
#include <vector>
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/color.h"
#include "esphome/core/helpers.h"
#include "esphome/core/string_ref.h"
#include "esphome/core/component.h"
@@ -157,7 +157,7 @@ class Graph final : public Component {
void set_grid_x(float val) { this->gridspacing_x_ = val; }
void set_grid_y(float val) { this->gridspacing_y_ = val; }
void set_border(bool val) { this->border_ = val; }
SLOT_LIST(GraphTrace, traces_, add_trace, GRAPH_TRACE_COUNT)
void add_trace(GraphTrace *trace) { traces_.push_back(trace); }
void add_legend(GraphLegend *legend) {
this->legend_ = legend;
legend->init(this);
@@ -181,6 +181,7 @@ class Graph final : public Component {
float gridspacing_x_{NAN};
float gridspacing_y_{NAN};
bool border_{true};
std::vector<GraphTrace *> traces_;
GraphLegend *legend_{nullptr};
friend GraphLegend;
+17 -11
View File
@@ -5,6 +5,8 @@
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <cstring>
namespace esphome::i2c {
ESPHOME_LOG_TAG(TAG, "i2c");
@@ -52,22 +54,26 @@ ErrorCode I2CDevice::read_register16(uint16_t a_register, uint8_t *data, size_t
return bus_->write_readv(this->address_, reinterpret_cast<const uint8_t *>(&a_register), 2, data, len);
}
ErrorCode I2CDevice::write_register(uint8_t a_register, const uint8_t *data, size_t len) const {
SmallBufferWithHeapFallback<17> buffer_alloc(len + 1); // Most I2C writes are <= 16 bytes
ErrorCode I2CBus::write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) {
SmallBufferWithHeapFallback<20> buffer_alloc(prefix_len + len);
uint8_t *buffer = buffer_alloc.get();
// memcpy needs valid pointers even for a zero length
if (prefix_len != 0)
std::memcpy(buffer, prefix, prefix_len);
if (len != 0)
std::memcpy(buffer + prefix_len, data, len);
return this->write_readv(address, buffer, prefix_len + len, nullptr, 0);
}
buffer[0] = a_register;
std::copy(data, data + len, buffer + 1);
return this->bus_->write_readv(this->address_, buffer, len + 1, nullptr, 0);
ErrorCode I2CDevice::write_register(uint8_t a_register, const uint8_t *data, size_t len) const {
return this->bus_->write_prefixed(this->address_, &a_register, 1, data, len);
}
ErrorCode I2CDevice::write_register16(uint16_t a_register, const uint8_t *data, size_t len) const {
SmallBufferWithHeapFallback<18> buffer_alloc(len + 2); // Most I2C writes are <= 16 bytes + 2 for register
uint8_t *buffer = buffer_alloc.get();
put_be16(buffer, a_register);
std::copy(data, data + len, buffer + 2);
return this->bus_->write_readv(this->address_, buffer, len + 2, nullptr, 0);
uint8_t reg[2];
put_be16(reg, a_register);
return this->bus_->write_prefixed(this->address_, reg, sizeof(reg), data, len);
}
bool I2CDevice::write_registers(const I2CRegValue *table, size_t count) const {
+6
View File
@@ -44,6 +44,12 @@ class I2CBus {
virtual ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) = 0;
/// @brief Writes `prefix` then `data` in one transaction, as for a register address followed by its data.
/// The built-in buses send the two parts without copying them; the default joins them in a buffer for
/// write_readv(), on the stack for up to 20 bytes.
virtual ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len);
// Legacy functions for compatibility
ErrorCode read(uint8_t address, uint8_t *buffer, size_t len) {
+16 -5
View File
@@ -84,8 +84,9 @@ void ArduinoI2CBus::dump_config() {
this->dump_scan_results_();
}
ErrorCode ArduinoI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count,
uint8_t *read_buffer, size_t read_count) {
ErrorCode ArduinoI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len,
const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) {
#if defined(USE_ESP8266)
this->set_pins_and_clock_(); // reconfigure Wire global state in case there are multiple instances
#endif
@@ -94,13 +95,23 @@ ErrorCode ArduinoI2CBus::write_readv(uint8_t address, const uint8_t *write_buffe
return ERROR_NOT_INITIALIZED;
}
if (prefix_len != 0)
ESP_LOGV_HEX(TAG, prefix, prefix_len, I2C_MAX_LOG_BYTES, "0x%02X TX prefix %s", address);
ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
uint8_t status = 0;
if (write_count != 0 || read_count == 0) {
if (prefix_len != 0 || write_count != 0 || read_count == 0) {
#ifdef USE_RP2
// arduino-pico leaves a transmission open when a write overflows its buffer, and every later
// beginTransmission() is then ignored, so refuse the write before starting it
if (prefix_len + write_count > WIRE_BUFFER_SIZE) {
ESP_LOGVV(TAG, "TX of %zu bytes exceeds the %u byte Wire buffer", prefix_len + write_count, WIRE_BUFFER_SIZE);
return ERROR_TOO_LARGE;
}
#endif
this->wire_->beginTransmission(address);
size_t ret = this->wire_->write(write_buffer, write_count);
if (ret != write_count) {
if ((prefix_len != 0 && this->wire_->write(prefix, prefix_len) != prefix_len) ||
this->wire_->write(write_buffer, write_count) != write_count) {
ESP_LOGV(TAG, "TX failed");
return ERROR_UNKNOWN;
}
+10 -1
View File
@@ -19,7 +19,13 @@ class ArduinoI2CBus final : public InternalI2CBus, public Component {
void setup() override;
void dump_config() override;
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override;
size_t read_count) override {
return this->transfer_(address, nullptr, 0, write_buffer, write_count, read_buffer, read_count);
}
ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) override {
return this->transfer_(address, prefix, prefix_len, data, len, nullptr, 0);
}
float get_setup_priority() const override { return setup_priority::BUS; }
void set_scan(bool scan) { this->scan_ = scan; }
@@ -35,6 +41,9 @@ class ArduinoI2CBus final : public InternalI2CBus, public Component {
#endif
private:
/// Writes `prefix` then `write_buffer` in one transaction, then reads
ErrorCode transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *write_buffer,
size_t write_count, uint8_t *read_buffer, size_t read_count);
void recover_();
void set_pins_and_clock_();
RecoveryCode recovery_result_;
+35 -41
View File
@@ -200,8 +200,8 @@ void IDFI2CBus::dump_config() {
this->dump_scan_results_();
}
ErrorCode IDFI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) {
ErrorCode IDFI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *write_buffer,
size_t write_count, uint8_t *read_buffer, size_t read_count) {
// logging is only enabled with v level, if warnings are shown the caller
// should log them
if (!this->initialized_) {
@@ -209,50 +209,44 @@ ErrorCode IDFI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, s
return ERROR_NOT_INITIALIZED;
}
i2c_operation_job_t jobs[8]{};
// START, address, prefix, data, START, address, two reads, STOP
i2c_operation_job_t jobs[9]{};
size_t num_jobs = 0;
uint8_t write_addr = (address << 1) | I2C_MASTER_WRITE;
uint8_t read_addr = (address << 1) | I2C_MASTER_READ;
ESP_LOGV(TAG, "Writing %zu bytes, reading %zu bytes", write_count, read_count);
if (read_count == 0 && write_count == 0) {
// basically just a bus probe. Send a start, address and stop
ESP_LOGV(TAG, "0x%02X BUS PROBE", address);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
auto add_write = [&jobs, &num_jobs](const uint8_t *data, size_t len) ESPHOME_ALWAYS_INLINE {
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = &write_addr;
jobs[num_jobs++].write.total_bytes = 1;
} else {
if (write_count != 0) {
ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = &write_addr;
jobs[num_jobs++].write.total_bytes = 1;
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = (uint8_t *) write_buffer;
jobs[num_jobs++].write.total_bytes = write_count;
}
if (read_count != 0) {
ESP_LOGV(TAG, "0x%02X RX bytes %zu", address, read_count);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
jobs[num_jobs].command = I2C_MASTER_CMD_WRITE;
jobs[num_jobs].write.ack_check = true;
jobs[num_jobs].write.data = &read_addr;
jobs[num_jobs++].write.total_bytes = 1;
if (read_count > 1) {
jobs[num_jobs].command = I2C_MASTER_CMD_READ;
jobs[num_jobs].read.ack_value = I2C_ACK_VAL;
jobs[num_jobs].read.data = read_buffer;
jobs[num_jobs++].read.total_bytes = read_count - 1;
}
jobs[num_jobs].write.data = const_cast<uint8_t *>(data);
jobs[num_jobs++].write.total_bytes = len;
};
uint8_t write_addr = (address << 1) | I2C_MASTER_WRITE;
uint8_t read_addr = (address << 1) | I2C_MASTER_READ;
ESP_LOGV(TAG, "Writing %zu bytes, reading %zu bytes", prefix_len + write_count, read_count);
// With nothing to write or read this only addresses the device (the bus scan probe)
if (prefix_len != 0 || write_count != 0 || read_count == 0) {
if (prefix_len != 0)
ESP_LOGV_HEX(TAG, prefix, prefix_len, I2C_MAX_LOG_BYTES, "0x%02X TX prefix %s", address);
ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
add_write(&write_addr, 1);
if (prefix_len != 0)
add_write(prefix, prefix_len);
if (write_count != 0)
add_write(write_buffer, write_count);
}
if (read_count != 0) {
ESP_LOGV(TAG, "0x%02X RX bytes %zu", address, read_count);
jobs[num_jobs++].command = I2C_MASTER_CMD_START;
add_write(&read_addr, 1);
if (read_count > 1) {
jobs[num_jobs].command = I2C_MASTER_CMD_READ;
jobs[num_jobs].read.ack_value = I2C_NACK_VAL;
jobs[num_jobs].read.data = read_buffer + read_count - 1;
jobs[num_jobs++].read.total_bytes = 1;
jobs[num_jobs].read.ack_value = I2C_ACK_VAL;
jobs[num_jobs].read.data = read_buffer;
jobs[num_jobs++].read.total_bytes = read_count - 1;
}
jobs[num_jobs].command = I2C_MASTER_CMD_READ;
jobs[num_jobs].read.ack_value = I2C_NACK_VAL;
jobs[num_jobs].read.data = read_buffer + read_count - 1;
jobs[num_jobs++].read.total_bytes = 1;
}
jobs[num_jobs++].command = I2C_MASTER_CMD_STOP;
ESP_LOGV(TAG, "Sending %zu jobs", num_jobs);
+10 -1
View File
@@ -19,7 +19,13 @@ class IDFI2CBus final : public InternalI2CBus, public Component {
void setup() override;
void dump_config() override;
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override;
size_t read_count) override {
return this->transfer_(address, nullptr, 0, write_buffer, write_count, read_buffer, read_count);
}
ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) override {
return this->transfer_(address, prefix, prefix_len, data, len, nullptr, 0);
}
float get_setup_priority() const override { return setup_priority::BUS; }
void set_scan(bool scan) { this->scan_ = scan; }
@@ -42,6 +48,9 @@ class IDFI2CBus final : public InternalI2CBus, public Component {
#endif
private:
/// Writes `prefix` then `write_buffer` in one transaction, then reads
ErrorCode transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *write_buffer,
size_t write_count, uint8_t *read_buffer, size_t read_count);
void recover_();
i2c_master_dev_handle_t add_device_(uint32_t frequency);
RecoveryCode recovery_result_{};
+10 -6
View File
@@ -197,8 +197,9 @@ uint8_t SoftwareI2CBus::read_byte_(bool ack) {
return data;
}
ErrorCode SoftwareI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count,
uint8_t *read_buffer, size_t read_count) {
ErrorCode SoftwareI2CBus::transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len,
const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) {
if (!this->initialized_) {
ESP_LOGD(TAG, "i2c bus not initialized!");
return ERROR_NOT_INITIALIZED;
@@ -209,25 +210,28 @@ ErrorCode SoftwareI2CBus::write_readv(uint8_t address, const uint8_t *write_buff
}
this->bus_stuck_ = false;
if (prefix_len != 0)
ESP_LOGV_HEX(TAG, prefix, prefix_len, I2C_MAX_LOG_BYTES, "0x%02X TX prefix %s", address);
ESP_LOGV_HEX(TAG, write_buffer, write_count, I2C_MAX_LOG_BYTES, "0x%02X TX %s", address);
this->timed_out_ = false;
ErrorCode err = ERROR_OK;
this->start_();
// An empty transfer only addresses the device (used by the bus scan)
if (write_count != 0 || read_count == 0) {
const size_t total = prefix_len + write_count;
if (total != 0 || read_count == 0) {
if (!this->write_byte_(address << 1)) {
err = ERROR_NOT_ACKNOWLEDGED;
}
for (size_t i = 0; err == ERROR_OK && i < write_count; i++) {
if (!this->write_byte_(write_buffer[i])) {
for (size_t i = 0; err == ERROR_OK && i < total; i++) {
if (!this->write_byte_(i < prefix_len ? prefix[i] : write_buffer[i - prefix_len])) {
ESP_LOGVV(TAG, "TX of byte %u to 0x%02X not acknowledged", (unsigned) i, address);
err = ERROR_NOT_ACKNOWLEDGED;
}
}
}
if (err == ERROR_OK && read_count != 0) {
if (write_count != 0) {
if (total != 0) {
this->start_(); // repeated start
}
if (!this->write_byte_((address << 1) | 1)) {
+10 -1
View File
@@ -16,7 +16,13 @@ class SoftwareI2CBus final : public I2CBus, public Component {
void setup() override;
void dump_config() override;
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override;
size_t read_count) override {
return this->transfer_(address, nullptr, 0, write_buffer, write_count, read_buffer, read_count);
}
ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data,
size_t len) override {
return this->transfer_(address, prefix, prefix_len, data, len, nullptr, 0);
}
float get_setup_priority() const override { return setup_priority::BUS; }
void set_scan(bool scan) { this->scan_ = scan; }
@@ -31,6 +37,9 @@ class SoftwareI2CBus final : public I2CBus, public Component {
void set_timeout(uint32_t timeout) { this->timeout_ = timeout; }
protected:
/// Writes `prefix` then `write_buffer` in one transaction, then reads
ErrorCode transfer_(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *write_buffer,
size_t write_count, uint8_t *read_buffer, size_t read_count);
bool recover_();
void update_half_period_();
void start_();
@@ -1,5 +1,6 @@
#include "inkbird_ibsth1_mini.h"
#include "esphome/core/log.h"
#include "esphome/core/helpers.h"
namespace esphome::inkbird_ibsth1_mini {
@@ -82,7 +83,7 @@ bool InkbirdIbstH1Mini::parse_device(const ble_device_base::ESPBTDevice &device)
}
auto battery_level = mnf_data.data[5];
auto humidity = ((mnf_data.data[1] << 8) + mnf_data.data[0]) / 100.0f;
auto humidity = encode_value_le<uint16_t>(mnf_data.data.data()) / 100.0f;
// Send temperature only if the value is set
if (!std::isnan(temperature) && this->temperature_sensor_ != nullptr) {
@@ -1,7 +1 @@
import esphome.codegen as cg
DOMAIN = "kamstrup_kmp"
add_custom_sensor = cg.slot_list(
"KAMSTRUP_KMP_CUSTOM_SENSOR_COUNT", "add_custom_sensor", DOMAIN
)
@@ -28,9 +28,9 @@ void KamstrupKMPComponent::dump_config() {
LOG_SENSOR(" ", "Flow", this->flow_sensor_);
LOG_SENSOR(" ", "Volume", this->volume_sensor_);
for (const auto &custom : this->custom_sensors_) {
LOG_SENSOR(" ", "Custom Sensor", custom.sensor);
ESP_LOGCONFIG(TAG, " Command: 0x%04X", custom.command);
for (size_t i = 0; i < this->custom_sensors_.size(); i++) {
LOG_SENSOR(" ", "Custom Sensor", this->custom_sensors_[i]);
ESP_LOGCONFIG(TAG, " Command: 0x%04X", this->custom_commands_[i]);
}
}
@@ -63,8 +63,8 @@ void KamstrupKMPComponent::update() {
this->command_queue_.push(CMD_VOLUME);
}
for (const auto &custom : this->custom_sensors_) {
this->command_queue_.push(custom.command);
for (uint16_t custom_command : this->custom_commands_) {
this->command_queue_.push(custom_command);
}
}
@@ -261,9 +261,9 @@ void KamstrupKMPComponent::set_sensor_value_(uint16_t command, float value, uint
}
// Custom sensors
for (const auto &custom : this->custom_sensors_) {
if (command == custom.command) {
custom.sensor->publish_state(value);
for (size_t i = 0; i < this->custom_commands_.size(); i++) {
if (command == this->custom_commands_[i]) {
this->custom_sensors_[i]->publish_state(value);
}
}
@@ -4,7 +4,6 @@
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
namespace esphome::kamstrup_kmp {
@@ -76,17 +75,15 @@ class KamstrupKMPComponent final : public PollingComponent, public uart::UARTDev
void dump_config() override;
void update() override;
void loop() override;
SLOT_LIST_REQUIRES(KAMSTRUP_KMP_CUSTOM_SENSOR_COUNT)
void add_custom_sensor(sensor::Sensor *sensor, uint16_t command) {
this->custom_sensors_.push_back({sensor, command});
this->custom_sensors_.push_back(sensor);
this->custom_commands_.push_back(command);
}
protected:
struct CustomSensor {
sensor::Sensor *sensor;
uint16_t command;
};
[[no_unique_address]] SlotList<CustomSensor, KAMSTRUP_KMP_CUSTOM_SENSOR_COUNT> custom_sensors_;
// Custom sensors and commands
std::vector<sensor::Sensor *> custom_sensors_;
std::vector<uint16_t> custom_commands_;
// Command queue
std::queue<uint16_t> command_queue_;
+1 -3
View File
@@ -24,8 +24,6 @@ from esphome.const import (
)
from esphome.types import ConfigType
from . import add_custom_sensor
CODEOWNERS = ["@cfeenstra1024"]
DEPENDENCIES = ["uart"]
@@ -136,4 +134,4 @@ async def to_code(config: ConfigType) -> None:
if CONF_CUSTOM in config:
for conf in config[CONF_CUSTOM]:
sens = await sensor.new_sensor(conf)
cg.add(add_custom_sensor(var, sens, conf[CONF_COMMAND]))
cg.add(var.add_custom_sensor(sens, conf[CONF_COMMAND]))
+8
View File
@@ -90,7 +90,15 @@ __attribute__((always_inline)) inline bool is_main_loop_thread() {
return xTaskGetCurrentTaskHandle() == esphome_main_task_handle;
}
__attribute__((always_inline)) inline void yield() { ::yield(); }
#if defined(USE_LIBRETINY_VARIANT_RTL8710B)
// Already sleeps to a deadline (rtl8710b_micros.c)
__attribute__((always_inline)) inline void delay(uint32_t ms) { ::delay(ms); }
#else
// vTaskDelay() counts the partial tick, so one more tick makes the wait at least ms
__attribute__((always_inline)) inline void delay(uint32_t ms) {
vTaskDelay(ms == 0 ? 0 : (ms + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS + 1);
}
#endif
__attribute__((always_inline)) inline uint32_t micros() { return static_cast<uint32_t>(::micros()); }
// Per-variant millis() fast path — matches MillisInternal::get().
+16 -42
View File
@@ -37,6 +37,7 @@ from esphome.types import ConfigType
_LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@esphome/core"]
DOMAIN = "logger"
logger_ns = cg.esphome_ns.namespace("logger")
LOG_LEVELS = {
"NONE": cg.global_ns.ESPHOME_LOG_LEVEL_NONE,
@@ -108,8 +109,6 @@ HARDWARE_UART_TO_SERIAL = {
UART0: cg.global_ns.Serial,
UART0_SWAP: cg.global_ns.Serial,
UART1: cg.global_ns.Serial1,
UART2: cg.global_ns.Serial2,
DEFAULT: cg.global_ns.Serial,
},
PLATFORM_RP2: {
UART0: cg.global_ns.Serial1,
@@ -503,13 +502,10 @@ async def to_code(config: ConfigType) -> None:
CORE.data.setdefault(DOMAIN, {})[CONF_LEVEL] = level
tx_buffer_size = config[CONF_TX_BUFFER_SIZE]
cg.add_define("ESPHOME_LOGGER_TX_BUFFER_SIZE", tx_buffer_size)
# Determine task log buffer size. The buffer is a direct member of Logger
# (no separate heap allocation).
task_log_buffer_size = 0
if CORE.is_esp32 or CORE.is_libretiny or CORE.is_nrf52:
task_log_buffer_size = config[CONF_TASK_LOG_BUFFER_SIZE]
elif CORE.is_host:
task_log_buffer_size = 64 # Fixed 64 slots for host
# The host has a fixed 64 slots
task_log_buffer_size = (
64 if CORE.is_host else config.get(CONF_TASK_LOG_BUFFER_SIZE, 0)
)
if task_log_buffer_size > 0:
cg.add_define("USE_ESPHOME_TASK_LOG_BUFFER")
cg.add_define("ESPHOME_TASK_LOG_BUFFER_SIZE", task_log_buffer_size)
@@ -647,7 +643,6 @@ async def _late_logger_init(config: ConfigType) -> None:
if config[CONF_HARDWARE_UART] == USB_CDC:
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_CDC", True)
cg.add_define("USE_LOGGER_UART_SELECTION_USB_CDC")
elif config[CONF_HARDWARE_UART] == USB_SERIAL_JTAG:
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG", True)
cg.add_define("USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG")
@@ -667,7 +662,10 @@ async def _late_logger_init(config: ConfigType) -> None:
cg.add_define("USE_ESP32_LOG_V2")
# --wrap: a strong definition collides; see logger_esp32.cpp
cg.add_build_flag("-Wl,--wrap=esp_log_format")
if CORE.is_rp2 and config[CONF_HARDWARE_UART] == USB_CDC:
# Zephyr polls the USB port only when it logs there
if config.get(CONF_HARDWARE_UART) == USB_CDC and (
has_serial_logging or not CORE.is_nrf52
):
cg.add_define("USE_LOGGER_UART_SELECTION_USB_CDC")
# Define platform support flags for components that need auto-detection
try:
@@ -718,7 +716,6 @@ async def _late_logger_init(config: ConfigType) -> None:
if config[CONF_HARDWARE_UART] == UART1:
zephyr_add_overlay("""&uart1 { status = "okay";};""")
if config[CONF_HARDWARE_UART] == USB_CDC:
cg.add_define("USE_LOGGER_UART_SELECTION_USB_CDC")
zephyr_add_prj_conf("UART_LINE_CTRL", True)
# Register at end for safe mode
@@ -739,8 +736,6 @@ async def _late_logger_init(config: ConfigType) -> None:
conf,
)
CORE.add_job(final_step)
def validate_printf(value: ConfigType) -> ConfigType:
# https://stackoverflow.com/questions/30011379/how-can-i-parse-a-c-format-string-in-python
@@ -875,11 +870,6 @@ FILTER_SOURCE_FILES = filter_source_files_from_platform(
}
)
# Keys for CORE.data storage
DOMAIN = "logger"
KEY_LEVEL_LISTENERS = "level_listeners"
KEY_LOG_LISTENERS = "log_listeners"
def request_logger_level_listeners() -> None:
"""Request that logger level listeners be compiled in.
@@ -888,29 +878,13 @@ def request_logger_level_listeners() -> None:
function during their code generation. This enables the add_level_listener()
method and compiles in the listener vector.
"""
CORE.data.setdefault(DOMAIN, {})[KEY_LEVEL_LISTENERS] = True
cg.add_define("USE_LOGGER_LEVEL_LISTENERS")
_request_log_listener_slot = cg.slot_counter("ESPHOME_LOG_MAX_LISTENERS")
def request_log_listener() -> None:
"""Request a log listener slot.
Components that need to receive log messages should call this function
during their code generation. This increments the listener count used
to size the StaticVector.
"""
data = CORE.data.setdefault(DOMAIN, {})
data[KEY_LOG_LISTENERS] = data.get(KEY_LOG_LISTENERS, 0) + 1
@coroutine_with_priority(CoroPriority.FINAL)
async def final_step() -> None:
"""Final code generation step to configure optional logger features."""
domain_data = CORE.data.get(DOMAIN, {})
if domain_data.get(KEY_LEVEL_LISTENERS, False):
cg.add_define("USE_LOGGER_LEVEL_LISTENERS")
# Only generate log listener code if any component needs it
log_listener_count = domain_data.get(KEY_LOG_LISTENERS, 0)
if log_listener_count > 0:
cg.add_define("USE_LOG_LISTENERS")
cg.add_define("ESPHOME_LOG_MAX_LISTENERS", log_listener_count)
"""Reserve a log listener slot; call once per listener from to_code."""
cg.add_define("USE_LOG_LISTENERS")
_request_log_listener_slot()
+19 -20
View File
@@ -59,7 +59,7 @@ struct LogBuffer {
char *p = this->current_();
// Write ANSI color
this->write_ansi_color_(p, level);
p = write_ansi_color(p, level);
// Construct: [LEVEL][tag:line]
*p++ = '[';
@@ -75,27 +75,27 @@ struct LogBuffer {
*p++ = '[';
// Copy tag
this->copy_string_(p, tag);
p = copy_string(p, tag);
*p++ = ':';
// Format line number using subtraction loops (no division - important for ESP8266 which lacks hardware divider)
if (line > 999) [[unlikely]] {
write_digit(p, line, 1000);
p = write_digit(p, line, 1000);
}
write_digit(p, line, 100);
write_digit(p, line, 10);
p = write_digit(p, line, 100);
p = write_digit(p, line, 10);
*p++ = '0' + line;
*p++ = ']';
#if defined(USE_ESP32) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR) || defined(USE_HOST)
// Write thread name with bold red color
if (thread_name != nullptr) {
this->write_ansi_color_(p, 1); // Bold red for thread name
p = write_ansi_color(p, 1); // Bold red for thread name
*p++ = '[';
this->copy_string_(p, thread_name);
p = copy_string(p, thread_name);
*p++ = ']';
this->write_ansi_color_(p, level); // Restore original color
p = write_ansi_color(p, level); // Restore original color
}
#endif
@@ -123,7 +123,7 @@ struct LogBuffer {
if (this->pos + REPLAY_HEADER_MAX_SIZE > this->size)
return;
char *p = this->current_();
this->write_ansi_color_(p, level);
p = write_ansi_color(p, level);
*p++ = '@';
p = uint32_to_str_unchecked(p, ms);
*p++ = 'm';
@@ -185,19 +185,19 @@ struct LogBuffer {
}
#endif
// Extract one decimal digit via subtraction (no division - important for ESP8266)
static inline void ESPHOME_ALWAYS_INLINE write_digit(char *&p, int &value, int divisor) {
static inline char *ESPHOME_ALWAYS_INLINE write_digit(char *p, int &value, int divisor) {
char d = '0';
while (value >= divisor) {
d++;
value -= divisor;
}
*p++ = d;
return p;
}
// Write ANSI color escape sequence to buffer, updates pointer in place
// Caller is responsible for ensuring buffer has sufficient space
void write_ansi_color_(char *&p, uint8_t level) {
// Writes up to 7 bytes unchecked, so the caller reserves space; returns the new end, keeping p in a register
static char *write_ansi_color(char *p, uint8_t level) {
if (level == 0)
return;
return p;
// Direct buffer fill: "\033[{bold};3{color}m" (7 bytes)
*p++ = '\033';
*p++ = '[';
@@ -206,10 +206,10 @@ struct LogBuffer {
*p++ = '3';
*p++ = static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&LOG_LEVEL_COLOR_DIGIT[level])));
*p++ = 'm';
return p;
}
// Copy string without null terminator, updates pointer in place
// Caller is responsible for ensuring buffer has sufficient space. Tags may be in PROGMEM on ESP8266.
void copy_string_(char *&p, const char *str) {
// Copies str unchecked and without its null terminator, so the caller reserves space; returns the new end
static char *copy_string(char *p, const char *str) {
#ifdef USE_ESP8266
// Only ESP8266 caps the length; tags may be in PROGMEM, so read each byte once
for (size_t i = 0; i < MAX_TAG_LENGTH; i++) {
@@ -220,11 +220,10 @@ struct LogBuffer {
}
#else
const size_t len = strlen(str);
// NOLINTNEXTLINE(bugprone-not-null-terminated-result) - intentionally no null terminator, building string piece by
// piece
memcpy(p, str, len);
memcpy(p, str, len); // NOLINT(bugprone-not-null-terminated-result) - the header is built piece by piece
p += len;
#endif
return p;
}
};
+33 -17
View File
@@ -7,6 +7,14 @@
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#if defined(USE_ESP32) && defined(USE_NETWORK)
#include <sdkconfig.h>
#if defined(CONFIG_LWIP_TCPIP_CORE_LOCKING) && defined(USE_ESPHOME_TASK_LOG_BUFFER)
#include "lwip/sys.h"
#define USE_LOGGER_DEFER_UNDER_LWIP_LOCK
#endif
#endif
namespace esphome::logger {
ESPHOME_LOG_TAG(TAG, "logger");
@@ -32,7 +40,7 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
// Get task handle once - used for both main task check and passing to non-main thread handler
TaskHandle_t current_task = xTaskGetCurrentTaskHandle();
const bool is_main_task = (current_task == this->main_task_);
#elif (USE_ZEPHYR)
#elif defined(USE_ZEPHYR)
k_tid_t current_task = k_current_get();
const bool is_main_task = (current_task == this->main_task_);
#else // USE_HOST
@@ -42,6 +50,16 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
// Fast path: main thread, no recursion (99.9% of all logs)
// 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]] {
this->log_vprintf_non_main_thread_(level, tag, line, format, args, nullptr);
return;
}
#endif
this->log_message_to_buffer_and_send_(this->main_task_recursion_guard_, level, tag, line, format, args, nullptr);
return;
}
@@ -57,10 +75,10 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
// (we already have the handle from the main task check above).
// Host: pass a stack buffer for pthread_getname_np to write into.
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
const char *thread_name = get_thread_name_(current_task);
const char *thread_name = this->get_thread_name_(current_task);
#elif defined(USE_ZEPHYR)
char thread_name_buf[MAX_POINTER_REPRESENTATION];
const char *thread_name = get_thread_name_(thread_name_buf, current_task);
const char *thread_name = this->get_thread_name_(thread_name_buf, current_task);
#else // USE_HOST
char thread_name_buf[THREAD_NAME_BUF_SIZE];
const char *thread_name = this->get_thread_name_(thread_name_buf);
@@ -103,10 +121,10 @@ void Logger::log_vprintf_non_main_thread_(uint8_t level, const char *tag, int li
{
#ifdef USE_HOST
// Host always has console output - no baud_rate check needed
static const size_t MAX_CONSOLE_LOG_MSG_SIZE = 512;
static constexpr size_t MAX_CONSOLE_LOG_MSG_SIZE = 512;
#else
// Maximum size for console log messages (includes null terminator)
static const size_t MAX_CONSOLE_LOG_MSG_SIZE = 144;
static constexpr size_t MAX_CONSOLE_LOG_MSG_SIZE = 144;
#endif
char console_buffer[MAX_CONSOLE_LOG_MSG_SIZE]; // MUST be stack allocated for thread safety
LogBuffer buf{console_buffer, MAX_CONSOLE_LOG_MSG_SIZE};
@@ -118,13 +136,11 @@ void Logger::log_vprintf_non_main_thread_(uint8_t level, const char *tag, int li
}
#else
// Implementation for single-task platforms (ESP8266, RP2040)
// Logging calls are NOT thread-safe: global_recursion_guard_ is a plain bool and tx_buffer_ has no locking.
// Not a problem in practice yet since Zephyr has no API support (logs are console-only).
// Logging calls are NOT thread-safe: the recursion guard is a plain bool and tx_buffer_ has no locking.
void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const char *format, va_list args) { // NOLINT
if (level > this->level_for(tag) || global_recursion_guard_)
if (level > this->level_for(tag) || this->main_task_recursion_guard_)
return;
// Other single-task platforms don't have thread names, so pass nullptr
this->log_message_to_buffer_and_send_(global_recursion_guard_, level, tag, line, format, args, nullptr);
this->log_message_to_buffer_and_send_(this->main_task_recursion_guard_, level, tag, line, format, args, nullptr);
}
#endif // USE_ESP32 || USE_HOST || USE_LIBRETINY || USE_ZEPHYR
@@ -136,10 +152,10 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
//
void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __FlashStringHelper *format,
va_list args) { // NOLINT
if (level > this->level_for(tag) || global_recursion_guard_)
if (level > this->level_for(tag) || this->main_task_recursion_guard_)
return;
this->log_message_to_buffer_and_send_(global_recursion_guard_, level, tag, line, format, args, nullptr);
this->log_message_to_buffer_and_send_(this->main_task_recursion_guard_, level, tag, line, format, args, nullptr);
}
#endif // USE_ESP8266
@@ -213,11 +229,11 @@ void Logger::process_messages_() {
this->write_log_buffer_to_console_(buf);
}
}
// Zephyr with USB CDC keeps the loop running for cdc_loop_()
#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
else {
// No messages to process, disable loop if appropriate
// This reduces overhead when there's no async logging activity
this->disable_loop_when_buffer_empty_();
// A concurrent enable_loop_soon_any_context() still wakes the next iteration
this->disable_loop();
}
#endif
#endif // USE_ESPHOME_TASK_LOG_BUFFER
@@ -265,7 +281,7 @@ void Logger::boot_log_capture_(uint8_t level, const char *tag, const LogBuffer &
void Logger::replay_boot_logs() {
// The replay shares tx_buffer_ with normal logging, so it is dropped like any other re-entrant log
bool &recursion_guard = this->main_loop_recursion_guard_();
bool &recursion_guard = this->main_task_recursion_guard_;
if (recursion_guard)
return;
this->boot_log_done_ = true; // Stops capture first, so the replay output is not buffered again
@@ -342,7 +358,7 @@ void Logger::dump_config() {
}
#endif
#ifdef USE_ZEPHYR
dump_crash_();
this->dump_crash_();
#ifdef USE_BOOTLOADER_ADAFRUIT
this->dump_bootloader_();
#endif
+46 -80
View File
@@ -42,9 +42,6 @@ struct device;
namespace esphome::logger {
/** Lightweight callback for receiving log messages without virtual dispatch overhead.
*
* Replaces the former LogListener virtual interface to eliminate per-implementer
* vtable sub-tables and thunk code (~39 bytes saved per class that used LogListener).
*
* Usage:
* // In your component's setup():
@@ -73,7 +70,7 @@ struct LogCallback {
* public:
* void setup() override {
* if (logger::global_logger != nullptr)
* logger::global_logger->add_logger_level_listener(this);
* logger::global_logger->add_level_listener(this);
* }
* void on_log_level_change(uint8_t level) override {
* // Handle log level change
@@ -138,7 +135,7 @@ enum UARTSelection : uint8_t {
* - On ESP32: Uses task-specific recursion guards
* * Main task: Uses a dedicated boolean member variable for efficiency
* * Other tasks: Uses pthread TLS with a dynamically allocated key for task-specific state
* - On other platforms: Uses a simple global recursion guard
* - On single-task platforms: Uses the main task guard alone
*
* We use pthread TLS via pthread_key_create to create a unique key for storing
* task-specific recursion state, which:
@@ -157,19 +154,25 @@ class Logger final : public Component {
#endif
/// Manually set the baud rate for serial, set to 0 to disable.
void set_baud_rate(uint32_t baud_rate) { this->baud_rate_ = baud_rate; }
uint32_t get_baud_rate() const { return baud_rate_; }
uint32_t get_baud_rate() const { return this->baud_rate_; }
#if defined(USE_ARDUINO) && !defined(USE_ESP32)
Stream *get_hw_serial() const { return hw_serial_; }
Stream *get_hw_serial() const { return this->hw_serial_; }
#endif
#ifdef USE_ESP32
uart_port_t get_uart_num() const { return uart_num_; }
void create_pthread_key() { pthread_key_create(&log_recursion_key_, nullptr); }
/// UART_NUM_0 when logging to USB
uart_port_t get_uart_num() const {
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC) || defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
return UART_NUM_0;
#else
return static_cast<uart_port_t>(this->uart_);
#endif
#ifdef USE_HOST
void create_pthread_key() { pthread_key_create(&log_recursion_key_, nullptr); }
}
#endif
#if defined(USE_ESP32) || defined(USE_HOST)
void create_pthread_key() { pthread_key_create(&this->log_recursion_key_, nullptr); }
#endif
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
void set_uart_selection(UARTSelection uart_selection) { uart_ = uart_selection; }
void set_uart_selection(UARTSelection uart_selection) { this->uart_ = uart_selection; }
/// Get the UART used by the logger.
UARTSelection get_uart() const { return this->uart_; }
#endif
@@ -246,10 +249,13 @@ class Logger final : public Component {
void cdc_loop_();
#endif
void process_messages_();
#if defined(USE_HOST) || defined(USE_ZEPHYR)
void write_msg_(const char *msg, uint16_t len);
// msg already ends in a newline
#if defined(USE_ARDUINO) && !defined(USE_ESP32)
inline void HOT write_msg_(const char *msg, uint16_t len) { this->hw_serial_->write(msg, len); }
#elif defined(USE_ESP32)
inline void write_msg_(const char *msg, uint16_t len); // Defined in logger_esp32.h
#else
inline void write_msg_(const char *msg, uint16_t len); // Defined in platform-specific logger_*.h
void write_msg_(const char *msg, uint16_t len);
#endif
// Format a log message with printf-style arguments and write it to a buffer with header, footer, and null terminator
@@ -317,7 +323,6 @@ class Logger final : public Component {
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
// Helper to format a pre-formatted message from the task log buffer and notify listeners
// Used by process_messages_ to avoid code duplication between ESP32 and host platforms
inline void HOT format_buffered_message_and_notify_(uint8_t level, const char *tag, uint16_t line,
const char *thread_name, const char *text, uint16_t text_length,
LogBuffer &buf) {
@@ -359,15 +364,8 @@ class Logger final : public Component {
#ifdef USE_HOST
pthread_t main_thread_{}; // Main thread for pthread_equal() comparison
#endif
#ifdef USE_ESP32
// Task-specific recursion guards:
// - Main task uses a dedicated member variable for efficiency
// - Other tasks use pthread TLS with a dynamically created key via pthread_key_create
pthread_key_t log_recursion_key_; // 4 bytes
uart_port_t uart_num_; // 4 bytes (enum defaults to int size)
#endif
#ifdef USE_HOST
// Thread-specific recursion guards using pthread TLS
#if defined(USE_ESP32) || defined(USE_HOST)
// Non-main task recursion guard (pthread TLS)
pthread_key_t log_recursion_key_;
#endif
@@ -392,23 +390,14 @@ class Logger final : public Component {
bool boot_log_done_{false}; // Set on first replay; stops further capture
#endif
uint8_t current_level_{ESPHOME_LOG_LEVEL_VERY_VERBOSE};
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_ZEPHYR)
UARTSelection uart_{UART_SELECTION_UART0}; // Must match cpp_default_uart in __init__.py
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
// 0 is UART0, or DEFAULT on LibreTiny; must match cpp_default_uart in __init__.py
UARTSelection uart_{};
#endif
#ifdef USE_LIBRETINY
UARTSelection uart_{UART_SELECTION_DEFAULT}; // Must match cpp_default_uart in __init__.py
#endif
#if defined(USE_ESP32) || defined(USE_HOST) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
bool main_task_recursion_guard_{false};
bool main_task_recursion_guard_{false}; // Guards tx_buffer_ on the main loop
#ifdef USE_LIBRETINY
bool non_main_task_recursion_guard_{false}; // Shared guard for all non-main tasks on LibreTiny
#endif
// The guard that protects tx_buffer_ on the main loop, for callers that run on any platform
bool &main_loop_recursion_guard_() { return this->main_task_recursion_guard_; }
#else
bool global_recursion_guard_{false}; // Simple global recursion guard for single-task platforms
bool &main_loop_recursion_guard_() { return this->global_recursion_guard_; }
#endif
// Large buffers placed last to keep frequently-accessed member offsets small
char tx_buffer_[ESPHOME_LOGGER_TX_BUFFER_SIZE + 1]; // +1 for null terminator
@@ -477,9 +466,9 @@ class Logger final : public Component {
class NonMainTaskRecursionGuard {
public:
explicit NonMainTaskRecursionGuard(pthread_key_t key) : key_(key) {
pthread_setspecific(key_, reinterpret_cast<void *>(1));
pthread_setspecific(this->key_, reinterpret_cast<void *>(1));
}
~NonMainTaskRecursionGuard() { pthread_setspecific(key_, nullptr); }
~NonMainTaskRecursionGuard() { pthread_setspecific(this->key_, nullptr); }
NonMainTaskRecursionGuard(const NonMainTaskRecursionGuard &) = delete;
NonMainTaskRecursionGuard &operator=(const NonMainTaskRecursionGuard &) = delete;
NonMainTaskRecursionGuard(NonMainTaskRecursionGuard &&) = delete;
@@ -490,40 +479,24 @@ class Logger final : public Component {
};
// Check if non-main task is already in recursion (via TLS)
inline bool HOT is_non_main_task_recursive_() const { return pthread_getspecific(log_recursion_key_) != nullptr; }
inline bool HOT is_non_main_task_recursive_() const {
return pthread_getspecific(this->log_recursion_key_) != nullptr;
}
// Create RAII guard for non-main task recursion
inline NonMainTaskRecursionGuard make_non_main_task_guard_() { return NonMainTaskRecursionGuard(log_recursion_key_); }
#elif defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
// LibreTiny doesn't have FreeRTOS TLS, so use a simple approach:
// - Main task uses dedicated boolean (same as ESP32)
// - Non-main tasks share a single recursion guard
// This is safe because:
// - Recursion from logging within logging is the main concern
// - Cross-task "recursion" is prevented by the buffer mutex anyway
// - Missing a recursive call from another task is acceptable (falls back to direct output)
//
// Zephyr use __thread as TLS
// Check if non-main task is already in recursion
inline bool HOT is_non_main_task_recursive_() const { return non_main_task_recursion_guard_; }
// Create RAII guard for non-main task recursion (uses shared boolean for all non-main tasks)
inline RecursionGuard make_non_main_task_guard_() { return RecursionGuard(non_main_task_recursion_guard_); }
#endif
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) && !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
// Disable loop when task buffer is empty
// Zephyr with USB CDC needs loop active to poll port readiness via cdc_loop_()
inline void disable_loop_when_buffer_empty_() {
// Thread safety note: This is safe even if another task calls enable_loop_soon_any_context()
// concurrently. If that happens between our check and disable_loop(), the enable request
// will be processed on the next main loop iteration since:
// - disable_loop() takes effect immediately
// - enable_loop_soon_any_context() sets a pending flag that's checked at loop start
this->disable_loop();
inline NonMainTaskRecursionGuard make_non_main_task_guard_() {
return NonMainTaskRecursionGuard(this->log_recursion_key_);
}
#elif defined(USE_LIBRETINY)
// No FreeRTOS TLS on LibreTiny: all non-main tasks share one guard
inline bool HOT is_non_main_task_recursive_() const { return this->non_main_task_recursion_guard_; }
inline RecursionGuard make_non_main_task_guard_() { return RecursionGuard(this->non_main_task_recursion_guard_); }
#elif defined(USE_ZEPHYR)
// Thread-local guard (__thread)
inline bool HOT is_non_main_task_recursive_() const { return non_main_task_recursion_guard; }
inline RecursionGuard make_non_main_task_guard_() { return RecursionGuard(non_main_task_recursion_guard); }
#endif
};
extern Logger *global_logger; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
@@ -563,14 +536,7 @@ void log_crash_to_client();
} // namespace esphome::logger
// Platform-specific inline implementations of write_msg_()
// Must be included after the Logger class definition is complete
#if defined(USE_ESP32)
// ESP32 inline write_msg_(), included after the Logger class definition is complete
#ifdef USE_ESP32
#include "logger_esp32.h"
#elif defined(USE_ESP8266)
#include "logger_esp8266.h"
#elif defined(USE_RP2)
#include "logger_rp2.h"
#elif defined(USE_LIBRETINY)
#include "logger_libretiny.h"
#endif
+10 -11
View File
@@ -73,7 +73,7 @@ static void init_usb_serial_jtag() {
}
#endif
void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_size) {
static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_size) {
uart_config_t uart_config{};
uart_config.baud_rate = (int) baud_rate;
uart_config.data_bits = UART_DATA_8_BITS;
@@ -98,24 +98,23 @@ void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_size) {
#endif
}
// get_uart_num() and pre_setup() cast the selection straight to a port
static_assert(static_cast<int>(UART_SELECTION_UART0) == static_cast<int>(UART_NUM_0) &&
static_cast<int>(UART_SELECTION_UART1) == static_cast<int>(UART_NUM_1));
#ifdef USE_ESP32_VARIANT_ESP32
static_assert(static_cast<int>(UART_SELECTION_UART2) == static_cast<int>(UART_NUM_2));
#endif
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
this->uart_num_ = UART_NUM_0;
switch (this->uart_) {
case UART_SELECTION_UART0:
this->uart_num_ = UART_NUM_0;
init_uart(this->uart_num_, baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
break;
case UART_SELECTION_UART1:
this->uart_num_ = UART_NUM_1;
init_uart(this->uart_num_, baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
break;
#ifdef USE_ESP32_VARIANT_ESP32
case UART_SELECTION_UART2:
this->uart_num_ = UART_NUM_2;
init_uart(this->uart_num_, baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
break;
#endif
init_uart(static_cast<uart_port_t>(this->uart_), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
break;
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
break;
+1 -1
View File
@@ -19,7 +19,7 @@ inline void HOT Logger::write_msg_(const char *msg, uint16_t len) {
fwrite(msg, 1, len, stdout);
#else
// Regular UART - single write including newline (already in buffer)
uart_write_bytes(this->uart_num_, msg, len);
uart_write_bytes(this->get_uart_num(), msg, len);
#endif
}
@@ -1,13 +0,0 @@
#pragma once
#ifdef USE_ESP8266
#include "esphome/core/helpers.h"
namespace esphome::logger {
// Single write with newline already in buffer (added by caller)
inline void HOT Logger::write_msg_(const char *msg, uint16_t len) { this->hw_serial_->write(msg, len); }
} // namespace esphome::logger
#endif
@@ -1,13 +0,0 @@
#pragma once
#ifdef USE_LIBRETINY
#include "esphome/core/helpers.h"
namespace esphome::logger {
// Single write with newline already in buffer (added by caller)
inline void HOT Logger::write_msg_(const char *msg, uint16_t len) { this->hw_serial_->write(msg, len); }
} // namespace esphome::logger
#endif
-2
View File
@@ -55,10 +55,8 @@ const LogString *Logger::get_uart_selection_() {
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
#endif
default:
return LOG_STR("UNKNOWN");
}
-13
View File
@@ -1,13 +0,0 @@
#pragma once
#ifdef USE_RP2
#include "esphome/core/helpers.h"
namespace esphome::logger {
// Single write with newline already in buffer (added by caller)
inline void HOT Logger::write_msg_(const char *msg, uint16_t len) { this->hw_serial_->write(msg, len); }
} // namespace esphome::logger
#endif
+5 -9
View File
@@ -44,7 +44,7 @@ ESPHOME_LOG_TAG(TAG, "logger");
#ifdef USE_LOGGER_UART_SELECTION_USB_CDC
void Logger::cdc_loop_() {
if (this->uart_ != UART_SELECTION_USB_CDC || this->uart_dev_ == nullptr) {
if (this->uart_dev_ == nullptr) {
return;
}
static bool opened = false;
@@ -74,7 +74,7 @@ void Logger::cdc_loop_() {
void Logger::pre_setup() {
#ifdef CONFIG_SERIAL
if (this->baud_rate_ > 0) {
static const struct device *uart_dev = nullptr;
const struct device *uart_dev = nullptr;
switch (this->uart_) {
case UART_SELECTION_UART0: // NOLINT(bugprone-branch-clone)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
@@ -114,14 +114,10 @@ void Logger::pre_setup() {
char reason_buffer[zephyr::RESET_REASON_BUFFER_SIZE];
const char *reset_reason = zephyr::get_reset_reason(std::span<char, zephyr::RESET_REASON_BUFFER_SIZE>(reason_buffer));
ESP_LOGI(TAG, "Reset reason: %s", reset_reason);
dump_crash_();
this->dump_crash_();
#endif
#ifdef USE_CRASH_HANDLER
#ifdef USE_LOGGER_UART_SELECTION_USB_CDC
// Nobody reads a USB port this early; cdc_loop_() reports the dump once the port is opened
if (this->uart_ == UART_SELECTION_USB_CDC)
return;
#endif
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
// Without a UART (baud_rate: 0, or one that did not come up) nothing reaches the console
if (this->uart_dev_ != nullptr)
log_crash_to_client();
@@ -158,7 +154,7 @@ const LogString *Logger::get_uart_selection_() {
}
}
static const uint8_t REASON_BUF_SIZE = 32;
static constexpr uint8_t REASON_BUF_SIZE = 32;
static const char *reason_to_str(unsigned int reason, char *buf) {
switch (reason) {
@@ -44,19 +44,15 @@ void TaskLogBuffer::release_message_main_loop() {
bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uint16_t line, const char *thread_name,
const char *format, va_list args) {
// First, calculate the exact length needed using a null buffer (no actual writing)
// Measure on a copy; the caller's va_list formats the text later
va_list args_copy;
va_copy(args_copy, args);
int ret = vsnprintf(nullptr, 0, format, args_copy);
int ret = task_log_cap_length(vsnprintf(nullptr, 0, format, args_copy));
va_end(args_copy);
if (ret <= 0) {
return false; // Formatting error or empty message
}
// Calculate actual text length (capped to maximum size)
static constexpr size_t MAX_TEXT_SIZE = 255;
size_t text_length = (static_cast<size_t>(ret) > MAX_TEXT_SIZE) ? MAX_TEXT_SIZE : ret;
uint16_t text_length = ret;
// Calculate total size needed (header + text length + null terminator)
size_t total_size = sizeof(LogMessage) + text_length + 1;
@@ -69,24 +65,10 @@ bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uin
return false; // Failed to acquire memory
}
// Set up the message header in the acquired memory
LogMessage *msg = static_cast<LogMessage *>(acquired_memory);
msg->level = level;
msg->tag = tag;
msg->line = line;
// Store the thread name now instead of waiting until main loop processing
// This avoids crashes if the task completes or is deleted between when this message
// is enqueued and when it's processed by the main loop
if (thread_name != nullptr) {
strncpy(msg->thread_name, thread_name, sizeof(msg->thread_name) - 1);
msg->thread_name[sizeof(msg->thread_name) - 1] = '\0'; // Ensure null termination
} else {
msg->thread_name[0] = '\0'; // Empty string if no thread name
}
fill_task_log_header(msg, level, tag, line, thread_name);
// Format the message text directly into the acquired memory
// We add 1 to text_length to ensure space for null terminator during formatting
char *text_area = msg->text_data();
ret = vsnprintf(text_area, text_length + 1, format, args);
@@ -96,12 +78,7 @@ bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uin
return false;
}
// Remove trailing newlines
while (text_length > 0 && text_area[text_length - 1] == '\n') {
text_length--;
}
msg->text_length = text_length;
msg->text_length = trim_trailing_newlines(text_area, text_length);
// Complete the send operation with the acquired memory
result = xRingbufferSendComplete(this->handle_(), acquired_memory);
@@ -12,6 +12,8 @@
#include <freertos/FreeRTOS.h>
#include <freertos/ringbuf.h>
#include "task_log_message.h"
namespace esphome::logger {
/**
@@ -32,19 +34,7 @@ namespace esphome::logger {
*/
class TaskLogBuffer {
public:
// Structure for a log message header (text data follows immediately after)
struct LogMessage {
const char *tag; // We store the pointer, assuming tags are static
char thread_name[16]; // Store thread name directly (only used for non-main threads)
uint16_t text_length; // Length of the message text (up to ~64KB)
uint16_t line; // Source code line number
uint8_t level; // Log level (0-7)
// Methods for accessing message contents
inline char *text_data() { return reinterpret_cast<char *>(this) + sizeof(LogMessage); }
inline const char *text_data() const { return reinterpret_cast<const char *>(this) + sizeof(LogMessage); }
};
using LogMessage = TaskLogMessage;
TaskLogBuffer();
// No destructor: Logger is never destroyed
@@ -71,18 +71,8 @@ bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uin
LogMessage &msg = this->slots_[slot_index];
// Fill in the message header
msg.level = level;
msg.tag = tag;
msg.line = line;
// Store the thread name now to avoid crashes if thread exits before processing
if (thread_name != nullptr) {
strncpy(msg.thread_name, thread_name, sizeof(msg.thread_name) - 1);
msg.thread_name[sizeof(msg.thread_name) - 1] = '\0';
} else {
msg.thread_name[0] = '\0';
}
// Copied now; the thread may exit before processing
fill_task_log_header(&msg, level, tag, line, thread_name);
// Format the message text
int ret = vsnprintf(msg.text, sizeof(msg.text), format, args);
@@ -94,10 +84,7 @@ bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uin
msg.text_length = static_cast<uint16_t>(std::min(static_cast<size_t>(ret), sizeof(msg.text) - 1));
}
// Remove trailing newlines
while (msg.text_length > 0 && msg.text[msg.text_length - 1] == '\n') {
msg.text_length--;
}
msg.text_length = trim_trailing_newlines(msg.text, msg.text_length);
msg.text[msg.text_length] = '\0';
// Commit the slot
@@ -13,6 +13,8 @@
#include <cstring>
#include <pthread.h>
#include "task_log_message.h"
namespace esphome::logger {
/**
@@ -13,13 +13,6 @@ TaskLogBuffer::TaskLogBuffer() {
this->mutex_ = xSemaphoreCreateMutex();
}
TaskLogBuffer::~TaskLogBuffer() {
if (this->mutex_ != nullptr) {
vSemaphoreDelete(this->mutex_);
this->mutex_ = nullptr;
}
}
size_t TaskLogBuffer::available_contiguous_space_() const {
if (this->head_ >= this->tail_) {
// head is ahead of or equal to tail
@@ -85,19 +78,15 @@ void TaskLogBuffer::release_message_main_loop() {
bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uint16_t line, const char *thread_name,
const char *format, va_list args) {
// First, calculate the exact length needed using a null buffer (no actual writing)
// Measure on a copy; the caller's va_list formats the text later
va_list args_copy;
va_copy(args_copy, args);
int ret = vsnprintf(nullptr, 0, format, args_copy);
int ret = task_log_cap_length(vsnprintf(nullptr, 0, format, args_copy));
va_end(args_copy);
if (ret <= 0) {
return false; // Formatting error or empty message
}
// Calculate actual text length (capped to maximum size)
static constexpr size_t MAX_TEXT_SIZE = 255;
size_t text_length = (static_cast<size_t>(ret) > MAX_TEXT_SIZE) ? MAX_TEXT_SIZE : ret;
uint16_t text_length = ret;
// Calculate total size needed (header + text length + null terminator)
size_t total_size = message_total_size(text_length);
@@ -128,17 +117,7 @@ bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uin
// Write message header
LogMessage *msg = reinterpret_cast<LogMessage *>(this->storage_ + write_pos);
msg->level = level;
msg->tag = tag;
msg->line = line;
// Store the thread name now to avoid crashes if task is deleted before processing
if (thread_name != nullptr) {
strncpy(msg->thread_name, thread_name, sizeof(msg->thread_name) - 1);
msg->thread_name[sizeof(msg->thread_name) - 1] = '\0';
} else {
msg->thread_name[0] = '\0';
}
fill_task_log_header(msg, level, tag, line, thread_name);
// Format the message text directly into the buffer
char *text_area = msg->text_data();
@@ -150,9 +129,7 @@ bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uin
}
// Trim before storing so the next message reuses the freed bytes
while (text_length > 0 && text_area[text_length - 1] == '\n') {
text_length--;
}
text_length = trim_trailing_newlines(text_area, text_length);
text_area[text_length] = '\0';
msg->text_length = text_length;
@@ -13,6 +13,8 @@
#include <semphr.h>
#include <task.h>
#include "task_log_message.h"
namespace esphome::logger {
/**
@@ -42,25 +44,14 @@ namespace esphome::logger {
*/
class TaskLogBuffer {
public:
// Structure for a log message header (text data follows immediately after)
struct LogMessage {
const char *tag; // We store the pointer, assuming tags are static
char thread_name[16]; // Store thread name directly (only used for non-main threads)
uint16_t text_length; // Length of the message text (up to ~64KB)
uint16_t line; // Source code line number
uint8_t level; // Log level (0-7)
// Methods for accessing message contents
inline char *text_data() { return reinterpret_cast<char *>(this) + sizeof(LogMessage); }
inline const char *text_data() const { return reinterpret_cast<const char *>(this) + sizeof(LogMessage); }
};
using LogMessage = TaskLogMessage;
// Padding marker level to indicate wrap-around point (stored in LogMessage.level field)
// Valid log levels are 0-7, so 0xFF cannot be a real message
static constexpr uint8_t PADDING_MARKER_LEVEL = 0xFF;
TaskLogBuffer();
~TaskLogBuffer();
// No destructor: Logger is never destroyed
// NOT thread-safe - borrow a message from the buffer, only call from main loop
bool borrow_message_main_loop(LogMessage *&message, uint16_t &text_length);
@@ -4,7 +4,7 @@
namespace esphome::logger {
__thread bool non_main_task_recursion_guard_; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
__thread bool non_main_task_recursion_guard; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
@@ -29,29 +29,21 @@ TaskLogBuffer::TaskLogBuffer() {
bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uint16_t line, const char *thread_name,
const char *format, va_list args) {
// First, calculate the exact length needed using a null buffer (no actual writing)
// Measure on a copy; the caller's va_list formats the text later
va_list args_copy;
va_copy(args_copy, args);
int ret = vsnprintf(nullptr, 0, format, args_copy);
int ret = task_log_cap_length(vsnprintf(nullptr, 0, format, args_copy));
va_end(args_copy);
if (ret <= 0) {
return false; // Formatting error or empty message
}
// Calculate actual text length (capped to maximum size)
static constexpr size_t MAX_TEXT_SIZE = 255;
size_t text_length = (static_cast<size_t>(ret) > MAX_TEXT_SIZE) ? MAX_TEXT_SIZE : ret;
uint16_t text_length = ret;
size_t total_size = total_size_in_32bit_words(text_length);
auto *msg = reinterpret_cast<LogMessage *>(mpsc_pbuf_alloc(&this->log_buffer_, total_size, K_NO_WAIT));
if (msg == nullptr) {
return false;
}
msg->level = level;
msg->tag = tag;
msg->line = line;
strncpy(msg->thread_name, thread_name, sizeof(msg->thread_name) - 1);
msg->thread_name[sizeof(msg->thread_name) - 1] = '\0'; // Ensure null termination
fill_task_log_header(msg, level, tag, line, thread_name);
// Format the message text directly into the acquired memory
// We add 1 to text_length to ensure space for null terminator during formatting
@@ -90,11 +82,7 @@ bool TaskLogBuffer::borrow_message_main_loop(LogMessage *&message, uint16_t &tex
// we claimed buffer already, const_cast is safe here
message = const_cast<LogMessage *>(reinterpret_cast<const LogMessage *>(this->current_token_));
text_length = message->text_length;
// Remove trailing newlines
while (text_length > 0 && message->text_data()[text_length - 1] == '\n') {
text_length--;
}
text_length = trim_trailing_newlines(message->text_data(), message->text_length);
return true;
}
@@ -6,12 +6,14 @@
#include "esphome/core/helpers.h"
#include <zephyr/sys/mpsc_pbuf.h>
#include "task_log_message.h"
namespace esphome::logger {
// "0x" + 2 hex digits per byte + '\0'
static constexpr size_t MAX_POINTER_REPRESENTATION = 2 + sizeof(void *) * 2 + 1;
extern __thread bool non_main_task_recursion_guard_; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
extern __thread bool non_main_task_recursion_guard; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
@@ -34,7 +36,6 @@ class TaskLogBuffer {
inline char *text_data() { return reinterpret_cast<char *>(this) + sizeof(LogMessage); }
};
TaskLogBuffer();
~TaskLogBuffer() = default;
// Check if there are messages ready to be processed using an atomic counter for performance
inline bool HOT has_messages() { return mpsc_pbuf_is_pending(&this->log_buffer_); }
@@ -0,0 +1,54 @@
#pragma once
#include "esphome/core/defines.h"
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
namespace esphome::logger {
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
// Header of a variable-size task log message; the text follows it
struct TaskLogMessage {
const char *tag; // We store the pointer, assuming tags are static
char thread_name[16]; // Copied, the task may be gone before the main loop reads it
uint16_t text_length;
uint16_t line;
uint8_t level;
inline char *text_data() { return reinterpret_cast<char *>(this) + sizeof(TaskLogMessage); }
};
#endif
#if defined(USE_ESP32) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
static constexpr int TASK_LOG_MAX_TEXT_SIZE = 255;
inline int task_log_cap_length(int ret) { return ret > TASK_LOG_MAX_TEXT_SIZE ? TASK_LOG_MAX_TEXT_SIZE : ret; }
#endif
template<typename Message>
inline void fill_task_log_header(Message *msg, uint8_t level, const char *tag, uint16_t line, const char *thread_name) {
msg->level = level;
msg->tag = tag;
msg->line = line;
if (thread_name != nullptr) {
strncpy(msg->thread_name, thread_name, sizeof(msg->thread_name) - 1);
msg->thread_name[sizeof(msg->thread_name) - 1] = '\0';
} else {
msg->thread_name[0] = '\0';
}
}
inline uint16_t trim_trailing_newlines(const char *text, uint16_t length) {
while (length > 0 && text[length - 1] == '\n')
length--;
return length;
}
} // namespace esphome::logger
#endif // USE_ESPHOME_TASK_LOG_BUFFER
+3
View File
@@ -16,6 +16,7 @@ from esphome.const import (
UNIT_CELSIUS,
UNIT_MICROTESLA,
)
from esphome.core import CORE
from esphome.types import ConfigType
CODEOWNERS = ["@functionpointer"]
@@ -148,3 +149,5 @@ async def to_code(config: ConfigType) -> None:
await cg.add_pin(var.set_drdy_gpio, config.get(CONF_DRDY_PIN))
cg.add_library("functionpointer/arduino-MLX90393", "1.0.2")
if CORE.using_arduino:
cg.add_library("Wire", None)
+4 -4
View File
@@ -806,10 +806,10 @@ void ModbusServerHub::process_modbus_client_frame_(uint8_t address, uint8_t func
bool Modbus::send_frame_(const ModbusFrame &frame) {
int32_t tx_delay_remaining = this->tx_delay_remaining();
if (tx_delay_remaining > 0) {
// Yield the whole-ms part: delay() never blocks past the request on FreeRTOS, and only slightly
// over elsewhere, which just lengthens the gap. The recompute below makes the remainder exact.
if (tx_delay_remaining >= (int32_t) US_PER_MS) {
delay(tx_delay_remaining / US_PER_MS);
// Yield all but the last whole ms: delay() can block up to a tick past the request, and a tick
// longer than 1 ms just lengthens the gap. The recompute below makes the remainder exact.
if (tx_delay_remaining >= (int32_t) (2 * US_PER_MS)) {
delay(tx_delay_remaining / US_PER_MS - 1);
tx_delay_remaining = this->tx_delay_remaining();
}
if (tx_delay_remaining > 0)
Loaded 100 of 324 files, more files were not shown because too many files have changed in this diff. Show more