ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ld600x_frame.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5
7
8namespace esphome::ld600x {
9
10static constexpr uint8_t TF_SOF = 0x01;
11// ID, payload length and type, excluding SOF and the header checksum.
12static constexpr uint8_t TF_HEADER_LEN = 6;
13// SOF, header, header checksum and data checksum around a payload.
14static constexpr uint8_t TF_FRAME_OVERHEAD = TF_HEADER_LEN + 3;
15// SOF, header and header checksum come before the payload.
16static constexpr uint8_t TF_PAYLOAD_OFFSET = TF_HEADER_LEN + 2;
17
18inline float read_f32_le(const uint8_t *data) { return bit_cast<float>(encode_value_le<uint32_t>(data)); }
19
20inline void write_f32_le(uint8_t *data, float value) { put_le32(data, bit_cast<uint32_t>(value)); }
21
22class FrameParser final {
23 public:
24 // The caller owns the buffer; payloads longer than capacity are skipped.
25 void init(uint8_t *buffer, uint16_t capacity);
26 bool feed(uint8_t byte);
27 uint16_t type() const { return this->frame_type_; }
28 uint16_t id() const { return this->frame_id_; }
29 uint16_t length() const { return this->data_len_; }
30 const uint8_t *data() const { return this->data_len_ == 0 ? nullptr : this->data_buf_; }
31 uint16_t capacity() const { return this->max_data_len_; }
33
34 protected:
43
44 void start_header_();
45
46 uint8_t *data_buf_{nullptr};
47 uint16_t data_len_{0};
48 uint16_t frame_type_{0};
49 uint16_t frame_id_{0};
50 // Header or payload write position, or the payload bytes left to discard.
51 uint16_t pos_{0};
52 uint16_t max_data_len_{0};
54 uint8_t xor_{0};
55};
56
57// Frames this side sends have the top id bit set; the low 15 bits count up.
58inline uint16_t next_frame_id(uint16_t &counter) { return (counter++ & 0x7FFF) | 0x8000; }
59
60// Out must hold TF_FRAME_OVERHEAD + len bytes. Empty payloads have no data checksum.
61size_t encode_frame(uint16_t frame_id, uint16_t type, const uint8_t *data, uint16_t len, uint8_t *out);
62
63} // namespace esphome::ld600x
const uint8_t * data() const
void init(uint8_t *buffer, uint16_t capacity)
uint8_t type
std::vector< uint8_t > & out
Definition gif.cpp:49
uint32_t buffer
Definition gif.cpp:50
uint16_t next_frame_id(uint16_t &counter)
void write_f32_le(uint8_t *data, float value)
float read_f32_le(const uint8_t *data)
size_t encode_frame(uint16_t frame_id, uint16_t type, const uint8_t *data, uint16_t len, uint8_t *out)
uint32_t value
Definition hal.cpp:41
const void size_t len
Definition hal.h:68
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
Definition helpers.h:1084
constexpr uint8_t * put_le32(uint8_t *dst, uint32_t value)
Definition helpers.h:1135
To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:85