ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
frame_reader.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <cstddef>
5#include <cstdint>
6#include <cstring>
7#include <type_traits>
8
9// Out of line, one copy: the frame readers' rare paths call each other, and GCC would add specialised clones
10#if defined(__clang__)
11#define ESPHOME_FRAME_READER_COLD __attribute__((noinline))
12#else
13#define ESPHOME_FRAME_READER_COLD __attribute__((noinline, noclone))
14#endif
15
16namespace esphome {
17
18namespace frame_reader_detail {
19// A fold, not an array, so no header table lands in RAM on ESP8266
20template<uint8_t... HEADER> constexpr uint8_t header_byte(size_t i) {
21 size_t j = 0;
22 uint8_t r = 0;
23 ((r = (j++ == i) ? HEADER : r), ...);
24 return r;
25}
26} // namespace frame_reader_detail
27
30template<size_t N, uint8_t... HEADER> class FrameReader {
31 using pos_t = std::conditional_t<(N <= 0xFF), uint8_t, uint16_t>;
32 static constexpr size_t HEADER_LEN = sizeof...(HEADER);
33 static_assert(HEADER_LEN >= 1 && HEADER_LEN <= 8, "FrameReader takes 1 to 8 header bytes"); // bounds replay_() depth
34 static_assert(HEADER_LEN < N && N <= 0xFFFF, "FrameReader size out of range");
35
36 public:
38 const uint8_t *feed(uint8_t c) {
39 pos_t pos = this->pos_;
40 if (pos < HEADER_LEN && c != frame_reader_detail::header_byte<HEADER...>(pos)) {
41 // A later byte of the broken header, or c, may start the real one
42 if (pos == 0)
43 return nullptr;
44 this->buf_[pos] = c;
45 return this->replay_(pos);
46 }
47 this->buf_[pos++] = c;
48 if (pos < N) {
49 this->pos_ = pos;
50 return nullptr;
51 }
52 this->pos_ = 0;
53 return this->buf_;
54 }
55
57 size_t length() const { return this->pos_; }
58
60 void reset() { this->pos_ = 0; }
61
64 void resync() { this->replay_(N - 1); }
65
66 protected:
67 // Start over and feed buf_[1..last] again; never completes a frame as last < N, so it returns nullptr, which lets
68 // feed() end in a tail call. Out of line, as feed() and replay_() call each other.
69 const uint8_t *ESPHOME_FRAME_READER_COLD replay_(size_t last) {
70 this->pos_ = 0;
71 for (size_t i = 1; i <= last; i++) {
72 this->feed(this->buf_[i]);
73 }
74 return nullptr;
75 }
76
77 uint8_t buf_[N];
78 pos_t pos_{0};
79};
80
81// Length rules: get() gives the whole frame length once KNOWN_AT bytes are in, or 0 to reject the header.
82
87 size_t offset;
88 size_t payload_at = 0;
89 size_t trailer = 0;
90};
91
93template<LengthField F> struct FrameLengthU8 {
94 static_assert(F.payload_at == 0 && F.trailer == 0, "A whole-frame length has no payload_at or trailer");
95 static constexpr size_t KNOWN_AT = F.offset + 1;
96 static constexpr size_t get(const uint8_t *buf) { return buf[F.offset]; }
97};
98template<LengthField F> struct FrameLengthU16BE {
99 static_assert(F.payload_at == 0 && F.trailer == 0, "A whole-frame length has no payload_at or trailer");
100 static constexpr size_t KNOWN_AT = F.offset + 2;
101 static constexpr size_t get(const uint8_t *buf) { return (size_t(buf[F.offset]) << 8) | buf[F.offset + 1]; }
102};
103template<LengthField F> struct FrameLengthU16LE {
104 static_assert(F.payload_at == 0 && F.trailer == 0, "A whole-frame length has no payload_at or trailer");
105 static constexpr size_t KNOWN_AT = F.offset + 2;
106 static constexpr size_t get(const uint8_t *buf) { return buf[F.offset] | (size_t(buf[F.offset + 1]) << 8); }
107};
108namespace frame_reader_detail {
109// A payload length read by the whole-frame rule FIELD; the payload starts at PAYLOAD_AT
110template<LengthField F, class FIELD> struct PayloadLength {
111 static_assert(F.payload_at == 0 || F.payload_at >= FIELD::KNOWN_AT, "payload_at must follow the length field");
112 static constexpr size_t KNOWN_AT = FIELD::KNOWN_AT;
113 static constexpr size_t PAYLOAD_AT = F.payload_at != 0 ? F.payload_at : KNOWN_AT;
114 // The shortest frame: an empty payload
115 static constexpr size_t MIN = PAYLOAD_AT + F.trailer;
116 static constexpr size_t get(const uint8_t *buf) { return PAYLOAD_AT + FIELD::get(buf) + F.trailer; }
117};
118} // namespace frame_reader_detail
119
121template<LengthField F>
123template<LengthField F>
125template<LengthField F>
128template<size_t LEN> struct FrameFixedLength {
129 static_assert(LEN >= 2, "A fixed length frame has at least 2 bytes");
130 static constexpr size_t KNOWN_AT = 1;
131 static constexpr size_t get(const uint8_t * /*buf*/) { return LEN; }
132};
133
136 static constexpr size_t MIN = 0;
137 static constexpr size_t CHECK_AT = 0;
138 static constexpr size_t WARN_MAX = 0;
139 static constexpr bool check(const uint8_t * /*buf*/) { return true; }
140 static constexpr bool fits(size_t /*len*/) { return true; }
141};
143template<size_t LEN> struct FrameMinLength : FrameOption {
144 static constexpr size_t MIN = LEN;
145};
147template<size_t BYTES, bool (*CHECK)(const uint8_t *)> struct CheckFirstBytes : FrameOption {
148 static constexpr size_t CHECK_AT = BYTES;
149 static bool check(const uint8_t *buf) { return CHECK(buf); }
150};
152template<size_t MAX, void (*WARN)(size_t)> struct WarnIfLongerThan : FrameOption {
153 static constexpr size_t WARN_MAX = MAX;
154 static bool fits(size_t len) {
155 if (len <= MAX)
156 return true;
157 WARN(len);
158 return false;
159 }
160};
161
163template<uint8_t... BYTES> struct FrameHeader {
164 static constexpr size_t LEN = sizeof...(BYTES);
165 static_assert(LEN >= 1 && LEN <= 8, "A FrameHeader has 1 to 8 bytes");
166 static constexpr uint8_t byte(size_t i) { return frame_reader_detail::header_byte<BYTES...>(i); }
167};
168
169namespace frame_reader_detail {
170// The length rule with its options applied: every check runs before any warning, so a failed check never warns
171template<class LENGTH, class... OPTIONS> struct OptionLength {
172 static constexpr size_t KNOWN_AT = std::max<size_t>({LENGTH::KNOWN_AT, OPTIONS::CHECK_AT...});
173 static size_t get(const uint8_t *buf) {
174 if (!(OPTIONS::check(buf) && ...))
175 return 0;
176 const size_t len = LENGTH::get(buf);
177 return (OPTIONS::fits(len) && ...) ? len : 0;
178 }
179};
180// The shortest frame a length rule allows, 0 when it sets none
181template<class LENGTH> constexpr size_t RULE_MIN = 0;
182template<LengthField F, class FIELD> constexpr size_t RULE_MIN<PayloadLength<F, FIELD>> = PayloadLength<F, FIELD>::MIN;
183// The length of a FrameFixedLength rule, 0 for every other rule
184template<class LENGTH> constexpr size_t FIXED_LENGTH = 0;
185template<size_t LEN> constexpr size_t FIXED_LENGTH<FrameFixedLength<LEN>> = LEN;
186} // namespace frame_reader_detail
187
190template<class HEADER, class LENGTH, class... OPTIONS> struct FrameFormat {
191 static_assert((std::is_base_of_v<FrameOption, OPTIONS> && ...),
192 "FrameFormat options are FrameMinLength, CheckFirstBytes and WarnIfLongerThan");
193 static_assert(((OPTIONS::CHECK_AT == 0 || OPTIONS::CHECK_AT >= LENGTH::KNOWN_AT) && ...),
194 "CheckFirstBytes must cover the length field");
195 // Checks run only once the largest CHECK_AT is in, so a shorter one would reject late
196 static_assert((0 + ... + (OPTIONS::CHECK_AT != 0)) <= 1, "A FrameFormat takes at most one CheckFirstBytes");
197 // Only the shortest limit would ever warn
198 static_assert((0 + ... + (OPTIONS::WARN_MAX != 0)) <= 1, "A FrameFormat takes at most one WarnIfLongerThan");
199 using Length = frame_reader_detail::OptionLength<LENGTH, OPTIONS...>;
200 static constexpr size_t HEADER_LEN = HEADER::LEN;
201 static constexpr uint8_t FIRST = HEADER::byte(0);
203 static constexpr size_t WARN_MAX = std::max<size_t>({0, OPTIONS::WARN_MAX...});
204 static constexpr size_t MIN_LEN = std::max<size_t>({Length::KNOWN_AT, HEADER_LEN, 2});
205 // A shorter length is not a frame
206 static constexpr size_t SHORTEST =
207 std::max<size_t>({MIN_LEN, frame_reader_detail::RULE_MIN<LENGTH>, OPTIONS::MIN...});
208 static_assert(LENGTH::KNOWN_AT == 1 || LENGTH::KNOWN_AT > HEADER_LEN, "The length field must follow the header");
209 static constexpr uint8_t header_byte(size_t i) { return HEADER::byte(i); }
210};
211
221template<size_t N, class... FORMATS> class LengthFrameReader {
222 using pos_t = std::conditional_t<(N <= 0xFF), uint8_t, uint16_t>;
223 static_assert(sizeof...(FORMATS) >= 1, "LengthFrameReader takes at least one FrameFormat");
224 // flush_() copies a partial frame on the stack
225 static_assert(N >= 2 && N <= 1024, "LengthFrameReader size out of range");
226 static constexpr bool distinct_first() {
227 const uint8_t first[] = {FORMATS::FIRST...};
228 for (size_t i = 0; i < sizeof...(FORMATS); i++) {
229 for (size_t j = i + 1; j < sizeof...(FORMATS); j++) {
230 if (first[i] == first[j])
231 return false;
232 }
233 }
234 return true;
235 }
236 static_assert(distinct_first(), "Each FrameFormat needs a different first header byte");
237 static_assert(((FORMATS::SHORTEST <= N) && ...), "N must hold the shortest frame of every FrameFormat");
238 static_assert(((FORMATS::FIXED_LENGTH == 0 ||
239 (FORMATS::FIXED_LENGTH >= FORMATS::SHORTEST && FORMATS::FIXED_LENGTH <= N)) &&
240 ...),
241 "A fixed length must hold the header and fit in N");
242 static_assert(((FORMATS::WARN_MAX <= N) && ...),
243 "A WarnIfLongerThan MAX above N lets longer frames be skipped without a warning");
244
245 public:
249 template<class F> void __attribute__((always_inline)) feed(uint8_t c, F &&handle) {
250 // Most bytes are in the middle of a frame whose length is known, and not its last byte
251 const pos_t pos = this->pos_;
252 if (pos + 1u < this->end_) {
253 this->buf_[pos] = c;
254 this->pos_ = pos + 1;
255 } else if (const size_t len = this->feed_edge_(c)) {
256 this->drain_(len, handle);
257 }
258 }
259
262 template<class F> void flush(F &&handle) {
263 // held_end_ marks a partial frame already searched; new bytes move pos_ past it
264 if (this->pos_ != 0 && this->held_end_ != this->pos_)
265 this->flush_(handle);
266 }
267
269 size_t length() const { return this->pos_; }
270
272 bool receiving() const { return this->pos_ != 0 && this->held_end_ != this->pos_; }
273
275 void drop_kept() {
276 if (this->pos_ != 0 && this->held_end_ == this->pos_)
277 this->reset();
278 }
279
281 void reset() {
282 this->pos_ = 0;
283 this->end_ = 0;
284 this->held_end_ = 0;
285 }
286
287 protected:
288 // Hands each frame (len bytes at buf_) to handle, then goes on after a handled frame or from the second byte of a
289 // rejected one
290 template<class F> bool ESPHOME_FRAME_READER_COLD drain_(size_t len, F &handle) {
291 bool handled = false;
292 while (len != 0) {
293 const bool ok = handle(this->buf_, len);
294 handled |= ok;
295 len = this->replay_(ok ? len : 1, this->held_end_);
296 }
297 this->held_end_ = 0;
298 return handled;
299 }
300
301 // Searches the partial frame for frames; when handle takes none, puts the partial frame back and marks it searched
302 template<class F> void ESPHOME_FRAME_READER_COLD flush_(F &handle) {
303 const pos_t pos = this->pos_;
304 const pos_t end = this->end_;
305 uint8_t saved[N];
306 std::memcpy(saved, this->buf_, pos);
307 while (this->pos_ != 0) {
308 // A partial frame left behind the handed over ones is searched on the next idle pass
309 if (this->drain_(this->replay_(1, this->pos_), handle))
310 return;
311 }
312 std::memcpy(this->buf_, saved, pos);
313 this->pos_ = pos;
314 this->end_ = end;
315 this->held_end_ = pos;
316 }
317
318 // Every byte but the middle of a frame; returns the length of a completed frame, or 0
319 size_t ESPHOME_FRAME_READER_COLD feed_edge_(uint8_t c) {
320 // A byte that starts or ends a frame clears the searched mark, so it cannot match a later partial frame
321 this->held_end_ = 0;
322 const pos_t pos = this->pos_;
323 if (pos == 0) {
324 const bool header = ((c == FORMATS::FIRST) || ...);
325 if (header) {
326 this->buf_[0] = c;
327 this->pos_ = 1;
328 }
329 return 0;
330 }
331 if constexpr (sizeof...(FORMATS) == 1) {
332 return this->feed_as_<FORMATS...>(pos, c);
333 } else {
334 const uint8_t first = this->buf_[0];
335 size_t len = 0;
336 (void) ((first == FORMATS::FIRST && ((len = this->feed_as_<FORMATS>(pos, c)), true)) || ...);
337 return len;
338 }
339 }
340
341 template<class F> size_t feed_as_(pos_t pos, uint8_t c) {
342 if (pos < F::HEADER_LEN && c != F::header_byte(pos)) {
343 // A later byte of the broken header, or c, may start the real one
344 this->buf_[pos] = c;
345 return this->replay_(1, pos + 1);
346 }
347 this->buf_[pos++] = c;
348 if (pos == F::MIN_LEN) {
349 const size_t len = F::Length::get(this->buf_);
351 return this->replay_(1, pos);
352 this->end_ = len;
353 }
354 if (pos == this->end_) {
355 this->pos_ = 0;
356 this->end_ = 0;
357 this->held_end_ = pos;
358 return pos;
359 }
360 this->pos_ = pos;
361 return 0;
362 }
363
364 // Start over and feed buf_[from..to) again; writes stay behind the read position. On a completed frame, moves the
365 // bytes not fed yet right behind it, for drain_(), and returns its length; 0 otherwise.
366 size_t ESPHOME_FRAME_READER_COLD replay_(size_t from, size_t to) {
367 this->pos_ = 0;
368 this->end_ = 0;
369 for (size_t i = from; i < to; i++) {
370 const size_t len = this->feed_edge_(this->buf_[i]);
371 if (len == 0)
372 continue;
373 // A nested replay may already have put bytes of its own behind the frame
374 const size_t held = this->held_end_;
375 const size_t rest = to - i - 1;
376 std::memmove(this->buf_ + held, this->buf_ + i + 1, rest);
377 this->held_end_ = held + rest;
378 return len;
379 }
380 return 0;
381 }
382
383 // Before buf_, so they stay within a short load offset of the reader when N is large
384 pos_t pos_{0};
385 // Length of the frame being collected once its length is known; 0 otherwise
386 pos_t end_{0};
387 // End of a held frame plus the bytes after it not fed yet; or, after flush() kept a partial frame, the pos_ it
388 // searched
389 pos_t held_end_{0};
390 uint8_t buf_[N];
391};
392
393} // namespace esphome
394
395#undef ESPHOME_FRAME_READER_COLD
Collects fixed length binary frames of N bytes that start with the header bytes HEADER....
size_t length() const
Number of bytes of the partial frame; 0 after a frame is returned and while looking for a header.
const uint8_t * feed(uint8_t c)
Feed one byte; returns the completed frame, header included, valid until the next call,...
void resync()
For a frame the caller rejected (bad checksum): drop its first byte and realign on a header in the re...
const uint8_t *ESPHOME_FRAME_READER_COLD replay_(size_t last)
void reset()
Forget the partial frame and look for a header from the next byte.
Collects binary frames that give their own length, of up to N bytes, in one or more FrameFormats; the...
void reset()
Forget the partial frame, for a request/response protocol starting a new exchange.
void drop_kept()
Forget a partial frame an idle flush kept, before a request starts a new exchange; safe inside a fram...
void __attribute__((always_inline)) feed(uint8_t c
Feed one byte; calls handle(frame, length) for each frame it completes, header included.
size_t feed_as_(pos_t pos, uint8_t c)
bool ESPHOME_FRAME_READER_COLD drain_(size_t len, F &handle)
void ESPHOME_FRAME_READER_COLD flush_(F &handle)
size_t length() const
Number of bytes of the partial frame; 0 after a frame is returned and while looking for a header.
size_t ESPHOME_FRAME_READER_COLD replay_(size_t from, size_t to)
void flush(F &&handle)
For a partial frame idle too long: hands over the frames a corrupt length holds back inside it,...
size_t ESPHOME_FRAME_READER_COLD feed_edge_(uint8_t c)
bool receiving() const
Whether a frame is coming in: a partial frame that an idle flush has not searched and kept.
constexpr uint8_t header_byte(size_t i)
constexpr size_t FIXED_LENGTH
const void size_t len
Definition hal.h:68
size_t size_t pos
Definition helpers.h:1530
FrameFormat option: CHECK(frame) runs once the first BYTES bytes are in; a frame it fails is not a fr...
static bool check(const uint8_t *buf)
static constexpr size_t CHECK_AT
A frame type that always has LEN bytes.
static constexpr size_t get(const uint8_t *)
static constexpr size_t KNOWN_AT
One frame type for LengthFrameReader: a FrameHeader, a length rule from above, then any of the option...
static constexpr size_t HEADER_LEN
static constexpr size_t WARN_MAX
static constexpr uint8_t header_byte(size_t i)
static constexpr size_t FIXED_LENGTH
static constexpr size_t MIN_LEN
static constexpr size_t SHORTEST
static constexpr uint8_t FIRST
The bytes every frame of a FrameFormat starts with.
static constexpr size_t LEN
static constexpr uint8_t byte(size_t i)
static constexpr size_t KNOWN_AT
static constexpr size_t get(const uint8_t *buf)
static constexpr size_t KNOWN_AT
static constexpr size_t get(const uint8_t *buf)
Whole-frame length: the field counts every byte of the frame, header included.
static constexpr size_t KNOWN_AT
static constexpr size_t get(const uint8_t *buf)
FrameFormat option: the shortest frame, when that is more than its header and length field.
static constexpr size_t MIN
Base of the FrameFormat options; each option overrides only its own members.
static constexpr bool check(const uint8_t *)
static constexpr size_t WARN_MAX
static constexpr size_t MIN
static constexpr bool fits(size_t)
static constexpr size_t CHECK_AT
offset: where the length field starts, counted from the first header byte.
FrameFormat option: a frame longer than MAX calls WARN(length) and is skipped; a replay can warn agai...
static constexpr size_t WARN_MAX
static bool fits(size_t len)
static size_t get(const uint8_t *buf)
static constexpr size_t get(const uint8_t *buf)
uint8_t end[39]
Definition sun_gtil2.cpp:17