[modbus] Batch UART reads to reduce loop overhead (#13822)

This commit is contained in:
J. Nick Koston
2026-02-09 12:21:15 -06:00
committed by GitHub
parent 4a9ff48f02
commit cd55eb927d

View File

@@ -19,16 +19,25 @@ void Modbus::setup() {
void Modbus::loop() { void Modbus::loop() {
const uint32_t now = App.get_loop_component_start_time(); const uint32_t now = App.get_loop_component_start_time();
while (this->available()) { // Read all available bytes in batches to reduce UART call overhead.
uint8_t byte; int avail = this->available();
this->read_byte(&byte); uint8_t buf[64];
if (this->parse_modbus_byte_(byte)) { while (avail > 0) {
this->last_modbus_byte_ = now; size_t to_read = std::min(static_cast<size_t>(avail), sizeof(buf));
} else { if (!this->read_array(buf, to_read)) {
size_t at = this->rx_buffer_.size(); break;
if (at > 0) { }
ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse failed", at); avail -= to_read;
this->rx_buffer_.clear();
for (size_t i = 0; i < to_read; i++) {
if (this->parse_modbus_byte_(buf[i])) {
this->last_modbus_byte_ = now;
} else {
size_t at = this->rx_buffer_.size();
if (at > 0) {
ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse failed", at);
this->rx_buffer_.clear();
}
} }
} }
} }