ESPHome 2026.10.0-dev
Loading...
Searching...
No Matches
ds1603l.cpp
Go to the documentation of this file.
1#include "ds1603l.h"
2
3#include <cstring>
4
6#include "esphome/core/log.h"
7
8namespace esphome::ds1603l {
9
10static const char *const TAG = "ds1603l.sensor";
11
13 // Assemble frames one byte at a time so a stream that starts mid-frame can realign
14 uint8_t byte;
15 while (this->available() > 0 && this->read_byte(&byte)) {
16 if (this->rx_count_ == 0 && byte != HEADER_BYTE) {
17 ESP_LOGV(TAG, "Skipping byte 0x%02X while looking for header", byte);
18 continue;
19 }
20
21 this->rx_buffer_[this->rx_count_++] = byte;
22 if (this->rx_count_ < FRAME_SIZE) {
23 continue;
24 }
25
26 if (this->parse_data_()) {
27 this->rx_count_ = 0;
28 } else {
29 // The header byte was part of the payload of a misaligned frame, so realign instead of dropping everything
30 this->resync_();
31 }
32 }
33}
34
35void DS1603L::dump_config() { LOG_SENSOR("", "DS1603L", this); }
36
38 uint8_t header = this->rx_buffer_[0];
39 uint8_t data_h = this->rx_buffer_[1];
40 uint8_t data_l = this->rx_buffer_[2];
41 uint8_t checksum = this->rx_buffer_[3];
42
43 uint8_t computed_checksum = (header + data_h + data_l) & 0xFF;
44
45 ESP_LOGV(TAG, "Data: Header=0x%02X, Data_H=0x%02X, Data_L=0x%02X, Checksum=0x%02X", header, data_h, data_l, checksum);
46
47 if (checksum != computed_checksum) {
48 ESP_LOGW(TAG, "Checksum mismatch: received 0x%02X, expected 0x%02X", checksum, computed_checksum);
49 return false;
50 }
51
52 this->publish_state(encode_uint16(data_h, data_l));
53 return true;
54}
55
57 // Drop the byte that was treated as the header, then look for the next candidate header in what is left
58 size_t start = 1;
59 while (start < this->rx_count_ && this->rx_buffer_[start] != HEADER_BYTE) {
60 start++;
61 }
62 this->rx_count_ -= start;
63 if (this->rx_count_ > 0) {
64 memmove(this->rx_buffer_, this->rx_buffer_ + start, this->rx_count_);
65 }
66}
67
68} // namespace esphome::ds1603l
uint8_t checksum
Definition bl0906.h:3
void dump_config() override
Definition ds1603l.cpp:35
void loop() override
Definition ds1603l.cpp:12
uint8_t rx_buffer_[FRAME_SIZE]
Definition ds1603l.h:26
static constexpr uint8_t HEADER_BYTE
Definition ds1603l.h:18
static constexpr size_t FRAME_SIZE
Definition ds1603l.h:19
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
bool read_byte(uint8_t *data)
Definition uart.h:35
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:884