Compare commits

..
197 changed files with 3919 additions and 8643 deletions

No files matched your search

+1 -49
View File
@@ -20,9 +20,6 @@ flagging in a review; read the matching skill for the detail behind any item.
Only raise findings that the diff actually introduces or changes. Do not ask for
drive-by cleanup of pre-existing code the PR did not touch.
For error paths that fail without telling the user (early returns, swallowed
errors, ignored results), the `silent-failure-review` skill has its own checklist.
## Scope: shared code does not ride a component PR
Check the file list first. A PR titled for one component (`[ld2450] ...`) must
@@ -120,7 +117,7 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
| hand-written `set_x_sensor()` plus `x_sensor_` member | `SUB_SENSOR(x)`, `SUB_BINARY_SENSOR`, `SUB_TEXT_SENSOR`, `SUB_SWITCH`, ... |
| `if CONF_X in config: s = await sensor.new_sensor(config[CONF_X])` plus setter | `sensors = sensor.sub_sensors(config)` then `await sensors(CONF_X, hub.set_x_sensor)` |
| hand-written `{"a": MyEnum.MY_ENUM_A, ...}` dict | `MyEnum.options("a", "b", prefix="MY_ENUM_")` |
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>`, `LengthFrameReader<N, FrameFormat<...>...>` |
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>` |
| hand-rolled CRC, checksum or bit loop | `crc8`, `crc16`, `xor_bytes`, `sum16_bytes`, `encode_uint16`, ... (`esphome/core/helpers.h`) |
| integer split into buffer bytes by hand (`buf[0] = v >> 8; buf[1] = v;`) | `put_be16`/`24`/`32`, `put_le16`, `put_le32` (`esphome/core/helpers.h`) |
| bare `mark_failed()`, or `ESP_LOGE` then `mark_failed()` | `this->mark_failed(LOG_STR("reason"))` or `LOG_STR(ESP_LOG_MSG_COMM_FAIL)` |
@@ -128,51 +125,6 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
| action or condition class that only forwards to the parent | `register_apply_action` / `register_apply_condition` |
| enum-to-string `switch` returning literals | `PROGMEM_STRING_TABLE` with `get_log_str` / `get_progmem_str` |
| `if (x := config.get(CONF_X)) is not None: cg.add(var.set_x(x))` | `cg.add_optional(var.set_x, config.get(CONF_X))`, when the setter takes the value unchanged |
| `x = (x & ~mask) \| (on ? mask : 0)` or a bit-reversal loop | `assign_bits(x, mask, on)`, `reverse_bits(x)` (`esphome/core/helpers.h`) |
| `x < lo ? lo : (x > hi ? hi : x)` | `std::clamp(x, lo, hi)` |
| I2C read, mask, write by hand; private 16-bit register byte helpers | `update_register`, `update_register16`, `read_byte_reg16`, `write_byte_reg16` |
| custom validator that checks which keys are set, or one schema with model checks | `cv.has_exactly_one_key`, `cv.has_at_most_one_key`, `cv.Inclusive`/`cv.Exclusive`, `cv.typed_schema` per model |
## Cleanups automated reviews keep missing
Multi-pass cleanup reviews of contributor PRs find these again and again, and single-pass reviews
almost never flag them. Look for each one explicitly; the matching `AGENTS.md` section 4 entry has the
detail.
- **Copies within the PR** (the most common finding): two functions, branches, platform files or tests
that differ in a constant or two. Ask for one helper, loop or table.
- **State that copies other state:** a `write_pending_` bool beside a timer (use the return value of
`cancel_timeout(ID)`), a `has_x_` bool beside `x_` (use `NAN` or a sentinel), an enum that can be worked
out from stored fields.
- **Dead guards:** null checks on members codegen always sets, `is_failed()` checks in `loop()`, range
checks the schema already enforces, `default:` in a `switch` over every value of an `enum class` the
component sets itself (not one cast from bus data), calls that set a member to its default
(`set_cs_pin(nullptr)`).
- **Member layout:** field order that leaves padding, `int`/`uint32_t` for values that fit a `uint8_t`,
an `enum class` without `: uint8_t`, several `bool` members that could share a byte. Each costs RAM per
instance.
- **C++ work that belongs in codegen:** scaling, clamping, checksums or register bytes computed at boot
from config values; ask for the plain value from `to_code`.
- **Two `switch` ladders for one mapping:** encode and decode of the same value pairs should share one
`static constexpr` table (`PROGMEM` on ESP8266).
- **Compile-time constants:** `static const` or `#define` with a constant value (use `static constexpr`),
constant tables not in `PROGMEM`, unused constants.
- **Code for one model or feature compiled into every build:** ask for a `cg.add_define()` emitted only
when the config uses it, with the runtime check inside the `#ifdef`.
- **Failure handling:** `mark_failed()` outside `setup()` (runtime failures set a warning that the next
success clears), an error enum that only picks a log message.
- **Logging** that does not follow https://developers.esphome.io/architecture/logging/: `ESP_LOGD` on every
reading, "Setting up" or "initialized" lines in `setup()`, a `dump_config()` made of single-line
`ESP_LOGCONFIG` calls where related lines fit one call, a name helper that returns `const char *` instead
of `const LogString *`.
- **Leaf classes** that are not `final`.
- **Unused helpers, includes and imports** left behind; lint does not catch most of them.
- **Comments that restate the code** or tell its history: a block comment that walks through the next
ten lines, a docstring that repeats the signature, a derivation that a one-line note plus a datasheet
section would cover.
- **Tests:** near-identical test functions that differ only in inputs (ask for `pytest.mark.parametrize`
or a table-driven gtest), tests that repeat another test, test YAML that sets options to their defaults.
## Python conventions
@@ -1,71 +0,0 @@
---
name: silent-failure-review
description: Find code paths in a branch's diff that fail without telling the user - early returns, swallowed errors, ignored return values, half-done cleanup, and checks that are only safe under an unstated assumption. Use when asked for a silent failure review or before pushing a PR for review.
---
# Silent failure review
Report only. Do not edit files.
## Scope
The diff of the checked-out branch against its base. Fetch the base first (`git fetch upstream dev`, or
`git fetch origin dev` when there is no `upstream` remote); a stale base pulls in commits the branch only merged.
Then run `git merge-base upstream/dev HEAD` (or `origin/dev`) on its own. If it fails or prints nothing (often a
shallow clone; `git fetch --unshallow` fixes that), say the review could not run and stop; never report "no
findings" then. Diff against that commit with `git diff <base>`. The diff includes uncommitted changes but not
untracked files, so also read in full every file `git status --porcelain --untracked-files=all` lists as `??`.
Use another branch only if the user names one. If neither remote exists, say so and stop. Read each changed
function in full, and its callers, not just the hunks. When a failure depends on how a library call behaves,
read that library's code too.
## What to look for
1. **Early returns and skips:** a `return` or `continue` taken before a check or a fetch. Name the assumption
it relies on and the case that breaks it (a later release, a lost file, an older install).
2. **Swallowed errors:** `except` that logs, passes or returns a default; `OSError` tolerated where the next
step needs the file. In C++: an error code mapped to a default, or a status flag that is never set.
3. **Ignored results:** a `False`, `None`, exit code, `bool` or `ErrorCode` that the caller does not check.
4. **Half-done state:** a failure between two writes that leaves a marker, stamp, lock or filter saying
something is done when it is not; cleanup missing on an error path.
5. **Stale stored state:** markers, stamps or saved preferences (NVS, flash) written by an older version that
the new code trusts.
6. **Unclear late failure:** an error that surfaces later (CMake, compile, boot) instead of where it starts,
with a message that does not point back to the cause.
7. **Defaults standing in for errors:** `x or default`, `.get(key, default)` or an empty object takes the
place of a value that is missing or could not be read, and the code carries on as if it were real.
8. **Unwatched work:** a thread, task or subprocess is started and nothing ever looks at how it ended.
9. **Wrong value on an error branch:** the error is detected, but the branch returns success, `None` or the
wrong code instead of passing it on.
10. **State reset or skipped:** for each counter, flag, retry or timeout the diff adds or changes, find every
place that writes it, and check that no path resets or skips it before it can do its job.
11. **Boundaries:** length and buffer comparisons (`>=` against `>`, `len` against `len + 1`), the exact-fit
case and the empty case.
12. **Unjudged results:** a test or script that prints a result but never fails on it.
Moved code counts too: if the original had the same flaw, say so, but still report it. Report only flaws in
changed or moved lines; unchanged callers are context. If the branch has an open PR (`gh pr view --json number`
finds it), read its reviews (`gh pr view <n> --comments` and
`gh api --paginate repos/esphome/esphome/pulls/<n>/comments`) and skip what they already raised.
Before reporting a candidate, follow it to the line that proves it and quote that line. If you cannot
confirm it, drop it or mark it as likely.
## Skip
- Code that ignores a failure and has a comment explaining why.
- Tests that provoke an error and check for it.
- Optional tidy-up steps (removing a temp file, say) that may fail with only a log line.
## Report
One entry per finding, most severe first:
- **HIGH / MEDIUM / LOW** - one-line title, `file:line`. HIGH: wrong result or lost data. MEDIUM: a
misleading or delayed failure. LOW: affects only logs or diagnostics.
- **Confidence:** confirmed, or likely and why it could not be confirmed.
- **Risk:** the concrete input or state, and what the user sees.
- **Fix:** the smallest change.
- **Test:** the test that fails before the fix, or for on-device code, the steps to reproduce it on a board.
No findings: say so in one line. Keep the report short; no summary of what the PR does.
+2 -29
View File
@@ -66,8 +66,6 @@ file does, and it is the authority when they disagree. The most useful starting
* `breaking-changes`: what is public API, deprecation patterns and migration notes.
* `pr-workflow`, `code-review`, `hardware-test`, `display-test`: creating PRs, reviewing them, and testing
on real boards and panels.
* `silent-failure-review`: code paths in a branch's diff that fail without telling the user, checked
before a PR goes up for review.
* **Formatting:**
* **Python:** Uses `ruff` for linting and formatting. Configuration is in `pyproject.toml`.
@@ -246,10 +244,7 @@ file does, and it is the authority when they disagree. The most useful starting
`time::decode_bcd_calendar<LAYOUT>` and `encode_bcd_calendar<LAYOUT>` with `EPSON_BCD_CALENDAR`,
`DS_BCD_CALENDAR` or `PCF_BCD_CALENDAR`.
* **Bus helpers:** UART drains with `read_available(on_byte)` and `discard_available()`, text lines with
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`, frames that give their own length
with `LengthFrameReader<N, FrameFormat<FrameHeader<...>, PayloadLengthU16LE<LengthField{...}>>...>` fed by
`read_frames(reader, handler, now, last_rx)`, which frees frames a bad length holds; I2C has `update_register`,
`update_register16`, `read_byte_reg16` and `write_byte_reg16` for 16-bit register addresses,
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`; I2C has `update_register`,
`write_registers` (PROGMEM `I2CRegValue` table), `check_chip_id` and `read_bytes_16_le`.
`if (!this->status_comm_result(ok)) return;` sets or clears the warning; an earlier step of a multi-step
poll uses `status_comm_check(ok)`, which only sets it, so the last step must clear it; in `setup()`,
@@ -314,27 +309,6 @@ file does, and it is the authority when they disagree. The most useful starting
text::Text *source_{nullptr};
};
```
* **No state that copies other state:** a flag that mirrors a timer, a `has_x_` bool beside `x_`, or an enum
that can be worked out from fields already stored is a second source of truth. Use the source:
`pending = this->cancel_timeout(ID)`, an unset value of `NAN` or an out-of-range sentinel.
* **No dead guards:** do not check what the caller or core already guarantees: a member that codegen always
sets, `is_failed()` in `loop()` (core stops calling it), a value the config validation already limits, a
`default:` in a `switch` over every value of an `enum class` the component sets itself (keep it when the
value is cast from bus data).
* **Member layout:** order fields so the compiler adds no padding (usually largest first), store small codes
as `uint8_t`, declare `enum class X : uint8_t`, and pack flags into one byte.
* **Work out constants in Python:** math that only depends on the configuration (register bytes, scale
factors, thresholds, checksums) is done in `to_code` and passed as a plain value, not done in C++ at
boot.
* **One table for both directions:** a value that is encoded and decoded through the same mapping uses one
`static constexpr` (`PROGMEM` on ESP8266) table of `{value, code}` pairs, not two `switch` ladders.
* **Logging:** follow https://developers.esphome.io/architecture/logging/ for log levels and `dump_config()`.
In short: a reading is logged with `ESP_LOGV`, not `ESP_LOGD` on every update; `setup()` logs no
"Setting up" or "initialized" line (core logs setup); `dump_config()` combines related lines into one
`ESP_LOGCONFIG` call, within the 512-byte log buffer.
* **Leaf classes are `final`:** a component or entity class nothing derives from is declared `final`.
* **No copies within the PR:** two functions, branches or platform files that differ in a constant or two
become one helper, loop or table; helpers, includes and imports nothing uses are deleted.
* **Component Code Generation:** every component's `__init__.py` defines `DOMAIN` (its own name, checked by
CI). Hub entities go in platform files (`sensor.py`, ...) that take the hub's id, not under the hub's own
@@ -381,8 +355,7 @@ file does, and it is the authority when they disagree. The most useful starting
`script/test_build_components -c <component>`. Never define buses directly in test YAML: include the
shared packages from `tests/test_build_components/common/` with dict-style `packages:`. Test file naming,
`validate.*.yaml` config-only tests, CI grouping, C++ unit tests and integration tests are in the
`component-tests` skill. Tests that differ only in their inputs are one `pytest.mark.parametrize` test
or a table-driven gtest.
`component-tests` skill.
* **Debugging and Troubleshooting:**
* **Debug Tools:**
-4
View File
@@ -489,12 +489,10 @@ esphome/components/pca9505/* @ajfriesen @ssieb
esphome/components/pca9554/* @bdraco @clydebarrow @hwstar
esphome/components/pcf85063/* @brogon
esphome/components/pcf8563/* @KoenBreeman
esphome/components/pcm1863/* @anabolyc
esphome/components/pcm5122/* @remcom
esphome/components/pd_pioneer_ir/* @martinsah
esphome/components/pi4ioe5v6408/* @jesserockz
esphome/components/pid/* @OttoWinter
esphome/components/pioneer_wt/* @martinsah
esphome/components/pipsolar/* @andreashergert1984
esphome/components/pixoo/* @jesserockz
esphome/components/pm1006/* @habbie
@@ -701,7 +699,6 @@ esphome/components/toshiba/* @kbx81
esphome/components/touchscreen/* @jesserockz @nielsnl68
esphome/components/tsl2591/* @wjcarpenter
esphome/components/tt21100/* @kroimon
esphome/components/tuya/* @dwmw2 @ssieb
esphome/components/tuya/binary_sensor/* @jesserockz
esphome/components/tuya/climate/* @jesserockz
esphome/components/tuya/number/* @frankiboy1
@@ -738,7 +735,6 @@ esphome/components/veml7700/* @latonita
esphome/components/version/* @esphome/core
esphome/components/vevor_dtx/* @Bofr5555
esphome/components/vl53l1x/* @will-tm
esphome/components/vl6180x/* @NonaSuomy
esphome/components/vnc/* @MindFreeze
esphome/components/voice_assistant/* @jesserockz @kahrendt
esphome/components/wake_on_lan/* @clydebarrow @willwill2will54
@@ -2,6 +2,7 @@
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iterator>
#include "esphome/core/application.h"
@@ -13,6 +14,13 @@ namespace esphome::airton_serial {
ESPHOME_LOG_TAG(TAG, "airton_serial.climate");
static constexpr uint8_t SYNC_BYTE = 0x7A;
static constexpr uint8_t LENGTH_POS = 4;
static constexpr uint8_t OPCODE_POS = 7;
static constexpr uint8_t MIN_FRAME_LEN = OPCODE_POS + 1 + 2; // Up to the opcode, then the CRC
// A partial frame left this long without a new byte is not a frame start.
static constexpr uint32_t FRAME_GAP_MS = 50;
static constexpr uint8_t ADDR_MODULE = 0x21;
static constexpr uint8_t ADDR_DISPLAY = 0xD1;
static constexpr uint8_t ADDR_BOARD = 0xD5;
@@ -113,15 +121,58 @@ void AirtonSerialClimate::setup() {
void AirtonSerialClimate::loop() {
const uint32_t now = App.get_loop_component_start_time();
auto accept = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames(this->reader_, accept, now, this->last_rx_ms_);
bool received = false;
this->read_available([this, &received](uint8_t byte) {
received = true;
this->handle_byte_(byte);
});
if (received) {
this->last_rx_ms_ = now;
} else if (this->rx_pos_ > 0 && now - this->last_rx_ms_ >= FRAME_GAP_MS) {
// A corrupt length can hold back complete frames behind it; look for them in what is buffered.
while (this->rx_pos_ > 0)
this->drop_first_byte_();
}
}
bool AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t len) {
if (crc16(data, len - 2) != encode_uint16(data[len - 2], data[len - 1])) {
ESP_LOGW(TAG, "Bad CRC on %u-byte frame", static_cast<unsigned>(len));
return false;
void AirtonSerialClimate::handle_byte_(uint8_t byte) {
// Bytes are checked as they arrive, so rx_pos_ stays below the longest frame length.
this->rx_buffer_[this->rx_pos_++] = byte;
this->scan_buffer_();
}
void AirtonSerialClimate::drop_first_byte_() {
this->rx_pos_--;
std::memmove(this->rx_buffer_.data(), this->rx_buffer_.data() + 1, this->rx_pos_);
this->scan_buffer_();
}
void AirtonSerialClimate::scan_buffer_() {
const uint8_t *buf = this->rx_buffer_.data();
while (this->rx_pos_ > 0) {
uint8_t drop = 1;
if (buf[0] == SYNC_BYTE && (this->rx_pos_ < 2 || buf[1] == SYNC_BYTE)) {
if (this->rx_pos_ <= LENGTH_POS)
return;
const uint8_t len = buf[LENGTH_POS];
if (len >= MIN_FRAME_LEN && len <= MAX_FRAME_LEN) {
if (this->rx_pos_ < len)
return;
if (crc16(buf, len - 2) == encode_uint16(buf[len - 2], buf[len - 1])) {
this->handle_frame_(buf, len);
drop = len;
} else {
ESP_LOGW(TAG, "Bad CRC on %u-byte frame", len);
}
}
}
// Not a frame start, or a bad frame: look for the next start after its first byte.
this->rx_pos_ -= drop;
std::memmove(this->rx_buffer_.data(), buf + drop, this->rx_pos_);
}
}
void AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t len) {
const uint8_t opcode = data[OPCODE_POS];
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
if (opcode == OP_A3_STATE || opcode == OP_AC_POLL) {
@@ -130,7 +181,7 @@ bool AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t len) {
}
#endif
if (data[3] != ADDR_MODULE)
return true;
return;
if (data[2] == ADDR_BOARD) {
if (len == 34 && opcode == OP_A3_STATE) {
this->handle_a3_(data);
@@ -140,7 +191,6 @@ bool AirtonSerialClimate::handle_frame_(const uint8_t *data, size_t len) {
} else if (data[2] == ADDR_DISPLAY && len == 13 && opcode == OP_A4_ACK) {
ESP_LOGD(TAG, "A4 acknowledgement from display");
}
return true;
}
void AirtonSerialClimate::handle_a3_(const uint8_t *data) {
@@ -319,14 +369,11 @@ void AirtonSerialClimate::send_a5_() {
void AirtonSerialClimate::send_ab_() {
uint8_t frame[sizeof(AB_FRAME)];
progmem_memcpy(frame, AB_FRAME, sizeof(AB_FRAME));
this->reader_.drop_kept();
this->write_array(frame, sizeof(frame));
}
void AirtonSerialClimate::write_frame_(uint8_t *frame, size_t len) {
put_be16(frame + len - 2, crc16(frame, len - 2));
// Kept bytes of an earlier frame must not merge into the reply
this->reader_.drop_kept();
this->write_array(frame, len);
}
@@ -1,12 +1,12 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include "esphome/components/climate/climate.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/component.h"
#include "esphome/core/frame_reader.h"
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor_with_dedup.h"
@@ -24,9 +24,6 @@ static constexpr uint8_t FLAG_HEALTH = 0x10;
static constexpr uint8_t FLAG_SLEEP = 0x02;
static constexpr uint8_t FLAG_ECO = 0x01;
static constexpr uint8_t SYNC_BYTE = 0x7A;
static constexpr uint8_t LENGTH_POS = 4;
static constexpr uint8_t OPCODE_POS = 7;
static constexpr uint8_t MAX_FRAME_LEN = 64;
/// Climate on the Airton serial bus. The ESP takes the place of the original Wi-Fi module (address 0x21):
@@ -64,17 +61,16 @@ class AirtonSerialClimate final : public uart::UARTDevice, public climate::Clima
bool can_send_command_();
void send_command_();
void write_frame_(uint8_t *frame, size_t len);
/// Returns false for a frame that fails the CRC
bool handle_frame_(const uint8_t *data, size_t len);
void handle_byte_(uint8_t byte);
void drop_first_byte_();
void scan_buffer_();
void handle_frame_(const uint8_t *data, size_t len);
void handle_a3_(const uint8_t *data);
void handle_ac_(const uint8_t *data);
void publish_settings_();
// 7A 7A, ..., whole-frame length at 4, opcode, ..., CRC (2); the shortest runs up to the opcode
LengthFrameReader<MAX_FRAME_LEN,
FrameFormat<FrameHeader<SYNC_BYTE, SYNC_BYTE>, FrameLengthU8<LengthField{.offset = LENGTH_POS}>,
FrameMinLength<OPCODE_POS + 3>>>
reader_;
std::array<uint8_t, MAX_FRAME_LEN> rx_buffer_;
uint8_t rx_pos_{0};
uint8_t flags_{FLAG_DISPLAY};
bool state_received_{false};
uint8_t swing_{0}; // Raw swing byte
+88 -41
View File
@@ -5,7 +5,6 @@
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#include <array>
#include <cinttypes>
#include <cmath>
@@ -26,6 +25,8 @@ static constexpr uint32_t APC1_COLD_BOOT_INIT_DELAY_MS = 2000;
static constexpr uint32_t APC1_INIT_RETRY_INTERVAL_MS = 10000;
// Active mode streams a frame every second; this long without one means the sensor stopped
static constexpr uint32_t APC1_NO_DATA_TIMEOUT_MS = 15000;
// Drop a partial frame when the bytes stop mid-way
static constexpr uint32_t APC1_RX_IDLE_TIMEOUT_MS = 200;
void APC1Component::setup() {
if (this->set_pin_ != nullptr) {
@@ -98,40 +99,80 @@ void APC1Component::loop() {
}
}
auto handle = [this](const uint8_t *frame, size_t len) { return this->parse_frame_(frame, len); };
this->read_frames(this->reader_, handle, now, this->last_transmission_);
if (this->rx_index_ > 0 && now - this->last_transmission_ > APC1_RX_IDLE_TIMEOUT_MS) {
ESP_LOGV(TAG, "Timed out waiting for data, resetting buffer");
this->rx_index_ = 0;
}
this->read_available([this, now](uint8_t byte) {
this->last_transmission_ = now;
if (this->rx_index_ == 0) {
if (byte == APC1_HEADER_1) {
this->rx_buffer_[this->rx_index_++] = byte;
}
return;
}
if (this->rx_index_ == 1) {
if (byte == APC1_HEADER_2) {
this->rx_buffer_[this->rx_index_++] = byte;
} else if (byte != APC1_HEADER_1) {
this->rx_index_ = 0;
}
return;
}
this->rx_buffer_[this->rx_index_++] = byte;
if (this->rx_index_ < APC1_FRAME_HEADER_SIZE) {
return;
}
// The payload carries at least the checksum and must fit the buffer; checking it before the sum keeps a
// corrupt length from wrapping the total and walking past the buffer
const uint16_t payload_len = encode_uint16(this->rx_buffer_[2], this->rx_buffer_[3]);
if (payload_len < 2 || payload_len > this->rx_buffer_.size() - APC1_FRAME_HEADER_SIZE) {
ESP_LOGW(TAG, "Invalid frame length: %u", payload_len);
this->rx_index_ = 0;
return;
}
const uint8_t total_len = payload_len + APC1_FRAME_HEADER_SIZE;
if (this->rx_index_ == total_len) {
this->parse_frame_(total_len);
this->rx_index_ = 0;
}
});
}
bool APC1Component::parse_frame_(const uint8_t *frame, uint8_t total_len) {
uint16_t expected_checksum = encode_uint16(frame[total_len - 2], frame[total_len - 1]);
uint16_t calculated_checksum = sum16_bytes(frame, total_len - 2);
void APC1Component::parse_frame_(uint16_t total_len) {
uint16_t expected_checksum = encode_uint16(this->rx_buffer_[total_len - 2], this->rx_buffer_[total_len - 1]);
uint16_t calculated_checksum = sum16_bytes(this->rx_buffer_.data(), total_len - 2);
if (expected_checksum != calculated_checksum) {
ESP_LOGW(TAG, "APC1 checksum mismatch: calculated 0x%04X != expected 0x%04X", calculated_checksum,
expected_checksum);
return false;
return;
}
if (total_len == APC1_FRAME_SIZE_MEASUREMENT) {
this->parse_measurement_frame_(frame);
this->parse_measurement_frame_();
} else if (total_len == APC1_FRAME_SIZE_DEVICE_INFO) {
this->parse_device_info_frame_(frame);
this->parse_device_info_frame_();
} else if (total_len == APC1_FRAME_SIZE_COMMAND_RESPONSE) {
ESP_LOGD(TAG, "APC1 command response: cmd=0x%02X, data=0x%02X", frame[4], frame[5]);
ESP_LOGD(TAG, "APC1 command response: cmd=0x%02X, data=0x%02X", this->rx_buffer_[4], this->rx_buffer_[5]);
} else {
ESP_LOGD(TAG, "Received frame of unknown length %u", total_len);
}
return true;
}
// One message per error bit, bit 0 first
PROGMEM_STRING_TABLE(ErrorStrings, "Fan restart error (too many restarts)", "Fan speed low", "Photodiode fault",
"Fan stopped / startup error", "Laser fault", "VOC sensor fault", "RHT sensor fault");
void APC1Component::parse_measurement_frame_(const uint8_t *frame) {
void APC1Component::parse_measurement_frame_() {
const uint32_t now = App.get_loop_component_start_time();
this->last_valid_frame_ = now;
uint8_t error_code = frame[APC1_MEASUREMENT_OFFSET_ERROR_CODE];
uint8_t error_code = this->rx_buffer_[APC1_MEASUREMENT_OFFSET_ERROR_CODE];
if (error_code != this->last_error_code_) {
if (error_code != 0) {
for (uint8_t bit = 0; bit < ErrorStrings::COUNT; bit++) {
@@ -148,7 +189,7 @@ void APC1Component::parse_measurement_frame_(const uint8_t *frame) {
PUBLISH_STATE(this->error_code_sensor_, error_code);
}
uint8_t aqi = frame[APC1_MEASUREMENT_OFFSET_AQI];
uint8_t aqi = this->rx_buffer_[APC1_MEASUREMENT_OFFSET_AQI];
if (aqi == 0) {
if (!this->gas_warming_up_) {
this->gas_warming_up_ = true;
@@ -162,31 +203,38 @@ void APC1Component::parse_measurement_frame_(const uint8_t *frame) {
// Measurement payload data (bytes 4-57): big-endian sensor readings.
// The values below feed the debug summary, so they are always decoded; every
// other reading is only decoded when its sensor is configured.
uint16_t pm_1_0 = encode_value<uint16_t>(frame + 10);
uint16_t pm_2_5 = encode_value<uint16_t>(frame + 12);
uint16_t pm_10_0 = encode_value<uint16_t>(frame + 14);
uint16_t tvoc = encode_value<uint16_t>(frame + 28);
uint16_t eco2 = encode_value<uint16_t>(frame + 30);
float temp_comp = encode_value<int16_t>(frame + 34) / 10.0f;
float hum_comp = encode_value<uint16_t>(frame + 36) / 10.0f;
const auto u16 = [this](uint8_t offset) {
return encode_uint16(this->rx_buffer_[offset], this->rx_buffer_[offset + 1]);
};
const auto u32 = [this](uint8_t offset) {
return encode_uint32(this->rx_buffer_[offset], this->rx_buffer_[offset + 1], this->rx_buffer_[offset + 2],
this->rx_buffer_[offset + 3]);
};
uint16_t pm_1_0 = u16(10);
uint16_t pm_2_5 = u16(12);
uint16_t pm_10_0 = u16(14);
uint16_t tvoc = u16(28);
uint16_t eco2 = u16(30);
float temp_comp = static_cast<int16_t>(u16(34)) / 10.0f;
float hum_comp = u16(36) / 10.0f;
ESP_LOGD(TAG, "APC1: PM1.0: %u, PM2.5: %u, PM10: %u, TVOC: %u, eCO2: %u, AQI: %u, Temp: %.1f°C, Hum: %.1f%%", pm_1_0,
pm_2_5, pm_10_0, tvoc, eco2, aqi, temp_comp, hum_comp);
PUBLISH_STATE(this->pm_1_0_std_sensor_, encode_value<uint16_t>(frame + 4));
PUBLISH_STATE(this->pm_2_5_std_sensor_, encode_value<uint16_t>(frame + 6));
PUBLISH_STATE(this->pm_10_0_std_sensor_, encode_value<uint16_t>(frame + 8));
PUBLISH_STATE(this->pm_1_0_std_sensor_, u16(4));
PUBLISH_STATE(this->pm_2_5_std_sensor_, u16(6));
PUBLISH_STATE(this->pm_10_0_std_sensor_, u16(8));
PUBLISH_STATE(this->pm_1_0_sensor_, pm_1_0);
PUBLISH_STATE(this->pm_2_5_sensor_, pm_2_5);
PUBLISH_STATE(this->pm_10_0_sensor_, pm_10_0);
PUBLISH_STATE(this->pm_0_3um_sensor_, encode_value<uint16_t>(frame + 16));
PUBLISH_STATE(this->pm_0_5um_sensor_, encode_value<uint16_t>(frame + 18));
PUBLISH_STATE(this->pm_1_0um_sensor_, encode_value<uint16_t>(frame + 20));
PUBLISH_STATE(this->pm_2_5um_sensor_, encode_value<uint16_t>(frame + 22));
PUBLISH_STATE(this->pm_5_0um_sensor_, encode_value<uint16_t>(frame + 24));
PUBLISH_STATE(this->pm_10_0um_sensor_, encode_value<uint16_t>(frame + 26));
PUBLISH_STATE(this->pm_0_3um_sensor_, u16(16));
PUBLISH_STATE(this->pm_0_5um_sensor_, u16(18));
PUBLISH_STATE(this->pm_1_0um_sensor_, u16(20));
PUBLISH_STATE(this->pm_2_5um_sensor_, u16(22));
PUBLISH_STATE(this->pm_5_0um_sensor_, u16(24));
PUBLISH_STATE(this->pm_10_0um_sensor_, u16(26));
PUBLISH_STATE(this->tvoc_sensor_, tvoc);
PUBLISH_STATE(this->eco2_sensor_, eco2);
@@ -195,19 +243,20 @@ void APC1Component::parse_measurement_frame_(const uint8_t *frame) {
PUBLISH_STATE(this->temperature_sensor_, temp_comp);
PUBLISH_STATE(this->humidity_sensor_, hum_comp);
PUBLISH_STATE(this->raw_temperature_sensor_, encode_value<int16_t>(frame + 38) / 10.0f);
PUBLISH_STATE(this->raw_humidity_sensor_, encode_value<uint16_t>(frame + 40) / 10.0f);
PUBLISH_STATE(this->raw_temperature_sensor_, static_cast<int16_t>(u16(38)) / 10.0f);
PUBLISH_STATE(this->raw_humidity_sensor_, u16(40) / 10.0f);
PUBLISH_STATE(this->rs0_sensor_, encode_value<uint32_t>(frame + 42));
PUBLISH_STATE(this->rs2_sensor_, encode_value<uint32_t>(frame + 50));
PUBLISH_STATE(this->rs3_sensor_, encode_value<uint32_t>(frame + 54));
PUBLISH_STATE(this->rs0_sensor_, u32(42));
PUBLISH_STATE(this->rs2_sensor_, u32(50));
PUBLISH_STATE(this->rs3_sensor_, u32(54));
}
void APC1Component::parse_device_info_frame_(const uint8_t *frame) {
const uint8_t *serial = frame + APC1_DEVICE_INFO_OFFSET_SERIAL;
uint16_t fw_version = encode_uint16(frame[APC1_DEVICE_INFO_OFFSET_FW], frame[APC1_DEVICE_INFO_OFFSET_FW + 1]);
void APC1Component::parse_device_info_frame_() {
const uint8_t *serial = this->rx_buffer_.data() + APC1_DEVICE_INFO_OFFSET_SERIAL;
uint16_t fw_version =
encode_uint16(this->rx_buffer_[APC1_DEVICE_INFO_OFFSET_FW], this->rx_buffer_[APC1_DEVICE_INFO_OFFSET_FW + 1]);
ESP_LOGI(TAG, "APC1: Module: %.6s, Serial: %08" PRIX32 "%08" PRIX32 ", Firmware: 0x%04X (%u)",
reinterpret_cast<const char *>(frame + APC1_DEVICE_INFO_OFFSET_MODULE),
reinterpret_cast<const char *>(this->rx_buffer_.data() + APC1_DEVICE_INFO_OFFSET_MODULE),
encode_uint32(serial[0], serial[1], serial[2], serial[3]),
encode_uint32(serial[4], serial[5], serial[6], serial[7]), fw_version, fw_version);
}
@@ -246,8 +295,6 @@ void APC1Component::set_measurement_mode() {
}
void APC1Component::send_command_(APC1Command cmd, uint16_t data) {
// Kept bytes of an earlier reply must not merge into this command's
this->reader_.drop_kept();
std::array<uint8_t, APC1_COMMAND_FRAME_SIZE> buf{
APC1_HEADER_1,
APC1_HEADER_2,
+7 -10
View File
@@ -1,11 +1,12 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/hal.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart.h"
#include <array>
namespace esphome::apc1 {
static constexpr uint8_t APC1_HEADER_1 = 0x42;
@@ -78,21 +79,17 @@ class APC1Component final : public uart::UARTDevice, public Component {
void initialize_device_();
/// Restarts the no-data watchdog so a mode change gets the same grace period as a cold boot
void arm_watchdog_();
/// Returns false for a frame that fails the checksum
bool parse_frame_(const uint8_t *frame, uint8_t total_len);
void parse_measurement_frame_(const uint8_t *frame);
void parse_device_info_frame_(const uint8_t *frame);
void parse_frame_(uint16_t total_len);
void parse_measurement_frame_();
void parse_device_info_frame_();
GPIOPin *set_pin_{nullptr};
GPIOPin *reset_pin_{nullptr};
uint32_t last_transmission_{0};
uint32_t last_valid_frame_{0};
uint32_t last_init_attempt_{0};
// 42 4D, payload length (2, BE), payload ending in its checksum (2)
LengthFrameReader<APC1_FRAME_SIZE_MEASUREMENT,
FrameFormat<FrameHeader<APC1_HEADER_1, APC1_HEADER_2>, PayloadLengthU16BE<LengthField{.offset = 2}>,
FrameMinLength<APC1_FRAME_HEADER_SIZE + 2>>>
reader_;
std::array<uint8_t, APC1_FRAME_SIZE_MEASUREMENT> rx_buffer_{};
uint8_t rx_index_{0};
uint8_t last_error_code_{0xFF};
bool active_mode_{true};
bool idle_{false};
+1 -1
View File
@@ -385,7 +385,7 @@ async def to_code(config: ConfigType) -> None:
# Adds a define and IDF component for legacy `audio_decoder.cpp`.
if data.flac_support:
cg.add_define("USE_AUDIO_FLAC_SUPPORT")
add_idf_component(name="esphome/micro-flac", ref="0.3.1")
add_idf_component(name="esphome/micro-flac", ref="0.3.0")
_emit_memory_pair(
data.flac.buffer_memory,
"CONFIG_MICRO_FLAC_PREFER_PSRAM",
+136 -70
View File
@@ -1,6 +1,5 @@
#include "bmi270.h"
#include "bmi270_config.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include "esphome/core/progmem.h"
@@ -22,40 +21,48 @@ static constexpr size_t MAX_I2C_BUFFER_SIZE = 32;
static constexpr size_t MAX_I2C_BUFFER_SIZE = 256;
#endif
// Configuration blob upload
// The BMI270 requires a firmware config blob to be written to its internal
// memory after every power-on before sensors can be used.
bool BMI270Component::load_config_file_() {
// The config port is only reachable with advanced power save off
// 1. Disable advanced power-save so the config port is accessible
if (!this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_ADV_POWER_SAVE_OFF))
return false;
delay(1);
// 2. Prepare config load: write 0x00 to INIT_CTRL to start
if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_START))
return false;
// 3. Burst-write the config in pages
const uint8_t *cfg = BMI270_CONFIG_FILE;
constexpr size_t cfg_len = sizeof(BMI270_CONFIG_FILE);
// The register byte goes first, so each burst is copied once and sent with write()
uint8_t buf[1 + MAX_I2C_BUFFER_SIZE];
buf[0] = BMI270_REG_INIT_DATA;
size_t index = 0;
while (index != cfg_len) {
// INIT_ADDR_0 takes the word address bits 0-3 and INIT_ADDR_1 bits 4-11
const uint8_t addr[2] = {static_cast<uint8_t>((index / 2) & 0x0F), static_cast<uint8_t>((index / 2) >> 4)};
if (this->write_register(BMI270_REG_INIT_ADDR_0, addr, sizeof(addr)) != i2c::ERROR_OK)
// Set the page address in INIT_ADDR registers
uint8_t addr_lsb = (uint8_t) ((index / 2) & 0x0F);
uint8_t addr_msb = (uint8_t) ((index / 2) >> 4);
if (!this->write_byte(BMI270_REG_INIT_ADDR_0, addr_lsb))
return false;
if (!this->write_byte(BMI270_REG_INIT_ADDR_0 + 1, addr_msb))
return false;
// Write a burst of up to the maximum allowed size
size_t burst = clamp_at_most(cfg_len - index, MAX_I2C_BUFFER_SIZE);
progmem_memcpy(buf + 1, BMI270_CONFIG_FILE + index, burst);
if (this->write(buf, burst + 1) != i2c::ERROR_OK)
if (this->write_register(BMI270_REG_INIT_DATA, cfg + index, burst) != i2c::ERROR_OK)
return false;
index += burst;
// 256 bursts at 50 kHz, or through an I2C multiplexer, outlast the ESP8266 soft watchdog
App.feed_wdt();
}
// 4. Signal end of config load
if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_DONE))
return false;
delay(20); // The datasheet asks for at least 20 ms before INTERNAL_STATUS is valid
delay(20); // spec: wait ≥20 ms for init to complete
// 5. Check INTERNAL_STATUS: bit[0:3] should be 0x01 ("initialisation OK")
uint8_t status = 0;
if (!this->read_byte(BMI270_REG_INTERNAL_STATUS, &status))
return false;
@@ -66,52 +73,74 @@ bool BMI270Component::load_config_file_() {
return true;
}
// setup() ─
void BMI270Component::setup() {
MotionComponent::setup();
// 1. Verify chip ID
if (!this->check_chip_id(this, BMI270_REG_CHIP_ID, BMI270_CHIP_ID_VALUE))
return;
// 2. Soft-reset via CMD register (0x7E = 0xB6)
if (!this->setup_check(this->write_byte(BMI270_REG_CMD, BMI270_CMD_SOFT_RESET)))
return;
delay(20);
if (!this->setup_check(this->load_config_file_(), LOG_STR("Config file upload failed")))
// 4. Upload the configuration blob
if (!this->setup_check(load_config_file_(), LOG_STR("Config file upload failed")))
return;
ESP_LOGD(TAG, "Config blob uploaded ✓");
// 5. Configure accelerometer
// ACC_CONF: ODR | BWP(0x2 = normal avg4) | perf_mode(1)
uint8_t acc_conf =
(uint8_t) (accel_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf)))
return;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_RANGE, (uint8_t) accel_range_)))
return;
// Normal filter bandwidth; performance mode for the accelerometer, noise and filter performance for the gyroscope
const uint8_t acc_conf =
this->accel_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
const uint8_t gyr_conf = this->gyro_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf) &&
this->write_byte(BMI270_REG_ACC_RANGE, this->accel_range_) &&
this->write_byte(BMI270_REG_GYR_CONF, gyr_conf) &&
this->write_byte(BMI270_REG_GYR_RANGE, this->gyro_range_) &&
this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
// 6. Configure gyroscope
// GYR_CONF: ODR | BWP(0x2 = normal) | noise_perf(1) | filter_perf(1)
uint8_t gyr_conf = (uint8_t) (gyro_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
if (!this->setup_check(this->write_byte(BMI270_REG_GYR_CONF, gyr_conf)))
return;
if (!this->setup_check(this->write_byte(BMI270_REG_GYR_RANGE, (uint8_t) gyro_range_)))
return;
// 7. Enable accelerometer, gyroscope, and temperature sensor
// PWR_CTRL bits: temp_en[3] | gyr_en[2] | acc_en[1]
if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
return;
delay(5);
// Advanced power save stays off; FIFO self-wakeup on
// 8. Re-enable advanced power save (optional; keeps current low between reads)
// Disabled here for simplicity – leave in performance mode
// bit1 = fifo_self_wakeup
if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_FIFO_SELF_WAKEUP)))
return;
// 9. Optionally bring up whatever is wired to the aux interface.
// This is entirely additive: it is off by default, and failure only disables
// magnetometer reporting rather than the whole component.
#ifdef USE_BMI270_BMM150
// A missing magnetometer only disables magnetometer reporting
if (this->aux_device_ == BMI270_AUX_DEVICE_BMM150) {
const LogString *failed_step = this->setup_magnetometer_();
this->magnetometer_ready_ = failed_step == nullptr;
this->magnetometer_ready_ = this->setup_magnetometer_();
if (!this->magnetometer_ready_) {
ESP_LOGW(TAG, "BMM150 magnetometer setup failed at %s; continuing without it", LOG_STR_ARG(failed_step));
ESP_LOGW(TAG, "BMM150 magnetometer setup failed; continuing without it");
}
}
#endif
ESP_LOGCONFIG(TAG, "BMI270 initialised successfully");
}
#ifdef USE_BMI270_BMM150
static_assert(BMM150_TRIM_BLOCK_LEN == BMI270_AUX_DATA_LEN, "each trim block is one aux read");
bool BMI270Component::wait_for_aux_idle_() {
static constexpr uint32_t AUX_IDLE_TIMEOUT_MS = 20;
bool BMI270Component::wait_for_aux_idle_(uint32_t timeout_ms) {
// The STATUS aux-busy bit is set while an aux transaction is in flight. Aux transaction
// duration depends on the attached device's own timing, so poll with a bounded
// timeout instead of guessing a fixed delay.
uint32_t start = millis();
while (true) {
uint8_t status = 0;
@@ -119,63 +148,98 @@ bool BMI270Component::wait_for_aux_idle_() {
return false;
if ((status & BMI270_STATUS_AUX_BUSY) == 0)
return true;
if (millis() - start >= AUX_IDLE_TIMEOUT_MS)
if (millis() - start >= timeout_ms)
return false;
delay(1);
}
}
bool BMI270Component::write_aux_register_(uint8_t reg, uint8_t value) {
return this->write_byte(BMI270_REG_AUX_WR_DATA, value) && this->write_byte(BMI270_REG_AUX_WR_ADDR, reg) &&
this->wait_for_aux_idle_();
if (!this->write_byte(BMI270_REG_AUX_WR_DATA, value))
return false;
if (!this->write_byte(BMI270_REG_AUX_WR_ADDR, reg))
return false;
return this->wait_for_aux_idle_(20);
}
bool BMI270Component::read_aux_block_(uint8_t reg, uint8_t *buf) {
return this->write_byte(BMI270_REG_AUX_RD_ADDR, reg) && this->wait_for_aux_idle_() &&
this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, reg))
return false;
if (!this->wait_for_aux_idle_(20))
return false;
return this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
}
// Follows the Bosch BMI270 aux-interface sequence; ends in auto-burst mode, where the BMI270 keeps
// AUX_X/Y/Z/R filled from the BMM150's data registers
const LogString *BMI270Component::setup_magnetometer_() {
if (!(this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN) &&
this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8) &&
this->write_byte(BMI270_REG_AUX_DEV_ID, this->aux_device_address_ << 1)))
return LOG_STR("aux interface");
bool BMI270Component::read_magnetometer_trim_() {
uint8_t regs[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, regs + i * BMM150_TRIM_BLOCK_LEN))
return false;
}
this->mag_trim_ = bmm150_parse_trim(regs);
return true;
}
bool BMI270Component::setup_magnetometer_() {
// Sequence adapted from the Bosch BMI270 aux-interface protocol: enable the secondary
// I2C master in manual mode, point it at the BMM150's address, power the BMM150 up
// and soft-reset it, verify its chip ID, read its factory trim values, put it in
// normal/30Hz mode, then switch the aux interface to auto-burst mode so BMI270 keeps
// AUX_X/Y/Z/R refreshed from the BMM150's data registers.
ESP_LOGD(TAG, "Setting up BMM150 magnetometer via BMI270 aux interface...");
if (!this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN))
return false;
if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8))
return false;
if (!this->write_byte(BMI270_REG_AUX_DEV_ID, (uint8_t) (this->aux_device_address_ << 1)))
return false;
// Suspend -> sleep, then a soft reset so the BMM150 starts from a known state even if it
// stayed powered across a restart. The chip ID is only readable once the power bit is set.
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON))
return LOG_STR("power-on");
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON)) {
ESP_LOGW(TAG, "BMM150 power-on write timed out");
return false;
}
delay(BMM150_START_UP_TIME_MS);
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET))
return LOG_STR("soft reset");
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET)) {
ESP_LOGW(TAG, "BMM150 soft-reset write timed out");
return false;
}
delay(BMM150_SOFT_RESET_TIME_MS);
uint8_t chip_id[BMI270_AUX_DATA_LEN];
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id))
return LOG_STR("chip ID read");
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id)) {
ESP_LOGW(TAG, "BMM150 chip-ID read failed");
return false;
}
if (chip_id[0] != BMM150_CHIP_ID_VALUE) {
ESP_LOGW(TAG, "BMM150 chip ID 0x%02X, expected 0x%02X", chip_id[0], BMM150_CHIP_ID_VALUE);
return LOG_STR("chip ID check");
ESP_LOGW(TAG, "BMM150 not detected (chip ID 0x%02X, expected 0x%02X)", chip_id[0], BMM150_CHIP_ID_VALUE);
return false;
}
uint8_t trim[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, trim + i * BMM150_TRIM_BLOCK_LEN))
return LOG_STR("trim read");
if (!this->read_magnetometer_trim_()) {
ESP_LOGW(TAG, "BMM150 trim data read failed");
return false;
}
this->mag_trim_ = bmm150_parse_trim(trim);
if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ))
return LOG_STR("normal mode");
if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ)) {
ESP_LOGW(TAG, "BMM150 mode write timed out");
return false;
}
if (!(this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
BMI270_AUX_IF_CONF_RD_BURST_8) &&
this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB) &&
this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN)))
return LOG_STR("auto-burst mode");
return nullptr;
// Switch to auto-burst mode: BMI270 will keep polling 8 bytes from the BMM150's
// data registers (0x42) into its own AUX_X/Y/Z/R registers automatically.
if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
BMI270_AUX_IF_CONF_RD_BURST_8))
return false;
if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB))
return false;
if (!this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN))
return false;
ESP_LOGD(TAG, "BMM150 magnetometer ready");
return true;
}
#endif // USE_BMI270_BMM150
@@ -185,10 +249,9 @@ void BMI270Component::dump_config() {
if (this->is_failed())
return;
ESP_LOGCONFIG(TAG,
" Accel range : %s\n"
" Gyro range : %s",
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)),
ESP_LOGCONFIG(TAG, " Accel range : %s",
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)));
ESP_LOGCONFIG(TAG, " Gyro range : %s",
LOG_STR_ARG(GyroRangeStrings::get_log_str(this->gyro_range_, GyroRangeStrings::LAST_INDEX)));
#ifdef USE_BMI270_BMM150
if (this->aux_device_ == BMI270_AUX_DEVICE_BMM150) {
@@ -199,6 +262,9 @@ void BMI270Component::dump_config() {
MotionComponent::dump_config();
}
// update() ─
// Reads all 6 axes + temperature in one block
bool BMI270Component::update_data(motion::MotionData &data) {
if (this->is_failed())
return false;
+24 -8
View File
@@ -12,15 +12,18 @@
namespace esphome::bmi270 {
// Register map
static constexpr uint8_t BMI270_REG_CHIP_ID = 0x00;
static constexpr uint8_t BMI270_REG_ERR_REG = 0x02;
static constexpr uint8_t BMI270_REG_STATUS = 0x03;
static constexpr uint8_t BMI270_REG_DATA_8 = 0x0C; // ACC_X LSB
static constexpr uint8_t BMI270_REG_DATA_14 = 0x12; // GYR_X LSB
static constexpr uint8_t BMI270_REG_TEMP_0 = 0x22;
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23;
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23; // temperature (2 bytes big-endian ish)
// Accel, gyro, 10 unused bytes, then temperature: 0x0C to 0x23
static constexpr uint8_t REG_READ_LEN = BMI270_REG_TEMP_MSB - BMI270_REG_DATA_8 + 1;
static constexpr uint8_t REG_READ_LEN =
BMI270_REG_TEMP_MSB - BMI270_REG_DATA_8 +
1; // 0x23 - 0x0C + 1 = 0x18 bytes total for accel(6) + gyro(6) + temp(2) + padding(4)
static constexpr uint8_t BMI270_REG_PWR_CONF = 0x7C;
static constexpr uint8_t BMI270_REG_PWR_CTRL = 0x7D;
@@ -77,6 +80,7 @@ static constexpr uint8_t BMI270_AUX_IF_CONF_RD_BURST_8 = 0x03; // bits 1:0
static constexpr uint8_t BMI270_AUX_DATA_LEN = 8;
static_assert(BMI270_REG_AUX_X_LSB + BMI270_AUX_DATA_LEN == BMI270_REG_DATA_8, "aux data must precede accel data");
// Accelerometer range options
enum BMI270AccelRange : uint8_t {
BMI270_ACCEL_RANGE_2G = 0x00,
BMI270_ACCEL_RANGE_4G = 0x01,
@@ -84,6 +88,7 @@ enum BMI270AccelRange : uint8_t {
BMI270_ACCEL_RANGE_16G = 0x03,
};
// Accelerometer ODR options
enum BMI270AccelODR : uint8_t {
BMI270_ACCEL_ODR_12_5 = 0x05,
BMI270_ACCEL_ODR_25 = 0x06,
@@ -95,6 +100,7 @@ enum BMI270AccelODR : uint8_t {
BMI270_ACCEL_ODR_1600 = 0x0C,
};
// Gyroscope range options
enum BMI270GyroRange : uint8_t {
BMI270_GYRO_RANGE_2000 = 0x00,
BMI270_GYRO_RANGE_1000 = 0x01,
@@ -103,6 +109,7 @@ enum BMI270GyroRange : uint8_t {
BMI270_GYRO_RANGE_125 = 0x04,
};
// Gyroscope ODR options
enum BMI270GyroODR : uint8_t {
BMI270_GYRO_ODR_25 = 0x06,
BMI270_GYRO_ODR_50 = 0x07,
@@ -123,11 +130,14 @@ enum BMI270AuxDevice : uint8_t {
};
#endif
// Main component class
class BMI270Component final : public motion::MotionComponent, public i2c::I2CDevice {
public:
// Lifecycle
void setup() override;
void dump_config() override;
// Configuration setters
void set_accel_range(BMI270AccelRange r) { this->accel_range_ = r; }
void set_accel_odr(BMI270AccelODR o) { this->accel_odr_ = o; }
void set_gyro_range(BMI270GyroRange r) { this->gyro_range_ = r; }
@@ -143,15 +153,21 @@ class BMI270Component final : public motion::MotionComponent, public i2c::I2CDev
bool update_data(motion::MotionData &data) override;
bool load_config_file_();
#ifdef USE_BMI270_BMM150
// Returns the step that failed, or nullptr once the BMM150 is running
const LogString *setup_magnetometer_();
// Polls the aux busy bit, as the aux transaction time depends on the attached device
bool wait_for_aux_idle_();
// Manual-mode aux read of 8 bytes starting at `reg` on the aux device
// Brings up the BMM150 over the BMI270's aux interface. Optional: on failure this only
// disables magnetometer reporting, it does not fail the whole component (accel/gyro still work).
bool setup_magnetometer_();
// Blocking poll of the aux-transaction-busy bit; aux transaction time depends on the
// attached device, so this is bounded by retries/timeout rather than a fixed delay.
bool wait_for_aux_idle_(uint32_t timeout_ms);
// Manual-mode aux read of 8 bytes starting at `reg` on the aux device.
bool read_aux_block_(uint8_t reg, uint8_t *buf);
// Manual-mode aux write of one byte to `reg` on the aux device.
bool write_aux_register_(uint8_t reg, uint8_t value);
// Reads the BMM150 factory trim values used to compensate its samples.
bool read_magnetometer_trim_();
#endif
// Config
BMI270AccelRange accel_range_{BMI270_ACCEL_RANGE_4G};
BMI270AccelODR accel_odr_{BMI270_ACCEL_ODR_100};
BMI270GyroRange gyro_range_{BMI270_GYRO_RANGE_2000};
+1 -2
View File
@@ -1,6 +1,5 @@
#pragma once
#include <cstdint>
#include "esphome/core/hal.h"
namespace esphome::bmi270 {
@@ -45,7 +44,7 @@ POSSIBILITY OF SUCH DAMAGE.
after every power cycle, before any sensor data can be read.
--------------------------------------------------------------------------- */
static constexpr uint8_t BMI270_CONFIG_FILE[] PROGMEM = {
static constexpr uint8_t BMI270_CONFIG_FILE[] = {
0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x3d, 0xb1, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x91, 0x03, 0x80, 0x2e, 0xbc,
0xb0, 0x80, 0x2e, 0xa3, 0x03, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x00, 0xb0, 0x50, 0x30, 0x21, 0x2e, 0x59, 0xf5,
0x10, 0x30, 0x21, 0x2e, 0x6a, 0xf5, 0x80, 0x2e, 0x3b, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x19, 0x01, 0x00, 0x22,
+16 -16
View File
@@ -3,8 +3,11 @@
#include <cstdint>
#include "esphome/core/helpers.h"
// BMM150 magnetometer behind the BMI270's aux interface; it is not on the main I2C bus, so it is not
// its own component
// BMM150 magnetometer definitions - the chip that can optionally be wired to the BMI270's
// auxiliary (secondary I2C master) interface. Lives in its own header/namespace because this
// is BMM150-specific driver knowledge, not BMI270 knowledge - it just can't be a standalone
// ESPHome component, since the BMM150 has no address of its own on the main I2C bus and is only
// reachable by having the BMI270 proxy register reads/writes through its aux interface.
namespace esphome::bmi270::bmm150 {
static constexpr uint8_t BMM150_DEFAULT_I2C_ADDRESS = 0x10;
@@ -61,23 +64,20 @@ inline uint16_t bmm150_trim_word(const uint8_t *regs, uint8_t reg) {
return encode_value_le<uint16_t>(&regs[offset]);
}
// A trim byte, addressed by its register
inline uint8_t bmm150_trim_byte(const uint8_t *regs, uint8_t reg) { return regs[reg - BMM150_REG_TRIM_START]; }
// Decodes the trim registers; `regs` holds the bytes of registers 0x5D onwards (at least 21).
inline BMM150Trim bmm150_parse_trim(const uint8_t *regs) {
BMM150Trim trim;
trim.x1 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_X1));
trim.y1 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_Y1));
trim.x1 = static_cast<int8_t>(regs[BMM150_TRIM_X1 - BMM150_REG_TRIM_START]);
trim.y1 = static_cast<int8_t>(regs[BMM150_TRIM_Y1 - BMM150_REG_TRIM_START]);
trim.z4 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z4));
trim.x2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_X2));
trim.y2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_Y2));
trim.x2 = static_cast<int8_t>(regs[BMM150_TRIM_X2 - BMM150_REG_TRIM_START]);
trim.y2 = static_cast<int8_t>(regs[BMM150_TRIM_Y2 - BMM150_REG_TRIM_START]);
trim.z2 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z2));
trim.z1 = bmm150_trim_word(regs, BMM150_TRIM_Z1);
trim.xyz1 = bmm150_trim_word(regs, BMM150_TRIM_XYZ1) & BMM150_TRIM_XYZ1_MASK;
trim.z3 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z3));
trim.xy2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_XY2));
trim.xy1 = bmm150_trim_byte(regs, BMM150_TRIM_XY1);
trim.xy2 = static_cast<int8_t>(regs[BMM150_TRIM_XY2 - BMM150_REG_TRIM_START]);
trim.xy1 = regs[BMM150_TRIM_XY1 - BMM150_REG_TRIM_START];
return trim;
}
@@ -108,11 +108,11 @@ inline float bmm150_compensate_z(const BMM150Trim &trim, int16_t raw, uint16_t r
// Converts 8 raw bytes from the BMM150 data registers (X, Y, Z, RHALL; 0x42-0x49) to compensated µT.
inline BMM150Data bmm150_convert(const BMM150Trim &trim, const uint8_t *raw) {
// Left-aligned in their 16-bit words: X/Y are 13-bit, Z is 15-bit, RHALL is 14-bit
const int16_t x = encode_value_le<int16_t>(&raw[0]) >> 3;
const int16_t y = encode_value_le<int16_t>(&raw[2]) >> 3;
const int16_t z = encode_value_le<int16_t>(&raw[4]) >> 1;
const uint16_t rhall = encode_value_le<uint16_t>(&raw[6]) >> 2;
// X/Y are 13-bit (LSB byte bits 7:3), Z is 15-bit (bits 7:1), RHALL is 14-bit (bits 7:2).
int16_t x = (int16_t) (((int16_t) (int8_t) raw[1] * 32) | (raw[0] >> 3));
int16_t y = (int16_t) (((int16_t) (int8_t) raw[3] * 32) | (raw[2] >> 3));
int16_t z = (int16_t) (((int16_t) (int8_t) raw[5] * 128) | (raw[4] >> 1));
uint16_t rhall = (uint16_t) (((uint16_t) raw[7] << 6) | (raw[6] >> 2));
return BMM150Data{
.x = bmm150_compensate_xy(trim, trim.x1, trim.x2, x, rhall),
.y = bmm150_compensate_xy(trim, trim.y1, trim.y2, y, rhall),
+21 -28
View File
@@ -17,14 +17,6 @@ DEPENDENCIES = ["i2c"]
CONF_AUX_ADDRESS = "aux_address"
CONF_AUX_DEVICE = "aux_device"
# to_code skips the setters at these values, so each must match its member default in bmi270.h
DEFAULT_ACCELEROMETER_RANGE = "4G"
DEFAULT_ACCELEROMETER_ODR = "100HZ"
DEFAULT_GYROSCOPE_RANGE = "2000DPS"
DEFAULT_GYROSCOPE_ODR = "200HZ"
# The BMM150's fixed address
DEFAULT_AUX_ADDRESS = 0x10
# Enum proxies (must match the C++ enum values exactly)
BMI270AuxDevice = bmi270_ns.enum("BMI270AuxDevice")
BMI270AccelRange = bmi270_ns.enum("BMI270AccelRange")
@@ -65,49 +57,50 @@ GYRO_ODR_OPTIONS = {
"3200HZ": BMI270GyroODR.BMI270_GYRO_ODR_3200,
}
# Top-level CONFIG_SCHEMA
CONFIG_SCHEMA = (
motion_schema(BMI270Component, has_accel=True, has_gyro=True)
.extend(
{
cv.Optional(
CONF_ACCELEROMETER_RANGE, default=DEFAULT_ACCELEROMETER_RANGE
): cv.enum(ACCEL_RANGE_OPTIONS, upper=True),
cv.Optional(
CONF_ACCELEROMETER_ODR, default=DEFAULT_ACCELEROMETER_ODR
): cv.enum(ACCEL_ODR_OPTIONS, upper=True),
cv.Optional(CONF_GYROSCOPE_RANGE, default=DEFAULT_GYROSCOPE_RANGE): cv.enum(
cv.Optional(CONF_ACCELEROMETER_RANGE, default="4G"): cv.enum(
ACCEL_RANGE_OPTIONS, upper=True
),
cv.Optional(CONF_ACCELEROMETER_ODR, default="100HZ"): cv.enum(
ACCEL_ODR_OPTIONS, upper=True
),
cv.Optional(CONF_GYROSCOPE_RANGE, default="2000DPS"): cv.enum(
GYRO_RANGE_OPTIONS, upper=True
),
cv.Optional(CONF_GYROSCOPE_ODR, default=DEFAULT_GYROSCOPE_ODR): cv.enum(
cv.Optional(CONF_GYROSCOPE_ODR, default="200HZ"): cv.enum(
GYRO_ODR_OPTIONS, upper=True
),
# Optional device wired to the BMI270's aux interface (not the main I2C bus).
# Defaults to NONE so existing configs/boards are unaffected.
cv.Optional(CONF_AUX_DEVICE, default="NONE"): cv.one_of(
"NONE", "BMM150", upper=True
),
cv.Optional(CONF_AUX_ADDRESS, default=DEFAULT_AUX_ADDRESS): cv.i2c_address,
# Default matches the BMM150's fixed I2C address; irrelevant when aux_device is NONE.
cv.Optional(CONF_AUX_ADDRESS, default=0x10): cv.i2c_address,
}
)
.extend(i2c.i2c_device_schema(0x68))
)
# Code generation
async def to_code(config: ConfigType) -> None:
var = await new_motion_component(config)
await i2c.register_i2c_device(var, config)
# The C++ members already hold the schema defaults
for key, default, setter in (
(CONF_ACCELEROMETER_RANGE, DEFAULT_ACCELEROMETER_RANGE, var.set_accel_range),
(CONF_ACCELEROMETER_ODR, DEFAULT_ACCELEROMETER_ODR, var.set_accel_odr),
(CONF_GYROSCOPE_RANGE, DEFAULT_GYROSCOPE_RANGE, var.set_gyro_range),
(CONF_GYROSCOPE_ODR, DEFAULT_GYROSCOPE_ODR, var.set_gyro_odr),
):
if config[key] != default:
cg.add(setter(config[key]))
# Accelerometer sensors
# Hardware configuration
cg.add(var.set_accel_range(config[CONF_ACCELEROMETER_RANGE]))
cg.add(var.set_accel_odr(config[CONF_ACCELEROMETER_ODR]))
cg.add(var.set_gyro_range(config[CONF_GYROSCOPE_RANGE]))
cg.add(var.set_gyro_odr(config[CONF_GYROSCOPE_ODR]))
# The aux interface code only compiles when some instance has a BMM150; the
# instance still records its own device, as another one may have none
if config[CONF_AUX_DEVICE] == "BMM150":
cg.add_define("USE_BMI270_BMM150")
cg.add(var.set_aux_device(BMI270AuxDevice.BMI270_AUX_DEVICE_BMM150))
if (address := config[CONF_AUX_ADDRESS]) != DEFAULT_AUX_ADDRESS:
cg.add(var.set_aux_device_address(address))
cg.add(var.set_aux_device_address(config[CONF_AUX_ADDRESS]))
+10 -4
View File
@@ -515,12 +515,18 @@ void CC1101Component::dump_config() {
}
void CC1101Component::begin_tx() {
if (this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
ESP_LOGW(TAG, "begin_tx is for async serial mode; use send_packet in packet mode");
return;
}
this->wake_up();
// Read the mode before the PKTCTRL0 write below overwrites it in state_
const bool packet_mode = this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
// Ensure Packet Format is 3 (Async Serial)
this->write_(Register::PKTCTRL0, 0x32);
ESP_LOGV(TAG, "Beginning TX sequence");
if (this->gdo0_pin_ != nullptr) {
// setup() only attaches the interrupt in packet mode. In async serial mode the pin may be
// shared with remote_receiver, and detaching here would remove the receiver's interrupt.
if (packet_mode) {
this->gdo0_pin_->detach_interrupt();
}
this->gdo0_pin_->pin_mode(gpio::FLAG_OUTPUT);
}
// Transition through IDLE to bypass CCA (Clear Channel Assessment) which can
@@ -63,25 +63,13 @@ void CST816Touchscreen::update_touches() {
uint8_t data[13];
if (!this->status_comm_result(this->read_bytes(REG_STATUS, data, sizeof data)))
return;
// The low nibble is the touch count. CST816/CST820 are single-touch;
// CST826/CST836 can report two points, but this driver only reads the first
// point. Some CST8xx controllers report an all-0xFF frame when idle or after
// disabling auto-sleep: the count lands above two and the coordinates are
// the 0xFFF sentinel, so both guards below reject it.
uint8_t num_of_touches = low_nibble(data[REG_TOUCH_NUM]);
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 3;
if (num_of_touches == 0) {
return;
}
if (num_of_touches > 2) {
return;
}
uint16_t x = encode_uint16(low_nibble(data[REG_XPOS_HIGH]), data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(low_nibble(data[REG_YPOS_HIGH]), data[REG_YPOS_LOW]);
if (x == 0x0FFF || y == 0x0FFF) {
return;
}
ESP_LOGV(TAG, "Read touch %d/%d", x, y);
this->add_raw_touch_position_(0, x, y);
}
+138 -108
View File
@@ -1,5 +1,6 @@
#include "daly_bms.h"
#include <algorithm>
#include <vector>
#include "esphome/core/application.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
@@ -8,6 +9,7 @@ namespace esphome::daly_bms {
ESPHOME_LOG_TAG(TAG, "daly_bms");
static const uint8_t DALY_FRAME_SIZE = 13;
static const uint8_t DALY_TEMPERATURE_OFFSET = 40;
static const uint16_t DALY_CURRENT_OFFSET = 30000;
@@ -46,9 +48,14 @@ void DalyBmsComponent::update() {
void DalyBmsComponent::loop() {
const uint32_t now = App.get_loop_component_start_time();
auto handle = [this](const uint8_t *frame, size_t /*len*/) { return this->handle_frame_(frame); };
this->read_frames(this->reader_, handle, now, this->last_transmission_);
if (this->response_complete_() && !this->reader_.receiving() &&
const size_t avail = this->available();
if (this->receiving_ && (now - this->last_transmission_ >= 200)) {
// last transmission too long ago. Reset RX index.
ESP_LOGW(TAG, "Last transmission too long ago. Reset RX index.");
this->data_.clear();
this->receiving_ = false;
}
if (this->response_complete_() && !this->receiving_ && avail == 0 &&
(now - this->last_transmission_ >= DALY_RESPONSE_GAP_MS) && !this->trigger_next_) {
// response complete and nothing more on the line -> trigger next request without waiting for the timeout
this->last_transmission_ = now;
@@ -59,6 +66,25 @@ void DalyBmsComponent::loop() {
this->last_transmission_ = now;
this->trigger_next_ = true;
}
if (avail > 0)
this->last_transmission_ = now;
this->read_available(
[this](uint8_t c) {
if (!this->receiving_) {
if (c != 0xa5)
return;
this->receiving_ = true;
}
this->data_.push_back(c);
if (this->data_.size() == 4)
this->data_count_ = c;
if ((this->data_.size() > 4) and (data_.size() == this->data_count_ + 5)) {
this->decode_data_(this->data_);
this->data_.clear();
this->receiving_ = false;
}
},
avail);
if (!this->trigger_next_)
return;
@@ -79,8 +105,6 @@ void DalyBmsComponent::loop() {
this->last_transmission_ = now;
// the request IDs are consecutive, see DALY_REQUEST_BATTERY_LEVEL
this->last_request_ = DALY_REQUEST_BATTERY_LEVEL + this->next_request_++;
// Kept bytes of an earlier reply must not merge into this request's
this->reader_.drop_kept();
this->request_data_(this->last_request_);
}
@@ -119,122 +143,128 @@ void DalyBmsComponent::request_data_(uint8_t data_id) {
this->flush();
}
bool DalyBmsComponent::handle_frame_(const uint8_t *frame) {
// Only BMS responses (address 0x01) with their 8 data bytes carry data; an echoed request is skipped like noise
if (frame[1] != 0x01 || frame[3] != 8)
return false;
if (sum_bytes(frame, DALY_FRAME_SIZE - 1) != frame[DALY_FRAME_SIZE - 1]) {
ESP_LOGW(TAG, "Checksum-Error on Packet %x", frame[4]);
return false;
}
// only an answer to the last request counts
if (frame[2] == this->last_request_)
this->frames_received_++;
if (frame[2] == DALY_REQUEST_STATUS) {
this->cell_frames_ = (frame[4] + 2) / 3; // three cells per cell voltage frame
this->temperature_frames_ = std::max((frame[5] + 6) / 7, 1);
}
switch (frame[2]) {
void DalyBmsComponent::decode_data_(std::vector<uint8_t> data) {
auto it = data.begin();
while ((it = std::find(it, data.end(), 0xA5)) != data.end()) {
if (data.end() - it >= DALY_FRAME_SIZE && it[1] == 0x01) {
const uint8_t checksum = sum_bytes(&*it, 12);
if (checksum == it[12]) {
// only a valid frame answering the last request counts; an echoed request or a late answer does not
if (it[2] == this->last_request_)
this->frames_received_++;
if (it[2] == DALY_REQUEST_STATUS) {
this->cell_frames_ = (it[4] + 2) / 3; // three cells per cell voltage frame
this->temperature_frames_ = std::max((it[5] + 6) / 7, 1);
}
switch (it[2]) {
#ifdef USE_SENSOR
case DALY_REQUEST_BATTERY_LEVEL:
PUBLISH_STATE(this->voltage_sensor_, (float) encode_uint16(frame[4], frame[5]) / 10);
PUBLISH_STATE(this->current_sensor_, (float) (encode_uint16(frame[8], frame[9]) - DALY_CURRENT_OFFSET) / 10);
PUBLISH_STATE(this->battery_level_sensor_, (float) encode_uint16(frame[10], frame[11]) / 10);
break;
case DALY_REQUEST_BATTERY_LEVEL:
PUBLISH_STATE(this->voltage_sensor_, (float) encode_uint16(it[4], it[5]) / 10);
PUBLISH_STATE(this->current_sensor_, (float) (encode_uint16(it[8], it[9]) - DALY_CURRENT_OFFSET) / 10);
PUBLISH_STATE(this->battery_level_sensor_, (float) encode_uint16(it[10], it[11]) / 10);
break;
case DALY_REQUEST_MIN_MAX_VOLTAGE:
PUBLISH_STATE(this->max_cell_voltage_sensor_, (float) encode_uint16(frame[4], frame[5]) / 1000);
PUBLISH_STATE(this->max_cell_voltage_number_sensor_, frame[6]);
PUBLISH_STATE(this->min_cell_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->min_cell_voltage_number_sensor_, frame[9]);
break;
case DALY_REQUEST_MIN_MAX_VOLTAGE:
PUBLISH_STATE(this->max_cell_voltage_sensor_, (float) encode_uint16(it[4], it[5]) / 1000);
PUBLISH_STATE(this->max_cell_voltage_number_sensor_, it[6]);
PUBLISH_STATE(this->min_cell_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->min_cell_voltage_number_sensor_, it[9]);
break;
case DALY_REQUEST_MIN_MAX_TEMPERATURE:
PUBLISH_STATE(this->max_temperature_sensor_, frame[4] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->max_temperature_probe_number_sensor_, frame[5]);
PUBLISH_STATE(this->min_temperature_sensor_, frame[6] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->min_temperature_probe_number_sensor_, frame[7]);
break;
case DALY_REQUEST_MIN_MAX_TEMPERATURE:
PUBLISH_STATE(this->max_temperature_sensor_, it[4] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->max_temperature_probe_number_sensor_, it[5]);
PUBLISH_STATE(this->min_temperature_sensor_, it[6] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->min_temperature_probe_number_sensor_, it[7]);
break;
#endif
case DALY_REQUEST_MOS:
case DALY_REQUEST_MOS:
#ifdef USE_TEXT_SENSOR
if (this->status_text_sensor_ != nullptr) {
switch (frame[4]) {
case 0:
this->status_text_sensor_->publish_state("Stationary");
if (this->status_text_sensor_ != nullptr) {
switch (it[4]) {
case 0:
this->status_text_sensor_->publish_state("Stationary");
break;
case 1:
this->status_text_sensor_->publish_state("Charging");
break;
case 2:
this->status_text_sensor_->publish_state("Discharging");
break;
default:
break;
}
}
#endif
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->charging_mos_enabled_binary_sensor_, it[5]);
PUBLISH_STATE(this->discharging_mos_enabled_binary_sensor_, it[6]);
#endif
#ifdef USE_SENSOR
PUBLISH_STATE(this->remaining_capacity_sensor_, (float) encode_uint32(it[8], it[9], it[10], it[11]) / 1000);
#endif
break;
case 1:
this->status_text_sensor_->publish_state("Charging");
#ifdef USE_SENSOR
case DALY_REQUEST_STATUS:
PUBLISH_STATE(this->cells_number_sensor_, it[4]);
break;
case 2:
this->status_text_sensor_->publish_state("Discharging");
case DALY_REQUEST_TEMPERATURE:
if (it[4] == 1) {
PUBLISH_STATE(this->temperature_1_sensor_, it[5] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->temperature_2_sensor_, it[6] - DALY_TEMPERATURE_OFFSET);
}
break;
case DALY_REQUEST_CELL_VOLTAGE:
switch (it[4]) {
case 1:
PUBLISH_STATE(this->cell_1_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_2_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_3_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 2:
PUBLISH_STATE(this->cell_4_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_5_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_6_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 3:
PUBLISH_STATE(this->cell_7_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_8_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_9_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 4:
PUBLISH_STATE(this->cell_10_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_11_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_12_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 5:
PUBLISH_STATE(this->cell_13_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_14_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_15_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
case 6:
PUBLISH_STATE(this->cell_16_voltage_sensor_, (float) encode_uint16(it[5], it[6]) / 1000);
PUBLISH_STATE(this->cell_17_voltage_sensor_, (float) encode_uint16(it[7], it[8]) / 1000);
PUBLISH_STATE(this->cell_18_voltage_sensor_, (float) encode_uint16(it[9], it[10]) / 1000);
break;
}
break;
#endif
default:
break;
}
} else {
ESP_LOGW(TAG, "Checksum-Error on Packet %x", it[4]);
}
#endif
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->charging_mos_enabled_binary_sensor_, frame[5]);
PUBLISH_STATE(this->discharging_mos_enabled_binary_sensor_, frame[6]);
#endif
#ifdef USE_SENSOR
PUBLISH_STATE(this->remaining_capacity_sensor_,
(float) encode_uint32(frame[8], frame[9], frame[10], frame[11]) / 1000);
#endif
break;
#ifdef USE_SENSOR
case DALY_REQUEST_STATUS:
PUBLISH_STATE(this->cells_number_sensor_, frame[4]);
break;
case DALY_REQUEST_TEMPERATURE:
if (frame[4] == 1) {
PUBLISH_STATE(this->temperature_1_sensor_, frame[5] - DALY_TEMPERATURE_OFFSET);
PUBLISH_STATE(this->temperature_2_sensor_, frame[6] - DALY_TEMPERATURE_OFFSET);
}
break;
case DALY_REQUEST_CELL_VOLTAGE:
switch (frame[4]) {
case 1:
PUBLISH_STATE(this->cell_1_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_2_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_3_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 2:
PUBLISH_STATE(this->cell_4_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_5_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_6_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 3:
PUBLISH_STATE(this->cell_7_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_8_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_9_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 4:
PUBLISH_STATE(this->cell_10_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_11_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_12_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 5:
PUBLISH_STATE(this->cell_13_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_14_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_15_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
case 6:
PUBLISH_STATE(this->cell_16_voltage_sensor_, (float) encode_uint16(frame[5], frame[6]) / 1000);
PUBLISH_STATE(this->cell_17_voltage_sensor_, (float) encode_uint16(frame[7], frame[8]) / 1000);
PUBLISH_STATE(this->cell_18_voltage_sensor_, (float) encode_uint16(frame[9], frame[10]) / 1000);
break;
}
break;
#endif
default:
break;
std::advance(it, DALY_FRAME_SIZE);
} else {
std::advance(it, 1);
}
}
return true;
}
} // namespace esphome::daly_bms
+6 -7
View File
@@ -2,7 +2,6 @@
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/frame_reader.h"
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor.h"
#endif
@@ -14,9 +13,9 @@
#endif
#include "esphome/components/uart/uart.h"
namespace esphome::daly_bms {
#include <vector>
static constexpr uint8_t DALY_FRAME_SIZE = 13;
namespace esphome::daly_bms {
class DalyBmsComponent final : public PollingComponent, public uart::UARTDevice {
public:
@@ -77,13 +76,13 @@ class DalyBmsComponent final : public PollingComponent, public uart::UARTDevice
void request_data_(uint8_t data_id);
// all frames of the response to the last request are in
bool response_complete_() const;
/// Returns false for a frame that is not a BMS response or fails the checksum
bool handle_frame_(const uint8_t *frame);
void decode_data_(std::vector<uint8_t> data);
uint8_t addr_;
// A5, address, data ID, length 8, 8 data bytes, sum8; every request and response has 8 data bytes
LengthFrameReader<DALY_FRAME_SIZE, FrameFormat<FrameHeader<0xA5>, FrameFixedLength<DALY_FRAME_SIZE>>> reader_;
std::vector<uint8_t> data_;
bool receiving_{false};
uint8_t data_count_{0};
uint32_t last_transmission_{0};
bool trigger_next_{false};
// update() asked for a request cycle; it starts once no cycle is running. The first one runs at boot.
-2
View File
@@ -94,7 +94,5 @@ FILTER_SOURCE_FILES = filter_source_files_from_platform(
PlatformFramework.LN882X_ARDUINO,
},
"debug_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf52.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf54l.cpp": {PlatformFramework.NRF52_ZEPHYR},
}
)
-380
View File
@@ -1,380 +0,0 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && !defined(NRF54L_SERIES)
#include <cinttypes>
#include <cstdint>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <hal/nrf_power.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")),
mac_pretty, NRF_FICR->INFO.PART, NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF,
NRF_FICR->INFO.VARIANT >> 8 & 0xFF, NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE),
NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? LOG_STR_LITERAL("") : LOG_STR_LITERAL("not ")));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
-113
View File
@@ -1,113 +0,0 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && defined(NRF54L_SERIES)
#include <cinttypes>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
// UARTE, SPIM, SPIS, TWIM and TWIS with the same number share one instance
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " UARTE00: %-3s| UARTE20: %-3s| UARTE21: %-3s| UARTE22: %-3s| UARTE30: %-3s", //
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE00), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE20),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE21), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE22),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE30));
ESP_LOGV(TAG, " SPIM00: %-3s| SPIM20: %-3s| SPIM21: %-3s| SPIM22: %-3s| SPIM30: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM00), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM20),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM21), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM22),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM30));
ESP_LOGV(TAG, " SPIS00: %-3s| SPIS20: %-3s| SPIS21: %-3s| SPIS22: %-3s| SPIS30: %-3s", //
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS00), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS20),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS21), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS22),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS30));
ESP_LOGV(TAG, " TWIM20: %-3s| TWIM21: %-3s| TWIM22: %-3s| TWIM30: %-3s", //
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM20), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM21),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM22), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM30));
ESP_LOGV(TAG, " TWIS20: %-3s| TWIS21: %-3s| TWIS22: %-3s| TWIS30: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS20), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS21),
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS22), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS30));
ESP_LOGV(TAG, " PWM20: %-3s| PWM21: %-3s| PWM22: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM20), NRF_PERIPH_ENABLED(PWM, NRF_PWM21), NRF_PERIPH_ENABLED(PWM, NRF_PWM22),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " PDM20: %-3s| PDM21: %-3s| QDEC20: %-3s| QDEC21: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM20), NRF_PERIPH_ENABLED(PDM, NRF_PDM21), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC20),
NRF_PERIPH_ENABLED(QDEC, NRF_QDEC21));
ESP_LOGV(TAG, " COMP: %-3s| LPCOMP: %-3s| AAR00: %-3s| CCM00: %-3s", //
NRF_PERIPH_ENABLED(COMP, NRF_COMP), NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP),
NRF_PERIPH_ENABLED(AAR, NRF_AAR00), NRF_PERIPH_ENABLED(CCM, NRF_CCM00));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF registers are MMIO at fixed addresses
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main regulator
const char *reg_type = (NRF_REGULATORS->VREGMAIN.DCDCEN & REGULATORS_VREGMAIN_DCDCEN_VAL_Msk) ==
(REGULATORS_VREGMAIN_DCDCEN_VAL_Enabled << REGULATORS_VREGMAIN_DCDCEN_VAL_Pos)
? "DC/DC"
: "LDO";
ESP_LOGD(TAG, "Main regulator: %s", reg_type);
pos = buf_append_str(buf, size, pos, "|Main regulator: ");
pos = buf_append_str(buf, size, pos, reg_type);
// Power-fail comparator, the threshold goes from 1.7V up in 0.1V steps
const uint32_t pofcon = NRF_REGULATORS->POFCON;
if ((pofcon & REGULATORS_POFCON_POF_Msk) == (REGULATORS_POFCON_POF_Enabled << REGULATORS_POFCON_POF_Pos)) {
const uint32_t decivolts = 17 + ((pofcon & REGULATORS_POFCON_THRESHOLD_Msk) >> REGULATORS_POFCON_THRESHOLD_Pos);
ESP_LOGD(TAG, "Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10, decivolts % 10);
pos = buf_append_printf(buf, size, pos, "|Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10,
decivolts % 10);
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
const uint32_t variant = NRF_FICR->INFO.VARIANT;
ESP_LOGD(TAG,
"nRF debug info:\n"
" Device id: 0x%08" PRIx32 "%08" PRIx32 "\n"
" Encryption root: 0x%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "%08" PRIx32 ", Identity Root: 0x%08" PRIx32
"%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "\n"
" Device address type: %s, address: %s\n"
" Part code: 0x%" PRIx32 ", version: %c%c%c%c, package: 0x%" PRIx32 "\n"
" RAM: %" PRIu32 "kB, RRAM: %" PRIu32 "kB",
NRF_FICR->INFO.DEVICEID[1], NRF_FICR->INFO.DEVICEID[0], NRF_FICR->ER[0], NRF_FICR->ER[1], NRF_FICR->ER[2],
NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2], NRF_FICR->IR[3],
(NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")), mac_pretty,
NRF_FICR->INFO.PART, static_cast<char>(variant >> 24 & 0xFF), static_cast<char>(variant >> 16 & 0xFF),
static_cast<char>(variant >> 8 & 0xFF), static_cast<char>(variant & 0xFF), NRF_FICR->INFO.PACKAGE,
NRF_FICR->INFO.RAM, NRF_FICR->INFO.RRAM);
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#endif
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
+364
View File
@@ -2,14 +2,55 @@
#ifdef USE_ZEPHYR
#include <cinttypes>
#include <climits>
#include "esphome/core/alloc_helpers.h"
#include "esphome/core/log.h"
#include <esphome/components/zephyr/reset_reason.h>
#include <zephyr/drivers/hwinfo.h>
#include <zephyr/kernel.h>
#include <hal/nrf_power.h>
#include <cstdint>
#include <zephyr/storage/flash_map.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
const char *DebugComponent::get_reset_reason_(std::span<char, RESET_REASON_BUFFER_SIZE> buffer) {
const char *buf = zephyr::get_reset_reason(buffer);
@@ -55,6 +96,329 @@ void DebugComponent::log_partition_info_() {
flash_area_foreach(fa_cb, nullptr);
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? "Random" : "Public"), mac_pretty, NRF_FICR->INFO.PART,
NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF, NRF_FICR->INFO.VARIANT >> 8 & 0xFF,
NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE), NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? "" : "not "));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// The Python side enables the statistics only for a verbose logger
#ifdef CONFIG_SCHED_THREAD_USAGE_ANALYSIS
static void log_thread_usage(const struct k_thread *thread, void *user_data) {
@@ -215,9 +215,8 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
break;
}
// Indexed: a handler (an on_write lambda) can create a service, and push_back may move the vector.
for (size_t i = 0; i < this->services_.size(); i++) { // NOLINT(modernize-loop-convert)
this->services_[i].service->gatts_event_handler(event, gatts_if, param);
for (auto &entry : this->services_) {
entry.service->gatts_event_handler(event, gatts_if, param);
}
}
+29 -15
View File
@@ -180,18 +180,23 @@ void ArduinoI2CBus::recover_() {
return;
}
// Activate input and pull up resistor for the SDA pin, so it can be read during the pulses.
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
// From the specification:
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
// device that held the bus LOW should release it sometime within
// those nine clocks."
// We don't really have to detect if SDA is stuck low. We'll simply send
// nine clock pulses here, just in case SDA is stuck. Actual checks on
// the SDA line status will be done after the clock pulses.
// Make sure that switching to output mode will make SCL low, just in
// case other code has setup the pin for a HIGH signal.
digitalWrite(this->scl_pin_, LOW); // NOLINT
delayMicroseconds(half_period_usec);
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
for (auto i = 0; i < 9 && digitalRead(this->sda_pin_) == LOW; i++) { // NOLINT
// Drive LOW. Set the level while the pin is a plain input: on RP2040 a write to an
// INPUT_PULLUP pin drives it, which would leave SCL low if the loop never runs.
pinMode(this->scl_pin_, INPUT); // NOLINT
digitalWrite(this->scl_pin_, LOW); // NOLINT
pinMode(this->scl_pin_, OUTPUT); // NOLINT
for (auto i = 0; i < 9; i++) {
// Release pull up resistor and switch to output to make the signal LOW.
pinMode(this->scl_pin_, INPUT); // NOLINT
pinMode(this->scl_pin_, OUTPUT); // NOLINT
delayMicroseconds(half_period_usec);
// Release output and activate pull up resistor to make the signal HIGH.
@@ -218,7 +223,14 @@ void ArduinoI2CBus::recover_() {
}
}
// A device still holding SDA after nine pulses cannot be freed here.
// Activate input and pull resistor for the SDA pin, so we can verify
// that SDA is pulled HIGH in the following step.
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
digitalWrite(this->sda_pin_, LOW); // NOLINT
// By now, any stuck device ought to have sent all remaining bits of its
// transaction, meaning that it should have freed up the SDA line, resulting
// in SDA being pulled up.
if (digitalRead(this->sda_pin_) == LOW) { // NOLINT
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
@@ -230,13 +242,15 @@ void ArduinoI2CBus::recover_() {
// a START or repeated START condition such that they all anticipate
// the sending of a target address, even if these START conditions are
// not positioned according to the proper format."
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
// While the 9 clock pulses from above might have drained all bits of a
// single byte within a transaction, a device might have more bytes to
// transmit. So here we'll generate a START condition to snap the device
// out of this state.
// SCL and SDA are already high at this point, so we can generate a START
// condition by making the SDA signal LOW.
delayMicroseconds(half_period_usec);
pinMode(this->sda_pin_, INPUT); // NOLINT
digitalWrite(this->sda_pin_, LOW); // NOLINT
pinMode(this->sda_pin_, OUTPUT); // NOLINT
pinMode(this->sda_pin_, INPUT); // NOLINT
pinMode(this->sda_pin_, OUTPUT); // NOLINT
// From the specification:
// "A START condition immediately followed by a STOP condition (void
+15 -5
View File
@@ -346,9 +346,14 @@ void IDFI2CBus::recover_() {
return;
}
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
for (auto i = 0; i < 9 && gpio_get_level(sda_pin) == 0; i++) {
// From the specification:
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
// device that held the bus LOW should release it sometime within
// those nine clocks."
// We don't really have to detect if SDA is stuck low. We'll simply send
// nine clock pulses here, just in case SDA is stuck. Actual checks on
// the SDA line status will be done after the clock pulses.
for (auto i = 0; i < 9; i++) {
gpio_set_level(scl_pin, 0);
delayMicroseconds(half_period_usec);
gpio_set_level(scl_pin, 1);
@@ -373,7 +378,9 @@ void IDFI2CBus::recover_() {
}
}
// A device still holding SDA after nine pulses cannot be freed here.
// By now, any stuck device ought to have sent all remaining bits of its
// transaction, meaning that it should have freed up the SDA line, resulting
// in SDA being pulled up.
if (gpio_get_level(sda_pin) == 0) {
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
@@ -385,7 +392,10 @@ void IDFI2CBus::recover_() {
// a START or repeated START condition such that they all anticipate
// the sending of a target address, even if these START conditions are
// not positioned according to the proper format."
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
// While the 9 clock pulses from above might have drained all bits of a
// single byte within a transaction, a device might have more bytes to
// transmit. So here we'll generate a START condition to snap the device
// out of this state.
// SCL and SDA are already high at this point, so we can generate a START
// condition by making the SDA signal LOW.
delayMicroseconds(half_period_usec);
+81 -63
View File
@@ -1,7 +1,5 @@
#include "ld2410.h"
#include <algorithm>
#ifdef USE_NUMBER
#include "esphome/components/number/number.h"
#endif
@@ -121,9 +119,13 @@ static constexpr uint8_t UNCONFIRMED_INDEX = static_cast<uint8_t>(BgCorrectionRe
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
using ld24xx::HEADER_FOOTER_SIZE;
using ld24xx::validate_header_footer;
// Smallest frames whose values can all be read: the last value, data footer and check, then the frame footer
static constexpr uint8_t PERIODIC_FRAME_MIN = DETECT_DISTANCE_HIGH + 3 + HEADER_FOOTER_SIZE;
static constexpr uint8_t ENGINEERING_FRAME_MIN = OUT_PIN_SENSOR + 3 + HEADER_FOOTER_SIZE;
// Data Header & Footer
static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
void LD2410Component::dump_config() {
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
@@ -229,14 +231,13 @@ void LD2410Component::restart_and_read_all_info() {
}
void LD2410Component::loop() {
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<MAX_LINE_LENGTH>(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
}
void LD2410Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
ESP_LOGV(TAG, "Sending COMMAND %02X", command);
// frame header bytes
this->write_array_progmem(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -250,27 +251,29 @@ void LD2410Component::send_command_(uint8_t command, const uint8_t *command_valu
this->write_array(command_value, command_value_len);
}
// frame footer bytes
this->write_array_progmem(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(50); // NOLINT
}
}
bool LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
void LD2410Component::handle_periodic_data_() {
// 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
// data header=0xAA, data footer=0x55, crc=0x00
if (len < 12 || frame[7] != HEADER || frame[len - 6] != FOOTER || frame[len - 5] != CHECK) {
return false;
if (this->buffer_pos_ < 12 || !ld2410::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER ||
this->buffer_data_[this->buffer_pos_ - 5] != CHECK) {
return;
}
/*
Data Type: 7th
0x01: Engineering mode
0x02: Normal mode
*/
bool engineering_mode = frame[DATA_TYPES] == 0x01;
if (len < (engineering_mode ? ENGINEERING_FRAME_MIN : PERIODIC_FRAME_MIN)) {
return false; // too short to hold the values
bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
if (this->buffer_pos_ < (engineering_mode ? ENGINEERING_FRAME_MIN : PERIODIC_FRAME_MIN)) {
return; // too short to hold the values
}
#ifdef USE_SWITCH
PUBLISH_STATE(this->engineering_mode_switch_, engineering_mode);
@@ -282,7 +285,7 @@ bool LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
0x02 = Still targets
0x03 = Moving+Still targets
*/
const uint8_t target_state = frame[TARGET_STATES];
const uint8_t target_state = this->buffer_data_[TARGET_STATES];
#ifdef USE_LD2410_BG_CORRECTION
// Pass or fail comes only from these frames
if (this->bg_correction_running_) {
@@ -309,13 +312,13 @@ bool LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
*/
#ifdef USE_SENSOR
SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
encode_uint16(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, frame[MOVING_ENERGY]);
encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY]);
SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, frame[STILL_ENERGY]);
encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY]);
SAFE_PUBLISH_SENSOR(this->detection_distance_sensor_,
encode_uint16(frame[DETECT_DISTANCE_HIGH], frame[DETECT_DISTANCE_LOW]));
encode_uint16(this->buffer_data_[DETECT_DISTANCE_HIGH], this->buffer_data_[DETECT_DISTANCE_LOW]));
if (engineering_mode) {
/*
@@ -324,18 +327,18 @@ bool LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
Moving energy: 20~28th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], frame[MOVING_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i]);
}
/*
Still energy: 29~37th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], frame[STILL_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i]);
}
/*
Light sensor: 38th bytes
*/
SAFE_PUBLISH_SENSOR(this->light_sensor_, frame[LIGHT_SENSOR]);
SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR]);
} else {
for (auto &gate_move_sensor : this->gate_move_sensors_) {
SAFE_PUBLISH_SENSOR_UNKNOWN(gate_move_sensor);
@@ -347,9 +350,9 @@ bool LD2410Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
}
#endif
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->out_pin_presence_status_binary_sensor_, engineering_mode ? frame[OUT_PIN_SENSOR] == 0x01 : false);
PUBLISH_STATE(this->out_pin_presence_status_binary_sensor_,
engineering_mode ? this->buffer_data_[OUT_PIN_SENSOR] == 0x01 : false);
#endif
return true;
}
#ifdef USE_NUMBER
@@ -360,24 +363,24 @@ void set_number_value(number::Number *n, float value) {
}
#endif
bool LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", frame[COMMAND]);
if (frame[COMMAND_STATUS] != 0x01) {
void LD2410Component::handle_ack_data_() {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
ESP_LOGE(TAG, "Invalid status");
return false;
return;
}
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
if (this->buffer_data_[8] || this->buffer_data_[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
#ifdef USE_LD2410_BG_CORRECTION
// Only a refused start ends the run; a refused poll waits for the next poll or the deadline
if (frame[COMMAND] == CMD_BG_CORRECTION_START) {
if (this->buffer_data_[COMMAND] == CMD_BG_CORRECTION_START) {
this->finish_background_correction_(BgCorrectionResult::BG_CORRECTION_RESULT_REFUSED);
}
#endif
return true;
return;
}
switch (frame[COMMAND]) {
switch (this->buffer_data_[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -397,10 +400,10 @@ bool LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_VERSION: {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -411,12 +414,12 @@ bool LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_DISTANCE_RESOLUTION: {
if (len < 11 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the resolution
}
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, frame[10]);
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, this->buffer_data_[10]);
if (!index) {
ESP_LOGW(TAG, "Unknown distance resolution %u", frame[10]);
ESP_LOGW(TAG, "Unknown distance resolution %u", this->buffer_data_[10]);
break;
}
ESP_LOGV(TAG, "Distance resolution: %s",
@@ -428,12 +431,12 @@ bool LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_LIGHT_CONTROL: {
if (len < 13 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 13 + HEADER_FOOTER_SIZE) {
break; // too short to hold the light settings
}
this->light_function_ = frame[10];
this->light_threshold_ = frame[11];
this->out_pin_level_ = frame[12];
this->light_function_ = this->buffer_data_[10];
this->light_threshold_ = this->buffer_data_[11];
this->out_pin_level_ = this->buffer_data_[12];
ESP_LOGV(TAG, "Light function: %u, threshold: %u, out pin level: %u", this->light_function_,
this->light_threshold_, this->out_pin_level_);
#ifdef USE_SELECT
@@ -446,11 +449,11 @@ bool LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
}
case CMD_QUERY_MAC_ADDRESS: {
if (len < 20) {
if (this->buffer_pos_ < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[10], this->mac_address_);
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
@@ -474,7 +477,7 @@ bool LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_BG_CORRECTION_QUERY: {
const uint8_t status = frame[10];
const uint8_t status = this->buffer_data_[10];
ESP_LOGV(TAG, "Background correction status: %u", status);
// The module stops at idle after a fail frame; idle before the run starts is ignored
if (status == BG_CORRECTION_COMPLETED ||
@@ -503,55 +506,70 @@ bool LD2410Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY: { // Query parameters response
if (len < 38) {
if (this->buffer_pos_ < 38) {
break; // too short to hold the parameters
}
if (frame[10] != HEADER)
return true; // value head=0xAA
if (this->buffer_data_[10] != HEADER)
return; // value head=0xAA
#ifdef USE_NUMBER
/*
Moving distance range: 13th byte
Still distance range: 14th byte
*/
set_number_value(this->max_move_distance_gate_number_, frame[12]);
set_number_value(this->max_still_distance_gate_number_, frame[13]);
set_number_value(this->max_move_distance_gate_number_, this->buffer_data_[12]);
set_number_value(this->max_still_distance_gate_number_, this->buffer_data_[13]);
/*
Moving Sensitivities: 15~23th bytes
*/
for (size_t i = 0; i < TOTAL_GATES; i++) {
set_number_value(this->gate_move_threshold_numbers_[i], frame[14 + i]);
set_number_value(this->gate_move_threshold_numbers_[i], this->buffer_data_[14 + i]);
}
/*
Still Sensitivities: 24~32th bytes
*/
for (size_t i = 0; i < TOTAL_GATES; i++) {
set_number_value(this->gate_still_threshold_numbers_[i], frame[23 + i]);
set_number_value(this->gate_still_threshold_numbers_[i], this->buffer_data_[23 + i]);
}
/*
None Duration: 33~34th bytes
*/
set_number_value(this->timeout_number_, encode_uint16(frame[33], frame[32]));
set_number_value(this->timeout_number_, encode_uint16(this->buffer_data_[33], this->buffer_data_[32]));
#endif
break;
}
default:
break;
}
return true;
}
// Handles the frame when its footer is in place; returns false otherwise
bool LD2410Component::handle_frame_(const uint8_t *frame, uint8_t len) {
if (!ld24xx::has_footer(frame, len)) {
ESP_LOGW(TAG, "Invalid footer");
void LD2410Component::readline_(int readch) {
if (readch < 0) {
return; // No data available
}
// Periodic and command frames both carry their count after the header
ld24xx::feed_frame_byte(
this->buffer_data_, this->buffer_pos_, readch, DATA_FRAME_HEADER, ld24xx::cmd_frame_length,
[this](uint8_t frame_len) { return this->handle_frame_(frame_len); }, []() { ESP_LOGW(TAG, "Invalid length"); });
}
// Dispatches the frame of frame_len bytes at the start of the buffer when its footer is in place
bool LD2410Component::handle_frame_(uint8_t frame_len) {
this->buffer_pos_ = frame_len; // the handlers take the frame length from here
const uint8_t *tail = &this->buffer_data_[frame_len - HEADER_FOOTER_SIZE];
if (this->buffer_data_[0] == DATA_FRAME_HEADER[0]) {
if (!ld2410::validate_header_footer(DATA_FRAME_FOOTER, tail)) {
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->handle_periodic_data_();
return true;
}
if (!ld2410::validate_header_footer(CMD_FRAME_FOOTER, tail)) {
return false;
}
if (frame[0] == ld24xx::DataFrameFormat::FIRST) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
return this->handle_periodic_data_(frame, len);
}
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
return this->handle_ack_data_(frame, len);
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
}
void LD2410Component::set_config_mode_(bool enable) {
+6 -6
View File
@@ -24,7 +24,6 @@
#endif
#include "esphome/components/ld24xx/ld24xx.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include <array>
@@ -146,9 +145,10 @@ class LD2410Component final : public Component, public uart::UARTDevice {
protected:
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len);
void set_config_mode_(bool enable);
bool handle_periodic_data_(const uint8_t *frame, uint8_t len);
bool handle_ack_data_(const uint8_t *frame, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
void readline_(int readch);
void query_parameters_();
void get_version_();
void get_mac_();
@@ -161,11 +161,11 @@ class LD2410Component final : public Component, public uart::UARTDevice {
void publish_calibration_result_(BgCorrectionResult result);
#endif
uint32_t last_rx_{0};
uint8_t light_function_ = 0;
uint8_t light_threshold_ = 0;
uint8_t out_pin_level_ = 0;
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat> reader_;
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
uint8_t buffer_data_[MAX_LINE_LENGTH];
uint8_t mac_address_[MAC_ADDRESS_SIZE] = {0, 0, 0, 0, 0, 0};
uint8_t version_[6] = {0, 0, 0, 0, 0, 0};
bool bluetooth_on_{false};
+139 -40
View File
@@ -9,12 +9,16 @@ namespace esphome::ld2410s {
ESPHOME_LOG_TAG(TAG, "ld2410s");
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
static constexpr uint8_t SHORT_DATA_FRAME_FOOTER = 0x62;
using ld24xx::HEADER_FOOTER_SIZE;
// After the header and the two byte length
static constexpr uint8_t LONG_PAYLOAD_POS = ld24xx::PayloadLength::KNOWN_AT;
static constexpr uint8_t SHORT_DATA_FRAME_HEADER = 0x6E;
static constexpr uint8_t SHORT_DATA_FRAME_FOOTER[] PROGMEM = {0x62};
static constexpr uint8_t SHORT_DATA_FRAME_SIZE = 5; // header, state, distance low, distance high, footer
static constexpr uint8_t STD_DATA_FRAME_HEADER[] PROGMEM = {0xF4, 0xF3, 0xF2, 0xF1};
static constexpr uint8_t STD_DATA_FRAME_FOOTER[] PROGMEM = {0xF8, 0xF7, 0xF6, 0xF5};
static constexpr uint8_t CMD_FRAME_HEADER[] PROGMEM = {0xFD, 0xFC, 0xFB, 0xFA};
static constexpr uint8_t CMD_FRAME_FOOTER[] PROGMEM = {0x04, 0x03, 0x02, 0x01};
static constexpr uint8_t LONG_HEADER_SIZE = 4;
static constexpr uint8_t LENGTH_FIELD_SIZE = 2;
static constexpr uint8_t LONG_PAYLOAD_POS = LONG_HEADER_SIZE + LENGTH_FIELD_SIZE;
static constexpr uint16_t CMD_CONFIRMATION = 0x0100; // set in the command word of an acknowledgement
static constexpr uint16_t CONFIG_MODE_START_CMD = 0x00FF;
@@ -94,11 +98,10 @@ void LD2410SComponent::dump_config() {
}
void LD2410SComponent::loop() {
const uint32_t now = App.get_loop_component_start_time();
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
if (!this->read_frames<16>(this->reader_, handler, now, this->last_rx_)) {
if (!this->read_available<16>([this](uint8_t b) { this->receive_byte_(b); })) {
ESP_LOGV(TAG, "UART read failed");
}
const uint32_t now = App.get_loop_component_start_time();
if (this->sequence_ == nullptr) {
if (!this->init_done_) {
this->start_sequence_(INIT_SEQUENCE, INIT_SEQUENCE_LENGTH, now);
@@ -208,7 +211,7 @@ void LD2410SComponent::run_sequence_(uint32_t now) {
void LD2410SComponent::send_command_(uint16_t command) {
uint8_t frame[CMD_FRAME_MAX_SIZE];
progmem_memcpy(frame, CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
progmem_memcpy(frame, CMD_FRAME_HEADER, LONG_HEADER_SIZE);
uint8_t pos = LONG_PAYLOAD_POS;
put_le16(frame + pos, command);
pos += 2;
@@ -237,41 +240,138 @@ void LD2410SComponent::send_command_(uint16_t command) {
default:
break;
}
put_le16(frame + HEADER_FOOTER_SIZE, pos - LONG_PAYLOAD_POS); // payload length
put_le16(frame + LONG_HEADER_SIZE, pos - LONG_PAYLOAD_POS); // payload length
progmem_memcpy(&frame[pos], CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
pos += sizeof(CMD_FRAME_FOOTER);
this->write_array(frame, pos);
ESP_LOGVV_HEX(TAG, frame, pos, CMD_FRAME_MAX_SIZE, "> %s");
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
char hex_buf[format_hex_pretty_size(CMD_FRAME_MAX_SIZE)];
ESP_LOGVV(TAG, "> %s", format_hex_pretty_to(hex_buf, frame, pos, ' '));
#endif
}
bool LD2410SComponent::handle_frame_(const uint8_t *frame, uint8_t len) {
const uint8_t type = frame[0];
const bool short_frame = type == ShortDataFrameFormat::FIRST;
if (short_frame ? frame[len - 1] != SHORT_DATA_FRAME_FOOTER : !ld24xx::has_footer(frame, len)) {
ESP_LOGV_HEX(TAG, frame, len, RX_BUFFER_SIZE, "Footer does not match header: %s");
void LD2410SComponent::receive_byte_(uint8_t byte) {
if (this->rx_len_ >= RX_BUFFER_SIZE) {
this->reset_frame_();
}
this->rx_buffer_[this->rx_len_++] = byte;
if (this->frame_type_ == FrameType::NONE) {
if (this->rx_len_ == 1 && byte == SHORT_DATA_FRAME_HEADER) {
this->frame_type_ = FrameType::SHORT_DATA;
this->expected_len_ = SHORT_DATA_FRAME_SIZE;
return;
}
// The two long headers are told apart once all four bytes are in
uint8_t std_header[LONG_HEADER_SIZE];
uint8_t cmd_header[LONG_HEADER_SIZE];
progmem_memcpy(std_header, STD_DATA_FRAME_HEADER, LONG_HEADER_SIZE);
progmem_memcpy(cmd_header, CMD_FRAME_HEADER, LONG_HEADER_SIZE);
const bool std_prefix = memcmp(this->rx_buffer_, std_header, this->rx_len_) == 0;
const bool cmd_prefix = memcmp(this->rx_buffer_, cmd_header, this->rx_len_) == 0;
if (std_prefix || cmd_prefix) {
if (this->rx_len_ == LONG_HEADER_SIZE) {
this->frame_type_ = std_prefix ? FrameType::STD_DATA : FrameType::COMMAND;
}
return;
}
// Not a header: drop what was collected, and try this byte as the start of the next frame
const bool retry = this->rx_len_ > 1;
this->reset_frame_();
if (retry) {
this->receive_byte_(byte);
}
return;
}
if (this->expected_len_ == 0) {
if (this->rx_len_ < LONG_PAYLOAD_POS) {
return;
}
// Standard data and command frames carry a little-endian payload length after the header
const uint16_t payload_len =
encode_uint16(this->rx_buffer_[LONG_HEADER_SIZE + 1], this->rx_buffer_[LONG_HEADER_SIZE]);
if (payload_len > RX_BUFFER_SIZE - LONG_PAYLOAD_POS - sizeof(CMD_FRAME_FOOTER)) {
ESP_LOGV(TAG, "Dropping frame with a %u byte payload, larger than the receive buffer", payload_len);
this->count_dropped_frame_();
this->reset_frame_();
return;
}
this->expected_len_ = LONG_PAYLOAD_POS + payload_len + sizeof(CMD_FRAME_FOOTER);
return;
}
if (this->rx_len_ < this->expected_len_) {
return;
}
if (this->handle_frame_() || this->rescanning_) {
this->reset_frame_();
return;
}
// A truncated long frame swallowed the bytes that followed it; try them again as new frames, once
uint8_t rest[RX_BUFFER_SIZE];
const uint8_t rest_len = this->rx_len_ - 1;
memcpy(rest, &this->rx_buffer_[1], rest_len);
this->reset_frame_();
this->rescanning_ = true;
for (uint8_t i = 0; i < rest_len; i++) {
this->receive_byte_(rest[i]);
}
this->rescanning_ = false;
}
bool LD2410SComponent::handle_frame_() {
const uint8_t *footer_src;
uint8_t footer_size = sizeof(CMD_FRAME_FOOTER);
uint8_t payload_pos = LONG_PAYLOAD_POS;
switch (this->frame_type_) {
case FrameType::SHORT_DATA:
footer_src = SHORT_DATA_FRAME_FOOTER;
footer_size = sizeof(SHORT_DATA_FRAME_FOOTER);
payload_pos = 1;
break;
case FrameType::STD_DATA:
footer_src = STD_DATA_FRAME_FOOTER;
break;
default:
footer_src = CMD_FRAME_FOOTER;
break;
}
uint8_t footer[sizeof(CMD_FRAME_FOOTER)];
progmem_memcpy(footer, footer_src, footer_size);
if (memcmp(&this->rx_buffer_[this->rx_len_ - footer_size], footer, footer_size) != 0) {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(RX_BUFFER_SIZE)];
ESP_LOGV(TAG, "Footer does not match header: %s",
format_hex_pretty_to(hex_buf, this->rx_buffer_, this->rx_len_, ' '));
#endif
this->count_dropped_frame_();
return false;
}
const uint8_t payload_pos = short_frame ? 1 : LONG_PAYLOAD_POS;
const uint8_t *payload = &frame[payload_pos];
const uint16_t payload_len = len - payload_pos - (short_frame ? 1 : HEADER_FOOTER_SIZE);
if (type == ld24xx::CmdFrameFormat::FIRST) {
return this->handle_command_ack_(payload, payload_len);
const uint8_t *payload = &this->rx_buffer_[payload_pos];
const uint16_t payload_len = this->rx_len_ - payload_pos - footer_size;
switch (this->frame_type_) {
case FrameType::SHORT_DATA:
case FrameType::STD_DATA:
if (!this->handle_data_frame_(payload, payload_len)) {
this->count_dropped_frame_();
break;
}
this->last_frame_at_ = App.get_loop_component_start_time();
this->dropped_frames_ = 0;
break;
default:
this->handle_command_ack_(payload, payload_len);
break;
}
if (!this->handle_data_frame_(payload, payload_len, type == ld24xx::DataFrameFormat::FIRST)) {
this->count_dropped_frame_();
return false;
}
this->last_frame_at_ = App.get_loop_component_start_time();
this->dropped_frames_ = 0;
return true;
}
bool LD2410SComponent::handle_data_frame_(const uint8_t *payload, uint16_t len, bool standard) {
bool LD2410SComponent::handle_data_frame_(const uint8_t *payload, uint16_t len) {
// Short frames carry [state][distance low][distance high]; standard frames put a type byte first, and the
// module only sends them before the init sequence switches it to minimal output
const uint8_t *data = payload;
if (standard) {
if (this->frame_type_ == FrameType::STD_DATA) {
if (len < 4 || payload[0] != DATA_TYPE_STANDARD) {
if (len >= 1) {
ESP_LOGV(TAG, "Ignoring data frame type %02X", payload[0]);
@@ -292,21 +392,21 @@ bool LD2410SComponent::handle_data_frame_(const uint8_t *payload, uint16_t len,
return true;
}
bool LD2410SComponent::handle_command_ack_(const uint8_t *payload, uint16_t len) {
void LD2410SComponent::handle_command_ack_(const uint8_t *payload, uint16_t len) {
if (len < 4) {
ESP_LOGV(TAG, "Acknowledgement too short (%u bytes)", len);
return false;
return;
}
const uint16_t command_word = encode_uint16(payload[1], payload[0]);
const uint16_t ack = encode_uint16(payload[3], payload[2]);
if (!this->awaiting_ack_) {
ESP_LOGV(TAG, "Unexpected acknowledgement %04X", command_word);
return true;
return;
}
const uint16_t command = this->current_command_();
if (command_word != (command | CMD_CONFIRMATION)) {
ESP_LOGV(TAG, "Unexpected acknowledgement %04X", command_word);
return true;
return;
}
#ifdef USE_LD2410S_PARAMETERS
if (ack != 0 && command == PARAMETERS_WRITE_CMD) {
@@ -315,29 +415,29 @@ bool LD2410SComponent::handle_command_ack_(const uint8_t *payload, uint16_t len)
ESP_LOGW(TAG, "Module rejected the parameters, ack %04X", ack);
this->send_command_(CONFIG_MODE_END_CMD);
this->restart_init_(App.get_loop_component_start_time() + COMMAND_GAP_MS);
return true;
return;
}
#endif
if (ack != 0) {
// Leave the command pending so the timeout resends it
ESP_LOGW(TAG, "Module rejected command %04X, ack %04X", command, ack);
return true;
return;
}
// A short answer leaves the read pending the same way, so init cannot finish without the values
#ifdef USE_LD2410S_PARAMETERS
if (command == PARAMETERS_READ_CMD && !this->handle_parameters_(&payload[4], len - 4))
return false;
return;
#endif
#ifdef USE_LD2410S_VERSION
if (command == VERSION_READ_CMD && !this->handle_version_(&payload[4], len - 4))
return false;
return;
#endif
this->awaiting_ack_ = false;
this->step_timeouts_ = 0;
const uint32_t now = App.get_loop_component_start_time();
this->next_send_at_ = now + COMMAND_GAP_MS;
if (++this->step_ < this->sequence_len_) {
return true;
return;
}
const bool was_init = this->sequence_ == INIT_SEQUENCE;
this->sequence_ = nullptr;
@@ -347,7 +447,6 @@ bool LD2410SComponent::handle_command_ack_(const uint8_t *payload, uint16_t len)
this->last_frame_at_ = now;
this->status_clear_warning();
}
return true;
}
#ifdef USE_LD2410S_PARAMETERS
+18 -10
View File
@@ -2,7 +2,6 @@
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "esphome/components/uart/uart.h"
#ifdef USE_BINARY_SENSOR
@@ -10,8 +9,8 @@
#endif
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor.h"
#endif
#include "esphome/components/ld24xx/ld24xx.h"
#endif
#ifdef USE_LD2410S_VERSION
#include "esphome/components/text_sensor/text_sensor.h"
#endif
@@ -27,8 +26,6 @@ namespace esphome::ld2410s {
// Largest frame read here is the standard data frame: 4 header + 2 length + payload + 4 footer
static constexpr size_t RX_BUFFER_SIZE = 96;
static_assert(RX_BUFFER_SIZE <= 255, "frame lengths are kept in a byte");
// Minimal output: header, state, distance low, distance high, footer
using ShortDataFrameFormat = FrameFormat<FrameHeader<0x6E>, FrameFixedLength<5>>;
/// The module's common parameters, in the order the parameter read answers them
enum class Parameter : uint8_t {
@@ -81,11 +78,14 @@ class LD2410SComponent final : public Component, public uart::UARTDevice {
#endif
protected:
/// Returns false for bytes that are not a real frame.
bool handle_frame_(const uint8_t *frame, uint8_t len);
enum class FrameType : uint8_t { NONE, SHORT_DATA, STD_DATA, COMMAND };
void receive_byte_(uint8_t byte);
/// Returns false when the footer does not match, so the bytes can be scanned again.
bool handle_frame_();
/// Returns false for a data frame whose state byte is impossible, so it counts as dropped.
bool handle_data_frame_(const uint8_t *payload, uint16_t len, bool standard);
bool handle_command_ack_(const uint8_t *payload, uint16_t len);
bool handle_data_frame_(const uint8_t *payload, uint16_t len);
void handle_command_ack_(const uint8_t *payload, uint16_t len);
#ifdef USE_LD2410S_PARAMETERS
bool handle_parameters_(const uint8_t *values, uint16_t len);
#endif
@@ -97,6 +97,11 @@ class LD2410SComponent final : public Component, public uart::UARTDevice {
this->dropped_frames_++;
}
}
void reset_frame_() {
this->rx_len_ = 0;
this->expected_len_ = 0;
this->frame_type_ = FrameType::NONE;
}
void start_sequence_(const uint16_t *sequence, uint8_t length, uint32_t now);
void restart_init_(uint32_t at);
void run_sequence_(uint32_t now);
@@ -114,16 +119,19 @@ class LD2410SComponent final : public Component, public uart::UARTDevice {
const uint16_t *sequence_{nullptr}; // PROGMEM; null while nothing is being sent
uint32_t next_send_at_{0};
uint32_t last_frame_at_{0};
uint32_t last_rx_{0};
#ifdef USE_LD2410S_PARAMETERS
uint8_t parameters_[PARAMETER_COUNT]{}; // all fit a byte: gates, seconds, tenths of a hertz, speed
#endif
LengthFrameReader<RX_BUFFER_SIZE, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat, ShortDataFrameFormat> reader_;
uint8_t rx_buffer_[RX_BUFFER_SIZE];
uint8_t rx_len_{0};
uint8_t expected_len_{0};
uint8_t sequence_len_{0};
uint8_t step_{0};
uint8_t step_timeouts_{0};
uint8_t dropped_frames_{0}; // since the last accepted data frame, saturates at 255
FrameType frame_type_{FrameType::NONE};
bool awaiting_ack_{false};
bool rescanning_{false};
bool init_done_{false};
#ifdef USE_LD2410S_PARAMETERS
bool parameters_known_{false}; // the module answered the parameter read at least once
+83 -64
View File
@@ -113,9 +113,13 @@ static constexpr uint8_t STILL_BITMASK = 0x02;
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
using ld24xx::HEADER_FOOTER_SIZE;
using ld24xx::validate_header_footer;
// Smallest frames whose values can all be read: the last value, data footer and check, then the frame footer
static constexpr uint8_t PERIODIC_FRAME_MIN = STILL_ENERGY + 3 + HEADER_FOOTER_SIZE;
static constexpr uint8_t ENGINEERING_FRAME_MIN = LIGHT_SENSOR + 3 + HEADER_FOOTER_SIZE;
// Data Header & Footer
static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xF4, 0xF3, 0xF2, 0xF1};
static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0xF8, 0xF7, 0xF6, 0xF5};
static constexpr uint8_t GATE_SENS_ACK_SIZE = ACK_PAYLOAD + TOTAL_GATES + HEADER_FOOTER_SIZE;
void LD2412Component::dump_config() {
@@ -230,14 +234,13 @@ void LD2412Component::restart_and_read_all_info() {
}
void LD2412Component::loop() {
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<MAX_LINE_LENGTH>(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
}
void LD2412Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
ESP_LOGV(TAG, "Sending COMMAND %02X", command);
// frame header bytes
this->write_array_progmem(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
this->write_array(CMD_FRAME_HEADER, HEADER_FOOTER_SIZE);
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -252,7 +255,7 @@ void LD2412Component::send_command_(uint8_t command, const uint8_t *command_valu
this->write_array(command_value, command_value_len);
}
// frame footer bytes
this->write_array_progmem(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
this->write_array(CMD_FRAME_FOOTER, HEADER_FOOTER_SIZE);
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(30); // NOLINT
@@ -260,20 +263,21 @@ void LD2412Component::send_command_(uint8_t command, const uint8_t *command_valu
delay(20); // NOLINT
}
bool LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
void LD2412Component::handle_periodic_data_() {
// 4 frame header bytes + 2 length bytes + 1 data end byte + 1 crc byte + 4 frame footer bytes
// data header=0xAA, data footer=0x55, crc=0x00
if (len < 12 || frame[7] != HEADER || frame[len - 6] != FOOTER) {
return false;
if (this->buffer_pos_ < 12 || !ld2412::validate_header_footer(DATA_FRAME_HEADER, this->buffer_data_) ||
this->buffer_data_[7] != HEADER || this->buffer_data_[this->buffer_pos_ - 6] != FOOTER) {
return;
}
/*
Data Type: 7th
0x01: Engineering mode
0x02: Normal mode
*/
bool engineering_mode = frame[DATA_TYPES] == 0x01;
if (len < PERIODIC_FRAME_MIN) {
return false; // too short to hold the values
bool engineering_mode = this->buffer_data_[DATA_TYPES] == 0x01;
if (this->buffer_pos_ < PERIODIC_FRAME_MIN) {
return; // too short to hold the values
}
#ifdef USE_SWITCH
PUBLISH_STATE(this->engineering_mode_switch_, engineering_mode);
@@ -287,7 +291,7 @@ bool LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
0x02 = Still targets
0x03 = Moving+Still targets
*/
char target_state = frame[TARGET_STATES];
char target_state = this->buffer_data_[TARGET_STATES];
PUBLISH_STATE(this->target_binary_sensor_, target_state != 0x00);
PUBLISH_STATE(this->moving_target_binary_sensor_, target_state & MOVE_BITMASK);
PUBLISH_STATE(this->still_target_binary_sensor_, target_state & STILL_BITMASK);
@@ -301,23 +305,24 @@ bool LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
*/
#ifdef USE_SENSOR
SAFE_PUBLISH_SENSOR(this->moving_target_distance_sensor_,
encode_uint16(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, frame[MOVING_ENERGY]);
encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->moving_target_energy_sensor_, this->buffer_data_[MOVING_ENERGY]);
SAFE_PUBLISH_SENSOR(this->still_target_distance_sensor_,
encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, frame[STILL_ENERGY]);
encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]));
SAFE_PUBLISH_SENSOR(this->still_target_energy_sensor_, this->buffer_data_[STILL_ENERGY]);
if (this->detection_distance_sensor_.has_sensor()) {
int new_detect_distance = 0;
if (target_state != 0x00 && (target_state & MOVE_BITMASK)) {
new_detect_distance = encode_uint16(frame[MOVING_TARGET_HIGH], frame[MOVING_TARGET_LOW]);
new_detect_distance =
encode_uint16(this->buffer_data_[MOVING_TARGET_HIGH], this->buffer_data_[MOVING_TARGET_LOW]);
} else if (target_state != 0x00) {
new_detect_distance = encode_uint16(frame[STILL_TARGET_HIGH], frame[STILL_TARGET_LOW]);
new_detect_distance = encode_uint16(this->buffer_data_[STILL_TARGET_HIGH], this->buffer_data_[STILL_TARGET_LOW]);
}
this->detection_distance_sensor_.publish_state_if_not_dup(new_detect_distance);
}
if (engineering_mode) {
if (len < ENGINEERING_FRAME_MIN) {
ESP_LOGW(TAG, "Engineering mode packet too short: %u", len);
if (this->buffer_pos_ < ENGINEERING_FRAME_MIN) {
ESP_LOGW(TAG, "Engineering mode packet too short: %u", this->buffer_pos_);
} else {
/*
Moving distance range: 18th byte
@@ -325,18 +330,18 @@ bool LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
Moving energy: 20~28th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], frame[MOVING_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_move_sensors_[i], this->buffer_data_[MOVING_SENSOR_START + i]);
}
/*
Still energy: 29~37th bytes
*/
for (uint8_t i = 0; i < TOTAL_GATES; i++) {
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], frame[STILL_SENSOR_START + i]);
SAFE_PUBLISH_SENSOR(this->gate_still_sensors_[i], this->buffer_data_[STILL_SENSOR_START + i]);
}
/*
Light sensor value
*/
SAFE_PUBLISH_SENSOR(this->light_sensor_, frame[LIGHT_SENSOR]);
SAFE_PUBLISH_SENSOR(this->light_sensor_, this->buffer_data_[LIGHT_SENSOR]);
}
} else {
for (auto &gate_move_sensor : this->gate_move_sensors_) {
@@ -354,7 +359,6 @@ bool LD2412Component::handle_periodic_data_(const uint8_t *frame, uint8_t len) {
this->query_dynamic_background_correction_();
this->set_config_mode_(false);
}
return true;
}
#ifdef USE_NUMBER
@@ -374,18 +378,18 @@ static constexpr uint32_t GATE_QUERY_TIMEOUT_ID = 0;
static constexpr uint32_t BASIC_CONF_TIMEOUT_ID = 2;
static constexpr uint32_t QUERY_TIMEOUT_MS = 2000;
bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", frame[COMMAND]);
if (frame[COMMAND_STATUS] != 0x01) {
void LD2412Component::handle_ack_data_() {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
ESP_LOGW(TAG, "Invalid status");
return false;
return;
}
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
return true;
if (this->buffer_data_[8] || this->buffer_data_[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
return;
}
switch (frame[COMMAND]) {
switch (this->buffer_data_[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -405,10 +409,10 @@ bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_VERSION: {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -418,12 +422,12 @@ bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
}
case CMD_QUERY_DISTANCE_RESOLUTION: {
if (len < 11 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the resolution
}
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, frame[10]);
const auto index = ld24xx::find_index(DISTANCE_RESOLUTIONS, this->buffer_data_[10]);
if (!index) {
ESP_LOGW(TAG, "Unknown distance resolution %u", frame[10]);
ESP_LOGW(TAG, "Unknown distance resolution %u", this->buffer_data_[10]);
break;
}
ESP_LOGV(TAG, "Distance resolution: %s",
@@ -435,11 +439,11 @@ bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_LIGHT_CONTROL: {
if (len < 12 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 12 + HEADER_FOOTER_SIZE) {
break; // too short to hold the light settings
}
this->light_function_ = frame[10];
this->light_threshold_ = frame[11];
this->light_function_ = this->buffer_data_[10];
this->light_threshold_ = this->buffer_data_[11];
ESP_LOGV(TAG, "Light function: %u, threshold: %u", this->light_function_, this->light_threshold_);
#ifdef USE_SELECT
PUBLISH_STATE(this->light_function_select_, static_cast<size_t>(this->light_function_));
@@ -451,11 +455,11 @@ bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_MAC_ADDRESS: {
if (len < 20) {
if (this->buffer_pos_ < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[10], this->mac_address_);
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
@@ -474,11 +478,11 @@ bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_DYNAMIC_BACKGROUND_CORRECTION: {
if (len < 11 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the state
}
ESP_LOGV(TAG, "Handled query dynamic background correction");
bool dynamic_background_correction_active = (frame[10] != 0x00);
bool dynamic_background_correction_active = (this->buffer_data_[10] != 0x00);
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->dynamic_background_correction_status_binary_sensor_, dynamic_background_correction_active);
#endif
@@ -497,17 +501,17 @@ bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
case CMD_QUERY_MOTION_GATE_SENS:
case CMD_QUERY_STATIC_GATE_SENS: {
#ifdef USE_NUMBER
if (len != GATE_SENS_ACK_SIZE) {
if (this->buffer_pos_ != GATE_SENS_ACK_SIZE) {
// A length this driver does not know
ESP_LOGW(TAG, "Dropping gate threshold answer of %u bytes", len);
return true;
ESP_LOGW(TAG, "Dropping gate threshold answer of %u bytes", this->buffer_pos_);
return;
}
const bool motion = frame[COMMAND] == CMD_QUERY_MOTION_GATE_SENS;
const bool motion = this->buffer_data_[COMMAND] == CMD_QUERY_MOTION_GATE_SENS;
GateThresholds &group = this->gate_thresholds_(motion);
// True only while a held-back write waits for this answer
const bool pending = this->cancel_timeout(GATE_QUERY_TIMEOUT_ID + motion);
for (size_t i = 0; i < TOTAL_GATES; i++) {
group.last_read[i] = frame[ACK_PAYLOAD + i];
group.last_read[i] = this->buffer_data_[ACK_PAYLOAD + i];
// The pending write's user values must survive the answer
if (!pending || !has_value(group.numbers[i])) {
set_number_value(group.numbers[i], group.last_read[i]);
@@ -524,17 +528,17 @@ bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_BASIC_CONF: { // Query parameters response
if (len < 15 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 15 + HEADER_FOOTER_SIZE) {
break; // too short to hold the configuration
}
// True only while a held-back write waits for this answer
const bool pending = this->cancel_timeout(BASIC_CONF_TIMEOUT_ID);
this->basic_conf_read_ = true;
// Min gate: 9th byte, max gate: 10th byte, timeout: 11~12th bytes, output pin level: 13th byte
this->min_gate_ = frame[10];
this->max_gate_ = frame[11];
this->timeout_ = encode_uint16(frame[13], frame[12]);
this->out_pin_level_ = frame[14];
this->min_gate_ = this->buffer_data_[10];
this->max_gate_ = this->buffer_data_[11];
this->timeout_ = encode_uint16(this->buffer_data_[13], this->buffer_data_[12]);
this->out_pin_level_ = this->buffer_data_[14];
ESP_LOGV(TAG, "min_distance_gate_number_: %u, max_distance_gate_number_ %u", this->min_gate_, this->max_gate_);
ESP_LOGV(TAG, "timeout_number_: %u", this->timeout_);
// The pending write's user values must survive the answer
@@ -564,21 +568,36 @@ bool LD2412Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
default:
break;
}
return true;
}
// Handles the frame when its footer is in place; returns false otherwise
bool LD2412Component::handle_frame_(const uint8_t *frame, uint8_t len) {
if (!ld24xx::has_footer(frame, len)) {
ESP_LOGW(TAG, "Invalid footer");
void LD2412Component::readline_(int readch) {
if (readch < 0) {
return; // No data available
}
// Periodic and command frames both carry their count after the header
ld24xx::feed_frame_byte(
this->buffer_data_, this->buffer_pos_, readch, DATA_FRAME_HEADER, ld24xx::cmd_frame_length,
[this](uint8_t frame_len) { return this->handle_frame_(frame_len); }, []() { ESP_LOGW(TAG, "Invalid length"); });
}
// Dispatches the frame of frame_len bytes at the start of the buffer when its footer is in place
bool LD2412Component::handle_frame_(uint8_t frame_len) {
this->buffer_pos_ = frame_len; // the handlers take the frame length from here
const uint8_t *tail = &this->buffer_data_[frame_len - HEADER_FOOTER_SIZE];
if (this->buffer_data_[0] == DATA_FRAME_HEADER[0]) {
if (!ld2412::validate_header_footer(DATA_FRAME_FOOTER, tail)) {
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->handle_periodic_data_();
return true;
}
if (!ld2412::validate_header_footer(CMD_FRAME_FOOTER, tail)) {
return false;
}
if (frame[0] == ld24xx::DataFrameFormat::FIRST) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
return this->handle_periodic_data_(frame, len);
}
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
return this->handle_ack_data_(frame, len);
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
}
void LD2412Component::set_config_mode_(bool enable) {
+6 -6
View File
@@ -25,7 +25,6 @@
#include "esphome/components/ld24xx/ld24xx.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/automation.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include <array>
@@ -135,10 +134,11 @@ class LD2412Component final : public Component, public uart::UARTDevice {
protected:
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len);
void set_config_mode_(bool enable);
bool handle_periodic_data_(const uint8_t *frame, uint8_t len);
bool handle_ack_data_(const uint8_t *frame, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
void basic_conf_timeout_();
void readline_(int readch);
void query_parameters_();
void get_version_();
void get_mac_();
@@ -160,7 +160,6 @@ class LD2412Component final : public Component, public uart::UARTDevice {
void gate_query_timeout_(bool motion);
#endif
uint32_t last_rx_{0};
uint8_t light_function_ = 0;
uint8_t light_threshold_ = 0;
// Basic configuration as last reported by the module; resent for entities that are not configured
@@ -169,7 +168,8 @@ class LD2412Component final : public Component, public uart::UARTDevice {
uint8_t min_gate_ = 1;
uint8_t max_gate_ = TOTAL_GATES;
uint8_t out_pin_level_ = 1;
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, ld24xx::DataFrameFormat> reader_;
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
uint8_t buffer_data_[MAX_LINE_LENGTH];
uint8_t mac_address_[MAC_ADDRESS_SIZE] = {0, 0, 0, 0, 0, 0};
uint8_t version_[6] = {0, 0, 0, 0, 0, 0};
bool bluetooth_on_{false};
+89 -54
View File
@@ -71,10 +71,14 @@ static constexpr uint8_t CMD_SET_ZONE = 0xC2;
using ld24xx::CMD_FRAME_FOOTER;
using ld24xx::CMD_FRAME_HEADER;
using ld24xx::HEADER_FOOTER_SIZE;
static constexpr uint8_t PERIODIC_FRAME_FOOTER[2] = {0x55, 0xCC};
using ld24xx::validate_header_footer;
// Data Header & Footer
static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xAA, 0xFF, 0x03, 0x00};
static constexpr uint8_t DATA_FRAME_FOOTER[2] = {0x55, 0xCC};
// Successful zone query ACK: header (4) + length (2) + command/status (2) + result (2) + zone type (2) +
// 3 zones * 8 + footer (4).
static constexpr uint8_t ZONE_ACK_FRAME_SIZE = 40;
static constexpr uint8_t PERIODIC_FRAME_SIZE = 30; // header, three targets of 8 bytes, footer
static inline uint32_t convert_seconds_to_ms(uint16_t value) { return (uint32_t) value * 1000; };
@@ -100,10 +104,22 @@ static inline int16_t decode_speed(uint8_t low_byte, uint8_t high_byte) {
return speed * 10; // mm/s
}
// Length of the frame that opens the buffer: periodic frames are fixed size, command frames carry their
// payload length after the header. readline_ only buffers a valid header, so its first byte names it.
// Returns 0 while the length field has not arrived yet.
static inline uint32_t frame_length(const uint8_t *buffer, uint8_t len) {
if (len < HEADER_FOOTER_SIZE) {
return 0;
}
if (buffer[0] == DATA_FRAME_HEADER[0]) {
return PERIODIC_FRAME_SIZE;
}
return ld24xx::cmd_frame_length(buffer, len);
}
void LD2450Component::setup() {
// The first frame is due link_timeout after the boot restart's grace window
this->last_frame_ms_ = App.get_loop_component_start_time();
this->last_rx_ = this->last_frame_ms_;
this->link_deadline_ms_ = this->last_frame_ms_ + this->link_timeout_ms_;
#ifdef USE_BINARY_SENSOR
if (this->connected_binary_sensor_ != nullptr) {
@@ -225,8 +241,12 @@ void LD2450Component::dump_config() {
}
void LD2450Component::loop() {
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<MAX_LINE_LENGTH>(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
// Before reading, so a frame in this pass resets it
const size_t count = this->available();
if (count != 0) {
this->bytes_since_frame_ = true;
}
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); }, count);
this->check_link_();
}
@@ -269,6 +289,7 @@ void LD2450Component::on_valid_frame_() {
this->link_deadline_ms_ = later_ms(window, due);
}
this->last_frame_ms_ = now;
this->bytes_since_frame_ = false;
this->invalid_frames_ = 0;
if (previous != LinkState::LINK_STATE_UP) {
this->link_state_ = LinkState::LINK_STATE_UP;
@@ -302,7 +323,7 @@ void LD2450Component::publish_target_unknown_(uint8_t target) {
// Live values become unknown; settings and diagnostics keep theirs
void LD2450Component::on_link_lost_(uint32_t silent_ms, bool was_up) {
ESP_LOGW(TAG, "Radar link lost: no valid frame for %" PRIu32 " ms (%s, %u invalid frames)", silent_ms,
this->bytes_since_frame_() ? LOG_STR_LITERAL("bytes received") : LOG_STR_LITERAL("no bytes received"),
this->bytes_since_frame_ ? LOG_STR_LITERAL("bytes received") : LOG_STR_LITERAL("no bytes received"),
static_cast<unsigned>(this->invalid_frames_));
this->status_set_warning();
#ifdef USE_BINARY_SENSOR
@@ -426,14 +447,14 @@ bool LD2450Component::get_timeout_status_(uint32_t check_millis) {
}
// Extract, store and publish zone details LD2450 buffer
void LD2450Component::process_zone_(const uint8_t *frame) {
void LD2450Component::process_zone_() {
uint8_t index, start;
for (index = 0; index < MAX_ZONES; index++) {
start = 12 + index * 8;
this->zone_config_[index].x1 = encode_value_le<int16_t>(&frame[start]);
this->zone_config_[index].y1 = encode_value_le<int16_t>(&frame[start + 2]);
this->zone_config_[index].x2 = encode_value_le<int16_t>(&frame[start + 4]);
this->zone_config_[index].y2 = encode_value_le<int16_t>(&frame[start + 6]);
this->zone_config_[index].x1 = encode_value_le<int16_t>(&this->buffer_data_[start]);
this->zone_config_[index].y1 = encode_value_le<int16_t>(&this->buffer_data_[start + 2]);
this->zone_config_[index].x2 = encode_value_le<int16_t>(&this->buffer_data_[start + 4]);
this->zone_config_[index].y2 = encode_value_le<int16_t>(&this->buffer_data_[start + 6]);
#ifdef USE_NUMBER
// only one null check as all coordinates are required for a single zone
if (this->zone_numbers_[index].x1 != nullptr) {
@@ -483,7 +504,7 @@ void LD2450Component::restart_and_read_all_info() {
void LD2450Component::send_command_(uint8_t command, const uint8_t *command_value, uint8_t command_value_len) {
ESP_LOGV(TAG, "Sending COMMAND %02X", command);
// frame header bytes
this->write_array_progmem(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
this->write_array(CMD_FRAME_HEADER, sizeof(CMD_FRAME_HEADER));
// length bytes
uint8_t len = 2;
if (command_value != nullptr) {
@@ -497,7 +518,7 @@ void LD2450Component::send_command_(uint8_t command, const uint8_t *command_valu
this->write_array(command_value, command_value_len);
}
// frame footer bytes
this->write_array_progmem(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
this->write_array(CMD_FRAME_FOOTER, sizeof(CMD_FRAME_FOOTER));
if (command != CMD_ENABLE_CONF && command != CMD_DISABLE_CONF) {
delay(50); // NOLINT
@@ -507,7 +528,7 @@ void LD2450Component::send_command_(uint8_t command, const uint8_t *command_valu
// LD2450 Radar data message:
// [AA FF 03 00] [0E 03 B1 86 10 00 40 01] [00 00 00 00 00 00 00 00] [00 00 00 00 00 00 00 00] [55 CC]
// Header Target 1 Target 2 Target 3 End
void LD2450Component::handle_periodic_data_(const uint8_t *frame) {
void LD2450Component::handle_periodic_data_() {
int16_t target_count = 0;
int16_t still_target_count = 0;
int16_t moving_target_count = 0;
@@ -529,18 +550,18 @@ void LD2450Component::handle_periodic_data_(const uint8_t *frame) {
start = TARGET_X + index * 8;
is_moving = false;
// tx and ty are used for further calculations, so always need to be populated
tx = ld2450::decode_coordinate(frame[start], frame[start + 1]);
tx = ld2450::decode_coordinate(this->buffer_data_[start], this->buffer_data_[start + 1]);
// Y
start = TARGET_Y + index * 8;
ty = ld2450::decode_coordinate(frame[start], frame[start + 1]);
ty = ld2450::decode_coordinate(this->buffer_data_[start], this->buffer_data_[start + 1]);
#ifdef USE_SENSOR
// RESOLUTION
start = TARGET_RESOLUTION + index * 8;
res = encode_value_le<uint16_t>(&frame[start]);
res = encode_value_le<uint16_t>(&this->buffer_data_[start]);
#endif
// SPEED
start = TARGET_SPEED + index * 8;
ts = ld2450::decode_speed(frame[start], frame[start + 1]);
ts = ld2450::decode_speed(this->buffer_data_[start], this->buffer_data_[start + 1]);
if (ts) {
is_moving = true;
moving_target_count++;
@@ -695,18 +716,18 @@ void LD2450Component::handle_periodic_data_(const uint8_t *frame) {
this->data_callback_.call();
}
bool LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", frame[COMMAND]);
if (frame[COMMAND_STATUS] != 0x01) {
void LD2450Component::handle_ack_data_() {
ESP_LOGV(TAG, "Handling ACK DATA for COMMAND %02X", this->buffer_data_[COMMAND]);
if (this->buffer_data_[COMMAND_STATUS] != 0x01) {
ESP_LOGE(TAG, "Invalid status");
return false;
return;
}
if (frame[8] || frame[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", frame[8], frame[9]);
return true;
if (this->buffer_data_[8] || this->buffer_data_[9]) {
ESP_LOGW(TAG, "Invalid command: %02X, %02X", this->buffer_data_[8], this->buffer_data_[9]);
return;
}
switch (frame[COMMAND]) {
switch (this->buffer_data_[COMMAND]) {
case CMD_ENABLE_CONF:
ESP_LOGV(TAG, "Enable conf");
break;
@@ -726,10 +747,10 @@ bool LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_VERSION: {
if (len < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 12 + sizeof(this->version_) + HEADER_FOOTER_SIZE) {
break; // too short to hold a version
}
std::memcpy(this->version_, &frame[12], sizeof(this->version_));
std::memcpy(this->version_, &this->buffer_data_[12], sizeof(this->version_));
char version_s[20];
ld24xx::format_version_str(this->version_, version_s);
ESP_LOGV(TAG, "Firmware version: %s", version_s);
@@ -740,11 +761,11 @@ bool LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
}
case CMD_QUERY_MAC_ADDRESS: {
if (len < 20) {
if (this->buffer_pos_ < 20) {
break; // too short to hold a MAC address
}
this->bluetooth_on_ = ld24xx::store_mac(&frame[10], this->mac_address_);
this->bluetooth_on_ = ld24xx::store_mac(&this->buffer_data_[10], this->mac_address_);
char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
const char *mac_str = ld24xx::format_mac_str(this->mac_address_, mac_s);
@@ -777,21 +798,21 @@ bool LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
break;
case CMD_QUERY_TARGET_MODE:
if (len < 11 + HEADER_FOOTER_SIZE) {
if (this->buffer_pos_ < 11 + HEADER_FOOTER_SIZE) {
break; // too short to hold the mode
}
ESP_LOGV(TAG, "Query target tracking mode");
#ifdef USE_SWITCH
PUBLISH_STATE(this->multi_target_switch_, frame[10] == 0x02);
PUBLISH_STATE(this->multi_target_switch_, this->buffer_data_[10] == 0x02);
#endif
break;
case CMD_QUERY_ZONE:
if (len < ZONE_ACK_FRAME_SIZE) {
if (this->buffer_pos_ < ZONE_ACK_FRAME_SIZE) {
break; // too short to hold the zones
}
ESP_LOGV(TAG, "Query zone conf");
this->zone_type_ = frame[10];
this->zone_type_ = this->buffer_data_[10];
this->publish_zone_type();
#ifdef USE_SELECT
if (this->zone_type_select_ != nullptr) {
@@ -799,16 +820,16 @@ bool LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
ESP_LOGV(TAG, "Change zone type to: %.*s", (int) zone.size(), zone.c_str());
}
#endif
if (frame[10] == 0x00) {
if (this->buffer_data_[10] == 0x00) {
ESP_LOGV(TAG, "Zone: Disabled");
}
if (frame[10] == 0x01) {
if (this->buffer_data_[10] == 0x01) {
ESP_LOGV(TAG, "Zone: Area detection");
}
if (frame[10] == 0x02) {
if (this->buffer_data_[10] == 0x02) {
ESP_LOGV(TAG, "Zone: Area filter");
}
this->process_zone_(frame);
this->process_zone_();
break;
case CMD_SET_ZONE:
@@ -819,29 +840,43 @@ bool LD2450Component::handle_ack_data_(const uint8_t *frame, uint8_t len) {
default:
break;
}
return true;
}
// Handles the frame when its footer is in place; returns false otherwise
bool LD2450Component::handle_frame_(const uint8_t *frame, uint8_t len) {
const uint8_t *end = &frame[len];
const bool periodic = frame[0] == PeriodicFrameFormat::FIRST;
if (periodic ? end[-2] != PERIODIC_FRAME_FOOTER[0] || end[-1] != PERIODIC_FRAME_FOOTER[1]
: !ld24xx::has_footer(frame, len)) {
if (this->invalid_frames_ < UINT16_MAX) {
this->invalid_frames_++;
}
ESP_LOGW(TAG, "Invalid footer");
return false;
// Read LD2450 buffer data
void LD2450Component::readline_(int readch) {
if (readch < 0) {
return; // No data available
}
if (periodic) {
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
ld24xx::feed_frame_byte(
this->buffer_data_, this->buffer_pos_, readch, DATA_FRAME_HEADER, ld2450::frame_length,
[this](uint8_t frame_len) { return this->handle_frame_(frame_len); },
[this]() {
if (this->invalid_frames_ < UINT16_MAX) {
this->invalid_frames_++;
}
ESP_LOGW(TAG, "Invalid header/footer");
});
}
// Dispatches the frame of frame_len bytes at the start of the buffer when its footer is in place
bool LD2450Component::handle_frame_(uint8_t frame_len) {
this->buffer_pos_ = frame_len; // the handlers take the frame length from here
const uint8_t *end = &this->buffer_data_[frame_len];
if (this->buffer_data_[0] == DATA_FRAME_HEADER[0]) {
if (end[-2] != DATA_FRAME_FOOTER[0] || end[-1] != DATA_FRAME_FOOTER[1]) {
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Periodic Data: %s");
this->on_valid_frame_();
this->handle_periodic_data_(frame);
this->handle_periodic_data_();
return true;
}
ESP_LOGV_HEX(TAG, frame, len, MAX_LINE_LENGTH, "Handling Ack Data: %s");
return this->handle_ack_data_(frame, len);
if (!ld2450::validate_header_footer(CMD_FRAME_FOOTER, end - HEADER_FOOTER_SIZE)) {
return false;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Handling Ack Data: %s");
this->handle_ack_data_();
return true;
}
// Set Config Mode - Pre-requisite sending commands
+9 -13
View File
@@ -30,7 +30,6 @@
#include "esphome/components/ld24xx/ld24xx.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "esphome/core/preferences.h"
@@ -47,8 +46,6 @@ static constexpr uint8_t DEFAULT_PRESENCE_TIMEOUT = 5; // Timeout to reset pres
static constexpr uint8_t MAX_LINE_LENGTH = 45;
static constexpr uint8_t MAX_TARGETS = 3; // Max 3 Targets in LD2450
static constexpr uint8_t MAX_ZONES = 3; // Max 3 Zones in LD2450
// Periodic frames: header, three targets of 8 bytes, footer; they carry no length
using PeriodicFrameFormat = FrameFormat<FrameHeader<0xAA, 0xFF, 0x03, 0x00>, FrameFixedLength<30>>;
// Silence after our own commands (restart, Bluetooth toggle, ...) is not a link loss; a restart takes about 2.3 s
static constexpr uint32_t LINK_GRACE_MS = 5000;
@@ -205,10 +202,11 @@ class LD2450Component : public Component, public uart::UARTDevice {
protected:
void send_command_(uint8_t command_str, const uint8_t *command_value, uint8_t command_value_len);
void set_config_mode_(bool enable);
void handle_periodic_data_(const uint8_t *frame);
bool handle_ack_data_(const uint8_t *frame, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
void process_zone_(const uint8_t *frame);
void handle_periodic_data_();
void handle_ack_data_();
bool handle_frame_(uint8_t frame_len);
void process_zone_();
void readline_(int readch);
void get_version_();
void get_mac_();
void query_target_tracking_mode_();
@@ -220,9 +218,6 @@ class LD2450Component : public Component, public uart::UARTDevice {
bool get_timeout_status_(uint32_t check_millis);
void open_link_grace_();
void check_link_();
bool bytes_since_frame_() const {
return static_cast<int32_t>(this->last_rx_ - this->last_frame_ms_) > 0 || this->reader_.length() != 0;
}
void on_valid_frame_();
void on_link_lost_(uint32_t silent_ms, bool was_up);
void on_link_up_(bool restored);
@@ -243,15 +238,16 @@ class LD2450Component : public Component, public uart::UARTDevice {
uint32_t timeout_ = DEFAULT_PRESENCE_TIMEOUT * 1000; // presence_timeout, in ms
uint32_t link_timeout_ms_{0};
uint32_t last_frame_ms_{0}; // last valid periodic frame; until the first one, when setup() ran
uint32_t last_rx_{0}; // last pass that read bytes
uint32_t link_deadline_ms_{0}; // the link is lost when the loop clock reaches this
uint8_t buffer_data_[MAX_LINE_LENGTH];
uint8_t mac_address_[MAC_ADDRESS_SIZE] = {0, 0, 0, 0, 0, 0};
uint8_t version_[6] = {0, 0, 0, 0, 0, 0};
LengthFrameReader<MAX_LINE_LENGTH, ld24xx::CmdFrameFormat, PeriodicFrameFormat> reader_;
uint8_t buffer_pos_ = 0; // where to resume processing/populating buffer
uint8_t zone_type_ = 0;
bool bluetooth_on_{false};
LinkState link_state_{LinkState::LINK_STATE_WAITING};
uint16_t invalid_frames_{0}; // since the last valid frame, saturating
bool bytes_since_frame_{false}; // any bytes since the last valid frame
uint16_t invalid_frames_{0}; // since the last valid frame, saturating
Target target_info_[MAX_TARGETS];
Zone zone_config_[MAX_ZONES];
#ifdef USE_TEXT_SENSOR
+105 -34
View File
@@ -1,33 +1,66 @@
#include "ld2460.h"
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <numbers>
namespace esphome::ld2460 {
ESPHOME_LOG_TAG(TAG, "ld2460");
static constexpr uint8_t HEADER_FOOTER_SIZE = 4;
// PROGMEM keeps the patterns out of RAM on the ESP8266; they are copied out for each compare
static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] PROGMEM = {0xFD, 0xFC, 0xFB, 0xFA};
static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] PROGMEM = {0x04, 0x03, 0x02, 0x01};
static constexpr uint8_t DATA_FRAME_HEADER[HEADER_FOOTER_SIZE] PROGMEM = {0xF4, 0xF3, 0xF2, 0xF1};
static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] PROGMEM = {0xF8, 0xF7, 0xF6, 0xF5};
static constexpr uint8_t CMD_REPORT_DATA = 0x04;
static constexpr uint8_t CMD_QUERY_INSTALLATION_MODE = 0x0A;
static constexpr uint8_t ACK_FRAME_LENGTH = 12;
static constexpr uint8_t MAX_QUERY_ATTEMPTS = 3;
static constexpr float RADIANS_TO_DEGREES = 180.0f / std::numbers::pi_v<float>;
void LD2460Component::setup() { this->send_query_(); }
// Header, command, length (12, little endian), payload 0x01, footer
static constexpr uint8_t QUERY_INSTALLATION_MODE_FRAME[] PROGMEM = {
0xFD, 0xFC, 0xFB, 0xFA, CMD_QUERY_INSTALLATION_MODE, 0x0C, 0x00, 0x01, 0x04, 0x03, 0x02, 0x01,
};
static bool matches(const uint8_t *bytes, const uint8_t *pattern) {
uint8_t copy[HEADER_FOOTER_SIZE];
progmem_memcpy(copy, pattern, sizeof(copy));
return std::memcmp(bytes, copy, sizeof(copy)) == 0;
}
// Header (4), command (1), length (2, little endian); the length counts the whole frame
static constexpr uint8_t FRAME_PREFIX_SIZE = 7;
static uint16_t frame_length(const uint8_t *frame) { return encode_uint16(frame[6], frame[5]); }
// First offset after 0 whose bytes, as far as they go, match a header; len when there is none (len >= 1)
static uint8_t next_header_start(const uint8_t *buffer, uint8_t len) {
uint8_t data_header[HEADER_FOOTER_SIZE];
uint8_t cmd_header[HEADER_FOOTER_SIZE];
progmem_memcpy(data_header, DATA_FRAME_HEADER, sizeof(data_header));
progmem_memcpy(cmd_header, CMD_FRAME_HEADER, sizeof(cmd_header));
uint8_t start = 1;
for (; start < len; start++) {
const size_t n = std::min<size_t>(len - start, HEADER_FOOTER_SIZE);
if (std::memcmp(&buffer[start], data_header, n) == 0 || std::memcmp(&buffer[start], cmd_header, n) == 0) {
break;
}
}
return start;
}
static constexpr float RADIANS_TO_DEGREES = 180.0f / std::numbers::pi_v<float>;
void LD2460Component::setup() { this->send_query_(); }
void LD2460Component::send_query_() {
this->write_array_progmem(QUERY_INSTALLATION_MODE_FRAME, sizeof(QUERY_INSTALLATION_MODE_FRAME));
uint8_t frame[sizeof(QUERY_INSTALLATION_MODE_FRAME)];
progmem_memcpy(frame, QUERY_INSTALLATION_MODE_FRAME, sizeof(frame));
this->write_array(frame, sizeof(frame));
}
void LD2460Component::dump_config() {
@@ -49,19 +82,19 @@ void LD2460Component::dump_config() {
}
void LD2460Component::loop() {
const uint32_t now = App.get_loop_component_start_time();
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
this->read_frames<MAX_FRAME_LENGTH>(this->reader_, handler, now, this->last_rx_);
this->read_available<MAX_LINE_LENGTH>([this](uint8_t b) { this->readline_(b); });
}
bool LD2460Component::handle_periodic_data_(const uint8_t *data, uint8_t packet_len) {
if (data[4] != CMD_REPORT_DATA) {
void LD2460Component::handle_periodic_data_() {
const uint8_t *data = this->buffer_data_;
if (!this->align_to_header_(DATA_FRAME_HEADER) || data[4] != CMD_REPORT_DATA) {
ESP_LOGW(TAG, "Invalid periodic data header");
return false;
return;
}
if ((packet_len - MIN_FRAME_LENGTH) % 4 != 0) {
const uint8_t packet_len = this->buffer_pos_;
if (packet_len < 11 || (packet_len - 11) % 4 != 0) {
ESP_LOGW(TAG, "Periodic packet length %u is not a whole number of targets", packet_len);
return false;
return;
}
if (this->query_attempts_ != 0) {
@@ -76,7 +109,7 @@ bool LD2460Component::handle_periodic_data_(const uint8_t *data, uint8_t packet_
}
#ifdef USE_SENSOR
uint8_t num_targets = std::min<uint8_t>((packet_len - MIN_FRAME_LENGTH) / 4, MAX_TARGETS);
uint8_t num_targets = std::min<uint8_t>((packet_len - 11) / 4, MAX_TARGETS);
for (uint8_t i = 0; i < MAX_TARGETS; i++) {
TargetSensors &t = this->target_sensors_[i];
if (i >= num_targets) {
@@ -122,36 +155,75 @@ bool LD2460Component::handle_periodic_data_(const uint8_t *data, uint8_t packet_
#endif
this->data_callback_.call();
return true;
}
// Handles the frame when its footer and structure are in place; returns false otherwise
bool LD2460Component::handle_frame_(const uint8_t *frame, uint8_t len) {
if (!ld24xx::has_footer(frame, len)) {
ESP_LOGW(TAG, "Invalid footer");
ESP_LOGV_HEX(TAG, frame, len, MAX_FRAME_LENGTH, "Rejected: %s");
return false;
void LD2460Component::readline_(uint8_t readch) {
if (this->buffer_pos_ >= MAX_LINE_LENGTH) {
// Keep the bytes from the next offset that could start a header, so a frame already partly
// buffered behind stray bytes survives; it is still fully validated once its footer arrives
const uint8_t start = next_header_start(this->buffer_data_, this->buffer_pos_);
this->buffer_pos_ -= start;
std::memmove(this->buffer_data_, &this->buffer_data_[start], this->buffer_pos_);
// Header-shaped noise keeps a whole header; warning only otherwise bounds the warning rate
if (this->buffer_pos_ < HEADER_FOOTER_SIZE) {
ESP_LOGW(TAG, "Max frame length exceeded; ignoring");
} else {
ESP_LOGV(TAG, "Max frame length exceeded; kept %u bytes", this->buffer_pos_);
}
}
ESP_LOGV_HEX(TAG, frame, len, MAX_FRAME_LENGTH, "Frame: %s");
if (frame[0] == DataFrame::FIRST)
return this->handle_periodic_data_(frame, len);
return this->handle_ack_(frame, len);
this->buffer_data_[this->buffer_pos_++] = readch;
if (this->buffer_pos_ < HEADER_FOOTER_SIZE) {
return;
}
const uint8_t *tail = &this->buffer_data_[this->buffer_pos_ - HEADER_FOOTER_SIZE];
bool is_data = readch == progmem_read_byte(&DATA_FRAME_FOOTER[3]) && matches(tail, DATA_FRAME_FOOTER);
if (!is_data && (readch != progmem_read_byte(&CMD_FRAME_FOOTER[3]) || !matches(tail, CMD_FRAME_FOOTER))) {
return;
}
ESP_LOGV_HEX(TAG, this->buffer_data_, this->buffer_pos_, MAX_LINE_LENGTH, "Frame: %s");
if (is_data) {
this->handle_periodic_data_();
} else {
this->handle_ack_();
}
this->buffer_pos_ = 0;
}
bool LD2460Component::handle_ack_(const uint8_t *data, uint8_t len) {
if (len != ACK_FRAME_LENGTH) {
// Once a footer is matched, shift the buffer to the first offset holding a header whose length
// field ends the frame exactly at the footer. Stray bytes, truncated frames and header bytes inside
// a payload are skipped this way. Returns false when no such offset exists.
bool LD2460Component::align_to_header_(const uint8_t *header) {
for (uint8_t i = 0; i + FRAME_PREFIX_SIZE <= this->buffer_pos_; i++) {
const uint8_t *frame = &this->buffer_data_[i];
if (matches(frame, header) && frame_length(frame) == this->buffer_pos_ - i) {
if (i != 0) {
this->buffer_pos_ -= i;
std::memmove(this->buffer_data_, frame, this->buffer_pos_);
}
return true;
}
}
return false;
}
void LD2460Component::handle_ack_() {
const uint8_t *data = this->buffer_data_;
if (!this->align_to_header_(CMD_FRAME_HEADER) || this->buffer_pos_ != ACK_FRAME_LENGTH) {
ESP_LOGW(TAG, "Dropping malformed command frame");
return false;
return;
}
if (data[4] != CMD_QUERY_INSTALLATION_MODE) {
ESP_LOGD(TAG, "Ignoring reply to command 0x%02X", data[4]);
return true;
return;
}
const uint8_t mode = data[7];
if (mode != static_cast<uint8_t>(InstallationMode::INSTALLATION_MODE_SIDE) &&
mode != static_cast<uint8_t>(InstallationMode::INSTALLATION_MODE_TOP)) {
ESP_LOGW(TAG, "Unexpected installation mode %u", mode);
return true;
return;
}
this->installation_mode_ = static_cast<InstallationMode>(mode);
this->query_attempts_ = 0;
@@ -164,7 +236,6 @@ bool LD2460Component::handle_ack_(const uint8_t *data, uint8_t len) {
t.last_x = INT16_MIN;
}
#endif
return true;
}
} // namespace esphome::ld2460
+11 -17
View File
@@ -1,7 +1,6 @@
#pragma once
#include "esphome/core/defines.h"
#include "esphome/core/frame_reader.h"
#include "esphome/components/ld24xx/ld24xx.h"
#include "esphome/components/uart/uart.h"
@@ -9,13 +8,8 @@
namespace esphome::ld2460 {
static constexpr uint8_t MAX_FRAME_LENGTH = 31; // A 5-target data frame
static constexpr uint8_t MAX_LINE_LENGTH = 32; // Longest frame is a 5-target data frame of 31 bytes
static constexpr uint8_t MAX_TARGETS = 5;
// Header (4), command, whole-frame length (2, LE), payload, footer (4)
static constexpr uint8_t MIN_FRAME_LENGTH = 11;
using FrameLength = FrameLengthU16LE<LengthField{.offset = 5}>;
using DataFrame = FrameFormat<ld24xx::DataFrameHeader, FrameLength, FrameMinLength<MIN_FRAME_LENGTH>>;
using CmdFrame = FrameFormat<ld24xx::CmdFrameHeader, FrameLength, FrameMinLength<MIN_FRAME_LENGTH>>;
enum class InstallationMode : uint8_t {
INSTALLATION_MODE_SIDE = 1,
@@ -46,16 +40,10 @@ class LD2460Component : public Component, public uart::UARTDevice {
protected:
void send_query_();
bool handle_periodic_data_(const uint8_t *data, uint8_t packet_len);
bool handle_ack_(const uint8_t *data, uint8_t len);
bool handle_frame_(const uint8_t *frame, uint8_t len);
uint32_t last_rx_{0};
LengthFrameReader<MAX_FRAME_LENGTH, DataFrame, CmdFrame> reader_;
// The angle formula depends on how the module is mounted, so it is read from the module at boot
InstallationMode installation_mode_{InstallationMode::INSTALLATION_MODE_SIDE};
// Queries sent so far; 0 once the module answered. Data frames resend up to MAX_QUERY_ATTEMPTS.
uint8_t query_attempts_{1};
bool align_to_header_(const uint8_t *header);
void handle_periodic_data_();
void handle_ack_();
void readline_(uint8_t readch);
#ifdef USE_SENSOR
// INT16_MIN marks a slot with no published coordinates, so the next report always publishes
@@ -68,6 +56,12 @@ class LD2460Component : public Component, public uart::UARTDevice {
#endif
LazyCallbackManager<void()> data_callback_;
uint8_t buffer_data_[MAX_LINE_LENGTH];
uint8_t buffer_pos_{0};
// The angle formula depends on how the module is mounted, so it is read from the module at boot
InstallationMode installation_mode_{InstallationMode::INSTALLATION_MODE_SIDE};
// Queries sent so far; 0 once the module answered. Data frames resend up to MAX_QUERY_ATTEMPTS.
uint8_t query_attempts_{1};
};
} // namespace esphome::ld2460
+65 -17
View File
@@ -1,12 +1,13 @@
#pragma once
#include "esphome/core/defines.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/progmem.h"
#include <algorithm>
#include <cstring>
#include <memory>
#include <span>
#ifdef USE_SENSOR
@@ -78,25 +79,72 @@ inline void format_version_str(const uint8_t *version, std::span<char, 20> buffe
version[5], version[4], version[3], version[2]);
}
// Commands and their answers share this header, a little-endian byte count and this footer; periodic data frames have
// their own header and footer
// Commands and their answers share this header, a little-endian byte count and this footer
static constexpr uint8_t HEADER_FOOTER_SIZE = 4;
static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] PROGMEM = {0xFD, 0xFC, 0xFB, 0xFA};
static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] PROGMEM = {0x04, 0x03, 0x02, 0x01};
static constexpr uint8_t DATA_FRAME_FOOTER[HEADER_FOOTER_SIZE] PROGMEM = {0xF8, 0xF7, 0xF6, 0xF5};
static constexpr uint8_t CMD_FRAME_HEADER[HEADER_FOOTER_SIZE] = {0xFD, 0xFC, 0xFB, 0xFA};
static constexpr uint8_t CMD_FRAME_FOOTER[HEADER_FOOTER_SIZE] = {0x04, 0x03, 0x02, 0x01};
// Header (4), payload length (2, LE), payload, footer (4)
using PayloadLength = PayloadLengthU16LE<LengthField{.offset = HEADER_FOOTER_SIZE, .trailer = HEADER_FOOTER_SIZE}>;
using CmdFrameHeader = FrameHeader<0xFD, 0xFC, 0xFB, 0xFA>;
using DataFrameHeader = FrameHeader<0xF4, 0xF3, 0xF2, 0xF1>;
using CmdFrameFormat = FrameFormat<CmdFrameHeader, PayloadLength>;
using DataFrameFormat = FrameFormat<DataFrameHeader, PayloadLength>;
inline bool validate_header_footer(const uint8_t *header_footer, const uint8_t *buffer) {
return std::memcmp(header_footer, buffer, HEADER_FOOTER_SIZE) == 0;
}
// Whether a command or periodic data frame of at least HEADER_FOOTER_SIZE bytes ends in its footer
inline bool has_footer(const uint8_t *frame, size_t len) {
uint8_t footer[HEADER_FOOTER_SIZE];
progmem_memcpy(footer, frame[0] == DataFrameFormat::FIRST ? DATA_FRAME_FOOTER : CMD_FRAME_FOOTER, sizeof(footer));
return std::memcmp(&frame[len - HEADER_FOOTER_SIZE], footer, sizeof(footer)) == 0;
// Whole command frame length, or 0 until the count arrives; 32 bit so 0xFFFF cannot wrap to 0
inline uint32_t cmd_frame_length(const uint8_t *buffer, uint8_t count) {
if (count < HEADER_FOOTER_SIZE + 2) {
return 0;
}
return HEADER_FOOTER_SIZE + 2 + encode_value_le<uint16_t>(&buffer[HEADER_FOOTER_SIZE]) + HEADER_FOOTER_SIZE;
}
// Drops the first `from` bytes and anything after them that does not begin a header; returns the bytes kept
inline uint8_t drop_to_next_header(uint8_t *buffer, uint8_t count, uint8_t from, const uint8_t *data_header) {
for (; from < count; from++) {
const size_t n = std::min<size_t>(HEADER_FOOTER_SIZE, count - from);
if (std::memcmp(&buffer[from], CMD_FRAME_HEADER, n) == 0 || std::memcmp(&buffer[from], data_header, n) == 0) {
std::memmove(buffer, &buffer[from], count - from);
return count - from;
}
}
return 0;
}
// Feeds one byte into a frame buffer. A frame opens with the command header or `data_header` and ends at
// `frame_length(buffer, count)` bytes (0 while unknown); `handle_frame(len)` returns false for a footer out
// of place. A dropped or oversized frame calls `on_drop()`. The handler may overwrite `pos`; the splitter
// works from the count it saved.
template<size_t N, typename LengthFn, typename HandleFn, typename DropFn>
void feed_frame_byte(uint8_t (&buffer)[N], uint8_t &pos, uint8_t byte, const uint8_t *data_header,
LengthFn frame_length, HandleFn handle_frame, DropFn on_drop) {
// The first byte picks the header; bytes that do not continue it are dropped
if (pos > 0 && pos < HEADER_FOOTER_SIZE) {
const uint8_t *header = buffer[0] == data_header[0] ? data_header : CMD_FRAME_HEADER;
if (byte != header[pos]) {
pos = 0;
}
}
if (pos == 0 && byte != data_header[0] && byte != CMD_FRAME_HEADER[0]) {
return;
}
buffer[pos++] = byte;
// Drain every whole frame left in the buffer
while (true) {
const uint32_t frame_len = frame_length(buffer, pos);
if (frame_len == 0 || (frame_len <= N && pos < frame_len)) {
return;
}
const uint8_t total = pos;
// Keep only what begins a header: after the frame, or after its first byte when it is dropped
uint8_t from = 1;
if (frame_len <= N && handle_frame(static_cast<uint8_t>(frame_len))) {
from = frame_len;
} else {
on_drop();
}
pos = drop_to_next_header(buffer, total, from, data_header);
if (pos == 0) {
return;
}
}
}
} // namespace esphome::ld24xx
-56
View File
@@ -1,4 +1,3 @@
from dataclasses import dataclass
import json
import logging
from pathlib import Path
@@ -189,61 +188,6 @@ def get_board_pins() -> dict[str, int]:
return lookup_board_pins(get_libretiny_board())
@dataclass(frozen=True)
class HardwareUart:
"""A hardware UART of the configured board and the pin numbers it can use."""
port: int
tx_pins: tuple[int, ...]
rx_pins: tuple[int, ...]
# The board lists pin choices instead of a default pin for this direction
tx_pin_choices: bool
rx_pin_choices: bool
@property
def pin_choices(self) -> bool:
"""True when the pins must be passed when the UART starts."""
return self.tx_pin_choices or self.rx_pin_choices
def get_hardware_uarts() -> list[HardwareUart]:
"""Hardware UARTs of the configured board; empty for a board without pin data."""
board_pins = get_board_pins()
uarts = []
for port in range(3):
pins: dict[str, list[int]] = {"TX": [], "RX": []}
choices: dict[str, bool] = {"TX": False, "RX": False}
for role, role_pins in pins.items():
name = f"SERIAL{port}_{role}"
for key, pin in board_pins.items():
if key == name:
role_pins.append(pin)
elif key.startswith(f"{name}_"):
role_pins.append(pin)
choices[role] = True
if pins["TX"] or pins["RX"]:
uarts.append(
HardwareUart(
port,
tuple(pins["TX"]),
tuple(pins["RX"]),
choices["TX"],
choices["RX"],
)
)
return uarts
def has_software_serial() -> bool:
"""True when the family's Arduino core has SoftwareSerial (LT_ARD_HAS_SOFTSERIAL)."""
return get_libretiny_family() == FAMILY_RTL8710B
def can_choose_uart_pins() -> bool:
"""True when SerialClass::begin() takes the pins, which LibreTiny added in 1.12.0."""
return CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION] >= cv.Version(1, 12, 0)
def only_on_family(*, supported=None, unsupported=None):
"""Config validator for features only available on some LibreTiny families."""
if supported is not None and not isinstance(supported, list):
@@ -151,8 +151,7 @@ Color color_from_light_color_values(LightColorValues val) {
auto r = to_uint8_scale(val.get_color_brightness() * val.get_red());
auto g = to_uint8_scale(val.get_color_brightness() * val.get_green());
auto b = to_uint8_scale(val.get_color_brightness() * val.get_blue());
// White keeps its default of 100% in RGB mode, where it must not count as the strongest channel
uint8_t w = val.get_color_mode() == ColorMode::RGB ? 0 : to_uint8_scale(val.get_white());
auto w = to_uint8_scale(val.get_white());
return Color(r, g, b, w);
}
@@ -12,45 +12,6 @@ uint8_t ESPColorCorrection::gamma_correct_(uint8_t value) const {
return result;
}
uint16_t ESPColorCorrection::gamma_level_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value * 257;
return progmem_read_uint16(&this->gamma_table_[value]);
}
uint8_t ESPColorCorrection::gamma_round_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value;
return (progmem_read_uint16(&this->gamma_table_[value]) + 128) / 257;
}
// Lighting every non-zero channel instead would turn a dim red with a trace of green into yellow
Color ESPColorCorrection::correct_dark_pixel_(Color color) const {
// Compared without the local brightness, which is the same for every channel: the scaled 8-bit
// values are too coarse to compare at the lowest brightness
uint16_t strengths[4];
uint16_t max_strength = 0;
bool lit = false;
for (uint8_t i = 0; i < 4; i++) {
strengths[i] = color[i] * this->max_brightness_[i];
max_strength = std::max(max_strength, strengths[i]);
lit |= esp_scale8_twice(color[i], this->max_brightness_[i], this->local_brightness_) != 0;
}
Color res;
if (!lit)
return res;
// Stretch the strongest channel to full scale and round the others against it; the table is too
// coarse to compare its lowest levels
for (uint8_t i = 0; i < 4; i++) {
if (strengths[i] == max_strength) {
res[i] = 1;
} else if (strengths[i] != 0) {
res[i] = this->gamma_level_(strengths[i] * 255 / max_strength) >= 0x8000 ? 1 : 0;
}
}
return res;
}
uint8_t ESPColorCorrection::gamma_uncorrect_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value;
@@ -40,13 +40,10 @@ class ESPColorCorrection {
#endif
void set_gamma_table(const uint16_t *table) { this->gamma_table_ = table; }
/// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma, keeping a lit pixel lit
inline Color color_correct(Color color) const ESPHOME_ALWAYS_INLINE {
Color res(this->round_channel_(COLOR_CHANNEL_R, color.red), this->round_channel_(COLOR_CHANNEL_G, color.green),
this->round_channel_(COLOR_CHANNEL_B, color.blue), this->round_channel_(COLOR_CHANNEL_W, color.white));
if (res.raw_32 == 0 && color.raw_32 != 0)
res = this->correct_dark_pixel_(color);
return Color(this->limit_(res.red), this->limit_(res.green), this->limit_(res.blue), this->limit_(res.white));
// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma
return Color(this->color_correct_red(color.red), this->color_correct_green(color.green),
this->color_correct_blue(color.blue), this->color_correct_white(color.white));
}
inline uint8_t color_correct_red(uint8_t red) const ESPHOME_ALWAYS_INLINE {
return this->color_correct_channel(COLOR_CHANNEL_R, red);
@@ -93,15 +90,6 @@ class ESPColorCorrection {
#endif
return res;
}
inline uint8_t round_channel_(uint8_t channel, uint8_t value) const ESPHOME_ALWAYS_INLINE {
return this->gamma_round_(esp_scale8_twice(value, this->max_brightness_[channel], this->local_brightness_));
}
/// Forward gamma as the table's 16-bit level
uint16_t gamma_level_(uint8_t value) const;
/// Forward gamma rounded to uint8, where a low level becomes 0
uint8_t gamma_round_(uint8_t value) const;
/// The levels of a pixel whose channels all round to 0: 1 for its strongest channels, unless it is black
Color correct_dark_pixel_(Color color) const;
/// Forward gamma: read uint16 PROGMEM table, convert to uint8
uint8_t gamma_correct_(uint8_t value) const;
/// Reverse gamma and limit for one stored level
+1 -18
View File
@@ -36,10 +36,6 @@ class ESPColorAccessor {
#if defined(USE_LIGHT_PARTITION) && defined(USE_LIGHT_POWER_ESTIMATION)
virtual const ESPColorCorrection *get_color_correction_internal(int32_t index) const { return nullptr; }
#endif
#ifdef USE_LIGHT_PARTITION
// For internal use only: whether the LED at `index` stores a white level.
virtual bool has_white_internal(int32_t index) const { return true; }
#endif
};
/// Color accessor that is completely at peace with the void of nothingness.
@@ -82,10 +78,6 @@ class BufferColorAccessor : public ESPColorAccessor {
}
void set_effect_data(int32_t index, uint8_t value) override { this->effect_data[index] = value; }
#ifdef USE_LIGHT_PARTITION
bool has_white_internal(int32_t index) const override { return this->channel_colors.has_white(); }
#endif
/// Allocate a zeroed block of buffer_bytes() plus `extra_bytes` for the caller, which start at
/// `effect_data + num_leds`, and pass it to set_buffer(). Returns false if it failed.
bool allocate(RAMAllocator<uint8_t> &allocator, size_t num_leds, size_t extra_bytes = 0) {
@@ -159,12 +151,7 @@ class CorrectedBufferColorAccessor final : public BufferColorAccessor {
return this->color_correction->color_uncorrect_channel(channel, this->get_channel_raw(index, channel));
}
void set(int32_t index, Color color) override {
// A white level the strip cannot show must not count as the pixel's strongest channel
if (!this->channel_colors.has_white())
color.white = 0;
this->set_raw(index, this->color_correction->color_correct(color));
}
void set(int32_t index, Color color) override { this->set_raw(index, this->color_correction->color_correct(color)); }
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
this->set_channel_raw(index, channel, this->color_correction->color_correct_channel(channel, value));
}
@@ -286,10 +273,6 @@ class ESPColorView final : public ESPColorSettable {
return this->accessor_->get_color_correction_internal(this->index_);
}
#endif
#ifdef USE_LIGHT_PARTITION
// This method is for internal use only.
bool has_white_internal() const { return this->accessor_->has_white_internal(this->index_); }
#endif
protected:
ESPColorAccessor *const accessor_;
+26 -15
View File
@@ -94,6 +94,7 @@ UART_SELECTION_RP2040 = [USB_CDC, UART0, UART1]
UART_SELECTION_NRF52 = [USB_CDC, UART0]
# Read by device-builder
HARDWARE_UART_TO_UART_SELECTION = {
UART0: logger_ns.UART_SELECTION_UART0,
UART0_SWAP: logger_ns.UART_SELECTION_UART0_SWAP,
@@ -538,17 +539,17 @@ async def to_code(config: ConfigType) -> None:
cg.add(log.set_boot_log_level(tag, LOG_LEVELS[log_level]))
if CORE.is_esp32 or CORE.is_host:
cg.add(log.create_pthread_key())
# set_uart_selection() must be called before pre_setup() because
# pre_setup() switches on uart_ to decide which hardware to initialize
# (e.g. UART0 vs USB_SERIAL_JTAG). Without this, uart_ is still the
# default UART_SELECTION_UART0 and the wrong hardware gets initialized.
# uart_ is UART0 in C++ except on LibreTiny where it is DEFAULT; skip the
# setter when the config matches it.
cpp_default_uart = DEFAULT if CORE.is_libretiny else UART0
if (
hardware_uart := config.get(CONF_HARDWARE_UART)
) is not None and hardware_uart != cpp_default_uart:
cg.add(log.set_uart_selection(HARDWARE_UART_TO_UART_SELECTION[hardware_uart]))
if (hardware_uart := config.get(CONF_HARDWARE_UART)) is not None:
cg.add_define(f"USE_LOGGER_UART_SELECTION_{hardware_uart}")
cg.add_define(
"ESPHOME_LOGGER_UART_SELECTION",
cg.RawExpression(f"logger::UART_SELECTION_{hardware_uart}"),
)
# ESP8266 without serial logging never opens a port
cg.add_define(
"ESPHOME_LOGGER_UART_NAME",
"NONE" if CORE.is_esp8266 and baud_rate == 0 else hardware_uart,
)
# pre_setup() sets global_logger and must run before any other code
# that may call ESP_LOG* (e.g. setup_preferences contains ESP_LOGVV).
cg.add(log.pre_setup())
@@ -645,7 +646,6 @@ async def _late_logger_init(config: ConfigType) -> None:
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_CDC", True)
elif config[CONF_HARDWARE_UART] == USB_SERIAL_JTAG:
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG", True)
cg.add_define("USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG")
# Log V2 formats centrally in esp_log() (~4KB flash, ~180B RAM). 6.1
# adds CONSTRAINED_ENV_SAFE=n, keeping early/DRAM logs on
# esp_rom_printf instead of pulling ~1.2KB esp_rom_vprintf into IRAM.
@@ -663,10 +663,12 @@ async def _late_logger_init(config: ConfigType) -> None:
# --wrap: a strong definition collides; see logger_esp32.cpp
cg.add_build_flag("-Wl,--wrap=esp_log_format")
# Zephyr polls the USB port only when it logs there
if config.get(CONF_HARDWARE_UART) == USB_CDC and (
has_serial_logging or not CORE.is_nrf52
if (
CORE.using_zephyr
and has_serial_logging
and config[CONF_HARDWARE_UART] == USB_CDC
):
cg.add_define("USE_LOGGER_UART_SELECTION_USB_CDC")
cg.add_define("USE_LOGGER_ZEPHYR_CDC_LOOP")
# Define platform support flags for components that need auto-detection
try:
uart_selection(USB_SERIAL_JTAG)
@@ -884,6 +886,15 @@ def request_logger_level_listeners() -> None:
_request_log_listener_slot = cg.slot_counter("ESPHOME_LOG_MAX_LISTENERS")
def request_console() -> None:
"""Compile in Logger::console_read() and console_write(); call from to_code.
On ESP32 a USB_CDC logger only has a console where ESP-IDF sets CONFIG_ESP_CONSOLE_USB_CDC (targets with
USB OTG); elsewhere, such as the C3, C6 or H2, both do nothing. Host and Zephyr have no console API.
"""
cg.add_define("USE_LOGGER_CONSOLE")
def request_log_listener() -> None:
"""Reserve a log listener slot; call once per listener from to_code."""
cg.add_define("USE_LOG_LISTENERS")
+22 -3
View File
@@ -248,10 +248,10 @@ Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
#endif
}
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
void Logger::loop() {
this->process_messages_();
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
this->cdc_loop_();
#endif
}
@@ -278,7 +278,7 @@ void Logger::process_messages_() {
}
}
// Zephyr with USB CDC keeps the loop running for cdc_loop_()
#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#ifndef USE_LOGGER_ZEPHYR_CDC_LOOP
else {
// A concurrent enable_loop_soon_any_context() still wakes the next iteration
this->disable_loop();
@@ -371,6 +371,25 @@ static const LogString *get_log_level_str(uint8_t level) {
return LogLevelStrings::get_log_str(level, LogLevelStrings::LAST_INDEX);
}
#ifndef USE_HOST
const LogString *Logger::get_uart_selection_() {
#ifdef USE_LOGGER_UART_SELECTION_DEFAULT
// LibreTiny resolves DEFAULT to the board's port only when serial logging is on
if (this->baud_rate_ > 0) {
switch (this->get_uart()) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
default:
return LOG_STR("UART2");
}
}
#endif
return LOG_STR(ESPHOME_LOGGER_UART_NAME);
}
#endif
void Logger::dump_config() {
ESP_LOGCONFIG(TAG,
"Logger:\n"
+35 -10
View File
@@ -124,6 +124,9 @@ enum UARTSelection : uint8_t {
UART_SELECTION_UART0_SWAP,
#endif // USE_ESP8266
};
// The port chosen by hardware_uart, fixed at build time
static constexpr UARTSelection CONFIGURED_UART_SELECTION = ESPHOME_LOGGER_UART_SELECTION;
#endif // USE_ESP32 || USE_ESP8266 || USE_RP2 || USE_LIBRETINY || USE_ZEPHYR
/**
@@ -146,7 +149,7 @@ enum UARTSelection : uint8_t {
class Logger final : public Component {
public:
explicit Logger(uint32_t baud_rate);
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
void loop() override;
#endif
#if defined(USE_RP2_CRASH_HANDLER) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
@@ -160,11 +163,11 @@ class Logger final : public Component {
#endif
#ifdef USE_ESP32
/// UART_NUM_0 when logging to USB
uart_port_t get_uart_num() const {
constexpr uart_port_t get_uart_num() const {
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC) || defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
return UART_NUM_0;
#else
return static_cast<uart_port_t>(this->uart_);
return static_cast<uart_port_t>(CONFIGURED_UART_SELECTION);
#endif
}
#endif
@@ -172,9 +175,35 @@ class Logger final : public Component {
void create_pthread_key() { pthread_key_create(&this->log_recursion_key_, nullptr); }
#endif
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
void set_uart_selection(UARTSelection uart_selection) { this->uart_ = uart_selection; }
/// Get the UART used by the logger.
UARTSelection get_uart() const { return this->uart_; }
#ifdef USE_LIBRETINY
// DEFAULT resolves to the board's default port
constexpr UARTSelection get_uart() const {
return CONFIGURED_UART_SELECTION == UART_SELECTION_DEFAULT ? static_cast<UARTSelection>(LT_UART_DEFAULT_SERIAL + 1)
: CONFIGURED_UART_SELECTION;
}
#else
constexpr UARTSelection get_uart() const { return CONFIGURED_UART_SELECTION; }
#endif
#endif
#ifdef USE_LOGGER_CONSOLE
// Raw bytes on the console port, without log framing; request with logger.request_console()
// console_write() returns the bytes written: a UART write blocks until all are queued, but a USB write can stop
// short when the host is not reading (USB Serial/JTAG gives up after 20 ms)
#if defined(USE_ARDUINO) && !defined(USE_ESP32)
size_t console_write(const uint8_t *data, size_t len) { return this->hw_serial_->write(data, len); }
bool console_read(uint8_t &byte) {
int c = this->hw_serial_->read();
if (c < 0)
return false;
byte = c;
return true;
}
#elif defined(USE_ESP32)
size_t console_write(const uint8_t *data, size_t len);
/// Non-blocking read of one byte; false if none is waiting.
bool console_read(uint8_t &byte);
#endif
#endif
/// Set the default log level for this logger.
@@ -251,7 +280,7 @@ class Logger final : public Component {
void log_vprintf_non_main_thread_(uint8_t level, const char *tag, int line, const char *format, va_list args,
const char *thread_name);
#endif
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
void cdc_loop_();
#endif
void process_messages_();
@@ -411,10 +440,6 @@ class Logger final : public Component {
bool boot_log_done_{false}; // Set on first replay; stops further capture
#endif
uint8_t current_level_{ESPHOME_LOG_LEVEL_VERY_VERBOSE};
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
// 0 is UART0, or DEFAULT on LibreTiny; must match cpp_default_uart in __init__.py
UARTSelection uart_{};
#endif
bool main_task_recursion_guard_{false}; // Guards tx_buffer_ on the main loop
#ifdef USE_LIBRETINY
bool non_main_task_recursion_guard_{false}; // Shared guard for all non-main tasks on LibreTiny
+35 -37
View File
@@ -17,6 +17,10 @@
#include <driver/usb_serial_jtag_vfs.h>
#endif
#endif
// The logger accepts USB_CDC on targets without USB OTG (C3, C6, H2, ...), where IDF has no CDC console
#if defined(USE_LOGGER_CONSOLE) && defined(USE_LOGGER_UART_SELECTION_USB_CDC) && defined(CONFIG_ESP_CONSOLE_USB_CDC)
#include <esp_private/usb_console.h>
#endif
#if defined(CONFIG_PM_ENABLE) && defined(CONFIG_FREERTOS_USE_TICKLESS_IDLE) && \
(ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0))
#include "esp_sleep.h"
@@ -73,6 +77,7 @@ static void init_usb_serial_jtag() {
}
#endif
#if !defined(USE_LOGGER_UART_SELECTION_USB_CDC) && !defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_size) {
uart_config_t uart_config{};
uart_config.baud_rate = (int) baud_rate;
@@ -97,6 +102,7 @@ static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_si
esp_sleep_set_console_uart_handling_mode(ESP_SLEEP_ALWAYS_FLUSH_UART);
#endif
}
#endif
// get_uart_num() and pre_setup() cast the selection straight to a port
static_assert(static_cast<int>(UART_SELECTION_UART0) == static_cast<int>(UART_NUM_0) &&
@@ -107,26 +113,11 @@ static_assert(static_cast<int>(UART_SELECTION_UART2) == static_cast<int>(UART_NU
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
switch (this->uart_) {
case UART_SELECTION_UART0:
case UART_SELECTION_UART1:
#ifdef USE_ESP32_VARIANT_ESP32
case UART_SELECTION_UART2:
#endif
init_uart(static_cast<uart_port_t>(this->uart_), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
break;
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
break;
#endif
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case UART_SELECTION_USB_SERIAL_JTAG:
#ifdef USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
init_usb_serial_jtag();
init_usb_serial_jtag();
#elif !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
init_uart(this->get_uart_num(), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
#endif
break;
#endif
}
}
global_logger = this;
@@ -138,29 +129,36 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
#ifdef USE_ESP32_VARIANT_ESP32
case UART_SELECTION_UART2:
return LOG_STR("UART2");
#ifdef USE_LOGGER_CONSOLE
size_t Logger::console_write(const uint8_t *data, size_t len) {
int written = 0;
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef CONFIG_ESP_CONSOLE_USB_CDC // keep: not set without USB OTG, see the include above
written = esp_usb_console_write_buf(reinterpret_cast<const char *>(data), len);
#endif
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
#elif defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
written = usb_serial_jtag_write_bytes(data, len, pdMS_TO_TICKS(20));
#else
written = uart_write_bytes(this->get_uart_num(), data, len);
#endif
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case UART_SELECTION_USB_SERIAL_JTAG:
return LOG_STR("USB_SERIAL_JTAG");
#endif
default:
return LOG_STR("UNKNOWN");
}
return written > 0 ? written : 0;
}
bool Logger::console_read(uint8_t &byte) {
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef CONFIG_ESP_CONSOLE_USB_CDC // keep: not set without USB OTG, see the include above
return esp_usb_console_available_for_read() && esp_usb_console_read_buf(reinterpret_cast<char *>(&byte), 1) == 1;
#else
return false;
#endif
#elif defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
return usb_serial_jtag_read_bytes(&byte, 1, 0) > 0;
#else
return uart_read_bytes(this->get_uart_num(), &byte, 1, 0) > 0;
#endif
}
#endif
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return esp32::crash_handler_has_data(); }
void log_crash_to_client() {
+3 -16
View File
@@ -14,9 +14,9 @@ void Logger::pre_setup() {
#if defined(USE_ESP8266_LOGGER_SERIAL)
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
Serial.swap();
}
#ifdef USE_LOGGER_UART_SELECTION_UART0_SWAP
Serial.swap();
#endif
Serial.setDebugOutput(ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE);
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
this->hw_serial_ = &Serial1;
@@ -35,19 +35,6 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
#if defined(USE_ESP8266_LOGGER_SERIAL)
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
return LOG_STR("UART0_SWAP");
}
return LOG_STR("UART0");
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
return LOG_STR("UART1");
#else
return LOG_STR("NONE");
#endif
}
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return esp8266::crash_handler_has_data(); }
void log_crash_to_client() { esp8266::crash_handler_log(); }
+1 -1
View File
@@ -9,7 +9,7 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
char buffer[TIMESTAMP_LEN + ESPHOME_LOGGER_TX_BUFFER_SIZE + HEADROOM];
time_t rawtime;
::time(&rawtime);
time(&rawtime);
struct tm timeinfo;
localtime_r(&rawtime, &timeinfo); // Thread-safe version
size_t pos = strftime(buffer, TIMESTAMP_LEN + 1, "[%H:%M:%S]", &timeinfo);
+20 -51
View File
@@ -12,45 +12,28 @@ ESPHOME_LOG_TAG(TAG, "logger");
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
switch (this->uart_) {
#if LT_HW_UART0
case UART_SELECTION_UART0:
this->hw_serial_ = &Serial0;
libretiny::ensure_serial_handle(0);
Serial0.begin(this->baud_rate_);
break;
#endif
#if LT_HW_UART1
case UART_SELECTION_UART1:
this->hw_serial_ = &Serial1;
libretiny::ensure_serial_handle(1);
Serial1.begin(this->baud_rate_);
break;
#endif
#if LT_HW_UART2
case UART_SELECTION_UART2:
this->hw_serial_ = &Serial2;
libretiny::ensure_serial_handle(2);
Serial2.begin(this->baud_rate_);
break;
#endif
default:
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
if (this->uart_ != UART_SELECTION_DEFAULT) {
ESP_LOGW(TAG, " The chosen logger UART port is not available on this board."
"The default port was used instead.");
}
break;
#if defined(USE_LOGGER_UART_SELECTION_UART0) && LT_HW_UART0
this->hw_serial_ = &Serial0;
libretiny::ensure_serial_handle(0);
Serial0.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART1) && LT_HW_UART1
this->hw_serial_ = &Serial1;
libretiny::ensure_serial_handle(1);
Serial1.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART2) && LT_HW_UART2
this->hw_serial_ = &Serial2;
libretiny::ensure_serial_handle(2);
Serial2.begin(this->baud_rate_);
#else
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
if (CONFIGURED_UART_SELECTION != UART_SELECTION_DEFAULT) {
ESP_LOGW(TAG, " The chosen logger UART port is not available on this board."
"The default port was used instead.");
}
#endif
// change lt_log() port to match default Serial
if (this->uart_ == UART_SELECTION_DEFAULT) {
this->uart_ = (UARTSelection) (LT_UART_DEFAULT_SERIAL + 1);
lt_log_set_port(LT_UART_DEFAULT_SERIAL);
} else {
lt_log_set_port(this->uart_ - 1);
}
lt_log_set_port(this->get_uart() - 1);
}
global_logger = this;
@@ -60,20 +43,6 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_DEFAULT:
return LOG_STR("DEFAULT");
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
case UART_SELECTION_UART2:
default:
return LOG_STR("UART2");
}
}
#ifdef USE_LIBRETINY_CRASH_HANDLER
bool crash_log_pending() { return libretiny::crash_handler_has_data(); }
void log_crash_to_client() { libretiny::crash_handler_log(); }
+10 -27
View File
@@ -26,20 +26,16 @@ void Logger::setup() {
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
switch (this->uart_) {
case UART_SELECTION_UART0:
this->hw_serial_ = &Serial1;
Serial1.begin(this->baud_rate_);
break;
case UART_SELECTION_UART1:
this->hw_serial_ = &Serial2;
Serial2.begin(this->baud_rate_);
break;
case UART_SELECTION_USB_CDC:
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
break;
}
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART1)
this->hw_serial_ = &Serial2;
Serial2.begin(this->baud_rate_);
#else
this->hw_serial_ = &Serial1;
Serial1.begin(this->baud_rate_);
#endif
}
global_logger = this;
ESP_LOGI(TAG, "Log initialized");
@@ -49,19 +45,6 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
default:
return LOG_STR("UNKNOWN");
}
}
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return rp2::crash_handler_has_data(); }
void log_crash_to_client() { rp2::crash_handler_log(); }
+13 -34
View File
@@ -42,7 +42,7 @@ __attribute__((section(".noinit"))) struct {
ESPHOME_LOG_TAG(TAG, "logger");
#ifdef USE_LOGGER_UART_SELECTION_USB_CDC
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
void Logger::cdc_loop_() {
if (this->uart_dev_ == nullptr) {
return;
@@ -75,25 +75,19 @@ void Logger::pre_setup() {
#ifdef CONFIG_SERIAL
if (this->baud_rate_ > 0) {
const struct device *uart_dev = nullptr;
switch (this->uart_) {
case UART_SELECTION_UART0: // NOLINT(bugprone-branch-clone)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
break;
case UART_SELECTION_UART1:
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
break;
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#if defined(CONFIG_USB_DEVICE_STACK) || defined(CONFIG_USB_DEVICE_STACK_NEXT)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
if (device_is_ready(uart_dev)) {
// Nothing can log this early, and the logger has no output without USB anyway
zephyr::usb_device_enable();
}
#endif
break;
#endif
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
if (device_is_ready(uart_dev)) {
// Nothing can log this early, and the logger has no output without USB anyway
zephyr::usb_device_enable();
}
#endif
#elif defined(USE_LOGGER_UART_SELECTION_UART1)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
#else
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
#endif
if (device_is_ready(uart_dev)) {
this->uart_dev_ = uart_dev;
#if defined(USE_LOGGER_WAIT_FOR_CDC) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
@@ -117,7 +111,7 @@ void Logger::pre_setup() {
this->dump_crash_();
#endif
// Nobody reads a USB port this early; cdc_loop_() reports the dump once the port is opened
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
// Without a UART (baud_rate: 0, or one that did not come up) nothing reaches the console
if (this->uart_dev_ != nullptr)
log_crash_to_client();
@@ -139,21 +133,6 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
}
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
#endif
default:
return LOG_STR("UNKNOWN");
}
}
static constexpr uint8_t REASON_BUF_SIZE = 32;
static const char *reason_to_str(unsigned int reason, char *buf) {
-165
View File
@@ -1,165 +0,0 @@
#include "at_reply.h"
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <strings.h>
namespace esphome::modem {
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole) {
const size_t capacity = size - 1;
if (whole) {
len = 0;
}
bool dropped = false;
if (data_len > capacity) {
memcpy(buf, data + data_len - capacity, capacity);
len = capacity;
dropped = true;
} else {
if (len + data_len > capacity) {
const size_t drop = len + data_len - capacity;
memmove(buf, buf + drop, len - drop);
len -= drop;
dropped = true;
}
memcpy(buf + len, data, data_len);
len += data_len;
}
buf[len] = '\0';
return dropped;
}
ReplyEnd reply_end(const char *data, size_t len, bool skip_first) {
const char *end = data + len;
const char *line = data;
if (skip_first) {
const auto *newline = static_cast<const char *>(memchr(data, '\n', len));
line = newline != nullptr ? newline + 1 : end;
}
while (line < end) {
const auto *newline = static_cast<const char *>(memchr(line, '\n', end - line));
if (newline == nullptr) {
break; // the line has not ended yet
}
size_t size = newline - line;
if (size != 0 && line[size - 1] == '\r') {
size--;
}
if (size == 2 && memcmp(line, "OK", 2) == 0) {
return ReplyEnd::REPLY_END_OK;
}
// esp_modem drops a CMUX frame without a line end, so the ": <reason>" part may be missing
if ((size == 5 && memcmp(line, "ERROR", 5) == 0) || (size >= 10 && memcmp(line, "+CME ERROR", 10) == 0) ||
(size >= 10 && memcmp(line, "+CMS ERROR", 10) == 0)) {
return ReplyEnd::REPLY_END_ERROR;
}
line = newline + 1;
}
return ReplyEnd::REPLY_END_NONE;
}
size_t flatten_reply(char *reply, size_t len) {
for (size_t i = 0; i < len; i++) {
if (reply[i] == '\r' || reply[i] == '\n') {
reply[i] = ' ';
}
}
while (len != 0 && reply[len - 1] == ' ') {
len--;
}
if (len >= 2 && memcmp(reply + len - 2, "OK", 2) == 0 && (len == 2 || reply[len - 3] == ' ')) {
len -= 2;
while (len != 0 && reply[len - 1] == ' ') {
len--;
}
}
size_t start = 0;
while (start < len && reply[start] == ' ') {
start++;
}
len -= start;
memmove(reply, reply + start, len);
reply[len] = '\0';
return len;
}
int registration_from_reply(const char *reply, const char *prefix) {
const size_t prefix_len = strlen(prefix);
for (const char *line = strstr(reply, prefix); line != nullptr; line = strstr(line + 1, prefix)) {
const char *start = line + prefix_len;
char *end = nullptr;
strtol(start, &end, 10);
if (end == start || *end != ',') {
continue;
}
start = end + 1;
const auto stat = static_cast<int32_t>(strtol(start, &end, 10));
if (end != start) {
return stat;
}
}
return REGISTRATION_UNKNOWN;
}
int merge_registration(int lte, int legacy) {
// A multimode modem can be registered or still searching on one network type while the other refuses it
if (is_registered(lte)) {
return lte;
}
if (is_registered(legacy)) {
return legacy;
}
// A definite answer from one query outweighs a timeout of the other
if (lte == REGISTRATION_SEARCHING || legacy == REGISTRATION_SEARCHING) {
return REGISTRATION_SEARCHING;
}
if (lte == REGISTRATION_DENIED || legacy == REGISTRATION_DENIED) {
return REGISTRATION_DENIED;
}
if (lte >= 0 || legacy >= 0) {
return lte >= 0 ? lte : legacy;
}
if (lte == REGISTRATION_NO_ANSWER || legacy == REGISTRATION_NO_ANSWER) {
return REGISTRATION_NO_ANSWER;
}
if (lte == REGISTRATION_UNSUPPORTED && legacy == REGISTRATION_UNSUPPORTED) {
return REGISTRATION_UNSUPPORTED;
}
return REGISTRATION_UNKNOWN;
}
bool reply_names_unsupported(const char *reply) {
static constexpr char PREFIX[] = "+CME ERROR:";
static constexpr char TEXT[] = "operation not supported";
const char *code = strstr(reply, PREFIX);
if (code == nullptr) {
return false;
}
code += sizeof(PREFIX) - 1;
while (*code == ' ') {
code++;
}
return strncasecmp(code, TEXT, sizeof(TEXT) - 1) == 0 || (code[0] == '4' && !isdigit(code[1]));
}
const char *sim_status(char *reply) {
static constexpr char PREFIX[] = "+CPIN:";
char *status = strstr(reply, PREFIX);
if (status == nullptr) {
return nullptr;
}
status += sizeof(PREFIX) - 1;
while (*status == ' ') {
status++;
}
// A URC in the same reply follows on its own line, which flatten_reply() turned into two spaces
char *end = strstr(status, " ");
if (end != nullptr) {
*end = '\0';
}
return status;
}
} // namespace esphome::modem
-67
View File
@@ -1,67 +0,0 @@
#pragma once
#include <cstddef>
#include <cstdint>
// Parsers for raw AT replies; free of esp_modem so they build and run in host unit tests
namespace esphome::modem {
enum class ReplyEnd : uint8_t {
REPLY_END_NONE, // no complete final result line yet
REPLY_END_OK, // an OK line
REPLY_END_ERROR, // an ERROR, +CME ERROR: or +CMS ERROR: line
};
// AT+CEREG? and AT+CREG? <stat> values (3GPP TS 27.007)
static constexpr int REGISTRATION_NOT_SEARCHING = 0;
static constexpr int REGISTRATION_HOME = 1;
static constexpr int REGISTRATION_SEARCHING = 2;
static constexpr int REGISTRATION_DENIED = 3;
static constexpr int REGISTRATION_REPORTED_UNKNOWN = 4;
static constexpr int REGISTRATION_ROAMING = 5;
static constexpr int REGISTRATION_SMS_ONLY_HOME = 6;
static constexpr int REGISTRATION_SMS_ONLY_ROAMING = 7;
static constexpr int REGISTRATION_EMERGENCY_ONLY = 8;
static constexpr int REGISTRATION_CSFB_NOT_PREFERRED_HOME = 9;
static constexpr int REGISTRATION_CSFB_NOT_PREFERRED_ROAMING = 10;
// Results beyond the 3GPP values
static constexpr int REGISTRATION_UNKNOWN = -1; // no readable answer
static constexpr int REGISTRATION_UNSUPPORTED = -2; // the query is not supported
static constexpr int REGISTRATION_NO_ANSWER = -3; // the query timed out
/// Registered on a network, so the data attach can be requested. SMS only and "CSFB not preferred" limit the
/// circuit switched side, not the packet data attach; emergency only (8) is not a registration.
inline bool is_registered(int registration) {
return registration == REGISTRATION_HOME || registration == REGISTRATION_ROAMING ||
(registration >= REGISTRATION_SMS_ONLY_HOME && registration <= REGISTRATION_SMS_ONLY_ROAMING) ||
(registration >= REGISTRATION_CSFB_NOT_PREFERRED_HOME &&
registration <= REGISTRATION_CSFB_NOT_PREFERRED_ROAMING);
}
/// Add data to the reply in buf (size includes the terminator, len is the current length). With whole, data is
/// everything received so far (UART) and replaces the reply; otherwise it is one new CMUX frame and is appended. A
/// reply longer than the buffer keeps its newest bytes, where the final line is. Returns true when bytes were dropped.
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole);
/// How the reply ends. Only a complete final result line counts, so ERROR inside a payload line does not; a +CME ERROR
/// line counts even without its reason, which a dropped CMUX frame can take away. With
/// skip_first, the first line is a cut-off fragment and is ignored.
ReplyEnd reply_end(const char *data, size_t len, bool skip_first);
/// Puts a raw reply on one line for the log and drops the final OK; returns the new length
size_t flatten_reply(char *reply, size_t len);
/// The <stat> after the first comma of the "<n>,<stat>" line starting with prefix (+CREG: and friends), or
/// REGISTRATION_UNKNOWN; a one-field line is an unsolicited notification and is skipped
int registration_from_reply(const char *reply, const char *prefix);
/// The state that tells most from the AT+CEREG? (LTE) and AT+CREG? (2G and 3G) results
int merge_registration(int lte, int legacy);
/// Whether an error reply says the command is not supported (+CME ERROR: 4 or its verbose text)
bool reply_names_unsupported(const char *reply);
/// The SIM status in a flattened AT+CPIN? reply, cut before any following line, or nullptr
const char *sim_status(char *reply);
} // namespace esphome::modem
+47 -296
View File
@@ -1,6 +1,5 @@
#ifdef USE_ESP32
#include "modem_component.h"
#include "at_reply.h"
#include "soc/soc_caps.h"
#include <driver/uart.h>
@@ -43,14 +42,6 @@ static constexpr uint32_t PROBE_TIMEOUT_MS = 100;
// A silent modem is not going to answer the next second, so its probes are spaced out, doubling up to a minute
static constexpr uint32_t PROBE_RETRY_DELAY_MS = 5000;
static constexpr uint32_t PROBE_RETRY_MAX_MS = 60000;
// A modem in command mode answers the ATE0 sent before the mode detection within this time
static constexpr uint32_t ECHO_OFF_TIMEOUT_MS = 100;
// The +++ escape needs a second of silence before it; esp_modem waits for the answer after it
static constexpr uint32_t ESCAPE_GUARD_MS = 1100;
// A SIM7670 left in CMUX by an ESP reset ignores every frame until this many flag bytes overflow its receive buffer;
// it then reinitialises its AT channel within about 2 s
static constexpr size_t CMUX_FLUSH_BYTES = 4096;
static constexpr uint32_t CMUX_FLUSH_SETTLE_MS = 3000;
// How long the task waits for the main loop to run on_sync before attaching
static constexpr uint32_t SYNC_ACK_TIMEOUT_MS = 5000;
// esp_modem's command strings and the log lines are built on this stack
@@ -65,12 +56,6 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
static constexpr uint32_t ATTACH_POLL_MS = 4000;
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
static constexpr uint8_t ATTACH_UNKNOWN_POLLS = 15; // about a minute of polls
// AT+CGATT=1: SIMCom documents up to 75 s, but a SIM7080G that is not registered yet held it for 141 s
static constexpr uint32_t ATTACH_TIMEOUT_MS = 150000;
// SIM status polls that fail before a warning, and between repeats of it
static constexpr uint8_t SIM_WARN_AFTER = 10;
static constexpr uint8_t SIM_WARN_EVERY = 60;
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
@@ -88,22 +73,8 @@ static const LogString *state_to_str(ModemState state) {
// Indexed by ModemFault
PROGMEM_STRING_TABLE(ModemFaultStrings, "", "Modem not responding", "Configured baud rate failed",
"init_at command failed", "SIM not ready", "SIM locked", "SIM PIN not sent; check pin_code",
"PIN record not saved", "APN or radio setup failed", "No network attachment",
"Network registration denied", "PPP link failed", "Modem teardown failed");
// Indexed by the AT+CEREG? <stat> value
PROGMEM_STRING_TABLE(RegistrationStrings, "not searching", "registered", "searching", "denied", "unknown", "roaming",
"registered for SMS only", "roaming for SMS only", "emergency only",
"registered, CSFB not preferred", "roaming, CSFB not preferred", "other");
static const LogString *registration_to_str(int registration) {
if (registration == REGISTRATION_UNSUPPORTED) {
return LOG_STR("not supported");
}
if (registration < 0) {
return LOG_STR("not reported");
}
return RegistrationStrings::get_log_str(static_cast<uint8_t>(registration), RegistrationStrings::LAST_INDEX);
}
"PIN record not saved", "APN or radio setup failed", "No network attachment", "PPP link failed",
"Modem teardown failed");
// Indexed by esp_modem::command_result
PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
@@ -615,9 +586,6 @@ ModemState ModemComponent::compute_next_state_() {
}
ModemState ModemComponent::handle_state_enabling_() {
// With echo on (SIM7670G after power-up), the modem sends esp_modem's PPP probe back and the detection takes it for
// a PPP reply; in PPP or CMUX these bytes are dropped as a bad frame
this->at_reply_("ATE0", ECHO_OFF_TIMEOUT_MS);
// Find the baud rate the modem answers at and leave it in command mode, synced
if (!this->dce_->set_mode(modem_mode::AUTODETECT)) {
// A failed detection keeps the previous mode, which would skip the baud rate search below
@@ -643,18 +611,21 @@ ModemState ModemComponent::handle_state_enabling_() {
exited = false;
const int bauds[] = {this->restored_baud_, this->baud_rate_, FALLBACK_BAUD_RATE};
bool found = false;
bool probed = false;
bool rejected = false;
for (size_t i = 0; i != std::size(bauds) && !found; i++) {
const int baud = bauds[i];
if (baud == 0 || baud == detected || std::find(bauds, bauds + i, baud) != bauds + i) {
continue;
}
if (this->set_uart_baud_(baud) != ESP_OK) {
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud) != ESP_OK) {
ESP_LOGW(TAG, "UART rejected baud rate %d", baud);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
rejected = true;
continue;
}
this->current_baud_rate_ = baud;
probed = true;
std::string output;
found = this->dce_->at("AT", output, PROBE_TIMEOUT_MS) == command_result::OK;
if (!found) {
@@ -662,31 +633,11 @@ ModemState ModemComponent::handle_state_enabling_() {
}
}
if (!found) {
// A modem left in data mode before PPP started, or stuck in CMUX, answers none of the probes; both recoveries
// go out at the rate the detection used
if (this->current_baud_rate_ != detected) {
const esp_err_t err = this->set_uart_baud_(detected);
if (err != ESP_OK) {
ESP_LOGW(TAG, "UART rejected baud rate %d (%s); data mode and CMUX recovery skipped", detected,
esp_err_to_name(err));
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
rejected = true;
}
}
// The escape before the flush is what a stuck SIM7670G responds to; the order is measured, not arbitrary
if (this->current_baud_rate_ == detected && (this->escape_data_mode_() || this->flush_cmux_())) {
exited = true;
break;
}
// A UART that refused a rate set BAUD
if (!rejected) {
// The detection at the current rate already failed; a UART that refused every other rate set BAUD
if (!probed && !rejected) {
this->not_responding_(detected);
}
const uint32_t delay_ms = this->next_probe_delay_();
if (delay_ms == PROBE_RETRY_MAX_MS) {
this->answered_ = false; // silent for minutes, so the wiring hint applies again
}
return this->retry_(ModemState::MODEM_STATE_ENABLING, delay_ms);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
break;
@@ -720,19 +671,10 @@ ModemState ModemComponent::handle_state_enabling_() {
this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
// The modem answers AT, so it is in command mode. A failed data mode exit leaves esp_modem's UART side in data mode,
// from where its later switch to CMUX fails at once, so its mode is set to match; this sends nothing to the modem.
if (!this->dce_->set_mode(modem_mode::RESUME_COMMAND_MODE)) {
ESP_LOGW(TAG, "esp_modem refused command mode; the switch to PPP may fail");
}
// esp_modem keeps the last line before OK as the reply, which can be the echoed command
if (this->dce_->set_echo(false) != command_result::OK) {
ESP_LOGW(TAG, "Failed to disable command echo");
}
// Verbose +CME ERROR text, so a failed command or a missing SIM says why; a modem without it keeps plain ERROR
if (this->dce_->config_mobile_termination_error(2) != command_result::OK) {
ESP_LOGW(TAG, "Modem refused verbose errors (AT+CMEE=2)");
}
// The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
// session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
@@ -748,7 +690,6 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGW(TAG, "Failed to power the SIM up");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
this->modem_synced_ = true; // it answers, so a disable() still tears it down
this->answered_ = true;
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
@@ -757,11 +698,12 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
if (this->dce_->set_baud(this->baud_rate_) == command_result::OK) {
delay(200); // NOLINT
if (this->set_uart_baud_(this->baud_rate_) != ESP_OK) {
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), this->baud_rate_) != ESP_OK) {
ESP_LOGE(TAG, "UART rejected baud rate %d", this->baud_rate_);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
return ModemState::MODEM_STATE_DISCONNECTING;
}
this->current_baud_rate_ = this->baud_rate_;
if (this->dce_->sync() != command_result::OK) {
ESP_LOGE(TAG, "Failed to sync modem at baud rate %d.", this->baud_rate_);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
@@ -789,7 +731,6 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGW(TAG, "Modem refused hardware flow control; UART overruns are possible");
}
this->modem_synced_ = true;
this->answered_ = true;
return ModemState::MODEM_STATE_SYNCED;
}
@@ -805,13 +746,12 @@ ModemState ModemComponent::handle_state_synced_() {
this->clear_config_fault_(ModemFault::MODEM_FAULT_INIT_AT);
}
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
this->sim_polls_ = 0;
return ModemState::MODEM_STATE_CONNECTING;
}
ModemState ModemComponent::handle_state_connecting_() {
if (this->connect_step_ == ConnectStep::CONNECT_STEP_START) {
// ENABLING just synced; a command that timed out comes back here unsure of the modem
// ENABLING just synced; only a failed attachment read comes back here unsure of the modem
if (this->resync_) {
this->resync_ = false;
if (this->dce_->sync() != command_result::OK) {
@@ -852,78 +792,35 @@ ModemState ModemComponent::handle_state_connecting_() {
}
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
this->attach_polls_ = 0;
this->idle_polls_ = 0;
this->unknown_polls_ = 0;
}
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON) {
// A modem still searching for a network refuses this; the attachment poll asks again
if (this->dce_->set_network_attachment_state(1) != command_result::OK) {
ESP_LOGD(TAG, "Network attachment request refused");
}
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
}
int attached = 0;
if (this->dce_->get_network_attachment_state(attached) != command_result::OK) {
ESP_LOGW(TAG, "Failed to read the network attachment state");
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->request_resync_();
this->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
this->resync_ = true;
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (!attached) {
const int registration = this->read_registration_();
if (registration == REGISTRATION_NO_ANSWER) {
// The state is open, so the modem is checked with a sync instead
ESP_LOGW(TAG, "No answer to a registration query");
this->request_resync_();
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
// "Not searching" for a few polls in a row means the attachment is off; right after CFUN=1 it is only brief
this->idle_polls_ = registration == REGISTRATION_NOT_SEARCHING ? static_cast<uint8_t>(this->idle_polls_ + 1) : 0;
const bool idle = this->idle_polls_ >= ATTACH_DIAG_EVERY;
// A state that cannot be read or means nothing here holds the request back only for a while
const bool unknown = registration == REGISTRATION_UNKNOWN || registration == REGISTRATION_REPORTED_UNKNOWN ||
(registration > REGISTRATION_ROAMING && !is_registered(registration));
this->unknown_polls_ = unknown ? static_cast<uint8_t>(this->unknown_polls_ + 1) : 0;
const bool unknown_too_long = this->unknown_polls_ >= ATTACH_UNKNOWN_POLLS;
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON &&
(is_registered(registration) || registration == REGISTRATION_UNSUPPORTED || idle || unknown_too_long)) {
if (unknown_too_long) {
ESP_LOGI(TAG, "Registration state %d (%s) for %u polls; requesting the network attachment anyway", registration,
LOG_STR_ARG(registration_to_str(registration)), this->unknown_polls_);
this->unknown_polls_ = 0;
}
// Before registration a modem can hold the AT channel on this for minutes and drop every command meanwhile,
// so it waits for one; the fallbacks above send it anyway, and ATTACH_TIMEOUT_MS covers that hold
const command_result attach = this->at_reply_("AT+CGATT=1", ATTACH_TIMEOUT_MS);
if (attach == command_result::TIMEOUT) {
ESP_LOGW(TAG, "No answer to the network attachment request");
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->request_resync_();
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (attach != command_result::OK) {
ESP_LOGW(TAG, "Network attachment request refused: %s", this->reply_);
}
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (this->attach_polls_++ % ATTACH_DIAG_EVERY == 0) {
int rssi = 99, ber = 99, mode = -1; // -1 stays when the query fails
int rssi = 99, ber = 99, registration = -1, mode = -1; // -1 stays when the query fails
this->dce_->get_network_registration_state(registration);
this->dce_->get_signal_quality(rssi, ber);
this->dce_->get_network_system_mode(mode);
ESP_LOGW(TAG, "Modem not attached yet: registration %d (%s), network type %d, CSQ %d, BER %d", registration,
LOG_STR_ARG(registration_to_str(registration)), mode, rssi, ber);
if (unknown) {
ESP_LOGW(TAG, "Network attachment request held back while the registration state is unknown (%u of %u polls)",
this->unknown_polls_, ATTACH_UNKNOWN_POLLS);
}
if (registration == REGISTRATION_DENIED) {
// The modem's reason tells a rejected APN (ESM failure) from a SIM the network does not serve
const command_result reason_read = this->at_reply_("AT+CEER");
ESP_LOGW(TAG,
"The network refused registration (AT+CEER %s: %s); check the APN and that the SIM's plan covers "
"this modem's network types",
LOG_STR_ARG(result_to_str(reason_read)), this->reply_);
}
ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
rssi, ber);
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
}
this->set_fault_(registration == REGISTRATION_DENIED ? ModemFault::MODEM_FAULT_REGISTRATION_DENIED
: ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
}
@@ -1026,114 +923,11 @@ void ModemComponent::transition_to_(ModemState next_state) {
}
}
esp_err_t ModemComponent::set_uart_baud_(int baud) {
const esp_err_t err = uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud);
if (err == ESP_OK) {
this->current_baud_rate_ = baud;
}
return err;
}
bool ModemComponent::escape_data_mode_() {
delay(ESCAPE_GUARD_MS); // NOLINT
if (this->dce_->set_command_mode() != command_result::OK) {
ESP_LOGD(TAG, "No answer after the data mode escape");
return false;
}
ESP_LOGW(TAG, "Modem was left in data mode; escaped to command mode");
return true;
}
bool ModemComponent::flush_cmux_() {
// With RTS/CTS a silent modem can hold CTS off; the flag bytes would then stay queued and block every later write
if (this->rts_pin_ != nullptr) {
ESP_LOGW(TAG, "CMUX recovery is not available with RTS/CTS flow control");
return false;
}
static constexpr uint8_t CMUX_FLAG = 0xF9;
uint8_t flags[64];
memset(flags, CMUX_FLAG, sizeof(flags));
const auto port = static_cast<uart_port_t>(this->uart_port_);
for (size_t sent = 0; sent < CMUX_FLUSH_BYTES; sent += sizeof(flags)) {
if (this->dte_->write(flags, sizeof(flags)) != static_cast<int>(sizeof(flags))) {
ESP_LOGW(TAG, "CMUX flush: short write after %u bytes", static_cast<unsigned>(sent));
return false;
}
}
// 10 bits per byte, plus a margin
const uint32_t send_ms = CMUX_FLUSH_BYTES * 10 * 1000 / this->current_baud_rate_ + 100;
if (uart_wait_tx_done(port, pdMS_TO_TICKS(send_ms)) != ESP_OK) {
ESP_LOGW(TAG, "CMUX flush: transmit not finished after %u ms", static_cast<unsigned>(send_ms));
return false;
}
delay(CMUX_FLUSH_SETTLE_MS); // NOLINT
if (this->dce_->sync() != command_result::OK) {
ESP_LOGD(TAG, "No answer after the CMUX flush");
return false;
}
ESP_LOGW(TAG, "Modem was stuck in CMUX; reset it to command mode");
return true;
}
// A command timed out: the next pass checks with a sync that the modem still answers
void ModemComponent::request_resync_() {
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
this->resync_ = true;
}
// One registration query: the <stat>, REGISTRATION_UNSUPPORTED, REGISTRATION_NO_ANSWER or REGISTRATION_UNKNOWN
int ModemComponent::read_stat_(const char *cmd, const char *prefix) {
const command_result result = this->at_reply_(cmd);
if (result == command_result::TIMEOUT) {
return REGISTRATION_NO_ANSWER;
}
if (result == command_result::FAIL && reply_names_unsupported(this->reply_)) {
return REGISTRATION_UNSUPPORTED;
}
const int stat = result == command_result::OK ? registration_from_reply(this->reply_, prefix) : REGISTRATION_UNKNOWN;
if (stat == REGISTRATION_UNKNOWN) {
// An error such as a SIM failure is a warning on the diagnostic polls, so it shows at the default log level
if (result == command_result::FAIL && this->attach_polls_ % ATTACH_DIAG_EVERY == 0) {
ESP_LOGW(TAG, "%s failed: %s", cmd, this->reply_);
} else {
ESP_LOGD(TAG, "%s gave no state: %s", cmd, this->reply_);
}
}
return stat;
}
// AT+CEREG covers LTE; on 2G and 3G the network registration is in AT+CREG, and AT+CGATT=1 is answered quickly once
// it is set. Returns the <stat> that tells most, or one of the negative REGISTRATION_ values.
int ModemComponent::read_registration_() {
const int lte = this->read_stat_("AT+CEREG?", "+CEREG:");
if (is_registered(lte)) {
return lte;
}
return merge_registration(lte, this->read_stat_("AT+CREG?", "+CREG:"));
}
void ModemComponent::not_responding_(int baud) {
if (this->answered_) {
// It answered before, so the wiring is fine; a long command or a modem restart keeps it silent for minutes
ESP_LOGW(TAG, "Modem not responding at %d baud; it may be busy or restarting", baud);
} else {
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
}
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
this->set_fault_(ModemFault::MODEM_FAULT_NO_RESPONSE);
}
void ModemComponent::sim_not_ready_(const char *reason) {
// A missing or broken SIM never gets ready; the status is polled every second, so only some polls warn
if (++this->sim_polls_ == SIM_WARN_AFTER + SIM_WARN_EVERY) {
this->sim_polls_ = SIM_WARN_AFTER;
}
if (this->sim_polls_ == SIM_WARN_AFTER) {
ESP_LOGW(TAG, "SIM not ready: %s. Check that a working SIM is inserted",
reason[0] != '\0' ? reason : LOG_STR_LITERAL("no reply"));
}
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
}
#ifdef USE_MODEM_SEND_AT
bool ModemComponent::send_at(const std::string &cmd, uint32_t timeout) { return this->send_at(cmd.c_str(), timeout); }
@@ -1160,54 +954,13 @@ bool ModemComponent::send_at(const char *cmd, uint32_t timeout) {
#endif
// at() keeps no text from a failed command, so the raw reply is collected into reply_ to show the +CME ERROR
command_result ModemComponent::at_reply_(const char *cmd, uint32_t timeout) {
std::string line = cmd; // poll commands fit the short string buffer
line += '\r';
this->reply_len_ = 0;
this->reply_[0] = '\0';
#ifdef CONFIG_ESP_MODEM_USE_INFLATABLE_BUFFER_IF_NEEDED
// The inflatable buffer gathers CMUX frames too, so every reply comes over whole each time
const bool whole = true;
#else
// esp_modem hands a UART reply over whole each time, and a CMUX reply one frame at a time
const modem_mode mode = this->dce_->get_mode();
const bool whole = mode != modem_mode::CMUX_MODE && mode != modem_mode::CMUX_MANUAL_MODE &&
mode != modem_mode::CMUX_MANUAL_DATA && mode != modem_mode::CMUX_MANUAL_COMMAND;
#endif
struct {
bool whole;
bool cut;
} state{whole, false};
const command_result result = this->dce_->command(
line,
[this, &state](const uint8_t *data, size_t len) {
// OK, or FAIL once an ERROR line has ended (the +CME ERROR reason may still be on its way), else TIMEOUT
state.cut |= collect_reply(this->reply_, sizeof(this->reply_), this->reply_len_,
reinterpret_cast<const char *>(data), len, state.whole);
switch (reply_end(this->reply_, this->reply_len_, state.cut)) {
case ReplyEnd::REPLY_END_OK:
return command_result::OK;
case ReplyEnd::REPLY_END_ERROR:
return command_result::FAIL;
default:
return command_result::TIMEOUT;
}
},
timeout);
this->reply_len_ = flatten_reply(this->reply_, this->reply_len_);
this->reply_cut_ = state.cut;
return result;
}
command_result ModemComponent::at_(const char *cmd, uint32_t timeout) {
const command_result result = this->at_reply_(cmd, timeout);
// A reply longer than the buffer kept only its end
const char *cut = this->reply_cut_ ? LOG_STR_LITERAL("...") : "";
std::string output;
const command_result result = this->dce_->at(cmd, output, timeout);
if (result == command_result::OK) {
ESP_LOGI(TAG, "AT '%s' -> OK: %s%s", cmd, cut, this->reply_);
ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
} else {
ESP_LOGW(TAG, "AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
}
return result;
}
@@ -1220,27 +973,25 @@ SimResult ModemComponent::prepare_sim_() {
return SimResult::SIM_RESULT_RETRY; // the save wakes the task
}
#endif
// The raw reply keeps the +CME ERROR text a missing SIM gives; status below points into it
const command_result result = this->at_reply_("AT+CPIN?");
if (result == command_result::TIMEOUT) {
// The next pass checks with a sync whether the modem or only the SIM interface is silent
ESP_LOGD(TAG, "No answer to the SIM status request");
this->sim_not_ready_(LOG_STR_LITERAL("no answer to AT+CPIN?"));
this->request_resync_();
return SimResult::SIM_RESULT_RETRY;
}
if (result != command_result::OK) {
std::string output;
if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
// A SIM that is still starting answers with an error for a second or so
ESP_LOGD(TAG, "SIM status not readable yet: %s", this->reply_);
this->sim_not_ready_(this->reply_);
ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
return SimResult::SIM_RESULT_RETRY;
}
// Anything else, such as an echoed command, is not a status and must not reach the lock checks below
const char *found = sim_status(this->reply_);
const char *found = strstr(output.c_str(), "+CPIN:");
if (found != nullptr) {
found += sizeof("+CPIN:") - 1;
while (*found == ' ') {
found++;
}
}
const StringRef status = found != nullptr ? StringRef(found) : StringRef();
if (status.empty()) {
ESP_LOGD(TAG, "SIM status not reported yet: %s", this->reply_);
this->sim_not_ready_(this->reply_);
ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
return SimResult::SIM_RESULT_RETRY;
}
ESP_LOGD(TAG, "SIM: %s", status.c_str());
@@ -1268,8 +1019,8 @@ SimResult ModemComponent::prepare_sim_() {
this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
return SimResult::SIM_RESULT_LOCKED;
}
ESP_LOGD(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
this->sim_not_ready_(status.c_str());
ESP_LOGW(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
return SimResult::SIM_RESULT_RETRY;
}
#ifdef USE_MODEM_PIN_CODE
+1 -22
View File
@@ -62,7 +62,6 @@ enum class ModemFault : uint8_t {
MODEM_FAULT_PIN_RECORD,
MODEM_FAULT_SETUP,
MODEM_FAULT_NOT_ATTACHED,
MODEM_FAULT_REGISTRATION_DENIED,
MODEM_FAULT_PPP,
MODEM_FAULT_TEARDOWN,
};
@@ -152,7 +151,6 @@ class ModemComponent : public Component {
static constexpr uint32_t RETRY_DELAY_MS = 1000;
static constexpr size_t URC_LINE_SIZE = 128;
static constexpr size_t AT_COMMAND_SIZE = 128;
static constexpr size_t REPLY_SIZE = 256; // a longer reply keeps its newest bytes, so its final line counts
#ifdef USE_MODEM_POLL
static constexpr uint8_t CSQ_UNKNOWN = 99; // AT+CSQ rssi or ber the modem cannot tell
static constexpr uint8_t CSQ_RSSI_MAX = 31;
@@ -202,20 +200,8 @@ class ModemComponent : public Component {
void hand_over_(uint32_t pending);
/// Send an AT command from the task and log the result; blocks for up to the timeout
esp_modem::command_result at_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
/// Send an AT command; reply_ gets the whole reply on one line, including any +CME ERROR text
esp_modem::command_result at_reply_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
void publish_status_();
/// Send the +++ escape with its guard times; true when the modem answered
bool escape_data_mode_();
/// Overflow a stuck CMUX receiver with flag bytes; true when the modem answers AT afterwards
bool flush_cmux_();
void request_resync_();
int read_stat_(const char *cmd, const char *prefix);
int read_registration_();
/// Set the UART rate; current_baud_rate_ follows when the UART takes it
esp_err_t set_uart_baud_(int baud);
void not_responding_(int baud);
void sim_not_ready_(const char *reason);
void dump_connect_params_();
SimResult prepare_sim_();
#ifdef USE_MODEM_PIN_CODE
@@ -235,9 +221,6 @@ class ModemComponent : public Component {
const char *urc_line_{nullptr}; // the line urc_pending_ hands to loop(), inside urc_reader_
#endif
std::unique_ptr<esp_modem::DCE> dce_;
char reply_[REPLY_SIZE + 1]{}; // task only; the last reply, null-terminated
size_t reply_len_{0};
bool reply_cut_{false}; // the last reply was longer than reply_ and kept only its end
std::shared_ptr<esp_modem::DTE> dte_;
esp_netif_t *ppp_netif_{nullptr};
ESPPreferenceObject pref_;
@@ -308,9 +291,6 @@ class ModemComponent : public Component {
uint8_t init_at_count_{0};
uint8_t uart_port_{UART_NUM_MAX};
uint8_t attach_polls_{0};
uint8_t idle_polls_{0}; // polls in a row that reported "not searching"
uint8_t unknown_polls_{0}; // polls in a row with no usable registration state
uint8_t sim_polls_{0}; // failed SIM status reads in this attempt
#ifdef USE_MODEM_POLL
uint8_t poll_rssi_{CSQ_UNKNOWN}; // raw AT+CSQ answers
uint8_t poll_ber_{CSQ_UNKNOWN};
@@ -318,8 +298,7 @@ class ModemComponent : public Component {
#endif
bool connect_timeout_armed_{false};
bool modem_synced_{false}; // a modem that never answered has nothing to tear down
bool answered_{false}; // the modem synced since boot, so its wiring and power are fine
bool resync_{false}; // a command timed out, so CONNECTING syncs again first
bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
#ifdef USE_MODEM_SEND_AT
char at_command_[AT_COMMAND_SIZE];
+4 -16
View File
@@ -323,18 +323,12 @@ bool MQTTClientComponent::can_proceed() {
}
void MQTTClientComponent::start_dnslookup_() {
this->status_set_warning();
// No lookup can start before the network is up: there is no DNS server to ask yet.
// Stay disconnected, and loop() calls this again as soon as it is up.
this->waiting_for_network_ = !network::is_connected();
if (this->waiting_for_network_)
return;
for (auto &subscription : this->subscriptions_) {
subscription.subscribed = false;
subscription.resubscribe_timeout = 0;
}
this->status_set_warning();
this->dns_resolve_error_ = false;
this->dns_resolved_ = false;
ip_addr_t addr;
@@ -364,13 +358,9 @@ void MQTTClientComponent::start_dnslookup_() {
}
default:
case ERR_ARG: {
// The lookup never started, so there is no answer to wait for; loop() tries again in 5 seconds
// error
ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
this->state_ = MQTT_CLIENT_DISCONNECTED;
this->disconnect_reason_ = MQTTClientDisconnectReason::DNS_RESOLVE_ERROR;
this->on_disconnect_.call(MQTTClientDisconnectReason::DNS_RESOLVE_ERROR);
this->connect_begin_ = millis();
return;
break;
}
}
@@ -515,9 +505,7 @@ void MQTTClientComponent::loop() {
case MQTT_CLIENT_DISABLED:
return; // Return to avoid a reboot when disabled
case MQTT_CLIENT_DISCONNECTED:
// Back off 5 s after a failed attempt. Without a network no attempt was made, so the
// first one starts as soon as the network is up instead of 5 s after boot.
if (this->waiting_for_network_ || now - this->connect_begin_ > 5000) {
if (now - this->connect_begin_ > 5000) {
this->start_dnslookup_();
}
break;
-2
View File
@@ -436,8 +436,6 @@ class MQTTClientComponent final : public Component {
network::IPAddress ip_;
bool dns_resolved_{false};
bool dns_resolve_error_{false};
/// The last start_dnslookup_() found no network, so no attempt was made and there is nothing to back off from
bool waiting_for_network_{false};
bool enable_on_boot_{true};
#ifdef USE_MQTT_CRASH_LOG
bool crash_log_offered_{false};
+39 -117
View File
@@ -1,5 +1,4 @@
from collections.abc import Callable
import logging
from esphome import automation
import esphome.codegen as cg
@@ -9,8 +8,6 @@ import esphome.config_validation as cv
from esphome.const import CONF_DURATION, CONF_ID, CONF_MODE, CONF_VOLTAGE
from esphome.types import ConfigType
_LOGGER = logging.getLogger(__name__)
CODEOWNERS = ["@tomaszduda23"]
DEPENDENCIES = ["i2c"]
DOMAIN = "npm1300"
@@ -45,18 +42,20 @@ NPM1300_CHILD_SCHEMA = cv.Schema(
{cv.GenerateID(CONF_NPM1300_ID): cv.use_id(NPM1300Component)}
)
NPM1300Status = npm1300_ns.struct("NPM1300Status")
# The status registers read on each update
# Status registers read on each update: VBUSINSTATUS, BCHGCHARGESTATUS and BCHGERRREASON
STATUS_PUBLISHER = cg.HubFunction(
"status",
cg.void,
[(NPM1300Status.operator("const").operator("ref"), "status")],
[
(cg.uint8, "vbus_status"),
(cg.uint8, "charge_status"),
(cg.uint8, "error_reason"),
],
define="USE_NPM1300_STATUS_PUBLISHER",
)
STATUS = STATUS_PUBLISHER.param("status")
VBUS_STATUS = STATUS.vbus
CHARGE_STATUS = STATUS.charge
ERROR_REASON = STATUS.error_reason
VBUS_STATUS = STATUS_PUBLISHER.param("vbus_status")
CHARGE_STATUS = STATUS_PUBLISHER.param("charge_status")
ERROR_REASON = STATUS_PUBLISHER.param("error_reason")
# The ADC results and the amperes per code of the battery current
DATA_PUBLISHER = cg.HubFunction(
"data",
@@ -78,10 +77,7 @@ OUTPUTS = NPM1300Output.options(
# Written for a field the YAML leaves out
NPM1300_UNSET = 0xFF
# ADCNTCRSEL codes, by kiloohms
THERMISTOR_NONE = "none"
THERMISTOR_RESISTANCES = {10: 1, 47: 2, 100: 3}
# B25/50 of the thermistors the product specification lists for each resistance, by kiloohms
THERMISTOR_BETAS = {10: 3380, 47: 4050, 100: 4250}
LDO_MODES = {"load_switch": 0, "ldo": 1}
TERMINATION_CURRENTS = {"10%": 0, "20%": 1}
# BCHGVTRICKLESEL, by millivolts
@@ -105,13 +101,14 @@ def _one_of_units(
validator: Callable[[object], float],
allowed: list[int],
unit: str,
scale: float = 1000,
) -> Callable[[object], float]:
"""Validate a quantity with `validator` and accept only the listed values, given in thousandths of `unit`."""
"""Validate a quantity with `validator` and accept only the listed values, given in units * `scale`."""
def validate(value: object) -> float:
value = validator(value)
if _millis(value) not in allowed:
options = ", ".join(f"{v / 1000:g}{unit}" for v in allowed)
if round(value * scale) not in allowed:
options = ", ".join(f"{v / scale:g}{unit}" for v in allowed)
raise cv.Invalid(f"Must be one of {options}")
return value
@@ -138,23 +135,6 @@ def _stepped(
return validate
def _thermistor_resistance(value: object) -> float | str:
if isinstance(value, str) and value.lower() == THERMISTOR_NONE:
return THERMISTOR_NONE
value = cv.resistance(value)
if round(value) not in (kilohms * 1000 for kilohms in THERMISTOR_RESISTANCES):
options = ", ".join(f"{kilohms}kOhm" for kilohms in THERMISTOR_RESISTANCES)
raise cv.Invalid(f"Must be one of {options} or {THERMISTOR_NONE}")
return value
def thermistor_beta(config: ConfigType) -> int:
"""The B constant of the hub's thermistor: the configured one, or the one listed for its resistance."""
if (beta := config.get(CONF_THERMISTOR_BETA)) is not None:
return beta
return THERMISTOR_BETAS[round(config[CONF_THERMISTOR_RESISTANCE] / 1000)]
OUTPUT_VOLTAGE = _stepped(cv.voltage, 1000, 3300, 100, "V")
VBUS_CURRENT_LIMIT = _stepped(cv.current, 100, 1500, 100, "A")
@@ -170,58 +150,15 @@ LDO_SCHEMA = BUCK_SCHEMA.extend(
}
)
WARM_TERMINATION_VOLTAGE_DEFAULT = 3.6
def _warm_termination_default(config: ConfigType) -> ConfigType:
"""Keep the default warm termination voltage at or below the termination voltage.
Warn when the default stays below a higher termination voltage.
"""
if (
not isinstance(config, dict)
or CONF_WARM_TERMINATION_VOLTAGE in config
or CONF_TERMINATION_VOLTAGE not in config
):
return config
try:
termination = cv.voltage(config[CONF_TERMINATION_VOLTAGE])
except cv.Invalid:
# The schema reports it
return config
if termination < WARM_TERMINATION_VOLTAGE_DEFAULT - 0.001:
# A warm battery is never charged higher than a cool one
return {
**config,
CONF_WARM_TERMINATION_VOLTAGE: config[CONF_TERMINATION_VOLTAGE],
}
if termination > WARM_TERMINATION_VOLTAGE_DEFAULT + 0.001:
_LOGGER.warning(
"npm1300 '%s' is not set, so a warm battery (45 °C to 60 °C by default) stops "
"charging at %.2fV instead of the %.2fV of '%s'. Set '%s' to the value your "
"battery allows when warm",
CONF_WARM_TERMINATION_VOLTAGE,
WARM_TERMINATION_VOLTAGE_DEFAULT,
termination,
CONF_TERMINATION_VOLTAGE,
CONF_WARM_TERMINATION_VOLTAGE,
)
return config
_CHARGER_SETTINGS_SCHEMA = cv.Schema(
CHARGER_SCHEMA = cv.Schema(
{
# Defaults are the reset values of the product specification
cv.Optional(CONF_CHARGE_CURRENT, default="32mA"): _stepped(
cv.current, 32, 800, 2, "A"
cv.Required(CONF_CHARGE_CURRENT): _stepped(cv.current, 32, 800, 2, "A"),
cv.Optional(CONF_TERMINATION_VOLTAGE, default="4.2V"): _one_of_units(
cv.voltage, TERMINATION_VOLTAGES, "V"
),
cv.Optional(CONF_TERMINATION_VOLTAGE, default="3.6V"): _one_of_units(
cv.Optional(CONF_WARM_TERMINATION_VOLTAGE): _one_of_units(
cv.voltage, TERMINATION_VOLTAGES, "V"
),
cv.Optional(
CONF_WARM_TERMINATION_VOLTAGE,
default=f"{WARM_TERMINATION_VOLTAGE_DEFAULT}V",
): _one_of_units(cv.voltage, TERMINATION_VOLTAGES, "V"),
cv.Optional(CONF_TERMINATION_CURRENT, default="10%"): cv.enum(
TERMINATION_CURRENTS
),
@@ -232,37 +169,22 @@ _CHARGER_SETTINGS_SCHEMA = cv.Schema(
cv.current, list(DISCHARGE_CURRENT_LIMITS), "A"
),
cv.Optional(CONF_RECHARGE, default=True): cv.boolean,
cv.Optional(CONF_ENABLED, default=False): cv.boolean,
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
}
)
CHARGER_SCHEMA = cv.All(_warm_termination_default, _CHARGER_SETTINGS_SCHEMA)
def _check_thermistor(config: ConfigType) -> ConfigType:
"""A wrong thermistor shifts the battery temperature the charger sees, so charging needs one chosen."""
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
if CONF_CHARGER in config and resistance is None:
raise cv.Invalid(
f"'{CONF_THERMISTOR_RESISTANCE}' is required with '{CONF_CHARGER}': set the nominal "
f"resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
path=[CONF_THERMISTOR_RESISTANCE],
)
if CONF_THERMISTOR_BETA in config and resistance in (None, THERMISTOR_NONE):
raise cv.Invalid(
f"'{CONF_THERMISTOR_BETA}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
"resistance of the thermistor",
path=[CONF_THERMISTOR_BETA],
)
return config
CONFIG_SCHEMA = cv.All(
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(NPM1300Component),
cv.Optional(CONF_VBUS_CURRENT_LIMIT): VBUS_CURRENT_LIMIT,
cv.Optional(CONF_THERMISTOR_RESISTANCE): _thermistor_resistance,
cv.Optional(CONF_THERMISTOR_BETA): cv.int_range(min=1, max=65535),
cv.Optional(CONF_THERMISTOR_RESISTANCE): _one_of_units(
cv.resistance, list(THERMISTOR_RESISTANCES), "kOhm", scale=0.001
),
cv.Optional(CONF_THERMISTOR_BETA, default=3380): cv.int_range(
min=1, max=65535
),
cv.Optional(CONF_CHARGER): CHARGER_SCHEMA,
cv.Optional(CONF_BUCK1): BUCK_SCHEMA,
cv.Optional(CONF_BUCK2): BUCK_SCHEMA,
@@ -271,8 +193,7 @@ CONFIG_SCHEMA = cv.All(
}
)
.extend(cv.polling_component_schema("60s"))
.extend(i2c.i2c_device_schema(0x6B)),
_check_thermistor,
.extend(i2c.i2c_device_schema(0x6B))
)
@@ -287,7 +208,7 @@ def _vbus_current_limit_code(amps: float) -> int:
def _charger_config(config: ConfigType) -> cg.StructInitializer:
termination = _termination_voltage_code(config[CONF_TERMINATION_VOLTAGE])
warm = _termination_voltage_code(config[CONF_WARM_TERMINATION_VOLTAGE])
warm = config.get(CONF_WARM_TERMINATION_VOLTAGE)
return cg.StructInitializer(
NPM1300ChargerConfig,
("current", _millis(config[CONF_CHARGE_CURRENT]) // 2),
@@ -296,7 +217,10 @@ def _charger_config(config: ConfigType) -> cg.StructInitializer:
DISCHARGE_CURRENT_LIMITS[_millis(config[CONF_DISCHARGE_CURRENT_LIMIT])],
),
("termination_voltage", termination),
("warm_termination_voltage", warm),
(
"warm_termination_voltage",
termination if warm is None else _termination_voltage_code(warm),
),
("trickle_voltage", TRICKLE_VOLTAGES[_millis(config[CONF_TRICKLE_VOLTAGE])]),
("termination_current", TERMINATION_CURRENTS[config[CONF_TERMINATION_CURRENT]]),
("recharge", config[CONF_RECHARGE]),
@@ -323,13 +247,6 @@ def _output_config(config: ConfigType | None) -> cg.StructInitializer:
def _config(config: ConfigType) -> cg.StructInitializer:
charger = config.get(CONF_CHARGER)
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
if resistance is None:
thermistor, beta = NPM1300_UNSET, 0
elif resistance == THERMISTOR_NONE:
thermistor, beta = 0, 0
else:
thermistor = THERMISTOR_RESISTANCES[round(resistance / 1000)]
beta = thermistor_beta(config)
return cg.StructInitializer(
NPM1300Config,
(
@@ -337,8 +254,13 @@ def _config(config: ConfigType) -> cg.StructInitializer:
cg.ArrayInitializer(*(_output_config(config.get(key)) for key in OUTPUTS)),
),
("charger", None if charger is None else _charger_config(charger)),
("thermistor_beta", beta),
("thermistor", thermistor),
("thermistor_beta", config[CONF_THERMISTOR_BETA]),
(
"thermistor",
NPM1300_UNSET
if resistance is None
else THERMISTOR_RESISTANCES[round(resistance / 1000)],
),
("charger_configured", charger is not None),
)
+34 -51
View File
@@ -29,7 +29,6 @@ static constexpr uint16_t REG_BCHG_VTERM = 0x030C;
static constexpr uint16_t REG_BCHG_VTERM_R = 0x030D;
static constexpr uint16_t REG_BCHG_VTRICKLE_SEL = 0x030E;
static constexpr uint16_t REG_BCHG_ITERM_SEL = 0x030F;
static constexpr uint16_t REG_BCHG_NTC_STATUS = 0x0332;
static constexpr uint16_t REG_BCHG_CHARGE_STATUS = 0x0334;
static constexpr uint16_t REG_BCHG_ERR_REASON = 0x0336;
static constexpr uint16_t REG_BUCK1_ENA_SET = 0x0400;
@@ -54,9 +53,6 @@ static constexpr uint16_t REG_SHIP_TASK_SHIP_MODE = 0x0B02;
// VBUSINSTATUS
static constexpr uint8_t VBUS_PRESENT = 0x01;
// NTCSTATUS
static constexpr uint8_t NTC_STATUS_COLD = 0x01;
static constexpr uint8_t NTC_STATUS_HOT = 0x08;
// BCHGCHARGESTATUS; bit 0 (battery detected) is reserved since C00 silicon
static constexpr uint8_t CHARGE_STATUS_COMPLETED = 0x02;
static constexpr uint8_t CHARGE_STATUS_TRICKLE = 0x04;
@@ -111,36 +107,26 @@ float ntc_temperature(uint16_t code, float inv_beta) {
#endif
#ifdef USE_TEXT_SENSOR
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Discharging", "Error", "Disabled", "Paused, PMIC Too Hot",
"Charge Complete", "Trickle Charge", "Constant Current", "Constant Voltage",
"Paused, Battery Too Cold", "Paused, Battery Too Hot", "Not Charging");
static constexpr uint8_t CHARGER_STATUS_FIRST_BIT = 3;
// BCHGCHARGESTATUS bits in order of priority, reported from string CHARGER_STATUS_FIRST_BIT on
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Error", "Paused, Die Too Hot", "Charge Complete", "Trickle Charge",
"Constant Current", "Constant Voltage", "Discharging", "Not Charging");
// BCHGCHARGESTATUS bits in order of priority; bit i is reported as string i + 1
static const uint8_t CHARGER_STATUS_BITS[] PROGMEM = {CHARGE_STATUS_DIE_TEMP_HIGH, CHARGE_STATUS_COMPLETED,
CHARGE_STATUS_TRICKLE, CHARGE_STATUS_CONSTANT_CURRENT,
CHARGE_STATUS_CONSTANT_VOLTAGE};
static uint8_t charger_status_index(const NPM1300Status &status) {
if ((status.vbus & VBUS_PRESENT) == 0)
static uint8_t charger_status_index(uint8_t vbus_status, uint8_t charge_status, uint8_t error_reason) {
if (error_reason != 0)
return 0;
if (status.error_reason != 0)
return 1;
if ((status.charger_enable & 1) == 0)
return 2;
for (size_t i = 0; i < sizeof(CHARGER_STATUS_BITS); i++) {
if ((status.charge & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
return CHARGER_STATUS_FIRST_BIT + i;
if ((charge_status & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
return i + 1;
}
// The charger stops without an error outside the cold and hot limits of the battery temperature
if ((status.ntc & NTC_STATUS_COLD) != 0)
return 8;
if ((status.ntc & NTC_STATUS_HOT) != 0)
return 9;
return 10;
return (vbus_status & VBUS_PRESENT) == 0 ? 6 : 7;
}
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status) {
const uint8_t index = charger_status_index(status);
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
uint8_t error_reason) {
const uint8_t index = charger_status_index(vbus_status, charge_status, error_reason);
if (index == last)
return;
last = index;
@@ -212,7 +198,7 @@ bool NPM1300Component::configure_charger_(const NPM1300Config &config) {
split_9bit(charger.discharge_limit, discharge);
uint8_t disable = charger.recharge ? 0 : CHARGER_DISABLE_RECHARGE;
// Without a thermistor the charger reports an NTC error and does not charge
if (config.thermistor == 0 || config.thermistor == NPM1300_UNSET)
if (config.thermistor == NPM1300_UNSET)
disable |= CHARGER_DISABLE_NTC;
const uint8_t enable = (CHARGER_DISABLE_RECHARGE | CHARGER_DISABLE_NTC) & ~disable;
if (this->write_register16(REG_BCHG_ISET_MSB, current, sizeof(current)) != i2c::ERROR_OK ||
@@ -306,40 +292,33 @@ void NPM1300Component::hibernate(uint32_t duration_ms) {
}
void NPM1300Component::update() {
NPM1300Status status;
// NTCSTATUS, DIETEMPSTATUS and BCHGCHARGESTATUS
uint8_t charger_status[3];
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &status.vbus) &&
this->read_byte_reg16(REG_BCHG_ENABLE_SET, &status.charger_enable) &&
this->read_register16(REG_BCHG_NTC_STATUS, charger_status, sizeof(charger_status)) ==
i2c::ERROR_OK &&
this->read_byte_reg16(REG_BCHG_ERR_REASON, &status.error_reason)))
uint8_t vbus_status;
uint8_t charge_status;
uint8_t error_reason;
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &vbus_status) &&
this->read_byte_reg16(REG_BCHG_CHARGE_STATUS, &charge_status) &&
this->read_byte_reg16(REG_BCHG_ERR_REASON, &error_reason)))
return;
status.ntc = charger_status[0];
status.charge = charger_status[2];
// Without a thermistor the NTC pin is grounded and can read as a hot battery
if (progmem_read_byte(&this->config_->thermistor) == 0)
status.ntc = 0;
// The chip goes back to its default VBUS current limit whenever VBUS is removed
const bool vbus_present = (status.vbus & VBUS_PRESENT) != 0;
const bool vbus_present = (vbus_status & VBUS_PRESENT) != 0;
if (vbus_present && !this->vbus_present_ && this->vbus_current_limit_ != NPM1300_UNSET &&
!this->status_comm_check(this->apply_vbus_current_limit_()))
return;
this->vbus_present_ = vbus_present;
if (status.error_reason != this->last_error_reason_) {
this->last_error_reason_ = status.error_reason;
if (status.error_reason != 0) {
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", status.error_reason);
if (error_reason != this->last_error_reason_) {
this->last_error_reason_ = error_reason;
if (error_reason != 0) {
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", error_reason);
}
}
#ifdef USE_NPM1300_STATUS_PUBLISHER
if (this->status_publisher_ != nullptr)
this->status_publisher_(status);
this->status_publisher_(vbus_status, charge_status, error_reason);
#endif
#ifdef USE_SWITCH
if (!this->status_comm_check(this->publish_switches_(status)))
if (!this->status_comm_check(this->publish_switches_()))
return;
#endif
@@ -369,10 +348,16 @@ void NPM1300Component::update() {
}
#ifdef USE_SWITCH
bool NPM1300Component::publish_switches_(const NPM1300Status &status) {
PUBLISH_STATE(this->charger_switch_, (status.charger_enable & 1) != 0);
bool NPM1300Component::publish_switches_() {
uint8_t value;
bool ok = true;
if (this->charger_switch_ != nullptr) {
if (this->read_byte_reg16(REG_BCHG_ENABLE_SET, &value)) {
this->charger_switch_->publish_state((value & 1) != 0);
} else {
ok = false;
}
}
switch_::Switch *const bucks[2] = {this->buck1_switch_, this->buck2_switch_};
if (bucks[0] != nullptr || bucks[1] != nullptr) {
if (this->read_byte_reg16(REG_BUCK_STATUS, &value)) {
@@ -476,9 +461,7 @@ void NPM1300Component::dump_config() {
ESP_LOGCONFIG(TAG, " Enabled at boot: %s", YESNO(output.enabled != 0));
}
}
if (config.thermistor == 0) {
ESP_LOGCONFIG(TAG, " Thermistor: none");
} else if (config.thermistor != NPM1300_UNSET) {
if (config.thermistor != NPM1300_UNSET) {
ESP_LOGCONFIG(TAG, " Thermistor B constant: %u", config.thermistor_beta);
}
#ifdef USE_SENSOR
+5 -13
View File
@@ -54,19 +54,10 @@ struct NPM1300Config {
NPM1300OutputConfig outputs[NPM1300_OUTPUT_COUNT];
NPM1300ChargerConfig charger; // only applied when charger_configured
uint16_t thermistor_beta;
uint8_t thermistor; // ADCNTCRSEL code: 0 for none, 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
uint8_t thermistor; // ADCNTCRSEL code: 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
bool charger_configured;
};
/// The status registers read on every update
struct NPM1300Status {
uint8_t vbus; // VBUSINSTATUS
uint8_t charger_enable; // BCHGENABLESET
uint8_t ntc; // NTCSTATUS
uint8_t charge; // BCHGCHARGESTATUS
uint8_t error_reason; // BCHGERRREASON
};
#ifdef USE_NPM1300_DATA_PUBLISHER
/// The 10-bit ADC result whose high 8 bits are adc[msb] and low 2 bits are at `shift` in adc[lsbs]
inline uint16_t adc_code(const uint8_t *adc, uint8_t msb, uint8_t lsbs, uint8_t shift) {
@@ -77,7 +68,8 @@ float ntc_temperature(uint16_t code, float inv_beta);
#endif
#ifdef USE_TEXT_SENSOR
/// Publish the charger status text, only when it differs from `last`
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status);
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
uint8_t error_reason);
#endif
class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
@@ -103,7 +95,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
float get_setup_priority() const override { return setup_priority::BUS - 1.0f; }
#ifdef USE_NPM1300_STATUS_PUBLISHER
HUB_PUBLISHER(status, const NPM1300Status &)
HUB_PUBLISHER(status, uint8_t, uint8_t, uint8_t)
#endif
#ifdef USE_NPM1300_DATA_PUBLISHER
HUB_PUBLISHER(data, const uint8_t *, float)
@@ -136,7 +128,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
#endif
#ifdef USE_SWITCH
/// Returns false when a status read failed
bool publish_switches_(const NPM1300Status &status);
bool publish_switches_();
#endif
const NPM1300Config *config_;
+5 -6
View File
@@ -21,6 +21,7 @@ from esphome.types import ConfigType
from . import (
ADC,
CONF_NPM1300_ID,
CONF_THERMISTOR_BETA,
CONF_THERMISTOR_RESISTANCE,
CONF_VBUS_CURRENT_LIMIT,
DATA_PUBLISHER,
@@ -29,9 +30,7 @@ from . import (
DUMP_TAG,
IBAT_SCALE,
NPM1300_CHILD_SCHEMA,
THERMISTOR_NONE,
npm1300_ns,
thermistor_beta,
)
DEPENDENCIES = ["npm1300"]
@@ -110,10 +109,10 @@ def _final_validate(config: ConfigType) -> None:
if CONF_BATTERY_TEMPERATURE not in config:
return
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
if hub.get(CONF_THERMISTOR_RESISTANCE, THERMISTOR_NONE) == THERMISTOR_NONE:
if CONF_THERMISTOR_RESISTANCE not in hub:
raise cv.Invalid(
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
"nominal resistance of the battery thermistor on the npm1300 component",
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' "
"set on the npm1300 component",
path=[CONF_BATTERY_TEMPERATURE],
)
@@ -146,7 +145,7 @@ async def to_code(config: ConfigType) -> None:
if (var := await sensors(CONF_BATTERY_TEMPERATURE, None)) is not None:
hub_config = next(c for c in CORE.config[DOMAIN] if c[CONF_ID] == hub_id)
state = npm1300_ns.ntc_temperature(
_adc(2, 5, 2), 1.0 / thermistor_beta(hub_config)
_adc(2, 5, 2), 1.0 / hub_config[CONF_THERMISTOR_BETA]
)
_add_adc_sensor(hub, var, state, "Battery Temperature")
await sensors(CONF_VBUS_CURRENT_LIMIT, hub.set_vbus_current_limit_sensor)
+3 -11
View File
@@ -15,7 +15,6 @@ from . import (
CONF_THERMISTOR_RESISTANCE,
NPM1300_CHILD_SCHEMA,
OUTPUTS,
THERMISTOR_NONE,
)
DEPENDENCIES = ["npm1300"]
@@ -45,18 +44,11 @@ def _final_validate(config: ConfigType) -> None:
if CONF_CHARGER not in config:
return
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
# A wrong thermistor shifts the battery temperature the charger sees
if CONF_THERMISTOR_RESISTANCE not in hub:
raise cv.Invalid(
f"The '{CONF_CHARGER}' switch needs '{CONF_THERMISTOR_RESISTANCE}' on the npm1300 "
f"component: the nominal resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
path=[CONF_CHARGER],
)
# Only the charger block turns off the NTC check, without which the charger never starts
if CONF_CHARGER not in hub and hub[CONF_THERMISTOR_RESISTANCE] == THERMISTOR_NONE:
if CONF_CHARGER not in hub and CONF_THERMISTOR_RESISTANCE not in hub:
raise cv.Invalid(
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block when "
f"'{CONF_THERMISTOR_RESISTANCE}' is '{THERMISTOR_NONE}'",
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block or "
f"'{CONF_THERMISTOR_RESISTANCE}' on the npm1300 component",
path=[CONF_CHARGER],
)
+6 -2
View File
@@ -11,12 +11,14 @@ from esphome.cpp_generator import (
from esphome.types import ConfigType
from . import (
CHARGE_STATUS,
CONF_NPM1300_ID,
DUMP,
DUMP_TAG,
ERROR_REASON,
NPM1300_CHILD_SCHEMA,
STATUS,
STATUS_PUBLISHER,
VBUS_STATUS,
npm1300_ns,
)
@@ -46,7 +48,9 @@ async def to_code(config: ConfigType) -> None:
)
STATUS_PUBLISHER.add(
hub,
npm1300_ns.publish_charger_status(parent_ref(var), last, STATUS),
npm1300_ns.publish_charger_status(
parent_ref(var), last, VBUS_STATUS, CHARGE_STATUS, ERROR_REASON
),
)
DUMP.add(
hub,
+3 -10
View File
@@ -13,7 +13,6 @@ from esphome.build_helpers.ccache import resolve_ccache_path
import esphome.codegen as cg
from esphome.components import network
from esphome.components.zephyr import (
PreferenceStorage,
Section,
add_extra_script,
copy_files as zephyr_copy_files,
@@ -107,7 +106,6 @@ from .const import (
VARIANT_NRF52832,
VARIANT_NRF52840,
VARIANT_REGULATOR,
VARIANTS_NRF54L,
VARIANTS_WITHOUT_USB,
)
from .framework import (
@@ -538,11 +536,6 @@ def _final_validate(config):
FINAL_VALIDATE_SCHEMA = _final_validate
def _preferences_storage(variant: str) -> PreferenceStorage:
"""The storage for preferences: ZMS on the RRAM of the nRF54L, NVS on flash."""
return "ZMS" if variant in VARIANTS_NRF54L else "NVS"
@coroutine_with_priority(CoroPriority.PLATFORM)
async def to_code(config: ConfigType) -> None:
"""Convert the configuration to code."""
@@ -551,7 +544,7 @@ async def to_code(config: ConfigType) -> None:
variant = get_nrf52_variant()
cg.add_define("ESPHOME_VARIANT", variant)
cg.add_build_flag(f"-DUSE_NRF52_VARIANT_{variant}")
if variant in VARIANTS_NRF54L:
if variant in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
# The entropy driver runs on the CRACEN crypto unit, which needs Nordic's PSA crypto
include_west_project("mbedtls")
include_west_project("oberon-psa-crypto")
@@ -619,11 +612,11 @@ async def to_code(config: ConfigType) -> None:
if config[KEY_BOOTLOADER] in ADAFRUIT_BOOTLOADERS:
cg.add_define("USE_BOOTLOADER_ADAFRUIT")
zephyr_setup_preferences(_preferences_storage(variant))
zephyr_setup_preferences()
zephyr_to_code(config)
# The nRF54L has RRAM (cpuapp_rram) and no flash0 node
if CORE.testing_mode and variant not in VARIANTS_NRF54L:
if CORE.testing_mode and variant not in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
zephyr_add_overlay(
f"""
&flash0 {{
+1 -2
View File
@@ -17,7 +17,6 @@ from .const import (
VARIANT_NRF54LM20,
VARIANT_NRF52832,
VARIANT_NRF52840,
VARIANTS_NRF54L,
)
from .framework import (
check_and_install,
@@ -146,7 +145,7 @@ def upload_using_cmsis_dap(unique_id: str | None = None) -> None:
pyocd = [str(paths["python_executable"]), "-m", "pyocd"]
probe = ["-t", target] + (["-u", unique_id] if unique_id else [])
cmd = [*pyocd, "flash", "--no-wait", *probe, "-e", "sector"]
if variant in VARIANTS_NRF54L:
if variant in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
cmd += ["--script", str(_NRF54L_WATCHDOG_SCRIPT)]
cmd += [str(image) for image in images]
if not run_command_ok(cmd, env=env, stream_output=True):
-2
View File
@@ -41,8 +41,6 @@ VARIANT_I2C = {
VARIANT_NRF54LM20: VariantI2C("i2c21", (1, 3)),
}
VARIANTS_WITHOUT_USB = frozenset({VARIANT_NRF52832, VARIANT_NRF54L15})
# The nRF54L family: RRAM instead of flash, the CRACEN crypto unit and the wdt31 watchdog
VARIANTS_NRF54L = frozenset({VARIANT_NRF54L15, VARIANT_NRF54LM20})
# Devicetree label of the main regulator, reg1 on the others
VARIANT_REGULATOR = {VARIANT_NRF52832: "reg"}
VARIANT_FLASH_SIZE = {VARIANT_NRF52832: 0x80000, VARIANT_NRF52840: 0x100000}
@@ -83,9 +83,6 @@ class PartitionLightOutput final : public light::AddressableLight {
void set(int32_t index, Color color) override {
light::ESPColorView color_view = this->parent_->get_color_view_(index);
// A white level the LED cannot show must not count as the pixel's strongest channel
if (!color_view.has_white_internal()) // NOLINT
color.white = 0;
color_view.set_raw(this->parent_->get_color_correction_(color_view)->color_correct(color));
}
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
@@ -101,10 +98,6 @@ class PartitionLightOutput final : public light::AddressableLight {
this->parent_->get_color_view_(index).set_effect_data(value);
}
bool has_white_internal(int32_t index) const override { // NOLINT
return this->parent_->get_color_view_(index).has_white_internal();
}
#ifdef USE_LIGHT_POWER_ESTIMATION
const light::ESPColorCorrection *get_color_correction_internal(int32_t index) const override { // NOLINT
return this->parent_->get_color_correction_(this->parent_->get_color_view_(index));
-3
View File
@@ -1,3 +0,0 @@
"""PCM1863 audio ADC component."""
DOMAIN = "pcm1863"
-62
View File
@@ -1,62 +0,0 @@
import esphome.codegen as cg
from esphome.components import i2c
from esphome.components.audio_adc import AudioAdc
import esphome.config_validation as cv
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_INPUT, CONF_MIC_GAIN
from esphome.types import ConfigType
CODEOWNERS = ["@anabolyc"]
DEPENDENCIES = ["i2c"]
CONF_PCM1863_ID = "pcm1863_id"
# The PGA covers -12 dB to +40 dB in 0.5 dB steps
PCM1863_MIC_GAIN_MIN = -12.0
PCM1863_MIC_GAIN_MAX = 40.0
pcm1863_ns = cg.esphome_ns.namespace("pcm1863")
PCM1863 = pcm1863_ns.class_("PCM1863", AudioAdc, cg.Component, i2c.I2CDevice)
pcm1863_input = pcm1863_ns.enum("PCM1863Input")
# The declaration order is the select option order and the C++ enum value of each input
PCM1863_INPUT_ENUM = pcm1863_input.options(
"NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2", prefix="PCM1863_INPUT_"
)
pcm1863_bits_per_sample = pcm1863_ns.enum("PCM1863BitsPerSample")
PCM1863_BITS_PER_SAMPLE_ENUM = {
16: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_16,
20: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_20,
24: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_24,
32: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_32,
}
_validate_bits = cv.float_with_unit("bits", "bit")
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(PCM1863),
cv.Optional(CONF_BITS_PER_SAMPLE, default="24bit"): cv.All(
_validate_bits, cv.enum(PCM1863_BITS_PER_SAMPLE_ENUM)
),
cv.Optional(CONF_INPUT, default="VIN1"): cv.enum(
PCM1863_INPUT_ENUM, upper=True
),
cv.Optional(CONF_MIC_GAIN, default="0db"): cv.All(
cv.decibel,
cv.float_range(min=PCM1863_MIC_GAIN_MIN, max=PCM1863_MIC_GAIN_MAX),
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(i2c.i2c_device_schema(0x4A))
)
async def to_code(config: ConfigType) -> None:
var = await i2c.new_i2c_component(config)
cg.add(var.set_bits_per_sample(config[CONF_BITS_PER_SAMPLE]))
cg.add(var.set_input(config[CONF_INPUT]))
cg.add(var.set_mic_gain(config[CONF_MIC_GAIN]))
-96
View File
@@ -1,96 +0,0 @@
#include "pcm1863.h"
#include "pcm1863_const.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#include <cmath>
namespace esphome::pcm1863 {
ESPHOME_LOG_TAG(TAG, "pcm1863");
// Indexed by PCM1863BitsPerSample
PROGMEM_STRING_TABLE(BitsPerSampleStrings, "32", "24", "20", "16");
PROGMEM_STRING_TABLE(InputStrings, "NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2");
// Page select and power up: bits 2:0 clear is the run state, and the reserved bits 7:3
// must be written as 0b01110 or the analog section stops
static constexpr i2c::I2CRegValue PCM1863_INIT[] PROGMEM = {
{PCM1863_REG_PAGE, PCM1863_PAGE_0},
{PCM1863_REG_POWER_CTRL, PCM1863_PWR_CTRL_RSV},
};
void PCM1863::dump_config() {
ESP_LOGCONFIG(TAG,
"PCM1863 audio ADC:\n"
" Bits Per Sample: %s\n"
" Input: %s\n"
" Mic Gain: %.1f dB",
LOG_STR_ARG(BitsPerSampleStrings::get_log_str(this->bits_per_sample_, 0)),
LOG_STR_ARG(InputStrings::get_log_str(this->input_, 0)), this->mic_gain_);
#ifdef USE_PCM1863_SELECT
LOG_SELECT(" ", "Input", this->input_select_);
#endif
}
void PCM1863::setup() {
// Writing PCM1863_RESET to the page selector restores every register to its default
if (!this->setup_check(this->write_byte(PCM1863_REG_PAGE, PCM1863_RESET)))
return;
delay(2);
// The datasheet does not say which page the reset leaves selected, so select page 0 first
if (!this->setup_check(this->write_registers(PCM1863_INIT)))
return;
if (!this->setup_check(this->configure_i2s_format_() && this->configure_input_() && this->configure_mic_gain_()))
return;
this->setup_complete_ = true;
#ifdef USE_PCM1863_SELECT
// Show the input the ADC booted with, so the select does not start out blank
PUBLISH_STATE(this->input_select_, this->input_);
#endif
}
bool PCM1863::set_mic_gain(float mic_gain) {
// Nothing reaches the chip after a failed setup, so report the change as not applied
if (this->is_failed())
return false;
this->mic_gain_ = clamp<float>(mic_gain, PCM1863_MIC_GAIN_MIN, PCM1863_MIC_GAIN_MAX);
if (!this->setup_complete_)
return true;
return this->status_comm_result(this->configure_mic_gain_());
}
bool PCM1863::configure_mic_gain_() {
// The PGA gain registers take a two's complement value in 0.5 dB steps
const auto reg_val = static_cast<uint8_t>(lroundf(this->mic_gain_ / PCM1863_MIC_GAIN_STEP));
return this->write_byte(PCM1863_REG_PGA_VAL_CH1_L, reg_val) && this->write_byte(PCM1863_REG_PGA_VAL_CH1_R, reg_val);
}
bool PCM1863::set_input(PCM1863Input input) {
if (this->is_failed())
return false;
this->input_ = input;
if (!this->setup_complete_)
return true;
return this->status_comm_result(this->configure_input_());
}
bool PCM1863::configure_input_() {
// Bit 6 of both input select registers is reserved and must always be written as 1
const uint8_t mux = this->input_ == PCM1863_INPUT_NONE ? 0 : 1 << (this->input_ - 1);
const uint8_t reg_val = PCM1863_INPUT_SEL_RSV | mux;
return this->write_byte(PCM1863_REG_ADC1_INPUT_SEL_L, reg_val) &&
this->write_byte(PCM1863_REG_ADC1_INPUT_SEL_R, reg_val);
}
bool PCM1863::configure_i2s_format_() {
const uint8_t wlen = this->bits_per_sample_;
const uint8_t reg_val =
(wlen << PCM1863_PCM_CFG_RX_WLEN_SHIFT) | (wlen << PCM1863_PCM_CFG_TX_WLEN_SHIFT) | PCM1863_PCM_CFG_FMT_I2S;
return this->write_byte(PCM1863_REG_PCM_CFG, reg_val);
}
} // namespace esphome::pcm1863
-64
View File
@@ -1,64 +0,0 @@
#pragma once
#include "esphome/components/audio_adc/audio_adc.h"
#include "esphome/components/i2c/i2c.h"
#include "esphome/core/component.h"
#ifdef USE_PCM1863_SELECT
#include "esphome/components/select/select.h"
#endif
#include "pcm1863_const.h"
namespace esphome::pcm1863 {
// Positions of the select options, in the order audio_adc.py declares them
enum PCM1863Input : uint8_t {
PCM1863_INPUT_NONE,
PCM1863_INPUT_VIN1,
PCM1863_INPUT_VIN2,
PCM1863_INPUT_VIN3,
PCM1863_INPUT_VIN4,
PCM1863_INPUT_DIFF_1,
PCM1863_INPUT_DIFF_2,
};
// The word length code of PCM1863_REG_PCM_CFG
enum PCM1863BitsPerSample : uint8_t {
PCM1863_BITS_PER_SAMPLE_32,
PCM1863_BITS_PER_SAMPLE_24,
PCM1863_BITS_PER_SAMPLE_20,
PCM1863_BITS_PER_SAMPLE_16,
};
/// Texas Instruments PCM1863 stereo audio ADC for line and microphone input.
/// The register map and reset sequence follow the datasheet (SLAS831D) and the Linux
/// kernel driver in sound/soc/codecs/pcm186x.c.
class PCM1863 final : public audio_adc::AudioAdc, public Component, public i2c::I2CDevice {
#ifdef USE_PCM1863_SELECT
SUB_SELECT(input)
#endif
public:
void setup() override;
void dump_config() override;
void set_bits_per_sample(PCM1863BitsPerSample bits_per_sample) { this->bits_per_sample_ = bits_per_sample; }
/// Selects the analog input. Takes effect immediately once setup has run.
bool set_input(PCM1863Input input);
bool set_mic_gain(float mic_gain) override;
float mic_gain() override { return this->mic_gain_; }
protected:
bool configure_i2s_format_();
bool configure_mic_gain_();
bool configure_input_();
float mic_gain_{0};
bool setup_complete_{false};
PCM1863BitsPerSample bits_per_sample_{PCM1863_BITS_PER_SAMPLE_24};
PCM1863Input input_{PCM1863_INPUT_VIN1};
};
} // namespace esphome::pcm1863
@@ -1,50 +0,0 @@
#pragma once
#include <cstdint>
namespace esphome::pcm1863 {
// PCM1863 page 0 register addresses.
// Names and layout follow the Texas Instruments PCM186x family register map (SLAS831D).
static constexpr uint8_t PCM1863_REG_PAGE = 0x00; /* Page selector; writing 0xFE triggers a full reset */
static constexpr uint8_t PCM1863_REG_PGA_VAL_CH1_L = 0x01; /* ADC1 left PGA gain, 0.5 dB/LSB, two's complement */
static constexpr uint8_t PCM1863_REG_PGA_VAL_CH1_R = 0x02; /* ADC1 right PGA gain, 0.5 dB/LSB, two's complement */
static constexpr uint8_t PCM1863_REG_ADC1_INPUT_SEL_L = 0x06;
static constexpr uint8_t PCM1863_REG_ADC1_INPUT_SEL_R = 0x07;
static constexpr uint8_t PCM1863_REG_PCM_CFG = 0x0B; /* Word length and serial audio format */
static constexpr uint8_t PCM1863_REG_POWER_CTRL = 0x70; /* Power down, sleep and standby */
// PCM1863_REG_PAGE: the register holds the page number, and the two documented
// commands are selecting a page and resetting every register
static constexpr uint8_t PCM1863_PAGE_0 = 0x00;
static constexpr uint8_t PCM1863_RESET = 0xFE;
// PCM1863_REG_PCM_CFG: receive word length in bits 7:6, transmit word length in bits 3:2,
// serial audio format in bits 1:0. Bit 5 is reserved and bit 4 only applies to TDM; both
// are zero at reset and are written as zero here.
static constexpr uint8_t PCM1863_PCM_CFG_RX_WLEN_SHIFT = 6;
static constexpr uint8_t PCM1863_PCM_CFG_TX_WLEN_SHIFT = 2;
static constexpr uint8_t PCM1863_PCM_CFG_FMT_I2S = 0x00;
// PCM1863_REG_ADC1_INPUT_SEL_L / _R
// Bit 7 selects signal polarity, bit 6 is reserved and must always be written as 1,
// and bits 5:0 pick the analog input. See the PCM186x datasheet, "MUX, MIX, and
// Polarity Input Selection".
static constexpr uint8_t PCM1863_INPUT_SEL_RSV = 0x40; // bit 6, always write 1
// Bits 5:0 select one input: none, VIN1 to VIN4 single-ended (0x01 to 0x08), then the
// differential pairs VIN1/VIN2 (0x10) and VIN4/VIN3 (0x20)
// PCM1863_REG_POWER_CTRL
// Bits 2:0 are power down, sleep and standby; all three are clear in the run state.
// Bits 7:3 are reserved and the datasheet requires them to always be written as 0b01110,
// which is also their reset value. Writing them as zero stops the analog section.
static constexpr uint8_t PCM1863_PWR_CTRL_RSV = 0x70;
// The PGA gain registers hold a two's complement value in 0.5 dB steps,
// from -24 (-12 dB) to +80 (+40 dB)
static constexpr float PCM1863_MIC_GAIN_MIN = -12.0f;
static constexpr float PCM1863_MIC_GAIN_MAX = 40.0f;
static constexpr float PCM1863_MIC_GAIN_STEP = 0.5f;
} // namespace esphome::pcm1863
-32
View File
@@ -1,32 +0,0 @@
import esphome.codegen as cg
from esphome.components import select
import esphome.config_validation as cv
from esphome.const import ENTITY_CATEGORY_CONFIG, ICON_CHIP
from esphome.types import ConfigType
from .audio_adc import CONF_PCM1863_ID, PCM1863, PCM1863_INPUT_ENUM
PCM1863_INPUT_OPTIONS = list(PCM1863_INPUT_ENUM)
CONFIG_SCHEMA = select.select_schema(
select.ApplySelect,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_CHIP,
).extend(
{
cv.GenerateID(CONF_PCM1863_ID): cv.use_id(PCM1863),
}
)
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_PCM1863_SELECT")
hub = await cg.get_variable(config[CONF_PCM1863_ID])
# The ADC publishes the new option only once the I2C write went through
await select.sub_selects(config, parent=hub).create(
config,
hub.set_input_select,
options=PCM1863_INPUT_OPTIONS,
apply="set_input(static_cast<pcm1863::PCM1863Input>(index))",
publish="on_success",
)
-10
View File
@@ -1,10 +0,0 @@
"""Pioneer WT series mini splits, controlled through the serial port of the WiFi module."""
import esphome.codegen as cg
CODEOWNERS = ["@martinsah"]
DOMAIN = "pioneer_wt"
pioneer_wt_ns = cg.esphome_ns.namespace("pioneer_wt")
CONF_PIONEER_WT_ID = "pioneer_wt_id"
-33
View File
@@ -1,33 +0,0 @@
import esphome.codegen as cg
from esphome.components import climate, uart
import esphome.config_validation as cv
from esphome.types import ConfigType
from . import DOMAIN, pioneer_wt_ns
DEPENDENCIES = ["uart"]
PioneerWT = pioneer_wt_ns.class_(
"PioneerWT", climate.Climate, uart.UARTDevice, cg.Component
)
CONFIG_SCHEMA = (
climate.climate_schema(PioneerWT)
.extend(uart.UART_DEVICE_SCHEMA)
.extend(cv.COMPONENT_SCHEMA)
)
FINAL_VALIDATE_SCHEMA = uart.final_validate_device_schema(
DOMAIN,
baud_rate=115200,
require_tx=True,
require_rx=True,
data_bits=8,
parity="NONE",
stop_bits=1,
)
async def to_code(config: ConfigType) -> None:
var = await uart.new_uart_component(config)
await climate.register_climate(var, config)
@@ -1,343 +0,0 @@
#include "pioneer_wt.h"
#include <cinttypes>
#include <cmath>
#include <cstring>
#include <iterator>
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
namespace esphome::pioneer_wt {
ESPHOME_LOG_TAG(TAG, "pioneer_wt");
static constexpr uint32_t RESEND_INTERVAL_MS = 500;
static constexpr uint8_t MAX_ATTEMPTS = 4;
// Ask for a full status again if the AC has reported nothing for this long.
static constexpr uint32_t STATUS_REFRESH_MS = 5 * 60 * 1000;
// Until the first full status has arrived, ask again this often.
static constexpr uint32_t STATUS_RETRY_MS = 30 * 1000;
static constexpr float MIN_TEMPERATURE_C = 16.0f;
static constexpr float MAX_TEMPERATURE_C = 31.0f;
static constexpr uint8_t FAN_SPEED_COUNT = 7;
static constexpr const char *const FAN_SPEED_NAMES[FAN_SPEED_COUNT] PROGMEM = {
"Speed 1", "Speed 2", "Speed 3", "Speed 4", "Speed 5", "Speed 6", "Speed 7"};
// Reply to the AC's once-a-minute check, as the stock module sends it. The last body byte is the
// WiFi signal in dBm; a fixed -48 is enough for the AC.
static constexpr uint8_t PRESENCE_REPLY_FRAME[] PROGMEM = {0xA5, 0x01, 0x00, 0x23, 0x00, 0x00, 0x00, 0x12, 0x47,
0x09, 0x80, 0x0C, 0x02, 0x64, 0xFF, 0xFF, 0xFF, 0xD0};
// Climate mode for each value of ATTR_MODE
static constexpr uint8_t CLIMATE_MODES[] PROGMEM = {
climate::CLIMATE_MODE_HEAT_COOL, climate::CLIMATE_MODE_COOL, climate::CLIMATE_MODE_DRY,
climate::CLIMATE_MODE_FAN_ONLY, climate::CLIMATE_MODE_HEAT,
};
void PioneerWT::setup() {
this->set_supported_custom_fan_modes_static(FAN_SPEED_NAMES, FAN_SPEED_COUNT);
this->request_status_();
#ifdef USE_SWITCH
if (this->display_switch_ != nullptr)
this->display_switch_->restore();
if (this->beeper_switch_ != nullptr)
this->beeper_switch_->restore();
#endif
}
climate::ClimateTraits PioneerWT::traits() {
auto traits = climate::ClimateTraits();
traits.add_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_TEMPERATURE);
traits.set_supported_modes({climate::CLIMATE_MODE_OFF, climate::CLIMATE_MODE_HEAT_COOL, climate::CLIMATE_MODE_COOL,
climate::CLIMATE_MODE_HEAT, climate::CLIMATE_MODE_DRY, climate::CLIMATE_MODE_FAN_ONLY});
traits.set_supported_fan_modes({climate::CLIMATE_FAN_AUTO});
traits.set_supported_swing_modes({climate::CLIMATE_SWING_OFF, climate::CLIMATE_SWING_VERTICAL});
traits.set_supported_presets({climate::CLIMATE_PRESET_NONE, climate::CLIMATE_PRESET_ECO});
traits.set_visual_min_temperature(MIN_TEMPERATURE_C);
traits.set_visual_max_temperature(MAX_TEMPERATURE_C);
// The AC keeps its setpoint in whole degrees Fahrenheit, so half degrees Celsius would not all be kept.
traits.set_visual_target_temperature_step(1.0f);
traits.set_visual_current_temperature_step(0.1f);
return traits;
}
void PioneerWT::loop() {
const uint32_t now = App.get_loop_component_start_time();
auto handle = [this](const uint8_t *frame, size_t len) {
if (!checksum_valid(frame, len)) {
ESP_LOGD(TAG, "Dropped a frame with a wrong checksum");
return false;
}
this->handle_frame_(frame, len);
return true;
};
this->read_frames(this->reader_, handle, now, this->last_rx_);
// A frame still coming in may be the reply; wait for it before resending
if (!this->queue_.empty() && now - this->last_send_ >= RESEND_INTERVAL_MS && !this->reader_.receiving())
this->send_pending_();
// The target temperature only arrives in a full status, so it tells whether one has been received.
const uint32_t status_interval = std::isnan(this->target_temperature) ? STATUS_RETRY_MS : STATUS_REFRESH_MS;
if (now - this->last_status_ >= status_interval)
this->request_status_();
}
void PioneerWT::handle_frame_(const uint8_t *frame, size_t len) {
const uint8_t flags = frame[2];
const uint8_t type = frame[3];
const uint8_t seq = frame[4];
const uint8_t ack = frame[5];
const uint8_t *payload = frame + HEADER_SIZE;
const size_t payload_len = len - HEADER_SIZE;
ESP_LOGVV_HEX(TAG, frame, len, MAX_FRAME_SIZE, "RX %s");
if (type == TYPE_REPLY) {
if (!this->queue_.empty() && this->queue_.front().seq == ack) {
if (this->queue_.front().power != POWER_UNCHANGED)
this->acked_power_ = this->queue_.front().power;
// Pop first: the warning log can run automations that queue another command.
this->pop_command_();
this->status_clear_warning();
this->last_send_ = 0; // send the next one right away
}
return;
}
if (type != TYPE_DATA || payload_len < 2)
return;
const uint8_t msg_class = payload[0];
if (flags & FLAG_WANT_ACK)
this->write_frame_(FLAG_WANT_ACK, TYPE_REPLY, 0, seq, CLASS_REPLY, msg_class, nullptr, 0);
if (msg_class != CLASS_STATUS)
return;
if (payload_len == 2) {
if (!(flags & FLAG_WANT_ACK))
this->write_array_progmem(PRESENCE_REPLY_FRAME, sizeof(PRESENCE_REPLY_FRAME));
return;
}
this->handle_status_(payload + 2, payload_len - 2);
// Reports count only once a full status has arrived, so the boot request is repeated until one does.
if (!std::isnan(this->target_temperature))
this->last_status_ = App.get_loop_component_start_time();
}
void PioneerWT::handle_status_(const uint8_t *body, size_t len) {
AttributeReader attrs(body, len);
bool changed = false;
while (attrs.next()) {
const uint32_t v = attrs.value();
switch (attrs.id()) {
case ATTR_POWER:
this->power_ = v != 0;
this->acked_power_ = POWER_UNCHANGED;
break;
case ATTR_MODE:
if (v < std::size(CLIMATE_MODES)) {
this->ac_mode_ = v;
} else {
ESP_LOGD(TAG, "Unknown mode %" PRIu32, v);
}
break;
case ATTR_SETPOINT_F: {
const float target = fahrenheit_to_celsius(v);
changed |= target != this->target_temperature;
this->target_temperature = target;
break;
}
case ATTR_INDOOR_TEMP_C100: {
const float current = static_cast<float>(v) / 100.0f;
changed |= current != this->current_temperature;
this->current_temperature = current;
break;
}
case ATTR_FAN_SPEED:
if (v == 0) {
changed |= this->set_fan_mode_(climate::CLIMATE_FAN_AUTO);
} else if (v <= FAN_SPEED_COUNT) {
changed |= this->set_custom_fan_mode_(FAN_SPEED_NAMES[v - 1]);
} else {
ESP_LOGD(TAG, "Unknown fan speed %" PRIu32, v);
}
break;
case ATTR_SWING_VERTICAL: {
const auto swing = v == SWING_ON ? climate::CLIMATE_SWING_VERTICAL : climate::CLIMATE_SWING_OFF;
changed |= swing != this->swing_mode;
this->swing_mode = swing;
break;
}
case ATTR_ECO:
changed |= this->set_preset_(v ? climate::CLIMATE_PRESET_ECO : climate::CLIMATE_PRESET_NONE);
break;
#ifdef USE_SWITCH
case ATTR_DISPLAY:
PUBLISH_STATE(this->display_switch_, v != 0);
break;
case ATTR_BEEPER:
PUBLISH_STATE(this->beeper_switch_, v != 0);
break;
#endif
default:
break;
}
}
if (attrs.stopped_on_unknown()) {
ESP_LOGD(TAG, "Status attribute %04X has an unknown size; ignored the rest of the frame", attrs.id());
}
const auto mode = this->power_ ? static_cast<climate::ClimateMode>(progmem_read_byte(&CLIMATE_MODES[this->ac_mode_]))
: climate::CLIMATE_MODE_OFF;
changed |= mode != this->mode;
this->mode = mode;
if (changed)
this->publish_state();
}
void PioneerWT::control(const climate::ClimateCall &call) {
uint8_t body[MAX_BODY_SIZE];
uint8_t *p = body;
int8_t power = POWER_UNCHANGED;
if (call.get_mode().has_value()) {
const auto mode = *call.get_mode();
if (mode == climate::CLIMATE_MODE_OFF) {
power = 0;
p = put_attr(p, ATTR_POWER, 0);
} else {
uint8_t ac_mode = 0;
for (size_t i = 0; i < std::size(CLIMATE_MODES); i++) {
if (progmem_read_byte(&CLIMATE_MODES[i]) == mode) {
ac_mode = i;
break;
}
}
// Queued commands count: an "off" still waiting to be sent is followed by a power on.
if (!this->wanted_power_(this->queue_.size() == TX_QUEUE_SIZE)) {
power = 1;
p = put_attr(p, ATTR_POWER, 1);
}
p = put_attr(p, ATTR_MODE, ac_mode);
}
}
if (call.get_target_temperature().has_value()) {
// Automations can ask for any value; the visual range is not enforced for them.
const float celsius = clamp(*call.get_target_temperature(), MIN_TEMPERATURE_C, MAX_TEMPERATURE_C);
p = put_be32(put_be16(p, ATTR_SETPOINT_F), lroundf(celsius_to_fahrenheit(celsius)));
}
// The app always sends fan speed with these companions; match it exactly.
int fan_speed = -1;
if (call.get_fan_mode().has_value() && *call.get_fan_mode() == climate::CLIMATE_FAN_AUTO) {
fan_speed = 0;
} else if (call.has_custom_fan_mode()) {
// The call holds the pointer from FAN_SPEED_NAMES, so the pointers can be compared.
const char *name = call.get_custom_fan_mode().c_str();
for (uint8_t i = 0; i < FAN_SPEED_COUNT; i++) {
if (name == FAN_SPEED_NAMES[i]) {
fan_speed = i + 1;
break;
}
}
}
if (fan_speed >= 0) {
p = put_attr(p, ATTR_FAN_EXTRA_1, 0);
p = put_attr(p, ATTR_FAN_EXTRA_2, 0);
p = put_attr(p, ATTR_FAN_SPEED, fan_speed);
p = put_attr(p, ATTR_FAN_AUTO, fan_speed == 0);
}
if (call.get_swing_mode().has_value()) {
const bool swing = *call.get_swing_mode() == climate::CLIMATE_SWING_VERTICAL;
p = put_attr(p, ATTR_SWING_VERTICAL, swing ? SWING_ON : SWING_OFF);
}
if (call.get_preset().has_value())
p = put_attr(p, ATTR_ECO, *call.get_preset() == climate::CLIMATE_PRESET_ECO);
if (p != body)
this->queue_command_(CLASS_COMMAND, body, p - body, power);
// State is published when the AC reports the new values back.
}
void PioneerWT::send_setting_(uint16_t attr, bool on) {
uint8_t body[3];
put_attr(body, attr, on);
this->queue_command_(CLASS_COMMAND, body, sizeof(body));
}
void PioneerWT::request_status_() {
// Asks the AC to send every setting, as the stock module does at boot.
static constexpr uint8_t REQUEST_ALL[] = {0xFF, 0xFF};
this->queue_command_(CLASS_NETWORK, REQUEST_ALL, sizeof(REQUEST_ALL));
this->last_status_ = App.get_loop_component_start_time();
}
void PioneerWT::queue_command_(uint8_t msg_class, const uint8_t *body, size_t len, int8_t power) {
if (this->queue_.size() == TX_QUEUE_SIZE) {
ESP_LOGW(TAG, "Command queue full; dropping the oldest command");
this->pop_command_();
}
PendingCommand pending{msg_class, this->next_seq_++, static_cast<uint8_t>(len), power, {}};
std::memcpy(pending.body.data(), body, len);
this->queue_.push(pending);
if (this->next_seq_ == 0)
this->next_seq_ = 1;
}
void PioneerWT::pop_command_() {
this->queue_.pop();
this->attempts_ = 0;
}
bool PioneerWT::wanted_power_(bool skip_head) const {
// An acknowledged power change counts until the AC reports the power
bool power = this->acked_power_ == POWER_UNCHANGED ? this->power_ : this->acked_power_;
for (const PendingCommand &pending : this->queue_) {
if (skip_head) {
skip_head = false;
continue;
}
if (pending.power != POWER_UNCHANGED)
power = pending.power;
}
return power;
}
void PioneerWT::send_pending_() {
const PendingCommand &pending = this->queue_.front();
if (this->attempts_ >= MAX_ATTEMPTS) {
const uint8_t seq = pending.seq;
// Pop first: the warning log can run automations that queue another command.
this->pop_command_();
ESP_LOGD(TAG, "No acknowledgement for command seq %02X; giving up", seq);
this->status_set_warning(LOG_STR("No acknowledgement"));
return;
}
this->attempts_++;
this->write_frame_(FLAG_WANT_ACK, TYPE_DATA, pending.seq, 0, pending.msg_class, pending.msg_class,
pending.body.data(), pending.len);
this->last_send_ = App.get_loop_component_start_time();
}
void PioneerWT::write_frame_(uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1, uint8_t class_2,
const uint8_t *body, size_t len) {
uint8_t frame[HEADER_SIZE + 2 + MAX_BODY_SIZE];
const size_t total = build_frame(frame, flags, type, seq, ack, class_1, class_2, body, len);
ESP_LOGVV_HEX(TAG, frame, total, sizeof(frame), "TX %s");
// Kept bytes of an earlier frame must not merge into the reply
this->reader_.drop_kept();
this->write_array(frame, total);
}
void PioneerWT::dump_config() {
LOG_CLIMATE("", "Pioneer WT", this);
#ifdef USE_SWITCH
LOG_SWITCH(" ", "Display", this->display_switch_);
LOG_SWITCH(" ", "Beeper", this->beeper_switch_);
#endif
}
} // namespace esphome::pioneer_wt
@@ -1,85 +0,0 @@
#pragma once
#include <array>
#include <cstdint>
#include "esphome/components/climate/climate.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#ifdef USE_SWITCH
#include "esphome/components/switch/switch.h"
#endif
#include "pioneer_wt_protocol.h"
namespace esphome::pioneer_wt {
// The largest body control() builds is 30 bytes.
static constexpr size_t MAX_BODY_SIZE = 32;
static constexpr size_t TX_QUEUE_SIZE = 4;
class PioneerWT final : public climate::Climate, public uart::UARTDevice, public Component {
public:
void setup() override;
void loop() override;
void dump_config() override;
/// Turns the indoor unit's front display on or off.
void set_display_on(bool on) { this->send_setting_(ATTR_DISPLAY, on); }
/// Turns the beep that confirms each command on or off.
void set_beeper_on(bool on) { this->send_setting_(ATTR_BEEPER, on); }
#ifdef USE_SWITCH
SUB_SWITCH(display)
SUB_SWITCH(beeper)
#endif
protected:
climate::ClimateTraits traits() override;
void control(const climate::ClimateCall &call) override;
void handle_frame_(const uint8_t *frame, size_t len);
void handle_status_(const uint8_t *body, size_t len);
void write_frame_(uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1, uint8_t class_2,
const uint8_t *body, size_t len);
/// Queues a data frame that the AC must acknowledge; it is resent until it is.
void queue_command_(uint8_t msg_class, const uint8_t *body, size_t len, int8_t power = POWER_UNCHANGED);
void send_pending_();
/// Removes the command at the head of the queue.
void pop_command_();
/// Power once the queued commands are applied; skip_head leaves out a head about to be dropped.
bool wanted_power_(bool skip_head) const;
/// Queues a command that sets one on/off attribute.
void send_setting_(uint16_t attr, bool on);
void request_status_();
static constexpr int8_t POWER_UNCHANGED = -1;
struct PendingCommand {
uint8_t msg_class;
uint8_t seq;
uint8_t len;
// Power the command sets: 0, 1 or POWER_UNCHANGED
int8_t power;
std::array<uint8_t, MAX_BODY_SIZE> body;
};
uint32_t last_send_{0};
// Time of the last status report (counted once a full one has arrived), or of the last request for one
uint32_t last_status_{0};
uint32_t last_rx_{0};
PacketReader reader_;
StaticRingBuffer<PendingCommand, TX_QUEUE_SIZE> queue_;
// Send attempts of the command at the head of the queue
uint8_t attempts_{0};
uint8_t next_seq_{1};
// Power the AC last reported
bool power_{false};
// Power set by an acknowledged command, until the next power report: 0, 1 or POWER_UNCHANGED
int8_t acked_power_{POWER_UNCHANGED};
// Value of ATTR_MODE: 0 auto, 1 cool, 2 dry, 3 fan, 4 heat
uint8_t ac_mode_{0};
};
} // namespace esphome::pioneer_wt
@@ -1,122 +0,0 @@
#include "pioneer_wt_protocol.h"
#include <cstring>
#include "esphome/core/hal.h"
namespace esphome::pioneer_wt {
uint16_t frame_crc(const uint8_t *frame, size_t len) {
const uint16_t head = crc16be(frame, 8);
return crc16be(frame + HEADER_SIZE, len - HEADER_SIZE, head);
}
enum class AttrKind : uint8_t {
ATTR_KIND_UNKNOWN,
ATTR_KIND_ONE_BYTE,
ATTR_KIND_FOUR_BYTES,
// One count byte, then that many bytes
ATTR_KIND_COUNT_PREFIXED,
// Two length bytes, then that many bytes
ATTR_KIND_LENGTH_PREFIXED,
};
// The reader must know how every attribute is stored to step over the ones it does not use.
// The IDs are grouped by storage.
static constexpr uint16_t ONE_BYTE_IDS[] PROGMEM = {
0x0001, 0x0005, 0x000C, 0x000D, 0x000E, 0x0011, 0x0012, 0x0013, 0x0017, 0x001E, 0x0022, 0x0025, 0x0026, 0x0027,
0x002D, 0x0035, 0x005E, 0x0073, 0x0074, 0x00A4, 0x00C9, 0x00DF, 0x0148, 0x015E, 0x0173, 0x0224, 0x0225,
};
static constexpr uint16_t FOUR_BYTE_IDS[] PROGMEM = {
0x0002, 0x0003, 0x003D, 0x0041, 0x0042, 0x005C, 0x0060, 0x0064, 0x0065,
0x0072, 0x0095, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x0221, 0x0222, 0x0227,
};
static constexpr uint16_t COUNT_PREFIXED_IDS[] PROGMEM = {0x0038, 0x0039};
static constexpr uint16_t LENGTH_PREFIXED_IDS[] PROGMEM = {0x00FA, 0x00FB, 0x0147, 0x0223};
template<size_t N> static bool contains(const uint16_t (&ids)[N], uint16_t id) {
for (const uint16_t &entry : ids) {
if (progmem_read_uint16(&entry) == id)
return true;
}
return false;
}
static AttrKind attr_kind(uint16_t id) {
if (contains(ONE_BYTE_IDS, id))
return AttrKind::ATTR_KIND_ONE_BYTE;
if (contains(FOUR_BYTE_IDS, id))
return AttrKind::ATTR_KIND_FOUR_BYTES;
if (contains(COUNT_PREFIXED_IDS, id))
return AttrKind::ATTR_KIND_COUNT_PREFIXED;
if (contains(LENGTH_PREFIXED_IDS, id))
return AttrKind::ATTR_KIND_LENGTH_PREFIXED;
return AttrKind::ATTR_KIND_UNKNOWN;
}
bool AttributeReader::next() {
if (this->pos_ + 2 > this->len_)
return false;
const uint8_t *data = this->data_;
const uint16_t id = encode_uint16(data[this->pos_], data[this->pos_ + 1]);
size_t start = this->pos_ + 2;
size_t value_len;
const AttrKind kind = attr_kind(id);
switch (kind) {
case AttrKind::ATTR_KIND_ONE_BYTE:
value_len = 1;
break;
case AttrKind::ATTR_KIND_FOUR_BYTES:
value_len = 4;
break;
case AttrKind::ATTR_KIND_COUNT_PREFIXED:
if (start + 1 > this->len_)
return false;
value_len = data[start++];
break;
case AttrKind::ATTR_KIND_LENGTH_PREFIXED:
if (start + 2 > this->len_)
return false;
value_len = encode_uint16(data[start], data[start + 1]);
start += 2;
break;
default:
this->id_ = id;
this->unknown_ = true;
return false;
}
if (start + value_len > this->len_)
return false;
this->id_ = id;
const uint8_t *v = data + start;
if (kind == AttrKind::ATTR_KIND_ONE_BYTE) {
this->value_ = v[0];
} else if (kind == AttrKind::ATTR_KIND_FOUR_BYTES) {
this->value_ = encode_uint32(v[0], v[1], v[2], v[3]);
} else {
this->value_ = 0;
}
this->pos_ = start + value_len;
return true;
}
size_t build_frame(uint8_t *out, uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1,
uint8_t class_2, const uint8_t *body, size_t len) {
const size_t total = HEADER_SIZE + 2 + len;
out[0] = FRAME_START_1;
out[1] = FRAME_START_2;
out[2] = flags;
out[3] = type;
out[4] = seq;
out[5] = ack;
out[6] = 0x00;
out[LEN_POS] = total;
out[HEADER_SIZE] = class_1;
out[HEADER_SIZE + 1] = class_2;
if (len)
std::memcpy(out + HEADER_SIZE + 2, body, len);
put_be16(out + CRC_POS, frame_crc(out, total));
return total;
}
} // namespace esphome::pioneer_wt
@@ -1,93 +0,0 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
namespace esphome::pioneer_wt {
// Frame layout: A5 01 | flags | type | seq | ack | 00 | len | crc_hi crc_lo | class class | body
static constexpr size_t HEADER_SIZE = 10;
static constexpr uint8_t FRAME_START_1 = 0xA5;
static constexpr uint8_t FRAME_START_2 = 0x01;
// The length byte counts the whole frame.
static constexpr size_t LEN_POS = 7;
static constexpr size_t CRC_POS = 8;
static constexpr size_t MAX_FRAME_SIZE = 255;
static constexpr uint8_t FLAG_NO_ACK = 0x00;
static constexpr uint8_t FLAG_WANT_ACK = 0x01;
static constexpr uint8_t TYPE_DATA = 0x21;
static constexpr uint8_t TYPE_REPLY = 0x23;
static constexpr uint8_t CLASS_COMMAND = 0x0A;
static constexpr uint8_t CLASS_NETWORK = 0x0B;
static constexpr uint8_t CLASS_STATUS = 0x0C;
// First class byte of a reply
static constexpr uint8_t CLASS_REPLY = 0x80;
// Attribute IDs
static constexpr uint16_t ATTR_POWER = 0x0001;
static constexpr uint16_t ATTR_SETPOINT_C100 = 0x0002;
static constexpr uint16_t ATTR_INDOOR_TEMP_C100 = 0x0003;
static constexpr uint16_t ATTR_FAN_SPEED = 0x0005;
static constexpr uint16_t ATTR_SWING_VERTICAL = 0x0011;
static constexpr uint16_t ATTR_MODE = 0x0012;
static constexpr uint16_t ATTR_ECO = 0x0013;
static constexpr uint16_t ATTR_DISPLAY = 0x001E;
static constexpr uint16_t ATTR_BEEPER = 0x0025;
static constexpr uint16_t ATTR_FAN_AUTO = 0x0073;
static constexpr uint16_t ATTR_FAN_EXTRA_1 = 0x0224;
static constexpr uint16_t ATTR_FAN_EXTRA_2 = 0x0225;
static constexpr uint16_t ATTR_SETPOINT_F = 0x0227;
static constexpr uint8_t SWING_ON = 0x01;
static constexpr uint8_t SWING_OFF = 0x08;
/// CRC-16/XMODEM over a whole frame, skipping the two checksum bytes at offset 8.
uint16_t frame_crc(const uint8_t *frame, size_t len);
// A5 01, ..., whole-frame length at 7, CRC (2) at 8, body
using PacketReader =
LengthFrameReader<MAX_FRAME_SIZE,
FrameFormat<FrameHeader<FRAME_START_1, FRAME_START_2>,
FrameLengthU8<LengthField{.offset = LEN_POS}>, FrameMinLength<HEADER_SIZE>>>;
inline bool checksum_valid(const uint8_t *frame, size_t len) {
return frame_crc(frame, len) == encode_uint16(frame[CRC_POS], frame[CRC_POS + 1]);
}
/// Walks the attribute list in a status body. Stops at the first ID whose size is unknown.
class AttributeReader final {
public:
AttributeReader(const uint8_t *data, size_t len) : data_(data), len_(len) {}
/// Moves to the next attribute. Returns false at the end of the body or at an unknown ID.
bool next();
uint16_t id() const { return this->id_; }
uint32_t value() const { return this->value_; }
/// True when the walk stopped early on an ID of unknown size.
bool stopped_on_unknown() const { return this->unknown_; }
protected:
const uint8_t *data_;
size_t len_;
size_t pos_{0};
uint32_t value_{0};
uint16_t id_{0};
bool unknown_{false};
};
/// Builds a frame into out, which must hold HEADER_SIZE + 2 + len bytes. Returns the frame length.
size_t build_frame(uint8_t *out, uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1,
uint8_t class_2, const uint8_t *body, size_t len);
/// Writes a one-byte attribute (2-byte ID, then the value) at p. Returns the new end.
inline uint8_t *put_attr(uint8_t *p, uint16_t id, uint8_t value) {
p = put_be16(p, id);
*p++ = value;
return p;
}
} // namespace esphome::pioneer_wt
-37
View File
@@ -1,37 +0,0 @@
import esphome.codegen as cg
from esphome.components import switch
import esphome.config_validation as cv
from esphome.const import CONF_BEEPER, CONF_DISPLAY, ENTITY_CATEGORY_CONFIG
from esphome.types import ConfigType
from . import CONF_PIONEER_WT_ID
from .climate import PioneerWT
ICON_LED_ON = "mdi:led-on"
ICON_VOLUME_HIGH = "mdi:volume-high"
def _switch_schema(icon: str) -> cv.Schema:
return switch.switch_schema(
switch.ApplySwitch,
icon=icon,
entity_category=ENTITY_CATEGORY_CONFIG,
default_restore_mode="DISABLED",
)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(CONF_PIONEER_WT_ID): cv.use_id(PioneerWT),
cv.Optional(CONF_DISPLAY): _switch_schema(ICON_LED_ON),
cv.Optional(CONF_BEEPER): _switch_schema(ICON_VOLUME_HIGH),
}
)
async def to_code(config: ConfigType) -> None:
hub = await cg.get_variable(config[CONF_PIONEER_WT_ID])
switches = switch.sub_switches(config, parent=hub)
# No publish: the switch state follows what the AC reports back.
await switches(CONF_DISPLAY, hub.set_display_switch, apply="set_display_on(state)")
await switches(CONF_BEEPER, hub.set_beeper_switch, apply="set_beeper_on(state)")
+88 -44
View File
@@ -7,6 +7,9 @@ namespace esphome::pmsx003 {
ESPHOME_LOG_TAG(TAG, "pmsx003");
static const uint8_t START_CHARACTER_1 = 0x42;
static const uint8_t START_CHARACTER_2 = 0x4D;
static const uint16_t STABILISING_MS = 30000; // time taken for the sensor to become stable after power on in ms
static const uint16_t CMD_MEASUREMENT_MODE_PASSIVE =
@@ -80,9 +83,8 @@ void PMSX003Component::loop() {
// wait for the sensor to be stable
if (now - this->fan_on_time_ < STABILISING_MS)
return;
// consume any command responses that are in the serial buffer, and any partial frame from before the sleep
// consume any command responses that are in the serial buffer
this->discard_available();
this->reader_.reset();
// Trigger a new read
this->send_command_(Command::MANUAL_MEASUREMENT, 0);
this->state_ = State::WAITING;
@@ -93,38 +95,82 @@ void PMSX003Component::loop() {
}
}
auto handle = [this, now](const uint8_t *frame, size_t len) {
if (!this->check_frame_(frame, len))
return false;
if (this->update_interval_ > STABILISING_MS || now - this->last_update_ >= this->update_interval_) {
this->parse_data_(frame);
this->last_update_ = now;
if (now - this->last_transmission_ >= 500) {
// last transmission too long ago. Reset RX index.
this->data_index_ = 0;
}
const size_t avail = this->available();
if (avail == 0)
return;
this->last_transmission_ = now;
this->read_available(
[this, now](uint8_t byte) {
this->data_[this->data_index_] = byte;
auto check = this->check_byte_();
if (!check.has_value()) {
if (this->update_interval_ > STABILISING_MS || now - this->last_update_ >= this->update_interval_) {
this->parse_data_();
this->last_update_ = now;
}
this->data_index_ = 0;
} else if (!*check) {
// wrong data
this->data_index_ = 0;
} else {
// next byte
this->data_index_++;
}
},
avail);
}
optional<bool> PMSX003Component::check_byte_() {
const uint8_t index = this->data_index_;
const uint8_t byte = this->data_[index];
if (index == 0 || index == 1) {
const uint8_t start_char = index == 0 ? START_CHARACTER_1 : START_CHARACTER_2;
if (byte == start_char) {
return true;
}
return true;
};
this->read_frames(this->reader_, handle, now, this->last_transmission_);
}
void warn_too_long(size_t len) {
ESP_LOGW(TAG, "Payload length %u doesn't match. Are you using the correct PMSX003 type?",
static_cast<unsigned>(len - PayloadLength::KNOWN_AT));
}
bool PMSX003Component::check_frame_(const uint8_t *frame, size_t total_size) {
const uint16_t payload_length = total_size - PayloadLength::KNOWN_AT;
if (!this->check_payload_length_(payload_length)) {
ESP_LOGW(TAG, "Payload length %u doesn't match. Are you using the correct PMSX003 type?", payload_length);
ESP_LOGW(TAG, "Start character %u mismatch: 0x%02X != 0x%02X", index + 1, byte, start_char);
return false;
}
if (index == 2) {
return true;
}
const uint16_t payload_length = this->get_16_bit_uint_(2);
if (index == 3) {
if (this->check_payload_length_(payload_length)) {
return true;
} else {
ESP_LOGW(TAG, "Payload length %u doesn't match. Are you using the correct PMSX003 type?", payload_length);
return false;
}
}
// start (16bit) + length (16bit) + DATA (payload_length - 16bit) + checksum (16bit)
const uint16_t total_size = 4 + payload_length;
if (index < total_size - 1) {
return true;
}
// checksum is without checksum bytes
const uint16_t checksum = sum16_bytes(frame, total_size - 2);
const uint16_t check = encode_uint16(frame[total_size - 2], frame[total_size - 1]);
const uint16_t checksum = sum16_bytes(this->data_, total_size - 2);
const uint16_t check = this->get_16_bit_uint_(total_size - 2);
if (checksum != check) {
ESP_LOGW(TAG, "PMSX003 checksum mismatch! 0x%02X != 0x%02X", checksum, check);
return false;
}
return true;
return {};
}
bool PMSX003Component::check_payload_length_(uint16_t payload_length) {
@@ -150,8 +196,6 @@ bool PMSX003Component::check_payload_length_(uint16_t payload_length) {
}
void PMSX003Component::send_command_(Command cmd, uint16_t data) {
// Kept bytes of an earlier reply must not merge into this command's
this->reader_.drop_kept();
uint8_t send_data[7] = {
START_CHARACTER_1, // Start Byte 1
START_CHARACTER_2, // Start Byte 2
@@ -170,11 +214,11 @@ void PMSX003Component::send_command_(Command cmd, uint16_t data) {
}
}
void PMSX003Component::parse_data_(const uint8_t *frame) {
void PMSX003Component::parse_data_() {
// PM mass concentrations
const uint16_t pm_1_0_std_concentration = encode_value<uint16_t>(frame + 4);
const uint16_t pm_2_5_std_concentration = encode_value<uint16_t>(frame + 6);
const uint16_t pm_10_0_std_concentration = encode_value<uint16_t>(frame + 8);
const uint16_t pm_1_0_std_concentration = this->get_16_bit_uint_(4);
const uint16_t pm_2_5_std_concentration = this->get_16_bit_uint_(6);
const uint16_t pm_10_0_std_concentration = this->get_16_bit_uint_(8);
PUBLISH_STATE(this->pm_1_0_std_sensor_, pm_1_0_std_concentration);
PUBLISH_STATE(this->pm_2_5_std_sensor_, pm_2_5_std_concentration);
@@ -190,9 +234,9 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
const uint8_t pc_offset = is_luftmy ? 10 : 16;
if (!is_luftmy) {
const uint16_t pm_1_0_concentration = encode_value<uint16_t>(frame + 10);
const uint16_t pm_2_5_concentration = encode_value<uint16_t>(frame + 12);
const uint16_t pm_10_0_concentration = encode_value<uint16_t>(frame + 14);
const uint16_t pm_1_0_concentration = this->get_16_bit_uint_(10);
const uint16_t pm_2_5_concentration = this->get_16_bit_uint_(12);
const uint16_t pm_10_0_concentration = this->get_16_bit_uint_(14);
ESP_LOGD(TAG, "Got PM1.0 Concentration: %u µg/m³, PM2.5 Concentration %u µg/m³, PM10.0 Concentration: %u µg/m³",
pm_1_0_concentration, pm_2_5_concentration, pm_10_0_concentration);
@@ -203,10 +247,10 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
}
// Particle counts at pc_offset: >0.3, >0.5, >1.0, >2.5µm
const uint16_t pm_particles_03um = encode_value<uint16_t>(frame + pc_offset);
const uint16_t pm_particles_05um = encode_value<uint16_t>(frame + pc_offset + 2);
const uint16_t pm_particles_10um = encode_value<uint16_t>(frame + pc_offset + 4);
const uint16_t pm_particles_25um = encode_value<uint16_t>(frame + pc_offset + 6);
const uint16_t pm_particles_03um = this->get_16_bit_uint_(pc_offset);
const uint16_t pm_particles_05um = this->get_16_bit_uint_(pc_offset + 2);
const uint16_t pm_particles_10um = this->get_16_bit_uint_(pc_offset + 4);
const uint16_t pm_particles_25um = this->get_16_bit_uint_(pc_offset + 6);
PUBLISH_STATE(this->pm_particles_03um_sensor_, pm_particles_03um);
PUBLISH_STATE(this->pm_particles_05um_sensor_, pm_particles_05um);
@@ -219,8 +263,8 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
// PMS5003T uses pc_offset+8 and pc_offset+10 for temperature/humidity, not particle counts
if (this->type_ != Type::PMS5003T) {
const uint16_t pm_particles_50um = encode_value<uint16_t>(frame + pc_offset + 8);
const uint16_t pm_particles_100um = encode_value<uint16_t>(frame + pc_offset + 10);
const uint16_t pm_particles_50um = this->get_16_bit_uint_(pc_offset + 8);
const uint16_t pm_particles_100um = this->get_16_bit_uint_(pc_offset + 10);
ESP_LOGD(TAG, "Got PM5.0 Particles: %u Count/0.1L, PM10.0 Particles: %u Count/0.1L", pm_particles_50um,
pm_particles_100um);
@@ -231,7 +275,7 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
// Formaldehyde
if (this->type_ == Type::PMS5003S || this->type_ == Type::PMS5003ST) {
const uint16_t formaldehyde = encode_value<uint16_t>(frame + 28);
const uint16_t formaldehyde = this->get_16_bit_uint_(28);
ESP_LOGD(TAG, "Got Formaldehyde: %u µg/m^3", formaldehyde);
@@ -242,8 +286,8 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
if (this->type_ == Type::PMS5003T || this->type_ == Type::PMS5003ST) {
const uint8_t temperature_offset = (this->type_ == Type::PMS5003T) ? 24 : 30;
const float temperature = encode_value<int16_t>(frame + temperature_offset) / 10.0f;
const float humidity = encode_value<uint16_t>(frame + temperature_offset + 2) / 10.0f;
const float temperature = static_cast<int16_t>(this->get_16_bit_uint_(temperature_offset)) / 10.0f;
const float humidity = this->get_16_bit_uint_(temperature_offset + 2) / 10.0f;
ESP_LOGD(TAG, "Got Temperature: %.1f°C, Humidity: %.1f%%", temperature, humidity);
@@ -254,8 +298,8 @@ void PMSX003Component::parse_data_(const uint8_t *frame) {
// Firmware Version and Error Code
if (this->type_ == Type::PMS1003 || this->type_ == Type::PMS5003ST || this->type_ == Type::PMS9003M) {
const uint8_t firmware_error_code_offset = (this->type_ == Type::PMS5003ST) ? 36 : 28;
const uint8_t firmware_version = frame[firmware_error_code_offset];
const uint8_t error_code = frame[firmware_error_code_offset + 1];
const uint8_t firmware_version = this->data_[firmware_error_code_offset];
const uint8_t error_code = this->data_[firmware_error_code_offset + 1];
ESP_LOGD(TAG, "Got Firmware Version: 0x%02X, Error Code: 0x%02X", firmware_version, error_code);
}
+7 -15
View File
@@ -1,24 +1,12 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart.h"
namespace esphome::pmsx003 {
static constexpr uint8_t START_CHARACTER_1 = 0x42;
static constexpr uint8_t START_CHARACTER_2 = 0x4D;
// PMS5003ST: 36 byte payload after the 2 start and 2 length bytes
static constexpr uint8_t MAX_FRAME_SIZE = 40;
// 42 4D, payload length (2, BE), payload ending in its checksum (2)
using PayloadLength = PayloadLengthU16BE<LengthField{.offset = 2}>;
/// The wrong-type warning, for a frame longer than any supported type sends
void warn_too_long(size_t len);
using PmsFrame = FrameFormat<FrameHeader<START_CHARACTER_1, START_CHARACTER_2>,
WarnIfLonger<PayloadLength, MAX_FRAME_SIZE, warn_too_long>>;
enum class Type : uint8_t {
PMS1003 = 0,
PMS3003,
@@ -79,15 +67,19 @@ class PMSX003Component final : public uart::UARTDevice, public Component {
SUB_SENSOR(humidity)
protected:
bool check_frame_(const uint8_t *frame, size_t total_size);
void parse_data_(const uint8_t *frame);
optional<bool> check_byte_();
void parse_data_();
bool check_payload_length_(uint16_t payload_length);
void send_command_(Command cmd, uint16_t data);
uint16_t get_16_bit_uint_(uint8_t start_index) const {
return encode_uint16(this->data_[start_index], this->data_[start_index + 1]);
}
Type type_;
State state_{State::IDLE};
bool initialised_{false};
LengthFrameReader<MAX_FRAME_SIZE, PmsFrame> reader_;
uint8_t data_[64];
uint8_t data_index_{0};
uint32_t fan_on_time_{0};
uint32_t last_update_{0};
uint32_t last_transmission_{0};
+13 -11
View File
@@ -10,10 +10,12 @@ CODEOWNERS = ["@kahrendt"]
qwiic_pir_ns = cg.esphome_ns.namespace("qwiic_pir")
DebounceMode = qwiic_pir_ns.enum("DebounceMode", is_class=True)
DEBOUNCE_MODE_OPTIONS = DebounceMode.options(
"RAW", "NATIVE", "HYBRID", prefix="DEBOUNCE_MODE_"
)
DebounceMode = qwiic_pir_ns.enum("DebounceMode")
DEBOUNCE_MODE_OPTIONS = {
"RAW": DebounceMode.RAW_DEBOUNCE_MODE,
"NATIVE": DebounceMode.NATIVE_DEBOUNCE_MODE,
"HYBRID": DebounceMode.HYBRID_DEBOUNCE_MODE,
}
CONF_DEBOUNCE_MODE = "debounce_mode"
@@ -45,12 +47,12 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config: ConfigType) -> None:
# Without a debounce time the device is set to 1 ms; NATIVE is the only mode that takes one
debounce = config.get(CONF_DEBOUNCE)
var = await binary_sensor.new_binary_sensor(
config,
config[CONF_DEBOUNCE_MODE],
1 if debounce is None else debounce.total_milliseconds,
)
var = await binary_sensor.new_binary_sensor(config)
await cg.register_component(var, config)
await i2c.register_i2c_device(var, config)
if debounce_time_setting := config.get(CONF_DEBOUNCE):
cg.add(var.set_debounce_time(debounce_time_setting.total_milliseconds))
else:
cg.add(var.set_debounce_time(1)) # default to 1 ms if not configured
cg.add(var.set_debounce_mode(config[CONF_DEBOUNCE_MODE]))
+65 -51
View File
@@ -1,85 +1,99 @@
#include "qwiic_pir.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
namespace esphome::qwiic_pir {
ESPHOME_LOG_TAG(TAG, "qwiic_pir");
static constexpr uint8_t REG_CHIP_ID = 0x00;
static constexpr uint8_t REG_EVENT_STATUS = 0x03;
static constexpr uint8_t REG_DEBOUNCE_TIME = 0x05; // milliseconds, 16 bits little endian
static constexpr uint8_t DEVICE_ID = 0x72;
// REG_EVENT_STATUS bits
static constexpr uint8_t EVENT_RAW_READING = 0x01; // raw state of the PIR sensor
static constexpr uint8_t EVENT_AVAILABLE = 0x02; // a debounced object was detected or removed
static constexpr uint8_t EVENT_OBJECT_REMOVED = 0x04; // a debounced object is no longer detected
static constexpr uint8_t EVENT_OBJECT_DETECTED = 0x08; // a debounced object has been detected
// Indexed by DebounceMode
PROGMEM_STRING_TABLE(DebounceModeStrings, "RAW", "NATIVE", "HYBRID");
void QwiicPIRComponent::setup() {
if (!this->check_chip_id(this, REG_CHIP_ID, DEVICE_ID))
if (!this->check_chip_id(this, QWIIC_PIR_CHIP_ID, QWIIC_PIR_DEVICE_ID))
return;
if (!this->setup_check(this->write_byte_16_le(REG_DEBOUNCE_TIME, this->debounce_time_),
if (!this->setup_check(this->write_byte_16(QWIIC_PIR_DEBOUNCE_TIME, this->debounce_time_),
LOG_STR("Failed to configure debounce time")))
return;
if (this->debounce_mode_ == DebounceMode::DEBOUNCE_MODE_NATIVE) {
// NATIVE only publishes on motion events, so start from the raw state
uint8_t event;
if (!this->setup_check(this->read_byte(REG_EVENT_STATUS, &event), LOG_STR("Failed to read initial state")))
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
// Publish the starting raw state of the PIR sensor
// If NATIVE mode, the binary_sensor state would be unknown until a motion event
if (!this->setup_check(this->read_byte(QWIIC_PIR_EVENT_STATUS, &this->event_register_.reg),
LOG_STR("Failed to read initial state")))
return;
this->publish_state((event & EVENT_RAW_READING) != 0);
this->publish_state(this->event_register_.raw_reading);
}
}
void QwiicPIRComponent::loop() {
uint8_t event;
if (!this->status_comm_check(this->read_byte(REG_EVENT_STATUS, &event)))
// Read Event Register
if (!this->read_byte(QWIIC_PIR_EVENT_STATUS, &this->event_register_.reg)) {
ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
return;
switch (this->debounce_mode_) {
case DebounceMode::DEBOUNCE_MODE_HYBRID:
// The device debounces for 1 ms and ESPHome filters do the rest; any event means motion since the last loop
this->publish_state((event & (EVENT_RAW_READING | EVENT_AVAILABLE)) != 0);
break;
case DebounceMode::DEBOUNCE_MODE_NATIVE:
// The device's own debounce, as in SparkFun's Example2_PrintPIRStatus; it often misses objects being removed
if (event & EVENT_AVAILABLE) {
if (event & EVENT_OBJECT_DETECTED)
this->publish_state(true);
if (event & EVENT_OBJECT_REMOVED)
this->publish_state(false);
}
break;
case DebounceMode::DEBOUNCE_MODE_RAW:
// Can miss a very short detection when the loop is slow
this->publish_state((event & EVENT_RAW_READING) != 0);
break;
}
// HYBRID and NATIVE clear a handled event; the last bus step of the poll decides the warning
bool ok = true;
if (this->debounce_mode_ != DebounceMode::DEBOUNCE_MODE_RAW && (event & EVENT_AVAILABLE))
ok = this->write_byte(REG_EVENT_STATUS, 0x00);
this->status_comm_result(ok);
if (this->debounce_mode_ == HYBRID_DEBOUNCE_MODE) {
// Use a combination of the raw sensor reading and the device's event detection to determine state
// - The device is hardcoded to use a debounce time of 1 ms in this mode
// - Any event, even if it is object_removed, implies motion was active since the last loop, so publish true
// - Use ESPHome's built-in filters for debouncing
this->publish_state(this->event_register_.raw_reading || this->event_register_.event_available);
if (this->event_register_.event_available) {
this->clear_events_();
}
} else if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
// Uses the device's firmware to debounce the signal
// - Follows the logic of SparkFun's example implementation:
// https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library/blob/master/examples/Example2_PrintPIRStatus/Example2_PrintPIRStatus.ino
// (accessed July 2023)
// - Is unreliable at detecting an object being removed, especially at debounce rates even slightly large
if (this->event_register_.event_available) {
// If an object is detected, publish true
if (this->event_register_.object_detected)
this->publish_state(true);
// If an object has been removed, publish false
if (this->event_register_.object_removed)
this->publish_state(false);
this->clear_events_();
}
} else if (this->debounce_mode_ == RAW_DEBOUNCE_MODE) {
// Publishes the raw PIR sensor reading with no further logic
// - May miss a very short motion detection if the ESP's loop time is slow
this->publish_state(this->event_register_.raw_reading);
}
}
void QwiicPIRComponent::dump_config() {
static const char *const RAW = "RAW";
static const char *const NATIVE = "NATIVE";
static const char *const HYBRID = "HYBRID";
const char *debounce_mode_str = RAW;
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
debounce_mode_str = NATIVE;
} else if (this->debounce_mode_ == HYBRID_DEBOUNCE_MODE) {
debounce_mode_str = HYBRID;
}
ESP_LOGCONFIG(TAG,
"Qwiic PIR:\n"
" Debounce Mode: %s",
LOG_STR_ARG(DebounceModeStrings::get_log_str(static_cast<uint8_t>(this->debounce_mode_), 0)));
if (this->debounce_mode_ == DebounceMode::DEBOUNCE_MODE_NATIVE) {
debounce_mode_str);
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
ESP_LOGCONFIG(TAG, " Debounce Time: %ums", this->debounce_time_);
}
LOG_I2C_DEVICE(this);
LOG_BINARY_SENSOR(" ", "Binary Sensor", this);
}
void QwiicPIRComponent::clear_events_() {
// Clear event status register
if (!this->write_byte(QWIIC_PIR_EVENT_STATUS, 0x00)) {
ESP_LOGW(TAG, "Failed to clear events");
}
}
} // namespace esphome::qwiic_pir
+35 -11
View File
@@ -2,8 +2,8 @@
* Adds support for Qwiic PIR motion sensors that communicate over an I2C bus.
* These sensors use Sharp PIR motion sensors to detect motion. A firmware running on an ATTiny84 translates the digital
* output to I2C communications.
* ATTiny84 firmware: https://github.com/sparkfun/Qwiic_PIR
* SparkFun's Arduino library: https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library
* ATTiny84 firmware: https://github.com/sparkfun/Qwiic_PIR (accessed July 2023)
* SparkFun's Arduino library: https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library (accessed July 2023)
*/
#pragma once
@@ -14,24 +14,48 @@
namespace esphome::qwiic_pir {
enum class DebounceMode : uint8_t {
DEBOUNCE_MODE_RAW,
DEBOUNCE_MODE_NATIVE,
DEBOUNCE_MODE_HYBRID,
// Qwiic PIR I2C Register Addresses
enum {
QWIIC_PIR_CHIP_ID = 0x00,
QWIIC_PIR_EVENT_STATUS = 0x03,
QWIIC_PIR_DEBOUNCE_TIME = 0x05, // uint16_t debounce time in milliseconds
};
enum DebounceMode {
RAW_DEBOUNCE_MODE,
NATIVE_DEBOUNCE_MODE,
HYBRID_DEBOUNCE_MODE,
};
static const uint8_t QWIIC_PIR_DEVICE_ID = 0x72;
class QwiicPIRComponent final : public Component, public i2c::I2CDevice, public binary_sensor::BinarySensor {
public:
QwiicPIRComponent(DebounceMode debounce_mode, uint16_t debounce_time)
: debounce_time_(debounce_time), debounce_mode_(debounce_mode) {}
void setup() override;
void loop() override;
void dump_config() override;
void set_debounce_time(uint16_t debounce_time) { this->debounce_time_ = debounce_time; }
void set_debounce_mode(DebounceMode mode) { this->debounce_mode_ = mode; }
protected:
uint16_t debounce_time_;
DebounceMode debounce_mode_;
uint16_t debounce_time_{};
DebounceMode debounce_mode_{};
union {
struct {
bool raw_reading : 1; // raw state of PIR sensor
bool event_available : 1; // a debounced object has been detected or removed
bool object_removed : 1; // a debounced object is no longer detected
bool object_detected : 1; // a debounced object has been detected
bool : 4;
};
uint8_t reg;
} event_register_ = {.reg = 0};
void clear_events_();
};
} // namespace esphome::qwiic_pir
+8
View File
@@ -2,6 +2,10 @@
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#ifdef USE_ESP8266
#include <Wire.h>
#endif
namespace esphome::scd30 {
ESPHOME_LOG_TAG(TAG, "scd30");
@@ -23,6 +27,10 @@ static const uint16_t SCD30_CMD_TEMPERATURE_OFFSET = 0x5403;
static const uint16_t SCD30_CMD_SOFT_RESET = 0xD304;
void SCD30Component::setup() {
#ifdef USE_ESP8266
Wire.setClockStretchLimit(150000);
#endif
/// Firmware version identification
uint16_t raw_firmware_version[3];
if (!this->setup_check(this->get_register(SCD30_CMD_GET_FIRMWARE_VERSION, raw_firmware_version, 3),
@@ -1,7 +1,6 @@
#include "seeed_mr24hpc1.h"
#include "esphome/core/helpers.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
@@ -83,12 +82,17 @@ void MR24HPC1Component::setup() {
this->poll_time_base_func_check_ = false;
this->check_dev_inf_sign_ = true;
this->sg_start_query_data_ = STANDARD_FUNCTION_QUERY_PRODUCT_MODE;
this->sg_data_len_ = 0;
this->sg_frame_len_ = 0;
this->sg_recv_data_state_ = FRAME_IDLE;
this->s_output_info_switch_flag_ = OUTPUT_SWITCH_INIT;
memset(this->c_product_mode_, 0, PRODUCT_BUF_MAX_SIZE);
memset(this->c_product_id_, 0, PRODUCT_BUF_MAX_SIZE);
memset(this->c_firmware_version_, 0, PRODUCT_BUF_MAX_SIZE);
memset(this->c_hardware_model_, 0, PRODUCT_BUF_MAX_SIZE);
memset(this->sg_frame_prase_buf_, 0, FRAME_BUF_MAX_SIZE);
memset(this->sg_frame_buf_, 0, FRAME_BUF_MAX_SIZE);
// The module locks up when queried during its own boot, so hold all TX for a second
this->set_timeout(STARTUP_DELAY_MS, [this]() {
@@ -105,29 +109,9 @@ void MR24HPC1Component::update_() {
this->poll_time_base_func_check_ = true; // Query the base functionality information at regular intervals
}
// The reader keeps frames at MIN_FRAME_SIZE or more, so the three trailing bytes can always be left out
static uint8_t get_frame_crc_sum(const uint8_t *data, size_t len) { return sum_bytes(data, len - 3); }
// Footer and sum
static bool frame_valid(const uint8_t *data, size_t len) {
if (data[len - 2] != FRAME_TAIL1_VALUE || data[len - 1] != FRAME_TAIL2_VALUE)
return false;
if (data[len - 3] != get_frame_crc_sum(data, len)) {
ESP_LOGD(TAG, "frame check failure!");
return false;
}
return true;
}
// main loop
void MR24HPC1Component::loop() {
auto handler = [this](const uint8_t *frame, size_t len) {
if (!frame_valid(frame, len))
return false;
this->r24_parse_data_frame_(frame, len);
return true;
};
this->read_frames(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
this->read_available([this](uint8_t b) { this->r24_split_data_frame_(b); });
if ((this->s_output_info_switch_flag_ == OUTPUT_SWITCH_OFF) &&
(this->sg_start_query_data_ > CUSTOM_FUNCTION_QUERY_TIME_OF_ENTER_UNMANNED) && (!this->check_dev_inf_sign_)) {
@@ -262,8 +246,109 @@ void MR24HPC1Component::loop() {
}
}
// Frames are at least 10 bytes, so the three trailing bytes can always be left out
static uint8_t get_frame_crc_sum(const uint8_t *data, size_t len) { return sum_bytes(data, len - 3); }
// Check that the check digit is correct
static int get_frame_check_status(const uint8_t *data, size_t len) {
uint8_t crc_sum = get_frame_crc_sum(data, len);
uint8_t verified = data[len - 3];
return (verified == crc_sum) ? 1 : 0;
}
// split data frame
void MR24HPC1Component::r24_split_data_frame_(uint8_t value) {
switch (this->sg_recv_data_state_) {
case FRAME_IDLE: // starting value
if (FRAME_HEADER1_VALUE == value) {
this->sg_recv_data_state_ = FRAME_HEADER2;
}
break;
case FRAME_HEADER2:
if (FRAME_HEADER2_VALUE == value) {
this->sg_frame_buf_[0] = FRAME_HEADER1_VALUE;
this->sg_frame_buf_[1] = FRAME_HEADER2_VALUE;
this->sg_recv_data_state_ = FRAME_CTL_WORD;
} else {
this->sg_recv_data_state_ = FRAME_IDLE;
ESP_LOGD(TAG, "FRAME_IDLE ERROR value:%x", value);
}
break;
case FRAME_CTL_WORD:
this->sg_frame_buf_[2] = value;
this->sg_recv_data_state_ = FRAME_CMD_WORD;
break;
case FRAME_CMD_WORD:
this->sg_frame_buf_[3] = value;
this->sg_recv_data_state_ = FRAME_DATA_LEN_H;
break;
case FRAME_DATA_LEN_H:
if (value == 0) {
this->sg_frame_buf_[4] = value;
this->sg_recv_data_state_ = FRAME_DATA_LEN_L;
} else {
this->sg_recv_data_state_ = FRAME_IDLE;
ESP_LOGD(TAG, "FRAME_DATA_LEN_H ERROR value:%x", value);
}
break;
case FRAME_DATA_LEN_L:
this->sg_data_len_ = value;
if (this->sg_data_len_ == 0 || this->sg_data_len_ > 32) {
ESP_LOGD(TAG, "len=%d, FRAME_DATA_LEN_L ERROR value:%x", this->sg_data_len_, value);
this->sg_data_len_ = 0;
this->sg_recv_data_state_ = FRAME_IDLE;
} else {
this->sg_frame_buf_[5] = value;
this->sg_frame_len_ = 6;
this->sg_recv_data_state_ = FRAME_DATA_BYTES;
}
break;
case FRAME_DATA_BYTES:
this->sg_frame_buf_[this->sg_frame_len_++] = value;
if (--this->sg_data_len_ == 0) {
this->sg_recv_data_state_ = FRAME_DATA_CRC;
}
break;
case FRAME_DATA_CRC:
this->sg_frame_buf_[this->sg_frame_len_++] = value;
this->sg_recv_data_state_ = FRAME_TAIL1;
break;
case FRAME_TAIL1:
if (FRAME_TAIL1_VALUE == value) {
this->sg_recv_data_state_ = FRAME_TAIL2;
} else {
this->sg_recv_data_state_ = FRAME_IDLE;
this->sg_frame_len_ = 0;
this->sg_data_len_ = 0;
ESP_LOGD(TAG, "FRAME_TAIL1 ERROR value:%x", value);
}
break;
case FRAME_TAIL2:
if (FRAME_TAIL2_VALUE == value) {
this->sg_frame_buf_[this->sg_frame_len_++] = FRAME_TAIL1_VALUE;
this->sg_frame_buf_[this->sg_frame_len_++] = FRAME_TAIL2_VALUE;
memcpy(this->sg_frame_prase_buf_, this->sg_frame_buf_, this->sg_frame_len_);
if (get_frame_check_status(this->sg_frame_prase_buf_, this->sg_frame_len_)) {
this->r24_parse_data_frame_(this->sg_frame_prase_buf_, this->sg_frame_len_);
} else {
ESP_LOGD(TAG, "frame check failure!");
}
} else {
ESP_LOGD(TAG, "FRAME_TAIL2 ERROR value:%x", value);
}
memset(this->sg_frame_prase_buf_, 0, FRAME_BUF_MAX_SIZE);
memset(this->sg_frame_buf_, 0, FRAME_BUF_MAX_SIZE);
this->sg_frame_len_ = 0;
this->sg_data_len_ = 0;
this->sg_recv_data_state_ = FRAME_IDLE;
break;
default:
this->sg_recv_data_state_ = FRAME_IDLE;
}
}
// Parses data frames related to product information
void MR24HPC1Component::r24_frame_parse_product_information_(const uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_product_information_(uint8_t *data) {
#ifdef USE_TEXT_SENSOR
uint16_t product_len = encode_uint16(data[FRAME_COMMAND_WORD_INDEX + 1], data[FRAME_COMMAND_WORD_INDEX + 2]);
if (data[FRAME_COMMAND_WORD_INDEX] == COMMAND_PRODUCT_MODE) {
@@ -304,7 +389,7 @@ void MR24HPC1Component::r24_frame_parse_product_information_(const uint8_t *data
}
// Parsing the underlying open parameters
void MR24HPC1Component::r24_frame_parse_open_underlying_information_(const uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_open_underlying_information_(uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
case 0x00:
case 0x80:
@@ -397,7 +482,7 @@ void MR24HPC1Component::r24_frame_parse_open_underlying_information_(const uint8
}
}
void MR24HPC1Component::r24_parse_data_frame_(const uint8_t *data, uint8_t len) {
void MR24HPC1Component::r24_parse_data_frame_(uint8_t *data, uint8_t len) {
switch (data[FRAME_CONTROL_WORD_INDEX]) {
case 0x01: {
if (data[FRAME_COMMAND_WORD_INDEX] == 0x02) {
@@ -427,7 +512,7 @@ void MR24HPC1Component::r24_parse_data_frame_(const uint8_t *data, uint8_t len)
}
}
void MR24HPC1Component::r24_frame_parse_work_status_(const uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_work_status_(uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
case 0x01:
case 0x81:
@@ -484,7 +569,7 @@ void MR24HPC1Component::r24_frame_parse_work_status_(const uint8_t *data) {
}
}
void MR24HPC1Component::r24_frame_parse_human_information_(const uint8_t *data) {
void MR24HPC1Component::r24_frame_parse_human_information_(uint8_t *data) {
switch (data[FRAME_COMMAND_WORD_INDEX]) {
#ifdef USE_BINARY_SENSOR
case 0x01:
@@ -24,7 +24,6 @@
#endif
#include "esphome/components/uart/uart.h"
#include "esphome/core/automation.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include "seeed_mr24hpc1_constants.h"
@@ -33,6 +32,19 @@
namespace esphome::seeed_mr24hpc1 {
enum FrameState {
FRAME_IDLE,
FRAME_HEADER2,
FRAME_CTL_WORD,
FRAME_CMD_WORD,
FRAME_DATA_LEN_H,
FRAME_DATA_LEN_L,
FRAME_DATA_BYTES,
FRAME_DATA_CRC,
FRAME_TAIL1,
FRAME_TAIL2,
};
enum PollingState {
STANDARD_FUNCTION_QUERY_PRODUCT_MODE = 0,
STANDARD_FUNCTION_QUERY_PRODUCT_ID,
@@ -122,24 +134,24 @@ class MR24HPC1Component final : public Component,
char c_product_id_[PRODUCT_BUF_MAX_SIZE + 1];
char c_hardware_model_[PRODUCT_BUF_MAX_SIZE + 1];
char c_firmware_version_[PRODUCT_BUF_MAX_SIZE + 1];
uint32_t last_rx_{0};
// 53 59, control, command, payload length (2, BE), payload (at least 1), sum, 54 43
LengthFrameReader<FRAME_BUF_MAX_SIZE, FrameFormat<FrameHeader<FRAME_HEADER1_VALUE, FRAME_HEADER2_VALUE>,
PayloadLengthU16BE<LengthField{.offset = 4, .trailer = 3}>,
FrameMinLength<MIN_FRAME_SIZE>>>
reader_;
int sg_start_query_data_;
uint8_t s_output_info_switch_flag_;
uint8_t sg_recv_data_state_;
uint8_t sg_frame_len_;
uint8_t sg_data_len_;
uint8_t sg_frame_buf_[FRAME_BUF_MAX_SIZE];
uint8_t sg_frame_prase_buf_[FRAME_BUF_MAX_SIZE];
int sg_start_query_data_;
bool check_dev_inf_sign_;
bool poll_time_base_func_check_;
bool module_ready_{false};
void update_();
void r24_parse_data_frame_(const uint8_t *data, uint8_t len);
void r24_frame_parse_open_underlying_information_(const uint8_t *data);
void r24_frame_parse_work_status_(const uint8_t *data);
void r24_frame_parse_product_information_(const uint8_t *data);
void r24_frame_parse_human_information_(const uint8_t *data);
void r24_split_data_frame_(uint8_t value);
void r24_parse_data_frame_(uint8_t *data, uint8_t len);
void r24_frame_parse_open_underlying_information_(uint8_t *data);
void r24_frame_parse_work_status_(uint8_t *data);
void r24_frame_parse_product_information_(uint8_t *data);
void r24_frame_parse_human_information_(uint8_t *data);
void send_query_(const uint8_t *query, size_t string_length);
public:
@@ -4,9 +4,7 @@
namespace esphome::seeed_mr24hpc1 {
// 6 header bytes, up to 32 data bytes, sum and 2 footer bytes
static constexpr uint8_t FRAME_BUF_MAX_SIZE = 41;
static constexpr uint8_t MIN_FRAME_SIZE = 10; // header (2), control, command, length (2), 1 data byte, sum, footer (2)
static const uint8_t FRAME_BUF_MAX_SIZE = 128;
static const uint8_t PRODUCT_BUF_MAX_SIZE = 32;
static const uint8_t FRAME_CONTROL_WORD_INDEX = 2;
@@ -1,6 +1,5 @@
#include "seeed_mr60bha2.h"
#include "esphome/core/helpers.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include <cinttypes>
@@ -28,6 +27,16 @@ void MR60BHA2Component::dump_config() {
#endif
}
// main loop
void MR60BHA2Component::loop() {
this->read_available([this](uint8_t b) {
this->rx_message_.push_back(b);
if (!this->validate_message_()) {
this->rx_message_.clear();
}
});
}
/**
* @brief Validate the checksum of a byte array.
*
@@ -43,62 +52,75 @@ static bool validate_checksum(const uint8_t *data, size_t len, uint8_t expected_
return static_cast<uint8_t>(~xor_bytes(data, len)) == expected_checksum;
}
static bool is_known_type(uint16_t type) {
return type == BREATH_RATE_TYPE_BUFFER || type == HEART_RATE_TYPE_BUFFER || type == DISTANCE_TYPE_BUFFER ||
type == PEOPLE_EXIST_TYPE_BUFFER || type == PRINT_CLOUD_BUFFER;
}
bool MR60BHA2Component::validate_message_() {
size_t at = this->rx_message_.size() - 1;
auto *data = &this->rx_message_[0];
uint8_t new_byte = data[at];
// An unknown type or a bad header checksum gives no length, so the header is dropped at once
size_t TinyFrameLength::get(const uint8_t *buf) {
if (!is_known_type(encode_uint16(buf[5], buf[6])))
return 0;
constexpr size_t cksum_pos = TinyFrameLength::KNOWN_AT - 1;
if (!validate_checksum(buf, cksum_pos, buf[cksum_pos])) {
ESP_LOGE(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", buf[cksum_pos]);
ESP_LOGV_HEX(TAG, buf, TinyFrameLength::KNOWN_AT, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
return 0;
if (at == 0) {
return new_byte == FRAME_HEADER_BUFFER;
}
return encode_uint16(buf[3], buf[4]) + FRAME_OVERHEAD;
}
void warn_too_long(size_t len) {
ESP_LOGW(TAG, "Skipped a %u byte frame, longer than the %u byte buffer", static_cast<unsigned>(len),
static_cast<unsigned>(FRAME_MAX_SIZE));
}
if (at <= 2) {
return true;
}
uint16_t frame_id = encode_uint16(data[1], data[2]);
// The reader checks the type and the header; the data checksum is checked here
static bool frame_valid(const uint8_t *frame, size_t len) {
if (!validate_checksum(frame + TinyFrameLength::KNOWN_AT, len - FRAME_OVERHEAD, frame[len - 1])) {
ESP_LOGE(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", frame[len - 1]);
ESP_LOGV_HEX(TAG, frame, len - 1, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
if (at <= 4) {
return true;
}
uint16_t length = encode_uint16(data[3], data[4]);
if (at <= 6) {
return true;
}
uint16_t frame_type = encode_uint16(data[5], data[6]);
if (frame_type != BREATH_RATE_TYPE_BUFFER && frame_type != HEART_RATE_TYPE_BUFFER &&
frame_type != DISTANCE_TYPE_BUFFER && frame_type != PEOPLE_EXIST_TYPE_BUFFER &&
frame_type != PRINT_CLOUD_BUFFER) {
return false;
}
return true;
}
void MR60BHA2Component::loop() {
auto handler = [this](const uint8_t *frame, size_t len) {
if (!frame_valid(frame, len))
uint8_t header_checksum = new_byte;
if (at == 7) {
if (!validate_checksum(data, 7, header_checksum)) {
ESP_LOGE(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", header_checksum);
ESP_LOGV_HEX(TAG, data, 8, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
return false;
this->handle_frame_(frame, len);
}
return true;
};
this->read_frames(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
}
}
void MR60BHA2Component::handle_frame_(const uint8_t *frame, size_t len) {
const uint16_t frame_id = encode_uint16(frame[1], frame[2]);
const uint16_t frame_type = encode_uint16(frame[5], frame[6]);
const uint8_t *frame_data = frame + TinyFrameLength::KNOWN_AT;
const size_t length = len - FRAME_OVERHEAD;
// Wait until all data is read
if (at - 8 < length) {
return true;
}
uint8_t data_checksum = new_byte;
if (at == 8 + length) {
if (!validate_checksum(data + 8, length, data_checksum)) {
ESP_LOGE(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", data_checksum);
ESP_LOGV_HEX(TAG, data, 8 + length, MR60BHA2_MAX_LOG_BYTES, "GET FRAME: %s");
return false;
}
}
const uint8_t *frame_data = data + 8;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf1[format_hex_pretty_size(MR60BHA2_MAX_LOG_BYTES)];
char hex_buf2[format_hex_pretty_size(MR60BHA2_MAX_LOG_BYTES)];
#endif
ESP_LOGV(TAG, "Received Frame: ID: 0x%04x, Type: 0x%04x, Data: [%s] Raw Data: [%s]", frame_id, frame_type,
format_hex_pretty_to(hex_buf1, sizeof(hex_buf1), frame_data, length),
format_hex_pretty_to(hex_buf2, sizeof(hex_buf2), frame, len));
this->process_frame_(frame_id, frame_type, frame_data, length);
format_hex_pretty_to(hex_buf2, sizeof(hex_buf2), this->rx_message_.data(), this->rx_message_.size()));
this->process_frame_(frame_id, frame_type, data + 8, length);
// Return false to reset rx buffer
return false;
}
void MR60BHA2Component::process_frame_(uint16_t frame_id, uint16_t frame_type, const uint8_t *data, size_t length) {
@@ -9,24 +9,12 @@
#endif
#include "esphome/components/uart/uart.h"
#include "esphome/core/automation.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include <map>
namespace esphome::seeed_mr60bha2 {
static constexpr uint8_t FRAME_HEADER_BUFFER = 0x01;
/// 01, id (2), data length (2, BE), type (2), header checksum, data, data checksum; 0 for a bad header
struct TinyFrameLength {
static constexpr size_t KNOWN_AT = 8;
static size_t get(const uint8_t *buf);
};
void warn_too_long(size_t len);
// Header, id, length and type bytes, header checksum, then the data and its checksum
static constexpr uint8_t FRAME_OVERHEAD = 9;
// A point cloud frame is 13 bytes plus 16 per target and only its count is read; 128 holds up to 7 targets
static constexpr uint8_t FRAME_MAX_SIZE = 128;
static const uint8_t FRAME_HEADER_BUFFER = 0x01;
static const uint16_t BREATH_RATE_TYPE_BUFFER = 0x0A14;
static const uint16_t PEOPLE_EXIST_TYPE_BUFFER = 0x0F09;
static const uint16_t HEART_RATE_TYPE_BUFFER = 0x0A15;
@@ -51,13 +39,10 @@ class MR60BHA2Component final : public Component,
void loop() override;
protected:
void handle_frame_(const uint8_t *frame, size_t len);
bool validate_message_();
void process_frame_(uint16_t frame_id, uint16_t frame_type, const uint8_t *data, size_t length);
uint32_t last_rx_{0};
LengthFrameReader<FRAME_MAX_SIZE, FrameFormat<FrameHeader<FRAME_HEADER_BUFFER>,
WarnIfLonger<TinyFrameLength, FRAME_MAX_SIZE, warn_too_long>>>
reader_;
std::vector<uint8_t> rx_message_;
};
} // namespace esphome::seeed_mr60bha2
@@ -1,7 +1,6 @@
#include "seeed_mr60fda2.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include <cinttypes>
@@ -34,7 +33,22 @@ void MR60FDA2Component::dump_config() {
}
// Initialisation functions
void MR60FDA2Component::setup() { this->get_radar_parameters(); }
void MR60FDA2Component::setup() {
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
this->current_frame_id_ = 0;
this->current_frame_len_ = 0;
this->current_data_frame_len_ = 0;
this->current_frame_type_ = 0;
this->get_radar_parameters();
memset(this->current_frame_buf_, 0, FRAME_BUF_MAX_SIZE);
memset(this->current_data_buf_, 0, DATA_BUF_MAX_SIZE);
}
// main loop
void MR60FDA2Component::loop() {
this->read_available([this](uint8_t b) { this->split_frame_(b); });
}
// The checksum is the inverted XOR of the bytes
static uint8_t calculate_checksum(const uint8_t *data, size_t len) { return ~xor_bytes(data, len); }
@@ -54,45 +68,6 @@ static bool validate_checksum(const uint8_t *data, size_t len, uint8_t expected_
return calculate_checksum(data, len) == expected_checksum;
}
static bool is_known_type(uint16_t type) {
return type == IS_FALL_TYPE_BUFFER || type == PEOPLE_EXIST_TYPE_BUFFER || type == RESULT_INSTALL_HEIGHT ||
type == RESULT_PARAMETERS || type == RESULT_HEIGHT_THRESHOLD || type == RESULT_SENSITIVITY;
}
// An unknown type or a bad header checksum gives no length, so the header is dropped at once
size_t TinyFrameLength::get(const uint8_t *buf) {
const uint16_t type = encode_uint16(buf[5], buf[6]);
const uint16_t data_len = encode_uint16(buf[3], buf[4]);
// A parameter reply is read for 12 data bytes
if (!is_known_type(type) || (type == RESULT_PARAMETERS && data_len < 12))
return 0;
if (!validate_checksum(buf, LEN_TO_HEAD_CKSUM - 1, buf[LEN_TO_HEAD_CKSUM - 1])) {
ESP_LOGD(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", buf[LEN_TO_HEAD_CKSUM - 1]);
ESP_LOGV_HEX(TAG, buf, LEN_TO_HEAD_CKSUM, MR60FDA2_MAX_LOG_BYTES, "CURRENT_FRAME: %s");
return 0;
}
return data_len + LEN_TO_DATA_FRAME;
}
static bool frame_valid(const uint8_t *frame, size_t len) {
if (!validate_checksum(frame + LEN_TO_HEAD_CKSUM, len - LEN_TO_DATA_FRAME, frame[len - 1])) {
ESP_LOGD(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", frame[len - 1]);
ESP_LOGV_HEX(TAG, frame, len, MR60FDA2_MAX_LOG_BYTES, "GET CURRENT_FRAME: %s");
return false;
}
return true;
}
void MR60FDA2Component::loop() {
auto handler = [this](const uint8_t *frame, size_t len) {
if (!frame_valid(frame, len))
return false;
this->process_frame_(frame);
return true;
};
this->read_frames(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_);
}
#ifdef USE_SELECT
static uint8_t find_nearest_index(float value, const float *arr, int size) {
int nearest_index = 0;
@@ -113,43 +88,152 @@ alignas(4) static const float INSTALL_HEIGHT[7] PROGMEM = {2.4f, 2.5f, 2.6f, 2.7
alignas(4) static const float HEIGHT_THRESHOLD[7] PROGMEM = {0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f};
alignas(4) static const float SENSITIVITY[3] PROGMEM = {3, 15, 30};
void MR60FDA2Component::process_frame_(const uint8_t *frame) {
const uint8_t *data = frame + LEN_TO_HEAD_CKSUM;
switch (encode_uint16(frame[5], frame[6])) {
void MR60FDA2Component::split_frame_(uint8_t buffer) {
switch (this->current_frame_locate_) {
case LOCATE_FRAME_HEADER: // starting buffer
if (buffer == FRAME_HEADER_BUFFER) {
this->current_frame_len_ = 0;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
}
break;
case LOCATE_ID_FRAME1:
this->current_frame_id_ = buffer << 8;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
break;
case LOCATE_ID_FRAME2:
this->current_frame_id_ += buffer;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
break;
case LOCATE_LENGTH_FRAME_H:
this->current_data_frame_len_ = buffer << 8;
if (this->current_data_frame_len_ == 0) {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
} else {
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
}
break;
case LOCATE_LENGTH_FRAME_L:
this->current_data_frame_len_ += buffer;
if (this->current_data_frame_len_ > DATA_BUF_MAX_SIZE) {
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
} else {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
}
break;
case LOCATE_TYPE_FRAME1:
this->current_frame_type_ = buffer << 8;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
break;
case LOCATE_TYPE_FRAME2:
this->current_frame_type_ += buffer;
if ((this->current_frame_type_ == IS_FALL_TYPE_BUFFER) ||
(this->current_frame_type_ == PEOPLE_EXIST_TYPE_BUFFER) ||
(this->current_frame_type_ == RESULT_INSTALL_HEIGHT) || (this->current_frame_type_ == RESULT_PARAMETERS) ||
(this->current_frame_type_ == RESULT_HEIGHT_THRESHOLD) || (this->current_frame_type_ == RESULT_SENSITIVITY)) {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
} else {
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
}
break;
case LOCATE_HEAD_CKSUM_FRAME:
if (validate_checksum(this->current_frame_buf_, this->current_frame_len_, buffer)) {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
} else {
ESP_LOGD(TAG, "HEAD_CKSUM_FRAME ERROR: 0x%02x", buffer);
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char frame_buf[format_hex_pretty_size(MR60FDA2_MAX_LOG_BYTES)];
char byte_buf[format_hex_pretty_size(1)];
#endif
ESP_LOGV(TAG, "CURRENT_FRAME: %s %s",
format_hex_pretty_to(frame_buf, this->current_frame_buf_, this->current_frame_len_),
format_hex_pretty_to(byte_buf, &buffer, 1));
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
}
break;
case LOCATE_DATA_FRAME:
if (this->current_frame_len_ >= FRAME_BUF_MAX_SIZE) {
ESP_LOGD(TAG, "PRACTICE_DATA_FRAME_LEN ERROR: %d", this->current_frame_len_ - LEN_TO_HEAD_CKSUM);
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
}
this->current_data_buf_[this->current_frame_len_ - LEN_TO_DATA_FRAME + 1] = buffer;
this->current_frame_buf_[this->current_frame_len_++] = buffer;
if (this->current_frame_len_ - LEN_TO_HEAD_CKSUM == this->current_data_frame_len_) {
this->current_frame_locate_++;
}
break;
case LOCATE_DATA_CKSUM_FRAME:
if (validate_checksum(this->current_data_buf_, this->current_data_frame_len_, buffer)) {
this->current_frame_buf_[this->current_frame_len_++] = buffer;
this->current_frame_locate_++;
this->process_frame_();
} else {
ESP_LOGD(TAG, "DATA_CKSUM_FRAME ERROR: 0x%02x", buffer);
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char frame_buf[format_hex_pretty_size(MR60FDA2_MAX_LOG_BYTES)];
char byte_buf[format_hex_pretty_size(1)];
#endif
ESP_LOGV(TAG, "GET CURRENT_FRAME: %s %s",
format_hex_pretty_to(frame_buf, this->current_frame_buf_, this->current_frame_len_),
format_hex_pretty_to(byte_buf, &buffer, 1));
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
}
break;
default:
break;
}
}
void MR60FDA2Component::process_frame_() {
switch (this->current_frame_type_) {
case IS_FALL_TYPE_BUFFER:
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->fall_detected_binary_sensor_, data[0]);
PUBLISH_STATE(this->fall_detected_binary_sensor_, this->current_frame_buf_[LEN_TO_HEAD_CKSUM]);
#endif
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case PEOPLE_EXIST_TYPE_BUFFER:
#ifdef USE_BINARY_SENSOR
PUBLISH_STATE(this->people_exist_binary_sensor_, data[0]);
PUBLISH_STATE(this->people_exist_binary_sensor_, this->current_frame_buf_[LEN_TO_HEAD_CKSUM]);
#endif
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_INSTALL_HEIGHT:
if (data[0]) {
if (this->current_data_buf_[0]) {
ESP_LOGD(TAG, "Successfully set the mounting height");
} else {
ESP_LOGD(TAG, "Failed to set the mounting height");
}
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_HEIGHT_THRESHOLD:
if (data[0]) {
if (this->current_data_buf_[0]) {
ESP_LOGD(TAG, "Successfully set the height threshold");
} else {
ESP_LOGD(TAG, "Failed to set the height threshold");
}
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_SENSITIVITY:
if (data[0]) {
if (this->current_data_buf_[0]) {
ESP_LOGD(TAG, "Successfully set the sensitivity");
} else {
ESP_LOGD(TAG, "Failed to set the sensitivity");
}
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
case RESULT_PARAMETERS: {
@@ -158,7 +242,8 @@ void MR60FDA2Component::process_frame_(const uint8_t *frame) {
uint32_t current_sensitivity = 0;
#ifdef USE_SELECT
if (this->install_height_select_ != nullptr) {
uint32_t current_install_height_int = encode_uint32(data[3], data[2], data[1], data[0]);
uint32_t current_install_height_int =
encode_uint32(current_data_buf_[3], current_data_buf_[2], current_data_buf_[1], current_data_buf_[0]);
install_height_float = bit_cast<float>(current_install_height_int);
uint32_t select_index = find_nearest_index(install_height_float, INSTALL_HEIGHT, 7);
@@ -166,7 +251,8 @@ void MR60FDA2Component::process_frame_(const uint8_t *frame) {
}
if (this->height_threshold_select_ != nullptr) {
uint32_t current_height_threshold_int = encode_uint32(data[7], data[6], data[5], data[4]);
uint32_t current_height_threshold_int =
encode_uint32(current_data_buf_[7], current_data_buf_[6], current_data_buf_[5], current_data_buf_[4]);
height_threshold_float = bit_cast<float>(current_height_threshold_int);
size_t select_index = find_nearest_index(height_threshold_float, HEIGHT_THRESHOLD, 7);
@@ -174,7 +260,8 @@ void MR60FDA2Component::process_frame_(const uint8_t *frame) {
}
if (this->sensitivity_select_ != nullptr) {
current_sensitivity = encode_uint32(data[11], data[10], data[9], data[8]);
current_sensitivity =
encode_uint32(current_data_buf_[11], current_data_buf_[10], current_data_buf_[9], current_data_buf_[8]);
uint32_t select_index = find_nearest_index(current_sensitivity, SENSITIVITY, 3);
this->sensitivity_select_->publish_state(select_index);
@@ -183,6 +270,7 @@ void MR60FDA2Component::process_frame_(const uint8_t *frame) {
ESP_LOGD(TAG, "Mounting height: %.2f, Height threshold: %.2f, Sensitivity: %" PRIu32, install_height_float,
height_threshold_float, current_sensitivity);
this->current_frame_locate_ = LOCATE_FRAME_HEADER;
break;
}
default:
@@ -15,25 +15,18 @@
#endif
#include "esphome/components/uart/uart.h"
#include "esphome/core/automation.h"
#include "esphome/core/frame_reader.h"
#include "esphome/core/helpers.h"
#include <map>
namespace esphome::seeed_mr60fda2 {
static constexpr uint8_t DATA_BUF_MAX_SIZE = 28;
static constexpr uint8_t LEN_TO_HEAD_CKSUM = 8;
static constexpr uint8_t LEN_TO_DATA_FRAME = 9;
static constexpr uint8_t FRAME_BUF_MAX_SIZE = DATA_BUF_MAX_SIZE + LEN_TO_DATA_FRAME;
static const uint8_t DATA_BUF_MAX_SIZE = 28;
static const uint8_t FRAME_BUF_MAX_SIZE = 37;
static const uint8_t LEN_TO_HEAD_CKSUM = 8;
static const uint8_t LEN_TO_DATA_FRAME = 9;
static constexpr uint8_t FRAME_HEADER_BUFFER = 0x01;
/// 01, id (2), data length (2, BE), type (2), header checksum, data, data checksum; 0 for a bad header
struct TinyFrameLength {
static constexpr size_t KNOWN_AT = LEN_TO_HEAD_CKSUM;
static size_t get(const uint8_t *buf);
};
static const uint8_t FRAME_HEADER_BUFFER = 0x01;
static const uint16_t IS_FALL_TYPE_BUFFER = 0x0E02;
static const uint16_t PEOPLE_EXIST_TYPE_BUFFER = 0x0F09;
static const uint16_t RESULT_INSTALL_HEIGHT = 0x0E04;
@@ -41,6 +34,20 @@ static const uint16_t RESULT_PARAMETERS = 0x0E06;
static const uint16_t RESULT_HEIGHT_THRESHOLD = 0x0E08;
static const uint16_t RESULT_SENSITIVITY = 0x0E0A;
enum FrameLocation {
LOCATE_FRAME_HEADER,
LOCATE_ID_FRAME1,
LOCATE_ID_FRAME2,
LOCATE_LENGTH_FRAME_H,
LOCATE_LENGTH_FRAME_L,
LOCATE_TYPE_FRAME1,
LOCATE_TYPE_FRAME2,
LOCATE_HEAD_CKSUM_FRAME, // Header checksum: [from the first byte to the previous byte of the HEAD_CKSUM bit]
LOCATE_DATA_FRAME,
LOCATE_DATA_CKSUM_FRAME, // Data checksum: [from the first to the previous byte of the DATA_CKSUM bit]
LOCATE_PROCESS_FRAME,
};
class MR60FDA2Component final : public Component,
public uart::UARTDevice { // The class name must be the name defined by text_sensor.py
#ifdef USE_BINARY_SENSOR
@@ -58,12 +65,16 @@ class MR60FDA2Component final : public Component,
#endif
protected:
uint32_t last_rx_{0};
LengthFrameReader<FRAME_BUF_MAX_SIZE, FrameFormat<FrameHeader<FRAME_HEADER_BUFFER>, TinyFrameLength,
FrameMinLength<LEN_TO_DATA_FRAME + 1>>>
reader_;
uint8_t current_frame_locate_;
uint8_t current_frame_buf_[FRAME_BUF_MAX_SIZE];
uint8_t current_data_buf_[DATA_BUF_MAX_SIZE];
uint16_t current_frame_id_;
size_t current_frame_len_;
size_t current_data_frame_len_;
uint16_t current_frame_type_;
void process_frame_(const uint8_t *frame);
void split_frame_(uint8_t buffer);
void process_frame_();
public:
float get_setup_priority() const override { return esphome::setup_priority::LATE; }
@@ -98,7 +98,7 @@ CONFIG_SCHEMA = cv.All(
cv.positive_time_period_milliseconds,
cv.Range(max=cv.TimePeriod(milliseconds=5000)),
),
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=True): cv.boolean,
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=False): cv.boolean,
cv.Optional(CONF_FIXED_DELAY, default="0us"): cv.All(
cv.positive_time_period_microseconds,
cv.Range(max=cv.TimePeriod(microseconds=10000)),
@@ -61,7 +61,7 @@ class SendspinMediaSource final : public SendspinChild,
bool cached_muted_{false};
bool pending_start_{false};
bool static_delay_adjustable_{true};
bool static_delay_adjustable_{false};
};
} // namespace esphome::sendspin_
@@ -15,17 +15,20 @@
#include <algorithm>
#include <cstring>
#include <memory>
#include <numeric>
namespace {
ESPHOME_LOG_TAG(TAG, "shelly_dimmer");
constexpr uint8_t SHELLY_DIMMER_ACK_TIMEOUT = 200; // ms
// After this long without a byte, a partial frame is searched, so a stray header cannot hide the reply
constexpr uint8_t SHELLY_DIMMER_RX_GAP = 20; // ms
constexpr uint8_t SHELLY_DIMMER_MAX_RETRIES = 3;
constexpr uint16_t SHELLY_DIMMER_MAX_BRIGHTNESS = 1000; // 100%
// Protocol framing.
constexpr uint8_t SHELLY_DIMMER_PROTO_START_BYTE = 0x01;
constexpr uint8_t SHELLY_DIMMER_PROTO_END_BYTE = 0x04;
// Supported commands.
constexpr uint8_t SHELLY_DIMMER_PROTO_CMD_SWITCH = 0x01;
constexpr uint8_t SHELLY_DIMMER_PROTO_CMD_POLL = 0x10;
@@ -55,6 +58,11 @@ template<typename T, size_t N> constexpr size_t size(const T (& /*unused*/)[N])
namespace esphome::shelly_dimmer {
/// Computes a crappy checksum as defined by the Shelly Dimmer protocol.
uint16_t shelly_dimmer_checksum(const uint8_t *buf, int len) {
return std::accumulate<decltype(buf), uint16_t>(buf, buf + len, 0);
}
bool ShellyDimmer::is_running_configured_version() const {
return this->version_major_ == USE_SHD_FIRMWARE_MAJOR_VERSION &&
this->version_minor_ == USE_SHD_FIRMWARE_MINOR_VERSION;
@@ -265,16 +273,13 @@ bool ShellyDimmer::send_command_(uint8_t cmd, const uint8_t *const payload, uint
// Write the frame and wait for acknowledgement.
int retries = SHELLY_DIMMER_MAX_RETRIES;
while (retries--) {
// Kept bytes of an earlier reply must not merge into this one
this->reader_.drop_kept();
this->write_array(frame, frame_len);
this->flush();
ESP_LOGD(TAG, "Command sent, waiting for reply");
const uint32_t tx_time = millis();
uint32_t last_rx = tx_time;
for (uint32_t now = tx_time; now - tx_time < SHELLY_DIMMER_ACK_TIMEOUT; now = millis()) {
if (this->read_frame_(now, last_rx)) {
while (millis() - tx_time < SHELLY_DIMMER_ACK_TIMEOUT) {
if (this->read_frame_()) {
return true;
}
delay(1);
@@ -298,31 +303,83 @@ size_t ShellyDimmer::frame_command_(uint8_t *data, uint8_t cmd, const uint8_t *c
}
// Checksum over the sequence, command, length and payload bytes
p = put_be16(p, sum16_bytes(data + 1, 3 + len));
p = put_be16(p, shelly_dimmer_checksum(data + 1, 3 + len));
*p++ = SHELLY_DIMMER_PROTO_END_BYTE;
return p - data;
}
bool ShellyDimmer::read_frame_(uint32_t now, uint32_t &last_rx) {
bool received = false;
auto handler = [this, &received](const uint8_t *frame, size_t len) {
// The checksum covers seq, cmd, length and payload
if (frame[len - 1] != SHELLY_DIMMER_PROTO_END_BYTE ||
encode_uint16(frame[len - 3], frame[len - 2]) != sum16_bytes(frame + 1, len - 4)) {
return false;
int ShellyDimmer::handle_byte_(uint8_t c) {
const uint8_t pos = this->buffer_pos_;
if (pos == 0) {
// Must be start byte.
return c == SHELLY_DIMMER_PROTO_START_BYTE ? 1 : -1;
} else if (pos < 4) {
// Header.
return 1;
}
// Decode payload length from header.
const uint8_t payload_len = this->buffer_[3];
if ((4 + payload_len + 3) > SHELLY_DIMMER_BUFFER_SIZE) {
return -1;
}
if (pos < 4 + payload_len + 1) {
// Payload.
return 1;
}
if (pos == 4 + payload_len + 1) {
// Verify checksum.
const uint16_t csum = encode_uint16(this->buffer_[pos - 1], c);
const uint16_t csum_verify = shelly_dimmer_checksum(&this->buffer_[1], 3 + payload_len);
if (csum != csum_verify) {
return -1;
}
this->handle_frame_(frame);
received = true;
return true;
};
this->read_frames(this->reader_, handler, now, last_rx, SHELLY_DIMMER_RX_GAP);
return received;
return 1;
}
if (pos == 4 + payload_len + 2) {
// Must be end byte.
return c == SHELLY_DIMMER_PROTO_END_BYTE ? 0 : -1;
}
return -1;
}
bool ShellyDimmer::handle_frame_(const uint8_t *frame) {
const uint8_t seq = frame[1];
const uint8_t cmd = frame[2];
const uint8_t payload_len = frame[3];
bool ShellyDimmer::read_frame_() {
while (this->available()) {
const uint8_t c = this->read();
this->buffer_[this->buffer_pos_] = c;
ESP_LOGV(TAG, "Read byte: 0x%02x (pos %d)", c, this->buffer_pos_);
switch (this->handle_byte_(c)) {
case 0: {
// Frame successfully received.
this->handle_frame_();
this->buffer_pos_ = 0;
return true;
}
case -1: {
// Failure.
this->buffer_pos_ = 0;
break;
}
case 1: {
// Need more data.
this->buffer_pos_++;
break;
}
}
}
return false;
}
bool ShellyDimmer::handle_frame_() {
const uint8_t seq = this->buffer_[1];
const uint8_t cmd = this->buffer_[2];
const uint8_t payload_len = this->buffer_[3];
ESP_LOGD(TAG, "Got frame: 0x%02x", cmd);
@@ -332,7 +389,7 @@ bool ShellyDimmer::handle_frame_(const uint8_t *frame) {
return false;
}
const uint8_t *payload = frame + PayloadLength::KNOWN_AT;
const uint8_t *payload = &this->buffer_[4];
// Handle response.
switch (cmd) {
@@ -8,7 +8,7 @@
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/uart/uart.h"
#include "esphome/core/frame_reader.h"
#include <array>
namespace esphome::shelly_dimmer {
@@ -18,10 +18,7 @@ class ShellyDimmer final : public PollingComponent, public light::LightOutput, p
SUB_SENSOR(current)
private:
// Holds the largest reply, a 24 byte poll
static constexpr uint16_t SHELLY_DIMMER_BUFFER_SIZE = 32;
static constexpr uint8_t SHELLY_DIMMER_PROTO_START_BYTE = 0x01;
static constexpr uint8_t SHELLY_DIMMER_PROTO_END_BYTE = 0x04;
static constexpr uint16_t SHELLY_DIMMER_BUFFER_SIZE = 256;
public:
float get_setup_priority() const override { return setup_priority::LATE; }
@@ -55,11 +52,10 @@ class ShellyDimmer final : public PollingComponent, public light::LightOutput, p
GPIOPin *pin_nrst_;
GPIOPin *pin_boot0_;
// Frame parser state.
uint8_t seq_{0};
// Start byte, seq, cmd, payload length, payload, checksum (2), end byte
using PayloadLength = PayloadLengthU8<LengthField{.offset = 3, .trailer = 3}>;
LengthFrameReader<SHELLY_DIMMER_BUFFER_SIZE, FrameFormat<FrameHeader<SHELLY_DIMMER_PROTO_START_BYTE>, PayloadLength>>
reader_;
std::array<uint8_t, SHELLY_DIMMER_BUFFER_SIZE> buffer_;
uint8_t buffer_pos_{0};
// Firmware version.
uint8_t version_major_;
@@ -96,11 +92,16 @@ class ShellyDimmer final : public PollingComponent, public light::LightOutput, p
/// Frames a given command payload.
size_t frame_command_(uint8_t *data, uint8_t cmd, const uint8_t *payload, size_t len);
/// Handles a single byte as part of a protocol frame.
///
/// Returns -1 on failure, 0 when finished and 1 when more bytes needed.
int handle_byte_(uint8_t c);
/// Reads a response frame.
bool read_frame_(uint32_t now, uint32_t &last_rx);
bool read_frame_();
/// Handles a complete frame.
bool handle_frame_(const uint8_t *frame);
bool handle_frame_();
/// Reset STM32 with the BOOT0 pin set to the given value.
void reset_(bool boot0);
+30 -68
View File
@@ -4,22 +4,13 @@ import esphome.codegen as cg
from esphome.components import time, uart
import esphome.config_validation as cv
from esphome.const import CONF_SENSOR_DATAPOINT, CONF_TIME_ID
from esphome.core import CORE, AutoLoad, CoroPriority, coroutine_with_priority
from esphome.core import CORE, CoroPriority, coroutine_with_priority
from esphome.cpp_generator import MockObj
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
from esphome.types import ConfigType
CODEOWNERS = ["@dwmw2", "@ssieb"]
DEPENDENCIES = ["uart"]
DOMAIN = "tuya"
# AutoLoad: another transport pulled in only the base class. None: CI dependency probe.
def AUTO_LOAD(config: ConfigType | AutoLoad | None) -> list[str]:
if isinstance(config, AutoLoad):
return []
return ["uart"]
CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS = "ignore_mcu_update_on_datapoints"
CONF_ON_DATAPOINT_UPDATE = "on_datapoint_update"
@@ -29,8 +20,7 @@ CONF_FORCE_TIME_SYNC = "force_time_sync"
tuya_ns = cg.esphome_ns.namespace("tuya")
TuyaDatapointType = tuya_ns.enum("TuyaDatapointType", is_class=True)
Tuya = tuya_ns.class_("Tuya", cg.Component)
TuyaUART = tuya_ns.class_("TuyaUART", Tuya, uart.UARTDevice)
Tuya = tuya_ns.class_("Tuya", cg.Component, uart.UARTDevice)
TuyaDatapoint = tuya_ns.struct("TuyaDatapoint")
@@ -82,50 +72,42 @@ def _validate_time_options(config: ConfigType) -> ConfigType:
return config
TUYA_SCHEMA = cv.Schema(
{
cv.Optional(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS): cv.ensure_list(cv.uint8_t),
cv.Optional(CONF_ON_DATAPOINT_UPDATE): automation.validate_automation(
{
cv.Required(CONF_SENSOR_DATAPOINT): cv.uint8_t,
cv.Optional(CONF_DATAPOINT_TYPE, default=DPTYPE_ANY): cv.one_of(
*DATAPOINT_TYPES, lower=True
),
}
),
}
).extend(cv.COMPONENT_SCHEMA)
UART_SCHEMA = cv.All(
TUYA_SCHEMA.extend(
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(TuyaUART),
cv.GenerateID(): cv.declare_id(Tuya),
cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock),
cv.Optional(CONF_FORCE_TIME_SYNC, default=False): cv.boolean,
cv.Optional(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS): cv.ensure_list(
cv.uint8_t
),
cv.Optional(CONF_STATUS_PIN): pins.gpio_output_pin_schema,
cv.Optional(CONF_ON_DATAPOINT_UPDATE): automation.validate_automation(
{
cv.Required(CONF_SENSOR_DATAPOINT): cv.uint8_t,
cv.Optional(CONF_DATAPOINT_TYPE, default=DPTYPE_ANY): cv.one_of(
*DATAPOINT_TYPES, lower=True
),
}
),
}
).extend(uart.UART_DEVICE_SCHEMA),
)
.extend(cv.COMPONENT_SCHEMA)
.extend(uart.UART_DEVICE_SCHEMA),
_validate_time_options,
)
@schema_extractor("schema")
def _validate_config(value: ConfigType | AutoLoad) -> ConfigType | AutoLoad | cv.Schema:
if value is SCHEMA_EXTRACT:
# Expose the UART schema to the language-schema dumper
return UART_SCHEMA
if isinstance(value, AutoLoad):
return value
return UART_SCHEMA(value)
CONFIG_SCHEMA = _validate_config
async def setup_tuya(var: MockObj, config: ConfigType) -> None:
"""Apply the base-class options; called from a transport's to_code()."""
for dp in config.get(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS, []):
cg.add(var.add_ignore_mcu_update_on_datapoints(dp))
async def to_code(config):
var = await uart.new_uart_component(config)
if (time_id := config.get(CONF_TIME_ID)) is not None:
await cg.add_variable(var.set_time_id, time_id)
if config[CONF_FORCE_TIME_SYNC]:
cg.add(var.set_force_time_sync(True))
await cg.add_pin(var.set_status_pin, config.get(CONF_STATUS_PIN))
if CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS in config:
for dp in config[CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS]:
cg.add(var.add_ignore_mcu_update_on_datapoints(dp))
for conf in config.get(CONF_ON_DATAPOINT_UPDATE, []):
type_, expected, field = DATAPOINT_TYPES[conf[CONF_DATAPOINT_TYPE]]
forward = None
@@ -135,23 +117,3 @@ async def setup_tuya(var: MockObj, config: ConfigType) -> None:
[(type_, "x")], conf, params=[(TuyaDatapoint, "x")], forward=forward
)
cg.add(var.register_listener(conf[CONF_SENSOR_DATAPOINT], callback))
async def to_code(config: ConfigType | AutoLoad) -> None:
if isinstance(config, AutoLoad):
return
var = await uart.new_uart_component(config)
if (time_id := config.get(CONF_TIME_ID)) is not None:
await cg.add_variable(var.set_time_id, time_id)
if config[CONF_FORCE_TIME_SYNC]:
cg.add(var.set_force_time_sync(True))
await cg.add_pin(var.set_status_pin, config.get(CONF_STATUS_PIN))
await setup_tuya(var, config)
def FILTER_SOURCE_FILES() -> list[str]:
# When only auto-loaded as a base class, the UART implementation is unused
if isinstance(CORE.config.get(DOMAIN), AutoLoad):
return ["tuya_uart.cpp", "tuya_uart.h"]
return []
+684 -38
View File
@@ -1,13 +1,85 @@
#include "tuya.h"
#include <cstring>
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#ifdef USE_NETWORK
#include "esphome/components/network/util.h"
#endif
#ifdef USE_WIFI
#include "esphome/components/wifi/wifi_component.h"
#endif
#ifdef USE_CAPTIVE_PORTAL
#include "esphome/components/captive_portal/captive_portal.h"
#endif
namespace esphome::tuya {
ESPHOME_LOG_TAG(TAG, "tuya");
void Tuya::dump_datapoints_() {
static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
static const int COMMAND_DELAY = 10;
static const int RECEIVE_TIMEOUT = 300;
static const int MAX_RETRIES = 5;
// Max bytes to log for datapoint values (larger values are truncated)
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
static bool network_is_connected() {
#ifdef USE_NETWORK
return network::is_connected();
#else
return false;
#endif
}
void Tuya::setup() {
this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
#ifdef USE_TIME
if (this->force_time_sync_) {
this->register_local_time_sync_callback_();
this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
[this] { this->check_force_time_sync_(); });
}
#endif
if (this->status_pin_ != nullptr) {
this->status_pin_->digital_write(false);
}
}
void Tuya::loop() {
this->read_available([this](uint8_t b) { this->handle_char_(b); });
process_command_queue_();
}
void Tuya::dump_config() {
this->dump_mcu_config_();
#ifdef USE_TUYA_DUMP_PUBLISHER
if (this->dump_publisher_ != nullptr)
this->dump_publisher_();
#endif
}
// Also logged again once the MCU reports its datapoints
void Tuya::dump_mcu_config_() {
ESP_LOGCONFIG(TAG, "Tuya:");
if (this->init_state_ != TuyaInitState::INIT_DONE) {
if (this->init_failed_) {
ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
} else {
ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
static_cast<uint8_t>(this->init_state_));
}
ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
return;
}
for (auto &info : this->datapoints_) {
if (info.type == TuyaDatapointType::RAW) {
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
@@ -27,36 +99,595 @@ void Tuya::dump_datapoints_() {
ESP_LOGCONFIG(TAG, " Datapoint %u: unknown", info.id);
}
}
if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
this->reset_pin_reported_);
}
LOG_PIN(" Status Pin: ", this->status_pin_);
ESP_LOGCONFIG(TAG, " Product: '%s'",
this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
: (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
}
#endif
}
void Tuya::handle_datapoint_(const TuyaDatapoint &datapoint) {
// drop update if datapoint is in ignore_mcu_datapoint_update list
for (auto i : this->ignore_mcu_update_on_datapoints_) {
if (datapoint.id == i) {
ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
bool Tuya::validate_message_() {
uint32_t at = this->rx_message_.size() - 1;
auto *data = &this->rx_message_[0];
uint8_t new_byte = data[at];
// Byte 0: HEADER1 (always 0x55)
if (at == 0)
return new_byte == 0x55;
// Byte 1: HEADER2 (always 0xAA)
if (at == 1)
return new_byte == 0xAA;
// Byte 2: VERSION
// no validation for the following fields:
uint8_t version = data[2];
if (at == 2)
return true;
// Byte 3: COMMAND
uint8_t command = data[3];
if (at == 3)
return true;
// Byte 4: LENGTH1
// Byte 5: LENGTH2
if (at <= 5) {
// no validation for these fields
return true;
}
uint16_t length = encode_uint16(data[4], data[5]);
// wait until all data is read
if (at - 6 < length)
return true;
// Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
uint8_t rx_checksum = new_byte;
const uint8_t calc_checksum = sum_bytes(data, 6 + length);
if (rx_checksum != calc_checksum) {
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
return false;
}
// valid message
const uint8_t *message_data = data + 6;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
#endif
this->handle_command_(command, version, message_data, length);
// return false to reset rx buffer
return false;
}
void Tuya::handle_char_(uint8_t c) {
this->rx_message_.push_back(c);
if (!this->validate_message_()) {
this->rx_message_.clear();
} else {
this->last_rx_char_timestamp_ = millis();
}
}
void Tuya::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
TuyaCommandType command_type = (TuyaCommandType) command;
if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
this->expected_response_.reset();
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
switch (command_type) {
case TuyaCommandType::HEARTBEAT:
ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
this->protocol_version_ = version;
if (buffer[0] == 0) {
ESP_LOGI(TAG, "MCU restarted");
this->init_state_ = TuyaInitState::INIT_HEARTBEAT;
}
if (this->init_state_ == TuyaInitState::INIT_HEARTBEAT) {
this->init_state_ = TuyaInitState::INIT_PRODUCT;
this->send_empty_command_(TuyaCommandType::PRODUCT_QUERY);
}
break;
case TuyaCommandType::PRODUCT_QUERY: {
// check it is a valid string made up of printable characters
bool valid = true;
for (size_t i = 0; i < len; i++) {
if (!std::isprint(buffer[i])) {
valid = false;
break;
}
}
if (valid) {
this->product_ = std::make_unique<char[]>(len + 1);
memcpy(this->product_.get(), buffer, len);
} else {
this->product_.reset();
}
this->product_invalid_ = !valid;
if (this->init_state_ == TuyaInitState::INIT_PRODUCT) {
this->init_state_ = TuyaInitState::INIT_CONF;
this->send_empty_command_(TuyaCommandType::CONF_QUERY);
}
break;
}
case TuyaCommandType::CONF_QUERY: {
if (len >= 2) {
this->status_pin_reported_ = buffer[0];
this->reset_pin_reported_ = buffer[1];
}
if (this->init_state_ == TuyaInitState::INIT_CONF) {
// If mcu returned status gpio, then we can omit sending wifi state
if (this->status_pin_reported_ != -1) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
if (this->status_pin_ != nullptr) {
if (this->status_pin_->get_pin() != this->status_pin_reported_) {
ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
this->status_pin_reported_);
}
ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
} else {
ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
this->status_pin_reported_);
}
} else {
this->init_state_ = TuyaInitState::INIT_WIFI;
ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
}
}
break;
}
case TuyaCommandType::WIFI_STATE:
if (this->init_state_ == TuyaInitState::INIT_WIFI) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
}
break;
case TuyaCommandType::WIFI_SELECT:
case TuyaCommandType::WIFI_RESET: {
const bool is_select = (len >= 1);
// Send WIFI_SELECT ACK
TuyaCommand ack;
ack.cmd = is_select ? TuyaCommandType::WIFI_SELECT : TuyaCommandType::WIFI_RESET;
ack.payload.clear();
this->send_command_(ack);
// Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
uint8_t first = 0x00;
const char *mode_str = "EZ";
if (is_select && buffer[0] == 0x01) {
first = 0x01;
mode_str = "AP";
}
// Send WIFI_STATE response, MCU exits pairing mode
TuyaCommand st;
st.cmd = TuyaCommandType::WIFI_STATE;
st.payload.resize(1);
st.payload[0] = first;
this->send_command_(st);
st.payload[0] = 0x02;
this->send_command_(st);
st.payload[0] = 0x03;
this->send_command_(st);
st.payload[0] = 0x04;
this->send_command_(st);
ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
break;
}
case TuyaCommandType::DATAPOINT_DELIVER:
break;
case TuyaCommandType::DATAPOINT_REPORT_ASYNC:
case TuyaCommandType::DATAPOINT_REPORT_SYNC:
if (this->init_state_ == TuyaInitState::INIT_DATAPOINT) {
this->init_state_ = TuyaInitState::INIT_DONE;
this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_mcu_config_(); });
this->initialized_callback_.call();
}
this->handle_datapoints_(buffer, len);
if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
}
break;
case TuyaCommandType::DATAPOINT_QUERY:
break;
case TuyaCommandType::WIFI_TEST:
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
break;
case TuyaCommandType::WIFI_RSSI:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
break;
case TuyaCommandType::LOCAL_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_local_time_();
this->register_local_time_sync_callback_();
} else
#endif
{
ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::GMT_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_gmt_time_();
if (!this->gmt_time_sync_callback_registered_) {
// tuya mcu supports time, so we let them know when our time changed
this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
this->gmt_time_sync_callback_registered_ = true;
}
} else
#endif
{
ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::VACUUM_MAP_UPLOAD:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
break;
case TuyaCommandType::GET_NETWORK_STATUS: {
uint8_t wifi_status = this->get_wifi_status_code_();
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
break;
}
case TuyaCommandType::EXTENDED_SERVICES: {
uint8_t subcommand = buffer[0];
switch ((TuyaExtendedServicesCommandType) subcommand) {
case TuyaExtendedServicesCommandType::RESET_NOTIFICATION: {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::EXTENDED_SERVICES,
.payload = std::vector<uint8_t>{
static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
ESP_LOGV(TAG, "Reset status notification enabled");
break;
}
case TuyaExtendedServicesCommandType::MODULE_RESET: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
break;
}
case TuyaExtendedServicesCommandType::UPDATE_IN_PROGRESS: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
break;
}
default:
ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
}
break;
}
default:
ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
}
}
void Tuya::handle_datapoints_(const uint8_t *buffer, size_t len) {
while (len >= 4) {
TuyaDatapoint datapoint{};
datapoint.id = buffer[0];
datapoint.type = (TuyaDatapointType) buffer[1];
datapoint.value_uint = 0;
size_t data_size = encode_uint16(buffer[2], buffer[3]);
const uint8_t *data = buffer + 4;
size_t data_len = len - 4;
if (data_size > data_len) {
ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
return;
}
}
// Update internal datapoints
bool found = false;
for (auto &other : this->datapoints_) {
if (other.id == datapoint.id) {
other = datapoint;
found = true;
datapoint.len = data_size;
switch (datapoint.type) {
case TuyaDatapointType::RAW:
datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
{
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
}
break;
case TuyaDatapointType::BOOLEAN:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
return;
}
datapoint.value_bool = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
break;
case TuyaDatapointType::INTEGER:
if (data_size != 4) {
ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
return;
}
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
break;
case TuyaDatapointType::STRING:
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
break;
case TuyaDatapointType::ENUM:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
return;
}
datapoint.value_enum = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
break;
case TuyaDatapointType::BITMASK:
switch (data_size) {
case 1:
datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
break;
case 2:
datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
break;
case 4:
datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
return;
}
ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
return;
}
len -= data_size + 4;
buffer = data + data_size;
// drop update if datapoint is in ignore_mcu_datapoint_update list
bool skip = false;
for (auto i : this->ignore_mcu_update_on_datapoints_) {
if (datapoint.id == i) {
ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
skip = true;
break;
}
}
if (skip)
continue;
// Update internal datapoints
bool found = false;
for (auto &other : this->datapoints_) {
if (other.id == datapoint.id) {
other = datapoint;
found = true;
}
}
if (!found) {
this->datapoints_.push_back(datapoint);
}
// Run through listeners
for (auto &listener : this->listeners_) {
if (listener.datapoint_id == datapoint.id)
listener.on_datapoint.call(datapoint);
}
}
if (!found) {
this->datapoints_.push_back(datapoint);
}
void Tuya::send_raw_command_(TuyaCommand command) {
uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
uint8_t version = 0;
this->last_command_timestamp_ = millis();
switch (command.cmd) {
case TuyaCommandType::HEARTBEAT:
this->expected_response_ = TuyaCommandType::HEARTBEAT;
break;
case TuyaCommandType::PRODUCT_QUERY:
this->expected_response_ = TuyaCommandType::PRODUCT_QUERY;
break;
case TuyaCommandType::CONF_QUERY:
this->expected_response_ = TuyaCommandType::CONF_QUERY;
break;
case TuyaCommandType::DATAPOINT_DELIVER:
case TuyaCommandType::DATAPOINT_QUERY:
this->expected_response_ = TuyaCommandType::DATAPOINT_REPORT_ASYNC;
break;
default:
break;
}
// Run through listeners
for (auto &listener : this->listeners_) {
if (listener.datapoint_id == datapoint.id)
listener.on_datapoint.call(datapoint);
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
static_cast<uint8_t>(this->init_state_));
#endif
this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
if (!command.payload.empty())
this->write_array(command.payload.data(), command.payload.size());
const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
}
void Tuya::process_command_queue_() {
uint32_t now = millis();
uint32_t delay = now - this->last_command_timestamp_;
if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
this->rx_message_.clear();
}
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
this->expected_response_.reset();
if (init_state_ != TuyaInitState::INIT_DONE) {
if (++this->init_retries_ >= MAX_RETRIES) {
this->init_failed_ = true;
ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
} else {
this->command_queue_.erase(command_queue_.begin());
}
}
// Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
!this->expected_response_.has_value()) {
this->send_raw_command_(command_queue_.front());
if (!this->expected_response_.has_value())
this->command_queue_.erase(command_queue_.begin());
}
}
void Tuya::send_command_(const TuyaCommand &command) {
command_queue_.push_back(command);
process_command_queue_();
}
void Tuya::send_empty_command_(TuyaCommandType command) {
send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
}
void Tuya::set_status_pin_() {
bool is_network_ready = network_is_connected() && remote_is_connected();
this->status_pin_->digital_write(is_network_ready);
}
uint8_t Tuya::get_wifi_status_code_() {
uint8_t status = 0x02;
if (network_is_connected()) {
status = 0x03;
// Protocol version 3 also supports specifying when connected to "the cloud"
if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
status = 0x04;
}
} else {
#ifdef USE_CAPTIVE_PORTAL
if (captive_portal::global_captive_portal != nullptr && captive_portal::global_captive_portal->is_active()) {
status = 0x01;
}
#endif
};
return status;
}
uint8_t Tuya::get_wifi_rssi_() {
#ifdef USE_WIFI
if (wifi::global_wifi_component != nullptr)
return wifi::global_wifi_component->wifi_rssi();
#endif
return 0;
}
void Tuya::send_wifi_status_() {
uint8_t status = this->get_wifi_status_code_();
if (status == this->wifi_status_) {
return;
}
ESP_LOGD(TAG, "Sending WiFi Status");
this->wifi_status_ = status;
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
}
#ifdef USE_TIME
void Tuya::register_local_time_sync_callback_() {
if (this->time_sync_callback_registered_) {
return;
}
this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
this->time_sync_callback_registered_ = true;
}
void Tuya::check_force_time_sync_() {
ESPTime now = this->time_id_->now();
if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
return;
this->last_force_time_sync_minute_ = now.minute;
this->send_local_time_(true);
}
void Tuya::send_local_time_(bool periodic) {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->now();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
// Tuya days starts from Monday, esphome uses Sunday as day 1
uint8_t day_of_week = now.day_of_week - 1;
if (day_of_week == 0) {
day_of_week = 7;
}
// The forced send repeats every minute, so it stays out of the debug log
if (periodic) {
ESP_LOGV(TAG, "Sending local time");
} else {
ESP_LOGD(TAG, "Sending local time");
}
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing local time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
}
void Tuya::send_gmt_time_() {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->utcnow();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
ESP_LOGD(TAG, "Sending gmt time");
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing gmt time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
}
#endif
void Tuya::set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
this->set_raw_datapoint_value_(datapoint_id, value, false);
}
@@ -113,19 +744,19 @@ void Tuya::force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t valu
this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BITMASK, value, length, true);
}
const TuyaDatapoint *Tuya::get_datapoint_(uint8_t datapoint_id) const {
for (const auto &datapoint : this->datapoints_) {
optional<TuyaDatapoint> Tuya::get_datapoint_(uint8_t datapoint_id) {
for (auto &datapoint : this->datapoints_) {
if (datapoint.id == datapoint_id)
return &datapoint;
return datapoint;
}
return nullptr;
return {};
}
void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint32_t value,
uint8_t length, bool forced) {
ESP_LOGD(TAG, "Setting datapoint %u to %" PRIu32, datapoint_id, value);
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != datapoint_type) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -135,29 +766,30 @@ void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType
return;
}
uint8_t data[4];
std::vector<uint8_t> data;
switch (length) {
case 4:
put_be32(data, value);
break;
data.push_back(value >> 24);
data.push_back(value >> 16);
[[fallthrough]];
case 2:
put_be16(data, value);
break;
data.push_back(value >> 8);
[[fallthrough]];
case 1:
data[0] = value;
data.push_back(value >> 0);
break;
default:
ESP_LOGE(TAG, "Unexpected datapoint length %u", length);
return;
}
this->send_datapoint_command(datapoint_id, datapoint_type, data, length);
this->send_datapoint_command_(datapoint_id, datapoint_type, data);
}
void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced) {
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, format_hex_pretty_to(hex_buf, value.data(), value.size()));
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != TuyaDatapointType::RAW) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -166,13 +798,13 @@ void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint
ESP_LOGV(TAG, "Not sending unchanged value");
return;
}
this->send_datapoint_command(datapoint_id, TuyaDatapointType::RAW, value.data(), value.size());
this->send_datapoint_command_(datapoint_id, TuyaDatapointType::RAW, value);
}
void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const char *value, size_t len, bool forced) {
ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, value);
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != TuyaDatapointType::STRING) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -182,7 +814,19 @@ void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const char *value,
ESP_LOGV(TAG, "Not sending unchanged value");
return;
}
this->send_datapoint_command(datapoint_id, TuyaDatapointType::STRING, reinterpret_cast<const uint8_t *>(value), len);
std::vector<uint8_t> data(value, value + len);
this->send_datapoint_command_(datapoint_id, TuyaDatapointType::STRING, data);
}
void Tuya::send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data) {
std::vector<uint8_t> buffer;
buffer.push_back(datapoint_id);
buffer.push_back(static_cast<uint8_t>(datapoint_type));
buffer.push_back(data.size() >> 8);
buffer.push_back(data.size() >> 0);
buffer.insert(buffer.end(), data.begin(), data.end());
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = buffer});
}
void Tuya::register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func) {
@@ -206,4 +850,6 @@ const TuyaDatapoint &TuyaDatapoint::expect_type(TuyaDatapointType expected) cons
return *this;
}
TuyaInitState Tuya::get_init_state() { return this->init_state_; }
} // namespace esphome::tuya
+100 -24
View File
@@ -1,17 +1,21 @@
#pragma once
#include <cinttypes>
#include <memory>
#include <vector>
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#include "esphome/components/uart/uart.h"
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
#include "esphome/core/time.h"
#endif
namespace esphome::tuya {
// Max bytes to log for datapoint values (larger values are truncated)
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
enum class TuyaDatapointType : uint8_t {
RAW = 0x00, // variable length
BOOLEAN = 0x01, // 1 byte (0/1)
@@ -44,18 +48,53 @@ struct TuyaDatapointListener {
Callback<void(const TuyaDatapoint &)> on_datapoint;
};
/// Transport-agnostic Tuya controller. Subclasses implement send_datapoint_command(), feed received datapoints
/// to handle_datapoint_(), and call mark_initialized_() once the MCU has reported.
class Tuya : public Component {
enum class TuyaCommandType : uint8_t {
HEARTBEAT = 0x00,
PRODUCT_QUERY = 0x01,
CONF_QUERY = 0x02,
WIFI_STATE = 0x03,
WIFI_RESET = 0x04,
WIFI_SELECT = 0x05,
DATAPOINT_DELIVER = 0x06,
DATAPOINT_REPORT_ASYNC = 0x07,
DATAPOINT_QUERY = 0x08,
GMT_TIME_QUERY = 0x0C,
WIFI_TEST = 0x0E,
LOCAL_TIME_QUERY = 0x1C,
DATAPOINT_REPORT_SYNC = 0x22,
DATAPOINT_REPORT_ACK = 0x23,
WIFI_RSSI = 0x24,
VACUUM_MAP_UPLOAD = 0x28,
GET_NETWORK_STATUS = 0x2B,
EXTENDED_SERVICES = 0x34,
};
enum class TuyaExtendedServicesCommandType : uint8_t {
RESET_NOTIFICATION = 0x04,
MODULE_RESET = 0x05,
UPDATE_IN_PROGRESS = 0x0A,
};
enum class TuyaInitState : uint8_t {
INIT_HEARTBEAT = 0x00,
INIT_PRODUCT,
INIT_CONF,
INIT_WIFI,
INIT_DATAPOINT,
INIT_DONE,
};
struct TuyaCommand {
TuyaCommandType cmd;
std::vector<uint8_t> payload;
};
class Tuya final : public Component, public uart::UARTDevice {
public:
float get_setup_priority() const override { return setup_priority::LATE; }
/// Prints each child entity's dump; a transport that overrides it prints its own block first, then calls this
void dump_config() override {
#ifdef USE_TUYA_DUMP_PUBLISHER
if (this->dump_publisher_ != nullptr)
this->dump_publisher_();
#endif
}
void setup() override;
void loop() override;
void dump_config() override;
#ifdef USE_TUYA_DUMP_PUBLISHER
HUB_PUBLISHER(dump)
#endif
@@ -65,6 +104,7 @@ class Tuya : public Component {
void set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value);
void set_boolean_datapoint_value(uint8_t datapoint_id, bool value);
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value);
void set_status_pin(InternalGPIOPin *status_pin) { this->status_pin_ = status_pin; }
void set_string_datapoint_value(uint8_t datapoint_id, const std::string &value);
void set_string_datapoint_value(uint8_t datapoint_id, const char *value);
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value);
@@ -76,6 +116,11 @@ class Tuya : public Component {
void force_set_string_datapoint_value(uint8_t datapoint_id, const char *value);
void force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value);
void force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length);
TuyaInitState get_init_state();
#ifdef USE_TIME
void set_time_id(time::RealTimeClock *time_id) { this->time_id_ = time_id; }
void set_force_time_sync(bool force_time_sync) { this->force_time_sync_ = force_time_sync; }
#endif
void add_ignore_mcu_update_on_datapoints(uint8_t ignore_mcu_update_on_datapoints) {
this->ignore_mcu_update_on_datapoints_.push_back(ignore_mcu_update_on_datapoints);
}
@@ -85,25 +130,56 @@ class Tuya : public Component {
protected:
void register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func);
/// Store a datapoint received from the MCU and notify listeners.
void handle_datapoint_(const TuyaDatapoint &datapoint);
void mark_initialized_() { this->initialized_callback_.call(); }
const TuyaDatapoint *get_datapoint_(uint8_t datapoint_id) const;
void dump_datapoints_();
void dump_mcu_config_();
void handle_char_(uint8_t c);
void handle_datapoints_(const uint8_t *buffer, size_t len);
optional<TuyaDatapoint> get_datapoint_(uint8_t datapoint_id);
bool validate_message_();
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len);
void send_raw_command_(TuyaCommand command);
void process_command_queue_();
void send_command_(const TuyaCommand &command);
void send_empty_command_(TuyaCommandType command);
void set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, uint32_t value,
uint8_t length, bool forced);
void set_string_datapoint_value_(uint8_t datapoint_id, const char *value, size_t len, bool forced);
void set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced);
/// Deliver a datapoint value to the MCU over the subclass's transport.
/// The payload is borrowed for the duration of the call only.
virtual void send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) = 0;
void send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data);
void set_status_pin_();
void send_wifi_status_();
uint8_t get_wifi_status_code_();
uint8_t get_wifi_rssi_();
#ifdef USE_TIME
void register_local_time_sync_callback_();
void check_force_time_sync_();
void send_local_time_(bool periodic = false);
void send_gmt_time_();
time::RealTimeClock *time_id_{nullptr};
bool force_time_sync_{false};
uint8_t last_force_time_sync_minute_{0xFF}; // 0xFF: no minute seen yet
bool time_sync_callback_registered_{false};
bool gmt_time_sync_callback_registered_{false};
#endif
TuyaInitState init_state_ = TuyaInitState::INIT_HEARTBEAT;
bool init_failed_{false};
int init_retries_{0};
uint8_t protocol_version_ = -1;
InternalGPIOPin *status_pin_{nullptr};
int status_pin_reported_ = -1;
int reset_pin_reported_ = -1;
uint32_t last_command_timestamp_ = 0;
uint32_t last_rx_char_timestamp_ = 0;
std::unique_ptr<char[]> product_;
std::vector<TuyaDatapointListener> listeners_;
std::vector<TuyaDatapoint> datapoints_;
std::vector<uint8_t> rx_message_;
std::vector<uint8_t> ignore_mcu_update_on_datapoints_{};
private:
std::vector<TuyaCommand> command_queue_;
optional<TuyaCommandType> expected_response_{};
uint8_t wifi_status_ = -1;
bool product_invalid_{false};
CallbackManager<void()> initialized_callback_{};
};
-622
View File
@@ -1,622 +0,0 @@
#include "tuya_uart.h"
#include "esphome/core/application.h"
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#include <cctype>
#include <cstring>
#ifdef USE_NETWORK
#include "esphome/components/network/util.h"
#endif
#ifdef USE_WIFI
#include "esphome/components/wifi/wifi_component.h"
#endif
#ifdef USE_CAPTIVE_PORTAL
#include "esphome/components/captive_portal/captive_portal.h"
#endif
namespace esphome::tuya {
ESPHOME_LOG_TAG(TAG, "tuya");
static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
static const int COMMAND_DELAY = 10;
static constexpr uint32_t RECEIVE_TIMEOUT = 300;
static const int MAX_RETRIES = 5;
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
static bool network_is_connected() {
#ifdef USE_NETWORK
return network::is_connected();
#else
return false;
#endif
}
void TuyaUART::setup() {
this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
#ifdef USE_TIME
if (this->force_time_sync_) {
this->register_local_time_sync_callback_();
this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
[this] { this->check_force_time_sync_(); });
}
#endif
if (this->status_pin_ != nullptr) {
this->status_pin_->digital_write(false);
}
}
void TuyaUART::loop() {
auto handler = [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); };
// Holds commands back for the whole read, the idle search and its log lines included
this->handling_frame_ = true;
this->read_frames(this->reader_, handler, App.get_loop_component_start_time(), this->last_rx_char_timestamp_,
RECEIVE_TIMEOUT);
this->handling_frame_ = false;
process_command_queue_();
}
void TuyaUART::dump_config() {
this->dump_mcu_config_();
Tuya::dump_config();
}
// Also logged again once the MCU reports its datapoints
void TuyaUART::dump_mcu_config_() {
ESP_LOGCONFIG(TAG, "Tuya:");
if (this->init_state_ != TuyaInitState::INIT_DONE) {
if (this->init_failed_) {
ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
} else {
ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
static_cast<uint8_t>(this->init_state_));
}
ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
return;
}
this->dump_datapoints_();
if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
this->reset_pin_reported_);
}
LOG_PIN(" Status Pin: ", this->status_pin_);
ESP_LOGCONFIG(TAG, " Product: '%s'",
this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
: (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
}
#endif
}
void warn_too_long(size_t len) {
ESP_LOGW(TAG, "Skipped a %u byte frame, longer than the %u byte buffer", static_cast<unsigned>(len),
static_cast<unsigned>(MAX_FRAME_SIZE));
}
bool TuyaUART::handle_frame_(const uint8_t *frame, size_t len) {
// Last byte: sum of all bytes before it, header included, modulo 256
const uint8_t rx_checksum = frame[len - 1];
const uint8_t calc_checksum = sum_bytes(frame, len - 1);
if (rx_checksum != calc_checksum) {
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
return false;
}
const uint8_t version = frame[2];
const uint8_t command = frame[3];
const uint8_t *message_data = frame + TuyaLength::KNOWN_AT;
const size_t length = len - TuyaLength::KNOWN_AT - 1;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
#endif
this->handle_command_(command, version, message_data, length);
return true;
}
void TuyaUART::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
TuyaCommandType command_type = (TuyaCommandType) command;
if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
this->expected_response_.reset();
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
switch (command_type) {
case TuyaCommandType::HEARTBEAT:
ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
this->protocol_version_ = version;
if (buffer[0] == 0) {
ESP_LOGI(TAG, "MCU restarted");
this->init_state_ = TuyaInitState::INIT_HEARTBEAT;
}
if (this->init_state_ == TuyaInitState::INIT_HEARTBEAT) {
this->init_state_ = TuyaInitState::INIT_PRODUCT;
this->send_empty_command_(TuyaCommandType::PRODUCT_QUERY);
}
break;
case TuyaCommandType::PRODUCT_QUERY: {
// check it is a valid string made up of printable characters
bool valid = true;
for (size_t i = 0; i < len; i++) {
if (!std::isprint(buffer[i])) {
valid = false;
break;
}
}
if (valid) {
this->product_ = std::make_unique<char[]>(len + 1);
memcpy(this->product_.get(), buffer, len);
} else {
this->product_.reset();
}
this->product_invalid_ = !valid;
if (this->init_state_ == TuyaInitState::INIT_PRODUCT) {
this->init_state_ = TuyaInitState::INIT_CONF;
this->send_empty_command_(TuyaCommandType::CONF_QUERY);
}
break;
}
case TuyaCommandType::CONF_QUERY: {
if (len >= 2) {
this->status_pin_reported_ = buffer[0];
this->reset_pin_reported_ = buffer[1];
}
if (this->init_state_ == TuyaInitState::INIT_CONF) {
// If mcu returned status gpio, then we can omit sending wifi state
if (this->status_pin_reported_ != -1) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
if (this->status_pin_ != nullptr) {
if (this->status_pin_->get_pin() != this->status_pin_reported_) {
ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
this->status_pin_reported_);
}
ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
} else {
ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
this->status_pin_reported_);
}
} else {
this->init_state_ = TuyaInitState::INIT_WIFI;
ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
}
}
break;
}
case TuyaCommandType::WIFI_STATE:
if (this->init_state_ == TuyaInitState::INIT_WIFI) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
}
break;
case TuyaCommandType::WIFI_SELECT:
case TuyaCommandType::WIFI_RESET: {
const bool is_select = (len >= 1);
// Send WIFI_SELECT ACK
TuyaCommand ack;
ack.cmd = is_select ? TuyaCommandType::WIFI_SELECT : TuyaCommandType::WIFI_RESET;
ack.payload.clear();
this->send_command_(ack);
// Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
uint8_t first = 0x00;
const char *mode_str = "EZ";
if (is_select && buffer[0] == 0x01) {
first = 0x01;
mode_str = "AP";
}
// Send WIFI_STATE response, MCU exits pairing mode
TuyaCommand st;
st.cmd = TuyaCommandType::WIFI_STATE;
st.payload.resize(1);
st.payload[0] = first;
this->send_command_(st);
st.payload[0] = 0x02;
this->send_command_(st);
st.payload[0] = 0x03;
this->send_command_(st);
st.payload[0] = 0x04;
this->send_command_(st);
ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
break;
}
case TuyaCommandType::DATAPOINT_DELIVER:
break;
case TuyaCommandType::DATAPOINT_REPORT_ASYNC:
case TuyaCommandType::DATAPOINT_REPORT_SYNC:
if (this->init_state_ == TuyaInitState::INIT_DATAPOINT) {
this->init_state_ = TuyaInitState::INIT_DONE;
this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_mcu_config_(); });
this->mark_initialized_();
}
this->handle_datapoints_(buffer, len);
if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
}
break;
case TuyaCommandType::DATAPOINT_QUERY:
break;
case TuyaCommandType::WIFI_TEST:
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
break;
case TuyaCommandType::WIFI_RSSI:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
break;
case TuyaCommandType::LOCAL_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_local_time_();
this->register_local_time_sync_callback_();
} else
#endif
{
ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::GMT_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_gmt_time_();
if (!this->gmt_time_sync_callback_registered_) {
// tuya mcu supports time, so we let them know when our time changed
this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
this->gmt_time_sync_callback_registered_ = true;
}
} else
#endif
{
ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::VACUUM_MAP_UPLOAD:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
break;
case TuyaCommandType::GET_NETWORK_STATUS: {
uint8_t wifi_status = this->get_wifi_status_code_();
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
break;
}
case TuyaCommandType::EXTENDED_SERVICES: {
uint8_t subcommand = buffer[0];
switch ((TuyaExtendedServicesCommandType) subcommand) {
case TuyaExtendedServicesCommandType::RESET_NOTIFICATION: {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::EXTENDED_SERVICES,
.payload = std::vector<uint8_t>{
static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
ESP_LOGV(TAG, "Reset status notification enabled");
break;
}
case TuyaExtendedServicesCommandType::MODULE_RESET: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
break;
}
case TuyaExtendedServicesCommandType::UPDATE_IN_PROGRESS: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
break;
}
default:
ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
}
break;
}
default:
ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
}
}
void TuyaUART::handle_datapoints_(const uint8_t *buffer, size_t len) {
while (len >= 4) {
TuyaDatapoint datapoint{};
datapoint.id = buffer[0];
datapoint.type = (TuyaDatapointType) buffer[1];
datapoint.value_uint = 0;
size_t data_size = encode_uint16(buffer[2], buffer[3]);
const uint8_t *data = buffer + 4;
size_t data_len = len - 4;
if (data_size > data_len) {
ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
return;
}
datapoint.len = data_size;
switch (datapoint.type) {
case TuyaDatapointType::RAW:
datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
{
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
}
break;
case TuyaDatapointType::BOOLEAN:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
return;
}
datapoint.value_bool = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
break;
case TuyaDatapointType::INTEGER:
if (data_size != 4) {
ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
return;
}
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
break;
case TuyaDatapointType::STRING:
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
break;
case TuyaDatapointType::ENUM:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
return;
}
datapoint.value_enum = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
break;
case TuyaDatapointType::BITMASK:
switch (data_size) {
case 1:
datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
break;
case 2:
datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
break;
case 4:
datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
return;
}
ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
return;
}
len -= data_size + 4;
buffer = data + data_size;
this->handle_datapoint_(datapoint);
}
}
void TuyaUART::send_raw_command_(TuyaCommand command) {
uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
uint8_t version = 0;
this->last_command_timestamp_ = millis();
switch (command.cmd) {
case TuyaCommandType::HEARTBEAT:
this->expected_response_ = TuyaCommandType::HEARTBEAT;
break;
case TuyaCommandType::PRODUCT_QUERY:
this->expected_response_ = TuyaCommandType::PRODUCT_QUERY;
break;
case TuyaCommandType::CONF_QUERY:
this->expected_response_ = TuyaCommandType::CONF_QUERY;
break;
case TuyaCommandType::DATAPOINT_DELIVER:
case TuyaCommandType::DATAPOINT_QUERY:
this->expected_response_ = TuyaCommandType::DATAPOINT_REPORT_ASYNC;
break;
default:
break;
}
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
static_cast<uint8_t>(this->init_state_));
#endif
this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
if (!command.payload.empty())
this->write_array(command.payload.data(), command.payload.size());
const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
}
void TuyaUART::process_command_queue_() {
uint32_t now = millis();
uint32_t delay = now - this->last_command_timestamp_;
// A reply still coming in, or held behind a corrupt length, is waited for
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT && !this->reader_.receiving()) {
this->expected_response_.reset();
if (init_state_ != TuyaInitState::INIT_DONE) {
if (++this->init_retries_ >= MAX_RETRIES) {
this->init_failed_ = true;
ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
} else {
this->command_queue_.erase(command_queue_.begin());
}
}
// Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
// A partial frame kept by an idle flush does not hold commands back; a command clears it, so it cannot merge into
// the reply
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && !this->reader_.receiving() && !this->handling_frame_ &&
!this->expected_response_.has_value()) {
this->reader_.drop_kept();
this->send_raw_command_(command_queue_.front());
if (!this->expected_response_.has_value())
this->command_queue_.erase(command_queue_.begin());
}
}
void TuyaUART::send_command_(TuyaCommand command) {
command_queue_.push_back(std::move(command));
process_command_queue_();
}
void TuyaUART::send_empty_command_(TuyaCommandType command) {
send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
}
void TuyaUART::send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) {
std::vector<uint8_t> buffer;
buffer.reserve(4 + len);
buffer.push_back(datapoint_id);
buffer.push_back(static_cast<uint8_t>(datapoint_type));
buffer.push_back(len >> 8);
buffer.push_back(len >> 0);
buffer.insert(buffer.end(), data, data + len);
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = std::move(buffer)});
}
void TuyaUART::set_status_pin_() {
bool is_network_ready = network_is_connected() && remote_is_connected();
this->status_pin_->digital_write(is_network_ready);
}
uint8_t TuyaUART::get_wifi_status_code_() {
uint8_t status = 0x02;
if (network_is_connected()) {
status = 0x03;
// Protocol version 3 also supports specifying when connected to "the cloud"
if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
status = 0x04;
}
} else {
#ifdef USE_CAPTIVE_PORTAL
if (captive_portal::global_captive_portal != nullptr && captive_portal::global_captive_portal->is_active()) {
status = 0x01;
}
#endif
};
return status;
}
uint8_t TuyaUART::get_wifi_rssi_() {
#ifdef USE_WIFI
if (wifi::global_wifi_component != nullptr)
return wifi::global_wifi_component->wifi_rssi();
#endif
return 0;
}
void TuyaUART::send_wifi_status_() {
uint8_t status = this->get_wifi_status_code_();
if (status == this->wifi_status_) {
return;
}
ESP_LOGD(TAG, "Sending WiFi Status");
this->wifi_status_ = status;
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
}
#ifdef USE_TIME
void TuyaUART::register_local_time_sync_callback_() {
if (this->time_sync_callback_registered_) {
return;
}
this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
this->time_sync_callback_registered_ = true;
}
void TuyaUART::check_force_time_sync_() {
ESPTime now = this->time_id_->now();
if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
return;
this->last_force_time_sync_minute_ = now.minute;
this->send_local_time_(true);
}
void TuyaUART::send_local_time_(bool periodic) {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->now();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
// Tuya days starts from Monday, esphome uses Sunday as day 1
uint8_t day_of_week = now.day_of_week - 1;
if (day_of_week == 0) {
day_of_week = 7;
}
// The forced send repeats every minute, so it stays out of the debug log
if (periodic) {
ESP_LOGV(TAG, "Sending local time");
} else {
ESP_LOGD(TAG, "Sending local time");
}
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing local time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
}
void TuyaUART::send_gmt_time_() {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->utcnow();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
ESP_LOGD(TAG, "Sending gmt time");
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing gmt time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
}
#endif
TuyaInitState TuyaUART::get_init_state() { return this->init_state_; }
} // namespace esphome::tuya
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff. Show more