ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
api_frame_helper_plaintext.h
Go to the documentation of this file.
1#pragma once
2#include "api_frame_helper.h"
3#ifdef USE_API
4#ifdef USE_API_PLAINTEXT
5
6namespace esphome::api {
7
9 public:
10 // Plaintext header structure (worst case):
11 // Pos 0: indicator (0x00)
12 // Pos 1-3: payload size varint (up to 3 bytes)
13 // Pos 4-5: message type varint (up to 2 bytes)
14 // Pos 6+: actual payload data
15 static constexpr uint8_t HEADER_PADDING = 1 + 3 + 2; // indicator + size varint + type varint
16
17 explicit APIPlaintextFrameHelper(std::unique_ptr<socket::Socket> socket) : APIFrameHelper(std::move(socket)) {
19 }
20 ~APIPlaintextFrameHelper() override = default;
21 APIError init() override;
22 APIError loop() override;
23 APIError read_packet(ReadPacketBuffer *buffer) override;
24 APIError write_protobuf_packet(uint8_t type, ProtoWriteBuffer buffer) override;
25 APIError write_protobuf_messages(ProtoWriteBuffer buffer, std::span<const MessageInfo> messages) override;
26#ifdef USE_API_NOISE
27 // After try_read_frame_ returned PROTOCOL_SWITCH_TO_NOISE: copy out the
28 // header bytes already consumed from the socket (at most 3, the size of the
29 // Noise fixed header) so the replacement Noise helper can be seeded with them.
30 uint8_t get_consumed_header(uint8_t out[3]) const {
31 memcpy(out, this->rx_header_buf_, this->rx_header_buf_pos_);
32 return this->rx_header_buf_pos_;
33 }
34#endif
35
36 protected:
38
39 // Group 2-byte aligned types
42
43 // Group 1-byte types together
44 // Fixed-size header buffer for plaintext protocol:
45 // We now store the indicator byte + the two varints.
46 // To match noise protocol's maximum message size (UINT16_MAX = 65535), we need:
47 // 1 byte for indicator + 3 bytes for message size varint (supports up to 2097151) + 2 bytes for message type varint
48 //
49 // While varints could theoretically be up to 10 bytes each for 64-bit values,
50 // attempting to process messages with headers that large would likely crash the
51 // ESP32 due to memory constraints.
52 uint8_t rx_header_buf_[6]; // 1 byte indicator + 5 bytes for varints (3 for size + 2 for type)
53 uint8_t rx_header_buf_pos_ = 0;
54 bool rx_header_parsed_ = false;
55 // 8 bytes total, no padding needed
56};
57
58} // namespace esphome::api
59#endif // USE_API_PLAINTEXT
60#endif // USE_API
APIPlaintextFrameHelper(std::unique_ptr< socket::Socket > socket)
uint8_t get_consumed_header(uint8_t out[3]) const
APIError try_read_frame_()
Read a packet into the rx_buf_.
APIError init() override
Initialize the frame helper, returns OK if successful.
~APIPlaintextFrameHelper() override=default
APIError write_protobuf_packet(uint8_t type, ProtoWriteBuffer buffer) override
APIError read_packet(ReadPacketBuffer *buffer) override
APIError write_protobuf_messages(ProtoWriteBuffer buffer, std::span< const MessageInfo > messages) override
uint16_t type
STL namespace.