ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
uart_binary_sensor.cpp
Go to the documentation of this file.
2#include "esphome/core/hal.h"
3#include "esphome/core/log.h"
4
5namespace esphome::uart {
6
7ESPHOME_LOG_TAG(TAG, "uart.binary_sensor");
8
10 ESP_LOGCONFIG(TAG, "UART Binary Sensor:");
11 for (const auto &matcher : this->matchers_) {
12 LOG_BINARY_SENSOR(" ", "Pattern", matcher.sensor);
13 }
14}
15
17 this->read_available([this](uint8_t byte) {
18 this->buffer_.push_overwrite(byte);
19 for (const auto &matcher : this->matchers_) {
20 // The byte just read has to be the pattern's last one before the rest is compared
21 if (progmem_read_byte(&matcher.data[matcher.data_len - 1]) != byte || !this->matches_(matcher)) {
22 continue;
23 }
24 // A momentary press, as the remote receiver binary sensors publish theirs
25 matcher.sensor->publish_state(true);
26 matcher.sensor->publish_state(false);
27 this->buffer_.clear();
28 break;
29 }
30 });
31}
32
33// Whether the pattern, apart from its last byte, ends the buffer
34bool UARTBinarySensorHub::matches_(const EventMatcher &matcher) const {
35 if (this->buffer_.size() < matcher.data_len) {
36 return false;
37 }
38 const size_t start = this->buffer_.size() - matcher.data_len;
39 for (size_t i = 0; i + 1 < matcher.data_len; i++) {
40 if (this->buffer_[start + i] != progmem_read_byte(&matcher.data[i])) {
41 return false;
42 }
43 }
44 return true;
45}
46
47} // namespace esphome::uart
void push_overwrite(const T &value)
Push a value, overwriting the oldest if full.
Definition helpers.h:541
void clear()
Clear all elements (reset to empty, keep capacity)
Definition helpers.h:568
index_type size() const
Definition helpers.h:562
bool matches_(const EventMatcher &matcher) const
StaticVector< EventMatcher, UART_BINARY_SENSOR_COUNT > matchers_
FixedRingBuffer< uint8_t, 255 > buffer_
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
ESPHOME_LOG_TAG(TAG, "uart.binary_sensor")
uint8_t progmem_read_byte(const uint8_t *addr)
Definition hal.h:51