14constexpr uint8_t
TAB = 0x9;
22static size_t get_field(
char *dest,
const uint8_t *buf_start,
const uint8_t *buf_end,
size_t max_len) {
23 const auto *
const field_end =
static_cast<const uint8_t *
>(memchr(buf_start,
TAB, buf_end - buf_start));
26 const size_t len = field_end - buf_start;
28 ESP_LOGE(TAG,
"Field too long: %zu bytes (max %zu)",
len, max_len);
32 memcpy(dest, buf_start,
len);
44 const auto grp_len = grp_end - grp;
46 ESP_LOGE(TAG,
"Empty or too short group");
49 const auto raw_crc = grp[grp_len - 1];
53 if (raw_crc != calculated_crc) {
54 ESP_LOGE(TAG,
"CRC mismatch: expected %d, got %d", calculated_crc, raw_crc);
65 size_t field_len = get_field(this->
tag_, grp, grp_end, MAX_TAG_SIZE);
66 if (!field_len || field_len >= MAX_TAG_SIZE) {
67 ESP_LOGE(TAG,
"Invalid tag");
70 const auto *val_start = grp + field_len + 1;
72 field_len = get_field(this->
val_, val_start, grp_end, MAX_VAL_SIZE);
73 if (!field_len || field_len >= MAX_VAL_SIZE) {
74 ESP_LOGE(TAG,
"Invalid value for tag %s", this->
tag_);
94 ESP_LOGW(TAG,
"Internal buffer full");
108 ESP_LOGVV(TAG,
"State: WAITING_FOR_START");
113 ESP_LOGVV(TAG,
"State: START_FRAME_RECEIVED");
118 ESP_LOGVV(TAG,
"State: END_FRAME_RECEIVED -> processing");
125 auto *buf_finger = this->
buf_;
130 while ((buf_finger =
static_cast<uint8_t *
>(memchr(buf_finger,
LINE_FEED, buf_end - buf_finger))) !=
nullptr) {
133 auto *
const grp_end =
static_cast<uint8_t *
>(memchr(buf_finger,
CARRIAGE_RETURN, buf_end - buf_finger));
135 ESP_LOGE(TAG,
"No group found");
141 buf_finger = grp_end;
143 this->buf_index_ = 0;
151#ifdef MK2PVROUTER_LISTENER_COUNT
153 if (strcmp(tag, element->get_tag()) != 0)
155 element->publish_val(
val);
162#ifdef MK2PVROUTER_LISTENER_COUNT
bool check_crc_(const uint8_t *grp, const uint8_t *grp_end)
static constexpr size_t CRC_SUFFIX_LEN
void process_group_(const uint8_t *grp, const uint8_t *grp_end)
void publish_value_(const char *tag, const char *val)
bool read_chars_until_(bool drop, uint8_t c)
void register_mk2pvrouter_listener(Mk2PVRouterListener *listener)
void dump_config() override
StaticVector< Mk2PVRouterListener *, MK2PVROUTER_LISTENER_COUNT > mk2pvrouter_listeners_
uint8_t calculate_crc_(const uint8_t *grp, size_t grp_len)
uint8_t buf_[MAX_BUF_SIZE]
bool read_byte(uint8_t *data)
constexpr uint8_t MAX_ITERATIONS
ESPHOME_LOG_TAG(TAG, "mk2pvrouter_binary_sensor")
constexpr uint8_t CARRIAGE_RETURN
constexpr uint8_t START_FRAME
constexpr uint8_t CRC_OFFSET
constexpr uint8_t LINE_FEED
constexpr uint8_t END_FRAME
constexpr uint8_t CRC_MASK
constexpr uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t sum=0)
Add up the bytes of data with size len, truncated to 8 bits: the checksum many serial and IR protocol...