mirror of
https://github.com/esphome/esphome.git
synced 2026-11-18 19:15:59 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7959a00fc | ||
|
|
6f0d629e43 |
No files matched your search
@@ -128,51 +128,6 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
|
||||
| action or condition class that only forwards to the parent | `register_apply_action` / `register_apply_condition` |
|
||||
| enum-to-string `switch` returning literals | `PROGMEM_STRING_TABLE` with `get_log_str` / `get_progmem_str` |
|
||||
| `if (x := config.get(CONF_X)) is not None: cg.add(var.set_x(x))` | `cg.add_optional(var.set_x, config.get(CONF_X))`, when the setter takes the value unchanged |
|
||||
| `x = (x & ~mask) \| (on ? mask : 0)` or a bit-reversal loop | `assign_bits(x, mask, on)`, `reverse_bits(x)` (`esphome/core/helpers.h`) |
|
||||
| `x < lo ? lo : (x > hi ? hi : x)` | `std::clamp(x, lo, hi)` |
|
||||
| I2C read, mask, write by hand; private 16-bit register byte helpers | `update_register`, `update_register16`, `read_byte_reg16`, `write_byte_reg16` |
|
||||
| custom validator that checks which keys are set, or one schema with model checks | `cv.has_exactly_one_key`, `cv.has_at_most_one_key`, `cv.Inclusive`/`cv.Exclusive`, `cv.typed_schema` per model |
|
||||
|
||||
|
||||
## Cleanups automated reviews keep missing
|
||||
|
||||
Multi-pass cleanup reviews of contributor PRs find these again and again, and single-pass reviews
|
||||
almost never flag them. Look for each one explicitly; the matching `AGENTS.md` section 4 entry has the
|
||||
detail.
|
||||
|
||||
- **Copies within the PR** (the most common finding): two functions, branches, platform files or tests
|
||||
that differ in a constant or two. Ask for one helper, loop or table.
|
||||
- **State that copies other state:** a `write_pending_` bool beside a timer (use the return value of
|
||||
`cancel_timeout(ID)`), a `has_x_` bool beside `x_` (use `NAN` or a sentinel), an enum that can be worked
|
||||
out from stored fields.
|
||||
- **Dead guards:** null checks on members codegen always sets, `is_failed()` checks in `loop()`, range
|
||||
checks the schema already enforces, `default:` in a `switch` over every value of an `enum class` the
|
||||
component sets itself (not one cast from bus data), calls that set a member to its default
|
||||
(`set_cs_pin(nullptr)`).
|
||||
- **Member layout:** field order that leaves padding, `int`/`uint32_t` for values that fit a `uint8_t`,
|
||||
an `enum class` without `: uint8_t`, several `bool` members that could share a byte. Each costs RAM per
|
||||
instance.
|
||||
- **C++ work that belongs in codegen:** scaling, clamping, checksums or register bytes computed at boot
|
||||
from config values; ask for the plain value from `to_code`.
|
||||
- **Two `switch` ladders for one mapping:** encode and decode of the same value pairs should share one
|
||||
`static constexpr` table (`PROGMEM` on ESP8266).
|
||||
- **Compile-time constants:** `static const` or `#define` with a constant value (use `static constexpr`),
|
||||
constant tables not in `PROGMEM`, unused constants.
|
||||
- **Code for one model or feature compiled into every build:** ask for a `cg.add_define()` emitted only
|
||||
when the config uses it, with the runtime check inside the `#ifdef`.
|
||||
- **Failure handling:** `mark_failed()` outside `setup()` (runtime failures set a warning that the next
|
||||
success clears), an error enum that only picks a log message.
|
||||
- **Logging** that does not follow https://developers.esphome.io/architecture/logging/: `ESP_LOGD` on every
|
||||
reading, "Setting up" or "initialized" lines in `setup()`, a `dump_config()` made of single-line
|
||||
`ESP_LOGCONFIG` calls where related lines fit one call, a name helper that returns `const char *` instead
|
||||
of `const LogString *`.
|
||||
- **Leaf classes** that are not `final`.
|
||||
- **Unused helpers, includes and imports** left behind; lint does not catch most of them.
|
||||
- **Comments that restate the code** or tell its history: a block comment that walks through the next
|
||||
ten lines, a docstring that repeats the signature, a derivation that a one-line note plus a datasheet
|
||||
section would cover.
|
||||
- **Tests:** near-identical test functions that differ only in inputs (ask for `pytest.mark.parametrize`
|
||||
or a table-driven gtest), tests that repeat another test, test YAML that sets options to their defaults.
|
||||
|
||||
## Python conventions
|
||||
|
||||
|
||||
@@ -247,7 +247,6 @@ file does, and it is the authority when they disagree. The most useful starting
|
||||
`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`,
|
||||
`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()`,
|
||||
@@ -312,27 +311,6 @@ file does, and it is the authority when they disagree. The most useful starting
|
||||
text::Text *source_{nullptr};
|
||||
};
|
||||
```
|
||||
* **No state that copies other state:** a flag that mirrors a timer, a `has_x_` bool beside `x_`, or an enum
|
||||
that can be worked out from fields already stored is a second source of truth. Use the source:
|
||||
`pending = this->cancel_timeout(ID)`, an unset value of `NAN` or an out-of-range sentinel.
|
||||
* **No dead guards:** do not check what the caller or core already guarantees: a member that codegen always
|
||||
sets, `is_failed()` in `loop()` (core stops calling it), a value the config validation already limits, a
|
||||
`default:` in a `switch` over every value of an `enum class` the component sets itself (keep it when the
|
||||
value is cast from bus data).
|
||||
* **Member layout:** order fields so the compiler adds no padding (usually largest first), store small codes
|
||||
as `uint8_t`, declare `enum class X : uint8_t`, and pack flags into one byte.
|
||||
* **Work out constants in Python:** math that only depends on the configuration (register bytes, scale
|
||||
factors, thresholds, checksums) is done in `to_code` and passed as a plain value, not done in C++ at
|
||||
boot.
|
||||
* **One table for both directions:** a value that is encoded and decoded through the same mapping uses one
|
||||
`static constexpr` (`PROGMEM` on ESP8266) table of `{value, code}` pairs, not two `switch` ladders.
|
||||
* **Logging:** follow https://developers.esphome.io/architecture/logging/ for log levels and `dump_config()`.
|
||||
In short: a reading is logged with `ESP_LOGV`, not `ESP_LOGD` on every update; `setup()` logs no
|
||||
"Setting up" or "initialized" line (core logs setup); `dump_config()` combines related lines into one
|
||||
`ESP_LOGCONFIG` call, within the 512-byte log buffer.
|
||||
* **Leaf classes are `final`:** a component or entity class nothing derives from is declared `final`.
|
||||
* **No copies within the PR:** two functions, branches or platform files that differ in a constant or two
|
||||
become one helper, loop or table; helpers, includes and imports nothing uses are deleted.
|
||||
|
||||
* **Component Code Generation:** every component's `__init__.py` defines `DOMAIN` (its own name, checked by
|
||||
CI). Hub entities go in platform files (`sensor.py`, ...) that take the hub's id, not under the hub's own
|
||||
@@ -379,8 +357,7 @@ file does, and it is the authority when they disagree. The most useful starting
|
||||
`script/test_build_components -c <component>`. Never define buses directly in test YAML: include the
|
||||
shared packages from `tests/test_build_components/common/` with dict-style `packages:`. Test file naming,
|
||||
`validate.*.yaml` config-only tests, CI grouping, C++ unit tests and integration tests are in the
|
||||
`component-tests` skill. Tests that differ only in their inputs are one `pytest.mark.parametrize` test
|
||||
or a table-driven gtest.
|
||||
`component-tests` skill.
|
||||
|
||||
* **Debugging and Troubleshooting:**
|
||||
* **Debug Tools:**
|
||||
|
||||
@@ -494,7 +494,6 @@ 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
|
||||
|
||||
@@ -385,7 +385,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
# Adds a define and IDF component for legacy `audio_decoder.cpp`.
|
||||
if data.flac_support:
|
||||
cg.add_define("USE_AUDIO_FLAC_SUPPORT")
|
||||
add_idf_component(name="esphome/micro-flac", ref="0.3.1")
|
||||
add_idf_component(name="esphome/micro-flac", ref="0.3.0")
|
||||
_emit_memory_pair(
|
||||
data.flac.buffer_memory,
|
||||
"CONFIG_MICRO_FLAC_PREFER_PSRAM",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#include "bmi270.h"
|
||||
#include "bmi270_config.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/progmem.h"
|
||||
@@ -22,40 +21,48 @@ static constexpr size_t MAX_I2C_BUFFER_SIZE = 32;
|
||||
static constexpr size_t MAX_I2C_BUFFER_SIZE = 256;
|
||||
#endif
|
||||
|
||||
// Configuration blob upload
|
||||
// The BMI270 requires a firmware config blob to be written to its internal
|
||||
// memory after every power-on before sensors can be used.
|
||||
|
||||
bool BMI270Component::load_config_file_() {
|
||||
// The config port is only reachable with advanced power save off
|
||||
// 1. Disable advanced power-save so the config port is accessible
|
||||
if (!this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_ADV_POWER_SAVE_OFF))
|
||||
return false;
|
||||
delay(1);
|
||||
|
||||
// 2. Prepare config load: write 0x00 to INIT_CTRL to start
|
||||
if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_START))
|
||||
return false;
|
||||
|
||||
// 3. Burst-write the config in pages
|
||||
const uint8_t *cfg = BMI270_CONFIG_FILE;
|
||||
constexpr size_t cfg_len = sizeof(BMI270_CONFIG_FILE);
|
||||
// The register byte goes first, so each burst is copied once and sent with write()
|
||||
uint8_t buf[1 + MAX_I2C_BUFFER_SIZE];
|
||||
buf[0] = BMI270_REG_INIT_DATA;
|
||||
size_t index = 0;
|
||||
|
||||
while (index != cfg_len) {
|
||||
// INIT_ADDR_0 takes the word address bits 0-3 and INIT_ADDR_1 bits 4-11
|
||||
const uint8_t addr[2] = {static_cast<uint8_t>((index / 2) & 0x0F), static_cast<uint8_t>((index / 2) >> 4)};
|
||||
if (this->write_register(BMI270_REG_INIT_ADDR_0, addr, sizeof(addr)) != i2c::ERROR_OK)
|
||||
// Set the page address in INIT_ADDR registers
|
||||
uint8_t addr_lsb = (uint8_t) ((index / 2) & 0x0F);
|
||||
uint8_t addr_msb = (uint8_t) ((index / 2) >> 4);
|
||||
if (!this->write_byte(BMI270_REG_INIT_ADDR_0, addr_lsb))
|
||||
return false;
|
||||
if (!this->write_byte(BMI270_REG_INIT_ADDR_0 + 1, addr_msb))
|
||||
return false;
|
||||
|
||||
// Write a burst of up to the maximum allowed size
|
||||
size_t burst = clamp_at_most(cfg_len - index, MAX_I2C_BUFFER_SIZE);
|
||||
progmem_memcpy(buf + 1, BMI270_CONFIG_FILE + index, burst);
|
||||
if (this->write(buf, burst + 1) != i2c::ERROR_OK)
|
||||
if (this->write_register(BMI270_REG_INIT_DATA, cfg + index, burst) != i2c::ERROR_OK)
|
||||
return false;
|
||||
|
||||
index += burst;
|
||||
// 256 bursts at 50 kHz, or through an I2C multiplexer, outlast the ESP8266 soft watchdog
|
||||
App.feed_wdt();
|
||||
}
|
||||
|
||||
// 4. Signal end of config load
|
||||
if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_DONE))
|
||||
return false;
|
||||
delay(20); // The datasheet asks for at least 20 ms before INTERNAL_STATUS is valid
|
||||
delay(20); // spec: wait ≥20 ms for init to complete
|
||||
|
||||
// 5. Check INTERNAL_STATUS: bit[0:3] should be 0x01 ("initialisation OK")
|
||||
uint8_t status = 0;
|
||||
if (!this->read_byte(BMI270_REG_INTERNAL_STATUS, &status))
|
||||
return false;
|
||||
@@ -66,52 +73,74 @@ bool BMI270Component::load_config_file_() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// setup() ─
|
||||
|
||||
void BMI270Component::setup() {
|
||||
MotionComponent::setup();
|
||||
// 1. Verify chip ID
|
||||
if (!this->check_chip_id(this, BMI270_REG_CHIP_ID, BMI270_CHIP_ID_VALUE))
|
||||
return;
|
||||
|
||||
// 2. Soft-reset via CMD register (0x7E = 0xB6)
|
||||
if (!this->setup_check(this->write_byte(BMI270_REG_CMD, BMI270_CMD_SOFT_RESET)))
|
||||
return;
|
||||
delay(20);
|
||||
|
||||
if (!this->setup_check(this->load_config_file_(), LOG_STR("Config file upload failed")))
|
||||
// 4. Upload the configuration blob
|
||||
if (!this->setup_check(load_config_file_(), LOG_STR("Config file upload failed")))
|
||||
return;
|
||||
ESP_LOGD(TAG, "Config blob uploaded ✓");
|
||||
|
||||
// 5. Configure accelerometer
|
||||
// ACC_CONF: ODR | BWP(0x2 = normal avg4) | perf_mode(1)
|
||||
uint8_t acc_conf =
|
||||
(uint8_t) (accel_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
|
||||
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf)))
|
||||
return;
|
||||
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_RANGE, (uint8_t) accel_range_)))
|
||||
return;
|
||||
|
||||
// Normal filter bandwidth; performance mode for the accelerometer, noise and filter performance for the gyroscope
|
||||
const uint8_t acc_conf =
|
||||
this->accel_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
|
||||
const uint8_t gyr_conf = this->gyro_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
|
||||
BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
|
||||
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf) &&
|
||||
this->write_byte(BMI270_REG_ACC_RANGE, this->accel_range_) &&
|
||||
this->write_byte(BMI270_REG_GYR_CONF, gyr_conf) &&
|
||||
this->write_byte(BMI270_REG_GYR_RANGE, this->gyro_range_) &&
|
||||
this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
|
||||
// 6. Configure gyroscope
|
||||
// GYR_CONF: ODR | BWP(0x2 = normal) | noise_perf(1) | filter_perf(1)
|
||||
uint8_t gyr_conf = (uint8_t) (gyro_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
|
||||
BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
|
||||
if (!this->setup_check(this->write_byte(BMI270_REG_GYR_CONF, gyr_conf)))
|
||||
return;
|
||||
if (!this->setup_check(this->write_byte(BMI270_REG_GYR_RANGE, (uint8_t) gyro_range_)))
|
||||
return;
|
||||
|
||||
// 7. Enable accelerometer, gyroscope, and temperature sensor
|
||||
// PWR_CTRL bits: temp_en[3] | gyr_en[2] | acc_en[1]
|
||||
if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
|
||||
return;
|
||||
delay(5);
|
||||
|
||||
// Advanced power save stays off; FIFO self-wakeup on
|
||||
// 8. Re-enable advanced power save (optional; keeps current low between reads)
|
||||
// Disabled here for simplicity – leave in performance mode
|
||||
// bit1 = fifo_self_wakeup
|
||||
if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_FIFO_SELF_WAKEUP)))
|
||||
return;
|
||||
|
||||
// 9. Optionally bring up whatever is wired to the aux interface.
|
||||
// This is entirely additive: it is off by default, and failure only disables
|
||||
// magnetometer reporting rather than the whole component.
|
||||
#ifdef USE_BMI270_BMM150
|
||||
// A missing magnetometer only disables magnetometer reporting
|
||||
if (this->aux_device_ == BMI270_AUX_DEVICE_BMM150) {
|
||||
const LogString *failed_step = this->setup_magnetometer_();
|
||||
this->magnetometer_ready_ = failed_step == nullptr;
|
||||
this->magnetometer_ready_ = this->setup_magnetometer_();
|
||||
if (!this->magnetometer_ready_) {
|
||||
ESP_LOGW(TAG, "BMM150 magnetometer setup failed at %s; continuing without it", LOG_STR_ARG(failed_step));
|
||||
ESP_LOGW(TAG, "BMM150 magnetometer setup failed; continuing without it");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
ESP_LOGCONFIG(TAG, "BMI270 initialised successfully");
|
||||
}
|
||||
|
||||
#ifdef USE_BMI270_BMM150
|
||||
static_assert(BMM150_TRIM_BLOCK_LEN == BMI270_AUX_DATA_LEN, "each trim block is one aux read");
|
||||
|
||||
bool BMI270Component::wait_for_aux_idle_() {
|
||||
static constexpr uint32_t AUX_IDLE_TIMEOUT_MS = 20;
|
||||
bool BMI270Component::wait_for_aux_idle_(uint32_t timeout_ms) {
|
||||
// The STATUS aux-busy bit is set while an aux transaction is in flight. Aux transaction
|
||||
// duration depends on the attached device's own timing, so poll with a bounded
|
||||
// timeout instead of guessing a fixed delay.
|
||||
uint32_t start = millis();
|
||||
while (true) {
|
||||
uint8_t status = 0;
|
||||
@@ -119,63 +148,98 @@ bool BMI270Component::wait_for_aux_idle_() {
|
||||
return false;
|
||||
if ((status & BMI270_STATUS_AUX_BUSY) == 0)
|
||||
return true;
|
||||
if (millis() - start >= AUX_IDLE_TIMEOUT_MS)
|
||||
if (millis() - start >= timeout_ms)
|
||||
return false;
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
|
||||
bool BMI270Component::write_aux_register_(uint8_t reg, uint8_t value) {
|
||||
return this->write_byte(BMI270_REG_AUX_WR_DATA, value) && this->write_byte(BMI270_REG_AUX_WR_ADDR, reg) &&
|
||||
this->wait_for_aux_idle_();
|
||||
if (!this->write_byte(BMI270_REG_AUX_WR_DATA, value))
|
||||
return false;
|
||||
if (!this->write_byte(BMI270_REG_AUX_WR_ADDR, reg))
|
||||
return false;
|
||||
return this->wait_for_aux_idle_(20);
|
||||
}
|
||||
|
||||
bool BMI270Component::read_aux_block_(uint8_t reg, uint8_t *buf) {
|
||||
return this->write_byte(BMI270_REG_AUX_RD_ADDR, reg) && this->wait_for_aux_idle_() &&
|
||||
this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
|
||||
if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, reg))
|
||||
return false;
|
||||
if (!this->wait_for_aux_idle_(20))
|
||||
return false;
|
||||
return this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
|
||||
}
|
||||
|
||||
// Follows the Bosch BMI270 aux-interface sequence; ends in auto-burst mode, where the BMI270 keeps
|
||||
// AUX_X/Y/Z/R filled from the BMM150's data registers
|
||||
const LogString *BMI270Component::setup_magnetometer_() {
|
||||
if (!(this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN) &&
|
||||
this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8) &&
|
||||
this->write_byte(BMI270_REG_AUX_DEV_ID, this->aux_device_address_ << 1)))
|
||||
return LOG_STR("aux interface");
|
||||
bool BMI270Component::read_magnetometer_trim_() {
|
||||
uint8_t regs[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
|
||||
for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
|
||||
if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, regs + i * BMM150_TRIM_BLOCK_LEN))
|
||||
return false;
|
||||
}
|
||||
this->mag_trim_ = bmm150_parse_trim(regs);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BMI270Component::setup_magnetometer_() {
|
||||
// Sequence adapted from the Bosch BMI270 aux-interface protocol: enable the secondary
|
||||
// I2C master in manual mode, point it at the BMM150's address, power the BMM150 up
|
||||
// and soft-reset it, verify its chip ID, read its factory trim values, put it in
|
||||
// normal/30Hz mode, then switch the aux interface to auto-burst mode so BMI270 keeps
|
||||
// AUX_X/Y/Z/R refreshed from the BMM150's data registers.
|
||||
ESP_LOGD(TAG, "Setting up BMM150 magnetometer via BMI270 aux interface...");
|
||||
|
||||
if (!this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN))
|
||||
return false;
|
||||
if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8))
|
||||
return false;
|
||||
if (!this->write_byte(BMI270_REG_AUX_DEV_ID, (uint8_t) (this->aux_device_address_ << 1)))
|
||||
return false;
|
||||
|
||||
// Suspend -> sleep, then a soft reset so the BMM150 starts from a known state even if it
|
||||
// stayed powered across a restart. The chip ID is only readable once the power bit is set.
|
||||
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON))
|
||||
return LOG_STR("power-on");
|
||||
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON)) {
|
||||
ESP_LOGW(TAG, "BMM150 power-on write timed out");
|
||||
return false;
|
||||
}
|
||||
delay(BMM150_START_UP_TIME_MS);
|
||||
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET))
|
||||
return LOG_STR("soft reset");
|
||||
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET)) {
|
||||
ESP_LOGW(TAG, "BMM150 soft-reset write timed out");
|
||||
return false;
|
||||
}
|
||||
delay(BMM150_SOFT_RESET_TIME_MS);
|
||||
|
||||
uint8_t chip_id[BMI270_AUX_DATA_LEN];
|
||||
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id))
|
||||
return LOG_STR("chip ID read");
|
||||
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id)) {
|
||||
ESP_LOGW(TAG, "BMM150 chip-ID read failed");
|
||||
return false;
|
||||
}
|
||||
if (chip_id[0] != BMM150_CHIP_ID_VALUE) {
|
||||
ESP_LOGW(TAG, "BMM150 chip ID 0x%02X, expected 0x%02X", chip_id[0], BMM150_CHIP_ID_VALUE);
|
||||
return LOG_STR("chip ID check");
|
||||
ESP_LOGW(TAG, "BMM150 not detected (chip ID 0x%02X, expected 0x%02X)", chip_id[0], BMM150_CHIP_ID_VALUE);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t trim[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
|
||||
for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
|
||||
if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, trim + i * BMM150_TRIM_BLOCK_LEN))
|
||||
return LOG_STR("trim read");
|
||||
if (!this->read_magnetometer_trim_()) {
|
||||
ESP_LOGW(TAG, "BMM150 trim data read failed");
|
||||
return false;
|
||||
}
|
||||
this->mag_trim_ = bmm150_parse_trim(trim);
|
||||
|
||||
if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ))
|
||||
return LOG_STR("normal mode");
|
||||
if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ)) {
|
||||
ESP_LOGW(TAG, "BMM150 mode write timed out");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
|
||||
BMI270_AUX_IF_CONF_RD_BURST_8) &&
|
||||
this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB) &&
|
||||
this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN)))
|
||||
return LOG_STR("auto-burst mode");
|
||||
return nullptr;
|
||||
// Switch to auto-burst mode: BMI270 will keep polling 8 bytes from the BMM150's
|
||||
// data registers (0x42) into its own AUX_X/Y/Z/R registers automatically.
|
||||
if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
|
||||
BMI270_AUX_IF_CONF_RD_BURST_8))
|
||||
return false;
|
||||
if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB))
|
||||
return false;
|
||||
if (!this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN))
|
||||
return false;
|
||||
|
||||
ESP_LOGD(TAG, "BMM150 magnetometer ready");
|
||||
return true;
|
||||
}
|
||||
#endif // USE_BMI270_BMM150
|
||||
|
||||
@@ -185,10 +249,9 @@ void BMI270Component::dump_config() {
|
||||
if (this->is_failed())
|
||||
return;
|
||||
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Accel range : %s\n"
|
||||
" Gyro range : %s",
|
||||
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)),
|
||||
ESP_LOGCONFIG(TAG, " Accel range : %s",
|
||||
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)));
|
||||
ESP_LOGCONFIG(TAG, " Gyro range : %s",
|
||||
LOG_STR_ARG(GyroRangeStrings::get_log_str(this->gyro_range_, GyroRangeStrings::LAST_INDEX)));
|
||||
#ifdef USE_BMI270_BMM150
|
||||
if (this->aux_device_ == BMI270_AUX_DEVICE_BMM150) {
|
||||
@@ -199,6 +262,9 @@ void BMI270Component::dump_config() {
|
||||
MotionComponent::dump_config();
|
||||
}
|
||||
|
||||
// update() ─
|
||||
// Reads all 6 axes + temperature in one block
|
||||
|
||||
bool BMI270Component::update_data(motion::MotionData &data) {
|
||||
if (this->is_failed())
|
||||
return false;
|
||||
|
||||
@@ -12,15 +12,18 @@
|
||||
|
||||
namespace esphome::bmi270 {
|
||||
|
||||
// Register map
|
||||
static constexpr uint8_t BMI270_REG_CHIP_ID = 0x00;
|
||||
static constexpr uint8_t BMI270_REG_ERR_REG = 0x02;
|
||||
static constexpr uint8_t BMI270_REG_STATUS = 0x03;
|
||||
static constexpr uint8_t BMI270_REG_DATA_8 = 0x0C; // ACC_X LSB
|
||||
static constexpr uint8_t BMI270_REG_DATA_14 = 0x12; // GYR_X LSB
|
||||
static constexpr uint8_t BMI270_REG_TEMP_0 = 0x22;
|
||||
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23;
|
||||
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23; // temperature (2 bytes big-endian ish)
|
||||
|
||||
// Accel, gyro, 10 unused bytes, then temperature: 0x0C to 0x23
|
||||
static constexpr uint8_t REG_READ_LEN = BMI270_REG_TEMP_MSB - BMI270_REG_DATA_8 + 1;
|
||||
static constexpr uint8_t REG_READ_LEN =
|
||||
BMI270_REG_TEMP_MSB - BMI270_REG_DATA_8 +
|
||||
1; // 0x23 - 0x0C + 1 = 0x18 bytes total for accel(6) + gyro(6) + temp(2) + padding(4)
|
||||
|
||||
static constexpr uint8_t BMI270_REG_PWR_CONF = 0x7C;
|
||||
static constexpr uint8_t BMI270_REG_PWR_CTRL = 0x7D;
|
||||
@@ -77,6 +80,7 @@ static constexpr uint8_t BMI270_AUX_IF_CONF_RD_BURST_8 = 0x03; // bits 1:0
|
||||
static constexpr uint8_t BMI270_AUX_DATA_LEN = 8;
|
||||
static_assert(BMI270_REG_AUX_X_LSB + BMI270_AUX_DATA_LEN == BMI270_REG_DATA_8, "aux data must precede accel data");
|
||||
|
||||
// Accelerometer range options
|
||||
enum BMI270AccelRange : uint8_t {
|
||||
BMI270_ACCEL_RANGE_2G = 0x00,
|
||||
BMI270_ACCEL_RANGE_4G = 0x01,
|
||||
@@ -84,6 +88,7 @@ enum BMI270AccelRange : uint8_t {
|
||||
BMI270_ACCEL_RANGE_16G = 0x03,
|
||||
};
|
||||
|
||||
// Accelerometer ODR options
|
||||
enum BMI270AccelODR : uint8_t {
|
||||
BMI270_ACCEL_ODR_12_5 = 0x05,
|
||||
BMI270_ACCEL_ODR_25 = 0x06,
|
||||
@@ -95,6 +100,7 @@ enum BMI270AccelODR : uint8_t {
|
||||
BMI270_ACCEL_ODR_1600 = 0x0C,
|
||||
};
|
||||
|
||||
// Gyroscope range options
|
||||
enum BMI270GyroRange : uint8_t {
|
||||
BMI270_GYRO_RANGE_2000 = 0x00,
|
||||
BMI270_GYRO_RANGE_1000 = 0x01,
|
||||
@@ -103,6 +109,7 @@ enum BMI270GyroRange : uint8_t {
|
||||
BMI270_GYRO_RANGE_125 = 0x04,
|
||||
};
|
||||
|
||||
// Gyroscope ODR options
|
||||
enum BMI270GyroODR : uint8_t {
|
||||
BMI270_GYRO_ODR_25 = 0x06,
|
||||
BMI270_GYRO_ODR_50 = 0x07,
|
||||
@@ -123,11 +130,14 @@ enum BMI270AuxDevice : uint8_t {
|
||||
};
|
||||
#endif
|
||||
|
||||
// Main component class
|
||||
class BMI270Component final : public motion::MotionComponent, public i2c::I2CDevice {
|
||||
public:
|
||||
// Lifecycle
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
|
||||
// Configuration setters
|
||||
void set_accel_range(BMI270AccelRange r) { this->accel_range_ = r; }
|
||||
void set_accel_odr(BMI270AccelODR o) { this->accel_odr_ = o; }
|
||||
void set_gyro_range(BMI270GyroRange r) { this->gyro_range_ = r; }
|
||||
@@ -143,15 +153,21 @@ class BMI270Component final : public motion::MotionComponent, public i2c::I2CDev
|
||||
bool update_data(motion::MotionData &data) override;
|
||||
bool load_config_file_();
|
||||
#ifdef USE_BMI270_BMM150
|
||||
// Returns the step that failed, or nullptr once the BMM150 is running
|
||||
const LogString *setup_magnetometer_();
|
||||
// Polls the aux busy bit, as the aux transaction time depends on the attached device
|
||||
bool wait_for_aux_idle_();
|
||||
// Manual-mode aux read of 8 bytes starting at `reg` on the aux device
|
||||
// Brings up the BMM150 over the BMI270's aux interface. Optional: on failure this only
|
||||
// disables magnetometer reporting, it does not fail the whole component (accel/gyro still work).
|
||||
bool setup_magnetometer_();
|
||||
// Blocking poll of the aux-transaction-busy bit; aux transaction time depends on the
|
||||
// attached device, so this is bounded by retries/timeout rather than a fixed delay.
|
||||
bool wait_for_aux_idle_(uint32_t timeout_ms);
|
||||
// Manual-mode aux read of 8 bytes starting at `reg` on the aux device.
|
||||
bool read_aux_block_(uint8_t reg, uint8_t *buf);
|
||||
// Manual-mode aux write of one byte to `reg` on the aux device.
|
||||
bool write_aux_register_(uint8_t reg, uint8_t value);
|
||||
// Reads the BMM150 factory trim values used to compensate its samples.
|
||||
bool read_magnetometer_trim_();
|
||||
#endif
|
||||
|
||||
// Config
|
||||
BMI270AccelRange accel_range_{BMI270_ACCEL_RANGE_4G};
|
||||
BMI270AccelODR accel_odr_{BMI270_ACCEL_ODR_100};
|
||||
BMI270GyroRange gyro_range_{BMI270_GYRO_RANGE_2000};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
namespace esphome::bmi270 {
|
||||
|
||||
@@ -45,7 +44,7 @@ POSSIBILITY OF SUCH DAMAGE.
|
||||
after every power cycle, before any sensor data can be read.
|
||||
--------------------------------------------------------------------------- */
|
||||
|
||||
static constexpr uint8_t BMI270_CONFIG_FILE[] PROGMEM = {
|
||||
static constexpr uint8_t BMI270_CONFIG_FILE[] = {
|
||||
0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x3d, 0xb1, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x91, 0x03, 0x80, 0x2e, 0xbc,
|
||||
0xb0, 0x80, 0x2e, 0xa3, 0x03, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x00, 0xb0, 0x50, 0x30, 0x21, 0x2e, 0x59, 0xf5,
|
||||
0x10, 0x30, 0x21, 0x2e, 0x6a, 0xf5, 0x80, 0x2e, 0x3b, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x19, 0x01, 0x00, 0x22,
|
||||
|
||||
@@ -3,8 +3,11 @@
|
||||
#include <cstdint>
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
// BMM150 magnetometer behind the BMI270's aux interface; it is not on the main I2C bus, so it is not
|
||||
// its own component
|
||||
// BMM150 magnetometer definitions - the chip that can optionally be wired to the BMI270's
|
||||
// auxiliary (secondary I2C master) interface. Lives in its own header/namespace because this
|
||||
// is BMM150-specific driver knowledge, not BMI270 knowledge - it just can't be a standalone
|
||||
// ESPHome component, since the BMM150 has no address of its own on the main I2C bus and is only
|
||||
// reachable by having the BMI270 proxy register reads/writes through its aux interface.
|
||||
namespace esphome::bmi270::bmm150 {
|
||||
|
||||
static constexpr uint8_t BMM150_DEFAULT_I2C_ADDRESS = 0x10;
|
||||
@@ -61,23 +64,20 @@ inline uint16_t bmm150_trim_word(const uint8_t *regs, uint8_t reg) {
|
||||
return encode_value_le<uint16_t>(®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>(bmm150_trim_byte(regs, BMM150_TRIM_X1));
|
||||
trim.y1 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_Y1));
|
||||
trim.x1 = static_cast<int8_t>(regs[BMM150_TRIM_X1 - BMM150_REG_TRIM_START]);
|
||||
trim.y1 = static_cast<int8_t>(regs[BMM150_TRIM_Y1 - BMM150_REG_TRIM_START]);
|
||||
trim.z4 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z4));
|
||||
trim.x2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_X2));
|
||||
trim.y2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_Y2));
|
||||
trim.x2 = static_cast<int8_t>(regs[BMM150_TRIM_X2 - BMM150_REG_TRIM_START]);
|
||||
trim.y2 = static_cast<int8_t>(regs[BMM150_TRIM_Y2 - BMM150_REG_TRIM_START]);
|
||||
trim.z2 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z2));
|
||||
trim.z1 = bmm150_trim_word(regs, BMM150_TRIM_Z1);
|
||||
trim.xyz1 = bmm150_trim_word(regs, BMM150_TRIM_XYZ1) & BMM150_TRIM_XYZ1_MASK;
|
||||
trim.z3 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z3));
|
||||
trim.xy2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_XY2));
|
||||
trim.xy1 = bmm150_trim_byte(regs, BMM150_TRIM_XY1);
|
||||
trim.xy2 = static_cast<int8_t>(regs[BMM150_TRIM_XY2 - BMM150_REG_TRIM_START]);
|
||||
trim.xy1 = regs[BMM150_TRIM_XY1 - BMM150_REG_TRIM_START];
|
||||
return trim;
|
||||
}
|
||||
|
||||
@@ -108,11 +108,11 @@ inline float bmm150_compensate_z(const BMM150Trim &trim, int16_t raw, uint16_t r
|
||||
|
||||
// Converts 8 raw bytes from the BMM150 data registers (X, Y, Z, RHALL; 0x42-0x49) to compensated µT.
|
||||
inline BMM150Data bmm150_convert(const BMM150Trim &trim, const uint8_t *raw) {
|
||||
// Left-aligned in their 16-bit words: X/Y are 13-bit, Z is 15-bit, RHALL is 14-bit
|
||||
const int16_t x = encode_value_le<int16_t>(&raw[0]) >> 3;
|
||||
const int16_t y = encode_value_le<int16_t>(&raw[2]) >> 3;
|
||||
const int16_t z = encode_value_le<int16_t>(&raw[4]) >> 1;
|
||||
const uint16_t rhall = encode_value_le<uint16_t>(&raw[6]) >> 2;
|
||||
// X/Y are 13-bit (LSB byte bits 7:3), Z is 15-bit (bits 7:1), RHALL is 14-bit (bits 7:2).
|
||||
int16_t x = (int16_t) (((int16_t) (int8_t) raw[1] * 32) | (raw[0] >> 3));
|
||||
int16_t y = (int16_t) (((int16_t) (int8_t) raw[3] * 32) | (raw[2] >> 3));
|
||||
int16_t z = (int16_t) (((int16_t) (int8_t) raw[5] * 128) | (raw[4] >> 1));
|
||||
uint16_t rhall = (uint16_t) (((uint16_t) raw[7] << 6) | (raw[6] >> 2));
|
||||
return BMM150Data{
|
||||
.x = bmm150_compensate_xy(trim, trim.x1, trim.x2, x, rhall),
|
||||
.y = bmm150_compensate_xy(trim, trim.y1, trim.y2, y, rhall),
|
||||
|
||||
@@ -17,14 +17,6 @@ DEPENDENCIES = ["i2c"]
|
||||
CONF_AUX_ADDRESS = "aux_address"
|
||||
CONF_AUX_DEVICE = "aux_device"
|
||||
|
||||
# to_code skips the setters at these values, so each must match its member default in bmi270.h
|
||||
DEFAULT_ACCELEROMETER_RANGE = "4G"
|
||||
DEFAULT_ACCELEROMETER_ODR = "100HZ"
|
||||
DEFAULT_GYROSCOPE_RANGE = "2000DPS"
|
||||
DEFAULT_GYROSCOPE_ODR = "200HZ"
|
||||
# The BMM150's fixed address
|
||||
DEFAULT_AUX_ADDRESS = 0x10
|
||||
|
||||
# Enum proxies (must match the C++ enum values exactly)
|
||||
BMI270AuxDevice = bmi270_ns.enum("BMI270AuxDevice")
|
||||
BMI270AccelRange = bmi270_ns.enum("BMI270AccelRange")
|
||||
@@ -65,49 +57,50 @@ GYRO_ODR_OPTIONS = {
|
||||
"3200HZ": BMI270GyroODR.BMI270_GYRO_ODR_3200,
|
||||
}
|
||||
|
||||
# Top-level CONFIG_SCHEMA
|
||||
CONFIG_SCHEMA = (
|
||||
motion_schema(BMI270Component, has_accel=True, has_gyro=True)
|
||||
.extend(
|
||||
{
|
||||
cv.Optional(
|
||||
CONF_ACCELEROMETER_RANGE, default=DEFAULT_ACCELEROMETER_RANGE
|
||||
): cv.enum(ACCEL_RANGE_OPTIONS, upper=True),
|
||||
cv.Optional(
|
||||
CONF_ACCELEROMETER_ODR, default=DEFAULT_ACCELEROMETER_ODR
|
||||
): cv.enum(ACCEL_ODR_OPTIONS, upper=True),
|
||||
cv.Optional(CONF_GYROSCOPE_RANGE, default=DEFAULT_GYROSCOPE_RANGE): cv.enum(
|
||||
cv.Optional(CONF_ACCELEROMETER_RANGE, default="4G"): cv.enum(
|
||||
ACCEL_RANGE_OPTIONS, upper=True
|
||||
),
|
||||
cv.Optional(CONF_ACCELEROMETER_ODR, default="100HZ"): cv.enum(
|
||||
ACCEL_ODR_OPTIONS, upper=True
|
||||
),
|
||||
cv.Optional(CONF_GYROSCOPE_RANGE, default="2000DPS"): cv.enum(
|
||||
GYRO_RANGE_OPTIONS, upper=True
|
||||
),
|
||||
cv.Optional(CONF_GYROSCOPE_ODR, default=DEFAULT_GYROSCOPE_ODR): cv.enum(
|
||||
cv.Optional(CONF_GYROSCOPE_ODR, default="200HZ"): cv.enum(
|
||||
GYRO_ODR_OPTIONS, upper=True
|
||||
),
|
||||
# Optional device wired to the BMI270's aux interface (not the main I2C bus).
|
||||
# Defaults to NONE so existing configs/boards are unaffected.
|
||||
cv.Optional(CONF_AUX_DEVICE, default="NONE"): cv.one_of(
|
||||
"NONE", "BMM150", upper=True
|
||||
),
|
||||
cv.Optional(CONF_AUX_ADDRESS, default=DEFAULT_AUX_ADDRESS): cv.i2c_address,
|
||||
# Default matches the BMM150's fixed I2C address; irrelevant when aux_device is NONE.
|
||||
cv.Optional(CONF_AUX_ADDRESS, default=0x10): cv.i2c_address,
|
||||
}
|
||||
)
|
||||
.extend(i2c.i2c_device_schema(0x68))
|
||||
)
|
||||
|
||||
|
||||
# Code generation
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await new_motion_component(config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
# The C++ members already hold the schema defaults
|
||||
for key, default, setter in (
|
||||
(CONF_ACCELEROMETER_RANGE, DEFAULT_ACCELEROMETER_RANGE, var.set_accel_range),
|
||||
(CONF_ACCELEROMETER_ODR, DEFAULT_ACCELEROMETER_ODR, var.set_accel_odr),
|
||||
(CONF_GYROSCOPE_RANGE, DEFAULT_GYROSCOPE_RANGE, var.set_gyro_range),
|
||||
(CONF_GYROSCOPE_ODR, DEFAULT_GYROSCOPE_ODR, var.set_gyro_odr),
|
||||
):
|
||||
if config[key] != default:
|
||||
cg.add(setter(config[key]))
|
||||
# Accelerometer sensors
|
||||
# Hardware configuration
|
||||
cg.add(var.set_accel_range(config[CONF_ACCELEROMETER_RANGE]))
|
||||
cg.add(var.set_accel_odr(config[CONF_ACCELEROMETER_ODR]))
|
||||
cg.add(var.set_gyro_range(config[CONF_GYROSCOPE_RANGE]))
|
||||
cg.add(var.set_gyro_odr(config[CONF_GYROSCOPE_ODR]))
|
||||
# The aux interface code only compiles when some instance has a BMM150; the
|
||||
# instance still records its own device, as another one may have none
|
||||
if config[CONF_AUX_DEVICE] == "BMM150":
|
||||
cg.add_define("USE_BMI270_BMM150")
|
||||
cg.add(var.set_aux_device(BMI270AuxDevice.BMI270_AUX_DEVICE_BMM150))
|
||||
if (address := config[CONF_AUX_ADDRESS]) != DEFAULT_AUX_ADDRESS:
|
||||
cg.add(var.set_aux_device_address(address))
|
||||
cg.add(var.set_aux_device_address(config[CONF_AUX_ADDRESS]))
|
||||
@@ -215,8 +215,9 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
|
||||
break;
|
||||
}
|
||||
|
||||
for (auto &entry : this->services_) {
|
||||
entry.service->gatts_event_handler(event, gatts_if, param);
|
||||
// Indexed: a handler (an on_write lambda) can create a service, and push_back may move the vector.
|
||||
for (size_t i = 0; i < this->services_.size(); i++) { // NOLINT(modernize-loop-convert)
|
||||
this->services_[i].service->gatts_event_handler(event, gatts_if, param);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
@@ -189,61 +188,6 @@ def get_board_pins() -> dict[str, int]:
|
||||
return lookup_board_pins(get_libretiny_board())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HardwareUart:
|
||||
"""A hardware UART of the configured board and the pin numbers it can use."""
|
||||
|
||||
port: int
|
||||
tx_pins: tuple[int, ...]
|
||||
rx_pins: tuple[int, ...]
|
||||
# The board lists pin choices instead of a default pin for this direction
|
||||
tx_pin_choices: bool
|
||||
rx_pin_choices: bool
|
||||
|
||||
@property
|
||||
def pin_choices(self) -> bool:
|
||||
"""True when the pins must be passed when the UART starts."""
|
||||
return self.tx_pin_choices or self.rx_pin_choices
|
||||
|
||||
|
||||
def get_hardware_uarts() -> list[HardwareUart]:
|
||||
"""Hardware UARTs of the configured board; empty for a board without pin data."""
|
||||
board_pins = get_board_pins()
|
||||
uarts = []
|
||||
for port in range(3):
|
||||
pins: dict[str, list[int]] = {"TX": [], "RX": []}
|
||||
choices: dict[str, bool] = {"TX": False, "RX": False}
|
||||
for role, role_pins in pins.items():
|
||||
name = f"SERIAL{port}_{role}"
|
||||
for key, pin in board_pins.items():
|
||||
if key == name:
|
||||
role_pins.append(pin)
|
||||
elif key.startswith(f"{name}_"):
|
||||
role_pins.append(pin)
|
||||
choices[role] = True
|
||||
if pins["TX"] or pins["RX"]:
|
||||
uarts.append(
|
||||
HardwareUart(
|
||||
port,
|
||||
tuple(pins["TX"]),
|
||||
tuple(pins["RX"]),
|
||||
choices["TX"],
|
||||
choices["RX"],
|
||||
)
|
||||
)
|
||||
return uarts
|
||||
|
||||
|
||||
def has_software_serial() -> bool:
|
||||
"""True when the family's Arduino core has SoftwareSerial (LT_ARD_HAS_SOFTSERIAL)."""
|
||||
return get_libretiny_family() == FAMILY_RTL8710B
|
||||
|
||||
|
||||
def can_choose_uart_pins() -> bool:
|
||||
"""True when SerialClass::begin() takes the pins, which LibreTiny added in 1.12.0."""
|
||||
return CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION] >= cv.Version(1, 12, 0)
|
||||
|
||||
|
||||
def only_on_family(*, supported=None, unsupported=None):
|
||||
"""Config validator for features only available on some LibreTiny families."""
|
||||
if supported is not None and not isinstance(supported, list):
|
||||
|
||||
@@ -151,8 +151,7 @@ Color color_from_light_color_values(LightColorValues val) {
|
||||
auto r = to_uint8_scale(val.get_color_brightness() * val.get_red());
|
||||
auto g = to_uint8_scale(val.get_color_brightness() * val.get_green());
|
||||
auto b = to_uint8_scale(val.get_color_brightness() * val.get_blue());
|
||||
// White keeps its default of 100% in RGB mode, where it must not count as the strongest channel
|
||||
uint8_t w = val.get_color_mode() == ColorMode::RGB ? 0 : to_uint8_scale(val.get_white());
|
||||
auto w = to_uint8_scale(val.get_white());
|
||||
return Color(r, g, b, w);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,45 +12,6 @@ uint8_t ESPColorCorrection::gamma_correct_(uint8_t value) const {
|
||||
return result;
|
||||
}
|
||||
|
||||
uint16_t ESPColorCorrection::gamma_level_(uint8_t value) const {
|
||||
if (this->gamma_table_ == nullptr)
|
||||
return value * 257;
|
||||
return progmem_read_uint16(&this->gamma_table_[value]);
|
||||
}
|
||||
|
||||
uint8_t ESPColorCorrection::gamma_round_(uint8_t value) const {
|
||||
if (this->gamma_table_ == nullptr)
|
||||
return value;
|
||||
return (progmem_read_uint16(&this->gamma_table_[value]) + 128) / 257;
|
||||
}
|
||||
|
||||
// Lighting every non-zero channel instead would turn a dim red with a trace of green into yellow
|
||||
Color ESPColorCorrection::correct_dark_pixel_(Color color) const {
|
||||
// Compared without the local brightness, which is the same for every channel: the scaled 8-bit
|
||||
// values are too coarse to compare at the lowest brightness
|
||||
uint16_t strengths[4];
|
||||
uint16_t max_strength = 0;
|
||||
bool lit = false;
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
strengths[i] = color[i] * this->max_brightness_[i];
|
||||
max_strength = std::max(max_strength, strengths[i]);
|
||||
lit |= esp_scale8_twice(color[i], this->max_brightness_[i], this->local_brightness_) != 0;
|
||||
}
|
||||
Color res;
|
||||
if (!lit)
|
||||
return res;
|
||||
// Stretch the strongest channel to full scale and round the others against it; the table is too
|
||||
// coarse to compare its lowest levels
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
if (strengths[i] == max_strength) {
|
||||
res[i] = 1;
|
||||
} else if (strengths[i] != 0) {
|
||||
res[i] = this->gamma_level_(strengths[i] * 255 / max_strength) >= 0x8000 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
uint8_t ESPColorCorrection::gamma_uncorrect_(uint8_t value) const {
|
||||
if (this->gamma_table_ == nullptr)
|
||||
return value;
|
||||
|
||||
@@ -40,13 +40,10 @@ class ESPColorCorrection {
|
||||
#endif
|
||||
void set_gamma_table(const uint16_t *table) { this->gamma_table_ = table; }
|
||||
|
||||
/// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma, keeping a lit pixel lit
|
||||
inline Color color_correct(Color color) const ESPHOME_ALWAYS_INLINE {
|
||||
Color res(this->round_channel_(COLOR_CHANNEL_R, color.red), this->round_channel_(COLOR_CHANNEL_G, color.green),
|
||||
this->round_channel_(COLOR_CHANNEL_B, color.blue), this->round_channel_(COLOR_CHANNEL_W, color.white));
|
||||
if (res.raw_32 == 0 && color.raw_32 != 0)
|
||||
res = this->correct_dark_pixel_(color);
|
||||
return Color(this->limit_(res.red), this->limit_(res.green), this->limit_(res.blue), this->limit_(res.white));
|
||||
// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma
|
||||
return Color(this->color_correct_red(color.red), this->color_correct_green(color.green),
|
||||
this->color_correct_blue(color.blue), this->color_correct_white(color.white));
|
||||
}
|
||||
inline uint8_t color_correct_red(uint8_t red) const ESPHOME_ALWAYS_INLINE {
|
||||
return this->color_correct_channel(COLOR_CHANNEL_R, red);
|
||||
@@ -93,15 +90,6 @@ class ESPColorCorrection {
|
||||
#endif
|
||||
return res;
|
||||
}
|
||||
inline uint8_t round_channel_(uint8_t channel, uint8_t value) const ESPHOME_ALWAYS_INLINE {
|
||||
return this->gamma_round_(esp_scale8_twice(value, this->max_brightness_[channel], this->local_brightness_));
|
||||
}
|
||||
/// Forward gamma as the table's 16-bit level
|
||||
uint16_t gamma_level_(uint8_t value) const;
|
||||
/// Forward gamma rounded to uint8, where a low level becomes 0
|
||||
uint8_t gamma_round_(uint8_t value) const;
|
||||
/// The levels of a pixel whose channels all round to 0: 1 for its strongest channels, unless it is black
|
||||
Color correct_dark_pixel_(Color color) const;
|
||||
/// Forward gamma: read uint16 PROGMEM table, convert to uint8
|
||||
uint8_t gamma_correct_(uint8_t value) const;
|
||||
/// Reverse gamma and limit for one stored level
|
||||
|
||||
@@ -36,10 +36,6 @@ class ESPColorAccessor {
|
||||
#if defined(USE_LIGHT_PARTITION) && defined(USE_LIGHT_POWER_ESTIMATION)
|
||||
virtual const ESPColorCorrection *get_color_correction_internal(int32_t index) const { return nullptr; }
|
||||
#endif
|
||||
#ifdef USE_LIGHT_PARTITION
|
||||
// For internal use only: whether the LED at `index` stores a white level.
|
||||
virtual bool has_white_internal(int32_t index) const { return true; }
|
||||
#endif
|
||||
};
|
||||
|
||||
/// Color accessor that is completely at peace with the void of nothingness.
|
||||
@@ -82,10 +78,6 @@ class BufferColorAccessor : public ESPColorAccessor {
|
||||
}
|
||||
void set_effect_data(int32_t index, uint8_t value) override { this->effect_data[index] = value; }
|
||||
|
||||
#ifdef USE_LIGHT_PARTITION
|
||||
bool has_white_internal(int32_t index) const override { return this->channel_colors.has_white(); }
|
||||
#endif
|
||||
|
||||
/// Allocate a zeroed block of buffer_bytes() plus `extra_bytes` for the caller, which start at
|
||||
/// `effect_data + num_leds`, and pass it to set_buffer(). Returns false if it failed.
|
||||
bool allocate(RAMAllocator<uint8_t> &allocator, size_t num_leds, size_t extra_bytes = 0) {
|
||||
@@ -159,12 +151,7 @@ class CorrectedBufferColorAccessor final : public BufferColorAccessor {
|
||||
return this->color_correction->color_uncorrect_channel(channel, this->get_channel_raw(index, channel));
|
||||
}
|
||||
|
||||
void set(int32_t index, Color color) override {
|
||||
// A white level the strip cannot show must not count as the pixel's strongest channel
|
||||
if (!this->channel_colors.has_white())
|
||||
color.white = 0;
|
||||
this->set_raw(index, this->color_correction->color_correct(color));
|
||||
}
|
||||
void set(int32_t index, Color color) override { this->set_raw(index, this->color_correction->color_correct(color)); }
|
||||
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
|
||||
this->set_channel_raw(index, channel, this->color_correction->color_correct_channel(channel, value));
|
||||
}
|
||||
@@ -286,10 +273,6 @@ class ESPColorView final : public ESPColorSettable {
|
||||
return this->accessor_->get_color_correction_internal(this->index_);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_LIGHT_PARTITION
|
||||
// This method is for internal use only.
|
||||
bool has_white_internal() const { return this->accessor_->has_white_internal(this->index_); }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
ESPColorAccessor *const accessor_;
|
||||
|
||||
@@ -325,9 +325,8 @@ 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_)
|
||||
// Stay disconnected, and loop() calls this again.
|
||||
if (!network::is_connected())
|
||||
return;
|
||||
|
||||
for (auto &subscription : this->subscriptions_) {
|
||||
@@ -515,9 +514,7 @@ void MQTTClientComponent::loop() {
|
||||
case MQTT_CLIENT_DISABLED:
|
||||
return; // Return to avoid a reboot when disabled
|
||||
case MQTT_CLIENT_DISCONNECTED:
|
||||
// Back off 5 s after a failed attempt. Without a network no attempt was made, so the
|
||||
// first one starts as soon as the network is up instead of 5 s after boot.
|
||||
if (this->waiting_for_network_ || now - this->connect_begin_ > 5000) {
|
||||
if (now - this->connect_begin_ > 5000) {
|
||||
this->start_dnslookup_();
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -436,8 +436,6 @@ class MQTTClientComponent final : public Component {
|
||||
network::IPAddress ip_;
|
||||
bool dns_resolved_{false};
|
||||
bool dns_resolve_error_{false};
|
||||
/// The last start_dnslookup_() found no network, so no attempt was made and there is nothing to back off from
|
||||
bool waiting_for_network_{false};
|
||||
bool enable_on_boot_{true};
|
||||
#ifdef USE_MQTT_CRASH_LOG
|
||||
bool crash_log_offered_{false};
|
||||
|
||||
@@ -83,9 +83,6 @@ class PartitionLightOutput final : public light::AddressableLight {
|
||||
|
||||
void set(int32_t index, Color color) override {
|
||||
light::ESPColorView color_view = this->parent_->get_color_view_(index);
|
||||
// A white level the LED cannot show must not count as the pixel's strongest channel
|
||||
if (!color_view.has_white_internal()) // NOLINT
|
||||
color.white = 0;
|
||||
color_view.set_raw(this->parent_->get_color_correction_(color_view)->color_correct(color));
|
||||
}
|
||||
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
|
||||
@@ -101,10 +98,6 @@ class PartitionLightOutput final : public light::AddressableLight {
|
||||
this->parent_->get_color_view_(index).set_effect_data(value);
|
||||
}
|
||||
|
||||
bool has_white_internal(int32_t index) const override { // NOLINT
|
||||
return this->parent_->get_color_view_(index).has_white_internal();
|
||||
}
|
||||
|
||||
#ifdef USE_LIGHT_POWER_ESTIMATION
|
||||
const light::ESPColorCorrection *get_color_correction_internal(int32_t index) const override { // NOLINT
|
||||
return this->parent_->get_color_correction_(this->parent_->get_color_view_(index));
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
"""Pioneer WT series mini splits, controlled through the serial port of the WiFi module."""
|
||||
|
||||
import esphome.codegen as cg
|
||||
|
||||
CODEOWNERS = ["@martinsah"]
|
||||
DOMAIN = "pioneer_wt"
|
||||
|
||||
pioneer_wt_ns = cg.esphome_ns.namespace("pioneer_wt")
|
||||
|
||||
CONF_PIONEER_WT_ID = "pioneer_wt_id"
|
||||
@@ -1,33 +0,0 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import climate, uart
|
||||
import esphome.config_validation as cv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import DOMAIN, pioneer_wt_ns
|
||||
|
||||
DEPENDENCIES = ["uart"]
|
||||
|
||||
PioneerWT = pioneer_wt_ns.class_(
|
||||
"PioneerWT", climate.Climate, uart.UARTDevice, cg.Component
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
climate.climate_schema(PioneerWT)
|
||||
.extend(uart.UART_DEVICE_SCHEMA)
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
)
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = uart.final_validate_device_schema(
|
||||
DOMAIN,
|
||||
baud_rate=115200,
|
||||
require_tx=True,
|
||||
require_rx=True,
|
||||
data_bits=8,
|
||||
parity="NONE",
|
||||
stop_bits=1,
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await uart.new_uart_component(config)
|
||||
await climate.register_climate(var, config)
|
||||
@@ -1,348 +0,0 @@
|
||||
#include "pioneer_wt.h"
|
||||
|
||||
#include <cinttypes>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <iterator>
|
||||
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::pioneer_wt {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "pioneer_wt");
|
||||
|
||||
static constexpr uint32_t RESEND_INTERVAL_MS = 500;
|
||||
static constexpr uint8_t MAX_ATTEMPTS = 4;
|
||||
// Ask for a full status again if the AC has reported nothing for this long.
|
||||
static constexpr uint32_t STATUS_REFRESH_MS = 5 * 60 * 1000;
|
||||
// Until the first full status has arrived, ask again this often.
|
||||
static constexpr uint32_t STATUS_RETRY_MS = 30 * 1000;
|
||||
// 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
|
||||
@@ -1,85 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/components/climate/climate.h"
|
||||
#include "esphome/components/uart/uart.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#ifdef USE_SWITCH
|
||||
#include "esphome/components/switch/switch.h"
|
||||
#endif
|
||||
#include "pioneer_wt_protocol.h"
|
||||
|
||||
namespace esphome::pioneer_wt {
|
||||
|
||||
// The largest body control() builds is 30 bytes.
|
||||
static constexpr size_t MAX_BODY_SIZE = 32;
|
||||
static constexpr size_t TX_QUEUE_SIZE = 4;
|
||||
|
||||
class PioneerWT final : public climate::Climate, public uart::UARTDevice, public Component {
|
||||
public:
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
void dump_config() override;
|
||||
|
||||
/// Turns the indoor unit's front display on or off.
|
||||
void set_display_on(bool on) { this->send_setting_(ATTR_DISPLAY, on); }
|
||||
/// Turns the beep that confirms each command on or off.
|
||||
void set_beeper_on(bool on) { this->send_setting_(ATTR_BEEPER, on); }
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
SUB_SWITCH(display)
|
||||
SUB_SWITCH(beeper)
|
||||
#endif
|
||||
|
||||
protected:
|
||||
climate::ClimateTraits traits() override;
|
||||
void control(const climate::ClimateCall &call) override;
|
||||
|
||||
void handle_frame_(const uint8_t *frame, size_t len);
|
||||
void handle_status_(const uint8_t *body, size_t len);
|
||||
void write_frame_(uint8_t flags, uint8_t type, uint8_t seq, uint8_t ack, uint8_t class_1, uint8_t class_2,
|
||||
const uint8_t *body, size_t len);
|
||||
/// Queues a data frame that the AC must acknowledge; it is resent until it is.
|
||||
void queue_command_(uint8_t msg_class, const uint8_t *body, size_t len, int8_t power = POWER_UNCHANGED);
|
||||
void send_pending_();
|
||||
/// Removes the command at the head of the queue.
|
||||
void pop_command_();
|
||||
/// Power once the queued commands are applied; skip_head leaves out a head about to be dropped.
|
||||
bool wanted_power_(bool skip_head) const;
|
||||
/// Queues a command that sets one on/off attribute.
|
||||
void send_setting_(uint16_t attr, bool on);
|
||||
void request_status_();
|
||||
|
||||
static constexpr int8_t POWER_UNCHANGED = -1;
|
||||
|
||||
struct PendingCommand {
|
||||
uint8_t msg_class;
|
||||
uint8_t seq;
|
||||
uint8_t len;
|
||||
// Power the command sets: 0, 1 or POWER_UNCHANGED
|
||||
int8_t power;
|
||||
std::array<uint8_t, MAX_BODY_SIZE> body;
|
||||
};
|
||||
|
||||
uint32_t last_send_{0};
|
||||
// Time of the last status report (counted once a full one has arrived), or of the last request for one
|
||||
uint32_t last_status_{0};
|
||||
uint32_t last_rx_{0};
|
||||
PacketReader reader_;
|
||||
StaticRingBuffer<PendingCommand, TX_QUEUE_SIZE> queue_;
|
||||
// Send attempts of the command at the head of the queue
|
||||
uint8_t attempts_{0};
|
||||
uint8_t next_seq_{1};
|
||||
// Power the AC last reported
|
||||
bool power_{false};
|
||||
// Power set by an acknowledged command, until the next power report: 0, 1 or POWER_UNCHANGED
|
||||
int8_t acked_power_{POWER_UNCHANGED};
|
||||
// Value of ATTR_MODE: 0 auto, 1 cool, 2 dry, 3 fan, 4 heat
|
||||
uint8_t ac_mode_{0};
|
||||
};
|
||||
|
||||
} // namespace esphome::pioneer_wt
|
||||
@@ -1,147 +0,0 @@
|
||||
#include "pioneer_wt_protocol.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
namespace esphome::pioneer_wt {
|
||||
|
||||
uint16_t frame_crc(const uint8_t *frame, size_t len) {
|
||||
const uint16_t head = crc16be(frame, 8);
|
||||
return crc16be(frame + HEADER_SIZE, len - HEADER_SIZE, head);
|
||||
}
|
||||
|
||||
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
|
||||
@@ -1,102 +0,0 @@
|
||||
#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
|
||||
@@ -1,37 +0,0 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import switch
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_BEEPER, CONF_DISPLAY, ENTITY_CATEGORY_CONFIG
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import CONF_PIONEER_WT_ID
|
||||
from .climate import PioneerWT
|
||||
|
||||
ICON_LED_ON = "mdi:led-on"
|
||||
ICON_VOLUME_HIGH = "mdi:volume-high"
|
||||
|
||||
|
||||
def _switch_schema(icon: str) -> cv.Schema:
|
||||
return switch.switch_schema(
|
||||
switch.ApplySwitch,
|
||||
icon=icon,
|
||||
entity_category=ENTITY_CATEGORY_CONFIG,
|
||||
default_restore_mode="DISABLED",
|
||||
)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(CONF_PIONEER_WT_ID): cv.use_id(PioneerWT),
|
||||
cv.Optional(CONF_DISPLAY): _switch_schema(ICON_LED_ON),
|
||||
cv.Optional(CONF_BEEPER): _switch_schema(ICON_VOLUME_HIGH),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
hub = await cg.get_variable(config[CONF_PIONEER_WT_ID])
|
||||
switches = switch.sub_switches(config, parent=hub)
|
||||
# No publish: the switch state follows what the AC reports back.
|
||||
await switches(CONF_DISPLAY, hub.set_display_switch, apply="set_display_on(state)")
|
||||
await switches(CONF_BEEPER, hub.set_beeper_switch, apply="set_beeper_on(state)")
|
||||
@@ -98,7 +98,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.positive_time_period_milliseconds,
|
||||
cv.Range(max=cv.TimePeriod(milliseconds=5000)),
|
||||
),
|
||||
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=True): cv.boolean,
|
||||
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=False): cv.boolean,
|
||||
cv.Optional(CONF_FIXED_DELAY, default="0us"): cv.All(
|
||||
cv.positive_time_period_microseconds,
|
||||
cv.Range(max=cv.TimePeriod(microseconds=10000)),
|
||||
|
||||
@@ -61,7 +61,7 @@ class SendspinMediaSource final : public SendspinChild,
|
||||
|
||||
bool cached_muted_{false};
|
||||
bool pending_start_{false};
|
||||
bool static_delay_adjustable_{true};
|
||||
bool static_delay_adjustable_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::sendspin_
|
||||
|
||||
@@ -3,7 +3,7 @@ from dataclasses import dataclass, field
|
||||
from logging import getLogger
|
||||
import math
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import Any
|
||||
|
||||
from esphome import automation, pins
|
||||
import esphome.codegen as cg
|
||||
@@ -42,12 +42,8 @@ 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,
|
||||
@@ -64,9 +60,6 @@ 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"]
|
||||
@@ -340,89 +333,6 @@ 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)
|
||||
@@ -516,11 +426,6 @@ 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,42 +25,6 @@ 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;
|
||||
|
||||
@@ -85,8 +49,8 @@ uint16_t LibreTinyUARTComponent::get_config() {
|
||||
}
|
||||
|
||||
void LibreTinyUARTComponent::setup() {
|
||||
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();
|
||||
int16_t tx_pin = tx_pin_ == nullptr ? -1 : tx_pin_->get_pin();
|
||||
int16_t rx_pin = rx_pin_ == nullptr ? -1 : rx_pin_->get_pin();
|
||||
|
||||
auto should_fallback_to_software_serial = [&]() -> bool {
|
||||
auto has_flags = [](InternalGPIOPin *pin, const gpio::Flags mask) -> bool {
|
||||
@@ -106,49 +70,61 @@ void LibreTinyUARTComponent::setup() {
|
||||
return false;
|
||||
};
|
||||
|
||||
// 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_);
|
||||
#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
|
||||
if (false) { // NOLINT(readability-simplify-boolean-expr)
|
||||
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);
|
||||
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
|
||||
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL1_TX, PIN_SERIAL1_RX);
|
||||
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
|
||||
ESP_LOGE(TAG, " TX=%u, RX=%u", PIN_SERIAL2_TX, PIN_SERIAL2_RX);
|
||||
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
|
||||
this->mark_failed(LOG_STR("SoftwareSerial is not implemented for this chip."));
|
||||
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)
|
||||
libretiny::ensure_serial_handle(this->hardware_idx_);
|
||||
this->serial_->begin(this->baud_rate_, get_config());
|
||||
}
|
||||
|
||||
void LibreTinyUARTComponent::dump_config() {
|
||||
|
||||
@@ -25,8 +25,6 @@ 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_; }
|
||||
|
||||
@@ -884,7 +884,6 @@
|
||||
#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
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies:
|
||||
esphome/micro-decoder:
|
||||
version: 0.4.0
|
||||
esphome/micro-flac:
|
||||
version: 0.3.1
|
||||
version: 0.3.0
|
||||
esphome/micro-mp3:
|
||||
version: 0.4.0
|
||||
esphome/micro-opus:
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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
|
||||
@@ -1,139 +0,0 @@
|
||||
"""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),
|
||||
]
|
||||
@@ -1,6 +0,0 @@
|
||||
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,6 +36,7 @@ sensor:
|
||||
name: "BMI270 Accel Z"
|
||||
accuracy_decimals: 4
|
||||
|
||||
# Gyroscope axes (unit: °/s)
|
||||
- platform: motion
|
||||
motion_id: bmi270_motion
|
||||
type: gyroscope_x
|
||||
@@ -75,11 +76,21 @@ motion:
|
||||
- platform: bmi270
|
||||
id: bmi270_motion
|
||||
i2c_id: i2c_bus
|
||||
accelerometer_range: 8G
|
||||
accelerometer_odr: 200HZ
|
||||
gyroscope_range: 1000DPS
|
||||
gyroscope_odr: 400HZ
|
||||
# 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
|
||||
aux_device: BMM150
|
||||
aux_address: 0x10
|
||||
axis_map:
|
||||
x: y
|
||||
y: x
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
#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
|
||||
@@ -1,69 +0,0 @@
|
||||
#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
|
||||
@@ -6,7 +6,6 @@
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/components/light/esp_color_correction.h"
|
||||
#include "esphome/components/light/esp_color_view.h"
|
||||
|
||||
namespace esphome::light::testing {
|
||||
|
||||
@@ -68,69 +67,6 @@ 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}) {
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
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"]
|
||||
@@ -1,56 +0,0 @@
|
||||
#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
|
||||
@@ -1,504 +0,0 @@
|
||||
#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
|
||||
@@ -1,48 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <gmock/gmock.h>
|
||||
#include <gtest/gtest.h>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "esphome/components/uart/uart_component.h"
|
||||
|
||||
namespace esphome::pioneer_wt::testing {
|
||||
|
||||
inline std::vector<uint8_t> from_hex(const std::string &hex) {
|
||||
std::vector<uint8_t> out;
|
||||
for (size_t i = 0; i + 1 < hex.size(); i += 2)
|
||||
out.push_back(static_cast<uint8_t>(std::stoul(hex.substr(i, 2), nullptr, 16)));
|
||||
return out;
|
||||
}
|
||||
|
||||
class MockUARTComponent : public uart::UARTComponent {
|
||||
public:
|
||||
std::vector<uint8_t> tx;
|
||||
std::vector<uint8_t> rx;
|
||||
|
||||
void push_rx(const std::vector<uint8_t> &data) { this->rx.insert(this->rx.end(), data.begin(), data.end()); }
|
||||
void push_rx_hex(const std::string &hex) { this->push_rx(from_hex(hex)); }
|
||||
|
||||
void write_array(const uint8_t *data, size_t len) override { this->tx.insert(this->tx.end(), data, data + len); }
|
||||
|
||||
bool read_array(uint8_t *data, size_t len) override {
|
||||
if (this->rx.size() < len)
|
||||
return false;
|
||||
std::copy(this->rx.begin(), this->rx.begin() + len, data);
|
||||
this->rx.erase(this->rx.begin(), this->rx.begin() + len);
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t available() override { return this->rx.size(); }
|
||||
|
||||
MOCK_METHOD(bool, peek_byte, (uint8_t *data), (override));
|
||||
MOCK_METHOD(uart::UARTFlushResult, flush, (), (override));
|
||||
MOCK_METHOD(void, check_logger_conflict, (), (override));
|
||||
#if defined(USE_ESP8266) || defined(USE_ESP32)
|
||||
void load_settings(bool dump_config) override {}
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace esphome::pioneer_wt::testing
|
||||
@@ -1,11 +0,0 @@
|
||||
climate:
|
||||
- platform: pioneer_wt
|
||||
uart_id: uart_bus
|
||||
name: Pioneer WT
|
||||
|
||||
switch:
|
||||
- platform: pioneer_wt
|
||||
display:
|
||||
name: Pioneer WT Display
|
||||
beeper:
|
||||
name: Pioneer WT Beeper
|
||||
@@ -1,45 +0,0 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/pioneer_wt/pioneer_wt.h"
|
||||
#include "esphome/components/switch/switch.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "../common.h"
|
||||
|
||||
namespace esphome::pioneer_wt::testing {
|
||||
|
||||
namespace {
|
||||
|
||||
class TestSwitch : public switch_::Switch {
|
||||
protected:
|
||||
void write_state(bool state) override {}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// Reports captured from the AC after the app changed the display and the beep.
|
||||
TEST(PioneerWTSwitch, StateFollowsReports) {
|
||||
MockUARTComponent uart;
|
||||
PioneerWT sut;
|
||||
TestSwitch display;
|
||||
TestSwitch beeper;
|
||||
sut.set_uart_parent(&uart);
|
||||
sut.set_display_switch(&display);
|
||||
sut.set_beeper_switch(&beeper);
|
||||
EXPECT_FALSE(display.has_state());
|
||||
|
||||
uart.push_rx_hex("a50101217400000f53010c0c001e01");
|
||||
uart.push_rx_hex("a50101217700000fb70b0c0c002500");
|
||||
sut.loop();
|
||||
EXPECT_TRUE(display.has_state());
|
||||
EXPECT_TRUE(display.state);
|
||||
EXPECT_TRUE(beeper.has_state());
|
||||
EXPECT_FALSE(beeper.state);
|
||||
|
||||
uart.push_rx_hex("a50101217300000ff28b0c0c001e00");
|
||||
uart.push_rx_hex("a50101217800000f3f7e0c0c002501");
|
||||
sut.loop();
|
||||
EXPECT_FALSE(display.state);
|
||||
EXPECT_TRUE(beeper.state);
|
||||
}
|
||||
|
||||
} // namespace esphome::pioneer_wt::testing
|
||||
@@ -1,3 +0,0 @@
|
||||
packages:
|
||||
uart_115200: !include ../../test_build_components/common/uart_115200/esp32-idf.yaml
|
||||
pioneer_wt: !include common.yaml
|
||||
@@ -1,3 +0,0 @@
|
||||
packages:
|
||||
uart_115200: !include ../../test_build_components/common/uart_115200/esp8266-ard.yaml
|
||||
pioneer_wt: !include common.yaml
|
||||
@@ -1,12 +0,0 @@
|
||||
# UART1 on its second pair of pins (the board allows PA01/PA00 or PA03/PA02)
|
||||
uart:
|
||||
- id: uart_id
|
||||
tx_pin: PA03
|
||||
rx_pin: PA02
|
||||
baud_rate: 9600
|
||||
|
||||
switch:
|
||||
- platform: uart
|
||||
name: "UART Switch"
|
||||
uart_id: uart_id
|
||||
data: [0x01, 0x02, 0x03]
|
||||
Reference in new issue
Block a user