From 50310fe49498ba56d3770de0906b7440441a1818 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 5 Jun 2025 17:54:03 +0100 Subject: [PATCH] batch --- esphome/components/api/api_connection.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index 79f7c79e33..01a85be384 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -1741,12 +1741,15 @@ void APIConnection::process_batch_() { size_t total_size = 0; size_t processed_count = 0; - // Create initial buffer with estimated size - ProtoWriteBuffer batch_buffer = this->create_buffer(MAX_BATCH_SIZE_BYTES); - // Conservative estimate for minimum packet size: 6 byte header + 100 bytes minimum message + footer const uint16_t min_next_packet_size = 106 + this->helper_->frame_footer_size(); + // Create initial buffer with estimated size based on number of items + // Use min of (estimated total size, MAX_BATCH_SIZE_BYTES) + uint32_t estimated_size = std::min(static_cast(min_next_packet_size * this->deferred_batch_.items.size()), + static_cast(MAX_BATCH_SIZE_BYTES)); + ProtoWriteBuffer batch_buffer = this->create_buffer(estimated_size); + for (size_t i = 0; i < this->deferred_batch_.items.size(); i++) { const auto &item = this->deferred_batch_.items[i];