Compare commits

...
Author SHA1 Message Date
J. Nick Koston c2e364d7bf Test that the property returns the stored version 2026-11-18 11:44:25 -06:00
J. Nick Koston 1ff447f4e6 [core] Add CORE.framework_version 2026-11-18 11:43:09 -06:00
Leandro 791d6e15ee [mqtt] Connect as soon as the network is up, not 5 s after boot (#22871) 2026-11-18 11:11:03 -06:00
J. Nick Koston d2b505e76c [bmi270] Feed the watchdog during the config upload (#22862) 2026-11-18 11:08:24 -06:00
J. Nick Koston 0cca1f8c02 [bmi270] Keep the config file in flash on ESP8266, upload it without the heap and simplify the component (#22778) 2026-11-18 11:08:23 -06:00
Martin Klingensmith 3bcd0da1f4 [uart] Accept alternate hardware UART pins on LibreTiny (#22863) 2026-11-18 10:44:53 -06:00
Martin Klingensmith 3e54c5b46d [pioneer_wt] Add Pioneer WT mini split climate component (#22865) 2026-11-18 10:24:00 -06:00
J. Nick Koston e7f7fc162b [qwiic_pir] Set a warning on read failures instead of logging every loop (#22854) 2026-11-18 07:10:30 -05:00
rwrozelle b3474a1ed5 [ci] Add a silent failure review skill (#22846) 2026-11-17 22:33:16 -06:00
Jesse Hills 69037820fa Merge branch 'beta' into dev 2026-11-18 16:07:40 +13:00
Jesse Hills 6c28ef21d9 Merge pull request #22866 from esphome/bump-2026.11.0b7
2026.11.0b7
2026-11-18 16:07:21 +13:00
Jesse Hills ab6e3d9bf0 Bump version to 2026.11.0b7 2026-11-18 15:35:39 +13:00
J. Nick Koston 10ef6e371b [i2c] Stop bus recovery clock pulses once SDA is released (#22852) 2026-11-18 15:35:35 +13:00
J. Nick Koston c84cd04cf7 [modem] Wait for registration before attaching and recover SIM7670 data mode and CMUX (#22816) 2026-11-18 15:35:35 +13:00
J. Nick Koston fb6d7bf265 [scd30] Stop overriding the I2C bus clock-stretch limit on ESP8266 (#22512) 2026-11-18 15:35:35 +13:00
David WoodhouseandJ. Nick Koston 3ad8e35be8 [mqtt] Don't start the broker lookup before the network is up (#22843)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-18 15:35:35 +13:00
Mattheinrichs 11f9f20b61 [cst816] Ignore idle 0xFF touch frames and invalid coordinates (#22435) 2026-11-18 15:35:28 +13:00
Jacopo Labardi b6d0961f25 [logger] Qualify the host clock function (#22838) 2026-11-18 15:31:22 +13:00
David Woodhouse 6046d067aa [climate] Don't fail on a platform entry that only holds nested climates (#22844) 2026-11-18 15:30:52 +13:00
Jonathan Swoboda 690c5f2fb6 [mlx90393] Enable the Wire library on ESP32 Arduino (#22801) 2026-11-18 15:30:52 +13:00
J. Nick Koston 654954f684 [api] Make the event order backpressure test wait until the pipe is full (#22112) 2026-11-18 15:30:44 +13:00
J. Nick Koston e5728407db [i2c] Stop bus recovery clock pulses once SDA is released (#22852) 2026-11-17 18:06:32 -06:00
J. Nick Koston 0cf5af743e [modem] Wait for registration before attaching and recover SIM7670 data mode and CMUX (#22816) 2026-11-17 18:05:44 -06:00
J. Nick Koston 7ffead44fe [scd30] Stop overriding the I2C bus clock-stretch limit on ESP8266 (#22512) 2026-11-17 18:25:29 -05:00
Andriy Malyshenko f2aadcf0b5 [pcm1863] Add PCM1863 stereo audio ADC component (#22794) 2026-11-17 15:18:48 -06:00
NonaSuomy d4d53aa965 [vl6180x] Add VL6180X I2C sensor component (#22689) 2026-11-17 15:16:22 -06:00
dependabot[bot] 735ba9c98a Bump smp from 4.2.0 to 4.3.0 (#22853) 2026-11-17 14:06:09 -06:00
tomaszduda23andClaude 141789d240 [debug] Fix the debug component on nRF54L boards (#22839)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 17:32:52 +01:00
Bascht74 c4df1b163c [uart] Fix undefined shift in the RP2 hardware UART pin check (#22841) 2026-11-17 09:54:29 -06:00
David WoodhouseandJ. Nick Koston 773afa0bb1 [mqtt] Don't start the broker lookup before the network is up (#22843)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-17 09:53:52 -06:00
tomaszduda23andClaude 9bf2bbc241 [nrf52] Store preferences in ZMS on nRF54L (#22840)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 18:21:54 +03:00
Mattheinrichs 84dea8078b [cst816] Ignore idle 0xFF touch frames and invalid coordinates (#22435) 2026-11-17 08:58:24 -06:00
Jacopo Labardi dbf6af2fd7 [logger] Qualify the host clock function (#22838) 2026-11-17 08:50:19 -06:00
David Woodhouse bc6fb7082f [climate] Don't fail on a platform entry that only holds nested climates (#22844) 2026-11-17 08:49:00 -06:00
tomaszduda23andClaude cfa27cea58 [npm1300] Fix the thermistor resistance error message (#22835)
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-17 17:40:04 +03:00
rwrozelleandClaude Opus 5.5 5c061f9e1e [espidf] Hide the ccache binary in the forced-on, no-binary test (#22842)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:29:34 -05:00
Jesse Hills 34b24d0cf5 Merge branch 'beta' into dev 2026-11-17 22:25:16 +13:00
Jesse Hills e27614fda3 Merge pull request #22833 from esphome/bump-2026.11.0b6
2026.11.0b6
2026-11-17 22:24:55 +13:00
J. Nick Koston 8426d04138 [api] Make the event order backpressure test wait until the pipe is full (#22112) 2026-11-17 21:09:01 +13:00
641c8bedc9 [npm1300] Use datasheet defaults, require the thermistor setting for charging, fix charger status (#22769)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-17 09:00:10 +01:00
Jesse Hills 4a39ca1b71 Fix 2026-11-17 20:54:40 +13:00
Jesse Hills 4a218fdbd8 Remove extra test 2026-11-17 20:47:40 +13:00
Jesse Hills d8fc1cd214 Bump version to 2026.11.0b6 2026-11-17 18:54:23 +13:00
J. Nick Koston 1e030b7371 [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 18:54:20 +13:00
J. Nick Koston 3b113f2c39 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 18:54:20 +13:00
J. Nick Koston 73468592a9 [remote_base] Fix the Haier and Mirage remote_receiver binary sensors failing to compile 2026-11-17 18:54:06 +13:00
Jonathan Swoboda a1b456150d [esp32][libretiny] Make delay() wait at least the requested time (#22822) 2026-11-17 18:53:11 +13:00
J. Nick Koston 865a883abb [remote_base] Fix the canalsatld binary sensor and trigger build 2026-11-17 18:53:11 +13:00
J. Nick Koston 357a6717c8 [core] Release only the lwIP core lock a LwIPLock took (#22683) 2026-11-17 18:53:11 +13:00
J. Nick Koston bcb434e05e [esp32_ble] Stop Bluedroid re-running a failed queued MTU or execute write request (#22670) 2026-11-17 18:53:11 +13:00
J. Nick Koston fb65fcc5f6 [esp32_power_management] Clamp the tick step after light sleep so it cannot trip vTaskStepTick (#22637) 2026-11-17 18:53:11 +13:00
J. Nick Koston b5e379a9d4 [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog at 57600 baud (#22641) 2026-11-17 18:53:11 +13:00
J. Nick Kostonandpre-commit-ci-lite[bot] 05286dfd5d [api] Send queued entity states before DisconnectRequest on shutdown (#22625)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-17 18:53:11 +13:00
J. Nick Koston 36184f09aa [zephyr] Count micros() in microseconds and busy-wait in delayMicroseconds() (#22612) 2026-11-17 18:53:11 +13:00
Adam Matthews 449933891e [wifi] Clear the error flag when the adapter restart is skipped (#22797) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda a5bfa6dac3 [esp32_ble] Apply the Bluedroid workarounds to the ESP-IDF 6.1 releases that need them (#22806) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda 5aaa5b0552 [esp32_ble] Replace Bluedroid's sscanf callers on ESP-IDF 6 too (#22805) 2026-11-17 18:53:11 +13:00
J. Nick Koston 9ab090a818 [i2c] Refuse RP2040 writes larger than the Wire buffer instead of leaving the bus stuck (#22791) 2026-11-17 18:53:10 +13:00
J. Nick Koston 02d0bb56a6 [cc1101] Refuse begin_tx in packet mode (#22636) 2026-11-16 22:21:59 -06:00
Mark Mayo e12784543d [logger] Copy log lines that have no arguments instead of formatting them (#22644) 2026-11-16 22:16:47 -06:00
J. Nick Koston bc3e9c88f4 [select] Set a fixed option by index and look up a template lambda's option once (#22655) 2026-11-16 22:48:05 -05:00
luar123andCopilot Autofix powered by AI 7e3c2ebc10 [zigbee] refactor ZigbeeAttribute (#22765)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-11-16 22:31:05 -05:00
J. Nick Koston 3f6c0f35fe [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 16:23:11 +13:00
J. Nick Koston 200bf69035 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 16:23:06 +13:00
huangkongshengandhuangkongsheng 0054041d6a [core] Reject sign-padded bind key pairs (#22660)
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
Co-authored-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-11-16 22:15:45 -05:00
J. Nick Koston b75b3e2bef [tuya] Register entity listeners from generated code and print their dumps from the hub (#22724) 2026-11-16 21:03:11 -06:00
J. Nick KostonandJonathan Swoboda 144c799cf5 [components] Print the xiaomi BLE sensor dumps from the tracker instead of a component per sensor (#22727)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-11-16 20:56:53 -06:00
J. Nick Koston 61cce92aaa [homeassistant] Subscribe and dump the import entities from the API server (#22725) 2026-11-16 20:56:35 -06:00
J. Nick Koston 38c1646870 [homeassistant] Share the action helpers and drop state that did nothing (#22592) 2026-11-16 20:56:35 -06:00
J. Nick Koston b60c2864ef [sml][teleinfo] Print entity dumps from their hub instead of a component per entity (#22722) 2026-11-16 21:55:49 -05:00
J. Nick Koston db0121bc21 [remote_base] Move the plain-field protocols to register_simple_protocol (#22713) 2026-11-16 20:53:05 -06:00
J. Nick Koston be8f6c5e41 [remote_base] Add register_simple_protocol for plain field protocols (#22711) 2026-11-16 20:53:04 -06:00
J. Nick Koston b621332de5 [components] Print BLE sensor dumps from the tracker instead of a component per sensor (#22728) 2026-11-16 20:52:05 -06:00
J. Nick KostonandJonathan Swoboda 982cbba291 [analyze_memory] List ESP8266 string literals in RAM by component (#22755)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-11-16 20:50:51 -06:00
J. Nick Koston a2ac68faac [sun] Assign the invalid coordinates instead of copying a constant (#22741) 2026-11-16 21:47:36 -05:00
J. Nick Koston 731f6e2722 [mitsubishi] Keep the IR frame template in flash on ESP8266 (#22746) 2026-11-16 21:44:59 -05:00
J. Nick Koston 598d87836c [daikin_arc] Keep the IR frame templates in flash on ESP8266 (#22743) 2026-11-16 21:44:36 -05:00
J. Nick Koston e852e15ca3 [ble_device_base] Let BLE trackers print their device listeners' dumps (#22726) 2026-11-16 21:42:02 -05:00
Jacopo Labardi 6b82e127fe [const] Share destination between components (#22785) 2026-11-16 21:23:41 -05:00
17baeae3ea [nrf52][zephyr] Share the Zephyr SDK install steps with nrf52 (#22623)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-11-16 19:54:34 -05:00
J. Nick Kostonandpre-commit-ci-lite[bot] bc57ad5c87 [sntp] Pass the servers as separate constructor arguments (#22737)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-16 19:09:39 -05:00
J. Nick Koston 0c1606d3b8 [analyze_memory] Count ESP8266 .rodata as RAM and list the constants GCC copies into it (#22748) 2026-11-16 18:06:26 -06:00
J. Nick Koston a155401afc [wifi_info] Publish the BSSID without copying a padded constant (#22736) 2026-11-16 19:04:39 -05:00
J. Nick Koston e3bfffc8ab [core] Use the nibble and encode_uint12 helpers in touch and BME drivers (#22761) 2026-11-17 00:04:28 +00:00
J. Nick Koston 9f5ca49e2f [light] Keep the wrapper's color mode precedence in flash on ESP8266 (#22742) 2026-11-16 19:03:43 -05:00
362 changed files with 10051 additions and 3096 deletions

No files matched your search

+3
View File
@@ -20,6 +20,9 @@ flagging in a review; read the matching skill for the detail behind any item.
Only raise findings that the diff actually introduces or changes. Do not ask for
drive-by cleanup of pre-existing code the PR did not touch.
For error paths that fail without telling the user (early returns, swallowed
errors, ignored results), the `silent-failure-review` skill has its own checklist.
## Scope: shared code does not ride a component PR
Check the file list first. A PR titled for one component (`[ld2450] ...`) must
@@ -0,0 +1,71 @@
---
name: silent-failure-review
description: Find code paths in a branch's diff that fail without telling the user - early returns, swallowed errors, ignored return values, half-done cleanup, and checks that are only safe under an unstated assumption. Use when asked for a silent failure review or before pushing a PR for review.
---
# Silent failure review
Report only. Do not edit files.
## Scope
The diff of the checked-out branch against its base. Fetch the base first (`git fetch upstream dev`, or
`git fetch origin dev` when there is no `upstream` remote); a stale base pulls in commits the branch only merged.
Then run `git merge-base upstream/dev HEAD` (or `origin/dev`) on its own. If it fails or prints nothing (often a
shallow clone; `git fetch --unshallow` fixes that), say the review could not run and stop; never report "no
findings" then. Diff against that commit with `git diff <base>`. The diff includes uncommitted changes but not
untracked files, so also read in full every file `git status --porcelain --untracked-files=all` lists as `??`.
Use another branch only if the user names one. If neither remote exists, say so and stop. Read each changed
function in full, and its callers, not just the hunks. When a failure depends on how a library call behaves,
read that library's code too.
## What to look for
1. **Early returns and skips:** a `return` or `continue` taken before a check or a fetch. Name the assumption
it relies on and the case that breaks it (a later release, a lost file, an older install).
2. **Swallowed errors:** `except` that logs, passes or returns a default; `OSError` tolerated where the next
step needs the file. In C++: an error code mapped to a default, or a status flag that is never set.
3. **Ignored results:** a `False`, `None`, exit code, `bool` or `ErrorCode` that the caller does not check.
4. **Half-done state:** a failure between two writes that leaves a marker, stamp, lock or filter saying
something is done when it is not; cleanup missing on an error path.
5. **Stale stored state:** markers, stamps or saved preferences (NVS, flash) written by an older version that
the new code trusts.
6. **Unclear late failure:** an error that surfaces later (CMake, compile, boot) instead of where it starts,
with a message that does not point back to the cause.
7. **Defaults standing in for errors:** `x or default`, `.get(key, default)` or an empty object takes the
place of a value that is missing or could not be read, and the code carries on as if it were real.
8. **Unwatched work:** a thread, task or subprocess is started and nothing ever looks at how it ended.
9. **Wrong value on an error branch:** the error is detected, but the branch returns success, `None` or the
wrong code instead of passing it on.
10. **State reset or skipped:** for each counter, flag, retry or timeout the diff adds or changes, find every
place that writes it, and check that no path resets or skips it before it can do its job.
11. **Boundaries:** length and buffer comparisons (`>=` against `>`, `len` against `len + 1`), the exact-fit
case and the empty case.
12. **Unjudged results:** a test or script that prints a result but never fails on it.
Moved code counts too: if the original had the same flaw, say so, but still report it. Report only flaws in
changed or moved lines; unchanged callers are context. If the branch has an open PR (`gh pr view --json number`
finds it), read its reviews (`gh pr view <n> --comments` and
`gh api --paginate repos/esphome/esphome/pulls/<n>/comments`) and skip what they already raised.
Before reporting a candidate, follow it to the line that proves it and quote that line. If you cannot
confirm it, drop it or mark it as likely.
## Skip
- Code that ignores a failure and has a comment explaining why.
- Tests that provoke an error and check for it.
- Optional tidy-up steps (removing a temp file, say) that may fail with only a log line.
## Report
One entry per finding, most severe first:
- **HIGH / MEDIUM / LOW** - one-line title, `file:line`. HIGH: wrong result or lost data. MEDIUM: a
misleading or delayed failure. LOW: affects only logs or diagnostics.
- **Confidence:** confirmed, or likely and why it could not be confirmed.
- **Risk:** the concrete input or state, and what the user sees.
- **Fix:** the smallest change.
- **Test:** the test that fails before the fix, or for on-device code, the steps to reproduce it on a board.
No findings: say so in one line. Keep the report short; no summary of what the PR does.
+2
View File
@@ -66,6 +66,8 @@ file does, and it is the authority when they disagree. The most useful starting
* `breaking-changes`: what is public API, deprecation patterns and migration notes.
* `pr-workflow`, `code-review`, `hardware-test`, `display-test`: creating PRs, reviewing them, and testing
on real boards and panels.
* `silent-failure-review`: code paths in a branch's diff that fail without telling the user, checked
before a PR goes up for review.
* **Formatting:**
* **Python:** Uses `ruff` for linting and formatting. Configuration is in `pyproject.toml`.
+3
View File
@@ -489,10 +489,12 @@ esphome/components/pca9505/* @ajfriesen @ssieb
esphome/components/pca9554/* @bdraco @clydebarrow @hwstar
esphome/components/pcf85063/* @brogon
esphome/components/pcf8563/* @KoenBreeman
esphome/components/pcm1863/* @anabolyc
esphome/components/pcm5122/* @remcom
esphome/components/pd_pioneer_ir/* @martinsah
esphome/components/pi4ioe5v6408/* @jesserockz
esphome/components/pid/* @OttoWinter
esphome/components/pioneer_wt/* @martinsah
esphome/components/pipsolar/* @andreashergert1984
esphome/components/pixoo/* @jesserockz
esphome/components/pm1006/* @habbie
@@ -735,6 +737,7 @@ esphome/components/veml7700/* @latonita
esphome/components/version/* @esphome/core
esphome/components/vevor_dtx/* @Bofr5555
esphome/components/vl53l1x/* @will-tm
esphome/components/vl6180x/* @NonaSuomy
esphome/components/vnc/* @MindFreeze
esphome/components/voice_assistant/* @jesserockz @kahrendt
esphome/components/wake_on_lan/* @clydebarrow @willwill2will54
+628 -19
View File
@@ -1,7 +1,9 @@
"""Memory usage analyzer for ESPHome compiled binaries."""
from collections import Counter, defaultdict
from collections.abc import Container
from dataclasses import dataclass, field
from functools import cached_property
import logging
from pathlib import Path
import re
@@ -55,6 +57,7 @@ _COMPONENT_PREFIX_EXTERNAL = "[external]"
_COMPONENT_PREFIX_LIB = "[lib]"
_COMPONENT_CORE = f"{_COMPONENT_PREFIX_ESPHOME}core"
_COMPONENT_API = f"{_COMPONENT_PREFIX_ESPHOME}api"
_COMPONENT_ARDUINO_CORE = "arduino_core"
# Placement new storage suffix (generated by codegen Pvariable)
_PSTORAGE_SUFFIX = "__pstorage"
@@ -83,6 +86,28 @@ _NAMESPACE_STD = "std::"
# Type alias for symbol information: (symbol_name, size, component)
SymbolInfoType = tuple[str, int, str]
# Only ESP8266 has this section; its .rodata is copied to RAM at boot like .data
_ESP8266_FLASH_CODE_SECTION = ".irom0.text"
# readelf -SW row: [Nr] Name Type Address Off Size ES Flg
_OBJ_SECTION_PATTERN = re.compile(
r"^\s*\[\s*(\d+)\]\s+(\S+)\s+(\S+)\s+[\da-f]+\s+[\da-f]+\s+([\da-f]+)\s+[\da-f]+\s+(\S*)"
)
_RELOC_SECTION_PATTERN = re.compile(r"^Relocation section '\.rela(\S+)'")
# String literal section; group 1 is the function for -fdata-sections names
_STRING_SECTION_PATTERN = re.compile(r"^\.rodata(?:\.(.+))?\.str\d+\.\d+$")
# Data section of one symbol; group 1 is the symbol
_DATA_SECTION_PATTERN = re.compile(r"^\.(?:rodata|data)\.(.+)$")
# Code section; group 1 is the function for -ffunction-sections names, after any
# placement prefix (.text.startup.<fn>, .iram.text.<fn> for IRAM_ATTR)
_CODE_SECTION_PATTERN = re.compile(
r"^\.(?:literal|text|irom0\.text|iram\.text|iram0\.text)"
r"(?:\.(?:startup|unlikely|hot|exit)(?=\.|$))?(?:\.(.+))?$"
)
# readelf -x row: " 0x00000000 0000803f 0000803f 0000803f 0000803f ...?...?...?...?"
_HEX_DUMP_PREFIX = " 0x"
_HEX_DUMP_COLUMNS = slice(13, 48)
# RAM sections - symbols in these sections consume RAM
RAM_SECTIONS = frozenset([".data", ".bss"])
@@ -119,6 +144,31 @@ class SDKSymbol:
demangled: str = "" # Demangled name (populated after analysis)
@dataclass
class UnnamedConstant:
"""Constant without a symbol in an object's .rodata (RAM on ESP8266)."""
size: int
source_file: str
component: str
functions: list[str] # Functions that reference it, mangled
jump_table: bool # Holds code addresses (a switch table), not a value
data: bytes # Leading bytes, to recognize the value
strings: list[str] = field(default_factory=list) # String literals it points to
# Every function that uses the section, which decides whether the link kept it
users: list[str] = field(default_factory=list)
@dataclass
class StringLiteral:
"""A string literal kept in RAM (.rodata on ESP8266)."""
text: str
size: int # Bytes in RAM; strings shared or merged into a longer one count once
# Component -> functions or objects that use it, mangled
users: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set))
@dataclass
class ComponentMemory:
"""Tracks memory usage for a component."""
@@ -152,6 +202,201 @@ class ComponentMemory:
return self.data_size + self.bss_size
@dataclass
class _RodataSection:
"""An object's .rodata section and the byte ranges its symbols cover."""
name: str
size: int
covered: list[tuple[int, int]] = field(default_factory=list) # (offset, size)
@cached_property
def _named(self) -> frozenset[int]:
return frozenset(
offset
for start, size in self.covered
for offset in range(start, min(start + size, self.size))
)
def is_unnamed(self, offset: int) -> bool:
return 0 <= offset < self.size and offset not in self._named
@property
def unnamed_size(self) -> int:
return self.size - len(self._named)
def _parse_string_sections(output: str) -> dict[str, dict[str, tuple[str, str | None]]]:
"""Find string literal sections in ``readelf -SW`` output.
Returns:
Object path -> section index -> (section name, function it is named after)
"""
sections: dict[str, dict[str, tuple[str, str | None]]] = defaultdict(dict)
file_path = ""
for line in output.splitlines():
if line.startswith("File: "):
file_path = line[6:]
elif (match := _OBJ_SECTION_PATTERN.match(line)) is not None:
index, name, section_type, size_hex, flags = match.groups()
if (
section_type == "PROGBITS"
and "S" in flags
and int(size_hex, 16)
and (string := _STRING_SECTION_PATTERN.match(name))
):
sections[file_path][index] = (name, string.group(1))
return sections
def _ram_string_size(text: bytes, rodata: bytes, literals: Container[bytes]) -> int:
"""Bytes a literal takes in RAM: 0 if dropped or only the tail of another literal."""
needle = text + b"\0"
start = rodata.find(needle)
while start != -1:
head = rodata.rfind(b"\0", 0, start) + 1
end = start + len(text)
# Only the tail of a longer literal of ours if one starts before it; other
# bytes there are data, or a literal from an object that was not scanned
if not any(rodata[k:end] in literals for k in range(head, start)):
return len(needle)
start = rodata.find(needle, start + 1)
return 0
def _parse_hex_dumps(output: str) -> dict[str, bytearray]:
"""Collect the bytes of each ``readelf -x`` section dump by section name."""
contents: dict[str, bytearray] = defaultdict(bytearray)
section: str | None = None
for line in output.splitlines():
if line.startswith("Hex dump of section"):
section = line.split("'")[1]
elif section is not None and line.startswith(_HEX_DUMP_PREFIX):
contents[section] += bytes.fromhex(line[_HEX_DUMP_COLUMNS].replace(" ", ""))
elif line and not line.startswith(" "):
section = None
return contents
def _parse_relocations(output: str) -> list[tuple[str, int, str, int]]:
"""List (relocated section, offset, target, addend) from ``readelf -rW`` output."""
relocations: list[tuple[str, int, str, int]] = []
section: str | None = None
for line in output.splitlines():
if line.startswith("Relocation section"):
match = _RELOC_SECTION_PATTERN.match(line)
section = match.group(1) if match else None
elif line[:1].isdigit() and section is not None:
# Offset Info Type Sym.Value Sym.Name + Addend
fields = line.split()
if len(fields) < 5:
continue
addend = int(fields[6], 16) if len(fields) > 6 else 0
if len(fields) > 6 and fields[5] == "-":
addend = -addend
relocations.append((section, int(fields[0], 16), fields[4], addend))
elif line and line[0] != " ":
section = None
return relocations
def _pointer_target(referrer: bytes, offset: int, addend: int) -> int | None:
"""Offset a relocated pointer at ``offset`` points to, or None if not dumped."""
if offset < 0 or offset + 4 > len(referrer):
return None
# Xtensa keeps part of the addend in the relocated word
return addend + int.from_bytes(referrer[offset : offset + 4], "little")
def _pointed_literal(
referrer: bytes, offset: int, addend: int, strings: bytes
) -> bytes | None:
"""Read the string literal a relocated pointer refers to, or None if out of range."""
start = _pointer_target(referrer, offset, addend)
if start is None or not 0 <= start < len(strings):
return None
end = strings.find(b"\0", start)
return bytes(strings[start : end if end != -1 else len(strings)])
def _section_user(section: str) -> str | None:
"""The function or data symbol a -ffunction-sections/-fdata-sections name is for."""
match = _CODE_SECTION_PATTERN.match(section) or _DATA_SECTION_PATTERN.match(section)
return match.group(1) if match else None
@dataclass
class _FunctionDefinitions:
"""Where each function is defined across the scanned objects."""
weak: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set))
strong: set[str] = field(default_factory=set) # Global, non-weak
count: Counter[str] = field(default_factory=Counter) # Objects defining it
def linked_copy_unknown(self, file_path: str, functions: list[str]) -> bool:
"""True if another object's copy of these functions may be the linked one."""
if not functions:
return False
if self.weak[file_path].issuperset(functions):
# Inline copies: dropped only once a strong definition replaces every user
return self.strong.issuperset(functions)
# Same-named local functions in several objects; the ELF can't tell them apart
return all(f not in self.strong and self.count[f] > 1 for f in functions)
def _parse_unnamed_rodata(
output: str,
) -> tuple[dict[str, dict[str, _RodataSection]], _FunctionDefinitions]:
"""Find .rodata sections with bytes no symbol covers in ``readelf -SW -sW`` output.
Returns:
Object path -> section index -> section, and where functions are defined
"""
sections: dict[str, dict[str, _RodataSection]] = defaultdict(dict)
definitions = _FunctionDefinitions()
file_path = ""
for line in output.splitlines():
if line.startswith("File: "):
file_path = line[6:]
elif match := _OBJ_SECTION_PATTERN.match(line):
index, name, section_type, size_hex, flags = match.groups()
# Merged sections (string literals) are shared between objects
if (
section_type == "PROGBITS"
and name.startswith(".rodata")
and "A" in flags
and "M" not in flags
):
sections[file_path][index] = _RodataSection(name, int(size_hex, 16))
else:
# Num: Value Size Type Bind Vis Ndx Name
fields = line.split()
if len(fields) < 8:
continue
if fields[3] == "OBJECT" and (
section := sections[file_path].get(fields[6])
):
section.covered.append((int(fields[1], 16), int(fields[2], 0)))
elif fields[3] == "FUNC" and fields[6] != "UND":
definitions.count[fields[7]] += 1
if fields[4] == "WEAK":
definitions.weak[file_path].add(fields[7])
elif fields[4] == "GLOBAL":
definitions.strong.add(fields[7])
unnamed = {
path: kept
for path, file_sections in sections.items()
if (
kept := {
index: section
for index, section in file_sections.items()
if section.unnamed_size
}
)
}
return unnamed, definitions
class MemoryAnalyzer:
"""Analyzes memory usage from ELF files."""
@@ -231,6 +476,10 @@ class MemoryAnalyzer:
self._heuristic_to_lib: dict[str, str] = {}
# Function call counts: mangled_name -> call_count
self._function_call_counts: Counter[str] = Counter()
# True on ESP8266, where .rodata is RAM; it is then counted as .data
self.rodata_in_ram = False
self._unnamed_constants: list[UnnamedConstant] = []
self._string_literals: list[StringLiteral] = []
def analyze(self) -> dict[str, ComponentMemory]:
"""Analyze the ELF file and return component memory usage."""
@@ -240,6 +489,7 @@ class MemoryAnalyzer:
self._scan_source_symbols()
self._categorize_symbols()
self._analyze_cswtch_symbols()
self._analyze_object_rodata()
self._analyze_sdk_libraries()
self._analyze_function_calls()
return dict(self.components)
@@ -253,18 +503,17 @@ class MemoryAnalyzer:
check=True,
)
# Parse section headers
for line in result.stdout.splitlines():
# Look for section entries
if not (match := _READELF_SECTION_PATTERN.match(line)):
continue
raw_sections = [
(match.group(1), int(match.group(2), 16))
for line in result.stdout.splitlines()
if (match := _READELF_SECTION_PATTERN.match(line))
]
self.rodata_in_ram = any(
name == _ESP8266_FLASH_CODE_SECTION for name, _ in raw_sections
)
section_name = match.group(1)
size_hex = match.group(2)
size = int(size_hex, 16)
# Map to standard section name
mapped_section = map_section_name(section_name)
for section_name, size in raw_sections:
mapped_section = self._standard_section(map_section_name(section_name))
if not mapped_section:
continue
@@ -272,6 +521,12 @@ class MemoryAnalyzer:
self.sections[mapped_section] = MemorySection(mapped_section)
self.sections[mapped_section].total_size += size
def _standard_section(self, section: str | None) -> str | None:
"""Count .rodata as .data where it is RAM (ESP8266)."""
if section == ".rodata" and self.rodata_in_ram:
return ".data"
return section
def _parse_symbols(self) -> None:
"""Parse symbols from ELF file."""
result = subprocess.run(
@@ -289,14 +544,18 @@ class MemoryAnalyzer:
continue
section, name, size, address = symbol_info
section = self._standard_section(section)
if section not in self.sections:
continue
# Every alias is in the ELF, even when its size is counted once
self._elf_symbol_names.add(name)
# Skip duplicate symbols at the same address (e.g., C1/C2 constructors)
if address in seen_addresses or section not in self.sections:
if address in seen_addresses:
continue
self.sections[section].symbols.append((name, size, ""))
self.sections[section].symbol_size += size
self._elf_symbol_names.add(name)
seen_addresses.add(address)
def _categorize_symbols(self) -> None:
@@ -925,10 +1184,12 @@ class MemoryAnalyzer:
Path to the directory containing .o files, or None if not found.
"""
# The ELF is typically at .pioenvs/<env>/firmware.elf
# Object files are in .pioenvs/<env>/src/ and .pioenvs/<env>/lib*/
# PlatformIO puts object files in .pioenvs/<env>/src/ and .pioenvs/<env>/lib*/,
# the native ESP8266 build in .pioenvs/<env>/obj/src/ and obj/lib/
pioenvs_dir = self.elf_path.parent
if pioenvs_dir.exists() and any(pioenvs_dir.glob("src/*.o")):
return pioenvs_dir
for obj_dir in (pioenvs_dir, pioenvs_dir / "obj"):
if any(obj_dir.glob("src/*.o")):
return obj_dir
return None
@staticmethod
@@ -1110,6 +1371,12 @@ class MemoryAnalyzer:
):
return f"{_COMPONENT_PREFIX_LIB}{self._lib_hash_to_name[parts[1]]}"
# Native ESP8266 build: lib/<owner>__<Name>/... and the Arduino core in core/
if len(parts) >= 3 and parts[0] == "lib":
return f"{_COMPONENT_PREFIX_LIB}{parts[1].rsplit('__', 1)[-1].lower()}"
if len(parts) >= 2 and parts[0] == "core":
return _COMPONENT_ARDUINO_CORE
# Other framework/library files - return the first path component
# e.g., FrameworkArduino/... -> FrameworkArduino
return parts[0] if parts else source_file
@@ -1191,9 +1458,7 @@ class MemoryAnalyzer:
and other_mem is not None
):
other_mem.add_section_size(section_name, -size)
if component not in self.components:
self.components[component] = ComponentMemory(component)
self.components[component].add_section_size(section_name, size)
self._add_component_size(component, section_name, size)
# Sort by size descending
self._cswtch_symbols.sort(key=lambda x: x[1], reverse=True)
@@ -1205,6 +1470,350 @@ class MemoryAnalyzer:
total_size,
)
def _analyze_object_rodata(self) -> None:
"""Attribute .rodata without a symbol, which is RAM on ESP8266, to components."""
if not self.rodata_in_ram:
return
if (obj_dir := self._find_object_files_dir()) is None:
_LOGGER.warning(
"No object files next to the ELF, so constants in RAM are not listed"
)
return
objects = [str(f) for f in sorted(obj_dir.rglob("*.o"))]
result = run_tool([self.readelf_path, "-SW", "-sW", *objects])
if result is None:
_LOGGER.warning("readelf failed, so constants in RAM are not listed")
return
if result.returncode != 0:
# readelf still prints every object it could read
_LOGGER.warning(
"readelf could not read every object: %s", result.stderr.strip()
)
output = result.stdout
# readelf names each file only when given several
if len(objects) == 1:
output = f"File: {objects[0]}\n{output}"
self._attribute_unnamed_constants(output, obj_dir)
self._attribute_string_literals(output, obj_dir)
names = {n for c in self._unnamed_constants for n in c.functions} | {
n
for literal in self._string_literals
for users in literal.users.values()
for n in users
}
self._batch_demangle_symbols(sorted(names - self._demangle_cache.keys()))
def _attribute_unnamed_constants(self, output: str, obj_dir: Path) -> None:
"""Attribute constants GCC copies into objects built from constant initializers."""
unnamed, definitions = _parse_unnamed_rodata(output)
# Inline (weak) functions are emitted, with their constants, in every
# object that uses them; the linker keeps one copy
inline_copies: dict[tuple[tuple[str, ...], int], str] = {}
for file_path, sections in unnamed.items():
rel_path = Path(file_path).relative_to(obj_dir).as_posix()
component = self._source_file_to_component(rel_path)
for constant in self._scan_object_constants(
file_path, sections, rel_path, component
):
# Only linked users can show which object's copy survived
live = [u for u in constant.users if u in self._elf_symbol_names]
if definitions.linked_copy_unknown(file_path, live):
continue
if definitions.weak[file_path].issuperset(live):
key = (tuple(live), constant.size)
if inline_copies.setdefault(key, file_path) != file_path:
continue
self._unnamed_constants.append(constant)
self._charge_ram(component, constant.size)
self._unnamed_constants.sort(key=lambda c: c.size, reverse=True)
def _attribute_string_literals(self, output: str, obj_dir: Path) -> None:
"""Attribute string literals in RAM to the components whose code uses them.
The linker merges identical literals across objects, so each is counted
once, from the bytes it really takes in the ELF's .rodata.
"""
result = run_tool([self.readelf_path, "-x", ".rodata", str(self.elf_path)])
rodata = _parse_hex_dumps(result.stdout).get(".rodata") if result else None
if not rodata:
_LOGGER.warning(
"No .rodata dump of %s, so string literals are not listed",
self.elf_path,
)
return
rodata = bytes(rodata)
_, definitions = _parse_unnamed_rodata(output)
# Literal -> component -> functions or data using it
users: dict[bytes, dict[str, set[str]]] = defaultdict(lambda: defaultdict(set))
for file_path, sections in _parse_string_sections(output).items():
component = self._source_file_to_component(
Path(file_path).relative_to(obj_dir).as_posix()
)
for text, found in self._scan_object_strings(file_path, sections).items():
kept = {
user
for user in found & self._elf_symbol_names
if not definitions.linked_copy_unknown(file_path, [user])
}
if text and kept:
users[text][component] |= kept
literals = (
StringLiteral(
text.decode("utf-8", "backslashreplace"),
_ram_string_size(text, rodata, users),
by_component,
)
for text, by_component in users.items()
)
self._string_literals = sorted(
(s for s in literals if s.size), key=lambda s: (-s.size, s.text)
)
for literal in self._string_literals:
# A literal used by several components is not charged to any of them
if len(literal.users) == 1:
self._charge_ram(next(iter(literal.users)), literal.size)
def _scan_object_strings(
self, file_path: str, sections: dict[str, tuple[str, str | None]]
) -> dict[bytes, set[str]]:
"""Map each string literal of one object to the functions or data using it.
Args:
file_path: Object file to read
sections: String sections by index, with the function each is named after
"""
result = run_tool(
[self.readelf_path, "-rW"]
+ [arg for index in sections for arg in ("-x", index)]
+ [file_path]
)
if result is None or result.returncode != 0:
_LOGGER.warning(
"readelf failed reading strings of %s: %s",
file_path,
result.stderr.strip() if result else "not run",
)
return {}
contents = _parse_hex_dumps(result.stdout)
users: dict[bytes, set[str]] = defaultdict(set)
# Section -> the function it is named after, None for the shared section
owners = dict(sections.values())
for name, function in owners.items():
# A section named after a function holds its literals; others may use them too
if function:
for text in bytes(contents[name]).split(b"\0")[:-1]:
users[text].add(function)
relocations = _parse_relocations(result.stdout)
# Functions using each unnamed table, for literals reached through a pointer in it
table_users: dict[str, set[str]] = defaultdict(set)
for section, _, target, _ in relocations:
if (
target.startswith(".rodata")
and not _STRING_SECTION_PATTERN.match(target)
and (function := _section_user(section))
and _CODE_SECTION_PATTERN.match(section)
):
table_users[target].add(function)
# Other users are found from the pointers they hold
refs = [
(section, found, offset, target, addend)
for section, offset, target, addend in relocations
if target in owners
and (
found := {u} if (u := _section_user(section)) else table_users[section]
)
and found != {owners[target]}
]
unnamed = sum(
1
for section, _, target, _ in relocations
if target in owners
and owners[target] is None
and not _section_user(section)
and not table_users[section]
)
if unnamed:
_LOGGER.debug(
"%s: %d string pointers with no named user", file_path, unnamed
)
if not refs:
return users
result = run_tool(
[self.readelf_path]
+ [arg for name in sorted({r[0] for r in refs}) for arg in ("-x", name)]
+ [file_path]
)
if result is None or result.returncode != 0:
_LOGGER.warning(
"readelf failed reading string users of %s: %s",
file_path,
result.stderr.strip() if result else "not run",
)
return users
referrers = _parse_hex_dumps(result.stdout)
for section, found, offset, target, addend in refs:
# A pointer that can't be read names no literal
text = _pointed_literal(
referrers.get(section, b""), offset, addend, contents[target]
)
if text is not None:
users[text] |= found
return users
def _scan_object_constants(
self,
file_path: str,
sections: dict[str, _RodataSection],
rel_path: str,
component: str,
) -> list[UnnamedConstant]:
"""Return the unnamed constants of one object that the link kept.
Args:
file_path: Object file to read
sections: Candidate sections by index
rel_path: Object path shown in the report
component: Component the object belongs to
"""
result = run_tool(
[self.readelf_path, "-rW"]
+ [arg for index in sections for arg in ("-x", index)]
+ [file_path]
)
if result is None or result.returncode != 0:
_LOGGER.warning(
"readelf failed reading constants of %s: %s",
file_path,
result.stderr.strip() if result else "not run",
)
return []
by_name = {section.name: section for section in sections.values()}
contents = _parse_hex_dumps(result.stdout)
# Every function using the section decides whether the link kept it
users: dict[str, set[str]] = defaultdict(set)
# Functions shown as using the unnamed bytes
functions: dict[str, set[str]] = defaultdict(set)
# (code section, offset, addend, target, function) into sections with named bytes
mixed: list[tuple[str, int, int, str, str]] = []
jump_tables: set[str] = set()
# Section -> (offset, string section, addend) of each pointer to a literal
pointers: dict[str, list[tuple[int, str, int]]] = defaultdict(list)
for section, offset, target, addend in _parse_relocations(result.stdout):
if target in by_name:
code = _CODE_SECTION_PATTERN.match(section)
if code and code.group(1):
users[target].add(code.group(1))
if by_name[target].covered:
mixed.append((section, offset, addend, target, code.group(1)))
else:
functions[target].add(code.group(1))
elif section in by_name and by_name[section].is_unnamed(offset):
if _CODE_SECTION_PATTERN.match(target):
jump_tables.add(section)
elif ".str" in target:
pointers[section].append((offset, target, addend))
self._add_mixed_section_users(file_path, mixed, by_name, functions)
strings = self._read_pointed_strings(file_path, pointers, contents)
return [
UnnamedConstant(
size=section.unnamed_size,
source_file=rel_path,
component=component,
functions=sorted(functions[name]),
jump_table=name in jump_tables,
data=bytes(
byte
for offset, byte in enumerate(contents[name])
if section.is_unnamed(offset)
)[:16],
strings=strings.get(name, []),
users=sorted(users[name]),
)
for name, section in by_name.items()
# Dropped by --gc-sections unless a function that uses it was kept
if not self._elf_symbol_names.isdisjoint(users[name])
]
def _add_mixed_section_users(
self,
file_path: str,
mixed: list[tuple[str, int, int, str, str]],
by_name: dict[str, _RodataSection],
functions: dict[str, set[str]],
) -> None:
"""Name only the functions that point at the unnamed bytes of a mixed section."""
if not mixed:
return
result = run_tool(
[self.readelf_path]
+ [arg for name in sorted({m[0] for m in mixed}) for arg in ("-x", name)]
+ [file_path]
)
code = _parse_hex_dumps(result.stdout) if result else {}
for section, offset, addend, target, function in mixed:
start = _pointer_target(code.get(section, b""), offset, addend)
# A pointer that can't be read, or lands outside the section, keeps the user
section_size = by_name[target].size
if (
start is None
or not 0 <= start < section_size
or by_name[target].is_unnamed(start)
):
functions[target].add(function)
def _read_pointed_strings(
self,
file_path: str,
pointers: dict[str, list[tuple[int, str, int]]],
contents: dict[str, bytearray],
) -> dict[str, list[str]]:
"""Resolve each constant's pointers to string literals, in offset order."""
if not pointers:
return {}
targets = sorted({t for refs in pointers.values() for _, t, _ in refs})
result = run_tool(
[self.readelf_path]
+ [arg for target in targets for arg in ("-x", target)]
+ [file_path]
)
if result is None or result.returncode != 0:
_LOGGER.warning(
"readelf failed reading strings of %s: %s",
file_path,
result.stderr.strip() if result else "not run",
)
return {}
literals = _parse_hex_dumps(result.stdout)
resolved: dict[str, list[str]] = {}
for name, refs in pointers.items():
texts = [
_pointed_literal(
contents[name], offset, addend, literals.get(target, b"")
)
for offset, target, addend in sorted(refs)
]
# One pointer that can't be read makes the list misleading; show bytes instead
if all(text is not None for text in texts):
resolved[name] = [t.decode("utf-8", "backslashreplace") for t in texts]
return resolved
def _charge_ram(self, component: str, size: int) -> None:
"""Charge RAM bytes that have no ELF symbol to a component."""
self._add_component_size(component, ".data", size)
if (data_section := self.sections.get(".data")) is not None:
data_section.symbol_size += size
def _add_component_size(self, component: str, section: str, size: int) -> None:
"""Add size to a component, creating it under its own name."""
if component not in self.components:
self.components[component] = ComponentMemory(component)
self.components[component].add_section_size(section, size)
def _analyze_function_calls(self) -> None:
"""Count function call sites by parsing disassembly output.
+88 -2
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
from collections import defaultdict
from collections.abc import Callable
import heapq
import json
from operator import itemgetter
from pathlib import Path
import sys
@@ -23,7 +24,7 @@ from . import (
from .toolchain import find_elf_path, find_idedata_path, idedata_candidates
if TYPE_CHECKING:
from . import ComponentMemory
from . import ComponentMemory, StringLiteral
def _format_pstorage_name(name: str) -> str:
@@ -46,6 +47,8 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
)
# Lower threshold for RAM symbols (RAM is more constrained)
RAM_SYMBOL_SIZE_THRESHOLD: int = 24
# String literals listed per component in the RAM strings report
STRINGS_PER_COMPONENT: int = 10
# Number of top symbols to show in the largest symbols report
TOP_SYMBOLS_LIMIT: int = 30
# Width for symbol name display in top symbols report
@@ -204,6 +207,79 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
f"{i + 1:>2}. {size:>7,} B {section_label:<8} {demangled_display:<{self.COL_TOP_SYMBOL_NAME}} {component}"
)
def _add_unnamed_constants_analysis(self, lines: list[str]) -> None:
"""Add the unnamed constants (ESP8266 .rodata in RAM) section."""
self._add_section_header(lines, "Unnamed Constants in RAM (.rodata)")
total_size = sum(c.size for c in self._unnamed_constants)
lines.append(
f"Total: {len(self._unnamed_constants)} constant(s), {total_size:,} B. "
"GCC copies these into objects built from constant initializers;"
)
lines.append(
"PROGMEM tables, assigned fields or a user-provided constructor avoid the copy."
)
lines.append("")
for constant in self._unnamed_constants:
kind = "switch table" if constant.jump_table else "constant"
lines.append(
f"{constant.size:>6,} B {kind:<12} {constant.component} ({constant.source_file})"
)
lines.extend(
f"{'':>9} used by {self._demangle_symbol(function)}"
for function in constant.functions
)
if constant.strings:
# Escaped, so control characters in a literal can't disturb the terminal
shown = ", ".join(
json.dumps(text[:40]) for text in constant.strings[:4]
)
more = ", ..." if len(constant.strings) > 4 else ""
lines.append(f"{'':>9} points to {shown}{more}")
elif constant.data and not constant.jump_table:
more = " ..." if constant.size > len(constant.data) else ""
lines.append(f"{'':>9} bytes: {constant.data.hex(' ')}{more}")
lines.append("")
def _add_string_literals_analysis(self, lines: list[str]) -> None:
"""Add the string literals in RAM (ESP8266 .rodata) section, by component."""
self._add_section_header(lines, "String Literals in RAM (.rodata)")
total_size = sum(s.size for s in self._string_literals)
lines.append(
f"Total: {len(self._string_literals)} string(s), {total_size:,} B. "
"LOG_STR, ESPHOME_F or a PROGMEM table keeps a literal in flash."
)
lines.append(
"Only literals whose user is known are counted; one used by several components is "
"listed under each and charged to none."
)
lines.append("")
by_component: dict[str, list[StringLiteral]] = defaultdict(list)
for literal in self._string_literals:
for component in literal.users:
by_component[component].append(literal)
totals = {c: sum(s.size for s in ls) for c, ls in by_component.items()}
for component, literals in sorted(
by_component.items(), key=lambda x: (-totals[x[0]], x[0])
):
comp_total = totals[component]
lines.append(f"{component} ({comp_total:,} B, {len(literals)} strings):")
for literal in literals[: self.STRINGS_PER_COMPONENT]:
text = json.dumps(literal.text)
if len(text) > 50:
text = f'{text[:47]}..."'
users = sorted(
self._demangle_symbol(u) for u in literal.users[component]
)
used_by = users[0][:60] + (
f" (+{len(users) - 1})" if len(users) > 1 else ""
)
lines.append(f" {literal.size:>5,} B {text:<50} {used_by}")
if len(literals) > self.STRINGS_PER_COMPONENT:
lines.append(
f" ... and {len(literals) - self.STRINGS_PER_COMPONENT} more"
)
lines.append("")
def _add_cswtch_analysis(self, lines: list[str]) -> None:
"""Add CSWTCH (GCC switch table lookup) analysis section."""
self._add_section_header(lines, "CSWTCH Analysis (GCC Switch Table Lookups)")
@@ -394,6 +470,12 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
f"{total_flash:>{self.COL_TOTAL_FLASH - 2},} B | {total_ram:>{self.COL_TOTAL_RAM - 2},} B"
)
if self.rodata_in_ram:
lines.append("")
lines.append(
"ESP8266 keeps .rodata in RAM, so constants are counted in RAM (data)."
)
# Show unattributed RAM (SDK/framework overhead)
unattributed_bss, unattributed_data, unattributed_total = (
self.get_unattributed_ram()
@@ -657,6 +739,11 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
lines.append(f" ... and {len(large_ram_syms) - 10} more")
lines.append("")
if self._unnamed_constants:
self._add_unnamed_constants_analysis(lines)
if self._string_literals:
self._add_string_literals_analysis(lines)
# CSWTCH (GCC switch table) analysis
if self._cswtch_symbols:
self._add_cswtch_analysis(lines)
@@ -738,7 +825,6 @@ def main():
build_dir = sys.argv[1]
# Load build directory
import json
from esphome.platformio.toolchain import IDEData
+2 -2
View File
@@ -96,7 +96,7 @@ void AHT10Component::read_data_() {
this->restart_read_();
return;
}
if (data[1] == 0x0 && data[2] == 0x0 && (data[3] >> 4) == 0x0) {
if (data[1] == 0x0 && data[2] == 0x0 && high_nibble(data[3]) == 0x0) {
// Invalid humidity (0x0)
if (this->humidity_sensor_ == nullptr) {
ESP_LOGV(TAG, "Invalid humidity (reading not required)");
@@ -110,7 +110,7 @@ void AHT10Component::read_data_() {
if (this->read_count_ > 1) {
ESP_LOGD(TAG, "Success at %ums", (unsigned) (millis() - this->start_time_));
}
uint32_t raw_temperature = encode_uint24(data[3] & 0xF, data[4], data[5]);
uint32_t raw_temperature = encode_uint24(low_nibble(data[3]), data[4], data[5]);
uint32_t raw_humidity = encode_uint24(data[1], data[2], data[3]) >> 4;
PUBLISH_STATE(this->temperature_sensor_, ((200.0f * static_cast<float>(raw_temperature)) / AHT10_DIVISOR) - 50.0f);
+2 -2
View File
@@ -62,9 +62,9 @@ bool AM2315C::reset_register_(uint8_t reg) {
bool AM2315C::convert_(uint8_t *data, float &humidity, float &temperature) {
uint32_t raw;
raw = (data[1] << 12) | (data[2] << 4) | (data[3] >> 4);
raw = encode_uint24(data[1], data[2], data[3]) >> 4;
humidity = raw * 9.5367431640625e-5;
raw = encode_uint24(data[3] & 0x0F, data[4], data[5]);
raw = encode_uint24(low_nibble(data[3]), data[4], data[5]);
temperature = raw * 1.9073486328125e-4 - 50;
return crc8(data, 6, 0xFF, 0x31, true) == data[6];
}
+8
View File
@@ -70,6 +70,10 @@ void APIServer::setup() {
#if defined(USE_API_HOMEASSISTANT_STATES) && defined(HOMEASSISTANT_STATE_SUBSCRIPTION_COUNT)
this->state_subs_.reserve(HOMEASSISTANT_STATE_SUBSCRIPTION_COUNT);
#endif
#ifdef USE_API_HOMEASSISTANT_IMPORTS
if (this->homeassistant_subscribe_publisher_ != nullptr)
this->homeassistant_subscribe_publisher_();
#endif
#ifdef USE_API_NOISE
// Always reserve the slot: flash preferences are positional on esp8266, so
// a yaml key build must keep the layout of a runtime key build
@@ -389,6 +393,10 @@ void APIServer::dump_config() {
#ifdef USE_API_OUTGOING_CONNECTION
this->outgoing_conn_.dump_config();
#endif
#ifdef USE_API_HOMEASSISTANT_IMPORTS
if (this->homeassistant_dump_publisher_ != nullptr)
this->homeassistant_dump_publisher_();
#endif
}
void APIServer::handle_disconnect(APIConnection *conn) {}
+5
View File
@@ -272,6 +272,11 @@ class APIServer final : public Component
/// Measure again the subscriptions whose entity id is this buffer, after the wizard wrote a new id into it.
void update_state_subscription_entity_id(const char *entity_id);
#endif
#ifdef USE_API_HOMEASSISTANT_IMPORTS
// Generated: subscribes the imported Home Assistant entities, and prints their dumps
HUB_PUBLISHER(homeassistant_subscribe)
HUB_PUBLISHER(homeassistant_dump)
#endif
#endif
#ifdef USE_API_USER_DEFINED_ACTIONS
const std::vector<UserServiceDescriptor *> &get_user_services() const { return this->user_services_; }
+1 -1
View File
@@ -24,7 +24,7 @@ enum class AranetDeviceType : uint8_t {
// https://github.com/Anrijs/Aranet4-Python/blob/master/aranet4/client.py
// https://github.com/Anrijs/Aranet4-ESP32/blob/main/src/Aranet4.h
void Aranet::dump_config() {
void Aranet::dump_child_config() {
ESP_LOGCONFIG(TAG, "Aranet");
LOG_SENSOR(" ", "Carbon Dioxide", this->co2_sensor_);
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
+2 -3
View File
@@ -2,16 +2,15 @@
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/component.h"
namespace esphome::aranet {
class Aranet final : public Component, public ble_device_base::ESPBTDeviceListener {
class Aranet final : public ble_device_base::ESPBTDeviceListener {
public:
explicit Aranet(uint64_t address) : address_(address) {}
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
protected:
static constexpr uint8_t WARNED_INVALID_LENGTH = 1 << 0;
+72 -78
View File
@@ -43,7 +43,7 @@ CONF_RADIATION_DURATION = "radiation_duration"
UNIT_NANOSIEVERT = "nSv"
aranet_ns = cg.esphome_ns.namespace("aranet")
Aranet = aranet_ns.class_("Aranet", ble_device_base.ESPBTDeviceListener, cg.Component)
Aranet = aranet_ns.class_("Aranet", ble_device_base.ESPBTDeviceListener)
DIAGNOSTIC_DURATION_SCHEMA = sensor.sensor_schema(
unit_of_measurement=UNIT_SECOND,
@@ -53,86 +53,80 @@ DIAGNOSTIC_DURATION_SCHEMA = sensor.sensor_schema(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
)
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(Aranet),
cv.Required(CONF_MAC_ADDRESS): cv.mac_address,
cv.Optional(CONF_CO2): sensor.sensor_schema(
unit_of_measurement=UNIT_PARTS_PER_MILLION,
accuracy_decimals=0,
device_class=DEVICE_CLASS_CARBON_DIOXIDE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_TEMPERATURE): sensor.sensor_schema(
unit_of_measurement=UNIT_CELSIUS,
accuracy_decimals=1,
device_class=DEVICE_CLASS_TEMPERATURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_HUMIDITY): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=1,
device_class=DEVICE_CLASS_HUMIDITY,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_PRESSURE): sensor.sensor_schema(
unit_of_measurement=UNIT_HECTOPASCAL,
accuracy_decimals=1,
device_class=DEVICE_CLASS_PRESSURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_BATTERY_LEVEL): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=0,
device_class=DEVICE_CLASS_BATTERY,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_MEASUREMENT_INTERVAL): DIAGNOSTIC_DURATION_SCHEMA,
cv.Optional(CONF_MEASUREMENT_AGE): DIAGNOSTIC_DURATION_SCHEMA,
cv.Optional(CONF_SIGNAL_STRENGTH): sensor.sensor_schema(
unit_of_measurement=UNIT_DECIBEL_MILLIWATT,
accuracy_decimals=0,
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_RADON): sensor.sensor_schema(
unit_of_measurement=UNIT_BECQUEREL_PER_CUBIC_METER,
accuracy_decimals=0,
device_class=DEVICE_CLASS_RADON,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_RADIATION_RATE): sensor.sensor_schema(
unit_of_measurement=UNIT_MICROSILVERTS_PER_HOUR,
accuracy_decimals=3,
icon=ICON_RADIOACTIVE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_RADIATION_TOTAL): sensor.sensor_schema(
unit_of_measurement=UNIT_NANOSIEVERT,
accuracy_decimals=0,
icon=ICON_RADIOACTIVE,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
cv.Optional(CONF_RADIATION_DURATION): sensor.sensor_schema(
unit_of_measurement=UNIT_SECOND,
accuracy_decimals=0,
device_class=DEVICE_CLASS_DURATION,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA)
)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(Aranet),
cv.Required(CONF_MAC_ADDRESS): cv.mac_address,
cv.Optional(CONF_CO2): sensor.sensor_schema(
unit_of_measurement=UNIT_PARTS_PER_MILLION,
accuracy_decimals=0,
device_class=DEVICE_CLASS_CARBON_DIOXIDE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_TEMPERATURE): sensor.sensor_schema(
unit_of_measurement=UNIT_CELSIUS,
accuracy_decimals=1,
device_class=DEVICE_CLASS_TEMPERATURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_HUMIDITY): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=1,
device_class=DEVICE_CLASS_HUMIDITY,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_PRESSURE): sensor.sensor_schema(
unit_of_measurement=UNIT_HECTOPASCAL,
accuracy_decimals=1,
device_class=DEVICE_CLASS_PRESSURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_BATTERY_LEVEL): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=0,
device_class=DEVICE_CLASS_BATTERY,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_MEASUREMENT_INTERVAL): DIAGNOSTIC_DURATION_SCHEMA,
cv.Optional(CONF_MEASUREMENT_AGE): DIAGNOSTIC_DURATION_SCHEMA,
cv.Optional(CONF_SIGNAL_STRENGTH): sensor.sensor_schema(
unit_of_measurement=UNIT_DECIBEL_MILLIWATT,
accuracy_decimals=0,
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_RADON): sensor.sensor_schema(
unit_of_measurement=UNIT_BECQUEREL_PER_CUBIC_METER,
accuracy_decimals=0,
device_class=DEVICE_CLASS_RADON,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_RADIATION_RATE): sensor.sensor_schema(
unit_of_measurement=UNIT_MICROSILVERTS_PER_HOUR,
accuracy_decimals=3,
icon=ICON_RADIOACTIVE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_RADIATION_TOTAL): sensor.sensor_schema(
unit_of_measurement=UNIT_NANOSIEVERT,
accuracy_decimals=0,
icon=ICON_RADIOACTIVE,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
cv.Optional(CONF_RADIATION_DURATION): sensor.sensor_schema(
unit_of_measurement=UNIT_SECOND,
accuracy_decimals=0,
device_class=DEVICE_CLASS_DURATION,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
}
).extend(ble_device_base.BLE_DEVICE_SCHEMA)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(
config, config[CONF_MAC_ADDRESS].as_hex
)
var = await ble_device_base.new_ble_device(config, config[CONF_MAC_ADDRESS].as_hex)
sensors = sensor.sub_sensors(config)
await sensors(CONF_CO2, var.set_co2_sensor)
@@ -6,7 +6,7 @@ namespace esphome::atc_mithermometer {
ESPHOME_LOG_TAG(TAG, "atc_mithermometer");
void ATCMiThermometer::dump_config() {
void ATCMiThermometer::dump_child_config() {
ESP_LOGCONFIG(TAG, "ATC MiThermometer");
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
@@ -1,6 +1,5 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/ble_device_base/ble_device.h"
@@ -16,7 +15,7 @@ struct ParseResult {
int raw_offset;
};
class ATCMiThermometer final : public Component, public ble_device_base::ESPBTDeviceListener {
class ATCMiThermometer final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(temperature)
SUB_SENSOR(humidity)
SUB_SENSOR(battery_level)
@@ -27,7 +26,7 @@ class ATCMiThermometer final : public Component, public ble_device_base::ESPBTDe
void set_address(uint64_t address) { address_ = address; };
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
protected:
uint64_t address_;
@@ -28,7 +28,7 @@ AUTO_LOAD = ["ble_device_base"]
atc_mithermometer_ns = cg.esphome_ns.namespace("atc_mithermometer")
ATCMiThermometer = atc_mithermometer_ns.class_(
"ATCMiThermometer", ble_device_base.ESPBTDeviceListener, cg.Component
"ATCMiThermometer", ble_device_base.ESPBTDeviceListener
)
CONFIG_SCHEMA = cv.All(
@@ -71,14 +71,12 @@ CONFIG_SCHEMA = cv.All(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
).extend(ble_device_base.BLE_DEVICE_SCHEMA),
)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(config)
var = await ble_device_base.new_ble_device(config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
@@ -39,8 +39,8 @@ void AXS15231Touchscreen::update_touches() {
this->status_clear_warning();
if (data[0] != 0 || data[1] == 0) // no touches
return;
uint16_t x = encode_uint16(data[2] & 0xF, data[3]);
uint16_t y = encode_uint16(data[4] & 0xF, data[5]);
uint16_t x = encode_uint16(low_nibble(data[2]), data[3]);
uint16_t y = encode_uint16(low_nibble(data[4]), data[5]);
this->add_raw_touch_position_(0, x, y);
}
+1 -1
View File
@@ -6,7 +6,7 @@ namespace esphome::b_parasite {
ESPHOME_LOG_TAG(TAG, "b_parasite");
void BParasite::dump_config() {
void BParasite::dump_child_config() {
ESP_LOGCONFIG(TAG, "b_parasite");
LOG_SENSOR(" ", "Battery Voltage", this->battery_voltage_sensor_);
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
+2 -3
View File
@@ -1,12 +1,11 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/ble_device_base/ble_device.h"
namespace esphome::b_parasite {
class BParasite final : public Component, public ble_device_base::ESPBTDeviceListener {
class BParasite final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(battery_voltage)
SUB_SENSOR(temperature)
SUB_SENSOR(humidity)
@@ -18,7 +17,7 @@ class BParasite final : public Component, public ble_device_base::ESPBTDeviceLis
void set_bindkey(const std::string &bindkey);
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
protected:
// The received advertisement packet contains an unsigned 4 bits wrap-around counter
+3 -7
View File
@@ -26,9 +26,7 @@ CODEOWNERS = ["@rbaron"]
AUTO_LOAD = ["ble_device_base"]
b_parasite_ns = cg.esphome_ns.namespace("b_parasite")
BParasite = b_parasite_ns.class_(
"BParasite", ble_device_base.ESPBTDeviceListener, cg.Component
)
BParasite = b_parasite_ns.class_("BParasite", ble_device_base.ESPBTDeviceListener)
CONFIG_SCHEMA = cv.All(
ble_device_base.rename_legacy_hub_id("b_parasite"),
@@ -68,14 +66,12 @@ CONFIG_SCHEMA = cv.All(
state_class=STATE_CLASS_MEASUREMENT,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
).extend(ble_device_base.BLE_DEVICE_SCHEMA),
)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(config)
var = await ble_device_base.new_ble_device(config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
@@ -206,6 +206,7 @@ void BK72xxBLETracker::dump_config() {
this->scan_duration_ / 1000, ble_units_to_ms(this->scan_interval_), this->scan_interval_,
ble_units_to_ms(this->scan_window_), this->scan_window_, this->scan_active_ ? "ACTIVE" : "PASSIVE",
this->scan_active_configured_ ? "ACTIVE" : "PASSIVE", YESNO(this->scan_continuous_));
this->dispatcher_.dump_child_configs();
}
// ---------------------------------------------------------------------------
@@ -35,6 +35,7 @@ from esphome.const import (
CONF_ACTIVE,
CONF_CONTINUOUS,
CONF_DURATION,
CONF_ID,
CONF_INTERVAL,
KEY_TARGET_PLATFORM,
)
@@ -193,6 +194,11 @@ def new_ble_device_component(
return cg.new_bus_component(register_ble_device, config, *args)
async def new_ble_device(config: ConfigType, *args: Any) -> cg.MockObj:
"""Construct a listener that is not a Component and attach it to the BLE hub."""
return await register_ble_device(cg.new_Pvariable(config[CONF_ID], *args), config)
# ---- shared validation / codegen helpers (platform-neutral) ----
@@ -323,6 +323,8 @@ class ESPBTDeviceListener {
/// Called at the end of each scan duration period.
virtual void on_scan_end() {}
virtual bool parse_device(const ESPBTDevice &device) = 0;
/// Called from the tracker's dump_config(); not dump_config() so Component listeners don't print twice.
virtual void dump_child_config() {}
};
} // namespace esphome::ble_device_base
@@ -58,6 +58,13 @@ class AdvDispatcher {
bool raw_only, const char *log_unclaimed_tag);
/// Fire listeners' on_scan_end and reset the per-scan discovered-log dedup.
void on_scan_end();
/// Print each listener's dump_child_config(); called from the tracker's dump_config().
void dump_child_configs() {
#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
for (auto *listener : this->listeners_)
listener->dump_child_config();
#endif
}
protected:
RawAdvertisementCallback raw_callback_{};
@@ -5,6 +5,6 @@ namespace esphome::ble_rssi {
ESPHOME_LOG_TAG(TAG, "ble_rssi");
void BLERSSISensor::dump_config() { LOG_SENSOR("", "BLE RSSI Sensor", this); }
void BLERSSISensor::dump_child_config() { LOG_SENSOR("", "BLE RSSI Sensor", this); }
} // namespace esphome::ble_rssi
@@ -1,6 +1,5 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/sensor/sensor.h"
@@ -10,7 +9,7 @@
// guard.
namespace esphome::ble_rssi {
class BLERSSISensor final : public sensor::Sensor, public ble_device_base::ESPBTDeviceListener, public Component {
class BLERSSISensor final : public sensor::Sensor, public ble_device_base::ESPBTDeviceListener {
public:
void set_address(uint64_t address) {
this->match_by_ = MATCH_BY_MAC_ADDRESS;
@@ -100,7 +99,7 @@ class BLERSSISensor final : public sensor::Sensor, public ble_device_base::ESPBT
}
return false;
}
void dump_config() override;
void dump_child_config() override;
protected:
enum MatchType { MATCH_BY_MAC_ADDRESS, MATCH_BY_IRK, MATCH_BY_SERVICE_UUID, MATCH_BY_IBEACON_UUID };
+1 -3
View File
@@ -19,7 +19,7 @@ AUTO_LOAD = ["ble_device_base"]
ble_rssi_ns = cg.esphome_ns.namespace("ble_rssi")
BLERSSISensor = ble_rssi_ns.class_(
"BLERSSISensor", sensor.Sensor, cg.Component, ble_device_base.ESPBTDeviceListener
"BLERSSISensor", sensor.Sensor, ble_device_base.ESPBTDeviceListener
)
@@ -50,7 +50,6 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_IBEACON_UUID): ble_device_base.bt_uuid,
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
cv.has_exactly_one_key(
CONF_MAC_ADDRESS, CONF_IRK, CONF_SERVICE_UUID, CONF_IBEACON_UUID
@@ -61,7 +60,6 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config: ConfigType) -> None:
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
await ble_device_base.register_ble_device(var, config)
if mac_address := config.get(CONF_MAC_ADDRESS):
@@ -5,6 +5,6 @@ namespace esphome::ble_scanner {
ESPHOME_LOG_TAG(TAG, "ble_scanner");
void BLEScanner::dump_config() { LOG_TEXT_SENSOR("", "BLE Scanner", this); }
void BLEScanner::dump_child_config() { LOG_TEXT_SENSOR("", "BLE Scanner", this); }
} // namespace esphome::ble_scanner
+2 -3
View File
@@ -4,7 +4,6 @@
#include <cstdio>
#include <ctime>
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/string_ref.h"
#include "esphome/components/ble_device_base/ble_device.h"
@@ -16,7 +15,7 @@
// guard.
namespace esphome::ble_scanner {
class BLEScanner final : public text_sensor::TextSensor, public ble_device_base::ESPBTDeviceListener, public Component {
class BLEScanner final : public text_sensor::TextSensor, public ble_device_base::ESPBTDeviceListener {
public:
bool parse_device(const ble_device_base::ESPBTDevice &device) override {
char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
@@ -31,7 +30,7 @@ class BLEScanner final : public text_sensor::TextSensor, public ble_device_base:
this->publish_state(buf);
return true;
}
void dump_config() override;
void dump_child_config() override;
};
} // namespace esphome::ble_scanner
@@ -9,19 +9,17 @@ ble_scanner_ns = cg.esphome_ns.namespace("ble_scanner")
BLEScanner = ble_scanner_ns.class_(
"BLEScanner",
text_sensor.TextSensor,
cg.Component,
ble_device_base.ESPBTDeviceListener,
)
CONFIG_SCHEMA = cv.All(
ble_device_base.rename_legacy_hub_id("ble_scanner"),
text_sensor.text_sensor_schema(BLEScanner)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
text_sensor.text_sensor_schema(BLEScanner).extend(
ble_device_base.BLE_DEVICE_SCHEMA
),
)
async def to_code(config: ConfigType) -> None:
var = await text_sensor.new_text_sensor(config)
await cg.register_component(var, config)
await ble_device_base.register_ble_device(var, config)
@@ -114,10 +114,10 @@ void BME280Component::setup() {
this->calibration_.h1 = read_u8_(BME280_REGISTER_DIG_H1);
this->calibration_.h2 = read_s16_le_(BME280_REGISTER_DIG_H2);
this->calibration_.h3 = read_u8_(BME280_REGISTER_DIG_H3);
this->calibration_.h4 =
sign_extend<12>(read_u8_(BME280_REGISTER_DIG_H4) << 4 | (read_u8_(BME280_REGISTER_DIG_H4 + 1) & 0x0F));
this->calibration_.h5 =
sign_extend<12>(read_u8_(BME280_REGISTER_DIG_H5 + 1) << 4 | (read_u8_(BME280_REGISTER_DIG_H5) >> 4));
this->calibration_.h4 = sign_extend<12>(
encode_uint12(read_u8_(BME280_REGISTER_DIG_H4), low_nibble(read_u8_(BME280_REGISTER_DIG_H4 + 1))));
this->calibration_.h5 = sign_extend<12>(
encode_uint12(read_u8_(BME280_REGISTER_DIG_H5 + 1), high_nibble(read_u8_(BME280_REGISTER_DIG_H5))));
this->calibration_.h6 = read_u8_(BME280_REGISTER_DIG_H6);
uint8_t humid_control_val = 0;
+4 -3
View File
@@ -70,8 +70,9 @@ bool BME680Component::setup_registers_() {
this->calibration_.t2 = encode_value_le<int16_t>(&coeff1[1]);
this->calibration_.t3 = coeff1[3];
this->calibration_.h1 = coeff2[2] << 4 | (coeff2[1] & 0x0F);
this->calibration_.h2 = encode_uint16(coeff2[0], coeff2[1]) >> 4;
// H1 and H2 are 12-bit values sharing byte 1: its low nibble ends H1, its high nibble ends H2
this->calibration_.h1 = encode_uint12(coeff2[2], low_nibble(coeff2[1]));
this->calibration_.h2 = encode_uint12(coeff2[0], high_nibble(coeff2[1]));
this->calibration_.h3 = coeff2[3];
this->calibration_.h4 = coeff2[4];
this->calibration_.h5 = coeff2[5];
@@ -243,7 +244,7 @@ void BME680Component::read_data_() {
uint32_t raw_pressure = encode_uint24(data[2], data[3], data[4]) >> 4;
uint32_t raw_humidity = encode_uint16(data[8], data[9]);
uint16_t raw_gas = encode_uint16(data[13], data[14]) >> 6;
uint8_t gas_range = data[14] & 0x0F;
uint8_t gas_range = low_nibble(data[14]);
float temperature = this->calc_temperature_(raw_temperature);
float pressure = this->calc_pressure_(raw_pressure);
+70 -136
View File
@@ -1,5 +1,6 @@
#include "bmi270.h"
#include "bmi270_config.h"
#include "esphome/core/application.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include "esphome/core/progmem.h"
@@ -21,48 +22,40 @@ static constexpr size_t MAX_I2C_BUFFER_SIZE = 32;
static constexpr size_t MAX_I2C_BUFFER_SIZE = 256;
#endif
// Configuration blob upload
// The BMI270 requires a firmware config blob to be written to its internal
// memory after every power-on before sensors can be used.
bool BMI270Component::load_config_file_() {
// 1. Disable advanced power-save so the config port is accessible
// The config port is only reachable with advanced power save off
if (!this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_ADV_POWER_SAVE_OFF))
return false;
delay(1);
// 2. Prepare config load: write 0x00 to INIT_CTRL to start
if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_START))
return false;
// 3. Burst-write the config in pages
const uint8_t *cfg = BMI270_CONFIG_FILE;
constexpr size_t cfg_len = sizeof(BMI270_CONFIG_FILE);
// The register byte goes first, so each burst is copied once and sent with write()
uint8_t buf[1 + MAX_I2C_BUFFER_SIZE];
buf[0] = BMI270_REG_INIT_DATA;
size_t index = 0;
while (index != cfg_len) {
// Set the page address in INIT_ADDR registers
uint8_t addr_lsb = (uint8_t) ((index / 2) & 0x0F);
uint8_t addr_msb = (uint8_t) ((index / 2) >> 4);
if (!this->write_byte(BMI270_REG_INIT_ADDR_0, addr_lsb))
return false;
if (!this->write_byte(BMI270_REG_INIT_ADDR_0 + 1, addr_msb))
// INIT_ADDR_0 takes the word address bits 0-3 and INIT_ADDR_1 bits 4-11
const uint8_t addr[2] = {static_cast<uint8_t>((index / 2) & 0x0F), static_cast<uint8_t>((index / 2) >> 4)};
if (this->write_register(BMI270_REG_INIT_ADDR_0, addr, sizeof(addr)) != i2c::ERROR_OK)
return false;
// Write a burst of up to the maximum allowed size
size_t burst = clamp_at_most(cfg_len - index, MAX_I2C_BUFFER_SIZE);
if (this->write_register(BMI270_REG_INIT_DATA, cfg + index, burst) != i2c::ERROR_OK)
progmem_memcpy(buf + 1, BMI270_CONFIG_FILE + index, burst);
if (this->write(buf, burst + 1) != i2c::ERROR_OK)
return false;
index += burst;
// 256 bursts at 50 kHz, or through an I2C multiplexer, outlast the ESP8266 soft watchdog
App.feed_wdt();
}
// 4. Signal end of config load
if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_DONE))
return false;
delay(20); // spec: wait ≥20 ms for init to complete
delay(20); // The datasheet asks for at least 20 ms before INTERNAL_STATUS is valid
// 5. Check INTERNAL_STATUS: bit[0:3] should be 0x01 ("initialisation OK")
uint8_t status = 0;
if (!this->read_byte(BMI270_REG_INTERNAL_STATUS, &status))
return false;
@@ -73,74 +66,52 @@ bool BMI270Component::load_config_file_() {
return true;
}
// setup() ─
void BMI270Component::setup() {
MotionComponent::setup();
// 1. Verify chip ID
if (!this->check_chip_id(this, BMI270_REG_CHIP_ID, BMI270_CHIP_ID_VALUE))
return;
// 2. Soft-reset via CMD register (0x7E = 0xB6)
if (!this->setup_check(this->write_byte(BMI270_REG_CMD, BMI270_CMD_SOFT_RESET)))
return;
delay(20);
// 4. Upload the configuration blob
if (!this->setup_check(load_config_file_(), LOG_STR("Config file upload failed")))
return;
ESP_LOGD(TAG, "Config blob uploaded ✓");
// 5. Configure accelerometer
// ACC_CONF: ODR | BWP(0x2 = normal avg4) | perf_mode(1)
uint8_t acc_conf =
(uint8_t) (accel_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf)))
return;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_RANGE, (uint8_t) accel_range_)))
if (!this->setup_check(this->load_config_file_(), LOG_STR("Config file upload failed")))
return;
// 6. Configure gyroscope
// GYR_CONF: ODR | BWP(0x2 = normal) | noise_perf(1) | filter_perf(1)
uint8_t gyr_conf = (uint8_t) (gyro_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
if (!this->setup_check(this->write_byte(BMI270_REG_GYR_CONF, gyr_conf)))
return;
if (!this->setup_check(this->write_byte(BMI270_REG_GYR_RANGE, (uint8_t) gyro_range_)))
return;
// 7. Enable accelerometer, gyroscope, and temperature sensor
// PWR_CTRL bits: temp_en[3] | gyr_en[2] | acc_en[1]
if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
// Normal filter bandwidth; performance mode for the accelerometer, noise and filter performance for the gyroscope
const uint8_t acc_conf =
this->accel_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
const uint8_t gyr_conf = this->gyro_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf) &&
this->write_byte(BMI270_REG_ACC_RANGE, this->accel_range_) &&
this->write_byte(BMI270_REG_GYR_CONF, gyr_conf) &&
this->write_byte(BMI270_REG_GYR_RANGE, this->gyro_range_) &&
this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
return;
delay(5);
// 8. Re-enable advanced power save (optional; keeps current low between reads)
// Disabled here for simplicity – leave in performance mode
// bit1 = fifo_self_wakeup
// Advanced power save stays off; FIFO self-wakeup on
if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_FIFO_SELF_WAKEUP)))
return;
// 9. Optionally bring up whatever is wired to the aux interface.
// This is entirely additive: it is off by default, and failure only disables
// magnetometer reporting rather than the whole component.
#ifdef USE_BMI270_BMM150
// A missing magnetometer only disables magnetometer reporting
if (this->aux_device_ == BMI270_AUX_DEVICE_BMM150) {
this->magnetometer_ready_ = this->setup_magnetometer_();
const LogString *failed_step = this->setup_magnetometer_();
this->magnetometer_ready_ = failed_step == nullptr;
if (!this->magnetometer_ready_) {
ESP_LOGW(TAG, "BMM150 magnetometer setup failed; continuing without it");
ESP_LOGW(TAG, "BMM150 magnetometer setup failed at %s; continuing without it", LOG_STR_ARG(failed_step));
}
}
#endif
ESP_LOGCONFIG(TAG, "BMI270 initialised successfully");
}
#ifdef USE_BMI270_BMM150
bool BMI270Component::wait_for_aux_idle_(uint32_t timeout_ms) {
// The STATUS aux-busy bit is set while an aux transaction is in flight. Aux transaction
// duration depends on the attached device's own timing, so poll with a bounded
// timeout instead of guessing a fixed delay.
static_assert(BMM150_TRIM_BLOCK_LEN == BMI270_AUX_DATA_LEN, "each trim block is one aux read");
bool BMI270Component::wait_for_aux_idle_() {
static constexpr uint32_t AUX_IDLE_TIMEOUT_MS = 20;
uint32_t start = millis();
while (true) {
uint8_t status = 0;
@@ -148,98 +119,63 @@ bool BMI270Component::wait_for_aux_idle_(uint32_t timeout_ms) {
return false;
if ((status & BMI270_STATUS_AUX_BUSY) == 0)
return true;
if (millis() - start >= timeout_ms)
if (millis() - start >= AUX_IDLE_TIMEOUT_MS)
return false;
delay(1);
}
}
bool BMI270Component::write_aux_register_(uint8_t reg, uint8_t value) {
if (!this->write_byte(BMI270_REG_AUX_WR_DATA, value))
return false;
if (!this->write_byte(BMI270_REG_AUX_WR_ADDR, reg))
return false;
return this->wait_for_aux_idle_(20);
return this->write_byte(BMI270_REG_AUX_WR_DATA, value) && this->write_byte(BMI270_REG_AUX_WR_ADDR, reg) &&
this->wait_for_aux_idle_();
}
bool BMI270Component::read_aux_block_(uint8_t reg, uint8_t *buf) {
if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, reg))
return false;
if (!this->wait_for_aux_idle_(20))
return false;
return this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
return this->write_byte(BMI270_REG_AUX_RD_ADDR, reg) && this->wait_for_aux_idle_() &&
this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
}
bool BMI270Component::read_magnetometer_trim_() {
uint8_t regs[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, regs + i * BMM150_TRIM_BLOCK_LEN))
return false;
}
this->mag_trim_ = bmm150_parse_trim(regs);
return true;
}
bool BMI270Component::setup_magnetometer_() {
// Sequence adapted from the Bosch BMI270 aux-interface protocol: enable the secondary
// I2C master in manual mode, point it at the BMM150's address, power the BMM150 up
// and soft-reset it, verify its chip ID, read its factory trim values, put it in
// normal/30Hz mode, then switch the aux interface to auto-burst mode so BMI270 keeps
// AUX_X/Y/Z/R refreshed from the BMM150's data registers.
ESP_LOGD(TAG, "Setting up BMM150 magnetometer via BMI270 aux interface...");
if (!this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN))
return false;
if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8))
return false;
if (!this->write_byte(BMI270_REG_AUX_DEV_ID, (uint8_t) (this->aux_device_address_ << 1)))
return false;
// Follows the Bosch BMI270 aux-interface sequence; ends in auto-burst mode, where the BMI270 keeps
// AUX_X/Y/Z/R filled from the BMM150's data registers
const LogString *BMI270Component::setup_magnetometer_() {
if (!(this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN) &&
this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8) &&
this->write_byte(BMI270_REG_AUX_DEV_ID, this->aux_device_address_ << 1)))
return LOG_STR("aux interface");
// Suspend -> sleep, then a soft reset so the BMM150 starts from a known state even if it
// stayed powered across a restart. The chip ID is only readable once the power bit is set.
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON)) {
ESP_LOGW(TAG, "BMM150 power-on write timed out");
return false;
}
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON))
return LOG_STR("power-on");
delay(BMM150_START_UP_TIME_MS);
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET)) {
ESP_LOGW(TAG, "BMM150 soft-reset write timed out");
return false;
}
if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET))
return LOG_STR("soft reset");
delay(BMM150_SOFT_RESET_TIME_MS);
uint8_t chip_id[BMI270_AUX_DATA_LEN];
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id)) {
ESP_LOGW(TAG, "BMM150 chip-ID read failed");
return false;
}
if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id))
return LOG_STR("chip ID read");
if (chip_id[0] != BMM150_CHIP_ID_VALUE) {
ESP_LOGW(TAG, "BMM150 not detected (chip ID 0x%02X, expected 0x%02X)", chip_id[0], BMM150_CHIP_ID_VALUE);
return false;
ESP_LOGW(TAG, "BMM150 chip ID 0x%02X, expected 0x%02X", chip_id[0], BMM150_CHIP_ID_VALUE);
return LOG_STR("chip ID check");
}
if (!this->read_magnetometer_trim_()) {
ESP_LOGW(TAG, "BMM150 trim data read failed");
return false;
uint8_t trim[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, trim + i * BMM150_TRIM_BLOCK_LEN))
return LOG_STR("trim read");
}
this->mag_trim_ = bmm150_parse_trim(trim);
if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ)) {
ESP_LOGW(TAG, "BMM150 mode write timed out");
return false;
}
if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ))
return LOG_STR("normal mode");
// Switch to auto-burst mode: BMI270 will keep polling 8 bytes from the BMM150's
// data registers (0x42) into its own AUX_X/Y/Z/R registers automatically.
if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
BMI270_AUX_IF_CONF_RD_BURST_8))
return false;
if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB))
return false;
if (!this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN))
return false;
ESP_LOGD(TAG, "BMM150 magnetometer ready");
return true;
if (!(this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
BMI270_AUX_IF_CONF_RD_BURST_8) &&
this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB) &&
this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN)))
return LOG_STR("auto-burst mode");
return nullptr;
}
#endif // USE_BMI270_BMM150
@@ -249,9 +185,10 @@ void BMI270Component::dump_config() {
if (this->is_failed())
return;
ESP_LOGCONFIG(TAG, " Accel range : %s",
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)));
ESP_LOGCONFIG(TAG, " Gyro range : %s",
ESP_LOGCONFIG(TAG,
" Accel range : %s\n"
" Gyro range : %s",
LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)),
LOG_STR_ARG(GyroRangeStrings::get_log_str(this->gyro_range_, GyroRangeStrings::LAST_INDEX)));
#ifdef USE_BMI270_BMM150
if (this->aux_device_ == BMI270_AUX_DEVICE_BMM150) {
@@ -262,9 +199,6 @@ void BMI270Component::dump_config() {
MotionComponent::dump_config();
}
// update() ─
// Reads all 6 axes + temperature in one block
bool BMI270Component::update_data(motion::MotionData &data) {
if (this->is_failed())
return false;
+8 -24
View File
@@ -12,18 +12,15 @@
namespace esphome::bmi270 {
// Register map
static constexpr uint8_t BMI270_REG_CHIP_ID = 0x00;
static constexpr uint8_t BMI270_REG_ERR_REG = 0x02;
static constexpr uint8_t BMI270_REG_STATUS = 0x03;
static constexpr uint8_t BMI270_REG_DATA_8 = 0x0C; // ACC_X LSB
static constexpr uint8_t BMI270_REG_DATA_14 = 0x12; // GYR_X LSB
static constexpr uint8_t BMI270_REG_TEMP_0 = 0x22;
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23; // temperature (2 bytes big-endian ish)
static constexpr uint8_t BMI270_REG_TEMP_MSB = 0x23;
static constexpr uint8_t REG_READ_LEN =
BMI270_REG_TEMP_MSB - BMI270_REG_DATA_8 +
1; // 0x23 - 0x0C + 1 = 0x18 bytes total for accel(6) + gyro(6) + temp(2) + padding(4)
// Accel, gyro, 10 unused bytes, then temperature: 0x0C to 0x23
static constexpr uint8_t REG_READ_LEN = BMI270_REG_TEMP_MSB - BMI270_REG_DATA_8 + 1;
static constexpr uint8_t BMI270_REG_PWR_CONF = 0x7C;
static constexpr uint8_t BMI270_REG_PWR_CTRL = 0x7D;
@@ -80,7 +77,6 @@ static constexpr uint8_t BMI270_AUX_IF_CONF_RD_BURST_8 = 0x03; // bits 1:0
static constexpr uint8_t BMI270_AUX_DATA_LEN = 8;
static_assert(BMI270_REG_AUX_X_LSB + BMI270_AUX_DATA_LEN == BMI270_REG_DATA_8, "aux data must precede accel data");
// Accelerometer range options
enum BMI270AccelRange : uint8_t {
BMI270_ACCEL_RANGE_2G = 0x00,
BMI270_ACCEL_RANGE_4G = 0x01,
@@ -88,7 +84,6 @@ enum BMI270AccelRange : uint8_t {
BMI270_ACCEL_RANGE_16G = 0x03,
};
// Accelerometer ODR options
enum BMI270AccelODR : uint8_t {
BMI270_ACCEL_ODR_12_5 = 0x05,
BMI270_ACCEL_ODR_25 = 0x06,
@@ -100,7 +95,6 @@ enum BMI270AccelODR : uint8_t {
BMI270_ACCEL_ODR_1600 = 0x0C,
};
// Gyroscope range options
enum BMI270GyroRange : uint8_t {
BMI270_GYRO_RANGE_2000 = 0x00,
BMI270_GYRO_RANGE_1000 = 0x01,
@@ -109,7 +103,6 @@ enum BMI270GyroRange : uint8_t {
BMI270_GYRO_RANGE_125 = 0x04,
};
// Gyroscope ODR options
enum BMI270GyroODR : uint8_t {
BMI270_GYRO_ODR_25 = 0x06,
BMI270_GYRO_ODR_50 = 0x07,
@@ -130,14 +123,11 @@ enum BMI270AuxDevice : uint8_t {
};
#endif
// Main component class
class BMI270Component final : public motion::MotionComponent, public i2c::I2CDevice {
public:
// Lifecycle
void setup() override;
void dump_config() override;
// Configuration setters
void set_accel_range(BMI270AccelRange r) { this->accel_range_ = r; }
void set_accel_odr(BMI270AccelODR o) { this->accel_odr_ = o; }
void set_gyro_range(BMI270GyroRange r) { this->gyro_range_ = r; }
@@ -153,21 +143,15 @@ class BMI270Component final : public motion::MotionComponent, public i2c::I2CDev
bool update_data(motion::MotionData &data) override;
bool load_config_file_();
#ifdef USE_BMI270_BMM150
// Brings up the BMM150 over the BMI270's aux interface. Optional: on failure this only
// disables magnetometer reporting, it does not fail the whole component (accel/gyro still work).
bool setup_magnetometer_();
// Blocking poll of the aux-transaction-busy bit; aux transaction time depends on the
// attached device, so this is bounded by retries/timeout rather than a fixed delay.
bool wait_for_aux_idle_(uint32_t timeout_ms);
// Manual-mode aux read of 8 bytes starting at `reg` on the aux device.
// Returns the step that failed, or nullptr once the BMM150 is running
const LogString *setup_magnetometer_();
// Polls the aux busy bit, as the aux transaction time depends on the attached device
bool wait_for_aux_idle_();
// Manual-mode aux read of 8 bytes starting at `reg` on the aux device
bool read_aux_block_(uint8_t reg, uint8_t *buf);
// Manual-mode aux write of one byte to `reg` on the aux device.
bool write_aux_register_(uint8_t reg, uint8_t value);
// Reads the BMM150 factory trim values used to compensate its samples.
bool read_magnetometer_trim_();
#endif
// Config
BMI270AccelRange accel_range_{BMI270_ACCEL_RANGE_4G};
BMI270AccelODR accel_odr_{BMI270_ACCEL_ODR_100};
BMI270GyroRange gyro_range_{BMI270_GYRO_RANGE_2000};
+2 -1
View File
@@ -1,5 +1,6 @@
#pragma once
#include <cstdint>
#include "esphome/core/hal.h"
namespace esphome::bmi270 {
@@ -44,7 +45,7 @@ POSSIBILITY OF SUCH DAMAGE.
after every power cycle, before any sensor data can be read.
--------------------------------------------------------------------------- */
static constexpr uint8_t BMI270_CONFIG_FILE[] = {
static constexpr uint8_t BMI270_CONFIG_FILE[] PROGMEM = {
0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x3d, 0xb1, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x91, 0x03, 0x80, 0x2e, 0xbc,
0xb0, 0x80, 0x2e, 0xa3, 0x03, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x00, 0xb0, 0x50, 0x30, 0x21, 0x2e, 0x59, 0xf5,
0x10, 0x30, 0x21, 0x2e, 0x6a, 0xf5, 0x80, 0x2e, 0x3b, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x19, 0x01, 0x00, 0x22,
+16 -16
View File
@@ -3,11 +3,8 @@
#include <cstdint>
#include "esphome/core/helpers.h"
// BMM150 magnetometer definitions - the chip that can optionally be wired to the BMI270's
// auxiliary (secondary I2C master) interface. Lives in its own header/namespace because this
// is BMM150-specific driver knowledge, not BMI270 knowledge - it just can't be a standalone
// ESPHome component, since the BMM150 has no address of its own on the main I2C bus and is only
// reachable by having the BMI270 proxy register reads/writes through its aux interface.
// BMM150 magnetometer behind the BMI270's aux interface; it is not on the main I2C bus, so it is not
// its own component
namespace esphome::bmi270::bmm150 {
static constexpr uint8_t BMM150_DEFAULT_I2C_ADDRESS = 0x10;
@@ -64,20 +61,23 @@ inline uint16_t bmm150_trim_word(const uint8_t *regs, uint8_t reg) {
return encode_value_le<uint16_t>(&regs[offset]);
}
// A trim byte, addressed by its register
inline uint8_t bmm150_trim_byte(const uint8_t *regs, uint8_t reg) { return regs[reg - BMM150_REG_TRIM_START]; }
// Decodes the trim registers; `regs` holds the bytes of registers 0x5D onwards (at least 21).
inline BMM150Trim bmm150_parse_trim(const uint8_t *regs) {
BMM150Trim trim;
trim.x1 = static_cast<int8_t>(regs[BMM150_TRIM_X1 - BMM150_REG_TRIM_START]);
trim.y1 = static_cast<int8_t>(regs[BMM150_TRIM_Y1 - BMM150_REG_TRIM_START]);
trim.x1 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_X1));
trim.y1 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_Y1));
trim.z4 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z4));
trim.x2 = static_cast<int8_t>(regs[BMM150_TRIM_X2 - BMM150_REG_TRIM_START]);
trim.y2 = static_cast<int8_t>(regs[BMM150_TRIM_Y2 - BMM150_REG_TRIM_START]);
trim.x2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_X2));
trim.y2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_Y2));
trim.z2 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z2));
trim.z1 = bmm150_trim_word(regs, BMM150_TRIM_Z1);
trim.xyz1 = bmm150_trim_word(regs, BMM150_TRIM_XYZ1) & BMM150_TRIM_XYZ1_MASK;
trim.z3 = static_cast<int16_t>(bmm150_trim_word(regs, BMM150_TRIM_Z3));
trim.xy2 = static_cast<int8_t>(regs[BMM150_TRIM_XY2 - BMM150_REG_TRIM_START]);
trim.xy1 = regs[BMM150_TRIM_XY1 - BMM150_REG_TRIM_START];
trim.xy2 = static_cast<int8_t>(bmm150_trim_byte(regs, BMM150_TRIM_XY2));
trim.xy1 = bmm150_trim_byte(regs, BMM150_TRIM_XY1);
return trim;
}
@@ -108,11 +108,11 @@ inline float bmm150_compensate_z(const BMM150Trim &trim, int16_t raw, uint16_t r
// Converts 8 raw bytes from the BMM150 data registers (X, Y, Z, RHALL; 0x42-0x49) to compensated µT.
inline BMM150Data bmm150_convert(const BMM150Trim &trim, const uint8_t *raw) {
// X/Y are 13-bit (LSB byte bits 7:3), Z is 15-bit (bits 7:1), RHALL is 14-bit (bits 7:2).
int16_t x = (int16_t) (((int16_t) (int8_t) raw[1] * 32) | (raw[0] >> 3));
int16_t y = (int16_t) (((int16_t) (int8_t) raw[3] * 32) | (raw[2] >> 3));
int16_t z = (int16_t) (((int16_t) (int8_t) raw[5] * 128) | (raw[4] >> 1));
uint16_t rhall = (uint16_t) (((uint16_t) raw[7] << 6) | (raw[6] >> 2));
// Left-aligned in their 16-bit words: X/Y are 13-bit, Z is 15-bit, RHALL is 14-bit
const int16_t x = encode_value_le<int16_t>(&raw[0]) >> 3;
const int16_t y = encode_value_le<int16_t>(&raw[2]) >> 3;
const int16_t z = encode_value_le<int16_t>(&raw[4]) >> 1;
const uint16_t rhall = encode_value_le<uint16_t>(&raw[6]) >> 2;
return BMM150Data{
.x = bmm150_compensate_xy(trim, trim.x1, trim.x2, x, rhall),
.y = bmm150_compensate_xy(trim, trim.y1, trim.y2, y, rhall),
+28 -21
View File
@@ -17,6 +17,14 @@ DEPENDENCIES = ["i2c"]
CONF_AUX_ADDRESS = "aux_address"
CONF_AUX_DEVICE = "aux_device"
# to_code skips the setters at these values, so each must match its member default in bmi270.h
DEFAULT_ACCELEROMETER_RANGE = "4G"
DEFAULT_ACCELEROMETER_ODR = "100HZ"
DEFAULT_GYROSCOPE_RANGE = "2000DPS"
DEFAULT_GYROSCOPE_ODR = "200HZ"
# The BMM150's fixed address
DEFAULT_AUX_ADDRESS = 0x10
# Enum proxies (must match the C++ enum values exactly)
BMI270AuxDevice = bmi270_ns.enum("BMI270AuxDevice")
BMI270AccelRange = bmi270_ns.enum("BMI270AccelRange")
@@ -57,50 +65,49 @@ GYRO_ODR_OPTIONS = {
"3200HZ": BMI270GyroODR.BMI270_GYRO_ODR_3200,
}
# Top-level CONFIG_SCHEMA
CONFIG_SCHEMA = (
motion_schema(BMI270Component, has_accel=True, has_gyro=True)
.extend(
{
cv.Optional(CONF_ACCELEROMETER_RANGE, default="4G"): cv.enum(
ACCEL_RANGE_OPTIONS, upper=True
),
cv.Optional(CONF_ACCELEROMETER_ODR, default="100HZ"): cv.enum(
ACCEL_ODR_OPTIONS, upper=True
),
cv.Optional(CONF_GYROSCOPE_RANGE, default="2000DPS"): cv.enum(
cv.Optional(
CONF_ACCELEROMETER_RANGE, default=DEFAULT_ACCELEROMETER_RANGE
): cv.enum(ACCEL_RANGE_OPTIONS, upper=True),
cv.Optional(
CONF_ACCELEROMETER_ODR, default=DEFAULT_ACCELEROMETER_ODR
): cv.enum(ACCEL_ODR_OPTIONS, upper=True),
cv.Optional(CONF_GYROSCOPE_RANGE, default=DEFAULT_GYROSCOPE_RANGE): cv.enum(
GYRO_RANGE_OPTIONS, upper=True
),
cv.Optional(CONF_GYROSCOPE_ODR, default="200HZ"): cv.enum(
cv.Optional(CONF_GYROSCOPE_ODR, default=DEFAULT_GYROSCOPE_ODR): cv.enum(
GYRO_ODR_OPTIONS, upper=True
),
# Optional device wired to the BMI270's aux interface (not the main I2C bus).
# Defaults to NONE so existing configs/boards are unaffected.
cv.Optional(CONF_AUX_DEVICE, default="NONE"): cv.one_of(
"NONE", "BMM150", upper=True
),
# Default matches the BMM150's fixed I2C address; irrelevant when aux_device is NONE.
cv.Optional(CONF_AUX_ADDRESS, default=0x10): cv.i2c_address,
cv.Optional(CONF_AUX_ADDRESS, default=DEFAULT_AUX_ADDRESS): cv.i2c_address,
}
)
.extend(i2c.i2c_device_schema(0x68))
)
# Code generation
async def to_code(config: ConfigType) -> None:
var = await new_motion_component(config)
await i2c.register_i2c_device(var, config)
# Accelerometer sensors
# Hardware configuration
cg.add(var.set_accel_range(config[CONF_ACCELEROMETER_RANGE]))
cg.add(var.set_accel_odr(config[CONF_ACCELEROMETER_ODR]))
cg.add(var.set_gyro_range(config[CONF_GYROSCOPE_RANGE]))
cg.add(var.set_gyro_odr(config[CONF_GYROSCOPE_ODR]))
# The C++ members already hold the schema defaults
for key, default, setter in (
(CONF_ACCELEROMETER_RANGE, DEFAULT_ACCELEROMETER_RANGE, var.set_accel_range),
(CONF_ACCELEROMETER_ODR, DEFAULT_ACCELEROMETER_ODR, var.set_accel_odr),
(CONF_GYROSCOPE_RANGE, DEFAULT_GYROSCOPE_RANGE, var.set_gyro_range),
(CONF_GYROSCOPE_ODR, DEFAULT_GYROSCOPE_ODR, var.set_gyro_odr),
):
if config[key] != default:
cg.add(setter(config[key]))
# The aux interface code only compiles when some instance has a BMM150; the
# instance still records its own device, as another one may have none
if config[CONF_AUX_DEVICE] == "BMM150":
cg.add_define("USE_BMI270_BMM150")
cg.add(var.set_aux_device(BMI270AuxDevice.BMI270_AUX_DEVICE_BMM150))
cg.add(var.set_aux_device_address(config[CONF_AUX_ADDRESS]))
if (address := config[CONF_AUX_ADDRESS]) != DEFAULT_AUX_ADDRESS:
cg.add(var.set_aux_device_address(address))
@@ -15,7 +15,7 @@ CONF_REPLAY_PROTECTION = "replay_protection"
bthome_mithermometer_ns = cg.esphome_ns.namespace("bthome_mithermometer")
BTHomeMiThermometer = bthome_mithermometer_ns.class_(
"BTHomeMiThermometer", ble_device_base.ESPBTDeviceListener, cg.Component
"BTHomeMiThermometer", ble_device_base.ESPBTDeviceListener
)
@@ -34,7 +34,6 @@ def bthome_mithermometer_base_schema(
cv.Optional(CONF_REPLAY_PROTECTION, default=False): cv.boolean,
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(extra_schema)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
_validate_replay_protection,
@@ -51,7 +50,6 @@ def _validate_replay_protection(config: ConfigType) -> ConfigType:
async def setup_bthome_mithermometer(var: MockObj, config: ConfigType) -> None:
await cg.register_component(var, config)
await ble_device_base.register_ble_device(var, config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
if bindkey := config.get(CONF_BINDKEY):
@@ -154,7 +154,7 @@ static bool get_bthome_value_length(uint8_t obj_type, size_t &value_length) {
}
}
void BTHomeMiThermometer::dump_config() {
void BTHomeMiThermometer::dump_child_config() {
char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
ESP_LOGCONFIG(TAG, "BTHome MiThermometer");
ESP_LOGCONFIG(TAG, " MAC Address: %s", format_mac_address(addr_buf, this->address_));
@@ -2,7 +2,6 @@
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/component.h"
#include <cstdint>
#include <initializer_list>
@@ -17,7 +16,7 @@ namespace testing {
class ReplayClockAccess;
} // namespace testing
class BTHomeMiThermometer final : public ble_device_base::ESPBTDeviceListener, public Component {
class BTHomeMiThermometer final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(temperature)
SUB_SENSOR(humidity)
SUB_SENSOR(battery_level)
@@ -31,7 +30,7 @@ class BTHomeMiThermometer final : public ble_device_base::ESPBTDeviceListener, p
void set_replay_protection(bool replay_protection) { this->replay_protection_ = replay_protection; }
#endif
void dump_config() override;
void dump_child_config() override;
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
protected:
+4 -10
View File
@@ -515,18 +515,12 @@ void CC1101Component::dump_config() {
}
void CC1101Component::begin_tx() {
this->wake_up();
// Read the mode before the PKTCTRL0 write below overwrites it in state_
const bool packet_mode = this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
// Ensure Packet Format is 3 (Async Serial)
this->write_(Register::PKTCTRL0, 0x32);
if (this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
ESP_LOGW(TAG, "begin_tx is for async serial mode; use send_packet in packet mode");
return;
}
ESP_LOGV(TAG, "Beginning TX sequence");
if (this->gdo0_pin_ != nullptr) {
// setup() only attaches the interrupt in packet mode. In async serial mode the pin may be
// shared with remote_receiver, and detaching here would remove the receiver's interrupt.
if (packet_mode) {
this->gdo0_pin_->detach_interrupt();
}
this->gdo0_pin_->pin_mode(gpio::FLAG_OUTPUT);
}
// Transition through IDLE to bypass CCA (Clear Channel Assessment) which can
+1
View File
@@ -36,6 +36,7 @@ CONF_CONVERSION_RATE = "conversion_rate"
CONF_CRC_ENABLE = "crc_enable"
CONF_DATA_BITS = "data_bits"
CONF_DESCRIPTION = "description"
CONF_DESTINATION = "destination"
CONF_DEVICE_TYPE = "device_type"
CONF_DISCONNECTS = "disconnects"
CONF_DRAW_ROUNDING = "draw_rounding"
@@ -68,7 +68,7 @@ void CST3240Touchscreen::update_touches() {
return;
}
const uint8_t count = data[cstxxx::FINGER_COUNT_IDX] & 0x0F;
const uint8_t count = low_nibble(data[cstxxx::FINGER_COUNT_IDX]);
if (count <= CST3240_MAX_TOUCHES) {
for (uint8_t i = 0; i < count; i++) {
auto touch = cstxxx::decode_touch(data, i);
@@ -1,4 +1,5 @@
#include "cst328_touchscreen.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::cst328 {
@@ -99,7 +100,7 @@ void CST328Touchscreen::update_touches() {
return;
}
uint8_t touch_cnt = touch_data[CST_REG_FINGER_COUNT_IDX] & 0x0F;
uint8_t touch_cnt = low_nibble(touch_data[CST_REG_FINGER_COUNT_IDX]);
if (touch_cnt == 0 || touch_cnt > CST328_TOUCH_MAX_POINTS) {
this->update_button_state_(false);
} else {
@@ -63,13 +63,25 @@ void CST816Touchscreen::update_touches() {
uint8_t data[13];
if (!this->status_comm_result(this->read_bytes(REG_STATUS, data, sizeof data)))
return;
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 3;
// The low nibble is the touch count. CST816/CST820 are single-touch;
// CST826/CST836 can report two points, but this driver only reads the first
// point. Some CST8xx controllers report an all-0xFF frame when idle or after
// disabling auto-sleep: the count lands above two and the coordinates are
// the 0xFFF sentinel, so both guards below reject it.
uint8_t num_of_touches = low_nibble(data[REG_TOUCH_NUM]);
if (num_of_touches == 0) {
return;
}
if (num_of_touches > 2) {
return;
}
uint16_t x = encode_uint16(data[REG_XPOS_HIGH] & 0xF, data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(data[REG_YPOS_HIGH] & 0xF, data[REG_YPOS_LOW]);
uint16_t x = encode_uint16(low_nibble(data[REG_XPOS_HIGH]), data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(low_nibble(data[REG_YPOS_HIGH]), data[REG_YPOS_LOW]);
if (x == 0x0FFF || y == 0x0FFF) {
return;
}
ESP_LOGV(TAG, "Read touch %d/%d", x, y);
this->add_raw_touch_position_(0, x, y);
}
+10 -3
View File
@@ -37,11 +37,18 @@ struct TouchRecord {
uint8_t z;
};
/// Decodes record `index` of a touch report.
/// Decodes record `index` of a touch report. Each record is 5 bytes:
/// [id:4 | event:4] [x 11..4] [y 11..4] [x 3..0 | y 3..0] [z].
/// The first record is followed by 2 extra bytes, so later records start 2 bytes further on.
inline TouchRecord decode_touch(const uint8_t *report, uint8_t index) {
const uint8_t *r = report + index * 5 + (index == 0 ? 0 : 2);
return {static_cast<uint8_t>(r[0] >> 4), static_cast<uint8_t>(r[0] & 0x0F),
static_cast<uint16_t>(r[1] << 4 | r[3] >> 4), static_cast<uint16_t>(r[2] << 4 | (r[3] & 0x0F)), r[4]};
return {
.id = high_nibble(r[0]),
.event = low_nibble(r[0]),
.x = encode_uint12(r[1], high_nibble(r[3])),
.y = encode_uint12(r[2], low_nibble(r[3])),
.z = r[4],
};
}
class CSTTouchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
+15 -7
View File
@@ -4,6 +4,7 @@
#include "esphome/components/remote_base/remote_base.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
namespace esphome::daikin_arc {
@@ -23,7 +24,10 @@ void DaikinArcClimate::setup() {
}
void DaikinArcClimate::transmit_query_() {
uint8_t remote_header[8] = {0x11, 0xDA, 0x27, 0x00, 0x84, 0x87, 0x20, 0x00};
// In flash: an initialized local array is copied from a RAM constant on ESP8266
static constexpr uint8_t REMOTE_HEADER_TEMPLATE[8] PROGMEM = {0x11, 0xDA, 0x27, 0x00, 0x84, 0x87, 0x20, 0x00};
uint8_t remote_header[sizeof(REMOTE_HEADER_TEMPLATE)];
progmem_memcpy(remote_header, REMOTE_HEADER_TEMPLATE, sizeof(remote_header));
// Calculate checksum
for (size_t i = 0; i < sizeof(remote_header) - 1; i++) {
@@ -50,11 +54,13 @@ void DaikinArcClimate::transmit_query_() {
void DaikinArcClimate::transmit_state() {
// 0x11, 0xDA, 0x27, 0x00, 0xC5, 0x00, 0x00, 0xD7, 0x11, 0xDA, 0x27, 0x00,
// 0x42, 0x49, 0x05, 0xA2,
uint8_t remote_header[20] = {0x11, 0xDA, 0x27, 0x00, 0x02, 0xd0, 0x02, 0x03, 0x80, 0x03, 0x82, 0x30, 0x41, 0x1f, 0x82,
0xf4,
/* とつど */
/* 0x13 */
0x00, 0x24, 0x00, 0x00};
static constexpr uint8_t REMOTE_HEADER_TEMPLATE[20] PROGMEM = {
0x11, 0xDA, 0x27, 0x00, 0x02, 0xd0, 0x02, 0x03, 0x80, 0x03, 0x82, 0x30, 0x41, 0x1f, 0x82, 0xf4,
/* とつど */
/* 0x13 */
0x00, 0x24, 0x00, 0x00};
uint8_t remote_header[sizeof(REMOTE_HEADER_TEMPLATE)];
progmem_memcpy(remote_header, REMOTE_HEADER_TEMPLATE, sizeof(remote_header));
// 05 0 [1:3]MODE 1 [OFF TMR] [ON TMR] Power
// 06-07 TEMP
@@ -68,7 +74,7 @@ void DaikinArcClimate::transmit_state() {
// 16 [0:3] 8 00 [6:7] SENSOR WIND = 11 / NORMAL = 00
// 17 24
uint8_t remote_state[19] = {
static constexpr uint8_t REMOTE_STATE_TEMPLATE[DAIKIN_STATE_FRAME_SIZE] PROGMEM = {
0x11, 0xDA, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x60, 0x00, 0x0a, 0xC4,
/* MODE TEMP HUMD FANH FANL
パワフル音声応答 */
@@ -81,6 +87,8 @@ void DaikinArcClimate::transmit_state() {
/* ON 0x83 */
/* OF 0x80 */
};
uint8_t remote_state[sizeof(REMOTE_STATE_TEMPLATE)];
progmem_memcpy(remote_state, REMOTE_STATE_TEMPLATE, sizeof(remote_state));
remote_state[5] = this->operation_mode_() | 0x08;
remote_state[6] = this->temperature_();
+2
View File
@@ -94,5 +94,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_platform(
PlatformFramework.LN882X_ARDUINO,
},
"debug_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf52.cpp": {PlatformFramework.NRF52_ZEPHYR},
"debug_nrf54l.cpp": {PlatformFramework.NRF52_ZEPHYR},
}
)
+380
View File
@@ -0,0 +1,380 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && !defined(NRF54L_SERIES)
#include <cinttypes>
#include <cstdint>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <hal/nrf_power.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")),
mac_pretty, NRF_FICR->INFO.PART, NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF,
NRF_FICR->INFO.VARIANT >> 8 & 0xFF, NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE),
NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? LOG_STR_LITERAL("") : LOG_STR_LITERAL("not ")));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
+113
View File
@@ -0,0 +1,113 @@
#include "debug_component.h"
#ifdef USE_ZEPHYR
#include <nrfx.h>
#endif
#if defined(USE_ZEPHYR) && defined(NRF54L_SERIES)
#include <cinttypes>
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
#ifdef ESPHOME_LOG_HAS_VERBOSE
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
// UARTE, SPIM, SPIS, TWIM and TWIS with the same number share one instance
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " UARTE00: %-3s| UARTE20: %-3s| UARTE21: %-3s| UARTE22: %-3s| UARTE30: %-3s", //
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE00), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE20),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE21), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE22),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE30));
ESP_LOGV(TAG, " SPIM00: %-3s| SPIM20: %-3s| SPIM21: %-3s| SPIM22: %-3s| SPIM30: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM00), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM20),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM21), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM22),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM30));
ESP_LOGV(TAG, " SPIS00: %-3s| SPIS20: %-3s| SPIS21: %-3s| SPIS22: %-3s| SPIS30: %-3s", //
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS00), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS20),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS21), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS22),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS30));
ESP_LOGV(TAG, " TWIM20: %-3s| TWIM21: %-3s| TWIM22: %-3s| TWIM30: %-3s", //
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM20), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM21),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM22), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM30));
ESP_LOGV(TAG, " TWIS20: %-3s| TWIS21: %-3s| TWIS22: %-3s| TWIS30: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS20), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS21),
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS22), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS30));
ESP_LOGV(TAG, " PWM20: %-3s| PWM21: %-3s| PWM22: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM20), NRF_PERIPH_ENABLED(PWM, NRF_PWM21), NRF_PERIPH_ENABLED(PWM, NRF_PWM22),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " PDM20: %-3s| PDM21: %-3s| QDEC20: %-3s| QDEC21: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM20), NRF_PERIPH_ENABLED(PDM, NRF_PDM21), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC20),
NRF_PERIPH_ENABLED(QDEC, NRF_QDEC21));
ESP_LOGV(TAG, " COMP: %-3s| LPCOMP: %-3s| AAR00: %-3s| CCM00: %-3s", //
NRF_PERIPH_ENABLED(COMP, NRF_COMP), NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP),
NRF_PERIPH_ENABLED(AAR, NRF_AAR00), NRF_PERIPH_ENABLED(CCM, NRF_CCM00));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#endif
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF registers are MMIO at fixed addresses
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main regulator
const char *reg_type = (NRF_REGULATORS->VREGMAIN.DCDCEN & REGULATORS_VREGMAIN_DCDCEN_VAL_Msk) ==
(REGULATORS_VREGMAIN_DCDCEN_VAL_Enabled << REGULATORS_VREGMAIN_DCDCEN_VAL_Pos)
? "DC/DC"
: "LDO";
ESP_LOGD(TAG, "Main regulator: %s", reg_type);
pos = buf_append_str(buf, size, pos, "|Main regulator: ");
pos = buf_append_str(buf, size, pos, reg_type);
// Power-fail comparator, the threshold goes from 1.7V up in 0.1V steps
const uint32_t pofcon = NRF_REGULATORS->POFCON;
if ((pofcon & REGULATORS_POFCON_POF_Msk) == (REGULATORS_POFCON_POF_Enabled << REGULATORS_POFCON_POF_Pos)) {
const uint32_t decivolts = 17 + ((pofcon & REGULATORS_POFCON_THRESHOLD_Msk) >> REGULATORS_POFCON_THRESHOLD_Pos);
ESP_LOGD(TAG, "Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10, decivolts % 10);
pos = buf_append_printf(buf, size, pos, "|Power-fail comparator: %" PRIu32 ".%" PRIu32 "V", decivolts / 10,
decivolts % 10);
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
const uint32_t variant = NRF_FICR->INFO.VARIANT;
ESP_LOGD(TAG,
"nRF debug info:\n"
" Device id: 0x%08" PRIx32 "%08" PRIx32 "\n"
" Encryption root: 0x%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "%08" PRIx32 ", Identity Root: 0x%08" PRIx32
"%08" PRIx32 "%08" PRIx32 "%08" PRIx32 "\n"
" Device address type: %s, address: %s\n"
" Part code: 0x%" PRIx32 ", version: %c%c%c%c, package: 0x%" PRIx32 "\n"
" RAM: %" PRIu32 "kB, RRAM: %" PRIu32 "kB",
NRF_FICR->INFO.DEVICEID[1], NRF_FICR->INFO.DEVICEID[0], NRF_FICR->ER[0], NRF_FICR->ER[1], NRF_FICR->ER[2],
NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2], NRF_FICR->IR[3],
(NRF_FICR->DEVICEADDRTYPE & 0x1 ? LOG_STR_LITERAL("Random") : LOG_STR_LITERAL("Public")), mac_pretty,
NRF_FICR->INFO.PART, static_cast<char>(variant >> 24 & 0xFF), static_cast<char>(variant >> 16 & 0xFF),
static_cast<char>(variant >> 8 & 0xFF), static_cast<char>(variant & 0xFF), NRF_FICR->INFO.PACKAGE,
NRF_FICR->INFO.RAM, NRF_FICR->INFO.RRAM);
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#endif
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
} // namespace esphome::debug
#endif
-364
View File
@@ -2,55 +2,14 @@
#ifdef USE_ZEPHYR
#include <cinttypes>
#include <climits>
#include "esphome/core/alloc_helpers.h"
#include "esphome/core/log.h"
#include <esphome/components/zephyr/reset_reason.h>
#include <zephyr/drivers/hwinfo.h>
#include <zephyr/kernel.h>
#include <hal/nrf_power.h>
#include <cstdint>
#include <zephyr/storage/flash_map.h>
#define BOOTLOADER_VERSION_REGISTER NRF_TIMER2->CC[0]
namespace esphome::debug {
ESPHOME_LOG_TAG(TAG, "debug");
constexpr std::uintptr_t MBR_PARAM_PAGE_ADDR = 0xFFC;
constexpr std::uintptr_t MBR_BOOTLOADER_ADDR = 0xFF8;
static inline uint32_t read_mem_u32(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint32_t *>(addr);
}
static inline uint8_t read_mem_u8(uintptr_t addr) {
// NOLINTNEXTLINE(performance-no-int-to-ptr,clang-analyzer-core.FixedAddressDereference)
return *reinterpret_cast<volatile uint8_t *>(addr);
}
// defines from https://github.com/adafruit/Adafruit_nRF52_Bootloader which prints those information
constexpr uint32_t SD_MAGIC_NUMBER = 0x51B1E5DB;
constexpr uintptr_t MBR_SIZE = 0x1000;
constexpr uintptr_t SOFTDEVICE_INFO_STRUCT_OFFSET = 0x2000;
constexpr uintptr_t SD_ID_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x10;
constexpr uintptr_t SD_VERSION_OFFSET = SOFTDEVICE_INFO_STRUCT_OFFSET + 0x14;
static inline bool is_sd_present() {
return read_mem_u32(SOFTDEVICE_INFO_STRUCT_OFFSET + MBR_SIZE + 4) == SD_MAGIC_NUMBER;
}
static inline uint32_t sd_id_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_ID_OFFSET);
}
return 0;
}
static inline uint32_t sd_version_get() {
if (read_mem_u8(MBR_SIZE + SOFTDEVICE_INFO_STRUCT_OFFSET) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) {
return read_mem_u32(MBR_SIZE + SD_VERSION_OFFSET);
}
return 0;
}
const char *DebugComponent::get_reset_reason_(std::span<char, RESET_REASON_BUFFER_SIZE> buffer) {
const char *buf = zephyr::get_reset_reason(buffer);
@@ -96,329 +55,6 @@ void DebugComponent::log_partition_info_() {
flash_area_foreach(fa_cb, nullptr);
}
#ifdef ESPHOME_LOG_HAS_VERBOSE
// Check if an nRF peripheral's ENABLE register indicates it is enabled.
// periph: peripheral register prefix (e.g. USBD, UARTE, SPI)
// reg: register block pointer (e.g. NRF_USBD, NRF_UARTE0)
#define NRF_PERIPH_ENABLED(periph, reg) \
YESNO(((reg)->ENABLE & periph##_ENABLE_ENABLE_Msk) == (periph##_ENABLE_ENABLE_Enabled << periph##_ENABLE_ENABLE_Pos))
// NOLINTBEGIN(clang-analyzer-core.FixedAddressDereference) -- nRF peripheral registers are MMIO at fixed addresses
static void log_peripherals_info() {
// most peripherals are enabled only when in use so ESP_LOGV is enough
ESP_LOGV(TAG, "Peripherals status:");
ESP_LOGV(TAG, " USBD: %-3s| UARTE0: %-3s| UARTE1: %-3s| UART0: %-3s", //
NRF_PERIPH_ENABLED(USBD, NRF_USBD), NRF_PERIPH_ENABLED(UARTE, NRF_UARTE0),
NRF_PERIPH_ENABLED(UARTE, NRF_UARTE1), NRF_PERIPH_ENABLED(UART, NRF_UART0));
ESP_LOGV(TAG, " TWIS0: %-3s| TWIS1: %-3s| TWIM0: %-3s| TWIM1: %-3s", //
NRF_PERIPH_ENABLED(TWIS, NRF_TWIS0), NRF_PERIPH_ENABLED(TWIS, NRF_TWIS1),
NRF_PERIPH_ENABLED(TWIM, NRF_TWIM0), NRF_PERIPH_ENABLED(TWIM, NRF_TWIM1));
ESP_LOGV(TAG, " TWI0: %-3s| TWI1: %-3s| COMP: %-3s| CCM: %-3s", //
NRF_PERIPH_ENABLED(TWI, NRF_TWI0), NRF_PERIPH_ENABLED(TWI, NRF_TWI1), NRF_PERIPH_ENABLED(COMP, NRF_COMP),
NRF_PERIPH_ENABLED(CCM, NRF_CCM));
ESP_LOGV(TAG, " PDM: %-3s| SPIS0: %-3s| SPIS1: %-3s| SPIS2: %-3s", //
NRF_PERIPH_ENABLED(PDM, NRF_PDM), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS0), NRF_PERIPH_ENABLED(SPIS, NRF_SPIS1),
NRF_PERIPH_ENABLED(SPIS, NRF_SPIS2));
ESP_LOGV(TAG, " SPIM0: %-3s| SPIM1: %-3s| SPIM2: %-3s| SPIM3: %-3s", //
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM0), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM1),
NRF_PERIPH_ENABLED(SPIM, NRF_SPIM2), NRF_PERIPH_ENABLED(SPIM, NRF_SPIM3));
ESP_LOGV(TAG, " SPI0: %-3s| SPI1: %-3s| SPI2: %-3s| SAADC: %-3s", //
NRF_PERIPH_ENABLED(SPI, NRF_SPI0), NRF_PERIPH_ENABLED(SPI, NRF_SPI1), NRF_PERIPH_ENABLED(SPI, NRF_SPI2),
NRF_PERIPH_ENABLED(SAADC, NRF_SAADC));
ESP_LOGV(TAG, " QSPI: %-3s| QDEC: %-3s| LPCOMP: %-3s| I2S: %-3s", //
NRF_PERIPH_ENABLED(QSPI, NRF_QSPI), NRF_PERIPH_ENABLED(QDEC, NRF_QDEC),
NRF_PERIPH_ENABLED(LPCOMP, NRF_LPCOMP), NRF_PERIPH_ENABLED(I2S, NRF_I2S));
ESP_LOGV(TAG, " PWM0: %-3s| PWM1: %-3s| PWM2: %-3s| PWM3: %-3s", //
NRF_PERIPH_ENABLED(PWM, NRF_PWM0), NRF_PERIPH_ENABLED(PWM, NRF_PWM1), NRF_PERIPH_ENABLED(PWM, NRF_PWM2),
NRF_PERIPH_ENABLED(PWM, NRF_PWM3));
ESP_LOGV(TAG, " AAR: %-3s| QSPI deep power-down:%-3s| CRYPTOCELL: %-3s", NRF_PERIPH_ENABLED(AAR, NRF_AAR),
YESNO((NRF_QSPI->IFCONFIG0 & QSPI_IFCONFIG0_DPMENABLE_Msk) ==
(QSPI_IFCONFIG0_DPMENABLE_Enable << QSPI_IFCONFIG0_DPMENABLE_Pos)),
YESNO((NRF_CRYPTOCELL->ENABLE & CRYPTOCELL_ENABLE_ENABLE_Msk) ==
(CRYPTOCELL_ENABLE_ENABLE_Enabled << CRYPTOCELL_ENABLE_ENABLE_Pos)));
}
// NOLINTEND(clang-analyzer-core.FixedAddressDereference)
#undef NRF_PERIPH_ENABLED
#endif
static const char *regout0_to_str(uint32_t value) {
switch (value) {
case (UICR_REGOUT0_VOUT_DEFAULT):
return "1.8V (default)";
case (UICR_REGOUT0_VOUT_1V8):
return "1.8V";
case (UICR_REGOUT0_VOUT_2V1):
return "2.1V";
case (UICR_REGOUT0_VOUT_2V4):
return "2.4V";
case (UICR_REGOUT0_VOUT_2V7):
return "2.7V";
case (UICR_REGOUT0_VOUT_3V0):
return "3.0V";
case (UICR_REGOUT0_VOUT_3V3):
return "3.3V";
default:
break;
}
return "???V";
}
size_t DebugComponent::get_device_info_(std::span<char, DEVICE_INFO_BUFFER_SIZE> buffer, size_t pos) {
constexpr size_t size = DEVICE_INFO_BUFFER_SIZE;
char *buf = buffer.data();
// Main supply status
// NOLINTNEXTLINE(clang-analyzer-core.FixedAddressDereference) -- NRF_POWER is MMIO at a fixed address
auto regstatus = nrf_power_mainregstatus_get(NRF_POWER);
const char *supply_status = (regstatus == NRF_POWER_MAINREGSTATUS_NORMAL) ? "Normal voltage." : "High voltage.";
ESP_LOGD(TAG, "Main supply status: %s", supply_status);
pos = buf_append_str(buf, size, pos, "|Main supply status: ");
pos = buf_append_str(buf, size, pos, supply_status);
// Regulator stage 0
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *reg0_type = nrf_power_dcdcen_vddh_get(NRF_POWER) ? "DC/DC" : "LDO";
const char *reg0_voltage = regout0_to_str((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos);
ESP_LOGD(TAG, "Regulator stage 0: %s, %s", reg0_type, reg0_voltage);
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: ");
pos = buf_append_str(buf, size, pos, reg0_type);
pos = buf_append_str(buf, size, pos, ", ");
pos = buf_append_str(buf, size, pos, reg0_voltage);
#ifdef USE_NRF52_REG0_VOUT
if ((NRF_UICR->REGOUT0 & UICR_REGOUT0_VOUT_Msk) >> UICR_REGOUT0_VOUT_Pos != USE_NRF52_REG0_VOUT) {
ESP_LOGE(TAG, "Regulator stage 0: expected %s", regout0_to_str(USE_NRF52_REG0_VOUT));
}
#endif
} else {
ESP_LOGD(TAG, "Regulator stage 0: disabled");
pos = buf_append_str(buf, size, pos, "|Regulator stage 0: disabled");
}
// Regulator stage 1
const char *reg1_type = nrf_power_dcdcen_get(NRF_POWER) ? "DC/DC" : "LDO";
ESP_LOGD(TAG, "Regulator stage 1: %s", reg1_type);
pos = buf_append_str(buf, size, pos, "|Regulator stage 1: ");
pos = buf_append_str(buf, size, pos, reg1_type);
// USB power state
const char *usb_state;
if (nrf_power_usbregstatus_vbusdet_get(NRF_POWER)) {
usb_state = nrf_power_usbregstatus_outrdy_get(NRF_POWER) ? "ready" : "connected (regulator is not ready)";
} else {
usb_state = "disconnected";
}
ESP_LOGD(TAG, "USB power state: %s", usb_state);
pos = buf_append_str(buf, size, pos, "|USB power state: ");
pos = buf_append_str(buf, size, pos, usb_state);
// Power-fail comparator
bool enabled;
nrf_power_pof_thr_t pof_thr = nrf_power_pofcon_get(NRF_POWER, &enabled);
if (enabled) {
const char *pof_voltage;
switch (pof_thr) {
case POWER_POFCON_THRESHOLD_V17:
pof_voltage = "1.7V";
break;
case POWER_POFCON_THRESHOLD_V18:
pof_voltage = "1.8V";
break;
case POWER_POFCON_THRESHOLD_V19:
pof_voltage = "1.9V";
break;
case POWER_POFCON_THRESHOLD_V20:
pof_voltage = "2.0V";
break;
case POWER_POFCON_THRESHOLD_V21:
pof_voltage = "2.1V";
break;
case POWER_POFCON_THRESHOLD_V22:
pof_voltage = "2.2V";
break;
case POWER_POFCON_THRESHOLD_V23:
pof_voltage = "2.3V";
break;
case POWER_POFCON_THRESHOLD_V24:
pof_voltage = "2.4V";
break;
case POWER_POFCON_THRESHOLD_V25:
pof_voltage = "2.5V";
break;
case POWER_POFCON_THRESHOLD_V26:
pof_voltage = "2.6V";
break;
case POWER_POFCON_THRESHOLD_V27:
pof_voltage = "2.7V";
break;
case POWER_POFCON_THRESHOLD_V28:
pof_voltage = "2.8V";
break;
default:
pof_voltage = "???V";
break;
}
if (nrf_power_mainregstatus_get(NRF_POWER) == NRF_POWER_MAINREGSTATUS_HIGH) {
const char *vddh_voltage;
switch (nrf_power_pofcon_vddh_get(NRF_POWER)) {
case NRF_POWER_POFTHRVDDH_V27:
vddh_voltage = "2.7V";
break;
case NRF_POWER_POFTHRVDDH_V28:
vddh_voltage = "2.8V";
break;
case NRF_POWER_POFTHRVDDH_V29:
vddh_voltage = "2.9V";
break;
case NRF_POWER_POFTHRVDDH_V30:
vddh_voltage = "3.0V";
break;
case NRF_POWER_POFTHRVDDH_V31:
vddh_voltage = "3.1V";
break;
case NRF_POWER_POFTHRVDDH_V32:
vddh_voltage = "3.2V";
break;
case NRF_POWER_POFTHRVDDH_V33:
vddh_voltage = "3.3V";
break;
case NRF_POWER_POFTHRVDDH_V34:
vddh_voltage = "3.4V";
break;
case NRF_POWER_POFTHRVDDH_V35:
vddh_voltage = "3.5V";
break;
case NRF_POWER_POFTHRVDDH_V36:
vddh_voltage = "3.6V";
break;
case NRF_POWER_POFTHRVDDH_V37:
vddh_voltage = "3.7V";
break;
case NRF_POWER_POFTHRVDDH_V38:
vddh_voltage = "3.8V";
break;
case NRF_POWER_POFTHRVDDH_V39:
vddh_voltage = "3.9V";
break;
case NRF_POWER_POFTHRVDDH_V40:
vddh_voltage = "4.0V";
break;
case NRF_POWER_POFTHRVDDH_V41:
vddh_voltage = "4.1V";
break;
case NRF_POWER_POFTHRVDDH_V42:
vddh_voltage = "4.2V";
break;
default:
vddh_voltage = "???V";
break;
}
ESP_LOGD(TAG, "Power-fail comparator: %s, VDDH: %s", pof_voltage, vddh_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
pos = buf_append_str(buf, size, pos, ", VDDH: ");
pos = buf_append_str(buf, size, pos, vddh_voltage);
} else {
ESP_LOGD(TAG, "Power-fail comparator: %s", pof_voltage);
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: ");
pos = buf_append_str(buf, size, pos, pof_voltage);
}
} else {
ESP_LOGD(TAG, "Power-fail comparator: disabled");
pos = buf_append_str(buf, size, pos, "|Power-fail comparator: disabled");
}
auto package = [](uint32_t value) {
switch (value) {
case 0x2004:
return "QIxx - 7x7 73-pin aQFN";
case 0x2000:
return "QFxx - 6x6 48-pin QFN";
case 0x2005:
return "CKxx - 3.544 x 3.607 WLCSP";
default:
break;
}
return "Unspecified";
};
char mac_pretty[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
get_mac_address_pretty_into_buffer(mac_pretty);
ESP_LOGD(TAG,
"nRF debug info:\n"
" Code page size: %u, code size: %u, device id: 0x%08x%08x\n"
" Encryption root: 0x%08x%08x%08x%08x, Identity Root: 0x%08x%08x%08x%08x\n"
" Device address type: %s, address: %s\n"
" Part code: nRF%x, version: %c%c%c%c, package: %s\n"
" RAM: %ukB, Flash: %ukB, production test: %sdone",
NRF_FICR->CODEPAGESIZE, NRF_FICR->CODESIZE, NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0], NRF_FICR->ER[0],
NRF_FICR->ER[1], NRF_FICR->ER[2], NRF_FICR->ER[3], NRF_FICR->IR[0], NRF_FICR->IR[1], NRF_FICR->IR[2],
NRF_FICR->IR[3], (NRF_FICR->DEVICEADDRTYPE & 0x1 ? "Random" : "Public"), mac_pretty, NRF_FICR->INFO.PART,
NRF_FICR->INFO.VARIANT >> 24 & 0xFF, NRF_FICR->INFO.VARIANT >> 16 & 0xFF, NRF_FICR->INFO.VARIANT >> 8 & 0xFF,
NRF_FICR->INFO.VARIANT & 0xFF, package(NRF_FICR->INFO.PACKAGE), NRF_FICR->INFO.RAM, NRF_FICR->INFO.FLASH,
(NRF_FICR->PRODTEST[0] == 0xBB42319F ? "" : "not "));
bool n_reset_enabled = NRF_UICR->PSELRESET[0] == NRF_UICR->PSELRESET[1] &&
(NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) == UICR_PSELRESET_CONNECT_Connected
<< UICR_PSELRESET_CONNECT_Pos;
ESP_LOGD(
TAG, " GPIO as NFC pins: %s, GPIO as nRESET pin: %s",
YESNO((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)),
YESNO(n_reset_enabled));
if (n_reset_enabled) {
uint8_t port = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PORT_Msk) >> UICR_PSELRESET_PORT_Pos;
uint8_t pin = (NRF_UICR->PSELRESET[0] & UICR_PSELRESET_PIN_Msk) >> UICR_PSELRESET_PIN_Pos;
ESP_LOGD(TAG, " nRESET port P%u.%02u", port, pin);
}
#ifdef USE_BOOTLOADER_MCUBOOT
ESP_LOGD(TAG, " Bootloader: mcuboot");
#else
ESP_LOGD(TAG, " Bootloader: Adafruit, version %u.%u.%u", (BOOTLOADER_VERSION_REGISTER >> 16) & 0xFF,
(BOOTLOADER_VERSION_REGISTER >> 8) & 0xFF, BOOTLOADER_VERSION_REGISTER & 0xFF);
ESP_LOGD(TAG, " MBR bootloader addr 0x%08x, UICR bootloader addr 0x%08x", read_mem_u32(MBR_BOOTLOADER_ADDR),
NRF_UICR->NRFFW[0]);
ESP_LOGD(TAG, " MBR param page addr 0x%08x, UICR param page addr 0x%08x", read_mem_u32(MBR_PARAM_PAGE_ADDR),
NRF_UICR->NRFFW[1]);
if (is_sd_present()) {
uint32_t const sd_id = sd_id_get();
uint32_t const sd_version = sd_version_get();
uint32_t ver[3];
ver[0] = sd_version / 1000000;
ver[1] = (sd_version - ver[0] * 1000000) / 1000;
ver[2] = (sd_version - ver[0] * 1000000 - ver[1] * 1000);
ESP_LOGD(TAG, " SoftDevice: S%u %u.%u.%u", sd_id, ver[0], ver[1], ver[2]);
#ifdef USE_SOFTDEVICE_ID
#ifdef USE_SOFTDEVICE_VERSION
if (USE_SOFTDEVICE_ID != sd_id || USE_SOFTDEVICE_VERSION != ver[0]) {
ESP_LOGE(TAG, "Built for SoftDevice S%u %u.x.y. It may crash due to mismatch of bootloader version.",
USE_SOFTDEVICE_ID, USE_SOFTDEVICE_VERSION);
}
#else
if (USE_SOFTDEVICE_ID != sd_id) {
ESP_LOGE(TAG, "Built for SoftDevice S%u. It may crash due to mismatch of bootloader version.", USE_SOFTDEVICE_ID);
}
#endif
#endif
}
#endif
// 13 words of 8 hex digits, separated by spaces
char uicr_buf[13 * 9];
auto uicr = [&uicr_buf](volatile uint32_t *data, uint8_t size) {
size_t len = 0;
for (size_t i = 0; i < size; i++) {
len = buf_append_printf(uicr_buf, sizeof(uicr_buf), len, i > 0 ? " %08" PRIX32 : "%08" PRIX32, data[i]);
}
return uicr_buf;
};
ESP_LOGD(TAG, " NRFFW %s", uicr(NRF_UICR->NRFFW, 13));
ESP_LOGD(TAG, " NRFHW %s", uicr(NRF_UICR->NRFHW, 12));
#ifdef ESPHOME_LOG_HAS_VERBOSE
log_peripherals_info();
#endif
return pos;
}
// The Python side enables the statistics only for a verbose logger
#ifdef CONFIG_SCHED_THREAD_USAGE_ANALYSIS
static void log_thread_usage(const struct k_thread *thread, void *user_data) {
+3 -1
View File
@@ -605,7 +605,9 @@ async def to_code(config: ConfigType) -> None:
cg.add(var.set_type(conf[CONF_TYPE]))
for conf in config[CONF_SELECTS]:
var = await select.new_select(conf, options=conf[CONF_OPTIONS])
var = await select.new_select(
conf, options=conf[CONF_OPTIONS], fixed_options=True
)
await cg.register_component(var, conf)
for conf in config[CONF_SENSORS]:
+1 -1
View File
@@ -41,5 +41,5 @@ CONFIG_SCHEMA = (
async def to_code(config: ConfigType) -> None:
var = await select.new_select(config, options=DUCO_MODE_OPTIONS)
var = await select.new_select(config, options=DUCO_MODE_OPTIONS, fixed_options=True)
await register_duco_device(var, config, config[CONF_DUCO_ID])
@@ -35,12 +35,12 @@ void EKTF2232Touchscreen::setup() {
if (err == i2c::ERROR_OK) {
err = this->read(received, 4);
if (err == i2c::ERROR_OK) {
this->x_raw_max_ = ((received[2])) | ((received[3] & 0xf0) << 4);
this->x_raw_max_ = encode_uint16(high_nibble(received[3]), received[2]);
err = this->write(GET_Y_RES, 4);
if (err == i2c::ERROR_OK) {
err = this->read(received, 4);
if (err == i2c::ERROR_OK) {
this->y_raw_max_ = ((received[2])) | ((received[3] & 0xf0) << 4);
this->y_raw_max_ = encode_uint16(high_nibble(received[3]), received[2]);
}
}
}
@@ -74,8 +74,9 @@ void EKTF2232Touchscreen::update_touches() {
for (int i = 0; i < touch_count; i++) {
uint8_t *d = raw + 1 + (i * 3);
x_raw = (d[0] & 0xF0) << 4 | d[1];
y_raw = (d[0] & 0x0F) << 8 | d[2];
// d[0] holds the top 4 bits of X (high nibble) and of Y (low nibble)
x_raw = encode_uint16(high_nibble(d[0]), d[1]);
y_raw = encode_uint16(low_nibble(d[0]), d[2]);
this->add_raw_touch_position_(i, x_raw, y_raw);
}
}
@@ -485,6 +485,14 @@ void ESP32BLETracker::dump_config() {
if (this->scan_start_fail_count_) {
ESP_LOGCONFIG(TAG, " Scan Start Fail Count: %d", this->scan_start_fail_count_);
}
#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
for (auto *listener : this->listeners_)
listener->dump_child_config();
#endif
#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
for (auto *listener : this->neutral_listeners_)
listener->dump_child_config();
#endif
}
#ifdef USE_ESP32_BLE_DEVICE
@@ -69,8 +69,8 @@ void FT5x06Touchscreen::update_touches() {
for (uint8_t i = 0; i != touch_cnt; i++) {
uint8_t status = data[i][0] >> 6;
uint8_t id = data[i][2] >> 3;
uint16_t x = encode_uint16(data[i][0] & 0x0F, data[i][1]);
uint16_t y = encode_uint16(data[i][2] & 0xF, data[i][3]);
uint16_t x = encode_uint16(low_nibble(data[i][0]), data[i][1]);
uint16_t y = encode_uint16(low_nibble(data[i][2]), data[i][3]);
ESP_LOGV(TAG, "Read %X status, id: %d, pos %d/%d", status, id, x, y);
if (status == 0 || status == 2) {
+5 -5
View File
@@ -90,31 +90,31 @@ void FT63X6Touchscreen::update_touches() {
}
}
uint8_t FT63X6Touchscreen::read_touch_number_() { return this->read_byte_(FT63X6_ADDR_TD_STATUS) & 0x0F; }
uint8_t FT63X6Touchscreen::read_touch_number_() { return low_nibble(this->read_byte_(FT63X6_ADDR_TD_STATUS)); }
// Touch 1 functions
uint16_t FT63X6Touchscreen::read_touch_x_(uint8_t touch) {
uint8_t read_buf[2];
read_buf[0] = this->read_byte_(FT63X6_ADDR_TOUCH1_X + (touch * 6));
read_buf[1] = this->read_byte_(FT63X6_ADDR_TOUCH1_X + 1 + (touch * 6));
return encode_uint16(read_buf[0] & 0x0f, read_buf[1]);
return encode_uint16(low_nibble(read_buf[0]), read_buf[1]);
}
uint16_t FT63X6Touchscreen::read_touch_y_(uint8_t touch) {
uint8_t read_buf[2];
read_buf[0] = this->read_byte_(FT63X6_ADDR_TOUCH1_Y + (touch * 6));
read_buf[1] = this->read_byte_(FT63X6_ADDR_TOUCH1_Y + 1 + (touch * 6));
return encode_uint16(read_buf[0] & 0x0f, read_buf[1]);
return encode_uint16(low_nibble(read_buf[0]), read_buf[1]);
}
uint8_t FT63X6Touchscreen::read_touch_event_(uint8_t touch) {
return this->read_byte_(FT63X6_ADDR_TOUCH1_X + (touch * 6)) >> 6;
}
uint8_t FT63X6Touchscreen::read_touch_id_(uint8_t touch) {
return this->read_byte_(FT63X6_ADDR_TOUCH1_ID + (touch * 6)) >> 4;
return high_nibble(this->read_byte_(FT63X6_ADDR_TOUCH1_ID + (touch * 6)));
}
uint8_t FT63X6Touchscreen::read_touch_weight_(uint8_t touch) {
return this->read_byte_(FT63X6_ADDR_TOUCH1_WEIGHT + (touch * 6));
}
uint8_t FT63X6Touchscreen::read_touch_misc_(uint8_t touch) {
return this->read_byte_(FT63X6_ADDR_TOUCH1_MISC + (touch * 6)) >> 4;
return high_nibble(this->read_byte_(FT63X6_ADDR_TOUCH1_MISC + (touch * 6)));
}
uint8_t FT63X6Touchscreen::read_byte_(uint8_t addr) {
@@ -1,6 +1,7 @@
#include "gsl3670_touchscreen.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
namespace esphome::gsl3670 {
@@ -66,10 +67,11 @@ void GSL3670Touchscreen::update_touches() {
// Build gsl_touch_info exactly as the Seeed driver does
for (uint8_t j = 0; j != finger_num; j++) {
// buf[(j+1)*4 + 0..3]: byte0=y_lo, byte1=y_hi, byte2=x_lo, byte3=id|x_hi
auto x = (uint16_t) (((buf[(j + 1) * 4 + 3] & 0x0f) << 8) | buf[(j + 1) * 4 + 2]);
auto y = (uint16_t) ((buf[(j + 1) * 4 + 1] << 8) | buf[(j + 1) * 4 + 0]);
auto id = (buf[(j + 1) * 4 + 3] >> 4) & 0x0f;
// Record: y_lo, y_hi, x_lo, then the id (high nibble) and the top 4 bits of X (low nibble)
const uint8_t *record = &buf[(j + 1) * 4];
auto x = encode_uint16(low_nibble(record[3]), record[2]);
auto y = encode_uint16(record[1], record[0]);
auto id = high_nibble(record[3]);
ESP_LOGV(TAG, "Touch id=%u, x=%u y=%u", id, x, y);
if (x <= 8192 && y <= 8192)
this->add_raw_touch_position_(id, x, y);
+1 -1
View File
@@ -1,5 +1,6 @@
from esphome import automation, pins
import esphome.codegen as cg
from esphome.components.const import CONF_DESTINATION
from esphome.components.esp32 import include_builtin_idf_component
import esphome.config_validation as cv
from esphome.const import (
@@ -26,7 +27,6 @@ MAX_LOGICAL_ADDRESS = 15
MAX_PAYLOAD_LENGTH = 15
CONF_PROMISCUOUS_MODE = "promiscuous_mode"
CONF_MONITOR_MODE = "monitor_mode"
CONF_DESTINATION = "destination"
CONF_OPCODE = "opcode"
hdmi_cec_ns = cg.esphome_ns.namespace("hdmi_cec")
+31 -9
View File
@@ -1,6 +1,7 @@
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from esphome.automation import parent_ref
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_ATTRIBUTE, CONF_ENTITY_ID, CONF_ID, CONF_INTERNAL
@@ -14,6 +15,14 @@ CODEOWNERS = ["@OttoWinter", "@esphome/core"]
DOMAIN = "homeassistant"
homeassistant_ns = cg.esphome_ns.namespace("homeassistant")
# The API server subscribes the imported entities in its setup() and prints their dumps
IMPORT_SUBSCRIBE = cg.HubFunction(
"homeassistant_subscribe", cg.void, [], define="USE_API_HOMEASSISTANT_IMPORTS"
)
IMPORT_DUMP = cg.HubFunction(
"homeassistant_dump", cg.void, [], define="USE_API_HOMEASSISTANT_IMPORTS"
)
def validate_entity_domain(
platform: str, supported_domains: Iterable[str]
@@ -31,14 +40,6 @@ def validate_entity_domain(
return validator
HOME_ASSISTANT_IMPORT_SCHEMA = cv.Schema(
{
cv.Optional(CONF_ENTITY_ID): cv.entity_id,
cv.Optional(CONF_ATTRIBUTE): cv.string,
cv.Optional(CONF_INTERNAL, default=True): cv.boolean,
}
)
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA = cv.Schema(
{
cv.Optional(CONF_ENTITY_ID): cv.entity_id,
@@ -46,6 +47,12 @@ HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA = cv.Schema(
}
)
HOME_ASSISTANT_IMPORT_SCHEMA = HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA.extend(
{
cv.Optional(CONF_ATTRIBUTE): cv.string,
}
)
def final_validate_entity_id(config: ConfigType) -> ConfigType:
"""Without an entity_id, the entity must be a wizard input, as Home Assistant then supplies it."""
@@ -82,8 +89,14 @@ async def _emit_state_subscription_count_define() -> None:
def setup_home_assistant_entity(
var: MockObj, config: ConfigType, state_subscription_count: int = 1
var: MockObj,
config: ConfigType,
state_subscription_count: int = 1,
services: bool = False,
) -> None:
"""Set up an imported entity; services for one that sends actions."""
if services:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
# A wizard input has no entity_id; the api wizard sets it
cg.add_optional(var.set_entity_id, config.get(CONF_ENTITY_ID))
cg.add_optional(var.set_attribute, config.get(CONF_ATTRIBUTE))
@@ -93,3 +106,12 @@ def setup_home_assistant_entity(
if data.state_subscription_count == 0:
CORE.add_job(_emit_state_subscription_count_define)
data.state_subscription_count += state_subscription_count
async def register_home_assistant_import(var: MockObj) -> None:
"""Attach an imported entity to the API server, which subscribes it and prints its dump."""
from esphome.components.api import DOMAIN as API_DOMAIN
api = await cg.get_variable(CORE.config[API_DOMAIN][CONF_ID])
IMPORT_SUBSCRIBE.add(api, parent_ref(var).subscribe())
IMPORT_DUMP.add(api, parent_ref(var).dump_config())
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import binary_sensor
from esphome.types import ConfigType
@@ -6,6 +5,7 @@ from .. import (
HOME_ASSISTANT_IMPORT_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
)
@@ -14,7 +14,7 @@ DEPENDENCIES = ["api"]
AUTO_LOAD = ["homeassistant"]
HomeassistantBinarySensor = homeassistant_ns.class_(
"HomeassistantBinarySensor", binary_sensor.BinarySensor, cg.Component
"HomeassistantBinarySensor", binary_sensor.BinarySensor
)
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(HomeassistantBinarySensor).extend(
@@ -26,5 +26,5 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
await cg.register_component(var, config)
setup_home_assistant_entity(var, config)
await register_home_assistant_import(var)
@@ -8,35 +8,25 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.binary_sensor");
void HomeassistantBinarySensor::setup() {
void HomeassistantBinarySensor::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, this->attribute_, [this](StringRef state) {
auto val = parse_on_off(state.c_str());
switch (val) {
case PARSE_NONE:
case PARSE_TOGGLE:
// Home Assistant sends these when there is no value, which is not an error
if (is_unset(state)) {
ESP_LOGV(TAG, "'%s': No value (%s)", this->entity_id_, state.c_str());
} else {
ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
}
break;
case PARSE_ON:
case PARSE_OFF:
bool new_state = val == PARSE_ON;
if (this->attribute_ != nullptr) {
ESP_LOGD(TAG, "'%s::%s': Got attribute state %s", this->entity_id_, this->attribute_, ONOFF(new_state));
} else {
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
}
if (this->initial_) {
this->publish_initial_state(new_state);
} else {
this->publish_state(new_state);
}
break;
if (val != PARSE_ON && val != PARSE_OFF) {
// Home Assistant sends these when there is no value, which is not an error
if (is_unset(state)) {
ESP_LOGV(TAG, "'%s': No value (%s)", this->entity_id_, state.c_str());
} else {
ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
}
return;
}
this->initial_ = false;
bool new_state = val == PARSE_ON;
if (this->attribute_ != nullptr) {
ESP_LOGD(TAG, "'%s::%s': Got attribute state %s", this->entity_id_, this->attribute_, ONOFF(new_state));
} else {
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
}
this->publish_state(new_state);
});
}
void HomeassistantBinarySensor::dump_config() {
@@ -46,6 +36,5 @@ void HomeassistantBinarySensor::dump_config() {
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
}
}
float HomeassistantBinarySensor::get_setup_priority() const { return setup_priority::AFTER_WIFI; }
} // namespace esphome::homeassistant
@@ -1,22 +1,19 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
namespace esphome::homeassistant {
class HomeassistantBinarySensor final : public binary_sensor::BinarySensor, public Component {
class HomeassistantBinarySensor final : public binary_sensor::BinarySensor {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
const char *entity_id_{nullptr};
const char *attribute_{nullptr};
bool initial_{true};
};
} // namespace esphome::homeassistant
@@ -1,11 +1,32 @@
#include "homeassistant.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#ifdef USE_API_HOMEASSISTANT_SERVICES
#include "esphome/components/api/api_server.h"
#endif
namespace esphome::homeassistant {
PROGMEM_STRING_TABLE(UnsetValues, "None", "unavailable", "unknown");
bool is_unset(StringRef value) { return progmem_string_table_find<UnsetValues>(value.c_str(), value.size()) >= 0; }
#ifdef USE_API_HOMEASSISTANT_SERVICES
bool can_send_action(const char *tag, const char *entity_id, [[maybe_unused]] EntityBase *entity) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(tag, "'%s': No clients connected to API server", entity_id);
return false;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (entity_id[0] == '\0') {
ESP_LOGW(tag, "'%s': No entity ID set yet", LOG_STR_ARG(entity->get_log_name()));
return false;
}
#endif
return true;
}
#endif
} // namespace esphome::homeassistant
@@ -2,15 +2,40 @@
#include <cctype>
#include "esphome/core/defines.h"
#include "esphome/core/entity_base.h"
#include "esphome/core/helpers.h"
#include "esphome/core/progmem.h"
#include "esphome/core/string_ref.h"
#ifdef USE_API_HOMEASSISTANT_SERVICES
#include "esphome/components/api/api_pb2.h"
#endif
namespace esphome::homeassistant {
/// True for what Home Assistant reports when there is no value: "None" for an attribute that is not
/// set, "unavailable" and "unknown" for the state of an entity that is not ready
bool is_unset(StringRef value);
/// True if entity_id is an input helper; input_service must start with "input_"
inline bool is_input_helper(const char *entity_id, const char *input_service) {
return ESPHOME_strncmp_P(entity_id, input_service, sizeof("input_") - 1) == 0;
}
#ifdef USE_API_HOMEASSISTANT_SERVICES
/// Logs and returns false when no API client is connected or no entity is linked yet
bool can_send_action(const char *tag, const char *entity_id, EntityBase *entity);
/// Adds the entity_id entry to an action's data
inline void add_entity_id(api::HomeassistantActionRequest &resp, const char *entity_id) {
static constexpr char ENTITY_ID_KEY[] PROGMEM = "entity_id";
auto &entry = resp.data.emplace_back();
entry.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entry.value = ProgmemStringRef(StringRef(entity_id));
}
#endif
/// Emit the UTF-8 encoding of a code point. Rejects NUL, which would end the item early.
template<typename C> bool emit_utf8(uint32_t code_point, C &on_char) {
if (code_point == 0 || code_point > 0x10FFFF)
@@ -72,10 +72,9 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = await light.new_light(config)
await cg.register_component(var, config)
cg.add(var.set_report_timeout(config[CONF_REPORT_TIMEOUT].total_seconds))
# 1 state + supported_color_modes, min/max_color_temp_kelvin, color_mode, brightness,
# color_temp_kelvin and rgb_color in HomeassistantLight::setup()
setup_home_assistant_entity(var, config, state_subscription_count=8)
setup_home_assistant_entity(var, config, state_subscription_count=8, services=True)
@@ -25,7 +25,7 @@ namespace {
// color mode, all handled as RGB: Home Assistant reports rgb_color for all of them and derives
// the white channels from rgb_color itself.
PROGMEM_STRING_TABLE(ColorModeNames, "onoff", "brightness", "white", "color_temp", "hs", "xy", "rgb", "rgbw", "rgbww");
const uint8_t COLOR_MODES[] PROGMEM = {
constexpr uint8_t COLOR_MODES[] PROGMEM = {
static_cast<uint8_t>(ColorMode::ON_OFF),
static_cast<uint8_t>(ColorMode::BRIGHTNESS),
static_cast<uint8_t>(ColorMode::WHITE),
@@ -381,27 +381,18 @@ void HomeassistantLight::write_state(LightState *state) {
}
return;
}
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "'%s': No clients connected to API server, change lost", this->entity_id_);
if (!can_send_action(TAG, this->entity_id_, state)) {
this->fall_back_();
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(state->get_log_name()));
this->fall_back_();
return;
}
#endif
// In flash on the ESP8266 and encoded from there
static const char SERVICE_TURN_ON[] PROGMEM = "light.turn_on";
static const char SERVICE_TURN_OFF[] PROGMEM = "light.turn_off";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static const char BRIGHTNESS_KEY[] PROGMEM = "brightness";
static const char WHITE_KEY[] PROGMEM = "white";
static const char COLOR_TEMP_KELVIN_KEY[] PROGMEM = "color_temp_kelvin";
static const char RGB_COLOR_KEY[] PROGMEM = "rgb_color";
static constexpr char SERVICE_TURN_ON[] PROGMEM = "light.turn_on";
static constexpr char SERVICE_TURN_OFF[] PROGMEM = "light.turn_off";
static constexpr char BRIGHTNESS_KEY[] PROGMEM = "brightness";
static constexpr char WHITE_KEY[] PROGMEM = "white";
static constexpr char COLOR_TEMP_KELVIN_KEY[] PROGMEM = "color_temp_kelvin";
static constexpr char RGB_COLOR_KEY[] PROGMEM = "rgb_color";
// The request refers to these buffers until it is sent below
char level_buf[4]; // up to 255
@@ -410,9 +401,7 @@ void HomeassistantLight::write_state(LightState *state) {
api::HomeassistantActionRequest resp;
resp.data.init(3);
auto &entity_id = resp.data.emplace_back();
entity_id.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
auto add_number = [&](ProgmemStringRef key, char *buf, size_t size, unsigned number) {
auto &entry = resp.data.emplace_back();
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import number
import esphome.config_validation as cv
from esphome.types import ConfigType
@@ -7,23 +6,23 @@ from .. import (
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
validate_entity_domain,
)
CODEOWNERS = ["@landonr"]
DEPENDENCIES = ["api"]
AUTO_LOAD = ["homeassistant"]
SUPPORTED_DOMAINS = ["input_number", "number"]
HomeassistantNumber = homeassistant_ns.class_(
"HomeassistantNumber", number.Number, cg.Component
)
HomeassistantNumber = homeassistant_ns.class_("HomeassistantNumber", number.Number)
CONFIG_SCHEMA = cv.All(
number.number_schema(HomeassistantNumber)
.extend(HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA)
.extend(cv.COMPONENT_SCHEMA),
number.number_schema(HomeassistantNumber).extend(
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA
),
validate_entity_domain("number", SUPPORTED_DOMAINS),
)
@@ -31,13 +30,12 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = await number.new_number(
config,
min_value=0,
max_value=0,
step=0,
)
await cg.register_component(var, config)
# 1 state + min/max/step fetches in HomeassistantNumber::setup()
setup_home_assistant_entity(var, config, state_subscription_count=4)
# 1 state + min/max/step fetches in HomeassistantNumber::subscribe()
setup_home_assistant_entity(var, config, state_subscription_count=4, services=True)
await register_home_assistant_import(var)
@@ -1,6 +1,6 @@
#include "homeassistant_number.h"
#include <cstring>
#include "../homeassistant.h"
#include "esphome/components/api/api_pb2.h"
#include "esphome/components/api/api_server.h"
@@ -26,46 +26,32 @@ void HomeassistantNumber::state_changed_(StringRef state) {
this->publish_state(number_value.value());
}
void HomeassistantNumber::min_retrieved_(StringRef min) {
auto min_value = parse_number<float>(min.c_str());
if (!min_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_, min.c_str());
return;
optional<float> HomeassistantNumber::parse_attribute_(const char *name, StringRef value) {
auto number = parse_number<float>(value.c_str());
if (!number.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert '%s' value '%s' to number!", this->entity_id_, name, value.c_str());
return nullopt;
}
ESP_LOGD(TAG, "'%s': Min retrieved: %s", LOG_STR_ARG(this->get_log_name()), min.c_str());
this->traits.set_min_value(min_value.value());
ESP_LOGD(TAG, "'%s': Retrieved '%s': %s", LOG_STR_ARG(this->get_log_name()), name, value.c_str());
return number;
}
void HomeassistantNumber::max_retrieved_(StringRef max) {
auto max_value = parse_number<float>(max.c_str());
if (!max_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_, max.c_str());
return;
}
ESP_LOGD(TAG, "'%s': Max retrieved: %s", LOG_STR_ARG(this->get_log_name()), max.c_str());
this->traits.set_max_value(max_value.value());
}
void HomeassistantNumber::step_retrieved_(StringRef step) {
auto step_value = parse_number<float>(step.c_str());
if (!step_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'step' value '%s' to number!", this->entity_id_, step.c_str());
return;
}
ESP_LOGD(TAG, "'%s': Step Retrieved %s", LOG_STR_ARG(this->get_log_name()), step.c_str());
this->traits.set_step(step_value.value());
}
void HomeassistantNumber::setup() {
void HomeassistantNumber::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullptr,
[this](StringRef state) { this->state_changed_(state); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "min",
[this](StringRef min) { this->min_retrieved_(min); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "max",
[this](StringRef max) { this->max_retrieved_(max); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "step",
[this](StringRef step) { this->step_retrieved_(step); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "min", [this](StringRef value) {
if (auto min = this->parse_attribute_("min", value))
this->traits.set_min_value(*min);
});
api::global_api_server->get_home_assistant_state(this->entity_id_, "max", [this](StringRef value) {
if (auto max = this->parse_attribute_("max", value))
this->traits.set_max_value(*max);
});
api::global_api_server->get_home_assistant_state(this->entity_id_, "step", [this](StringRef value) {
if (auto step = this->parse_attribute_("step", value))
this->traits.set_step(*step);
});
}
void HomeassistantNumber::dump_config() {
@@ -73,39 +59,24 @@ void HomeassistantNumber::dump_config() {
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
}
float HomeassistantNumber::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void HomeassistantNumber::control(float value) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "No clients connected to API server");
if (!can_send_action(TAG, this->entity_id_, this))
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(this->get_log_name()));
return;
}
#endif
this->publish_state(value);
// In flash on the ESP8266 and encoded from there
static const char NUMBER_SERVICE_NAME[] PROGMEM = "number.set_value";
static const char INPUT_NUMBER_SERVICE_NAME[] PROGMEM = "input_number.set_value";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static const char VALUE_KEY[] PROGMEM = "value";
static constexpr char NUMBER_SERVICE_NAME[] PROGMEM = "number.set_value";
static constexpr char INPUT_NUMBER_SERVICE_NAME[] PROGMEM = "input_number.set_value";
static constexpr char VALUE_KEY[] PROGMEM = "value";
api::HomeassistantActionRequest resp;
// An input helper entity id starts with the "input_" its action name starts with
const bool input_helper = ESPHOME_strncmp_P(this->entity_id_, INPUT_NUMBER_SERVICE_NAME, sizeof("input_") - 1) == 0;
resp.service = input_helper ? ProgmemStringRef::from_lit(INPUT_NUMBER_SERVICE_NAME)
: ProgmemStringRef::from_lit(NUMBER_SERVICE_NAME);
resp.service = is_input_helper(this->entity_id_, INPUT_NUMBER_SERVICE_NAME)
? ProgmemStringRef::from_lit(INPUT_NUMBER_SERVICE_NAME)
: ProgmemStringRef::from_lit(NUMBER_SERVICE_NAME);
resp.data.init(2);
auto &entity_id = resp.data.emplace_back();
entity_id.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
auto &entity_value = resp.data.emplace_back();
entity_value.key = ProgmemStringRef::from_lit(VALUE_KEY);
@@ -1,24 +1,21 @@
#pragma once
#include "esphome/components/number/number.h"
#include "esphome/core/component.h"
#include "esphome/core/optional.h"
#include "esphome/core/string_ref.h"
namespace esphome::homeassistant {
class HomeassistantNumber final : public number::Number, public Component {
class HomeassistantNumber final : public number::Number {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
void state_changed_(StringRef state);
void min_retrieved_(StringRef min);
void max_retrieved_(StringRef max);
void step_retrieved_(StringRef step);
optional<float> parse_attribute_(const char *name, StringRef value);
void control(float value) override;
@@ -8,6 +8,7 @@ from .. import (
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
validate_entity_domain,
)
@@ -24,9 +25,7 @@ SUPPORTED_DOMAINS = [
"select",
]
HomeassistantSelect = homeassistant_ns.class_(
"HomeassistantSelect", select.Select, cg.Component
)
HomeassistantSelect = homeassistant_ns.class_("HomeassistantSelect", select.Select)
CONFIG_SCHEMA = cv.All(
select.select_schema(HomeassistantSelect)
@@ -38,8 +37,7 @@ CONFIG_SCHEMA = cv.All(
min=2, max=4096
),
}
)
.extend(cv.COMPONENT_SCHEMA),
),
validate_entity_domain("select", SUPPORTED_DOMAINS),
)
@@ -47,13 +45,12 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = await select.new_select(
config,
cg.static_buffer(config[CONF_ID], cg.char, config[CONF_OPTIONS_BUFFER_SIZE]),
cg.static_buffer(config[CONF_ID], cg.const_char_ptr, config[CONF_MAX_OPTIONS]),
options=[],
)
await cg.register_component(var, config)
# 1 state + options fetch in HomeassistantSelect::setup()
setup_home_assistant_entity(var, config, state_subscription_count=2)
# 1 state + options fetch in HomeassistantSelect::subscribe()
setup_home_assistant_entity(var, config, state_subscription_count=2, services=True)
await register_home_assistant_import(var)
@@ -1,7 +1,5 @@
#include "homeassistant_select.h"
#include <cstring>
#include "../homeassistant.h"
#include "esphome/components/api/api_pb2.h"
@@ -15,7 +13,7 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.select");
void HomeassistantSelect::setup() {
void HomeassistantSelect::subscribe() {
// Subscribe to the options first: Home Assistant answers subscriptions in order, so the options are
// known by the time the first state arrives.
api::global_api_server->subscribe_home_assistant_state(
@@ -110,37 +108,22 @@ void HomeassistantSelect::dump_config() {
this->entity_id_, this->max_options_, this->options_buffer_size_);
}
float HomeassistantSelect::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void HomeassistantSelect::control(size_t index) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "No clients connected to API server");
if (!can_send_action(TAG, this->entity_id_, this))
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(this->get_log_name()));
return;
}
#endif
// In flash on the ESP8266 and encoded from there
static const char SERVICE_SELECT[] PROGMEM = "select.select_option";
static const char SERVICE_INPUT_SELECT[] PROGMEM = "input_select.select_option";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static const char OPTION_KEY[] PROGMEM = "option";
static constexpr char SERVICE_SELECT[] PROGMEM = "select.select_option";
static constexpr char SERVICE_INPUT_SELECT[] PROGMEM = "input_select.select_option";
static constexpr char OPTION_KEY[] PROGMEM = "option";
api::HomeassistantActionRequest resp;
// An input helper entity id starts with the "input_" its action name starts with
const bool input_helper = ESPHOME_strncmp_P(this->entity_id_, SERVICE_INPUT_SELECT, sizeof("input_") - 1) == 0;
resp.service =
input_helper ? ProgmemStringRef::from_lit(SERVICE_INPUT_SELECT) : ProgmemStringRef::from_lit(SERVICE_SELECT);
resp.service = is_input_helper(this->entity_id_, SERVICE_INPUT_SELECT)
? ProgmemStringRef::from_lit(SERVICE_INPUT_SELECT)
: ProgmemStringRef::from_lit(SERVICE_SELECT);
resp.data.init(2);
auto &entity_id = resp.data.emplace_back();
entity_id.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
auto &option = resp.data.emplace_back();
option.key = ProgmemStringRef::from_lit(OPTION_KEY);
@@ -5,7 +5,6 @@
#include <span>
#include "esphome/components/select/select.h"
#include "esphome/core/component.h"
#include "esphome/core/string_ref.h"
namespace esphome::homeassistant {
@@ -16,7 +15,7 @@ namespace esphome::homeassistant {
* `options_buffer_size` bytes and a list of at most `max_options` entries, both static arrays from code
* generation, so options never allocate.
*/
class HomeassistantSelect final : public select::Select, public Component {
class HomeassistantSelect final : public select::Select {
public:
HomeassistantSelect(std::span<char> options_buffer, std::span<const char *> option_list)
: options_buffer_(options_buffer.data()),
@@ -26,9 +25,8 @@ class HomeassistantSelect final : public select::Select, public Component {
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
void options_changed_(StringRef options);
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import sensor
from esphome.types import ConfigType
@@ -6,6 +5,7 @@ from .. import (
HOME_ASSISTANT_IMPORT_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
)
@@ -13,9 +13,7 @@ DEPENDENCIES = ["api"]
# For is_unset() in homeassistant.h
AUTO_LOAD = ["homeassistant"]
HomeassistantSensor = homeassistant_ns.class_(
"HomeassistantSensor", sensor.Sensor, cg.Component
)
HomeassistantSensor = homeassistant_ns.class_("HomeassistantSensor", sensor.Sensor)
CONFIG_SCHEMA = sensor.sensor_schema(HomeassistantSensor, accuracy_decimals=1).extend(
HOME_ASSISTANT_IMPORT_SCHEMA
@@ -26,5 +24,5 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
setup_home_assistant_entity(var, config)
await register_home_assistant_import(var)
@@ -21,7 +21,7 @@ static void __attribute__((noinline, cold)) publish_not_a_number(HomeassistantSe
sensor->publish_state(NAN);
}
void HomeassistantSensor::setup() {
void HomeassistantSensor::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, this->attribute_, [this](StringRef state) {
auto val = parse_number<float>(state.c_str());
if (!val.has_value()) {
@@ -44,6 +44,5 @@ void HomeassistantSensor::dump_config() {
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
}
}
float HomeassistantSensor::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
} // namespace esphome::homeassistant
@@ -1,17 +1,15 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
namespace esphome::homeassistant {
class HomeassistantSensor final : public sensor::Sensor, public Component {
class HomeassistantSensor final : public sensor::Sensor {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
const char *entity_id_{nullptr};
@@ -1,19 +1,19 @@
import esphome.codegen as cg
from esphome.components import switch
import esphome.config_validation as cv
from esphome.const import CONF_ID
from esphome.types import ConfigType
from .. import (
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
validate_entity_domain,
)
CODEOWNERS = ["@Links2004"]
DEPENDENCIES = ["api"]
AUTO_LOAD = ["homeassistant"]
SUPPORTED_DOMAINS = [
"automation",
@@ -27,14 +27,12 @@ SUPPORTED_DOMAINS = [
"switch",
]
HomeassistantSwitch = homeassistant_ns.class_(
"HomeassistantSwitch", switch.Switch, cg.Component
)
HomeassistantSwitch = homeassistant_ns.class_("HomeassistantSwitch", switch.Switch)
CONFIG_SCHEMA = cv.All(
switch.switch_schema(HomeassistantSwitch)
.extend(HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA)
.extend(cv.COMPONENT_SCHEMA),
switch.switch_schema(HomeassistantSwitch).extend(
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA
),
validate_entity_domain("switch", SUPPORTED_DOMAINS),
)
@@ -42,8 +40,6 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await switch.register_switch(var, config)
setup_home_assistant_entity(var, config)
var = await switch.new_switch(config)
setup_home_assistant_entity(var, config, services=True)
await register_home_assistant_import(var)
@@ -1,4 +1,5 @@
#include "homeassistant_switch.h"
#include "../homeassistant.h"
#include "esphome/components/api/api_server.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
@@ -8,23 +9,16 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.switch");
using namespace esphome::switch_;
void HomeassistantSwitch::setup() {
void HomeassistantSwitch::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullptr, [this](StringRef state) {
auto val = parse_on_off(state.c_str());
switch (val) {
case PARSE_NONE:
case PARSE_TOGGLE:
ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
break;
case PARSE_ON:
case PARSE_OFF:
bool new_state = val == PARSE_ON;
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
this->publish_state(new_state);
break;
if (val != PARSE_ON && val != PARSE_OFF) {
ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
return;
}
bool new_state = val == PARSE_ON;
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
this->publish_state(new_state);
});
}
@@ -33,33 +27,19 @@ void HomeassistantSwitch::dump_config() {
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
}
float HomeassistantSwitch::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void HomeassistantSwitch::write_state(bool state) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "No clients connected to API server");
if (!can_send_action(TAG, this->entity_id_, this))
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(this->get_log_name()));
return;
}
#endif
// In flash on the ESP8266 and encoded from there
static const char SERVICE_ON[] PROGMEM = "homeassistant.turn_on";
static const char SERVICE_OFF[] PROGMEM = "homeassistant.turn_off";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static constexpr char SERVICE_ON[] PROGMEM = "homeassistant.turn_on";
static constexpr char SERVICE_OFF[] PROGMEM = "homeassistant.turn_off";
api::HomeassistantActionRequest resp;
resp.service = state ? ProgmemStringRef::from_lit(SERVICE_ON) : ProgmemStringRef::from_lit(SERVICE_OFF);
resp.data.init(1);
auto &entity_id_kv = resp.data.emplace_back();
entity_id_kv.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id_kv.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
api::global_api_server->send_homeassistant_action(resp);
}
@@ -1,16 +1,14 @@
#pragma once
#include "esphome/components/switch/switch.h"
#include "esphome/core/component.h"
namespace esphome::homeassistant {
class HomeassistantSwitch final : public switch_::Switch, public Component {
class HomeassistantSwitch final : public switch_::Switch {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
void write_state(bool state) override;
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import text
import esphome.config_validation as cv
from esphome.types import ConfigType
@@ -7,26 +6,26 @@ from .. import (
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
validate_entity_domain,
)
CODEOWNERS = ["@jesserockz"]
DEPENDENCIES = ["api"]
AUTO_LOAD = ["homeassistant"]
SUPPORTED_DOMAINS = [
"input_text",
"text",
]
HomeassistantText = homeassistant_ns.class_(
"HomeassistantText", text.Text, cg.Component
)
HomeassistantText = homeassistant_ns.class_("HomeassistantText", text.Text)
CONFIG_SCHEMA = cv.All(
text.text_schema(HomeassistantText, mode="TEXT")
.extend(HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA)
.extend(cv.COMPONENT_SCHEMA),
text.text_schema(HomeassistantText, mode="TEXT").extend(
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA
),
validate_entity_domain("text", SUPPORTED_DOMAINS),
)
@@ -34,8 +33,7 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = await text.new_text(config)
await cg.register_component(var, config)
# 1 state + min/max/mode fetches in HomeassistantText::setup()
setup_home_assistant_entity(var, config, state_subscription_count=4)
# 1 state + min/max/mode fetches in HomeassistantText::subscribe()
setup_home_assistant_entity(var, config, state_subscription_count=4, services=True)
await register_home_assistant_import(var)
@@ -1,6 +1,6 @@
#include "homeassistant_text.h"
#include <cstring>
#include "../homeassistant.h"
#include "esphome/components/api/api_pb2.h"
#include "esphome/components/api/api_server.h"
@@ -13,6 +13,9 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.text");
PROGMEM_STRING_TABLE(TextModeNames, "text", "password");
static_assert(text::TEXT_MODE_TEXT == 0 && text::TEXT_MODE_PASSWORD == 1 && TextModeNames::COUNT == 2);
void HomeassistantText::state_changed_(StringRef state) {
if (state == this->state) {
return;
@@ -21,46 +24,38 @@ void HomeassistantText::state_changed_(StringRef state) {
this->publish_state(state.c_str(), state.size());
}
void HomeassistantText::min_retrieved_(StringRef min) {
auto min_value = parse_number<int>(min.c_str());
if (!min_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_, min.c_str());
return;
optional<int> HomeassistantText::parse_length_(const char *name, StringRef value) {
auto length = parse_number<int>(value.c_str());
if (!length.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert '%s' value '%s' to number!", this->entity_id_, name, value.c_str());
return nullopt;
}
ESP_LOGD(TAG, "'%s': Min retrieved: %s", this->entity_id_, min.c_str());
this->traits.set_min_length(min_value.value());
}
void HomeassistantText::max_retrieved_(StringRef max) {
auto max_value = parse_number<int>(max.c_str());
if (!max_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_, max.c_str());
return;
}
ESP_LOGD(TAG, "'%s': Max retrieved: %s", this->entity_id_, max.c_str());
this->traits.set_max_length(max_value.value());
ESP_LOGD(TAG, "'%s': Retrieved '%s': %s", this->entity_id_, name, value.c_str());
return length;
}
void HomeassistantText::mode_retrieved_(StringRef mode) {
if (mode == "text") {
this->traits.set_mode(text::TEXT_MODE_TEXT);
} else if (mode == "password") {
this->traits.set_mode(text::TEXT_MODE_PASSWORD);
} else {
const int16_t index = progmem_string_table_find<TextModeNames>(mode.c_str(), mode.size());
if (index < 0) {
ESP_LOGW(TAG, "'%s': Unknown 'mode' value '%s'", this->entity_id_, mode.c_str());
return;
}
this->traits.set_mode(static_cast<text::TextMode>(index));
ESP_LOGD(TAG, "'%s': Mode retrieved: %s", this->entity_id_, mode.c_str());
}
void HomeassistantText::setup() {
void HomeassistantText::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullptr,
[this](StringRef state) { this->state_changed_(state); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "min",
[this](StringRef min) { this->min_retrieved_(min); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "max",
[this](StringRef max) { this->max_retrieved_(max); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "min", [this](StringRef value) {
if (auto min = this->parse_length_("min", value))
this->traits.set_min_length(*min);
});
api::global_api_server->get_home_assistant_state(this->entity_id_, "max", [this](StringRef value) {
if (auto max = this->parse_length_("max", value))
this->traits.set_max_length(*max);
});
api::global_api_server->get_home_assistant_state(this->entity_id_, "mode",
[this](StringRef mode) { this->mode_retrieved_(mode); });
// The "pattern" attribute is not fetched: Home Assistant sends "None" when it is unset,
@@ -72,37 +67,21 @@ void HomeassistantText::dump_config() {
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
}
float HomeassistantText::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void HomeassistantText::control(const std::string &value) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "No clients connected to API server");
if (!can_send_action(TAG, this->entity_id_, this))
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(this->get_log_name()));
return;
}
#endif
// In flash on the ESP8266 and encoded from there
static const char SERVICE_TEXT[] PROGMEM = "text.set_value";
static const char SERVICE_INPUT_TEXT[] PROGMEM = "input_text.set_value";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static const char VALUE_KEY[] PROGMEM = "value";
static constexpr char SERVICE_TEXT[] PROGMEM = "text.set_value";
static constexpr char SERVICE_INPUT_TEXT[] PROGMEM = "input_text.set_value";
static constexpr char VALUE_KEY[] PROGMEM = "value";
api::HomeassistantActionRequest resp;
// An input helper entity id starts with the "input_" its action name starts with
const bool input_helper = ESPHOME_strncmp_P(this->entity_id_, SERVICE_INPUT_TEXT, sizeof("input_") - 1) == 0;
resp.service =
input_helper ? ProgmemStringRef::from_lit(SERVICE_INPUT_TEXT) : ProgmemStringRef::from_lit(SERVICE_TEXT);
resp.service = is_input_helper(this->entity_id_, SERVICE_INPUT_TEXT) ? ProgmemStringRef::from_lit(SERVICE_INPUT_TEXT)
: ProgmemStringRef::from_lit(SERVICE_TEXT);
resp.data.init(2);
auto &entity_id_kv = resp.data.emplace_back();
entity_id_kv.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id_kv.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
auto &value_kv = resp.data.emplace_back();
value_kv.key = ProgmemStringRef::from_lit(VALUE_KEY);
@@ -1,23 +1,21 @@
#pragma once
#include "esphome/components/text/text.h"
#include "esphome/core/component.h"
#include "esphome/core/optional.h"
#include "esphome/core/string_ref.h"
namespace esphome::homeassistant {
class HomeassistantText final : public text::Text, public Component {
class HomeassistantText final : public text::Text {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
void state_changed_(StringRef state);
void min_retrieved_(StringRef min);
void max_retrieved_(StringRef max);
optional<int> parse_length_(const char *name, StringRef value);
void mode_retrieved_(StringRef mode);
void control(const std::string &value) override;
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import text_sensor
from esphome.types import ConfigType
@@ -6,13 +5,14 @@ from .. import (
HOME_ASSISTANT_IMPORT_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
)
DEPENDENCIES = ["api"]
HomeassistantTextSensor = homeassistant_ns.class_(
"HomeassistantTextSensor", text_sensor.TextSensor, cg.Component
"HomeassistantTextSensor", text_sensor.TextSensor
)
CONFIG_SCHEMA = text_sensor.text_sensor_schema(HomeassistantTextSensor).extend(
@@ -24,5 +24,5 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
var = await text_sensor.new_text_sensor(config)
await cg.register_component(var, config)
setup_home_assistant_entity(var, config)
await register_home_assistant_import(var)
@@ -7,7 +7,7 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.text_sensor");
void HomeassistantTextSensor::setup() {
void HomeassistantTextSensor::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, this->attribute_, [this](StringRef state) {
if (this->attribute_ != nullptr) {
ESP_LOGD(TAG, "'%s::%s': Got attribute state '%s'", this->entity_id_, this->attribute_, state.c_str());
@@ -24,5 +24,4 @@ void HomeassistantTextSensor::dump_config() {
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
}
}
float HomeassistantTextSensor::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
} // namespace esphome::homeassistant
@@ -1,17 +1,15 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/text_sensor/text_sensor.h"
namespace esphome::homeassistant {
class HomeassistantTextSensor final : public text_sensor::TextSensor, public Component {
class HomeassistantTextSensor final : public text_sensor::TextSensor {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
const char *entity_id_{nullptr};
+15 -29
View File
@@ -180,23 +180,18 @@ void ArduinoI2CBus::recover_() {
return;
}
// From the specification:
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
// device that held the bus LOW should release it sometime within
// those nine clocks."
// We don't really have to detect if SDA is stuck low. We'll simply send
// nine clock pulses here, just in case SDA is stuck. Actual checks on
// the SDA line status will be done after the clock pulses.
// Make sure that switching to output mode will make SCL low, just in
// case other code has setup the pin for a HIGH signal.
digitalWrite(this->scl_pin_, LOW); // NOLINT
// Activate input and pull up resistor for the SDA pin, so it can be read during the pulses.
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
delayMicroseconds(half_period_usec);
for (auto i = 0; i < 9; i++) {
// Release pull up resistor and switch to output to make the signal LOW.
pinMode(this->scl_pin_, INPUT); // NOLINT
pinMode(this->scl_pin_, OUTPUT); // NOLINT
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
for (auto i = 0; i < 9 && digitalRead(this->sda_pin_) == LOW; i++) { // NOLINT
// Drive LOW. Set the level while the pin is a plain input: on RP2040 a write to an
// INPUT_PULLUP pin drives it, which would leave SCL low if the loop never runs.
pinMode(this->scl_pin_, INPUT); // NOLINT
digitalWrite(this->scl_pin_, LOW); // NOLINT
pinMode(this->scl_pin_, OUTPUT); // NOLINT
delayMicroseconds(half_period_usec);
// Release output and activate pull up resistor to make the signal HIGH.
@@ -223,14 +218,7 @@ void ArduinoI2CBus::recover_() {
}
}
// Activate input and pull resistor for the SDA pin, so we can verify
// that SDA is pulled HIGH in the following step.
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
digitalWrite(this->sda_pin_, LOW); // NOLINT
// By now, any stuck device ought to have sent all remaining bits of its
// transaction, meaning that it should have freed up the SDA line, resulting
// in SDA being pulled up.
// A device still holding SDA after nine pulses cannot be freed here.
if (digitalRead(this->sda_pin_) == LOW) { // NOLINT
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
@@ -242,15 +230,13 @@ void ArduinoI2CBus::recover_() {
// a START or repeated START condition such that they all anticipate
// the sending of a target address, even if these START conditions are
// not positioned according to the proper format."
// While the 9 clock pulses from above might have drained all bits of a
// single byte within a transaction, a device might have more bytes to
// transmit. So here we'll generate a START condition to snap the device
// out of this state.
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
// SCL and SDA are already high at this point, so we can generate a START
// condition by making the SDA signal LOW.
delayMicroseconds(half_period_usec);
pinMode(this->sda_pin_, INPUT); // NOLINT
pinMode(this->sda_pin_, OUTPUT); // NOLINT
pinMode(this->sda_pin_, INPUT); // NOLINT
digitalWrite(this->sda_pin_, LOW); // NOLINT
pinMode(this->sda_pin_, OUTPUT); // NOLINT
// From the specification:
// "A START condition immediately followed by a STOP condition (void
+5 -15
View File
@@ -346,14 +346,9 @@ void IDFI2CBus::recover_() {
return;
}
// From the specification:
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
// device that held the bus LOW should release it sometime within
// those nine clocks."
// We don't really have to detect if SDA is stuck low. We'll simply send
// nine clock pulses here, just in case SDA is stuck. Actual checks on
// the SDA line status will be done after the clock pulses.
for (auto i = 0; i < 9; i++) {
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
for (auto i = 0; i < 9 && gpio_get_level(sda_pin) == 0; i++) {
gpio_set_level(scl_pin, 0);
delayMicroseconds(half_period_usec);
gpio_set_level(scl_pin, 1);
@@ -378,9 +373,7 @@ void IDFI2CBus::recover_() {
}
}
// By now, any stuck device ought to have sent all remaining bits of its
// transaction, meaning that it should have freed up the SDA line, resulting
// in SDA being pulled up.
// A device still holding SDA after nine pulses cannot be freed here.
if (gpio_get_level(sda_pin) == 0) {
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
@@ -392,10 +385,7 @@ void IDFI2CBus::recover_() {
// a START or repeated START condition such that they all anticipate
// the sending of a target address, even if these START conditions are
// not positioned according to the proper format."
// While the 9 clock pulses from above might have drained all bits of a
// single byte within a transaction, a device might have more bytes to
// transmit. So here we'll generate a START condition to snap the device
// out of this state.
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
// SCL and SDA are already high at this point, so we can generate a START
// condition by making the SDA signal LOW.
delayMicroseconds(half_period_usec);
@@ -6,7 +6,7 @@ namespace esphome::inkbird_ibsth1_mini {
ESPHOME_LOG_TAG(TAG, "inkbird_ibsth1_mini");
void InkbirdIbstH1Mini::dump_config() {
void InkbirdIbstH1Mini::dump_child_config() {
ESP_LOGCONFIG(TAG, "Inkbird IBS TH1 MINI");
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
LOG_SENSOR(" ", "External Temperature", this->external_temperature_sensor_);
@@ -1,12 +1,11 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/ble_device_base/ble_device.h"
namespace esphome::inkbird_ibsth1_mini {
class InkbirdIbstH1Mini final : public Component, public ble_device_base::ESPBTDeviceListener {
class InkbirdIbstH1Mini final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(temperature)
SUB_SENSOR(external_temperature)
SUB_SENSOR(humidity)
@@ -17,7 +16,7 @@ class InkbirdIbstH1Mini final : public Component, public ble_device_base::ESPBTD
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
protected:
uint64_t address_;
@@ -22,7 +22,7 @@ AUTO_LOAD = ["ble_device_base"]
inkbird_ibsth1_mini_ns = cg.esphome_ns.namespace("inkbird_ibsth1_mini")
InkbirdIbstH1Mini = inkbird_ibsth1_mini_ns.class_(
"InkbirdIbstH1Mini", ble_device_base.ESPBTDeviceListener, cg.Component
"InkbirdIbstH1Mini", ble_device_base.ESPBTDeviceListener
)
CONFIG_SCHEMA = cv.All(
@@ -57,14 +57,12 @@ CONFIG_SCHEMA = cv.All(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
).extend(ble_device_base.BLE_DEVICE_SCHEMA),
)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(config)
var = await ble_device_base.new_ble_device(config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
+56
View File
@@ -1,3 +1,4 @@
from dataclasses import dataclass
import json
import logging
from pathlib import Path
@@ -188,6 +189,61 @@ def get_board_pins() -> dict[str, int]:
return lookup_board_pins(get_libretiny_board())
@dataclass(frozen=True)
class HardwareUart:
"""A hardware UART of the configured board and the pin numbers it can use."""
port: int
tx_pins: tuple[int, ...]
rx_pins: tuple[int, ...]
# The board lists pin choices instead of a default pin for this direction
tx_pin_choices: bool
rx_pin_choices: bool
@property
def pin_choices(self) -> bool:
"""True when the pins must be passed when the UART starts."""
return self.tx_pin_choices or self.rx_pin_choices
def get_hardware_uarts() -> list[HardwareUart]:
"""Hardware UARTs of the configured board; empty for a board without pin data."""
board_pins = get_board_pins()
uarts = []
for port in range(3):
pins: dict[str, list[int]] = {"TX": [], "RX": []}
choices: dict[str, bool] = {"TX": False, "RX": False}
for role, role_pins in pins.items():
name = f"SERIAL{port}_{role}"
for key, pin in board_pins.items():
if key == name:
role_pins.append(pin)
elif key.startswith(f"{name}_"):
role_pins.append(pin)
choices[role] = True
if pins["TX"] or pins["RX"]:
uarts.append(
HardwareUart(
port,
tuple(pins["TX"]),
tuple(pins["RX"]),
choices["TX"],
choices["RX"],
)
)
return uarts
def has_software_serial() -> bool:
"""True when the family's Arduino core has SoftwareSerial (LT_ARD_HAS_SOFTSERIAL)."""
return get_libretiny_family() == FAMILY_RTL8710B
def can_choose_uart_pins() -> bool:
"""True when SerialClass::begin() takes the pins, which LibreTiny added in 1.12.0."""
return CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION] >= cv.Version(1, 12, 0)
def only_on_family(*, supported=None, unsupported=None):
"""Config validator for features only available on some LibreTiny families."""
if supported is not None and not isinstance(supported, list):
@@ -1,6 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "addressable_light.h"
namespace esphome::light {
@@ -23,19 +24,21 @@ class AddressableLightWrapper : public light::AddressableLight {
// Choose which color mode to use.
// This is ordered by how closely each color mode matches the underlying RGBW data structure used in LightPartition.
ColorMode color_mode_precedence[] = {ColorMode::RGB_WHITE,
ColorMode::RGB_COLD_WARM_WHITE,
ColorMode::RGB_COLOR_TEMPERATURE,
ColorMode::RGB,
ColorMode::WHITE,
ColorMode::COLD_WARM_WHITE,
ColorMode::COLOR_TEMPERATURE,
ColorMode::BRIGHTNESS,
ColorMode::ON_OFF,
ColorMode::UNKNOWN};
// In flash: a local array is copied from a RAM constant on ESP8266
static constexpr ColorMode COLOR_MODE_PRECEDENCE[] PROGMEM = {ColorMode::RGB_WHITE,
ColorMode::RGB_COLD_WARM_WHITE,
ColorMode::RGB_COLOR_TEMPERATURE,
ColorMode::RGB,
ColorMode::WHITE,
ColorMode::COLD_WARM_WHITE,
ColorMode::COLOR_TEMPERATURE,
ColorMode::BRIGHTNESS,
ColorMode::ON_OFF,
ColorMode::UNKNOWN};
LightTraits parent_traits = this->light_state_->get_traits();
for (auto cm : color_mode_precedence) {
for (const auto &entry : COLOR_MODE_PRECEDENCE) {
auto cm = static_cast<ColorMode>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&entry)));
if (parent_traits.supports_color_mode(cm)) {
this->color_mode_ = cm;
break;
@@ -62,7 +62,7 @@ void LilygoT547Touchscreen::update_touches() {
return;
}
point = buffer[5] & 0xF;
point = low_nibble(buffer[5]);
if (point > 2) {
ESP_LOGW(TAG, "Invalid touch point count: %d", point);
point = 2;
@@ -88,9 +88,11 @@ void LilygoT547Touchscreen::update_touches() {
uint16_t id, x_raw, y_raw;
for (uint8_t i = 0; i < point; i++) {
id = (buffer[i * 5] >> 4) & 0x0F;
y_raw = (uint16_t) ((buffer[i * 5 + 1] << 4) | ((buffer[i * 5 + 3] >> 4) & 0x0F));
x_raw = (uint16_t) ((buffer[i * 5 + 2] << 4) | (buffer[i * 5 + 3] & 0x0F));
const uint8_t *record = buffer + i * 5;
id = high_nibble(record[0]);
// The low 4 bits of Y and X share byte 3
y_raw = encode_uint12(record[1], high_nibble(record[3]));
x_raw = encode_uint12(record[2], low_nibble(record[3]));
this->add_raw_touch_position_(id, x_raw, y_raw);
}
@@ -134,6 +134,7 @@ void LN882HBLETracker::dump_config() {
this->scan_duration_ / 1000, this->scan_interval_ * BLE_SCAN_UNIT_MS, this->scan_interval_,
this->scan_window_ * BLE_SCAN_UNIT_MS, this->scan_window_, this->scan_active_ ? "ACTIVE" : "PASSIVE",
YESNO(this->scan_continuous_));
this->dispatcher_.dump_child_configs();
}
// ---------------------------------------------------------------------------
+22 -1
View File
@@ -114,6 +114,26 @@ struct LogBuffer {
this->finalize_();
}
#endif
// Writes a message that needs no formatting, truncated and stripped of trailing newlines as format_body() does
void HOT write_unformatted_body(const char *text, size_t len) {
if (!this->full_()) {
const uint16_t limit = this->remaining_() - 1; // vsnprintf() keeps the last byte for the null terminator
const uint16_t copy_len = (len < limit) ? static_cast<uint16_t>(len) : limit;
memcpy(this->current_(), text, copy_len);
this->pos += copy_len;
this->strip_trailing_newlines_();
}
this->finalize_();
}
// write_unformatted_body() for a message in flash
inline void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body_p(ESPHOME_PGM_P text) {
if (!this->full_()) {
char *const start = this->current_();
this->pos = static_cast<uint16_t>(progmem_copy_str(start, start + this->remaining_() - 1, text) - this->data);
this->strip_trailing_newlines_();
}
this->finalize_();
}
static constexpr uint16_t ANSI_COLOR_LEN = 7; // "\033[{bold};3{color}m" written by write_header for level != 0
static constexpr uint16_t ANSI_RESET_LEN = 4; // "\033[0m"
// Largest replay header: color plus "@4294967295ms "
@@ -161,7 +181,8 @@ struct LogBuffer {
this->pos += ANSI_RESET_LEN;
}
}
void strip_trailing_newlines_() {
// Forced inline: an outlined copy slows every formatted line
inline void ESPHOME_ALWAYS_INLINE strip_trailing_newlines_() {
while (this->pos > 0 && this->data[this->pos - 1] == '\n')
this->pos--;
}
+53 -5
View File
@@ -19,6 +19,15 @@ namespace esphome::logger {
ESPHOME_LOG_TAG(TAG, "logger");
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes to a socket would
// take that lock again and deadlock, so such a line is queued for loop() instead. It can print after later inline
// lines, and is lost if loop() never runs again (safe_reboot()).
static inline bool HOT ESPHOME_ALWAYS_INLINE under_lwip_core_lock() {
return sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED);
}
#endif
#if defined(USE_ESP32) || defined(USE_HOST) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
// Implementation for multi-threaded platforms (ESP32 with FreeRTOS, Host with pthreads, LibreTiny with FreeRTOS,
// Zephyr) Main thread/task always uses direct buffer access for console output and callbacks
@@ -51,11 +60,7 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
// Pass nullptr for thread_name since we already know this is the main task
if (is_main_task && !this->main_task_recursion_guard_) [[likely]] {
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes
// to a socket would take that lock again and deadlock, so queue the message for loop() instead. Such lines
// can print after later inline ones, and are lost if loop() never runs again (safe_reboot()).
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED))
[[unlikely]] {
if (under_lwip_core_lock()) [[unlikely]] {
this->log_vprintf_non_main_thread_(level, tag, line, format, args, nullptr);
return;
}
@@ -159,6 +164,49 @@ void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __Flas
}
#endif // USE_ESP8266
// Not shared with log_message_to_buffer_and_send_(): sharing it slows formatted lines
inline void HOT ESPHOME_ALWAYS_INLINE Logger::send_unformatted_line_(uint8_t level, const char *tag, LogBuffer &buf) {
#ifdef USE_LOGGER_BOOT_LOG_BUFFER
if (!this->boot_log_done_)
this->boot_log_capture_(level, tag, buf);
#endif
this->notify_listeners_(level, tag, buf);
this->write_log_buffer_to_console_(buf);
}
bool HOT Logger::log_str_(uint8_t level, const char *tag, int line, const char *msg) {
if (level > this->level_for(tag))
return true;
// Check the task first: the guard belongs to the main task and must not be read from other threads
if (!this->is_main_task_())
return false;
if (this->main_task_recursion_guard_)
return true;
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// The formatting path queues it
if (under_lwip_core_lock()) [[unlikely]]
return false;
#endif
RecursionGuard guard(this->main_task_recursion_guard_);
LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
buf.write_header(level, tag, line, nullptr);
buf.write_unformatted_body(msg, strlen(msg));
this->send_unformatted_line_(level, tag, buf);
return true;
}
#ifdef USE_ESP8266
void Logger::log_str_(uint8_t level, const char *tag, int line, const __FlashStringHelper *msg) {
if (level > this->level_for(tag) || this->main_task_recursion_guard_)
return;
RecursionGuard guard(this->main_task_recursion_guard_);
LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
buf.write_header(level, tag, line, nullptr);
buf.write_unformatted_body_p(reinterpret_cast<PGM_P>(msg));
this->send_unformatted_line_(level, tag, buf);
}
#endif // USE_ESP8266
#if defined(USE_LOGGER_RUNTIME_TAG_LEVELS) || defined(USE_LOGGER_BOOT_LOG_PER_TAG_LEVELS)
// Level for tag from a per-tag map, or fallback when the tag has none; tags may live in flash
static inline uint8_t tag_level(const std::map<const char *, uint8_t, CStrCompare> &levels, const char *tag,
+22 -1
View File
@@ -223,6 +223,12 @@ class Logger final : public Component {
// NOLINTNEXTLINE(readability-identifier-naming)
void log_vprintf_(uint8_t level, const char *tag, int line, const __FlashStringHelper *format, va_list args);
#endif
// Copies a line with no '%' without formatting; false means the caller must format it
bool log_str_(uint8_t level, const char *tag, int line, const char *msg); // NOLINT
#ifdef USE_ESP8266
// NOLINTNEXTLINE(readability-identifier-naming)
void log_str_(uint8_t level, const char *tag, int line, const __FlashStringHelper *msg);
#endif
protected:
// RAII guard for recursion flags - sets flag on construction, clears on destruction
@@ -292,7 +298,7 @@ class Logger final : public Component {
}
// Helper to write log buffer to console if logging is enabled
inline void HOT write_log_buffer_to_console_(LogBuffer &buf) {
inline void HOT ESPHOME_ALWAYS_INLINE write_log_buffer_to_console_(LogBuffer &buf) {
if (this->baud_rate_ > 0)
this->write_to_console_(buf);
}
@@ -321,6 +327,21 @@ class Logger final : public Component {
this->write_log_buffer_to_console_(buf);
}
inline void send_unformatted_line_(uint8_t level, const char *tag, LogBuffer &buf);
// True on the task that runs the main loop, and always on single-task platforms
inline bool HOT is_main_task_() const {
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
return xTaskGetCurrentTaskHandle() == this->main_task_;
#elif defined(USE_ZEPHYR)
return k_current_get() == this->main_task_;
#elif defined(USE_HOST)
return pthread_equal(pthread_self(), this->main_thread_);
#else
return true;
#endif
}
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
// Helper to format a pre-formatted message from the task log buffer and notify listeners
inline void HOT format_buffered_message_and_notify_(uint8_t level, const char *tag, uint16_t line,
+1 -1
View File
@@ -9,7 +9,7 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
char buffer[TIMESTAMP_LEN + ESPHOME_LOGGER_TX_BUFFER_SIZE + HEADROOM];
time_t rawtime;
time(&rawtime);
::time(&rawtime);
struct tm timeinfo;
localtime_r(&rawtime, &timeinfo); // Thread-safe version
size_t pos = strftime(buffer, TIMESTAMP_LEN + 1, "[%H:%M:%S]", &timeinfo);
+1 -1
View File
@@ -34,6 +34,6 @@ async def to_code(config: ConfigType) -> None:
levels = list(LOG_LEVELS)
index = levels.index(CORE.data[DOMAIN][CONF_LEVEL])
levels = levels[: index + 1]
var = await select.new_select(config, options=levels)
var = await select.new_select(config, options=levels, fixed_options=True)
await register_parented(var, parent)
await register_component(var, config)
+3 -2
View File
@@ -1,5 +1,6 @@
#include "max44009.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::max44009 {
@@ -80,8 +81,8 @@ float MAX44009Sensor::read_illuminance_() {
}
float MAX44009Sensor::convert_to_lux_(uint8_t data_high, uint8_t data_low) {
uint8_t exponent = data_high >> 4;
uint32_t mantissa = ((data_high & 0x0F) << 4) + (data_low & 0x0F);
uint8_t exponent = high_nibble(data_high);
uint32_t mantissa = (low_nibble(data_high) << 4) | low_nibble(data_low);
return ((0x0001 << exponent) * 0.045) * mantissa;
}
Loaded 100 of 362 files, more files were not shown because too many files have changed in this diff. Show more