| 1 |
# CLAUDE.md — habluetooth |
| 2 |
|
| 3 |
Guide for AI assistants working in this repo. Skim it before editing. |
| 4 |
|
| 5 |
## What this is |
| 6 |
|
| 7 |
`habluetooth` is the Bluetooth core library used by Home Assistant. It wraps |
| 8 |
[`bleak`](https://github.com/hbldh/bleak) with multi-scanner orchestration, |
| 9 |
advertisement tracking, a per-scanner discovery cache, and Cython-compiled hot |
| 10 |
paths. The package is published to PyPI and consumed by Home Assistant plus |
| 11 |
related glue libraries (`bleak-retry-connector`, `bleak-esphome`, |
| 12 |
`bluetooth-adapters`, etc.). |
| 13 |
|
| 14 |
It is **not** a daemon. It runs in-process inside HA's event loop and |
| 15 |
coordinates multiple `BaseHaScanner` instances (local USB/UART adapters via |
| 16 |
BlueZ, ESPHome remote scanners, etc.). |
| 17 |
|
| 18 |
## Layout |
| 19 |
|
| 20 |
``` |
| 21 |
src/habluetooth/ |
| 22 |
manager.py BluetoothManager — central orchestrator, dispatch, scoring |
| 23 |
base_scanner.py BaseHaScanner / BaseHaRemoteScanner — shared scanner logic |
| 24 |
scanner.py HaScanner — local bleak scanner (BlueZ / CoreBluetooth) |
| 25 |
scanner_device.py BluetoothScannerDevice dataclass |
| 26 |
advertisement_tracker.py Per-device advertising interval estimator |
| 27 |
models.py BluetoothServiceInfo(Bleak), HaScannerDetails, enums |
| 28 |
storage.py Discovery-cache (de)serialization — TypedDict ↔ dataclass |
| 29 |
wrappers.py HaBleakClientWrapper / HaBleakScannerWrapper (public API) |
| 30 |
channels/bluez.py Low-level BlueZ raw-advertisement channel (Cython) |
| 31 |
central_manager.py Module-level singleton holder (get_manager / set_manager) |
| 32 |
const.py Timeouts, thresholds, connection-parameter presets |
| 33 |
usage.py, util.py Misc helpers |
| 34 |
tests/ pytest suite (asyncio + freezegun + codspeed) |
| 35 |
docs/ Sphinx documentation (readthedocs) |
| 36 |
build_ext.py Cython build script invoked by Poetry |
| 37 |
``` |
| 38 |
|
| 39 |
Each "hot" module has a paired `.pxd` declaring its Cython attributes. See |
| 40 |
[Cython rules](#cython) below. |
| 41 |
|
| 42 |
## Core concepts |
| 43 |
|
| 44 |
- **BluetoothManager** (`manager.py`) is the single in-process orchestrator. |
| 45 |
It is held by `central_manager.CentralBluetoothManager.manager` and accessed |
| 46 |
via `get_manager()` / `set_manager()`. There is no DI: tests typically set |
| 47 |
it directly. |
| 48 |
- **Scanners** subclass `BaseHaScanner` (with the local-vs-remote split in |
| 49 |
`BaseHaRemoteScanner`). Each scanner reports advertisements to the manager |
| 50 |
via the `_async_on_advertisement` path; the manager dedupes, scores, and |
| 51 |
fans out to registered Bleak callbacks. |
| 52 |
- **Advertisement tracker** (`advertisement_tracker.py`) learns each device's |
| 53 |
advertising interval and feeds expiry decisions. Until it has |
| 54 |
`ADVERTISING_TIMES_NEEDED` samples it uses a fallback timeout. |
| 55 |
- **Wrappers** (`wrappers.py`) — `HaBleakClientWrapper` / |
| 56 |
`HaBleakScannerWrapper` are the _public_ Bleak-compatible facade. External |
| 57 |
callers (HA integrations) talk to these, not to scanners directly. |
| 58 |
- **Allocations** — for proxy scanners (ESPHome) the manager tracks per-source |
| 59 |
slot allocations via `async_on_allocation_changed`. This state is push-only |
| 60 |
and trusted; habluetooth does **not** independently verify slot counts. See |
| 61 |
[Allocations are unverified](#allocations) below. |
| 62 |
|
| 63 |
## Storage / "schema" |
| 64 |
|
| 65 |
There is no SQL. The persistence layer is `storage.py`: |
| 66 |
|
| 67 |
- HA's `Store` writes a JSON blob (`DiscoveryStorageType`) to disk. |
| 68 |
- Round-trip: in-memory timestamps are `time.monotonic()`; on serialize they |
| 69 |
are converted to wall-time via |
| 70 |
`_get_monotonic_time_diff = time.time() - time.monotonic()`, then inverted |
| 71 |
on load. |
| 72 |
- There is **no `version` field** as of 6.1.0. Backward compatibility is |
| 73 |
shape-based (`data.get(KEY, default)` + strip-on-read for removed |
| 74 |
`BLEDevice` fields). If you touch the schema in a load-bearing way, |
| 75 |
consider proposing a version key. |
| 76 |
- `discovered_device_advertisement_data_from_dict` / `..._to_dict` are the |
| 77 |
only legitimate entry points — don't hand-roll the format. |
| 78 |
|
| 79 |
## Cython |
| 80 |
|
| 81 |
`build_ext.py` cythonizes these modules: |
| 82 |
|
| 83 |
``` |
| 84 |
advertisement_tracker.py |
| 85 |
base_scanner.py |
| 86 |
manager.py |
| 87 |
models.py |
| 88 |
scanner.py |
| 89 |
channels/bluez.py |
| 90 |
``` |
| 91 |
|
| 92 |
**Rules:** |
| 93 |
|
| 94 |
1. When changing the attributes of a class declared `cdef class` in a `.pxd`, |
| 95 |
update the matching `.pxd` or the build breaks. |
| 96 |
2. Type annotations in `.py` are advisory; the `.pxd` is authoritative for |
| 97 |
Cython. `cdef public object foo` in `.pxd` corresponds to an instance |
| 98 |
attribute on the Python side. |
| 99 |
3. Set `SKIP_CYTHON=1` to install without compilation (faster local dev, |
| 100 |
matches one half of the CI matrix). Set `REQUIRE_CYTHON=1` to fail if |
| 101 |
compilation fails (matches the other half). |
| 102 |
4. Avoid implicit Cython type narrowing for objects that must remain Python |
| 103 |
types. `models.py` declares `_float = float`, `_str = str`, `_int = int` |
| 104 |
for exactly this reason — use the underscore aliases when you need to |
| 105 |
guarantee a Python object. |
| 106 |
5. Do not annotate a global that is `cdef`-declared in a `.pxd` with |
| 107 |
`typing.Final`; Cython 3.3 crashes on it (cython/cython#7942). |
| 108 |
6. Parameters of `.pxd`-declared functions must not use a subscripted builtin |
| 109 |
whose arguments Cython can resolve (`list[str]`, `dict[str, int]`, |
| 110 |
`set[ActiveScanRequest]`); Cython 3.3 rejects them as incompatible with the |
| 111 |
bare `list`/`dict`/`set` in the `.pxd`. Route them through an alias Cython |
| 112 |
cannot resolve (`list[_str]`, `set[_ActiveScanRequest]`) so the `.pxd` |
| 113 |
type applies and mypy still sees the full type. |
| 114 |
|
| 115 |
## Development workflow |
| 116 |
|
| 117 |
Setup: |
| 118 |
|
| 119 |
```bash |
| 120 |
poetry install # cython build |
| 121 |
SKIP_CYTHON=1 poetry install # pure-python (faster) |
| 122 |
``` |
| 123 |
|
| 124 |
Run tests: |
| 125 |
|
| 126 |
```bash |
| 127 |
poetry run pytest # full suite |
| 128 |
poetry run pytest tests/test_manager.py # single file |
| 129 |
poetry run pytest -k allocation # by keyword |
| 130 |
``` |
| 131 |
|
| 132 |
Lint / format (pre-commit covers ruff, ruff-format, mypy, codespell, prettier, |
| 133 |
poetry-check): |
| 134 |
|
| 135 |
```bash |
| 136 |
pre-commit run -a |
| 137 |
``` |
| 138 |
|
| 139 |
Type checking (strict mypy — see `pyproject.toml`): |
| 140 |
|
| 141 |
```bash |
| 142 |
poetry run mypy src |
| 143 |
``` |
| 144 |
|
| 145 |
Tests use `pytest-asyncio` (no auto-mode — mark coroutines explicitly) and |
| 146 |
`freezegun` for time control. `pytest-codspeed` powers the benchmark file |
| 147 |
(`tests/test_benchmark_base_scanner.py`). |
| 148 |
|
| 149 |
## Coding conventions |
| 150 |
|
| 151 |
- **Python ≥ 3.11**, target `py311` for ruff/black. Code may use 3.11+ |
| 152 |
features (PEP 604 unions, `Self`, etc.). |
| 153 |
- `from __future__ import annotations` at the top of every module. |
| 154 |
- Imports sorted by isort (ruff `I`); first-party = `habluetooth`, `tests`. |
| 155 |
- Black formatting, line length 88. |
| 156 |
- Public API is exported from `habluetooth/__init__.py` — when adding a |
| 157 |
symbol, also add it to `__all__`. |
| 158 |
- Docstrings: ruff enforces `D` rules with a small ignore list (see |
| 159 |
`pyproject.toml`). Module/package/`__init__` docstrings are not required; |
| 160 |
public function/class docstrings are. |
| 161 |
- `mypy` is strict (`disallow_untyped_defs`, `disallow_any_generics`, |
| 162 |
`warn_unreachable`, `warn_unused_ignores`). Tests are exempted via override. |
| 163 |
- Logging: module-level `_LOGGER = logging.getLogger(__name__)`. Never print. |
| 164 |
- No `assert` in production code (ruff `S101`). Tests are exempted. |
| 165 |
|
| 166 |
## Commit / PR conventions |
| 167 |
|
| 168 |
- **Conventional Commits PR title, lowercase subject.** PRs are |
| 169 |
squash-merged, so the **PR title** becomes the commit on `main` and is the |
| 170 |
only string that has to parse as a Conventional Commit. The repo enforces |
| 171 |
this via the `pr-title` CI job in `ci.yml` using |
| 172 |
`amannn/action-semantic-pull-request`. Accepted types: `feat`, `fix`, |
| 173 |
`chore`, `ci`, `docs`, `refactor`, `test`, `perf`, `build`, etc. The |
| 174 |
subject (text after `type(scope):`) must start lowercase (enforced by |
| 175 |
`subjectPattern: ^(?![A-Z]).+$`). Per-commit messages on the PR branch are |
| 176 |
**not** linted; they get collapsed at squash-merge. |
| 177 |
- Releases are fully automated by `python-semantic-release` from the commit |
| 178 |
log. Anything that should land in the changelog must use `feat:` or `fix:` |
| 179 |
(or a breaking-change footer). `chore*` and `ci*` are excluded. |
| 180 |
- The version lives in three places, kept in sync by semantic-release: |
| 181 |
`pyproject.toml`, `src/habluetooth/__init__.py:__version__`, |
| 182 |
`docs/conf.py:release`. **Do not bump versions by hand.** |
| 183 |
- PRs target `main`. CI runs the matrix `{3.11, 3.12, 3.13, 3.14, 3.14t} × |
| 184 |
{linux, macos, windows} × {skip_cython, use_cython}` — flaky breakage in |
| 185 |
one cell usually means a Cython annotation got too aggressive. |
| 186 |
|
| 187 |
## Gotchas <a id="allocations"></a> |
| 188 |
|
| 189 |
- **Allocations are unverified.** `_allocations[source]` is updated solely |
| 190 |
from `async_on_allocation_changed` (called by external glue when a proxy |
| 191 |
reports slot state). habluetooth has no parallel "currently-connected" |
| 192 |
counter and does not cross-check. When a proxy gets stuck, the only |
| 193 |
observable symptom is the per-source score collapsing to `NO_RSSI_VALUE` |
| 194 |
in `wrappers.py`. |
| 195 |
- **`_connect_in_progress` is the only per-scanner "busy" signal.** There is |
| 196 |
no counter of active or completed connections — only "does this scanner |
| 197 |
have a connect attempt in flight right now". |
| 198 |
- **bleak 3.0 deprecations:** |
| 199 |
- `BleakScanner(adapter="hciN")` is gone; use `BleakScanner(bluez={"adapter": |
| 200 |
"hciN"})`. When also passing `PASSIVE_SCANNER_ARGS` (itself a |
| 201 |
`BlueZScannerArgs`), merge — don't overwrite. |
| 202 |
- `BLEDevice(..., rssi=-NN)` is gone; bleak 3.0 only accepts |
| 203 |
`(address, name, details)`. RSSI lives on `AdvertisementData` only. |
| 204 |
- **Test deprecation hygiene:** |
| 205 |
```bash |
| 206 |
pytest tests/ -W "error::DeprecationWarning" \ |
| 207 |
-W "ignore::DeprecationWarning:asyncio" |
| 208 |
``` |
| 209 |
turns each deprecation into a failure (while ignoring asyncio's internal |
| 210 |
ones). |
| 211 |
- **Time source.** Everything in hot paths uses |
| 212 |
`bluetooth_data_tools.monotonic_time_coarse()` — do not mix with |
| 213 |
`time.time()` or `time.monotonic()` except at storage boundaries. |
| 214 |
|
| 215 |
## When in doubt |
| 216 |
|
| 217 |
- Public API contracts live in `__init__.py`'s `__all__` and in `wrappers.py`. |
| 218 |
Breaking those is a major version bump. |
| 219 |
- Internal refactors are fine as long as the public surface, the storage |
| 220 |
schema, and the scanner-callback signatures don't move. |
| 221 |
- Tests are the source of truth for expected behavior — if a test is awkward |
| 222 |
to write, the API probably needs to change, not the test. |