diff --git a/esphome/components/api/proto.cpp b/esphome/components/api/proto.cpp index 9db7e91282..73a3bab12a 100644 --- a/esphome/components/api/proto.cpp +++ b/esphome/components/api/proto.cpp @@ -78,6 +78,11 @@ void ProtoWriteBuffer::debug_check_bounds_(size_t bytes, const char *caller) { abort(); } } +void ProtoWriteBuffer::debug_check_encode_size_(uint32_t field_id, uint32_t expected, ptrdiff_t actual) { + ESP_LOGE(TAG, "encode_message: size mismatch for field %" PRIu32 ": calculated=%" PRIu32 " actual=%td", field_id, + expected, actual); + abort(); +} #endif void ProtoDecodableMessage::decode(const uint8_t *buffer, size_t length) { diff --git a/esphome/components/api/proto.h b/esphome/components/api/proto.h index af76616445..4522fc9665 100644 --- a/esphome/components/api/proto.h +++ b/esphome/components/api/proto.h @@ -350,6 +350,7 @@ class ProtoWriteBuffer { protected: #ifdef ESPHOME_DEBUG_API void debug_check_bounds_(size_t bytes, const char *caller = __builtin_FUNCTION()); + void debug_check_encode_size_(uint32_t field_id, uint32_t expected, ptrdiff_t actual); #else void debug_check_bounds_([[maybe_unused]] size_t bytes) {} #endif @@ -943,14 +944,11 @@ inline void ProtoWriteBuffer::encode_message(uint32_t field_id, const ProtoMessa // Encode nested message - pos_ advances directly through the reference #ifdef ESPHOME_DEBUG_API uint8_t *start = this->pos_; -#endif value.encode(*this); -#ifdef ESPHOME_DEBUG_API - if (static_cast(this->pos_ - start) != msg_length_bytes) { - ESP_LOGE(TAG, "encode_message: size mismatch for field %" PRIu32 ": calculated=%" PRIu32 " actual=%td", field_id, - msg_length_bytes, this->pos_ - start); - abort(); - } + if (static_cast(this->pos_ - start) != msg_length_bytes) + this->debug_check_encode_size_(field_id, msg_length_bytes, this->pos_ - start); +#else + value.encode(*this); #endif }