From 6d1281301fbbb2d5e9572fd9969a898866d02fbf Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 6 Feb 2026 23:36:01 +0100 Subject: [PATCH] [ld2412] Batch UART reads to reduce loop overhead Read all available bytes in batches via read_array() instead of byte-at-a-time read() calls. Each read() internally chains through read_byte -> read_array(1) -> check_read_timeout_ -> available(), resulting in 3 UART calls per byte. Batching reduces this significantly. --- esphome/components/ld2412/ld2412.cpp | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/esphome/components/ld2412/ld2412.cpp b/esphome/components/ld2412/ld2412.cpp index c2f441e472..e5d35b7ffb 100644 --- a/esphome/components/ld2412/ld2412.cpp +++ b/esphome/components/ld2412/ld2412.cpp @@ -310,8 +310,23 @@ void LD2412Component::restart_and_read_all_info() { } void LD2412Component::loop() { - while (this->available()) { - this->readline_(this->read()); + int avail = this->available(); + if (avail == 0) { + return; + } + + // Read all available bytes in batches to reduce UART call overhead. + uint8_t buf[MAX_LINE_LENGTH]; + while (avail > 0) { + size_t to_read = std::min(static_cast(avail), sizeof(buf)); + if (!this->read_array(buf, to_read)) { + break; + } + avail -= to_read; + + for (size_t i = 0; i < to_read; i++) { + this->readline_(buf[i]); + } } }