diff --git a/esphome/components/api/api_pb2.cpp b/esphome/components/api/api_pb2.cpp index 9d8b109986..f2c4d1797f 100644 --- a/esphome/components/api/api_pb2.cpp +++ b/esphome/components/api/api_pb2.cpp @@ -1938,15 +1938,11 @@ void BluetoothGATTService::calculate_size(uint32_t &total_size) const { } void BluetoothGATTGetServicesResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_uint64(1, this->address); - for (const auto &it : this->services) { - buffer.encode_message(2, it, true); - } + buffer.encode_message(2, this->services[0], true); } void BluetoothGATTGetServicesResponse::calculate_size(uint32_t &total_size) const { ProtoSize::add_uint64_field(total_size, 1, this->address); - for (const auto &it : this->services) { - ProtoSize::add_message_object_repeated(total_size, 1, it); - } + ProtoSize::add_message_object_repeated(total_size, 1, this->services[0]); } void BluetoothGATTGetServicesDoneResponse::encode(ProtoWriteBuffer buffer) const { buffer.encode_uint64(1, this->address); diff --git a/script/api_protobuf/api_protobuf.py b/script/api_protobuf/api_protobuf.py index 453f4ffe10..b9d7f1fd6e 100755 --- a/script/api_protobuf/api_protobuf.py +++ b/script/api_protobuf/api_protobuf.py @@ -929,6 +929,14 @@ class FixedArrayRepeatedType(TypeInfo): @property def encode_content(self) -> str: + # Special case for single-element arrays - no loop needed + if self.array_size == 1: + if isinstance(self._ti, EnumType): + return f"buffer.{self._ti.encode_func}({self.number}, static_cast(this->{self.field_name}[0]), true);" + else: + return f"buffer.{self._ti.encode_func}({self.number}, this->{self.field_name}[0], true);" + + # Multiple elements need a loop o = f"for (const auto &it : this->{self.field_name}) {{\n" if isinstance(self._ti, EnumType): o += f" buffer.{self._ti.encode_func}({self.number}, static_cast(it), true);\n" @@ -953,6 +961,11 @@ class FixedArrayRepeatedType(TypeInfo): def get_size_calculation(self, name: str, force: bool = False) -> str: # For fixed arrays, we always encode all elements + + # Special case for single-element arrays - no loop needed + if self.array_size == 1: + return self._ti.get_size_calculation(f"{name}[0]", True) + # Check if this is a fixed-size type by seeing if it has a fixed byte count num_bytes = self._ti.get_fixed_size_bytes() if num_bytes is not None: