ESPHome 2026.2.2
Loading...
Searching...
No Matches
api_frame_helper.h
Go to the documentation of this file.
1#pragma once
2#include <array>
3#include <cstdint>
4#include <limits>
5#include <memory>
6#include <span>
7#include <utility>
8#include <vector>
9
11#ifdef USE_API
14#include "esphome/core/log.h"
15
16namespace esphome::api {
17
18// uncomment to log raw packets
19//#define HELPER_LOG_PACKETS
20
21// Maximum message size limits to prevent OOM on constrained devices
22// Handshake messages are limited to a small size for security
23static constexpr uint16_t MAX_HANDSHAKE_SIZE = 128;
24
25// Data message limits vary by platform based on available memory
26#ifdef USE_ESP8266
27static constexpr uint16_t MAX_MESSAGE_SIZE = 8192; // 8 KiB for ESP8266
28#else
29static constexpr uint16_t MAX_MESSAGE_SIZE = 32768; // 32 KiB for ESP32 and other platforms
30#endif
31
32// Maximum number of messages to batch in a single write operation
33// Must be >= MAX_INITIAL_PER_BATCH in api_connection.h (enforced by static_assert there)
34static constexpr size_t MAX_MESSAGES_PER_BATCH = 34;
35
36class ProtoWriteBuffer;
37
38// Max client name length (e.g., "Home Assistant 2026.1.0.dev0" = 28 chars)
39static constexpr size_t CLIENT_INFO_NAME_MAX_LEN = 32;
40
42 const uint8_t *data; // Points directly into frame helper's rx_buf_ (valid until next read_packet call)
43 uint16_t data_len;
44 uint16_t type;
45};
46
47// Packed message info structure to minimize memory usage
49 uint16_t offset; // Offset in buffer where message starts
50 uint16_t payload_size; // Size of the message payload
51 uint8_t message_type; // Message type (0-255)
52
53 MessageInfo(uint8_t type, uint16_t off, uint16_t size) : offset(off), payload_size(size), message_type(type) {}
54};
55
56enum class APIError : uint16_t {
57 OK = 0,
58 WOULD_BLOCK = 1001,
59 BAD_INDICATOR = 1003,
60 BAD_DATA_PACKET = 1004,
61 TCP_NODELAY_FAILED = 1005,
63 CLOSE_FAILED = 1007,
64 SHUTDOWN_FAILED = 1008,
65 BAD_STATE = 1009,
66 BAD_ARG = 1010,
67 SOCKET_READ_FAILED = 1011,
69 OUT_OF_MEMORY = 1018,
70 CONNECTION_CLOSED = 1022,
71#ifdef USE_API_NOISE
81#endif
82};
83
84const LogString *api_error_to_logstr(APIError err);
85
87 public:
88 APIFrameHelper() = default;
89 explicit APIFrameHelper(std::unique_ptr<socket::Socket> socket) : socket_(std::move(socket)) {}
90
91 // Get client name (null-terminated)
92 const char *get_client_name() const { return this->client_name_; }
93 // Get client peername/IP into caller-provided buffer (fetches on-demand from socket)
94 // Returns pointer to buf for convenience in printf-style calls
95 const char *get_peername_to(std::span<char, socket::SOCKADDR_STR_LEN> buf) const;
96 // Set client name from buffer with length (truncates if needed)
97 void set_client_name(const char *name, size_t len) {
98 size_t copy_len = std::min(len, sizeof(this->client_name_) - 1);
99 memcpy(this->client_name_, name, copy_len);
100 this->client_name_[copy_len] = '\0';
101 }
102 virtual ~APIFrameHelper() = default;
103 virtual APIError init() = 0;
104 virtual APIError loop();
106 bool can_write_without_blocking() { return this->state_ == State::DATA && this->tx_buf_count_ == 0; }
107 int getpeername(struct sockaddr *addr, socklen_t *addrlen) { return socket_->getpeername(addr, addrlen); }
109 if (state_ == State::CLOSED)
110 return APIError::OK; // Already closed
112 int err = this->socket_->close();
113 if (err == -1)
115 return APIError::OK;
116 }
118 int err = this->socket_->shutdown(how);
119 if (err == -1)
121 if (how == SHUT_RDWR) {
123 }
124 return APIError::OK;
125 }
126 // Manage TCP_NODELAY (Nagle's algorithm) based on message type.
127 //
128 // For non-log messages (sensor data, state updates): Always disable Nagle
129 // (NODELAY on) for immediate delivery - these are time-sensitive.
130 //
131 // For log messages: Use Nagle to coalesce multiple small log packets into
132 // fewer larger packets, reducing WiFi overhead. However, we limit batching
133 // to 3 messages to avoid excessive LWIP buffer pressure on memory-constrained
134 // devices like ESP8266. LWIP's TCP_OVERSIZE option coalesces the data into
135 // shared pbufs, but holding data too long waiting for Nagle's timer causes
136 // buffer exhaustion and dropped messages.
137 //
138 // Flow: Log 1 (Nagle on) -> Log 2 (Nagle on) -> Log 3 (NODELAY, flush all)
139 //
140 void set_nodelay_for_message(bool is_log_message) {
141 if (!is_log_message) {
142 if (this->nodelay_state_ != NODELAY_ON) {
143 this->set_nodelay_raw_(true);
145 }
146 return;
147 }
148
149 // Log messages 1-3: state transitions -1 -> 1 -> 2 -> -1 (flush on 3rd)
150 if (this->nodelay_state_ == NODELAY_ON) {
151 this->set_nodelay_raw_(false);
152 this->nodelay_state_ = 1;
153 } else if (this->nodelay_state_ >= LOG_NAGLE_COUNT) {
154 this->set_nodelay_raw_(true);
156 } else {
157 this->nodelay_state_++;
158 }
159 }
161 // Write multiple protobuf messages in a single operation
162 // messages contains (message_type, offset, length) for each message in the buffer
163 // The buffer contains all messages with appropriate padding before each
164 virtual APIError write_protobuf_messages(ProtoWriteBuffer buffer, std::span<const MessageInfo> messages) = 0;
165 // Get the frame header padding required by this protocol
166 uint8_t frame_header_padding() const { return frame_header_padding_; }
167 // Get the frame footer size required by this protocol
168 uint8_t frame_footer_size() const { return frame_footer_size_; }
169 // Check if socket has data ready to read
170 bool is_socket_ready() const { return socket_ != nullptr && socket_->ready(); }
171 // Release excess memory from internal buffers after initial sync
173 // rx_buf_: Safe to clear only if no partial read in progress.
174 // rx_buf_len_ tracks bytes read so far; if non-zero, we're mid-frame
175 // and clearing would lose partially received data.
176 if (this->rx_buf_len_ == 0) {
177 // Use swap trick since shrink_to_fit() is non-binding and may be ignored
178 std::vector<uint8_t>().swap(this->rx_buf_);
179 }
180 }
181
182 protected:
183 // Buffer containing data to be sent
184 struct SendBuffer {
185 std::unique_ptr<uint8_t[]> data;
186 uint16_t size{0}; // Total size of the buffer
187 uint16_t offset{0}; // Current offset within the buffer
188
189 // Using uint16_t reduces memory usage since ESPHome API messages are limited to UINT16_MAX (65535) bytes
190 uint16_t remaining() const { return size - offset; }
191 const uint8_t *current_data() const { return data.get() + offset; }
192 };
193
194 // Common implementation for writing raw data to socket
195 APIError write_raw_(const struct iovec *iov, int iovcnt, uint16_t total_write_len);
196
197 // Try to send data from the tx buffer
199
200 // Helper method to buffer data from IOVs
201 void buffer_data_from_iov_(const struct iovec *iov, int iovcnt, uint16_t total_write_len, uint16_t offset);
202
203 // Common socket write error handling
205 template<typename StateEnum>
206 APIError write_raw_(const struct iovec *iov, int iovcnt, socket::Socket *socket, std::vector<uint8_t> &tx_buf,
207 const std::string &info, StateEnum &state, StateEnum failed_state);
208
209 // Socket ownership (4 bytes on 32-bit, 8 bytes on 64-bit)
210 std::unique_ptr<socket::Socket> socket_;
211
212 // Common state enum for all frame helpers
213 // Note: Not all states are used by all implementations
214 // - INITIALIZE: Used by both Noise and Plaintext
215 // - CLIENT_HELLO, SERVER_HELLO, HANDSHAKE: Only used by Noise protocol
216 // - DATA: Used by both Noise and Plaintext
217 // - CLOSED: Used by both Noise and Plaintext
218 // - FAILED: Used by both Noise and Plaintext
219 // - EXPLICIT_REJECT: Only used by Noise protocol
220 enum class State : uint8_t {
221 INITIALIZE = 1,
222 CLIENT_HELLO = 2, // Noise only
223 SERVER_HELLO = 3, // Noise only
224 HANDSHAKE = 4, // Noise only
225 DATA = 5,
226 CLOSED = 6,
227 FAILED = 7,
228 EXPLICIT_REJECT = 8, // Noise only
229 };
230
231 // Containers (size varies, but typically 12+ bytes on 32-bit)
232 std::array<std::unique_ptr<SendBuffer>, API_MAX_SEND_QUEUE> tx_buf_;
233 std::vector<uint8_t> rx_buf_;
234
235 // Client name buffer - stores name from Hello message or initial peername
236 char client_name_[CLIENT_INFO_NAME_MAX_LEN]{};
237
238 // Group smaller types together
239 uint16_t rx_buf_len_ = 0;
243 uint8_t tx_buf_head_{0};
244 uint8_t tx_buf_tail_{0};
245 uint8_t tx_buf_count_{0};
246 // Nagle batching state for log messages. NODELAY_ON (-1) means NODELAY is enabled
247 // (immediate send). Values 1-2 count log messages in the current Nagle batch.
248 // After LOG_NAGLE_COUNT logs, we switch to NODELAY to flush and reset.
249 static constexpr int8_t NODELAY_ON = -1;
250 static constexpr int8_t LOG_NAGLE_COUNT = 2;
252
253 // Internal helper to set TCP_NODELAY socket option
254 void set_nodelay_raw_(bool enable) {
255 int val = enable ? 1 : 0;
256 this->socket_->setsockopt(IPPROTO_TCP, TCP_NODELAY, &val, sizeof(int));
257 }
258
259 // Common initialization for both plaintext and noise protocols
261
262 // Helper method to handle socket read results
264};
265
266} // namespace esphome::api
267
268#endif // USE_API
const char * get_client_name() const
APIError handle_socket_read_result_(ssize_t received)
std::vector< uint8_t > rx_buf_
APIError write_raw_(const struct iovec *iov, int iovcnt, socket::Socket *socket, std::vector< uint8_t > &tx_buf, const std::string &info, StateEnum &state, StateEnum failed_state)
virtual APIError read_packet(ReadPacketBuffer *buffer)=0
std::array< std::unique_ptr< SendBuffer >, API_MAX_SEND_QUEUE > tx_buf_
void buffer_data_from_iov_(const struct iovec *iov, int iovcnt, uint16_t total_write_len, uint16_t offset)
int getpeername(struct sockaddr *addr, socklen_t *addrlen)
virtual APIError write_protobuf_messages(ProtoWriteBuffer buffer, std::span< const MessageInfo > messages)=0
virtual APIError init()=0
APIFrameHelper(std::unique_ptr< socket::Socket > socket)
const char * get_peername_to(std::span< char, socket::SOCKADDR_STR_LEN > buf) const
std::unique_ptr< socket::Socket > socket_
char client_name_[CLIENT_INFO_NAME_MAX_LEN]
void set_client_name(const char *name, size_t len)
virtual APIError write_protobuf_packet(uint8_t type, ProtoWriteBuffer buffer)=0
APIError write_raw_(const struct iovec *iov, int iovcnt, uint16_t total_write_len)
static constexpr int8_t NODELAY_ON
void set_nodelay_for_message(bool is_log_message)
static constexpr int8_t LOG_NAGLE_COUNT
virtual ~APIFrameHelper()=default
uint16_t type
bool state
Definition fan.h:2
uint32_t socklen_t
Definition headers.h:97
__int64 ssize_t
Definition httplib.h:178
mopeka_std_values val[4]
const LogString * api_error_to_logstr(APIError err)
std::string size_t len
Definition helpers.h:692
size_t size
Definition helpers.h:729
MessageInfo(uint8_t type, uint16_t off, uint16_t size)