ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
frame_reader.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <type_traits>
6
7namespace esphome {
8
11template<size_t N, uint8_t... HEADER> class FrameReader {
12 using pos_t = std::conditional_t<(N <= 0xFF), uint8_t, uint16_t>;
13 static constexpr size_t HEADER_LEN = sizeof...(HEADER);
14 static_assert(HEADER_LEN >= 1 && HEADER_LEN <= 8, "FrameReader takes 1 to 8 header bytes"); // bounds replay_() depth
15 static_assert(HEADER_LEN < N && N <= 0xFFFF, "FrameReader size out of range");
16
17 public:
19 const uint8_t *feed(uint8_t c) {
20 pos_t pos = this->pos_;
21 if (pos < HEADER_LEN && c != header_byte(pos)) {
22 // A later byte of the broken header, or c, may start the real one
23 this->buf_[pos] = c;
24 this->replay_(pos);
25 return nullptr;
26 }
27 this->buf_[pos++] = c;
28 if (pos < N) {
29 this->pos_ = pos;
30 return nullptr;
31 }
32 this->pos_ = 0;
33 return this->buf_;
34 }
35
37 size_t length() const { return this->pos_; }
38
40 void reset() { this->pos_ = 0; }
41
44 void resync() { this->replay_(N - 1); }
45
46 protected:
47 // A fold, not an array, so no header table lands in RAM on ESP8266
48 static constexpr uint8_t header_byte(size_t i) {
49 size_t j = 0;
50 uint8_t r = 0;
51 ((r = (j++ == i) ? HEADER : r), ...);
52 return r;
53 }
54
55 // Start over and feed buf_[1..last] again; never completes a frame as last < N
56 void replay_(size_t last) {
57 this->pos_ = 0;
58 for (size_t i = 1; i <= last; i++) {
59 this->feed(this->buf_[i]);
60 }
61 }
62
63 uint8_t buf_[N];
64 pos_t pos_{0};
65};
66
67} // namespace esphome
Collects fixed length binary frames of N bytes that start with the header bytes HEADER....
static constexpr uint8_t header_byte(size_t i)
size_t length() const
Number of bytes of the partial frame; 0 after a frame is returned and while looking for a header.
void replay_(size_t last)
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...
void reset()
Forget the partial frame and look for a header from the next byte.
size_t size_t pos
Definition helpers.h:1333