mirror of
https://github.com/esphome/esphome.git
synced 2026-11-18 19:15:59 +00:00
Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61b99d91bf | ||
|
|
69a7f7a408 | ||
|
|
9fb6cb4867 | ||
|
|
e0a5fad2de | ||
|
|
00125a448d | ||
|
|
d76c655553 | ||
|
|
9bdd466e51 | ||
|
|
3fc8bcbd14 | ||
|
|
03880d5ea6 | ||
|
|
9898eb124a | ||
|
|
4a04c61ab5 | ||
|
|
2cd9ddf246 | ||
|
|
cac0e29421 | ||
|
|
791d6e15ee | ||
|
|
d2b505e76c | ||
|
|
0cca1f8c02 | ||
|
|
3bcd0da1f4 | ||
|
|
3e54c5b46d | ||
|
|
e7f7fc162b | ||
|
|
b3474a1ed5 | ||
|
|
69037820fa | ||
|
|
6c28ef21d9 | ||
|
|
ab6e3d9bf0 | ||
|
|
10ef6e371b | ||
|
|
c84cd04cf7 | ||
|
|
fb6d7bf265 | ||
|
|
3ad8e35be8 | ||
|
|
11f9f20b61 | ||
|
|
b6d0961f25 | ||
|
|
6046d067aa | ||
|
|
690c5f2fb6 | ||
|
|
654954f684 | ||
|
|
e5728407db | ||
|
|
0cf5af743e | ||
|
|
7ffead44fe | ||
|
|
f2aadcf0b5 | ||
|
|
d4d53aa965 | ||
|
|
735ba9c98a | ||
|
|
141789d240 | ||
|
|
c4df1b163c | ||
|
|
773afa0bb1 | ||
|
|
9bf2bbc241 | ||
|
|
84dea8078b | ||
|
|
dbf6af2fd7 | ||
|
|
bc6fb7082f | ||
|
|
cfa27cea58 | ||
|
|
5c061f9e1e | ||
|
|
34b24d0cf5 | ||
|
|
e27614fda3 | ||
|
|
8426d04138 | ||
|
|
641c8bedc9 | ||
|
|
4a39ca1b71 | ||
|
|
4a218fdbd8 | ||
|
|
d8fc1cd214 | ||
|
|
1e030b7371 | ||
|
|
3b113f2c39 | ||
|
|
73468592a9 | ||
|
|
a1b456150d | ||
|
|
865a883abb | ||
|
|
357a6717c8 | ||
|
|
bcb434e05e | ||
|
|
fb65fcc5f6 | ||
|
|
b5e379a9d4 | ||
|
|
05286dfd5d | ||
|
|
36184f09aa | ||
|
|
449933891e | ||
|
|
a5bfa6dac3 | ||
|
|
5aaa5b0552 | ||
|
|
9ab090a818 | ||
|
|
02d0bb56a6 |
No files matched your search
@@ -20,6 +20,9 @@ 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
|
||||
@@ -117,7 +120,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...>` |
|
||||
| loops on `available()` / `read_byte()` | UART `read_available(on_byte)`, `discard_available()`, `LineReader<N>`, `FrameReader<N, HEADER...>`, `LengthFrameReader<N, FrameFormat<...>...>` |
|
||||
| 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)` |
|
||||
@@ -125,6 +128,51 @@ 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
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
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.
|
||||
@@ -66,6 +66,8 @@ 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`.
|
||||
@@ -244,7 +246,9 @@ 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...>`; I2C has `update_register`,
|
||||
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`, frames that give their own length
|
||||
with `LengthFrameReader<N, FrameFormat<FrameLengthU16LE<POS, ADD>, HEADER...>...>`; I2C has `update_register`,
|
||||
`update_register16`, `read_byte_reg16` and `write_byte_reg16` for 16-bit register addresses,
|
||||
`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()`,
|
||||
@@ -309,6 +313,27 @@ 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
|
||||
@@ -355,7 +380,8 @@ 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.
|
||||
`component-tests` skill. Tests that differ only in their inputs are one `pytest.mark.parametrize` test
|
||||
or a table-driven gtest.
|
||||
|
||||
* **Debugging and Troubleshooting:**
|
||||
* **Debug Tools:**
|
||||
|
||||
@@ -489,10 +489,12 @@ 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
|
||||
@@ -735,6 +737,7 @@ 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
|
||||
|
||||
@@ -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.0")
|
||||
add_idf_component(name="esphome/micro-flac", ref="0.3.1")
|
||||
_emit_memory_pair(
|
||||
data.flac.buffer_memory,
|
||||
"CONFIG_MICRO_FLAC_PREFER_PSRAM",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#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"
|
||||
@@ -21,48 +22,40 @@ 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_() {
|
||||
// 1. Disable advanced power-save so the config port is accessible
|
||||
// The config port is only reachable with advanced power save off
|
||||
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) {
|
||||
// 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))
|
||||
// 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)
|
||||
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);
|
||||
if (this->write_register(BMI270_REG_INIT_DATA, cfg + index, burst) != i2c::ERROR_OK)
|
||||
progmem_memcpy(buf + 1, BMI270_CONFIG_FILE + index, burst);
|
||||
if (this->write(buf, burst + 1) != 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); // spec: wait ≥20 ms for init to complete
|
||||
delay(20); // The datasheet asks for at least 20 ms before INTERNAL_STATUS is valid
|
||||
|
||||
// 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;
|
||||
@@ -73,74 +66,52 @@ 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);
|
||||
|
||||
// 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_)))
|
||||
if (!this->setup_check(this->load_config_file_(), LOG_STR("Config file upload failed")))
|
||||
return;
|
||||
|
||||
// 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)))
|
||||
// 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)))
|
||||
return;
|
||||
delay(5);
|
||||
|
||||
// 8. Re-enable advanced power save (optional; keeps current low between reads)
|
||||
// Disabled here for simplicity – leave in performance mode
|
||||
// bit1 = fifo_self_wakeup
|
||||
// Advanced power save stays off; FIFO self-wakeup on
|
||||
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) {
|
||||
this->magnetometer_ready_ = this->setup_magnetometer_();
|
||||
const LogString *failed_step = this->setup_magnetometer_();
|
||||
this->magnetometer_ready_ = failed_step == nullptr;
|
||||
if (!this->magnetometer_ready_) {
|
||||
ESP_LOGW(TAG, "BMM150 magnetometer setup failed; continuing without it");
|
||||
ESP_LOGW(TAG, "BMM150 magnetometer setup failed at %s; continuing without it", LOG_STR_ARG(failed_step));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
ESP_LOGCONFIG(TAG, "BMI270 initialised successfully");
|
||||
}
|
||||
|
||||
#ifdef USE_BMI270_BMM150
|
||||
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.
|
||||
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;
|
||||
uint32_t start = millis();
|
||||
while (true) {
|
||||
uint8_t status = 0;
|
||||
@@ -148,98 +119,63 @@ bool BMI270Component::wait_for_aux_idle_(uint32_t timeout_ms) {
|
||||
return false;
|
||||
if ((status & BMI270_STATUS_AUX_BUSY) == 0)
|
||||
return true;
|
||||
if (millis() - start >= timeout_ms)
|
||||
if (millis() - start >= AUX_IDLE_TIMEOUT_MS)
|
||||
return false;
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
|
||||
bool BMI270Component::write_aux_register_(uint8_t reg, uint8_t value) {
|
||||
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);
|
||||
return this->write_byte(BMI270_REG_AUX_WR_DATA, value) && this->write_byte(BMI270_REG_AUX_WR_ADDR, reg) &&
|
||||
this->wait_for_aux_idle_();
|
||||
}
|
||||
|
||||
bool BMI270Component::read_aux_block_(uint8_t reg, uint8_t *buf) {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
// 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");
|
||||
|
||||
// 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)) {
|
||||
ESP_LOGW(TAG, "BMM150 power-on write timed out");
|
||||
return false;
|
||||
}
|
||||
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON))
|
||||
return LOG_STR("power-on");
|
||||
delay(BMM150_START_UP_TIME_MS);
|
||||
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET)) {
|
||||
ESP_LOGW(TAG, "BMM150 soft-reset write timed out");
|
||||
return false;
|
||||
}
|
||||
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET))
|
||||
return LOG_STR("soft reset");
|
||||
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)) {
|
||||
ESP_LOGW(TAG, "BMM150 chip-ID read failed");
|
||||
return false;
|
||||
}
|
||||
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id))
|
||||
return LOG_STR("chip ID read");
|
||||
if (chip_id[0] != BMM150_CHIP_ID_VALUE) {
|
||||
ESP_LOGW(TAG, "BMM150 not detected (chip ID 0x%02X, expected 0x%02X)", chip_id[0], BMM150_CHIP_ID_VALUE);
|
||||
return false;
|
||||
ESP_LOGW(TAG, "BMM150 chip ID 0x%02X, expected 0x%02X", chip_id[0], BMM150_CHIP_ID_VALUE);
|
||||
return LOG_STR("chip ID check");
|
||||
}
|
||||
|
||||
if (!this->read_magnetometer_trim_()) {
|
||||
ESP_LOGW(TAG, "BMM150 trim data read failed");
|
||||
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");
|
||||
}
|
||||
this->mag_trim_ = bmm150_parse_trim(trim);
|
||||
|
||||
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_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ))
|
||||
return LOG_STR("normal mode");
|
||||
|
||||
// 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;
|
||||
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;
|
||||
}
|
||||
#endif // USE_BMI270_BMM150
|
||||
|
||||
@@ -249,9 +185,10 @@ void BMI270Component::dump_config() {
|
||||
if (this->is_failed())
|
||||
return;
|
||||
|
||||
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",
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Accel range : %s\n"
|
||||
" Gyro range : %s",
|
||||
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)),
|
||||
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) {
|
||||
@@ -262,9 +199,6 @@ 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;
|
||||
|
||||
@@ -12,18 +12,15 @@
|
||||
|
||||
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; // temperature (2 bytes big-endian ish)
|
||||
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23;
|
||||
|
||||
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)
|
||||
// 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 BMI270_REG_PWR_CONF = 0x7C;
|
||||
static constexpr uint8_t BMI270_REG_PWR_CTRL = 0x7D;
|
||||
@@ -80,7 +77,6 @@ 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,
|
||||
@@ -88,7 +84,6 @@ 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,
|
||||
@@ -100,7 +95,6 @@ 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,
|
||||
@@ -109,7 +103,6 @@ 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,
|
||||
@@ -130,14 +123,11 @@ 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; }
|
||||
@@ -153,21 +143,15 @@ class BMI270Component final : public motion::MotionComponent, public i2c::I2CDev
|
||||
bool update_data(motion::MotionData &data) override;
|
||||
bool load_config_file_();
|
||||
#ifdef USE_BMI270_BMM150
|
||||
// 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.
|
||||
// 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
|
||||
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,5 +1,6 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
namespace esphome::bmi270 {
|
||||
|
||||
@@ -44,7 +45,7 @@ POSSIBILITY OF SUCH DAMAGE.
|
||||
after every power cycle, before any sensor data can be read.
|
||||
--------------------------------------------------------------------------- */
|
||||
|
||||
static constexpr uint8_t BMI270_CONFIG_FILE[] = {
|
||||
static constexpr uint8_t BMI270_CONFIG_FILE[] PROGMEM = {
|
||||
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,
|
||||
|
||||
@@ -3,11 +3,8 @@
|
||||
#include <cstdint>
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
// 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.
|
||||
// BMM150 magnetometer behind the BMI270's aux interface; it is not on the main I2C bus, so it is not
|
||||
// its own component
|
||||
namespace esphome::bmi270::bmm150 {
|
||||
|
||||
static constexpr uint8_t BMM150_DEFAULT_I2C_ADDRESS = 0x10;
|
||||
@@ -64,20 +61,23 @@ inline uint16_t bmm150_trim_word(const uint8_t *regs, uint8_t reg) {
|
||||
return encode_value_le<uint16_t>(®s[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>(regs[BMM150_TRIM_X1 - BMM150_REG_TRIM_START]);
|
||||
trim.y1 = static_cast<int8_t>(regs[BMM150_TRIM_Y1 - BMM150_REG_TRIM_START]);
|
||||
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.z4 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z4));
|
||||
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.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.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>(regs[BMM150_TRIM_XY2 - BMM150_REG_TRIM_START]);
|
||||
trim.xy1 = regs[BMM150_TRIM_XY1 - BMM150_REG_TRIM_START];
|
||||
trim.xy2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_XY2));
|
||||
trim.xy1 = bmm150_trim_byte(regs, BMM150_TRIM_XY1);
|
||||
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) {
|
||||
// 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));
|
||||
// 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;
|
||||
return BMM150Data{
|
||||
.x = bmm150_compensate_xy(trim, trim.x1, trim.x2, x, rhall),
|
||||
.y = bmm150_compensate_xy(trim, trim.y1, trim.y2, y, rhall),
|
||||
|
||||
@@ -17,6 +17,14 @@ 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")
|
||||
@@ -57,50 +65,49 @@ 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="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(
|
||||
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(
|
||||
GYRO_RANGE_OPTIONS, upper=True
|
||||
),
|
||||
cv.Optional(CONF_GYROSCOPE_ODR, default="200HZ"): cv.enum(
|
||||
cv.Optional(CONF_GYROSCOPE_ODR, default=DEFAULT_GYROSCOPE_ODR): 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
|
||||
),
|
||||
# Default matches the BMM150's fixed I2C address; irrelevant when aux_device is NONE.
|
||||
cv.Optional(CONF_AUX_ADDRESS, default=0x10): cv.i2c_address,
|
||||
cv.Optional(CONF_AUX_ADDRESS, default=DEFAULT_AUX_ADDRESS): 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)
|
||||
|
||||
# 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 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]))
|
||||
# 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))
|
||||
cg.add(var.set_aux_device_address(config[CONF_AUX_ADDRESS]))
|
||||
if (address := config[CONF_AUX_ADDRESS]) != DEFAULT_AUX_ADDRESS:
|
||||
cg.add(var.set_aux_device_address(address))
|
||||
@@ -515,18 +515,12 @@ void CC1101Component::dump_config() {
|
||||
}
|
||||
|
||||
void CC1101Component::begin_tx() {
|
||||
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);
|
||||
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;
|
||||
}
|
||||
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,13 +63,25 @@ void CST816Touchscreen::update_touches() {
|
||||
uint8_t data[13];
|
||||
if (!this->status_comm_result(this->read_bytes(REG_STATUS, data, sizeof data)))
|
||||
return;
|
||||
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 3;
|
||||
|
||||
// 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]);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -94,5 +94,7 @@ 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},
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,380 @@
|
||||
#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
|
||||
@@ -0,0 +1,113 @@
|
||||
#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
|
||||
@@ -2,55 +2,14 @@
|
||||
#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);
|
||||
@@ -96,329 +55,6 @@ 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) {
|
||||
|
||||
@@ -180,23 +180,18 @@ void ArduinoI2CBus::recover_() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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
|
||||
|
||||
delayMicroseconds(half_period_usec);
|
||||
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
|
||||
// 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
|
||||
delayMicroseconds(half_period_usec);
|
||||
|
||||
// Release output and activate pull up resistor to make the signal HIGH.
|
||||
@@ -223,14 +218,7 @@ void ArduinoI2CBus::recover_() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// A device still holding SDA after nine pulses cannot be freed here.
|
||||
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;
|
||||
@@ -242,15 +230,13 @@ 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."
|
||||
// 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.
|
||||
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
|
||||
// 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
|
||||
pinMode(this->sda_pin_, OUTPUT); // NOLINT
|
||||
pinMode(this->sda_pin_, INPUT); // NOLINT
|
||||
digitalWrite(this->sda_pin_, LOW); // NOLINT
|
||||
pinMode(this->sda_pin_, OUTPUT); // NOLINT
|
||||
|
||||
// From the specification:
|
||||
// "A START condition immediately followed by a STOP condition (void
|
||||
|
||||
@@ -346,14 +346,9 @@ void IDFI2CBus::recover_() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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++) {
|
||||
// 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++) {
|
||||
gpio_set_level(scl_pin, 0);
|
||||
delayMicroseconds(half_period_usec);
|
||||
gpio_set_level(scl_pin, 1);
|
||||
@@ -378,9 +373,7 @@ void IDFI2CBus::recover_() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// A device still holding SDA after nine pulses cannot be freed here.
|
||||
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;
|
||||
@@ -392,10 +385,7 @@ 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."
|
||||
// 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.
|
||||
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
|
||||
// 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);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
@@ -188,6 +189,61 @@ 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,7 +151,8 @@ 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());
|
||||
auto w = to_uint8_scale(val.get_white());
|
||||
// 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());
|
||||
return Color(r, g, b, w);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,45 @@ 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,10 +40,13 @@ 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 {
|
||||
// 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));
|
||||
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));
|
||||
}
|
||||
inline uint8_t color_correct_red(uint8_t red) const ESPHOME_ALWAYS_INLINE {
|
||||
return this->color_correct_channel(COLOR_CHANNEL_R, red);
|
||||
@@ -90,6 +93,15 @@ 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
|
||||
|
||||
@@ -36,6 +36,10 @@ 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.
|
||||
@@ -78,6 +82,10 @@ 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) {
|
||||
@@ -151,7 +159,12 @@ 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 { this->set_raw(index, this->color_correction->color_correct(color)); }
|
||||
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_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));
|
||||
}
|
||||
@@ -273,6 +286,10 @@ 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_;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
#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
|
||||
@@ -0,0 +1,67 @@
|
||||
#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
|
||||
@@ -1,5 +1,6 @@
|
||||
#ifdef USE_ESP32
|
||||
#include "modem_component.h"
|
||||
#include "at_reply.h"
|
||||
#include "soc/soc_caps.h"
|
||||
#include <driver/uart.h>
|
||||
|
||||
@@ -42,6 +43,14 @@ 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
|
||||
@@ -56,6 +65,12 @@ 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;
|
||||
@@ -73,8 +88,22 @@ 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", "PPP link failed",
|
||||
"Modem teardown failed");
|
||||
"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);
|
||||
}
|
||||
|
||||
// Indexed by esp_modem::command_result
|
||||
PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
|
||||
@@ -586,6 +615,9 @@ 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
|
||||
@@ -611,21 +643,18 @@ 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 (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud) != ESP_OK) {
|
||||
if (this->set_uart_baud_(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) {
|
||||
@@ -633,11 +662,31 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
// The detection at the current rate already failed; a UART that refused every other rate set BAUD
|
||||
if (!probed && !rejected) {
|
||||
// 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) {
|
||||
this->not_responding_(detected);
|
||||
}
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
|
||||
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);
|
||||
}
|
||||
ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
|
||||
break;
|
||||
@@ -671,10 +720,19 @@ 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.
|
||||
@@ -690,6 +748,7 @@ 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);
|
||||
@@ -698,12 +757,11 @@ 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 (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), this->baud_rate_) != ESP_OK) {
|
||||
if (this->set_uart_baud_(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);
|
||||
@@ -731,6 +789,7 @@ 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;
|
||||
}
|
||||
|
||||
@@ -746,12 +805,13 @@ 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; only a failed attachment read comes back here unsure of the modem
|
||||
// ENABLING just synced; a command that timed out comes back here unsure of the modem
|
||||
if (this->resync_) {
|
||||
this->resync_ = false;
|
||||
if (this->dce_->sync() != command_result::OK) {
|
||||
@@ -792,35 +852,78 @@ ModemState ModemComponent::handle_state_connecting_() {
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
|
||||
this->attach_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;
|
||||
this->idle_polls_ = 0;
|
||||
this->unknown_polls_ = 0;
|
||||
}
|
||||
|
||||
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->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
|
||||
this->resync_ = true;
|
||||
this->request_resync_();
|
||||
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, registration = -1, mode = -1; // -1 stays when the query fails
|
||||
this->dce_->get_network_registration_state(registration);
|
||||
int rssi = 99, ber = 99, mode = -1; // -1 stays when the query fails
|
||||
this->dce_->get_signal_quality(rssi, ber);
|
||||
this->dce_->get_network_system_mode(mode);
|
||||
ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
|
||||
rssi, ber);
|
||||
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_);
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
|
||||
}
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
this->set_fault_(registration == REGISTRATION_DENIED ? ModemFault::MODEM_FAULT_REGISTRATION_DENIED
|
||||
: ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
|
||||
}
|
||||
|
||||
@@ -923,11 +1026,114 @@ 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) {
|
||||
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", 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);
|
||||
}
|
||||
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); }
|
||||
|
||||
@@ -954,13 +1160,54 @@ 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) {
|
||||
std::string output;
|
||||
const command_result result = this->dce_->at(cmd, output, 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("...") : "";
|
||||
if (result == command_result::OK) {
|
||||
ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
|
||||
ESP_LOGI(TAG, "AT '%s' -> OK: %s%s", cmd, cut, this->reply_);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
|
||||
ESP_LOGW(TAG, "AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -973,25 +1220,27 @@ SimResult ModemComponent::prepare_sim_() {
|
||||
return SimResult::SIM_RESULT_RETRY; // the save wakes the task
|
||||
}
|
||||
#endif
|
||||
std::string output;
|
||||
if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
|
||||
// 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) {
|
||||
// A SIM that is still starting answers with an error for a second or so
|
||||
ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM status not readable yet: %s", this->reply_);
|
||||
this->sim_not_ready_(this->reply_);
|
||||
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 = strstr(output.c_str(), "+CPIN:");
|
||||
if (found != nullptr) {
|
||||
found += sizeof("+CPIN:") - 1;
|
||||
while (*found == ' ') {
|
||||
found++;
|
||||
}
|
||||
}
|
||||
const char *found = sim_status(this->reply_);
|
||||
const StringRef status = found != nullptr ? StringRef(found) : StringRef();
|
||||
if (status.empty()) {
|
||||
ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM status not reported yet: %s", this->reply_);
|
||||
this->sim_not_ready_(this->reply_);
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
ESP_LOGD(TAG, "SIM: %s", status.c_str());
|
||||
@@ -1019,8 +1268,8 @@ SimResult ModemComponent::prepare_sim_() {
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
|
||||
return SimResult::SIM_RESULT_LOCKED;
|
||||
}
|
||||
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);
|
||||
ESP_LOGD(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
|
||||
this->sim_not_ready_(status.c_str());
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
#ifdef USE_MODEM_PIN_CODE
|
||||
|
||||
@@ -62,6 +62,7 @@ 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,
|
||||
};
|
||||
@@ -151,6 +152,7 @@ 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;
|
||||
@@ -200,8 +202,20 @@ 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
|
||||
@@ -221,6 +235,9 @@ 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_;
|
||||
@@ -291,6 +308,9 @@ 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};
|
||||
@@ -298,7 +318,8 @@ 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 resync_{false}; // the attachment read failed, so CONNECTING syncs again first
|
||||
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 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];
|
||||
|
||||
@@ -323,12 +323,18 @@ 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;
|
||||
@@ -358,9 +364,13 @@ void MQTTClientComponent::start_dnslookup_() {
|
||||
}
|
||||
default:
|
||||
case ERR_ARG: {
|
||||
// error
|
||||
// The lookup never started, so there is no answer to wait for; loop() tries again in 5 seconds
|
||||
ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
|
||||
break;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -505,7 +515,9 @@ void MQTTClientComponent::loop() {
|
||||
case MQTT_CLIENT_DISABLED:
|
||||
return; // Return to avoid a reboot when disabled
|
||||
case MQTT_CLIENT_DISCONNECTED:
|
||||
if (now - this->connect_begin_ > 5000) {
|
||||
// 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) {
|
||||
this->start_dnslookup_();
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -436,6 +436,8 @@ 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};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
import logging
|
||||
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
@@ -8,6 +9,8 @@ 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"
|
||||
@@ -42,20 +45,18 @@ NPM1300_CHILD_SCHEMA = cv.Schema(
|
||||
{cv.GenerateID(CONF_NPM1300_ID): cv.use_id(NPM1300Component)}
|
||||
)
|
||||
|
||||
# Status registers read on each update: VBUSINSTATUS, BCHGCHARGESTATUS and BCHGERRREASON
|
||||
NPM1300Status = npm1300_ns.struct("NPM1300Status")
|
||||
# The status registers read on each update
|
||||
STATUS_PUBLISHER = cg.HubFunction(
|
||||
"status",
|
||||
cg.void,
|
||||
[
|
||||
(cg.uint8, "vbus_status"),
|
||||
(cg.uint8, "charge_status"),
|
||||
(cg.uint8, "error_reason"),
|
||||
],
|
||||
[(NPM1300Status.operator("const").operator("ref"), "status")],
|
||||
define="USE_NPM1300_STATUS_PUBLISHER",
|
||||
)
|
||||
VBUS_STATUS = STATUS_PUBLISHER.param("vbus_status")
|
||||
CHARGE_STATUS = STATUS_PUBLISHER.param("charge_status")
|
||||
ERROR_REASON = STATUS_PUBLISHER.param("error_reason")
|
||||
STATUS = STATUS_PUBLISHER.param("status")
|
||||
VBUS_STATUS = STATUS.vbus
|
||||
CHARGE_STATUS = STATUS.charge
|
||||
ERROR_REASON = STATUS.error_reason
|
||||
# The ADC results and the amperes per code of the battery current
|
||||
DATA_PUBLISHER = cg.HubFunction(
|
||||
"data",
|
||||
@@ -77,7 +78,10 @@ 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
|
||||
@@ -101,14 +105,13 @@ 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 units * `scale`."""
|
||||
"""Validate a quantity with `validator` and accept only the listed values, given in thousandths of `unit`."""
|
||||
|
||||
def validate(value: object) -> float:
|
||||
value = validator(value)
|
||||
if round(value * scale) not in allowed:
|
||||
options = ", ".join(f"{v / scale:g}{unit}" for v in allowed)
|
||||
if _millis(value) not in allowed:
|
||||
options = ", ".join(f"{v / 1000:g}{unit}" for v in allowed)
|
||||
raise cv.Invalid(f"Must be one of {options}")
|
||||
return value
|
||||
|
||||
@@ -135,6 +138,23 @@ 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")
|
||||
|
||||
@@ -150,15 +170,58 @@ LDO_SCHEMA = BUCK_SCHEMA.extend(
|
||||
}
|
||||
)
|
||||
|
||||
CHARGER_SCHEMA = cv.Schema(
|
||||
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(
|
||||
{
|
||||
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"
|
||||
# Defaults are the reset values of the product specification
|
||||
cv.Optional(CONF_CHARGE_CURRENT, default="32mA"): _stepped(
|
||||
cv.current, 32, 800, 2, "A"
|
||||
),
|
||||
cv.Optional(CONF_WARM_TERMINATION_VOLTAGE): _one_of_units(
|
||||
cv.Optional(CONF_TERMINATION_VOLTAGE, default="3.6V"): _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
|
||||
),
|
||||
@@ -169,22 +232,37 @@ CHARGER_SCHEMA = cv.Schema(
|
||||
cv.current, list(DISCHARGE_CURRENT_LIMITS), "A"
|
||||
),
|
||||
cv.Optional(CONF_RECHARGE, default=True): cv.boolean,
|
||||
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
|
||||
cv.Optional(CONF_ENABLED, default=False): cv.boolean,
|
||||
}
|
||||
)
|
||||
CHARGER_SCHEMA = cv.All(_warm_termination_default, _CHARGER_SETTINGS_SCHEMA)
|
||||
|
||||
|
||||
CONFIG_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(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(NPM1300Component),
|
||||
cv.Optional(CONF_VBUS_CURRENT_LIMIT): VBUS_CURRENT_LIMIT,
|
||||
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_THERMISTOR_RESISTANCE): _thermistor_resistance,
|
||||
cv.Optional(CONF_THERMISTOR_BETA): 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,
|
||||
@@ -193,7 +271,8 @@ CONFIG_SCHEMA = (
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
.extend(i2c.i2c_device_schema(0x6B))
|
||||
.extend(i2c.i2c_device_schema(0x6B)),
|
||||
_check_thermistor,
|
||||
)
|
||||
|
||||
|
||||
@@ -208,7 +287,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 = config.get(CONF_WARM_TERMINATION_VOLTAGE)
|
||||
warm = _termination_voltage_code(config[CONF_WARM_TERMINATION_VOLTAGE])
|
||||
return cg.StructInitializer(
|
||||
NPM1300ChargerConfig,
|
||||
("current", _millis(config[CONF_CHARGE_CURRENT]) // 2),
|
||||
@@ -217,10 +296,7 @@ def _charger_config(config: ConfigType) -> cg.StructInitializer:
|
||||
DISCHARGE_CURRENT_LIMITS[_millis(config[CONF_DISCHARGE_CURRENT_LIMIT])],
|
||||
),
|
||||
("termination_voltage", termination),
|
||||
(
|
||||
"warm_termination_voltage",
|
||||
termination if warm is None else _termination_voltage_code(warm),
|
||||
),
|
||||
("warm_termination_voltage", warm),
|
||||
("trickle_voltage", TRICKLE_VOLTAGES[_millis(config[CONF_TRICKLE_VOLTAGE])]),
|
||||
("termination_current", TERMINATION_CURRENTS[config[CONF_TERMINATION_CURRENT]]),
|
||||
("recharge", config[CONF_RECHARGE]),
|
||||
@@ -247,6 +323,13 @@ 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,
|
||||
(
|
||||
@@ -254,13 +337,8 @@ 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", config[CONF_THERMISTOR_BETA]),
|
||||
(
|
||||
"thermistor",
|
||||
NPM1300_UNSET
|
||||
if resistance is None
|
||||
else THERMISTOR_RESISTANCES[round(resistance / 1000)],
|
||||
),
|
||||
("thermistor_beta", beta),
|
||||
("thermistor", thermistor),
|
||||
("charger_configured", charger is not None),
|
||||
)
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ 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;
|
||||
@@ -53,6 +54,9 @@ 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;
|
||||
@@ -107,26 +111,36 @@ float ntc_temperature(uint16_t code, float inv_beta) {
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
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
|
||||
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
|
||||
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(uint8_t vbus_status, uint8_t charge_status, uint8_t error_reason) {
|
||||
if (error_reason != 0)
|
||||
static uint8_t charger_status_index(const NPM1300Status &status) {
|
||||
if ((status.vbus & VBUS_PRESENT) == 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 ((charge_status & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
|
||||
return i + 1;
|
||||
if ((status.charge & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
|
||||
return CHARGER_STATUS_FIRST_BIT + i;
|
||||
}
|
||||
return (vbus_status & VBUS_PRESENT) == 0 ? 6 : 7;
|
||||
// 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;
|
||||
}
|
||||
|
||||
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);
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status) {
|
||||
const uint8_t index = charger_status_index(status);
|
||||
if (index == last)
|
||||
return;
|
||||
last = index;
|
||||
@@ -198,7 +212,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 == NPM1300_UNSET)
|
||||
if (config.thermistor == 0 || 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 ||
|
||||
@@ -292,33 +306,40 @@ void NPM1300Component::hibernate(uint32_t duration_ms) {
|
||||
}
|
||||
|
||||
void NPM1300Component::update() {
|
||||
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)))
|
||||
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)))
|
||||
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 = (vbus_status & VBUS_PRESENT) != 0;
|
||||
const bool vbus_present = (status.vbus & 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 (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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
#ifdef USE_NPM1300_STATUS_PUBLISHER
|
||||
if (this->status_publisher_ != nullptr)
|
||||
this->status_publisher_(vbus_status, charge_status, error_reason);
|
||||
this->status_publisher_(status);
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
if (!this->status_comm_check(this->publish_switches_()))
|
||||
if (!this->status_comm_check(this->publish_switches_(status)))
|
||||
return;
|
||||
#endif
|
||||
|
||||
@@ -348,16 +369,10 @@ void NPM1300Component::update() {
|
||||
}
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
bool NPM1300Component::publish_switches_() {
|
||||
bool NPM1300Component::publish_switches_(const NPM1300Status &status) {
|
||||
PUBLISH_STATE(this->charger_switch_, (status.charger_enable & 1) != 0);
|
||||
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)) {
|
||||
@@ -461,7 +476,9 @@ void NPM1300Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, " Enabled at boot: %s", YESNO(output.enabled != 0));
|
||||
}
|
||||
}
|
||||
if (config.thermistor != NPM1300_UNSET) {
|
||||
if (config.thermistor == 0) {
|
||||
ESP_LOGCONFIG(TAG, " Thermistor: none");
|
||||
} else if (config.thermistor != NPM1300_UNSET) {
|
||||
ESP_LOGCONFIG(TAG, " Thermistor B constant: %u", config.thermistor_beta);
|
||||
}
|
||||
#ifdef USE_SENSOR
|
||||
|
||||
@@ -54,10 +54,19 @@ struct NPM1300Config {
|
||||
NPM1300OutputConfig outputs[NPM1300_OUTPUT_COUNT];
|
||||
NPM1300ChargerConfig charger; // only applied when charger_configured
|
||||
uint16_t thermistor_beta;
|
||||
uint8_t thermistor; // ADCNTCRSEL code: 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
|
||||
uint8_t thermistor; // ADCNTCRSEL code: 0 for none, 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) {
|
||||
@@ -68,8 +77,7 @@ 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, uint8_t vbus_status, uint8_t charge_status,
|
||||
uint8_t error_reason);
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status);
|
||||
#endif
|
||||
|
||||
class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
@@ -95,7 +103,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, uint8_t, uint8_t, uint8_t)
|
||||
HUB_PUBLISHER(status, const NPM1300Status &)
|
||||
#endif
|
||||
#ifdef USE_NPM1300_DATA_PUBLISHER
|
||||
HUB_PUBLISHER(data, const uint8_t *, float)
|
||||
@@ -128,7 +136,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
/// Returns false when a status read failed
|
||||
bool publish_switches_();
|
||||
bool publish_switches_(const NPM1300Status &status);
|
||||
#endif
|
||||
|
||||
const NPM1300Config *config_;
|
||||
|
||||
@@ -21,7 +21,6 @@ from esphome.types import ConfigType
|
||||
from . import (
|
||||
ADC,
|
||||
CONF_NPM1300_ID,
|
||||
CONF_THERMISTOR_BETA,
|
||||
CONF_THERMISTOR_RESISTANCE,
|
||||
CONF_VBUS_CURRENT_LIMIT,
|
||||
DATA_PUBLISHER,
|
||||
@@ -30,7 +29,9 @@ from . import (
|
||||
DUMP_TAG,
|
||||
IBAT_SCALE,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
THERMISTOR_NONE,
|
||||
npm1300_ns,
|
||||
thermistor_beta,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["npm1300"]
|
||||
@@ -109,10 +110,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 CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
if hub.get(CONF_THERMISTOR_RESISTANCE, THERMISTOR_NONE) == THERMISTOR_NONE:
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' "
|
||||
"set on the npm1300 component",
|
||||
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
|
||||
"nominal resistance of the battery thermistor on the npm1300 component",
|
||||
path=[CONF_BATTERY_TEMPERATURE],
|
||||
)
|
||||
|
||||
@@ -145,7 +146,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 / hub_config[CONF_THERMISTOR_BETA]
|
||||
_adc(2, 5, 2), 1.0 / thermistor_beta(hub_config)
|
||||
)
|
||||
_add_adc_sensor(hub, var, state, "Battery Temperature")
|
||||
await sensors(CONF_VBUS_CURRENT_LIMIT, hub.set_vbus_current_limit_sensor)
|
||||
@@ -15,6 +15,7 @@ from . import (
|
||||
CONF_THERMISTOR_RESISTANCE,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
OUTPUTS,
|
||||
THERMISTOR_NONE,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["npm1300"]
|
||||
@@ -44,11 +45,18 @@ def _final_validate(config: ConfigType) -> None:
|
||||
if CONF_CHARGER not in config:
|
||||
return
|
||||
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
|
||||
# Only the charger block turns off the NTC check, without which the charger never starts
|
||||
if CONF_CHARGER not in hub and CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
# 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 a '{CONF_CHARGER}' block or "
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' on the npm1300 component",
|
||||
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:
|
||||
raise cv.Invalid(
|
||||
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block when "
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' is '{THERMISTOR_NONE}'",
|
||||
path=[CONF_CHARGER],
|
||||
)
|
||||
|
||||
|
||||
@@ -11,14 +11,12 @@ 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,
|
||||
)
|
||||
|
||||
@@ -48,9 +46,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
)
|
||||
STATUS_PUBLISHER.add(
|
||||
hub,
|
||||
npm1300_ns.publish_charger_status(
|
||||
parent_ref(var), last, VBUS_STATUS, CHARGE_STATUS, ERROR_REASON
|
||||
),
|
||||
npm1300_ns.publish_charger_status(parent_ref(var), last, STATUS),
|
||||
)
|
||||
DUMP.add(
|
||||
hub,
|
||||
|
||||
@@ -13,6 +13,7 @@ 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,
|
||||
@@ -106,6 +107,7 @@ from .const import (
|
||||
VARIANT_NRF52832,
|
||||
VARIANT_NRF52840,
|
||||
VARIANT_REGULATOR,
|
||||
VARIANTS_NRF54L,
|
||||
VARIANTS_WITHOUT_USB,
|
||||
)
|
||||
from .framework import (
|
||||
@@ -536,6 +538,11 @@ 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."""
|
||||
@@ -544,7 +551,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 (VARIANT_NRF54L15, VARIANT_NRF54LM20):
|
||||
if variant in VARIANTS_NRF54L:
|
||||
# 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")
|
||||
@@ -612,11 +619,11 @@ async def to_code(config: ConfigType) -> None:
|
||||
if config[KEY_BOOTLOADER] in ADAFRUIT_BOOTLOADERS:
|
||||
cg.add_define("USE_BOOTLOADER_ADAFRUIT")
|
||||
|
||||
zephyr_setup_preferences()
|
||||
zephyr_setup_preferences(_preferences_storage(variant))
|
||||
zephyr_to_code(config)
|
||||
|
||||
# The nRF54L has RRAM (cpuapp_rram) and no flash0 node
|
||||
if CORE.testing_mode and variant not in (VARIANT_NRF54L15, VARIANT_NRF54LM20):
|
||||
if CORE.testing_mode and variant not in VARIANTS_NRF54L:
|
||||
zephyr_add_overlay(
|
||||
f"""
|
||||
&flash0 {{
|
||||
|
||||
@@ -17,6 +17,7 @@ from .const import (
|
||||
VARIANT_NRF54LM20,
|
||||
VARIANT_NRF52832,
|
||||
VARIANT_NRF52840,
|
||||
VARIANTS_NRF54L,
|
||||
)
|
||||
from .framework import (
|
||||
check_and_install,
|
||||
@@ -145,7 +146,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 (VARIANT_NRF54L15, VARIANT_NRF54LM20):
|
||||
if variant in VARIANTS_NRF54L:
|
||||
cmd += ["--script", str(_NRF54L_WATCHDOG_SCRIPT)]
|
||||
cmd += [str(image) for image in images]
|
||||
if not run_command_ok(cmd, env=env, stream_output=True):
|
||||
|
||||
@@ -41,6 +41,8 @@ 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,6 +83,9 @@ 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 {
|
||||
@@ -98,6 +101,10 @@ 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));
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
"""PCM1863 audio ADC component."""
|
||||
|
||||
DOMAIN = "pcm1863"
|
||||
@@ -0,0 +1,62 @@
|
||||
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]))
|
||||
@@ -0,0 +1,96 @@
|
||||
#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
|
||||
@@ -0,0 +1,64 @@
|
||||
#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
|
||||
@@ -0,0 +1,50 @@
|
||||
#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
|
||||
@@ -0,0 +1,32 @@
|
||||
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",
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""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"
|
||||
@@ -0,0 +1,33 @@
|
||||
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)
|
||||
@@ -0,0 +1,348 @@
|
||||
#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;
|
||||
// A frame arrives in one burst; after a pause this long a partly received frame is dropped.
|
||||
static constexpr uint32_t RX_GAP_MS = 100;
|
||||
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();
|
||||
if (const size_t count = this->available()) {
|
||||
this->last_rx_ = now;
|
||||
this->read_available(
|
||||
[this](uint8_t byte) {
|
||||
if (const size_t len = this->reader_.feed(byte))
|
||||
this->handle_frame_(this->reader_.frame(), len);
|
||||
},
|
||||
count);
|
||||
if (this->reader_.take_checksum_error()) {
|
||||
ESP_LOGD(TAG, "Dropped a frame with a wrong checksum");
|
||||
}
|
||||
} else if (this->reader_.partial() && now - this->last_rx_ >= RX_GAP_MS) {
|
||||
// Only on an idle pass: after a slow loop the rest of the frame may already be buffered.
|
||||
this->reader_.reset();
|
||||
}
|
||||
if (!this->queue_.empty() && now - this->last_send_ >= RESEND_INTERVAL_MS)
|
||||
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");
|
||||
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
|
||||
@@ -0,0 +1,85 @@
|
||||
#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
|
||||
@@ -0,0 +1,147 @@
|
||||
#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);
|
||||
}
|
||||
|
||||
size_t PacketReader::feed(uint8_t byte) {
|
||||
if (this->pos_ == 0 && byte != 0xA5)
|
||||
return 0;
|
||||
if (this->pos_ == 1 && byte != 0x01) {
|
||||
this->pos_ = byte == 0xA5 ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
this->buf_[this->pos_++] = byte;
|
||||
if (this->pos_ < 8)
|
||||
return 0;
|
||||
const uint8_t len = this->buf_[7];
|
||||
if (len < HEADER_SIZE) {
|
||||
this->pos_ = 0;
|
||||
return 0;
|
||||
}
|
||||
if (this->pos_ < len)
|
||||
return 0;
|
||||
this->pos_ = 0;
|
||||
if (frame_crc(this->buf_.data(), len) != encode_uint16(this->buf_[8], this->buf_[9])) {
|
||||
this->checksum_error_ = true;
|
||||
return 0;
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
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] = 0xA5;
|
||||
out[1] = 0x01;
|
||||
out[2] = flags;
|
||||
out[3] = type;
|
||||
out[4] = seq;
|
||||
out[5] = ack;
|
||||
out[6] = 0x00;
|
||||
out[7] = 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 + 8, frame_crc(out, total));
|
||||
return total;
|
||||
}
|
||||
|
||||
} // namespace esphome::pioneer_wt
|
||||
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#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;
|
||||
// The length byte counts the whole frame.
|
||||
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);
|
||||
|
||||
/// Collects bytes from the serial line into complete frames with a valid checksum.
|
||||
class PacketReader final {
|
||||
public:
|
||||
/// Feeds one byte. Returns the frame length once a complete, valid frame is in frame().
|
||||
size_t feed(uint8_t byte);
|
||||
const uint8_t *frame() const { return this->buf_.data(); }
|
||||
/// True while part of a frame has been collected.
|
||||
bool partial() const { return this->pos_ != 0; }
|
||||
/// Drops a partly collected frame, so the next byte can start a new one.
|
||||
void reset() { this->pos_ = 0; }
|
||||
/// True once after a complete frame was dropped for a wrong checksum.
|
||||
bool take_checksum_error() {
|
||||
const bool error = this->checksum_error_;
|
||||
this->checksum_error_ = false;
|
||||
return error;
|
||||
}
|
||||
|
||||
protected:
|
||||
std::array<uint8_t, MAX_FRAME_SIZE> buf_{};
|
||||
uint8_t pos_{0};
|
||||
bool checksum_error_{false};
|
||||
};
|
||||
|
||||
/// 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
|
||||
@@ -0,0 +1,37 @@
|
||||
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)")
|
||||
@@ -10,12 +10,10 @@ CODEOWNERS = ["@kahrendt"]
|
||||
|
||||
qwiic_pir_ns = cg.esphome_ns.namespace("qwiic_pir")
|
||||
|
||||
DebounceMode = qwiic_pir_ns.enum("DebounceMode")
|
||||
DEBOUNCE_MODE_OPTIONS = {
|
||||
"RAW": DebounceMode.RAW_DEBOUNCE_MODE,
|
||||
"NATIVE": DebounceMode.NATIVE_DEBOUNCE_MODE,
|
||||
"HYBRID": DebounceMode.HYBRID_DEBOUNCE_MODE,
|
||||
}
|
||||
DebounceMode = qwiic_pir_ns.enum("DebounceMode", is_class=True)
|
||||
DEBOUNCE_MODE_OPTIONS = DebounceMode.options(
|
||||
"RAW", "NATIVE", "HYBRID", prefix="DEBOUNCE_MODE_"
|
||||
)
|
||||
|
||||
CONF_DEBOUNCE_MODE = "debounce_mode"
|
||||
|
||||
@@ -47,12 +45,12 @@ CONFIG_SCHEMA = cv.All(
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await binary_sensor.new_binary_sensor(config)
|
||||
# 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,
|
||||
)
|
||||
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]))
|
||||
@@ -1,99 +1,85 @@
|
||||
#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, QWIIC_PIR_CHIP_ID, QWIIC_PIR_DEVICE_ID))
|
||||
if (!this->check_chip_id(this, REG_CHIP_ID, DEVICE_ID))
|
||||
return;
|
||||
|
||||
if (!this->setup_check(this->write_byte_16(QWIIC_PIR_DEBOUNCE_TIME, this->debounce_time_),
|
||||
if (!this->setup_check(this->write_byte_16_le(REG_DEBOUNCE_TIME, this->debounce_time_),
|
||||
LOG_STR("Failed to configure debounce time")))
|
||||
return;
|
||||
|
||||
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")))
|
||||
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")))
|
||||
return;
|
||||
|
||||
this->publish_state(this->event_register_.raw_reading);
|
||||
this->publish_state((event & EVENT_RAW_READING) != 0);
|
||||
}
|
||||
}
|
||||
|
||||
void QwiicPIRComponent::loop() {
|
||||
// Read Event Register
|
||||
if (!this->read_byte(QWIIC_PIR_EVENT_STATUS, &this->event_register_.reg)) {
|
||||
ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
|
||||
uint8_t event;
|
||||
if (!this->status_comm_check(this->read_byte(REG_EVENT_STATUS, &event)))
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
|
||||
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",
|
||||
debounce_mode_str);
|
||||
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
|
||||
LOG_STR_ARG(DebounceModeStrings::get_log_str(static_cast<uint8_t>(this->debounce_mode_), 0)));
|
||||
if (this->debounce_mode_ == DebounceMode::DEBOUNCE_MODE_NATIVE) {
|
||||
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
|
||||
@@ -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 (accessed July 2023)
|
||||
* SparkFun's Arduino library: https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library (accessed July 2023)
|
||||
* ATTiny84 firmware: https://github.com/sparkfun/Qwiic_PIR
|
||||
* SparkFun's Arduino library: https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
@@ -14,48 +14,24 @@
|
||||
|
||||
namespace esphome::qwiic_pir {
|
||||
|
||||
// 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 class DebounceMode : uint8_t {
|
||||
DEBOUNCE_MODE_RAW,
|
||||
DEBOUNCE_MODE_NATIVE,
|
||||
DEBOUNCE_MODE_HYBRID,
|
||||
};
|
||||
|
||||
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_{};
|
||||
|
||||
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_();
|
||||
uint16_t debounce_time_;
|
||||
DebounceMode debounce_mode_;
|
||||
};
|
||||
|
||||
} // namespace esphome::qwiic_pir
|
||||
@@ -2,10 +2,6 @@
|
||||
#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");
|
||||
@@ -27,10 +23,6 @@ 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),
|
||||
|
||||
@@ -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=False): cv.boolean,
|
||||
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=True): 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_{false};
|
||||
bool static_delay_adjustable_{true};
|
||||
};
|
||||
|
||||
} // namespace esphome::sendspin_
|
||||
|
||||
@@ -3,7 +3,7 @@ from dataclasses import dataclass, field
|
||||
from logging import getLogger
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from esphome import automation, pins
|
||||
import esphome.codegen as cg
|
||||
@@ -42,8 +42,12 @@ from esphome.const import (
|
||||
CONF_FLOW_CONTROL_PIN,
|
||||
CONF_ID,
|
||||
CONF_LAMBDA,
|
||||
CONF_MODE,
|
||||
CONF_NUMBER,
|
||||
CONF_OPEN_DRAIN,
|
||||
CONF_PORT,
|
||||
CONF_PULLDOWN,
|
||||
CONF_PULLUP,
|
||||
CONF_RX_BUFFER_SIZE,
|
||||
CONF_RX_PIN,
|
||||
CONF_SEQUENCE,
|
||||
@@ -60,6 +64,9 @@ import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
from esphome.yaml_util import make_data_base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from esphome.components.libretiny import HardwareUart
|
||||
|
||||
_LOGGER = getLogger(__name__)
|
||||
|
||||
CODEOWNERS = ["@esphome/core"]
|
||||
@@ -333,6 +340,89 @@ CONFIG_SCHEMA = cv.All(
|
||||
)
|
||||
|
||||
|
||||
def _libretiny_hardware_uart(config: ConfigType) -> "HardwareUart | None":
|
||||
"""Hardware UART the board can route the configured pins to; None if none can or the board is unknown."""
|
||||
from esphome.components.libretiny import get_hardware_uarts, has_software_serial
|
||||
|
||||
# Pin flags make setup() use SoftwareSerial where the family has it
|
||||
if has_software_serial() and any(
|
||||
pin[CONF_MODE].get(flag)
|
||||
for pin in (config.get(CONF_TX_PIN), config.get(CONF_RX_PIN))
|
||||
if pin is not None
|
||||
for flag in (CONF_OPEN_DRAIN, CONF_PULLUP, CONF_PULLDOWN)
|
||||
):
|
||||
return None
|
||||
tx = config[CONF_TX_PIN][CONF_NUMBER] if CONF_TX_PIN in config else None
|
||||
rx = config[CONF_RX_PIN][CONF_NUMBER] if CONF_RX_PIN in config else None
|
||||
return next(
|
||||
(
|
||||
uart
|
||||
for uart in get_hardware_uarts()
|
||||
if tx in (None, *uart.tx_pins) and rx in (None, *uart.rx_pins)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _final_validate(config: ConfigType) -> None:
|
||||
if CORE.is_libretiny:
|
||||
_validate_libretiny_pins(config)
|
||||
|
||||
|
||||
def _validate_libretiny_pins(config: ConfigType) -> None:
|
||||
from esphome.components.libretiny import (
|
||||
can_choose_uart_pins,
|
||||
get_hardware_uarts,
|
||||
get_libretiny_board,
|
||||
has_software_serial,
|
||||
)
|
||||
|
||||
# A board without pin data is matched against its default pins at boot
|
||||
if not (uarts := get_hardware_uarts()):
|
||||
return
|
||||
board = get_libretiny_board()
|
||||
uart = _libretiny_hardware_uart(config)
|
||||
if uart is None:
|
||||
if has_software_serial():
|
||||
return
|
||||
choices = "; ".join(
|
||||
f"UART{u.port}: TX={'/'.join(map(str, u.tx_pins)) or 'none'}, "
|
||||
f"RX={'/'.join(map(str, u.rx_pins)) or 'none'}"
|
||||
for u in uarts
|
||||
)
|
||||
raise cv.Invalid(
|
||||
f"Board {board} has no hardware UART on these pins. Pin numbers per UART: {choices}"
|
||||
)
|
||||
# Two entries on one port would share the Serial object, and the second begin() would move its pins
|
||||
for other in fv.full_config.get().get(DOMAIN, []):
|
||||
if other is config or other[CONF_ID] == config[CONF_ID]:
|
||||
continue
|
||||
if (
|
||||
other_uart := _libretiny_hardware_uart(other)
|
||||
) and other_uart.port == uart.port:
|
||||
raise cv.Invalid(
|
||||
f"UART {other[CONF_ID]} already uses hardware UART{uart.port} of board {board}"
|
||||
)
|
||||
if not uart.pin_choices:
|
||||
return
|
||||
# A left-out direction with no default pin is opened on an invalid pin, which hangs at boot
|
||||
for key, role, choices in (
|
||||
(CONF_TX_PIN, "TX", uart.tx_pin_choices),
|
||||
(CONF_RX_PIN, "RX", uart.rx_pin_choices),
|
||||
):
|
||||
if choices and key not in config:
|
||||
raise cv.Invalid(
|
||||
f"UART{uart.port} of board {board} has no default {role} pin, so it needs {key}"
|
||||
)
|
||||
if not can_choose_uart_pins():
|
||||
raise cv.Invalid(
|
||||
f"Choosing the pins of UART{uart.port} on board {board} needs LibreTiny 1.12.0 or later"
|
||||
)
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _final_validate
|
||||
|
||||
|
||||
async def debug_to_code(config, parent):
|
||||
trigger = cg.new_Pvariable(config[CONF_TRIGGER_ID], parent)
|
||||
await cg.register_component(trigger, config)
|
||||
@@ -426,6 +516,11 @@ async def to_code(config):
|
||||
enable_serial1()
|
||||
cg.add_define("USE_ESP8266_UART_SERIAL1")
|
||||
|
||||
if CORE.is_libretiny and (uart := _libretiny_hardware_uart(config)) is not None:
|
||||
cg.add(var.set_hardware_port(uart.port))
|
||||
if uart.pin_choices:
|
||||
cg.add_define("USE_UART_LIBRETINY_PIN_ROUTING")
|
||||
|
||||
CORE.add_job(final_step)
|
||||
|
||||
|
||||
|
||||
@@ -25,6 +25,42 @@ static const char *const UART_TYPE[] = {
|
||||
"software",
|
||||
};
|
||||
|
||||
// Port whose default pins match, for a board codegen has no pin data for; PIN_INVALID means not configured.
|
||||
static int8_t default_port(pin_size_t tx, pin_size_t rx) {
|
||||
#if LT_HW_UART0
|
||||
if ((tx == PIN_INVALID || tx == PIN_SERIAL0_TX) && (rx == PIN_INVALID || rx == PIN_SERIAL0_RX))
|
||||
return 0;
|
||||
#endif
|
||||
#if LT_HW_UART1
|
||||
if ((tx == PIN_INVALID || tx == PIN_SERIAL1_TX) && (rx == PIN_INVALID || rx == PIN_SERIAL1_RX))
|
||||
return 1;
|
||||
#endif
|
||||
#if LT_HW_UART2
|
||||
if ((tx == PIN_INVALID || tx == PIN_SERIAL2_TX) && (rx == PIN_INVALID || rx == PIN_SERIAL2_RX))
|
||||
return 2;
|
||||
#endif
|
||||
return -1;
|
||||
}
|
||||
|
||||
static SerialClass *hardware_serial(int8_t port) {
|
||||
switch (port) {
|
||||
#if LT_HW_UART0
|
||||
case 0:
|
||||
return &Serial0;
|
||||
#endif
|
||||
#if LT_HW_UART1
|
||||
case 1:
|
||||
return &Serial1;
|
||||
#endif
|
||||
#if LT_HW_UART2
|
||||
case 2:
|
||||
return &Serial2;
|
||||
#endif
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t LibreTinyUARTComponent::get_config() {
|
||||
uint16_t config = 0;
|
||||
|
||||
@@ -49,8 +85,8 @@ uint16_t LibreTinyUARTComponent::get_config() {
|
||||
}
|
||||
|
||||
void LibreTinyUARTComponent::setup() {
|
||||
int16_t tx_pin = tx_pin_ == nullptr ? -1 : tx_pin_->get_pin();
|
||||
int16_t rx_pin = rx_pin_ == nullptr ? -1 : rx_pin_->get_pin();
|
||||
const pin_size_t tx_pin = this->tx_pin_ == nullptr ? PIN_INVALID : this->tx_pin_->get_pin();
|
||||
const pin_size_t rx_pin = this->rx_pin_ == nullptr ? PIN_INVALID : this->rx_pin_->get_pin();
|
||||
|
||||
auto should_fallback_to_software_serial = [&]() -> bool {
|
||||
auto has_flags = [](InternalGPIOPin *pin, const gpio::Flags mask) -> bool {
|
||||
@@ -70,61 +106,49 @@ void LibreTinyUARTComponent::setup() {
|
||||
return false;
|
||||
};
|
||||
|
||||
if (false) { // NOLINT(readability-simplify-boolean-expr)
|
||||
return;
|
||||
}
|
||||
#if LT_HW_UART0
|
||||
else if ((tx_pin == -1 || tx_pin == PIN_SERIAL0_TX) && (rx_pin == -1 || rx_pin == PIN_SERIAL0_RX) &&
|
||||
!should_fallback_to_software_serial()) {
|
||||
this->serial_ = &Serial0;
|
||||
this->hardware_idx_ = 0;
|
||||
}
|
||||
#endif
|
||||
#if LT_HW_UART1
|
||||
else if ((tx_pin == -1 || tx_pin == PIN_SERIAL1_TX) && (rx_pin == -1 || rx_pin == PIN_SERIAL1_RX) &&
|
||||
!should_fallback_to_software_serial()) {
|
||||
this->serial_ = &Serial1;
|
||||
this->hardware_idx_ = 1;
|
||||
}
|
||||
#endif
|
||||
#if LT_HW_UART2
|
||||
else if ((tx_pin == -1 || tx_pin == PIN_SERIAL2_TX) && (rx_pin == -1 || rx_pin == PIN_SERIAL2_RX) &&
|
||||
!should_fallback_to_software_serial()) {
|
||||
this->serial_ = &Serial2;
|
||||
this->hardware_idx_ = 2;
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
#if LT_ARD_HAS_SOFTSERIAL
|
||||
if (this->rx_pin_) {
|
||||
this->rx_pin_->setup();
|
||||
}
|
||||
if (this->tx_pin_ && this->rx_pin_ != this->tx_pin_) {
|
||||
this->tx_pin_->setup();
|
||||
}
|
||||
bool tx_inverted = tx_pin_ != nullptr && tx_pin_->is_inverted();
|
||||
bool rx_inverted = rx_pin_ != nullptr && rx_pin_->is_inverted();
|
||||
this->serial_ = new SoftwareSerial(rx_pin, tx_pin, rx_inverted || tx_inverted);
|
||||
#else
|
||||
this->serial_ = &Serial;
|
||||
ESP_LOGE(TAG, " SoftwareSerial is not implemented for this chip. Only hardware pins are supported:");
|
||||
#if LT_HW_UART0
|
||||
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL0_TX, PIN_SERIAL0_RX);
|
||||
#endif
|
||||
#if LT_HW_UART1
|
||||
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL1_TX, PIN_SERIAL1_RX);
|
||||
#endif
|
||||
#if LT_HW_UART2
|
||||
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL2_TX, PIN_SERIAL2_RX);
|
||||
#endif
|
||||
this->mark_failed(LOG_STR("SoftwareSerial is not implemented for this chip."));
|
||||
return;
|
||||
#endif
|
||||
}
|
||||
|
||||
if (this->hardware_idx_ >= 0)
|
||||
// Codegen picks the port from the board's pin lists; a board it has no pin data for matches the defaults here.
|
||||
if (this->hardware_idx_ < 0)
|
||||
this->hardware_idx_ = default_port(tx_pin, rx_pin);
|
||||
SerialClass *hardware = should_fallback_to_software_serial() ? nullptr : hardware_serial(this->hardware_idx_);
|
||||
if (hardware != nullptr) {
|
||||
this->serial_ = hardware;
|
||||
libretiny::ensure_serial_handle(this->hardware_idx_);
|
||||
this->serial_->begin(this->baud_rate_, get_config());
|
||||
#ifdef USE_UART_LIBRETINY_PIN_ROUTING
|
||||
// Routes a port with pin choices to the configured pins (LibreTiny 1.12+, checked in codegen). setPins()
|
||||
// replaces a left-out pin (PIN_INVALID) with the port's default, so default-pin ports start as before.
|
||||
hardware->begin(this->baud_rate_, this->get_config(), rx_pin, tx_pin);
|
||||
#else
|
||||
hardware->begin(this->baud_rate_, this->get_config());
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
this->hardware_idx_ = -1;
|
||||
|
||||
#if LT_ARD_HAS_SOFTSERIAL
|
||||
if (this->rx_pin_) {
|
||||
this->rx_pin_->setup();
|
||||
}
|
||||
if (this->tx_pin_ && this->rx_pin_ != this->tx_pin_) {
|
||||
this->tx_pin_->setup();
|
||||
}
|
||||
bool tx_inverted = tx_pin_ != nullptr && tx_pin_->is_inverted();
|
||||
bool rx_inverted = rx_pin_ != nullptr && rx_pin_->is_inverted();
|
||||
this->serial_ = new SoftwareSerial(rx_pin, tx_pin, rx_inverted || tx_inverted);
|
||||
this->serial_->begin(this->baud_rate_, this->get_config());
|
||||
#else
|
||||
this->serial_ = &Serial;
|
||||
ESP_LOGE(TAG, " SoftwareSerial is not implemented for this chip. Only hardware pins are supported:");
|
||||
#if LT_HW_UART0
|
||||
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL0_TX, PIN_SERIAL0_RX);
|
||||
#endif
|
||||
#if LT_HW_UART1
|
||||
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL1_TX, PIN_SERIAL1_RX);
|
||||
#endif
|
||||
#if LT_HW_UART2
|
||||
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL2_TX, PIN_SERIAL2_RX);
|
||||
#endif
|
||||
this->mark_failed(LOG_STR("SoftwareSerial is not implemented for this chip."));
|
||||
#endif
|
||||
}
|
||||
|
||||
void LibreTinyUARTComponent::dump_config() {
|
||||
|
||||
@@ -25,6 +25,8 @@ class LibreTinyUARTComponent final : public UARTComponent, public Component {
|
||||
UARTFlushResult flush() override;
|
||||
|
||||
uint16_t get_config();
|
||||
/// Hardware port codegen picked from the board's pin lists.
|
||||
void set_hardware_port(int8_t port) { this->hardware_idx_ = port; }
|
||||
|
||||
HardwareSerial *get_hw_serial() { return this->serial_; }
|
||||
int8_t get_hw_serial_number() { return this->hardware_idx_; }
|
||||
|
||||
@@ -15,6 +15,9 @@ namespace esphome::uart {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "uart");
|
||||
|
||||
// GPIO32-47 (RP2350B) and GPIO64 (CYW43) are in no mask; a 32-bit shift by them is undefined.
|
||||
static constexpr bool pin_in_mask(uint8_t pin, uint32_t mask) { return pin < 32 && (mask & (1U << pin)) != 0; }
|
||||
|
||||
uint16_t RP2UartComponent::get_config() {
|
||||
uint16_t config = 0;
|
||||
|
||||
@@ -81,9 +84,9 @@ void RP2UartComponent::setup() {
|
||||
if (this->tx_pin_->is_inverted()) {
|
||||
ESP_LOGD(TAG, "An inverted TX pin %u can only be used with SerialPIO", this->tx_pin_->get_pin());
|
||||
} else {
|
||||
if (((1 << this->tx_pin_->get_pin()) & valid_tx_uart_0) != 0) {
|
||||
if (pin_in_mask(this->tx_pin_->get_pin(), valid_tx_uart_0)) {
|
||||
tx_hw = 0;
|
||||
} else if (((1 << this->tx_pin_->get_pin()) & valid_tx_uart_1) != 0) {
|
||||
} else if (pin_in_mask(this->tx_pin_->get_pin(), valid_tx_uart_1)) {
|
||||
tx_hw = 1;
|
||||
} else {
|
||||
ESP_LOGD(TAG, "TX pin %u can only be used with SerialPIO", this->tx_pin_->get_pin());
|
||||
@@ -95,9 +98,9 @@ void RP2UartComponent::setup() {
|
||||
if (this->rx_pin_->is_inverted()) {
|
||||
ESP_LOGD(TAG, "An inverted RX pin %u can only be used with SerialPIO", this->rx_pin_->get_pin());
|
||||
} else {
|
||||
if (((1 << this->rx_pin_->get_pin()) & valid_rx_uart_0) != 0) {
|
||||
if (pin_in_mask(this->rx_pin_->get_pin(), valid_rx_uart_0)) {
|
||||
rx_hw = 0;
|
||||
} else if (((1 << this->rx_pin_->get_pin()) & valid_rx_uart_1) != 0) {
|
||||
} else if (pin_in_mask(this->rx_pin_->get_pin(), valid_rx_uart_1)) {
|
||||
rx_hw = 1;
|
||||
} else {
|
||||
ESP_LOGD(TAG, "RX pin %u can only be used with SerialPIO", this->rx_pin_->get_pin());
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c
|
||||
from esphome.components.i2c import CONF_I2C_ID
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ADDRESS, CONF_ENABLE_PIN
|
||||
import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
AUTO_LOAD = ["sensor"]
|
||||
CODEOWNERS = ["@NonaSuomy"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
DOMAIN = "vl6180x"
|
||||
MULTI_CONF = True
|
||||
|
||||
CONF_VL6180X_ID = "vl6180x_id"
|
||||
|
||||
vl6180x_ns = cg.esphome_ns.namespace("vl6180x")
|
||||
VL6180XComponent = vl6180x_ns.class_(
|
||||
"VL6180XComponent", cg.PollingComponent, i2c.I2CDevice
|
||||
)
|
||||
|
||||
_request_enable_pin_slot = cg.slot_counter("VL6180X_ENABLE_PIN_COUNT")
|
||||
|
||||
DEFAULT_ADDRESS = 0x29
|
||||
|
||||
|
||||
def _validate_address(config: ConfigType) -> ConfigType:
|
||||
# The sensor always boots at 0x29; only an enable pin lets it move elsewhere
|
||||
if config[CONF_ADDRESS] != DEFAULT_ADDRESS and CONF_ENABLE_PIN not in config:
|
||||
raise cv.Invalid(
|
||||
f"An address other than 0x{DEFAULT_ADDRESS:02X} needs an enable_pin"
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(VL6180XComponent),
|
||||
cv.Optional(CONF_ENABLE_PIN): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
.extend(i2c.i2c_device_schema(DEFAULT_ADDRESS)),
|
||||
_validate_address,
|
||||
)
|
||||
|
||||
|
||||
def _final_validate(config: ConfigType) -> ConfigType:
|
||||
# With several sensors on one bus each needs its own enable_pin so it can be held in reset
|
||||
# while the others are re-addressed, and none may stay at 0x29, or a later sibling boots at
|
||||
# the same address and the re-address write reaches both chips.
|
||||
addresses = [
|
||||
conf[CONF_ADDRESS]
|
||||
for conf in fv.full_config.get()[DOMAIN]
|
||||
if conf[CONF_I2C_ID] == config[CONF_I2C_ID]
|
||||
]
|
||||
if len(addresses) < 2:
|
||||
return config
|
||||
if CONF_ENABLE_PIN not in config:
|
||||
raise cv.Invalid(
|
||||
"Every VL6180X on a shared I2C bus needs an enable_pin",
|
||||
path=[CONF_ENABLE_PIN],
|
||||
)
|
||||
address = config[CONF_ADDRESS]
|
||||
if address == DEFAULT_ADDRESS:
|
||||
raise cv.Invalid(
|
||||
f"VL6180X sensors sharing an I2C bus must all be re-addressed away "
|
||||
f"from 0x{DEFAULT_ADDRESS:02X}",
|
||||
path=[CONF_ADDRESS],
|
||||
)
|
||||
if addresses.count(address) > 1:
|
||||
raise cv.Invalid(
|
||||
f"Address 0x{address:02X} is used by more than one VL6180X on this bus",
|
||||
path=[CONF_ADDRESS],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _final_validate
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await i2c.new_i2c_component(config)
|
||||
if pin := await cg.add_pin(var.set_enable_pin, config.get(CONF_ENABLE_PIN)):
|
||||
_request_enable_pin_slot()
|
||||
cg.add(var.register_enable_pin(pin))
|
||||
@@ -0,0 +1,80 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import sensor
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_DISTANCE,
|
||||
CONF_GAIN,
|
||||
CONF_ILLUMINANCE,
|
||||
CONF_INTEGRATION_TIME,
|
||||
DEVICE_CLASS_DISTANCE,
|
||||
DEVICE_CLASS_ILLUMINANCE,
|
||||
STATE_CLASS_MEASUREMENT,
|
||||
UNIT_LUX,
|
||||
UNIT_MILLIMETER,
|
||||
)
|
||||
import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import CONF_VL6180X_ID, DOMAIN, VL6180XComponent
|
||||
|
||||
DEPENDENCIES = ["vl6180x"]
|
||||
|
||||
CONF_SCALER = "scaler"
|
||||
|
||||
# Gain factor to the SYSALS_ANALOGUE_GAIN code
|
||||
ALS_GAINS = {1: 6, 1.25: 5, 1.67: 4, 2.5: 3, 5: 2, 10: 1, 20: 0, 40: 7}
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(CONF_VL6180X_ID): cv.use_id(VL6180XComponent),
|
||||
cv.Optional(CONF_DISTANCE): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_MILLIMETER,
|
||||
accuracy_decimals=0,
|
||||
device_class=DEVICE_CLASS_DISTANCE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
).extend(
|
||||
{cv.Optional(CONF_SCALER, default=1): cv.one_of(1, 2, 3, int=True)}
|
||||
),
|
||||
cv.Optional(CONF_ILLUMINANCE): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_LUX,
|
||||
accuracy_decimals=1,
|
||||
device_class=DEVICE_CLASS_ILLUMINANCE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
).extend(
|
||||
{
|
||||
cv.Optional(CONF_GAIN, default=1): cv.enum(ALS_GAINS),
|
||||
cv.Optional(CONF_INTEGRATION_TIME, default="100ms"): cv.All(
|
||||
cv.positive_time_period_milliseconds,
|
||||
cv.Range(
|
||||
min=cv.TimePeriod(milliseconds=1),
|
||||
max=cv.TimePeriod(milliseconds=512),
|
||||
),
|
||||
),
|
||||
}
|
||||
),
|
||||
}
|
||||
),
|
||||
cv.has_at_least_one_key(CONF_DISTANCE, CONF_ILLUMINANCE),
|
||||
)
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = fv.unique_platform_key(
|
||||
domain=sensor.DOMAIN,
|
||||
platform=DOMAIN,
|
||||
keys=(CONF_VL6180X_ID,),
|
||||
message="Only one VL6180X sensor platform entry is allowed per hub",
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
hub = await cg.get_variable(config[CONF_VL6180X_ID])
|
||||
sensors = sensor.sub_sensors(config)
|
||||
if (distance_config := config.get(CONF_DISTANCE)) is not None:
|
||||
await sensors(CONF_DISTANCE, hub.set_distance_sensor)
|
||||
cg.add(hub.set_scaler(distance_config[CONF_SCALER]))
|
||||
if (illuminance_config := config.get(CONF_ILLUMINANCE)) is not None:
|
||||
await sensors(CONF_ILLUMINANCE, hub.set_illuminance_sensor)
|
||||
gain = illuminance_config[CONF_GAIN]
|
||||
time_ms = illuminance_config[CONF_INTEGRATION_TIME].total_milliseconds
|
||||
# The datasheet scale is 0.32 lux per count at 1x gain and 100 ms
|
||||
cg.add(hub.set_als(gain.enum_value, time_ms, 32.0 / (float(gain) * time_ms)))
|
||||
@@ -0,0 +1,267 @@
|
||||
#include "vl6180x.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::vl6180x {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "vl6180x");
|
||||
|
||||
static constexpr uint32_t MEASUREMENT_ID = 0;
|
||||
|
||||
static constexpr uint8_t DEFAULT_ADDRESS = 0x29;
|
||||
static constexpr uint8_t MODEL_ID = 0xB4;
|
||||
|
||||
static constexpr uint16_t REG_IDENTIFICATION_MODEL_ID = 0x000;
|
||||
static constexpr uint16_t REG_SYSTEM_INTERRUPT_CLEAR = 0x015;
|
||||
static constexpr uint16_t REG_SYSTEM_FRESH_OUT_OF_RESET = 0x016;
|
||||
static constexpr uint16_t REG_SYSRANGE_START = 0x018;
|
||||
static constexpr uint16_t REG_SYSRANGE_CROSSTALK_VALID_HEIGHT = 0x021;
|
||||
static constexpr uint16_t REG_SYSRANGE_PART_TO_PART_OFFSET = 0x024;
|
||||
static constexpr uint16_t REG_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D;
|
||||
static constexpr uint16_t REG_SYSALS_START = 0x038;
|
||||
static constexpr uint16_t REG_SYSALS_ANALOGUE_GAIN = 0x03F;
|
||||
static constexpr uint16_t REG_SYSALS_INTEGRATION_PERIOD = 0x040;
|
||||
static constexpr uint16_t REG_RESULT_RANGE_STATUS = 0x04D;
|
||||
static constexpr uint16_t REG_RESULT_ALS_STATUS = 0x04E;
|
||||
static constexpr uint16_t REG_RESULT_RANGE_VAL = 0x062;
|
||||
static constexpr uint16_t REG_RANGE_SCALING = 0x096;
|
||||
static constexpr uint16_t REG_I2C_DEVICE_ADDRESS = 0x212;
|
||||
|
||||
// RESULT_INTERRUPT_STATUS_GPIO: a new range sample in bits 2:0, a new ALS sample in bits 5:3
|
||||
static constexpr uint8_t RANGE_SAMPLE_READY = 0x04;
|
||||
static constexpr uint8_t ALS_SAMPLE_READY = 0x04 << 3;
|
||||
|
||||
// Range conversion is at most the 50 ms convergence time set below plus readout
|
||||
static constexpr uint32_t RANGE_TIME_MS = 70;
|
||||
static constexpr uint32_t ALS_READOUT_MARGIN_MS = 400;
|
||||
|
||||
// Indexed by the range scaler, 1x to 3x (AN4545)
|
||||
static constexpr uint16_t RANGE_SCALING_VALUES[] PROGMEM = {0, 253, 127, 84};
|
||||
|
||||
struct RegValue {
|
||||
uint16_t reg;
|
||||
uint8_t value;
|
||||
};
|
||||
|
||||
// Private settings written once after a power-on reset (AN4545 table 7)
|
||||
static constexpr RegValue MANDATORY_SETTINGS[] PROGMEM = {
|
||||
{0x0207, 0x01},
|
||||
{0x0208, 0x01},
|
||||
{0x0096, 0x00},
|
||||
{0x0097, 0xFD},
|
||||
{0x00E3, 0x00},
|
||||
{0x00E4, 0x04},
|
||||
{0x00E5, 0x02},
|
||||
{0x00E6, 0x01},
|
||||
{0x00E7, 0x03},
|
||||
{0x00F5, 0x02},
|
||||
{0x00D9, 0x05},
|
||||
{0x00DB, 0xCE},
|
||||
{0x00DC, 0x03},
|
||||
{0x00DD, 0xF8},
|
||||
{0x009F, 0x00},
|
||||
{0x00A3, 0x3C},
|
||||
{0x00B7, 0x00},
|
||||
{0x00BB, 0x3C},
|
||||
{0x00B2, 0x09},
|
||||
{0x00CA, 0x09},
|
||||
{0x0198, 0x01},
|
||||
{0x01B0, 0x17},
|
||||
{0x01AD, 0x00},
|
||||
{0x00FF, 0x05},
|
||||
{0x0100, 0x05},
|
||||
{0x0199, 0x05},
|
||||
{0x01A6, 0x1B},
|
||||
{0x01AC, 0x3E},
|
||||
{0x01A7, 0x1F},
|
||||
{0x0030, 0x00},
|
||||
{REG_SYSTEM_FRESH_OUT_OF_RESET, 0x00},
|
||||
};
|
||||
|
||||
// Recommended settings (AN4545 section 9), with GPIO1 left floating and new-sample interrupts flagged
|
||||
static constexpr RegValue DEFAULT_SETTINGS[] PROGMEM = {
|
||||
{0x010A, 0x30}, // averaging sample period
|
||||
{0x0031, 0xFF}, // repeat temperature calibration every 255 range measurements
|
||||
{0x002E, 0x01}, // run the first temperature calibration now
|
||||
{0x001C, 0x32}, // 50 ms maximum convergence time
|
||||
{0x0011, 0x20}, // GPIO1 off
|
||||
{0x0014, RANGE_SAMPLE_READY | ALS_SAMPLE_READY},
|
||||
{REG_SYSTEM_INTERRUPT_CLEAR, 0x07},
|
||||
};
|
||||
|
||||
template<size_t N> static bool write_settings(i2c::I2CDevice *device, const RegValue (&table)[N]) {
|
||||
for (const auto &entry : table) {
|
||||
RegValue setting;
|
||||
progmem_memcpy(&setting, &entry, sizeof(setting));
|
||||
if (!device->write_byte_reg16(setting.reg, setting.value))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
SlotList<GPIOPin *, VL6180X_ENABLE_PIN_COUNT> VL6180XComponent::enable_pins; // NOLINT
|
||||
#endif
|
||||
|
||||
void VL6180XComponent::setup() {
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
// Every sensor boots at 0x29, so all are held in reset and then released one at a time
|
||||
for (auto *pin : enable_pins) {
|
||||
pin->setup();
|
||||
pin->digital_write(false);
|
||||
}
|
||||
enable_pins.clear();
|
||||
if (this->enable_pin_ != nullptr) {
|
||||
this->enable_pin_->digital_write(true);
|
||||
delay(10);
|
||||
}
|
||||
#endif
|
||||
const uint8_t address = this->address_;
|
||||
this->set_i2c_address(DEFAULT_ADDRESS);
|
||||
uint8_t model_id = 0;
|
||||
const bool read_ok = this->read_byte_reg16(REG_IDENTIFICATION_MODEL_ID, &model_id);
|
||||
const bool ok = read_ok && model_id == MODEL_ID && this->init_() &&
|
||||
(address == DEFAULT_ADDRESS || this->write_byte_reg16(REG_I2C_DEVICE_ADDRESS, address));
|
||||
this->set_i2c_address(address);
|
||||
if (ok)
|
||||
return;
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
// A sensor left at 0x29 would answer for the next one released
|
||||
if (this->enable_pin_ != nullptr)
|
||||
this->enable_pin_->digital_write(false);
|
||||
#endif
|
||||
if (read_ok && model_id != MODEL_ID) {
|
||||
ESP_LOGE(TAG, "Wrong model ID 0x%02X", model_id);
|
||||
this->mark_failed(LOG_STR("Wrong model ID"));
|
||||
return;
|
||||
}
|
||||
this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
|
||||
}
|
||||
|
||||
bool VL6180XComponent::init_() {
|
||||
uint8_t fresh;
|
||||
uint8_t offset;
|
||||
if (!this->read_byte_reg16(REG_SYSTEM_FRESH_OUT_OF_RESET, &fresh) ||
|
||||
!this->read_byte_reg16(REG_SYSRANGE_PART_TO_PART_OFFSET, &offset))
|
||||
return false;
|
||||
// The factory offset is for 1x; a sensor that kept power through an MCU reboot already holds it divided by the
|
||||
// scaler from the last setup
|
||||
int16_t part_offset = static_cast<int8_t>(offset);
|
||||
if (fresh & 0x01) {
|
||||
if (!write_settings(this, MANDATORY_SETTINGS))
|
||||
return false;
|
||||
} else {
|
||||
uint8_t scaling[2];
|
||||
if (this->read_register16(REG_RANGE_SCALING, scaling, 2) != i2c::ERROR_OK)
|
||||
return false;
|
||||
const uint16_t value = encode_uint16(scaling[0], scaling[1]);
|
||||
for (uint8_t scaler = 2; scaler <= 3; scaler++) {
|
||||
if (value == progmem_read_uint16(&RANGE_SCALING_VALUES[scaler]))
|
||||
part_offset *= scaler;
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t period[2];
|
||||
put_be16(period, this->als_integration_time_ms_ - 1);
|
||||
uint8_t scaling[2];
|
||||
put_be16(scaling, progmem_read_uint16(&RANGE_SCALING_VALUES[this->scaler_]));
|
||||
return write_settings(this, DEFAULT_SETTINGS) &&
|
||||
this->write_byte_reg16(REG_SYSALS_ANALOGUE_GAIN, 0x40 | this->als_gain_code_) &&
|
||||
this->write_register16(REG_SYSALS_INTEGRATION_PERIOD, period, 2) == i2c::ERROR_OK &&
|
||||
this->write_register16(REG_RANGE_SCALING, scaling, 2) == i2c::ERROR_OK &&
|
||||
this->write_byte_reg16(REG_SYSRANGE_PART_TO_PART_OFFSET, static_cast<uint8_t>(part_offset / this->scaler_)) &&
|
||||
this->write_byte_reg16(REG_SYSRANGE_CROSSTALK_VALID_HEIGHT, 20 / this->scaler_) &&
|
||||
// SNR check, plus the early convergence estimate only at 1x, as in ST's API
|
||||
this->write_byte_reg16(REG_SYSRANGE_RANGE_CHECK_ENABLES, 0x10 | (this->scaler_ == 1 ? 0x01 : 0x00));
|
||||
}
|
||||
|
||||
void VL6180XComponent::update() {
|
||||
// A measurement still running means the update interval is shorter than one cycle
|
||||
if (this->measuring_)
|
||||
return;
|
||||
this->measuring_ = true;
|
||||
if (this->distance_sensor_ != nullptr) {
|
||||
this->start_range_();
|
||||
} else {
|
||||
this->start_als_();
|
||||
}
|
||||
}
|
||||
|
||||
void VL6180XComponent::start_range_() {
|
||||
if (!this->status_comm_check(this->write_byte_reg16(REG_SYSRANGE_START, 0x01))) {
|
||||
this->measuring_ = false;
|
||||
return;
|
||||
}
|
||||
this->set_timeout(MEASUREMENT_ID, RANGE_TIME_MS, [this]() { this->read_range_(); });
|
||||
}
|
||||
|
||||
void VL6180XComponent::read_range_() {
|
||||
uint8_t status[3]; // range status, ALS status, interrupt status
|
||||
uint8_t raw;
|
||||
if (!this->status_comm_check(this->read_register16(REG_RESULT_RANGE_STATUS, status, 3) == i2c::ERROR_OK) ||
|
||||
!this->status_comm_check((status[2] & 0x07) == RANGE_SAMPLE_READY) ||
|
||||
!this->status_comm_check(this->read_byte_reg16(REG_RESULT_RANGE_VAL, &raw) &&
|
||||
this->write_byte_reg16(REG_SYSTEM_INTERRUPT_CLEAR, 0x07))) {
|
||||
this->measuring_ = false;
|
||||
return;
|
||||
}
|
||||
const uint8_t error = status[0] >> 4;
|
||||
// Codes 1 to 5 are self-test faults (VCSEL or PLL); a fault keeps the warning until a whole cycle works
|
||||
if (error >= 1 && error <= 5) {
|
||||
ESP_LOGW(TAG, "Range self-test fault %u", error);
|
||||
PUBLISH_STATE(this->distance_sensor_, NAN);
|
||||
this->status_set_warning();
|
||||
this->measuring_ = false;
|
||||
return;
|
||||
}
|
||||
// Other codes mean no target or out of range
|
||||
if (error != 0) {
|
||||
ESP_LOGV(TAG, "Range error code %u", error);
|
||||
PUBLISH_STATE(this->distance_sensor_, NAN);
|
||||
} else {
|
||||
PUBLISH_STATE(this->distance_sensor_, static_cast<float>(raw * this->scaler_));
|
||||
}
|
||||
// With illuminance configured, read_als_() clears the warning once the whole cycle has worked
|
||||
if (this->illuminance_sensor_ != nullptr) {
|
||||
this->start_als_();
|
||||
} else {
|
||||
this->measuring_ = false;
|
||||
this->status_clear_warning();
|
||||
}
|
||||
}
|
||||
|
||||
void VL6180XComponent::start_als_() {
|
||||
if (!this->status_comm_check(this->write_byte_reg16(REG_SYSALS_START, 0x01))) {
|
||||
this->measuring_ = false;
|
||||
return;
|
||||
}
|
||||
this->set_timeout(MEASUREMENT_ID, this->als_integration_time_ms_ + ALS_READOUT_MARGIN_MS,
|
||||
[this]() { this->read_als_(); });
|
||||
}
|
||||
|
||||
void VL6180XComponent::read_als_() {
|
||||
this->measuring_ = false;
|
||||
uint8_t result[4]; // ALS status, interrupt status, ALS value
|
||||
if (!this->status_comm_check(this->read_register16(REG_RESULT_ALS_STATUS, result, 4) == i2c::ERROR_OK) ||
|
||||
!this->status_comm_check((result[1] & 0x38) == ALS_SAMPLE_READY) ||
|
||||
!this->status_comm_result(this->write_byte_reg16(REG_SYSTEM_INTERRUPT_CLEAR, 0x07)))
|
||||
return;
|
||||
// An overflow in bright light is a reading, not a fault
|
||||
if (result[0] >> 4) {
|
||||
ESP_LOGV(TAG, "ALS error code %u", result[0] >> 4);
|
||||
PUBLISH_STATE(this->illuminance_sensor_, NAN);
|
||||
return;
|
||||
}
|
||||
PUBLISH_STATE(this->illuminance_sensor_, encode_uint16(result[2], result[3]) * this->lux_per_count_);
|
||||
}
|
||||
|
||||
void VL6180XComponent::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "VL6180X:");
|
||||
LOG_I2C_DEVICE(this);
|
||||
LOG_PIN(" Enable Pin: ", this->enable_pin_);
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_SENSOR(" ", "Distance", this->distance_sensor_);
|
||||
LOG_SENSOR(" ", "Illuminance", this->illuminance_sensor_);
|
||||
}
|
||||
|
||||
} // namespace esphome::vl6180x
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
namespace esphome::vl6180x {
|
||||
|
||||
class VL6180XComponent final : public PollingComponent, public i2c::I2CDevice {
|
||||
SUB_SENSOR(distance)
|
||||
SUB_SENSOR(illuminance)
|
||||
|
||||
public:
|
||||
void setup() override;
|
||||
void update() override;
|
||||
void dump_config() override;
|
||||
|
||||
void set_enable_pin(GPIOPin *pin) { this->enable_pin_ = pin; }
|
||||
void set_scaler(uint8_t scaler) { this->scaler_ = scaler; }
|
||||
/// @param gain_code SYSALS_ANALOGUE_GAIN code of the gain
|
||||
/// @param integration_time_ms 1 to 512 ms
|
||||
/// @param lux_per_count lux of one ALS count at this gain and integration time
|
||||
void set_als(uint8_t gain_code, uint16_t integration_time_ms, float lux_per_count) {
|
||||
this->als_gain_code_ = gain_code;
|
||||
this->als_integration_time_ms_ = integration_time_ms;
|
||||
this->lux_per_count_ = lux_per_count;
|
||||
}
|
||||
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
/// The first setup() holds every registered sensor in reset, so each can be moved off 0x29 alone.
|
||||
static void register_enable_pin(GPIOPin *pin) { enable_pins.push_back(pin); }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
bool init_();
|
||||
void start_range_();
|
||||
void read_range_();
|
||||
void start_als_();
|
||||
void read_als_();
|
||||
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
static SlotList<GPIOPin *, VL6180X_ENABLE_PIN_COUNT> enable_pins; // NOLINT
|
||||
#endif
|
||||
|
||||
GPIOPin *enable_pin_{nullptr};
|
||||
float lux_per_count_{0.0f};
|
||||
uint16_t als_integration_time_ms_{100};
|
||||
uint8_t als_gain_code_{6};
|
||||
uint8_t scaler_{1};
|
||||
bool measuring_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::vl6180x
|
||||
@@ -1,7 +1,7 @@
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
import textwrap
|
||||
from typing import NamedTuple, TypedDict
|
||||
from typing import Literal, NamedTuple, TypedDict
|
||||
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
@@ -212,10 +212,18 @@ async def _cdc_acm_to_code() -> None:
|
||||
_cdc_acm_add_ports()
|
||||
|
||||
|
||||
def zephyr_setup_preferences() -> None:
|
||||
PreferenceStorage = Literal["NVS", "ZMS"]
|
||||
|
||||
|
||||
def zephyr_setup_preferences(storage: PreferenceStorage = "NVS") -> None:
|
||||
"""Store preferences through the settings subsystem.
|
||||
|
||||
`storage` picks the Zephyr storage backend: NVS for flash, ZMS for RRAM and MRAM.
|
||||
"""
|
||||
cg.add(zephyr_ns.setup_preferences())
|
||||
zephyr_add_prj_conf("SETTINGS", True)
|
||||
zephyr_add_prj_conf("NVS", True)
|
||||
zephyr_add_prj_conf(storage, True)
|
||||
zephyr_add_prj_conf(f"SETTINGS_{storage}", True)
|
||||
zephyr_add_prj_conf("FLASH_MAP", True)
|
||||
zephyr_add_prj_conf("FLASH", True)
|
||||
|
||||
|
||||
@@ -241,6 +241,7 @@
|
||||
#define REMOTE_BASE_DUMPER_COUNT 1
|
||||
#define REMOTE_BASE_LISTENER_COUNT 1
|
||||
#define SX1509_ON_KEY_COUNT 1
|
||||
#define VL6180X_ENABLE_PIN_COUNT 2
|
||||
#define WIEGAND_ON_KEY_COUNT 1
|
||||
#define WIEGAND_ON_RAW_COUNT 1
|
||||
#define WIEGAND_ON_TAG_COUNT 1
|
||||
@@ -334,6 +335,7 @@
|
||||
#define USE_PACKET_INTERFACE_HDLC
|
||||
#define USE_PACKET_INTERFACE_XXTEA
|
||||
#define USE_PCA9554_PCAL
|
||||
#define USE_PCM1863_SELECT
|
||||
#define USE_POWER_SUPPLY
|
||||
// Only defined by key-lookup preference backends; the slot-based platforms
|
||||
// (esp8266, rp2040) never set it in generated builds, and their preferences
|
||||
@@ -882,6 +884,7 @@
|
||||
#define USE_BK72XX_BLE_TRACKER
|
||||
#endif
|
||||
#define USE_LIBRETINY_RTC_PREFERENCES
|
||||
#define USE_UART_LIBRETINY_PIN_ROUTING
|
||||
#define LT_GPIO_RECOVER 1
|
||||
#define ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT 1
|
||||
#define ESPHOME_SUSPEND_LOOP
|
||||
|
||||
@@ -846,7 +846,9 @@ def convert_visual_temperatures(
|
||||
that needs ``full_config`` is left for final validation, which runs this again with it."""
|
||||
if (unit := entity_temperature_unit(config, full_config)) is None:
|
||||
return config
|
||||
visual = config[CONF_VISUAL]
|
||||
# A platform entry that only holds nested entities has no visual section of its own
|
||||
if (visual := config.get(CONF_VISUAL)) is None:
|
||||
return config
|
||||
convert_temperature_keys(visual, (CONF_MIN_TEMPERATURE, CONF_MAX_TEMPERATURE), unit)
|
||||
section = visual if delta_section is None else visual.get(delta_section)
|
||||
if section is not None:
|
||||
|
||||
+227
-13
@@ -1,11 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <type_traits>
|
||||
|
||||
// Out of line, one copy: the frame readers' rare paths call each other, and GCC would add specialised clones
|
||||
#if defined(__clang__)
|
||||
#define ESPHOME_FRAME_READER_COLD __attribute__((noinline))
|
||||
#else
|
||||
#define ESPHOME_FRAME_READER_COLD __attribute__((noinline, noclone))
|
||||
#endif
|
||||
|
||||
namespace esphome {
|
||||
|
||||
namespace frame_reader_detail {
|
||||
// A fold, not an array, so no header table lands in RAM on ESP8266
|
||||
template<uint8_t... HEADER> constexpr uint8_t header_byte(size_t i) {
|
||||
size_t j = 0;
|
||||
uint8_t r = 0;
|
||||
((r = (j++ == i) ? HEADER : r), ...);
|
||||
return r;
|
||||
}
|
||||
template<class FIRST, class... REST> struct First {
|
||||
using type = FIRST;
|
||||
};
|
||||
} // namespace frame_reader_detail
|
||||
|
||||
/// Collects fixed length binary frames of N bytes that start with the header bytes HEADER...; the binary twin of
|
||||
/// LineReader. Bytes before a header are skipped; checksums are left to the caller.
|
||||
template<size_t N, uint8_t... HEADER> class FrameReader {
|
||||
@@ -18,11 +40,12 @@ template<size_t N, uint8_t... HEADER> class FrameReader {
|
||||
/// Feed one byte; returns the completed frame, header included, valid until the next call, or nullptr.
|
||||
const uint8_t *feed(uint8_t c) {
|
||||
pos_t pos = this->pos_;
|
||||
if (pos < HEADER_LEN && c != header_byte(pos)) {
|
||||
if (pos < HEADER_LEN && c != frame_reader_detail::header_byte<HEADER...>(pos)) {
|
||||
// A later byte of the broken header, or c, may start the real one
|
||||
if (pos == 0)
|
||||
return nullptr;
|
||||
this->buf_[pos] = c;
|
||||
this->replay_(pos);
|
||||
return nullptr;
|
||||
return this->replay_(pos);
|
||||
}
|
||||
this->buf_[pos++] = c;
|
||||
if (pos < N) {
|
||||
@@ -44,24 +67,215 @@ template<size_t N, uint8_t... HEADER> class FrameReader {
|
||||
void resync() { this->replay_(N - 1); }
|
||||
|
||||
protected:
|
||||
// A fold, not an array, so no header table lands in RAM on ESP8266
|
||||
static constexpr uint8_t header_byte(size_t i) {
|
||||
size_t j = 0;
|
||||
uint8_t r = 0;
|
||||
((r = (j++ == i) ? HEADER : r), ...);
|
||||
return r;
|
||||
}
|
||||
|
||||
// Start over and feed buf_[1..last] again; never completes a frame as last < N
|
||||
void replay_(size_t last) {
|
||||
// Start over and feed buf_[1..last] again; never completes a frame as last < N, so it returns nullptr, which lets
|
||||
// feed() end in a tail call. Out of line, as feed() and replay_() call each other.
|
||||
const uint8_t *ESPHOME_FRAME_READER_COLD replay_(size_t last) {
|
||||
this->pos_ = 0;
|
||||
for (size_t i = 1; i <= last; i++) {
|
||||
this->feed(this->buf_[i]);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
uint8_t buf_[N];
|
||||
pos_t pos_{0};
|
||||
};
|
||||
|
||||
/// Length rules for FrameFormat: the frame length is known once KNOWN_AT bytes are collected, and get() returns it
|
||||
/// for the whole frame, header included. A component can pass its own type with these two members.
|
||||
/// One length byte at POS; ADD is added to give the whole frame length.
|
||||
template<size_t POS, size_t ADD = 0> struct FrameLengthU8 {
|
||||
static constexpr size_t KNOWN_AT = POS + 1;
|
||||
static constexpr size_t get(const uint8_t *buf) { return buf[POS] + ADD; }
|
||||
};
|
||||
/// Two length bytes at POS, high byte first.
|
||||
template<size_t POS, size_t ADD = 0> struct FrameLengthU16BE {
|
||||
static constexpr size_t KNOWN_AT = POS + 2;
|
||||
static constexpr size_t get(const uint8_t *buf) { return ((size_t(buf[POS]) << 8) | buf[POS + 1]) + ADD; }
|
||||
};
|
||||
/// Two length bytes at POS, low byte first.
|
||||
template<size_t POS, size_t ADD = 0> struct FrameLengthU16LE {
|
||||
static constexpr size_t KNOWN_AT = POS + 2;
|
||||
static constexpr size_t get(const uint8_t *buf) { return (buf[POS] | (size_t(buf[POS + 1]) << 8)) + ADD; }
|
||||
};
|
||||
/// A frame type that always has LEN bytes.
|
||||
template<size_t LEN> struct FrameFixedLength {
|
||||
static constexpr size_t KNOWN_AT = 1;
|
||||
static constexpr size_t get(const uint8_t * /*buf*/) { return LEN; }
|
||||
};
|
||||
|
||||
/// One frame type for LengthFrameReader: frames that start with the header bytes HEADER... and whose length follows
|
||||
/// LENGTH, one of the FrameLength types above.
|
||||
template<class LENGTH, uint8_t... HEADER> struct FrameFormat {
|
||||
using Length = LENGTH;
|
||||
static constexpr size_t HEADER_LEN = sizeof...(HEADER);
|
||||
static constexpr uint8_t FIRST = frame_reader_detail::header_byte<HEADER...>(0);
|
||||
// Bytes collected when the length is checked; also the shortest frame
|
||||
static constexpr size_t MIN_LEN = std::max<size_t>({LENGTH::KNOWN_AT, HEADER_LEN, 2});
|
||||
static_assert(HEADER_LEN >= 1 && HEADER_LEN <= 8, "FrameFormat takes 1 to 8 header bytes");
|
||||
static_assert(LENGTH::KNOWN_AT == 1 || LENGTH::KNOWN_AT > HEADER_LEN, "The length field must follow the header");
|
||||
static constexpr uint8_t header_byte(size_t i) { return frame_reader_detail::header_byte<HEADER...>(i); }
|
||||
};
|
||||
|
||||
/// Collects binary frames that give their own length, of up to N bytes, in one or more FrameFormats; the first byte
|
||||
/// picks the format, so each format needs a different first header byte. Bytes before a header are skipped. A length
|
||||
/// that ends the frame before its length field, or is longer than N, is not a frame, and the reader looks for a
|
||||
/// header after its first byte. Checksums, footers and a minimum length that covers them are left to the caller,
|
||||
/// which passes a handler that returns false for a frame it rejects:
|
||||
///
|
||||
/// this->reader_.feed(c, [this](const uint8_t *frame, size_t len) { return this->handle_frame_(frame, len); });
|
||||
template<size_t N, class... FORMATS> class LengthFrameReader {
|
||||
using pos_t = std::conditional_t<(N <= 0xFF), uint8_t, uint16_t>;
|
||||
static_assert(sizeof...(FORMATS) >= 1, "LengthFrameReader takes at least one FrameFormat");
|
||||
static_assert(N >= 2 && N <= 0xFFFF, "LengthFrameReader size out of range");
|
||||
static constexpr bool distinct_first() {
|
||||
const uint8_t first[] = {FORMATS::FIRST...};
|
||||
for (size_t i = 0; i < sizeof...(FORMATS); i++) {
|
||||
for (size_t j = i + 1; j < sizeof...(FORMATS); j++) {
|
||||
if (first[i] == first[j])
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
static_assert(distinct_first(), "Each FrameFormat needs a different first header byte");
|
||||
|
||||
public:
|
||||
/// Feed one byte; calls handle(frame, length) for each frame it completes, header included. A rejected frame
|
||||
/// (handle returns false) is searched for frames inside it and after it, which go to handle the same way.
|
||||
template<class F> inline void __attribute__((always_inline)) feed(uint8_t c, F &&handle) {
|
||||
if (const uint8_t *frame = this->feed(c))
|
||||
this->drain_(frame, handle);
|
||||
}
|
||||
|
||||
/// For a partial frame left too long without a byte, which a corrupt length can cause: give up on it, and pass the
|
||||
/// frames it held back to handle.
|
||||
template<class F> void flush(F &&handle) {
|
||||
while (this->pos_ != 0)
|
||||
this->drain_(this->resync(), handle);
|
||||
}
|
||||
|
||||
/// Lower level: feed one byte; returns the completed frame, valid until the next call, or nullptr. After it, call
|
||||
/// next() when the frame is handled or resync() when it is rejected, until they return nullptr.
|
||||
inline const uint8_t *__attribute__((always_inline)) feed(uint8_t c) {
|
||||
// Most bytes are in the middle of a frame whose length is known, and not its last byte
|
||||
const pos_t pos = this->pos_;
|
||||
if (pos + 1u < this->end_) {
|
||||
this->buf_[pos] = c;
|
||||
this->pos_ = pos + 1;
|
||||
return nullptr;
|
||||
}
|
||||
return this->feed_edge_(c);
|
||||
}
|
||||
|
||||
/// Length of the frame feed(), resync() or next() returned; valid until the next call on the reader.
|
||||
size_t frame_length() const {
|
||||
if constexpr (sizeof...(FORMATS) == 1) {
|
||||
return frame_reader_detail::First<FORMATS...>::type::Length::get(this->buf_);
|
||||
} else {
|
||||
const uint8_t first = this->buf_[0];
|
||||
size_t len = 0;
|
||||
(void) ((first == FORMATS::FIRST && ((len = FORMATS::Length::get(this->buf_)), true)) || ...);
|
||||
return len;
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of bytes of the partial frame; 0 after a frame is returned and while looking for a header.
|
||||
size_t length() const { return this->pos_; }
|
||||
|
||||
/// Forget the partial frame and any held bytes, and look for a header from the next byte.
|
||||
void reset() {
|
||||
this->pos_ = 0;
|
||||
this->end_ = 0;
|
||||
this->held_end_ = 0;
|
||||
}
|
||||
|
||||
/// Lower level: for a rejected frame, or a partial one: drop its first byte and look for a frame in the rest.
|
||||
/// Returns the next frame found, or nullptr. Does nothing when no frame is held and nothing is collected.
|
||||
const uint8_t *resync() { return this->replay_(1, this->pos_ != 0 ? this->pos_ : this->held_end_); }
|
||||
|
||||
/// Lower level: after handling a frame, look for the next one in the bytes that followed it in a resync().
|
||||
/// Returns that frame, or nullptr once they are used up.
|
||||
const uint8_t *next() { return this->replay_(this->frame_length(), this->held_end_); }
|
||||
|
||||
protected:
|
||||
template<class F> void ESPHOME_FRAME_READER_COLD drain_(const uint8_t *frame, F &handle) {
|
||||
while (frame != nullptr)
|
||||
frame = handle(frame, this->frame_length()) ? this->next() : this->resync();
|
||||
}
|
||||
|
||||
// A header byte, the bytes up to the length, the last byte of a frame, or a byte between frames
|
||||
const uint8_t *ESPHOME_FRAME_READER_COLD feed_edge_(uint8_t c) {
|
||||
const pos_t pos = this->pos_;
|
||||
if (pos == 0) {
|
||||
this->held_end_ = 0;
|
||||
const bool header = ((c == FORMATS::FIRST) || ...);
|
||||
if (header) {
|
||||
this->buf_[0] = c;
|
||||
this->pos_ = 1;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
if constexpr (sizeof...(FORMATS) == 1) {
|
||||
return this->feed_as_<FORMATS...>(pos, c);
|
||||
} else {
|
||||
const uint8_t first = this->buf_[0];
|
||||
const uint8_t *frame = nullptr;
|
||||
(void) ((first == FORMATS::FIRST && ((frame = this->feed_as_<FORMATS>(pos, c)), true)) || ...);
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
|
||||
template<class F> const uint8_t *feed_as_(pos_t pos, uint8_t c) {
|
||||
if (pos < F::HEADER_LEN && c != F::header_byte(pos)) {
|
||||
// A later byte of the broken header, or c, may start the real one
|
||||
this->buf_[pos] = c;
|
||||
return this->replay_(1, pos + 1);
|
||||
}
|
||||
this->buf_[pos++] = c;
|
||||
if (pos == F::MIN_LEN) {
|
||||
const size_t len = F::Length::get(this->buf_);
|
||||
if (len < F::MIN_LEN || len > N)
|
||||
return this->replay_(1, pos);
|
||||
this->end_ = len;
|
||||
}
|
||||
if (pos == this->end_) {
|
||||
this->pos_ = 0;
|
||||
this->end_ = 0;
|
||||
this->held_end_ = pos;
|
||||
return this->buf_;
|
||||
}
|
||||
this->pos_ = pos;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Start over and feed buf_[from..to) again; writes stay behind the read position. On a completed frame, moves the
|
||||
// bytes not fed yet right behind it, for next() and resync(), and returns it.
|
||||
const uint8_t *ESPHOME_FRAME_READER_COLD replay_(size_t from, size_t to) {
|
||||
this->pos_ = 0;
|
||||
this->end_ = 0;
|
||||
this->held_end_ = 0;
|
||||
for (size_t i = from; i < to; i++) {
|
||||
if (this->feed_edge_(this->buf_[i]) == nullptr)
|
||||
continue;
|
||||
// A nested replay may already have put bytes of its own behind the frame
|
||||
const size_t held = this->held_end_;
|
||||
const size_t rest = to - i - 1;
|
||||
std::memmove(this->buf_ + held, this->buf_ + i + 1, rest);
|
||||
this->held_end_ = held + rest;
|
||||
return this->buf_;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
uint8_t buf_[N];
|
||||
pos_t pos_{0};
|
||||
// Length of the frame being collected once its length is known; 0 otherwise
|
||||
pos_t end_{0};
|
||||
// While a frame is held: end of the frame plus the bytes after it that are not fed yet; 0 otherwise
|
||||
pos_t held_end_{0};
|
||||
};
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#undef ESPHOME_FRAME_READER_COLD
|
||||
@@ -10,7 +10,7 @@ dependencies:
|
||||
esphome/micro-decoder:
|
||||
version: 0.4.0
|
||||
esphome/micro-flac:
|
||||
version: 0.3.0
|
||||
version: 0.3.1
|
||||
esphome/micro-mp3:
|
||||
version: 0.4.0
|
||||
esphome/micro-opus:
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ bleak==3.1.0
|
||||
smpclient==7.4.0
|
||||
# smp 4.2+ needs cbor2 6+, which ships no Intel macOS wheels (arm64 only).
|
||||
smp==4.3.0; platform_system != "Darwin" or platform_machine != "x86_64"
|
||||
smp==4.2.0; platform_system == "Darwin" and platform_machine == "x86_64"
|
||||
smp==4.3.0; platform_system == "Darwin" and platform_machine == "x86_64"
|
||||
requests==2.34.2
|
||||
py7zr==1.1.4
|
||||
platformdirs==4.14.5 # native esp-idf toolchain global cache dir
|
||||
|
||||
@@ -20,6 +20,12 @@ static constexpr uint8_t FRAME_30[30] = {0xAA, 0xFF, 0x03, 0x00, 0x0E, 0x03, 0xB
|
||||
static constexpr uint8_t ULTRASONIC_NOISY[] = {0x12, 0xFF, 0x07, 0xA1, 0xA7, 0x34, 0xFF, 0xFF, 0x07, 0xA1, 0xA7,
|
||||
0x00, 0xFF, 0x07, 0xA1, 0xA7, 0x56, 0xFF, 0x07, 0xA1, 0xA7};
|
||||
|
||||
// Pioneer WT shaped frames (A5 01 header, whole-frame length at byte 7) of 12, 20 and 12 bytes among noise
|
||||
static constexpr uint8_t LENGTH_FRAMES[] = {0x00, 0xA5, 0x01, 0x01, 0x23, 0x00, 0xA5, 0x00, 0x0C, 0x11, 0x22, 0x33,
|
||||
0x44, 0xA5, 0x01, 0x01, 0x23, 0x00, 0xA5, 0x00, 0x14, 0x11, 0x22, 0x33,
|
||||
0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0x7E, 0xA5, 0x01,
|
||||
0x01, 0x23, 0x00, 0xA5, 0x00, 0x0C, 0x11, 0x22, 0x33, 0x44};
|
||||
|
||||
// --- LineReader: one GGA sentence fed byte by byte ---
|
||||
|
||||
static void LineReader_NmeaLine(benchmark::State &state) {
|
||||
@@ -93,4 +99,28 @@ static void FrameReader_UltrasonicNoisy(benchmark::State &state) {
|
||||
}
|
||||
BENCHMARK(FrameReader_UltrasonicNoisy);
|
||||
|
||||
// --- LengthFrameReader: frames of different lengths among noise ---
|
||||
|
||||
static void LengthFrameReader_MixedFrames(benchmark::State &state) {
|
||||
LengthFrameReader<255, FrameFormat<FrameLengthU8<7>, 0xA5, 0x01>> reader;
|
||||
const uint8_t *bytes = LENGTH_FRAMES;
|
||||
uint32_t frames = 0;
|
||||
|
||||
for (auto _ : state) {
|
||||
benchmark::DoNotOptimize(bytes);
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
for (size_t j = 0; j < sizeof(LENGTH_FRAMES); j++) {
|
||||
const uint8_t *frame = reader.feed(bytes[j]);
|
||||
if (frame == nullptr)
|
||||
continue;
|
||||
benchmark::DoNotOptimize(frame);
|
||||
frames++;
|
||||
}
|
||||
}
|
||||
benchmark::DoNotOptimize(frames);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LengthFrameReader_MixedFrames);
|
||||
|
||||
} // namespace esphome::benchmarks
|
||||
@@ -222,6 +222,20 @@ def test_a_resolved_unit_waits_for_the_full_config() -> None:
|
||||
assert config[CONF_VISUAL][CONF_MIN_TEMPERATURE] == pytest.approx(59.0)
|
||||
|
||||
|
||||
def test_final_validate_skips_a_platform_that_only_holds_nested_climates() -> None:
|
||||
"""A hub platform may put each of its climates under a key of one platform entry."""
|
||||
nested = climate_schema(climate_ns.class_("NestedClimate", Climate))
|
||||
platform_schema = cv.Schema({cv.Optional("zone_1"): nested})
|
||||
config = platform_schema(
|
||||
{"zone_1": {CONF_NAME: "Zone 1", CONF_VISUAL: {CONF_MIN_TEMPERATURE: "50°F"}}}
|
||||
)
|
||||
# The platform entry itself is not a climate and has no visual section
|
||||
assert CONF_VISUAL not in config
|
||||
_final_validate([config])
|
||||
# The nested climate was converted by its own schema
|
||||
assert config["zone_1"][CONF_VISUAL][CONF_MIN_TEMPERATURE] == pytest.approx(10.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("use_fahrenheit", "cn105_lines"),
|
||||
[
|
||||
|
||||
@@ -8,11 +8,16 @@ from esphome.components.npm1300 import (
|
||||
CHARGER_SCHEMA,
|
||||
NPM1300_UNSET,
|
||||
OUTPUT_VOLTAGE,
|
||||
THERMISTOR_NONE,
|
||||
VBUS_CURRENT_LIMIT,
|
||||
_charger_config,
|
||||
_check_thermistor,
|
||||
_config,
|
||||
_output_config,
|
||||
_termination_voltage_code,
|
||||
_thermistor_resistance,
|
||||
_vbus_current_limit_code,
|
||||
thermistor_beta,
|
||||
)
|
||||
from esphome.const import CONF_MODE, CONF_VOLTAGE
|
||||
from esphome.cpp_generator import StructInitializer
|
||||
@@ -54,10 +59,35 @@ def test_termination_voltage_gap_rejected(voltage: str) -> None:
|
||||
CHARGER_SCHEMA({"charge_current": "100mA", "termination_voltage": voltage})
|
||||
|
||||
|
||||
def test_warm_termination_defaults_to_termination() -> None:
|
||||
def test_warm_termination_defaults_to_reset_value() -> None:
|
||||
fields = _charger({"charge_current": "100mA", "termination_voltage": "4.1V"})
|
||||
assert fields["termination_voltage"] == "6"
|
||||
assert fields["warm_termination_voltage"] == "6"
|
||||
assert fields["warm_termination_voltage"] == "2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config", "warns"),
|
||||
[
|
||||
({"termination_voltage": "4.2V"}, True),
|
||||
({"termination_voltage": "3.5V"}, False),
|
||||
({"termination_voltage": "3.6V"}, False),
|
||||
({}, False),
|
||||
({"termination_voltage": "4.2V", "warm_termination_voltage": "4.0V"}, False),
|
||||
],
|
||||
)
|
||||
def test_warm_termination_default_warning(
|
||||
config: ConfigType, warns: bool, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
CHARGER_SCHEMA(config)
|
||||
assert ("warm_termination_voltage" in caplog.text) is warns
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("termination", "code"), [("3.5V", "0"), ("3.55V", "1")])
|
||||
def test_warm_termination_default_not_above_termination(
|
||||
termination: str, code: str
|
||||
) -> None:
|
||||
fields = _charger({"termination_voltage": termination})
|
||||
assert fields["warm_termination_voltage"] == code
|
||||
|
||||
|
||||
def test_warm_termination_code() -> None:
|
||||
@@ -112,3 +142,66 @@ def test_vbus_current_limit_code(limit: str, code: int) -> None:
|
||||
def test_vbus_current_limit_rejected(limit: str) -> None:
|
||||
with pytest.raises(cv.Invalid):
|
||||
VBUS_CURRENT_LIMIT(limit)
|
||||
|
||||
|
||||
def test_charger_needs_thermistor() -> None:
|
||||
with pytest.raises(cv.Invalid, match="thermistor_resistance"):
|
||||
_check_thermistor({"charger": {}})
|
||||
config = {"charger": {}, "thermistor_resistance": THERMISTOR_NONE}
|
||||
assert _check_thermistor(config) is config
|
||||
|
||||
|
||||
@pytest.mark.parametrize("resistance", [None, THERMISTOR_NONE])
|
||||
def test_thermistor_beta_needs_resistance(resistance: str | None) -> None:
|
||||
config = {"thermistor_beta": 3380}
|
||||
if resistance is not None:
|
||||
config["thermistor_resistance"] = resistance
|
||||
with pytest.raises(cv.Invalid, match="thermistor_beta"):
|
||||
_check_thermistor(config)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("resistance", "beta"), [(10000.0, 3380), (47000.0, 4050), (100000.0, 4250)]
|
||||
)
|
||||
def test_thermistor_beta_default(resistance: float, beta: int) -> None:
|
||||
assert thermistor_beta({"thermistor_resistance": resistance}) == beta
|
||||
|
||||
|
||||
def test_thermistor_beta_configured() -> None:
|
||||
config = {"thermistor_resistance": 47000.0, "thermistor_beta": 3950}
|
||||
assert thermistor_beta(config) == 3950
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("resistance", "code", "beta"),
|
||||
[
|
||||
(None, str(NPM1300_UNSET), "0"),
|
||||
(THERMISTOR_NONE, "0", "0"),
|
||||
(100000.0, "3", "4250"),
|
||||
],
|
||||
)
|
||||
def test_config_thermistor(
|
||||
resistance: str | float | None, code: str, beta: str
|
||||
) -> None:
|
||||
config = {} if resistance is None else {"thermistor_resistance": resistance}
|
||||
fields = _fields(_config(config))
|
||||
assert fields["thermistor"] == code
|
||||
assert fields["thermistor_beta"] == beta
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "result"),
|
||||
[
|
||||
("10kOhm", 10000.0),
|
||||
("0.047MOhm", 47000.0),
|
||||
("100000", 100000.0),
|
||||
("None", "none"),
|
||||
],
|
||||
)
|
||||
def test_thermistor_resistance(value: str, result: float | str) -> None:
|
||||
assert _thermistor_resistance(value) == result
|
||||
|
||||
|
||||
def test_thermistor_resistance_rejected() -> None:
|
||||
with pytest.raises(cv.Invalid, match="10kOhm, 47kOhm, 100kOhm or none"):
|
||||
_thermistor_resistance("22kOhm")
|
||||
@@ -0,0 +1,15 @@
|
||||
esphome:
|
||||
name: libretiny-pin-choices
|
||||
|
||||
rtl87xx:
|
||||
board: bw15
|
||||
|
||||
uart:
|
||||
- id: routed_uart
|
||||
tx_pin: PA03
|
||||
rx_pin: PA02
|
||||
baud_rate: 9600
|
||||
- id: default_uart
|
||||
tx_pin: PA14
|
||||
rx_pin: PA13
|
||||
baud_rate: 9600
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Tests for picking a LibreTiny hardware UART from the board's pin lists."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome import config, yaml_util
|
||||
from esphome.core import CORE
|
||||
|
||||
CONFIG = """
|
||||
esphome:
|
||||
name: libretiny-uart-pins
|
||||
rtl87xx:
|
||||
board: {board}
|
||||
{framework}
|
||||
uart:
|
||||
{uart}
|
||||
"""
|
||||
|
||||
|
||||
def _write_config(path: Path, board: str, framework: str, pins: str) -> None:
|
||||
"""One UART with these pins, or the pins text as is when it already lists entries."""
|
||||
uart = pins if pins.startswith(" - ") else f" baud_rate: 9600\n{pins}"
|
||||
path.write_text(
|
||||
CONFIG.format(board=board, framework=framework, uart=uart), encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def test_port_with_pin_choices_is_routed(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
"""The port is picked in codegen, and only a port with pin choices gets its pins passed."""
|
||||
main_cpp = generate_main(component_config_path("libretiny_pin_choices.yaml"))
|
||||
|
||||
assert "routed_uart->set_hardware_port(1);" in main_cpp
|
||||
assert "default_uart->set_hardware_port(0);" in main_cpp
|
||||
assert any(
|
||||
define.name == "USE_UART_LIBRETINY_PIN_ROUTING" for define in CORE.defines
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("board", "framework", "pins", "error"),
|
||||
[
|
||||
pytest.param(
|
||||
"bw15", "", " tx_pin: PA03\n rx_pin: PA02", None, id="second_pair"
|
||||
),
|
||||
pytest.param(
|
||||
"bw15", "", " tx_pin: PA01\n rx_pin: PA02", None, id="mixed_pair"
|
||||
),
|
||||
pytest.param("bw15", "", " tx_pin: PA14", None, id="default_pins_tx_only"),
|
||||
pytest.param(
|
||||
"bw15",
|
||||
"",
|
||||
" tx_pin: PA03",
|
||||
"UART1 of board bw15 has no default RX pin, so it needs rx_pin",
|
||||
id="pin_choices_tx_only",
|
||||
),
|
||||
pytest.param(
|
||||
"bw15",
|
||||
"",
|
||||
" tx_pin: PA17\n rx_pin: PA18",
|
||||
"UART1: TX=1/3, RX=0/2",
|
||||
id="no_uart_on_pins",
|
||||
),
|
||||
pytest.param(
|
||||
"bw15",
|
||||
" framework:\n version: 1.11.0",
|
||||
" tx_pin: PA03\n rx_pin: PA02",
|
||||
"needs LibreTiny 1.12.0 or later",
|
||||
id="old_libretiny",
|
||||
),
|
||||
pytest.param(
|
||||
"bw15",
|
||||
"",
|
||||
" - id: uart_a\n baud_rate: 9600\n tx_pin: PA01\n rx_pin: PA00\n"
|
||||
" - id: uart_b\n baud_rate: 9600\n tx_pin: PA03\n rx_pin: PA02",
|
||||
"already uses hardware UART1 of board bw15",
|
||||
id="two_entries_one_port",
|
||||
),
|
||||
# Pin flags force SoftwareSerial on RTL8710B, so these do not share hardware UART0
|
||||
pytest.param(
|
||||
"generic-rtl8710bn-2mb-788k",
|
||||
"",
|
||||
" - id: uart_a\n baud_rate: 9600\n tx_pin:\n number: PA23\n"
|
||||
" mode:\n output: true\n open_drain: true\n"
|
||||
" - id: uart_b\n baud_rate: 9600\n rx_pin:\n number: PA18\n"
|
||||
" mode:\n input: true\n pullup: true",
|
||||
None,
|
||||
id="software_serial_flags",
|
||||
),
|
||||
# UART1 TX has a default pin on this board; only RX has choices
|
||||
pytest.param("wbru", "", " rx_pin: PA02", None, id="default_tx_rx_only"),
|
||||
pytest.param(
|
||||
"wbru",
|
||||
"",
|
||||
" tx_pin: PA03",
|
||||
"UART1 of board wbru has no default RX pin, so it needs rx_pin",
|
||||
id="default_tx_tx_only",
|
||||
),
|
||||
# RTL8710B falls back to SoftwareSerial
|
||||
pytest.param(
|
||||
"generic-rtl8710bn-2mb-788k",
|
||||
"",
|
||||
" tx_pin: PA05\n rx_pin: PA12",
|
||||
None,
|
||||
id="software_serial",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_pins_are_checked_against_the_board(
|
||||
board: str, framework: str, pins: str, error: str | None, tmp_path: Path
|
||||
) -> None:
|
||||
path = tmp_path / "uart.yaml"
|
||||
_write_config(path, board, framework, pins)
|
||||
CORE.config_path = path
|
||||
result = config.validate_config(yaml_util.load_yaml(path), {})
|
||||
errors = [str(err) for err in result.errors]
|
||||
if error is None:
|
||||
assert errors == []
|
||||
else:
|
||||
assert any(error in err for err in errors), errors
|
||||
|
||||
|
||||
def test_hardware_uarts_of_a_board_with_pin_choices(tmp_path: Path) -> None:
|
||||
"""The libretiny component reports each UART's pins and whether they are choices."""
|
||||
from esphome.components.libretiny import HardwareUart, get_hardware_uarts
|
||||
|
||||
path = tmp_path / "uart.yaml"
|
||||
_write_config(path, "bw15", "", " tx_pin: PA14")
|
||||
CORE.config_path = path
|
||||
config.validate_config(yaml_util.load_yaml(path), {})
|
||||
assert get_hardware_uarts() == [
|
||||
HardwareUart(0, (14,), (13,), False, False),
|
||||
HardwareUart(1, (1, 3), (0, 2), True, True),
|
||||
HardwareUart(2, (16,), (15,), False, False),
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# bmi270 declares i2c on its motion platform, which the harness does not walk
|
||||
manifest.dependencies = manifest.dependencies + ["i2c", "motion"]
|
||||
@@ -36,7 +36,6 @@ sensor:
|
||||
name: "BMI270 Accel Z"
|
||||
accuracy_decimals: 4
|
||||
|
||||
# Gyroscope axes (unit: °/s)
|
||||
- platform: motion
|
||||
motion_id: bmi270_motion
|
||||
type: gyroscope_x
|
||||
@@ -76,21 +75,11 @@ motion:
|
||||
- platform: bmi270
|
||||
id: bmi270_motion
|
||||
i2c_id: i2c_bus
|
||||
# Accelerometer full-scale range: 2G | 4G | 8G | 16G
|
||||
accelerometer_range: 4G
|
||||
|
||||
# Accelerometer output data rate: 12_5HZ | 25HZ | 50HZ | 100HZ |
|
||||
# 200HZ | 400HZ | 800HZ | 1600HZ
|
||||
accelerometer_odr: 100HZ
|
||||
|
||||
# Gyroscope full-scale range: 125DPS | 250DPS | 500DPS | 1000DPS | 2000DPS
|
||||
gyroscope_range: 2000DPS
|
||||
|
||||
# Gyroscope output data rate: 25HZ | 50HZ | 100HZ | 200HZ |
|
||||
# 400HZ | 800HZ | 1600HZ | 3200HZ
|
||||
gyroscope_odr: 200HZ
|
||||
accelerometer_range: 8G
|
||||
accelerometer_odr: 200HZ
|
||||
gyroscope_range: 1000DPS
|
||||
gyroscope_odr: 400HZ
|
||||
aux_device: BMM150
|
||||
aux_address: 0x10
|
||||
axis_map:
|
||||
x: y
|
||||
y: x
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#include <gmock/gmock.h>
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/bmi270/bmm150_aux.h"
|
||||
|
||||
namespace esphome::bmi270::bmm150::testing {
|
||||
|
||||
// The axis decode before it used encode_value_le, kept as the reference
|
||||
static BMM150Data reference_convert(const BMM150Trim &trim, const uint8_t *raw) {
|
||||
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),
|
||||
.z = bmm150_compensate_z(trim, z, rhall),
|
||||
};
|
||||
}
|
||||
|
||||
TEST(BMM150Convert, MatchesTheReferenceForEveryWordOfEachField) {
|
||||
const BMM150Trim trim{.x1 = 0,
|
||||
.y1 = 0,
|
||||
.x2 = 26,
|
||||
.y2 = 26,
|
||||
.xy2 = -3,
|
||||
.xy1 = 29,
|
||||
.z2 = 760,
|
||||
.z3 = 0,
|
||||
.z4 = 0,
|
||||
.z1 = 24786,
|
||||
.xyz1 = 7101};
|
||||
// Sweep one field through every 16-bit value while the others hold mid-range readings
|
||||
for (int field = 0; field < 4; field++) {
|
||||
for (uint32_t word = 0; word <= 0xFFFF; word++) {
|
||||
uint8_t raw[8] = {0x10, 0x12, 0x20, 0xF0, 0x30, 0x08, 0x40, 0x1A};
|
||||
raw[2 * field] = word & 0xFF;
|
||||
raw[2 * field + 1] = word >> 8;
|
||||
const BMM150Data got = bmm150_convert(trim, raw);
|
||||
const BMM150Data want = reference_convert(trim, raw);
|
||||
ASSERT_THAT(got.x, ::testing::NanSensitiveFloatEq(want.x)) << "field " << field << " word 0x" << std::hex << word;
|
||||
ASSERT_THAT(got.y, ::testing::NanSensitiveFloatEq(want.y)) << "field " << field << " word 0x" << std::hex << word;
|
||||
ASSERT_THAT(got.z, ::testing::NanSensitiveFloatEq(want.z)) << "field " << field << " word 0x" << std::hex << word;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::bmi270::bmm150::testing
|
||||
@@ -0,0 +1,69 @@
|
||||
#ifdef USE_HOST
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include "esphome/components/bmi270/bmi270.h"
|
||||
#include "esphome/components/bmi270/bmi270_config.h"
|
||||
|
||||
namespace esphome::bmi270::testing {
|
||||
|
||||
// Host builds upload in 256-byte bursts
|
||||
static constexpr size_t MAX_BURST = 256;
|
||||
|
||||
// A BMI270 register file: writes go to consecutive registers, except INIT_DATA, which streams into
|
||||
// the config memory at the word address set in INIT_ADDR_0/1
|
||||
class Bmi270Bus final : public i2c::I2CBus {
|
||||
public:
|
||||
std::array<uint8_t, 128> regs{};
|
||||
std::array<uint8_t, sizeof(BMI270_CONFIG_FILE)> config_memory{};
|
||||
unsigned upload_writes{0};
|
||||
|
||||
Bmi270Bus() {
|
||||
this->regs[BMI270_REG_CHIP_ID] = BMI270_CHIP_ID_VALUE;
|
||||
this->regs[BMI270_REG_INTERNAL_STATUS] = BMI270_INTERNAL_STATUS_INIT_OK;
|
||||
}
|
||||
|
||||
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *data, size_t size, uint8_t *out,
|
||||
size_t out_size) override {
|
||||
if (size == 0)
|
||||
return i2c::ERROR_INVALID_ARGUMENT;
|
||||
uint8_t reg = data[0];
|
||||
if (size > 1) {
|
||||
if (reg == BMI270_REG_INIT_ADDR_0 || reg == BMI270_REG_INIT_ADDR_0 + 1 || reg == BMI270_REG_INIT_DATA)
|
||||
++this->upload_writes;
|
||||
if (reg == BMI270_REG_INIT_DATA) {
|
||||
size_t offset =
|
||||
2 * ((this->regs[BMI270_REG_INIT_ADDR_0] & 0x0F) | (this->regs[BMI270_REG_INIT_ADDR_0 + 1] << 4));
|
||||
if (offset + size - 1 > this->config_memory.size())
|
||||
return i2c::ERROR_INVALID_ARGUMENT;
|
||||
std::memcpy(this->config_memory.data() + offset, data + 1, size - 1);
|
||||
} else {
|
||||
for (size_t i = 1; i < size; i++)
|
||||
this->regs[(reg + i - 1) & 0x7F] = data[i];
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < out_size; i++)
|
||||
out[i] = this->regs[(reg + i) & 0x7F];
|
||||
return i2c::ERROR_OK;
|
||||
}
|
||||
};
|
||||
|
||||
TEST(BMI270ConfigUpload, UploadsTheWholeConfigFileInOrder) {
|
||||
Bmi270Bus bus;
|
||||
BMI270Component imu;
|
||||
imu.set_i2c_bus(&bus);
|
||||
imu.set_i2c_address(0x68);
|
||||
imu.setup();
|
||||
|
||||
EXPECT_FALSE(imu.is_failed());
|
||||
EXPECT_EQ(0, std::memcmp(bus.config_memory.data(), BMI270_CONFIG_FILE, sizeof(BMI270_CONFIG_FILE)));
|
||||
EXPECT_EQ(bus.regs[BMI270_REG_INIT_CTRL], BMI270_INIT_CTRL_LOAD_DONE);
|
||||
// One INIT_ADDR write and one INIT_DATA write per burst
|
||||
EXPECT_EQ(bus.upload_writes, 2 * ((sizeof(BMI270_CONFIG_FILE) + MAX_BURST - 1) / MAX_BURST));
|
||||
}
|
||||
|
||||
} // namespace esphome::bmi270::testing
|
||||
|
||||
#endif
|
||||
@@ -140,4 +140,211 @@ TEST(FrameReaderTest, SixteenBitIndex) {
|
||||
EXPECT_EQ(frames[0][299], 0x42);
|
||||
}
|
||||
|
||||
// Feeds bytes and collects every completed frame of a LengthFrameReader, taking each one with next().
|
||||
template<size_t N, class... F> static Frames feed_all(LengthFrameReader<N, F...> &reader, const Bytes &input) {
|
||||
Frames frames;
|
||||
for (uint8_t c : input) {
|
||||
for (const uint8_t *frame = reader.feed(c); frame != nullptr; frame = reader.next())
|
||||
frames.emplace_back(frame, frame + reader.frame_length());
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
// Feeds bytes and returns the last frame feed() completed, or nullptr.
|
||||
template<size_t N, class... F> static const uint8_t *feed_last(LengthFrameReader<N, F...> &reader, const Bytes &input) {
|
||||
const uint8_t *last = nullptr;
|
||||
for (uint8_t c : input) {
|
||||
if (const uint8_t *frame = reader.feed(c))
|
||||
last = frame;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
template<size_t N, class... F> static Bytes held(const LengthFrameReader<N, F...> &reader, const uint8_t *frame) {
|
||||
return Bytes(frame, frame + reader.frame_length());
|
||||
}
|
||||
|
||||
// pioneer_wt: A5 01, one byte at 7 holds the whole length
|
||||
using OneByte = FrameFormat<FrameLengthU8<7>, 0xA5, 0x01>;
|
||||
// tuya: 55 AA, payload length big-endian at 4, header, length and checksum add 7
|
||||
using TwoByteBE = FrameFormat<FrameLengthU16BE<4, 7>, 0x55, 0xAA>;
|
||||
// ld24xx command and data frames: payload length little-endian at 4, header, length and footer add 10
|
||||
using LdCmd = FrameFormat<FrameLengthU16LE<4, 10>, 0xFD, 0xFC, 0xFB, 0xFA>;
|
||||
using LdData = FrameFormat<FrameLengthU16LE<4, 10>, 0xF4, 0xF3, 0xF2, 0xF1>;
|
||||
// ld2410s short frame: 6E, always 5 bytes
|
||||
using LdShort = FrameFormat<FrameFixedLength<5>, 0x6E>;
|
||||
// Small formats for the recovery tests: A5, one byte at 1 holds the whole length
|
||||
using Small = FrameFormat<FrameLengthU8<1>, 0xA5>;
|
||||
|
||||
static_assert(sizeof(LengthFrameReader<255, OneByte>) == 258);
|
||||
static_assert(sizeof(LengthFrameReader<300, TwoByteBE>) == 306);
|
||||
|
||||
TEST(LengthFrameReaderTest, OneByteLength) {
|
||||
LengthFrameReader<16, OneByte> reader;
|
||||
EXPECT_EQ(feed_all(reader, {0x00, 0xA5, 0x01, 0x10, 0x11, 0x12, 0x13, 0x00, 0x09, 0x42}),
|
||||
(Frames{{0xA5, 0x01, 0x10, 0x11, 0x12, 0x13, 0x00, 0x09, 0x42}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, TwoByteBigEndianPayloadLength) {
|
||||
LengthFrameReader<300, TwoByteBE> reader;
|
||||
// Payload of 0x0102 = 258 bytes: 265 in all
|
||||
Bytes input{0x55, 0xAA, 0x03, 0x07, 0x01, 0x02};
|
||||
input.resize(265, 0x33);
|
||||
Frames frames = feed_all(reader, input);
|
||||
ASSERT_EQ(frames.size(), 1u);
|
||||
EXPECT_EQ(frames[0].size(), 265u);
|
||||
// Too long for N: not a frame
|
||||
EXPECT_EQ(feed_all(reader, {0x55, 0xAA, 0x03, 0x07, 0x01, 0x30}), Frames{});
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, TwoFormatsPickedByFirstByte) {
|
||||
LengthFrameReader<32, LdCmd, LdData> reader;
|
||||
const Bytes cmd{0xFD, 0xFC, 0xFB, 0xFA, 0x02, 0x00, 0xA0, 0x01, 0x04, 0x03, 0x02, 0x01};
|
||||
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x01, 0x00, 0x55, 0xF8, 0xF7, 0xF6, 0xF5};
|
||||
Bytes input{0x00};
|
||||
input.insert(input.end(), data.begin(), data.end());
|
||||
input.insert(input.end(), cmd.begin(), cmd.end());
|
||||
EXPECT_EQ(feed_all(reader, input), (Frames{data, cmd}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FixedAndLengthFormatsTogether) {
|
||||
LengthFrameReader<32, LdShort, LdData> reader;
|
||||
const Bytes small{0x6E, 0x01, 0x02, 0x03, 0x62};
|
||||
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x00, 0x00, 0xF8, 0xF7, 0xF6, 0xF5};
|
||||
Bytes input = small;
|
||||
input.insert(input.end(), data.begin(), data.end());
|
||||
input.insert(input.end(), small.begin(), small.end());
|
||||
EXPECT_EQ(feed_all(reader, input), (Frames{small, data, small}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, BrokenHeaderRealigns) {
|
||||
LengthFrameReader<32, LdCmd, LdData> reader;
|
||||
// FD FC then F4 breaks the command header and starts a data header
|
||||
const Bytes data{0xF4, 0xF3, 0xF2, 0xF1, 0x00, 0x00, 0xF8, 0xF7, 0xF6, 0xF5};
|
||||
Bytes input{0xFD, 0xFC};
|
||||
input.insert(input.end(), data.begin(), data.end());
|
||||
EXPECT_EQ(feed_all(reader, input), (Frames{data}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, BadLengthRealignsAfterFirstByte) {
|
||||
LengthFrameReader<8, Small> reader;
|
||||
// 0x01 ends the frame before its length byte and 0x09 is longer than 8: neither is a frame.
|
||||
// The second A5 inside the bad one starts the real frame.
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x01, 0xA5, 0x09, 0xA5, 0x04, 0x01, 0x02}), (Frames{{0xA5, 0x04, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, LengthByteCanStartHeader) {
|
||||
LengthFrameReader<8, FrameFormat<FrameLengthU8<1>, 0x09>> reader;
|
||||
// Length 9 is longer than 8, so the length byte becomes the next header
|
||||
EXPECT_EQ(feed_all(reader, {0x09, 0x09, 0x03, 0x07}), (Frames{{0x09, 0x03, 0x07}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, LengthTracksPartialFrame) {
|
||||
LengthFrameReader<8, Small> reader;
|
||||
feed_all(reader, {0xA5, 0x05});
|
||||
EXPECT_EQ(reader.length(), 2u);
|
||||
reader.reset();
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
EXPECT_EQ(feed_all(reader, {0x01, 0xA5, 0x03, 0x07}), (Frames{{0xA5, 0x03, 0x07}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ResyncFindsHeaderInRejectedFrame) {
|
||||
LengthFrameReader<8, Small> reader;
|
||||
// The A5 taken as a header was payload; the real frame starts at the second A5
|
||||
const uint8_t *frame = feed_last(reader, {0xA5, 0x05, 0x00, 0xA5, 0x04});
|
||||
ASSERT_NE(frame, nullptr);
|
||||
EXPECT_EQ(reader.frame_length(), 5u);
|
||||
EXPECT_EQ(reader.resync(), nullptr);
|
||||
EXPECT_EQ(reader.length(), 2u);
|
||||
EXPECT_EQ(feed_all(reader, {0x10, 0x20}), (Frames{{0xA5, 0x04, 0x10, 0x20}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ResyncReturnsEveryFrameInsideRejectedOne) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
// A bad checksum rejects the 9 byte frame; two complete frames sit inside it, and a partial one after them
|
||||
const uint8_t *frame = feed_last(reader, {0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04});
|
||||
ASSERT_NE(frame, nullptr);
|
||||
frame = reader.resync();
|
||||
ASSERT_NE(frame, nullptr);
|
||||
EXPECT_EQ(held(reader, frame), (Bytes{0xA5, 0x03, 0x01}));
|
||||
frame = reader.next();
|
||||
ASSERT_NE(frame, nullptr);
|
||||
EXPECT_EQ(held(reader, frame), (Bytes{0xA5, 0x02}));
|
||||
EXPECT_EQ(reader.next(), nullptr);
|
||||
EXPECT_EQ(reader.length(), 2u);
|
||||
EXPECT_EQ(feed_all(reader, {0x01, 0x02}), (Frames{{0xA5, 0x04, 0x01, 0x02}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ResyncAgainAfterRecoveredFrameIsRejected) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
// The 9 byte frame holds a 4 byte candidate, which holds a 3 byte one, followed by two more bytes
|
||||
const uint8_t *frame = feed_last(reader, {0xA5, 0x09, 0xA5, 0x04, 0xA5, 0x03, 0x01, 0x02, 0x03});
|
||||
ASSERT_NE(frame, nullptr);
|
||||
frame = reader.resync();
|
||||
ASSERT_NE(frame, nullptr);
|
||||
EXPECT_EQ(held(reader, frame), (Bytes{0xA5, 0x04, 0xA5, 0x03}));
|
||||
// Rejected too: the 3 byte frame inside it comes back, and the bytes after the 4 byte one are kept
|
||||
frame = reader.resync();
|
||||
ASSERT_NE(frame, nullptr);
|
||||
EXPECT_EQ(held(reader, frame), (Bytes{0xA5, 0x03, 0x01}));
|
||||
EXPECT_EQ(reader.next(), nullptr);
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ResyncPartialFrameAfterSilence) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
// A corrupt length of 15 holds back two complete frames until the caller gives up on the partial one
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x03, 0x09}), Frames{});
|
||||
EXPECT_EQ(reader.length(), 9u);
|
||||
Frames found;
|
||||
for (const uint8_t *frame = reader.resync(); frame != nullptr; frame = reader.next())
|
||||
found.push_back(held(reader, frame));
|
||||
EXPECT_EQ(found, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x03, 0x09}}));
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, ResyncWhileIdleIsHarmless) {
|
||||
LengthFrameReader<8, Small> reader;
|
||||
EXPECT_EQ(reader.resync(), nullptr);
|
||||
// A handled frame, then noise: nothing is held any more
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x03, 0x01, 0x00}), (Frames{{0xA5, 0x03, 0x01}}));
|
||||
EXPECT_EQ(reader.resync(), nullptr);
|
||||
// A rejected length leaves nothing collected
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x09}), Frames{});
|
||||
EXPECT_EQ(reader.resync(), nullptr);
|
||||
EXPECT_EQ(feed_all(reader, {0xA5, 0x03, 0x01}), (Frames{{0xA5, 0x03, 0x01}}));
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, HandlerRejectionRecoversFramesInside) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Frames seen;
|
||||
// The handler rejects the 9 byte frame; the two frames inside it reach the handler too
|
||||
auto handle = [&seen](const uint8_t *frame, size_t len) {
|
||||
seen.emplace_back(frame, frame + len);
|
||||
return len != 9;
|
||||
};
|
||||
for (uint8_t c : {0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(seen, (Frames{{0xA5, 0x09, 0xA5, 0x03, 0x01, 0xA5, 0x02, 0xA5, 0x04}, {0xA5, 0x03, 0x01}, {0xA5, 0x02}}));
|
||||
EXPECT_EQ(reader.length(), 2u);
|
||||
}
|
||||
|
||||
TEST(LengthFrameReaderTest, FlushHandsOverFramesHeldBack) {
|
||||
LengthFrameReader<16, Small> reader;
|
||||
Frames seen;
|
||||
auto handle = [&seen](const uint8_t *frame, size_t len) {
|
||||
seen.emplace_back(frame, frame + len);
|
||||
return true;
|
||||
};
|
||||
for (uint8_t c : {0xA5, 0x0F, 0xA5, 0x04, 0x01, 0x02, 0xA5, 0x03, 0x09})
|
||||
reader.feed(c, handle);
|
||||
EXPECT_EQ(seen, Frames{});
|
||||
reader.flush(handle);
|
||||
EXPECT_EQ(seen, (Frames{{0xA5, 0x04, 0x01, 0x02}, {0xA5, 0x03, 0x09}}));
|
||||
EXPECT_EQ(reader.length(), 0u);
|
||||
reader.flush(handle); // nothing collected: nothing to do
|
||||
EXPECT_EQ(seen.size(), 2u);
|
||||
}
|
||||
|
||||
} // namespace esphome::core::testing
|
||||
@@ -0,0 +1,6 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# touchscreen.h includes display.h
|
||||
manifest.dependencies = manifest.dependencies + ["display"]
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/cst816/touchscreen/cst816_touchscreen.h"
|
||||
|
||||
namespace esphome::cst816::testing {
|
||||
|
||||
static constexpr uint8_t ADDRESS = 0x15;
|
||||
// The driver reads REG_STATUS onwards in one transfer: status, gesture, touch count, then two points.
|
||||
static constexpr size_t FRAME_SIZE = 13;
|
||||
|
||||
/// Serves one fixed status frame.
|
||||
class FrameBus final : public i2c::I2CBus {
|
||||
public:
|
||||
explicit FrameBus(std::array<uint8_t, FRAME_SIZE> frame) : frame_(frame) {}
|
||||
|
||||
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
|
||||
size_t read_count) override {
|
||||
EXPECT_EQ(address, ADDRESS);
|
||||
for (size_t i = 0; i < read_count; i++)
|
||||
read_buffer[i] = i < FRAME_SIZE ? this->frame_[i] : 0;
|
||||
return i2c::ERROR_OK;
|
||||
}
|
||||
|
||||
protected:
|
||||
std::array<uint8_t, FRAME_SIZE> frame_;
|
||||
};
|
||||
|
||||
inline std::array<uint8_t, FRAME_SIZE> make_frame(uint8_t touch_num, uint16_t x = 0, uint16_t y = 0) {
|
||||
std::array<uint8_t, FRAME_SIZE> frame{};
|
||||
frame[REG_TOUCH_NUM] = touch_num;
|
||||
frame[REG_XPOS_HIGH] = (x >> 8) & 0x0F;
|
||||
frame[REG_XPOS_LOW] = x & 0xFF;
|
||||
frame[REG_YPOS_HIGH] = (y >> 8) & 0x0F;
|
||||
frame[REG_YPOS_LOW] = y & 0xFF;
|
||||
return frame;
|
||||
}
|
||||
|
||||
} // namespace esphome::cst816::testing
|
||||
@@ -0,0 +1,88 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "../common.h"
|
||||
|
||||
namespace esphome::cst816::testing {
|
||||
|
||||
class CST816TouchscreenTest : public ::testing::Test {
|
||||
protected:
|
||||
void feed_(const std::array<uint8_t, FRAME_SIZE> &frame) {
|
||||
this->bus_ = std::make_unique<FrameBus>(frame);
|
||||
this->touchscreen_.set_i2c_bus(this->bus_.get());
|
||||
this->touchscreen_.set_i2c_address(ADDRESS);
|
||||
this->touchscreen_.update_touches();
|
||||
}
|
||||
|
||||
std::unique_ptr<FrameBus> bus_;
|
||||
CST816Touchscreen touchscreen_;
|
||||
};
|
||||
|
||||
// An idle frame reports 0xFF in the touch count byte and 0xFFF coordinates. Masking 0xFF to the
|
||||
// low two bits turns that into three touches at the maximum position, a phantom tap.
|
||||
TEST_F(CST816TouchscreenTest, IdleAllOnesFrameIsIgnored) {
|
||||
this->feed_(make_frame(0xFF, 0x0FFF, 0x0FFF));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
TEST_F(CST816TouchscreenTest, ZeroTouchCountIsIgnored) {
|
||||
this->feed_(make_frame(0));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
// Three is the boundary the guard rejects: the old mask turned a count of three into three
|
||||
// touches, so this is the value whose behaviour changes.
|
||||
TEST_F(CST816TouchscreenTest, TouchCountThreeIsIgnored) {
|
||||
this->feed_(make_frame(3, 100, 200));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
// The count is the whole low nibble, so 0x05 must not be masked down to one touch by a 0x03 mask.
|
||||
TEST_F(CST816TouchscreenTest, TouchCountFiveIsIgnored) {
|
||||
this->feed_(make_frame(0x05, 100, 200));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
TEST_F(CST816TouchscreenTest, SingleTouchIsReported) {
|
||||
this->feed_(make_frame(1, 300, 100));
|
||||
auto touches = this->touchscreen_.get_touches();
|
||||
ASSERT_EQ(touches.size(), 1u);
|
||||
EXPECT_EQ(touches[0].x_raw, 300);
|
||||
EXPECT_EQ(touches[0].y_raw, 100);
|
||||
}
|
||||
|
||||
// CST826/CST836 can report two points; the driver only consumes the first one.
|
||||
TEST_F(CST816TouchscreenTest, TwoPointFrameReportsFirstPoint) {
|
||||
this->feed_(make_frame(2, 300, 100));
|
||||
auto touches = this->touchscreen_.get_touches();
|
||||
ASSERT_EQ(touches.size(), 1u);
|
||||
EXPECT_EQ(touches[0].x_raw, 300);
|
||||
EXPECT_EQ(touches[0].y_raw, 100);
|
||||
}
|
||||
|
||||
TEST_F(CST816TouchscreenTest, SentinelPositionIsIgnored) {
|
||||
this->feed_(make_frame(1, 0x0FFF, 100));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
// The sentinel is checked on both axes; a valid X with Y=0xFFF is still an idle reading.
|
||||
TEST_F(CST816TouchscreenTest, SentinelYPositionIsIgnored) {
|
||||
this->feed_(make_frame(1, 100, 0x0FFF));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
// x_raw_max_/y_raw_max_ are calibration endpoints, not validity limits: the base class applies them
|
||||
// after swapping axes and clamps readings outside them. A touch beyond the calibrated maximum is
|
||||
// still a real touch and must reach the base class.
|
||||
TEST_F(CST816TouchscreenTest, CalibrationBoundsDoNotDropTouches) {
|
||||
this->touchscreen_.set_calibration(0, 240, 0, 320);
|
||||
this->touchscreen_.set_swap_xy(true);
|
||||
this->feed_(make_frame(1, 300, 100));
|
||||
auto touches = this->touchscreen_.get_touches();
|
||||
ASSERT_EQ(touches.size(), 1u);
|
||||
EXPECT_EQ(touches[0].x_raw, 100);
|
||||
EXPECT_EQ(touches[0].y_raw, 300);
|
||||
}
|
||||
|
||||
} // namespace esphome::cst816::testing
|
||||
@@ -0,0 +1,2 @@
|
||||
packages:
|
||||
debug: !include common.yaml
|
||||
@@ -0,0 +1,2 @@
|
||||
packages:
|
||||
debug: !include common.yaml
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/components/light/esp_color_correction.h"
|
||||
#include "esphome/components/light/esp_color_view.h"
|
||||
|
||||
namespace esphome::light::testing {
|
||||
|
||||
@@ -67,6 +68,69 @@ TEST(GammaCorrection, DeadZoneFixedAtGamma28) {
|
||||
}
|
||||
}
|
||||
|
||||
// A whole pixel keeps its colour when dim: only the strongest channel is lifted to 1.
|
||||
TEST(GammaCorrection, DimPixelKeepsDominantChannel) {
|
||||
GammaFixture fixture(2.8);
|
||||
fixture.correction.set_local_brightness(13);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 30, 0, 0)), Color(1, 0, 0, 0));
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(0, 0, 255, 30)), Color(0, 0, 1, 0));
|
||||
}
|
||||
|
||||
// Orange at 2% brightness and below: the table reads 1 for both channels there, and at the lowest
|
||||
// step both scale to the same 8-bit value, so neither can be used to compare them.
|
||||
TEST(GammaCorrection, VeryDimPixelKeepsDominantChannel) {
|
||||
GammaFixture fixture(2.8);
|
||||
for (uint8_t brightness : {1, 2, 3, 4, 5, 6}) {
|
||||
fixture.correction.set_local_brightness(brightness);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 130, 0, 0)), Color(1, 0, 0, 0))
|
||||
<< "brightness=" << int(brightness);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(GammaCorrection, DimPixelKeepsSimilarChannels) {
|
||||
GammaFixture fixture(2.8);
|
||||
fixture.correction.set_local_brightness(13);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 255, 255, 0)), Color(1, 1, 1, 0));
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 230, 0, 0)), Color(1, 1, 0, 0));
|
||||
fixture.correction.set_local_brightness(1);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 250, 250, 0)), Color(1, 1, 1, 0));
|
||||
}
|
||||
|
||||
// A channel that color_correct sets to 0% stays dark even when it is the strongest in the pixel.
|
||||
TEST(GammaCorrection, DimPixelLeavesDisabledChannelDark) {
|
||||
GammaFixture fixture(2.8);
|
||||
fixture.correction.set_max_brightness(Color(255, 0, 255, 255));
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(1, 255, 0, 0)), Color(1, 0, 0, 0));
|
||||
}
|
||||
|
||||
// A strip without white drops the white level before the pixel is rounded, so it cannot outrank red.
|
||||
TEST(GammaCorrection, UnusedWhiteDoesNotDarkenRgbStrip) {
|
||||
GammaFixture fixture(2.8);
|
||||
fixture.correction.set_local_brightness(13);
|
||||
std::array<uint8_t, 3> color_data{};
|
||||
std::array<uint8_t, 1> effect_data{};
|
||||
CorrectedBufferColorAccessor accessor(color_data.data(), effect_data.data(), ChannelColors{0, 1, 2},
|
||||
&fixture.correction);
|
||||
accessor.set(0, Color(128, 0, 0, 255));
|
||||
EXPECT_EQ(color_data, (std::array<uint8_t, 3>{1, 0, 0}));
|
||||
}
|
||||
|
||||
TEST(GammaCorrection, LitPixelDropsChannelThatRoundsToZero) {
|
||||
GammaFixture fixture(2.8);
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(255, 5, 0, 0)), Color(255, 0, 0, 0));
|
||||
}
|
||||
|
||||
// The pixel-level form of esphome/esphome#18842: a non-zero pixel never goes fully dark.
|
||||
TEST(GammaCorrection, NonZeroPixelStaysLit) {
|
||||
for (double gamma : {1.0, 2.2, 2.8, 4.0}) {
|
||||
GammaFixture fixture(gamma);
|
||||
for (int i = 1; i < 256; i++) {
|
||||
EXPECT_GE(fixture.correction.color_correct(Color(i, 0, 0, 0)).red, 1) << "gamma=" << gamma << " index=" << i;
|
||||
}
|
||||
EXPECT_EQ(fixture.correction.color_correct(Color(0, 0, 0, 0)), Color(0, 0, 0, 0)) << "gamma=" << gamma;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(GammaCorrection, ReverseSearchFindsLargestIndexLessEqualTarget) {
|
||||
auto table = build_gamma_table(2.8);
|
||||
for (uint16_t target : {0, 128, 129, 135, 1000, 32768, 65535}) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_USE_ADDRESS
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# Only the reply parsers are tested; the build still needs the address a modem config provides.
|
||||
manifest.dependencies = []
|
||||
manifest.config_schema = cv.Schema(
|
||||
{cv.Optional(CONF_USE_ADDRESS, default="test.local"): cv.string_strict}
|
||||
)
|
||||
@@ -0,0 +1,211 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "esphome/components/modem/at_reply.h"
|
||||
|
||||
namespace esphome::modem::testing {
|
||||
|
||||
// Runs a raw reply through flatten_reply() as at_reply_() does
|
||||
static std::string flat(const char *raw) {
|
||||
char buf[256];
|
||||
const size_t len = strlen(raw);
|
||||
memcpy(buf, raw, len + 1);
|
||||
return std::string(buf, flatten_reply(buf, len));
|
||||
}
|
||||
|
||||
static ReplyEnd end_of(const char *reply, bool skip_first = false) {
|
||||
return reply_end(reply, strlen(reply), skip_first);
|
||||
}
|
||||
|
||||
TEST(ModemReplyEnd, OnlyCompleteFinalLinesCount) {
|
||||
EXPECT_EQ(end_of("\r\n+CSQ: 20,99\r\n\r\nOK\r\n"), ReplyEnd::REPLY_END_OK);
|
||||
EXPECT_EQ(end_of("\r\nERROR\r\n"), ReplyEnd::REPLY_END_ERROR);
|
||||
EXPECT_EQ(end_of("\r\n+CME ERROR: SIM not inserted\r\n"), ReplyEnd::REPLY_END_ERROR);
|
||||
EXPECT_EQ(end_of("\r\n+CMS ERROR: 500\r\n"), ReplyEnd::REPLY_END_ERROR);
|
||||
// ERROR inside a payload line is not a result
|
||||
EXPECT_EQ(end_of("\r\n+CEER: PROTOCOL_ERROR\r\n"), ReplyEnd::REPLY_END_NONE);
|
||||
EXPECT_EQ(end_of("\r\n+CEER: PROTOCOL_ERROR\r\n\r\nOK\r\n"), ReplyEnd::REPLY_END_OK);
|
||||
// A line that has not ended yet
|
||||
EXPECT_EQ(end_of("\r\nOK"), ReplyEnd::REPLY_END_NONE);
|
||||
EXPECT_EQ(end_of("\r\n+CME ERROR: 10"), ReplyEnd::REPLY_END_NONE);
|
||||
}
|
||||
|
||||
TEST(ModemReplyEnd, ErrorWithoutItsReason) {
|
||||
// esp_modem drops the CMUX frame ": SIM not inserted" because it holds no line end
|
||||
char buf[64];
|
||||
size_t len = 0;
|
||||
collect_reply(buf, sizeof(buf), len, "\r\n+CME ERROR", 12, false);
|
||||
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_NONE);
|
||||
collect_reply(buf, sizeof(buf), len, "\r\n", 2, false);
|
||||
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_ERROR);
|
||||
EXPECT_EQ(end_of("\r\n+CMS ERROR\r\n"), ReplyEnd::REPLY_END_ERROR);
|
||||
}
|
||||
|
||||
TEST(ModemReplyEnd, CutFirstLineIsSkipped) {
|
||||
// The tail of "...OK" from a longer line must not count as a result
|
||||
EXPECT_EQ(end_of("OK\r\nmore text\r\n", true), ReplyEnd::REPLY_END_NONE);
|
||||
EXPECT_EQ(end_of("OK\r\nmore text\r\n", false), ReplyEnd::REPLY_END_OK);
|
||||
EXPECT_EQ(end_of("tail\r\nOK\r\n", true), ReplyEnd::REPLY_END_OK);
|
||||
}
|
||||
|
||||
TEST(ModemCollectReply, UartReplyComesBackWhole) {
|
||||
char buf[9];
|
||||
size_t len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abc", 3, true));
|
||||
EXPECT_STREQ(buf, "abc");
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcdef", 6, true));
|
||||
EXPECT_STREQ(buf, "abcdef");
|
||||
// Data longer than the buffer keeps its tail
|
||||
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "0123456789", 10, true));
|
||||
EXPECT_STREQ(buf, "23456789");
|
||||
}
|
||||
|
||||
TEST(ModemCollectReply, GatheredCmuxFramesAreNotRepeated) {
|
||||
// With esp_modem's inflatable buffer, each CMUX frame comes with the ones before it
|
||||
char buf[64];
|
||||
size_t len = 0;
|
||||
const char *first = "\r\n+CSQ: 20,99\r\n";
|
||||
const char *both = "\r\n+CSQ: 20,99\r\n\r\nOK\r\n";
|
||||
collect_reply(buf, sizeof(buf), len, first, strlen(first), true);
|
||||
collect_reply(buf, sizeof(buf), len, both, strlen(both), true);
|
||||
EXPECT_STREQ(buf, both);
|
||||
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_OK);
|
||||
}
|
||||
|
||||
TEST(ModemCollectReply, ExactlyFullIsNotCut) {
|
||||
char buf[9];
|
||||
size_t len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\nabcd", 8, true));
|
||||
EXPECT_STREQ(buf, "OK\r\nabcd");
|
||||
len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\nabcd", 8, false));
|
||||
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_OK);
|
||||
// Filling up by appending is not a cut either, one more byte is
|
||||
len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\n", 4, false));
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcd", 4, false));
|
||||
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "e", 1, false));
|
||||
EXPECT_STREQ(buf, "K\r\nabcde");
|
||||
}
|
||||
|
||||
TEST(ModemCollectReply, CmuxFramesAreAppended) {
|
||||
char buf[9];
|
||||
size_t len = 0;
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abc", 3, false));
|
||||
// A frame that starts like the text so far is still new data
|
||||
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcd", 4, false));
|
||||
EXPECT_STREQ(buf, "abcabcd");
|
||||
// The oldest bytes go once the buffer is full
|
||||
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "XY", 2, false));
|
||||
EXPECT_STREQ(buf, "bcabcdXY");
|
||||
EXPECT_EQ(len, 8u);
|
||||
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "0123456789", 10, false));
|
||||
EXPECT_STREQ(buf, "23456789");
|
||||
}
|
||||
|
||||
TEST(ModemFlattenReply, OneLineWithoutFinalOk) {
|
||||
EXPECT_EQ(flat("\r\n+CSQ: 20,99\r\n\r\nOK\r\n"), "+CSQ: 20,99");
|
||||
EXPECT_EQ(flat("\r\nOK\r\n"), "");
|
||||
EXPECT_EQ(flat("\r\n+CME ERROR: SIM not inserted\r\n"), "+CME ERROR: SIM not inserted");
|
||||
EXPECT_EQ(flat("\r\n+COPS: 0,0,\"NOK\"\r\n"), "+COPS: 0,0,\"NOK\"");
|
||||
// A line ending in OK is not the final result
|
||||
EXPECT_EQ(flat("\r\n+CSPN: NOK\r\n"), "+CSPN: NOK");
|
||||
EXPECT_EQ(flat(""), "");
|
||||
}
|
||||
|
||||
TEST(ModemRegistration, QueryAnswerNotNotification) {
|
||||
// A one-field URC before the query answer is skipped
|
||||
EXPECT_EQ(registration_from_reply("+CEREG: 2 +CEREG: 0,1", "+CEREG:"), 1);
|
||||
EXPECT_EQ(registration_from_reply("+CEREG: 2,5,\"1A2B\",\"01A2B3C4\",7", "+CEREG:"), 5);
|
||||
EXPECT_EQ(registration_from_reply("+CREG: 0,3", "+CREG:"), 3);
|
||||
EXPECT_EQ(registration_from_reply("+CEREG: 1", "+CEREG:"), REGISTRATION_UNKNOWN);
|
||||
EXPECT_EQ(registration_from_reply("+CREG: 0,1", "+CEREG:"), REGISTRATION_UNKNOWN);
|
||||
EXPECT_EQ(registration_from_reply("", "+CEREG:"), REGISTRATION_UNKNOWN);
|
||||
}
|
||||
|
||||
TEST(ModemRegistration, OtherRegisteredStates) {
|
||||
EXPECT_TRUE(is_registered(REGISTRATION_HOME));
|
||||
EXPECT_TRUE(is_registered(REGISTRATION_ROAMING));
|
||||
EXPECT_TRUE(is_registered(REGISTRATION_SMS_ONLY_HOME));
|
||||
EXPECT_TRUE(is_registered(REGISTRATION_SMS_ONLY_ROAMING));
|
||||
EXPECT_TRUE(is_registered(REGISTRATION_CSFB_NOT_PREFERRED_HOME));
|
||||
EXPECT_TRUE(is_registered(REGISTRATION_CSFB_NOT_PREFERRED_ROAMING));
|
||||
EXPECT_FALSE(is_registered(REGISTRATION_NOT_SEARCHING));
|
||||
EXPECT_FALSE(is_registered(REGISTRATION_SEARCHING));
|
||||
EXPECT_FALSE(is_registered(REGISTRATION_DENIED));
|
||||
EXPECT_FALSE(is_registered(REGISTRATION_REPORTED_UNKNOWN));
|
||||
EXPECT_FALSE(is_registered(REGISTRATION_EMERGENCY_ONLY));
|
||||
EXPECT_FALSE(is_registered(11));
|
||||
EXPECT_FALSE(is_registered(REGISTRATION_UNKNOWN));
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, RegisteredOnEitherSideWins) {
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_HOME, REGISTRATION_DENIED), REGISTRATION_HOME);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_ROAMING), REGISTRATION_ROAMING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_HOME), REGISTRATION_HOME);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_ROAMING), REGISTRATION_ROAMING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_CSFB_NOT_PREFERRED_ROAMING),
|
||||
REGISTRATION_CSFB_NOT_PREFERRED_ROAMING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_SEARCHING, REGISTRATION_CSFB_NOT_PREFERRED_HOME),
|
||||
REGISTRATION_CSFB_NOT_PREFERRED_HOME);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_SMS_ONLY_HOME, REGISTRATION_DENIED), REGISTRATION_SMS_ONLY_HOME);
|
||||
// Emergency only is no registration, so a searching query still decides
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_EMERGENCY_ONLY, REGISTRATION_SEARCHING), REGISTRATION_SEARCHING);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, SearchingBeatsDenied) {
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_SEARCHING, REGISTRATION_DENIED), REGISTRATION_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_SEARCHING), REGISTRATION_SEARCHING);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, DefiniteAnswerBeatsTimeout) {
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_NO_ANSWER), REGISTRATION_DENIED);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_SEARCHING), REGISTRATION_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_NO_ANSWER), REGISTRATION_NO_ANSWER);
|
||||
// Any reported <stat> outweighs a timeout, so the fallbacks still count it
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NOT_SEARCHING, REGISTRATION_NO_ANSWER), REGISTRATION_NOT_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_NOT_SEARCHING), REGISTRATION_NOT_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_REPORTED_UNKNOWN, REGISTRATION_NO_ANSWER), REGISTRATION_REPORTED_UNKNOWN);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_REPORTED_UNKNOWN);
|
||||
// Only a timeout and no <stat> at all leave the state open
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_NO_ANSWER), REGISTRATION_NO_ANSWER);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_UNKNOWN), REGISTRATION_NO_ANSWER);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, UnsupportedOnlyWhenBothAre) {
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_UNSUPPORTED), REGISTRATION_UNSUPPORTED);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_NOT_SEARCHING), REGISTRATION_NOT_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_UNSUPPORTED), REGISTRATION_UNKNOWN);
|
||||
}
|
||||
|
||||
TEST(ModemMergeRegistration, UnknownFallback) {
|
||||
// The LTE value goes first, then the 2G and 3G one, then unknown
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_NOT_SEARCHING, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_NOT_SEARCHING);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_REPORTED_UNKNOWN);
|
||||
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_UNKNOWN), REGISTRATION_UNKNOWN);
|
||||
}
|
||||
|
||||
TEST(ModemUnsupported, OnlyWhenTheErrorSaysSo) {
|
||||
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: operation not supported"));
|
||||
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: Operation Not Supported"));
|
||||
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: 4"));
|
||||
EXPECT_FALSE(reply_names_unsupported("+CME ERROR: 40"));
|
||||
EXPECT_FALSE(reply_names_unsupported("+CME ERROR: SIM busy"));
|
||||
EXPECT_FALSE(reply_names_unsupported("ERROR"));
|
||||
EXPECT_FALSE(reply_names_unsupported(""));
|
||||
}
|
||||
|
||||
TEST(ModemSimStatus, CutBeforeTheNextLine) {
|
||||
char ready[] = "+CPIN: READY";
|
||||
EXPECT_STREQ(sim_status(ready), "READY");
|
||||
char with_urc[] = "+CPIN: SIM PIN +CGEV: ME PDN DEACT 1";
|
||||
EXPECT_STREQ(sim_status(with_urc), "SIM PIN");
|
||||
char echoed[] = "AT+CPIN?";
|
||||
EXPECT_EQ(sim_status(echoed), nullptr);
|
||||
char empty[] = "+CPIN:";
|
||||
EXPECT_STREQ(sim_status(empty), "");
|
||||
}
|
||||
|
||||
} // namespace esphome::modem::testing
|
||||
@@ -1,29 +1,38 @@
|
||||
npm1300:
|
||||
id: pmic
|
||||
i2c_id: i2c_bus
|
||||
vbus_current_limit: 500mA
|
||||
thermistor_resistance: 10kOhm
|
||||
thermistor_beta: 3380
|
||||
charger:
|
||||
charge_current: 150mA
|
||||
termination_voltage: 4.2V
|
||||
warm_termination_voltage: 4.0V
|
||||
termination_current: 20%
|
||||
trickle_voltage: 2.5V
|
||||
discharge_current_limit: 1000mA
|
||||
recharge: true
|
||||
buck2:
|
||||
voltage: 3.3V
|
||||
ldo1:
|
||||
voltage: 3.3V
|
||||
mode: ldo
|
||||
enabled: true
|
||||
ldo2:
|
||||
mode: load_switch
|
||||
enabled: false
|
||||
- id: pmic
|
||||
i2c_id: i2c_bus
|
||||
vbus_current_limit: 500mA
|
||||
thermistor_resistance: 10kOhm
|
||||
thermistor_beta: 3380
|
||||
charger:
|
||||
charge_current: 150mA
|
||||
termination_voltage: 4.2V
|
||||
warm_termination_voltage: 4.0V
|
||||
termination_current: 20%
|
||||
trickle_voltage: 2.5V
|
||||
discharge_current_limit: 1000mA
|
||||
recharge: true
|
||||
buck2:
|
||||
voltage: 3.3V
|
||||
ldo1:
|
||||
voltage: 3.3V
|
||||
mode: ldo
|
||||
enabled: true
|
||||
ldo2:
|
||||
mode: load_switch
|
||||
enabled: false
|
||||
# A battery without a thermistor
|
||||
- id: pmic_no_ntc
|
||||
i2c_id: i2c_bus
|
||||
address: 0x6C
|
||||
thermistor_resistance: none
|
||||
charger:
|
||||
termination_voltage: 3.5V
|
||||
enabled: true
|
||||
|
||||
sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
battery_voltage:
|
||||
name: Battery Voltage
|
||||
battery_current:
|
||||
@@ -41,6 +50,7 @@ sensor:
|
||||
|
||||
binary_sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
vbus_present:
|
||||
name: VBUS Present
|
||||
vbus_current_limit_active:
|
||||
@@ -54,11 +64,13 @@ binary_sensor:
|
||||
|
||||
text_sensor:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
charger_status:
|
||||
name: Charger Status
|
||||
|
||||
switch:
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic
|
||||
charger:
|
||||
name: Charger
|
||||
buck1:
|
||||
@@ -67,6 +79,10 @@ switch:
|
||||
name: LDO1
|
||||
ldo2:
|
||||
name: LDO2
|
||||
- platform: npm1300
|
||||
npm1300_id: pmic_no_ntc
|
||||
charger:
|
||||
name: Charger Without Thermistor
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import esphome.codegen as cg
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
async def to_code_testing(config):
|
||||
# The accessor hooks that partitions use, and the gamma table of the light under test
|
||||
cg.add_define("USE_LIGHT_PARTITION")
|
||||
cg.add_define("USE_LIGHT_GAMMA_LUT")
|
||||
|
||||
manifest.to_code = to_code_testing
|
||||
manifest.dependencies = manifest.dependencies + ["light"]
|
||||
@@ -0,0 +1,56 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/components/light/addressable_light.h"
|
||||
#include "esphome/components/light/light_state.h"
|
||||
#include "esphome/components/partition/light_partition.h"
|
||||
|
||||
namespace esphome::partition::testing {
|
||||
|
||||
namespace {
|
||||
|
||||
// One RGB pixel in memory
|
||||
class RgbStrip : public light::AddressableLight {
|
||||
public:
|
||||
RgbStrip()
|
||||
: internal_accessor_(this->buffer_.data(), this->buffer_.data() + 3, light::ChannelColors{0, 1, 2},
|
||||
&this->correction_) {
|
||||
this->accessor_ = &this->internal_accessor_;
|
||||
}
|
||||
int32_t size() const override { return 1; }
|
||||
void clear_effect_data() override {}
|
||||
light::LightTraits get_traits() override { return {}; }
|
||||
void write_state(light::LightState *state) override {}
|
||||
|
||||
protected:
|
||||
std::array<uint8_t, 4> buffer_{};
|
||||
light::CorrectedBufferColorAccessor internal_accessor_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// The partition corrects a pixel before the strip drops its white level, so it has to drop it first.
|
||||
TEST(PartitionWhite, UnusedWhiteDoesNotDarkenRgbSegment) {
|
||||
light::GammaTable table{};
|
||||
for (int i = 1; i < 256; i++)
|
||||
table.lut[i] = std::max(1.0, std::round(std::pow(i / 255.0, 2.8) * 65535.0));
|
||||
table.gamma_x100 = 280;
|
||||
|
||||
RgbStrip strip;
|
||||
light::LightState strip_state(&strip);
|
||||
PartitionLightOutput partition({AddressableSegment(&strip_state, 0, 1, false)});
|
||||
light::LightState partition_state(&partition);
|
||||
partition_state.set_gamma_table(&table);
|
||||
partition.setup_state(&partition_state);
|
||||
partition_state.current_values.set_state(1.0f);
|
||||
partition_state.current_values.set_brightness(13 / 255.0f);
|
||||
partition.update_state(&partition_state);
|
||||
|
||||
partition[0] = Color(128, 0, 0, 255);
|
||||
EXPECT_EQ(strip[0].get_raw(), Color(1, 0, 0, 0));
|
||||
}
|
||||
|
||||
} // namespace esphome::partition::testing
|
||||
@@ -0,0 +1,6 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# The ADC is an audio_adc platform on I2C; the tests drive its input select.
|
||||
manifest.dependencies = manifest.dependencies + ["audio_adc", "i2c", "select"]
|
||||
@@ -0,0 +1,24 @@
|
||||
esphome:
|
||||
on_boot:
|
||||
then:
|
||||
- audio_adc.set_mic_gain:
|
||||
id: pcm1863_adc
|
||||
mic_gain: 0db
|
||||
- audio_adc.set_mic_gain:
|
||||
id: pcm1863_adc
|
||||
mic_gain: !lambda 'return 4;'
|
||||
- audio_adc.set_mic_gain:
|
||||
id: pcm1863_adc
|
||||
mic_gain: 6db
|
||||
|
||||
audio_adc:
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_adc
|
||||
input: VIN2
|
||||
|
||||
select:
|
||||
# Switches the analog input mux at runtime
|
||||
- platform: pcm1863
|
||||
pcm1863_id: pcm1863_adc
|
||||
name: Line Input
|
||||
@@ -0,0 +1,98 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
|
||||
#include "esphome/components/pcm1863/pcm1863.h"
|
||||
#include "esphome/components/select/select.h"
|
||||
|
||||
namespace esphome::pcm1863::testing {
|
||||
|
||||
static constexpr uint8_t ADDRESS = 0x4A;
|
||||
|
||||
// The body codegen emits for the input select with publish="on_success".
|
||||
static PCM1863 *adc = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
static void apply_input(select::Select *entity, size_t index) {
|
||||
if (adc->set_input(static_cast<PCM1863Input>(index)))
|
||||
entity->publish_state(index);
|
||||
}
|
||||
|
||||
// Page 0 registers written as register/value pairs; failing writes are not acknowledged.
|
||||
class RegisterBus final : public i2c::I2CBus {
|
||||
public:
|
||||
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *data, size_t size, uint8_t * /*out*/,
|
||||
size_t /*out_size*/) override {
|
||||
EXPECT_EQ(address, ADDRESS);
|
||||
if (this->fail)
|
||||
return i2c::ERROR_NOT_ACKNOWLEDGED;
|
||||
if (size == 2)
|
||||
this->registers[data[0]] = data[1];
|
||||
return i2c::ERROR_OK;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 256> registers{};
|
||||
bool fail{false};
|
||||
};
|
||||
|
||||
class PCM1863InputSelectTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
this->adc_.set_i2c_bus(&this->bus_);
|
||||
this->adc_.set_i2c_address(ADDRESS);
|
||||
adc = &this->adc_;
|
||||
this->select_.traits.set_options({"NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2"});
|
||||
this->select_.add_on_state_callback([this](size_t) { ++this->publishes_; });
|
||||
}
|
||||
|
||||
void choose_(size_t index) { this->select_.make_call().set_index(index).perform(); }
|
||||
|
||||
RegisterBus bus_;
|
||||
PCM1863 adc_;
|
||||
select::ApplySelect<apply_input> select_;
|
||||
unsigned publishes_{0};
|
||||
};
|
||||
|
||||
TEST_F(PCM1863InputSelectTest, EveryOptionWritesItsMuxBitsToBothChannels) {
|
||||
this->adc_.setup();
|
||||
ASSERT_FALSE(this->adc_.is_failed());
|
||||
static constexpr std::array<uint8_t, 7> MUX = {0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20};
|
||||
for (size_t index = 0; index < MUX.size(); index++) {
|
||||
this->choose_(index);
|
||||
// Bit 6 is reserved and always written as 1
|
||||
EXPECT_EQ(this->bus_.registers[PCM1863_REG_ADC1_INPUT_SEL_L], PCM1863_INPUT_SEL_RSV | MUX[index]);
|
||||
EXPECT_EQ(this->bus_.registers[PCM1863_REG_ADC1_INPUT_SEL_R], PCM1863_INPUT_SEL_RSV | MUX[index]);
|
||||
EXPECT_EQ(this->select_.active_index(), index);
|
||||
}
|
||||
EXPECT_EQ(this->publishes_, MUX.size());
|
||||
}
|
||||
|
||||
TEST_F(PCM1863InputSelectTest, FailedWriteLeavesTheSelectUnpublished) {
|
||||
this->adc_.setup();
|
||||
this->bus_.fail = true;
|
||||
this->choose_(2);
|
||||
EXPECT_EQ(this->publishes_, 0u);
|
||||
EXPECT_FALSE(this->select_.has_state());
|
||||
}
|
||||
|
||||
TEST_F(PCM1863InputSelectTest, FailedWriteDoesNotLeakIntoTheNextRequest) {
|
||||
this->adc_.setup();
|
||||
this->bus_.fail = true;
|
||||
this->choose_(2);
|
||||
this->bus_.fail = false;
|
||||
this->choose_(5);
|
||||
EXPECT_EQ(this->publishes_, 1u);
|
||||
EXPECT_EQ(this->select_.active_index(), 5u);
|
||||
EXPECT_EQ(this->bus_.registers[PCM1863_REG_ADC1_INPUT_SEL_L], PCM1863_INPUT_SEL_RSV | 0x10);
|
||||
}
|
||||
|
||||
TEST_F(PCM1863InputSelectTest, FailedSetupRejectsTheSelect) {
|
||||
this->bus_.fail = true;
|
||||
this->adc_.setup();
|
||||
ASSERT_TRUE(this->adc_.is_failed());
|
||||
this->bus_.fail = false;
|
||||
this->choose_(3);
|
||||
EXPECT_EQ(this->publishes_, 0u);
|
||||
EXPECT_FALSE(this->select_.has_state());
|
||||
EXPECT_EQ(this->bus_.registers[PCM1863_REG_ADC1_INPUT_SEL_L], 0);
|
||||
}
|
||||
|
||||
} // namespace esphome::pcm1863::testing
|
||||
@@ -0,0 +1,3 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
pcm1863: !include common.yaml
|
||||
@@ -0,0 +1,46 @@
|
||||
# Every analog input the PCM1863 mux can select, and every supported word length
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
|
||||
audio_adc:
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_vin1
|
||||
address: 0x4A
|
||||
input: VIN1
|
||||
bits_per_sample: 16bit
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_vin2
|
||||
address: 0x4B
|
||||
input: VIN2
|
||||
bits_per_sample: 20bit
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_vin3
|
||||
address: 0x4C
|
||||
input: VIN3
|
||||
bits_per_sample: 32bit
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_vin4
|
||||
address: 0x4D
|
||||
input: vin4
|
||||
mic_gain: -12db
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_diff1
|
||||
address: 0x4E
|
||||
input: DIFF_1
|
||||
mic_gain: 40db
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_diff2
|
||||
address: 0x4F
|
||||
input: DIFF_2
|
||||
mic_gain: 20db
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_none
|
||||
address: 0x50
|
||||
input: none
|
||||
@@ -0,0 +1,504 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/pioneer_wt/pioneer_wt.h"
|
||||
#include "esphome/components/pioneer_wt/pioneer_wt_protocol.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "../common.h"
|
||||
|
||||
namespace esphome::pioneer_wt::testing {
|
||||
|
||||
namespace {
|
||||
|
||||
using Frame = std::vector<uint8_t>;
|
||||
|
||||
// Frames captured between a Pioneer WT indoor unit and its stock WiFi module.
|
||||
// Full status the AC sent at boot: on, heat, 77 F, indoor 21.7 C, fan auto, swing stopped, eco off.
|
||||
const char *const STATUS_DUMP = "a5010121a50000428a930c0c0001010002000009c400030000087a000500000c00000d00000e0800110800"
|
||||
"120400df0000c902001700001e0102270000004d014801";
|
||||
// The AC's once-a-minute "are you there?" check.
|
||||
const char *const PRESENCE_CHECK = "a50100210000000cd37d0c0c";
|
||||
const char *const PRESENCE_REPLY = "a5010023000000124709800c0264ffffffd0";
|
||||
|
||||
// payload starts with the two class bytes.
|
||||
Frame build(uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, const Frame &payload) {
|
||||
uint8_t frame[MAX_FRAME_SIZE];
|
||||
const size_t len =
|
||||
build_frame(frame, flags, type, seq, ack, payload[0], payload[1], payload.data() + 2, payload.size() - 2);
|
||||
return Frame(frame, frame + len);
|
||||
}
|
||||
|
||||
Frame status_request(uint8_t seq) {
|
||||
return build(FLAG_WANT_ACK, TYPE_DATA, seq, 0, {CLASS_NETWORK, CLASS_NETWORK, 0xff, 0xff});
|
||||
}
|
||||
|
||||
Frame command(uint8_t seq, const Frame &attrs) {
|
||||
Frame payload{CLASS_COMMAND, CLASS_COMMAND};
|
||||
payload.insert(payload.end(), attrs.begin(), attrs.end());
|
||||
return build(FLAG_WANT_ACK, TYPE_DATA, seq, 0, payload);
|
||||
}
|
||||
|
||||
size_t feed_all(PacketReader &reader, const Frame &bytes) {
|
||||
size_t last = 0;
|
||||
for (uint8_t b : bytes) {
|
||||
if (size_t len = reader.feed(b))
|
||||
last = len;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Frames built here must match what the stock module sent, byte for byte.
|
||||
TEST(PioneerWTProtocol, BuildsCapturedCommands) {
|
||||
EXPECT_EQ(command(0x09, {0x00, 0x01, 0x00}), from_hex("a50101210900000f4f990a0a000100"));
|
||||
EXPECT_EQ(command(0x0b, {0x00, 0x12, 0x03}), from_hex("a50101210b00000fefbd0a0a001203"));
|
||||
EXPECT_EQ(command(0x29, {0x00, 0x1e, 0x00}), from_hex("a50101212900000ffb280a0a001e00"));
|
||||
EXPECT_EQ(command(0x2b, {0x00, 0x25, 0x00}), from_hex("a50101212b00000fe4200a0a002500"));
|
||||
EXPECT_EQ(command(0x10, {0x02, 0x27, 0x00, 0x00, 0x00, 0x3f}), from_hex("a50101211000001238620a0a02270000003f"));
|
||||
EXPECT_EQ(status_request(0x01), from_hex("a50101210100000e4ae90b0bffff"));
|
||||
}
|
||||
|
||||
TEST(PioneerWTProtocol, BuildsCapturedReplies) {
|
||||
EXPECT_EQ(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0xb7, {0x80, CLASS_STATUS}), from_hex("a501012300b7000ce352800c"));
|
||||
EXPECT_EQ(build(FLAG_NO_ACK, TYPE_REPLY, 0, 0, {0x80, CLASS_STATUS, 0x02, 0x64, 0xff, 0xff, 0xff, 0xd8}),
|
||||
from_hex("a501002300000012c601800c0264ffffffd8"));
|
||||
}
|
||||
|
||||
TEST(PioneerWTProtocol, ReaderAcceptsCapturedFrame) {
|
||||
PacketReader reader;
|
||||
const Frame frame = from_hex(STATUS_DUMP);
|
||||
EXPECT_EQ(feed_all(reader, frame), frame.size());
|
||||
}
|
||||
|
||||
TEST(PioneerWTProtocol, ReaderSkipsNoiseAndStrayHeaderBytes) {
|
||||
PacketReader reader;
|
||||
Frame bytes = from_hex("00ffa5a5a502");
|
||||
const Frame frame = from_hex(PRESENCE_CHECK);
|
||||
bytes.insert(bytes.end(), frame.begin(), frame.end());
|
||||
EXPECT_EQ(feed_all(reader, bytes), frame.size());
|
||||
}
|
||||
|
||||
TEST(PioneerWTProtocol, ReaderDropsBadChecksum) {
|
||||
PacketReader reader;
|
||||
Frame frame = from_hex(PRESENCE_CHECK);
|
||||
frame[9] ^= 0x01;
|
||||
EXPECT_EQ(feed_all(reader, frame), 0u);
|
||||
EXPECT_TRUE(reader.take_checksum_error());
|
||||
EXPECT_FALSE(reader.take_checksum_error());
|
||||
// The next good frame is still accepted.
|
||||
EXPECT_EQ(feed_all(reader, from_hex(PRESENCE_CHECK)), 12u);
|
||||
}
|
||||
|
||||
TEST(PioneerWTProtocol, ReaderRejectsImpossibleLength) {
|
||||
PacketReader reader;
|
||||
EXPECT_EQ(feed_all(reader, from_hex("a501012100000005")), 0u);
|
||||
EXPECT_EQ(feed_all(reader, from_hex(PRESENCE_CHECK)), 12u);
|
||||
}
|
||||
|
||||
TEST(PioneerWTProtocol, AttributesOfStatusDump) {
|
||||
const Frame frame = from_hex(STATUS_DUMP);
|
||||
AttributeReader attrs(frame.data() + HEADER_SIZE + 2, frame.size() - HEADER_SIZE - 2);
|
||||
std::vector<std::pair<uint16_t, uint32_t>> seen;
|
||||
while (attrs.next())
|
||||
seen.emplace_back(attrs.id(), attrs.value());
|
||||
EXPECT_FALSE(attrs.stopped_on_unknown());
|
||||
ASSERT_EQ(seen.size(), 15u);
|
||||
EXPECT_EQ(seen[0], std::make_pair(ATTR_POWER, 1u));
|
||||
EXPECT_EQ(seen[1], std::make_pair(ATTR_SETPOINT_C100, 2500u));
|
||||
EXPECT_EQ(seen[2], std::make_pair(ATTR_INDOOR_TEMP_C100, 2170u));
|
||||
EXPECT_EQ(seen[8], std::make_pair(ATTR_MODE, 4u));
|
||||
EXPECT_EQ(seen[13], std::make_pair(ATTR_SETPOINT_F, 77u));
|
||||
}
|
||||
|
||||
TEST(PioneerWTProtocol, AttributesWithCountPrefix) {
|
||||
// 0038 carries a count byte: empty, then one byte of data, then the next attribute.
|
||||
const Frame body = from_hex("00380000380122000101");
|
||||
AttributeReader attrs(body.data(), body.size());
|
||||
ASSERT_TRUE(attrs.next());
|
||||
EXPECT_EQ(attrs.id(), 0x0038);
|
||||
ASSERT_TRUE(attrs.next());
|
||||
EXPECT_EQ(attrs.id(), 0x0038);
|
||||
ASSERT_TRUE(attrs.next());
|
||||
EXPECT_EQ(attrs.id(), ATTR_POWER);
|
||||
EXPECT_EQ(attrs.value(), 1u);
|
||||
EXPECT_FALSE(attrs.next());
|
||||
EXPECT_FALSE(attrs.stopped_on_unknown());
|
||||
}
|
||||
|
||||
TEST(PioneerWTProtocol, AttributesStopAtUnknownId) {
|
||||
const Frame body = from_hex("000101abcd00001200");
|
||||
AttributeReader attrs(body.data(), body.size());
|
||||
ASSERT_TRUE(attrs.next());
|
||||
EXPECT_EQ(attrs.id(), ATTR_POWER);
|
||||
EXPECT_FALSE(attrs.next());
|
||||
EXPECT_TRUE(attrs.stopped_on_unknown());
|
||||
EXPECT_EQ(attrs.id(), 0xabcd);
|
||||
}
|
||||
|
||||
// A cut-off frame, not an unknown ID: a four-byte value with three bytes, and 0147 with one of its two length bytes.
|
||||
TEST(PioneerWTProtocol, AttributesStopAtTruncatedValue) {
|
||||
for (const char *hex : {"0227000000", "014700"}) {
|
||||
const Frame body = from_hex(hex);
|
||||
AttributeReader attrs(body.data(), body.size());
|
||||
EXPECT_FALSE(attrs.next()) << hex;
|
||||
EXPECT_FALSE(attrs.stopped_on_unknown()) << hex;
|
||||
}
|
||||
}
|
||||
|
||||
class PioneerWTTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override { this->sut_.set_uart_parent(&this->uart_); }
|
||||
|
||||
void loop_at_(uint32_t now) {
|
||||
LoopBlockingGuard{nullptr, nullptr, now};
|
||||
this->sut_.loop();
|
||||
}
|
||||
|
||||
// Starts the component and acknowledges its boot request for the full status.
|
||||
void start_() {
|
||||
this->sut_.setup();
|
||||
this->loop_at_(1000);
|
||||
this->uart_.tx.clear();
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0x01, {0x80, CLASS_NETWORK}));
|
||||
this->loop_at_(1010);
|
||||
}
|
||||
|
||||
// Starts the component, applies the captured full status and clears what was sent so far.
|
||||
void start_with_status_() {
|
||||
this->start_();
|
||||
this->uart_.push_rx_hex(STATUS_DUMP);
|
||||
this->loop_at_(1100);
|
||||
this->uart_.tx.clear();
|
||||
}
|
||||
|
||||
// Lets the boot request for the full status run out of attempts.
|
||||
void exhaust_boot_request_() {
|
||||
this->sut_.setup();
|
||||
for (uint32_t t = 1000; t <= 4000; t += 500)
|
||||
this->loop_at_(t);
|
||||
}
|
||||
|
||||
MockUARTComponent uart_;
|
||||
PioneerWT sut_;
|
||||
};
|
||||
|
||||
TEST_F(PioneerWTTest, ResendsUntilAcknowledgedThenGivesUp) {
|
||||
this->sut_.setup();
|
||||
this->loop_at_(1000);
|
||||
const Frame request = status_request(0x01);
|
||||
EXPECT_EQ(this->uart_.tx, request);
|
||||
this->loop_at_(1200); // too soon to resend
|
||||
EXPECT_EQ(this->uart_.tx.size(), request.size());
|
||||
for (uint32_t t = 1500; t <= 2500; t += 500)
|
||||
this->loop_at_(t);
|
||||
EXPECT_EQ(this->uart_.tx.size(), request.size() * 4);
|
||||
this->loop_at_(3000); // fourth attempt was the last
|
||||
this->loop_at_(3500);
|
||||
EXPECT_EQ(this->uart_.tx.size(), request.size() * 4);
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, AppliesStatusDumpAndAcknowledges) {
|
||||
this->start_();
|
||||
this->uart_.push_rx_hex(STATUS_DUMP);
|
||||
this->loop_at_(1100);
|
||||
EXPECT_EQ(this->uart_.tx, from_hex("a501012300a5000ca38b800c"));
|
||||
EXPECT_EQ(this->sut_.mode, climate::CLIMATE_MODE_HEAT);
|
||||
EXPECT_NEAR(this->sut_.target_temperature, 25.0f, 0.01f);
|
||||
EXPECT_NEAR(this->sut_.current_temperature, 21.7f, 0.01f);
|
||||
ASSERT_TRUE(this->sut_.fan_mode.has_value());
|
||||
EXPECT_EQ(*this->sut_.fan_mode, climate::CLIMATE_FAN_AUTO);
|
||||
EXPECT_EQ(this->sut_.swing_mode, climate::CLIMATE_SWING_OFF);
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, AnswersPresenceCheck) {
|
||||
this->start_();
|
||||
this->uart_.push_rx_hex(PRESENCE_CHECK);
|
||||
this->loop_at_(1100);
|
||||
EXPECT_EQ(this->uart_.tx, from_hex(PRESENCE_REPLY));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, PublishesOnlyWhenTheReportChangesSomething) {
|
||||
this->start_with_status_();
|
||||
int published = 0;
|
||||
this->sut_.add_on_state_callback([&published](climate::Climate & /*climate*/) { published++; });
|
||||
this->uart_.push_rx_hex(STATUS_DUMP);
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(published, 0);
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_DATA, 0xb0, 0, {CLASS_STATUS, CLASS_STATUS, 0x00, 0x05, 0x03}));
|
||||
this->loop_at_(1300);
|
||||
EXPECT_EQ(published, 1);
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, ReportsFanSpeedAndPowerOff) {
|
||||
this->start_();
|
||||
this->uart_.push_rx_hex(STATUS_DUMP);
|
||||
this->loop_at_(1100);
|
||||
// Fan speed 3, then power off.
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_DATA, 0xb0, 0, {CLASS_STATUS, CLASS_STATUS, 0x00, 0x05, 0x03}));
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_DATA, 0xb1, 0, {CLASS_STATUS, CLASS_STATUS, 0x00, 0x01, 0x00}));
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->sut_.get_custom_fan_mode(), "Speed 3");
|
||||
EXPECT_EQ(this->sut_.mode, climate::CLIMATE_MODE_OFF);
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, IgnoresUnknownModeAndFanSpeed) {
|
||||
this->start_with_status_();
|
||||
// Mode 5 and fan speed 8 are past the ends of the tables.
|
||||
this->uart_.push_rx(
|
||||
build(FLAG_WANT_ACK, TYPE_DATA, 0xb0, 0, {CLASS_STATUS, CLASS_STATUS, 0x00, 0x12, 0x05, 0x00, 0x05, 0x08}));
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->sut_.mode, climate::CLIMATE_MODE_HEAT);
|
||||
ASSERT_TRUE(this->sut_.fan_mode.has_value());
|
||||
EXPECT_EQ(*this->sut_.fan_mode, climate::CLIMATE_FAN_AUTO);
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, ModeChangeWhileOnSendsModeOnly) {
|
||||
this->start_with_status_();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->uart_.tx, from_hex("a50101210200000f0d230a0a001201"));
|
||||
// State follows the AC's report, not the request.
|
||||
EXPECT_EQ(this->sut_.mode, climate::CLIMATE_MODE_HEAT);
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, TurnOnSendsPowerModeAndSetpoint) {
|
||||
this->start_();
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_HEAT).set_target_temperature(20.0f).perform();
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->uart_.tx, from_hex("a50101210200001869400a0a000101001204022700000044"));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, OffSendsPowerOnly) {
|
||||
this->start_with_status_();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_OFF).perform();
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->uart_.tx, from_hex("a50101210200000f4b220a0a000100"));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, FanSpeedSentLikeTheApp) {
|
||||
this->start_();
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.make_call().set_fan_mode("Speed 3").perform();
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->uart_.tx, from_hex("a501012102000018ac1f0a0a022400022500000503007300"));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, DisplayAndBeeperCommands) {
|
||||
this->start_();
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.set_display_on(false);
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x02, {0x00, 0x1e, 0x00}));
|
||||
this->uart_.tx.clear();
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0x02, {0x80, CLASS_COMMAND}));
|
||||
this->sut_.set_beeper_on(true);
|
||||
this->loop_at_(1300);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x03, {0x00, 0x25, 0x01}));
|
||||
}
|
||||
|
||||
// The request for the full status at boot can be lost when the AC powers up at the same time.
|
||||
TEST_F(PioneerWTTest, AsksAgainUntilFullStatusArrives) {
|
||||
this->exhaust_boot_request_();
|
||||
// The AC is alive: it sends its presence check and a small report, but never the full status.
|
||||
this->uart_.push_rx_hex(PRESENCE_CHECK);
|
||||
this->uart_.push_rx(build(FLAG_NO_ACK, TYPE_DATA, 0xb0, 0, {CLASS_STATUS, CLASS_STATUS, 0x00, 0x05, 0x03}));
|
||||
this->loop_at_(20000);
|
||||
this->uart_.tx.clear();
|
||||
this->loop_at_(29000);
|
||||
EXPECT_TRUE(this->uart_.tx.empty());
|
||||
this->loop_at_(30000);
|
||||
this->loop_at_(30010);
|
||||
EXPECT_EQ(this->uart_.tx, status_request(0x02));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, PresenceCheckDoesNotCountAsStatus) {
|
||||
this->start_();
|
||||
this->uart_.push_rx_hex(STATUS_DUMP);
|
||||
this->loop_at_(1100);
|
||||
// Presence checks keep arriving, but no status for five minutes.
|
||||
for (uint32_t t = 60000; t <= 300000; t += 60000) {
|
||||
this->uart_.push_rx_hex(PRESENCE_CHECK);
|
||||
this->loop_at_(t);
|
||||
}
|
||||
this->uart_.tx.clear();
|
||||
this->loop_at_(301100);
|
||||
this->loop_at_(301110);
|
||||
EXPECT_EQ(this->uart_.tx, status_request(0x02));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, WarningStaysUntilAcknowledgement) {
|
||||
this->exhaust_boot_request_();
|
||||
EXPECT_TRUE(this->sut_.status_has_warning());
|
||||
// Sending the next command does not prove the link works.
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->loop_at_(5000);
|
||||
EXPECT_TRUE(this->sut_.status_has_warning());
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0x02, {0x80, CLASS_COMMAND}));
|
||||
this->loop_at_(5100);
|
||||
EXPECT_FALSE(this->sut_.status_has_warning());
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, DropsPartialFrameAfterPause) {
|
||||
this->start_();
|
||||
// A cut-off header that claims 255 bytes would otherwise swallow the frames that follow.
|
||||
this->uart_.push_rx_hex("a5010121000000ff");
|
||||
this->loop_at_(1100);
|
||||
this->loop_at_(1300); // idle pass after the gap
|
||||
this->uart_.push_rx_hex(PRESENCE_CHECK);
|
||||
this->loop_at_(2000);
|
||||
EXPECT_EQ(this->uart_.tx, from_hex(PRESENCE_REPLY));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, KeepsPartialFrameAfterSlowLoop) {
|
||||
this->start_();
|
||||
const std::string check = PRESENCE_CHECK;
|
||||
this->uart_.push_rx_hex(check.substr(0, 10));
|
||||
this->loop_at_(1100);
|
||||
// The loop was busy; the rest of the frame is already waiting when it runs again.
|
||||
this->uart_.push_rx_hex(check.substr(10));
|
||||
this->loop_at_(1500);
|
||||
EXPECT_EQ(this->uart_.tx, from_hex(PRESENCE_REPLY));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, FailedPowerOnIsSentAgainWithTheNextMode) {
|
||||
this->start_(); // no status yet: the AC is off
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_HEAT).perform();
|
||||
for (uint32_t t = 1100; t <= 2600; t += 500)
|
||||
this->loop_at_(t); // four attempts, no acknowledgement
|
||||
this->loop_at_(3100); // given up
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->loop_at_(3200);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x03, {0x00, 0x01, 0x01, 0x00, 0x12, 0x01}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, ModeAfterQueuedOffTurnsBackOn) {
|
||||
this->start_with_status_();
|
||||
// Both calls are made before the AC reports that it is off.
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_OFF).perform();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x02, {0x00, 0x01, 0x00}));
|
||||
this->uart_.tx.clear();
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0x02, {0x80, CLASS_COMMAND}));
|
||||
this->loop_at_(1300);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x03, {0x00, 0x01, 0x01, 0x00, 0x12, 0x01}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, ReportOnDuringQueuedOffKeepsTheOff) {
|
||||
this->start_with_status_();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_OFF).perform();
|
||||
// A report sent before the AC got the off must not make the next mode change skip the power on.
|
||||
this->uart_.push_rx(build(FLAG_NO_ACK, TYPE_DATA, 0xb0, 0, {CLASS_STATUS, CLASS_STATUS, 0x00, 0x01, 0x01}));
|
||||
this->loop_at_(1200);
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->uart_.tx.clear();
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0x02, {0x80, CLASS_COMMAND}));
|
||||
this->loop_at_(1300);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x03, {0x00, 0x01, 0x01, 0x00, 0x12, 0x01}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, EcoAndAutoFanCommand) {
|
||||
this->start_();
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.make_call().set_fan_mode(climate::CLIMATE_FAN_AUTO).set_preset(climate::CLIMATE_PRESET_ECO).perform();
|
||||
this->loop_at_(1200);
|
||||
EXPECT_EQ(this->uart_.tx,
|
||||
command(0x02, {0x02, 0x24, 0x00, 0x02, 0x25, 0x00, 0x00, 0x05, 0x00, 0x00, 0x73, 0x01, 0x00, 0x13, 0x01}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, ReportsEcoAndSwing) {
|
||||
this->start_with_status_();
|
||||
this->uart_.push_rx(
|
||||
build(FLAG_NO_ACK, TYPE_DATA, 0xb0, 0, {CLASS_STATUS, CLASS_STATUS, 0x00, 0x13, 0x01, 0x00, 0x11, SWING_ON}));
|
||||
this->loop_at_(1200);
|
||||
ASSERT_TRUE(this->sut_.preset.has_value());
|
||||
EXPECT_EQ(*this->sut_.preset, climate::CLIMATE_PRESET_ECO);
|
||||
EXPECT_EQ(this->sut_.swing_mode, climate::CLIMATE_SWING_VERTICAL);
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, RemoteOffWhileASettingIsQueuedIsFollowed) {
|
||||
this->start_with_status_();
|
||||
this->sut_.set_display_on(false);
|
||||
// The handheld remote turns the AC off while the display command waits for its acknowledgement.
|
||||
this->uart_.push_rx(build(FLAG_NO_ACK, TYPE_DATA, 0xb0, 0, {CLASS_STATUS, CLASS_STATUS, 0x00, 0x01, 0x00}));
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0x02, {0x80, CLASS_COMMAND}));
|
||||
this->loop_at_(1200);
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->loop_at_(1300);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x03, {0x00, 0x01, 0x01, 0x00, 0x12, 0x01}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, DroppingAnotherCommandKeepsAQueuedOff) {
|
||||
this->start_with_status_();
|
||||
this->sut_.set_display_on(false);
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_OFF).perform();
|
||||
// The display command gets no acknowledgement and is dropped; the off is still queued.
|
||||
for (uint32_t t = 1200; t <= 2700; t += 500)
|
||||
this->loop_at_(t);
|
||||
this->loop_at_(3200);
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->uart_.tx.clear();
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0x03, {0x80, CLASS_COMMAND}));
|
||||
this->loop_at_(3300);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x04, {0x00, 0x01, 0x01, 0x00, 0x12, 0x01}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, PowerOnDroppedForRoomIsSentAgain) {
|
||||
this->start_(); // no status yet: the AC is off
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_HEAT).perform();
|
||||
for (uint8_t i = 0; i < 3; i++)
|
||||
this->sut_.set_display_on(i % 2);
|
||||
this->uart_.tx.clear();
|
||||
// The queue is full; the power on at its head makes room for this call.
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->loop_at_(1100);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x03, {0x00, 0x1e, 0x00}));
|
||||
for (uint8_t seq = 0x03; seq <= 0x05; seq++) {
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, seq, {0x80, CLASS_COMMAND}));
|
||||
this->loop_at_(1100 + seq * 100);
|
||||
}
|
||||
EXPECT_EQ(Frame(this->uart_.tx.end() - 18, this->uart_.tx.end()),
|
||||
command(0x06, {0x00, 0x01, 0x01, 0x00, 0x12, 0x01}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, AcknowledgedOffCountsBeforeItsReport) {
|
||||
this->start_with_status_();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_OFF).perform();
|
||||
this->loop_at_(1200);
|
||||
// The off is acknowledged, but the AC has not reported the power yet.
|
||||
this->uart_.push_rx(build(FLAG_WANT_ACK, TYPE_REPLY, 0, 0x02, {0x80, CLASS_COMMAND}));
|
||||
this->loop_at_(1300);
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.make_call().set_mode(climate::CLIMATE_MODE_COOL).perform();
|
||||
this->loop_at_(1400);
|
||||
EXPECT_EQ(this->uart_.tx, command(0x03, {0x00, 0x01, 0x01, 0x00, 0x12, 0x01}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, ClampsTargetTemperature) {
|
||||
this->start_();
|
||||
this->uart_.tx.clear();
|
||||
this->sut_.make_call().set_target_temperature(-20.0f).perform();
|
||||
this->loop_at_(1200);
|
||||
// 16 C is 60.8 F, sent as 61 F.
|
||||
EXPECT_EQ(this->uart_.tx, command(0x02, {0x02, 0x27, 0x00, 0x00, 0x00, 0x3d}));
|
||||
}
|
||||
|
||||
TEST_F(PioneerWTTest, FullQueueDropsOldestCommand) {
|
||||
this->start_();
|
||||
this->uart_.tx.clear();
|
||||
// Five commands with no acknowledgement; the queue holds four.
|
||||
for (uint8_t i = 1; i <= 5; i++) {
|
||||
this->sut_.make_call()
|
||||
.set_swing_mode(i % 2 ? climate::CLIMATE_SWING_VERTICAL : climate::CLIMATE_SWING_OFF)
|
||||
.perform();
|
||||
}
|
||||
this->loop_at_(1200);
|
||||
// The first command (seq 2) was dropped, so the second (seq 3, swing off) goes out first.
|
||||
EXPECT_EQ(this->uart_.tx, command(0x03, {0x00, 0x11, SWING_OFF}));
|
||||
}
|
||||
|
||||
} // namespace esphome::pioneer_wt::testing
|
||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user