# MajorDom Docs > MajorDom documentation MajorDom is a self-hosted smart-home hub. This documentation covers building device integrations (Matter, Zigbee, HomeKit, etc.) and the Hub/Bridge/Cloud HTTP/WebSocket APIs. # Device Integration # MajorDom Device Integration Guide Under active development MajorDom is still under development.\ The integration structure is now stable, but implementation details are still subject to change. An **integration** is a standalone Python package that bridges MajorDom Hub with IoT devices of a specific protocol or vendor (e.g. HomeKit, Zigbee, Z-Wave). It depends only on the published [`majordom-integration-sdk`](https://pypi.org/project/majordom-integration-sdk/) — not on the Hub source — so it can be developed, tested, and even run on its own. ### Getting started Don't start from a blank folder. Every integration is scaffolded from the **[`integration-template`](https://github.com/MajorDom-Systems/integration-template)** repository: click **Use this template → Create a new repository**, name it `integration-`, and follow the template README's checklist (rename the placeholder package to `majordom_`, `poe install`, wire up CI and PyPI publishing). The template ships a working example controller, tests, and CI, so you replace pieces rather than assemble them from scratch. This guide explains the concepts behind that code. ### Licensing The SDK and the integration template are released under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0): use them freely, for MajorDom integrations or in your own projects, including library mode. We do ask you to keep what you build on them open source. Most official integrations are source-available for noncommercial use. For a commercial license, contact us — we're open to partnership: . ______________________________________________________________________ ### Concepts | Term | Meaning | | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Hub** | The MajorDom Hub core software | | **Integration** | A protocol/vendor-specific plugin | | **Peripheral** | Anything that needs or provides capabilities: a radio, a service, an in-process provider, the integration's controller itself. See [Peripherals](https://docs.majordom.io/integrations/peripherals/index.md) | | **Need** | Something external a peripheral requires: a radio, a server, or a discovery provider (`ZEROCONF`, `UPNP_SSDP`, `BLE_ROUTER`). The runtime binds it and hands it over in `self.peripherals` | | **Discovery Service** | A provider the runtime runs in-process (Zeroconf, SSDP, or the Bluetooth router) that fires raw discovery events. Needed like any other, see [Discovery Services](https://docs.majordom.io/integrations/discovery/index.md) | | **Controller** (capitalized) | The class your integration must implement (`AbstractController` subclass) | | **a controller** (lowercase) | Any third-party device that can control IoT devices (smartphone, Alexa, etc.) | | **Discovery** | A detected, unpaired device that is available to be paired | | **Device** | A paired and controllable device saved in the Hub's database | | **Parameter** | A single controllable or observable property of a device (e.g. brightness, temperature) | A device moves through these states: ```text Invisible → Discoverable (Discovery) → Paired (Device) ``` ______________________________________________________________________ ## Suggested Module Structure Your integration is its own package, `majordom_/` (the template starts you with this — `integration_template/` renamed). An integration will typically need more than just a controller. Recommended minimal layout: ```text majordom_myintegration/ ├── __init__.py # exports peripherals(platform): the controller and the services it brings ├── controller.py # AbstractController subclass — the only required implementation; discovery callbacks and cancel closures are typically stored here too ├── models.py # Typed integration_data schemas for Device and Parameter subclasses, see Storing Data ├── mapper.py # Protocol ↔ MajorDom domain model conversions, isolated from the controller for readability └── parameters_map.py # Supplemental metadata for parameters that the API does not expose, usually in a form of a static dictionary. For example, device might expose min/max limits for a number via device's API, but the unit is only defined in pdf specification. ``` **`controller.py`** is the only required implementation. The rest are a template for keeping the controller clean — separate models, pull out conversion logic into a mapper, add metadata dictionary, etc. Of course, other files can be added as needed. ______________________________________________________________________ ## Implementation Checklist Track it in your repo: the [integration template](https://github.com/MajorDom-Systems/integration-template#progress) README ships this and the [Quality Checklist](https://docs.majordom.io/integrations/quality/index.md) as a fillable copy — tick items there as you implement them. The list below is the reference. - [ ] Discovery registered with the providers it needs — `self.peripherals.instance(ZEROCONF)`, `UPNP_SSDP` and/or `BLE_ROUTER` as appropriate; cancel closures saved and called in `stop` - [ ] Discovery listeners fire when devices are found, and the controller calls `self.output.controller_did_receive_discovery` - [ ] Every reachable paired device reported on start (`self.output.controller_did_connect_device(self, physical_id=...)`): the Hub marked them all unavailable when the integration stopped - [ ] `start_pairing_window` is implemented if the protocol requires an explicit scan mode - [ ] Device pairing (`pair_device` is implemented, and validates the incoming `ProvidedCredentials.type` against `discovery.expected_credentials_options` before using it; fills the draft it is given and returns it, without using the repository or reporting the device; sets `physical_id` and calls `check_device_id` once it is known, never changes the Hub's `id`) - [ ] Device schema is properly mapped: device info, parameter list, and each parameter's metadata are translated to MajorDom's domain model - [ ] Hub → Device control (`send_command` is implemented) - [ ] Device → Hub event subscription (`self.output.controller_did_receive_events` is called on incoming events) - [ ] `identify`, `unpair`, and `fetch` are implemented: `unpair` also rolls back a failed or unsaved pairing (any partial state, reverse order, only what blocks a re-pair, no waiting for the user, safe to call again) and raises `DeviceUnreachableError` when the device can't be reached; `pair_device` sets identity only, `fetch` returns the whole device with its parameters (or `None` when it doesn't answer); both are idempotent (check the device, re-subscribe only if the subscription is gone, bounded time) - [ ] Paired devices going offline/coming back online *while the Hub is running* (not just on reboot) — set `device.available` accordingly, and clear/set `last_error` to match - [ ] Graceful shutdown in `stop` - [ ] Everything external declared as a `Need` — radios, `BLE_ROUTER`, `ZEROCONF`, `UPNP_SSDP`, the services it brings; never raw Bluetooth - [ ] Bound needs read from `self.peripherals`, host facts and storage from `self.platform`, reports sent through `self.output` - [ ] Integration-level problems reported with a stable error id (`IntegrationError`) and resolved when they clear - [ ] **Quality:** once it's functional, the integration meets the [Quality Checklist](https://docs.majordom.io/integrations/quality/index.md) — reliability, tests, and maintainability — before release See [Implementing a Controller](https://docs.majordom.io/integrations/controller/index.md) for details, or [Example Integration](https://docs.majordom.io/integrations/example-integration/index.md) for a narrative walkthrough of the template's controller. The template README mirrors this checklist as its **Progress** list, so you can track your integration against it directly in your repo. ## Running standalone You don't need a running Hub to develop an integration. The SDK ships a dev runner that binds your controller's needs through the SDK runtime, as the Hub does (the Bluetooth router, Zeroconf, SSDP, radios and services), gives it a local repository, starts it, and logs everything it discovers: ```python import asyncio from majordom_integration_sdk.dev import run_controller import majordom_myintegration asyncio.run(run_controller(majordom_myintegration.peripherals)) ``` It needs the runtime extras: `pip install "majordom-integration-sdk[runtime,ble,discovery]"`. Pass `db_path=...` to persist devices across restarts (a file-backed SQLite repository) instead of the default in-memory one. See [Standalone Mode](https://docs.majordom.io/integrations/standalone/index.md) for the interactive CLI, `build_platform` for your own scripts, and running without Docker or radios. ## Testing Integrations run their tests against a virtual/simulated device where possible, so CI doesn't need physical hardware. The SDK's `majordom_integration_sdk.testing` module provides the doubles: `build_test_platform()` wires a `RecordingControllerOutput`, an in-memory repository and temp-dir storage, and `FakeZeroconf`, `FakeSSDP`, `FakeBLERouter` (with `FakeBLESource`s) and `FakeOffers` stand in for the peripherals, so a test can drive your controller and assert on what it reported. The template's `tests/` show the pattern. (Real-hardware validation lives in the Hub, not in the integration package.) ## Notes ### For IP Devices - **Handle IP changes.** DHCP can reassign addresses. Identify devices by a stable ID (MAC, serial, mDNS hostname, domain-provided id) rather than IP. Monitor ip address regularly and keep it up to date. - **Use the Hub's provided discovery.** Need `ZEROCONF`, `UPNP_SSDP` or `BLE_ROUTER` and register through `self.peripherals.instance(ZEROCONF).register(...)`. See [Discovery Services](https://docs.majordom.io/integrations/discovery/index.md). Do not run your own discovery stack. ### For all code - **No hand-typed keys: if a typo breaks it, type it.** Static keys and formatted strings come from typed names, never from a bare string literal repeated where they're used: - the SDK's typed needs, `BLE_ROUTER`, `ZEROCONF` and `UPNP_SSDP`, read back with `self.peripherals.instance(BLE_ROUTER)`; - `SettingsExtraField` for settings fields: `Field(11, json_schema_extra={Extra.read_only: True})`; - `ComposeService` for a service's compose definition; - your own enum or constant for anything else. - **Ids come from one helper each.** Derive device and parameter ids through the SDK helpers or one function of your own, never a format string repeated across the code. It's the same rule as above: a typo makes a second id, and state and automations stop matching. - Error messages and other text meant for people stay plain strings. # Implementing a Controller Start from the template Scaffold your integration from the [`integration-template`](https://github.com/MajorDom-Systems/integration-template) (**Use this template → Create a new repository**), and read the [Example Integration](https://docs.majordom.io/integrations/example-integration/index.md) walkthrough alongside this page — it puts every piece below together in one worked controller. ## AbstractController Overview Your integration's controller subclasses [`AbstractController`](https://github.com/MajorDom-Systems/integration-sdk/tree/develop/majordom_integration_sdk/controller/abstract_controller.py) from the SDK. It is generic over your `Device` and `Parameter` subclasses, your [settings](https://docs.majordom.io/integrations/settings/index.md) model, and the model of the draft a pairing fills (the last two are optional): ```python from majordom_integration_sdk.controller import AbstractController from majordom_integration_sdk.schemas import Device, Parameter class MyController(AbstractController[Device, Parameter]): name = "My Protocol" # optional — auto-derived from the class name ("My") otherwise ... ``` The full form is `AbstractController[TDevice, TParameter, TSettings, TDeviceState]`. `TSettings` defaults to `Any` and `TDeviceState` to `DeviceState`. To type the draft, write `Any` in the settings slot if you have none, and override `device_state_type` (see [Storing Data](https://docs.majordom.io/integrations/storing_data/#integration_data)). ### The `name` and `key` identity `name` is a **class attribute**, shown to the user. It defaults to the class name without `Controller` (`HueController` → `"Hue"`): ```python class MyController(AbstractController[Device, Parameter]): name = "Hue" ``` Its slug is the controller's `key` (`"hue"`). The Hub knows the integration by its key: its devices (`Device.integration`), settings, documents folder, `DISABLE_SERVICES` and `/integrations/{key}/…`. Never rename `name` once released. ### The entry point The integration package exports `peripherals(platform)`: the controller and the services it brings along. The Hub calls it with its `Platform`. ```python def peripherals(platform: Platform) -> list[Peripheral]: return [matterjs_server(), MatterController(platform)] ``` ### Hub → Device Implement all abstract methods defined in [`AbstractController`](https://github.com/MajorDom-Systems/integration-sdk/tree/develop/majordom_integration_sdk/controller/abstract_controller.py) — `start`, `stop`, `pair_device`, `unpair`, `identify`, `fetch`, `send_command`, and the `discoveries` property. The Hub calls these to drive your integration. ### Pairing The Hub pairs a device in two steps: your `pair_device` fills a **draft**, then the Hub saves it. No device record exists while `pair_device` runs. ```python async def pair_device( self, discovery: Discovery, draft: DeviceState, credentials: ProvidedCredentials | None ) -> DeviceState: ... ``` The Hub builds `draft` from what the user entered in the app: name, room, icon, category, note. Its `id` is the Hub's own and read-only: never change it. Its `physical_id` holds the discovery's id as a placeholder, and `integration` is your key. When the user picks an existing record to pair onto, the draft carries that record's data instead, its `id`, `physical_id` and `integration_data` included. The integration decides what in it is stale. You establish the device's identity and trust only: its `physical_id`, `integration_data` (keys, addresses), `available`. Then you return the draft. The Hub saves it, reports the device connected if it is `available`, and calls `fetch`, which gives the device its parameters. So, during `pair_device`: - **Don't use the device repository.** Nothing is saved while pairing. - **Report nothing about this device.** No `controller_did_connect_device`, no events. The Hub reports after it saved the draft. - **Check the physical id early.** As soon as you know it, call `check_device_id` (below), before anything irreversible: it confirms no other record holds this device already. - **Fill `integration_data` before each irreversible step.** A key you are about to set, a node you are about to include: write it to the draft first. It is saved with the device, so you need no storage of your own. If pairing fails, the Hub calls `unpair(draft)` to roll back, and `unpair` can only undo what the draft says ran. - **Just raise on failure.** The Hub's `unpair(draft)` undoes the partial pairing. - **Don't map parameters, read values or subscribe.** Leave `parameters` empty: the Hub calls `fetch` for all of that right after the save. - **Be idempotent.** The user may retry after a failed or rolled-back attempt, with a fresh draft. Bring the device to a known-good paired state from whatever the last attempt left: check each step and redo only what is missing or stale. A device found already paired is confirmed and returned, not refused. - **Raise when you can't pair.** Raise `MissingCredentialsError` before touching the device when the Hub lacks credentials. ```python async def pair_device(self, discovery, draft, credentials): if not discovery.accepts(credentials): raise ValueError("Unsupported or missing credentials for this discovery") serial = await self._client.read_serial(discovery.id) # pseudo, read-only draft.physical_id = self.device_uuid(serial) await self.check_device_id(draft.physical_id, draft) # before anything irreversible draft.integration_data = AcmeDeviceIntegrationData(device_key=new_key) # before the step it describes await self._client.pair(discovery.id, key=new_key) # pseudo, irreversible draft.available = True return draft ``` #### `check_device_id` ```python @final async def check_device_id(self, physical_id: UUID, draft: TDeviceState): ... ``` Optional, but call it. It raises `DeviceIdTakenError` when another record holds `physical_id`, the one you are giving the device. The record the user picked to pair onto (`draft.id`) is not another. The Hub refuses the pairing with that error and does not roll it back, because nothing ran. ```python from majordom_integration_sdk.errors import DeviceIdTakenError error: DeviceIdTakenError error.physical_id # the id in question error.device_id # the Hub id of the record that holds it error.name # the name of the record that holds it error.is_paired # False: a record kept after its device was removed ``` The app uses the record's name and `is_paired` to offer pairing onto that record instead. #### Device ids A device has two ids: - `id` is the Hub's. The Hub assigns it, and you never change it. - `physical_id` is yours: what you look the device up by, in the repository (`repo.get(physical_id=...)`), in events and in `controller_did_connect_device(self, physical_id=...)`. Build it with `device_uuid(s)`, where `s` is a string or bytes unique to that device: a MAC address or a serial number. Build it in one place, a single id-making method, never assembled anew at each call site. A name or an address two devices share gives them the same id, and the second one can't be paired. Never change the `physical_id` of a device that is already paired. #### `unpair` is also the rollback ```python async def unpair(self, device: TDevice): ... ``` The user triggers it to remove a device. The Hub also calls it to roll back, with the draft as `pair_device` left it, at any stage: when `pair_device` raises anything but `DeviceIdTakenError`, and when the Hub fails to save what it returned. So: - Undo everything pairing did, in reverse order: a key set on the device, the pairing it holds, its place on the network or fabric. - Tolerate any partial state: a placeholder `physical_id`, no `integration_data`, a device already reset. - Never wait for the user. Go as far as you can: it is best effort, and the Hub cuts it off after 30 seconds. - Make it safe to call again. On a device already unpaired, or never fully paired, it does nothing more. Talk to the device only: the Hub alone decides whether to delete the record and its `integration_data`. When the device can't be reached, raise `DeviceUnreachableError` and change nothing else. The user sees the original pairing error, not an error from the rollback. When the rollback can't reach the device, the Hub answers `pairing_failed`: "Pairing failed. The device may need a manual factory reset to pair again." #### Removing a device The app removes a device with `DELETE /device/{id}?mode=...`: | `mode` | What happens | | ------------------ | ------------------------------------------- | | `unpair` | calls `unpair`, keeps the record | | `delete` (default) | calls `unpair`, then removes the record | | `forget` | removes the record without calling `unpair` | When `unpair` raises `DeviceUnreachableError`, the Hub answers 409 `device_unreachable`: "Device unreachable. Forget it instead? It might need a manual factory reset to pair again." #### `fetch` reads the whole device ```python async def fetch(self, device: TDevice) -> TDeviceState | None: ... ``` The Hub calls it right after pairing, on a manual refresh, and to revive a device that is unavailable. It is idempotent: - Read the whole device and return it: `device` with its full `parameters` list (ids from `parameter_uuid`, current values) and `available`. The Hub creates the parameters on the first fetch, then compares each one with what it stored: new and gone parameters, changed values. The Hub saves it. Report none of it as events: those are for changes the device starts itself. - Check its event subscription. Subscribe again only if it is gone. Never create a second one. - Finish in bounded time. Return `None` when the device doesn't answer, like a sleeping battery device: it is not a failure, and the Hub keeps what it has. ### Device → Hub Use `self.output` (a `ControllerOutput`), injected by the Hub: ```python # New unpaired device found during discovery await self.output.controller_did_receive_discovery(self, discovery) # An already-discovered (unpaired) device changed its advertisement await self.output.controller_did_update_discovery(self, discovery) # A previously-discovered device is no longer visible await self.output.controller_did_lose_discovery(self, discovery_id) # Device connected; on start, report every paired device that answers. # Never during pair_device: the Hub reports a new device itself once it saved it. # Ids are keyword-only: pass physical_id= (device_id= is for relays passing on the Hub's id) await self.output.controller_did_connect_device(self, physical_id=physical_id) # A paired device became unreachable while the Hub is running await self.output.controller_did_lose_device(self, physical_id=physical_id) # Device reported new parameter values or events; the Hub saves their values await self.output.controller_did_receive_events(self, events) # A user-facing problem with the whole integration — a CTA, or (is_still_running=False) a failure # that leaves it inactive. Plain language for the user; technical detail goes to the logs. await self.output.controller_did_encounter_error( self, IntegrationError("server-unreachable", "The Acme server is unreachable — check that it is running") ) # The problem is gone await self.output.controller_did_resolve_error(self, "server-unreachable") ``` ### `last_error` Both `Discovery` and `Device` carry a `last_error: str | None` field. **The integration owns this field entirely** — the Hub only stores and exposes it. | Situation | Action | | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Connection attempt fails | Set `last_error` to a human-readable message and call the appropriate output method (`controller_did_receive_discovery`, `controller_did_update_discovery`, etc.) | | Device fetch or command fails | Set `discovery.last_error` / `device.last_error` accordingly | | Error is resolved | Set `last_error = None` explicitly — the Hub never clears it automatically | ```python # On failure — surface the error to the user discovery.last_error = "Connection timed out" await self.output.controller_did_update_discovery(self, discovery) # On recovery — clear it explicitly discovery.last_error = None await self.output.controller_did_update_discovery(self, discovery) ``` `Device.last_error` is persisted in the database, so stale errors survive restarts. Make sure to clear it whenever your integration successfully recovers, otherwise the error remains visible until explicitly resolved. The natural places to clear it depend on the error kind — for connection errors, clear on successful connection or successful fetch; for discovery errors, clear when the device re-appears or its advertisement updates successfully. In general: wherever you can confirm the condition that caused the error no longer holds, that's where the `None` assignment belongs. `last_error` is not limited to connection failures — use it for any condition worth surfacing to the user: authentication failures, unsupported firmware versions, misconfiguration, rate limiting, or any other integration-level problem. If the user should see it, put it here. ### `controller_did_encounter_error` `last_error` is *persistent per-device/discovery state* — a flag on one device that stays until you clear it. `controller_did_encounter_error` is complementary: the way to report a **controller-level** problem that isn't tied to a single device. The problem stays active until you resolve it, or until the integration stops or restarts. ```python @dataclass(frozen=True) class IntegrationError: # from majordom_integration_sdk import IntegrationError id: str message: str is_still_running: bool = True async def controller_did_encounter_error(self, controller, error: IntegrationError) -> None: ... async def controller_did_resolve_error(self, controller, error_id: str) -> None: ... ``` - **`id`** — stable per condition, e.g. `"server-unreachable"` or `"stick-unplugged"`: it links the report to its resolve. Reporting an active id again replaces it, so you can report on every failed attempt without piling up duplicates. Several ids can be active at once. Ids are scoped to your integration (the Hub and the app key an error by integration and id), and the `hub-` prefix is reserved for the errors the Hub reports on an integration's behalf. - **`message`** — plain language for the user, never a traceback. Put technical detail in the logs; put here only what the user should see, and fold any call-to-action right into the text. - **`is_still_running`** — `False` when the controller can no longer run. The Hub marks the integration **inactive** and tells the user it failed (and what to do, if actionable) — no technical dump. If the controller was running, the Hub then restarts it; when `start()` raises, it retries after 5, 30 and 120 seconds before it gives up. Keep the default `True` for a problem the integration keeps running through but the user should know about (a lost server it reconnects to, a user-fixable misconfiguration). Call `controller_did_resolve_error` with the id once the condition no longer holds: the connection is back, the user fixed the setup. Resolving an id that isn't active does nothing, so you can resolve after every successful connection. The Hub keeps active errors in memory only (they are not saved) and drops all of an integration's errors when it stops or restarts, so a `is_still_running=False` error is gone once the Hub restarts the integration. #### Which one do I use? There are five places an error can go. Pick by asking who it's for and how long it should stay: | Surface | Use it for | How long it lives | | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | | `Device.last_error` / `Discovery.last_error` | a problem with one device | stays until *you* clear it | | `controller_did_encounter_error` | the whole integration has a problem; `is_still_running=False` = it failed and stopped | until resolved, or the integration restarts | | `DeviceIdTakenError` raised by `check_device_id` | another record already holds the id this pairing would give; see [Device ids](#device-ids) | returned to the app with this pairing attempt | | `DeviceUnreachableError` raised by `unpair` | the device can't be reached to undo its pairing; see [`unpair`](#unpair-is-also-the-rollback) | returned to the app, which offers to forget the device | | `MissingCredentialsError` raised from `pair_device` | the Hub lacks credentials (e.g. Wi-Fi) for one pairing; see [Missing Hub credentials](https://docs.majordom.io/integrations/data_models/#missing-hub-credentials) | returned to the app with this pairing attempt | | any other error raised from `pair_device` | this pairing failed; the Hub rolls it back and returns `pairing_failed` to the app. Don't also set `last_error` or report it with `controller_did_encounter_error` | returned to the app with this pairing attempt | | logs (`logger.*`) | technical detail, for you the developer | log retention | **What about a parameter failing?** Parameters don't have an error field, on purpose. If one parameter fails (a rejected command, an unreadable value), tell the user at the *device* level and name the parameter in the message: `device.last_error = "Brightness could not be set — the device rejected the command"`. Status codes and tracebacks go to the logs. Two habits: - **User surfaces get plain language** — never a traceback or a protocol code. - **One incident usually goes to two places**: a detailed log line for you, plus one user-facing surface. Logs-only is fine only when the user can't see or fix anything. ```python # Recoverable, but the user must act; reported on every failed attempt, it stays one error: await self.output.controller_did_encounter_error( self, IntegrationError("server-unreachable", "Matter server unreachable — check that it is running") ) # ... and once connected again: await self.output.controller_did_resolve_error(self, "server-unreachable") # Fatal — the integration can't continue (the Hub restarts it, which clears the error): await self.output.controller_did_encounter_error( self, IntegrationError("radio-lost", "The Zigbee coordinator is not responding and the integration has stopped.", False), ) ``` ### The `discoveries` property Return your current in-memory cache of unpaired, visible devices. The Hub polls this — do not trigger scanning here. ```python @property def discoveries(self) -> dict[UUID, Discovery]: return self._discoveries # maintained elsewhere, e.g. in a discovery event callback ``` The `UUID` for a given physical device must remain stable as long as it is visible. ### `start_pairing_window(duration_sec, credentials=None)` ```python async def start_pairing_window(self, duration_sec: int, credentials: ProvidedCredentials | None = None) -> None: ... ``` Optional. Override only if your protocol requires an explicit short-lived scan mode to surface new devices (e.g. Zigbee permit-join, BLE burst scan). Always-on discovery (mDNS, SSDP) does not need this. Default is a no-op. `credentials` carries anything the user supplied when opening the window, before any device is discovered — e.g. a Z-Wave SmartStart QR code / DSK. It is `None` when the user gave none. The Hub relays it from `POST start_pairing_window` (target integration in the `integration` query parameter, credentials in the request body). ## What the Hub Gives A controller is a [`Peripheral`](https://docs.majordom.io/integrations/peripherals/index.md). It is constructed as `Controller(platform, settings=None)`; keep these parameters when you override `__init__`. The runtime sets the rest before `start()`. | Attribute | Type | Description | | ------------------ | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | | `self.platform` | `Platform` | The host, frozen and shared by every peripheral: `region`, `wifi`, `thread_dataset`, `documents_folder(self)`, `device_repository(self)` | | `self.output` | `ControllerOutput` | What it reports to the Hub; logs every call in library mode | | `self.settings` | your `Settings` | The validated [settings](https://docs.majordom.io/integrations/settings/index.md); `NoSettings` when you declare none | | `self.peripherals` | `Peripherals` | What your `needs` are bound to, by family | | Call | Returns | | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `self.peripherals.endpoint("zigbee")` | the `Endpoint` bound to that need; `KeyError` while it is unbound | | `self.peripherals.endpoints("zigbee")` | every endpoint bound to an `is_many` need (e.g. several Zigbee sticks), as a list; empty while unbound | | `self.peripherals.instance(BLE_ROUTER)` | the in-process peripheral bound to a typed need (`BLE_ROUTER`, `ZEROCONF`, `UPNP_SSDP`), typed by it; `None` while unbound | Device paths, server URLs, discovery and options all arrive here; see [using a peripheral](https://docs.majordom.io/integrations/peripherals/#tldr-using-a-peripheral) for a full example. Don't read them from environment variables or config files, and don't start your own mDNS, SSDP or Bluetooth stack. Read `self.platform` when you need a fact: a platform you kept holds the old ones. ### Needs and settings `needs` is a class attribute: everything external the controller uses. Settings are a nested `Settings` model, named as the last type parameter. ```python from majordom_integration_sdk import Need class ZigBeeController(AbstractController[Device, Parameter, "ZigBeeController.Settings"]): needs = [Need("zigbee", ZIGPY_DIALECTS)] # ezsp, znp, deconz, xbee, zigate, ziggurat, blz, cc class Settings(BaseModel): channel: int = Field(15, ge=11, le=26, title="Channel") async def start(self): zigbee = self.peripherals.endpoint("zigbee") channel = self.settings.channel ... ``` HomeKit, which only uses the network, needs just `ZEROCONF`. Make a typed need optional with `BLE_ROUTER(is_required=False)`. See [Peripherals](https://docs.majordom.io/integrations/peripherals/index.md) and [Settings](https://docs.majordom.io/integrations/settings/index.md). ### Hooks Each hook is optional and called while the controller runs. Return `True` when you handled the change in place; `False` has the runtime restart the controller. Several can fire at once: the controller restarts unless all return `True`. A hook that raises counts as `False`. | Hook | Called when | Default | | -------------------------------------- | --------------------------------------------------------------------------------------------------- | ------- | | `needed_peripheral_did_change(change)` | a bound need appeared, moved, or an optional one was lost; `self.peripherals` holds the new binding | `False` | | `settings_did_change(before)` | the user changed its settings; `self.settings` holds the new ones | `False` | | `platform_facts_did_change(before)` | region, Wi-Fi or Thread network changed; `self.platform` holds the new ones | `True` | When a **required** need is lost, no hook is called: the runtime stops the controller and starts it again once the need is bound. ```python async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: if change.family == "thread": # optional: Wi-Fi devices keep working without it self._border_router = change.after.url if change.after else None return True return False async def settings_did_change(self, before: Settings) -> bool: if self.settings.channel != before.channel: return False # start() forms the network on the channel: restart return True async def platform_facts_did_change(self, before: Platform) -> bool: return self.platform.region == before.region # start() sets the radio's region ``` ### Staying connected A [service](https://docs.majordom.io/integrations/peripherals/#tldr-bringing-a-docker-service) is recreated when its settings or bindings render it differently, and it may crash and come back. Nobody tells the controller. So don't let one connection live as long as the controller: keep a task that waits for the connection to drop and reconnects with backoff. ```python async def _stay_connected(self): """Reconnects whenever the server goes away, until stop() cancels it.""" while True: await self._client.wait_closed() message = "Lost the connection to the Acme server, reconnecting." await self.output.controller_did_encounter_error(self, IntegrationError("server-unreachable", message)) delay = self._RECONNECT_DELAY while True: await asyncio.sleep(delay) # 1, 2, 4, … 30, 30 seconds try: self._client = await self._connect() break except OSError as error: logger.info(f"The Acme server is not back yet: {error!r}") delay = min(delay * 2, self._RECONNECT_DELAY_MAX) await self.output.controller_did_resolve_error(self, "server-unreachable") ``` `is_still_running=True` (the default) tells the user the integration is degraded, not failed, until the error is resolved. Resolve it only once a connection held for `STABLE_RUN` seconds, so a server that answers and drops every time is still reported. While the connection is down, report the devices you reach through it as lost, and as connected again once it's back. ## Helper Methods `AbstractController` provides these `@final` helpers. Do not override them. ```python @property def key(self) -> str: ... # slug of name; the stable integration identifier def integration_uuid(self) -> UUID: ... # Stable UUID for this integration, derived from key def device_uuid(self, raw: str | bytes) -> UUID: ... # The physical_id of a device from a string unique to it (MAC, serial); devices sharing the string share the id async def check_device_id(self, physical_id: UUID, draft: TDeviceState): ... # Raises DeviceIdTakenError when another record holds the physical id; call it from pair_device def parameter_uuid(self, physical_id: UUID, raw: str | bytes) -> UUID: ... # Stable UUID for a parameter, scoped to its device's physical_id ``` ## See Also - [`integration-template`](https://github.com/MajorDom-Systems/integration-template) — scaffold your repo with **Use this template**, then fill in the controller - [Storing Data](https://docs.majordom.io/integrations/storing_data/index.md) — `integration_data`, typed schemas, file storage, and the device repository - [Data Models Reference](https://docs.majordom.io/integrations/data_models/index.md) — `Discovery`, `Device`, `Parameter`, and related types - [Example Integration](https://docs.majordom.io/integrations/example-integration/index.md) — a full pseudo-code controller putting all of the above together, to copy as a starting point # Peripherals An integration never opens `/dev/ttyUSB0`, starts its own Bluetooth scanner, or reads a server URL from an environment variable. It declares what it **needs**, and the Hub hands it over in `self.peripherals` once something can serve it. The same code then works with any supported stick, a multi-PAN radio, or a server running elsewhere. Everything around an integration is a *peripheral*: a radio, a Bluetooth router, a Docker service, even your controller. Each one `needs` capabilities and `provides` them. A capability is a `family/dialect` pair: the family says what it is (`zigbee`), the dialect how to talk to it (`ezsp`). ## What the SDK provides ### In-process capabilities Objects you call directly. Need them by the SDK's typed needs, from `majordom_integration_sdk.capabilities`. | Need | Capability | What you get | Docs | | ------------ | --------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | `BLE_ROUTER` | `ble/router` | a `BLERouter`: discovery, connections and leases over every Bluetooth radio | [Bluetooth LE](https://docs.majordom.io/integrations/capabilities/ble/index.md) | | `ZEROCONF` | `mdns/zeroconf` | a `Zeroconf` browser (mDNS / DNS-SD) | [Zeroconf](https://docs.majordom.io/integrations/discovery/zeroconf/index.md) | | `UPNP_SSDP` | `upnp/ssdp` | an `SSDP` listener | [SSDP](https://docs.majordom.io/integrations/discovery/ssdp/index.md) | ### Radios USB sticks the Hub recognises, and radios soldered on the Hub's board. You get a serial path (`/dev/serial/by-id/…`) and its serial settings in `params` (`baud`, `flow_control`). | Capability | Radio | | --------------------- | --------------------------------------------- | | `zigbee/ezsp` | Silicon Labs stick with Zigbee firmware | | `thread/spinel` | Silicon Labs stick with Thread (RCP) firmware | | `multipan/silabs-cpc` | Silicon Labs stick with multi-PAN firmware | | `zwave/serial-api` | any Z-Wave stick | Other sticks are recognised by the `UsbDriver`s integrations bring (see [Recognising a stick](#recognising-a-stick-usbdriver)). ### Services Docker services the SDK runs while something needs them. | Service | Needs | Provides | | --------------------------------- | --------------------- | ----------------------------------------------------------------------- | | `otbr` (OpenThread Border Router) | `thread/spinel` | `thread/otbr-rest`: a Thread border router's REST API, shared | | `silabs-multiprotocol` | `multipan/silabs-cpc` | `zigbee/ezsp` over TCP and `thread/otbr-rest`, from one multi-PAN stick | Integrations bring their own services the same way, see [Bringing a Docker service](#tldr-bringing-a-docker-service). ### Host and raw Bluetooth | Capability | What it is | | ------------------------------------------------------ | ---------------------------------------------------------------- | | `ip` | the Hub's network, shared by everyone | | `ble/bluez`, `ble/silabs-cpc-hci`, `ble/esphome-proxy` | raw Bluetooth radios: taken by the router only. Use `BLE_ROUTER` | Facts about the Hub (radio region, Wi-Fi network, Thread network) aren't peripherals: read them from `self.platform`, see [Settings](https://docs.majordom.io/integrations/settings/#hub-settings). [See all peripherals and how they connect →](https://docs.majordom.io/hub/peripherals-map/index.md) ## TL;DR: using a peripheral Declare `needs`, then read what they are bound to in `start()`: ```python from majordom_integration_sdk import AbstractController, Device, Need, Parameter from majordom_integration_sdk.capabilities import BLE_ROUTER class AcmeController(AbstractController[Device, Parameter]): needs = [ Need("zigbee", ["ezsp", "znp"]), # every dialect your library speaks BLE_ROUTER(is_required=False), # optional: works without it ] async def start(self): radio = self.peripherals.endpoint("zigbee") self._client = await connect_radio(radio.dialect, radio.url, baud=radio.params.get("baud")) if router := self.peripherals.instance(BLE_ROUTER): # None while unbound self._cancel_ble = router.register(self, MATCHERS) ``` | Read | Returns | | ------------------------------------ | ----------------------------------------------------------------------------- | | `self.peripherals.endpoint(family)` | the `Endpoint` bound to that need: `url`, `dialect`, `params` | | `self.peripherals.endpoints(family)` | every endpoint of an `is_many` need, as a list | | `self.peripherals.instance(NEED)` | the object of a typed need (`BLE_ROUTER`, `ZEROCONF`, `UPNP_SSDP`), or `None` | Connect to the `url` you're given and never build one yourself: it may point at a stick, a TCP socket, or a server somewhere else. ## TL;DR: bringing a Docker service When your protocol runs behind a server, ship the server with the integration as a `Service`. The Hub runs it in Docker while your controller runs. Z-Wave is the simple case: zwave-js-server opens the stick, and the controller talks to its WebSocket API. ```python from majordom_integration_sdk import AbstractController, Device, Endpoint, Need, Parameter, Peripheral, Platform, Service def zwave_js_server() -> Service: return Service( "zwave-js-server", needs=[Need("zwave", ["serial-api"])], # the stick provides=[Endpoint("zwave", "zwave-js-ws", "ws://127.0.0.1:{ports.api}")], ports={"api": 3000}, # preferred: the Hub picks another one when it's taken compose={ "image": "ghcr.io/kpine/zwave-js-server@sha256:…", # pin by digest "network_mode": "host", "command": ["server", "/dev/zwave", "--host", "{host.listen_address}", "--port", "{ports.api}"], "devices": ["{peripherals.zwave.url}:/dev/zwave"], "volumes": ["{data}:/cache"], "environment": {"RF_REGION": "{platform.region}"}, }, ) class ZwaveController(AbstractController[Device, Parameter]): needs = [Need("zwave", ["zwave-js-ws"])] # what the service provides async def start(self): url = self.peripherals.endpoint("zwave").url # ws://127.0.0.1:3000 ... def peripherals(platform: Platform) -> list[Peripheral]: """The integration's entry point: the Hub runs everything it returns.""" return [zwave_js_server(), ZwaveController(platform)] ``` That's all: the Hub finds the stick, starts the container with the stick's path, waits until its port answers, and starts the controller with the server's URL. Build a new `Service` on every `peripherals()` call. `compose` is a [Docker Compose service](https://docs.docker.com/reference/compose-file/services/) (typed as `ComposeService`). Its strings are templates: | Template | Becomes | | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `{peripherals..url}` | the URL bound to one of the service's needs, e.g. the stick's path; empty while an optional need is unbound | | `{peripherals..params[]}` | a parameter of that endpoint, e.g. `baud` | | `{ports.}` | the host port the Hub picked for that port | | `{data}` | the service's own data folder; mount it to keep state | | `{settings.}` | a field of the service's [settings](https://docs.majordom.io/integrations/settings/#settings-of-a-service) | | `{platform.}` | a Hub fact, e.g. `{platform.region}` | | `{host.listen_address}` | where a host-network service listens: loopback by default. Listen there, never on `0.0.0.0` | | `{host.interface}`, `{host.uid}`, `{host.gid}` | the Hub's network interface; its user and group, for a container that writes its data as the Hub | A format spec renders text by the value: `{x:?text}` renders `text` when `x` isn't empty, `{x:!text}` when it is. A list item that renders empty is left out, so `"volumes": ["{peripherals.ble.url:?/run/dbus:/run/dbus:ro}"]` mounts the system bus only while an adapter is bound. Write `{{` and `}}` for literal braces. The `params` of the endpoints a service provides are templates too: that's how it tells its consumer what it got, e.g. `params={"adapter": "{peripherals.ble.url}"}`. The service may be recreated or crash at any time. Keep the controller [reconnecting](https://docs.majordom.io/integrations/controller/#staying-connected). ## Needs ```python Need(family, dialects=(), is_required=True, is_many=False) ``` - **Dialects**: list every one your client speaks. With none, any dialect of the family is accepted: only for what the host shares, like `Need("ip")`. - **Required** (the default): the controller starts once the need is bound, and stops while it's lost. Meanwhile the app shows the integration as waiting for it. - **Optional** (`is_required=False`): the controller runs without it, and gets it once something can serve it. For a typed need: `BLE_ROUTER(is_required=False)`. - **Many** (`is_many=True`): every matching endpoint, as a list. An endpoint is exclusive by default, as a serial port opens once: the first consumer takes it. A shared one (`is_shared=True`), like a border router or `ip`, serves everyone. ## When a peripheral comes or goes | What happens | The controller | | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | | A required need is lost (stick unplugged, server gone) | is stopped, and started again once it's back | | A need appears or moves, an optional one is lost | gets [`needed_peripheral_did_change()`](https://docs.majordom.io/integrations/controller/#hooks); restarted unless it returns `True` | | Its settings or the Hub's facts change | gets `settings_did_change()` or `platform_facts_did_change()`, the same way | | A service it uses restarts | isn't told: it [reconnects](https://docs.majordom.io/integrations/controller/#staying-connected) itself | ## Bringing peripherals along A controller's `provides` may hold peripherals too: they run while it does. When the list changes, tell the Hub with `await self.output.controller_did_change_provided(self)`. The common case is a Bluetooth proxy: a device with its own Bluetooth radio, lent to the router as a `BLEProxy`. See [Adding a BLE proxy](https://docs.majordom.io/integrations/capabilities/ble/#adding-a-ble-proxy). ## Recognising a stick: `UsbDriver` The Hub recognises Silicon Labs and Z-Wave sticks itself. If your integration talks to a stick directly and it's of another kind, export a `UsbDriver` from `peripherals()`: `identify(path)` returns the firmware the stick runs (or `None` when it isn't yours), and `firmwares` says what each firmware provides, `{device}` being the stick's path. ```python from majordom_integration_sdk import Endpoint, UsbDriver class AcmeDriver(UsbDriver): name = "acme" firmwares = {"acme-zigbee": [Endpoint("zigbee", "acme", "{device}", params={"baud": 115200})]} async def identify(self, path: str) -> str | None: return "acme-zigbee" if await probe_acme(path) else None ``` The Hub asks each driver once per stick. ## Dependency trees The Hub resolves a whole chain of needs on its own: a controller needs a service, the service needs a radio or another service. A few more complex cases, as examples. ### Matter: a service, an optional border router, Bluetooth ```text MatterController needs matter/matter-server, ble/router (optional) ├── matterjs-server the integration's own Service: needs ip, thread/otbr-rest (optional) │ └── otbr the SDK's Service: needs thread/spinel │ └── a Thread stick │ (or silabs-multiprotocol, on a multi-PAN stick) └── the Bluetooth router lent to matterjs-server for commissioning ``` matterjs-server needs only `ip`, so Matter runs on any Hub. Its optional Thread need makes the Hub start a border router whenever a stick can serve one; nothing in the integration says which. The border router tells the Hub the Thread network it formed, and the controller reads it as `self.platform.thread_dataset`. Commissioning over Bluetooth holds a [lease](https://docs.majordom.io/integrations/capabilities/ble/#locking-a-radio-exclusive) for the whole flow. ### Zigbee: one need, many sticks ```text ZigBeeController needs zigbee/ezsp | znp | deconz | … ├── a Zigbee stick zigbee/ezsp at /dev/serial/by-id/… ├── or silabs-multiprotocol zigbee/ezsp at socket://127.0.0.1:9999 │ └── a multi-PAN stick multipan/silabs-cpc └── or another stick recognised by the integration's own UsbDriver, e.g. zigbee/znp ``` The controller reads `self.peripherals.endpoint("zigbee")` and opens whatever it gets: a serial path or a TCP socket, in the dialect it names. Switching from a Zigbee stick to a multi-PAN one needs no change in its code. ## Without the Hub The standalone runner binds peripherals the same way, or lets you pass them yourself. See [Standalone Mode](https://docs.majordom.io/integrations/standalone/#connecting-to-radios-and-services). # Settings Give the user options by declaring a pydantic model. The Hub turns it into a form in the app, stores the values, and hands them to your controller. ## Declaring settings Declare the model as a nested `Settings` class, named as the controller's last type parameter: ```python from pydantic import BaseModel, Field from majordom_integration_sdk import AbstractController, Device, Parameter from majordom_integration_sdk import SettingsExtraField as Extra class AcmeController(AbstractController[Device, Parameter, "AcmeController.Settings"]): class Settings(BaseModel): poll_interval: int = Field(30, ge=5, le=3600, title="Poll interval, seconds") api_token: str = Field("", title="Cloud API token", json_schema_extra={Extra.write_only: True}) firmware: str | None = Field(None, title="Bridge firmware", json_schema_extra={Extra.read_only: True}) ``` The app builds the form from the model's JSON schema. So: - Give every field a `title` and, where it helps, a `description`, in plain language for the user: what it is, and what an empty value does. - Use pydantic constraints (`ge`, `le`, `Literal[...]`). The Hub validates every change against them. - Give every field a default: the Hub creates the settings before the user opens the form. Mark fields with `SettingsExtraField`, never a spelled-out keyword: - `write_only`: the user sets it, and the Hub never shows it again (a secret). An update that leaves it out keeps it. - `read_only`: your controller fills it in itself (`self.settings.firmware = "2.1"`). The user sees it but can't change it. It isn't stored. ## Reading settings The validated instance is `self.settings`, typed by your model. Without a `Settings` class, it is `NoSettings`. ## Defaults are kept The Hub stores the values the first time it reads the settings, defaults included. A `default_factory` runs once, and its result stays: that's how to generate a secret once per Hub, e.g. network keys. ```python api_secret: str = Field(default_factory=lambda: secrets.token_hex(16), title="Secret", json_schema_extra={Extra.write_only: True}) ``` It also means a default you change in a later release applies to new Hubs only. ## Settings of a service A [`Service`](https://docs.majordom.io/integrations/peripherals/#tldr-bringing-a-docker-service) can have settings too. Pass the model as `settings=`, and use its fields in `compose` as `{settings.}`: ```python class ServerOptions(BaseModel): log_level: Literal["info", "debug"] = Field("info", title="Server log level") Service( "acme-server", compose={"image": "…", "environment": {"LOG_LEVEL": "{settings.log_level}"}}, settings=ServerOptions, ) ``` The user sees a service's settings next to the settings of every integration that uses it. ## Changing settings The user changes settings in the app; the Hub validates and stores them, then applies them. A service is recreated. Your controller gets [`settings_did_change(before)`](https://docs.majordom.io/integrations/controller/#hooks): return `True` when you applied them in place, or leave the default (`False`) to be restarted. In [standalone mode](https://docs.majordom.io/integrations/standalone/index.md), pass them to the constructor, `AcmeController(platform, settings=AcmeController.Settings(poll_interval=10))`, or change them through the runtime: `await runtime.update_settings(runtime.peripheral("acme"), {"poll_interval": 10})`. ## Hub settings Some settings belong to the whole Hub. They reach you as facts on `self.platform` (and `{platform.}` in a service's `compose`): | Fact | Meaning | | ------------------------- | -------------------------------------------------------------------------------------------------------- | | `platform.region` | where the Hub is used, for sub-GHz radios, named as Z-Wave JS names them: `Europe`, `USA`, … | | `platform.wifi` | the Wi-Fi network to set new devices up on (`ssid`, `password`), or `None` | | `platform.thread_dataset` | the active dataset of the Hub's Thread network, hex; learned from the border router, not set by the user | When they change, your controller gets [`platform_facts_did_change(before)`](https://docs.majordom.io/integrations/controller/#hooks). Read `self.platform` each time you need a fact: a platform object you kept holds the old values. # Storing Data ## integration_data MajorDom's Device and Parameter schemas expose an `integration_data` field for storing protocol-specific state (pairing tokens, internal IDs, etc.). By default it is an untyped dict persisted as JSON. Integrations can subclass Device/DeviceState and Parameter/ParameterState to declare a typed schema for that field — Hub will then handle (de-)serialization automatically before passing Device instance to Controller's methods or when saving to the database. ```python # majordom_myintegration/models.py from majordom_integration_sdk.schemas.base import Base from majordom_integration_sdk.schemas.device import Device, DeviceState from majordom_integration_sdk.schemas.parameter import Parameter, ParameterState class MyDeviceIntegrationData(Base): pairing_token: str | None = None class MyDevice(Device): integration_data: MyDeviceIntegrationData class MyParameterState(ParameterState): integration_data: MyParameterIntegrationData ``` To make the Hub use these custom types, the integration's Controller must override `device_type` and `parameter_type`: ```python @property def device_type(self) -> type[MyDevice]: return MyDevice @property def parameter_type(self) -> type[MyParameter]: return MyParameter ``` The Hub will deserialize objects into these types before passing them to your implemented methods. The draft that `pair_device` fills is a `DeviceState`. To give it your own `integration_data` schema, subclass `DeviceState` and override `device_state_type` the same way. The Hub validates the draft into it: ```python @property def device_state_type(self) -> type[MyDeviceState]: return MyDeviceState ``` ### Repository Use `self.platform.device_repository(self)`, scoped to your integration's key, to read or persist devices. Not in `pair_device`: it fills the draft and returns it, and the Hub saves it (see [Pairing](https://docs.majordom.io/integrations/controller/#pairing)). Use the repository everywhere else, for example to update a paired device later: ```python async with self.platform.device_repository(self) as repo: device = await repo.get(physical_id=physical_id, as_=MyDevice) # `as_=MyDevice` is optional but provides hassle-free deserialization async with self.platform.device_repository(self) as repo: device.integration_data.some_field = new_value # assuming `MyDevice.integration_data` uses custom class with `some_field` present await repo.save(device) ``` ## File Storage (`documents_folder`) For files that cannot be stored in the database (e.g. a protocol's own SQLite DB, certificates, binary blobs), use `self.platform.documents_folder(self)`: ```python path = self.platform.documents_folder(self) / "zigbee.db" ``` Resolves to a directory for this integration's key under the Hub's data root, created on use. For JSON files, `majordom_integration_sdk.files.read_json` / `write_json` write whole or not at all, readable by the owner only (0600): use them for anything holding secrets. # Data Models Reference ## Pairing ```python class CredentialsType(str, Enum): code = "code" # pin, e.g. 123-45-678 (HomeKit) or 1234-123-1234 (Matter) qr = "qr" # raw QR data secret = "secret" # e.g. AES key like in ESPHome button = "button" # physical confirmation on the device; carries no value none = "none" # pairing needs nothing from the user def with_mask(self, mask: str, hint: str | None = None) -> CredentialsOption: ... def with_hint(self, hint: str) -> CredentialsOption: ... class CredentialsOption(Base): type: CredentialsType mask: str | None = None # D = digit placeholder, other symbols unchanged: "DDD-DD-DDD" for "123-45-678" hint: str | None = None # a short UI prompt, e.g. "Press the button on the device" type CredentialsValue = str class ProvidedCredentials(Base): type: CredentialsType value: CredentialsValue | None = None class Discovery(Base): # technical id: UUID integration: NonEmptyStr expected_credentials_options: list[CredentialsOption] expiration: datetime | None = None # for UX transport: NonEmptyStr device_manufacturer: str | None device_name: NonEmptyStr device_category: str | None device_icon: str | None last_error: str | None = None # set by the integration on failure, cleared (None) on recovery def accepts(self, credentials: ProvidedCredentials | None) -> bool: ... # no credentials count as `none` ``` A discovery advertises every way it can actually be paired — `expected_credentials_options` — since a device can support more than one simultaneously (e.g. a Matter device with both a QR code and a manual pairing code). List every option the device supports, in the order you'd like the app to prefer them. `with_mask()` and `with_hint()` are the short form of `CredentialsOption(type=..., mask=..., hint=...)`; a bare type is an option without mask or hint: ```python Discovery( ..., expected_credentials_options=[ CredentialsType.code.with_mask("DDD-DD-DDD", hint="On the box"), CredentialsType.button.with_hint("Press the button on the device"), CredentialsType.qr, ], ) # on the wire: [{"type": "code", "mask": "DDD-DD-DDD", "hint": "On the box"}, {"type": "button", ...}, ...] ``` | Type | The user... | `ProvidedCredentials.value` | | -------- | ---------------------------------------------------------- | --------------------------- | | `code` | types a setup code, formatted by `mask` | the code | | `qr` | scans a setup QR code | the raw QR payload | | `secret` | enters a key (e.g. an ESPHome API encryption key) | the key | | `button` | physically confirms on the device (Improv, a setup button) | none: a confirmation step | | `none` | does nothing; pairing needs no input | none | For example, ESPHome offers both `none` and `secret` for a node the Hub already gave a key to earlier: `none` pairs with the key the Hub kept, `secret` covers a node reflashed with its own key. Pairing requests then send back `ProvidedCredentials`, pairing the actual value with which type it is, instead of a bare string. **Your `pair_device()` must validate the supplied type against the discovery's options before using it** — `discovery.accepts(credentials)` does it. Don't trust `discovery.credentials` from whatever your own discovery-time heuristic guessed; validate against what the caller explicitly asserts. ### Missing Hub credentials When the Hub itself lacks something a pairing needs (a Hub on Ethernet has no Wi-Fi to give a node set up over BLE), raise `MissingCredentialsError(type)` from `pair_device` **before touching the device**. No record is created and the Hub returns the error to the app, which asks the user for the credentials and retries (see `POST /device` in the [Hub API reference](https://docs.majordom.io/hub/api/index.md)). ```python from majordom_integration_sdk.errors import MissingCredentialsError error = MissingCredentialsError(MissingCredentialsError.WIFI) # "wifi" is the default str(error) # "Missing credentials: wifi" ``` `type` is a lower_snake_case string, so an integration can add its own and documents it; the app maps it to the screen to show. | `type` | The Hub lacks... | | -------- | ---------------------------------------------------- | | `wifi` | a Wi-Fi network (SSID and password) to give a device | | `thread` | a Thread network (dataset) to give a device | ESPHome raises `wifi` for a BLE (Improv) discovery when the Hub has no Wi-Fi to give. ## Device ```python class DeviceInfo(DevicePatch): id: UUID name: str note: str = "" icon: str | None = None category: str | None = None room_id: UUID transport: str integration: str manufacturer: str | None last_seen: datetime | None = None available: bool = False last_error: str | None = None # persisted; set by the integration on failure, cleared (None) on recovery main_parameter: UUID | None = None # for the tap action on the room view, toggle in most cases class Device(DeviceInfo): physical_id: UUID # the integration's lookup id (device_uuid of a serial or MAC); `id` is the Hub's integration_data: SerializeAsAny[dict | Base] = Field(default_factory=Base) class DeviceState(DeviceInfo): parameters: list[ParameterState] ``` ## Parameter ```python class ParameterDataType(StrEnum): none = "none" # e.g. button bool = "bool" integer = "integer" decimal = "decimal" # python float enum = "enum" # integer with string representation string = "string" struct = "struct" # multi-field object (e.g. command arguments); see "Commands with arguments" data = "data" # binary data, base64 encoded at high level class ParameterUnit(StrEnum): plain = "plain" percentage = "percentage" second = "second" hertz = "hertz" kilogram = "kilogram" arcdegree = "arcdegree" meters = "meters" mps = "mps" # meters per second mps2 = "mps2" # meters per second squared rpm = "rpm" newton = "newton" joule = "joule" watt = "watt" celsius = "celsius" kelvin = "kelvin" volt = "volt" ampere = "ampere" lux = "lux" pascal = "pascal" ppm = "ppm" # parts per million, air quality bytes = "bytes" bps = "bps" # bytes per second class ParameterRole(StrEnum): sensor = 'sensor' # read-only control = 'control' # read-write event = 'event' # fire-and-forget class ParameterVisibility(StrEnum): user = "user" # main, everyday interaction, device screen widgets (on/off, brightness, volume) setting = "setting" # user-configurable but behind am extra "settings"/"advanced" tap: configured once and rarely touched again; or diagnostic readings (RSSI, firmware version) system = "system" # hidden under-the-hood wirings; not visible to the user # Generic over its value type V — value, valid_values keys, and default_value all share V # (an int parameter has int labels and an int default; a str parameter is str throughout). class Parameter[V](UUIdentifable): id: UUID name: str description: str | None = None # manufacturer-provided, read-only note: str | None = None # user-editable, MajorDom-side only data_type: ParameterDataType unit: ParameterUnit = ParameterUnit.plain role: ParameterRole visibility: ParameterVisibility min_value: int | float | None = None max_value: int | float | None = None min_step: int | float | None = None # smallest increment for a numeric parameter valid_values: dict[V, str] | None = None # allowed values → labels; for enums (numbers: use min/max/step) fields: list["Parameter"] | None = None # sub-parameters for data_type=struct (e.g. command args) default_value: set[V] | V | None = None # main-parameter tap value(s): one = button, a set = cycle integration_data: Any # protocol-specific payload, opaque to the Hub @property def can_be_main_parameter(self) -> bool: return self.visibility == ParameterVisibility.user and bool( self.data_type in (ParameterDataType.bool, ParameterDataType.none) or self.default_value is not None or self.valid_values ) class ParameterState[V](Parameter[V]): value: V | None = None # pythonic value (int/bool/str/float/dict/...), not bytes ``` ### `main_parameter` and `default_value` `Device.main_parameter` points at the one `Parameter` behind the room-tile tap (a toggle in most cases — e.g. `OnOff` for a light, not `Brightness`). A parameter is eligible (`can_be_main_parameter`) when it's `user`-visible and a tap does something meaningful: a `bool` or `none` command inherently, an `enum` through its `valid_values`, or — for any data type — a `default_value`. `default_value` is what makes an arbitrary parameter tappable (any data type) and curates what a tap sends — set it to one value for a button, or a set for a cycle (e.g. brightness `{0, 80}` so a dimmer taps like an on/off switch). It shares the parameter's value type `V`. (`valid_values` only *describes* a parameter's allowed values and their labels — it doesn't carry the tap value.) See [Parameter UX](https://docs.majordom.io/integrations/parameter-ux/#the-one-tap-main-parameter) for how each case behaves on tap and how to pick the main parameter and good visibility. ### Commands with arguments Some integrations (e.g. Matter) expose commands that take a list of arguments — for those, the command itself is modeled as a `Parameter` and each of its arguments as a nested `Parameter` in `fields`: **command = parameter, argument = sub-parameter**. This is a convention on top of the generic schema, not a separate concept. If your integration's commands don't take structured arguments, you leave `fields` unset. # Example Integration This page is a **narrative walkthrough** of the example controller that ships in the [`integration-template`](https://github.com/MajorDom-Systems/integration-template) repository. The template is the source of truth for the actual, CI-verified code — start there with **Use this template**, then read this page to understand *why* each piece looks the way it does. The example isn't real protocol code — there's no such thing as "AcmeProtocol" or "AcmeClient". Every piece that would normally come from a real device library is marked `# pseudo` so you know it's made up. Everything else — module layout, method names, signatures, how the pieces call into each other — matches the real SDK interfaces described in [Implementing a Controller](https://docs.majordom.io/integrations/controller/index.md), [Storing Data](https://docs.majordom.io/integrations/storing_data/index.md), and [Data Models Reference](https://docs.majordom.io/integrations/data_models/index.md). Read this page *alongside* those, not instead of them. If this is your first integration, don't worry about understanding every line the first time through. Scaffold from the template, rename `Acme` to your protocol, and start replacing the `# pseudo` bits with calls into your actual device library one at a time. More examples This page is a *pedagogical* walkthrough. For real, production integrations to learn from — HomeKit, Zigbee, Matter, and more — browse the official MajorDom integrations at [github.com/orgs/MajorDom-Systems/repositories?q=integration-](https://github.com/orgs/MajorDom-Systems/repositories?q=integration-). ## The controller at a glance Before the details, here's the whole shape of a finished controller — every method you implement, in one place. Bodies are elided (`...`); the sections group them by direction of data flow. If you're new to OOP or SDKs, read this as the "table of contents" for the rest of the page. ```python class MyController(AbstractController[MyDevice, MyParameter]): name = "My Protocol" # optional — auto-derived from the class name otherwise # ── Lifecycle ──────────────────────────────────────────────────────────── async def start(self) -> None: ... # connect, start discovery, restore already-paired devices async def stop(self) -> None: ... # cancel tasks, stop discovery, close connections # ── Discovery (Device → Hub) ──────────────────────────────────────────── @property def discoveries(self) -> dict[UUID, Discovery]: ... # cached snapshot of unpaired devices # when a device appears, call: # await self.output.controller_did_receive_discovery(self, discovery) # ── Pairing ────────────────────────────────────────────────────────────── async def start_pairing_window(self, duration_sec: int, credentials=None) -> None: ... # optional (e.g. Zigbee) async def pair_device(self, discovery, draft, credentials) -> DeviceState: ... # fill the draft: commission, identity only async def unpair(self, device: MyDevice) -> None: ... # also the rollback of a failed pairing # ── Control & read (Hub → Device) ─────────────────────────────────────── async def send_command(self, command, device, parameter) -> None: ... # set a value / run command async def fetch(self, device: MyDevice) -> DeviceState | None: ... # read the whole device + re-subscribe async def identify(self, device: MyDevice) -> None: ... # blink / beep the device # ── Events (Device → Hub) ─────────────────────────────────────────────── # on an incoming device update, call: # await self.output.controller_did_receive_events(self, [DeviceParameterChange(...)]) ``` ## Module Layout Your integration is a standalone package (`majordom_/`), scaffolded from the template: ```text majordom_acme/ ├── __init__.py # exports peripherals(platform): [AcmeController(platform)] ├── controller.py # AbstractController subclass — the only file the Hub actually calls into ├── models.py # typed integration_data schemas — what MajorDom persists to disk for you └── mapper.py # protocol <-> MajorDom conversions — pure functions, no I/O ``` ## `models.py` — typed `integration_data` `integration_data` is a free-form field MajorDom lets every integration attach to its own `Device`/`Parameter` records, for protocol-specific bookkeeping (an auth token, an internal id, etc.). Subclass the SDK schemas to give it a typed shape — the Hub then (de)serializes it for you. Here we remember the device's network **hostname** (not IP — see the discovery note below) and an auth token the Acme protocol handed us during pairing: ```python from majordom_integration_sdk.schemas.base import Base from majordom_integration_sdk.schemas.device import Device, DeviceState from majordom_integration_sdk.schemas.parameter import Parameter, ParameterState class AcmeDeviceIntegrationData(Base): device_hostname: str # a hostname, resolved to the current IP by the OS auth_token: str | None = None class AcmeParameterIntegrationData(Base): acme_property_name: str # the name Acme's own API uses for this property # Device/DeviceState and Parameter/ParameterState are pairs: the "State" version carries the # same fields plus the actual live value(s). You need both — see Storing Data for why. class AcmeDevice(Device): integration_data: AcmeDeviceIntegrationData class AcmeDeviceState(DeviceState): integration_data: AcmeDeviceIntegrationData class AcmeParameter(Parameter): integration_data: AcmeParameterIntegrationData class AcmeParameterState(ParameterState): integration_data: AcmeParameterIntegrationData ``` To make the Hub hand you these subclasses (with `integration_data` already parsed), the controller overrides `device_type`/`parameter_type` — see [Storing Data](https://docs.majordom.io/integrations/storing_data/#integration_data). ## `mapper.py` — pure conversions Keep protocol↔domain conversions here: pure functions that turn "whatever your device library gives you" into MajorDom's `Parameter`/`Device` types. No I/O, no `self.platform`, nothing that touches the network or database — so you (or a test) can call them directly without a real device. A property's `kind` maps to a `ParameterDataType`; whether it's `writable` maps to `ParameterRole.control` vs `ParameterRole.sensor`: ```python from majordom_integration_sdk.schemas.parameter import ParameterDataType, ParameterRole, ParameterVisibility from .models import AcmeParameter, AcmeParameterIntegrationData class AcmeMapper: def parameter_from_acme_property(self, parameter_id, acme_property: dict) -> AcmeParameter: data_type = ParameterDataType.bool if acme_property["kind"] == "bool" else ParameterDataType.integer role = ParameterRole.control if acme_property["writable"] else ParameterRole.sensor return AcmeParameter( id=parameter_id, name=acme_property["name"], data_type=data_type, role=role, visibility=ParameterVisibility.user, # show on the device's main screen; see Data Models for setting/system integration_data=AcmeParameterIntegrationData(acme_property_name=acme_property["name"]), ) ``` `device_uuid`/`parameter_uuid` are helpers on `AbstractController` ([Helper Methods](https://docs.majordom.io/integrations/controller/#helper-methods)) — call them from the controller and pass the resulting ids into the mapper, since the mapper has no access to `self`. ## `controller.py` — the walkthrough The package's `peripherals(platform)` builds the controller. It declares its identity as a **class attribute** and subclasses the generic `AbstractController`: ```python from majordom_integration_sdk import DeviceUnreachableError from majordom_integration_sdk.capabilities import ZEROCONF from majordom_integration_sdk.controller import AbstractController from .models import AcmeDevice, AcmeParameter class AcmeController(AbstractController[AcmeDevice, AcmeParameter]): name = "Acme" # shown to the user; its slug "acme" is the key needs = [ZEROCONF] # Acme devices announce themselves over mDNS _mapper = AcmeMapper() # stateless, so one shared instance is fine ``` ### Lifecycle: `start` / `stop` `start()` runs once its needs are bound (at boot, when enabled, after a restart); `stop()` on shutdown or before a restart. Two things happen in `start()`: register for discovery (keep the returned **cancel closure** for `stop`), and — crucially — **reconnect to already-paired devices**. On every Hub restart, `start()` is your only chance to do that; skip it and paired devices look "stuck" until re-paired. `controller_did_connect_device` isn't just for "just finished pairing" — call it any time a device becomes reachable, including here at boot, to flip `device.available` back to `True`: ```python async def start(self): self._discoveries = {} self._subscriptions = {} # physical id -> cancel closure self._client = AcmeClient() # pseudo self._cancel_discovery = self.peripherals.instance(ZEROCONF).register(self, {"_acme._tcp.local."}) async with self.platform.device_repository(self) as repo: for device in await repo.get_all(as_=AcmeDevice): # scoped to this integration's key self._subscribe(device) await self.output.controller_did_connect_device(self, physical_id=device.physical_id) async def stop(self): self._cancel_discovery() await self._client.close() # pseudo ``` ### Discovery callbacks: identify by hostname, never by IP Zeroconf (`self.peripherals.instance(ZEROCONF)`) calls three listener methods (`zeroconf_did_discover_service`, `..._update_service`, `..._remove_service`) because you passed `self` to `register()`. Derive the **stable** discovery id from `info.name` (the mDNS instance name), which stays constant across discover/update/remove for the same physical device — **not** from its IP address: > If you keyed the id off the IP, a routine DHCP lease renewal would change the address and the Hub would think a *brand-new* device appeared instead of recognizing the one it already knew. Storing a **hostname** in `integration_data` (rather than an IP) sidesteps this entirely: the OS resolves the hostname to the current IP for you, so a paired device changing IP requires no work at all. If you must store an IP, you'd have to update it *and* re-verify reachability on every update event. `_update_service` only reports a device still in your `discoveries` dict (an unpaired device whose advertisement changed); `_remove_service` gives you only `name`, so pop by the same derived id and call `controller_did_lose_discovery`. ### `pair_device`: fill the draft The Hub builds a **draft** from what the user entered (name, room, icon) and hands it to you with the discovery. You fill it in and return it. The Hub saves it, so you don't touch the repository and you report nothing about the device yet. **Always validate** that the credentials actually sent match the discovery's advertised options — never trust your own discovery-time guess: ```python async def pair_device( self, discovery: Discovery, draft: DeviceState, credentials: ProvidedCredentials | None ) -> DeviceState: if not credentials or credentials.type not in discovery.expected_credentials_options: raise ValueError("Unsupported or missing credentials for this discovery") serial = await self._client.read_serial(discovery.id) # pseudo, read-only draft.physical_id = self.device_uuid(serial) # your lookup id; draft.id is the Hub's, never change it await self.check_device_id(draft.physical_id, draft) # raises DeviceIdTakenError: nothing irreversible ran yet ... ``` The device now has its `physical_id`, distinct from its (temporary) discovery id. Build it from the serial number, a string unique to that device. A name or an address two devices share would give them the same id. `check_device_id` raises `DeviceIdTakenError` when another record already holds the id, so the user gets a clear refusal and the device is left untouched. Now the irreversible step. Write what it changes to `integration_data` **first**, then run it. If anything fails, the Hub calls `unpair(draft)`, which reads the draft to know what to undo. Pairing must also be idempotent: a retry may find the device as an earlier attempt left it, so reuse a key the draft already carries instead of refusing: ```python known = draft.integration_data.session_key if draft.integration_data else None # pseudo: pairing onto a record key = known or new_session_key() # pseudo draft.integration_data = AcmeDeviceIntegrationData(device_hostname=hostname, session_key=key) await self._client.pair(discovery.id, code=credentials.value, session_key=key) # pseudo, irreversible; a no-op when already paired with this key draft.available = True return draft ``` Don't map parameters, call `_subscribe` or `controller_did_connect_device` here. The Hub saves the draft, reports the device connected, and then calls `fetch`, which reads the parameters and subscribes. ### `unpair`: also the rollback `unpair` tells the device to forget the pairing (the Hub removes its own record). It is also what the Hub calls to roll back a failed pairing, or one it failed to save, with the draft as you left it. So it must cope with a draft at any stage (no `integration_data`, a device already reset), undo everything pairing did in reverse order, never wait for the user, and be safe to call again. It talks to the device only: when the device can't be reached, raise `DeviceUnreachableError` and change nothing else. The app then offers the user to forget the device, which only the Hub does. ```python async def unpair(self, device: AcmeDevice): data = device.integration_data if data is None: # pair_device failed before the irreversible step: nothing to undo return self._unsubscribe(device) # stop listening; a no-op when not subscribed try: await self._client.forget(data.device_hostname, session_key=data.session_key) # pseudo; a no-op when already forgotten except AcmeError as error: # pseudo: the device is gone raise DeviceUnreachableError(f"{device.physical_id} is unreachable") from error ``` ### `identify` / `fetch` Thin wrappers over your client: `identify` makes the device blink/beep so the user can find it. `fetch` reads the whole device, and it is safe to call any number of times. It reads every parameter with its current value and returns the device with them: the Hub saves them and tells the app what changed. It checks the subscription and subscribes again only if it is gone, never twice. A sleeping battery device that doesn't answer returns `None`: not a failure. ```python async def fetch(self, device: AcmeDevice) -> AcmeDeviceState | None: try: properties = await asyncio.wait_for(self._client.get_properties(device.integration_data.device_hostname), 10) # pseudo except TimeoutError: return None if device.physical_id not in self._subscriptions: self._subscribe(device) parameters = self._mapper.parameters(self, device.physical_id, properties) # pseudo: with their current values return AcmeDeviceState(**device.model_dump(), parameters=parameters, available=True) ``` ### `send_command`: Hub → device Called when the user changes something in the app. `command.value` is the new value; `parameter` tells you which property — look up the protocol's own name from your `integration_data`: ```python async def send_command(self, command: DeviceCommand, device: AcmeDevice, parameter: AcmeParameter): await self._client.set_property( device.integration_data.device_hostname, parameter.integration_data.acme_property_name, command.value, ) # pseudo ``` ### `_subscribe`: device → Hub Called once per device — from `fetch` after pairing and once per already-paired device at boot. Whenever the device's own state changes, report it. Because protocol callbacks are usually plain (non-async), you schedule the async report as a task: ```python from majordom_integration_sdk.schemas.event import DeviceParameterChange def _subscribe(self, device: AcmeDevice): def on_property_changed(acme_property_name: str, value): event = DeviceParameterChange( physical_id=device.physical_id, parameter_id=self.parameter_uuid(device.physical_id, acme_property_name), value=value, ) asyncio.create_task(self.output.controller_did_receive_events(self, [event])) def on_availability_changed(is_available: bool): # Optional mid-session availability: report only if your protocol can detect a *paired* # device dropping/returning while the Hub runs. If it can't, omit this entirely. cb = (self.output.controller_did_connect_device if is_available else self.output.controller_did_lose_device) asyncio.create_task(cb(self, physical_id=device.physical_id)) self._subscriptions[device.physical_id] = self._client.subscribe( device.integration_data.device_hostname, on_property_changed=on_property_changed, on_availability_changed=on_availability_changed, ) # pseudo: returns a cancel closure; `_unsubscribe` pops it and calls it ``` ## What's Deliberately Left Out The example skips a few things your real integration will likely need, so it doesn't obscure the shape of the interface itself: - **Error handling** — set `discovery.last_error` / `device.last_error` on failures (see [Implementing a Controller: `last_error`](https://docs.majordom.io/integrations/controller/#last_error)). - **`start_pairing_window`** — only implement it if your protocol needs an explicit, short-lived scan mode (Zigbee permit-join, BLE burst scan). Always-on discovery (mDNS, SSDP) doesn't need it. - **Retry/backoff, connection pooling, rate limiting** — whatever your protocol's client needs; the SDK prescribes nothing here. - **Implementing the protocol yourself** — the example assumes `AcmeClient` already exists as a high-level SDK (`pair`, `get_properties`, `set_property`, ...). Real protocols don't always have one; if yours doesn't, you may implement the transport, connection management, and serialization directly inside your integration. That's expected. The framework (`AbstractController`, the discovery peripherals, the `Device`/`Parameter` models) is deliberately independent of any protocol's implementation details — and, the discovery providers and data models in particular being plain public SDK, can be reused standalone (e.g. to build a protocol library outside MajorDom entirely). ## Testing Test your controller against simulated devices with the SDK's `majordom_integration_sdk.testing` doubles — `build_test_platform()` plus `RecordingControllerOutput`, and `FakeZeroconf` for the `ZEROCONF` need — rather than real hardware. See [Testing](https://docs.majordom.io/integrations/#testing) and the template's own `tests/` for the pattern. # Discovery Services Discovery services tell your controller when devices appear, change or go away, over mDNS, SSDP or Bluetooth. Need them by the SDK's typed needs (`majordom_integration_sdk.capabilities`) and read the bound one with `self.peripherals.instance(ZEROCONF)`. They share one listener pattern, and your integration never runs its own mDNS, SSDP or BLE scanner. Three are available: | Capability | Need | Contract | Protocol | | --------------- | ------------ | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `mdns/zeroconf` | `ZEROCONF` | [`Zeroconf`](https://docs.majordom.io/integrations/discovery/zeroconf/index.md) | mDNS / DNS-SD | | `upnp/ssdp` | `UPNP_SSDP` | [`SSDP`](https://docs.majordom.io/integrations/discovery/ssdp/index.md) | UPnP SSDP | | `ble/router` | `BLE_ROUTER` | [`BLERouter`](https://docs.majordom.io/integrations/discovery/ble/index.md) | Bluetooth Low Energy, through every radio the hub has; for everything else over BLE see [Bluetooth LE](https://docs.majordom.io/integrations/capabilities/ble/index.md) | The contracts (interfaces and info types only) live in [`majordom_integration_sdk.capabilities`](https://github.com/MajorDom-Systems/integration-sdk/tree/develop/majordom_integration_sdk/capabilities). See [Peripherals](https://docs.majordom.io/integrations/peripherals/index.md) for needs in general. ## Common Pattern All three services share the same usage contract: - Call `register(...)` to subscribe. It returns a **cancel closure**. - Store the cancel closure and call it in your controller's `stop()`. - The runtime starts and stops them — do not call `start()` or `stop()` on them yourself. - Make the need optional, `BLE_ROUTER(is_required=False)`, when the integration works without it: a hub without Bluetooth then still runs it, with `instance(BLE_ROUTER)` returning `None`. ______________________________________________________________________ ## Combining Multiple Discovery Services A controller can register with multiple discovery protocols simultaneously, or with a few service types using the same protocol. Usage doesn't change. ```python from majordom_integration_sdk.capabilities import BLE_ROUTER, ZEROCONF needs = [ZEROCONF, BLE_ROUTER] async def start(self): self._cancels: set[Callable[[], None]] = set() self._cancels.add(self.peripherals.instance(ZEROCONF).register( self, {"_myprotocol._tcp.local."} )) self._cancels.add(self.peripherals.instance(BLE_ROUTER).register( self, {MY_SERVICE_UUID} )) async def stop(self): for cancel in self._cancels: cancel() ``` # Bluetooth (BLE) Discovery Never access Bluetooth hardware directly Never access Bluetooth hardware directly via bluez, bleak or other Python libraries, system services, or any other way. For Bluetooth discovery, always use `BLERouter` as described below. For the full BLE specification with other usage, e.g. pairing and controlling devices, see [Capabilities: Bluetooth LE](https://docs.majordom.io/integrations/capabilities/ble/index.md). The router hears every Bluetooth radio the hub has. You tell it which devices you are interested in, and it calls your controller when one appears, changes its advertisement, or goes away. ## Example Everything a controller needs for BLE discovery. Copy it and change the three numbered lines: ```python from uuid import UUID from majordom_integration_sdk import AbstractController, Device, Discovery, Parameter, Platform from majordom_integration_sdk.capabilities import BLE_ROUTER, BLEDiscoveryInfo, BLEMatcher, BLERouter from majordom_integration_sdk.schemas import CredentialsOption, CredentialsType # 1. Which devices to hear about: here, everything advertising this service UUID MATCHERS = [BLEMatcher(service_uuid=UUID("0000fd00-0000-1000-8000-00805f9b34fb"))] class AcmeController(AbstractController[Device, Parameter]): needs = [BLE_ROUTER] # the Hub hands the router over in self.peripherals def __init__(self, platform: Platform, *, settings=None): super().__init__(platform, settings=settings) self._discoveries: dict[UUID, Discovery] = {} async def start(self): ble = self.peripherals.instance(BLE_ROUTER) self._cancel_ble = ble.register(self, MATCHERS) async def stop(self): self._cancel_ble() @property def discoveries(self) -> dict[UUID, Discovery]: return self._discoveries.copy() # BLEDiscoveryListener: called by the router async def ble_did_discover_device(self, ble: BLERouter, info: BLEDiscoveryInfo): discovery = self._to_discovery(info) self._discoveries[discovery.id] = discovery await self.output.controller_did_receive_discovery(self, discovery) async def ble_did_update_device(self, ble: BLERouter, info: BLEDiscoveryInfo): discovery = self._to_discovery(info) self._discoveries[discovery.id] = discovery await self.output.controller_did_update_discovery(self, discovery) async def ble_did_remove_device(self, ble: BLERouter, info: BLEDiscoveryInfo): discovery_id = self._discovery_id(info) if self._discoveries.pop(discovery_id, None): await self.output.controller_did_lose_discovery(self, discovery_id) def _discovery_id(self, info: BLEDiscoveryInfo) -> UUID: # 2. A stable id from the advertisement's content, e.g. a serial number in the manufacturer data serial = info.advertisement.manufacturer_data[0xFFFF].hex() return self.device_uuid(serial) def _to_discovery(self, info: BLEDiscoveryInfo) -> Discovery: return Discovery( id=self._discovery_id(info), integration=self.key, expected_credentials_options=[CredentialsOption(type=CredentialsType.none)], transport="BLE", device_manufacturer="Acme", # 3. What the user sees device_name=info.advertisement.local_name or "Acme sensor", device_category=None, device_icon=None, ) # pair_device, send_command and the rest: see Implementing a Controller ``` Don't build ids from the address Many devices rotate their Bluetooth address, and each radio may report a different one. Derive the discovery id from the advertisement's content: a serial number, a MAC address inside the manufacturer data, Matter's discriminator with its vendor and product ids. If your integration also works without Bluetooth, make the need optional and check for `None`: ```python needs = [BLE_ROUTER(is_required=False)] async def start(self): ble = self.peripherals.instance(BLE_ROUTER) # None on a hub without Bluetooth self._cancel_ble = ble.register(self, MATCHERS) if ble else None ``` ## Matchers A listener hears about a device when it matches any of its matchers. A plain `UUID` matches that service. In a `BLEMatcher`, every field that is set must match: | Field | Matches | | ------------------------- | ------------------------------------------------------------------ | | `service_uuid` | a service UUID, advertised as a service or in the service data | | `service_data_uuid` | a UUID in the service data only | | `manufacturer_id` | a company id in the manufacturer data, e.g. `0x004C` for Apple | | `manufacturer_data_start` | the first bytes of that manufacturer data (with `manufacturer_id`) | | `local_name_prefix` | the start of the advertised name | ## Events | Callback | Called when | | ------------------------- | ------------------------------------------------------------------------------------------------------------------ | | `ble_did_discover_device` | a matching device is heard for the first time; devices heard before you registered count as new | | `ble_did_update_device` | its advertisement changed (name, service UUIDs, manufacturer or service data); signal strength alone doesn't count | | `ble_did_remove_device` | no radio has heard it for about 11 seconds | `info.device` is bleak's `BLEDevice` (`.address`, `.name`); `info.advertisement` is bleak's `AdvertisementData`; `info.rssi` is the signal of the radio that hears it best. To connect to a discovered device, see [Capabilities: Bluetooth LE](https://docs.majordom.io/integrations/capabilities/ble/index.md). ## Active scanning in a pairing window Radios scan passively: they hear every advertisement, but many devices send their name only when asked. While the user is pairing, ask for an active scan: ```python async def start_pairing_window(self, duration_sec: int, credentials: ProvidedCredentials | None = None): await self.peripherals.instance(BLE_ROUTER).scan_actively(duration_sec) ``` # SSDP / UPnP Discovery ## `SSDP` The `upnp/ssdp` peripheral. Declare `UPNP_SSDP`, and the runtime's listener (`SSDPDiscoveryService`) arrives as `self.peripherals.instance(UPNP_SSDP)`. Its contract is `majordom_integration_sdk.capabilities.SSDP`. ### `register` ```python def register( self, listener: SSDPDiscoveryListener, search_target: str, mcast_group: str = "239.255.255.250", port: int = 1900, ) -> Callable[[], None]: ... ``` | Arg | Type | Default | Description | | --------------- | ----------------------- | ------------------- | ------------------------------------------ | | `listener` | `SSDPDiscoveryListener` | required | Receives discovery events. | | `search_target` | `str` | required | SSDP ST field. See common templates below. | | `mcast_group` | `str` | `"239.255.255.250"` | Multicast group. Change only if necessary. | | `port` | `int` | `1900` | SSDP port. Change only if necessary. | Returns a cancel closure — call it in `stop()` to deregister. **Common `search_target` values:** | ST | Discovers | | --------------------------------------------- | ----------------------------- | | `"upnp:rootdevice"` | All UPnP root devices | | `"ssdp:all"` | All UPnP devices and services | | `"urn:schemas-upnp-org:device:MediaServer:1"` | UPnP MediaServer devices | | `"uuid:"` | A specific device by UUID | ______________________________________________________________________ ## `SSDPDiscoveryListener` (Protocol) ```python class SSDPDiscoveryListener(Protocol): async def ssdp_did_discover_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): ... async def ssdp_did_update_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): ... async def ssdp_did_remove_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): ... ``` `ssdp_did_remove_service` fires when a device sends a `ssdp:byebye` NOTIFY, or when a device fails to respond to several consecutive M-SEARCH bursts (controlled by `_missed_scans_evict`, default 3 missed scans). ______________________________________________________________________ ## `SSDPDiscoveryInfo` ```python @dataclass class SSDPDiscoveryInfo: addr: str host: str | None search_target: str | None service_name: str | None # USN (Unique Service Name) server: str | None cache_control: str | None location: str | None # URL to the device description XML response: dict[str, str] # full raw response headers ``` ______________________________________________________________________ ## Example ```python # in Controller ... async def start(self): self._cancels: set[Callable[[], None]] = set() cancel = self.peripherals.instance(UPNP_SSDP).register( self, # self implements SSDPDiscoveryListener "urn:schemas-upnp-org:device:MediaServer:1", ) self._cancels.add(cancel) async def stop(self): for cancel in self._cancels: cancel() # SSDPDiscoveryListener Implementation async def ssdp_did_discover_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): if discovery := self._mapper.map_to_discovery(info): self._discoveries[discovery.id] = discovery await self.output.controller_did_receive_discovery(self, discovery) async def ssdp_did_update_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): if discovery := self._mapper.map_to_discovery(info): self._discoveries[discovery.id] = discovery await self.output.controller_did_update_discovery(self, discovery) async def ssdp_did_remove_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): discovery_id = self.device_uuid(info.service_name or info.addr) if discovery_id in self._discoveries: self._discoveries.pop(discovery_id) await self.output.controller_did_lose_discovery(self, discovery_id) ... ``` # Zeroconf (mDNS / DNS-SD / Bonjour) Discovery ## `Zeroconf` The `mdns/zeroconf` peripheral. Declare `ZEROCONF`, and the runtime's browser (`ZeroconfDiscoveryService`, the SDK's `discovery` extra) arrives as `self.peripherals.instance(ZEROCONF)`. Its contract is `majordom_integration_sdk.capabilities.Zeroconf`. ### `register` ```python def register( listener: ZeroconfDiscoveryListener, services: set[str], ) -> Callable[[], None]: ... ``` | Arg | Type | Description | | ---------- | --------------------------- | -------------------------------------------------------------------- | | `listener` | `ZeroconfDiscoveryListener` | Receives discovery events | | `services` | `set[str]` | Fully-qualified mDNS service type strings, e.g. `"_hap._tcp.local."` | Returns a cancel closure — call it in `stop()` to deregister. ### `async_zeroconf` ```python async_zeroconf: AsyncZeroconf | None ``` The underlying `AsyncZeroconf` instance; `None` until it starts. Use only when you need low-level zeroconf access, or a library takes one (aiohomekit). ______________________________________________________________________ ## `ZeroconfDiscoveryListener` (Protocol) ```python class ZeroconfDiscoveryListener(Protocol): async def zeroconf_did_discover_service( self, zeroconf: Zeroconf, info: ZeroconfDiscoveryInfo, ): ... async def zeroconf_did_update_service( self, zeroconf: Zeroconf, info: ZeroconfDiscoveryInfo, ): ... async def zeroconf_did_remove_service( self, zeroconf: Zeroconf, type_: str, name: str, ): ... ``` Note: `zeroconf_did_remove_service` fires on mDNS goodbye packets (TTL=0) or when a silent departure is confirmed: A/AAAA records expired and a follow-up probe got no response. Typical latency for silent departures is ~120 s (A/AAAA TTL). For faster detection, implement liveness checks at the pairing/connection layer. ______________________________________________________________________ ## `ZeroconfDiscoveryInfo` ```python @dataclass class ZeroconfDiscoveryInfo: type_: str name: str server: str | None port: int | None addresses: list[bytes] | None parsed_addresses: list[str] | None weight: int | None priority: int | None properties: dict[bytes, bytes | None] decoded_properties: dict[str, str | None] text: bytes host_ttl: int | None other_ttl: int | None interface_index: int | None ``` Key fields: | Field | Type | Description | | -------------------- | ---------------------------- | --------------------------------------------------------------------------- | | `type_` | `str` | Fully qualified service type (e.g. `_hap._tcp.local.`) | | `name` | `str` | Fully qualified service name | | `server` | `str \| None` | Hostname of the service | | `port` | `int \| None` | Port the service listens on | | `parsed_addresses` | `list[str] \| None` | IP addresses as strings | | `decoded_properties` | `dict[str, str \| None]` | TXT record key-value pairs decoded to `str`; use this for most integrations | | `properties` | `dict[bytes, bytes \| None]` | Raw TXT record bytes | | `text` | `bytes` | Raw TXT record bytes (full) | | `interface_index` | `int \| None` | IPv6 zone id / scope id | `__eq__` excludes TTL fields — safe for change detection. ______________________________________________________________________ ## Example ```python # in Controller ... async def start(self): self._cancels: set[Callable[[], None]] = set() cancel = self.peripherals.instance(ZEROCONF).register( self, # self implements ZeroconfDiscoveryListener {"_hap._tcp.local."}, ) self._cancels.add(cancel) async def stop(self): for cancel in self._cancels: cancel() # ZeroconfDiscoveryListener Implementation async def zeroconf_did_discover_service(self, zeroconf: Zeroconf, info: ZeroconfDiscoveryInfo): if discovery := self._mapper._map_to_discovery(info): self._discoveries[discovery.id] = discovery await self.output.controller_did_receive_discovery(self, discovery) async def zeroconf_did_update_service(self, zeroconf: Zeroconf, info: ZeroconfDiscoveryInfo): if discovery := self._mapper._map_to_discovery(info): self._discoveries[discovery.id] = discovery await self.output.controller_did_update_discovery(self, discovery) async def zeroconf_did_remove_service(self, zeroconf: Zeroconf, type_: str, name: str): if discovery_id := self._mapper._name_to_id(name) and discovery_id in self._discoveries: self._discoveries.pop(discovery_id, None) await self.output.controller_did_lose_discovery(self, discovery_id) ... ``` # Bluetooth LE Everything an integration does over Bluetooth goes through one object: the `BLERouter`. ## What the router is The Hub may have several Bluetooth radios: its own adapter, a USB dongle, the Bluetooth of a multi-PAN stick, and ESPHome nodes acting as Bluetooth proxies around the house. The router holds all of them and gives every integration one API: - **Discovery**: you say which devices you want to hear about, and it reports them, whichever radio heard them. - **Connections**: you connect by address, and it picks the radio that hears the device best. - **Leases**: you lock one radio to one device for a long setup, while the others keep working for everyone. Your code never knows which radio carries a connection. A device in the garage reached through an ESPHome proxy works the same as one next to the Hub. Never access Bluetooth hardware directly Don't open adapters, scan or connect with bleak, BlueZ, `bluetoothctl` or any other library or service. The router already holds every radio: a direct scan competes with it, misses the proxies, and can break another integration's pairing. A need for raw Bluetooth (`Need("ble", ["bluez"])`) is never bound while the router runs. ## Getting the router Need `BLE_ROUTER`, and read it from `self.peripherals`: ```python from majordom_integration_sdk.capabilities import BLE_ROUTER class AcmeController(AbstractController[Device, Parameter]): needs = [BLE_ROUTER] async def start(self): self._ble = self.peripherals.instance(BLE_ROUTER) ``` When the integration also works without Bluetooth, make the need optional. `instance()` then returns `None` on a hub without Bluetooth: ```python needs = [BLE_ROUTER(is_required=False)] ``` ## Discovering devices See [Bluetooth Discovery](https://docs.majordom.io/integrations/discovery/ble/index.md): `router.register(listener, matchers)`, with a full example. `router.devices()` returns every device heard recently, if you need a snapshot instead of events. ## Connecting and using GATT `connect(address)` opens a GATT connection for the block, and closes it when the block ends. Characteristics are addressed by their handle, which you find in `services()`: ```python BATTERY_LEVEL = "00002a19-0000-1000-8000-00805f9b34fb" async def read_battery(self, address: str) -> int: async with self._ble.connect(address) as connection: characteristics = [c for s in await connection.services() for c in s.characteristics] battery = next(c for c in characteristics if c.uuid == BATTERY_LEVEL) return (await connection.read(battery.handle))[0] ``` | `BLEConnection` | Does | | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `await connection.services()` | the device's GATT services, each with its `characteristics` (`uuid`, `handle`, `properties`) | | `await connection.read(handle)` | reads a characteristic, as `bytes` | | `await connection.write(handle, data, is_response_needed=True)` | writes a characteristic; `False` for "write without response" | | `await connection.start_notify(handle, callback)` | calls `callback(data)` on every notification or indication | | `await connection.stop_notify(handle)` | stops them | | `await connection.disconnect()` | closes the connection before the block ends | | `connection.mtu` | the negotiated MTU, to size your packets | | `connect(…)` parameter | Meaning | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `on_disconnect` | called when the connection drops | | `busy_timeout` | seconds to reach the device, waiting for a radio leased to someone else (default 10). Then `BLEBusyError` when every radio that hears it is still leased, or `ConnectionError` (which `BLEBusyError` also is) when none reaches it | | `max_duration` | seconds after which the connection is closed and the block gets `TimeoutError` (default 600); `None` keeps it open, only when you mean it | Every Bluetooth radio has only a few connection slots, a proxy fewer still: keep the block short. When a connection must outlive a block, like a subscription kept while the integration runs, `open_connection(…, max_duration=None)` takes the same parameters and returns the connection: disconnect it yourself. ## Locking a radio: `exclusive` A short exchange (read a value, send a command) just connects. A long, multi-step setup should lease the radio first, so nobody else's connection or scan disrupts the operation: ```python from majordom_integration_sdk.capabilities import BLEBusyError try: async with self._ble.exclusive(address, owner=self.key, max_duration=300) as lease, lease.connect() as connection: await self._provision(connection) # several reads, writes and notifications except BLEBusyError: ... # tell the user the Hub's Bluetooth is busy, try again later ``` While the block runs, the radio that hears the device best stops scanning and serves only you; the other radios keep working for everyone. When the block ends, the radio goes back to the router. Always connect through `lease.connect()`, not `self._ble.connect()`, inside the block; it takes the same parameters. | Lock | Don't lock | | -------------------------------------------------------------------------------------------------------- | ------------------------------------- | | Commissioning or pairing that takes several steps (Matter commissioning, Wi-Fi provisioning over Improv) | Discovery: the router does it for you | | A firmware update | Reading a value or sending a command | | Anything that must not lose its radio halfway | Anything over in a second or two | A lease blocks other integrations from that radio, so hold it no longer than the setup takes. | Parameter | Meaning | | ------------------- | ----------------------------------------------------------------------------------------------------------- | | `owner` | who holds it, for the logs: your integration's `key` | | `busy_timeout` | seconds to wait for a free radio before `BLEBusyError` (default 30) | | `max_duration` | seconds the lease holds the radio; then the block gets `TimeoutError` and the radio goes back (default 120) | | `wait` | seconds to wait for the best radio before trying the next one (default 1) | | `is_pairing_needed` | lease only a radio that can pair (see below); `BLEPairingError` when none hears the device | ## Pairing and sending credentials Send credentials (a Wi-Fi password, a Thread network key) only over a secured link. Pick a `SecureChannel` and open it on the leased connection: ```python from majordom_integration_sdk.capabilities import BLEPairingError, LESecureConnections channel = LESecureConnections() async with self._ble.exclusive(address, owner=self.key, is_pairing_needed=channel.is_pairing_needed) as lease: async with lease.connect() as connection, channel.secure(connection) as secured: await secured.write(credentials_handle, credentials) ``` | Channel | Use for | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `LESecureConnections()` | the default: pairs ("Just Works") before anything is written, and unpairs when the block ends; `LESecureConnections(is_pairing_kept=True)` keeps the bond. Raises `BLEPairingError` when the link can't be encrypted, so nothing is sent unencrypted | | `Unsecured()` | firmware that can't pair at all; chosen explicitly, it logs a warning | Not every radio can pair: a source says it can with `is_pairable`. `is_pairing_needed=True` leases one that can. ## Adding a BLE proxy If your integration talks to devices that have a Bluetooth radio of their own (like ESPHome nodes with `bluetooth_proxy`), it can lend that radio to the router. Every integration then reaches Bluetooth devices through it. 1. Implement `BLESource` for the radio: ```python from collections.abc import Callable from majordom_integration_sdk.capabilities import BLEConnection, GattService, OnAdvertisement class AcmeBLESource: name = "acme-1" # unique: e.g. the radio's MAC is_pairable = False # True when its connections can pair free_slots: int | None = 3 # connections it can still open; None when unknown async def start(self, on_advertisement: OnAdvertisement): ... # call on_advertisement(device, advertisement) for each one heard async def stop(self): ... async def connect(self, address: str, on_disconnect: Callable[[], None]) -> BLEConnection: return AcmeBLEConnection(await self._radio.connect(address), on_disconnect) # pseudo class AcmeBLEConnection: """Wraps one GATT connection of the radio: the router hands it to integrations as a `BLEConnection`.""" mtu: int async def services(self) -> list[GattService]: ... async def read(self, handle: int) -> bytes: ... async def write(self, handle: int, data: bytes, is_response_needed: bool = True): ... async def start_notify(self, handle: int, callback: Callable[[bytes], None]): ... async def stop_notify(self, handle: int): ... async def disconnect(self): ... # call on_disconnect() when the radio reports the link dropped, too ``` A radio whose connections can pair returns `PairableBLEConnection`s (with `pair()` and `unpair()`) and sets `is_pairable = True`. A source that can stop scanning without letting go of its radio also implements `pause_scanning()` and `resume_scanning()`; one that can switch to active scanning implements `set_scan_mode(is_active)`. The router uses them when they are there. 1. Provide it as a `BLEProxy` while the radio is reachable, and tell the Hub each time that changes: ```python from majordom_integration_sdk.peripherals import BLEProxy class AcmeController(AbstractController[Device, Parameter]): @property def provides(self) -> list[BLEProxy]: return list(self._proxies.values()) async def _on_node_connected(self, node_id: str, source: AcmeBLESource): self._proxies[node_id] = BLEProxy(source) await self.output.controller_did_change_provided(self) async def _on_node_lost(self, node_id: str): if self._proxies.pop(node_id, None): await self.output.controller_did_change_provided(self) ``` Keep `BLEProxy`'s default dialect: the router hears through proxies as `ble/esphome-proxy`, whoever brings them. It starts hearing through the proxy at once, and lets it go when you take it back or the integration stops. See [Peripherals](https://docs.majordom.io/integrations/peripherals/#bringing-peripherals-along) for providing peripherals in general. ## Testing The SDK's test doubles (the `ble` extra) run a real router over fake radios: ```python from majordom_integration_sdk import Peripherals from majordom_integration_sdk.testing import FakeBLERouter, FakeBLESource, build_test_platform radio = FakeBLESource("hci0", connection=my_fake_connection, is_pairable=True) router = FakeBLERouter(sources=[radio]) await router.start() controller = AcmeController(build_test_platform()) controller.peripherals = Peripherals({"ble": router.endpoint}) await controller.start() radio.advertise("AA:BB:CC:DD:EE:FF", local_name="Acme", service_uuids=["0000fd00-0000-1000-8000-00805f9b34fb"]) ``` To test a proxy you provide, hand its source to the router: `await router.add_source(controller.provides[0].source)`. # API ### [Open Full Page](https://virtualhub.majordom-dev.parker-programs.com/api/docs) ### [Open Full Page](https://bridge.majordom.parker-programs.com/docs) ### [Open Full Page](https://api.majordom.parker-programs.com/docs) # Hub REST API (OpenAPI) ## GET /api/automation Get All Automations Responses: - 200 list[`Automation`] ## POST /api/automation Create Automation Body: `CreateAutomation` Responses: - 200 `Automation` - 422 `HTTPValidationError` ## DELETE /api/automation/{id} Delete Automation Parameters: `id` (path, required): string Responses: - 200 any - 422 `HTTPValidationError` ## GET /api/automation/{id} Get Automation Parameters: `id` (path, required): string Responses: - 200 `Automation` - 422 `HTTPValidationError` ## PATCH /api/automation/{id} Patch Automation Parameters: `id` (path, required): string Body: `Automation` Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/device Pairs the device and saves it; a failed pairing saves nothing and is rolled back, so post it again to retry. The returned `id` is the one to use: an integration may change it, so it can differ from `discovery_id`. When another record holds the discovery's id or that id (`device_id_taken`), pair onto it with `POST /device/{device_id}` instead. Body: `DeviceCreate` Responses: - 200 `DeviceInfo` - 409 `ErrorResponse[DeviceIdTakenError]`: `device_id_taken`: another record holds the physical id the device would get: pair onto it with `POST /device/{device_id}` (if it `is_paired`, delete it with `mode=unpair` first), or delete it; nothing was saved - `device_id_taken`: `{"detail": {"device_id": "1baa36f8-6f25-56c4-955c-f151a35de00b", "is_paired": false, "msg": "Physical id 6c1e2f0a-3b7d-5e94-8a21-0d4f9b3c7e15 is taken by 'Lamp' (1baa36f8-6f25-56c4-955c-f151a35de00b)", "name": "Lamp", "physical_id": "6c1e2f0a-3b7d-5e94-8a21-0d4f9b3c7e15", "type": "device_id_taken"}}` - 422 `ErrorResponse[MissingCredentialsError]` | `ValidationErrorResponse`: `missing_credentials`: the Hub lacks credentials of `credentials_type` to pair the device; nothing was saved; or the request is malformed - `missing_credentials`: `{"detail": {"credentials_type": "wifi", "msg": "Missing credentials: wifi", "type": "missing_credentials"}}` - `validation_error`: `{"detail": [{"input": {"discovery_id": "1baa36f8-6f25-56c4-955c-f151a35de00b", "name": "Lamp"}, "loc": ["body", "room_id"], "msg": "Field required", "type": "missing"}]}` - 500 `ErrorResponse[PairingFailedError]`: `pairing_failed`: the integration failed to pair; nothing was saved - `pairing_failed`: `{"detail": {"msg": "Pairing failed", "type": "pairing_failed"}}` ## GET /api/device/discoveries Get Discoveries Parameters: `include_ignored` (query): boolean Responses: - 200 dict[str, `Discovery`] - 422 `HTTPValidationError` ## DELETE /api/device/discoveries/{discovery_id}/ignore Unignore Discovery Parameters: `discovery_id` (path, required): uuid Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/device/discoveries/{discovery_id}/ignore Ignore Discovery Parameters: `discovery_id` (path, required): uuid Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/device/start_pairing_window Temporarily enables protocol-level discovery mechanisms that are not continuously active. Used to trigger short-lived scan/inquiry modes for transports that require explicit activation (e.g. Zigbee permit-join style discovery, BLE scan bursts, proprietary radios). `integration` opens the window of that integration only (every integration's otherwise). `credentials` are the ones a protocol needs during inclusion, before the device is a discovery (e.g. a Z-Wave device's S2 PIN or QR code): protocol-specific, so they need `integration`. Parameters: `duration_sec` (query, required): integer; `integration` (query): string | null Body: `ProvidedCredentials` | null Responses: - 200 any - 422 `HTTPValidationError` ## PATCH /api/device/{device_id}/parameter/{parameter_id} Patch Parameter Visibility Parameters: `device_id` (path, required): uuid; `parameter_id` (path, required): uuid Body: `ParameterVisibilityPatch` Responses: - 200 any - 422 `HTTPValidationError` ## DELETE /api/device/{id} `unpair`: the integration unpairs the device, its record is kept to skip setup after re-pairing. `delete`: the integration unpairs it, then its record is deleted. `forget`: its record is deleted without the integration, e.g. after `device_unreachable`: the device then needs a manual factory reset to pair again. Parameters: `id` (path, required): uuid; `mode` (query): `DeleteMode` Responses: - 200 any - 409 `ErrorResponse[DeviceUnreachableError]`: `device_unreachable`: the integration can't reach the device to unpair it; the record is unchanged: forget it instead (`mode=forget`), after which the device needs a manual factory reset to pair again - `device_unreachable`: `{"detail": {"msg": "Device unreachable. Forget it instead? It might need a manual factory reset to pair again.", "type": "device_unreachable"}}` - 422 `HTTPValidationError` ## GET /api/device/{id} Get Device Parameters: `id` (path, required): uuid Responses: - 200 `DeviceState` - 422 `HTTPValidationError` ## PATCH /api/device/{id} Patch Device Parameters: `id` (path, required): uuid Body: `DevicePatch` Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/device/{id} Pairs a live discovery onto a device deleted with `mode=unpair`, keeping its name, room and the rest: its integration decides what of its data still holds. Fails like `POST /device`, leaving the record as it was. Use the returned `id` from then on: it can differ from the path one, and automations follow it. Parameters: `id` (path, required): uuid Body: `DevicePair` Responses: - 200 `Device` - 409 `ErrorResponse[DeviceIdTakenError]`: `device_id_taken`: another record holds the physical id the device would get: pair onto it with `POST /device/{device_id}` (if it `is_paired`, delete it with `mode=unpair` first), or delete it; nothing was saved - `device_id_taken`: `{"detail": {"device_id": "1baa36f8-6f25-56c4-955c-f151a35de00b", "is_paired": false, "msg": "Physical id 6c1e2f0a-3b7d-5e94-8a21-0d4f9b3c7e15 is taken by 'Lamp' (1baa36f8-6f25-56c4-955c-f151a35de00b)", "name": "Lamp", "physical_id": "6c1e2f0a-3b7d-5e94-8a21-0d4f9b3c7e15", "type": "device_id_taken"}}` - 422 `ErrorResponse[MissingCredentialsError]` | `ValidationErrorResponse`: `missing_credentials`: the Hub lacks credentials of `credentials_type` to pair the device; nothing was saved; or the request is malformed - `missing_credentials`: `{"detail": {"credentials_type": "wifi", "msg": "Missing credentials: wifi", "type": "missing_credentials"}}` - `validation_error`: `{"detail": [{"input": {"discovery_id": "1baa36f8-6f25-56c4-955c-f151a35de00b", "name": "Lamp"}, "loc": ["body", "room_id"], "msg": "Field required", "type": "missing"}]}` - 500 `ErrorResponse[PairingFailedError]`: `pairing_failed`: the integration failed to pair; nothing was saved - `pairing_failed`: `{"detail": {"msg": "Pairing failed", "type": "pairing_failed"}}` ## POST /api/device/{id}/fetch Asks its integration to bring the device to a known-good state: whether it answers, its current values, its event subscription. The results arrive as the usual device events. Parameters: `id` (path, required): uuid Responses: - 200 any - 422 `HTTPValidationError` ## GET /api/hardware/radios Get Radios Responses: - 200 list[`RadioOut`] ## POST /api/hardware/radios/{key}/firmware Switch a radio to another firmware (what it serves); takes about a minute, `is_busy` meanwhile. 409 while it is busy. Parameters: `key` (path, required): string; `firmware` (query, required): string Responses: - 202 any - 422 `HTTPValidationError` ## POST /api/hardware/radios/{key}/forget Forget what a radio is; it is identified again while plugged in, up to minutes, `is_busy` meanwhile. 409 while it is busy. Parameters: `key` (path, required): string Responses: - 202 any - 422 `HTTPValidationError` ## POST /api/hardware/radios/{key}/probe Identify a plugged-in device that isn't a known radio; opening its port may reset it. Up to minutes, `is_busy` meanwhile. 409 while it is busy. Parameters: `key` (path, required): string Responses: - 202 any - 422 `HTTPValidationError` ## GET /api/house Get House Responses: - 200 `House` ## GET /api/hub Get Hub Responses: - 200 `Hub` ## HEAD /api/hub Ping Responses: - 200 any ## PATCH /api/hub Patch Hub Body: `HubPatch` Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/hub Setup Hub Body: `Body_setup_hub_api_hub_post` Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/hub/add_user Add User Body: `User` Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/hub/connect Connect To Wifi Body: `WifiConnection` Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/hub/disable_hotspot Disable Hotspot Responses: - 200 any ## GET /api/hub/hotspots Get Hub Hotspots Responses: - 200 list[`Hotspot`] ## GET /api/hub/is_connected Is Connected Responses: - 200 boolean ## GET /api/hub/logs Get Logs Responses: - 200 any ## POST /api/hub/reset Forget everything but the system config; the Hub starts afresh once it answered, ready to be set up again. Responses: - 200 any ## POST /api/hub/set_tokens Set Tokens Body: `TokensPair` Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/hub/set_wifi Connect the Hub to a Wi-Fi network, with `connect=true`. The network integrations set devices up onto (e.g. ESPHome over Improv BLE) is chosen in the Hub settings (`PATCH /settings/hub`): without `connect` it's a 400. Parameters: `connect` (query): boolean Body: `WifiConnection` Responses: - 200 any - 422 `HTTPValidationError` ## GET /api/integrations Get Integrations Responses: - 200 list[`IntegrationOut`] ## POST /api/integrations/{key}/disable Stop it until enabled again, across restarts. Parameters: `key` (path, required): string Responses: - 200 `IntegrationOut` - 422 `HTTPValidationError` ## POST /api/integrations/{key}/enable Enable Integration Parameters: `key` (path, required): string Responses: - 200 `IntegrationOut` - 422 `HTTPValidationError` ## POST /api/integrations/{key}/restart Start it anew, one that failed or stopped by itself too. Parameters: `key` (path, required): string Responses: - 200 `IntegrationOut` - 422 `HTTPValidationError` ## POST /api/room Create Room Body: `RoomCreate` Responses: - 200 `Room` - 422 `HTTPValidationError` ## DELETE /api/room/{id} Delete Room Parameters: `id` (path, required): uuid Responses: - 200 any - 422 `HTTPValidationError` ## GET /api/room/{id} Get Room Parameters: `id` (path, required): uuid Responses: - 200 `Room` - 422 `HTTPValidationError` ## PATCH /api/room/{id} Patch Room Parameters: `id` (path, required): uuid Body: `RoomPatch` Responses: - 200 any - 422 `HTTPValidationError` ## GET /api/scene Get All Scenes Responses: - 200 list[`Scene`] ## POST /api/scene Create Scene Body: `CreateScene` Responses: - 200 `Scene` - 422 `HTTPValidationError` ## DELETE /api/scene/{id} Delete Scene Parameters: `id` (path, required): string Responses: - 200 any - 422 `HTTPValidationError` ## GET /api/scene/{id} Get Scene Parameters: `id` (path, required): string Responses: - 200 `Scene` - 422 `HTTPValidationError` ## PATCH /api/scene/{id} Patch Scene Parameters: `id` (path, required): string Body: `Scene` Responses: - 200 any - 422 `HTTPValidationError` ## POST /api/scene/{id}/run Run Scene Parameters: `id` (path, required): string Responses: - 200 any - 422 `HTTPValidationError` ## GET /api/services Get Services Responses: - 200 list[`ServiceStatusResponse`] ## POST /api/services/{name}/disable Disable Service Parameters: `name` (path, required): string Responses: - 200 `ServiceStatusResponse` - 422 `HTTPValidationError` ## POST /api/services/{name}/enable Enable Service Parameters: `name` (path, required): string Responses: - 200 `ServiceStatusResponse` - 422 `HTTPValidationError` ## POST /api/services/{name}/restart Restart Service Parameters: `name` (path, required): string Responses: - 200 `ServiceStatusResponse` - 422 `HTTPValidationError` ## POST /api/services/{name}/start Start Service Parameters: `name` (path, required): string Responses: - 200 `ServiceStatusResponse` - 422 `HTTPValidationError` ## POST /api/services/{name}/stop Stop Service Parameters: `name` (path, required): string Responses: - 200 `ServiceStatusResponse` - 422 `HTTPValidationError` ## GET /api/settings/{scope} Settings of a peripheral by its key (an integration, a service, a radio), or of the Hub-wide facts ("hub"). Parameters: `scope` (path, required): string Responses: - 200 `SettingsOut` - 422 `HTTPValidationError` ## PATCH /api/settings/{scope} Change some settings; what uses them takes them in place or restarts with them. Parameters: `scope` (path, required): string Body: object Responses: - 200 `SettingsOut` - 422 `HTTPValidationError` ## HEAD /ws/user Websocket Endpoint Parameters: `authorization` (header, required): string Body: `DeviceCommandMessage` | `BridgeMessage` Responses: - 101: Switching Protocols - 2001 `DiscoveryMessage`: DiscoveryMessage - 2002 `DismissDiscoveryMessage`: DismissDiscoveryMessage - 2003 `DeviceConnectedMessage`: DeviceConnectedMessage - 2004 `DeviceDisconnectedMessage`: DeviceDisconnectedMessage - 2005 `DeviceEventMessage`: DeviceEventMessage - 2006 `BridgeResponseMessage`: BridgeResponseMessage - 2007 `IntegrationErrorMessage`: IntegrationErrorMessage - 2008 `IntegrationErrorResolvedMessage`: IntegrationErrorResolvedMessage - 2009 `IntegrationStatusMessage`: IntegrationStatusMessage - 2010 `NotificationMessage`: NotificationMessage - 422 `HTTPValidationError` ## POST /ws/user::BridgeMessage Body: object Responses: ## GET /ws/user::BridgeResponseMessage Responses: - 200 object ## POST /ws/user::DeviceCommandMessage Body: object Responses: ## GET /ws/user::DeviceConnectedMessage Responses: - 200 object ## GET /ws/user::DeviceDisconnectedMessage Responses: - 200 object ## GET /ws/user::DeviceEventMessage Responses: - 200 object ## GET /ws/user::DiscoveryMessage Responses: - 200 object ## GET /ws/user::DismissDiscoveryMessage Responses: - 200 object ## GET /ws/user::IntegrationErrorMessage A user-facing integration problem. `message` is plain language for display (with any call-to-action folded into the text); whether the integration still runs, its status says (IntegrationStatusMessage). Device-scoped problems travel on the device's `last_error` instead. `id` is stable per condition: a later message with the same `integration` and `id` replaces this one, and it stays until an IntegrationErrorResolvedMessage with them. Responses: - 200 object ## GET /ws/user::IntegrationErrorResolvedMessage The integration's error with this `id` is gone: it cleared, or the integration stopped or restarted. Responses: - 200 object ## GET /ws/user::IntegrationStatusMessage An integration's state changed: `kind` says why it waits or failed, for the app to act on. A user-facing error comes with the states the user can act on (IntegrationErrorMessage). Responses: - 200 object ## GET /ws/user::NotificationMessage A general user-facing notification from an integration — rendered as a floating tile. The nested `notification` carries the message, callout type (info/warning/error), delivery priority, and ttl. Distinct from IntegrationErrorMessage, which is specifically for failures. Responses: - 200 object # Schemas ## Automation - `condition`: `_Condition`, required - `delay_seconds`: number, default `0` - `executables`: list[`_Executable`], required - `executables_otherwise`: list[`_Executable`] | null - `id`: string, required - `name`: string, required - `needs_reset`: boolean, default `false` - `type`: string, required. The type of model. ## Base ## Body_setup_hub_api_hub_post - `house_info`: `HouseInfo`, required - `hub_auth`: `HubAuthItems`, required - `hub_info`: `HubInfo`, required - `user_info`: `User`, required ## BridgeMessage - `data`: `RestRequest`, required - `type`: `bridge`, default `"bridge"` ## BridgeRequestBody ## BridgeResponseMessage - `body`: any, required - `method`: string, required - `path`: string, required - `type`: `bridge_response`, default `"bridge_response"` ## CreateAutomation - `condition`: `_Condition`, required - `delay_seconds`: number, default `0` - `executables`: list[`_Executable`], required - `executables_otherwise`: list[`_Executable`] | null - `name`: string, required - `needs_reset`: boolean, default `false` - `type`: string, required. The type of model. ## CreateScene - `executables`: list[`_Executable`], required - `name`: string, required ## CredentialsOption One way a discovered device can be paired, with what the UI needs to ask for it. - `hint`: string | null, default `null` - `mask`: string | null, default `null` - `type`: `CredentialsType`, required ## CredentialsType One of: `code`, `qr`, `secret`, `button`, `none` ## CredentialsValue ## DeleteMode One of: `unpair`, `delete`, `forget` ## Device A device with what its integration keeps about it, ``integration_data``, typed as ``TData``: a bare ``Device`` holds any (a dict once read back), ``class HueDevice(Device[HueData])`` its own model. Unset, it is ``TData`` validated from ``{}`` (the Hub creates a device before its integration pairs it), and stays unset: a save keeps the stored one. For ``Device[HueData | None]`` that ``{}``, unset or stored, is None. - `available`: boolean, default `false` - `category`: string | null - `description`: string | null - `icon`: string | null - `id`: uuid, required - `integration`: string, required - `integration_data`: any - `last_error`: string | null - `last_seen`: date-time | null - `main_parameter`: uuid | null - `manufacturer`: string | null, required - `name`: string, required - `note`: string, default `""` - `physical_id`: uuid, required - `room_id`: uuid, required - `transport`: string, required ## DeviceCommand - `device_id`: uuid, required - `parameter_id`: uuid, required - `value`: any, required ## DeviceCommandMessage - `data`: `DeviceCommand`, required - `type`: `device_command`, default `"device_command"` ## DeviceConnectedMessage - `data`: uuid, required - `type`: `majordom_did_connect_device`, default `"majordom_did_connect_device"` ## DeviceCreate - `category`: string | null - `credentials`: `ProvidedCredentials` | null - `discovery_id`: uuid, required - `icon`: string | null - `main_parameter`: uuid | null - `name`: string, required - `note`: string, default `""` - `room_id`: uuid, required ## DeviceDisconnectedMessage - `data`: uuid, required - `type`: `majordom_did_disconnect_device`, default `"majordom_did_disconnect_device"` ## DeviceEventMessage - `data`: `DeviceParameterChangedEvent`, required - `type`: `majordom_did_receive_event`, default `"majordom_did_receive_event"` ## DeviceIdTakenError another record holds the physical id the device would get: pair onto it with `POST /device/{device_id}` (if it `is_paired`, delete it with `mode=unpair` first), or delete it; nothing was saved - `device_id`: uuid, required - `is_paired`: boolean, required - `msg`: string, required - `name`: string, required - `physical_id`: uuid, required - `type`: `device_id_taken`, required ## DeviceInfo - `available`: boolean, default `false` - `category`: string | null - `description`: string | null - `icon`: string | null - `id`: uuid, required - `integration`: string, required - `last_error`: string | null - `last_seen`: date-time | null - `main_parameter`: uuid | null - `manufacturer`: string | null, required - `name`: string, required - `note`: string, default `""` - `room_id`: uuid, required - `transport`: string, required ## DevicePair Re-pair discovery to the existing device. - `credentials`: `ProvidedCredentials` | null - `device_id`: uuid, required - `discovery_id`: uuid, required ## DeviceParameterChangedEvent A parameter change an integration reported (its ``DeviceParameterChange``), named by the Hub's device id. - `device_id`: uuid, required - `parameter_id`: uuid, required - `value`: any, required ## DevicePatch - `category`: string | null - `icon`: string | null - `main_parameter`: uuid | null - `name`: string, required - `note`: string, default `""` - `room_id`: uuid, required ## DeviceState A device with its parameters' current states, the data of each typed as ``TParameterData``. - `available`: boolean, default `false` - `category`: string | null - `description`: string | null - `icon`: string | null - `id`: uuid, required - `integration`: string, required - `integration_data`: any - `last_error`: string | null - `last_seen`: date-time | null - `main_parameter`: uuid | null - `manufacturer`: string | null, required - `name`: string, required - `note`: string, default `""` - `parameters`: list[`ParameterState[TypeVar, Any]`], required - `physical_id`: uuid, required - `room_id`: uuid, required - `transport`: string, required ## DeviceUnreachableError the integration can't reach the device to unpair it; the record is unchanged: forget it instead (`mode=forget`), after which the device needs a manual factory reset to pair again - `msg`: string, required - `type`: `device_unreachable`, required ## Discovery - `device_category`: string | null, required - `device_icon`: string | null, required - `device_manufacturer`: string | null, required - `device_name`: string, required. A non-empty string - `expected_credentials_options`: list[`CredentialsOption`], required - `expiration`: date-time | null, default `null` - `id`: uuid, required - `integration`: string, required. A non-empty string - `last_error`: string | null, default `null` - `transport`: string, required. A non-empty string ## DiscoveryMessage - `data`: `Discovery`, required - `type`: `majordom_did_discover_discovery`, default `"majordom_did_discover_discovery"` ## DismissDiscoveryMessage - `data`: uuid, required - `type`: `majordom_did_dismiss_discovery`, default `"majordom_did_dismiss_discovery"` ## EndpointOut - `dialect`: string, required - `family`: string, required - `is_shared`: boolean, required - `params`: object - `url`: string, required ## ErrorOut As the WebSocket tells it (`majordom_did_encounter_error`): whether the integration still runs, its status says. - `id`: string, required - `message`: string, required ## ErrorResponse[DeviceIdTakenError] - `detail`: `DeviceIdTakenError`, required ## ErrorResponse[DeviceUnreachableError] - `detail`: `DeviceUnreachableError`, required ## ErrorResponse[MissingCredentialsError] - `detail`: `MissingCredentialsError`, required ## ErrorResponse[PairingFailedError] - `detail`: `PairingFailedError`, required ## HTTPValidationError - `detail`: list[`ValidationError`] ## Hotspot - `encrypted`: boolean, required - `frequency`: string, required - `quality`: number, required - `ssid`: string, required ## House - `hubs`: list[`Hub`], required - `id`: uuid, required - `name`: string, required - `note`: string, default `""` - `owner_id`: uuid, required - `rooms`: list[`RoomInfo`], required ## HouseInfo - `id`: uuid, required - `name`: string, required - `note`: string, default `""` - `owner_id`: uuid, required ## HttpMethod One of: `get`, `post`, `put`, `patch`, `delete` ## Hub - `access_expiration`: date-time, required - `hostname`: string, required - `house_id`: uuid, required - `id`: uuid, required - `name`: string, required ## HubAuthItems - `access_token`: string, required - `public_key`: string, required - `refresh_token`: string, required ## HubInfo - `house_id`: uuid, required - `id`: uuid, required - `name`: string, required ## HubPatch - `name`: string, required ## IntegrationErrorMessage A user-facing integration problem. `message` is plain language for display (with any call-to-action folded into the text); whether the integration still runs, its status says (IntegrationStatusMessage). Device-scoped problems travel on the device's `last_error` instead. `id` is stable per condition: a later message with the same `integration` and `id` replaces this one, and it stays until an IntegrationErrorResolvedMessage with them. - `id`: string, required - `integration`: string, required - `message`: string, required - `type`: `majordom_did_encounter_error`, default `"majordom_did_encounter_error"` ## IntegrationErrorResolvedMessage The integration's error with this `id` is gone: it cleared, or the integration stopped or restarted. - `id`: string, required - `integration`: string, required - `type`: `majordom_did_resolve_error`, default `"majordom_did_resolve_error"` ## IntegrationOut - `errors`: list[`ErrorOut`], required - `key`: string, required - `kind`: `StatusKind` | null, required - `name`: string, required - `needs`: list[`NeedOut`], required - `settings`: list[string], required - `status`: `PeripheralState`, required ## IntegrationStatusMessage An integration's state changed: `kind` says why it waits or failed, for the app to act on. A user-facing error comes with the states the user can act on (IntegrationErrorMessage). - `integration`: string, required - `kind`: `StatusKind` | null, required - `state`: `PeripheralState`, required - `type`: `majordom_did_change_status`, default `"majordom_did_change_status"` ## MissingCredentialsError the Hub lacks credentials of `credentials_type` to pair the device; nothing was saved - `credentials_type`: string, required - `device_id`: uuid | null - `msg`: string, required - `type`: `missing_credentials`, required ## NeedOut - `endpoint`: `EndpointOut` | list[`EndpointOut`] | null, required - `family`: string, required - `is_many`: boolean, default `false` - `is_required`: boolean, required - `provider`: string | list[string] | null, required ## Notification A general user-facing message an integration surfaces to the user as a floating tile in the app. Distinct from ``controller_did_encounter_error`` (which is specifically for integration failures/health) — use this for anything informational or advisory the user should see. ``ttl`` is how many seconds the tile stays before auto-dismissing; ``None`` keeps it until the user dismisses it. - `message`: string, required - `priority`: `NotificationPriority`, default `"normal"` - `ttl`: integer | null, default `null` - `type`: `NotificationType`, default `"info"` ## NotificationMessage A general user-facing notification from an integration — rendered as a floating tile. The nested `notification` carries the message, callout type (info/warning/error), delivery priority, and ttl. Distinct from IntegrationErrorMessage, which is specifically for failures. - `integration`: string, required - `notification`: `Notification`, required - `type`: `majordom_did_emit_notification`, default `"majordom_did_emit_notification"` ## NotificationPriority How insistently the notification is delivered (maps to the OS interruption levels). One of: `silent`, `normal`, `time_sensitive`, `urgent` ## NotificationType The callout style the app renders the notification with. One of: `info`, `warning`, `error` ## PairingFailedError the integration failed to pair; nothing was saved - `device_id`: uuid | null - `msg`: string, required - `type`: `pairing_failed`, required ## ParameterDataType One of: `none`, `bool`, `integer`, `decimal`, `enum`, `string`, `struct`, `data` ## ParameterRole One of: `sensor`, `control`, `event` ## ParameterState[TypeVar, Any] - `data_type`: `ParameterDataType`, required - `default_value`: any - `description`: string | null - `fields`: list[any] | null - `id`: uuid, required - `integration_data`: any, required - `max_value`: integer | number | null - `min_step`: integer | number | null - `min_value`: integer | number | null - `name`: string, required - `note`: string | null - `role`: `ParameterRole`, required - `unit`: `ParameterUnit`, default `"plain"` - `valid_values`: dict[str, string] | null - `value`: any - `visibility`: `ParameterVisibility`, required ## ParameterUnit One of: `plain`, `percentage`, `second`, `hertz`, `kilogram`, `arcdegree`, `meters`, `mps`, `mps2`, `m3h`, `rpm`, `newton`, `joule`, `kwh`, `watt`, `celsius`, `kelvin`, `mired`, `volt`, `ampere`, `lux`, `pascal`, `ppm`, `ugm3`, `bytes`, `bps`, `json`, `document` ## ParameterVisibility One of: `user`, `setting`, `system` ## ParameterVisibilityPatch - `visibility`: `ParameterVisibility`, required ## PeripheralState One of: `disabled`, `waiting`, `starting`, `running`, `failed` ## ProvidedCredentials What a pairing request actually supplies — paired with its type, so pairing can validate it against Discovery.expected_credentials_options instead of trusting whatever the integration guessed at discovery time. - `type`: `CredentialsType`, required - `value`: `CredentialsValue` | null ## RadioOut - `driver`: string | null, required - `firmware`: string | null, required - `held_by`: string | null, required - `is_busy`: boolean, required - `key`: string, required - `offers`: list[string], required - `options`: dict[str, list[string]], required - `path`: string, required - `used_by`: list[string], required ## RestRequest - `body`: `BridgeRequestBody`, required - `method`: `HttpMethod`, required - `path`: string, required ## Room - `devices`: list[`Device`], required - `house_id`: uuid, required - `id`: uuid, required - `name`: string, required - `note`: string, default `""` ## RoomCreate - `name`: string, required - `note`: string, default `""` ## RoomInfo - `house_id`: uuid, required - `id`: uuid, required - `name`: string, required - `note`: string, default `""` ## RoomPatch - `name`: string, required - `note`: string, default `""` ## Scene - `executables`: list[`_Executable`], required - `id`: string, required - `name`: string, required ## ServiceStatusResponse - `enabled`: boolean, required - `last_error`: string | null, required - `name`: string, required - `running`: boolean, required - `status`: `disabled` | `pending` | `starting` | `running` | `stopping` | `inactive` | `error`, required ## SettingsOut - `error`: string | null - `json_schema`: object, required - `values`: object, required ## StatusKind Why a peripheral waits or failed, for its owner to act on; the status's ``detail`` says it in words. One of: `needs-unbound`, `needs-starting`, `unused`, `retrying`, `stopped-itself`, `gave-up`, `invalid-settings` ## TokensPair - `access_token`: string, required - `refresh_token`: string, required ## User - `id`: uuid, required - `name`: string, required ## ValidationError - `ctx`: object - `input`: any - `loc`: list[string | integer], required - `msg`: string, required - `type`: string, required ## ValidationErrorItem FastAPI's request validation error, as its own HTTPValidationError documents it. - `ctx`: object | null - `input`: any - `loc`: list[string | integer], required - `msg`: string, required - `type`: string, required ## ValidationErrorResponse - `detail`: list[`ValidationErrorItem`], required ## WifiConnection - `password`: string, required - `ssid`: string, required ## _Condition - `type`: string, required. The type of model. ## _Executable - `delay_seconds`: number, default `0` - `type`: string, required. The type of model. # integration-sdk — full source # repo: https://github.com/MajorDom-Systems/integration-sdk branch: master commit: e5606c6d9da6b9fee14c599c15a3af2b0ed912bf # generated: 2026-11-16 — AUTO-GENERATED, do not edit by hand ## File tree .gitignore LICENSE README.md majordom_integration_sdk/__init__.py majordom_integration_sdk/capabilities/__init__.py majordom_integration_sdk/capabilities/ble.py majordom_integration_sdk/capabilities/ble_security.py majordom_integration_sdk/capabilities/ssdp.py majordom_integration_sdk/capabilities/zeroconf.py majordom_integration_sdk/controller/__init__.py majordom_integration_sdk/controller/abstract_controller.py majordom_integration_sdk/controller/output.py majordom_integration_sdk/dev/__init__.py majordom_integration_sdk/dev/cli.py majordom_integration_sdk/errors.py majordom_integration_sdk/files.py majordom_integration_sdk/parameter_audit.py majordom_integration_sdk/peripherals/__init__.py majordom_integration_sdk/peripherals/ble_proxy.py majordom_integration_sdk/peripherals/endpoint.py majordom_integration_sdk/peripherals/need.py majordom_integration_sdk/peripherals/peripheral.py majordom_integration_sdk/peripherals/service.py majordom_integration_sdk/peripherals/usb.py majordom_integration_sdk/platform.py majordom_integration_sdk/repository/__init__.py majordom_integration_sdk/repository/_record.py majordom_integration_sdk/repository/memory.py majordom_integration_sdk/repository/protocol.py majordom_integration_sdk/repository/sqlite.py majordom_integration_sdk/runtime/__init__.py majordom_integration_sdk/runtime/defaults.py majordom_integration_sdk/runtime/output.py majordom_integration_sdk/runtime/peripherals/__init__.py majordom_integration_sdk/runtime/peripherals/hardware/__init__.py majordom_integration_sdk/runtime/peripherals/hardware/drivers.py majordom_integration_sdk/runtime/peripherals/hardware/fixed.py majordom_integration_sdk/runtime/peripherals/hardware/host.py majordom_integration_sdk/runtime/peripherals/hardware/usb.py majordom_integration_sdk/runtime/peripherals/pinned.py majordom_integration_sdk/runtime/peripherals/providers/__init__.py majordom_integration_sdk/runtime/peripherals/providers/ble/__init__.py majordom_integration_sdk/runtime/peripherals/providers/ble/bluez.py majordom_integration_sdk/runtime/peripherals/providers/ble/cpc_hci.py majordom_integration_sdk/runtime/peripherals/providers/ble/router.py majordom_integration_sdk/runtime/peripherals/providers/ssdp.py majordom_integration_sdk/runtime/peripherals/providers/zeroconf.py majordom_integration_sdk/runtime/peripherals/services/__init__.py majordom_integration_sdk/runtime/peripherals/services/builtin.py majordom_integration_sdk/runtime/peripherals/services/compose.py majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol/Dockerfile majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol/docker-compose.yml majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol/entrypoint.sh majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol-sisdk/Dockerfile majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol-sisdk/entrypoint.sh majordom_integration_sdk/runtime/runtime.py majordom_integration_sdk/schemas/__init__.py majordom_integration_sdk/schemas/base.py majordom_integration_sdk/schemas/command.py majordom_integration_sdk/schemas/credentials.py majordom_integration_sdk/schemas/device.py majordom_integration_sdk/schemas/event.py majordom_integration_sdk/schemas/notification.py majordom_integration_sdk/schemas/parameter.py majordom_integration_sdk/schemas/settings.py majordom_integration_sdk/spec_drift.py majordom_integration_sdk/testing/__init__.py pyproject.toml tests/conftest.py tests/factories.py tests/runtime/conftest.py tests/runtime/support.py tests/runtime/test_binding.py tests/runtime/test_ble_router.py tests/runtime/test_defaults.py tests/runtime/test_hardware.py tests/runtime/test_integration.py tests/runtime/test_lifecycle.py tests/runtime/test_services.py tests/runtime/test_thread.py tests/runtime/test_thread_source.py tests/runtime/test_zeroconf.py tests/test_ble_security.py tests/test_cli.py tests/test_controller.py tests/test_credentials.py tests/test_dev.py tests/test_errors.py tests/test_files.py tests/test_main_parameter.py tests/test_notification.py tests/test_parameter_audit.py tests/test_peripherals.py tests/test_repository.py tests/test_schemas.py tests/test_spec_drift.py tests/test_version.py ================================================================================ # FILE: .gitignore ================================================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[codz] *$py.class # C extensions *.so # Distribution / packaging build/ dist/ *.egg-info/ *.egg # Unit test / coverage reports .coverage .coverage.* coverage.xml htmlcov/ .pytest_cache/ .hypothesis/ # Environments .env .envrc .venv env/ venv/ # The dev runner's settings and keys .majordom-dev/ # Poetry # poetry.lock # uncomment for applications, keep commented for libraries # Type checkers .mypy_cache/ .dmypy.json .pyre/ .pytype/ # Tools .ruff_cache/ .ropeproject # mkdocs (only relevant if you kept mkdocs.yml + docs/) /site .cache/ # IDEs .idea/ .vscode/ # OS .DS_Store Thumbs.db ================================================================================ # FILE: LICENSE ================================================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================================================ # FILE: README.md ================================================================================ Part of MajorDom — the next-gen smart home # majordom-integration-sdk Models, protocols, and tooling for building [MajorDom](https://majordom.io) integrations. An integration bridges an external protocol or platform (Matter, Zigbee, HomeKit, a vendor cloud, …) into the MajorDom language. This SDK is the contract: the schemas, the `AbstractController` framework, the device-repository protocol, discovery services, and a standalone dev runner so you can build and test an integration **without a running Hub**. The Hub itself depends on this same package — first-party integrations use no private shortcut. ## Install ```sh pip install majordom-integration-sdk ``` Requires Python 3.12+. ## Also a standalone IoT toolkit You don't need MajorDom to get value from this package. `majordom_integration_sdk.discovery` ships three fully working, standardized device-discovery services you can drop into **any** async Python project: - **Zeroconf / mDNS** (`ZeroconfDiscoveryService`) — browse Bonjour/mDNS services with a clean listener protocol, and — unusually — **reliable disappearance tracking**: it augments raw zeroconf with an active cache-poll + confirm-evict loop so you get accurate "device went away" events, not just arrivals. - **SSDP / UPnP** (`SSDPDiscoveryService`) — flexible, per-listener **configurable** search targets and refresh behavior over raw sockets, without dragging in a full UPnP stack. - **BLE** (`BLEDiscoveryService`) — a uniform listener interface over Bleak for advertisement scanning. All three share one `register(listener, …) → cancel` shape, run standalone (each module has a runnable `__main__` demo), and are a solid reference for implementing **standardized interfaces over messy IoT protocols** even if you never touch MajorDom. The `AbstractController` framework and the `DeviceRepositoryProtocol` + in-memory/SQLite implementations are equally reusable as a small, typed device-modelling toolkit. ## Documentation Full integration-author docs — models, the controller lifecycle, storing data, discovery, and a worked example — live at **[docs.majordom.io](https://docs.majordom.io/device-integration)**. The fastest way to start a new integration is the [integration-template](https://github.com/MajorDom-Systems/integration-template) repository (**Use this template → Create a new repository**). ## License See [LICENSE](LICENSE). For commercial licensing or partnership inquiries, contact us via [parker-industries.org/partnership](https://parker-industries.org/partnership). --- ## Development Setup: ```sh poetry install && poetry run poe install ``` This installs dependencies and the pre-commit hook that runs `poe check`. | Task | Description | |------|-------------| | `poe install` | Install deps and register the pre-commit hook | | `poe check` | Full quality pipeline (ruff, ty, pytest, poetry build/check) | | `poe check --ci` | Same, plus `git diff --exit-code` | Two long-lived branches: `develop` (integration branch, all work lands here) and `master` (protected, released). Releases are cut from `develop` via **Actions → Release**; see [ParkerIndustries/workflows](https://github.com/ParkerIndustries/workflows) for the CI/CD. ================================================================================ # FILE: majordom_integration_sdk/__init__.py ================================================================================ """MajorDom Integration SDK — models, protocols, and tooling for building integrations. Public submodules: - ``majordom_integration_sdk.schemas`` — the wire protocol (pydantic models shared with the Hub) - ``majordom_integration_sdk.controller`` — ``AbstractController`` + its ``ControllerOutput`` - ``majordom_integration_sdk.platform`` — ``Platform``: the host every peripheral runs on, as ``self.platform`` - ``majordom_integration_sdk.peripherals`` — ``Peripheral``, ``Need``/``Endpoint``, ``Service``: what runs around it - ``majordom_integration_sdk.capabilities`` — the contracts of in-process peripherals: BLE router, DNS-SD, SSDP - ``majordom_integration_sdk.repository`` — ``DeviceRepositoryProtocol`` + in-memory / SQLite implementations - ``majordom_integration_sdk.testing`` — shared test doubles for integration test suites - ``majordom_integration_sdk.dev`` — standalone runner for developing an integration without the Hub - ``majordom_integration_sdk.runtime`` — runs peripherals and binds their needs (the ``runtime`` extra) - ``majordom_integration_sdk.errors`` — errors an integration raises for the Hub to act on - ``majordom_integration_sdk.files`` — ``read_json`` / ``write_json``: files kept whole, for their owner alone The names an integration author reaches for most are re-exported here for convenience, e.g. ``from majordom_integration_sdk import AbstractController, Device``. """ from importlib.metadata import version from majordom_integration_sdk.controller import AbstractController, ControllerOutput, IntegrationError from majordom_integration_sdk.errors import DeviceIdTakenError, DeviceUnreachableError, MissingCredentialsError from majordom_integration_sdk.peripherals import ( STABLE_RUN, ComposeService, Endpoint, Need, NoSettings, Peripheral, PeripheralChange, PeripheralOutput, Peripherals, Service, SettingsExtraField, UsbDriver, ) from majordom_integration_sdk.platform import Platform from majordom_integration_sdk.repository import ( DeviceRepositoryMemory, DeviceRepositoryProtocol, SqliteDeviceRepository, ) from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.credentials import ProvidedCredentials, WifiCredentials from majordom_integration_sdk.schemas.device import Device, Discovery, Parameter from majordom_integration_sdk.schemas.event import DeviceParameterChange, Event __version__ = version("majordom-integration-sdk") __all__ = [ "AbstractController", "ControllerOutput", "IntegrationError", "Platform", "DeviceRepositoryProtocol", "DeviceRepositoryMemory", "SqliteDeviceRepository", "DeviceCommand", "Device", "Discovery", "Parameter", "ProvidedCredentials", "Event", "DeviceParameterChange", "MissingCredentialsError", "DeviceIdTakenError", "DeviceUnreachableError", "Need", "Endpoint", "Peripheral", "NoSettings", "PeripheralOutput", "Peripherals", "Service", "ComposeService", "UsbDriver", "PeripheralChange", "WifiCredentials", "STABLE_RUN", "SettingsExtraField", ] ================================================================================ # FILE: majordom_integration_sdk/capabilities/__init__.py ================================================================================ """The contracts of the peripherals the runtime provides in-process, for integrations to use through their needs: ``ble/router`` (`ble`, secured by `ble_security`), ``mdns/zeroconf`` (`zeroconf`) and ``upnp/ssdp`` (`ssdp`). Interfaces only: the implementations live in `majordom_integration_sdk.runtime`.""" from .ble import ( BLE_ROUTER, BLEBusyError, BLEConnection, BLEDiscoveryInfo, BLEDiscoveryListener, BLELease, BLEMatcher, BLEPairingError, BLERouter, BLESource, GattCharacteristic, GattService, OnAdvertisement, PairableBLEConnection, PausableBLESource, ScanModeBLESource, ) from .ble_security import LESecureConnections, SecureChannel, Unsecured from .ssdp import SSDP, UPNP_SSDP, SSDPDiscoveryInfo, SSDPDiscoveryListener from .zeroconf import ZEROCONF, Zeroconf, ZeroconfDiscoveryInfo, ZeroconfDiscoveryListener __all__ = [ "BLE_ROUTER", "ZEROCONF", "UPNP_SSDP", "BLEBusyError", "BLEConnection", "BLEDiscoveryInfo", "BLEDiscoveryListener", "BLELease", "BLEMatcher", "BLEPairingError", "BLERouter", "BLESource", "GattCharacteristic", "GattService", "OnAdvertisement", "PairableBLEConnection", "PausableBLESource", "ScanModeBLESource", "LESecureConnections", "SecureChannel", "Unsecured", "Zeroconf", "ZeroconfDiscoveryInfo", "ZeroconfDiscoveryListener", "SSDP", "SSDPDiscoveryInfo", "SSDPDiscoveryListener", ] ================================================================================ # FILE: majordom_integration_sdk/capabilities/ble.py ================================================================================ """The ``ble/router`` contract: one Bluetooth LE router that hears every radio and reaches every device. Integrations need it as `BLE_ROUTER` and get it at ``self.peripherals.instance(BLE_ROUTER)``; never raw Bluetooth, which the router holds. Its sources are the radios the runtime binds to it (``ble/bluez`` adapters, ``ble/silabs-cpc-hci``, ``ble/esphome-proxy`` nodes an integration brings along): `BLESource`s. Listeners register `BLEMatcher`s and hear about matching devices whichever source saw them. `BLERouter.connect` opens a GATT connection through the source that hears the device best; `BLERouter.exclusive` leases that one source to a device for as long as pairing it takes. Credentials go to a device only over a link a `SecureChannel` (`ble_security`) has secured first. bleak's advertisement types describe what is heard; this module imports them for type checking only. """ from __future__ import annotations import contextlib from collections.abc import Callable, Iterable from dataclasses import dataclass, field from typing import TYPE_CHECKING, Protocol, runtime_checkable from uuid import UUID from majordom_integration_sdk.peripherals.need import Need if TYPE_CHECKING: from bleak.backends.device import BLEDevice from bleak.backends.scanner import AdvertisementData type OnAdvertisement = Callable[[BLEDevice, AdvertisementData], None] @dataclass(frozen=True) class BLEMatcher: """What a listener wants to hear about; every field that is set must match. A manufacturer id alone selects protocols that advertise no service UUID, e.g. HomeKit (HAP-BLE) accessories by Apple's company id.""" service_uuid: UUID | None = None # advertised as a service or in the service data service_data_uuid: UUID | None = None # in the service data only (what the listener reads) manufacturer_id: int | None = None manufacturer_data_start: bytes = b"" local_name_prefix: str | None = None def matches(self, adv: AdvertisementData) -> bool: if self.service_uuid and str(self.service_uuid) not in {*adv.service_uuids, *adv.service_data}: return False if self.service_data_uuid and str(self.service_data_uuid) not in adv.service_data: return False if self.manufacturer_id is not None: data = adv.manufacturer_data.get(self.manufacturer_id) if data is None or not bytes(data).startswith(self.manufacturer_data_start): return False return not self.local_name_prefix or (adv.local_name or "").startswith(self.local_name_prefix) @dataclass class BLEDiscoveryInfo: device: BLEDevice advertisement: AdvertisementData source: str = "local" # the source that hears it best: "hci0", "esphome:", … rssi: int | None = None # as that source hears it last_seen: float = 0.0 # monotonic class BLEDiscoveryListener(Protocol): async def ble_did_discover_device(self, ble: BLERouter, info: BLEDiscoveryInfo): ... async def ble_did_update_device(self, ble: BLERouter, info: BLEDiscoveryInfo): ... async def ble_did_remove_device(self, ble: BLERouter, info: BLEDiscoveryInfo): ... @dataclass(frozen=True) class GattCharacteristic: uuid: str handle: int properties: tuple[str, ...] # "read", "write", "write-without-response", "notify", "indicate", … @dataclass(frozen=True) class GattService: uuid: str handle: int characteristics: tuple[GattCharacteristic, ...] class BLEConnection(Protocol): """An open GATT connection; characteristics are addressed by handle.""" @property def mtu(self) -> int: ... async def services(self) -> list[GattService]: ... async def read(self, handle: int) -> bytes: ... async def write(self, handle: int, data: bytes, is_response_needed: bool = True): ... async def start_notify(self, handle: int, callback: Callable[[bytes], None]): ... async def stop_notify(self, handle: int): ... async def disconnect(self): ... @runtime_checkable class PairableBLEConnection(BLEConnection, Protocol): """A connection that can encrypt its link by pairing (LE Secure Connections where both ends support it).""" async def pair(self): """Pairs "Just Works", encrypting the link. Raises `BLEPairingError`.""" ... async def unpair(self): """Forgets the bond; the link may drop.""" ... class BLESource(Protocol): """A radio that hears advertisements and can connect to devices: a local adapter or a proxy. Optional attributes the router reads: a true ``is_pairable`` when its connections are `PairableBLEConnection`s, ``free_slots``, the connections it can still open (a proxy has a few), None when it can't tell, and a true ``is_loss_reported`` when its radio going away is reported otherwise (an ESPHome node's API connection drops, and the integration takes the source away): the router then never restarts it for hearing nothing for a while.""" name: str async def start(self, on_advertisement: OnAdvertisement): ... async def stop(self): ... async def connect(self, address: str, on_disconnect: Callable[[], None]) -> BLEConnection: ... @runtime_checkable class PausableBLESource(BLESource, Protocol): """A source that can stop hearing without letting go of its radio, e.g. a proxy whose connections only work while it stays subscribed; a lease pauses one rather than stopping it.""" async def pause_scanning(self): ... async def resume_scanning(self): ... @runtime_checkable class ScanModeBLESource(BLESource, Protocol): """A source that scans passively (every advertiser, the listeners' matchers choose) or actively (asking for the scan responses that often carry the name): the router switches it for a pairing window. Called before `start` too; a running source applies a change itself.""" async def set_scan_mode(self, is_active: bool): ... class BLEBusyError(ConnectionError): """Every source that hears the device is leased to someone else.""" class BLEPairingError(ConnectionError): """The link could not be encrypted: pairing failed, or no source that hears the device can pair.""" @dataclass(frozen=True) class BLELease: """One source held for one device: it doesn't scan, and only the holder connects through it.""" address: str source: str owner: str _source: BLESource = field(repr=False) async def connect(self, on_disconnect: Callable[[], None] = lambda: None) -> BLEConnection: return await self._source.connect(self.address, on_disconnect) class BLERouter(Protocol): """Bluetooth LE across all sources: discovery for listeners, GATT connections on demand.""" def register(self, listener: BLEDiscoveryListener, matchers: Iterable[BLEMatcher | UUID]) -> Callable[[], None]: """Registers a listener for BLE devices matching any of ``matchers`` (a UUID matches that service). `ble_did_discover_device` is called when a device first matches, `ble_did_update_device` when its advertisement changes, `ble_did_remove_device` when no source has heard it for a while; devices heard before it registered are new to it. Returns a cancel function — call it on stop to deregister.""" ... async def connect(self, address: str, on_disconnect: Callable[[], None] = lambda: None) -> BLEConnection: """Opens a GATT connection to ``address`` through the source hearing it best, falling back to the others; leased sources are skipped. ``on_disconnect`` is called when the connection drops.""" ... def exclusive( self, address: str, *, owner: str, timeout: float = 30, wait: float = 1, is_pairing_needed: bool = False ) -> contextlib.AbstractAsyncContextManager[BLELease]: """Leases the source hearing ``address`` best to ``owner`` (e.g. while pairing it): that source pauses scanning and others' connects avoid it; the rest keep going. A leased source is waited for ``wait`` seconds before the next best is tried, round after round, until ``timeout`` raises `BLEBusyError`. With ``is_pairing_needed``, only sources that can pair are leased (`BLEPairingError` when none hears it).""" ... async def scan_actively(self, duration: float): """Scans actively for ``duration`` seconds (a pairing window): names often come only in the scan responses a passive scan never asks for.""" ... def devices(self) -> list[BLEDiscoveryInfo]: """Every device heard recently, as the source hearing it best sees it.""" ... BLE_ROUTER = Need[BLERouter]("ble", ["router"]) # optional: dataclasses.replace(it, is_required=False) ================================================================================ # FILE: majordom_integration_sdk/capabilities/ble_security.py ================================================================================ """Secure channels: how credentials (a Wi-Fi password, a Thread network key) are protected on a BLE connection before they are written to a device. An integration picks one per device and opens it on the leased connection:: async with ble.exclusive(address, owner=OWNER, is_pairing_needed=channel.is_pairing_needed) as lease: async with channel.secure(await lease.connect()) as connection: await connection.write(rpc, credentials) `LESecureConnections` encrypts the link by pairing. "Just Works" pairing, all a headless Hub can do, stops passive sniffing but not an active man in the middle during the pairing itself. A channel that authenticates at the application layer (e.g. Improv's proposed SPAKE2+ setup code) would yield a connection that encrypts the frames it writes instead, and works through any proxy. """ import contextlib import logging from collections.abc import AsyncGenerator from typing import Protocol from .ble import BLEConnection, BLEPairingError, PairableBLEConnection logger = logging.getLogger(__name__) class SecureChannel(Protocol): is_pairing_needed: bool # lease a source that can pair: `BLERouter.exclusive(..., is_pairing_needed=...)` def secure(self, connection: BLEConnection) -> contextlib.AbstractAsyncContextManager[BLEConnection]: """The connection to write credentials through, secured; raises `BLEPairingError` (fail closed).""" ... class LESecureConnections: """Pairs before anything is written: the link is encrypted, or nothing is yielded. The device decides LE Secure Connections over legacy pairing (firmware built for it accepts nothing else). It unpairs once done, as the pairing served only the setup, unless ``is_pairing_kept``.""" is_pairing_needed = True def __init__(self, is_pairing_kept: bool = False): self._is_pairing_kept = is_pairing_kept @contextlib.asynccontextmanager async def secure(self, connection: BLEConnection) -> AsyncGenerator[BLEConnection]: if not isinstance(connection, PairableBLEConnection): raise BLEPairingError("This Bluetooth source can't pair, so it can't encrypt the link") await connection.pair() try: yield connection finally: if not self._is_pairing_kept: with contextlib.suppress(Exception): await connection.unpair() class Unsecured: """Writes over the link as it is: only for firmware that can't pair, chosen explicitly.""" is_pairing_needed = False @contextlib.asynccontextmanager async def secure(self, connection: BLEConnection) -> AsyncGenerator[BLEConnection]: logger.warning("Writing credentials over an unencrypted Bluetooth link") yield connection ================================================================================ # FILE: majordom_integration_sdk/capabilities/ssdp.py ================================================================================ """The ``upnp/ssdp`` contract: hearing UPnP devices and services over SSDP. Integrations need it as `UPNP_SSDP` and get the runtime's listener at ``self.peripherals.instance(UPNP_SSDP)``: an `SSDP`. """ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import Protocol from majordom_integration_sdk.peripherals.need import Need @dataclass class SSDPDiscoveryInfo: addr: str host: str | None search_target: str | None service_name: str | None server: str | None cache_control: str | None location: str | None response: dict[str, str] class SSDPDiscoveryListener(Protocol): async def ssdp_did_discover_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): ... async def ssdp_did_update_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): ... async def ssdp_did_remove_service(self, ssdp: SSDP, info: SSDPDiscoveryInfo): ... class SSDP(Protocol): def register( self, listener: SSDPDiscoveryListener, search_target: str, mcast_group: str = "239.255.255.250", port: int = 1900, ) -> Callable[[], None]: """Calls ``listener`` about what answers ``search_target`` (``"ssdp:all"``, a device or service type) as it comes, changes and goes. Returns a cancel function — call it on stop to deregister.""" ... UPNP_SSDP = Need[SSDP]("upnp", ["ssdp"]) # optional: dataclasses.replace(it, is_required=False) ================================================================================ # FILE: majordom_integration_sdk/capabilities/zeroconf.py ================================================================================ """The ``mdns/zeroconf`` contract: browsing DNS-SD services over mDNS. Integrations need it as `ZEROCONF` and get the runtime's browser at ``self.peripherals.instance(ZEROCONF)``: a `Zeroconf`. """ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol from majordom_integration_sdk.peripherals.need import Need if TYPE_CHECKING: from zeroconf.asyncio import AsyncZeroconf @dataclass class ZeroconfDiscoveryInfo: """ * `type_`: fully qualified service type name * `name`: fully qualified service name * `port`: port that the service runs on * `weight`: weight of the service * `priority`: priority of the service * `properties`: dictionary of properties as raw bytes. Keys with `None` values are value-less attributes. * `decoded_properties`: `properties` decoded to `str` — use this for most integrations. * `text`: raw TXT record bytes — use only if you need to parse the record manually. * `server`: fully qualified name for service host (defaults to name) * `host_ttl`: ttl used for A/SRV records * `other_ttl`: ttl used for PTR/TXT records * `addresses` and `parsed_addresses`: List of IP addresses (either as bytes, network byte order, or in parsed form as text; at most one of those parameters can be provided) * interface_index: scope_id or zone_id for IPv6 link-local addresses i.e. an identifier of the interface where the peer is connected to """ type_: str name: str server: str | None port: int | None addresses: list[bytes] | None parsed_addresses: list[str] | None weight: int | None priority: int | None properties: dict[bytes, bytes | None] decoded_properties: dict[str, str | None] text: bytes host_ttl: int | None other_ttl: int | None interface_index: int | None def __eq__(self, other: object) -> bool: if not isinstance(other, ZeroconfDiscoveryInfo): return NotImplemented # exclude host_ttl / other_ttl — they change on every re-announcement return ( self.type_ == other.type_ and self.name == other.name and self.server == other.server and self.port == other.port and self.addresses == other.addresses and self.parsed_addresses == other.parsed_addresses and self.weight == other.weight and self.priority == other.priority and self.properties == other.properties and self.text == other.text and self.interface_index == other.interface_index ) class ZeroconfDiscoveryListener(Protocol): async def zeroconf_did_discover_service(self, zeroconf: Zeroconf, info: ZeroconfDiscoveryInfo): ... async def zeroconf_did_update_service(self, zeroconf: Zeroconf, info: ZeroconfDiscoveryInfo): ... async def zeroconf_did_remove_service(self, zeroconf: Zeroconf, type_: str, name: str): """Fired on mDNS goodbye packets (TTL=0) or when a silent departure is confirmed: A/AAAA records expired (~120s TTL) and a follow-up async_request got no response. For faster detection, implement liveness checks at the pairing/connection layer.""" ... class Zeroconf(Protocol): def register(self, listener: ZeroconfDiscoveryListener, services: set[str]) -> Callable[[], None]: """Calls ``listener`` about the services of the given types (``"_hap._tcp.local."``) as they come, change and go. Returns a cancel function — call it on stop to deregister.""" ... @property def async_zeroconf(self) -> AsyncZeroconf | None: """The zeroconf instance it browses with, for libraries that take one (aiohomekit); None until it starts.""" ... ZEROCONF = Need[Zeroconf]("mdns", ["zeroconf"]) # optional: dataclasses.replace(it, is_required=False) ================================================================================ # FILE: majordom_integration_sdk/controller/__init__.py ================================================================================ """The integration controller framework — the interface the Hub drives.""" # The output first: it imports the controller last, once the names the controller takes from it exist from .output import ControllerOutput, IntegrationError, LoggingControllerOutput # isort: split from .abstract_controller import AbstractController __all__ = ["AbstractController", "ControllerOutput", "IntegrationError", "LoggingControllerOutput"] ================================================================================ # FILE: majordom_integration_sdk/controller/abstract_controller.py ================================================================================ """ Entrypoint and lifecycle boundary for an integration's Controller. See docs.majordom.io/device-integration for the full integration guide. """ from __future__ import annotations import re from abc import ABC, abstractmethod from collections.abc import Sequence from typing import Any, cast, final from uuid import UUID, uuid5 from pydantic import BaseModel from slugify import slugify from majordom_integration_sdk.controller.output import ControllerOutput, LoggingControllerOutput from majordom_integration_sdk.peripherals import Need, Peripheral, PeripheralChange from majordom_integration_sdk.platform import Platform from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import Device, DeviceState, Discovery, Parameter, ProvidedCredentials _NAME_HELP = ( "The integration name is auto-derived from your controller class name; set a class-level " '`name` only to override it (e.g. `name = "ZigBee"`). ' "See the example integration at https://docs.majordom.io/device-integration" ) def _titleize(class_name: str) -> str: """Human-readable integration name derived from a controller class name. Strips a trailing "Controller" and splits CamelCase/PascalCase into spaced words: ``HueController`` -> ``"Hue"``, ``ZigBeeController`` -> ``"Zig Bee"``. Set an explicit ``name`` on the subclass to override when you want different casing (e.g. ``"ZigBee"``). """ base = class_name[: -len("Controller")] if class_name.endswith("Controller") else class_name words = re.findall(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+", base) return " ".join(words) or base class AbstractController[ TDevice: Device, TParameter: Parameter, TSettings: BaseModel = Any, TDeviceState: DeviceState = DeviceState, ](Peripheral[TSettings], ABC): """ Base class for all integration controllers. Defines the interface the Hub uses to interact with an integration — its package's ``peripherals(platform)`` builds the subclass, the runtime starts and stops it, and the Hub drives it by calling these methods. A controller is a `Peripheral` like any other: the runtime starts it once its required needs are bound to what runs, stops it when one is lost, and hands moved needs, settings and platform facts over to its hooks. Its integration package exports it next to the servers it needs, which run while it does, given the platform the Hub builds for the integration:: def peripherals(platform: Platform) -> list[Peripheral]: return [matterjs_server(), MatterController(platform)] It holds: - ``self.platform``: the host, the same for every peripheral, given to its constructor: its facts (``region``, ``wifi``, ``thread_dataset``), its device repository and a documents folder, scoped to the controller (``self.platform.device_repository(self)``, ``self.platform.documents_folder(self)``); - ``self.output``: what it reports (``controller_did_…``: discoveries, devices, events, errors, notifications, what it provides), which the runtime relays to the Hub; it logs them in library mode until you give yours; - ``self.settings``: its validated ``Settings``, declared as a nested ``class Settings(BaseModel)`` named as the third type parameter, ``AbstractController[Device, Parameter, "HueController.Settings"]``; `NoSettings` without; - its device-state model, the fourth type parameter (`DeviceState` by default), returned by ``device_state_type``: what ``pair_device`` is given as its draft and returns; - ``self.peripherals``: the endpoints its needs are bound to (``endpoint()``, ``endpoints()``, ``instance()``). In library mode, with no runtime, give it any settings, hand the bound needs over yourself and, to hear what it reports rather than read it in the log, your output:: controller = HueController(platform, settings=HueController.Settings(bridge="192.168.1.2")) controller.peripherals = Peripherals({"mdns": Endpoint("mdns", "zeroconf", instance=zeroconf)}) controller.output = MyOutput() # a ControllerOutput """ def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) # Auto-derive `name` from the class name unless the subclass set one explicitly. if "name" not in cls.__dict__: cls.name = _titleize(cls.__name__) # A controller reports through the controller calls alone: the runtime's output answers the peripheral ones too output: ControllerOutput = LoggingControllerOutput() def __init__(self, platform: Platform, *, settings: TSettings | None = None): """``settings`` hold until the user changes them (the runtime keeps them): the defaults of ``Settings`` without. Keep these parameters when you override it.""" self.platform = platform self.settings = settings if settings is not None else self.Settings() # Abstract @property @abstractmethod def discoveries(self) -> dict[UUID, Discovery]: """ Returns the current set of unpaired, discoverable devices as a cached snapshot. The ID for a given physical device must remain stable. Do not trigger any scanning here — only return already-cached data. """ # TODO: save datetime and remove expired return {} name: str """ Human-readable name of the integration (e.g. "HomeKit", "ZigBee"). Auto-derived from the controller class name by default (``HueController`` -> "Hue", ``ZigBeeController`` -> "Zig Bee"), so you usually don't set it. Set it on your subclass only to override the casing/wording: class ZigBeeController(AbstractController[Device, Parameter]): name = "ZigBee" It identifies the integration, so it's a constant of the class rather than per-instance state: its `slug()` is the controller's ``key``, which the runtime knows it by and the platform scopes its devices (``Device.integration``) and documents folder by. """ @property def key(self) -> str: return self.slug() needs: Sequence[Need] = () """What the integration requires from its environment: everything external, which something else must provide — radios (``Need("zigbee", ["ezsp"])``), the Bluetooth router (`BLE_ROUTER`), DNS-SD (`ZEROCONF`), SSDP (`UPNP_SSDP`) and the services its integration provides next to it. Bound ones arrive in ``self.peripherals`` keyed by family, an in-process one typed by its need: ``self.peripherals.instance(BLE_ROUTER)``; in library mode hand them over yourself. A required need that can't be bound keeps the integration from starting (the Hub tells the user what it waits for, the log why); an optional one arrives once its provider runs, as it appears (`needed_peripheral_did_change`). Never need raw Bluetooth: the router holds every radio.""" async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: """A bound need was lost, appeared, or moved; ``self.peripherals`` is already updated. Return True when handled in place (e.g. Matter keeps working over IP without Thread). False (the default) restarts the integration. A lost required need stops it instead, until it is back. """ return False async def settings_did_change(self, before: TSettings) -> bool: """The integration's settings changed; ``self.settings`` already holds the new ones. Return True when applied in place; False (the default) restarts the integration. """ return False async def platform_facts_did_change(self, before: Platform) -> bool: """The host's facts changed (region, Wi-Fi, Thread network); ``self.platform`` holds the new ones. Return True (the default) when they don't concern it or were applied in place; False restarts the integration. One that reads them only when it acts (pairing a device) needs no override. """ return True # TODO: review if these two are needed, test the implementation @property def device_type(self) -> type[TDevice]: """Override to return a Device subclass. Hub will deserialize devices into this type before passing them to other controller methods.""" return cast(type[TDevice], Device) @property def device_state_type(self) -> type[TDeviceState]: """Override to return a DeviceState subclass. Hub will validate the pairing draft into this type before passing it to ``pair_device``.""" return cast(type[TDeviceState], DeviceState) @property def parameter_type(self) -> type[TParameter]: """Override to return a Parameter subclass. Hub will deserialize parameters into this type before passing them to other controller methods.""" return cast(type[TParameter], Parameter) # Lifecycle @abstractmethod async def start(self): """ Starts the integration. Called by the runtime once its required needs are bound to what runs, and again after a stop: a restart, a hook it didn't take, a retry after a failure, the user enabling it. Register discovery services, subscribe to events, and check the status of already-paired devices here. Raise when it can't start: it is tried again later, then failed. """ @abstractmethod async def stop(self): """ Stops the integration. Called by the runtime on Hub shutdown, when it is disabled, loses a required need or restarts, and after a start that failed or was cut short. Cancel running tasks and release all held resources, also after a partial start, and leave the object clean for the next ``start``: nothing in flight (a pairing) may take resources after it. """ # Hub -> device async def start_pairing_window(self, duration_sec: int, credentials: ProvidedCredentials | None = None): # noqa: B027 (optional no-op hook, not abstract) """ Temporarily enables protocol-level discovery mechanisms that are not continuously active. Must only be used when default continuous discovery options aren't available or are insufficient. Does not affect, nor does use always-on discovery channels such as mDNS or SSDP. Used to trigger short-lived scan/inquiry modes for transports that require explicit activation (e.g. Zigbee permit-join style discovery, BLE scan bursts, proprietary radios). Devices discovered during this window may be eligible for onboarding via the pairing API. If devices are not successfully paired within the window, they must be disconnected. """ pass @abstractmethod async def pair_device( self, discovery: Discovery, draft: TDeviceState, credentials: ProvidedCredentials | None ) -> TDeviceState: """ Pairs a discovered device to the Hub and returns ``draft`` filled in. Called when the user initiates pairing from the UI. The Hub builds ``draft`` (no record exists yet): the user's fields (name, room, icon, category, note), ``id`` the Hub's own (read-only: never change it), ``physical_id`` the discovery's id as a placeholder, ``integration`` this controller's key. When the user picked an existing record to pair onto, it carries that record's data, its ``id``, ``physical_id`` and ``integration_data`` included: decide what in it is stale. Fill in what the device is: ``parameters``, ``integration_data``, its ``physical_id`` (``device_uuid``, what you look the device up by from now on), ``available``, … and return it. The Hub then saves it to its database, reports it connected if you set it ``available``, and calls ``fetch``. So: - don't use the device repository: nothing is saved during pairing; - report nothing about this device (no ``controller_did_connect_device``, no events) until the Hub saved it; - once the ``physical_id`` is known, call ``check_device_id`` before anything irreversible; - keep what the device needs from now on (a key just set on it) in ``integration_data``, filled in *before* each irreversible step: it is saved with the device, so no storage of your own is needed. On any failure but a refused id, and when the Hub fails to save what you return, it calls ``unpair(draft)`` with the draft as far as you filled it, to roll back. Idempotent, like ``fetch``: called again after a failed or rolled-back attempt, bring the device to a known-good paired state from whatever the last one left. Check each step and redo only what is missing or stale (a key already set is checked, not set again), so a device found already paired is confirmed and returned, not refused. Raise when it can't pair (`MissingCredentialsError` before touching the device when credentials are lacking). """ @abstractmethod async def unpair(self, device: TDevice): """ Unpairs a device from the Hub. Called when the user initiates removal from the UI. Also the rollback of a failed pairing: the Hub calls it with the draft as ``pair_device`` left it, at any stage. Undo, in reverse order of pairing, only what would block a clean re-pair once the draft is lost (a key set on the device, a pairing the accessory holds); what stays harmless (a node left on a fabric or network, offered again as a discovery) needs no undo. Tolerate any partial state, never wait for the user, and go as far as you can: it is best effort, within the Hub's timeout. Calling it again must work: on a device already unpaired, or never fully paired, it does nothing more. Raise `DeviceUnreachableError` when the device can't be reached to undo its pairing, after forgetting your own state of it. """ @abstractmethod async def identify(self, device: TDevice): """ Asks the device to produce an identifying signal (e.g. blink a light, play a sound). Called when the user triggers identification from the UI. """ @abstractmethod async def fetch(self, device: TDevice): """ Brings the device to a known-good state; called after pairing, on a manual refresh, and to revive a device that is unavailable. Idempotent: - check the device answers and read its current values, reported through the normal events; - check its event subscription and subscribe again only when it is gone, never a second one; - finish in bounded time; a sleeping battery device that doesn't answer is not a failure. """ @abstractmethod async def send_command(self, command: DeviceCommand, device: TDevice, parameter: TParameter): """ Sends a control command targeting a specific device parameter. Called by the Hub when the user or an automation changes a parameter value. """ # helpers / services @final @classmethod def slug(cls) -> str: """Slugified name of the integration: the controller's ``key``, which the runtime and the Hub know it by and its devices and documents folder are scoped by. """ slug = slugify(cls.name) if not slug: raise ValueError( f"{cls.__name__}'s name {cls.name!r} has no letters or digits to build a slug from. {_NAME_HELP}" ) return slug @final def namespace_uuid(self) -> UUID: """Namespace UUID for the integration - used to generate device and parameter UUIDs""" return UUID(int=0) # TODO: consider basing it on hub's mac address @final def integration_uuid(self) -> UUID: """Unique identifier of the integration""" return uuid5(self.namespace_uuid(), self.key) @final def device_uuid(self, raw: str | bytes, strip: str = ":-") -> UUID: """The ``physical_id`` of a device from what is unique to it (MAC, serial number), seeded by the integration: a name or an address two devices share gives them the same id, and the second can't be paired. A string is normalised (lowercased, whitespace and every char in ``strip`` dropped) so "AA:BB-cc" and "aabbcc" agree; bytes (a raw MAC or UUID) are taken as they are.""" return uuid5(self.integration_uuid(), _normalised(raw, strip)) @final async def check_device_id(self, physical_id: UUID, draft: TDeviceState): """Raises `DeviceIdTakenError` when another record holds ``physical_id``, the one ``pair_device`` gives the device ``draft`` pairs. The record the user picked to pair onto (``draft.id``, its Hub id) is not another. Optional: call it in ``pair_device`` as soon as the physical id is known, before anything irreversible.""" await self.platform.check_device_id(physical_id, draft) @final def parameter_uuid(self, physical_id: UUID, raw: str | bytes, strip: str = ":-") -> UUID: """The id of a parameter from an identifier unique within its device, seeded by the device's ``physical_id`` (stable and known from protocol data alone, unlike the Hub's ``id``); normalised as in ``device_uuid``.""" return uuid5(physical_id, _normalised(raw, strip)) # def add_service_coroutine(self, coroutine: Callable[[], Awaitable]): ... # FUTURE # def add_service_thread(self, thread: Thread): ... # FUTURE # def schedule_task(self, callback: Callable[[], Awaitable] | Callable[[], Any], interval: float): ... # FUTURE # def search_native_parameter(self, name: str) -> Parameter | None: ... # FUTURE def _normalised(raw: str | bytes, strip: str) -> str | bytes: if isinstance(raw, bytes): return raw return "".join(char for char in raw.lower() if not char.isspace() and char not in strip) ================================================================================ # FILE: majordom_integration_sdk/controller/output.py ================================================================================ """What an integration reports back to the Hub, through its ``self.output``.""" from __future__ import annotations import logging from collections.abc import Iterable from dataclasses import dataclass from typing import Any, Protocol, overload from uuid import UUID from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.schemas.event import Event from majordom_integration_sdk.schemas.notification import Notification logger = logging.getLogger(__name__) @dataclass(frozen=True) class IntegrationError: """A problem with the whole integration, active until it is resolved or the integration restarts.""" # Stable per condition, e.g. "server-unreachable": links a report to its resolve. Scoped to the integration; # the "hub-" prefix is reserved for the errors the Hub reports on its behalf. id: str message: str # plain language, with any call-to-action in the text # False when it can't go on: it is stopped, and started again after each retry delay, then failed is_still_running: bool = True class ControllerOutput(Protocol): """ Defines the callback interface for passing data from an integration back to the Hub: a controller's ``self.output``, which the runtime sets (it relays to the Hub). Without one, in library mode, it logs every call (`LoggingControllerOutput`); give it yours: ``controller.output = MyOutput()``. """ async def controller_did_receive_discovery(self, controller: AnyController, discovery: Discovery): ... async def controller_did_update_discovery(self, controller: AnyController, discovery: Discovery): ... async def controller_did_lose_discovery(self, controller: AnyController, discovery_id: UUID): ... @overload async def controller_did_connect_device(self, controller: AnyController, *, physical_id: UUID): ... @overload async def controller_did_connect_device(self, controller: AnyController, *, device_id: UUID): ... async def controller_did_connect_device( self, controller: AnyController, *, physical_id: UUID | None = None, device_id: UUID | None = None ): """A paired device connected. Integrations pass its ``physical_id``; its ``device_id`` is accepted too, e.g. from a relay passing it on under the Hub's id.""" ... @overload async def controller_did_lose_device(self, controller: AnyController, *, physical_id: UUID): ... @overload async def controller_did_lose_device(self, controller: AnyController, *, device_id: UUID): ... async def controller_did_lose_device( self, controller: AnyController, *, physical_id: UUID | None = None, device_id: UUID | None = None ): """Paired device became unreachable while the Hub is running (not just at startup/reboot). Ids as in ``controller_did_connect_device``.""" ... async def controller_did_receive_events(self, controller: AnyController, events: Iterable[Event]): """Report device-domain events (e.g. DeviceParameterChange) observed by the controller.""" ... async def controller_did_encounter_error(self, controller: AnyController, error: IntegrationError): """A user-facing problem the integration hit — surfaced to the user, not the developer. Use this for things the user should know about or can act on (a wrong setup, an unplugged radio); developer/technical detail goes to the logs instead. ``error.message`` is plain language — include any call-to-action right in the text. Problems scoped to one device belong on that device's ``last_error``, not here. The error stays active until ``controller_did_resolve_error`` with its ``id``, or until the integration stops. Reporting an active ``id`` again replaces it, so it is fine to report on every failed attempt; several ids can be active at once. A controller that can't go on reports an error that isn't ``is_still_running``: it is stopped, started again after each of the runtime's retry delays (5, 30, 120 s), then failed until the user restarts it, ``error.message`` saying why: report it right from the task that found it (the runtime stops the controller in a task of its own; your ``stop`` cancels that task before it awaits it). One that can't start raises from ``start``. """ ... async def controller_did_resolve_error(self, controller: AnyController, error_id: str): """The problem reported with ``error_id`` is gone. Resolving an id that isn't active does nothing.""" ... async def controller_did_emit_notification(self, controller: AnyController, notification: Notification): """Surface a general user-facing notification — a floating tile in the app. Unlike ``controller_did_encounter_error`` (specifically for failures/health), this is for anything informational or advisory: a firmware update is available, a device needs a physical action, a routine finished. The ``Notification`` carries the message plus its callout ``type`` (info/warning/error), delivery ``priority``, and ``ttl`` (seconds before auto-dismiss). """ ... async def controller_did_change_provided(self, controller: AnyController): """What it ``provides`` changed on its own, e.g. ESPHome's Bluetooth proxies as nodes come and go: the runtime reads it again. The runtime's output takes this one itself: the Hub's needn't implement it.""" return class LoggingControllerOutput(ControllerOutput): """A ``ControllerOutput`` that logs every callback: the Hub's stand-in for dev runs and library mode.""" async def controller_did_receive_discovery(self, controller: AnyController, discovery: Discovery): logger.info(f"discovered {discovery.device_name} ({discovery.transport}) id={discovery.id}") async def controller_did_update_discovery(self, controller: AnyController, discovery: Discovery): logger.info(f"updated discovery {discovery.id}") async def controller_did_lose_discovery(self, controller: AnyController, discovery_id: UUID): logger.info(f"lost discovery {discovery_id}") async def controller_did_connect_device( self, controller: AnyController, *, physical_id: UUID | None = None, device_id: UUID | None = None ): logger.info(f"connected device {physical_id or device_id}") async def controller_did_lose_device( self, controller: AnyController, *, physical_id: UUID | None = None, device_id: UUID | None = None ): logger.info(f"lost device {physical_id or device_id}") async def controller_did_receive_events(self, controller: AnyController, events: Iterable[Event]): for event in events: logger.info(f"event {type(event).__name__}: {event!r}") async def controller_did_encounter_error(self, controller: AnyController, error: IntegrationError): stopped = "" if error.is_still_running else ", it can't go on" logger.error(f"integration error {error.id}{stopped}: {error.message}") async def controller_did_resolve_error(self, controller: AnyController, error_id: str): logger.info(f"integration error {error_id} resolved") async def controller_did_emit_notification(self, controller: AnyController, notification: Notification): logger.info(f"notification [{notification.type.value}/{notification.priority.value}]: {notification.message}") async def controller_did_change_provided(self, controller: AnyController): logger.info(f"{controller.key} changed what it provides") # Last, once the names the controller takes from here exist: the annotations above then evaluate from majordom_integration_sdk.controller.abstract_controller import AbstractController # noqa: E402 # any integration: its type parameters are invariant, so the bare generic would accept only the defaults type AnyController = AbstractController[Any, Any, Any, Any] ================================================================================ # FILE: majordom_integration_sdk/dev/__init__.py ================================================================================ """Run one integration controller standalone — no Hub process. This is the "run standalone, then bridge into the MajorDom language" half of the integration workflow: the runtime (the ``runtime`` extra) runs the controller among the SDK's `default_peripherals()` as under the Hub — the radios it finds, the Bluetooth router over the local adapters, DNS-SD, SSDP and the containers it runs — and starts it once its needs are bound, then you watch what it discovers/reports on the console. import asyncio import majordom_hue # your integration from majordom_integration_sdk.dev import run_controller asyncio.run(run_controller(majordom_hue.peripherals)) # its controller and the servers it needs Without Docker, ``pinned=[Endpoint(...)]`` gives the endpoints of the servers you run yourself; ``runtime_peripherals=[HostNetwork(), ...]`` runs only those around it (no USB scanning); ``peripherals={...}`` skips the runtime altogether (library mode). """ from __future__ import annotations import asyncio import importlib.util import logging from collections.abc import Callable, Mapping, Sequence from dataclasses import replace from pathlib import Path from typing import TYPE_CHECKING, Any from majordom_integration_sdk.controller.abstract_controller import AbstractController from majordom_integration_sdk.controller.output import ControllerOutput, LoggingControllerOutput from majordom_integration_sdk.peripherals import Bound, Endpoint, Peripheral, Peripherals from majordom_integration_sdk.platform import Platform from majordom_integration_sdk.repository.sqlite import SqliteDeviceRepository if TYPE_CHECKING: from majordom_integration_sdk.controller.output import AnyController from majordom_integration_sdk.runtime import PeripheralStatus, Runtime logger = logging.getLogger("majordom_integration_sdk.dev") STORAGE_ROOT = Path(".majordom-dev") # where a standalone run keeps what it stores, unless told otherwise def build_platform(*, storage_root: Path | None = None, db_path: str | Path | None = None) -> Platform: """Assemble the host for a standalone run, as the Hub gives it to every peripheral. ``db_path`` selects a file-backed :class:`SqliteDeviceRepository` (state survives restarts); omit it for an in-memory repository. The storage root, where each peripheral gets its documents folder, defaults to `STORAGE_ROOT`. """ root = Path(storage_root) if storage_root is not None else STORAGE_ROOT root.mkdir(parents=True, exist_ok=True) platform = Platform(documents_root=root) if db_path is not None: return replace(platform, make_device_repository=lambda key: SqliteDeviceRepository(db_path, key).session()) return platform class LoggingRuntimeOutput: """A ``RuntimeOutput`` that logs every change of status: why a peripheral waits or failed.""" def peripheral_did_change_status(self, peripheral: Peripheral, status: PeripheralStatus): logger.info(f"{peripheral.key} {status}") def peripheral_did_learn(self, peripheral: Peripheral, facts: Mapping[str, Any]): logger.info(f"{peripheral.key} learned {', '.join(facts)}") # the runtime's platform took them def peripheral_did_disappear(self, peripheral: Peripheral): logger.info(f"{peripheral.key} is gone") def build_runtime( integration: Sequence[Peripheral], data: Path, *, runtime_peripherals: Sequence[Peripheral] | None = None, pinned: Sequence[Endpoint] = (), platform: Platform, controller_output: ControllerOutput | None = None, ) -> Runtime: """The runtime for one integration, as under the Hub: the endpoints you pin first, then ``runtime_peripherals`` (`default_peripherals()` by default), then what the integration exports, all on ``platform`` (the one its controller was given), what its controller reports going to ``controller_output`` (logged by default). Needs the ``runtime`` extra.""" if importlib.util.find_spec("serial") is None: raise ImportError( "Resolving needs takes the runtime — install it with:\n" ' pip install "majordom-integration-sdk[runtime,ble,discovery]"\n' "or pass peripherals={...} yourself." ) from majordom_integration_sdk.runtime import Pinned, Runtime, default_peripherals around = default_peripherals() if runtime_peripherals is None else runtime_peripherals peripherals = [Pinned(*pinned), *around, *integration] return Runtime( data, peripherals, platform=platform, controller_output=controller_output, output=LoggingRuntimeOutput() ) class Runner: """Runs one controller standalone: under ``runtime``, which starts it once its needs are bound and hands moved peripherals, settings and platform facts over as under the Hub; or, without, with the needs bound by hand.""" def __init__(self, controller: AnyController, runtime: Runtime | None = None): self.controller, self.runtime = controller, runtime self._is_started = False @property def is_running(self) -> bool: if self.runtime is None: return self._is_started from majordom_integration_sdk.runtime import PeripheralState return self.runtime.status(self.controller).state == PeripheralState.RUNNING async def start(self): if self.runtime: await self.runtime.start() return await self.controller.start() self._is_started = True logger.info(f"{self.controller.name} started — watching for devices.") async def stop(self): if self.runtime: await self.runtime.stop() elif self._is_started: await self.controller.stop() self._is_started = False type Integration = Callable[[Platform], Sequence[Peripheral]] # what an integration package exports: peripherals async def run_controller( integration: Integration, *, storage_root: Path | None = None, db_path: str | Path | None = None, peripherals: Mapping[str, Bound] | None = None, runtime_peripherals: Sequence[Peripheral] | None = None, pinned: Sequence[Endpoint] = (), **platform: Any, ): """Start what ``integration`` exports (its ``peripherals``: the controller and the servers it needs) under the runtime, or only its controller with the ``peripherals`` you bind, and run until interrupted (Ctrl-C), then stop everything cleanly. It is given its platform as by the Hub, ``platform`` overriding fields of `Platform`, e.g. ``region``; ``runtime_peripherals`` and ``pinned`` go to the runtime (`build_runtime`).""" logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s") exported = integration(replace(build_platform(storage_root=storage_root, db_path=db_path), **platform)) runner = _runner(exported, storage_root, peripherals, runtime_peripherals, pinned, LoggingControllerOutput()) await runner.start() try: await asyncio.Event().wait() # run forever until cancelled except (KeyboardInterrupt, asyncio.CancelledError): pass finally: await runner.stop() logger.info(f"{runner.controller.name} stopped.") def _runner( exported: Sequence[Peripheral], storage_root: Path | None, peripherals: Mapping[str, Bound] | None, runtime_peripherals: Sequence[Peripheral] | None, pinned: Sequence[Endpoint], controller_output: ControllerOutput, ) -> Runner: """What an integration exported, run around its one controller, which reports to ``controller_output``.""" controllers = [peripheral for peripheral in exported if isinstance(peripheral, AbstractController)] if len(controllers) != 1: raise ValueError(f"An integration exports one controller, not {len(controllers)}: {list(exported)}") controller, root = controllers[0], Path(storage_root) if storage_root is not None else STORAGE_ROOT if peripherals is not None: controller.peripherals, controller.output = Peripherals(peripherals), controller_output return Runner(controller) runtime = build_runtime( exported, root / "runtime", runtime_peripherals=runtime_peripherals, pinned=pinned, platform=controller.platform, controller_output=controller_output, ) return Runner(controller, runtime) def __getattr__(name: str): # `run_cli` (interactive REPL) needs the optional `cli` extra — typer-shell + rich. Import it # lazily so `dev` (and `run_controller`) stay usable without those dependencies installed. if name == "run_cli": try: from .cli import run_cli except ImportError as exc: # pragma: no cover - only when the extra is missing raise ImportError( "The interactive CLI needs extra dependencies — install them with:\n" ' pip install "majordom-integration-sdk[cli]"' ) from exc return run_cli raise AttributeError(f"module {__name__!r} has no attribute {name!r}") __all__ = [ "run_controller", "run_cli", "build_platform", "build_runtime", "Runner", "LoggingControllerOutput", "LoggingRuntimeOutput", ] ================================================================================ # FILE: majordom_integration_sdk/dev/cli.py ================================================================================ """Interactive REPL for running one integration standalone — the ``majordom-integration-sdk[cli]`` extra. Ported from the MajorDom Hub's operator CLI and scoped to a single controller: start it under the runtime (its needs bound as under the Hub) with a local repository, then pair / control / inspect devices, and see or pin what its needs are bound to, from a prompt. Where :func:`run_controller` just *watches*, this lets you *drive* the integration by hand. Needs the ``cli`` extra (typer-shell + rich):: pip install "majordom-integration-sdk[cli]" import asyncio from majordom_integration_sdk.dev import run_cli import majordom_matter # your integration asyncio.run(run_cli(majordom_matter.peripherals, db_path="devices.db")) """ from __future__ import annotations import asyncio import builtins import json import logging import shutil import sys from collections.abc import Mapping, Sequence from dataclasses import replace from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Any from uuid import UUID, uuid4, uuid5 import rich from typer_shell import make_typer_shell from ..controller.output import ControllerOutput from ..peripherals import Bound, Endpoint, Peripheral from ..schemas.command import DeviceCommand from ..schemas.credentials import CredentialsType, ProvidedCredentials from ..schemas.event import DeviceParameterChange from ..schemas.parameter import ParameterRole from . import Integration, _runner, build_platform if TYPE_CHECKING: from majordom_integration_sdk.controller.output import AnyController from ..repository.protocol import DeviceRepositoryProtocol from ..runtime import Pinned, Runtime from ..schemas.device import Device logger = logging.getLogger("majordom_integration_sdk.dev") # --- prompt-safe output ------------------------------------------------------------------------ # The catch with an interactive REPL: the shell is blocked reading a line in a worker thread, so # anything printed from elsewhere (discoveries/events on the event loop, or a stray log line) lands # *on the prompt line* and eats what the user is typing. Print above the prompt and restore the # cursor instead. Ported from the Hub CLI's `println`; falls back to a plain print when stdout # isn't a TTY (pipes, tests, logs to a file) where the escape codes would just be noise. def _println(msg: object): console = rich.get_console() # markup off: the prefixes ("[error]") are text, not tags if not sys.stdout.isatty(): console.print(msg, markup=False) return builtins.print("\x1b[s\x1b[1A\x1b[999D\x1b[1S\x1b[L", end="", flush=True) # save, up, home, scroll, insert-line console.print(msg, end="", markup=False) builtins.print("\x1b[u", end="", flush=True) # restore cursor to the prompt def _print(*values: object, sep: str = " "): """Prompt-safe print: wrap to the terminal width and emit each line via :func:`_println`.""" columns, _ = shutil.get_terminal_size((80, 20)) for line in sep.join(str(v) for v in values).split("\n"): if not line: _println("") for i in range(0, len(line), columns or 80): _println(line[i : i + (columns or 80)]) class _CapturingHandler(logging.Handler): """Buffer every log record instead of emitting it, so chatty controllers / discovery / matter-server logs (and warnings, via ``logging.captureWarnings``) don't disrupt the interactive prompt. The whole buffer is dumped to stderr once on exit or crash — quiet TUI during the session, full logs for debugging after.""" def __init__(self): super().__init__() self.records: list[logging.LogRecord] = [] def emit(self, record: logging.LogRecord): self.records.append(record) def dump(self): if not self.records: return builtins.print("\n--- captured logs (CLI session) ---", file=sys.stderr, flush=True) for record in self.records: builtins.print(self.format(record), file=sys.stderr, flush=True) _CLI_ROOM = uuid5(UUID(int=0), "cli") # the dev runner has no rooms: every device it pairs is in this one # --- controller-driving core (testable without the REPL) --------------------------------------- class _CliSession: """The id-based logic behind the CLI commands. Kept separate from the typer-shell wiring so it can be exercised directly against a fake controller in tests. Mirrors the Hub relay's object resolution (``repo.get`` + ``get_parameter_state`` + ``model_validate`` into the controller's ``device_type`` / ``parameter_type``).""" def __init__(self, controller: AnyController, runtime: Runtime | None = None): self._controller = controller self._runtime = runtime @property def discoveries(self): return self._controller.discoveries async def pair(self, discovery_id: UUID, credentials_type: str = "none", credentials_value: str = ""): discovery = self._controller.discoveries.get(discovery_id) if not discovery: return None credentials = ProvidedCredentials(type=CredentialsType(credentials_type), value=credentials_value or None) draft = self._controller.device_state_type( id=uuid4(), # the Hub's own, which the integration never sees in lookups physical_id=discovery.id, name=discovery.device_name, category=discovery.device_category, icon=discovery.device_icon, room_id=_CLI_ROOM, transport=discovery.transport, integration=self._controller.key, manufacturer=discovery.device_manufacturer, parameters=[], ) device = await self._controller.pair_device(discovery, draft, credentials) async with self._controller.platform.device_repository(self._controller) as repo: await repo.save(device) # as the Hub does once it saved the device if device.available: await self._controller.output.controller_did_connect_device( self._controller, physical_id=device.physical_id ) await self._controller.fetch(device) return device.physical_id async def pair_window(self, seconds: int): await self._controller.start_pairing_window(seconds) async def list_devices(self): async with self._controller.platform.device_repository(self._controller) as repo: return await repo.get_all() async def device_state(self, physical_id: UUID): async with self._controller.platform.device_repository(self._controller) as repo: return await repo.state(physical_id=physical_id) async def _device(self, physical_id: UUID): async with self._controller.platform.device_repository(self._controller) as repo: device = await repo.get(physical_id=physical_id) return self._controller.device_type.model_validate(device) if device else None async def identify(self, physical_id: UUID) -> bool: if not (device := await self._device(physical_id)): return False await self._controller.identify(device) return True async def fetch(self, physical_id: UUID) -> bool: if not (device := await self._device(physical_id)): return False await self._controller.fetch(device) return True async def unpair(self, physical_id: UUID) -> bool: if not (device := await self._device(physical_id)): return False await self._controller.unpair(device) return True async def control(self, physical_id: UUID, parameter_id: UUID, value: object) -> str: async with self._controller.platform.device_repository(self._controller) as repo: device = await repo.get(physical_id=physical_id) if not device: return f"No device {physical_id}" command = DeviceCommand(device_id=device.id, parameter_id=parameter_id, value=value) parameter = await repo.get_parameter_state(physical_id=physical_id, parameter_id=parameter_id) if not parameter: return f"No parameter {parameter_id} on device {physical_id}" if parameter.role != ParameterRole.control: return f"Parameter {parameter_id} is not controllable (role={parameter.role.value})" await self._controller.send_command( command, self._controller.device_type.model_validate(device), self._controller.parameter_type.model_validate(parameter), ) return "Command sent" # needs def needs(self) -> list[str]: """Each need: what it is bound to and who provides it, or why it isn't bound.""" controller, runtime, rows = self._controller, self._runtime, [] bound = runtime.bound(controller) if runtime else controller.peripherals.bound providers = runtime.providers(controller) if runtime else {} unbound = runtime.unbound(controller) if runtime else {} for need in controller.needs: wanted = f"{need.family}/{'|'.join(need.dialects) or '*'}{' (many)' if need.is_many else ''}" wanted += "" if need.is_required else " (optional)" if (endpoints := bound.get(need.family)) is not None: urls = ", ".join( e.url or e.dialect for e in ([endpoints] if isinstance(endpoints, Endpoint) else endpoints) ) by = providers.get(need.family, "you") rows.append(f"{wanted} -> {urls} by {', '.join(by) if isinstance(by, list) else by}") else: rows.append(f"{wanted} unbound: {unbound.get(need.family, 'not given')}") return rows async def pin(self, family: str, url: str, dialect: str = ""): """Provide an endpoint yourself, e.g. ``zigbee socket://192.168.1.5:6638 ezsp``.""" dialect = dialect or next( (n.dialects[0] for n in self._controller.needs if n.family == family and n.dialects), "" ) await self._pinned().pin(Endpoint(family, dialect, url, is_shared=True)) async def unpin(self, family: str): await self._pinned().unpin(family) async def resolve(self): await self._require_runtime().refresh() def _require_runtime(self) -> Runtime: if self._runtime is None: raise RuntimeError("No runtime here: the peripherals were given by hand") return self._runtime def _pinned(self) -> Pinned: from ..runtime import Pinned return next(p for p in self._require_runtime().peripherals if isinstance(p, Pinned)) class _CliControllerOutput(ControllerOutput): """The CLI's own output delegate — a different approach from the logging one: it shows each callback through the prompt-safe printer (intentional TUI content, not logs) *and* persists state to the repository, so ``devices`` / ``device`` reflect live availability and values. A single-controller stand-in for the Hub relay's output side.""" async def controller_did_receive_discovery(self, controller, discovery): _print(f"[discovered] {discovery.id} {discovery.device_name} ({discovery.transport})") async def controller_did_update_discovery(self, controller, discovery): _print(f"[discovery updated] {discovery.id}") async def controller_did_lose_discovery(self, controller, discovery_id): _print(f"[discovery lost] {discovery_id}") async def controller_did_connect_device(self, controller, *, physical_id=None, device_id=None): _print(f"[connected] {physical_id or device_id}") async with controller.platform.device_repository(controller) as repo: if device := await _device(repo, physical_id, device_id): device.last_seen = datetime.now() device.available = True await repo.save(device) async def controller_did_lose_device(self, controller, *, physical_id=None, device_id=None): _print(f"[lost] {physical_id or device_id}") async with controller.platform.device_repository(controller) as repo: if device := await _device(repo, physical_id, device_id): device.available = False device.last_error = f"Device is no longer connected to the {controller.name} network" await repo.save(device) async def controller_did_receive_events(self, controller, events): events = list(events) async with controller.platform.device_repository(controller) as repo: for event in events: if not isinstance(event, DeviceParameterChange): continue if device := await repo.get(physical_id=event.physical_id): device.last_seen = datetime.now() await repo.save(device) if state := await repo.get_parameter_state( physical_id=event.physical_id, parameter_id=event.parameter_id ): state.value = event.value await repo.save_parameter_state(physical_id=event.physical_id, parameter_state=state) for event in events: _print(f"[event] {type(event).__name__}: {event!r}") async def controller_did_encounter_error(self, controller, error): _print(f"[error] {error.id}: {error.message}") async def controller_did_resolve_error(self, controller, error_id): _print(f"[error resolved] {error_id}") async def controller_did_emit_notification(self, controller, notification): _print(f"[notification] {notification.type.value}/{notification.priority.value}: {notification.message}") # --- the REPL ---------------------------------------------------------------------------------- async def _device(repo: DeviceRepositoryProtocol, physical_id: UUID | None, device_id: UUID | None) -> Device | None: if physical_id: return await repo.get(physical_id=physical_id) return next((device for device in await repo.get_all() if device.id == device_id), None) async def run_cli( integration: Integration, *, storage_root: Path | None = None, db_path: str | Path | None = None, peripherals: Mapping[str, Bound] | None = None, runtime_peripherals: Sequence[Peripheral] | None = None, pinned: Sequence[Endpoint] = (), **platform: Any, ): """Start what ``integration`` exports (its ``peripherals``: the controller and the servers it needs) under the runtime, or only its controller with the ``peripherals`` you bind, with a local repository and drop into an interactive prompt. ``platform`` overrides fields of `Platform` (``region``); ``runtime_peripherals`` and ``pinned`` go to the runtime (`build_runtime`). ``db_path`` file-backs the repository so paired devices survive restarts; omit it for in-memory. ``exit`` / Ctrl-D leaves the prompt and stops everything cleanly.""" # Capture all logs + warnings into a buffer for the duration of the session so they don't break # the interactive TUI; the buffer is dumped to stderr on exit/crash (see the finally block). # The CLI's own discovery/event/command output (via _print) stays visible and prompt-safe. root = logging.getLogger() saved_handlers, saved_level = root.handlers[:], root.level captured = _CapturingHandler() captured.setFormatter(logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")) root.handlers[:] = [captured] root.setLevel(logging.DEBUG) logging.captureWarnings(True) loop = asyncio.get_running_loop() base = replace(build_platform(storage_root=storage_root, db_path=db_path), **platform) # The output also persists state. runner = _runner(integration(base), storage_root, peripherals, runtime_peripherals, pinned, _CliControllerOutput()) controller = runner.controller session = _CliSession(controller, runner.runtime) await runner.start() state = "started" if runner.is_running else "waiting for its needs (see `needs`)" _print(f"{controller.name} {state}. Type 'help' for commands, 'exit' to quit.") # Shell commands run in a worker thread (typer-shell blocks); hop back onto this loop to call # the controller's async API. def call(coro): return asyncio.run_coroutine_threadsafe(coro, loop).result() app = make_typer_shell( prompt=f"{controller.name.lower()} > ", intro=f"MajorDom {controller.name} standalone CLI. Type 'help' for commands, 'exit' to quit.", ) @app.command() def discoveries(): """List discoveries currently visible (id, name, transport, expected credentials).""" found = session.discoveries if not found: _print("(no discoveries yet)") for id, d in found.items(): expects = ", ".join(o.type.value for o in d.expected_credentials_options) _print(f"{id} {d.device_name} transport={d.transport} expects=[{expects}]") @app.command() def discovery(discovery_id: str): """Show full discovery info by id.""" d = session.discoveries.get(UUID(discovery_id)) _print(d.model_dump_json(indent=2) if d else f"No discovery {discovery_id}") @app.command() def pair(discovery_id: str, credentials_type: str = "none", credentials_value: str = ""): """Pair a discovered device. credentials_type must be one of the discovery's expected options (see `discovery`); credentials_value is the code/QR string when that type needs one.""" device_id = call(session.pair(UUID(discovery_id), credentials_type, credentials_value)) _print(f"Paired device {device_id}" if device_id else f"No discovery {discovery_id}") @app.command() def pair_window(seconds: int = 60): """Open a pairing/join window for `seconds` (Zigbee needs this; a no-op for integrations that discover continuously).""" call(session.pair_window(seconds)) _print(f"Pairing window open for {seconds}s") @app.command() def devices(): """List paired devices (physical id, name, available).""" found = call(session.list_devices()) if not found: _print("(no paired devices)") for device in found: _print(f"{device.physical_id} {device.name} available={device.available}") @app.command() def device(device_id: str): """List a paired device's parameters (id, name, role, visibility, value).""" state = call(session.device_state(UUID(device_id))) if not state: _print(f"No device {device_id}") return for p in state.parameters: _print(f"{p.id} {p.name} role={p.role.value} visibility={p.visibility.value} value={p.value!r}") @app.command() def identify(device_id: str): """Ask a device to identify itself (blink/beep).""" _print("identify sent" if call(session.identify(UUID(device_id))) else f"No device {device_id}") @app.command() def fetch(device_id: str): """Refresh a device's state from the device.""" _print("fetched" if call(session.fetch(UUID(device_id))) else f"No device {device_id}") @app.command() def unpair(device_id: str): """Remove a paired device.""" _print(f"Unpaired {device_id}" if call(session.unpair(UUID(device_id))) else f"No device {device_id}") @app.command() def control(device_id: str, parameter_id: str, value: str): """Send a command: device_id parameter_id value (value is parsed as JSON when possible, else used as a raw string). The target parameter must have the `control` role.""" try: parsed: object = json.loads(value) except json.JSONDecodeError: parsed = value _print(call(session.control(UUID(device_id), UUID(parameter_id), parsed))) @app.command() def needs(): """List the integration's needs: what each is bound to and by whom, or why it isn't bound.""" for row in session.needs(): _print(row) @app.command() def pin(family: str, url: str, dialect: str = ""): """Provide an endpoint for a need yourself, e.g. `pin zigbee socket://192.168.1.5:6638 ezsp` or `pin matter ws://127.0.0.1:5580` (dialect defaults to the need's first).""" call(session.pin(family, url, dialect)) _print("\n".join(session.needs())) @app.command() def unpin(family: str): """Drop an endpoint you pinned: the runtime binds the need again.""" call(session.unpin(family)) _print("\n".join(session.needs())) @app.command() def resolve(): """Look for radios again and bind every need anew.""" call(session.resolve()) _print("\n".join(session.needs())) # typer-shell parses sys.argv on start; clear it so a bare `run_cli()` doesn't inherit flags. sys.argv = sys.argv[:1] try: await loop.run_in_executor(None, app) except (KeyboardInterrupt, asyncio.CancelledError): pass finally: await runner.stop() _print(f"{controller.name} stopped.") # restore logging and dump everything captured during the session for debugging logging.captureWarnings(False) root.handlers[:], root.level = saved_handlers, saved_level captured.dump() __all__ = ["run_cli"] ================================================================================ # FILE: majordom_integration_sdk/errors.py ================================================================================ """Errors an integration raises for the Hub (and through it the app) to act on.""" import re from typing import ClassVar from uuid import UUID _TYPE = re.compile(r"[a-z][a-z0-9]*(?:_[a-z0-9]+)*") class MissingCredentialsError(LookupError): """The Hub lacks credentials of ``type`` to pair a device, e.g. a Hub on Ethernet has no Wi-Fi to give a node. Raised before the device is touched; the Hub answers the pairing request with it (422 ``missing_credentials``, carrying ``type`` and the kept device id), so the app can ask the user for them and pair again. ``type`` is a lower_snake_case string kept open for integrations: the known ones are the class constants below; an integration documents any custom one it raises. The app maps it to an enum. """ WIFI: ClassVar[str] = "wifi" THREAD: ClassVar[str] = "thread" def __init__(self, type: str = WIFI): if not _TYPE.fullmatch(type): raise ValueError(f"Credentials type must be lower_snake_case, got {type!r}") self.type = type super().__init__(f"Missing credentials: {type}") class DeviceIdTakenError(Exception): """Another device record already holds ``physical_id``, the one a pairing would give its device. Raised by `AbstractController.check_device_id` before anything irreversible is done to the device; the Hub refuses the pairing with it and does not roll it back (nothing ran). It carries the record found: its Hub ``device_id``, ``name`` and whether it ``is_paired`` (an unpaired one is a record kept after its device was removed), so the app can offer to pair onto that record instead. """ def __init__(self, physical_id: UUID, device_id: UUID, name: str, is_paired: bool): self.physical_id = physical_id self.device_id = device_id self.name = name self.is_paired = is_paired state = "paired" if is_paired else "unpaired" super().__init__(f"Physical id {physical_id} is taken by {name!r} ({device_id}, {state})") class DeviceUnreachableError(Exception): """``unpair`` could not reach the device to undo its pairing, e.g. it is off or out of range. Raised after the controller forgot its own state of the device, so only the device keeps the pairing: the Hub answers with it (``device_unreachable``), and the app offers to forget the device instead, which then needs a manual factory reset to pair again. """ ================================================================================ # FILE: majordom_integration_sdk/files.py ================================================================================ """What the SDK and integrations keep on disk themselves: JSON, written whole or not at all, for its owner alone. The runtime keeps its state here, Compose its containers; an integration its own files (``documents_folder``).""" from __future__ import annotations import json import logging import os from pathlib import Path from typing import Any log = logging.getLogger(__name__) def read_json(path: Path) -> dict[str, Any]: """What ``path`` holds; nothing while it is missing, or unreadable (it starts afresh).""" try: value = json.loads(path.read_text()) except FileNotFoundError: return {} except (OSError, ValueError) as error: log.error(f"{path} is unreadable, starting afresh: {error}") return {} if not isinstance(value, dict): log.error(f"{path} holds no object, starting afresh") return {} return value def write_json(path: Path, value: Any): """Write ``value`` whole or not at all: a crash midway leaves the file as it was. Only its owner reads it: the settings and the rendered containers hold secrets (Z-Wave's network keys), an integration's own files too (the keys ESPHome set on its nodes).""" path.parent.mkdir(parents=True, exist_ok=True) written = path.with_name(f"{path.name}.tmp") written.touch(mode=0o600) written.chmod(0o600) # one a crash left keeps its mode written.write_text(json.dumps(value, indent=2)) os.replace(written, path) ================================================================================ # FILE: majordom_integration_sdk/parameter_audit.py ================================================================================ """Dev/pairing-time sanity checks on a device's mapped parameters — protocol-neutral, so every integration (and the audit tools) share one implementation. See the "Parameter Visibility & UX" recipe in the docs. All checks are advisory: they return human-readable warnings, never raise. """ from __future__ import annotations from collections import defaultdict from collections.abc import Iterable, Sequence from difflib import SequenceMatcher from .schemas.parameter import Parameter, ParameterUnit, ParameterVisibility # A device's `user` bucket is the everyday device screen; more than this is a strong # over-exposure smell (usually uncurated read-only attrs leaking through). MAX_USER_PARAMETERS = 8 # Name-similarity ratio (0..1) above which two `user` params look like near-duplicates. NAME_SIMILARITY_THRESHOLD = 0.86 def _name_similarity(a: str, b: str) -> float: return SequenceMatcher(None, a, b).ratio() def audit_device_parameters( device_name: str, parameters: Iterable[Parameter], *, max_user: int = MAX_USER_PARAMETERS, similarity_threshold: float = NAME_SIMILARITY_THRESHOLD, ignore_similar_pairs: Sequence[tuple[str, str]] = (), ) -> list[str]: """Return advisory warnings about a device's parameter mapping. Checks: * too many `user`-visible parameters (over-exposure), * near-duplicate names in the `user` bucket (a normalized string-similarity ratio — `difflib`, close to a Levenshtein signal without a dependency), * same-unit + same-role duplicates in the `user` bucket (catches redundant *representations* of one quantity even when the names differ, e.g. colour `hue/sat` and `x/y`). `ignore_similar_pairs` whitelists legitimately-similar name pairs (order-insensitive), e.g. `("occupied_heating_setpoint", "occupied_cooling_setpoint")`. """ warnings: list[str] = [] user = [p for p in parameters if p.visibility == ParameterVisibility.user] if len(user) > max_user: names = ", ".join(p.name for p in user[:12]) warnings.append( f"{device_name}: {len(user)} user-visible parameters (> {max_user}) — likely " f"over-exposed; review visibility curation. [{names}{' …' if len(user) > 12 else ''}]" ) # Near-duplicate names among user params (a Levenshtein-like signal). whitelist = {frozenset(pair) for pair in ignore_similar_pairs} for i in range(len(user)): for j in range(i + 1, len(user)): a, b = user[i], user[j] if frozenset((a.name, b.name)) in whitelist: continue ratio = _name_similarity(a.name, b.name) if ratio >= similarity_threshold: warnings.append( f"{device_name}: user params {a.name!r} and {b.name!r} have near-duplicate " f"names (similarity {ratio:.2f}) — is one redundant?" ) # Redundant *representations* of one quantity — several user params sharing a specific # (non-plain) unit + role + type, even with different names (e.g. colour hue/sat AND x/y). # Grouped and thresholded so ordinary multi-sensor devices don't trip it. groups: dict[tuple, list[str]] = defaultdict(list) for p in user: if p.unit != ParameterUnit.plain: groups[(p.unit, p.role, p.data_type)].append(p.name) for (unit, role, _dt), group_names in groups.items(): if len(group_names) >= 3: warnings.append( f"{device_name}: {len(group_names)} user params share {unit.value}/{role.value} " f"({', '.join(group_names)}) — possible redundant representations." ) return warnings ================================================================================ # FILE: majordom_integration_sdk/peripherals/__init__.py ================================================================================ """The language integrations and the runtime share to describe what they need and what they provide. Everything around an integration, and the integration itself, is a `Peripheral`: it ``needs`` capabilities, it ``provides`` `Endpoint`s and the peripherals it brings along. A capability is ``family/dialect``: ``zigbee/ezsp``, ``thread/spinel``, ``matter/matter-server``, ``ble/router``. A runtime (`majordom_integration_sdk.runtime`, or you by hand in library mode) binds every `Need` to an endpoint and hands it over as the peripheral's ``peripherals``: an `Endpoint` per family, a list for an ``is_many`` need. """ from majordom_integration_sdk.peripherals.ble_proxy import BLEProxy from majordom_integration_sdk.peripherals.endpoint import Bound, Endpoint, PeripheralChange from majordom_integration_sdk.peripherals.need import Need from majordom_integration_sdk.peripherals.peripheral import ( STABLE_RUN, NoSettings, Peripheral, PeripheralOutput, Peripherals, ) from majordom_integration_sdk.peripherals.service import ComposeService, Healthcheck, Service, ServiceHost from majordom_integration_sdk.peripherals.usb import USB_DRIVER, UsbDriver from majordom_integration_sdk.schemas.settings import SettingsExtraField __all__ = [ "Need", "Endpoint", "Bound", "Peripheral", "NoSettings", "PeripheralOutput", "Peripherals", "PeripheralChange", "Service", "ServiceHost", "ComposeService", "Healthcheck", "UsbDriver", "USB_DRIVER", "BLEProxy", "STABLE_RUN", "SettingsExtraField", ] ================================================================================ # FILE: majordom_integration_sdk/peripherals/ble_proxy.py ================================================================================ """Bluetooth sources integrations lend the runtime's router.""" from __future__ import annotations from collections.abc import Sequence from majordom_integration_sdk.capabilities.ble import BLESource from majordom_integration_sdk.peripherals.endpoint import Endpoint from majordom_integration_sdk.peripherals.peripheral import Peripheral class BLEProxy(Peripheral): """A Bluetooth source an integration brings along while it has it, e.g. an ESPHome node's proxy as ``ble/esphome-proxy``: the router binds it and hears through ``source``. Add one to what you provide when the source connects, remove it when it goes, and tell your ``output`` each time (``controller_did_change_provided``); they go when you stop. ``name`` is what it is known by after you, ``esphome/``: the source's name by default, else e.g. the node's Bluetooth MAC. """ def __init__(self, source: BLESource, name: str | None = None, dialect: str = "esphome-proxy"): self.name, self.source, self.dialect = name or source.name, source, dialect @property def provides(self) -> Sequence[Endpoint]: return [Endpoint("ble", self.dialect, self.source.name, instance=self.source)] ================================================================================ # FILE: majordom_integration_sdk/peripherals/endpoint.py ================================================================================ """What peripherals provide, and what a need is bound to.""" from __future__ import annotations from collections.abc import Mapping from dataclasses import dataclass, field from typing import Any @dataclass(frozen=True) class Endpoint: """What a peripheral provides — a radio, a service, the host, an in-process provider — and, once bound, what the peripheral that needs it uses. A radio firmware's ``url`` may hold ``{device}``, the stick's path; a service's ``{ports.}``. ``params`` says how to talk to it, e.g. a serial port's ``baud`` and ``flow_control`` as the radio's firmware sets them; a service reads them as ``{peripherals..params[baud]}``. The params a service provides render like its compose, telling its consumers what it got: ``{"adapter": "{peripherals.ble.url}"}``. ``instance`` carries an in-process peripheral itself (the runtime's Bluetooth router, a DNS-SD browser, an ESPHome node's Bluetooth source); ``url`` still names it, and two endpoints are the same when all but the instance match. """ family: str dialect: str = "" url: str = "" is_shared: bool = False # several consumers may bind it (one Thread network); otherwise exactly one params: Mapping[str, Any] = field(default_factory=dict, hash=False) instance: Any = field(default=None, hash=False, compare=False, repr=False) type Bound = Endpoint | list[Endpoint] # what a need is bound to: a list for an ``is_many`` need @dataclass(frozen=True) class PeripheralChange: """A bound need moved: ``after`` is None when it was lost, ``before`` is None when it (re)appeared.""" family: str before: Bound | None after: Bound | None ================================================================================ # FILE: majordom_integration_sdk/peripherals/need.py ================================================================================ """What a peripheral requires from its environment.""" from __future__ import annotations from collections.abc import Sequence from dataclasses import dataclass from typing import Any from majordom_integration_sdk.peripherals.endpoint import Endpoint @dataclass(frozen=True) class Need[T = Any]: """A dependency something else must provide, as ``family`` and the ``dialects`` it speaks; ``T`` types the in-process peripheral it binds, read back with ``self.peripherals.instance(need)``: ``Need[BLERouter]``. The runtime binds it to an `Endpoint` and hands that over in the peripheral's `Peripherals`, to a controller as ``self.peripherals.endpoint()`` and to a `Service` as ``{peripherals..url}``. An ``is_many`` need binds every matching endpoint that is free, as a list: a Bluetooth router hears through every radio it is given. """ family: str dialects: Sequence[str] = () # empty: any dialect of the family is_required: bool = True is_many: bool = False def accepts(self, endpoint: Endpoint) -> bool: return endpoint.family == self.family and (not self.dialects or endpoint.dialect in self.dialects) ================================================================================ # FILE: majordom_integration_sdk/peripherals/peripheral.py ================================================================================ """The one protocol for everything around an integration, and how a peripheral talks to whatever runs it.""" from __future__ import annotations import logging from collections.abc import Mapping, Sequence from types import MappingProxyType from typing import TYPE_CHECKING, Any, Protocol, cast from pydantic import BaseModel, ConfigDict from majordom_integration_sdk.peripherals.endpoint import Bound, Endpoint, PeripheralChange from majordom_integration_sdk.peripherals.need import Need if TYPE_CHECKING: from majordom_integration_sdk.platform import Platform log = logging.getLogger(__name__) START_TIMEOUT = 600 # seconds a start may take to serve by default, else it failed # seconds of running that clear a peripheral's failures in a row; an integration's outage ends once a reconnect held as # long (a server that sends its nodes and drops every time is reported) STABLE_RUN = 300 class NoSettings(BaseModel): """The settings of a peripheral without options: it takes none.""" model_config = ConfigDict(extra="forbid") class PeripheralOutput(Protocol): """What a peripheral tells whatever runs it, through its ``output``, delegate style like `ControllerOutput`: what changed on its own (a stick plugged in, a node connected), what it learned, and that it stopped or failed. The runtime gives every peripheral it runs the same output; a controller reports through `ControllerOutput` instead. Awaiting a call returns once the runtime acted on it, e.g. stopped what used a radio about to be flashed. From inside ``start``, ``stop`` or a hook, or a task that call awaits (a ``TaskGroup``'s), it returns at once: the runtime acts when that call returns. It acts in a task of its own, so a call from a task the peripheral keeps running, which its ``stop`` cancels before awaiting it, is fine: that task just ends. """ async def peripheral_did_change_provided(self, peripheral: Peripheral): """Its ``provides`` or the peripherals it brings along changed.""" ... async def peripheral_did_learn(self, peripheral: Peripheral, facts: Mapping[str, Any]): """`Platform` facts it read from what it runs or talks to, e.g. a border router's Thread network: they replace the platform's, and every peripheral that runs hears it (``platform_facts_did_change``). A name the platform holds no fact of is left out (logged).""" ... async def peripheral_did_stop(self, peripheral: Peripheral): """It stopped by itself, gracefully: it is stopped (``stop`` releases what it holds) and waits until one of its needs changes (goes and comes back, or moves) or the user restarts it.""" ... async def peripheral_did_fail(self, peripheral: Peripheral, reason: str): """It can't go on, ``reason`` saying why to the user: it is stopped and started again after each of the runtime's retry delays, then failed until the user restarts it. Told from inside ``start``, that start fails.""" ... class LoggingPeripheralOutput: """Nothing runs the peripheral (library mode, a test): what it tells is logged.""" async def peripheral_did_change_provided(self, peripheral: Peripheral): log.info(f"{peripheral.key} changed what it provides") async def peripheral_did_learn(self, peripheral: Peripheral, facts: Mapping[str, Any]): log.info(f"{peripheral.key} learned {', '.join(facts)}") async def peripheral_did_stop(self, peripheral: Peripheral): log.info(f"{peripheral.key} stopped by itself") async def peripheral_did_fail(self, peripheral: Peripheral, reason: str): log.error(f"{peripheral.key} failed: {reason}") class Peripherals: """What a peripheral's needs are bound to, by family: an `Endpoint`, or a list of them for an ``is_many`` need. A runtime hands a new one over before ``start`` and whenever the bindings change; in library mode hand it yours: ``controller.peripherals = Peripherals({"mdns": zeroconf.endpoint})``. """ def __init__(self, bound: Mapping[str, Bound] | None = None): self.bound: Mapping[str, Bound] = MappingProxyType(dict(bound or {})) def endpoint(self, family: str) -> Endpoint: """The endpoint bound to the need of ``family``; KeyError while it is unbound.""" bound = self.bound[family] if isinstance(bound, list): raise TypeError(f"The {family} need binds many endpoints: use endpoints({family!r})") return bound def endpoints(self, family: str) -> list[Endpoint]: """Every endpoint bound to the need of ``family``; empty while it is unbound.""" bound = self.bound.get(family, []) return [bound] if isinstance(bound, Endpoint) else bound def instance[T](self, need: Need[T]) -> T | None: """The in-process peripheral bound to ``need``, typed by it, e.g. the Bluetooth router; None while unbound.""" return self.endpoint(need.family).instance if need.family in self.bound else None class Peripheral[S: BaseModel = Any](Protocol): """Anything around an integration that needs and/or provides capabilities: a USB radio, soldered hardware, the host's Bluetooth adapters and network, a container, an in-process provider (the Bluetooth router, Zeroconf, SSDP), an integration itself, an ESPHome node's Bluetooth proxy. Only the construction differs. It ``needs`` capabilities, ``provides`` endpoints and the peripherals it brings along, and finds what its needs are bound to in ``peripherals``. A runtime (`majordom_integration_sdk.runtime.Runtime`) runs every peripheral it is given by one rule: one that isn't disabled or failed runs while whatever brought it along does, while something that runs binds it if it ``is_on_demand``, and once every required need is bound to a provider that runs. A required need that can't be bound keeps it waiting, with the reason; one lost later stops it until it is back. An optional need is handed over once its provider runs, as it appears. Subclass it for the defaults. The runtime sets ``platform`` (the host, the same for every peripheral: its facts, and a documents folder per peripheral), ``output`` (what it tells), ``peripherals``, ``contributor`` and ``settings``, its options validated by its ``Settings``. Declare them as a nested ``class Settings(BaseModel)`` named as the type parameter, which types ``settings``: ``class Radio(Peripheral["Radio.Settings"])``. Without, they are `NoSettings`; a bare ``Peripheral`` is one of any settings. A field marked read-only in its JSON schema, ``channel: int = Field(11, json_schema_extra={Extra.read_only: True})``, shows what the peripheral fills in itself (``self.settings.channel = 25``): the user sees it, and an update to another value is refused. It is never kept: until the peripheral fills it in again, it holds its default. One marked write-only, ``network_key: str = Field("", json_schema_extra={Extra.write_only: True})``, is the reverse: the user sets it, and the host never shows it (the Hub never reads it back), so an update that leaves it out keeps it. ``Extra`` is `SettingsExtraField`: never spell a keyword out. """ name: str # what it is shown by contributor: Peripheral | None = None # what brought it along needs: Sequence[Need] = () is_on_demand: bool = False # runs only while something that runs binds it: containers, in-process providers start_timeout: float = START_TIMEOUT settings: S platform: Platform # the host it runs on output: PeripheralOutput = LoggingPeripheralOutput() # what it tells whatever runs it peripherals: Peripherals = Peripherals() # what its needs are bound to @property def Settings(self) -> type[S]: """The model of its options; `NoSettings` when it has none. Read-only, so a nested class may override it.""" return cast(type[S], NoSettings) @property def key(self) -> str: """What it is known, kept and disabled by where it runs, unique there and stable across restarts: its name, after its contributor's key for one brought along (``usb/``, ``esphome/``).""" return f"{self.contributor.key}/{self.name}" if self.contributor else self.name @property def provides(self) -> Sequence[Endpoint | Peripheral]: """What it serves to the others' needs, and the peripherals it brings along while it runs: the USB scanner a radio per stick, ESPHome a Bluetooth proxy per node. When it changes on its own, tell ``output``.""" return () async def start(self): """Set up what it serves, and return once it serves: what needs it starts then. Raising, or taking longer than its ``start_timeout``, has the runtime stop it, try again later (``RETRY_DELAYS``), then give up.""" return async def stop(self): """Release everything it holds; what it brought along goes with it. It also follows a start that failed or was cut short: leave the object clean for the next ``start``, with nothing in flight taking resources after it.""" return async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: """A bound need was lost, appeared or moved while it runs; its ``peripherals`` already hold the new binding. Return True when handled in place (Matter keeps working over IP without Thread); False, the default, restarts it. A required need that is lost stops it instead, without asking. """ return False async def settings_did_change(self, before: S) -> bool: """Its ``settings`` changed while it runs. True when applied in place; False, the default, restarts it.""" return False async def platform_facts_did_change(self, before: Platform) -> bool: """The host's facts changed (region, Wi-Fi, Thread network) while it runs; ``platform`` holds the new ones. True, the default, when they don't concern it or were applied in place; False restarts it.""" return True ================================================================================ # FILE: majordom_integration_sdk/peripherals/service.py ================================================================================ """Companion servers an integration provides, run as containers while something uses them.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING, Any, Literal, Protocol, TypedDict from pydantic import BaseModel from majordom_integration_sdk.peripherals.endpoint import Endpoint, PeripheralChange from majordom_integration_sdk.peripherals.need import Need from majordom_integration_sdk.peripherals.peripheral import NoSettings, Peripheral if TYPE_CHECKING: from majordom_integration_sdk.platform import Platform class Healthcheck(TypedDict, total=False): test: list[str] interval: str timeout: str start_period: str retries: int class ComposeService(TypedDict, total=False): """A Docker Compose service definition, the keys services use typed (a typo fails type checking, not the start); another key goes here first. Its strings are templates: see `Service`.""" image: str build: str command: list[str] entrypoint: list[str] environment: dict[str, str] volumes: list[str] devices: list[str] tmpfs: list[str] network_mode: Literal["host", "bridge", "none"] userns_mode: Literal["host"] user: str privileged: bool hostname: str cap_add: list[str] cap_drop: list[str] group_add: list[str] healthcheck: Healthcheck class ServiceHost(Protocol): """What runs a `Service`'s container, bound to its ``container`` need: the runtime's `Compose`.""" def provided(self, service: Service) -> Sequence[Endpoint]: """Its ``provides`` rendered: the host ports it got, the params it renders.""" ... async def up(self, service: Service): """Run its container; return once it serves.""" ... async def down(self, service: Service): ... def is_current(self, service: Service) -> bool: """Whether its container still runs what it would render now.""" ... CONTAINER_HOST = Need[ServiceHost]("container", ["compose"]) # what every service needs class Service[S: BaseModel = Any](Peripheral[S]): """A companion server an integration provides, such as Matter's matterjs-server: a container that runs only while something that runs is bound to one of its endpoints. The integration lists it next to its controller, which `Need`s what it provides. ``compose`` is its Docker Compose service definition (image, environment, volumes, …); its strings may hold ``{data}`` (its own documents folder), ``{peripherals..url}``, ``{settings.}``, ``{platform.}`` (``{platform.region}``), ``{host.interface|uid|gid|listen_address|avahi}`` and ``{ports.}``. A format spec turns a value into text: ``{x:!text}`` renders ``text`` when ``x`` is empty, ``{x:?text}`` when it isn't; a list item that renders empty is left out, so ``"volumes": ["{peripherals.ble.url:?/run/dbus:/run/dbus:ro}"]`` mounts D-Bus only while an adapter is bound. One on the host network (``network_mode: host``) listens on ``{host.listen_address}``: loopback unless the host opens its services to the LAN for a lab harness. The ``params`` of the ``provides`` endpoints render the same way, which is how a consumer learns what its service got: ``params={"adapter": "{peripherals.ble.url}"}``. ``settings`` is the model of its options, its ``Settings``. ``ports`` names the host ports it listens on, each with the port it *prefers*, not a fixed one: the runtime uses it when free, else assigns another (45800-45999), keeps the choice across restarts, and fills ``{ports.}`` in ``compose`` and in the ``provides`` URLs. Integrations never read a port: they connect through ``self.peripherals.endpoint().url``. Its start returns once its container runs, its ports answer, `provision` finished and `is_healthy` says so. A change of what its needs are bound to or of the platform's facts recreates it only when it renders otherwise. Subclass it to hook in: `provision` sets up what it runs, `is_healthy` checks more; a ``start`` of your own may tell what it learned once it serves (``self.output.peripheral_did_learn``). """ is_on_demand = True start_timeout: float = 30 * 60 # its first start pulls its image def __init__( self, name: str, compose: ComposeService, needs: Sequence[Need] = (), provides: Sequence[Endpoint] = (), settings: type[S] = NoSettings, # ty: ignore[invalid-parameter-default] (none: it takes none) ports: Mapping[str, int] | None = None, # name -> PREFERRED host port; see the docstring ): self.name, self.compose, self.needs, self.templates = name, compose, [*needs, CONTAINER_HOST], provides self.settings_model, self.ports = settings, ports or {} @property def Settings(self) -> type[S]: return self.settings_model @property def host(self) -> ServiceHost | None: """The container host its need is bound to.""" return self.peripherals.instance(CONTAINER_HOST) @property def provides(self) -> Sequence[Endpoint]: return self.host.provided(self) if self.host else self.templates async def start(self): if not self.host: raise NotImplementedError( f"Nothing runs containers here: run {self.name} yourself and pin what it provides" ) await self.host.up(self) async def stop(self): if self.host: await self.host.down(self) async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: """Its container is recreated only when it would render otherwise now, or on another container host.""" return change.family != CONTAINER_HOST.family and self.host is not None and self.host.is_current(self) async def platform_facts_did_change(self, before: Platform) -> bool: """Its container is recreated only when it would render otherwise now.""" return self.host.is_current(self) if self.host else True async def provision(self, endpoint: Endpoint): """Set up one of its endpoints once it answers, e.g. form a network. Called each time its container is (re)created, cancelled when it stops: keep it idempotent.""" return async def is_healthy(self) -> bool: """A check of its own on top of its ports answering; asked until it says yes.""" return True def __repr__(self) -> str: return f"{type(self).__name__}({self.name!r})" ================================================================================ # FILE: majordom_integration_sdk/peripherals/usb.py ================================================================================ """Drivers that recognise USB devices for the runtime's USB scanner.""" from __future__ import annotations from collections.abc import Mapping, Sequence from dataclasses import replace from pathlib import Path from typing import Any, ClassVar from majordom_integration_sdk.peripherals.endpoint import Endpoint from majordom_integration_sdk.peripherals.peripheral import Peripheral USB_DRIVER = "usb-driver" # the family a driver provides itself as, to the scanners that need every driver class UsbDriver(Peripheral): """One kind of USB device: recognises which firmware a device runs and says what each firmware serves. The scanner asks its own drivers first, then the ones integrations provide next to their controller: Zigbee's tells the radios only zigpy knows apart. ``firmwares`` maps a firmware to what it serves: ``{device}`` in a URL is the device's path, ``params`` its serial settings (soldered hardware may wire them differently). """ is_on_demand = True # only while a scanner uses it firmwares: ClassVar[Mapping[str, Sequence[Endpoint]]] = {} bluetooth: ClassVar[frozenset[str]] = frozenset() # firmwares that serve Bluetooth too (multiprotocol over CPC) @property def provides(self) -> Sequence[Endpoint]: return [Endpoint(USB_DRIVER, self.name, self.name, is_shared=True, instance=self)] async def identify(self, path: str) -> str | tuple[str, Mapping[str, Any]] | None: """The firmware the device at ``path`` runs, or None when it isn't one of its kind; with the serial settings it found the device at where they may differ from the firmware's, ``("deconz", {"baud": 38400})``: the device's endpoints take them.""" return None def serves(self, firmware: str | None, path: str, params: Mapping[str, Any] | None = None) -> list[Endpoint]: """What ``firmware`` serves on the device at ``path``, ``params`` overriding its serial settings.""" endpoints = self.firmwares.get(firmware or "", []) return [replace(e, url=e.url.format(device=path), params={**e.params, **(params or {})}) for e in endpoints] def flashable(self, path: str, channel: str) -> list[str]: """Firmwares the device at ``path`` can be switched to on the ``stable`` or ``dev`` channel.""" return [] async def flash(self, path: str, firmware: str, channel: str, cache: Path): raise NotImplementedError(f"{type(self).__name__} can't flash") ================================================================================ # FILE: majordom_integration_sdk/platform.py ================================================================================ """The host every peripheral runs on, as its ``self.platform``: the facts it knows and its resources.""" from __future__ import annotations from collections.abc import Awaitable, Callable from contextlib import AbstractAsyncContextManager from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any from uuid import UUID from majordom_integration_sdk.repository.memory import DeviceRepositoryMemory from majordom_integration_sdk.repository.protocol import DeviceRepositoryProtocol from majordom_integration_sdk.schemas.credentials import WifiCredentials from majordom_integration_sdk.schemas.device import DeviceState if TYPE_CHECKING: from majordom_integration_sdk.peripherals import Peripheral type MakeDeviceRepository = Callable[[str], AbstractAsyncContextManager[DeviceRepositoryProtocol]] type CheckDeviceId = Callable[[UUID, DeviceState], Awaitable[None]] def _in_memory() -> MakeDeviceRepository: store: dict[UUID, dict[str, Any]] = {} # shared by the repositories of every peripheral return lambda key: DeviceRepositoryMemory(key, store).session() async def _any_id_is_free(physical_id: UUID, draft: DeviceState): pass @dataclass(frozen=True, kw_only=True) class Platform: """The host every peripheral runs on, the same object for all of them as ``self.platform``: a controller is given it, ``peripherals(platform)``, and the runtime sets it on the others. It holds the facts the host knows as plain fields, and its resources, scoped to the peripheral passed:: async with self.platform.device_repository(self) as repository: ... cache = self.platform.documents_folder(self) / "cache.json" Facts change only by replacement: the host builds a new platform (``dataclasses.replace``) and gives it to the runtime (`Runtime.update_platform`), which points every peripheral at it and tells the ones that run (``platform_facts_did_change``). Read ``self.platform`` when you need a fact: a platform kept holds the old ones. """ # Where each peripheral gets a folder of its own, by its key: the Hub's, or a local one under the dev runner documents_root: Path # One unit of work on the device repository, scoped to the devices of the peripheral keyed; in memory by default make_device_repository: MakeDeviceRepository = field(default_factory=_in_memory) # Raises `DeviceIdTakenError` when a record other than the one ``draft`` pairs onto (``draft.id``) holds the # physical id; the Hub's checks every record. Library mode has no other records to collide with: every id is free check_device_id: CheckDeviceId = _any_id_is_free region: str | None = None # RF region for sub-GHz radios, a Z-Wave JS name: "Europe", "USA", … wifi: WifiCredentials | None = None # the network to provision Wi-Fi devices onto thread_dataset: str | None = None # active operational dataset of the hub's Thread network, hex TLVs def documents_folder(self, peripheral: Peripheral) -> Path: """The folder of ``peripheral``, by its key, created on use: what it keeps across restarts that doesn't belong in the device database (certificates, protocol caches, a container's data).""" folder = self.documents_root / peripheral.key folder.mkdir(parents=True, exist_ok=True) return folder def device_repository(self, peripheral: Peripheral) -> AbstractAsyncContextManager[DeviceRepositoryProtocol]: """One unit of work on the device repository, scoped to the devices of ``peripheral``, by its key: a controller's is its slug, the ``integration`` of every `Device` it keeps.""" return self.make_device_repository(peripheral.key) ================================================================================ # FILE: majordom_integration_sdk/repository/__init__.py ================================================================================ """Device persistence for integrations — one protocol, two standalone implementations.""" from .memory import DeviceRepositoryMemory from .protocol import DeviceRepositoryProtocol from .sqlite import SqliteDeviceRepository __all__ = ["DeviceRepositoryProtocol", "DeviceRepositoryMemory", "SqliteDeviceRepository"] ================================================================================ # FILE: majordom_integration_sdk/repository/_record.py ================================================================================ """Internal record helpers shared by the SDK's repository implementations. A stored record is one JSON-safe dict per device holding *everything* known about it — info, ``integration_data`` and ``parameters`` (from a :class:`DeviceState`). A ``Device`` lacks the parameters, and a ``DeviceState`` built without ``integration_data`` doesn't hold the stored one; merging keeps both halves and lets a read deserialize into whichever view (``as_``) the caller asks for. """ from __future__ import annotations import json from typing import Any from pydantic import BaseModel from majordom_integration_sdk.schemas.device import Device, DeviceState type Record = dict[str, Any] def dump(device: BaseModel, exclude: set[str] | None = None) -> Record: """JSON-safe dump, so records round-trip identically through memory or SQLite. Goes through ``model_dump_json`` rather than ``model_dump(mode="json")`` — the JSON serializer is the one these models are actually exercised against (``ParameterState`` base64-encodes its ``bytes`` value there), so it's what the SQLite rows already store. """ return json.loads(device.model_dump_json(exclude=exclude)) def merge(base: Record | None, device: Device | DeviceState) -> Record: """Merge a device into an existing record without clobbering the other view's fields: an unset ``integration_data`` (its default) only where the record has none (the ``{}`` or null the Hub stores a device with before pairing is none), so that filling the default in place counts.""" unset = {"integration_data"} - device.model_fields_set if base and base.get("integration_data") else set() return {**(base or {}), **dump(device, exclude=unset)} __all__ = ["Record", "dump", "merge"] ================================================================================ # FILE: majordom_integration_sdk/repository/memory.py ================================================================================ """In-memory :class:`DeviceRepositoryProtocol` implementation. A legitimate, lightweight persistence choice for standalone/dev runs and tests — not a mock. State lives in a dict for the process lifetime; use :class:`SqliteDeviceRepository` when you need it to survive a restart. """ from __future__ import annotations from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from uuid import UUID from majordom_integration_sdk.repository._record import Record, dump, merge from majordom_integration_sdk.schemas.device import Device, DeviceState from majordom_integration_sdk.schemas.parameter import ParameterState, ParameterVisibility class DeviceRepositoryMemory: """Stores device records in a dict shared across sessions. Pass ``integration`` to scope every operation to that integration's devices (the guard the Hub sets when handing a repository to a controller). ``None`` gives full access. """ def __init__(self, integration: str | None = None, store: dict[UUID, Record] | None = None): self.integration = integration self._store: dict[UUID, Record] = store if store is not None else {} @asynccontextmanager async def session(self) -> AsyncGenerator[DeviceRepositoryMemory]: """One unit of work: what ``Platform.make_device_repository`` returns for its integration.""" yield self def _in_scope(self, record: Record) -> bool: return self.integration is None or record.get("integration") == self.integration def _owned(self, physical_id: UUID) -> Record | None: return next( (r for r in self._store.values() if r.get("physical_id") == str(physical_id) and self._in_scope(r)), None ) async def get_all[T: Device](self, as_: type[T] = Device) -> list[T]: return [as_.model_validate(r) for r in self._store.values() if self._in_scope(r)] async def get[T: Device](self, *, physical_id: UUID, as_: type[T] = Device) -> T | None: record = self._owned(physical_id) return as_.model_validate(record) if record else None async def state[T: DeviceState](self, *, physical_id: UUID, as_: type[T] = DeviceState) -> T | None: record = self._owned(physical_id) return as_.model_validate(record) if record else None async def get_parameter_state(self, *, physical_id: UUID, parameter_id: UUID) -> ParameterState | None: record = self._owned(physical_id) if not record: return None return next( (ParameterState.model_validate(p) for p in record.get("parameters", []) if p["id"] == str(parameter_id)), None, ) async def save(self, device: Device | DeviceState): if self.integration is not None and device.integration != self.integration: raise PermissionError(f"Device {device.id} is outside integration scope {self.integration!r}") holder = next( (i for i, r in self._store.items() if r.get("physical_id") == str(device.physical_id) and i != device.id), None, ) if holder is not None: raise ValueError(f"Physical id {device.physical_id} is held by device {holder}") self._store[device.id] = merge(self._store.get(device.id), device) async def save_parameter_state(self, *, physical_id: UUID, parameter_state: ParameterState): record = self._owned(physical_id) if not record: raise KeyError(f"Unknown or out-of-scope device {physical_id}") updated = dump(parameter_state) record["parameters"] = [ updated if p["id"] == str(parameter_state.id) else p for p in record.get("parameters", []) ] # Hub-internal (not on DeviceRepositoryProtocol), by the Hub's ids; still scope-checked. async def update_parameter_visibility(self, parameter_id: UUID, visibility: ParameterVisibility): for record in self._store.values(): if not self._in_scope(record): continue for parameter in record.get("parameters", []): if parameter["id"] == str(parameter_id): parameter["visibility"] = visibility.value return async def delete(self, device_id: UUID): record = self._store.get(device_id) if record is not None and self._in_scope(record): del self._store[device_id] __all__ = ["DeviceRepositoryMemory"] ================================================================================ # FILE: majordom_integration_sdk/repository/protocol.py ================================================================================ """The device-repository interface a controller talks to. A controller never touches a database directly — it goes through this protocol, obtained from its platform's ``device_repository(self)`` (an async context manager scoping one unit of work). The Hub backs it with its shared SQLAlchemy database; the SDK ships two first-class implementations for standalone/dev use — :class:`DeviceRepositoryMemory` and :class:`SqliteDeviceRepository`. **Integration scope.** The repository is bound to one integration at construction, so there is no ``integration`` argument on the reads: an integration only ever sees its own devices. Out-of-scope reads come back ``None``/empty and out-of-scope writes raise — a guard against carelessness, not a security boundary. Constructing with ``integration=None`` gives full access (the Hub's own higher-level use). **Keyed by ``physical_id``.** An integration looks its devices up by the ``physical_id`` it gave them (``device_uuid``), never by the Hub-owned ``id``: ``get``, ``state``, ``get_parameter_state`` and ``save_parameter_state`` take it as a keyword, ``save`` writes the record of ``device.id`` (read-only, set by the Hub). **Typed reads.** ``as_`` deserializes into your own ``Device[MyData]`` / ``DeviceState[MyData, MyParameterData]`` (or a subclass), so ``integration_data`` comes back typed instead of a bare dict:: async with self.platform.device_repository(self) as repo: device = await repo.get(physical_id=physical_id, as_=MyDevice) # class MyDevice(Device[MyData]) **Not here on purpose:** ``delete`` and ``update_parameter_visibility`` are Hub-internal lifecycle operations. They exist on the concrete implementations, but are kept off this protocol so an integration can't reach past its scope. """ from __future__ import annotations from typing import Protocol, runtime_checkable from uuid import UUID from majordom_integration_sdk.schemas.device import Device, DeviceState from majordom_integration_sdk.schemas.parameter import ParameterState @runtime_checkable class DeviceRepositoryProtocol(Protocol): """Persistence for one integration's paired devices and their parameter states.""" async def get_all[T: Device](self, as_: type[T] = Device) -> list[T]: """Every paired device in scope, deserialized as ``as_``.""" ... async def get[T: Device](self, *, physical_id: UUID, as_: type[T] = Device) -> T | None: """The device (info + ``integration_data``) as ``as_``, or ``None`` if unknown/out of scope.""" ... async def state[T: DeviceState](self, *, physical_id: UUID, as_: type[T] = DeviceState) -> T | None: """The device with its parameter states as ``as_``, or ``None`` if unknown/out of scope.""" ... async def get_parameter_state(self, *, physical_id: UUID, parameter_id: UUID) -> ParameterState | None: """One parameter's current state, or ``None`` if the device/parameter is unknown/out of scope.""" ... async def save(self, device: Device | DeviceState): """Insert or update a device, merging into whatever is already stored. Saving a ``Device`` updates its info/``integration_data``; saving a ``DeviceState`` updates its info/``parameters``, and its ``integration_data`` only when it was given one — neither clobbers the other's fields. The record is the one of ``device.id``; its ``physical_id`` must not be another record's. Rejects a device outside the bound integration's scope. """ ... async def save_parameter_state(self, *, physical_id: UUID, parameter_state: ParameterState): """Update a single parameter's value/state on an existing in-scope device.""" ... __all__ = ["DeviceRepositoryProtocol"] ================================================================================ # FILE: majordom_integration_sdk/repository/sqlite.py ================================================================================ """File-backed :class:`DeviceRepositoryProtocol` on the standard-library ``sqlite3``. No third-party dependency: each device is stored as one row of JSON (the record already stores pythonic parameter values as JSON via Pydantic). Suitable for a standalone integration that needs its paired devices to survive a restart; the Hub uses its own SQLAlchemy-backed repository instead. ``sqlite3`` is synchronous; calls are cheap and local, so the async methods invoke it directly. Obtain a session with :meth:`session` (opens a connection, commits on clean exit). """ from __future__ import annotations import json import sqlite3 from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from pathlib import Path from uuid import UUID from majordom_integration_sdk.repository._record import Record, dump, merge from majordom_integration_sdk.schemas.device import Device, DeviceState from majordom_integration_sdk.schemas.parameter import ParameterState, ParameterVisibility class SqliteDeviceRepository: """Persists device records as JSON rows in a SQLite file. Pass ``integration`` to scope every operation to that integration's devices (the guard the Hub sets when handing a repository to a controller). ``None`` gives full access. """ def __init__(self, path: str | Path, integration: str | None = None): self.path = str(path) self.integration = integration conn = self._connect() try: conn.execute( "CREATE TABLE IF NOT EXISTS devices (" " id INTEGER PRIMARY KEY, uuid TEXT UNIQUE NOT NULL, physical_uuid TEXT UNIQUE NOT NULL," " integration TEXT NOT NULL, data TEXT NOT NULL)" ) conn.commit() finally: conn.close() def _connect(self) -> sqlite3.Connection: conn = sqlite3.connect(self.path) conn.row_factory = sqlite3.Row return conn @asynccontextmanager async def session(self) -> AsyncGenerator[SqliteDeviceRepository]: """One unit of work: what ``Platform.make_device_repository`` returns for its integration.""" # A fresh connection per unit of work; sharing one across concurrent tasks is unsafe. self._conn = self._connect() try: yield self self._conn.commit() finally: self._conn.close() del self._conn def _cursor(self) -> sqlite3.Connection: conn = getattr(self, "_conn", None) if conn is None: raise RuntimeError("Use `async with repo.session():` before calling repository methods") return conn def _record(self, value: UUID, column: str = "physical_uuid") -> Record | None: """The stored record for an in-scope device by its ``physical_uuid`` (or Hub ``uuid``), or None.""" if self.integration is None: row = self._cursor().execute(f"SELECT data FROM devices WHERE {column} = ?", (str(value),)).fetchone() else: row = ( self._cursor() .execute( f"SELECT data FROM devices WHERE {column} = ? AND integration = ?", (str(value), self.integration), ) .fetchone() ) return json.loads(row["data"]) if row else None def _write(self, record: Record): self._cursor().execute( "INSERT INTO devices (uuid, physical_uuid, integration, data) VALUES (?, ?, ?, ?) " "ON CONFLICT(uuid) DO UPDATE SET physical_uuid = excluded.physical_uuid," " integration = excluded.integration, data = excluded.data", (record["id"], record["physical_id"], record["integration"], json.dumps(record)), ) async def get_all[T: Device](self, as_: type[T] = Device) -> list[T]: if self.integration is None: rows = self._cursor().execute("SELECT data FROM devices").fetchall() else: rows = ( self._cursor().execute("SELECT data FROM devices WHERE integration = ?", (self.integration,)).fetchall() ) return [as_.model_validate(json.loads(row["data"])) for row in rows] async def get[T: Device](self, *, physical_id: UUID, as_: type[T] = Device) -> T | None: record = self._record(physical_id) return as_.model_validate(record) if record else None async def state[T: DeviceState](self, *, physical_id: UUID, as_: type[T] = DeviceState) -> T | None: record = self._record(physical_id) return as_.model_validate(record) if record else None async def get_parameter_state(self, *, physical_id: UUID, parameter_id: UUID) -> ParameterState | None: record = self._record(physical_id) if not record: return None return next( (ParameterState.model_validate(p) for p in record.get("parameters", []) if p["id"] == str(parameter_id)), None, ) async def save(self, device: Device | DeviceState): if self.integration is not None and device.integration != self.integration: raise PermissionError(f"Device {device.id} is outside integration scope {self.integration!r}") self._write(merge(self._record(device.id, "uuid"), device)) # another record's physical_uuid: IntegrityError async def save_parameter_state(self, *, physical_id: UUID, parameter_state: ParameterState): record = self._record(physical_id) if not record: raise KeyError(f"Unknown or out-of-scope device {physical_id}") updated = dump(parameter_state) record["parameters"] = [ updated if p["id"] == str(parameter_state.id) else p for p in record.get("parameters", []) ] self._write(record) # Hub-internal (not on DeviceRepositoryProtocol), by the Hub's ids; still scope-checked. async def update_parameter_visibility(self, parameter_id: UUID, visibility: ParameterVisibility): for device in await self.get_all(): record = self._record(device.id, "uuid") if not record: continue if any(p["id"] == str(parameter_id) for p in record.get("parameters", [])): for parameter in record["parameters"]: if parameter["id"] == str(parameter_id): parameter["visibility"] = visibility.value self._write(record) return async def delete(self, device_id: UUID): if self._record(device_id, "uuid") is None: return self._cursor().execute("DELETE FROM devices WHERE uuid = ?", (str(device_id),)) __all__ = ["SqliteDeviceRepository"] ================================================================================ # FILE: majordom_integration_sdk/runtime/__init__.py ================================================================================ """The runtime (the ``runtime`` extra): runs peripherals — radios, the host's adapters and network, containers, the in-process providers, integrations — and binds their needs. `default_peripherals` are what it runs around integrations (see `majordom_integration_sdk.runtime.defaults`); DNS-SD, the ``discovery`` extra, is in `majordom_integration_sdk.runtime.peripherals.providers.zeroconf`. """ from majordom_integration_sdk.runtime.defaults import default_peripherals from majordom_integration_sdk.runtime.peripherals.hardware.drivers import Silabs, ZWave, default_usb_drivers from majordom_integration_sdk.runtime.peripherals.hardware.fixed import FixedPeripherals, FixedRadio from majordom_integration_sdk.runtime.peripherals.hardware.host import BluetoothAdapters, HostNetwork from majordom_integration_sdk.runtime.peripherals.hardware.usb import Radio, RadioBusy, UsbScanner from majordom_integration_sdk.runtime.peripherals.pinned import Pinned from majordom_integration_sdk.runtime.peripherals.providers.ble.router import BLEService from majordom_integration_sdk.runtime.peripherals.providers.ssdp import SSDPDiscoveryService from majordom_integration_sdk.runtime.peripherals.services.builtin import otbr, silabs_multiprotocol from majordom_integration_sdk.runtime.peripherals.services.compose import Compose from majordom_integration_sdk.runtime.runtime import ( RETRY_DELAYS, DisabledStore, MemoryDisabledStore, PeripheralState, PeripheralStatus, Runtime, RuntimeOutput, StatusKind, ) __all__ = [ "default_peripherals", "Runtime", "RuntimeOutput", "PeripheralState", "PeripheralStatus", "StatusKind", "DisabledStore", "MemoryDisabledStore", "RETRY_DELAYS", "UsbScanner", "Radio", "RadioBusy", "default_usb_drivers", "otbr", "silabs_multiprotocol", "Silabs", "ZWave", "FixedPeripherals", "FixedRadio", "BluetoothAdapters", "HostNetwork", "Pinned", "Compose", "BLEService", "SSDPDiscoveryService", ] ================================================================================ # FILE: majordom_integration_sdk/runtime/defaults.py ================================================================================ """What a runtime runs by default, given explicitly: the defaults keep a composition root short and replaceable. Each call builds new ones, so no two runtimes share a peripheral. Under the Hub, hardware first (the order given is the order of preference):: Runtime(data, [Pinned(*mine), FixedPeripherals(*soldered), *default_peripherals(), *integrations], platform=...) In library mode, one integration with what it needs:: Runtime(data, [*default_peripherals(), HueController(platform)], platform=platform) Runtime(data, [HostNetwork(), ZeroconfDiscoveryService(), HueController(platform)], platform=platform) """ from __future__ import annotations import functools import logging from majordom_integration_sdk.peripherals import Peripheral from majordom_integration_sdk.runtime.peripherals.hardware.host import BluetoothAdapters, HostNetwork from majordom_integration_sdk.runtime.peripherals.hardware.usb import UsbScanner from majordom_integration_sdk.runtime.peripherals.providers.ble.router import BLEService from majordom_integration_sdk.runtime.peripherals.providers.ssdp import SSDPDiscoveryService from majordom_integration_sdk.runtime.peripherals.services.builtin import otbr, silabs_multiprotocol from majordom_integration_sdk.runtime.peripherals.services.compose import Compose log = logging.getLogger(__name__) def default_peripherals(*, listen_address: str = "127.0.0.1") -> list[Peripheral]: """Everything the SDK runs around integrations, in the order it binds: the sticks plugged in (by `default_usb_drivers`) before the containers that serve over them, Docker Compose that runs those, the multiprotocol border router before the standalone one, the Bluetooth router before the integrations, so it takes every adapter. On-demand ones run only while used. The containers on the host network answer on ``listen_address`` (`Compose`): the hub only by default.""" zeroconf = _zeroconf() return [ UsbScanner(), BluetoothAdapters(), HostNetwork(), Compose(listen_address), silabs_multiprotocol(), otbr(), BLEService(), *([zeroconf()] if zeroconf else []), SSDPDiscoveryService(), ] @functools.cache # said once def _zeroconf() -> type[Peripheral] | None: try: from majordom_integration_sdk.runtime.peripherals.providers.zeroconf import ZeroconfDiscoveryService except ImportError: log.warning('No DNS-SD without zeroconf: pip install "majordom-integration-sdk[discovery]"') return None return ZeroconfDiscoveryService __all__ = ["default_peripherals"] ================================================================================ # FILE: majordom_integration_sdk/runtime/output.py ================================================================================ """The one ``output`` every peripheral of a runtime shares.""" from __future__ import annotations from collections.abc import Iterable, Mapping from typing import TYPE_CHECKING, Any from uuid import UUID from majordom_integration_sdk.controller.output import ControllerOutput, IntegrationError from majordom_integration_sdk.peripherals import Peripheral from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.schemas.event import Event from majordom_integration_sdk.schemas.notification import Notification if TYPE_CHECKING: from majordom_integration_sdk.controller.output import AnyController from majordom_integration_sdk.runtime.runtime import Runtime class HostOutput(ControllerOutput): """What every peripheral of a runtime tells, as its ``output``: its lifecycle goes to the runtime, a controller's reports to ``controller_output`` (the Hub). A controller that can't go on (an error not ``is_still_running``) fails in the runtime too, and one that changed what it provides has the runtime read it again.""" def __init__(self, runtime: Runtime, controller_output: ControllerOutput): self.runtime, self.controller_output = runtime, controller_output # PeripheralOutput async def peripheral_did_change_provided(self, peripheral: Peripheral): await self.runtime.peripheral_did_change_provided(peripheral) async def peripheral_did_learn(self, peripheral: Peripheral, facts: Mapping[str, Any]): await self.runtime.peripheral_did_learn(peripheral, facts) async def peripheral_did_stop(self, peripheral: Peripheral): await self.runtime.peripheral_did_stop(peripheral) async def peripheral_did_fail(self, peripheral: Peripheral, reason: str): await self.runtime.peripheral_did_fail(peripheral, reason) # ControllerOutput async def controller_did_receive_discovery(self, controller: AnyController, discovery: Discovery): await self.controller_output.controller_did_receive_discovery(controller, discovery) async def controller_did_update_discovery(self, controller: AnyController, discovery: Discovery): await self.controller_output.controller_did_update_discovery(controller, discovery) async def controller_did_lose_discovery(self, controller: AnyController, discovery_id: UUID): await self.controller_output.controller_did_lose_discovery(controller, discovery_id) async def controller_did_connect_device( self, controller: AnyController, *, physical_id: UUID | None = None, device_id: UUID | None = None ): if physical_id: await self.controller_output.controller_did_connect_device(controller, physical_id=physical_id) elif device_id: await self.controller_output.controller_did_connect_device(controller, device_id=device_id) async def controller_did_lose_device( self, controller: AnyController, *, physical_id: UUID | None = None, device_id: UUID | None = None ): if physical_id: await self.controller_output.controller_did_lose_device(controller, physical_id=physical_id) elif device_id: await self.controller_output.controller_did_lose_device(controller, device_id=device_id) async def controller_did_receive_events(self, controller: AnyController, events: Iterable[Event]): await self.controller_output.controller_did_receive_events(controller, events) async def controller_did_encounter_error(self, controller: AnyController, error: IntegrationError): await self.controller_output.controller_did_encounter_error(controller, error) if not error.is_still_running: await self.runtime.peripheral_did_fail(controller, error.message) async def controller_did_resolve_error(self, controller: AnyController, error_id: str): await self.controller_output.controller_did_resolve_error(controller, error_id) async def controller_did_emit_notification(self, controller: AnyController, notification: Notification): await self.controller_output.controller_did_emit_notification(controller, notification) async def controller_did_change_provided(self, controller: AnyController): await self.runtime.peripheral_did_change_provided(controller) ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/__init__.py ================================================================================ """The peripherals the runtime brings: hardware (`hardware`), the containers between radios and integrations (`services`), the ones it runs in-process (`providers`) and the endpoints you provide yourself (`pinned`).""" ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/hardware/__init__.py ================================================================================ """Hardware as peripherals: USB sticks (`usb`, recognised by `drivers`), what is soldered on the board (`fixed`), the host's network and Bluetooth adapters (`host`).""" ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/hardware/drivers.py ================================================================================ """The SDK's USB drivers, for radios: recognise which firmware a stick runs, say what each firmware serves, flash between them.""" from __future__ import annotations import asyncio import hashlib import re import urllib.request from dataclasses import dataclass from pathlib import Path from typing import ClassVar from majordom_integration_sdk.peripherals import Endpoint, UsbDriver @dataclass(frozen=True) class Firmware: url: str sha256: str is_stable: bool = False # verified for shipping; the rest is offered on the dev channel only _NABUCASA = "https://github.com/NabuCasa/silabs-firmware-builder/releases/download" class Silabs(UsbDriver): """Silicon Labs EFR32 sticks: Zigbee NCP (EZSP), Thread RCP (Spinel) or multi-PAN RCP (CPC).""" name = "silabs" firmwares = { "zigbee-ncp": [Endpoint("zigbee", "ezsp", "{device}", params={"baud": 115200, "flow_control": True})], "thread-rcp": [Endpoint("thread", "spinel", "{device}", params={"baud": 460800, "flow_control": True})], "multipan-rcp": [Endpoint("multipan", "silabs-cpc", "{device}", params={"baud": 460800, "flow_control": True})], } #: Builds per board, keyed by the product name in the stick's /dev/serial/by-id path. boards: ClassVar[dict[str, dict[str, Firmware]]] = { "SkyConnect": { "zigbee-ncp": Firmware( f"{_NABUCASA}/v2025.11.24/skyconnect_zigbee_ncp_7.4.4.5.gbl", "9a189c5797ee4ac975c0a5ebdd96b126332ac348cab27d065bd58e993e7bb7b0", ), "thread-rcp": Firmware( f"{_NABUCASA}/v2025.11.24/skyconnect_openthread_rcp_2.4.4.0_GitHub-7074a43e4_gsdk_4.4.4.gbl", "4cb5d04f4fab827745665104110fe1d272e4eb9bc38d1f496abb0311ef76e062", ), # no multipan-rcp: NabuCasa's is gsdk 4.4.4 (CPC v5), the multi-PAN service runs SiSDK 2025.6.3 (CPC v6) # and our SiSDK build isn't published yet; a stick already on it is still recognised (``_apps``) }, } # NabuCasa's multi-PAN RCP is 802.15.4 only: none of these builds serves Bluetooth (``bluetooth`` stays empty) _apps = {"EZSP": "zigbee-ncp", "SPINEL": "thread-rcp", "CPC": "multipan-rcp"} async def identify(self, path: str) -> str | None: found = re.search(r"Detected ApplicationType\.(\w+)", await _flasher(path, "probe")) return self._apps.get(found[1]) if found else None def flashable(self, path: str, channel: str) -> list[str]: builds = next((b for name, b in self.boards.items() if name in path), {}) return [fw for fw, build in builds.items() if build.is_stable or channel == "dev"] async def flash(self, path: str, firmware: str, channel: str, cache: Path): if firmware not in self.flashable(path, channel): raise ValueError(f"No {firmware} firmware for {path} on the {channel} channel") build = next(b[firmware] for name, b in self.boards.items() if name in path) file = cache / build.url.rsplit("/", 1)[1] if not file.exists(): cache.mkdir(parents=True, exist_ok=True) data = await asyncio.to_thread(lambda: urllib.request.urlopen(build.url, timeout=60).read()) if hashlib.sha256(data).hexdigest() != build.sha256: raise ValueError(f"Checksum mismatch for {build.url}") file.write_bytes(data) await _flasher(path, "flash", "--firmware", str(file)) class ZWave(UsbDriver): """Z-Wave controllers speaking the Serial API (any vendor).""" name = "zwave" firmwares = { "serial-api": [Endpoint("zwave", "serial-api", "{device}", params={"baud": 115200, "flow_control": False})] } async def identify(self, path: str) -> str | None: return "serial-api" if await asyncio.to_thread(_zwave_answers, path) else None def _zwave_answers(path: str) -> bool: import serial # the runtime extra # Serial API request frame for FUNC_ID_ZW_GET_VERSION: SOF, length, REQ, 0x15, checksum. # A controller replies with its library version string, "Z-Wave x.y", and repeats any reply # the host didn't ACK (answering CAN to new requests meanwhile): NAK first, ACK the answer. with serial.Serial(path, 115200, timeout=1) as port: port.write(b"\x15") for _ in range(3): port.reset_input_buffer() port.write(bytes([0x01, 0x03, 0x00, 0x15, 0xE9])) if b"Z-Wave" in port.read(64): port.write(b"\x06") return True return False async def _flasher(path: str, *args: str) -> str: """Run universal-silabs-flasher (an external tool, kept out of this package's dependencies).""" process = await asyncio.create_subprocess_exec( "universal-silabs-flasher", "--device", path, *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, ) # fmt: skip output = (await process.communicate())[0].decode(errors="replace") if process.returncode: raise RuntimeError(f"universal-silabs-flasher {args[0]} failed on {path}:\n{output[-2000:]}") return output #: USB ids of radios opened unasked to identify them. Generic bridges common on other boards stay out #: (CH340 1a86:7523 on Arduinos, Espressif 303a on ESP32s): opening their port resets the board. #: A device that isn't listed is identified only when asked (`Radio.probe`). RADIO_USB_IDS = { ("10c4", "ea60"), # CP210x: Home Assistant SkyConnect / ZBT-1, Sonoff ZBDongle-P and Z-Wave PZG23, Zooz ZST10 ("10c4", "8a2a"), # Nortek HUSBZB-1 ("1a86", "55d4"), # CH9102: Sonoff ZBDongle-E, SMLIGHT SLZB-07 ("0658", "0200"), # Sigma Designs: Aeotec Z-Stick, HomeSeer SmartStick ("1cf1", "0030"), # dresden elektronik ConBee II ("0403", "6015"), # FTDI X: ConBee III, ZiGate+ ("0451", "16a8"), # TI CC2531 } def default_usb_drivers() -> list[UsbDriver]: """Every driver of the SDK, tried in this order on every unidentified stick: the cheap single-frame Z-Wave check first.""" return [ZWave(), Silabs()] ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/hardware/fixed.py ================================================================================ """Hardware soldered on the board, as peripherals.""" from __future__ import annotations from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path from typing import Any from majordom_integration_sdk.peripherals import Peripheral, UsbDriver from majordom_integration_sdk.runtime.peripherals.hardware.drivers import default_usb_drivers from majordom_integration_sdk.runtime.peripherals.hardware.usb import Radio @dataclass(frozen=True) class FixedRadio: """A radio wired to the board: used without asking, by the driver named ``driver``. With no ``firmware`` that driver identifies it; ``params`` override the firmware's serial settings where the board wires them otherwise, and may name the line wired to its reset (``reset_gpio``, e.g. ``gpiochip0:23``) for a multi-PAN RCP on a bare UART.""" name: str path: str driver: str firmware: str | None = None params: Mapping[str, Any] = field(default_factory=dict) class FixedPeripherals(Peripheral): """What is soldered on the board, as its owner describes it (the Hub reads its board profile): each one whose path exists is brought along, a radio as a `Radio`. FixedPeripherals( FixedRadio("mg26", "/dev/ttyAMA3", "silabs", "multipan-rcp", {"baud": 115200, "flow_control": False}) ) """ name = "board" def __init__(self, *radios: FixedRadio, drivers: Sequence[UsbDriver] | None = None): self.radios, self.drivers = radios, default_usb_drivers() if drivers is None else list(drivers) self._present: list[Radio] = [] @property def provides(self) -> list[Radio]: return self._present async def start(self): drivers = {driver.name: driver for driver in self.drivers} present = [] for fixed in self.radios: if not Path(fixed.path).exists(): continue driver = drivers[fixed.driver] known = driver if fixed.firmware else None radio = Radio(fixed.name, fixed.path, lambda driver=driver: [driver], known, fixed.firmware, fixed.params) await (radio.check_bluetooth() if known else radio.recognise()) present.append(radio) self._present = present async def stop(self): self._present = [] ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/hardware/host.py ================================================================================ """What the host itself serves: its network and its Bluetooth adapters.""" from __future__ import annotations import asyncio import logging import sys from collections.abc import Sequence from glob import glob from pathlib import Path from majordom_integration_sdk.peripherals import Endpoint, Peripheral log = logging.getLogger(__name__) POLL = 2 # seconds between looks at the adapters there are class HostNetwork(Peripheral): """The host's IP network, shared by everything that talks over it: ``ip``.""" name = "host" provides = [Endpoint("ip", is_shared=True)] class BluetoothAdapters(Peripheral): """Every Bluetooth adapter of the host as its own single-use ``ble/bluez`` endpoint, with its ``index`` (the router takes them all when it is given first); off Linux, bleak's default adapter on the OS's own stack. Adapters that appear or disappear are followed.""" name = "bluetooth-adapters" def __init__(self): self._adapters: list[str] = [] self._watcher: asyncio.Task | None = None @property def provides(self) -> Sequence[Endpoint]: return [Endpoint("ble", "bluez", name, params={"index": name.removeprefix("hci")}) for name in self._adapters] async def start(self): self._adapters = _adapters() self._watcher = asyncio.create_task(self._watch(), name="bluetooth-adapters.watch") async def stop(self): if self._watcher: self._watcher.cancel() self._adapters = [] async def _watch(self): while True: await asyncio.sleep(POLL) if (found := _adapters()) != self._adapters: self._adapters = found try: await self.output.peripheral_did_change_provided(self) except Exception: log.exception("Following the Bluetooth adapters failed") def _adapters() -> list[str]: if sys.platform != "linux": return [""] return sorted(Path(path).name for path in glob("/sys/class/bluetooth/hci*") if ":" not in Path(path).name) ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/hardware/usb.py ================================================================================ """USB devices as peripherals: the scanner brings one `Radio` along per stick plugged in.""" from __future__ import annotations import asyncio import contextlib import errno import fcntl import logging import os import tempfile from collections.abc import Callable, Coroutine, Mapping, Sequence from glob import glob from pathlib import Path from typing import Any, Literal from pydantic import BaseModel, Field from majordom_integration_sdk.files import read_json, write_json from majordom_integration_sdk.peripherals import ( USB_DRIVER, Endpoint, Need, Peripheral, PeripheralChange, UsbDriver, ) from majordom_integration_sdk.runtime.peripherals.hardware.drivers import RADIO_USB_IDS, default_usb_drivers from majordom_integration_sdk.runtime.peripherals.providers.ble import cpc_hci log = logging.getLogger(__name__) PROBE_TIMEOUT = 60 # per driver: one that hangs (bellows resetting a busy port) is given up POLL = 2 # seconds between looks at the sticks plugged in FIRMWARE_CACHE = Path(tempfile.gettempdir()) / "majordom-firmware" # downloads are checked against their checksum UNSEEN = "another program" # one that locked a port: whether it let go shows only by opening it class RadioBusy(RuntimeError): """The radio is being flashed or probed already: ask again once that is done.""" class Radio(Peripheral["Radio.Settings"]): """A radio, a USB stick or soldered on the board: it serves what its firmware does once a driver identified it, and nothing while another program holds it or it is being flashed. Flashing, probing and forgetting it are the user's to ask for, one at a time: asked while one runs, they raise `RadioBusy`.""" class Settings(BaseModel): firmware_channel: Literal["stable", "dev"] = Field( "stable", title="Radio firmware", description="Stable offers verified builds only, dev every known build." ) def __init__( self, name: str, path: str, drivers: Callable[[], Sequence[UsbDriver]], driver: UsbDriver | None = None, firmware: str | None = None, params: Mapping[str, Any] | None = None, # the firmware's serial settings, where soldered hardware wires them scanner: UsbScanner | None = None, # what found it plugged in, which keeps what it is ): self.name, self.path, self.drivers, self.scanner = name, path, drivers, scanner self.driver, self.firmware, self.params = driver, firmware, params or {} self._given = driver, firmware # what the board says a soldered one runs: kept if, forgotten, no driver tells self.found: dict[str, Any] = {} # the serial settings its driver found it at, under the board's ``params`` self.node = os.path.realpath(path) # a container keeps the node it was created with: follow a re-enumeration self.held_by: str | None = None # another program that has it open: left alone until probed self.is_claimed = False # the user probed it: opened whoever holds it or whatever its USB id self.lock = asyncio.Lock() # held while it is flashed, probed or identified: one opens its port at a time self.has_bluetooth = False # its multiprotocol firmware serves Bluetooth too self.settings = self.Settings() self._asked: list[UsbDriver] = [] # the drivers that didn't recognise it def __repr__(self) -> str: return f"Radio({self.name!r}, {self.firmware!r})" @property def provides(self) -> list[Endpoint]: if self.is_busy or self.held_by or self.driver is None: return [] endpoints = self.driver.serves(self.firmware, self.node, {**self.found, **self.params}) if self.has_bluetooth: # the multiprotocol container attaches it and tells its hciN endpoints.append(Endpoint("ble", "silabs-cpc-hci", self.node, params={"hci": None})) return endpoints @property def is_busy(self) -> bool: """Being flashed, probed or identified.""" return self.lock.locked() @property def options(self) -> list[str]: """Firmwares it can be switched to on its channel.""" return self.driver.flashable(self.path, self.settings.firmware_channel) if self.driver else [] # Peripheral hooks async def settings_did_change(self, before: Radio.Settings) -> bool: """Its channel only changes what it may be flashed to: nothing restarts.""" return True # Actions async def recognise(self, is_asking_again: bool = False): """Ask the drivers which firmware it runs, each once unless ``is_asking_again``, until one tells.""" for driver in [d for d in self.drivers() if is_asking_again or all(d is not a for a in self._asked)]: if identified := await _identified(driver, self.path): self.driver, (self.firmware, self.found) = driver, identified await self.check_bluetooth() return self._asked.append(driver) log.info(f"No driver recognised {self.path}") async def probe(self): """Identify it now, also a stick no driver knows the USB id of, or one another program holds: its port is opened, which may reset what's behind it. Whatever uses it lets go of it first.""" async with self._busy(): self.held_by, self.is_claimed = None, True await self.recognise(is_asking_again=True) self._remember() async def flash(self, firmware: str): """Switch it to ``firmware`` on its channel; whatever uses it lets go of it first and gets it back after.""" if (driver := self.driver) is None: raise LookupError(f"No driver knows {self.name}: probe it first") async with self._busy(): try: await driver.flash(self.path, firmware, self.settings.firmware_channel, FIRMWARE_CACHE) finally: # whether it took or not, what ran before may be gone self.firmware, self.found = await _identified(driver, self.path) or (None, {}) self.has_bluetooth = False await self.check_bluetooth() self._remember() async def forget(self): """Forget what it is and that the user probed it: whatever uses it lets go of it, and it is looked at again as a stick plugged in anew, or, soldered, identified again: as the board says when no driver tells.""" async with self._busy(): if self.scanner: # first: a scan going on would take it back from there self.scanner.forget(self) self.driver, self.firmware, self.found, self.has_bluetooth = None, None, {}, False self.is_claimed, self._asked = False, [] if self.scanner is None: await self.recognise() if self.driver is None and self._given[1]: self.driver, self.firmware = self._given await self.check_bluetooth() if self.scanner: await self.scanner.rescan() async def check_bluetooth(self): """Whether a multi-PAN firmware serves Bluetooth too: the driver says where it knows, else it is asked.""" endpoints = self.driver.serves(self.firmware, self.node) if self.driver else [] if any(e.family == "multipan" for e in endpoints) and self.driver: self.has_bluetooth = self.firmware in self.driver.bluetooth or await cpc_hci.has_bluetooth(self.path) # Private def _remember(self): if self.scanner: self.scanner.remember(self) @contextlib.asynccontextmanager async def _busy(self): if self.lock.locked(): raise RadioBusy(f"{self.name} is being flashed or probed: ask again once that is done") try: async with self.lock: await self.output.peripheral_did_change_provided(self) # returns once what used it let go of it yield finally: await self.output.peripheral_did_change_provided(self) class UsbScanner(Peripheral): """USB devices plugged in (``/dev/serial/by-id``), each brought along as a `Radio` and identified by its drivers, then by the ones integrations provide (``usb-driver``): radios today. Only a device whose USB id is a known radio's is opened unasked; another is identified when the user asks (`Radio.probe`). One another program holds is left alone until then. What it identified and what the user probed is remembered, in ``sticks.json`` of its data folder: a stick known from before isn't opened again, and waits for the driver that identified it (an integration's, bound once that runs). UsbScanner() # every SDK driver: default_usb_drivers() UsbScanner(drivers=[Silabs()]) """ name = "usb" needs = [Need(USB_DRIVER, is_many=True, is_required=False)] def __init__(self, drivers: Sequence[UsbDriver] | None = None): self.drivers = default_usb_drivers() if drivers is None else list(drivers) self._radios: list[Radio] = [] self._known: dict[str, Any] = {} # by-id name -> what it was identified as, whether the user claimed it self._tasks: set[asyncio.Task] = set() # watching the sticks, and asking new drivers about them self._scanning = asyncio.Lock() # one scan at a time: two would open a stick at once @property def provides(self) -> list[Radio]: return self._radios @property def radios(self) -> list[Radio]: return list(self._radios) # Lifecycle async def start(self): self._known = read_json(self.platform.documents_folder(self) / "sticks.json") await self._scan() self._spawn(self._watch()) async def stop(self): for task in self._tasks: task.cancel() self._radios = [] async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: """A driver was bound, e.g. one an integration provides: it may know the sticks no other driver did. Asked in the background, as a probe may take long.""" self._spawn(self.rescan()) return True # Actions async def rescan(self): """Follow the sticks plugged in now, identifying the new ones it may open.""" try: await self._scan() await self.output.peripheral_did_change_provided(self) except Exception: log.exception("Following the USB sticks failed") def remember(self, *radios: Radio): """Keep what ``radios`` are, and whether the user claimed them, across restarts.""" for radio in radios: driver = radio.driver.name if radio.driver else None known = { "driver": driver, "firmware": radio.firmware, "params": radio.found, "has_bluetooth": radio.has_bluetooth, } self._known[radio.name] = known | {"is_claimed": radio.is_claimed} write_json(self.platform.documents_folder(self) / "sticks.json", self._known) def forget(self, radio: Radio): """Forget what ``radio`` is, and that the user claimed it: the next scan looks at it as a stick plugged in anew.""" self._known.pop(radio.name, None) write_json(self.platform.documents_folder(self) / "sticks.json", self._known) # Private def _spawn(self, coroutine: Coroutine[Any, Any, Any]): task = asyncio.create_task(coroutine) self._tasks.add(task) task.add_done_callback(self._tasks.discard) def _drivers(self) -> list[UsbDriver]: return [*self.drivers, *(endpoint.instance for endpoint in self.peripherals.endpoints(USB_DRIVER))] async def _scan(self): """Follow the sticks plugged in, and identify the new ones it may open.""" async with self._scanning: radios = {radio.name: radio for radio in self.radios} found = _sticks() drivers = {driver.name for driver in self._drivers()} for name, path in found.items(): radio = radios.get(name) or self._radio(name, path) if radio.driver is None: # what identified it may only now be here: a driver an integration provides self._restore(radio) radio.node = os.path.realpath(path) remembered = self._known.get(name, {}).get("driver") is_awaited = radio.driver is None and remembered is not None and remembered not in drivers is_trusted = (radio.is_claimed or _usb_id(path) in RADIO_USB_IDS) and not is_awaited if not radio.is_claimed and not radio.is_busy: radio.held_by = _holder(path, is_opening_allowed=is_trusted and radio.driver is None) if is_trusted and radio.driver is None and not radio.held_by and not radio.is_busy: async with radio.lock: await radio.recognise() radios[name] = radio self._radios = [radios[name] for name in sorted(found)] self.remember(*[radio for radio in self._radios if radio.driver or radio.is_claimed]) def _radio(self, name: str, path: str) -> Radio: """A stick plugged in, claimed if the user probed it before.""" radio = Radio(name, path, self._drivers, scanner=self) radio.is_claimed = self._known.get(name, {}).get("is_claimed", False) return radio def _restore(self, radio: Radio): """What it was identified as before, once the driver that did is here.""" known, drivers = self._known.get(radio.name, {}), {driver.name: driver for driver in self._drivers()} if (driver := drivers.get(known.get("driver", ""))) and (firmware := known.get("firmware")): radio.driver, radio.firmware, radio.has_bluetooth = driver, firmware, known.get("has_bluetooth", False) radio.found = known.get("params", {}) async def _watch(self): seen = _nodes(_sticks()) while True: await asyncio.sleep(POLL) found = _nodes(_sticks()) if found != seen: # act once the change held for one more poll (a stick re-enumerating) seen = found continue is_moved = found != {radio.name: radio.node for radio in self.radios} is_let_go = any(r.held_by not in (None, UNSEEN) and not _holder(r.path) for r in self.radios) if is_moved or is_let_go: await self.rescan() async def _identified(driver: UsbDriver, path: str) -> tuple[str, dict[str, Any]] | None: """What ``driver`` recognises the device at ``path`` running, and the serial settings it found it at; None when it doesn't, can't tell, or hangs.""" try: async with asyncio.timeout(PROBE_TIMEOUT): found = await driver.identify(path) except Exception as error: log.warning(f"{driver.name} failed to identify {path}: {_failure(error)}") return None firmware, params = (found, {}) if isinstance(found, str) or found is None else found return (firmware, dict(params)) if firmware else None def _failure(error: Exception) -> str: return str(error) or type(error).__name__ def _sticks() -> dict[str, str]: return {Path(path).name: path for path in glob("/dev/serial/by-id/*")} def _nodes(paths: Mapping[str, str]) -> dict[str, str]: """The device node behind each path. After a USB reset a stick keeps its by-id name but may come back on another tty; a container keeps the node it was created with, which may then be another device.""" return {name: os.path.realpath(path) for name, path in paths.items()} def _usb_id(path: str) -> tuple[str, str] | None: """USB vendor and product id of the device behind a serial port; None for a UART.""" device = Path("/sys/class/tty", Path(os.path.realpath(path)).name, "device").resolve() for parent in (device, *device.parents): with contextlib.suppress(OSError): return (parent / "idVendor").read_text().strip(), (parent / "idProduct").read_text().strip() return None def _holder(path: str, is_opening_allowed: bool = False) -> str | None: """The other program that has a serial port open: one whose open files we may read, or with ``is_opening_allowed`` (it opens the port) one that locked it, whoever runs it (`UNSEEN`). Our own containers see the port under another name (/dev/ttyRCP), so they don't count.""" names = {path, os.path.realpath(path)} for fd in glob("/proc/[0-9]*/fd/*"): with contextlib.suppress(OSError): if (pid := fd.split("/")[2]) != str(os.getpid()) and os.readlink(fd) in names: return Path(f"/proc/{pid}/comm").read_text().strip() if not is_opening_allowed: return None try: port = os.open(path, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) except OSError as error: return UNSEEN if error.errno == errno.EBUSY else None # EBUSY: opened exclusively (TIOCEXCL) try: fcntl.flock(port, fcntl.LOCK_EX | fcntl.LOCK_NB) # pyserial's and node-serialport's exclusive lock except OSError: return UNSEEN finally: os.close(port) return None ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/pinned.py ================================================================================ """Endpoints you provide yourself.""" from __future__ import annotations from collections.abc import Sequence from majordom_integration_sdk.peripherals import Endpoint, Peripheral class Pinned(Peripheral): """Endpoints you run yourself, one per family: a ``socket://`` EZSP stick on the network, a matter-server of your own. Give it to the runtime first, so they win over anything found. stick = Endpoint("zigbee", "ezsp", "socket://192.168.1.5:6638") Runtime(data, [Pinned(stick), *default_peripherals()], platform=platform) """ name = "pinned" def __init__(self, *endpoints: Endpoint): self._endpoints = {endpoint.family: endpoint for endpoint in endpoints} @property def provides(self) -> Sequence[Endpoint]: return list(self._endpoints.values()) async def pin(self, endpoint: Endpoint): """Provide ``endpoint`` for its family, in place of the one pinned before.""" self._endpoints[endpoint.family] = endpoint await self.output.peripheral_did_change_provided(self) async def unpin(self, family: str): self._endpoints.pop(family, None) await self.output.peripheral_did_change_provided(self) ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/providers/__init__.py ================================================================================ """The peripherals the runtime runs in its own process, on demand, each provided as a shared endpoint carrying itself: the Bluetooth router (``ble/router``, its sources: the ``ble`` extra), DNS-SD (``mdns/zeroconf``, the ``discovery`` extra) and SSDP (``upnp/ssdp``); and `BLEProxy`, a Bluetooth source an integration lends the router.""" ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/providers/ble/__init__.py ================================================================================ """Bluetooth LE in the runtime: the router (`router`), the host's adapters (`bluez`, the ``ble`` extra), the multiprotocol radio's Bluetooth (`cpc_hci`); integrations lend it sources as `majordom_integration_sdk.peripherals.BLEProxy`.""" ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/providers/ble/bluez.py ================================================================================ """The host's Bluetooth adapters as ble/bluez sources of the router, through bleak (BlueZ on Linux, the OS's own stack elsewhere), and pairing through BlueZ with an agent of our own, scoped to the one device being paired. LE Secure Connections "Just Works" still asks the host to confirm (the kernel's confirm hint), and bluetoothd turns that into an agent call: without an agent the pairing fails ("Numeric comparison failed"), and bleak registers none. So the pairing is started from a D-Bus connection that holds an `org.bluez.Agent1` (bluetoothd asks the agent of whoever called `Pair`): it confirms only that device, and goes away with the connection. """ import asyncio import contextlib import itertools import logging import sys from collections.abc import Callable from typing import Any from bleak import BleakClient, BleakScanner from bleak.args.bluez import OrPattern from bleak.assigned_numbers import AdvertisementDataType from bleak.backends.device import BLEDevice from bleak.backends.scanner import AdvertisementData from bleak.exc import BleakError from majordom_integration_sdk.capabilities.ble import ( BLEConnection, BLEPairingError, GattCharacteristic, GattService, OnAdvertisement, ) logger = logging.getLogger(__name__) AGENT_PATH = "/io/majordom/pairing_agent" REJECTED = "org.bluez.Error.Rejected" _agents = itertools.count() Answer = tuple[str, list[Any]] | str # (signature, body) to return, or the name of the error to raise def agent_answer(member: str, body: list[Any], device_path: str) -> Answer: """What the agent answers bluetoothd's ``member`` call; anything not about ``device_path`` is refused.""" if member in ("Release", "Cancel"): return "", [] if not body or body[0] != device_path: return REJECTED if member in ("RequestAuthorization", "RequestConfirmation"): # Just Works: nothing to compare without a display return "", [] return REJECTED # passkeys and PIN codes (BR/EDR), service authorization, displays we don't have def device_path(adapter: str, address: str) -> str: return f"/org/bluez/{adapter}/dev_{address.upper().replace(':', '_')}" async def pair_through_agent(adapter: str, address: str): """Pairs the connected device ``address`` on ``adapter`` (hci0, …); raises `ConnectionError` with BlueZ's error.""" # bleak's BlueZ backend brings dbus-fast, on Linux only from dbus_fast import BusType, Message, MessageType from dbus_fast.aio import MessageBus path, agent = device_path(adapter, address), f"{AGENT_PATH}{next(_agents)}" def on_message(message: Message) -> Message | None: if message.message_type != MessageType.METHOD_CALL or message.path != agent: return None answer = agent_answer(message.member or "", list(message.body), path) if isinstance(answer, str): return Message.new_error(message, answer, "Not the device being paired") return Message.new_method_return(message, *answer) async def call(message: Message): reply = await bus.call(message) if reply is not None and reply.message_type == MessageType.ERROR: raise ConnectionError(f"{reply.error_name}: {' '.join(map(str, reply.body))}".strip(": ")) bus = await MessageBus(bus_type=BusType.SYSTEM).connect() bus.add_message_handler(on_message) try: manager = {"destination": "org.bluez", "path": "/org/bluez", "interface": "org.bluez.AgentManager1"} await call(Message(**manager, member="RegisterAgent", signature="os", body=[agent, "NoInputNoOutput"])) try: await call(Message(destination="org.bluez", path=path, interface="org.bluez.Device1", member="Pair")) except ConnectionError as e: if not str(e).startswith("org.bluez.Error.AlreadyExists"): # paired already: the link is encrypted raise finally: with contextlib.suppress(ConnectionError): await call(Message(**manager, member="UnregisterAgent", signature="o", body=[agent])) finally: bus.disconnect() _EVERY_ADVERTISER = [OrPattern(0, AdvertisementDataType.FLAGS, flags) for flags in (b"\x02", b"\x06", b"\x1a")] class LocalAdapter: """A Bluetooth adapter of this machine, through bleak (BlueZ on Linux).""" is_pairable = True # LE Secure Connections where the device offers it; through a scoped BlueZ agent on Linux def __init__(self, adapter: str | None = None): self.name = adapter or "local" self._options = {"bluez": {"adapter": adapter}} if adapter else {} self._scanner: BleakScanner | None = None self._devices: dict[str, BLEDevice] = {} # address -> last seen; connecting by it skips a scan self.is_passive = False # set: a passive scan of every advertiser, the listeners' matchers choose self._is_passive_refused = False self._on_advertisement: OnAdvertisement | None = None self._scan_lock = asyncio.Lock() # a connect holds it: no scan starts until it ends async def set_scan_mode(self, is_active: bool): if self.is_passive == (not is_active): return self.is_passive = not is_active if self._scanner and self._on_advertisement: # scanning: again, in the new mode await self.stop() await self.start(self._on_advertisement) async def start(self, on_advertisement: OnAdvertisement): self._on_advertisement = on_advertisement def on_detection(device: BLEDevice, adv_data: AdvertisementData): self._devices.pop(device.address, None) # re-added last: the dict stays oldest first self._devices[device.address] = device if len(self._devices) > 1024: # phones rotate their address: drop the oldest del self._devices[next(iter(self._devices))] on_advertisement(device, adv_data) # BlueZ refuses a passive scan without --experimental (Raspberry Pi OS's default): then it scans actively. With # it, a Pi 5 (BlueZ 5.82, no offload) passes adverts only through patterns on the flags (2026-10-14), as in HA. async with self._scan_lock: if self.is_passive and not self._is_passive_refused: bluez = {**self._options.get("bluez", {}), "or_patterns": _EVERY_ADVERTISER} try: # macOS refuses a passive scan already when the scanner is made self._scanner = BleakScanner(detection_callback=on_detection, scanning_mode="passive", bluez=bluez) return await self._scanner.start() except Exception as e: # BlueZ's advertisement monitor is missing (an old or non-experimental bluetoothd) logger.warning(f"BLE {self.name} can't scan passively, scanning actively: {e}") self._is_passive_refused = True self.is_passive = False self._scanner = BleakScanner(detection_callback=on_detection, **self._options) await self._scanner.start() async def stop(self): async with self._scan_lock: scanner, self._scanner = self._scanner, None if scanner: await scanner.stop() async def connect(self, address: str, on_disconnect: Callable[[], None]) -> BLEConnection: device = self._devices.get(address, address) client = BleakClient(device, disconnected_callback=lambda _: on_disconnect(), **self._options) async with self._scan_lock: scanner = self._scanner if scanner: # many adapters (the Raspberry Pi's included) stall a connect while discovering await scanner.stop() try: await client.connect() finally: if scanner: await scanner.start() return _BleakConnection(client, self._options.get("bluez", {}).get("adapter") or "hci0") class _BleakConnection: def __init__(self, client: BleakClient, adapter: str): self._client, self._adapter = client, adapter @property def mtu(self) -> int: # On BlueZ bleak says 23 until the MTU is acquired, though BlueZ exchanged the real one on connect and every # characteristic carries it; Matter's BTP sized its segments by the 23 and ran ~10x slower (2026-10-22). characteristics = self._client.services.characteristics.values() return max((c.max_write_without_response_size + 3 for c in characteristics), default=self._client.mtu_size) async def services(self) -> list[GattService]: return [ GattService( service.uuid, service.handle, tuple(GattCharacteristic(c.uuid, c.handle, tuple(c.properties)) for c in service.characteristics), ) for service in self._client.services ] async def read(self, handle: int) -> bytes: return bytes(await self._client.read_gatt_char(handle)) async def write(self, handle: int, data: bytes, is_response_needed: bool = True): await self._client.write_gatt_char(handle, data, response=is_response_needed) async def start_notify(self, handle: int, callback: Callable[[bytes], None]): await self._client.start_notify(handle, lambda _, data: callback(bytes(data))) async def stop_notify(self, handle: int): await self._client.stop_notify(handle) async def pair(self): try: if sys.platform == "linux": # bleak's pair() brings no agent: LE Secure Connections fails without one await pair_through_agent(self._adapter, self._client.address) else: # the OS pairs on its own, with its own prompts await self._client.pair() except (ConnectionError, BleakError, EOFError) as e: # org.bluez.Error.AuthenticationFailed, a dropped link raise BLEPairingError(f"Pairing failed: {e}") from e async def unpair(self): await self._client.unpair() async def disconnect(self): await self._client.disconnect() ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/providers/ble/cpc_hci.py ================================================================================ """Bluetooth of a Silicon Labs multiprotocol radio, as the ``ble/silabs-cpc-hci`` source of the router. A multi-PAN RCP whose firmware carries the Bluetooth controller serves HCI over CPC next to 802.15.4: cpcd's ``cpc-hci-bridge`` exposes it as a pty, and ``btattach`` makes that a BlueZ adapter (``hciN``), heard through bleak like any other. The radio provides the endpoint only when its firmware has Bluetooth: from the driver's firmware metadata (`UsbDriver.bluetooth`) where it knows, else from `has_bluetooth`, asked once per radio. To verify on hardware (nothing here is yet): which CPC endpoint answers for Bluetooth on a given firmware (and how to ask cpcd without taking the port from the multiprotocol container), and the ``hciN`` the bridge comes up as — it arrives in the endpoint's ``params["hci"]`` once the multiprotocol service attaches it. """ from __future__ import annotations from majordom_integration_sdk.capabilities.ble import BLESource from majordom_integration_sdk.peripherals import Endpoint async def has_bluetooth(path: str) -> bool: """Whether the multi-PAN radio at ``path`` serves Bluetooth over CPC. Unverified on hardware: says no until it asks cpcd (see the module docstring).""" return False def source_of(endpoint: Endpoint) -> BLESource: from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter # the ble extra if not (hci := endpoint.params.get("hci")): raise ConnectionError(f"{endpoint.url} has no Bluetooth adapter attached yet") return LocalAdapter(hci) ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/providers/ble/router.py ================================================================================ """The runtime's ``ble/router``: one router over every Bluetooth source the runtime binds to it (see `majordom_integration_sdk.capabilities.ble` for the contract integrations use). It needs every raw radio, ``ble/bluez`` adapters, ``ble/silabs-cpc-hci`` and the ``ble/esphome-proxy`` nodes ESPHome brings along (`BLEProxy`), and provides itself as the one shared ``ble/router``, on demand. Sources come and go as the runtime rebinds it. """ from __future__ import annotations import asyncio import contextlib import logging from collections.abc import AsyncGenerator, Callable, Iterable from dataclasses import dataclass, field from time import monotonic from typing import TYPE_CHECKING from uuid import UUID from majordom_integration_sdk.capabilities.ble import ( BLEBusyError, BLEConnection, BLEDiscoveryInfo, BLEDiscoveryListener, BLELease, BLEMatcher, BLEPairingError, BLESource, OnAdvertisement, PausableBLESource, ScanModeBLESource, ) from majordom_integration_sdk.peripherals import Endpoint, Need, Peripheral, PeripheralChange if TYPE_CHECKING: from bleak.backends.device import BLEDevice from bleak.backends.scanner import AdvertisementData logger = logging.getLogger(__name__) RAW_BLE = ["bluez", "silabs-cpc-hci", "esphome-proxy"] # every radio the router hears through def _adv_signature(adv: AdvertisementData) -> tuple: """Stable advertisement fingerprint — avoids false updates from object identity changes.""" return ( adv.local_name, tuple(sorted(adv.service_uuids)), tuple(sorted((k, bytes(v)) for k, v in adv.manufacturer_data.items())), tuple(sorted((k, bytes(v)) for k, v in adv.service_data.items())), ) def _matches(matchers: list[BLEMatcher], adv: AdvertisementData) -> bool: return any(m.matches(adv) for m in matchers) @dataclass class _BLETrackedDevice: info: BLEDiscoveryInfo heard: dict[str, tuple[int, float]] = field(default_factory=dict) # source -> (rssi, monotonic last seen) name: str | None = None # the last local name heard: a passive scan misses the scan responses that carry it def sources(self, grace: float) -> list[str]: """Sources that heard it within ``grace`` seconds, the strongest signal first.""" now = monotonic() recent = [(rssi, source) for source, (rssi, seen) in self.heard.items() if now - seen < grace] return [source for _, source in sorted(recent, reverse=True)] class BLEService(Peripheral): """Bluetooth LE across all sources: discovery for listeners, GATT connections on demand. A `BLERouter`.""" name = "ble-router" needs = [Need("ble", RAW_BLE, is_many=True, is_required=False)] is_on_demand = True def __init__(self, sources: Iterable[BLESource] = ()): """``sources``: radios to hear through besides the ones the runtime binds.""" self._listeners: list[tuple[BLEDiscoveryListener, list[BLEMatcher]]] = [] self._sources: dict[str, BLESource] = {s.name: s for s in sources} self._bound: dict[tuple[str, int], str] = {} # bound endpoint (url, instance) -> the source it became self._is_running: bool = False self._leases: dict[str, asyncio.Lock] = {} # source -> held while it is leased self._leased: dict[str, str] = {} # source -> the address it is leased for: kept while its radio is silenced self._removal_grace_sec: float = 11.0 # seconds unheard by every source before did_remove is fired self._eviction_interval_sec: float = 10.0 self._silence_sec: float = 60.0 # a source unheard this long is restarted self._active_until: float = 0.0 # monotonic end of an active scan burst self._name_burst_sec: float = 5.0 # an active burst to hear the name of a new device advertising none self._name_burst_interval_sec: float = 60.0 # at most one such burst this often self._name_burst_at: float = float("-inf") # monotonic start of the last one self._heard_at: dict[str, float] = {} # source -> monotonic time it last heard anything self._tracked: dict[str, _BLETrackedDevice] = {} # address -> tracked device self._tasks: set[asyncio.Task] = set() @property def is_running(self) -> bool: return self._is_running @property def endpoint(self) -> Endpoint: """This router, shared by every consumer: pass it to a controller in library mode.""" return Endpoint("ble", "router", "router", is_shared=True, instance=self) @property def provides(self) -> list[Endpoint]: return [self.endpoint] async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: """The runtime bound other radios to it: hear through the new ones, let go of the lost ones.""" await self._follow_bound() return True async def _follow_bound(self): bound = {(e.url, id(e.instance)): e for e in self.peripherals.endpoints("ble")} for key in self._bound.keys() - bound.keys(): await self.remove_source(self._bound.pop(key)) for key in bound.keys() - self._bound.keys(): try: source = source_of(bound[key]) except Exception as e: # a radio that can't be used here (a missing extra) leaves the others working logger.warning(f"BLE can't use {bound[key].dialect} {bound[key].url}: {e}") continue self._bound[key] = source.name await self.add_source(source) def register(self, listener: BLEDiscoveryListener, matchers: Iterable[BLEMatcher | UUID]) -> Callable[[], None]: """ Registers a listener for BLE devices matching any of ``matchers`` (a UUID matches that service). `ble_did_discover_device` is called when a device first matches, `ble_did_update_device` when its advertisement changes, `ble_did_remove_device` when no source has heard it for a while. Returns a cancel function — call it on stop to deregister. """ entry = (listener, [m if isinstance(m, BLEMatcher) else BLEMatcher(service_uuid=m) for m in matchers]) self._listeners.append(entry) for tracked in self._tracked.values(): # devices heard before it registered are new to it if _matches(entry[1], tracked.info.advertisement): self._spawn(listener.ble_did_discover_device(self, tracked.info)) def cancel(): if entry in self._listeners: self._listeners.remove(entry) return cancel async def add_source(self, source: BLESource): """Listen with one more radio, e.g. a proxy that came online.""" await self.remove_source(source.name) self._sources[source.name] = source if self._is_running and self._may_start(source.name): await self._start_source(source.name) async def remove_source(self, name: str): """Stop listening with a radio; one that fails to stop (its node went away) is let go of all the same.""" if source := self._sources.pop(name, None): try: await source.stop() except Exception as e: logger.warning(f"BLE source {name} failed to stop: {e}") async def start(self): await self._follow_bound() self._is_running = True await self._start_sources() self._spawn(self._eviction_loop()) logger.debug(f"BLE started with sources {list(self._sources)}, {len(self._listeners)} listener(s)") async def stop(self): self._is_running = False await self._stop_sources() for task in list(self._tasks): task.cancel() logger.debug(f"BLE stopped, {len(self._listeners)} listener(s) registered") @contextlib.asynccontextmanager async def exclusive( self, address: str, *, owner: str, timeout: float = 30, wait: float = 1, is_pairing_needed: bool = False ) -> AsyncGenerator[BLELease]: """Leases the source hearing ``address`` best to ``owner`` (e.g. while pairing it): that source stops scanning and others' connects avoid it; the rest keep going. A leased source is waited for ``wait`` seconds before the next best is tried, round after round, until ``timeout`` raises `BLEBusyError`. With ``is_pairing_needed``, only sources that can pair are leased (`BLEPairingError` when none hears it). The device stays tracked until the lease ends, though no radio may hear it meanwhile.""" name = await self._acquire(address, owner, timeout, wait, is_pairing_needed) self._leased[name] = address try: source = self._sources[name] with contextlib.suppress(Exception): # paused, not stopped: a proxy answers connects only while it stays subscribed await (source.pause_scanning() if isinstance(source, PausableBLESource) else source.stop()) yield BLELease(address, name, owner, self._sources[name]) finally: await asyncio.shield(self._release(name, owner)) async def connect(self, address: str, on_disconnect: Callable[[], None] = lambda: None) -> BLEConnection: """Opens a GATT connection to ``address`` through the source hearing it best, falling back to the others; leased sources are skipped. ``on_disconnect`` is called when the connection drops.""" candidates = self._candidates(address) free = [name for name in candidates if not self._is_leased(name)] if candidates and not free: raise BLEBusyError(f"all Bluetooth sources that hear {address} are busy") errors = [] for name in free: try: return await self._sources[name].connect(address, on_disconnect) except Exception as e: errors.append(f"{name}: {e}") raise ConnectionError(f"Can't connect to {address}: {'; '.join(errors) or 'no Bluetooth sources'}") async def scan_actively(self, duration: float): """Scans actively for ``duration`` seconds (a pairing window): names often come only in the scan responses a passive scan never asks for.""" self._active_until = max(self._active_until, monotonic() + duration) await self._rescan() self._spawn(self._rescan(after=duration)) def devices(self) -> list[BLEDiscoveryInfo]: """Every device heard recently, as the source hearing it best sees it.""" return [tracked.info for tracked in self._tracked.values()] # Internals def _candidates(self, address: str) -> list[str]: """Sources to reach ``address`` through, the strongest first; a proxy with no connection slot left last.""" tracked = self._tracked.get(address) names = (tracked.sources(self._removal_grace_sec) if tracked else []) or list(self._sources) return sorted(names, key=lambda name: getattr(self._sources.get(name), "free_slots", None) == 0) def _is_leased(self, name: str) -> bool: return name in self._leases and self._leases[name].locked() def _may_start(self, name: str) -> bool: """A leased source starts only when it can pause (`_start_source` pauses it): the lease connects through it.""" return not self._is_leased(name) or isinstance(self._sources[name], PausableBLESource) async def _acquire( self, address: str, owner: str, timeout: float, wait: float, is_pairing_needed: bool = False ) -> str: """Locks the first candidate source that frees up within ``wait``, cycling until ``timeout``.""" deadline = monotonic() + timeout while True: if not (candidates := self._candidates(address)): raise ConnectionError(f"Can't reach {address}: no Bluetooth sources") if is_pairing_needed and not ( candidates := [n for n in candidates if getattr(self._sources[n], "is_pairable", False)] ): raise BLEPairingError(f"No Bluetooth source that hears {address} can pair") for name in candidates: lock = self._leases.setdefault(name, asyncio.Lock()) if (remaining := deadline - monotonic()) <= 0: raise BLEBusyError(f"all Bluetooth sources that hear {address} are busy") try: async with asyncio.timeout(min(wait, remaining)): await lock.acquire() except TimeoutError: continue if name in self._sources: # not removed meanwhile logger.info(f"BLE source {name} leased to {owner} for {address}") return name lock.release() async def _release(self, name: str, owner: str): try: if self._is_running and name in self._sources: await self._resume_source(name) finally: self._leased.pop(name, None) self._leases[name].release() logger.info(f"BLE source {name} released by {owner}") async def _resume_source(self, name: str): source = self._sources[name] if not isinstance(source, PausableBLESource): return await self._start_source(name) self._heard_at[name] = monotonic() try: await source.resume_scanning() except Exception as e: logger.warning(f"BLE source {name} failed to resume: {e}") async def _start_sources(self): # a lease can outlive a stop: its source starts too when it can pause, so the lease connects through it names = [name for name in self._sources if self._may_start(name)] await asyncio.gather(*(self._start_source(name) for name in names)) def _scans_passively(self) -> bool: return monotonic() >= self._active_until async def _rescan(self, after: float = 0): """Switches every source that can between passive and active scanning (a burst began or ended).""" await asyncio.sleep(after) if not self._is_running: return active = not self._scans_passively() for name, source in list(self._sources.items()): if isinstance(source, ScanModeBLESource) and not self._is_leased(name): try: await source.set_scan_mode(active) except Exception as e: logger.warning(f"BLE source {name} failed to switch its scan: {e}") async def _start_source(self, name: str): self._heard_at[name] = monotonic() # one that fails to start is retried once it counts as silent source = self._sources[name] try: if isinstance(source, ScanModeBLESource): await source.set_scan_mode(not self._scans_passively()) await source.start(self._advertisement_handler(name)) if isinstance(source, PausableBLESource): # paused exactly while leased, though a lease ended while stopped await (source.pause_scanning() if self._is_leased(name) else source.resume_scanning()) except Exception as e: logger.warning(f"BLE source {name} failed to start: {e}") async def _stop_sources(self): """Stop every radio, and let go of the ones it was bound to: the runtime binds them anew before it starts.""" await asyncio.gather(*(s.stop() for s in self._sources.values()), return_exceptions=True) for name in self._bound.values(): self._sources.pop(name, None) self._bound.clear() def _advertisement_handler(self, source: str) -> OnAdvertisement: def on_advertisement(device: BLEDevice, adv_data: AdvertisementData): self._heard_at[source] = monotonic() self._spawn(self._handle_advertisement(source, device, adv_data)) return on_advertisement def _spawn(self, coroutine): task = asyncio.create_task(coroutine) self._tasks.add(task) task.add_done_callback(self._on_task_done) def _on_task_done(self, task: asyncio.Task): self._tasks.discard(task) if not task.cancelled() and (exc := task.exception()): logger.error(f"BLE task crashed: {exc}") async def _handle_advertisement(self, source: str, device: BLEDevice, adv_data: AdvertisementData): address = device.address prev = self._tracked.get(address) before = prev.info.advertisement if prev else None # update tracking before awaiting listeners — guards against concurrent advertisements # for the same address both appearing as new tracked = prev or _BLETrackedDevice(BLEDiscoveryInfo(device, adv_data, source, adv_data.rssi, monotonic())) tracked.heard[source] = (adv_data.rssi, monotonic()) self._tracked[address] = tracked if adv_data.local_name: tracked.name = adv_data.local_name elif tracked.name: adv_data = adv_data._replace(local_name=tracked.name) elif prev is None: self._burst_for_name() # a weaker source only keeps the device alive: sources hear different subsets of the # advertisement (e.g. no scan response), so mixing them would report false updates if tracked.sources(self._removal_grace_sec)[0] != source: return tracked.info = info = BLEDiscoveryInfo(device, adv_data, source, adv_data.rssi, monotonic()) adv_changed = before is not None and _adv_signature(before) != _adv_signature(adv_data) tasks = [] for listener, matchers in list(self._listeners): if not _matches(matchers, adv_data): continue # is_new is per-subscriber match: first time this device matched this filter if before is None or not _matches(matchers, before): tasks.append((True, listener.ble_did_discover_device(self, info))) elif adv_changed: tasks.append((False, listener.ble_did_update_device(self, info))) if tasks: is_new = tasks[0][0] logger.debug(f"BLE {'discovered' if is_new else 'updated'}: {device.name} ({address}) via {source}") await asyncio.gather(*(coro for _, coro in tasks)) def _burst_for_name(self): """Scans actively for a moment, bounded to one burst per interval, so a new device's scan response is heard.""" if not self._scans_passively() or monotonic() - self._name_burst_at < self._name_burst_interval_sec: return self._name_burst_at = monotonic() self._spawn(self.scan_actively(self._name_burst_sec)) async def _eviction_loop(self): while self._is_running: await asyncio.sleep(self._eviction_interval_sec) await self._evict_stale() await self._revive_silent() async def _revive_silent(self): """Restarts sources that heard nothing for a while: their radio went away under them without a word (bluetoothd restarted, the adapter reset) and they won't come back by themselves. One whose loss is reported otherwise (``is_loss_reported``) may just hear no one, and a restart would drop the links it proxies.""" for name, source in list(self._sources.items()): if getattr(source, "is_loss_reported", False) or self._is_leased(name): continue if monotonic() - self._heard_at.get(name, 0) > self._silence_sec: logger.info(f"BLE source {name} heard nothing for {self._silence_sec:.0f} s, restarting it") with contextlib.suppress(Exception): await source.stop() await self._start_source(name) async def _evict_stale(self): for address, tracked in list(self._tracked.items()): if tracked.sources(self._removal_grace_sec) or address in self._leased.values(): continue del self._tracked[address] adv_data = tracked.info.advertisement tasks = [ listener.ble_did_remove_device(self, tracked.info) for listener, matchers in list(self._listeners) if _matches(matchers, adv_data) ] if tasks: logger.debug(f"BLE removed: {tracked.info.device.name} ({address})") await asyncio.gather(*tasks) async def perform_scan(self): """Triggers an immediate eviction check. Sources listen continuously — no manual scan needed.""" await self._evict_stale() def source_of(endpoint: Endpoint) -> BLESource: """The source a bound raw-BLE endpoint is: the one it carries (an ESPHome proxy), else a BlueZ adapter.""" if endpoint.instance is not None: return endpoint.instance if endpoint.dialect == "silabs-cpc-hci": from majordom_integration_sdk.runtime.peripherals.providers.ble.cpc_hci import source_of as cpc_source return cpc_source(endpoint) from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter # the ble extra return LocalAdapter(endpoint.url or None) # Example usage if __name__ == "__main__": # logging.basicConfig() # logger.setLevel(logging.DEBUG) async def main(): from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter discovery = BLEService([LocalAdapter()]) class SwitchBotListener: async def ble_did_discover_device(self, ble: BLEService, info: BLEDiscoveryInfo): print(f"Found: {info.device.name} ({info.device.address})") async def ble_did_update_device(self, ble: BLEService, info: BLEDiscoveryInfo): print(f"Updated: {info.device.name} ({info.device.address})") async def ble_did_remove_device(self, ble: BLEService, info: BLEDiscoveryInfo): print(f"Removed: {info.device.name} ({info.device.address})") switchbot_services = { UUID("00000d00-0000-1000-8000-00805f9b34fb"), UUID("0000fd3d-0000-1000-8000-00805f9b34fb"), UUID("cba20d00-224d-11e6-9fb8-0002a5d5c51b"), } discovery.register(SwitchBotListener(), switchbot_services) await discovery.start() while True: await asyncio.sleep(1) asyncio.run(main()) ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/providers/ssdp.py ================================================================================ """The runtime's ``upnp/ssdp``: one SSDP listener shared by every integration that needs it. See `majordom_integration_sdk.capabilities.ssdp` for the contract.""" import asyncio import logging import socket import struct from collections import defaultdict from collections.abc import Callable from dataclasses import dataclass, field from time import monotonic from typing import NamedTuple from majordom_integration_sdk.capabilities.ssdp import SSDPDiscoveryInfo, SSDPDiscoveryListener from majordom_integration_sdk.peripherals import Endpoint, Peripheral logger = logging.getLogger(__name__) @dataclass class _KnownService: info: SSDPDiscoveryInfo last_seen_at: float # monotonic — updated on every scan reply @dataclass class _Subscriber: listener: SSDPDiscoveryListener search_target: str mcast_group: str port: int socket: socket.socket known: dict[str, _KnownService] = field(default_factory=dict) # USN -> _KnownService class _Endpoint(NamedTuple): mcast_group: str port: int @dataclass class _SocketSubscribers: scan_socket: socket.socket # ephemeral, unbound — sends M-SEARCH and reads unicast replies (blocking + timeout) search_subscribers: dict[str, list[_Subscriber]] = field( default_factory=lambda: defaultdict(list) ) # search_target -> list of Subscriber class SSDPDiscoveryService(Peripheral): """An `SSDP`, on demand.""" name = "ssdp" is_on_demand = True @property def endpoint(self) -> Endpoint: return Endpoint("upnp", "ssdp", "ssdp", is_shared=True, instance=self) @property def provides(self) -> list[Endpoint]: return [self.endpoint] def __init__(self): # Single dict: Endpoint -> SocketSubscribers(socket, [Subscriber]) self._endpoints_subscribers: dict[_Endpoint, _SocketSubscribers] = dict() self._is_running = False self._tasks: list[asyncio.Task] = [] self._mx = 2 # MX - maximum wait time (timeout) seconds. Used to even scan responses across time and reduce network load. self._scan_interval: float = 10.0 # seconds between M-SEARCH bursts self._missed_scans_evict: int = 3 # evict after this many consecutive scans with no reply self._ignorelist: set[str] = self._local_ips() # FUTURE: filter type def register( self, listener: SSDPDiscoveryListener, search_target: str, mcast_group: str = "239.255.255.250", port: int = 1900, ) -> Callable[[], None]: """ Args: listener: Object that will receive discovery events. search_target: SSDP ST (Search Target) field to specify the type of device or service to discover. Common ST templates: - "uuid:": discover a device by its UUID - "urn:schemas-upnp-org:device::": discover devices of a specific type - "urn:schemas-upnp-org:service::": discover specific service types - "upnp:rootdevice": discover root devices - "ssdp:all": discover all devices/services Examples: - "uuid:550e8400-e29b-41d4-a716-446655440000" - "urn:schemas-upnp-org:device:MediaServer:1" mcast_group: Multicast group address for SSDP (default: "239.255.255.250"). Don't change it unless you know what you're doing. port: Port for SSDP (default: 1900). Don't change it unless you know what you're doing. """ endpoint = _Endpoint(mcast_group, port) if endpoint not in self._endpoints_subscribers: scan_sock = self._create_scan_socket() self._endpoints_subscribers[endpoint] = _SocketSubscribers(scan_sock) subscriber = _Subscriber( listener, search_target, mcast_group, port, self._endpoints_subscribers[endpoint].scan_socket ) self._endpoints_subscribers[endpoint].search_subscribers[search_target].append(subscriber) def cancel(): subscribers = self._endpoints_subscribers.get(endpoint, _SocketSubscribers(None)).search_subscribers # type: ignore[arg-type] if search_target in subscribers: try: subscribers[search_target].remove(subscriber) except ValueError: pass return cancel # Putting workers together async def start(self): for es in self._endpoints_subscribers.values(): if es.scan_socket.fileno() == -1: # closed when it stopped: the subscriptions go on es.scan_socket = self._create_scan_socket() self._is_running = True self._tasks = [ asyncio.create_task(self._start_scanning()), asyncio.create_task(self._start_expiry_checks()), asyncio.create_task(self._start_listening_notify()), ] def perform_scan(self): """Triggers an immediate M-SEARCH burst on all registered endpoints. Use from start_pairing_window.""" asyncio.create_task(self._scan_and_read()) async def stop(self): self._is_running = False for task in self._tasks: task.cancel() await asyncio.gather(*self._tasks, return_exceptions=True) self._tasks.clear() for es in self._endpoints_subscribers.values(): es.scan_socket.close() # Private async def _start_scanning(self): """Send M-SEARCH bursts and collect unicast replies; repeat every scan_interval.""" while self._is_running: await self._scan_and_read() await asyncio.sleep(self._scan_interval) async def _start_expiry_checks(self): while self._is_running: await asyncio.sleep(self._scan_interval) await self._evict_expired() async def _start_listening_notify(self): """Listens for unsolicited SSDP NOTIFY advertisements on the multicast group.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("", 1900)) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._get_mreq("239.255.255.250")) sock.setblocking(False) loop = asyncio.get_event_loop() try: while self._is_running: try: data, addr = await loop.sock_recvfrom(sock, 2048) except (BlockingIOError, OSError): await asyncio.sleep(0.5) continue if addr[0] in self._ignorelist: continue msg = data.decode(errors="ignore") if not msg.startswith("NOTIFY"): continue response = self._parse_ssdp_response(msg) nts = response.get("NTS", "") usn = response.get("USN") st = response.get("NT") # NOTIFY uses NT instead of ST if usn is None or st is None: continue for es in self._endpoints_subscribers.values(): subscribers = es.search_subscribers.get(st, []) if not subscribers: continue if nts == "ssdp:byebye": for subscriber in subscribers: if usn in subscriber.known: ks = subscriber.known.pop(usn) logger.debug(f"SSDP byebye: {ks.info.service_name} ({ks.info.addr})") await subscriber.listener.ssdp_did_remove_service(self, ks.info) elif nts == "ssdp:alive": info = SSDPDiscoveryInfo( addr=addr[0], host=response.get("HOST"), search_target=st, service_name=usn, server=response.get("SERVER"), cache_control=response.get("CACHE-CONTROL"), location=response.get("LOCATION"), response=response, ) await asyncio.gather(*[self._notify_subscriber(s, usn, info) for s in subscribers]) finally: sock.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, self._get_mreq("239.255.255.250")) sock.close() # SSDP Implementation def _collect_scan_replies(self, sock: socket.socket, mx: int) -> list[tuple[bytes, tuple[str, int]]]: """Blocking: reads all unicast M-SEARCH replies within the MX window. Runs in executor.""" replies: list[tuple[bytes, tuple[str, int]]] = [] sock.settimeout(mx + 0.5) # slightly over MX so we catch late responders deadline = monotonic() + mx + 0.5 while True: remaining = deadline - monotonic() if remaining <= 0: break sock.settimeout(remaining) try: data, addr = sock.recvfrom(1024) replies.append((data, addr)) except TimeoutError: break except OSError: break return replies async def _notify_subscriber(self, subscriber: _Subscriber, usn: str, info: SSDPDiscoveryInfo): now = monotonic() if usn not in subscriber.known: subscriber.known[usn] = _KnownService(info, now) logger.debug(f"SSDP discovered: {info.service_name} ({info.addr})") await subscriber.listener.ssdp_did_discover_service(self, info) else: known = subscriber.known[usn] subscriber.known[usn] = _KnownService(info, now) if info.location != known.info.location or info.server != known.info.server: logger.debug(f"SSDP updated: {info.service_name} ({info.addr})") await subscriber.listener.ssdp_did_update_service(self, info) async def _evict_expired(self): now = monotonic() missed_scans_cutoff = now - self._scan_interval * self._missed_scans_evict for es in self._endpoints_subscribers.values(): for subscribers in es.search_subscribers.values(): for subscriber in subscribers: expired = [usn for usn, ks in subscriber.known.items() if ks.last_seen_at < missed_scans_cutoff] for usn in expired: ks = subscriber.known.pop(usn) logger.debug(f"SSDP expired: {ks.info.service_name} ({ks.info.addr})") await subscriber.listener.ssdp_did_remove_service(self, ks.info) async def _scan_and_read(self): """Send all M-SEARCH requests then collect replies for each endpoint.""" loop = asyncio.get_running_loop() for endpoint, es in self._endpoints_subscribers.items(): search_targets = list(es.search_subscribers.keys()) for search_target in search_targets: query = self._ssdp_query_template( ip=endpoint.mcast_group, port=str(endpoint.port), mx=str(self._mx), st=search_target ) logger.debug(f"SSDP scan: {search_target} on {endpoint.mcast_group}:{endpoint.port}") es.scan_socket.sendto(query.encode(), (endpoint.mcast_group, endpoint.port)) replies = await loop.run_in_executor(None, self._collect_scan_replies, es.scan_socket, self._mx) await self._process_scan_replies(endpoint, search_targets, replies) async def _process_scan_replies( self, endpoint: _Endpoint, search_targets: list[str], replies: list[tuple[bytes, tuple[str, int]]] ): for data, addr in replies: if addr[0] in self._ignorelist: continue response = self._parse_ssdp_response(data.decode(errors="ignore")) # 200 OK replies omit ST — fall back to matching against all search targets for this endpoint response_st = response.get("ST") # USN is standard UPnP but Yeelight (and others) omit it — fall back to Location then addr usn = response.get("USN") or response.get("LOCATION") or addr[0] search_subscribers = self._endpoints_subscribers[endpoint].search_subscribers candidates = [response_st] if response_st else search_targets for st in candidates: subscribers = search_subscribers.get(st, []) if not subscribers: continue info = SSDPDiscoveryInfo( addr=addr[0], host=response.get("HOST"), search_target=st, service_name=usn, server=response.get("SERVER"), cache_control=response.get("CACHE-CONTROL"), location=response.get("LOCATION"), response=response, ) await asyncio.gather(*[self._notify_subscriber(subscriber, usn, info) for subscriber in subscribers]) # SSDP config def _create_scan_socket(self) -> socket.socket: # Ephemeral unbound socket — OS assigns a random source port. # Devices send M-SEARCH replies back to that source port (unicast), # so we must read replies on the same socket we sent from. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) return sock def _get_mreq(self, mcast_group) -> bytes: return struct.pack("4sL", socket.inet_aton(mcast_group), socket.INADDR_ANY) def _ssdp_query_template(self, ip: str, port: str, mx: str, st: str) -> str: return f'M-SEARCH * HTTP/1.1\r\nMAN: "ssdp:discover"\r\nHOST: {ip}:{port}\r\nMX: {mx}\r\nST: {st}\r\n\r\n' def _parse_ssdp_response(self, response: str) -> dict[str, str]: lines = response.split("\r\n") data = {} for line in lines: if ":" in line: key, value = line.split(":", 1) data[key.strip().upper()] = value.strip() return data # Helpers def _local_ips(self) -> set[str]: """Returns all local IPv4 addresses to exclude from discovery responses.""" ips: set[str] = {"127.0.0.1"} try: infos = socket.getaddrinfo(None, None, socket.AF_INET, socket.SOCK_DGRAM, 0, socket.AI_PASSIVE) ips.update(str(info[4][0]) for info in infos if info[4][0] != "0.0.0.0") except Exception: pass return ips if __name__ == "__main__": # logging.basicConfig() # logger.setLevel(logging.DEBUG) async def main(): ssdp = SSDPDiscoveryService() class SSDPListener: async def ssdp_did_discover_service(self, ssdp: SSDPDiscoveryService, info: SSDPDiscoveryInfo): print(f"Found: {info.service_name} @ {info.addr} location={info.location}") async def ssdp_did_update_service(self, ssdp: SSDPDiscoveryService, info: SSDPDiscoveryInfo): print(f"Updated: {info.service_name} @ {info.addr}") async def ssdp_did_remove_service(self, ssdp: SSDPDiscoveryService, info: SSDPDiscoveryInfo): print(f"Removed: {info.service_name} @ {info.addr}") ssdp.register(SSDPListener(), "wifi_bulb", port=1982) await ssdp.start() while True: await asyncio.sleep(1) asyncio.run(main()) ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/providers/zeroconf.py ================================================================================ """The runtime's ``mdns/zeroconf``: one zeroconf browser shared by every integration that needs DNS-SD (the ``discovery`` extra). See `majordom_integration_sdk.capabilities.zeroconf` for the contract.""" import asyncio import logging from collections.abc import Callable from typing import cast from zeroconf import BadTypeInNameException, ServiceListener, Zeroconf, current_time_millis from zeroconf._dns import DNSPointer from zeroconf.asyncio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconf from zeroconf.const import _CLASS_IN, _TYPE_A, _TYPE_AAAA, _TYPE_PTR from majordom_integration_sdk.capabilities.zeroconf import ZeroconfDiscoveryInfo, ZeroconfDiscoveryListener from majordom_integration_sdk.peripherals import Endpoint, Peripheral logger = logging.getLogger(__name__) _RESOLVE_DELAY = 0.5 # seconds — coalesces burst PTR/SRV/TXT/A packets into one resolve _RESOLVE_TIMEOUT_MS = 3_000 _CACHE_POLL_INTERVAL = 30 # seconds — how often to reconcile our state against zeroconf's PTR cache _EVICT_GRACE_MS = 10_000 # ms — grace window after A/AAAA expiry before probing; allows zeroconf to renew class ZeroconfDiscoveryService(Peripheral): """A `Zeroconf`, on demand.""" name = "zeroconf" is_on_demand = True @property def endpoint(self) -> Endpoint: return Endpoint("mdns", "zeroconf", "zeroconf", is_shared=True, instance=self) @property def provides(self) -> list[Endpoint]: return [self.endpoint] @property def async_zeroconf(self) -> AsyncZeroconf | None: return self._async_zeroconf def __init__(self): self._async_zeroconf: AsyncZeroconf | None = None self._browsers: set[AsyncServiceBrowser] = set() self._adapters: list[_ServiceListenerAdapter] = [] self._poll_task: asyncio.Task | None = None # registrations made before start() — flushed on start self._pending: list[tuple[set[str], ZeroconfDiscoveryListener, int]] = [] self._pending_id: int = 0 # FUTURE: filter type def register(self, listener: ZeroconfDiscoveryListener, services: set[str]) -> Callable[[], None]: if self._async_zeroconf is None: reg_id = self._pending_id self._pending_id += 1 self._pending.append((services, listener, reg_id)) # internal order unchanged def cancel_pending(): for i, (_, _, rid) in enumerate(self._pending): if rid == reg_id: del self._pending[i] break return cancel_pending browser, adapter = self._make_browser(services, listener) def cancel(): if adapter not in self._adapters: # it stopped since, cancelling it already return adapter.cancel_all_pending() self._browsers.discard(browser) self._adapters.remove(adapter) asyncio.create_task(browser.async_cancel()) return cancel async def start(self): self._async_zeroconf = AsyncZeroconf() for services, listener, _ in self._pending: self._make_browser(services, listener) self._pending.clear() self._poll_task = asyncio.create_task(self._cache_poll_loop()) logger.debug(f"Zeroconf started, {len(self._browsers)} browser(s) active") async def stop(self): if self._poll_task: self._poll_task.cancel() self._poll_task = None for adapter in self._adapters: adapter.cancel_all_pending() for browser in list(self._browsers): await browser.async_cancel() self._browsers.clear() self._adapters.clear() if self._async_zeroconf is not None: await self._async_zeroconf.async_close() self._async_zeroconf = None logger.debug("Zeroconf stopped") async def _cache_poll_loop(self): while True: await asyncio.sleep(_CACHE_POLL_INTERVAL) if self._async_zeroconf is None: continue zc = self._async_zeroconf.zeroconf now = current_time_millis() for adapter in list(self._adapters): adapter.sync_with_cache(zc, now) def _make_browser( self, services: set[str], listener: ZeroconfDiscoveryListener ) -> tuple[AsyncServiceBrowser, "_ServiceListenerAdapter"]: assert self._async_zeroconf is not None adapter = _ServiceListenerAdapter(self, listener, services) browser = AsyncServiceBrowser( self._async_zeroconf.zeroconf, list(services), listener=adapter, ) self._browsers.add(browser) self._adapters.append(adapter) return browser, adapter class _ServiceListenerAdapter(ServiceListener): def __init__( self, zeroconf_discovery: ZeroconfDiscoveryService, listener: ZeroconfDiscoveryListener, services: set[str] ): self._zc_service = zeroconf_discovery self._listener = listener self._services = services self._loop = asyncio.get_running_loop() self._resolve_later_queue: dict[str, asyncio.TimerHandle] = {} self._known_names: dict[str, ZeroconfDiscoveryInfo] = {} # name → last known info def add_service(self, zc: Zeroconf, type_: str, name: str): self._schedule_resolve(type_, name) def update_service(self, zc: Zeroconf, type_: str, name: str): self._schedule_resolve(type_, name) def remove_service(self, zc: Zeroconf, type_: str, name: str): # goodbye packet — cancel pending resolve and notify immediately if handle := self._resolve_later_queue.pop(name, None): handle.cancel() self._known_names.pop(name, None) logger.debug(f"Zeroconf goodbye received: {name}") asyncio.create_task(self._listener.zeroconf_did_remove_service(self._zc_service, type_, name)) def cancel_all_pending(self): while self._resolve_later_queue: _, handle = self._resolve_later_queue.popitem() handle.cancel() def sync_with_cache(self, zc: Zeroconf, now: float): """Reconcile _known_names against the live cache. When A/AAAA records expire, we confirm via async_request before evicting — expiry alone is unreliable (device may have just re-announced). A failed async_request is the definitive "no goodbye" departure signal. Rediscovery scans live PTR records for names we don't know yet. """ # confirm-evict: A/AAAA expired → probe network; evict only if unreachable for name, last_info in list(self._known_names.items()): if last_info.server is None: continue a_records = list(zc.cache.get_all_by_details(last_info.server, _TYPE_A, _CLASS_IN)) aaaa_records = list(zc.cache.get_all_by_details(last_info.server, _TYPE_AAAA, _CLASS_IN)) all_address_records = a_records + aaaa_records if not all_address_records or all( r.get_expiration_time(100) + _EVICT_GRACE_MS <= now for r in all_address_records ): if name not in self._resolve_later_queue: logger.debug(f"Zeroconf A/AAAA expired, confirming: {name}") asyncio.create_task(self._confirm_evict(name, last_info.type_)) # rediscover: scan live PTR records for unknown names for type_ in self._services: for record in zc.cache.get_all_by_details(type_, _TYPE_PTR, _CLASS_IN): ptr = cast(DNSPointer, record) if ( not ptr.is_expired(now) and ptr.alias not in self._known_names and ptr.alias not in self._resolve_later_queue ): logger.debug(f"Zeroconf cache rediscovery: {ptr.alias}") self._schedule_resolve(type_, ptr.alias) async def _confirm_evict(self, name: str, type_: str): """Probe the network for a device whose A/AAAA records expired. Evict only if unreachable.""" assert self._zc_service._async_zeroconf is not None zc = self._zc_service._async_zeroconf.zeroconf info = AsyncServiceInfo(type_, name) if await info.async_request(zc, _RESOLVE_TIMEOUT_MS): # device responded — it's alive, update via normal resolve path logger.debug(f"Zeroconf confirm-evict: {name} is alive, refreshing") discovery_info = _build_info(info) if discovery_info and name in self._known_names: if discovery_info != self._known_names[name]: self._known_names[name] = discovery_info await self._listener.zeroconf_did_update_service(self._zc_service, discovery_info) else: self._known_names[name] = discovery_info # refresh server silently else: # no response — confirmed departed if name in self._known_names: self._known_names.pop(name) logger.debug(f"Zeroconf eviction confirmed (no response): {name}") await self._listener.zeroconf_did_remove_service(self._zc_service, type_, name) def _schedule_resolve(self, type_: str, name: str): # already queued — let the existing timer fire, burst coalescing if name in self._resolve_later_queue: return try: info = AsyncServiceInfo(type_, name) except BadTypeInNameException as ex: logger.debug(f"Ignoring record with bad type in name: {name}: {ex}") return handle = self._loop.call_later( _RESOLVE_DELAY, lambda: asyncio.create_task(self._do_resolve(name, info)), ) self._resolve_later_queue[name] = handle async def _do_resolve(self, name: str, info: AsyncServiceInfo): self._resolve_later_queue.pop(name, None) assert self._zc_service._async_zeroconf is not None zc = self._zc_service._async_zeroconf.zeroconf # cache-first: free if warm, network round-trip only if cold if not info.load_from_cache(zc): if not await info.async_request(zc, _RESOLVE_TIMEOUT_MS): logger.debug(f"Zeroconf resolve failed (no data): {name}") return discovery_info = _build_info(info) if discovery_info is None: return if name in self._known_names: if discovery_info != self._known_names[name]: self._known_names[name] = discovery_info await self._listener.zeroconf_did_update_service(self._zc_service, discovery_info) else: self._known_names[name] = discovery_info # refresh silently else: self._known_names[name] = discovery_info await self._listener.zeroconf_did_discover_service(self._zc_service, discovery_info) def _build_info(info: AsyncServiceInfo) -> ZeroconfDiscoveryInfo | None: if info.port is None: return None return ZeroconfDiscoveryInfo( type_=info.type, name=info.name, server=info.server, port=info.port, addresses=list(info.addresses), parsed_addresses=info.parsed_addresses(), weight=info.weight, priority=info.priority, properties=info.properties, decoded_properties=info.decoded_properties, text=info.text, host_ttl=info.host_ttl, other_ttl=info.other_ttl, interface_index=info.interface_index, ) if __name__ == "__main__": logging.basicConfig() logger.setLevel(logging.DEBUG) async def main(): discovery = ZeroconfDiscoveryService() class HAPListener: async def zeroconf_did_discover_service( self, zeroconf: ZeroconfDiscoveryService, info: ZeroconfDiscoveryInfo ): print(f"Found: {info.name} @ {info.parsed_addresses}:{info.port}") async def zeroconf_did_update_service( self, zeroconf: ZeroconfDiscoveryService, info: ZeroconfDiscoveryInfo ): print(f"Updated: {info.name} @ {info.parsed_addresses}:{info.port}") async def zeroconf_did_remove_service(self, zeroconf: ZeroconfDiscoveryService, type_: str, name: str): print(f"Removed: {name}") discovery.register(HAPListener(), {"_hap._tcp.local."}) await discovery.start() while True: await asyncio.sleep(1) asyncio.run(main()) ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/services/__init__.py ================================================================================ """Containers: how the runtime runs them (`compose`), the ones the SDK brings (`builtin`) and the images they run (``images/``).""" ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/services/builtin.py ================================================================================ """The containers the SDK brings between radios and integrations: Thread border routers.""" from __future__ import annotations import asyncio import contextlib import json import time import urllib.request from pathlib import Path from typing import Any from pydantic import BaseModel, Field from majordom_integration_sdk.peripherals import Endpoint, Need, Service _IMAGES = Path(__file__).parent / "images" class ThreadRadio(BaseModel): tx_power: int | None = Field(None, title="Thread transmit power, dBm", description="Empty uses the radio default.") _OTBR_REST = Endpoint("thread", "otbr-rest", "http://127.0.0.1:{ports.rest}", is_shared=True) FORM_PATIENCE = 15 # seconds a border router answers without a network before one is formed on it POLL = 1 # seconds between asks of a border router that isn't there yet MOVE_DELAY = 10_000 # ms before a network moves to another channel, so its devices move along, as the entrypoints do _CHANNEL, _EXTENDED_PAN_ID, _ACTIVE_TIMESTAMP, _PENDING_TIMESTAMP, _DELAY_TIMER = 0, 2, 14, 51, 52 # dataset TLVs class _BorderRouter[S: BaseModel = Any](Service[S]): """On the hub's Thread network, ``platform.thread_dataset``: set up over its REST API to join it, or to form one when there is none yet; it tells the network it has once it serves. The network is never rendered into its container, so learning it recreates nothing.""" async def provision(self, endpoint: Endpoint): if endpoint.dialect == _OTBR_REST.dialect: await join_network(endpoint.url, self.platform.thread_dataset, FORM_PATIENCE) async def start(self): await super().start() rest = next(endpoint for endpoint in self.provides if endpoint.dialect == _OTBR_REST.dialect) await self._align(rest.url) await self.output.peripheral_did_learn(self, {"thread_dataset": await active_dataset(rest.url)}) async def _align(self, url: str): """Put the network it joined where its radio needs it, before it is told: nowhere in particular here.""" return class _MultiPanBorderRouter(_BorderRouter[ThreadRadio]): """One multi-PAN radio listens on one channel: the Thread network follows Zigbee's, the one its container put Thread on before it answered (it forms there, and moves a network it restored on another).""" _zigbee_channel: int | None = None # Zigbee's channel, read before the network is joined async def provision(self, endpoint: Endpoint): if endpoint.dialect == _OTBR_REST.dialect: self._zigbee_channel = await network_channel(endpoint.url) await super().provision(endpoint) async def _align(self, url: str): if self._zigbee_channel is not None: await move_channel(url, self._zigbee_channel, FORM_PATIENCE) # one that can't land fails the start def silabs_multiprotocol() -> Service[ThreadRadio]: """One multi-PAN RCP serving Zigbee (zigbeed, EZSP over TCP) and Thread (OTBR) through cpcd.""" return _MultiPanBorderRouter( "silabs-multiprotocol", needs=[Need("multipan", ["silabs-cpc"])], provides=[Endpoint("zigbee", "ezsp", "socket://127.0.0.1:{ports.ezsp}"), _OTBR_REST], settings=ThreadRadio, ports={"ezsp": 9999, "rest": 8081}, compose={ "image": "majordom/multiprotocol:sisdk-2025.6.3-avahi-arm64", "build": str(_IMAGES / "multiprotocol-sisdk"), "privileged": True, "userns_mode": "host", "network_mode": "host", "hostname": "majordom-thread", # its mDNS daemon announces this, not the hub's own name # a privileged container sees the host's /dev: a common name (ttyACM0) would be the host's own device "devices": ["{peripherals.multipan.url}:/dev/ttyRCP", "/dev/net/tun:/dev/net/tun"], "volumes": [ f"{_IMAGES}/multiprotocol-sisdk/entrypoint.sh:/entrypoint.sh:ro", f"{_IMAGES}/thread-source/run:/thread-source:ro", # the avahi build publishes through the host's avahi-daemon, on the host's bus "{host.avahi:?/run/dbus:/run/dbus}", "{data}/thread:/var/lib/thread", "{data}/zigbee:/var/lib/zigbee", ], "tmpfs": ["/run:exec,mode=1777"], "entrypoint": ["/bin/bash", "/entrypoint.sh"], "environment": { "RADIO_DEVICE": "/dev/ttyRCP", "RADIO_BAUD": "{peripherals.multipan.params[baud]}", "RADIO_HARDFLOW": "{peripherals.multipan.params[flow_control]:?true}" "{peripherals.multipan.params[flow_control]:!false}", # a bare UART: the entrypoint pulses RESETn so cpcd syncs; privileged, it sees the gpiochip "RADIO_RESET_GPIO": "{peripherals.multipan.params[reset_gpio]}", "BACKBONE_IF": "{host.interface}", "EZSP_TCP_PORT": "{ports.ezsp}", "OTBR_REST_PORT": "{ports.rest}", "LISTEN_ADDRESS": "{host.listen_address}", "THREAD_TX_DBM": "{settings.tx_power}", }, "healthcheck": { "test": ["CMD-SHELL", "pgrep -f tcp-listen && ot-ctl state | grep -qE 'leader|router|child'"], "interval": "10s", "start_period": "120s", "retries": 3, }, }, ) def otbr() -> Service: """OpenThread Border Router on a plain Thread RCP.""" return _BorderRouter( "otbr", needs=[Need("thread", ["spinel"])], provides=[_OTBR_REST], ports={"rest": 8081}, compose={ # Pinned: a moved :latest once shipped a broken RCP serial init (no wpan0). Bump on purpose. "image": "openthread/border-router@sha256:acc612303d3bd5aea28621ec8f3d2cc154cdc94c370398285dc828d08c5a5cf9", "privileged": True, "userns_mode": "host", "network_mode": "host", "hostname": "majordom-thread", # its mDNS daemon announces this, not the hub's own name "devices": ["{peripherals.thread.url}:/dev/ttyRCP", "/dev/net/tun:/dev/net/tun"], "volumes": ["{data}:/data", f"{_IMAGES}/thread-source:/etc/services.d/thread-source:ro"], "tmpfs": ["/run:exec,mode=1777", "/tmp:mode=1777"], # s6-overlay runs its init from /run "environment": { "OT_RCP_DEVICE": "spinel+hdlc+uart:///dev/ttyRCP?uart-baudrate={peripherals.thread.params[baud]}" "{peripherals.thread.params[flow_control]:&uart-flow-control}", "OT_INFRA_IF": "{host.interface}", "OT_THREAD_IF": "wpan0", "OT_REST_LISTEN_ADDR": "{host.listen_address}", "OT_REST_LISTEN_PORT": "{ports.rest}", }, "healthcheck": { "test": ["CMD-SHELL", "ot-ctl state | grep -qE 'leader|router|child'"], "interval": "10s", "start_period": "60s", "retries": 3, }, }, ) def _call(url: str, method: str, path: str, body: str | None = None, kind: str = "text/plain") -> str: request = urllib.request.Request( url + path, method=method, data=body.encode() if body is not None else None, headers={"Accept": "text/plain", "Content-Type": kind}, ) # fmt: skip with urllib.request.urlopen(request, timeout=5) as response: return response.read().decode().strip() def _datasets(url: str) -> tuple[str, str]: """The active and the pending dataset of the border router at ``url`` as hex TLVs, empty when it has none; one pending for another network (the one it had before it joined) is none: it moves nothing of this one.""" pending = _call(url, "GET", "/node/dataset/pending") # first: a move landing meanwhile is in the active one active = _call(url, "GET", "/node/dataset/active") if pending and _tlvs(pending).get(_EXTENDED_PAN_ID) != _tlvs(active).get(_EXTENDED_PAN_ID): pending = "" return active, pending async def active_dataset(url: str) -> str: """Wait for the border router at ``url`` to have a network, and no change of it pending (a channel move landing); its active dataset as hex TLVs.""" while True: with contextlib.suppress(OSError): # not up yet active, pending = await asyncio.to_thread(_datasets, url) if active and not pending: return active await asyncio.sleep(POLL) async def network_channel(url: str) -> int: """Wait for the border router at ``url`` to have a network; the channel it is on, or moving to.""" while True: with contextlib.suppress(OSError): # not up yet active, pending = await asyncio.to_thread(_datasets, url) if active: return _channel(pending or active) await asyncio.sleep(POLL) async def move_channel(url: str, channel: int, patience: float = FORM_PATIENCE): """Move the network of the border router at ``url`` to ``channel`` through a pending dataset, which its devices follow in `MOVE_DELAY`, unless it is there or on its way; TimeoutError once it couldn't for ``patience`` seconds.""" waited = 0.0 while True: try: active, pending = await asyncio.to_thread(_datasets, url) if _channel(pending or active) != channel: await asyncio.to_thread(_call, url, "PUT", "/node/dataset/pending", _moved(active, channel)) return except OSError as error: # not up, or not attached yet: a pending dataset needs a network to go to if waited >= patience: raise TimeoutError(f"The Thread network didn't move to Zigbee's channel {channel}: {error}") from None waited += POLL await asyncio.sleep(POLL) async def join_network(url: str, dataset: str | None, patience: float = FORM_PATIENCE): """Have the border router at ``url`` join the network of ``dataset`` (its active dataset, hex TLVs) in place of another one it has, or once it has answered for ``patience`` seconds without one; with no ``dataset``, form a new network then — once. Thread is on once it returns.""" def put(is_running: bool): if is_running: # the active dataset is written only while Thread is off _call(url, "PUT", "/node/state", json.dumps("disable"), "application/json") if dataset: _call(url, "PUT", "/node/dataset/active", dataset) else: _call(url, "PUT", "/node/dataset/active", json.dumps({"NetworkName": "MajorDom"}), "application/json") enable() def enable(): _call(url, "PUT", "/node/state", json.dumps("enable"), "application/json") answered = 0.0 while True: try: if active := await asyncio.to_thread(_call, url, "GET", "/node/dataset/active"): if dataset and _tlvs(active)[_EXTENDED_PAN_ID] != _tlvs(dataset)[_EXTENDED_PAN_ID]: await asyncio.to_thread(put, True) elif "disabled" in await asyncio.to_thread(_call, url, "GET", "/node/state"): await asyncio.to_thread(enable) # a join or a forming whose enable failed, tried again return answered += POLL if answered > patience: await asyncio.to_thread(put, False) return except OSError: pass # not up yet await asyncio.sleep(POLL) def _tlvs(dataset: str) -> dict[int, bytes]: """A dataset's TLVs by type: the Extended PAN ID tells networks apart, whatever moved since (the channel).""" data, tlvs = bytes.fromhex(dataset), {} while len(data) >= 2: tlvs[data[0]], data = data[2 : 2 + data[1]], data[2 + data[1] :] return tlvs def _channel(dataset: str) -> int: return int.from_bytes(_tlvs(dataset)[_CHANNEL][1:]) # after the channel page def _moved(active: str, channel: int) -> str: """A pending dataset moving the network of ``active`` to ``channel`` in `MOVE_DELAY` ms.""" tlvs = _tlvs(active) # newer than the network's own, which a clock still behind (no RTC, before NTP) wouldn't be: seconds, then no # ticks and not authoritative seconds = max(int(time.time()), (int.from_bytes(tlvs.get(_ACTIVE_TIMESTAMP, b"")) >> 16) + 1) now = (seconds << 16).to_bytes(8) moved = {_CHANNEL: b"\0" + channel.to_bytes(2), _ACTIVE_TIMESTAMP: now, _PENDING_TIMESTAMP: now} tlvs = tlvs | moved | {_DELAY_TIMER: MOVE_DELAY.to_bytes(4)} return b"".join(bytes([kind, len(value)]) + value for kind, value in tlvs.items()).hex() ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/services/compose.py ================================================================================ """Docker Compose as the container host of every `Service`: the containers of the ones that run, as one project.""" from __future__ import annotations import asyncio import contextlib import functools import logging import os import socket import string from collections.abc import Awaitable, Callable, Mapping from dataclasses import replace from functools import partial from glob import glob from pathlib import Path from types import SimpleNamespace from typing import Any from majordom_integration_sdk.files import read_json, write_json from majordom_integration_sdk.peripherals import Bound, Endpoint, Peripheral, Service log = logging.getLogger(__name__) PORTS = range(45800, 46000) # where a service goes when the port it prefers is taken READY_POLL = 1 # seconds between checks of whether a container is up, its setup done and it is healthy class Compose(Peripheral): """Docker Compose as the container host every `Service` needs (``container/compose``): the containers of the services that run, as one ``majordom`` project in ``compose.json`` of its documents folder, each service with its own documents folder as ``{data}`` (created when it renders, the folders under it the service binds when it is created: Docker would create them as root). Each gets the host ports it prefers when free, kept across restarts. A service's start returns once compose reports its container running, its ports answer, its `Service.provision` finished and it is healthy. It runs while a service does; while Docker isn't reachable its start fails, and the services wait, saying so. ``listen_address`` is where the services on the host network answer, ``{host.listen_address}``: loopback, the hub only, by default; ``0.0.0.0`` for a lab harness reached from another host, where nothing guards them.""" name = "compose" is_on_demand = True def __init__(self, listen_address: str = "127.0.0.1"): self.listen_address = listen_address self._running: dict[str, Service] = {} self._tentative: dict[str, dict[str, int]] = {} # the ports a service that doesn't run would get self._rendered: dict[str, Mapping[str, Any]] = {} # what each one runs with, rendered when it was created self._applied: Mapping[str, Any] | None = None # the compose file docker last took self._lock = asyncio.Lock() @property def provides(self) -> list[Endpoint]: return [Endpoint("container", "compose", "compose", is_shared=True, instance=self)] @functools.cached_property def ports(self) -> dict[str, dict[str, int]]: """The host ports each service keeps, by its name.""" return read_json(self.platform.documents_folder(self) / "ports.json") async def start(self): try: await self._docker("info", "--format", "{{.ServerVersion}}") except RuntimeError as error: raise RuntimeError(f"Docker isn't reachable: {error}") from None # ServiceHost def provided(self, service: Service) -> list[Endpoint]: values = self._values(service) ports = values["ports"] return [ replace(e, url=_render(e.url, {"ports": ports}), params=_render(e.params, values)) for e in service.templates ] async def up(self, service: Service): await self._keep_ports(service) self._running[service.name] = service self._rendered[service.name] = self._render(service) _make_bound_folders(self._rendered[service.name], service.platform.documents_folder(service)) try: await self._apply() except Exception: self._running.pop(service.name) raise await _until(lambda: self._is_up(service), f"{service.name} isn't up") for endpoint in service.provides: await _until(partial(_provision, service, endpoint), f"{service.name} failed to set up {endpoint.url}") await _until(service.is_healthy, f"{service.name} isn't healthy") async def down(self, service: Service): if self._running.pop(service.name, None): self._rendered.pop(service.name, None) try: await self._apply() except Exception as error: log.error(f"Removing {service.name}'s container failed: {error}") def is_current(self, service: Service) -> bool: return service.name not in self._running or self._rendered.get(service.name) == self._render(service) async def wipe(self, service: Service): """Empty the documents folder of ``service``, which doesn't run: through Docker, in its own image (pulled already, with the tools in it), as its container wrote there as root, which the hub's user can't remove (the Thread network, zigbeed's state). RuntimeError while it runs, or when Docker can't.""" if service.name in self._running: raise RuntimeError(f"{service.name} runs: its container would write on") folder = service.platform.documents_folder(service) if not (image := service.compose.get("image")) or not any(folder.iterdir()): return # no container of its own, or nothing to remove await self._docker( *("run", "--rm", "--pull", "never", "--network", "none", "--userns", "host", "--user", "0"), *("--entrypoint", "find", "-v", f"{folder}:/d", image, "/d", "-mindepth", "1", "-delete"), ) # Internals def _values(self, service: Service) -> dict[str, Any]: """What its compose and the params it provides render with.""" return { "data": service.platform.documents_folder(service), "peripherals": _Peripherals(service.peripherals.bound), "settings": service.settings, "platform": service.platform, "host": _Host(self.listen_address), "ports": SimpleNamespace(**self._ports(service)), } def _render(self, service: Service) -> Mapping[str, Any]: # no depends_on: everything retries until its links answer, and a dependency would recreate # a service whenever an optional provider (matter-server's border router) comes or goes rendered = {"restart": "unless-stopped", **_render(service.compose, self._values(service))} if isinstance(environment := rendered.get("environment"), Mapping): # a variable rendering empty is left out, unset rather than set to nothing: a server parsing it would fail rendered["environment"] = {k: v for k, v in environment.items() if v != ""} return rendered def _ports(self, service: Service) -> dict[str, int]: """Its host ports: the ones it kept unless another service took one since, else the preferred one when free. One that doesn't run is told what it would get.""" mine = {**self._tentative.get(service.name, {}), **self.ports.get(service.name, {})} others = {port for name, ports in self.ports.items() if name != service.name for port in ports.values()} for name, preferred in service.ports.items(): if not mine.get(name) or mine[name] in others: mine[name] = next(p for p in (preferred, *PORTS) if p not in others and not _is_listening(p)) self._tentative[service.name] = mine return mine async def _keep_ports(self, service: Service): """Keep its ports from now on; move off one something else took meanwhile, e.g. after a reboot before our container came up. Not knowing which containers run, it moves nothing: it raises.""" ports = self._ports(service) if any(_is_listening(port) for port in ports.values()) and service.name not in await self._containers(): self.ports.pop(service.name, None) self._tentative[service.name] = {name: port for name, port in ports.items() if not _is_listening(port)} ports = self._ports(service) self.ports[service.name] = ports write_json(self.platform.documents_folder(self) / "ports.json", self.ports) async def _apply(self): """Have docker take what runs now. Applies run in turn, each to its end even when its caller is cancelled: one cut short would leave a container that the next one, finding nothing changed, keeps.""" await asyncio.shield(asyncio.ensure_future(self._apply_in_turn())) async def _apply_in_turn(self): async with self._lock: compose, path = {"name": "majordom", "services": dict(self._rendered)}, self._path() if compose == self._applied: return write_json(path, compose) self._applied = None # unknown until docker took it all args = ["up", "-d", "--remove-orphans"] if self._rendered else ["down"] await self._docker("compose", "-f", str(path), *args) self._applied = compose # only what actually runs: a failure is tried again def _path(self) -> Path: return self.platform.documents_folder(self) / "compose.json" async def _is_up(self, service: Service) -> bool: ports = self.ports.get(service.name, {}).values() return all(_is_listening(port) for port in ports) and service.name in await self._containers() async def _containers(self) -> set[str]: """Our services whose containers are up.""" return set((await self._docker("compose", "-p", "majordom", "ps", "--status", "running", "--services")).split()) async def _docker(self, *args: str) -> str: """What ``docker`` with ``args`` printed; RuntimeError when it failed.""" try: process = await asyncio.create_subprocess_exec( "docker", *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT ) output = (await process.communicate())[0].decode(errors="replace") except OSError as error: # no docker at all raise RuntimeError(str(error)) from error if process.returncode: raise RuntimeError(f"docker {' '.join(args[:3])} failed:\n{output[-3000:]}") return output async def _until(check: Callable[[], Awaitable[bool]], failure: str): """Ask ``check`` until it says yes; one that raises says no.""" while True: try: if await check(): return except Exception as error: log.warning(f"{failure}, trying again: {error}") await asyncio.sleep(READY_POLL) async def _provision(service: Service, endpoint: Endpoint) -> bool: await service.provision(endpoint) return True def _make_bound_folders(compose: Mapping[str, Any], data: Path): """Create the folders under ``data`` that ``compose`` binds, as the hub's user: Docker would create them as root.""" for volume in compose.get("volumes", []): source = Path(volume.get("source", "") if isinstance(volume, Mapping) else volume.split(":")[0]) if source.is_relative_to(data): source.mkdir(parents=True, exist_ok=True) def _is_listening(port: int) -> bool: """Whether something on the host listens on a TCP port (all services run on the host network).""" with socket.socket() as probe: probe.settimeout(0.5) if probe.connect_ex(("127.0.0.1", port)) == 0: # also one on loopback only, which BSDs let a bind pass return True with socket.socket() as probe: probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # a closed connection in TIME_WAIT is no one's try: probe.bind(("", port)) except OSError: return True return False class _Peripherals(dict): """Template access ``{peripherals.thread.url}``; an unbound optional need, or a param it lacks, renders empty. An ``is_many`` need renders its first endpoint.""" def __getattr__(self, family: str) -> Endpoint: bound: Bound = self.get(family, Endpoint("")) endpoint = bound if isinstance(bound, Endpoint) else (bound or [Endpoint("")])[0] return replace(endpoint, params=_Params(endpoint.params)) class _Params(dict): def __missing__(self, name: str): return None class _Host: uid, gid = os.getuid(), os.getgid() # for services that should write their data as the hub's user def __init__(self, listen_address: str): self.listen_address = listen_address @property def avahi(self) -> bool: """Whether the host runs avahi-daemon on its system bus, for a service that publishes through it.""" return Path("/run/dbus/system_bus_socket").exists() and Path("/run/avahi-daemon/socket").exists() @property def interface(self) -> str: """The backbone interface: a wired one with a link (Wi-Fi drops the multicast a Thread border router relies on), else the one of the default route.""" for wired in sorted(glob("/sys/class/net/e*/carrier")): with contextlib.suppress(OSError): if Path(wired).read_text().strip() == "1": return Path(wired).parent.name with contextlib.suppress(OSError): for line in Path("/proc/net/route").read_text().splitlines()[1:]: name, destination, *_ = line.split() if destination == "00000000": return name return "eth0" class _Formatter(string.Formatter): """None renders empty; a flag with a format spec renders the spec when set: ``{x:&uart-flow-control}``; a ``!`` spec renders what follows when the value is empty, e.g. a proxy without an adapter: ``{peripherals.ble.url:!true}``, a ``?`` spec when it isn't, e.g. a backend only with one: ``{peripherals.ble.url:?dbus}``.""" def format_field(self, value: Any, format_spec: str) -> str: if format_spec.startswith("!"): return "" if value else format_spec[1:] if format_spec.startswith("?"): return format_spec[1:] if value else "" if isinstance(value, bool) and format_spec: return format_spec if value else "" return "" if value is None else super().format_field(value, format_spec) def _render(value: Any, values: Mapping[str, Any]) -> Any: if isinstance(value, str): return _Formatter().vformat(value, (), values) if isinstance(value, Mapping): return {k: _render(v, values) for k, v in value.items()} if isinstance(value, list | tuple): # an item rendering empty is left out: a volume only with an adapter return [item for v in value if (item := _render(v, values)) != ""] return value ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol/Dockerfile ================================================================================ # Thin derived image over Silicon Labs' first-party multiprotocol image. # # The ONLY thing added is the Zigbee coordinator-forming tool. EZSP `form` (a latency-sensitive # radio-level sequence) cannot traverse the zigbeed->pty->socat->TCP bridge — it loses ASH frames # and times out — so the coordinator must be formed IN-CONTAINER, directly on the pty, at startup # (entrypoint.sh does this when the NCP reports NOT_JOINED). Baking bellows in keeps first boot # offline (no runtime pip), matching the "complete image" build principle. # # Versions are pinned to the proven combo (py3.10 base caps bellows at 0.46.x): # bellows 0.46.2 + zigpy 0.84.0 + aiosqlite 0.22.1 # (a cosmetic aiosqlite ".join" AttributeError prints at DB-shutdown AFTER the network is committed; # the entrypoint verifies success via `bellows info`, not the exit code.) FROM siliconlabsinc/multiprotocol:gsdk-4.4.6-arm64 RUN pip3 install --no-cache-dir bellows==0.46.2 zigpy==0.84.0 aiosqlite==0.22.1 ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol/docker-compose.yml ================================================================================ # Harness: the SiSDK multi-PAN stack (../multiprotocol-sisdk, avahi build) and integration-matter's matterjs-server # (its config.py), as static services for a host without the hub, as the cage's lab-pi5 runs them. # Keep both in step with those definitions. # Host side once: the OTBR publishes through the host's avahi over D-Bus (../multiprotocol-sisdk/Dockerfile, MDNS): # docker cp silabs-multiprotocol:/etc/dbus-1/system.d/otbr-agent.conf /etc/dbus-1/system.d/ && systemctl reload dbus # RADIO_BY_ID=/dev/serial/by-id/ docker compose up -d --build services: silabs-multiprotocol: image: majordom/multiprotocol:sisdk-2025.6.3-avahi-arm64 build: context: ../multiprotocol-sisdk platforms: [linux/arm64] container_name: silabs-multiprotocol restart: unless-stopped privileged: true userns_mode: host network_mode: host devices: - /dev/net/tun:/dev/net/tun volumes: - /dev/serial:/dev/serial:ro # the by-id link is followed at every start, not pinned to a tty at creation - /run/dbus:/run/dbus # the host's bus: otbr-agent publishes through the host's avahi-daemon - ../thread-source/run:/thread-source:ro - otbr-data-sisdk:/var/lib/thread - zigbee-data-sisdk:/var/lib/zigbee tmpfs: - /run:exec,mode=1777 environment: RADIO_DEVICE: ${RADIO_BY_ID:?set RADIO_BY_ID to the stick's /dev/serial/by-id path} RADIO_BAUD: "460800" RADIO_HARDFLOW: "true" CHANNEL: "15" BACKBONE_IF: eth0 THREAD_TX_DBM: ${THREAD_TX_DBM:-} LISTEN_ADDRESS: ${LISTEN_ADDRESS:-127.0.0.1} # 0.0.0.0 for tests on another host (the CI node's IP): nothing guards it healthcheck: test: ["CMD-SHELL", "pgrep -f tcp-listen && ot-ctl state | grep -qE 'leader|router|child'"] interval: 10s start_period: 120s retries: 3 matterjs-server: image: ghcr.io/matter-js/matterjs-server@sha256:bcaacf6b2b2df9ce2b929ad7469d5380a4d627f05f790e201d127e8b65af5b0e container_name: matterjs-server restart: unless-stopped network_mode: host userns_mode: host environment: STORAGE_PATH: /data LISTEN_ADDRESS: ${LISTEN_ADDRESS:-127.0.0.1} # as the border router's: no authentication guards the fabric BLE_PROXY: "true" # Bluetooth comes from the hub (integration-matter's MatterServerBLEDelegate), as in production LOG_LEVEL: warning # at info matter.js logs every command's fields, the Thread network key included volumes: - ${MATTER_DATA_DIR:-/var/lib/majordom/matter-data}:/data volumes: otbr-data-sisdk: zigbee-data-sisdk: ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol/entrypoint.sh ================================================================================ #!/usr/bin/env bash # Concurrent-multiprotocol harness entrypoint (Silicon Labs multi-PAN RCP). # # Brings up, in order, inside the siliconlabsinc/multiprotocol image: # dbus -> cpcd -> socat(EZSP pty pair) -> zigbeed(iid=1) -> socat(EZSP->TCP :9999) # -> otbr-agent(iid=2, REST :8081) # so that ONE EFR32 multi-PAN RCP serves Zigbee (EZSP over TCP for bellows) and Thread (OTBR) # at the same time. Idempotent: Zigbee network state lives in the NCP flash and Thread state in # the mounted OTBR datadir, so a restart re-adopts the existing networks instead of re-forming. # # Env (with defaults): # RADIO_DEVICE /dev/ttyRCP the RCP as mapped into the container, or its /dev/serial/by-id path # (resolved at every start: the stick's tty changes when USB re-enumerates) # RADIO_BAUD 460800 multi-PAN RCP UART baud, as its firmware sets it # RADIO_FLOW_CONTROL True hardware flow control (RTS/CTS) on that UART: True or False # EZSP_TCP_PORT 9999 bellows connects to socket://:9999 # OTBR_REST_PORT 8081 Matter server reads the Thread dataset here # LISTEN_ADDRESS 127.0.0.1 where both ports answer: only this host; 0.0.0.0 exposes them on the LAN # (a lab harness: nothing guards them) # BACKBONE_IF eth0 OTBR backbone interface # ZIGBEE_FORM 1 form a Zigbee network if the NCP has none # THREAD_FORM 1 form a Thread network if OTBR has none # CHANNEL 15 Zigbee and Thread form on it: one multi-PAN radio listens on one channel, # networks on two channels lose frames (a Thread device then can't attach). # Our Thread network is moved to Zigbee's channel when they differ set -euo pipefail RADIO_DEVICE=${RADIO_DEVICE:-/dev/ttyRCP} RADIO_BAUD=${RADIO_BAUD:-460800} RADIO_FLOW_CONTROL=${RADIO_FLOW_CONTROL:-True} EZSP_TCP_PORT=${EZSP_TCP_PORT:-9999} CHANNEL=${CHANNEL:-15} OTBR_REST_PORT=${OTBR_REST_PORT:-8081} LISTEN_ADDRESS=${LISTEN_ADDRESS:-127.0.0.1} BACKBONE_IF=${BACKBONE_IF:-eth0} ZIGBEE_FORM=${ZIGBEE_FORM:-1} THREAD_FORM=${THREAD_FORM:-1} log() { echo "[multiprotocol] $*"; } # 0. Kernel prerequisites that OTBR's Backbone-Router/ND-proxy needs (harmless if already set). sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true # Forwarding makes Linux ignore router advertisements unless accept_ra=2: keep learning the routes # other border routers announce on the backbone (route info up to /64). sysctl -w "net.ipv6.conf.${BACKBONE_IF}.accept_ra=2" >/dev/null 2>&1 || true sysctl -w "net.ipv6.conf.${BACKBONE_IF}.accept_ra_rt_info_max_plen=64" >/dev/null 2>&1 || true # 1. System D-Bus — otbr-agent EMERG-crashes without it. mkdir -p /run/dbus [ -S /run/dbus/system_bus_socket ] || dbus-daemon --system --fork mdnsd 2>/dev/null || true # 2. cpcd owns the serial RCP and multiplexes it (CPC). Config is mounted at the image's path. [ "${RADIO_DEVICE}" = /dev/ttyRCP ] || ln -sf "$(readlink -f "${RADIO_DEVICE}")" /dev/ttyRCP log "starting cpcd on ${RADIO_DEVICE} @ ${RADIO_BAUD}, flow control ${RADIO_FLOW_CONTROL}" case "${RADIO_FLOW_CONTROL}" in [Tt]rue | 1) hardflow=true ;; *) hardflow=false ;; esac sed -e "s/^uart_device_baud:.*/uart_device_baud: ${RADIO_BAUD}/" -e "s/^uart_hardflow:.*/uart_hardflow: ${hardflow}/" \ /usr/local/etc/cpcd.conf > /run/cpcd.conf cpcd --conf /run/cpcd.conf >/var/log/cpcd.log 2>&1 & # wait for the secondary (RCP) to attach for _ in $(seq 1 30); do grep -q "Secondary APP" /var/log/cpcd.log 2>/dev/null && break; sleep 1; done grep -q "Secondary APP" /var/log/cpcd.log || { log "cpcd never reached the RCP"; cat /var/log/cpcd.log; exit 1; } log "cpcd attached: $(grep -m1 'Secondary APP' /var/log/cpcd.log | sed 's/.*Info : //')" # 3. Zigbee side: zigbeed (CPC iid=1) presents EZSP on a pty. Run it from a PERSISTED state dir: # zigbeed writes its emulated-NCP tokens to `host_token.nvm` relative to its cwd, so a cwd on a # mounted volume makes the formed coordinator survive container recreation — otherwise every # recreate re-forms a NEW network (new PAN id) and orphans already-paired devices. ZB_HOST_PTY=/dev/ttyZigbeeNCP ZB_STATE_DIR=${ZB_STATE_DIR:-/var/lib/zigbee} mkdir -p "${ZB_STATE_DIR}" socat pty,link=${ZB_HOST_PTY},raw,echo=0 pty,link=/tmp/ttyZigbeeNCP,raw,echo=0 & sleep 1 ( cd "${ZB_STATE_DIR}" && exec zigbeed --radio-url "spinel+cpc://cpcd_0?iid=1&iid-list=0" \ --ezsp-interface /tmp/ttyZigbeeNCP ) >/var/log/zigbeed.log 2>&1 & sleep 2 # 4. Thread side FIRST: otbr-agent (CPC iid=2) + REST, then form the Thread network. Bringing Thread # up before forming Zigbee WARMS THE SHARED RADIO — forming Zigbee in the first seconds after zigbeed # starts (cold radio) reliably times out, but with Thread already running it succeeds. otbr-agent -I wpan0 -B "${BACKBONE_IF}" \ --rest-listen-address "${LISTEN_ADDRESS}" --rest-listen-port "${OTBR_REST_PORT}" \ "spinel+cpc://cpcd_0?iid=2&iid-list=0" >/var/log/otbr.log 2>&1 & sleep 4 log "otbr-agent up; Thread REST on :${OTBR_REST_PORT}" bash /thread-source & # the host reaches Thread nodes over TCP (see the script) if [ "${THREAD_FORM}" = "1" ]; then # Decide on the saved dataset, not the state: a restored network is still "detached" right after # start, and forming then would replace it (new network, orphaned devices). if ot-ctl dataset active -x 2>/dev/null | grep -qE "^[0-9a-fA-F]{20,}"; then log "Thread network restored" else log "forming Thread network" ot-ctl dataset init new >/dev/null 2>&1 || true ot-ctl dataset channel "${CHANNEL}" >/dev/null 2>&1 || true ot-ctl dataset commit active >/dev/null 2>&1 || true fi ot-ctl ifconfig up >/dev/null 2>&1 || true ot-ctl thread start >/dev/null 2>&1 || true fi # 5. Zigbee coordinator: form ON THE PTY if the NCP has no network. EZSP `form` is a latency-sensitive # radio-level sequence and CANNOT traverse the EZSP->TCP bridge (ASH frame loss -> networkInit timeout # / ERR_FLASH_VERIFY_FAILED), so it must run here, in-container, on the pty, as the SINGLE reader, # BEFORE we expose TCP. bellows is baked into the image (see Dockerfile). # # Idempotency + success detection deliberately AVOID a separate `bellows info` probe: `info` is itself # flaky on this stack (ASH sync), and a probe that hangs and gets `timeout`-killed leaves zigbeed's # ASH desynced, which poisons every following call. Instead: # * idempotency = a persistent MARKER in the state volume (no bellows call on the already-formed path) # * success = the form's OWN exit + log. `timeout` returns 124 iff it had to KILL a hung bellows # (nothing committed). Any other exit means bellows ran to completion — the network # commits just before the cosmetic aiosqlite ".join" crash, so that traceback in the # log is a reliable "committed" signature. ZB_MARKER="${ZB_STATE_DIR}/.coordinator-formed" if [ "${ZIGBEE_FORM}" = "1" ]; then if [ -f "${ZB_MARKER}" ]; then log "Zigbee coordinator already formed (marker present) — skipping form" else log "Forming Zigbee coordinator on ${ZB_HOST_PTY}" formed=0 for attempt in 1 2 3 4; do : > /tmp/zbform.db timeout 120 bellows -d "${ZB_HOST_PTY}" form --channel "${CHANNEL}" --database /tmp/zbform.db >/var/log/zigbee-form.log 2>&1 rc=$? if [ "${rc}" != 124 ] && grep -q "has no attribute 'join'" /var/log/zigbee-form.log; then echo "${CHANNEL}" > "${ZB_MARKER}"; formed=1; break fi log "Zigbee form attempt ${attempt} unconfirmed (rc=${rc}) — retrying"; sleep 8 done if [ "${formed}" = 1 ]; then log "Zigbee coordinator formed"; else log "WARN: Zigbee form unconfirmed after retries — see /var/log/zigbee-form.log"; fi fi fi # 5b. Our Thread network follows Zigbee's channel (one restored from before CHANNEL changed would sit on # another). Through a pending dataset with a delay, so attached Thread devices move along. The hub moves a # network it has this border router join later the same way, over the REST API. ZB_CHANNEL=$(cat "${ZB_MARKER}" 2>/dev/null || true) # empty from older images: formed on CHANNEL ZB_CHANNEL=${ZB_CHANNEL:-${CHANNEL}} TH_CHANNEL=$(ot-ctl channel 2>/dev/null | head -1 | tr -dc 0-9 || true) if [ "${THREAD_FORM}" = "1" ] && [ -n "${TH_CHANNEL}" ] && [ "${TH_CHANNEL}" != "${ZB_CHANNEL}" ]; then for _ in $(seq 1 30); do ot-ctl state 2>/dev/null | grep -qE "leader|router|child" && break; sleep 1; done log "moving Thread from channel ${TH_CHANNEL} to ${ZB_CHANNEL}, Zigbee's" now=$(date +%s) if ot-ctl dataset init active >/dev/null && ot-ctl dataset channel "${ZB_CHANNEL}" >/dev/null \ && ot-ctl dataset activetimestamp "${now}" >/dev/null && ot-ctl dataset pendingtimestamp "${now}" >/dev/null \ && ot-ctl dataset delay 10000 >/dev/null && ot-ctl dataset commit pending >/dev/null; then log "Thread changes channel in 10 s" else log "WARN: the Thread channel change was refused" fi fi # 6. Now expose EZSP over TCP for the Hub/bellows (socket://:${EZSP_TCP_PORT}); steady-state # load + commands tolerate the bridge even though forming could not. socat "tcp-listen:${EZSP_TCP_PORT},bind=${LISTEN_ADDRESS},reuseaddr,fork" file:/dev/ttyZigbeeNCP,raw,echo=0 & log "zigbeed up; EZSP exposed on tcp:${EZSP_TCP_PORT} (bellows: socket://:${EZSP_TCP_PORT})" # Thread TX power (THREAD_TX_DBM). On a multi-PAN RCP the radio transmits at Zigbee's power: `ot-ctl # txpower` reads back but isn't applied (observed 2026-10-13). Lower Zigbee's tx_power instead (zigpy's -10 dBm # minimum gives about -11 dBm). BLE TX and receiver sensitivity are not tunable. if [ -n "${THREAD_TX_DBM:-}" ]; then log "setting Thread TX power to ${THREAD_TX_DBM} dBm (clamps to radio min)" ot-ctl txpower "${THREAD_TX_DBM}" >/dev/null 2>&1 || true log "Thread TX now: $(ot-ctl txpower 2>/dev/null | head -1)" fi log "harness ready — Zigbee EZSP tcp:${EZSP_TCP_PORT}, Thread OTBR REST :${OTBR_REST_PORT}" # 6. Supervise: if any core daemon dies, exit non-zero so the container restart policy recycles us. while true; do for p in cpcd zigbeed otbr-agent; do pgrep -x "$p" >/dev/null || { log "$p died — exiting for restart"; exit 1; } done sleep 5 done ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol-sisdk/Dockerfile ================================================================================ # Slim multi-PAN host stack (cpcd + zigbeed + otbr-agent) from Silicon Labs' first-party SiSDK debs. # # Matches RCPs built on the same SiSDK release (CPC protocol v6; our MG26 runs SiSDK 2025.6.3, CPC 4.7.1). # Host programs and RCP firmware must come from ONE SDK release: do not mix with gsdk-4.4.x radios. # docker buildx build --platform linux/arm64 -t majordom/multiprotocol:sisdk-2025.6.3 --load . ARG DEBIAN=debian:bookworm-slim # mDNS publisher behind otbr-agent: # avahi otbr-agent built from SiSDK's ot-br-posix publishes through the HOST's avahi-daemon, so the hub # runs one mDNS responder. A second responder on the host network (mdnsd) publishes reverse PTRs # for all host addresses under its own name, and avahi renames the hub on every OTBR start. # Host side, both reversible: # - bind-mount the host's /run/dbus into the container (the entrypoint then starts no bus); # - install the policy that lets root own io.openthread.BorderRouter.*: # docker cp :/etc/dbus-1/system.d/otbr-agent.conf /etc/dbus-1/system.d/ # systemctl reload dbus (undo: rm the file, reload again) # Container root must be host root for that policy (userns_mode: host). # mdnsresponder SiSDK's prebuilt otbr-agent with its own mdnsd (no host changes; renames the hub, see above). ARG MDNS=avahi # Unpacks the debs only: their maintainer scripts install bind9, nodejs, radvd... and compile mDNSResponder. # Runs on the build platform; it only picks the target architecture's debs. FROM --platform=$BUILDPLATFORM ${DEBIAN} AS pkgs ARG TARGETARCH ARG SISDK=v2025.6.3 ARG SISDK_DEBS_SHA256=7ecbd91cdae94da1ec9eb4817a6bc1fe73741106a0c70a40879956bc09833c0e RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl unzip && rm -rf /var/lib/apt/lists/* RUN curl -fsSL -o /tmp/debs.zip "https://github.com/SiliconLabs/simplicity_sdk/releases/download/${SISDK}/debian-bookworm.zip" \ && echo "${SISDK_DEBS_SHA256} /tmp/debs.zip" | sha256sum -c - \ && unzip -q /tmp/debs.zip -d /tmp \ && for p in libcpc3 libcpc-dev cpcd zigbeed ot-br-posix; do dpkg-deb -x /tmp/debian-bookworm/deb/${p}_*_${TARGETARCH}.deb /out; done # otbr-agent links libdns_sd.so: build the mDNSResponder its deb ships as source (what its postinst does). FROM ${DEBIAN} AS mdns RUN apt-get update && apt-get install -y --no-install-recommends gcc libc6-dev make && rm -rf /var/lib/apt/lists/* COPY --from=pkgs /out/usr/src/mDNSResponder /src RUN make -C /src/mDNSPosix os=linux tls=no Daemon libdns_sd -j"$(nproc)" FROM scratch AS otbr-mdnsresponder COPY --from=pkgs /out/usr/sbin/otbr-agent /out/usr/sbin/ot-ctl /usr/sbin/ COPY --from=mdns /src/mDNSPosix/build/prod/mdnsd /usr/sbin/ COPY --from=mdns /src/mDNSPosix/build/prod/libdns_sd.so /usr/lib/ COPY --from=mdns /src/LICENSE /usr/share/doc/mDNSResponder/LICENSE # otbr-agent from the same SiSDK release (Silicon Labs' ot-br-posix fork, which still has the avahi publisher upstream # dropped) with the prebuilt one's features, on the CPC vendor bus. Sources: a sparse checkout of the SiSDK tag. FROM ${DEBIAN} AS otbr-avahi-build ARG SISDK=v2025.6.3 ARG SISDK_COMMIT=b41bec3ff2485199c1a5a9995b3e649e118c1b8d RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates cmake g++ git libavahi-client-dev libdbus-1-dev libnetfilter-queue-dev libprotobuf-dev \ libreadline-dev libsystemd-dev ninja-build pkg-config protobuf-compiler \ && rm -rf /var/lib/apt/lists/* RUN git clone -q --depth 1 --branch "${SISDK}" --filter=blob:none --sparse https://github.com/SiliconLabs/simplicity_sdk.git /sisdk \ && cd /sisdk && test "$(git rev-parse HEAD)" = "${SISDK_COMMIT}" \ && git sparse-checkout set util/third_party/ot-br-posix util/third_party/openthread protocol/openthread/platform-abstraction/posix \ && ln -s /sisdk/util/third_party/openthread util/third_party/ot-br-posix/third_party/openthread/repo COPY --from=pkgs /out/usr/include/ /usr/include/ COPY --from=pkgs /out/usr/lib/ /usr/lib/ ARG VENDOR=/sisdk/protocol/openthread/platform-abstraction/posix RUN cmake -GNinja -S /sisdk/util/third_party/ot-br-posix -B /build -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF \ -DCMAKE_INSTALL_PREFIX=/usr -DOTBR_MDNS=avahi -DOTBR_DBUS=ON -DOTBR_REST=ON -DOTBR_WEB=OFF \ -DOTBR_BORDER_ROUTING=ON -DOTBR_BACKBONE_ROUTER=ON -DOTBR_DUA_ROUTING=ON -DOTBR_SRP_ADVERTISING_PROXY=ON \ -DOTBR_DNSSD_DISCOVERY_PROXY=ON -DOTBR_TREL=ON -DOTBR_NAT64=ON -DOT_POSIX_NAT64_CIDR=192.168.255.0/24 \ -DOTBR_DNS_UPSTREAM_QUERY=ON -DOTBR_TELEMETRY_DATA_API=ON -DOT_FIREWALL=ON \ -DOT_MULTIPAN_RCP=ON -DOT_POSIX_RCP_VENDOR_BUS=ON -DOT_PLATFORM_CONFIG=openthread-core-silabs-posix-config.h \ -DCMAKE_C_FLAGS=-I${VENDOR} -DCMAKE_CXX_FLAGS=-I${VENDOR} \ -DOT_POSIX_CONFIG_RCP_VENDOR_DEPS_PACKAGE=${VENDOR}/posix_vendor_rcp.cmake \ -DOT_POSIX_CONFIG_RCP_VENDOR_INTERFACE=${VENDOR}/cpc_interface.cpp \ && ninja -C /build otbr-agent ot-ctl && strip /build/src/agent/otbr-agent /build/third_party/openthread/repo/src/posix/ot-ctl FROM scratch AS otbr-avahi COPY --from=otbr-avahi-build /build/src/agent/otbr-agent /build/third_party/openthread/repo/src/posix/ot-ctl /usr/sbin/ FROM otbr-${MDNS} AS otbr # bellows forms the Zigbee coordinator in-container (see entrypoint.sh). zigbeed 8.2.2 speaks EZSP v18, # first supported by bellows 0.49; pinned to the Hub's lock so both ends agree. FROM ${DEBIAN} AS py RUN apt-get update && apt-get install -y --no-install-recommends python3-venv && rm -rf /var/lib/apt/lists/* RUN python3 -m venv /opt/venv && /opt/venv/bin/pip install --no-cache-dir bellows==0.49.2 zigpy==2.0.1 aiosqlite==0.21.0 \ && /opt/venv/bin/pip uninstall -y pip setuptools FROM ${DEBIAN} ARG SISDK=v2025.6.3 ARG MDNS LABEL org.opencontainers.image.title="MajorDom multi-PAN host stack" \ org.opencontainers.image.description="cpcd 4.7.1, zigbeed 8.2.2, ot-br-posix 2.7.3.0 from Silicon Labs SiSDK ${SISDK}" \ org.opencontainers.image.source="https://github.com/majordom-systems/majordom-transports" \ io.majordom.sisdk="${SISDK}" \ io.majordom.mdns="${MDNS}" RUN apt-get update && apt-get install -y --no-install-recommends \ dbus dbus-bin gpiod ipset iproute2 iptables libdbus-1-3 libjsoncpp25 libmbedcrypto7 libnetfilter-queue1 \ libprotobuf-lite32 libreadline8 procps python3 socat $([ "${MDNS}" = avahi ] && echo libavahi-client3) \ && rm -rf /var/lib/apt/lists/* COPY --from=pkgs /out/usr/lib/ /usr/lib/ COPY --from=pkgs /out/usr/bin/cpcd /usr/bin/ COPY --from=pkgs /out/usr/local/bin/zigbeed /usr/local/bin/ COPY --from=pkgs /out/usr/local/etc/zigbeed.conf /usr/local/etc/ COPY --from=otbr / / COPY --from=pkgs /out/etc/dbus-1/system.d/otbr-agent.conf /etc/dbus-1/system.d/ COPY --from=pkgs /out/usr/share/doc/zigbeed/copyright /usr/share/doc/silabs/MSLA COPY --from=py /opt/venv /opt/venv COPY LICENSES /usr/share/doc/majordom-multiprotocol/ COPY cpcd.conf.tmpl /usr/share/majordom/cpcd.conf.tmpl COPY entrypoint.sh /entrypoint.sh ENV PATH=/opt/venv/bin:$PATH # Fails the build when a copied binary misses a shared library. RUN ldconfig && ! ldd /usr/bin/cpcd /usr/local/bin/zigbeed /usr/sbin/otbr-agent /usr/sbin/ot-ctl $(command -v mdnsd) | grep "not found" \ && cpcd --version | head -1 && bellows --help >/dev/null ENTRYPOINT ["/bin/bash", "/entrypoint.sh"] ================================================================================ # FILE: majordom_integration_sdk/runtime/peripherals/services/images/multiprotocol-sisdk/entrypoint.sh ================================================================================ #!/usr/bin/env bash # Concurrent-multiprotocol harness entrypoint (Silicon Labs multi-PAN RCP). # # Brings up, in order, inside the SiSDK multi-PAN image (Dockerfile next to this file): # dbus -> cpcd -> socat(EZSP pty pair) -> zigbeed(iid=1) -> socat(EZSP->TCP :9999) # -> otbr-agent(iid=2, REST :8081) # so that ONE EFR32 multi-PAN RCP serves Zigbee (EZSP over TCP for bellows) and Thread (OTBR) # at the same time. Idempotent: Zigbee network state lives in the NCP flash and Thread state in # the mounted OTBR datadir, so a restart re-adopts the existing networks instead of re-forming. # # Env (with defaults): # RADIO_DEVICE /dev/ttyRCP the RCP as mapped into the container, or its /dev/serial/by-id path # (resolved at every start: the stick's tty changes when USB re-enumerates) # RADIO_BAUD 460800 multi-PAN RCP UART baud # RADIO_HARDFLOW true RTS/CTS flow control (false on a bare UART without control lines) # RADIO_RESET_GPIO : wired to the RCP's RESETn (e.g. gpiochip0:23 on the CM4): # pulsed while cpcd waits, so it syncs on the reset reason # EZSP_TCP_PORT 9999 bellows connects to socket://:9999 # OTBR_REST_PORT 8081 Matter server reads the Thread dataset here # LISTEN_ADDRESS 127.0.0.1 where both ports answer: only this host; 0.0.0.0 exposes them on the LAN # (a lab harness: nothing guards them) # BACKBONE_IF eth0 OTBR backbone interface # ZIGBEE_FORM 1 form a Zigbee network if the NCP has none # THREAD_FORM 1 form a Thread network if OTBR has none # CHANNEL 15 Zigbee and Thread form on it: one multi-PAN radio listens on one channel, # networks on two channels lose frames (a Thread device then can't attach). # Our Thread network is moved to Zigbee's channel when they differ set -euo pipefail RADIO_DEVICE=${RADIO_DEVICE:-/dev/ttyRCP} RADIO_BAUD=${RADIO_BAUD:-460800} RADIO_HARDFLOW=${RADIO_HARDFLOW:-true} RADIO_RESET_GPIO=${RADIO_RESET_GPIO:-} EZSP_TCP_PORT=${EZSP_TCP_PORT:-9999} CHANNEL=${CHANNEL:-15} OTBR_REST_PORT=${OTBR_REST_PORT:-8081} LISTEN_ADDRESS=${LISTEN_ADDRESS:-127.0.0.1} BACKBONE_IF=${BACKBONE_IF:-eth0} ZIGBEE_FORM=${ZIGBEE_FORM:-1} THREAD_FORM=${THREAD_FORM:-1} log() { echo "[multiprotocol] $*"; } # 0. Kernel prerequisites that OTBR's Backbone-Router/ND-proxy needs (harmless if already set). sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null 2>&1 || true sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true # Forwarding makes Linux ignore router advertisements unless accept_ra=2: keep learning the routes # other border routers announce on the backbone (route info up to /64). sysctl -w "net.ipv6.conf.${BACKBONE_IF}.accept_ra=2" >/dev/null 2>&1 || true sysctl -w "net.ipv6.conf.${BACKBONE_IF}.accept_ra_rt_info_max_plen=64" >/dev/null 2>&1 || true # 1. System D-Bus — otbr-agent EMERG-crashes without it. The avahi build (no mdnsd) publishes through the # host's avahi-daemon on the host's bus, bind-mounted at /run/dbus (Dockerfile, MDNS). mkdir -p /run/dbus HOST_DBUS=0 if [ -S /run/dbus/system_bus_socket ]; then log "using the host's D-Bus" HOST_DBUS=1 else dbus-daemon --system --fork command -v mdnsd >/dev/null || log "WARN: no host D-Bus at /run/dbus: Thread services won't reach mDNS" fi if command -v mdnsd >/dev/null; then mdnsd 2>/dev/null || true; fi # 2. cpcd owns the serial RCP and multiplexes it (CPC). A mounted /etc/cpcd.conf wins over the template. [ "${RADIO_DEVICE}" = /dev/ttyRCP ] || ln -sf "$(readlink -f "${RADIO_DEVICE}")" /dev/ttyRCP [ -f /etc/cpcd.conf ] || sed -e "s/@RADIO_BAUD@/${RADIO_BAUD}/" -e "s/@RADIO_HARDFLOW@/${RADIO_HARDFLOW}/" \ /usr/share/majordom/cpcd.conf.tmpl >/etc/cpcd.conf log "starting cpcd on ${RADIO_DEVICE} @ ${RADIO_BAUD}, hardflow ${RADIO_HARDFLOW}" cpcd -c /etc/cpcd.conf >/var/log/cpcd.log 2>&1 & if [ -n "${RADIO_RESET_GPIO}" ]; then # Once cpcd has opened the port and waits to connect: assert RESETn for 0.2 s, then hold it released. # The holder keeps the line driven high while the container runs; on exit the line falls back to # the RCP's own pull-up. sleep 1.5 gpioset --mode=time --usec=200000 "${RADIO_RESET_GPIO%%:*}" "${RADIO_RESET_GPIO##*:}=0" gpioset --mode=signal "${RADIO_RESET_GPIO%%:*}" "${RADIO_RESET_GPIO##*:}=1" & fi # wait for the secondary (RCP) to attach for _ in $(seq 1 30); do grep -q "Connected to Secondary" /var/log/cpcd.log 2>/dev/null && break; sleep 1; done grep -q "Connected to Secondary" /var/log/cpcd.log || { log "cpcd never reached the RCP"; cat /var/log/cpcd.log; exit 1; } sleep 1 log "cpcd attached: $(grep -oE 'Secondary (Protocol|CPC) v[^ ]+' /var/log/cpcd.log | paste -sd ' ')" # 3. Zigbee side: zigbeed (CPC iid=1) presents EZSP on a pty. Run it from a PERSISTED state dir: # zigbeed writes its emulated-NCP tokens to `host_token.nvm` relative to its cwd, so a cwd on a # mounted volume makes the formed coordinator survive container recreation — otherwise every # recreate re-forms a NEW network (new PAN id) and orphans already-paired devices. ZB_HOST_PTY=/dev/ttyZigbeeNCP ZB_STATE_DIR=${ZB_STATE_DIR:-/var/lib/zigbee} mkdir -p "${ZB_STATE_DIR}" socat pty,link=${ZB_HOST_PTY},raw,echo=0 pty,link=/tmp/ttyZigbeeNCP,raw,echo=0 & sleep 1 ( cd "${ZB_STATE_DIR}" && exec zigbeed --radio-url "spinel+cpc://cpcd_0?iid=1&iid-list=0" \ --ezsp-interface /tmp/ttyZigbeeNCP ) >/var/log/zigbeed.log 2>&1 & sleep 2 # 4. Thread side FIRST: otbr-agent (CPC iid=2) + REST, then form the Thread network. Bringing Thread # up before forming Zigbee WARMS THE SHARED RADIO — forming Zigbee in the first seconds after zigbeed # starts (cold radio) reliably times out, but with Thread already running it succeeds. otbr-agent -I wpan0 -B "${BACKBONE_IF}" \ --rest-listen-address "${LISTEN_ADDRESS}" --rest-listen-port "${OTBR_REST_PORT}" \ "spinel+cpc://cpcd_0?iid=2&iid-list=0" >/var/log/otbr.log 2>&1 & sleep 4 log "otbr-agent up; Thread REST on :${OTBR_REST_PORT}" [ -f /thread-source ] && { bash /thread-source & } # the host reaches Thread nodes over TCP (see the script) # The host's avahi drops otbr-agent's publications when it restarts, and the SRP services of Thread nodes stay # off mDNS until each node's next SRP refresh (hours). When avahi takes its bus name again, restart the SRP server: # nodes re-register at once and otbr-agent republishes them. avahi_has_owner() { dbus-send --system --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus \ org.freedesktop.DBus.NameHasOwner string:org.freedesktop.Avahi 2>/dev/null | grep -q "boolean true" } watch_avahi() { while true; do dbus-monitor --system "type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.Avahi'" 2>/dev/null | while read -r kind _; do [ "${kind}" = signal ] || continue sleep 2 # avahi registers its objects after taking the name avahi_has_owner && pgrep -x otbr-agent >/dev/null || continue [ "$(ot-ctl srp server state 2>/dev/null | head -1)" = disabled ] && continue ot-ctl srp server disable >/dev/null 2>&1 || true; sleep 2; ot-ctl srp server enable >/dev/null 2>&1 || true log "avahi restarted: SRP server restarted so Thread nodes re-register" done sleep 5 # the monitor went away done } [ "${HOST_DBUS}" = 1 ] && command -v dbus-monitor >/dev/null && { watch_avahi & } if [ "${THREAD_FORM}" = "1" ]; then # Decide on the saved dataset, not the state: a restored network is still "detached" right after # start, and forming then would replace it (new network, orphaned devices). if ot-ctl dataset active -x 2>/dev/null | grep -qE "^[0-9a-fA-F]{20,}"; then log "Thread network restored" else log "forming Thread network" ot-ctl dataset init new >/dev/null 2>&1 || true ot-ctl dataset channel "${CHANNEL}" >/dev/null 2>&1 || true ot-ctl dataset commit active >/dev/null 2>&1 || true fi ot-ctl ifconfig up >/dev/null 2>&1 || true ot-ctl thread start >/dev/null 2>&1 || true fi # 5. Zigbee coordinator: form ON THE PTY if the NCP has no network. EZSP `form` is a latency-sensitive # radio-level sequence and CANNOT traverse the EZSP->TCP bridge (ASH frame loss -> networkInit timeout # / ERR_FLASH_VERIFY_FAILED), so it must run here, in-container, on the pty, as the SINGLE reader, # BEFORE we expose TCP. bellows is baked into the image (see Dockerfile). # # Idempotency + success detection deliberately AVOID a separate `bellows info` probe: `info` is itself # flaky on this stack (ASH sync), and a probe that hangs and gets `timeout`-killed leaves zigbeed's # ASH desynced, which poisons every following call. Instead: # * idempotency = a persistent MARKER in the state volume (no bellows call on the already-formed path) # * success = the form's OWN exit status: 0 only once the network is committed (bellows 0.49 + # aiosqlite 0.21 no longer crash after it). A crash before forming, e.g. an EZSP version # bellows lacks, exits non-zero and is retried, never marked as formed. ZB_MARKER="${ZB_STATE_DIR}/.coordinator-formed" if [ "${ZIGBEE_FORM}" = "1" ]; then if [ -f "${ZB_MARKER}" ]; then log "Zigbee coordinator already formed (marker present) — skipping form" else log "Forming Zigbee coordinator on ${ZB_HOST_PTY}" formed=0 for attempt in 1 2 3 4; do : > /tmp/zbform.db rc=0 timeout 120 bellows -d "${ZB_HOST_PTY}" form --channel "${CHANNEL}" --database /tmp/zbform.db >/var/log/zigbee-form.log 2>&1 || rc=$? if [ "${rc}" = 0 ]; then echo "${CHANNEL}" > "${ZB_MARKER}"; formed=1; break fi log "Zigbee form attempt ${attempt} unconfirmed (rc=${rc}) — retrying"; sleep 8 done if [ "${formed}" = 1 ]; then log "Zigbee coordinator formed"; else log "WARN: Zigbee form unconfirmed after retries — see /var/log/zigbee-form.log"; fi fi fi # 5b. Our Thread network follows Zigbee's channel (one restored from before CHANNEL changed would sit on # another). Through a pending dataset with a delay, so attached Thread devices move along. The hub moves a # network it has this border router join later the same way, over the REST API. ZB_CHANNEL=$(cat "${ZB_MARKER}" 2>/dev/null || true) # empty from older images: formed on CHANNEL ZB_CHANNEL=${ZB_CHANNEL:-${CHANNEL}} TH_CHANNEL=$(ot-ctl channel 2>/dev/null | head -1 | tr -dc 0-9 || true) if [ "${THREAD_FORM}" = "1" ] && [ -n "${TH_CHANNEL}" ] && [ "${TH_CHANNEL}" != "${ZB_CHANNEL}" ]; then for _ in $(seq 1 30); do ot-ctl state 2>/dev/null | grep -qE "leader|router|child" && break; sleep 1; done log "moving Thread from channel ${TH_CHANNEL} to ${ZB_CHANNEL}, Zigbee's" now=$(date +%s) if ot-ctl dataset init active >/dev/null && ot-ctl dataset channel "${ZB_CHANNEL}" >/dev/null \ && ot-ctl dataset activetimestamp "${now}" >/dev/null && ot-ctl dataset pendingtimestamp "${now}" >/dev/null \ && ot-ctl dataset delay 10000 >/dev/null && ot-ctl dataset commit pending >/dev/null; then log "Thread changes channel in 10 s" else log "WARN: the Thread channel change was refused" fi fi # 6. Now expose EZSP over TCP for the Hub/bellows (socket://:${EZSP_TCP_PORT}); steady-state # load + commands tolerate the bridge even though forming could not. socat "tcp-listen:${EZSP_TCP_PORT},bind=${LISTEN_ADDRESS},reuseaddr,fork" file:/dev/ttyZigbeeNCP,raw,echo=0 & log "zigbeed up; EZSP exposed on tcp:${EZSP_TCP_PORT} (bellows: socket://:${EZSP_TCP_PORT})" # Thread TX power (THREAD_TX_DBM). On a multi-PAN RCP the radio transmits at Zigbee's power: `ot-ctl # txpower` reads back but isn't applied (observed 2026-10-13). Lower Zigbee's tx_power instead (zigpy's -10 dBm # minimum gives about -11 dBm). BLE TX and receiver sensitivity are not tunable. THREAD_TX_DBM=${THREAD_TX_DBM:-${HARNESS_TX_DBM:-}} # HARNESS_TX_DBM: the lab's old name, until 0.4 if [ -n "${THREAD_TX_DBM}" ]; then log "setting Thread TX power to ${THREAD_TX_DBM} dBm (clamps to radio min)" ot-ctl txpower "${THREAD_TX_DBM}" >/dev/null 2>&1 || true log "Thread TX now: $(ot-ctl txpower 2>/dev/null | head -1)" fi log "harness ready — Zigbee EZSP tcp:${EZSP_TCP_PORT}, Thread OTBR REST :${OTBR_REST_PORT}" # 6. Supervise: if any core daemon dies, exit non-zero so the container restart policy recycles us. while true; do for p in cpcd zigbeed otbr-agent; do pgrep -x "$p" >/dev/null || { log "$p died — exiting for restart"; exit 1; } done sleep 5 done ================================================================================ # FILE: majordom_integration_sdk/runtime/runtime.py ================================================================================ """Run peripherals by one rule and bind their needs — what the runtime is given and what those bring along — then keep it in sync as sticks come and go, providers change, and the user enables, disables or restarts them.""" from __future__ import annotations import asyncio import contextlib import contextvars import copy import logging from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, Sequence from dataclasses import dataclass, field, fields, replace from enum import StrEnum from pathlib import Path from time import monotonic from typing import Any, Protocol from pydantic import BaseModel, ValidationError from pydantic_core import InitErrorDetails from majordom_integration_sdk.controller.output import ControllerOutput, LoggingControllerOutput from majordom_integration_sdk.files import read_json, write_json from majordom_integration_sdk.peripherals import ( STABLE_RUN, Bound, Endpoint, Need, Peripheral, PeripheralChange, Peripherals, SettingsExtraField, ) from majordom_integration_sdk.platform import Platform from majordom_integration_sdk.runtime.output import HostOutput log = logging.getLogger(__name__) RETRY_DELAYS = (5, 30, 120) # seconds before each new start of a peripheral that failed, then it is given up on HOOK_TIMEOUT = 30 # seconds a hook may take: it runs while the runtime waits STOP_TIMEOUT = 15 # a stop stuck on a vanished radio (zigpy awaiting its dead I/O thread) is abandoned _PASSES = 10 # bound on the passes one change takes to settle: each may change what the next one binds _FACTS = {f.name for f in fields(Platform)} - {"documents_root", "make_device_repository"} # never its resources # The peripheral call (start, stop, a hook) a task runs in: the tasks it creates inherit it _CALL: contextvars.ContextVar[object | None] = contextvars.ContextVar("_CALL", default=None) class PeripheralState(StrEnum): DISABLED = "disabled" # by the user, persisted: until enabled WAITING = "waiting" # for a need, a provider, what brought it along, something to use it, or a retry STARTING = "starting" RUNNING = "running" FAILED = "failed" # given up on: until restarted or its settings change class StatusKind(StrEnum): """Why a peripheral waits or failed, for its owner to act on; the status's ``detail`` says it in words.""" NEEDS_UNBOUND = "needs-unbound" # waiting: a required need can't be bound NEEDS_STARTING = "needs-starting" # waiting: its needs are bound, to providers that don't run yet UNUSED = "unused" # waiting: on demand, and nothing that runs uses it RETRYING = "retrying" # waiting: it failed, and starts again after a delay STOPPED_ITSELF = "stopped-itself" # waiting: until its needs change or the user restarts it GAVE_UP = "gave-up" # failed: its retries are spent INVALID_SETTINGS = "invalid-settings" # failed: its stored settings don't validate @dataclass(frozen=True) class PeripheralStatus: state: PeripheralState kind: StatusKind | None = None # why it waits or failed detail: str = "" # the same in words, for logs and the CLI def __str__(self) -> str: return f"{self.state}: {self.detail}" if self.detail else self.state class RuntimeOutput(Protocol): """What the runtime reports to its owner (the Hub), delegate style like `PeripheralOutput`. Called synchronously from the runtime's loop, in order: don't block, schedule what takes time.""" def peripheral_did_change_status(self, peripheral: Peripheral, status: PeripheralStatus): ... def peripheral_did_learn(self, peripheral: Peripheral, facts: Mapping[str, Any]): """`Platform` facts it read from what it runs (a border router's Thread network), which the runtime's platform takes now (`Runtime.update_platform`): keep them for the next boot.""" ... def peripheral_did_disappear(self, peripheral: Peripheral): """It is no longer run here: what brought it along let go of it (a stick unplugged), or it was removed.""" ... class DisabledStore(Protocol): """Where the user's disabling of a peripheral is kept, by its ``key``: the Hub's enable/disable store.""" def is_disabled(self, key: str) -> bool: ... def set_disabled(self, key: str, is_disabled: bool): ... class MemoryDisabledStore: """Disabled until the process ends: library mode, the dev runner.""" def __init__(self, disabled: Iterable[str] = ()): self.disabled = set(disabled) def is_disabled(self, key: str) -> bool: return key in self.disabled def set_disabled(self, key: str, is_disabled: bool): (self.disabled.add if is_disabled else self.disabled.discard)(key) _GIVEN_UP = (PeripheralState.DISABLED, PeripheralState.FAILED) type Binding = tuple[_Entry, Endpoint] # who provides it, and what type _Identity = dict[str, list[tuple[_Entry, Endpoint, int]]] # what tells bindings apart @dataclass(eq=False) class _Entry: peripheral: Peripheral key: str # what it is known by here state: PeripheralState kind: StatusKind | None = None detail: str = "" attempts: int = 0 # failures in a row running_since: float | None = None # monotonic retry_at: float = 0.0 # monotonic: a waiting one starts no earlier failure: str = "" # why, and when it is tried again bindings: dict[str, list[Binding]] = field(default_factory=dict) # what it was started or last told with stopped_with: _Identity | None = None # what it was bound to when it stopped by itself: it waits for a change told_failure: str = "" # while starting is_stopping_itself: bool = False # told while starting platform_before: Platform | None = None # what the platform was when it changed while starting: told once it runs settings_before: BaseModel | None = None # the same of its settings task: asyncio.Task | None = None # its start reported: PeripheralStatus | None = None @property def status(self) -> PeripheralStatus: return PeripheralStatus(self.state, self.kind, self.detail) @property def is_started(self) -> bool: return self.state in (PeripheralState.STARTING, PeripheralState.RUNNING) class Runtime: """Runs every peripheral it is given, and what those bring along, by one rule (see `Peripheral`); binds their needs, and hears what each tells through the ``output`` they share:: runtime = Runtime( data, [Pinned(*mine), FixedPeripherals(*soldered), *default_peripherals(), *integrations], platform=platform ) await runtime.start() ``peripherals`` bind in the order given, what each brings along right after it: one given first wins a single-use endpoint (the Bluetooth router takes every adapter before the containers) and serves a need first: `Pinned`, then the hardware, the defaults and the integrations. ``platform`` is the host every peripheral runs on, its ``self.platform``: the facts peripherals read and containers render, a documents folder per peripheral and the device repository; `update_platform` replaces it. ``controller_output`` (the Hub's) hears what controllers report through their ``output``, logged by default. ``output`` hears every change of status, what is learned and what is gone; ``disabled`` keeps what the user disabled (in memory by default). Its own state, the settings, goes to ``data``. A peripheral that isn't disabled or failed runs while something that runs binds it if it ``is_on_demand``, while what brought it along runs, and once every required need is bound to a provider that runs. Only a waiting one starts by itself: a stick plugged in again never revives a disabled or failed one. A start that raises or takes too long, a crash it tells (``peripheral_did_fail``) and a hook that raises are tried again after each of ``retry_delays`` (`RETRY_DELAYS` unless given: a test passes short ones), then it is failed; one that stops by itself (``peripheral_did_stop``) waits for its needs to change. What it brought along goes when it stops. A provider restarting is a blip for what runs on it, but for one whose required need is bound to the very object it runs in process (a zeroconf browser): that one stops first and starts again after. """ def __init__( self, data: Path, peripherals: Sequence[Peripheral] = (), *, platform: Platform, controller_output: ControllerOutput | None = None, output: RuntimeOutput | None = None, disabled: DisabledStore | None = None, retry_delays: Sequence[float] | None = None, ): self.data, self.given, self.output = data, list(peripherals), output self._retry_delays = retry_delays # None: RETRY_DELAYS, read when it fails (a test may patch it) self.platform = platform self._shared_output = HostOutput(self, controller_output or LoggingControllerOutput()) self.disabled = disabled or MemoryDisabledStore() self.state: dict[str, Any] = {"settings": {}} saved = read_json(data / "state.json") self.state |= {key: saved[key] for key in saved.keys() & self.state.keys()} # older keys start fresh self._entries: dict[str, _Entry] = {} # in binding order self._duplicates: list[Peripheral] = [] # left out: another has their key self._gone: list[_Entry] = [] # to report self._failed: dict[str, str] = {} # key -> why, for the session: one brought along anew stays failed self._wanted: set[str] = set() # the ones that should run self._bound: dict[str, dict[str, list[Binding]]] = {} self._unbound: dict[str, dict[str, str]] = {} # key -> family -> why its need isn't bound self._lock = asyncio.Lock() self._holder: asyncio.Task | None = None # the task holding the lock self._calls: set[object] = set() # the marks of the peripheral calls it waits on self._tasks: set[asyncio.Task] = set() self._timer: asyncio.TimerHandle | None = None self._is_running = False self._collect() # known, with their status and settings, before it starts # Lifecycle async def start(self): self._is_running = True await self.refresh() async def stop(self): self._is_running = False if self._timer: self._timer.cancel() async with self._locked(): for entry in _users_first([entry for entry in self._entries.values() if entry.is_started]): await self._stop(entry, _waiting()) for task in self._tasks: task.cancel() async def refresh(self): """Collect, bind and run everything anew now; before it starts, only collect.""" if not self._is_running: self._collect() # none of them ran: none to stop or report gone return async with self._locked(): for _ in range(_PASSES): if not await self._pass(): break else: log.warning(f"Peripherals still changing after {_PASSES} passes") self._report() self._schedule_retry() # What the Hub (or you) reads @property def peripherals(self) -> list[Peripheral]: """Every peripheral it runs, in binding order: what it was given and what those brought along. One whose key another one before it has is left out, and logged.""" return [entry.peripheral for entry in self._entries.values()] def peripheral(self, key: str) -> Peripheral: return self._entries[key].peripheral def status(self, peripheral: Peripheral) -> PeripheralStatus: return self._entry(peripheral).status def bound(self, peripheral: Peripheral) -> dict[str, Bound]: """What each need is bound to, by family: an `Endpoint`, a list of them for an ``is_many`` need. What it has (or would have) in ``peripherals``: an optional need only once its provider runs.""" return _view(peripheral, self._held(self._entry(peripheral))) def providers(self, peripheral: Peripheral) -> dict[str, str | list[str]]: """Who serves each bound need, by family: its key, a list of them for an ``is_many`` need (one per endpoint, as `bound` lists them).""" many = {need.family for need in peripheral.needs if need.is_many} bound = self._held(self._entry(peripheral)) return {family: [p.key for p, _ in b] if family in many else b[0][0].key for family, b in bound.items()} def unbound(self, peripheral: Peripheral) -> dict[str, str]: """Why each need isn't bound, by family: for the developer (logs, the CLI), with what to do when there is something, e.g. 'need ble/bluez: every provider taken by ble-router — use Need("ble", ["router"])'. The Hub words its own message for the user.""" return dict(self._unbound.get(self._entry(peripheral).key, {})) def stored_settings(self, peripheral: Peripheral) -> dict[str, Any]: """Its settings as kept, raw: what to show with an invalid-settings failure, where they don't validate.""" return copy.deepcopy(self.state["settings"].get(self._entry(peripheral).key, {})) def settings_error(self, peripheral: Peripheral) -> ValidationError | None: """Why its kept settings don't validate as they load, also while it is disabled (it fails once enabled); None when they do. Show it with `stored_settings`.""" stored = self.state["settings"].get(self._entry(peripheral).key) try: if stored is not None: _loaded(peripheral.Settings, stored) except ValidationError as error: return error return None def users(self, peripheral: Peripheral) -> list[str]: """Every peripheral that runs on it, directly or through others: a radio's integrations and their containers.""" users: list[str] = [] providers = {self._entry(peripheral).key} while True: more = [ key for key, bound in self._bound.items() if key not in users and any(p.key in providers for b in bound.values() for p, _ in b) ] if not more: return users users += more providers.update(more) def uses(self, peripheral: Peripheral) -> list[str]: """Every peripheral it runs on, directly or through others: an integration's containers and radios.""" used: list[str] = [] owners = [self._entry(peripheral).key] while owners: bound = self._bound.get(owners.pop(0), {}) more = [p.key for b in bound.values() for p, _ in b if p.key not in used] used += dict.fromkeys(more) owners += more return used def reach(self, endpoints: Iterable[Endpoint]) -> list[str]: """The families ``endpoints`` would serve, themselves or through the on-demand peripherals here they would run, that something needs: one that runs anyway, or one used that isn't on the way: what a radio's firmware is good for.""" alive = [entry for entry in self._entries.values() if entry.state not in _GIVEN_UP] available = {endpoint.family for entry in alive for endpoint in _offered(entry.peripheral)} families: set[str] = set() reached, on_the_way = {e.family for e in endpoints}, set[str]() while reached != families: families = reached on_the_way = { key for key, entry in self._entries.items() if entry.peripheral.is_on_demand and _is_fed(entry.peripheral.needs, families, available) } reached = families.union( *({e.family for e in _offered(self._entries[key].peripheral)} for key in on_the_way) ) users = [ entry.peripheral for key, entry in self._entries.items() if not entry.peripheral.is_on_demand or (key in self._wanted and key not in on_the_way) ] return sorted(families & {need.family for peripheral in users for need in peripheral.needs}) # What the Hub (or you) changes async def add(self, peripheral: Peripheral): """Run ``peripheral`` too, as if given last: an integration installed while the hub runs. ValueError when another peripheral has its key.""" if any(other.key == peripheral.key for other in [*self.given, *self.peripherals]): raise ValueError(f"Can't add {peripheral.name}: another peripheral has the key {peripheral.key}") self.given.append(peripheral) await self._settle() async def remove(self, peripheral: Peripheral): """Stop running ``peripheral``, given or added; its owner hears it is gone (``peripheral_did_disappear``).""" self.given = [given for given in self.given if given is not peripheral] await self._settle() async def enable(self, peripheral: Peripheral): entry = self._entry(peripheral) self.disabled.set_disabled(entry.key, False) async def apply(): if entry.state == PeripheralState.DISABLED: entry.state = PeripheralState.WAITING self._revive(entry) self._check_settings(entry) await self._act(apply) async def disable(self, peripheral: Peripheral): """Stop it, and what it brought along, until enabled again; kept across restarts.""" entry = self._entry(peripheral) self.disabled.set_disabled(entry.key, True) await self._act(lambda: self._stop(entry, PeripheralStatus(PeripheralState.DISABLED))) async def restart(self, peripheral: Peripheral): """Stop it if it runs and start it again, a failed one or one that stopped by itself too: its retries start over, and its kept settings are read again (still invalid, it stays failed until they are updated). Called from inside a peripheral's own start, stop or hook, it happens once that call returns.""" entry = self._entry(peripheral) if entry.state == PeripheralState.DISABLED: raise ValueError(f"{entry.key} is disabled: enable it") async def apply(): await self._stop(entry, _waiting()) self._revive(entry) self._check_settings(entry) await self._act(apply) async def update_settings[S: BaseModel](self, peripheral: Peripheral[S], values: Mapping[str, Any]) -> S: """Validate and keep new values of its ``Settings``, none it doesn't have and no other value of a read-only one than its own; the ones left out stay as kept (a write-only one too). One that runs hears it (`settings_did_change`), one still starting once it runs, a failed one or one that stopped by itself tries again.""" entry, model = self._entry(peripheral), peripheral.Settings live = getattr(peripheral, "settings", None) # none yet when the ones kept didn't validate read_only = _read_only(model) filled = live.model_dump(mode="json", include=read_only) if live else {} # never kept: only the live ones current = self.state["settings"].get(entry.key, {}) | filled unknown = sorted(values.keys() - model.model_fields.keys()) if changed := sorted(k for k in values.keys() & read_only if values[k] != current.get(k)) + unknown: refused: list[InitErrorDetails] = [ {"type": "extra_forbidden" if k in unknown else "frozen_field", "loc": (k,), "input": values[k]} for k in changed ] raise ValidationError.from_exception_data(model.__name__, refused) settings = model.model_validate(current | dict(values)) before = live if live is not None else settings peripheral.settings = settings self._keep_settings(entry.key, settings) async def apply(): if entry.state in (PeripheralState.FAILED, PeripheralState.WAITING): entry.state = PeripheralState.WAITING self._revive(entry) elif entry.state == PeripheralState.RUNNING: await self._ask(entry, peripheral.settings_did_change(before)) elif entry.state == PeripheralState.STARTING and entry.settings_before is None: # it may have read them entry.settings_before = before await self._act(apply) return peripheral.settings async def update_platform(self, platform: Platform): """The host's facts changed: every peripheral reads ``platform`` from now on, built from the one there was (``dataclasses.replace(runtime.platform, region="Europe")``); one that runs hears it (`Peripheral.platform_facts_did_change`), one still starting may have read the ones before, so it hears it once it runs.""" before, self.platform = self.platform, platform for entry in self._entries.values(): entry.peripheral.platform = platform if platform == before: return started = [entry for entry in self._entries.values() if entry.is_started] # the ones that read the ones before async def apply(): for entry in started: if entry.state == PeripheralState.RUNNING: await self._ask(entry, entry.peripheral.platform_facts_did_change(before)) elif entry.state == PeripheralState.STARTING and entry.platform_before is None: entry.platform_before = before await self._act(apply) # What peripherals tell, through their output async def peripheral_did_change_provided(self, peripheral: Peripheral): await self._settle() async def peripheral_did_learn(self, peripheral: Peripheral, facts: Mapping[str, Any]): if self._find(peripheral) is None: return if unknown := sorted(facts.keys() - _FACTS): # a newer peripheral's: neither kept nor in the way of the others log.warning(f"{peripheral.key} learned what the platform holds no fact of, left out: {', '.join(unknown)}") if not (known := {name: value for name, value in facts.items() if name in _FACTS}): return if self.output: with _logged(f"Reporting what {peripheral.name} learned"): self.output.peripheral_did_learn(peripheral, known) await self.update_platform(replace(self.platform, **known)) async def peripheral_did_stop(self, peripheral: Peripheral): if (entry := self._find(peripheral)) is None: return if entry.state == PeripheralState.STARTING: entry.is_stopping_itself = True return async def apply(): if entry.state == PeripheralState.RUNNING: await self._stop_itself(entry) await self._act(apply) async def peripheral_did_fail(self, peripheral: Peripheral, reason: str): if (entry := self._find(peripheral)) is None: return if entry.state == PeripheralState.STARTING: entry.told_failure = entry.told_failure or reason return async def apply(): if entry.state == PeripheralState.RUNNING: await self._stop(entry, _waiting()) self._fail(entry, reason) await self._act(apply) # Internals def _entry(self, peripheral: Peripheral) -> _Entry: if (entry := self._find(peripheral)) is None: raise LookupError(f"{peripheral.name} isn't run here") return entry def _find(self, peripheral: Peripheral) -> _Entry | None: return next((entry for entry in self._entries.values() if entry.peripheral is peripheral), None) async def _act(self, change: Callable[[], Awaitable[Any]]): """Make a change and settle.""" await self._in_own_task(self._act_unlocked(change)) async def _act_unlocked(self, change: Callable[[], Awaitable[Any]]): async with self._locked(): await change() await self.refresh() async def _settle(self): """Bind and run anew.""" await self._in_own_task(self.refresh()) async def _in_own_task(self, work: Coroutine[Any, Any, Any]): """Do ``work`` in a task of the runtime's own, never in the caller's: a stop it brings may cancel the caller (a peripheral telling from its own task), and a caller cancelled meanwhile only stops waiting. The caller waits for it, unless the runtime waits on the caller: then it happens once that call returns.""" task = self._spawn(work) if not self._is_driving(): await asyncio.shield(task) def _is_driving(self) -> bool: """Whether the runtime waits on the current task: it holds the lock, or it runs a peripheral's start, stop or hook, or a task that call awaits. Waiting in it for the runtime to act would never end; a task a call left running (a keeper a start spawned) is no one the runtime waits on.""" return asyncio.current_task() is self._holder or _CALL.get() in self._calls async def _call[T](self, seconds: float, call: Awaitable[T], late: str) -> T: """A peripheral's ``call``, which the runtime waits on, marked so that what it awaits in tasks of its own (a ``TaskGroup``, ``gather``) counts as inside it while it runs: `_within`.""" mark = object() self._calls.add(mark) reset = _CALL.set(mark) try: return await _within(seconds, call, late) finally: _CALL.reset(reset) self._calls.discard(mark) @contextlib.asynccontextmanager async def _locked(self): async with self._lock: self._holder = asyncio.current_task() try: yield finally: self._holder = None async def _pass(self) -> bool: """One round: collect what there is, bind it, stop what shouldn't run, tell what runs what moved, start what can. True when something changed that the next round may bind differently.""" before = self._snapshot() is_changed = False gone = self._collect() # what brought it along let go of it, or it was replaced self._resolve() # first: what is read while they stop names none of them for entry in gone: is_changed = True await self._stop(entry, _waiting()) self._gone.append(entry) for entry in _users_first([e for e in self._entries.values() if e.is_started and e.key not in self._wanted]): is_changed = True await self._stop(entry, _waiting()) for entry in list(self._entries.values()): bound = self._handed(entry) if entry.state == PeripheralState.RUNNING and _identity(bound) != _identity(entry.bindings): is_changed = True await self._deliver(entry, bound) elif entry.state in (PeripheralState.WAITING, PeripheralState.FAILED, PeripheralState.DISABLED): self._bind_view(entry, bound) if entry.stopped_with is not None and _identity(bound) != entry.stopped_with: entry.stopped_with = None for entry in self._entries.values(): if entry.state == PeripheralState.WAITING: if (status := self._why_waiting(entry)) is None: self._start(entry) else: entry.kind, entry.detail = status.kind, status.detail return is_changed or self._snapshot() != before def _snapshot(self) -> list[tuple[str, tuple[Endpoint | Peripheral, ...]]]: return [(entry.key, tuple(_read(entry.peripheral))) for entry in self._entries.values()] def _collect(self) -> list[_Entry]: """Every peripheral given, and what the ones that run brought along, in binding order; the ones gone are returned.""" entries: dict[str, _Entry] = {} duplicates: list[Peripheral] = [] gone: list[_Entry] = [] def walk(peripheral: Peripheral, contributor: Peripheral | None): peripheral.contributor = contributor key = peripheral.key if (seen := entries.get(key)) is not None: if seen.peripheral is not peripheral: duplicates.append(peripheral) return entry = self._entries.get(key) if entry is None or entry.peripheral is not peripheral: if entry is not None: gone.append(entry) # replaced by another of the same key entry = self._adopt(peripheral) entries[key] = entry if entry.state == PeripheralState.RUNNING: for child in _brought(peripheral): walk(child, peripheral) for peripheral in self.given: walk(peripheral, None) gone += [entry for key, entry in self._entries.items() if key not in entries] for duplicate in duplicates: if all(duplicate is not known for known in self._duplicates): log.error(f"Another peripheral has the key {duplicate.key}: {duplicate.name} is left out") self._entries, self._duplicates = entries, duplicates return gone def _adopt(self, peripheral: Peripheral) -> _Entry: key = peripheral.key peripheral.output, peripheral.platform = self._shared_output, self.platform status = _waiting() if key in self._failed: status = PeripheralStatus(PeripheralState.FAILED, StatusKind.GAVE_UP, self._failed[key]) status = self._invalid_settings(peripheral, key) or status if self.disabled.is_disabled(key): status = PeripheralStatus(PeripheralState.DISABLED) return _Entry(peripheral, key, status.state, status.kind, status.detail) def _invalid_settings(self, peripheral: Peripheral, key: str) -> PeripheralStatus | None: """Load its settings: the failure of one whose kept ones don't validate, which keeps them as they are.""" try: self._load_settings(peripheral, key) except ValidationError as error: invalid = "; ".join(f"{'.'.join(map(str, e['loc']))}: {e['msg']}" for e in error.errors()) return PeripheralStatus(PeripheralState.FAILED, StatusKind.INVALID_SETTINGS, f"Invalid settings: {invalid}") return None def _check_settings(self, entry: _Entry): """Read its kept settings again as it is let start: one whose don't validate stays failed until updated.""" if status := self._invalid_settings(entry.peripheral, entry.key): entry.state, entry.kind, entry.detail = status.state, status.kind, status.detail def _load_settings(self, peripheral: Peripheral, key: str): """The ones kept, else the ones it was given or the defaults, kept from now on; kept ones it no longer has (its update dropped them, or made them read-only) go.""" model, stored = peripheral.Settings, self.state["settings"].get(key) if stored is not None: peripheral.settings = _loaded(model, stored) elif not isinstance(getattr(peripheral, "settings", None), model): peripheral.settings = model() if _kept(peripheral.settings) != (stored or {}): # freeze generated defaults self._keep_settings(key, peripheral.settings) def _keep_settings(self, key: str, settings: BaseModel): """Keep ``settings`` from now on; nothing for a peripheral without any.""" if dumped := _kept(settings): self.state["settings"][key] = dumped else: self.state["settings"].pop(key, None) self._save() def _resolve(self): """The ones that should run: from the ones alive that run anyway, down through what they bind, binding in order with single-use endpoints taken; one whose required need finds nothing is left out, and it all binds anew.""" alive = {key for key, entry in self._entries.items() if entry.state not in _GIVEN_UP} provides = {key: _offered(entry.peripheral) for key, entry in self._entries.items()} left_out: set[str] = set() while True: among = alive - left_out wanted = {key for key in among if not self._entries[key].peripheral.is_on_demand} while True: bound, taken = self._bind(wanted, among, provides) used = {p.key for b in bound.values() for bindings in b.values() for p, _ in bindings} if used <= wanted: break wanted |= used if not (unbound := wanted - bound.keys()): break left_out |= unbound self._wanted, self._bound = wanted, bound self._unbound = _Reasons(self, alive, wanted, provides, taken).all() def _bind( self, wanted: set[str], among: set[str], provides: Mapping[str, list[Endpoint]] ) -> tuple[dict[str, dict[str, list[Binding]]], dict[tuple[str, str, str], str]]: """Bind the needs of every wanted one in order to providers ``among``; one whose required need finds nothing is left out.""" bound: dict[str, dict[str, list[Binding]]] = {} taken: dict[tuple[str, str, str], str] = {} # (provider, family, url) of a single-use endpoint -> who took it for key in [key for key in self._entries if key in wanted]: owner, mine, bindings = self._entries[key].peripheral, [], {} for need in owner.needs: chosen = [ (provider, endpoint) for provider, endpoint in self._candidates(key, need, among, provides) if (provider.key, endpoint.family, endpoint.url) not in taken ] chosen = chosen if need.is_many else chosen[:1] for provider, endpoint in chosen: if not endpoint.is_shared: taken[provider.key, endpoint.family, endpoint.url] = key mine.append((provider.key, endpoint.family, endpoint.url)) if chosen: bindings[need.family] = chosen elif need.is_required: for held in mine: # what it took goes back to the others del taken[held] break else: bound[key] = bindings return bound, taken def _candidates( self, owner: str, need: Need, among: set[str], provides: Mapping[str, list[Endpoint]] ) -> list[Binding]: """What could serve ``need`` of ``owner``, in the order given.""" return [ (self._entries[key], endpoint) for key in self._entries if key in among and key != owner for endpoint in provides[key] if need.accepts(endpoint) ] def _why_waiting(self, entry: _Entry) -> PeripheralStatus | None: """Why a waiting one doesn't start now; None when it can.""" if entry.stopped_with is not None: return _waiting(StatusKind.STOPPED_ITSELF, "stopped by itself: waits for its needs to change or a restart") contributor = self._entries.get(by.key) if (by := entry.peripheral.contributor) else None if contributor is not None and contributor.state != PeripheralState.RUNNING: # it goes with the next pass return _waiting(detail=f"comes with {contributor.key}, which stopped") if entry.key not in self._wanted: required = {need.family for need in entry.peripheral.needs if need.is_required} if reasons := [why for family, why in self._unbound.get(entry.key, {}).items() if family in required]: return _waiting(StatusKind.NEEDS_UNBOUND, "; ".join(reasons)) return _waiting(StatusKind.UNUSED, "nothing that runs uses it") if entry.retry_at > monotonic(): return _waiting(StatusKind.RETRYING, entry.failure) bound = self._bound[entry.key] required = [n.family for n in entry.peripheral.needs if n.is_required and n.family in bound] pending = dict.fromkeys(p.key for family in required for p, _ in bound[family] if not self._is_serving(p.key)) return _waiting(StatusKind.NEEDS_STARTING, f"waiting for {', '.join(pending)}") if pending else None def _is_serving(self, key: str) -> bool: entry = self._entries[key] return entry.state == PeripheralState.RUNNING def _handed(self, entry: _Entry) -> dict[str, list[Binding]]: """What it is bound to, an optional need only to a provider that runs, or that it was handed before: the start doesn't wait for it, and one restarting is a blip.""" optional = {need.family for need in entry.peripheral.needs if not need.is_required} handed: dict[str, list[Binding]] = {} for family, bindings in self._bound.get(entry.key, {}).items(): before = entry.bindings.get(family, []) if family in optional: bindings = [b for b in bindings if self._is_serving(b[0].key) or b in before] if bindings: handed[family] = bindings return handed def _held(self, entry: _Entry) -> dict[str, list[Binding]]: """What it was started or last told with; what it would be handed, while it doesn't run.""" return entry.bindings if entry.is_started else self._handed(entry) def _bind_view(self, entry: _Entry, bound: Mapping[str, list[Binding]]): entry.peripheral.peripherals = Peripherals(_view(entry.peripheral, bound)) def _start(self, entry: _Entry): entry.state, entry.kind, entry.detail = PeripheralState.STARTING, None, "" entry.bindings, entry.told_failure, entry.is_stopping_itself = self._handed(entry), "", False entry.platform_before = entry.settings_before = None self._bind_view(entry, entry.bindings) entry.task = self._spawn(self._run_start(entry)) async def _run_start(self, entry: _Entry): peripheral, failure = entry.peripheral, "" timeout = peripheral.start_timeout try: await self._call(timeout, peripheral.start(), f"didn't start within {timeout} s") except asyncio.CancelledError as error: if _is_cancelled(): # stopped raise failure = _failure(error) # raised from inside, e.g. by a task it awaited except Exception as error: log.error(f"{peripheral.name} failed to start: {error}", exc_info=error) failure = _failure(error) async with self._locked(): if entry.task is not asyncio.current_task(): # stopped, though it went on return entry.task = None if failure := entry.told_failure or failure: await self._stop(entry, _waiting()) # it releases what it took before it failed self._fail(entry, failure) elif entry.is_stopping_itself: await self._stop_itself(entry) else: entry.state, entry.running_since = PeripheralState.RUNNING, monotonic() await self._tell_missed(entry) await self.refresh() async def _tell_missed(self, entry: _Entry): """Tell one that just started what changed while it started, from what it may have read.""" platform, settings = entry.platform_before, entry.settings_before entry.platform_before = entry.settings_before = None if platform is not None and not await self._ask(entry, entry.peripheral.platform_facts_did_change(platform)): return # restarted: it reads the settings anew if settings is not None: await self._ask(entry, entry.peripheral.settings_did_change(settings)) async def _stop_itself(self, entry: _Entry): stopped_with = _identity(entry.bindings) await self._stop(entry, _waiting()) entry.stopped_with = stopped_with # TODO: stop reason as an enum + per-reason restart policies def _fail(self, entry: _Entry, reason: str): """Count a failure: wait to try again, or give up once the retries are spent.""" entry.attempts += 1 delays = RETRY_DELAYS if self._retry_delays is None else self._retry_delays if entry.attempts > len(delays): entry.state, entry.kind, entry.detail, entry.attempts = ( PeripheralState.FAILED, StatusKind.GAVE_UP, reason, 0, ) self._failed[entry.key] = reason return delay = delays[entry.attempts - 1] entry.state, entry.kind, entry.retry_at = PeripheralState.WAITING, StatusKind.RETRYING, monotonic() + delay entry.detail = entry.failure = f"{reason}; trying again in {delay} s" async def _stop(self, entry: _Entry, status: PeripheralStatus): """Stop it if it runs or starts, and leave it in ``status``. What runs on the very object it provides (a required need bound to an endpoint with its ``instance``) stops first: what it registered there goes with it, so it starts again only once it runs anew.""" if entry.state == PeripheralState.DISABLED and status.state != PeripheralState.DISABLED: return # only enabling ends it if entry.is_started: for user in _users_first([user for user in self._entries.values() if _runs_inside(user, entry)]): await self._stop(user, _waiting()) is_started = entry.is_started if task := entry.task: entry.task = None task.cancel() if not (await asyncio.wait({task}, timeout=STOP_TIMEOUT))[0]: log.error(f"{entry.key} goes on starting though stopped: left behind") if entry.running_since is not None and monotonic() - entry.running_since >= STABLE_RUN: entry.attempts = 0 entry.running_since = None if is_started: try: await self._call(STOP_TIMEOUT, entry.peripheral.stop(), f"didn't stop within {STOP_TIMEOUT} s") except Exception as error: log.error(f"{entry.key} failed to stop cleanly: {error}", exc_info=error) entry.state, entry.kind, entry.detail, entry.bindings = status.state, status.kind, status.detail, {} async def _deliver(self, entry: _Entry, bound: dict[str, list[Binding]]): """Tell one that runs what moved; restart it unless it handles every change.""" before, entry.bindings = entry.bindings, bound self._bind_view(entry, bound) was, now = _view(entry.peripheral, before), _view(entry.peripheral, bound) for family in sorted(was.keys() | now.keys()): if _identity({family: before.get(family, [])}) != _identity({family: bound.get(family, [])}): change = PeripheralChange(family, was.get(family), now.get(family)) if not await self._ask(entry, entry.peripheral.needed_peripheral_did_change(change)): return async def _ask(self, entry: _Entry, hook: Awaitable[bool]) -> bool: """Whether it handled a change in place; if not it restarts, and a hook that raised counts as a failure.""" failure = "" try: if await self._call(HOOK_TIMEOUT, hook, f"didn't take the change within {HOOK_TIMEOUT} s"): return True except asyncio.CancelledError as error: if _is_cancelled(): raise log.error(f"{entry.key} was cancelled taking a change", exc_info=error) # from inside: a call it awaited failure = _failure(error) except Exception as error: log.error(f"{entry.key} failed to take a change: {error}", exc_info=error) failure = _failure(error) await self._stop(entry, _waiting()) if failure: self._fail(entry, failure) return False def _revive(self, entry: _Entry): """The user's say: its failures in a row, a retry it waits for and its stopping by itself are forgotten.""" entry.attempts, entry.retry_at, entry.stopped_with = 0, 0.0, None self._failed.pop(entry.key, None) def _report(self): gone, self._gone = self._gone, [] for entry in gone: if self.output and entry.reported is not None: with _logged(f"Reporting {entry.key} gone"): self.output.peripheral_did_disappear(entry.peripheral) for entry in self._entries.values(): if entry.reported != (status := entry.status): entry.reported = status if self.output: with _logged(f"Reporting {entry.key} {status.state}"): self.output.peripheral_did_change_status(entry.peripheral, status) def _schedule_retry(self): if self._timer: self._timer.cancel() now = monotonic() waiting = [e for e in self._entries.values() if e.state == PeripheralState.WAITING] retries = [e.retry_at for e in waiting if e.retry_at > now] if retries and self._is_running: delay = min(retries) - now self._timer = asyncio.get_running_loop().call_later(delay, lambda: self._spawn(self.refresh())) def _save(self): write_json(self.data / "state.json", self.state) def _spawn(self, work: Coroutine[Any, Any, Any]) -> asyncio.Task: context = contextvars.copy_context() context.run(_CALL.set, None) # the runtime's own: inside no peripheral's call, whichever set it off task = asyncio.get_running_loop().create_task(work, context=context) self._tasks.add(task) task.add_done_callback(self._tasks.discard) return task @dataclass class _Reasons: """Why each need of every peripheral alive isn't bound, from the final binding.""" runtime: Runtime alive: set[str] wanted: set[str] provides: Mapping[str, list[Endpoint]] taken: Mapping[tuple[str, str, str], str] reasons: dict[str, dict[str, str]] = field(default_factory=dict) def all(self) -> dict[str, dict[str, str]]: for key in self.runtime._entries: if key in self.alive: self.of(key) return {key: reasons for key, reasons in self.reasons.items() if reasons} def of(self, key: str) -> dict[str, str]: if key in self.reasons: return self.reasons[key] self.reasons[key] = reasons = {} # also guards against cycles bound = self.runtime._bound.get(key, {}) for need in self.runtime._entries[key].peripheral.needs: if need.family not in bound and (why := self.why(key, need)): reasons[need.family] = why return reasons def why(self, owner: str, need: Need) -> str | None: """Why ``need`` of ``owner`` can't be bound; None when it could be, had the owner a reason to run.""" rejected: list[str] = [] entries = self.runtime._entries for provider, endpoint in self.runtime._candidates(owner, need, set(entries), self.provides): if (taker := self.taken.get((provider.key, endpoint.family, endpoint.url))) not in (None, owner): rejected.append(f"every provider taken by {taker}" + self.hint(taker, need.family)) elif provider.key not in self.alive: rejected.append(f"{provider.key} is {entries[provider.key].state}") elif provider.key not in self.wanted and (why := self.blocking(provider)): rejected.append(f"{provider.key} can't run ({why})") else: return None # free, or on demand and idle only because the owner doesn't run wanted = f"{need.family}/{'|'.join(need.dialects) or '*'}" return f"need {wanted}: {'; '.join(dict.fromkeys(rejected)) or 'nothing offers it'}" def blocking(self, provider: _Entry) -> str: """Why the required needs of ``provider`` can't be bound: the optional ones don't keep it from running.""" required = {need.family for need in provider.peripheral.needs if need.is_required} return "; ".join(why for family, why in self.of(provider.key).items() if family in required) def hint(self, taker: str, family: str) -> str: """What to need instead when what took the endpoint offers the same family itself: the router for raw BLE.""" endpoint = next((e for e in self.provides.get(taker, []) if e.family == family), None) return f' — use Need("{family}", ["{endpoint.dialect}"])' if endpoint else "" async def _within[T](seconds: float, call: Awaitable[T], late: str) -> T: """What ``call`` returns, or TimeoutError(``late``) once it took ``seconds``.""" timeout = asyncio.timeout(seconds) try: async with timeout: return await call except TimeoutError: if timeout.expired(): raise TimeoutError(late) from None raise def _is_read_only(schema: Any) -> bool: """Whether a settings field is marked read-only in its JSON schema: its peripheral fills it in, never the user.""" return isinstance(schema, dict) and schema.get(SettingsExtraField.read_only) is True def _read_only(model: type[BaseModel]) -> set[str]: return {name for name, field in model.model_fields.items() if _is_read_only(field.json_schema_extra)} def _loaded[S: BaseModel](model: type[S], stored: Mapping[str, Any]) -> S: """Kept settings as they load: the fields the model has but the read-only ones, never kept.""" kept = model.model_fields.keys() - _read_only(model) return model.model_validate({k: v for k, v in stored.items() if k in kept}) def _kept(settings: BaseModel) -> dict[str, Any]: """What is kept of ``settings``: never what their peripheral fills in, shown only while it runs.""" return settings.model_dump(mode="json", exclude=_read_only(type(settings))) def _failure(error: BaseException) -> str: return str(error) or type(error).__name__ def _is_cancelled() -> bool: """Whether the current task is being cancelled, rather than a CancelledError raised from inside what it awaits.""" return bool((task := asyncio.current_task()) and task.cancelling()) def _read(peripheral: Peripheral) -> list[Endpoint | Peripheral]: """What ``peripheral`` provides; one that can't say provides nothing, and the others run on.""" try: return list(peripheral.provides) except Exception as error: log.error(f"{peripheral.name} failed to say what it provides: {error}", exc_info=error) return [] def _offered(peripheral: Peripheral) -> list[Endpoint]: return [item for item in _read(peripheral) if isinstance(item, Endpoint)] def _brought(peripheral: Peripheral) -> list[Peripheral]: return [item for item in _read(peripheral) if not isinstance(item, Endpoint)] @contextlib.contextmanager def _logged(what: str): """A call into the runtime's owner that raises is logged: the runtime goes on.""" try: yield except Exception as error: log.error(f"{what} failed: {error}", exc_info=error) def _users_first(entries: list[_Entry]) -> list[_Entry]: """``entries`` in the order to stop them: each after what it was started with is bound to it, else last given first.""" left, ordered = entries[::-1], [] while left: entry = next((e for e in left if not any(_is_using(user, e) for user in left)), left[0]) left.remove(entry) ordered.append(entry) return ordered def _is_using(user: _Entry, provider: _Entry) -> bool: return any(p is provider for bindings in user.bindings.values() for p, _ in bindings) def _runs_inside(user: _Entry, provider: _Entry) -> bool: """Whether ``user`` runs with a required need bound to the in-process object ``provider`` runs: a zeroconf browser, whose restart it can't ride out as it does a server's.""" required = {need.family for need in user.peripheral.needs if need.is_required} return user.is_started and any( p is provider and endpoint.instance is not None for family, bindings in user.bindings.items() if family in required for p, endpoint in bindings ) def _waiting(kind: StatusKind | None = None, detail: str = "") -> PeripheralStatus: return PeripheralStatus(PeripheralState.WAITING, kind, detail) def _view(peripheral: Peripheral, bound: Mapping[str, list[Binding]]) -> dict[str, Bound]: many = {need.family for need in peripheral.needs if need.is_many} return {family: [e for _, e in b] if family in many else b[0][1] for family, b in bound.items()} def _identity(bound: Mapping[str, list[Binding]]) -> _Identity: """What tells two bindings apart: the provider, the endpoint and the very instance it carries.""" return {family: [(p, e, id(e.instance)) for p, e in bindings] for family, bindings in bound.items()} def _is_fed(needs: Sequence[Need], families: set[str], available: set[str]) -> bool: """Whether ``families`` feed one of the required ``needs``, and with what is ``available`` all of them.""" required = {need.family for need in needs if need.is_required} return bool(required & families) and required <= families | available __all__ = [ "Runtime", "RuntimeOutput", "PeripheralState", "PeripheralStatus", "StatusKind", "DisabledStore", "MemoryDisabledStore", "RETRY_DELAYS", ] ================================================================================ # FILE: majordom_integration_sdk/schemas/__init__.py ================================================================================ """The MajorDom wire protocol — the device/parameter models shared between an integration and the Hub. Scope is deliberately the device domain: devices, parameters, pairing/discovery, commands, and parameter-change reports. Hub-only concerns (rooms, houses, users, the websocket protocol) and the automation event bus live in the Hub, not here. """ from .base import Base, NonEmptyStr, StrEnum, StrIdentifiable, UUIdentifable from .command import DeviceCommand from .credentials import CredentialsOption, CredentialsType, CredentialsValue, ProvidedCredentials, WifiCredentials from .device import ( Device, DeviceCreate, DeviceDataModel, DeviceInfo, DevicePair, DevicePatch, DeviceState, Discovery, ) from .event import DeviceParameterChange, Event from .parameter import ( Parameter, ParameterDataType, ParameterRole, ParameterState, ParameterUnit, ParameterVisibility, ParameterVisibilityPatch, ) __all__ = [ # base "Base", "NonEmptyStr", "StrEnum", "StrIdentifiable", "UUIdentifable", # command / events "DeviceCommand", "Event", "DeviceParameterChange", # credentials "CredentialsOption", "CredentialsType", "CredentialsValue", "ProvidedCredentials", "WifiCredentials", # device "Device", "DeviceCreate", "DeviceDataModel", "DeviceInfo", "DevicePair", "DevicePatch", "DeviceState", "Discovery", # parameter "Parameter", "ParameterDataType", "ParameterRole", "ParameterState", "ParameterUnit", "ParameterVisibility", "ParameterVisibilityPatch", ] ================================================================================ # FILE: majordom_integration_sdk/schemas/base.py ================================================================================ from __future__ import annotations from enum import Enum from typing import Any from uuid import UUID from pydantic import BaseModel as PydanticBaseModel from pydantic import Field, GetJsonSchemaHandler from pydantic_core import core_schema as cs class StrEnum(str, Enum): pass class Base(PydanticBaseModel): # TODO: make sure all models use it model_config = { "from_attributes": True, "validate_assignment": True, } class NonEmptyStr(str): @classmethod def __get_pydantic_core_schema__(cls, _source: Any, _handler) -> cs.CoreSchema: # Create a core schema of type string with a validator function return cs.str_schema( min_length=1, strict=True, # You can add custom validation here if needed, but min_length=1 ensures non-empty ) @classmethod def __get_pydantic_json_schema__( cls, core_schema: cs.CoreSchema, handler: GetJsonSchemaHandler, ) -> dict: json_schema = handler(core_schema) json_schema.update( title="NonEmptyStr", description="A non-empty string", examples=["example text"], ) return json_schema class UUIdentifable(Base): # TODO: review id: UUID = Field(frozen=True) def __hash__(self): return hash(self.id) def __eq__(self, other): if not isinstance(other, UUIdentifable): return NotImplemented return self.id == other.id class StrIdentifiable(Base): id: str ================================================================================ # FILE: majordom_integration_sdk/schemas/command.py ================================================================================ from typing import Any from uuid import UUID from .base import Base class DeviceCommand(Base): device_id: UUID parameter_id: UUID value: Any ================================================================================ # FILE: majordom_integration_sdk/schemas/credentials.py ================================================================================ """How a device is paired and set up: the credentials the user gives, and the Wi-Fi the Hub provisions it onto.""" from __future__ import annotations from dataclasses import dataclass from enum import Enum from typing import Annotated from pydantic import Field from .base import Base from .settings import SettingsExtraField as Extra class CredentialsType(str, Enum): code = "code" # e.g. 1234-123-1234 (matter) or 123-45-678 (homekit) # TODO: rename to pin qr = "qr" # raw qr data; TODO: decode to see what data is inside some protocols secret = "secret" # AES key like in esphome # The user physically confirms on the device (ESPHome Improv authorizer, a Matter/HomeKit # setup button). A confirmation step that carries no value — unlike `none`, which means # pairing needs nothing from the user at all. button = "button" none = "none" # like yeelight classic LAN def with_mask(self, mask: str, hint: str | None = None) -> CredentialsOption: """ Returns a CredentialsOption of this type with the mask (and optionally a hint). mask format: D as digit placeholder, other symbols remain unchanged e.g. dashes, for example "DDD-DD-DDD" for "123-45-678" """ return CredentialsOption(type=self, mask=mask, hint=hint) def with_hint(self, hint: str) -> CredentialsOption: """ Returns a CredentialsOption of this type with the hint: a short UI prompt, for example "Press the button on the device" """ return CredentialsOption(type=self, hint=hint) class CredentialsOption(Base): """One way a discovered device can be paired, with what the UI needs to ask for it.""" type: CredentialsType # D is a digit placeholder, other symbols stay as they are: "DDD-DD-DDD" for "123-45-678" mask: str | None = None # a short UI prompt, e.g. "Press the button on the device" or "Printed on the label" hint: str | None = None def __eq__(self, other: object) -> bool: # Compat: integrations check `credentials.type in discovery.expected_credentials_options`; # a bare type (or its str value) matches the option of that type. if isinstance(other, str): return self.type == other return super().__eq__(other) # FUTURE: # @dataclass # class CredentialsCode: # code: str # @dataclass # class CredentialsSecret: # secret: str # Credentials = Union[CredentialsCode] type CredentialsValue = str class ProvidedCredentials(Base): """What a pairing request actually supplies — paired with its type, so pairing can validate it against Discovery.expected_credentials_options instead of trusting whatever the integration guessed at discovery time.""" type: CredentialsType value: CredentialsValue | None = None @dataclass(frozen=True) class WifiCredentials: ssid: str # the user writes it, nothing reads it back: settings holding a network never return it password: Annotated[str, Field(json_schema_extra={Extra.write_only: True})] = "" ================================================================================ # FILE: majordom_integration_sdk/schemas/device.py ================================================================================ from __future__ import annotations from datetime import datetime from types import NoneType from typing import Any, get_args from uuid import UUID from pydantic import Field, SerializeAsAny, field_validator from .base import Base, NonEmptyStr from .credentials import ( # noqa: F401 (they lived here) CredentialsOption, CredentialsType, CredentialsValue, ProvidedCredentials, ) from .parameter import Parameter, ParameterState # TODO: split the file # Pairing class Discovery(Base): # technical id: UUID integration: NonEmptyStr expected_credentials_options: list[CredentialsOption] expiration: datetime | None = None # for UX transport: NonEmptyStr device_manufacturer: str | None device_name: NonEmptyStr device_category: str | None device_icon: str | None # TODO: icon system last_error: str | None = None # device_model_id: UUID | None = None # is it still relevant? # TODO: room hint? # TODO: integration_data # TODO: handle devices with multiple transports or multiple integrations, show options, add priority, allow choosing @field_validator("expected_credentials_options", mode="before") @classmethod def _accept_bare_types(cls, options: Any) -> Any: # stored discoveries and older integrations pass bare types: ["code"] / [CredentialsType.code] if not isinstance(options, list): return options return [{"type": option} if isinstance(option, str) else option for option in options] def accepts(self, credentials: ProvidedCredentials | None) -> bool: """Whether `credentials` match one of the advertised options; no credentials count as `none`.""" provided = credentials.type if credentials else CredentialsType.none return any(option.type == provided for option in self.expected_credentials_options) # Device class DevicePatch(Base): name: str note: str = "" icon: str | None = None category: str | None = None room_id: UUID main_parameter: UUID | None = None class DeviceCreate(DevicePatch): discovery_id: UUID # | None = None credentials: ProvidedCredentials | None = None class DevicePair(Base): """Re-pair discovery to the existing device.""" device_id: UUID discovery_id: UUID credentials: ProvidedCredentials | None = None class DeviceInfo(DevicePatch): id: UUID = Field(frozen=True) # Hub-owned, set at the pairing write, never changes transport: str integration: str manufacturer: str | None # Manufacturer-provided, read-only description of the device (a model blurb / product name). # Integrations set it when the protocol exposes one; the Hub never edits it. (User-editable # free text is `note`, on DevicePatch.) description: str | None = None main_parameter: UUID | None = None # for the tap action on the room view, toggle in most cases last_seen: datetime | None = None available: bool = False last_error: str | None = None # model_id: UUID | None = None # model: DeviceModel - is it needed here? # merlin24: DeviceMerlin24 | None # DEPRECATED class Device[TData = Any](DeviceInfo): # TODO: review models """A device with what its integration keeps about it, ``integration_data``, typed as ``TData``: a bare ``Device`` holds any (a dict once read back), ``class HueDevice(Device[HueData])`` its own model. Unset, it is ``TData`` validated from ``{}`` (the Hub creates a device before its integration pairs it), and stays unset: a save keeps the stored one. For ``Device[HueData | None]`` that ``{}``, unset or stored, is None.""" # The integration's lookup id (``device_uuid`` of what the protocol identifies the device by): unique, filled in # by ``pair_device``; inbound protocol data maps to the record through it, and the repository is keyed by it physical_id: UUID integration_data: SerializeAsAny[TData] = Field(default_factory=dict, validate_default=True) @field_validator("integration_data", mode="before") @classmethod def _empty_is_none_when_optional(cls, value: Any) -> Any: if value == {} and NoneType in get_args(cls.model_fields["integration_data"].annotation): return None return value class DeviceDataModel(DeviceInfo): parameters: list[Parameter] class DeviceState[TData = Any, TParameterData = Any](Device[TData]): """A device with its parameters' current states, the data of each typed as ``TParameterData``.""" parameters: list[ParameterState[TParameterData]] @property def parameters_dict(self): return {param.id: param for param in self.parameters} def can_set_main_parameter(self, parameter_id: UUID | None) -> bool: """Whether `parameter_id` may be this device's main (one-tap) parameter: clearing it (None) is always allowed, otherwise it must be one of this device's parameters and satisfy ParameterState.can_be_main_parameter.""" if parameter_id is None: return True parameter = self.parameters_dict.get(parameter_id) return parameter is not None and parameter.can_be_main_parameter # Device Model TODO: review usage; # Current idea is to store more metadata that can't be accessed from the device itself, # for example, manufacturer's website, preview picture, 3d model, specs, etc # class DeviceModelInfo(Base): # id: UUID # name: NonEmptyStr # transports: list[str] # integration: NonEmptyStr # manufacturer: str | None # category: str | None # icon: str | None # is_custom: bool = False # TODO: DEPRECATE? # # picture: str | None # TODO: resolve # class DeviceModel(DeviceModelInfo): # parameters: list[Parameter] ================================================================================ # FILE: majordom_integration_sdk/schemas/event.py ================================================================================ from typing import Any from uuid import UUID from .base import Base class Event(Base): """Base class for device-domain events a controller reports to the Hub. Delivered through :meth:`ControllerOutput.controller_did_receive_events`. A parameter change is the first concrete kind; more (button presses, device online/offline, …) can extend this without changing the callback. Kept device-domain and distinct from the Hub's automation event bus, which wraps these on its side. """ class DeviceParameterChange(Event): """A device reported that one of its parameters changed to a new value. Mirrors :class:`DeviceCommand`'s shape (``parameter_id``, ``value``) but flows the other direction — device → Hub, so it names the device by its ``physical_id``: the integration knows no other. """ physical_id: UUID parameter_id: UUID value: Any ================================================================================ # FILE: majordom_integration_sdk/schemas/notification.py ================================================================================ from .base import Base, StrEnum class NotificationType(StrEnum): """The callout style the app renders the notification with.""" info = "info" warning = "warning" error = "error" class NotificationPriority(StrEnum): """How insistently the notification is delivered (maps to the OS interruption levels).""" silent = "silent" # appears in the list, no alert normal = "normal" # default banner time_sensitive = "time_sensitive" # breaks through focus/quiet modes urgent = "urgent" # demands attention class Notification(Base): """A general user-facing message an integration surfaces to the user as a floating tile in the app. Distinct from ``controller_did_encounter_error`` (which is specifically for integration failures/health) — use this for anything informational or advisory the user should see. ``ttl`` is how many seconds the tile stays before auto-dismissing; ``None`` keeps it until the user dismisses it. """ message: str type: NotificationType = NotificationType.info priority: NotificationPriority = NotificationPriority.normal ttl: int | None = None ================================================================================ # FILE: majordom_integration_sdk/schemas/parameter.py ================================================================================ from collections.abc import Sequence from typing import Any from uuid import UUID from pydantic import field_validator from .base import Base, StrEnum, UUIdentifable # TODO: consider adding clusters / groups / endpoints to the device model to group parameters like in zigbee # OLD (Merlin-alpha): # class ParameterDataType(StrEnum): # integer = "integer" # uint8 # decimal = "decimal" # uint8 to be casted to [0...1] decimal range # bool = "bool" # one-bit integer # enum = "enum" # uint8 with string_representation # string = "string" # string # class ParameterUnit(StrEnum): # plain = "plain" # any # humidity = "humidity" # decimal; # temperature_c = "temperature_c" # float32; # color_temperature = "color_temperature" # Kelvin, decimal; 0.5 is white # rgb = "rgb" # hue wheel angle, decimal; # volume = "volume" # decimal; # button = "button" # None, just a button # timeinterval = "timeinterval" # seconds, int32; class ParameterDataType(StrEnum): none = "none" # e.g. button # numeric bool = "bool" integer = "integer" decimal = "decimal" # python float enum = "enum" # integer with string_representation # data string = "string" struct = "struct" # multi-field object for things like Metter command arguments or just complex Parameters; Value format: {:} data = "data" # freeform binary data, base64 encoded at high level, for documents and extensions' internal usage # homekit also has array and dict # can be extended if needed class ParameterUnit(StrEnum): plain = "plain" # raw data type percentage = "percentage" # time second = "second" hertz = "hertz" # kinematic kilogram = "kilogram" arcdegree = "arcdegree" meters = "meters" mps = "mps" # meters per second, speed mps2 = "mps2" # meters per second squared, acceleration m3h = "m3h" # cubic meters per hour, volumetric flow rpm = "rpm" # revolutions per minute newton = "newton" # force joule = "joule" # energy kwh = "kwh" # kilowatt-hour, energy (metering display unit) watt = "watt" # power # temperature celsius = "celsius" kelvin = "kelvin" mired = "mired" # reciprocal megakelvin, color temperature # electricity volt = "volt" ampere = "ampere" # light # check if lumen or candela are needed lux = "lux" # rgb = "rgb" # hex str; UPD: homekit implements color as separate simple HSV parameters w/o adding complex data structs # air pascal = "pascal" ppm = "ppm" # parts per million, air quality ugm3 = "ugm3" # micrograms per cubic meter, particulate matter (PM2.5/PM10) # informatics bytes = "bytes" # data size bps = "bps" # bytes per second, data rate json = "json" # freeform json with code snippet display document = "document" # upload/download files class ParameterRole(StrEnum): sensor = "sensor" # get-only control = "control" # get-set event = "event" class ParameterVisibility(StrEnum): user = "user" # main, everyday interaction, device screen widgets (on/off, brightness, volume) setting = "setting" # user-configurable but behind am extra "settings"/"advanced" tap: configured once and rarely touched again; or diagnostic readings (RSSI, firmware version) system = "system" # hidden under-the-hood wirings; not visible to the user def next_main_parameter_value( current: int | float | str | bool | None, cycle: Sequence[int | float | str] | None, ) -> int | float | str | None: """The value a one-tap (cycle/toggle) main parameter should send next. ``cycle`` is the ordered set of values to rotate through — the parameter's ``default_value`` values (a set), or its ``valid_values`` keys when no ``default_value`` is set. A single-element cycle is a "set to this value" button. Returns the element after ``current`` (wrapping), or the first element when ``current`` isn't in the set (or is unknown). ``None`` for an empty cycle. """ if not cycle: return None if len(cycle) == 1 or current not in cycle: return cycle[0] return cycle[(cycle.index(current) + 1) % len(cycle)] def _sorted_values(values) -> list: """Cycle values in a deterministic order — numeric where the values are numbers. (Accepts a ``valid_values`` dict, iterating its keys, or any iterable of values, e.g. a decoded set.)""" try: return sorted(values, key=float) except (TypeError, ValueError): return list(values) class Parameter[TData = Any, V = Any](UUIdentifable): """A device parameter. Generic over what its integration keeps about it, ``integration_data``, typed as ``TData`` (a bare ``Parameter`` holds any), and over its value type ``V`` — ``value``, the keys of ``valid_values``, and ``default_value`` all share ``V`` (an ``int`` parameter has ``int`` labels and an ``int`` default, a ``str`` parameter has ``str`` throughout, etc.).""" id: UUID name: str # Manufacturer-provided, read-only description (for display / tooltips). Integrations set it # when the protocol exposes one; the Hub never edits it. description: str | None = None # User-editable free-text note, stored MajorDom-side only (never sent to the device). note: str | None = None data_type: ParameterDataType unit: ParameterUnit = ParameterUnit.plain # TODO: consider making str in case of an unsupported value (e.g. version mismatch). Alternativelely, consider adding a case like unknown role: ParameterRole visibility: ParameterVisibility # mainly for UX # value constraints (value for nubmers, char length for string, byte length for data) min_value: int | float | None = None max_value: int | float | None = None min_step: int | float | None = None # Allowed values -> display labels (an enum's members, or labelled presets). Keys are the same # type V as `value`. Mostly for enums; numeric parameters usually use min/max/step instead. valid_values: dict[V, str] | None = None fields: list[Any] | None = None # sub-parameters (Parameter instances) for data_type=struct # Integrations that expose commands with arguments (e.g. Matter) model the command itself as a # Parameter and each of its arguments as a nested Parameter in `fields` — command=parameter, arg=sub-parameter. # The main-parameter tap value(s): one value is a button, a set is a cycle (2 = toggle, # 3+ = cycle). Same value type V as `value`. See `main_cycle` / `can_be_main_parameter`. default_value: set[V] | V | None = None integration_data: TData @field_validator("default_value", mode="before") @classmethod def _coerce_default_value_array_to_set(cls, v: Any) -> Any: """A set default dumps to a JSON array. Validated back from that dict (not from a JSON string) with ``V`` unbound, the union matches the list as a single ``V`` and the cycle silently becomes a one-element button. No data type has a list value, so an array here is always the set.""" return set(v) if isinstance(v, list | tuple) else v @field_validator("valid_values", mode="before") @classmethod def _coerce_valid_values_keys(cls, v, info): """Coerce `valid_values` keys to the parameter's value type. JSON object keys are always strings, so a stored ``{0: "off"}`` (int enum) comes back as ``{"0": "off"}`` — without a concrete ``V`` (heterogeneous parameter lists are used unparametrized) Pydantic can't recover the type. Drive it off ``data_type`` instead, so keys match ``value``.""" if not isinstance(v, dict): return v coerce = { ParameterDataType.integer: int, ParameterDataType.enum: int, ParameterDataType.decimal: float, ParameterDataType.bool: bool, }.get(info.data.get("data_type")) if coerce is None: return v out = {} for key, label in v.items(): try: out[coerce(key)] = label except (TypeError, ValueError): out[key] = label return out @property def can_be_main_parameter(self) -> bool: """Whether this parameter can be a device's one-tap ``main_parameter`` (the room-tile shortcut). Requires ``user`` visibility — the main action is the most exposed control of all, so a settings/system parameter is never a candidate. Beyond that, eligible when a tap can do something meaningful: - ``bool`` — a toggle (each tap flips it); ``none`` — a button (fires the command); - ``valid_values`` set (an enum) — a **cycle** through its values; - ``default_value`` set — one value is a button, a set is a cycle (2 = toggle, 3+ = cycle) for ANY data type (see :func:`next_main_parameter_value`). """ return self.visibility == ParameterVisibility.user and bool( self.data_type in (ParameterDataType.bool, ParameterDataType.none) or self.default_value is not None or self.valid_values ) @property def main_cycle(self) -> list | None: """The ordered values a main-parameter tap cycles through, or ``None`` when a tap isn't a cycle (a ``none`` command button, or nothing to derive from). Derivation, first match: - ``default_value`` -> its values (a set is a cycle; a single value is a one-element button); - ``valid_values`` -> its keys; - ``bool`` -> ``[False, True]`` (a toggle). Values are ordered numerically where possible, so e.g. off(0) -> on(4) -> wraps. """ if self.default_value is not None: if isinstance(self.default_value, set): return _sorted_values(self.default_value) return [self.default_value] if self.valid_values: return _sorted_values(self.valid_values) if self.data_type == ParameterDataType.bool: return [False, True] return None # @classmethod # def from_orm(cls, obj): # if isinstance(obj, DeviceModelParameter): # return super().model_validate(obj.parameter) # else: # return super().model_validate(obj) class ParameterVisibilityPatch(Base): visibility: ParameterVisibility class ParameterState[TData = Any, V = Any](Parameter[TData, V]): """A parameter plus its current ``value`` (same type ``V`` as the parameter's labels/default). Values are pythonic and serialize natively (Pydantic handles JSON — a ``set`` default_value becomes an array, etc.). The Hub persists them as JSON; integrations set ``value`` directly. """ value: V | None = None # device_id: UUID ================================================================================ # FILE: majordom_integration_sdk/schemas/settings.py ================================================================================ """How a settings model marks its fields for the host.""" from enum import StrEnum class SettingsExtraField(StrEnum): """The JSON schema keywords a settings field is marked with: ``Field(json_schema_extra={Extra.read_only: True})`` with ``from majordom_integration_sdk import SettingsExtraField as Extra``.""" read_only = "readOnly" # the peripheral fills it in itself; never the user, never kept write_only = "writeOnly" # the user sets it, nothing reads it back: a secret ================================================================================ # FILE: majordom_integration_sdk/spec_drift.py ================================================================================ """Source-agnostic spec-drift diffing — the shared engine behind the MVD canary and the zha / matter-HA harvest refreshers. A "spec" here is any ``dict`` keyed by an identity (e.g. ``(cluster_id, attribute_id)``) whose values are the harvested judgment. :func:`diff_specs` compares a freshly-produced spec against the committed baseline and tiers every change by risk, mirroring how Dependabot tiers a version bump: ADD a key that didn't exist — low risk (reveals a previously-uncurated item) REMOVE a key that disappeared — medium (something we surfaced may vanish) RECLASSIFY an existing key's value changed — HIGH (changes what current users already see) CI runs the harvester, calls :func:`diff_specs` against the vendored artifact, and opens a Dependabot-style PR when anything changed — highlighting RECLASSIFY at the top for human review. """ from __future__ import annotations from collections.abc import Callable, Hashable, Mapping from dataclasses import dataclass from typing import Any # Generic over the key type — `Mapping` is invariant in its key, so a plain # `Mapping[Hashable, Any]` would reject perfectly valid concrete specs like # `dict[tuple[int, int], str]`. @dataclass(frozen=True) class DriftReport[K: Hashable]: added: dict[K, Any] removed: dict[K, Any] reclassified: dict[K, tuple[Any, Any]] # key -> (old, new) @property def is_empty(self) -> bool: return not (self.added or self.removed or self.reclassified) @property def has_high_risk(self) -> bool: """RECLASSIFY changes an existing item's judgment — the only tier that can silently alter what current users already see, so it always warrants human review.""" return bool(self.reclassified) def render(self, *, source: str = "spec", key_label: Callable[[K], str] | None = None) -> str: """Render a human-readable drift summary. ``key_label`` optionally resolves a key to a human name (e.g. a raw ``(cluster_id, attribute_id)`` -> ``"Chime.SelectedChime"``) so a reviewer reading the PR body sees what actually changed, not just numeric ids. It's kept out of the engine because the mapping is integration-specific (chip bindings for matter, zigpy for zha); each canary passes its own. A resolver that raises or returns falsy for a key falls back to the bare id. """ def tag(key: K) -> str: label = None if key_label is not None: try: label = key_label(key) except Exception: # noqa: BLE001 - a name lookup must never break the drift report label = None return f"{label} {key!r}" if label else f"{key!r}" if self.is_empty: return f"[{source}] no drift" lines = [ f"[{source}] drift: +{len(self.added)} added -{len(self.removed)} removed " f"~{len(self.reclassified)} reclassified" ] # RECLASSIFY first — it's the high-risk tier. for key, (old, new) in sorted(self.reclassified.items(), key=lambda kv: repr(kv[0])): lines.append(f" ~ RECLASSIFY {tag(key)}: {old!r} -> {new!r}") for key, val in sorted(self.added.items(), key=lambda kv: repr(kv[0])): lines.append(f" + ADD {tag(key)}: {val!r}") for key, val in sorted(self.removed.items(), key=lambda kv: repr(kv[0])): lines.append(f" - REMOVE {tag(key)}: {val!r}") return "\n".join(lines) def diff_specs[K: Hashable](current: Mapping[K, Any], baseline: Mapping[K, Any]) -> DriftReport[K]: """Diff a freshly-harvested ``current`` spec against the committed ``baseline``.""" added = {k: current[k] for k in current if k not in baseline} removed = {k: baseline[k] for k in baseline if k not in current} reclassified = {k: (baseline[k], current[k]) for k in current if k in baseline and current[k] != baseline[k]} return DriftReport(added=added, removed=removed, reclassified=reclassified) ================================================================================ # FILE: majordom_integration_sdk/testing/__init__.py ================================================================================ """Shared test doubles for integration test suites. Both the Hub's own integration tests and third-party ``integration-*`` packages import these instead of reinventing them, so every integration is exercised through the same harness: - :class:`RecordingControllerOutput` — a spy implementing every ``ControllerOutput`` callback, capturing what a controller reports back to the Hub: set it as its ``output``. - :class:`FakePeripheral` — a peripheral that records how it is run: what it needs and provides (endpoints and the peripherals it brings along) is set per test, its starts can fail, its hooks answer as told. - :class:`RecordingPeripheralOutput` — what any other peripheral tells the runtime, as its ``output``; :class:`RecordingRuntimeOutput` — what the runtime reports to the Hub. - :class:`FakeCompose` — the container host without Docker, for the services an integration provides. - Offline doubles of every capability (no radios/sockets touched): :class:`FakeBLESource` for the Bluetooth router to hear through (``router.add_source(source)``), :class:`FakeBLERouter`, :class:`FakeZeroconf` (the ``discovery`` extra) and :class:`FakeSSDP`. Each provides itself as ``.endpoint``, to bind as the controller's peripherals: ``Peripherals({"ble": router.endpoint})``. - :func:`build_test_platform` — assembles a ``Platform`` with an in-memory device repository (its ``store`` yours to read), an id check over that store, temp-dir storage and the facts you give, so a test can drive a controller (or any peripheral) exactly as the Hub would. """ from __future__ import annotations import functools import tempfile from collections.abc import Callable, Iterable, Mapping, Sequence from pathlib import Path from typing import TYPE_CHECKING, Any, cast from uuid import UUID from pydantic import BaseModel from majordom_integration_sdk.capabilities.ble import BLEConnection, BLEDiscoveryListener, BLEMatcher, OnAdvertisement from majordom_integration_sdk.controller.output import ControllerOutput, IntegrationError from majordom_integration_sdk.errors import DeviceIdTakenError from majordom_integration_sdk.peripherals import Endpoint, Need, NoSettings, Peripheral, PeripheralChange, Service from majordom_integration_sdk.platform import Platform from majordom_integration_sdk.repository.memory import DeviceRepositoryMemory from majordom_integration_sdk.runtime.peripherals.providers.ble.router import BLEService from majordom_integration_sdk.runtime.peripherals.providers.ssdp import SSDPDiscoveryService from majordom_integration_sdk.runtime.peripherals.services.compose import Compose from majordom_integration_sdk.schemas.credentials import WifiCredentials from majordom_integration_sdk.schemas.device import DeviceState, Discovery from majordom_integration_sdk.schemas.event import Event from majordom_integration_sdk.schemas.notification import Notification if TYPE_CHECKING: from majordom_integration_sdk.controller.output import AnyController as _Controller from majordom_integration_sdk.runtime import PeripheralStatus class RecordingControllerOutput(ControllerOutput): """Captures every callback a controller makes, for assertions in tests.""" def __init__(self): self.received_discoveries: list[Discovery] = [] self.updated_discoveries: list[Discovery] = [] self.lost_discoveries: list[UUID] = [] self.connected_devices: list[UUID] = [] # the ids passed, physical ones from integrations self.lost_devices: list[UUID] = [] # the ids passed, physical ones from integrations self.events: list[Event] = [] self.errors: dict[str, IntegrationError] = {} # the active ones, by id self.error_log: list[IntegrationError | str] = [] # every report, and the id of every resolve self.notifications: list[Notification] = [] self.provided_changes: list[_Controller] = [] # every time one said what it provides changed async def controller_did_receive_discovery(self, controller: _Controller, discovery: Discovery): self.received_discoveries.append(discovery) async def controller_did_update_discovery(self, controller: _Controller, discovery: Discovery): self.updated_discoveries.append(discovery) async def controller_did_lose_discovery(self, controller: _Controller, discovery_id: UUID): self.lost_discoveries.append(discovery_id) async def controller_did_connect_device( self, controller: _Controller, *, physical_id: UUID | None = None, device_id: UUID | None = None ): self.connected_devices.append(cast(UUID, physical_id or device_id)) async def controller_did_lose_device( self, controller: _Controller, *, physical_id: UUID | None = None, device_id: UUID | None = None ): self.lost_devices.append(cast(UUID, physical_id or device_id)) async def controller_did_receive_events(self, controller: _Controller, events: Iterable[Event]): self.events.extend(events) async def controller_did_encounter_error(self, controller: _Controller, error: IntegrationError): self.errors[error.id] = error self.error_log.append(error) async def controller_did_resolve_error(self, controller: _Controller, error_id: str): self.errors.pop(error_id, None) self.error_log.append(error_id) async def controller_did_emit_notification(self, controller: _Controller, notification: Notification): self.notifications.append(notification) async def controller_did_change_provided(self, controller: _Controller): self.provided_changes.append(controller) class FakePeripheral(Peripheral): """A peripheral that records how it is run (``calls``: "start", "stop") and the changes it hears. Its first ``failures`` starts raise; ``answer`` is what its hooks return, or an exception they raise. Change ``provided``, then tell ``output``, as a real one does when a stick is plugged in.""" def __init__( self, name: str, needs: Sequence[Need] = (), provides: Sequence[Endpoint | Peripheral] = (), *, is_on_demand: bool = False, failures: int = 0, answer: bool | Exception = False, settings: type[BaseModel] = NoSettings, ): self.name, self.needs, self.provided = name, list(needs), list(provides) self.is_on_demand = is_on_demand self.failures, self.answer = failures, answer self.settings_model = settings self.calls: list[str] = [] self.changes: list[PeripheralChange | tuple[str, Any]] = [] # needs moved; ("settings"|"platform", before) @property def Settings(self) -> type[BaseModel]: return self.settings_model @property def provides(self) -> Sequence[Endpoint | Peripheral]: return self.provided async def start(self): self.calls.append("start") if self.failures: self.failures -= 1 raise RuntimeError(f"{self.name} broke") async def stop(self): self.calls.append("stop") async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: self.changes.append(change) return self._answer() async def settings_did_change(self, before: Any) -> bool: self.changes.append(("settings", before)) return self._answer() async def platform_facts_did_change(self, before: Any) -> bool: self.changes.append(("platform", before)) return self._answer() def _answer(self) -> bool: if isinstance(self.answer, Exception): raise self.answer return self.answer def __repr__(self) -> str: return f"FakePeripheral({self.name!r})" class RecordingPeripheralOutput: """Captures what peripherals report to whatever runs them: set it as a peripheral's ``output``.""" def __init__(self): self.changed: list[Peripheral] = [] self.learned: list[tuple[Peripheral, Mapping[str, Any]]] = [] self.stopped: list[Peripheral] = [] self.failed: list[tuple[Peripheral, str]] = [] async def peripheral_did_change_provided(self, peripheral: Peripheral): self.changed.append(peripheral) async def peripheral_did_learn(self, peripheral: Peripheral, facts: Mapping[str, Any]): self.learned.append((peripheral, facts)) async def peripheral_did_stop(self, peripheral: Peripheral): self.stopped.append(peripheral) async def peripheral_did_fail(self, peripheral: Peripheral, reason: str): self.failed.append((peripheral, reason)) class RecordingRuntimeOutput: """Captures what a runtime reports to the Hub: every status in order, the last one by key, what was learned, the ones gone.""" def __init__(self): self.statuses: list[tuple[str, PeripheralStatus]] = [] self.learned: list[tuple[str, Mapping[str, Any]]] = [] self.disappeared: list[Peripheral] = [] def peripheral_did_change_status(self, peripheral: Peripheral, status: PeripheralStatus): self.statuses.append((peripheral.key, status)) def peripheral_did_learn(self, peripheral: Peripheral, facts: Mapping[str, Any]): self.learned.append((peripheral.key, facts)) def peripheral_did_disappear(self, peripheral: Peripheral): self.disappeared.append(peripheral) def last(self, key: str) -> PeripheralStatus | None: return next((status for k, status in reversed(self.statuses) if k == key), None) class FakeCompose(Compose): """Docker Compose without Docker: it renders, keeps ports and writes ``compose.json`` as the real one, and a container runs and answers once applied. ``calls`` are the docker commands it would have run.""" def __init__(self, listen_address: str = "127.0.0.1"): super().__init__(listen_address) self.calls: list[tuple[str, ...]] = [] async def _docker(self, *args: str) -> str: self.calls.append(args) return "\n".join(self._running) if "ps" in args else "" async def _is_up(self, service: Service) -> bool: return service.name in self._running class FakeSSDP(SSDPDiscoveryService): """Real registration bookkeeping, but ``start``/``stop`` touch no network.""" async def start(self): pass async def stop(self): pass class FakeBLERouter(BLEService): """A router with no radio unless given `FakeBLESource`s; ``start``/``stop`` run no background tasks.""" @property def registrations(self) -> list[tuple[BLEDiscoveryListener, list[BLEMatcher]]]: """Every listener registered (and not cancelled) with what it listens for, as a copy.""" return [(listener, list(matchers)) for listener, matchers in self._listeners] async def start(self): await self._follow_bound() self._is_running = True await self._start_sources() async def stop(self): self._is_running = False await self._stop_sources() def __getattr__(name: str): if name == "FakeZeroconf": # the discovery extra (zeroconf): only for the suites that use it from majordom_integration_sdk.runtime.peripherals.providers.zeroconf import ZeroconfDiscoveryService class FakeZeroconf(ZeroconfDiscoveryService): """Real registration bookkeeping, but ``start``/``stop`` touch no network.""" async def start(self): pass async def stop(self): pass globals()[name] = FakeZeroconf return FakeZeroconf raise AttributeError(f"module {__name__!r} has no attribute {name!r}") class FakeBLESource: """A Bluetooth radio for tests: ``advertise`` feeds the service it serves, ``connect`` returns ``connection`` (or fails when there is none). Use with ``BLEService(sources=[...])``.""" def __init__( self, name: str = "fake", connection: BLEConnection | None = None, is_pairable: bool = False, free_slots: int | None = None, is_loss_reported: bool = False, ): self.name = name self.connection = connection self.is_pairable = is_pairable self.free_slots = free_slots self.is_loss_reported = is_loss_reported self.on_advertisement: OnAdvertisement | None = None self.connected: list[str] = [] async def start(self, on_advertisement: OnAdvertisement): self.on_advertisement = on_advertisement async def stop(self): self.on_advertisement = None async def connect(self, address: str, on_disconnect: Callable[[], None]) -> BLEConnection: if self.connection is None: raise ConnectionError(f"{self.name} can't reach {address}") self.connected.append(address) return self.connection def advertise( self, address: str, rssi: int = -60, local_name: str | None = None, service_uuids: list[str] | None = None, service_data: dict[str, bytes] | None = None, manufacturer_data: dict[int, bytes] | None = None, ): from bleak.backends.device import BLEDevice # the ble extra from bleak.backends.scanner import AdvertisementData assert self.on_advertisement, f"{self.name} isn't listening" adv = AdvertisementData( local_name, manufacturer_data or {}, service_data or {}, service_uuids or [], None, rssi, () ) self.on_advertisement(BLEDevice(address, local_name, self.name), adv) # details: the radio def build_test_platform( documents_root: Path | None = None, *, region: str | None = None, wifi: WifiCredentials | None = None, thread_dataset: str | None = None, store: dict[UUID, dict[str, Any]] | None = None, ) -> Platform: """Assemble a ``Platform`` wired entirely with offline test doubles, as the Hub gives it to every peripheral: an in-memory repository each controller sees only its own devices of, scoped by its key, and the facts given. Pass ``documents_root`` as the root of the peripherals' folders; a fresh temp folder otherwise, removed when the process ends. Pass ``store`` to see every device kept there: ``DeviceRepositoryMemory(store=store)``. Its ``check_device_id`` takes any record in ``store`` but the draft's own (``draft.id``) for another holder of the physical id: a test seeds the store with the record a collision should hit (``"is_paired": False`` in it for an unpaired one; paired otherwise). """ store = store if store is not None else {} async def check_device_id(physical_id: UUID, draft: DeviceState): for device_id, record in store.items(): if record.get("physical_id") == str(physical_id) and device_id != draft.id: raise DeviceIdTakenError(physical_id, device_id, record.get("name", ""), record.get("is_paired", True)) return Platform( documents_root=documents_root or Path(tempfile.mkdtemp(dir=_temp_root().name)), make_device_repository=lambda key: DeviceRepositoryMemory(key, store).session(), check_device_id=check_device_id, region=region, wifi=wifi, thread_dataset=thread_dataset, ) @functools.cache def _temp_root() -> tempfile.TemporaryDirectory[str]: """Where the platforms built without a root keep their folders, one each: removed when the process ends.""" return tempfile.TemporaryDirectory(prefix="majordom-sdk-test-") __all__ = [ "RecordingControllerOutput", "FakePeripheral", "RecordingPeripheralOutput", "RecordingRuntimeOutput", "FakeBLESource", "FakeBLERouter", "FakeZeroconf", "FakeSSDP", "FakeCompose", "build_test_platform", ] ================================================================================ # FILE: pyproject.toml ================================================================================ [project] name = "majordom-integration-sdk" version = "0.4.0" description = "Models, protocols, tooling and the runtime for building and running MajorDom integrations." authors = [{ name = "Mark Parker", email = "mark@parker-programs.com" }] readme = "README.md" license = "Apache-2.0" license-files = ["LICENSE"] keywords = ["majordom", "smart-home", "home-automation", "iot", "integration", "sdk", "device-controller", "matter", "zigbee", "homekit"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Home Automation", "Topic :: Software Development :: Libraries :: Application Frameworks", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.13", "Operating System :: OS Independent", ] requires-python = ">=3.13,<4.0" dependencies = [ "pydantic (>=2.14.3,<3.0)", "python-slugify", ] [project.optional-dependencies] # Interactive standalone runner: `majordom_integration_sdk.dev.run_cli`. Kept out of the base # install (the SDK is a runtime dep of every integration) — `pip install "majordom-integration-sdk[cli]"`. cli = ["typer-shell (>=0.2)", "rich (>=13)"] # The runtime (`majordom_integration_sdk.runtime`): radios, firmware, services. The Hub and the dev runner install it. runtime = ["pyserial (>=3.5)"] # The Bluetooth router's adapters (bleak; dbus-fast pairs through BlueZ on Linux). ble = ["bleak (>=0.22)", "dbus-fast (>=2.0) ; sys_platform == 'linux'"] # DNS-SD over mDNS (zeroconf). discovery = ["zeroconf (>=0.153.0)"] [project.urls] Homepage = "https://majordom.io" Documentation = "https://docs.majordom.io/device-integration" Repository = "https://github.com/MajorDom-Systems/integration-sdk" Issues = "https://github.com/MajorDom-Systems/integration-sdk/issues" [dependency-groups] dev = [ "poethepoet (>=0.49.0,<1.0.0)", "ty", # type checker; swap for mypy/pyright by editing the `check` task below "ruff", "pip-audit", # dependency vuln scan — gates release (not everyday CI); run locally with `poetry run pip-audit` "pytest>=9.2.0", "pytest-asyncio", "pytest-cov", "pytest-timeout", "pytest-repeat", "pytest-benchmark", "pytest-profiling", "pytest-resource-usage", "coverage", "pympler", # object memory introspection, leak hunting "psutil", # process/system resource usage "faker", # realistic fake data for tests "typer-shell", # the `cli` extra — installed in dev so ty/ruff check dev/cli.py "rich", "pyserial", # the `runtime`, `ble` and `discovery` extras, for the same reason "bleak", "zeroconf", ] [build-system] requires = ["poetry-core>=2.0.0,<3.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] requires-poetry = ">=2.0" packages = [{ include = "majordom_integration_sdk" }] include = [{ path = "majordom_integration_sdk/runtime/peripherals/services/images", format = ["sdist", "wheel"] }] # The BlueZ agent's dbus-fast comes with bleak on Linux only [tool.ty.analysis] allowed-unresolved-imports = ["dbus_fast.**"] # schemas/ and the providers (BLE, DNS-SD, SSDP) are lifted verbatim from the Hub, which type-checks them under # mypy (they carry mypy-style `# type: ignore` comments ty doesn't read). Exempt just those # rules for just those paths — all SDK-native code stays fully checked. Re-home in the Hub. [[tool.ty.overrides]] include = [ "majordom_integration_sdk/schemas/**", "majordom_integration_sdk/runtime/peripherals/providers/**", ] [tool.ty.overrides.rules] invalid-return-type = "ignore" invalid-assignment = "ignore" invalid-argument-type = "ignore" unsupported-base = "ignore" # The repository's typed reads use the `as_: type[T] = Device` idiom (same as the Hub's own # repository) so callers get `get(id, as_=MyDevice) -> MyDevice` while the bare `get(id)` # still returns a Device. ty rejects a concrete default for a TypeVar-typed parameter; the # alternative is @overload on every read across the protocol and both implementations. [[tool.ty.overrides]] include = ["majordom_integration_sdk/repository/**"] [tool.ty.overrides.rules] invalid-parameter-default = "ignore" # The runtime's tests stand plain objects in for bleak's (a BleakClient): ty can't match them [[tool.ty.overrides]] include = ["tests/runtime/**"] [tool.ty.overrides.rules] invalid-argument-type = "ignore" [tool.pytest.ini_options] asyncio_mode = "auto" pythonpath = ["."] filterwarnings = ["once"] [tool.coverage.run] omit = ["tests/*"] [tool.ruff] line-length = 120 indent-width = 4 [tool.ruff.lint] select = [ "E", # pycodestyle "F", # pyflakes "UP", # pyupgrade "B", # flake8-bugbear "SIM", # flake8-simplify "I", # isort ] fixable = ["ALL"] [tool.ruff.format] quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "tests/*" = ["E402"] # schemas/ and the DNS-SD / SSDP providers are lifted verbatim from the Hub and maintained under its lint # rules; abstract_controller.py keeps the Hub's long-form docstrings. Exempt only the # house-style rules for these paths — SDK-native code stays fully linted. "majordom_integration_sdk/schemas/*" = ["E501", "UP042"] "majordom_integration_sdk/runtime/peripherals/providers/{zeroconf,ssdp}.py" = ["E501", "SIM102", "SIM105"] "majordom_integration_sdk/controller/abstract_controller.py" = ["E501"] [tool.poe.tasks.install] shell = """ poetry install echo '#!/bin/sh\npoetry run poe check' > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit echo "Pre-commit hook installed." """ [tool.poe.tasks.check] shell = """ code=0 echo "\nRunning ruff lint:" poetry run ruff check --fix || code=1 echo "\nRunning ruff format:" poetry run ruff format || code=1 echo "\nRunning ty:" poetry run ty check || code=1 echo "\nRunning pytest:" poetry run pytest --cov=majordom_integration_sdk --cov-report=xml || code=1 echo "\nRunning poetry build:" poetry build || code=1 echo "\nRunning poetry check:" poetry check || code=1 ${ci:+git diff --exit-code} || code=1 exit $code """ args = [{ name = "ci", type = "boolean" }] ================================================================================ # FILE: tests/conftest.py ================================================================================ """Shared fixtures for the SDK's own test suite.""" import pytest from factories import make_device_state from majordom_integration_sdk.schemas.device import DeviceState @pytest.fixture def device_state() -> DeviceState: return make_device_state() ================================================================================ # FILE: tests/factories.py ================================================================================ """Factories for the SDK's own test suite: tests import them, as ``tests/runtime`` has a conftest of its own.""" from uuid import UUID, uuid4 from majordom_integration_sdk.schemas.device import DeviceState from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterState, ParameterVisibility, ) def make_parameter_state( *, id: UUID | None = None, name: str = "Power", data_type: ParameterDataType = ParameterDataType.bool, role: ParameterRole = ParameterRole.control, visibility: ParameterVisibility = ParameterVisibility.user, ) -> ParameterState: state = ParameterState( id=id or uuid4(), name=name, data_type=data_type, role=role, visibility=visibility, integration_data=None, ) if data_type is ParameterDataType.bool: state.value = True return state def make_device_state( *, id: UUID | None = None, physical_id: UUID | None = None, integration: str = "example", name: str = "Lamp", parameters: list[ParameterState] | None = None, ) -> DeviceState: return DeviceState( id=id or uuid4(), physical_id=physical_id or uuid4(), name=name, room_id=uuid4(), transport="wifi", integration=integration, manufacturer="ACME", parameters=parameters if parameters is not None else [make_parameter_state()], ) ================================================================================ # FILE: tests/runtime/conftest.py ================================================================================ import pytest from support import STARTED from majordom_integration_sdk.runtime import runtime as module from majordom_integration_sdk.runtime.peripherals.services import builtin, compose @pytest.fixture(autouse=True) def quick_retries(monkeypatch): monkeypatch.setattr(module, "RETRY_DELAYS", (0.01, 0.01, 0.01)) monkeypatch.setattr(compose, "READY_POLL", 0.01) monkeypatch.setattr(builtin, "POLL", 0.01) @pytest.fixture(autouse=True) async def stopped(): yield while STARTED: await STARTED.pop().stop() ================================================================================ # FILE: tests/runtime/support.py ================================================================================ """Driving a runtime in tests: run it, wait for what it started, tell it what changed.""" import asyncio from collections.abc import Callable from pathlib import Path from majordom_integration_sdk import Peripheral from majordom_integration_sdk.runtime import PeripheralState, Runtime from majordom_integration_sdk.testing import build_test_platform async def settle(runtime: Runtime): """Let every start in flight finish, and the runtime act on it.""" while pending := [task for task in runtime._tasks if not task.done()]: await asyncio.gather(*pending, return_exceptions=True) async def until(runtime: Runtime, condition: Callable[[], bool], timeout: float = 2, settled: bool = True): """Wait for what a timer does, e.g. a retry; then, if ``settled``, for what it set off.""" async with asyncio.timeout(timeout): while not condition(): await asyncio.sleep(0.005) if settled: await settle(runtime) STARTED: list[Runtime] = [] # stopped after each test async def run(path: Path, *peripherals: Peripheral, settled: bool = True, **kwargs) -> Runtime: """A runtime of ``peripherals``, started; with ``settled``, once every start it set off returned. Its platform keeps the documents under ``data/peripherals`` unless given.""" kwargs.setdefault("platform", build_test_platform(path / "data" / "peripherals")) runtime = Runtime(path / "data", peripherals, **kwargs) STARTED.append(runtime) await runtime.start() if settled: await settle(runtime) return runtime async def changed(runtime: Runtime, peripheral: Peripheral): """``peripheral`` changed what it provides or brings along on its own, and told the runtime.""" await peripheral.output.peripheral_did_change_provided(peripheral) await settle(runtime) def state(runtime: Runtime, peripheral: Peripheral) -> PeripheralState: return runtime.status(peripheral).state ================================================================================ # FILE: tests/runtime/test_binding.py ================================================================================ """How the runtime binds needs: in the order it is given, single-use endpoints once, and why a need stays unbound.""" import json import pytest from support import run, settle from majordom_integration_sdk import Endpoint, Need from majordom_integration_sdk.capabilities import BLE_ROUTER from majordom_integration_sdk.runtime import PeripheralState, PeripheralStatus from majordom_integration_sdk.runtime import StatusKind as K from majordom_integration_sdk.testing import FakePeripheral ADAPTERS = [Endpoint("ble", "bluez", "hci0"), Endpoint("ble", "bluez", "hci1")] ROUTER = Endpoint("ble", "router", "router", is_shared=True, instance=object()) def adapters() -> FakePeripheral: return FakePeripheral("bluetooth-adapters", provides=ADAPTERS) def router() -> FakePeripheral: return FakePeripheral( "ble-router", [Need("ble", ["bluez"], is_many=True, is_required=False)], [ROUTER], is_on_demand=True, answer=True, ) async def test_a_many_need_binds_every_free_matching_endpoint(tmp_path): sniffer = FakePeripheral("sniffer", [Need("ble", ["bluez"], is_many=True)]) runtime = await run(tmp_path, adapters(), sniffer) assert runtime.bound(sniffer) == {"ble": ADAPTERS} assert sniffer.peripherals.endpoints("ble") == ADAPTERS with pytest.raises(TypeError, match="endpoints"): sniffer.peripherals.endpoint("ble") assert runtime.providers(sniffer) == {"ble": ["bluetooth-adapters", "bluetooth-adapters"]} # one per endpoint async def test_a_many_need_that_finds_nothing_is_unbound(tmp_path): sniffer = FakePeripheral("sniffer", [Need("lora", is_many=True)]) runtime = await run(tmp_path, sniffer) assert runtime.unbound(sniffer) == {"lora": "need lora/*: nothing offers it"} async def test_an_in_process_provider_is_a_shared_endpoint_carrying_itself(tmp_path): ble, matter, homekit = router(), FakePeripheral("matter", [Need("ble", ["router"])]), None homekit = FakePeripheral("homekit", [Need("ble", ["router"])]) runtime = await run(tmp_path, ble, matter, homekit) instance = ROUTER.instance assert matter.peripherals.instance(BLE_ROUTER) is instance and homekit.peripherals.instance(BLE_ROUTER) is instance assert runtime.users(ble) == ["matter", "homekit"] async def test_the_first_given_takes_every_adapter_and_the_others_hear_what_to_need(tmp_path): ble, raw = router(), FakePeripheral("raw", [Need("ble", ["bluez"])]) matter = FakePeripheral("matter", [Need("ble", ["router"])]) runtime = await run(tmp_path, adapters(), ble, raw, matter) assert ble.peripherals.endpoints("ble") == ADAPTERS assert runtime.status(matter).state == PeripheralState.RUNNING # the others run on assert runtime.unbound(raw) == { "ble": 'need ble/bluez: every provider taken by ble-router — use Need("ble", ["router"])' } async def test_a_router_nothing_uses_leaves_the_adapters_to_who_needs_them_raw(tmp_path): ble, raw = router(), FakePeripheral("raw", [Need("ble", ["bluez"])]) runtime = await run(tmp_path, adapters(), ble, raw) assert runtime.status(ble) == PeripheralStatus(PeripheralState.WAITING, K.UNUSED, "nothing that runs uses it") assert runtime.status(raw).state == PeripheralState.RUNNING assert raw.peripherals.endpoint("ble") == ADAPTERS[0] async def test_on_demand_peripherals_binding_only_each_other_dont_run(tmp_path): a = FakePeripheral("a", [Need("b", is_required=False)], [Endpoint("a", is_shared=True)], is_on_demand=True) b = FakePeripheral("b", [Need("a", is_required=False)], [Endpoint("b", is_shared=True)], is_on_demand=True) runtime = await run(tmp_path, a, b) assert ( runtime.status(a) == runtime.status(b) == PeripheralStatus(PeripheralState.WAITING, K.UNUSED, "nothing that runs uses it") ) assert a.calls == b.calls == [] async def test_a_single_use_endpoint_goes_to_the_first_given_and_then_to_the_next(tmp_path): stick = FakePeripheral("stick", provides=[Endpoint("zigbee", "ezsp", "/dev/ttyUSB0")]) first, second = FakePeripheral("first", [Need("zigbee")]), FakePeripheral("second", [Need("zigbee")]) runtime = await run(tmp_path, stick, first, second) assert runtime.status(first).state == PeripheralState.RUNNING assert runtime.status(second) == PeripheralStatus( PeripheralState.WAITING, K.NEEDS_UNBOUND, "need zigbee/*: every provider taken by first" ) await runtime.disable(first) await settle(runtime) assert runtime.status(second).state == PeripheralState.RUNNING async def test_an_adapter_goes_by_the_order_given_alone(tmp_path): (tmp_path / "data").mkdir() reserved = {"settings": {}, "reserved": {"matterjs-server": {"ble": "hci1"}}} # kept by an older runtime (tmp_path / "data" / "state.json").write_text(json.dumps(reserved)) ble = router() server = FakePeripheral("matterjs-server", [Need("ble", ["bluez"])], [Endpoint("matter", "x", "ws")]) runtime = await run(tmp_path, adapters(), ble, FakePeripheral("matter", [Need("ble", ["router"])]), server) assert ble.peripherals.endpoints("ble") == ADAPTERS assert runtime.unbound(server) == { "ble": 'need ble/bluez: every provider taken by ble-router — use Need("ble", ["router"])' } assert "reserved" not in runtime.state and not hasattr(runtime, "reserve") async def test_the_first_given_of_two_providers_serves_a_need(tmp_path): multipan = FakePeripheral("silabs-multiprotocol", provides=[Endpoint("thread", "otbr-rest", "a", is_shared=True)]) otbr = FakePeripheral("otbr", provides=[Endpoint("thread", "otbr-rest", "b", is_shared=True)]) matter = FakePeripheral("matter", [Need("thread")]) runtime = await run(tmp_path, multipan, otbr, matter) assert runtime.providers(matter) == {"thread": "silabs-multiprotocol"} assert not hasattr(runtime, "pin") # the order given and Pinned say what to prefer async def test_a_provider_that_cant_run_says_why(tmp_path): multipan = FakePeripheral( "silabs-multiprotocol", [Need("multipan", ["silabs-cpc"])], [Endpoint("zigbee", "ezsp")], is_on_demand=True ) zigbee = FakePeripheral("zigbee", [Need("zigbee", ["ezsp", "znp"])]) runtime = await run(tmp_path, multipan, zigbee) assert runtime.unbound(zigbee) == { "zigbee": "need zigbee/ezsp|znp: silabs-multiprotocol can't run (need multipan/silabs-cpc: nothing offers it)" } assert runtime.unbound(multipan) == {"multipan": "need multipan/silabs-cpc: nothing offers it"} async def test_a_need_one_that_doesnt_run_could_bind_has_no_reason(tmp_path): host = FakePeripheral("host", provides=[Endpoint("ip", is_shared=True)]) server = FakePeripheral("server", [Need("ip")], [Endpoint("matter")], is_on_demand=True) runtime = await run(tmp_path, host, server) assert runtime.unbound(server) == {} assert runtime.status(server).detail == "nothing that runs uses it" async def test_what_a_firmware_would_serve_through_what_runs_here(tmp_path): multipan = FakePeripheral( "silabs-multiprotocol", [Need("multipan")], [Endpoint("zigbee", "ezsp"), Endpoint("thread", "otbr-rest")], is_on_demand=True, ) runtime = await run(tmp_path, multipan, FakePeripheral("zigbee", [Need("zigbee")])) assert runtime.reach([Endpoint("multipan", "silabs-cpc")]) == ["zigbee"] # thread: no one needs it assert runtime.reach([Endpoint("zwave")]) == [] ================================================================================ # FILE: tests/runtime/test_ble_router.py ================================================================================ """The Bluetooth router: what listeners hear from several radios, and which radio connects.""" import asyncio from unittest.mock import Mock from uuid import UUID import pytest from majordom_integration_sdk.capabilities import BLEBusyError, BLEConnection, BLEDiscoveryInfo, BLEMatcher from majordom_integration_sdk.peripherals import Endpoint, Peripherals from majordom_integration_sdk.runtime.peripherals.providers.ble.router import BLEService from majordom_integration_sdk.testing import FakeBLERouter, FakeBLESource MATTER = UUID("0000fff6-0000-1000-8000-00805f9b34fb") APPLE = 0x004C class Listener: def __init__(self): self.found: list[BLEDiscoveryInfo] = [] self.updated: list[BLEDiscoveryInfo] = [] self.removed: list[BLEDiscoveryInfo] = [] async def ble_did_discover_device(self, ble, info): self.found.append(info) async def ble_did_update_device(self, ble, info): self.updated.append(info) async def ble_did_remove_device(self, ble, info): self.removed.append(info) async def settle(): for _ in range(3): await asyncio.sleep(0) @pytest.fixture async def radios(): near, far = ( FakeBLESource("near", connection=Mock(spec=BLEConnection)), FakeBLESource("far", connection=Mock(spec=BLEConnection)), ) ble = BLEService(sources=[near, far]) await ble.start() yield ble, near, far await ble.stop() async def test_listeners_of_the_same_service_all_hear_it(radios): ble, near, _ = radios first, second = Listener(), Listener() ble.register(first, {MATTER}) ble.register(second, {MATTER}) near.advertise("AA", service_data={str(MATTER): b"\x00"}) await settle() assert len(first.found) == len(second.found) == 1 async def test_matchers_select_by_manufacturer_data_and_name(radios): ble, near, _ = radios homekit, named = Listener(), Listener() ble.register(homekit, [BLEMatcher(manufacturer_id=APPLE, manufacturer_data_start=b"\x06")]) ble.register(named, [BLEMatcher(local_name_prefix="Improv")]) near.advertise("AA", manufacturer_data={APPLE: b"\x10\x05"}) # an iPhone nearby near.advertise("BB", manufacturer_data={APPLE: b"\x06\x31"}, local_name="Improv-1") await settle() assert [i.device.address for i in homekit.found] == ["BB"] assert [i.device.address for i in named.found] == ["BB"] async def test_a_device_heard_by_two_radios_is_one_device_seen_by_the_stronger(radios): ble, near, far = radios listener = Listener() ble.register(listener, {MATTER}) far.advertise("AA", rssi=-90, service_uuids=[str(MATTER)]) near.advertise("AA", rssi=-50, service_uuids=[str(MATTER)], local_name="Bulb") far.advertise("AA", rssi=-90, service_uuids=[str(MATTER)]) # no scan response: no name await settle() assert len(listener.found) == 1 assert [i.source for i in listener.updated] == ["near"] assert ble.devices()[0].advertisement.local_name == "Bulb" async def test_a_device_is_removed_once_no_radio_hears_it(radios): ble, near, far = radios listener = Listener() ble.register(listener, {MATTER}) near.advertise("AA", service_uuids=[str(MATTER)]) await settle() ble._removal_grace_sec = 0 await ble.perform_scan() assert [i.device.address for i in listener.removed] == ["AA"] assert ble.devices() == [] async def test_a_device_whose_radio_is_leased_stays_until_the_lease_ends(radios): ble, near, far = radios listener = Listener() ble.register(listener, {MATTER}) near.advertise("AA", service_uuids=[str(MATTER)]) await settle() ble._removal_grace_sec = 0 async with ble.exclusive("AA", owner="esphome"): # its radio silenced while the user presses the button await ble.perform_scan() assert listener.removed == [] and len(ble.devices()) == 1 await ble.perform_scan() assert [i.device.address for i in listener.removed] == ["AA"] async def test_cancelled_listeners_hear_nothing(radios): ble, near, _ = radios listener = Listener() cancel = ble.register(listener, {MATTER}) cancel() cancel() near.advertise("AA", service_uuids=[str(MATTER)]) await settle() assert listener.found == [] async def test_connects_through_the_stronger_radio_and_falls_back(radios): ble, near, far = radios far.advertise("AA", rssi=-90) near.advertise("AA", rssi=-50) await settle() assert await ble.connect("AA") is near.connection near.connection = None assert await ble.connect("AA") is far.connection far.connection = None with pytest.raises(ConnectionError, match="near.*far"): await ble.connect("AA") async def test_a_lease_takes_the_radio_hearing_the_device_best(radios): ble, near, far = radios far.advertise("AA", rssi=-90) near.advertise("AA", rssi=-50) await settle() async with ble.exclusive("AA", owner="matter") as lease: assert lease.source == "near" assert await lease.connect() is near.connection assert (near.connected, far.connected) == (["AA"], []) async def test_a_lease_stops_only_its_radio_scanning_until_released(radios): ble, near, far = radios near.advertise("AA") await settle() async with ble.exclusive("AA", owner="matter"): assert near.on_advertisement is None assert far.on_advertisement is not None await ble.scan_actively(0) await ble._revive_silent() await ble.add_source(proxy := FakeBLESource("proxy")) assert near.on_advertisement is None assert proxy.on_advertisement is not None assert near.on_advertisement is not None class PausableFakeBLESource(FakeBLESource): def __init__(self, name: str): super().__init__(name) self.calls: list[str] = [] async def start(self, on_advertisement): self.calls.append("start") await super().start(on_advertisement) async def stop(self): self.calls.append("stop") await super().stop() async def pause_scanning(self): self.calls.append("pause") async def resume_scanning(self): self.calls.append("resume") async def test_a_lease_pauses_a_radio_that_can_pause_instead_of_stopping_it(radios): ble, _, _ = radios await ble.add_source(proxy := PausableFakeBLESource("proxy")) proxy.advertise("AA", rssi=-10) await settle() async with ble.exclusive("AA", owner="matter") as lease: assert lease.source == "proxy" assert proxy.calls == ["start", "resume", "pause"] assert proxy.calls == ["start", "resume", "pause", "resume"] async def test_a_radio_that_can_pause_is_paused_exactly_while_leased_across_a_router_restart(radios): """A lease held across a restart keeps its radio subscribed (its connects go through it) and muted; one that ended while the router was stopped leaves it hearing once the router starts.""" ble, _, _ = radios await ble.add_source(proxy := PausableFakeBLESource("proxy")) proxy.advertise("AA", rssi=-10) await settle() async with ble.exclusive("AA", owner="matter"): await ble.stop() await ble.start() assert proxy.on_advertisement is not None and proxy.calls[-1] == "pause" assert proxy.calls[-1] == "resume" async with ble.exclusive("AA", owner="matter"): await ble.stop() await ble.start() assert proxy.on_advertisement is not None and proxy.calls[-1] == "resume" async def test_a_radio_that_can_pause_added_while_leased_is_started_paused(radios): ble, _, _ = radios await ble.add_source(proxy := PausableFakeBLESource("proxy")) proxy.advertise("AA", rssi=-10) await settle() async with ble.exclusive("AA", owner="matter"): await ble.add_source(again := PausableFakeBLESource("proxy")) # its node reconnected: another source assert again.calls == ["start", "pause"] # subscribed for the lease's connects, and muted assert again.calls == ["start", "pause", "resume"] and again.on_advertisement is not None async def test_a_second_lease_waits_then_takes_the_next_radio(radios): ble, near, far = radios far.advertise("AA", rssi=-90) near.advertise("AA", rssi=-50) await settle() async with ble.exclusive("AA", owner="matter"): started = asyncio.get_running_loop().time() async with ble.exclusive("AA", owner="improv", wait=0.05) as lease: assert lease.source == "far" assert asyncio.get_running_loop().time() - started >= 0.05 async def test_a_connect_skips_leased_radios_and_fails_when_all_are(radios): ble, near, far = radios far.advertise("AA", rssi=-90) near.advertise("AA", rssi=-50) await settle() async with ble.exclusive("AA", owner="matter"): assert await ble.connect("AA") is far.connection async with ble.exclusive("AA", owner="improv", wait=0): with pytest.raises(BLEBusyError): await ble.connect("AA") async def test_a_lease_cycles_through_busy_radios_until_it_gives_up(radios): ble, near, far = radios far.advertise("AA", rssi=-90) near.advertise("AA", rssi=-50) await settle() async with ble.exclusive("AA", owner="matter"), ble.exclusive("AA", owner="matter", wait=0): started = asyncio.get_running_loop().time() with pytest.raises(BLEBusyError, match="hear AA are busy"): async with ble.exclusive("AA", owner="improv", timeout=0.1, wait=0.02): pass assert asyncio.get_running_loop().time() - started >= 0.1 async def test_a_lease_freed_meanwhile_is_taken_on_the_next_round(radios): ble, near, far = radios near.advertise("AA", rssi=-50) await settle() held = asyncio.Event() async def hold(): async with ble.exclusive("AA", owner="matter"): held.set() await asyncio.sleep(0.03) task = asyncio.create_task(hold()) await held.wait() async with ble.exclusive("AA", owner="improv", wait=0.01) as lease: # only near hears it assert lease.source == "near" await task async def test_a_cancelled_lease_releases_its_radio(radios): ble, near, _ = radios near.advertise("AA") await settle() held = asyncio.Event() async def hold(): async with ble.exclusive("AA", owner="matter"): held.set() await asyncio.Event().wait() task = asyncio.create_task(hold()) await held.wait() task.cancel() with pytest.raises(asyncio.CancelledError): await task assert near.on_advertisement is not None async with ble.exclusive("AA", owner="improv", wait=0) as lease: assert lease.source == "near" async def test_a_lease_cancelled_while_waiting_holds_nothing(radios): ble, near, far = radios near.advertise("AA") await settle() async with ble.exclusive("AA", owner="matter"): waiting = asyncio.create_task(ble.exclusive("AA", owner="improv", wait=1).__aenter__()) await settle() waiting.cancel() with pytest.raises(asyncio.CancelledError): await waiting async with ble.exclusive("AA", owner="improv", wait=0) as lease: assert lease.source == "near" assert near.on_advertisement and far.on_advertisement async def test_a_listener_registered_later_hears_devices_already_around(radios): ble, near, _ = radios near.advertise("AA", service_uuids=[str(MATTER)]) await settle() listener = Listener() ble.register(listener, {MATTER}) await settle() assert [i.device.address for i in listener.found] == ["AA"] def test_a_fake_router_shows_who_registered_for_what(): router = FakeBLERouter() cancel = router.register(listener := Listener(), [MATTER]) registered = [(listener, [BLEMatcher(service_uuid=MATTER)])] assert router.registrations == registered router.registrations.clear() # a copy: reading it changes nothing assert router.registrations == registered cancel() assert router.registrations == [] async def test_a_radio_that_fails_to_stop_is_let_go_of_all_the_same(radios): ble, near, _ = radios class Gone(FakeBLESource): async def stop(self): raise ConnectionError("its node went away") await ble.add_source(Gone("proxy")) await ble.remove_source("proxy") near.advertise("AA", service_uuids=[str(MATTER)]) await settle() assert ble.devices()[0].source == "near" and "proxy" not in ble._candidates("AA") async def test_a_stopped_router_lets_go_of_the_radios_it_was_bound_to(): proxy, given = FakeBLESource("esphome:aa"), FakeBLESource("given") ble = BLEService(sources=[given]) ble.peripherals = Peripherals({"ble": [Endpoint("ble", "esphome-proxy", "esphome:aa", instance=proxy)]}) await ble.start() await ble.stop() assert list(ble._sources) == ["given"] # the runtime binds them anew before its next start ble.peripherals = Peripherals({"ble": []}) # the node went meanwhile await ble.start() assert list(ble._sources) == ["given"] and proxy.on_advertisement is None await ble.stop() async def test_a_silent_radio_is_restarted(radios): ble, near, far = radios near.on_advertisement = None # bluetoothd restarted: the scanner is gone without a word far.advertise("AA") await settle() ble._silence_sec = 0.01 await asyncio.sleep(0.02) far.advertise("AA") await ble._revive_silent() assert near.on_advertisement is not None # listening again async def test_a_silent_radio_whose_loss_is_reported_otherwise_is_never_restarted(): proxy = FakeBLESource("esphome:aa", is_loss_reported=True) # the node's API connection tells when it goes ble = BLEService(sources=[proxy]) await ble.start() hearing = proxy.on_advertisement ble._silence_sec = 0.01 await asyncio.sleep(0.02) # no Bluetooth device around it await ble._revive_silent() assert proxy.on_advertisement is hearing # still subscribed: a restart would drop the links it proxies await ble.stop() async def test_a_local_adapter_stops_scanning_while_it_connects(monkeypatch): from majordom_integration_sdk.runtime.peripherals.providers.ble import bluez as module from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter scanning = [] class Scanner: def __init__(self, **kwargs): pass async def start(self): scanning.append(True) async def stop(self): scanning.append(False) class Client: def __init__(self, device, **kwargs): pass async def connect(self): assert scanning[-1] is False, "connecting while discovering: many adapters stall" monkeypatch.setattr(module, "BleakScanner", Scanner) monkeypatch.setattr(module, "BleakClient", Client) adapter = LocalAdapter("hci0") await adapter.start(lambda device, adv: None) await adapter.connect("AA", lambda: None) assert scanning == [True, False, True] def test_a_local_connection_reports_the_mtu_bluez_negotiated(): from types import SimpleNamespace from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import _BleakConnection # bleak reports BlueZ's MTU as 23 until it is acquired, while every characteristic already knows the real one characteristics = {1: SimpleNamespace(max_write_without_response_size=244)} client = SimpleNamespace(mtu_size=23, services=SimpleNamespace(characteristics=characteristics)) assert _BleakConnection(client, "hci0").mtu == 247 async def test_a_device_is_seen_as_the_strongest_radio_hears_it(radios): ble, near, far = radios far.advertise("AA", rssi=-90, service_uuids=[str(MATTER)]) near.advertise("AA", rssi=-50, service_uuids=[str(MATTER)]) await settle() info = ble.devices()[0] assert (info.source, info.rssi) == ("near", -50) assert info.last_seen > 0 assert info.device.details == "near" # bleak's device as that radio has it async def test_a_service_data_matcher_needs_the_data(radios): ble, near, _ = radios listener = Listener() ble.register(listener, [BLEMatcher(service_data_uuid=MATTER)]) near.advertise("AA", service_uuids=[str(MATTER)]) # only listed: no data to read near.advertise("BB", service_data={str(MATTER): b"\x00"}) await settle() assert [i.device.address for i in listener.found] == ["BB"] @pytest.fixture def scanners(monkeypatch): """The scanners local adapters open: their arguments, in order.""" from majordom_integration_sdk.runtime.peripherals.providers.ble import bluez as module opened: list[dict] = [] class Scanner: def __init__(self, detection_callback=None, scanning_mode="active", bluez=None, **kwargs): self.args = { "mode": scanning_mode, "patterns": (bluez or {}).get("or_patterns"), "on_detection": detection_callback, "scanning": False, } async def start(self): if self.args["mode"] == "passive" and opened and opened[-1].get("refuse_passive"): raise RuntimeError("passive scanning needs BlueZ's advertisement monitor") self.args["scanning"] = True opened.append(self.args) async def stop(self): self.args["scanning"] = False monkeypatch.setattr(module, "BleakScanner", Scanner) return opened async def test_local_adapters_hear_every_advertiser_and_the_matchers_choose(scanners): from bleak.assigned_numbers import AdvertisementDataType as T from bleak.backends.device import BLEDevice from bleak.backends.scanner import AdvertisementData from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter ble = BLEService(sources=[LocalAdapter("hci0")]) matter, everything = Listener(), Listener() ble.register(matter, {MATTER}) ble.register(everything, [BLEMatcher()]) await ble.start() assert scanners[-1]["mode"] == "passive" assert scanners[-1]["patterns"] == [(0, T.FLAGS, b"\x02"), (0, T.FLAGS, b"\x06"), (0, T.FLAGS, b"\x1a")] hear = scanners[-1]["on_detection"] hear(BLEDevice("AA", None, {}), AdvertisementData(None, {APPLE: b"\x10\x05"}, {}, [], None, -60, ())) hear(BLEDevice("BB", None, {}), AdvertisementData(None, {}, {str(MATTER): b"\x00"}, [], None, -60, ())) await settle() assert [i.device.address for i in matter.found] == ["BB"] assert len(everything.found) == 2 await ble.stop() async def test_local_adapters_scan_passively_and_actively_in_bursts(scanners): from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter ble = BLEService(sources=[LocalAdapter("hci0")]) await ble.start() assert scanners[-1]["mode"] == "passive" await ble.scan_actively(0.05) # a pairing window: names come in scan responses assert scanners[-1]["mode"] == "active" await asyncio.sleep(0.1) assert scanners[-1]["mode"] == "passive" await ble.stop() async def test_an_adapter_without_passive_scanning_scans_actively(scanners, caplog): from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter ble = BLEService(sources=[LocalAdapter("hci0")]) await ble.start() await ble.scan_actively(0.01) scanners[-1]["refuse_passive"] = True await asyncio.sleep(0.05) # the burst ends: back to passive, refused assert scanners[-1]["mode"] == "active" assert "can't scan passively" in caplog.text await ble.stop() async def test_a_rescan_waits_until_a_local_adapter_has_connected(scanners, monkeypatch): from majordom_integration_sdk.runtime.peripherals.providers.ble import bluez as module from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter connecting, connected = asyncio.Event(), asyncio.Event() class Client: def __init__(self, device, **kwargs): pass async def connect(self): connecting.set() await connected.wait() monkeypatch.setattr(module, "BleakClient", Client) ble = BLEService(sources=[LocalAdapter("hci0")]) await ble.start() connection = asyncio.create_task(ble.connect("AA")) await connecting.wait() burst = asyncio.create_task(ble.scan_actively(1)) # a pairing window opens meanwhile await settle() assert not any(s["scanning"] for s in scanners), "discovering while connecting: many adapters stall" connected.set() await connection await burst assert [s["mode"] for s in scanners if s["scanning"]] == ["active"] await ble.stop() class ScanModeFakeBLESource(FakeBLESource): def __init__(self, name: str): super().__init__(name) self.modes: list[bool] = [] async def set_scan_mode(self, is_active: bool): self.modes.append(is_active) async def test_a_pairing_window_switches_every_source_that_can_to_active_scanning(): radio = ScanModeFakeBLESource("hci0") ble = BLEService(sources=[radio, FakeBLESource("proxy")]) # one that can't switch is left as it is await ble.start() assert radio.modes == [False] # passive from the start await ble.scan_actively(0.02) assert radio.modes == [False, True] await asyncio.sleep(0.05) assert radio.modes == [False, True, False] await ble.stop() async def test_a_proxy_without_a_free_connection_slot_is_tried_last(): full = FakeBLESource("full", connection=Mock(spec=BLEConnection), free_slots=0) free = FakeBLESource("free", connection=Mock(spec=BLEConnection), free_slots=2) ble = BLEService(sources=[full, free]) await ble.start() full.advertise("AA", rssi=-40) free.advertise("AA", rssi=-80) await settle() await ble.connect("AA") assert (full.connected, free.connected) == ([], ["AA"]) await ble.stop() async def test_the_router_hears_through_the_proxies_an_integration_brings_along(tmp_path): from support import changed, run from majordom_integration_sdk.peripherals import BLEProxy, Need from majordom_integration_sdk.testing import FakePeripheral ble, proxy = BLEService(), FakeBLESource("esphome:aa") esphome = FakePeripheral("esphome", [Need("ble", ["router"], is_required=False)], answer=True) runtime = await run(tmp_path, ble, esphome) esphome.provided.append(BLEProxy(proxy, name="aa:bb")) # a node connected, known by its Bluetooth MAC await changed(runtime, esphome) assert proxy.on_advertisement is not None # heard through assert runtime.peripheral("esphome/aa:bb") is esphome.provided[0] again = FakeBLESource("esphome:aa") # it reconnected: another source under the same name esphome.provided[:] = [BLEProxy(again)] await changed(runtime, esphome) assert proxy.on_advertisement is None and again.on_advertisement is not None esphome.provided.clear() # gone await changed(runtime, esphome) assert again.on_advertisement is None async def test_a_manufacturer_id_alone_selects_devices_that_advertise_no_service(radios): """Ported from feature/ble-manufacturer-filter: HomeKit (HAP-BLE) accessories advertise Apple manufacturer data and no service UUID.""" ble, near, _ = radios by_service, by_manufacturer = Listener(), Listener() ble.register(by_service, {MATTER}) ble.register(by_manufacturer, [BLEMatcher(manufacturer_id=APPLE)]) near.advertise("AA", service_uuids=[str(MATTER)]) near.advertise("BB", manufacturer_data={APPLE: b"\x06\x31"}) near.advertise("CC", manufacturer_data={0x0059: b"\x01"}) await settle() assert [i.device.address for i in by_service.found] == ["AA"] assert [i.device.address for i in by_manufacturer.found] == ["BB"] async def test_changed_manufacturer_data_is_an_update(radios): ble, near, _ = radios listener = Listener() ble.register(listener, [BLEMatcher(manufacturer_id=APPLE)]) for data in (b"\x06\x31\x01", b"\x06\x31\x01", b"\x06\x31\x02"): near.advertise("BB", manufacturer_data={APPLE: data}) await settle() assert (len(listener.found), len(listener.updated)) == (1, 1) async def test_a_name_heard_once_stays_with_the_device_under_passive_scanning(radios): ble, near, _ = radios listener = Listener() ble.register(listener, {MATTER}) near.advertise("AA", local_name="KAJPLATS WS BULB", service_data={str(MATTER): b"\x00"}) # a scan response near.advertise("AA", service_data={str(MATTER): b"\x00"}) # passive: no scan response, no name await settle() assert [i.advertisement.local_name for i in listener.found] == ["KAJPLATS WS BULB"] assert not listener.updated # a name missing from a passive sighting isn't a change assert ble.devices()[0].advertisement.local_name == "KAJPLATS WS BULB" async def test_a_new_device_without_a_name_gets_a_short_active_burst_bounded_in_time(): radio = ScanModeFakeBLESource("hci0") ble = BLEService(sources=[radio]) ble._name_burst_sec = 0.02 await ble.start() radio.advertise("AA", service_data={str(MATTER): b"\x00"}) radio.advertise("BB", service_data={str(MATTER): b"\x00"}) # within the same window: no second burst await settle() assert radio.modes == [False, True] await asyncio.sleep(0.05) assert radio.modes == [False, True, False] radio.advertise("CC", local_name="named") # a name of its own needs no burst radio.advertise("DD") # nor does one heard before the burst interval passed await settle() assert radio.modes == [False, True, False] await ble.stop() ================================================================================ # FILE: tests/runtime/test_defaults.py ================================================================================ """What runs by default, and that it is there without the extras.""" import subprocess import sys from majordom_integration_sdk.runtime import Compose, UsbScanner, default_peripherals, default_usb_drivers from majordom_integration_sdk.runtime.peripherals.services.builtin import otbr, silabs_multiprotocol WITHOUT_EXTRAS = """ import importlib.abc, sys class Missing(importlib.abc.MetaPathFinder): def find_spec(self, name, path=None, target=None): if name.split(".")[0] in {"serial", "bleak", "dbus_fast", "zeroconf", "typer_shell", "rich"}: raise ImportError(f"No module named {name!r}") sys.meta_path.insert(0, Missing()) import majordom_integration_sdk, majordom_integration_sdk.dev, majordom_integration_sdk.testing from majordom_integration_sdk.runtime import default_peripherals print(" ".join(p.name for p in default_peripherals())) """ def test_the_defaults_are_what_runs_around_integrations_in_the_order_they_bind(): assert [p.name for p in default_peripherals()] == [ "usb", "bluetooth-adapters", "host", "compose", "silabs-multiprotocol", "otbr", "ble-router", "zeroconf", "ssdp", ] on_demand = [p.name for p in default_peripherals() if p.is_on_demand] assert on_demand == ["compose", "silabs-multiprotocol", "otbr", "ble-router", "zeroconf", "ssdp"] def test_the_containers_listen_where_the_host_says(): assert next(p for p in default_peripherals() if isinstance(p, Compose)).listen_address == "127.0.0.1" lab = default_peripherals(listen_address="0.0.0.0") # a lab harness reached from another host assert next(p for p in lab if isinstance(p, Compose)).listen_address == "0.0.0.0" def test_the_usb_scanner_knows_every_sdk_driver_by_default(): assert [driver.name for driver in default_usb_drivers()] == ["zwave", "silabs"] # the cheap Z-Wave check first assert [driver.name for driver in UsbScanner().drivers] == ["zwave", "silabs"] scanner = next(p for p in default_peripherals() if isinstance(p, UsbScanner)) assert [driver.name for driver in scanner.drivers] == ["zwave", "silabs"] def test_every_runtime_gets_defaults_of_its_own(): first, second = default_peripherals(), default_peripherals() assert not {id(p) for p in first} & {id(p) for p in second} assert otbr() is not otbr() and silabs_multiprotocol() is not silabs_multiprotocol() assert not {id(d) for d in default_usb_drivers()} & {id(d) for d in default_usb_drivers()} assert not {id(d) for d in UsbScanner().drivers} & {id(d) for d in UsbScanner().drivers} def test_the_package_and_its_defaults_import_without_the_extras(): result = subprocess.run([sys.executable, "-c", WITHOUT_EXTRAS], capture_output=True, text=True, check=True) assert result.stdout.split() == [ "usb", "bluetooth-adapters", "host", "compose", "silabs-multiprotocol", "otbr", "ble-router", "ssdp", ] assert 'pip install "majordom-integration-sdk[discovery]"' in result.stderr # no DNS-SD, said once ================================================================================ # FILE: tests/runtime/test_hardware.py ================================================================================ """Hardware as peripherals, over fakes of /dev and /sys: no real stick is opened.""" import asyncio import json from collections.abc import Mapping from pathlib import Path from typing import Any import pytest from support import run, settle, state, until from majordom_integration_sdk import Endpoint, Need, Peripheral, PeripheralChange, UsbDriver from majordom_integration_sdk.runtime import ( BluetoothAdapters, FixedPeripherals, FixedRadio, HostNetwork, PeripheralState, Pinned, Radio, RadioBusy, Silabs, UsbScanner, ) from majordom_integration_sdk.runtime.peripherals.hardware import host, usb from majordom_integration_sdk.runtime.peripherals.providers.ble import cpc_hci from majordom_integration_sdk.testing import FakePeripheral, RecordingPeripheralOutput, RecordingRuntimeOutput NCP = {"baud": 115200, "flow_control": True} # the firmware's serial settings SKYCONNECT = "usb-Nabu_Casa_SkyConnect_v1.0_1-if00" class Driver(UsbDriver): """Recognises the sticks named in ``recognised``, with the serial settings it found them at where given, recording each one it opened.""" firmwares = { "zigbee-ncp": [Endpoint("zigbee", "ezsp", "{device}", params=NCP)], "multipan-rcp": [Endpoint("multipan", "silabs-cpc", "{device}")], } def __init__(self, name: str = "silabs", **recognised: str | tuple[str, Mapping[str, Any]]): self.name, self.recognised, self.opened = name, recognised, [] async def identify(self, path: str) -> str | tuple[str, Mapping[str, Any]] | None: self.opened.append(Path(path).name) return self.recognised.get(Path(path).name) @pytest.fixture def sticks(monkeypatch) -> dict[str, str]: """The sticks plugged in, by their by-id name; each is a known radio's USB id unless named "arduino".""" plugged: dict[str, str] = {} monkeypatch.setattr(usb, "_sticks", lambda: dict(plugged)) monkeypatch.setattr(usb, "_nodes", lambda paths: dict(paths)) monkeypatch.setattr(usb.os.path, "realpath", lambda path: path) monkeypatch.setattr(usb, "_usb_id", lambda path: ("1a86", "7523") if "arduino" in path else ("10c4", "ea60")) monkeypatch.setattr(usb, "POLL", 0.01) return plugged @pytest.fixture(autouse=True) def held(monkeypatch) -> dict[str, str]: """Other programs holding a stick open, by its file name; none unless a test says so.""" holders: dict[str, str] = {} monkeypatch.setattr(usb, "_holder", lambda path, is_opening_allowed=False: holders.get(Path(path).name)) return holders def plug(sticks: dict[str, str], *names: str): sticks.update({name: f"/dev/serial/by-id/{name}" for name in names}) def zigbee() -> FakePeripheral: return FakePeripheral("zigbee", [Need("zigbee")]) async def test_each_stick_is_a_radio_serving_what_its_firmware_does(tmp_path, sticks): plug(sticks, "sky") scanner, integration = UsbScanner([Driver(sky="zigbee-ncp")]), zigbee() runtime = await run(tmp_path, scanner, integration) [radio] = scanner.radios assert runtime.peripherals == [scanner, radio, integration] assert (radio.name, radio.driver and radio.driver.name, radio.firmware) == ("sky", "silabs", "zigbee-ncp") assert integration.peripherals.endpoint("zigbee") == Endpoint("zigbee", "ezsp", "/dev/serial/by-id/sky", params=NCP) assert runtime.users(radio) == ["zigbee"] async def test_the_serial_settings_a_driver_found_a_stick_at_reach_its_endpoint_and_are_remembered(tmp_path, sticks): plug(sticks, "conbee") driver, integration = Driver(conbee=("zigbee-ncp", {"baud": 38400})), zigbee() runtime = await run(tmp_path, UsbScanner([driver]), integration) expected = Endpoint("zigbee", "ezsp", "/dev/serial/by-id/conbee", params=NCP | {"baud": 38400}) assert integration.peripherals.endpoint("zigbee") == expected await runtime.stop() again, integration = Driver(conbee="zigbee-ncp"), zigbee() await run(tmp_path, UsbScanner([again]), integration) # after a reboot assert again.opened == [] and integration.peripherals.endpoint("zigbee") == expected async def test_only_known_radios_are_opened_until_asked(tmp_path, sticks): plug(sticks, "sky", "arduino") # an Arduino resets whenever its port opens driver = Driver(sky="multipan-rcp", arduino="zigbee-ncp") scanner = UsbScanner([driver]) runtime = await run(tmp_path, scanner) assert driver.opened == ["sky"] sky, arduino = sorted(scanner.radios, key=lambda r: r.name, reverse=True) assert (sky.firmware, arduino.firmware, arduino.provides) == ("multipan-rcp", None, []) await arduino.probe() # the user asked: open it after all await settle(runtime) assert driver.opened == ["sky", "arduino"] assert arduino.firmware == "zigbee-ncp" async def test_the_sticks_identified_and_probed_are_remembered_across_restarts(tmp_path, sticks): plug(sticks, "sky", "arduino") driver = Driver(sky="zigbee-ncp", arduino="zigbee-ncp") scanner = UsbScanner([driver]) runtime = await run(tmp_path, scanner) await next(radio for radio in scanner.radios if radio.name == "arduino").probe() # the user claims it await settle(runtime) await runtime.stop() assert driver.opened == ["sky", "arduino"] again, integration = Driver(sky="zigbee-ncp", arduino="zigbee-ncp"), zigbee() scanner = UsbScanner([again]) await run(tmp_path, scanner, integration) # after a reboot assert again.opened == [] # neither opened again assert {radio.name: (radio.firmware, radio.is_claimed) for radio in scanner.radios} == { "arduino": ("zigbee-ncp", True), "sky": ("zigbee-ncp", False), } assert integration.peripherals.endpoint("zigbee").url == "/dev/serial/by-id/arduino" async def test_a_forgotten_stick_is_looked_at_again_as_one_plugged_in_anew(tmp_path, sticks): plug(sticks, "sky", "arduino") driver = Driver(sky="zigbee-ncp", arduino="zigbee-ncp") scanner = UsbScanner([driver]) runtime = await run(tmp_path, scanner) sky, arduino = sorted(scanner.radios, key=lambda r: r.name, reverse=True) await arduino.probe() await settle(runtime) await sky.forget() # a known radio's USB id: identified again await arduino.forget() # one the user probed: left alone again until probed await settle(runtime) assert driver.opened == ["sky", "arduino", "sky"] assert (sky.firmware, arduino.firmware, arduino.is_claimed, arduino.provides) == ("zigbee-ncp", None, False, []) assert json.loads((scanner.platform.documents_folder(scanner) / "sticks.json").read_text()).keys() == {"sky"} async def test_a_scan_in_flight_never_undoes_a_forget(tmp_path, sticks): gate = asyncio.Event() class Slow(Driver): async def identify(self, path: str) -> str | tuple[str, Mapping[str, Any]] | None: if Path(path).name == "a": await gate.wait() # bellows resetting a stick return await super().identify(path) plug(sticks, "b") driver = Slow(a="zigbee-ncp", b="zigbee-ncp") scanner = UsbScanner([driver]) runtime = await run(tmp_path, scanner) [b] = scanner.radios sticks.clear() plug(sticks, "a", "b") # listed first: a scan now waits on its probe scanning = asyncio.create_task(scanner.rescan()) await asyncio.sleep(0.01) shared, told = b.output, [] class Output(RecordingPeripheralOutput): async def peripheral_did_change_provided(self, peripheral: Peripheral): told.append(peripheral) if len(told) == 2: # leaving its forget, cleared gate.set() await asyncio.sleep(0.01) # the runtime takes a moment: the scan goes on meanwhile await shared.peripheral_did_change_provided(peripheral) b.output = Output() await b.forget() await scanning await settle(runtime) assert driver.opened == ["b", "a", "b"] # looked at again, as one plugged in anew async def test_a_forgotten_soldered_radio_is_identified_again(tmp_path): (tmp_path / "ttyAMA3").touch() driver = Driver(ttyAMA3="multipan-rcp") board = FixedPeripherals(FixedRadio("mg26", str(tmp_path / "ttyAMA3"), "silabs", "zigbee-ncp"), drivers=[driver]) runtime = await run(tmp_path, board) [radio] = board.provides assert (radio.firmware, driver.opened) == ("zigbee-ncp", []) # as the board says await radio.forget() await settle(runtime) assert (radio.firmware, driver.opened) == ("multipan-rcp", ["ttyAMA3"]) # what it runs, asked async def test_a_forgotten_soldered_radio_no_driver_tells_serves_what_the_board_says(tmp_path): (tmp_path / "ttyAMA3").touch() driver = Driver() # it can't read it at the firmware's own serial settings wired = FixedRadio("mg26", str(tmp_path / "ttyAMA3"), "silabs", "multipan-rcp", {"flow_control": False}) board, multipan = FixedPeripherals(wired, drivers=[driver]), FakePeripheral("multipan", [Need("multipan")]) runtime = await run(tmp_path, board, multipan) [radio] = board.provides await radio.forget() await settle(runtime) assert (radio.firmware, driver.opened) == ("multipan-rcp", ["ttyAMA3"]) assert state(runtime, multipan) == PeripheralState.RUNNING async def test_a_stick_another_program_holds_is_left_alone_until_probed(tmp_path, sticks, held): plug(sticks, "sky") held["sky"] = "zigbee2mqtt" driver, integration = Driver(sky="zigbee-ncp"), zigbee() scanner = UsbScanner([driver]) runtime = await run(tmp_path, scanner, integration) assert driver.opened == [] # never opened: probing would reset the radio under zigbee2mqtt assert scanner.radios[0].held_by == "zigbee2mqtt" assert state(runtime, integration) == PeripheralState.WAITING await scanner.radios[0].probe() # the user claims it anyway await settle(runtime) assert scanner.radios[0].held_by is None assert state(runtime, integration) == PeripheralState.RUNNING async def test_a_stick_is_used_once_the_other_program_lets_go(tmp_path, sticks, held): plug(sticks, "sky") held["sky"] = "node" scanner, integration = UsbScanner([Driver(sky="zigbee-ncp")]), zigbee() runtime = await run(tmp_path, scanner, integration) held.clear() await until(runtime, lambda: state(runtime, integration) == PeripheralState.RUNNING) async def test_a_stick_held_out_of_sight_isnt_looked_at_again_and_again(tmp_path, sticks, monkeypatch): plug(sticks, "sky") # its holder locked it: no open file of it can be read monkeypatch.setattr( usb, "_holder", lambda path, is_opening_allowed=False: is_opening_allowed and "another program" or None ) scanner, rescans = UsbScanner([Driver(sky="zigbee-ncp")]), [] async def rescan(): rescans.append(scanner.radios[0].held_by) monkeypatch.setattr(scanner, "rescan", rescan) await run(tmp_path, scanner) assert scanner.radios[0].held_by == "another program" await asyncio.sleep(0.1) # ten looks assert rescans == [] async def test_a_stick_plugged_in_or_out_is_followed(tmp_path, sticks): scanner, integration = UsbScanner([Driver(sky="zigbee-ncp")]), zigbee() runtime = await run(tmp_path, scanner, integration) plug(sticks, "sky") await until(runtime, lambda: state(runtime, integration) == PeripheralState.RUNNING) sticks.clear() await until(runtime, lambda: state(runtime, integration) == PeripheralState.WAITING) assert scanner.radios == [] and integration.calls == ["start", "stop"] async def test_a_stick_that_comes_back_on_another_tty_is_followed(tmp_path, sticks, monkeypatch): """A USB bus reset re-enumerates sticks onto new ttys under the same by-id name, faster than the watcher's debounce: what uses it must not keep the old device node (it may be another device now).""" nodes = {"sky": "/dev/ttyUSB0"} monkeypatch.setattr(usb.os.path, "realpath", lambda path: nodes.get(Path(path).name, path)) monkeypatch.setattr(usb, "_nodes", lambda paths: {name: nodes[name] for name in paths}) plug(sticks, "sky") integration = FakePeripheral("zigbee", [Need("zigbee")]) runtime = await run(tmp_path, UsbScanner([Driver(sky="zigbee-ncp")]), integration) assert integration.peripherals.endpoint("zigbee").url == "/dev/ttyUSB0" nodes["sky"] = "/dev/ttyUSB4" await until(runtime, lambda: integration.peripherals.endpoint("zigbee").url == "/dev/ttyUSB4") async def test_a_driver_an_integration_brings_along_recognises_what_the_others_dont(tmp_path, sticks): class Zigpy(Driver): firmwares = {"deconz": [Endpoint("zigbee", "deconz", "{device}")]} plug(sticks, "conbee") zigpy = Zigpy("zigpy", conbee="deconz") integration = FakePeripheral("zigbee", [Need("zigbee")]) scanner = UsbScanner([Driver()]) # the SDK's drivers know nothing of it runtime = await run(tmp_path, scanner, zigpy, integration) await until(runtime, lambda: state(runtime, integration) == PeripheralState.RUNNING) assert integration.peripherals.endpoint("zigbee") == Endpoint("zigbee", "deconz", "/dev/serial/by-id/conbee") assert zigpy.opened == ["conbee"] assert runtime.providers(scanner) == {"usb-driver": ["zigpy"]} await runtime.stop() sdk, again, integration = Driver(), Zigpy("zigpy", conbee="deconz"), FakePeripheral("zigbee", [Need("zigbee")]) runtime = await run(tmp_path, UsbScanner([sdk]), again, integration) # after a reboot await until(runtime, lambda: state(runtime, integration) == PeripheralState.RUNNING) assert again.opened == sdk.opened == [] # known from before: not opened again, also while its driver starts async def test_one_rescan_at_a_time_opens_a_stick_once(tmp_path, sticks): opening: list[str] = [] at_once: list[int] = [] class Slow(Driver): async def identify(self, path: str) -> str | tuple[str, Mapping[str, Any]] | None: opening.append(path) at_once.append(len(opening)) await asyncio.sleep(0.02) opening.remove(path) return await super().identify(path) plug(sticks, "conbee") scanner, slow = UsbScanner([Driver()]), Slow("zigpy", conbee="zigbee-ncp") runtime = await run(tmp_path, scanner) scanner.drivers.append(slow) # as if an integration's driver got bound change = PeripheralChange("usb-driver", None, None) await asyncio.gather(scanner.needed_peripheral_did_change(change), scanner.needed_peripheral_did_change(change)) await until(runtime, lambda: scanner.radios[0].firmware == "zigbee-ncp") await asyncio.sleep(0.05) assert at_once == [1] async def test_a_probe_that_never_answers_gives_up(tmp_path, sticks, monkeypatch): class Silent(Driver): async def identify(self, path: str) -> str | None: await asyncio.Event().wait() # e.g. bellows resetting a port someone else holds return None monkeypatch.setattr(usb, "PROBE_TIMEOUT", 0.01) plug(sticks, "odd") scanner = UsbScanner([Silent()]) async with asyncio.timeout(1): await run(tmp_path, scanner) assert scanner.radios[0].driver is None async def test_a_radio_is_released_before_it_is_flashed_and_used_again_after(tmp_path, sticks): seen_while_flashed = [] class Flashing(Driver): def flashable(self, path: str, channel: str) -> list[str]: return ["zigbee-ncp", "multipan-rcp"] async def flash(self, path: str, firmware: str, channel: str, cache: Path): seen_while_flashed.append(state(runtime, integration)) self.recognised["sky"] = firmware plug(sticks, "sky") integration = FakePeripheral("zigbee", [Need("zigbee")], answer=True) multipan = FakePeripheral("multipan", [Need("multipan")]) scanner = UsbScanner([Flashing(sky="zigbee-ncp")]) runtime = await run(tmp_path, scanner, integration, multipan) await scanner.radios[0].flash("multipan-rcp") await settle(runtime) assert seen_while_flashed == [PeripheralState.WAITING] # it let go of the stick first assert (state(runtime, integration), state(runtime, multipan)) == (PeripheralState.WAITING, PeripheralState.RUNNING) async def test_a_radio_being_flashed_refuses_another_flash_probe_or_forget(tmp_path, sticks): gate = asyncio.Event() class Flashing(Driver): def flashable(self, path: str, channel: str) -> list[str]: return ["zigbee-ncp", "multipan-rcp"] async def flash(self, path: str, firmware: str, channel: str, cache: Path): await gate.wait() self.recognised["sky"] = firmware plug(sticks, "sky") scanner = UsbScanner([Flashing(sky="zigbee-ncp")]) runtime = await run(tmp_path, scanner, zigbee()) [radio] = scanner.radios flashing = asyncio.create_task(radio.flash("multipan-rcp")) await until(runtime, lambda: radio.is_busy, settled=False) for again in (radio.flash("zigbee-ncp"), radio.probe(), radio.forget()): # a double tap, a second app with pytest.raises(RadioBusy): await again gate.set() await flashing await settle(runtime) assert (radio.is_busy, radio.firmware) == (False, "multipan-rcp") async def test_a_radio_whose_flash_failed_serves_what_it_runs_now(tmp_path, sticks): class Bricking(Driver): def flashable(self, path: str, channel: str) -> list[str]: return ["multipan-rcp"] async def flash(self, path: str, firmware: str, channel: str, cache: Path): del self.recognised["sky"] # left in its bootloader raise RuntimeError("the flasher crashed") plug(sticks, "sky") integration, scanner = zigbee(), UsbScanner([Bricking(sky="zigbee-ncp")]) runtime = await run(tmp_path, scanner, integration) with pytest.raises(RuntimeError, match="crashed"): await scanner.radios[0].flash("multipan-rcp") await settle(runtime) assert (scanner.radios[0].firmware, scanner.radios[0].provides) == (None, []) assert state(runtime, integration) == PeripheralState.WAITING async def test_the_firmware_offered_follows_the_radios_channel(tmp_path): radio = Radio(SKYCONNECT, f"/dev/serial/by-id/{SKYCONNECT}", lambda: [], Silabs(), "thread-rcp") runtime = await run(tmp_path, FakePeripheral("board", provides=[radio]), zigbee()) assert radio.options == [] # stable channel: nothing verified to flash yet await runtime.update_settings(radio, {"firmware_channel": "dev"}) assert radio.options == ["zigbee-ncp", "thread-rcp"] assert runtime.reach(Silabs().serves("multipan-rcp", "x")) == [] # nothing here needs what it would serve assert runtime.reach(Silabs().serves("zigbee-ncp", "x")) == ["zigbee"] async def test_switching_a_radios_firmware_channel_restarts_nothing(tmp_path): radio = Radio(SKYCONNECT, f"/dev/serial/by-id/{SKYCONNECT}", lambda: [], Silabs(), "zigbee-ncp") output, integration = RecordingRuntimeOutput(), zigbee() runtime = await run(tmp_path, FakePeripheral("board", provides=[radio]), integration, output=output) told = len(output.statuses) await runtime.update_settings(radio, {"firmware_channel": "dev"}) # it only changes what it may be flashed to await settle(runtime) assert output.statuses[told:] == [] and integration.calls == ["start"] async def test_a_multiprotocol_firmware_that_serves_bluetooth_offers_it_too(tmp_path, sticks, monkeypatch): asked: list[str] = [] async def has_bluetooth(path: str) -> bool: asked.append(path) return True monkeypatch.setattr(cpc_hci, "has_bluetooth", has_bluetooth) plug(sticks, "sky", "ncp") scanner = UsbScanner([Driver(sky="multipan-rcp", ncp="zigbee-ncp")]) await run(tmp_path, scanner) sky, ncp = sorted(scanner.radios, key=lambda r: r.name, reverse=True) assert asked == ["/dev/serial/by-id/sky"] # a multi-PAN firmware only, asked once assert sky.provides[-1] == Endpoint("ble", "silabs-cpc-hci", "/dev/serial/by-id/sky", params={"hci": None}) assert [e.family for e in ncp.provides] == ["zigbee"] async def test_the_cpc_probe_says_no_until_verified_on_hardware(): assert await cpc_hci.has_bluetooth("/dev/ttyUSB0") is False with pytest.raises(ConnectionError, match="no Bluetooth adapter"): cpc_hci.source_of(Endpoint("ble", "silabs-cpc-hci", "/dev/ttyUSB0", params={"hci": None})) async def test_soldered_radios_are_used_without_asking_wired_as_the_board_says(tmp_path): (tmp_path / "ttyAMA3").touch() driver = Driver(ttyAMA3="zigbee-ncp") board = FixedPeripherals( FixedRadio("mg26", str(tmp_path / "ttyAMA3"), "silabs", "zigbee-ncp", {"flow_control": False}), FixedRadio("absent", str(tmp_path / "ttyAMA4"), "silabs", "zigbee-ncp"), FixedRadio("unknown", str(tmp_path / "ttyAMA3"), "silabs"), drivers=[driver], ) integration = zigbee() runtime = await run(tmp_path, board, integration) assert [radio.name for radio in board.provides] == ["mg26", "unknown"] # one that isn't there is left out expected = Endpoint("zigbee", "ezsp", str(tmp_path / "ttyAMA3"), params={"baud": 115200, "flow_control": False}) assert integration.peripherals.endpoint("zigbee") == expected assert driver.opened == ["ttyAMA3"] # only the one whose firmware the board doesn't tell assert runtime.status(board.provides[1]).state == PeripheralState.RUNNING async def test_the_host_offers_its_network_and_every_adapter_with_its_index(tmp_path, monkeypatch): found = ["/sys/class/bluetooth/hci1", "/sys/class/bluetooth/hci0", "/sys/class/bluetooth/hci0:1"] monkeypatch.setattr(host, "glob", lambda pattern: list(found)) monkeypatch.setattr(host.sys, "platform", "linux") monkeypatch.setattr(host, "POLL", 0.01) adapters = BluetoothAdapters() sniffer = FakePeripheral("sniffer", [Need("ip"), Need("ble", is_many=True)], answer=True) runtime = await run(tmp_path, HostNetwork(), adapters, sniffer) assert runtime.bound(sniffer) == { "ip": Endpoint("ip", is_shared=True), "ble": [ Endpoint("ble", "bluez", "hci0", params={"index": "0"}), Endpoint("ble", "bluez", "hci1", params={"index": "1"}), ], } found.append("/sys/class/bluetooth/hci2") # plugged in await until(runtime, lambda: len(sniffer.peripherals.endpoints("ble")) == 3) def test_off_linux_the_host_has_its_default_adapter(monkeypatch): monkeypatch.setattr(host.sys, "platform", "darwin") assert host._adapters() == [""] async def test_endpoints_pinned_first_win_and_come_and_go(tmp_path, sticks): plug(sticks, "sky") mine = Endpoint("zigbee", "ezsp", "socket://192.168.1.5:6638", is_shared=True) pinned, integration = Pinned(mine), FakePeripheral("zigbee", [Need("zigbee")], answer=True) runtime = await run(tmp_path, pinned, UsbScanner([Driver(sky="zigbee-ncp")]), integration) assert integration.peripherals.endpoint("zigbee") == mine await pinned.unpin("zigbee") await settle(runtime) assert integration.peripherals.endpoint("zigbee").url == "/dev/serial/by-id/sky" await pinned.pin(mine) await settle(runtime) assert runtime.providers(integration) == {"zigbee": "pinned"} def test_a_skyconnect_is_never_offered_a_multipan_build_the_sisdk_stack_cant_run(monkeypatch): from majordom_integration_sdk.runtime.peripherals.hardware import drivers sky = "/dev/serial/by-id/usb-Nabu_Casa_SkyConnect_v1.0_0-if00-port0" assert "multipan-rcp" not in drivers.Silabs().flashable(sky, "dev") # gsdk 4.4.4 / CPC v5: no match for CPC v6 assert set(drivers.Silabs().flashable(sky, "dev")) == {"zigbee-ncp", "thread-rcp"} async def probe(path: str, *args: str) -> str: return "Detected ApplicationType.CPC" monkeypatch.setattr(drivers, "_flasher", probe) assert asyncio.run(drivers.Silabs().identify(sky)) == "multipan-rcp" # a stick already on our SiSDK build ================================================================================ # FILE: tests/runtime/test_integration.py ================================================================================ """An integration controller run by the runtime like any peripheral: its platform, settings and peripherals.""" import json from typing import cast from uuid import UUID, uuid4 from pydantic import BaseModel from support import run, settle from majordom_integration_sdk import AbstractController, Endpoint, IntegrationError, Need, Peripheral, Platform, Service from majordom_integration_sdk.runtime import HostNetwork, MemoryDisabledStore, PeripheralState, PeripheralStatus from majordom_integration_sdk.runtime import StatusKind as K from majordom_integration_sdk.schemas.device import Device, Discovery, Parameter from majordom_integration_sdk.testing import FakeCompose, FakePeripheral, RecordingControllerOutput, build_test_platform DEVICE = uuid4() class Greeting(BaseModel): greeting: str = "hello" def echo_server() -> Service[Greeting]: return Service( "echo-server", compose={"image": "echo", "command": ["--greeting", "{settings.greeting}"]}, needs=[Need("ip")], provides=[Endpoint("example", "echo", "ws://127.0.0.1:{ports.api}")], settings=Greeting, ports={"api": 5600}, ) class EchoController(AbstractController[Device, Parameter, "EchoController.Settings"]): needs = [Need("example", ["echo"])] class Settings(BaseModel): is_loud: bool = False def __init__(self, platform: Platform, *, settings: Settings | None = None): super().__init__(platform, settings=settings) self.started_with: list[tuple[str, bool]] = [] @property def discoveries(self) -> dict[UUID, Discovery]: return {} async def start(self): self.started_with.append((self.peripherals.endpoint("example").url, self.settings.is_loud)) async def stop(self): pass async def settings_did_change(self, before) -> bool: return True # it tells the server over its connection async def pair_device(self, discovery, draft, credentials): return draft async def unpair(self, device): pass async def identify(self, device): pass async def fetch(self, device): pass async def send_command(self, command, device, parameter): pass def peripherals(platform: Platform) -> list[Peripheral]: """What the integration package exports: its server, and the controller that needs it.""" return [echo_server(), EchoController(platform)] def integration() -> tuple[Service[Greeting], EchoController]: """What the integration exports, given its platform as by the Hub.""" server, echo = peripherals(build_test_platform()) assert isinstance(server, Service) and isinstance(echo, EchoController) return cast(Service[Greeting], server), echo async def test_an_integration_runs_once_the_server_it_provides_serves(tmp_path): server, echo = integration() runtime = await run(tmp_path, HostNetwork(), FakeCompose(), server, echo) assert runtime.status(echo) == PeripheralStatus(PeripheralState.RUNNING) assert echo.started_with == [("ws://127.0.0.1:5600", False)] # its needs bound, its settings given, before start assert runtime.users(server) == ["echo"] and echo.key == "echo" # known by its slug async def test_an_integration_is_kept_by_its_slug_and_shown_by_its_name(tmp_path): class ZWaveJS(EchoController): name = "Z-Wave JS" store, server, echo = MemoryDisabledStore(), echo_server(), ZWaveJS(build_test_platform()) runtime = await run(tmp_path, HostNetwork(), FakeCompose(), server, echo, disabled=store) await runtime.update_settings(echo, {"is_loud": True}) await runtime.disable(echo) assert (echo.key, echo.name) == ("z-wave-js", "Z-Wave JS") documents = tmp_path / "data" / "peripherals" / "z-wave-js" assert store.is_disabled("z-wave-js") and echo.platform.documents_folder(echo) == documents assert json.loads((tmp_path / "data" / "state.json").read_text())["settings"]["z-wave-js"] == {"is_loud": True} assert runtime.peripheral("z-wave-js") is echo async def test_an_integration_and_its_server_keep_their_settings(tmp_path): server, echo = integration() runtime = await run(tmp_path, HostNetwork(), FakeCompose(), server, echo) compose = tmp_path / "data" / "peripherals" / "compose" / "compose.json" await runtime.update_settings(server, {"greeting": "hi"}) await settle(runtime) assert json.loads(compose.read_text())["services"]["echo-server"]["command"] == ["--greeting", "hi"] assert echo.started_with == [("ws://127.0.0.1:5600", False)] # the server restarted under it: it reconnects await runtime.update_settings(echo, {"is_loud": True}) await settle(runtime) assert echo.settings.is_loud and len(echo.started_with) == 1 # applied in place server, again = integration() # after a reboot await run(tmp_path, HostNetwork(), FakeCompose(), server, again) assert again.started_with == [("ws://127.0.0.1:5600", True)] async def test_an_integration_waits_with_a_reason_when_its_server_cant_run(tmp_path): server, echo = integration() runtime = await run(tmp_path, FakeCompose(), server, echo) # no network for the server assert runtime.status(echo) == PeripheralStatus( PeripheralState.WAITING, K.NEEDS_UNBOUND, "need example/echo: echo-server can't run (need ip/*: nothing offers it)", ) assert echo.started_with == [] async def test_a_controller_given_its_settings_keeps_them_until_the_user_changes_them(tmp_path): echo = EchoController(build_test_platform(), settings=EchoController.Settings(is_loud=True)) # library mode await run(tmp_path, HostNetwork(), FakeCompose(), echo_server(), echo) assert echo.started_with == [("ws://127.0.0.1:5600", True)] server, again = integration() # after a reboot await run(tmp_path, HostNetwork(), FakeCompose(), server, again) assert again.started_with == [("ws://127.0.0.1:5600", True)] # what a controller tells, through the one output every peripheral shares async def test_every_peripheral_shares_one_output_and_a_controllers_reports_reach_the_hub(tmp_path): hub, server, echo = RecordingControllerOutput(), *integration() runtime = await run(tmp_path, HostNetwork(), FakeCompose(), server, echo, controller_output=hub) assert echo.output is server.output and not hasattr(echo, "runtime") await echo.output.controller_did_lose_device(echo, physical_id=DEVICE) await echo.output.controller_did_encounter_error(echo, IntegrationError("server-slow", "The server is slow.")) assert hub.lost_devices == [DEVICE] and list(hub.errors) == ["server-slow"] assert runtime.status(echo).state == PeripheralState.RUNNING # it goes on async def test_a_controller_that_cant_go_on_says_why_and_is_tried_again(tmp_path): hub, server, echo = RecordingControllerOutput(), *integration() runtime = await run(tmp_path, HostNetwork(), FakeCompose(), server, echo, controller_output=hub) lost = IntegrationError("radio-lost", "The radio is gone: plug it in again.", is_still_running=False) await echo.output.controller_did_encounter_error(echo, lost) await settle(runtime) assert hub.errors == {"radio-lost": lost} # the user sees it status = runtime.status(echo) assert (status.state, status.kind, status.detail.split(";")[0]) == ( PeripheralState.WAITING, K.RETRYING, lost.message, ) async def test_what_a_controller_provides_is_read_again_when_it_says_so(tmp_path): class ESPHome(EchoController): name = "esphome" def __init__(self, platform: Platform): super().__init__(platform) self.proxies: list[Peripheral] = [] @property def provides(self) -> list[Peripheral]: return self.proxies server, esphome = echo_server(), ESPHome(build_test_platform()) runtime = await run(tmp_path, HostNetwork(), FakeCompose(), server, esphome) esphome.proxies.append(proxy := FakePeripheral("aa:bb")) # a node connected await esphome.output.controller_did_change_provided(esphome) await settle(runtime) assert runtime.peripheral("esphome/aa:bb") is proxy and proxy.output is esphome.output async def test_without_a_runtime_a_controller_logs_what_it_tells_or_reports_to_the_output_given(caplog): echo = EchoController(build_test_platform()) # library mode await echo.output.controller_did_encounter_error(echo, IntegrationError("down", "Down.", is_still_running=False)) assert "Down." in caplog.text echo.output = hub = RecordingControllerOutput() await echo.output.controller_did_change_provided(echo) assert hub.provided_changes == [echo] ================================================================================ # FILE: tests/runtime/test_lifecycle.py ================================================================================ """Every row of the peripheral state machine, the one lifetime rule, retries and readiness.""" import asyncio import json from collections.abc import Awaitable, Callable from dataclasses import replace from typing import Any import pytest from pydantic import BaseModel, Field, ValidationError from support import changed, run, settle, state, until from majordom_integration_sdk import STABLE_RUN, Endpoint, Need, NoSettings, PeripheralChange, Platform from majordom_integration_sdk import SettingsExtraField as Extra from majordom_integration_sdk.runtime import MemoryDisabledStore, PeripheralStatus, Runtime from majordom_integration_sdk.runtime import PeripheralState as S from majordom_integration_sdk.runtime import StatusKind as K from majordom_integration_sdk.runtime import runtime as module from majordom_integration_sdk.testing import FakePeripheral, RecordingRuntimeOutput, build_test_platform ZIGBEE = Endpoint("zigbee", "ezsp", "/dev/ttyUSB0") MOVED = Endpoint("zigbee", "ezsp", "/dev/ttyUSB1") THREAD = Endpoint("thread", "otbr-rest", "http://127.0.0.1:8081", is_shared=True) SERVER = Endpoint("matter", "matter-server", "ws://127.0.0.1:5580", is_shared=True) UNBOUND = "need zigbee/*: nothing offers it" def radio(*provides: Endpoint) -> FakePeripheral: return FakePeripheral("radio", provides=provides) def zigbee(**kwargs) -> FakePeripheral: return FakePeripheral("zigbee", [Need("zigbee")], **kwargs) # boot async def test_a_peripheral_with_nothing_to_wait_for_runs_and_stops_with_the_runtime(tmp_path): host = FakePeripheral("host", provides=[Endpoint("ip", is_shared=True)]) runtime = await run(tmp_path, host) assert runtime.status(host) == PeripheralStatus(S.RUNNING) await runtime.stop() assert host.calls == ["start", "stop"] async def test_what_it_runs_is_known_before_it_starts(tmp_path): host, hue = FakePeripheral("host"), FakePeripheral("hue") runtime = Runtime(tmp_path / "data", [host], platform=build_test_platform(tmp_path)) await runtime.add(hue) # library mode: given one by one assert runtime.peripherals == [host, hue] and runtime.status(hue) == PeripheralStatus(S.WAITING) assert hue.calls == [] and hue.platform is runtime.platform await runtime.remove(host) assert runtime.peripherals == [hue] and host.calls == [] async def test_boot_without_a_required_need_waits_and_says_why(tmp_path): output = RecordingRuntimeOutput() integration = zigbee() runtime = await run(tmp_path, integration, output=output) assert runtime.status(integration) == PeripheralStatus(S.WAITING, K.NEEDS_UNBOUND, UNBOUND) assert runtime.unbound(integration) == {"zigbee": UNBOUND} assert output.statuses == [("zigbee", PeripheralStatus(S.WAITING, K.NEEDS_UNBOUND, UNBOUND))] assert str(runtime.status(integration)) == f"waiting: {UNBOUND}" # for logs and the CLI assert integration.calls == [] async def test_it_starts_once_its_need_appears_and_waits_again_while_it_is_lost(tmp_path): stick, integration = radio(), zigbee() output = RecordingRuntimeOutput() runtime = await run(tmp_path, stick, integration, output=output) stick.provided = [ZIGBEE] # identified await changed(runtime, stick) assert state(runtime, integration) == S.RUNNING assert integration.peripherals.endpoint("zigbee") == ZIGBEE assert runtime.providers(integration) == {"zigbee": "radio"} assert [status.state for name, status in output.statuses if name == "zigbee"] == [S.WAITING, S.STARTING, S.RUNNING] stick.provided = [] # unplugged await changed(runtime, stick) assert runtime.status(integration) == PeripheralStatus(S.WAITING, K.NEEDS_UNBOUND, UNBOUND) assert integration.changes == [] # a lost required need stops it without asking stick.provided = [ZIGBEE] # plugged in again await changed(runtime, stick) assert state(runtime, integration) == S.RUNNING assert integration.calls == ["start", "stop", "start"] # running: what moved async def test_a_moved_need_is_handed_over_or_restarts_it(tmp_path): stick, integration = radio(ZIGBEE), zigbee(answer=True) runtime = await run(tmp_path, stick, integration) stick.provided = [MOVED] await changed(runtime, stick) assert integration.changes == [PeripheralChange("zigbee", ZIGBEE, MOVED)] assert integration.calls == ["start"] # handled in place assert integration.peripherals.endpoint("zigbee") == MOVED # already there when it heard integration.answer = False stick.provided = [ZIGBEE] await changed(runtime, stick) assert integration.calls == ["start", "stop", "start"] assert state(runtime, integration) == S.RUNNING async def test_an_optional_need_lost_or_back_is_handed_over(tmp_path): border = FakePeripheral("otbr", provides=[THREAD]) matter = FakePeripheral("matter", [Need("thread", is_required=False)], answer=True) runtime = await run(tmp_path, border, matter) await runtime.disable(border) await settle(runtime) appeared = PeripheralChange("thread", None, THREAD) # it started beside the border router, at boot assert matter.changes == [appeared, PeripheralChange("thread", THREAD, None)] assert state(runtime, matter) == S.RUNNING assert runtime.unbound(matter) == {"thread": "need thread/*: otbr is disabled"} await runtime.enable(border) await settle(runtime) assert matter.changes == [appeared, PeripheralChange("thread", THREAD, None), appeared] assert matter.calls == ["start"] async def test_a_hook_that_hangs_times_out(tmp_path, monkeypatch): monkeypatch.setattr(module, "HOOK_TIMEOUT", 0.01) class Hangs(FakePeripheral): async def needed_peripheral_did_change(self, change): await asyncio.Event().wait() stick, integration = radio(ZIGBEE), Hangs("zigbee", [Need("zigbee")]) runtime = await run(tmp_path, stick, integration) stick.provided = [MOVED] await changed(runtime, stick) expected = PeripheralStatus(S.WAITING, K.RETRYING, "didn't take the change within 0.01 s; trying again in 0.01 s") assert runtime.status(integration) == expected async def test_a_hook_that_raises_restarts_it_through_the_retries(tmp_path): stick, integration = radio(ZIGBEE), zigbee(answer=RuntimeError("confused")) runtime = await run(tmp_path, stick, integration) stick.provided = [MOVED] await changed(runtime, stick) assert runtime.status(integration) == PeripheralStatus(S.WAITING, K.RETRYING, "confused; trying again in 0.01 s") assert integration.calls == ["start", "stop"] await until(runtime, lambda: state(runtime, integration) == S.RUNNING) assert integration.peripherals.endpoint("zigbee") == MOVED async def test_a_hook_cancelled_from_inside_is_a_failure_and_the_others_hear_on(tmp_path): class Cancelled(FakePeripheral): async def platform_facts_did_change(self, before): raise asyncio.CancelledError # e.g. a call it awaited lost its server cancelled, after = Cancelled("matter"), FakePeripheral("after", answer=True) runtime = await run(tmp_path, cancelled, after) before = runtime.platform await runtime.update_platform(replace(before, region="Europe")) assert runtime.status(cancelled) == PeripheralStatus( S.WAITING, K.RETRYING, "CancelledError; trying again in 0.01 s" ) assert after.changes == [("platform", before)] async def moves(runtime, stick: FakePeripheral, integration: FakePeripheral, times: int): """The stick moves ``times``, each once the integration runs again.""" for endpoint in [MOVED, ZIGBEE] * times: await until(runtime, lambda: state(runtime, integration) == S.RUNNING) stick.provided = [endpoint] await changed(runtime, stick) times -= 1 if not times: return async def test_hook_failures_in_a_row_give_it_up(tmp_path): stick, integration = radio(ZIGBEE), zigbee(answer=RuntimeError("confused")) runtime = await run(tmp_path, stick, integration) await moves(runtime, stick, integration, len(module.RETRY_DELAYS) + 1) assert runtime.status(integration) == PeripheralStatus(S.FAILED, K.GAVE_UP, "confused") async def test_a_failure_after_a_stable_run_starts_the_retries_over(tmp_path, monkeypatch): monkeypatch.setattr(module, "STABLE_RUN", 0) stick, integration = radio(ZIGBEE), zigbee(answer=RuntimeError("confused")) runtime = await run(tmp_path, stick, integration) await moves(runtime, stick, integration, len(module.RETRY_DELAYS) + 1) assert state(runtime, integration) == S.WAITING def test_an_integration_holds_a_reconnect_as_long_as_the_runtime_holds_a_run(): # its outage is over once a reconnect held a stable run: a server that drops every time is reported assert STABLE_RUN == module.STABLE_RUN == 300 # starting: retries async def test_a_start_that_raises_is_tried_again_then_given_up_on(tmp_path): output = RecordingRuntimeOutput() broken = FakePeripheral("broken", failures=10) runtime = await run(tmp_path, broken, output=output) assert runtime.status(broken) == PeripheralStatus(S.WAITING, K.RETRYING, "broken broke; trying again in 0.01 s") await until(runtime, lambda: state(runtime, broken) == S.FAILED) assert runtime.status(broken) == PeripheralStatus(S.FAILED, K.GAVE_UP, "broken broke") assert broken.calls == ["start", "stop"] * 4 # the first, then one per retry delay; each releases what it holds assert output.last("broken") == PeripheralStatus(S.FAILED, K.GAVE_UP, "broken broke") async def test_a_start_that_hangs_times_out_and_is_tried_again(tmp_path): class Hangs(FakePeripheral): start_timeout = 0.01 async def start(self): await super().start() if len(self.calls) == 1: await asyncio.Event().wait() hangs = Hangs("hangs") runtime = await run(tmp_path, hangs) assert runtime.status(hangs) == PeripheralStatus( S.WAITING, K.RETRYING, "didn't start within 0.01 s; trying again in 0.01 s" ) await until(runtime, lambda: state(runtime, hangs) == S.RUNNING) assert hangs.calls == ["start", "stop", "start"] async def test_a_start_cancelled_from_inside_is_a_failure(tmp_path): class Cancelled(FakePeripheral): async def start(self): await super().start() if len(self.calls) == 1: raise asyncio.CancelledError # e.g. a task it awaited was cancelled cancelled = Cancelled("cancelled") runtime = await run(tmp_path, cancelled) assert runtime.status(cancelled) == PeripheralStatus( S.WAITING, K.RETRYING, "CancelledError; trying again in 0.01 s" ) await until(runtime, lambda: state(runtime, cancelled) == S.RUNNING) async def test_a_start_that_ignores_being_stopped_is_left_behind(tmp_path, monkeypatch): monkeypatch.setattr(module, "STOP_TIMEOUT", 0.01) started = asyncio.Event() class Stubborn(FakePeripheral): async def start(self): await super().start() started.set() try: await asyncio.Event().wait() except asyncio.CancelledError: await asyncio.sleep(0.05) # goes on regardless stubborn = Stubborn("stubborn") runtime = Runtime(tmp_path / "data", [stubborn], platform=build_test_platform(tmp_path)) await runtime.start() await started.wait() await asyncio.wait_for(runtime.disable(stubborn), 1) assert state(runtime, stubborn) == S.DISABLED await settle(runtime) assert state(runtime, stubborn) == S.DISABLED async def test_a_start_that_raises_once_runs_on_the_retry(tmp_path): flaky = FakePeripheral("flaky", failures=1) runtime = await run(tmp_path, flaky) await until(runtime, lambda: state(runtime, flaky) == S.RUNNING) assert flaky.calls == ["start", "stop", "start"] async def test_a_failed_one_isnt_revived_by_a_replug_only_by_the_user(tmp_path): stick, integration = radio(ZIGBEE), zigbee(failures=10) runtime = await run(tmp_path, stick, integration) await until(runtime, lambda: state(runtime, integration) == S.FAILED) stick.provided = [] await changed(runtime, stick) stick.provided = [ZIGBEE] await changed(runtime, stick) assert state(runtime, integration) == S.FAILED assert integration.calls == ["start", "stop"] * 4 integration.failures = 0 await runtime.restart(integration) await settle(runtime) assert state(runtime, integration) == S.RUNNING async def test_a_failed_one_tries_again_once_its_settings_change(tmp_path): class Channel(BaseModel): channel: int = 11 integration = FakePeripheral("zigbee", failures=4, settings=Channel) runtime = await run(tmp_path, integration) await until(runtime, lambda: state(runtime, integration) == S.FAILED) await runtime.update_settings(integration, {"channel": 15}) await settle(runtime) assert state(runtime, integration) == S.RUNNING assert integration.settings == Channel(channel=15) # disabled async def test_disabled_is_kept_and_never_revived_by_a_replug(tmp_path): store = MemoryDisabledStore() stick, integration = radio(ZIGBEE), zigbee() runtime = await run(tmp_path, stick, integration, disabled=store) await runtime.disable(integration) assert runtime.status(integration) == PeripheralStatus(S.DISABLED) assert integration.calls == ["start", "stop"] assert store.is_disabled("zigbee") stick.provided = [] await changed(runtime, stick) stick.provided = [ZIGBEE] await changed(runtime, stick) assert state(runtime, integration) == S.DISABLED with pytest.raises(ValueError, match="enable it"): await runtime.restart(integration) again = zigbee() # after a reboot runtime = await run(tmp_path / "again", radio(ZIGBEE), again, disabled=store) assert state(runtime, again) == S.DISABLED and again.calls == [] await runtime.enable(again) await settle(runtime) assert state(runtime, again) == S.RUNNING assert not store.is_disabled("zigbee") # self-stop and crashes STOPPED = "stopped by itself: waits for its needs to change or a restart" async def test_one_that_stops_by_itself_waits_for_its_needs_to_change(tmp_path): stick, integration = radio(ZIGBEE), zigbee() runtime = await run(tmp_path, stick, integration) await integration.output.peripheral_did_stop(integration) assert runtime.status(integration) == PeripheralStatus(S.WAITING, K.STOPPED_ITSELF, STOPPED) assert integration.calls == ["start", "stop"] await runtime.refresh() assert runtime.status(integration) == PeripheralStatus(S.WAITING, K.STOPPED_ITSELF, STOPPED) stick.provided = [] # replugged await changed(runtime, stick) stick.provided = [ZIGBEE] await changed(runtime, stick) assert state(runtime, integration) == S.RUNNING async def test_one_that_stopped_by_itself_starts_once_its_optional_provider_blips(tmp_path): border = FakePeripheral("otbr", provides=[THREAD]) matter = FakePeripheral("matter", [Need("thread", is_required=False)], answer=True) runtime = await run(tmp_path, border, matter) await matter.output.peripheral_did_stop(matter) await runtime.restart(border) # its need went (it isn't handed one that doesn't run) and came back await settle(runtime) assert state(runtime, matter) == S.RUNNING and matter.calls == ["start", "stop", "start"] async def test_one_that_stopped_by_itself_starts_once_restarted(tmp_path): integration = FakePeripheral("hue") runtime = await run(tmp_path, integration) await integration.output.peripheral_did_stop(integration) await runtime.restart(integration) await settle(runtime) assert state(runtime, integration) == S.RUNNING async def test_one_that_crashes_is_started_again_then_given_up(tmp_path): integration = FakePeripheral("zigbee") runtime = await run(tmp_path, integration) for _ in range(len(module.RETRY_DELAYS) + 1): await until(runtime, lambda: state(runtime, integration) == S.RUNNING) await integration.output.peripheral_did_fail(integration, "Lost the connection to the Zigbee radio.") assert runtime.status(integration) == PeripheralStatus( S.FAILED, K.GAVE_UP, "Lost the connection to the Zigbee radio." ) await runtime.restart(integration) await settle(runtime) assert state(runtime, integration) == S.RUNNING async def test_the_retries_are_the_ones_it_is_given(tmp_path): integration = FakePeripheral("zigbee") runtime = await run(tmp_path, integration, retry_delays=[0]) # a test's own: once, at once await integration.output.peripheral_did_fail(integration, "Lost the radio.") await until(runtime, lambda: state(runtime, integration) == S.RUNNING) await integration.output.peripheral_did_fail(integration, "Lost the radio.") await settle(runtime) assert runtime.status(integration) == PeripheralStatus(S.FAILED, K.GAVE_UP, "Lost the radio.") async def test_a_failure_told_from_inside_its_start_fails_that_start(tmp_path): class GivesUp(FakePeripheral): async def start(self): await super().start() if len(self.calls) == 1: await self.output.peripheral_did_fail(self, "Wrong credentials: re-enter them.") raise RuntimeError("can't go on") hue = GivesUp("hue") runtime = await run(tmp_path, hue) assert runtime.status(hue) == PeripheralStatus( S.WAITING, K.RETRYING, "Wrong credentials: re-enter them.; trying again in 0.01 s" ) await until(runtime, lambda: state(runtime, hue) == S.RUNNING) assert hue.calls == ["start", "stop", "start"] # calls from what a peripheral runs in the background, and from the runtime's own output async def test_a_call_from_a_task_a_start_spawned_returns_once_acted_on(tmp_path): seen: list[S] = [] class Stick(FakePeripheral): async def start(self): await super().start() self.task = asyncio.create_task(self.flash_later()) async def flash_later(self): await asyncio.sleep(0.01) self.provided = [] # busy: being flashed await self.output.peripheral_did_change_provided(self) seen.append(state(runtime, integration)) stick, integration = Stick("stick", provides=[ZIGBEE]), zigbee() runtime = await run(tmp_path, stick, integration) await stick.task assert seen == [S.WAITING] # it let go of the stick before the flash goes on async def test_a_call_from_a_task_a_hook_awaits_returns_at_once(tmp_path, monkeypatch): """A task a hook awaits counts as inside it (a TaskGroup reconnecting its nodes): the runtime acts once the hook returned, rather than the hook waiting on the runtime that waits on it.""" monkeypatch.setattr(module, "HOOK_TIMEOUT", 0.5) class Reconnects(FakePeripheral): async def needed_peripheral_did_change(self, change): async with asyncio.TaskGroup() as group: group.create_task(self.output.peripheral_did_change_provided(self)) return await super().needed_peripheral_did_change(change) stick, integration = radio(ZIGBEE), Reconnects("zigbee", [Need("zigbee")], answer=True) runtime = await run(tmp_path, stick, integration) stick.provided = [MOVED] await changed(runtime, stick) assert (runtime.status(integration), integration.calls) == (PeripheralStatus(S.RUNNING), ["start"]) async def test_a_call_from_a_task_a_stop_awaits_returns_at_once(tmp_path, monkeypatch): monkeypatch.setattr(module, "STOP_TIMEOUT", 0.5) stopped: list[bool] = [] class LetsGo(FakePeripheral): async def stop(self): await super().stop() await asyncio.gather(self.output.peripheral_did_change_provided(self)) # its nodes go, each telling stopped.append(True) integration = LetsGo("esphome") runtime = await run(tmp_path, integration) await runtime.disable(integration) assert stopped == [True] # ran to its end, never cut short async def test_a_call_scheduled_by_a_status_callback_returns_once_acted_on(tmp_path): seen: list[S] = [] integration, ran = FakePeripheral("zigbee"), asyncio.Event() class Output(RecordingRuntimeOutput): def peripheral_did_change_status(self, peripheral, status): super().peripheral_did_change_status(peripheral, status) if status.state == S.RUNNING: self.task = asyncio.ensure_future(disable()) async def disable(): await ran.wait() await runtime.disable(integration) seen.append(state(runtime, integration)) output = Output() runtime = await run(tmp_path, integration, output=output) ran.set() await output.task assert seen == [S.DISABLED] async def test_a_call_scheduled_from_what_a_starts_task_set_off_returns_once_acted_on(tmp_path): """The runtime's own work is inside no peripheral's call, though a task of one's start set it off: what its owner schedules from there waits like any other caller.""" seen: list[S] = [] integration, released = zigbee(), asyncio.Event() class Brings(FakePeripheral): async def start(self): await super().start() async with asyncio.TaskGroup() as group: group.create_task(self.bring()) await released.wait() async def bring(self): self.provided = [ZIGBEE] await self.output.peripheral_did_change_provided(self) class Output(RecordingRuntimeOutput): def peripheral_did_change_status(self, peripheral, status): super().peripheral_did_change_status(peripheral, status) if peripheral is integration and status.kind == K.NEEDS_STARTING: self.task = asyncio.ensure_future(disable()) async def disable(): await runtime.disable(integration) seen.append(state(runtime, integration)) output = Output() runtime = await run(tmp_path, Brings("stick"), integration, output=output, settled=False) await until(runtime, lambda: hasattr(output, "task"), settled=False) await output.task released.set() assert seen == [S.DISABLED] class Keeper(FakePeripheral): """Keeps a connection in a task of its own, which tells the runtime it can't go on; its stop cancels that task and waits for it, as a controller's does.""" def __init__(self, tell: Callable[[FakePeripheral], Awaitable[Any]]): super().__init__("keeper") self.tell = tell async def start(self): await super().start() self.keeper = asyncio.create_task(self.keep()) async def keep(self): await asyncio.sleep(0) if len(self.calls) == 1: await self.tell(self) async def stop(self): await super().stop() self.keeper.cancel() await asyncio.wait([self.keeper]) @pytest.mark.parametrize( ("tell", "status"), [ (lambda p: p.output.peripheral_did_fail(p, "Lost the server."), PeripheralStatus(S.WAITING, K.RETRYING)), (lambda p: p.output.peripheral_did_stop(p), PeripheralStatus(S.WAITING, K.STOPPED_ITSELF)), ], ) async def test_one_that_tells_from_its_own_task_is_stopped_in_the_runtimes(tmp_path, tell, status): keeper = Keeper(tell) runtime = await run(tmp_path, keeper) await asyncio.wait([keeper.keeper]) await settle(runtime) assert (keeper.calls, runtime.status(keeper).state, runtime.status(keeper).kind) == ( ["start", "stop"], status.state, status.kind, ) assert keeper.keeper.cancelled() # its stop ended the task that told async def test_a_pass_a_call_set_off_goes_on_when_the_caller_is_cancelled(tmp_path): heard, release = asyncio.Event(), asyncio.Event() class Slow(FakePeripheral): async def needed_peripheral_did_change(self, change): heard.set() await release.wait() return await super().needed_peripheral_did_change(change) stick, integration = radio(ZIGBEE), Slow("zigbee", [Need("zigbee")], answer=True) runtime = await run(tmp_path, stick, integration) stick.provided = [MOVED] caller = asyncio.create_task(stick.output.peripheral_did_change_provided(stick)) # e.g. a node's connection await heard.wait() caller.cancel() # e.g. the node was unpaired meanwhile release.set() await settle(runtime) assert integration.changes == [PeripheralChange("zigbee", ZIGBEE, MOVED)] # the hook ran to its end assert (state(runtime, integration), integration.calls) == (S.RUNNING, ["start"]) # a server next to what needs it, and what a peripheral brings along while it runs def matter_and_server() -> tuple[FakePeripheral, FakePeripheral]: return FakePeripheral("matter", [Need("matter")]), FakePeripheral( "matter-server", provides=[SERVER], is_on_demand=True ) async def test_a_server_runs_while_what_needs_it_runs(tmp_path): matter, server = matter_and_server() runtime = await run(tmp_path, server, matter) assert (state(runtime, matter), state(runtime, server)) == (S.RUNNING, S.RUNNING) await runtime.disable(matter) assert server.calls == ["start", "stop"] assert runtime.status(server) == PeripheralStatus(S.WAITING, K.UNUSED, "nothing that runs uses it") await runtime.enable(matter) await settle(runtime) assert (state(runtime, matter), state(runtime, server)) == (S.RUNNING, S.RUNNING) async def test_a_server_only_a_failed_one_needs_stops(tmp_path): matter, server = matter_and_server() runtime = await run(tmp_path, server, matter) for _ in range(len(module.RETRY_DELAYS) + 1): await until(runtime, lambda: state(runtime, matter) == S.RUNNING) await matter.output.peripheral_did_fail(matter, "gave up") assert runtime.status(server) == PeripheralStatus(S.WAITING, K.UNUSED, "nothing that runs uses it") async def test_what_it_brought_along_while_running_goes_when_it_stops(tmp_path): esphome = FakePeripheral("esphome") proxy = FakePeripheral("esphome:aa", provides=[Endpoint("ble", "esphome-proxy", "esphome:aa")]) router = FakePeripheral("router", [Need("ble", ["esphome-proxy"], is_many=True, is_required=False)], answer=True) runtime = await run(tmp_path, router, esphome) esphome.provided.append(proxy) # a node connected await changed(runtime, esphome) assert state(runtime, proxy) == S.RUNNING assert router.peripherals.endpoints("ble") == list(proxy.provides) await runtime.disable(esphome) # it holds on to it: it goes all the same assert proxy not in runtime.peripherals assert proxy.calls == ["start", "stop"] assert router.peripherals.endpoints("ble") == [] async def test_what_it_brings_along_is_known_under_its_key(tmp_path): proxy = FakePeripheral("aa") esphome = FakePeripheral("esphome", provides=[proxy]) runtime = await run(tmp_path, esphome) assert (proxy.key, proxy.name) == ("esphome/aa", "aa") and runtime.peripheral("esphome/aa") is proxy async def test_each_one_keeps_its_documents_in_a_folder_of_its_own(tmp_path): proxy = FakePeripheral("aa") esphome = FakePeripheral("esphome", provides=[proxy]) runtime = await run(tmp_path, esphome) assert esphome.platform is proxy.platform is runtime.platform # one per host assert esphome.platform.documents_folder(esphome) == tmp_path / "data" / "peripherals" / "esphome" assert proxy.platform.documents_folder(proxy) == tmp_path / "data" / "peripherals" / "esphome" / "aa" assert (tmp_path / "data" / "peripherals" / "esphome" / "aa").is_dir() # once used async def test_every_one_runs_on_the_runtimes_platform(tmp_path): platform = Platform(documents_root=tmp_path / "documents", region="Europe") given = FakePeripheral("given") given.platform = Platform(documents_root=tmp_path / "another") # e.g. a controller built with another one await run(tmp_path, given, platform=platform) assert given.platform is platform async def test_the_owner_hears_when_one_goes(tmp_path): output, radio = RecordingRuntimeOutput(), FakePeripheral("radio") scanner = FakePeripheral("usb", provides=[radio]) runtime = await run(tmp_path, scanner, output=output) scanner.provided.clear() # unplugged await changed(runtime, scanner) assert output.disappeared == [radio] and radio.key == "usb/radio" # it says which one went assert radio not in runtime.peripherals async def test_what_is_read_while_one_goes_names_only_what_is_still_there(tmp_path): seen: list[list[str]] = [] class Node(FakePeripheral): async def stop(self): await super().stop() seen.append([runtime.peripheral(key).key for key in runtime.uses(app)]) # the Hub reads meanwhile node = Node("node", provides=[Endpoint("bridge", is_shared=True)]) bridge = FakePeripheral("bridge", provides=[node]) app = FakePeripheral("app", [Need("bridge", is_required=False)], answer=True) runtime = await run(tmp_path, bridge, app) bridge.provided.clear() # the node went await changed(runtime, bridge) assert (seen, node.calls) == ([[]], ["start", "stop"]) async def test_one_that_failed_stays_failed_when_brought_along_anew(tmp_path): esphome = FakePeripheral("esphome", provides=[FakePeripheral("aa", failures=10)]) runtime = await run(tmp_path, esphome) await until(runtime, lambda: state(runtime, runtime.peripheral("esphome/aa")) == S.FAILED) again = FakePeripheral("aa") # the node connected again esphome.provided[:] = [again] await changed(runtime, esphome) assert runtime.status(again) == PeripheralStatus(S.FAILED, K.GAVE_UP, "aa broke") await runtime.restart(again) await settle(runtime) assert state(runtime, again) == S.RUNNING async def test_a_second_one_of_a_key_is_left_out_and_logged_once(tmp_path, caplog): first = FakePeripheral("mqtt", provides=[Endpoint("mqtt", "a", "x", is_shared=True)], is_on_demand=True) second = FakePeripheral("mqtt", provides=[Endpoint("mqtt", "b", "y", is_shared=True)], is_on_demand=True) one, two = FakePeripheral("one", [Need("mqtt", ["a"])]), FakePeripheral("two", [Need("mqtt", ["b"])]) output = RecordingRuntimeOutput() runtime = await run(tmp_path, first, one, second, two, output=output) await runtime.refresh() assert runtime.peripherals == [first, one, two] and runtime.peripheral("mqtt") is first with pytest.raises(LookupError): runtime.status(second) # nothing the Hub keys by its key: no status, no settings, never gone assert output.last("mqtt") == PeripheralStatus(S.RUNNING) and second.calls == [] assert (state(runtime, one), runtime.status(two)) == ( S.RUNNING, PeripheralStatus(S.WAITING, K.NEEDS_UNBOUND, "need mqtt/b: nothing offers it"), ) assert caplog.text.count("Another peripheral has the key mqtt") == 1 async def test_one_brought_along_under_a_taken_key_is_left_out(tmp_path): proxy, again = FakePeripheral("aa"), FakePeripheral("aa") runtime = await run(tmp_path, FakePeripheral("esphome", provides=[proxy, again])) assert runtime.peripheral("esphome/aa") is proxy and again not in runtime.peripherals assert (proxy.calls, again.calls) == (["start"], []) async def test_adding_one_whose_key_is_taken_raises(tmp_path): output, original = RecordingRuntimeOutput(), FakePeripheral("zigbee") runtime = await run(tmp_path, original, output=output) fork = FakePeripheral("zigbee") # e.g. a fork installed beside the original with pytest.raises(ValueError, match="another peripheral has the key zigbee"): await runtime.add(fork) await settle(runtime) assert runtime.peripherals == [original] and output.last("zigbee") == PeripheralStatus(S.RUNNING) await runtime.remove(fork) # never added: nothing goes assert output.disappeared == [] and state(runtime, original) == S.RUNNING async def test_what_uses_a_provider_stops_before_it(tmp_path): stopped: list[str] = [] class Logged(FakePeripheral): async def stop(self): stopped.append(self.name) server = Logged("matter-server", provides=[SERVER], is_on_demand=True) bridge = Logged("bridge", [Need("matter")], [Endpoint("bridge", is_shared=True)], is_on_demand=True) app = Logged("app", [Need("bridge")]) runtime = await run(tmp_path, app, bridge, server) # listed users first await runtime.disable(app) assert stopped == ["app", "bridge", "matter-server"] await runtime.enable(app) await settle(runtime) stopped.clear() await runtime.stop() assert stopped == ["app", "bridge", "matter-server"] # on demand async def test_one_on_demand_runs_only_while_something_that_runs_binds_it(tmp_path): router = FakePeripheral("router", provides=[Endpoint("ble", "router", is_shared=True)], is_on_demand=True) matter = FakePeripheral("matter", [Need("ble", ["router"], is_required=False)]) runtime = await run(tmp_path, router, matter) assert state(runtime, router) == S.RUNNING await runtime.disable(matter) assert runtime.status(router) == PeripheralStatus(S.WAITING, K.UNUSED, "nothing that runs uses it") assert router.calls == ["start", "stop"] async def test_one_on_demand_that_nothing_binds_never_starts(tmp_path): router = FakePeripheral("router", provides=[Endpoint("ble", "router", is_shared=True)], is_on_demand=True) runtime = await run(tmp_path, router) assert runtime.status(router) == PeripheralStatus(S.WAITING, K.UNUSED, "nothing that runs uses it") assert router.calls == [] async def test_one_on_demand_stops_once_what_needs_it_cant_run(tmp_path): server = FakePeripheral("matter-server", provides=[SERVER], is_on_demand=True) matter = FakePeripheral("matter", [Need("matter"), Need("zigbee")]) runtime = await run(tmp_path, server, matter) assert state(runtime, server) == S.WAITING # matter waits for zigbee: no reason to run its server assert runtime.status(matter).detail == UNBOUND # readiness class Gated(FakePeripheral): """Serves once ``gate`` opens: its start returns then.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.gate = asyncio.Event() async def start(self): await super().start() await self.gate.wait() async def test_what_needs_a_provider_starts_once_its_start_returned(tmp_path): server = Gated("matter-server", provides=[SERVER], is_on_demand=True) matter = FakePeripheral("matter", [Need("matter")]) runtime = await run(tmp_path, server, matter, settled=False) await until(runtime, lambda: state(runtime, server) == S.STARTING, settled=False) assert runtime.status(matter) == PeripheralStatus(S.WAITING, K.NEEDS_STARTING, "waiting for matter-server") server.gate.set() await settle(runtime) assert state(runtime, matter) == S.RUNNING async def test_a_running_peripheral_rides_out_its_provider_restarting(tmp_path): server = Gated("matter-server", provides=[SERVER], is_on_demand=True) server.gate.set() matter = FakePeripheral("matter", [Need("matter")]) runtime = await run(tmp_path, server, matter) server.gate.clear() await runtime.restart(server) assert state(runtime, server) == S.STARTING assert state(runtime, matter) == S.RUNNING and matter.calls == ["start"] server.gate.set() @pytest.mark.parametrize("ends", ["restart", "disable"]) async def test_what_runs_on_an_in_process_provider_stops_first_and_starts_once_it_runs_again(tmp_path, ends): order: list[str] = [] class Ordered(Gated): async def start(self): order.append(f"{self.name} start") await super().start() async def stop(self): order.append(f"{self.name} stop") zeroconf, homekit = Ordered("zeroconf", is_on_demand=True), Ordered("homekit", [Need("mdns")]) zeroconf.provided = [Endpoint("mdns", "zeroconf", "zeroconf", is_shared=True, instance=zeroconf)] # its browser zeroconf.gate.set() homekit.gate.set() runtime = await run(tmp_path, zeroconf, homekit) order.clear() zeroconf.gate.clear() await getattr(runtime, ends)(zeroconf) assert order[:2] == ["homekit stop", "zeroconf stop"] # what it registered goes with the one that ran if ends == "disable": await runtime.enable(zeroconf) assert runtime.status(homekit) == PeripheralStatus(S.WAITING, K.NEEDS_STARTING, "waiting for zeroconf") zeroconf.gate.set() await settle(runtime) assert order[2:] == ["zeroconf start", "homekit start"] and state(runtime, homekit) == S.RUNNING async def test_an_optional_need_is_handed_over_once_its_provider_runs(tmp_path): border = Gated("otbr", provides=[THREAD], is_on_demand=True) matter = FakePeripheral("matter", [Need("thread", is_required=False)], answer=True) runtime = await run(tmp_path, border, matter, settled=False) await until(runtime, lambda: state(runtime, matter) == S.RUNNING, settled=False) assert state(runtime, border) == S.STARTING # it doesn't hold it back assert matter.peripherals.bound == {} # nor is it handed over before it serves assert runtime.bound(matter) == runtime.providers(matter) == {} # what the Hub shows: what it was handed border.gate.set() await settle(runtime) assert matter.changes == [PeripheralChange("thread", None, THREAD)] and matter.calls == ["start"] assert (runtime.bound(matter), runtime.providers(matter)) == ({"thread": THREAD}, {"thread": "otbr"}) async def test_an_optional_need_rides_out_its_provider_restarting(tmp_path): border = Gated("otbr", provides=[THREAD], is_on_demand=True) border.gate.set() matter = FakePeripheral("matter", [Need("thread", is_required=False)], answer=True) runtime = await run(tmp_path, border, matter) changes = list(matter.changes) border.gate.clear() await runtime.restart(border) assert state(runtime, border) == S.STARTING assert matter.peripherals.endpoint("thread") == THREAD and matter.changes == changes border.gate.set() # a start cut short async def starting(tmp_path, *peripherals: FakePeripheral): """A runtime of ``peripherals`` with the last one in the middle of its start, held there.""" runtime = await run(tmp_path, *peripherals, settled=False) await until(runtime, lambda: peripherals[-1].calls == ["start"], settled=False) return runtime async def test_a_start_cut_short_by_disabling_it_stays_disabled(tmp_path): slow = Gated("slow") runtime = await starting(tmp_path, slow) await runtime.disable(slow) slow.gate.set() await settle(runtime) assert (state(runtime, slow), slow.calls) == (S.DISABLED, ["start", "stop"]) async def test_a_start_cut_short_by_a_restart_starts_anew(tmp_path): slow = Gated("slow") runtime = await starting(tmp_path, slow) await runtime.restart(slow) await until(runtime, lambda: slow.calls == ["start", "stop", "start"], settled=False) slow.gate.set() await settle(runtime) assert (state(runtime, slow), slow.calls) == (S.RUNNING, ["start", "stop", "start"]) async def test_a_start_cut_short_by_losing_its_need_waits_for_it(tmp_path): stick, slow = radio(ZIGBEE), Gated("zigbee", [Need("zigbee")]) runtime = await starting(tmp_path, stick, slow) stick.provided = [] await changed(runtime, stick) assert runtime.status(slow) == PeripheralStatus(S.WAITING, K.NEEDS_UNBOUND, UNBOUND) assert slow.calls == ["start", "stop"] async def test_a_start_cut_short_by_the_runtime_stopping_is_stopped(tmp_path): slow = Gated("slow") runtime = await starting(tmp_path, slow) await runtime.stop() assert slow.calls == ["start", "stop"] async def test_one_replaced_by_another_of_its_name_goes_and_the_other_runs(tmp_path): output, old, new = RecordingRuntimeOutput(), FakePeripheral("aa"), FakePeripheral("aa") esphome = FakePeripheral("esphome", provides=[old]) runtime = await run(tmp_path, esphome, output=output) esphome.provided[:] = [new] # the node reconnected await changed(runtime, esphome) assert (old.calls, output.disappeared) == (["start", "stop"], [old]) assert state(runtime, new) == S.RUNNING and runtime.peripheral("esphome/aa") is new # settings and platform facts async def test_settings_are_kept_and_handed_over_or_restart_it(tmp_path): class Channel(BaseModel): channel: int = 11 integration = FakePeripheral("zigbee", settings=Channel, answer=True) runtime = await run(tmp_path, integration) assert integration.settings == Channel() assert await runtime.update_settings(integration, {"channel": 15}) == Channel(channel=15) assert integration.changes == [("settings", Channel())] assert integration.calls == ["start"] integration.answer = False await runtime.update_settings(integration, {"channel": 20}) await settle(runtime) assert integration.calls == ["start", "stop", "start"] again = FakePeripheral("zigbee", settings=Channel) await run(tmp_path, again) # the same data: after a reboot assert again.settings == Channel(channel=20) async def test_one_without_settings_takes_none(tmp_path): host = FakePeripheral("host") runtime = await run(tmp_path, host) assert host.settings == NoSettings() with pytest.raises(ValidationError): await runtime.update_settings(host, {"x": 1}) await runtime.update_settings(host, {}) assert runtime.state["settings"] == {} # nothing kept for it async def test_changed_facts_replace_the_platform_and_are_handed_over_or_restart_it(tmp_path): handles, restarts = FakePeripheral("handles", answer=True), FakePeripheral("restarts") runtime = await run(tmp_path, handles, restarts) before, europe = runtime.platform, replace(runtime.platform, region="Europe") await runtime.update_platform(europe) await settle(runtime) assert runtime.platform is handles.platform is restarts.platform is europe assert handles.changes == restarts.changes == [("platform", before)] assert (handles.calls, restarts.calls) == (["start"], ["start", "stop", "start"]) async def test_changed_facts_reach_one_still_starting_once_it_runs(tmp_path): gate = asyncio.Event() class Slow(FakePeripheral): async def start(self): await super().start() await gate.wait() handles, restarts = Slow("handles", answer=True), Slow("restarts") runtime = await run(tmp_path, handles, restarts, settled=False) await until(runtime, lambda: state(runtime, handles) == state(runtime, restarts) == S.STARTING, settled=False) before = runtime.platform await runtime.update_platform(replace(before, region="Europe")) # it may have read the one before await runtime.update_platform(replace(before, region="USA")) assert handles.changes == restarts.changes == [] and handles.platform.region == "USA" gate.set() await settle(runtime) assert handles.changes == restarts.changes == [("platform", before)] # once, since what it read assert (handles.calls, restarts.calls) == (["start"], ["start", "stop", "start"]) assert state(runtime, handles) == state(runtime, restarts) == S.RUNNING async def test_new_settings_reach_one_still_starting_once_it_runs(tmp_path): handles, restarts = Gated("handles", answer=True, settings=Channel), Gated("restarts", settings=Channel) runtime = await run(tmp_path, handles, restarts, settled=False) await until(runtime, lambda: state(runtime, handles) == state(runtime, restarts) == S.STARTING, settled=False) for slow in (handles, restarts): await runtime.update_settings(slow, {"channel": 15}) # it may have read the ones before await runtime.update_settings(slow, {"channel": 20}) assert handles.changes == restarts.changes == [] handles.gate.set() restarts.gate.set() await settle(runtime) assert handles.changes == restarts.changes == [("settings", Channel())] # once, since what it read assert (handles.calls, restarts.calls) == (["start"], ["start", "stop", "start"]) assert handles.settings == restarts.settings == Channel(channel=20) assert state(runtime, handles) == state(runtime, restarts) == S.RUNNING async def test_facts_that_restart_one_once_it_runs_leave_it_to_read_its_new_settings(tmp_path): restarts = Gated("restarts", settings=Channel) runtime = await run(tmp_path, restarts, settled=False) await until(runtime, lambda: state(runtime, restarts) == S.STARTING, settled=False) before = runtime.platform await runtime.update_platform(replace(before, region="Europe")) await runtime.update_settings(restarts, {"channel": 15}) restarts.gate.set() await settle(runtime) assert restarts.changes == [("platform", before)] # restarted for them: it read the settings anew assert restarts.calls == ["start", "stop", "start"] and restarts.settings == Channel(channel=15) async def test_a_hook_told_once_it_runs_that_raises_is_a_failure(tmp_path): raises = Gated("raises", answer=RuntimeError("confused")) runtime = await run(tmp_path, raises, settled=False) await until(runtime, lambda: state(runtime, raises) == S.STARTING, settled=False) await runtime.update_platform(replace(runtime.platform, region="Europe")) raises.gate.set() await settle(runtime) assert runtime.status(raises) == PeripheralStatus(S.WAITING, K.RETRYING, "confused; trying again in 0.01 s") async def test_new_settings_of_a_disabled_one_are_kept_and_start_nothing(tmp_path): integration = FakePeripheral("zigbee", settings=Channel) runtime = await run(tmp_path, integration) await runtime.disable(integration) await runtime.update_settings(integration, {"channel": 15}) await settle(runtime) assert (state(runtime, integration), integration.calls) == (S.DISABLED, ["start", "stop"]) assert runtime.stored_settings(integration) == {"channel": 15} async def test_any_peripheral_reads_the_facts_and_what_it_learned_replaces_the_platform(tmp_path): output, europe = RecordingRuntimeOutput(), Platform(documents_root=tmp_path, region="Europe") router, matter = FakePeripheral("my-border-router"), FakePeripheral("matter", answer=True) # one of the user's own runtime = await run(tmp_path, router, matter, output=output, platform=europe) assert router.platform.region == "Europe" await router.output.peripheral_did_learn(router, {"thread_dataset": "0e08"}) await settle(runtime) assert output.learned == [("my-border-router", {"thread_dataset": "0e08"})] # for the host to keep assert matter.platform == runtime.platform == replace(europe, thread_dataset="0e08") assert matter.changes == [("platform", europe)] await router.output.peripheral_did_learn(router, {"thread_dataset": "0e08"}) # again, at the next boot await settle(runtime) assert matter.changes == [("platform", europe)] # nothing changed async def test_only_the_facts_a_platform_holds_are_learned(tmp_path): output, router = RecordingRuntimeOutput(), FakePeripheral("my-border-router") runtime = await run(tmp_path, router, output=output) root = runtime.platform.documents_root learned = {"thread_dataset": "0e08", "thread_channel": 25, "documents_root": tmp_path / "elsewhere"} await router.output.peripheral_did_learn(router, learned) # a newer peripheral's, and a resource: no facts await settle(runtime) assert output.learned == [("my-border-router", {"thread_dataset": "0e08"})] assert (runtime.platform.thread_dataset, runtime.platform.documents_root) == ("0e08", root) await router.output.peripheral_did_learn(router, {"thread_channel": 26}) await settle(runtime) assert len(output.learned) == 1 async def test_one_added_while_it_runs_runs_and_one_removed_is_gone(tmp_path): output, hue = RecordingRuntimeOutput(), FakePeripheral("hue") runtime = await run(tmp_path, FakePeripheral("host"), output=output) await runtime.add(hue) # installed while the hub runs await settle(runtime) assert state(runtime, hue) == S.RUNNING await runtime.remove(hue) assert hue.calls == ["start", "stop"] and hue not in runtime.peripherals assert output.disappeared == [hue] # one that misbehaves stops nothing else class Channel(BaseModel): channel: int = 11 async def test_invalid_stored_settings_fail_only_their_peripheral(tmp_path): (tmp_path / "data").mkdir() (tmp_path / "data" / "state.json").write_text(json.dumps({"settings": {"zigbee": {"channel": "eleven"}}})) host, integration = FakePeripheral("host"), FakePeripheral("zigbee", settings=Channel) runtime = await run(tmp_path, host, integration) assert state(runtime, host) == S.RUNNING assert runtime.status(integration) == PeripheralStatus( S.FAILED, K.INVALID_SETTINGS, "Invalid settings: channel: Input should be a valid integer, unable to parse string as an integer", ) assert runtime.stored_settings(integration) == {"channel": "eleven"} # what the Hub shows with the failure await runtime.restart(integration) # the user tries again: they still don't validate await settle(runtime) assert runtime.status(integration).kind == K.INVALID_SETTINGS and integration.calls == [] await runtime.update_settings(integration, {"channel": 15}) await settle(runtime) assert state(runtime, integration) == S.RUNNING and integration.settings == Channel(channel=15) assert runtime.stored_settings(integration) == {"channel": 15} async def test_one_disabled_with_invalid_stored_settings_fails_once_enabled(tmp_path): (tmp_path / "data").mkdir() (tmp_path / "data" / "state.json").write_text(json.dumps({"settings": {"zigbee": {"channel": "eleven"}}})) integration = FakePeripheral("zigbee", settings=Channel) runtime = await run(tmp_path, integration, disabled=MemoryDisabledStore(["zigbee"])) assert state(runtime, integration) == S.DISABLED await runtime.enable(integration) await settle(runtime) assert runtime.status(integration).kind == K.INVALID_SETTINGS and integration.calls == [] async def test_why_stored_settings_are_invalid_reads_as_they_load_also_while_disabled(tmp_path): (tmp_path / "data").mkdir() stored = {"zigbee": {"channel": "eleven"}, "network": {"channel": "eleven", "permit_join": True}} (tmp_path / "data" / "state.json").write_text(json.dumps({"settings": stored})) integration, network = FakePeripheral("zigbee", settings=Channel), FakePeripheral("network", settings=Network) runtime = await run(tmp_path, integration, network, disabled=MemoryDisabledStore(["zigbee"])) error = runtime.settings_error(integration) # what the Hub shows with them: it fails once enabled assert error is not None and [e["loc"] for e in error.errors()] == [("channel",)] assert runtime.settings_error(network) is None # a read-only value is never loaded await runtime.update_settings(integration, {"channel": 15}) assert runtime.settings_error(integration) is None async def test_stored_settings_it_no_longer_has_are_dropped(tmp_path): (tmp_path / "data").mkdir() stored = {"zigbee": {"channel": 15, "pan_id": 1}, "host": {"old": 1}} # the host's update dropped its settings (tmp_path / "data" / "state.json").write_text(json.dumps({"settings": stored})) host, integration = FakePeripheral("host"), FakePeripheral("zigbee", settings=Channel) runtime = await run(tmp_path, host, integration) assert state(runtime, host) == state(runtime, integration) == S.RUNNING assert integration.settings == Channel(channel=15) assert json.loads((tmp_path / "data" / "state.json").read_text())["settings"] == {"zigbee": {"channel": 15}} async def test_new_settings_it_doesnt_have_are_refused(tmp_path): integration = FakePeripheral("zigbee", settings=Channel) runtime = await run(tmp_path, integration) with pytest.raises(ValidationError, match="pan_id"): await runtime.update_settings(integration, {"channel": 15, "pan_id": 1}) assert integration.settings == Channel() and runtime.state["settings"] == {"zigbee": {"channel": 11}} class Network(BaseModel): channel: int = Field( 11, json_schema_extra={Extra.read_only: True} ) # the live network's, filled in by the peripheral permit_join: bool = False async def test_a_read_only_setting_is_filled_in_by_its_peripheral_and_never_changed_by_an_update(tmp_path): assert Network.model_json_schema()["properties"]["channel"]["readOnly"] is True integration = FakePeripheral("zigbee", settings=Network, answer=True) runtime = await run(tmp_path, integration) integration.settings.channel = 25 # the network it found with pytest.raises(ValidationError, match="frozen"): await runtime.update_settings(integration, {"channel": 15}) assert integration.settings == Network(channel=25) and integration.changes == [] assert await runtime.update_settings(integration, {"channel": 25, "permit_join": True}) == Network( channel=25, permit_join=True ) assert integration.changes == [("settings", Network(channel=25))] async def test_a_read_only_setting_is_never_kept(tmp_path): """It shows what the peripheral filled in while it runs, never a value kept from before (the user's, when the field wasn't read-only yet).""" (tmp_path / "data").mkdir() (tmp_path / "data" / "state.json").write_text(json.dumps({"settings": {"zigbee": {"channel": 15}}})) integration = FakePeripheral("zigbee", settings=Network) runtime = Runtime(tmp_path / "data", [integration], platform=build_test_platform(tmp_path)) assert integration.settings == Network() and runtime.state["settings"] == {"zigbee": {"permit_join": False}} await runtime.start() integration.settings.channel = 25 await runtime.update_settings(integration, {"permit_join": True}) assert json.loads((tmp_path / "data" / "state.json").read_text())["settings"] == {"zigbee": {"permit_join": True}} await runtime.stop() class Keys(BaseModel): network_key: str = Field("", json_schema_extra={Extra.write_only: True}) # set by the user, never shown region: str = "Europe" async def test_a_write_only_setting_is_kept_when_an_update_leaves_it_out(tmp_path): """The host never shows it, so an update of the others comes without it: the one kept stays.""" assert Keys.model_json_schema()["properties"]["network_key"]["writeOnly"] is True server = FakePeripheral("zwave-js-server", settings=Keys) runtime = await run(tmp_path, server) await runtime.update_settings(server, {"network_key": "secret"}) assert await runtime.update_settings(server, {"region": "USA"}) == Keys(network_key="secret", region="USA") assert runtime.stored_settings(server) == {"network_key": "secret", "region": "USA"} # kept, unlike a read-only one async def test_one_that_cant_say_what_it_provides_provides_nothing(tmp_path): class Broken(FakePeripheral): @property def provides(self): raise RuntimeError("confused") host, integration = FakePeripheral("host"), zigbee() runtime = await run(tmp_path, host, Broken("broken"), integration) assert state(runtime, host) == S.RUNNING assert runtime.status(integration) == PeripheralStatus(S.WAITING, K.NEEDS_UNBOUND, UNBOUND) async def test_an_output_that_raises_stops_nothing(tmp_path): class Output(RecordingRuntimeOutput): def peripheral_did_change_status(self, peripheral, status): raise RuntimeError("the Hub broke") host = FakePeripheral("host") runtime = await run(tmp_path, host, output=Output()) assert state(runtime, host) == S.RUNNING async def test_a_corrupt_state_starts_afresh(tmp_path): (tmp_path / "data").mkdir() (tmp_path / "data" / "state.json").write_text('{"settings": {"zigbee": {"chan') # cut by a crash integration = FakePeripheral("zigbee", settings=Channel) runtime = await run(tmp_path, integration) assert state(runtime, integration) == S.RUNNING and integration.settings == Channel() async def test_the_state_is_written_whole_or_not_at_all(tmp_path, monkeypatch): integration = FakePeripheral("zigbee", settings=Channel) runtime = await run(tmp_path, integration) await runtime.update_settings(integration, {"channel": 15}) kept = (tmp_path / "data" / "state.json").read_text() def crash(self, text: str): open(self, "w").close() # the file is cut, then the power goes raise OSError("power lost") monkeypatch.setattr(type(tmp_path), "write_text", crash) with pytest.raises(OSError): await runtime.update_settings(integration, {"channel": 20}) assert (tmp_path / "data" / "state.json").read_text() == kept ================================================================================ # FILE: tests/runtime/test_services.py ================================================================================ """Containers as peripherals: what they render, the ports they get, when they are ready, what they learn.""" import asyncio import json from dataclasses import replace from pathlib import Path from typing import Any import pytest import yaml from pydantic import BaseModel from support import changed, run, settle, state, until from majordom_integration_sdk import Endpoint, Need, Platform, Service from majordom_integration_sdk.runtime import PeripheralState, PeripheralStatus from majordom_integration_sdk.runtime import StatusKind as K from majordom_integration_sdk.runtime.peripherals.hardware.drivers import Silabs from majordom_integration_sdk.runtime.peripherals.services import builtin from majordom_integration_sdk.runtime.peripherals.services.compose import Compose, _Host from majordom_integration_sdk.testing import FakeCompose, FakePeripheral, RecordingRuntimeOutput IP = Endpoint("ip", is_shared=True) MULTIPAN = Endpoint("multipan", "silabs-cpc", "/dev/ttyUSB0", params={"baud": 460800, "flow_control": True}) NCP = Endpoint("zigbee", "ezsp", "/dev/ttyUSB1", params={"baud": 115200, "flow_control": True}) RCP = Endpoint("thread", "spinel", "/dev/ttyUSB2", params={"baud": 460800, "flow_control": True}) @pytest.fixture(autouse=True) def listening(monkeypatch) -> set[int]: """Host ports something listens on; none unless a test says so.""" ports: set[int] = set() monkeypatch.setattr( "majordom_integration_sdk.runtime.peripherals.services.compose._is_listening", ports.__contains__ ) return ports @pytest.fixture(autouse=True) def no_thread_network(monkeypatch): """The built-in border routers form and read no real network.""" async def nothing(*args: Any): return None for talking in ("join_network", "active_dataset", "network_channel", "move_channel"): monkeypatch.setattr(builtin, talking, nothing) def host() -> FakePeripheral: return FakePeripheral("host", provides=[IP]) def stick(name: str, *provides: Endpoint) -> FakePeripheral: return FakePeripheral(name, provides=provides) def zigbee() -> FakePeripheral: return FakePeripheral("zigbee", [Need("zigbee")]) def matter(**compose: Any) -> tuple[FakePeripheral, Service]: server = Service( "matterjs-server", compose={"image": "matter", "environment": {"OTBR": "{peripherals.thread.url}"} | compose}, needs=[Need("ip"), Need("thread", ["otbr-rest"], is_required=False)], provides=[Endpoint("matter", "matter-server-ws", "ws://127.0.0.1:{ports.api}/ws")], ports={"api": 5580}, ) return FakePeripheral("matter", [Need("matter", ["matter-server-ws"])]), server def compose(tmp_path) -> dict[str, Any]: return json.loads((tmp_path / "data" / "peripherals" / "compose" / "compose.json").read_text())["services"] async def test_a_multipan_stick_serves_zigbee_and_matter_through_one_container(tmp_path): radio, integration, (app, server), otbr = stick("sky", MULTIPAN), zigbee(), matter(), builtin.otbr() peripherals = (host(), radio, builtin.silabs_multiprotocol(), otbr, integration, server, app) runtime = await run(tmp_path, FakeCompose(), *peripherals) assert integration.peripherals.endpoint("zigbee") == Endpoint("zigbee", "ezsp", "socket://127.0.0.1:9999") assert app.peripherals.endpoint("matter").url == "ws://127.0.0.1:5580/ws" services = compose(tmp_path) assert set(services) == {"silabs-multiprotocol", "matterjs-server"} # no one binds the standalone border router assert services["silabs-multiprotocol"]["devices"][0] == "/dev/ttyUSB0:/dev/ttyRCP" environment = services["silabs-multiprotocol"]["environment"] assert (environment["RADIO_DEVICE"], environment["RADIO_BAUD"], environment["RADIO_HARDFLOW"]) == ( "/dev/ttyRCP", "460800", "true", ) assert services["matterjs-server"]["environment"]["OTBR"] == "http://127.0.0.1:8081" assert "depends_on" not in services["matterjs-server"] # its border router coming and going doesn't restart it assert runtime.users(radio) == ["silabs-multiprotocol", "zigbee", "matterjs-server", "matter"] assert runtime.uses(app) == ["matterjs-server", "host", "silabs-multiprotocol", "compose", "sky"] assert runtime.reach([MULTIPAN]) == ["thread", "zigbee"] # through the containers it would run assert runtime.status(otbr) == PeripheralStatus( PeripheralState.WAITING, K.NEEDS_UNBOUND, "need thread/spinel: nothing offers it" ) async def test_a_board_uart_without_flow_control_renders_its_own_serial_settings(tmp_path): wired = Silabs().serves("multipan-rcp", "/dev/ttyAMA3", {"baud": 115200, "flow_control": False}) # the CM4's MG26 await run(tmp_path, FakeCompose(), host(), stick("board", *wired), builtin.silabs_multiprotocol(), zigbee()) service = compose(tmp_path)["silabs-multiprotocol"] assert service["devices"][0] == "/dev/ttyAMA3:/dev/ttyRCP" assert (service["environment"]["RADIO_BAUD"], service["environment"]["RADIO_HARDFLOW"]) == ("115200", "false") assert "RADIO_RESET_GPIO" not in service["environment"] # no reset line wired: left unset async def test_a_board_uart_with_a_reset_line_has_the_radio_pulsed_through_it(tmp_path): params = {"baud": 115200, "flow_control": False, "reset_gpio": "gpiochip0:23"} # the CM4's MG26 RESETn wired = Silabs().serves("multipan-rcp", "/dev/ttyAMA3", params) await run(tmp_path, FakeCompose(), host(), stick("board", *wired), builtin.silabs_multiprotocol(), zigbee()) service = compose(tmp_path)["silabs-multiprotocol"] assert service["environment"]["RADIO_RESET_GPIO"] == "gpiochip0:23" assert service["privileged"] # it sees the host's /dev/gpiochip0 without a device mapping @pytest.mark.parametrize("has_avahi", [True, False]) async def test_the_multipan_border_router_publishes_through_the_hosts_avahi_when_it_runs( tmp_path, monkeypatch, has_avahi ): monkeypatch.setattr(_Host, "avahi", has_avahi) await run(tmp_path, FakeCompose(), host(), stick("sky", MULTIPAN), builtin.silabs_multiprotocol(), zigbee()) volumes = compose(tmp_path)["silabs-multiprotocol"]["volumes"] assert ("/run/dbus:/run/dbus" in volumes) == has_avahi async def test_learning_the_thread_network_recreates_no_border_router(tmp_path): containers = FakeCompose() network = Platform(documents_root=tmp_path / "data" / "peripherals", thread_dataset="0e08hub") peripherals = (host(), stick("sky", MULTIPAN), builtin.silabs_multiprotocol(), zigbee()) runtime = await run(tmp_path, containers, *peripherals, platform=network) applied = len(containers.calls) await runtime.update_platform(replace(network, thread_dataset="0e08learned")) # provisioned onto it instead await settle(runtime) assert containers.calls[applied:] == [] async def test_split_radios_use_direct_zigbee_and_a_standalone_border_router(tmp_path): ncp, rcp, integration, (app, server) = stick("ncp", NCP), stick("rcp", RCP), zigbee(), matter() peripherals = (host(), ncp, rcp, builtin.silabs_multiprotocol(), builtin.otbr(), integration, server, app) await run(tmp_path, FakeCompose(), *peripherals) assert integration.peripherals.endpoint("zigbee") == NCP assert set(compose(tmp_path)) == {"otbr", "matterjs-server"} assert compose(tmp_path)["otbr"]["devices"][0] == "/dev/ttyUSB2:/dev/ttyRCP" rcp_url = "spinel+hdlc+uart:///dev/ttyRCP?uart-baudrate=460800&uart-flow-control" assert compose(tmp_path)["otbr"]["environment"]["OT_RCP_DEVICE"] == rcp_url @pytest.mark.parametrize( ("router", "radio", "listening"), [(builtin.silabs_multiprotocol, MULTIPAN, "LISTEN_ADDRESS"), (builtin.otbr, RCP, "OT_REST_LISTEN_ADDR")], ) async def test_a_border_router_answers_only_the_hub_unless_the_host_listens_on_the_lan( tmp_path, router, radio, listening ): service, matter = router(), FakePeripheral("matter", [Need("thread", ["otbr-rest"])]) await run(tmp_path, FakeCompose(), host(), stick("radio", radio), service, matter) assert compose(tmp_path)[service.name]["environment"][listening] == "127.0.0.1" # over loopback, on the host lab, service, matter = tmp_path / "lab", router(), FakePeripheral("matter", [Need("thread", ["otbr-rest"])]) containers = FakeCompose(listen_address="0.0.0.0") # a lab harness: no password guards it await run(lab, containers, host(), stick("radio", radio), service, matter) assert compose(lab)[service.name]["environment"][listening] == "0.0.0.0" assert "is_exposed_on_lan" not in service.Settings.model_fields # the host's switch, not the user's def test_the_harness_runs_matterjs_server_on_loopback_without_logging_the_thread_key(): # at info matter.js logs every command's fields, the Thread network key among them; the LAN only for a lab harness harness = yaml.safe_load((builtin._IMAGES / "multiprotocol" / "docker-compose.yml").read_text()) environment = harness["services"]["matterjs-server"]["environment"] assert (environment["LISTEN_ADDRESS"], environment["LOG_LEVEL"]) == ("${LISTEN_ADDRESS:-127.0.0.1}", "warning") async def test_a_container_keeps_its_data_in_its_documents_folder(tmp_path): otbr, matter = builtin.otbr(), FakePeripheral("matter", [Need("thread", ["otbr-rest"])]) await run(tmp_path, FakeCompose(), host(), stick("rcp", RCP), otbr, matter) assert compose(tmp_path)["otbr"]["volumes"][0] == f"{tmp_path}/data/peripherals/otbr:/data" assert (tmp_path / "data" / "peripherals" / "otbr").is_dir() async def test_the_folders_a_container_binds_from_its_data_are_created_before_docker_would_as_root(tmp_path): # a factory reset then removes what the container wrote in them through Docker, and the folders as the hub's user await run(tmp_path, FakeCompose(), host(), stick("sky", MULTIPAN), builtin.silabs_multiprotocol(), zigbee()) data = tmp_path / "data" / "peripherals" / "silabs-multiprotocol" assert sorted(path.name for path in data.iterdir()) == ["thread", "zigbee"] async def test_a_wipe_empties_a_service_s_data_through_docker_in_its_own_image(tmp_path): # its container wrote there as root, which the hub's user can't remove (a factory reset): the Thread network containers, otbr, matter = FakeCompose(), builtin.otbr(), FakePeripheral("matter", [Need("thread", ["otbr-rest"])]) runtime = await run(tmp_path, containers, host(), stick("rcp", RCP), otbr, matter) data = otbr.platform.documents_folder(otbr) (data / "0_a5c.data").write_text("dataset") with pytest.raises(RuntimeError, match="runs"): await containers.wipe(otbr) # its container would write on await runtime.stop() applied = len(containers.calls) await containers.wipe(otbr) assert containers.calls[applied:] == [ ("run", "--rm", "--pull", "never", "--network", "none", "--userns", "host", "--user", "0", "--entrypoint") + ("find", "-v", f"{data}:/d", otbr.compose["image"], "/d", "-mindepth", "1", "-delete") ] (data / "0_a5c.data").unlink() await containers.wipe(otbr) assert len(containers.calls) == applied + 1 # nothing to remove: no container run async def test_without_radios_zigbee_waits_and_matter_runs_over_ip(tmp_path): integration, (app, server) = zigbee(), matter() peripherals = (host(), builtin.silabs_multiprotocol(), builtin.otbr(), integration, server, app) runtime = await run(tmp_path, FakeCompose(), *peripherals) assert state(runtime, integration) == PeripheralState.WAITING assert state(runtime, app) == PeripheralState.RUNNING # unset, not set to nothing: a server parsing it (matterjs-server's BLUETOOTH_ADAPTER as an integer) would fail assert "OTBR" not in compose(tmp_path)["matterjs-server"]["environment"] async def test_an_endpoint_given_first_replaces_the_border_router(tmp_path): mine = stick("pinned", Endpoint("thread", "otbr-rest", "http://mine:8081", is_shared=True)) app, server = matter() await run(tmp_path, FakeCompose(), mine, host(), stick("rcp", RCP), builtin.otbr(), server, app) assert set(compose(tmp_path)) == {"matterjs-server"} assert compose(tmp_path)["matterjs-server"]["environment"]["OTBR"] == "http://mine:8081" async def test_a_disabled_integration_takes_its_container_down(tmp_path): app, server = matter() runtime = await run(tmp_path, FakeCompose(), host(), server, app) assert set(compose(tmp_path)) == {"matterjs-server"} await runtime.disable(app) assert compose(tmp_path) == {} class Keys(BaseModel): key: str = "secret" async def test_a_service_setting_recreates_only_that_service(tmp_path): zwave_server = Service( "zwave-js-server", compose={"image": "zwave", "environment": {"KEY": "{settings.key}"}}, needs=[Need("ip")], provides=[Endpoint("zwave", "zwave-js-ws", "ws://127.0.0.1:3000")], settings=Keys, ) zwave = FakePeripheral("zwave", [Need("zwave")]) app, server = matter() runtime = await run(tmp_path, FakeCompose(), host(), zwave_server, zwave, server, app) before = compose(tmp_path) assert before["zwave-js-server"]["environment"]["KEY"] == "secret" await runtime.update_settings(zwave_server, {"key": "other"}) await settle(runtime) after = compose(tmp_path) assert {name for name in before if before[name] != after[name]} == {"zwave-js-server"} assert zwave.calls == ["start"] # what it is bound to is the same: it reconnects on its own async def test_the_rendered_containers_and_the_settings_are_kept_from_other_users(tmp_path): keys = Service( "zwave-js-server", {"environment": {"KEY": "{settings.key}"}}, provides=[Endpoint("zwave")], settings=Keys ) await run(tmp_path, FakeCompose(), keys, FakePeripheral("zwave", [Need("zwave")])) # its network keys assert compose(tmp_path)["zwave-js-server"]["environment"] == {"KEY": "secret"} for kept in (tmp_path / "data" / "peripherals" / "compose" / "compose.json", tmp_path / "data" / "state.json"): assert kept.stat().st_mode & 0o777 == 0o600 async def test_a_moved_need_recreates_a_service_only_when_it_renders_otherwise(tmp_path): containers, radio = FakeCompose(), stick("sky", NCP) bridge = Service("bridge", {"devices": ["{peripherals.zigbee.url}:/dev/ttyRCP"]}, [Need("zigbee")], [Endpoint("b")]) runtime = await run(tmp_path, containers, radio, bridge, FakePeripheral("user", [Need("b")])) applied = len(containers.calls) radio.provided = [replace(NCP, params={"baud": 57600})] # moved, but what it renders is the same await changed(runtime, radio) assert containers.calls[applied:] == [] and state(runtime, bridge) == PeripheralState.RUNNING radio.provided = [replace(NCP, url="/dev/ttyUSB9")] await changed(runtime, radio) assert compose(tmp_path)["bridge"]["devices"] == ["/dev/ttyUSB9:/dev/ttyRCP"] async def test_the_platform_facts_render_and_a_change_recreates_only_what_renders_them(tmp_path): before, containers = Platform(documents_root=tmp_path / "data" / "peripherals", region="Europe"), FakeCompose() app, server = matter(REGION="{platform.region}") plain = Service("plain", {"image": "plain"}, [Need("ip")], [Endpoint("plain")]) user = FakePeripheral("user", [Need("plain")], answer=True) runtime = await run(tmp_path, containers, host(), server, app, plain, user, platform=before) assert compose(tmp_path)["matterjs-server"]["environment"]["REGION"] == "Europe" applied = len(containers.calls) await runtime.update_platform(replace(before, region="USA")) await settle(runtime) assert compose(tmp_path)["matterjs-server"]["environment"]["REGION"] == "USA" assert len([call for call in containers.calls[applied:] if "-f" in call]) == 2 # without it, then with it again assert runtime.status(server).state == PeripheralState.RUNNING assert app.changes == user.changes == [("platform", before)] # the integrations hear it too async def test_a_service_renders_only_when_it_is_created(tmp_path): class InPlace(Service): async def platform_facts_did_change(self, before: Platform) -> bool: return True # it takes the region over its API europe = Platform(documents_root=tmp_path / "data" / "peripherals", region="Europe") radio = InPlace( "radio", {"image": "radio", "environment": {"REGION": "{platform.region}"}}, [Need("ip")], [Endpoint("r")] ) plain = Service("plain", {"image": "plain"}, [Need("ip")], [Endpoint("plain")]) user = FakePeripheral("user", [Need("r"), Need("plain")]) runtime = await run(tmp_path, FakeCompose(), host(), radio, plain, user, platform=europe) await runtime.update_platform(replace(europe, region="USA")) await runtime.restart(plain) await settle(runtime) assert compose(tmp_path)["radio"]["environment"]["REGION"] == "Europe" # not recreated behind its back async def test_a_container_still_starting_is_recreated_once_it_serves_only_if_the_facts_render_it(tmp_path): gate, containers, created = asyncio.Event(), FakeCompose(), set() europe = Platform(documents_root=tmp_path / "data" / "peripherals", region="Europe") class Slow(Service): async def is_healthy(self) -> bool: created.add(self.name) await gate.wait() return True environment = {"REGION": "{platform.region}"} renders = Slow("renders", {"image": "r", "environment": environment}, [Need("ip")], [Endpoint("r")]) plain = Slow("plain", {"image": "plain"}, [Need("ip")], [Endpoint("plain")]) user = FakePeripheral("user", [Need("r"), Need("plain")]) runtime = await run(tmp_path, containers, host(), renders, plain, user, settled=False, platform=europe) await until(runtime, lambda: created == {"renders", "plain"}, settled=False) applied = len(containers.calls) await runtime.update_platform(replace(europe, region="USA")) gate.set() await settle(runtime) assert compose(tmp_path)["renders"]["environment"]["REGION"] == "USA" assert len([call for call in containers.calls[applied:] if "-f" in call]) == 2 # renders' only: down, then up assert state(runtime, user) == PeripheralState.RUNNING async def test_services_get_free_host_ports_and_keep_them(tmp_path, listening): async def ezsp() -> tuple[str, str]: """The zigbee URL bound after a (re)boot, and the port the container got.""" integration = zigbee() peripherals = (host(), stick("sky", MULTIPAN), builtin.silabs_multiprotocol(), integration) runtime = await run(tmp_path, FakeCompose(), *peripherals) port = compose(tmp_path)["silabs-multiprotocol"]["environment"]["EZSP_TCP_PORT"] await runtime.stop() return integration.peripherals.endpoint("zigbee").url, port assert await ezsp() == ("socket://127.0.0.1:9999", "9999") # the preferred port, free listening.add(9999) # after a reboot something else took it before our container came up moved, port = await ezsp() assert moved == f"socket://127.0.0.1:{port}" != "socket://127.0.0.1:9999" listening.clear() # the preferred port is free again: the service stays where it is now assert (await ezsp())[0] == moved async def test_a_port_held_by_our_own_running_container_is_kept(tmp_path, listening, monkeypatch): peripherals = (host(), stick("sky", MULTIPAN), builtin.silabs_multiprotocol()) runtime = await run(tmp_path, FakeCompose(), *peripherals, zigbee()) await runtime.stop() listening.update({9999, 8081}) # our silabs-multiprotocol container is up and holds them async def containers(self) -> set[str]: return {"silabs-multiprotocol"} monkeypatch.setattr(Compose, "_containers", containers) integration = zigbee() await run(tmp_path, FakeCompose(), *peripherals, integration) assert integration.peripherals.endpoint("zigbee").url == "socket://127.0.0.1:9999" async def test_services_preferring_the_same_port_get_different_ones(tmp_path): bridge = Service( "bridge", {"image": "bridge", "command": ["--port", "{ports.api}"]}, provides=[Endpoint("bridge", "x", "ws://127.0.0.1:{ports.api}")], ports={"api": 5580}, ) user = FakePeripheral("user", [Need("bridge")]) app, server = matter() await run(tmp_path, FakeCompose(), host(), server, app, bridge, user) api = compose(tmp_path)["bridge"]["command"][1] assert user.peripherals.endpoint("bridge").url == f"ws://127.0.0.1:{api}" ports = {api, app.peripherals.endpoint("matter").url.rsplit(":", 1)[1].removesuffix("/ws")} assert len(ports) == 2 and "5580" in ports # one got the port both prefer, the other another class Router(Service): """A border router that is set up once it answers and knows its Thread network.""" def __init__(self): super().__init__("router", {"image": "router"}, [Need("ip")], [Endpoint("thread", "rest", "http://ours")]) self.release, self.calls = asyncio.Event(), [] async def provision(self, endpoint: Endpoint): await self.release.wait() self.calls.append(("provision", endpoint.url)) async def start(self): await super().start() self.calls.append(("learn", "http://ours")) await self.output.peripheral_did_learn(self, {"thread_dataset": "0e08"}) async def test_what_needs_a_service_waits_for_its_setup_then_hears_what_it_learned(tmp_path): router, output = Router(), RecordingRuntimeOutput() thread = FakePeripheral("thread", [Need("thread")]) runtime = await run(tmp_path, FakeCompose(), host(), router, thread, output=output, settled=False) await until(runtime, lambda: state(runtime, router) == PeripheralState.STARTING, settled=False) assert runtime.status(thread) == PeripheralStatus(PeripheralState.WAITING, K.NEEDS_STARTING, "waiting for router") await runtime.refresh() # something else changed meanwhile: its setup goes on router.release.set() await until(runtime, lambda: state(runtime, thread) == PeripheralState.RUNNING) assert router.calls == [("provision", "http://ours"), ("learn", "http://ours")] assert output.learned == [("router", {"thread_dataset": "0e08"})] await runtime.restart(router) # recreated: it may hold another network now await until(runtime, lambda: len(output.learned) == 2) assert router.calls[-2:] == [("provision", "http://ours"), ("learn", "http://ours")] assert thread.calls == ["start"] class Docker: """Docker, faked: ``calls`` it got; a container runs once applied, and its ports answer while ``is_answering``. Applying fails while ``failure`` is set; it isn't reachable unless ``is_reachable``, can't tell what runs unless ``is_listing``.""" def __init__(self): self.calls: list[tuple[str, ...]] = [] self.applied: list[set[str]] = [] # the services of each compose file it took self.composes: list[Compose] = [] self.is_answering = self.is_reachable = self.is_listing = True self.left_running: set[str] = set() # containers that outlived the runtime that ran them self.failure = b"" self.gate: asyncio.Event | None = None # while set, applying waits for it async def exec(self, *args: str, **kwargs: Any) -> "Process": self.calls.append(args) if "info" in args: return Process(b"", 0 if self.is_reachable else 1) if "ps" in args: running = "\n".join({*self.left_running, *(name for c in self.composes for name in c._running)}) return Process(running.encode(), 0 if self.is_listing else 1) self.applied.append(set(json.loads(Path(args[args.index("-f") + 1]).read_text())["services"])) return Process(self.failure, 1 if self.failure else 0, self.gate) def holds(self, port: int) -> bool: running = ( ports for compose in self.composes for name, ports in compose.ports.items() if name in compose._running ) return self.is_answering and any(port in ports.values() for ports in running) class Process: def __init__(self, output: bytes, returncode: int, gate: asyncio.Event | None = None): self.output, self.returncode, self.gate = output, returncode, gate async def communicate(self) -> tuple[bytes, bytes]: if self.gate: await self.gate.wait() return self.output, b"" @pytest.fixture def docker(monkeypatch, listening) -> Docker: docker, init = Docker(), Compose.__init__ def record(self): init(self) docker.composes.append(self) monkeypatch.setattr(Compose, "__init__", record) monkeypatch.setattr("asyncio.create_subprocess_exec", docker.exec) monkeypatch.setattr( "majordom_integration_sdk.runtime.peripherals.services.compose._is_listening", lambda port: port in listening or docker.holds(port), ) return docker async def test_without_docker_the_services_wait_saying_so(tmp_path, docker): docker.is_reachable = False app, server = matter() containers = Compose() runtime = await run(tmp_path, containers, host(), server, app) await until(runtime, lambda: state(runtime, containers) == PeripheralState.FAILED) assert runtime.status(containers).detail.startswith("Docker isn't reachable: docker info") reason = "need matter/matter-server-ws: matterjs-server can't run (need container/compose: compose is failed)" assert runtime.status(app) == PeripheralStatus(PeripheralState.WAITING, K.NEEDS_UNBOUND, reason) async def test_a_port_stays_while_docker_cant_tell_what_runs(tmp_path, docker, listening): app, server = matter() runtime = await run(tmp_path, Compose(), host(), server, app) await runtime.stop() listening.add(5580) # our container is still up after the hub restarted: it holds its port docker.left_running.add("matterjs-server") docker.is_listing = False app, server = matter() runtime = await run(tmp_path, Compose(), host(), server, app) assert state(runtime, app) == PeripheralState.WAITING docker.is_listing = True await until(runtime, lambda: state(runtime, app) == PeripheralState.RUNNING) assert app.peripherals.endpoint("matter").url == "ws://127.0.0.1:5580/ws" async def test_a_failed_compose_up_is_tried_again(tmp_path, docker): docker.failure = b"Conflict. The container name is already in use" app, server = matter() runtime = await run(tmp_path, Compose(), host(), server, app) assert runtime.status(server).state == PeripheralState.WAITING assert "Conflict. The container name is already in use" in runtime.status(server).detail docker.failure = b"" await until(runtime, lambda: state(runtime, app) == PeripheralState.RUNNING) assert [call[-3:] for call in docker.calls if "-f" in call] == [("up", "-d", "--remove-orphans")] * 2 async def test_a_container_is_ready_once_compose_runs_it_and_its_ports_answer(tmp_path, docker): docker.is_answering = False app, server = matter() runtime = await run(tmp_path, Compose(), host(), server, app, settled=False) await until(runtime, lambda: state(runtime, server) == PeripheralState.STARTING, settled=False) assert runtime.status(app).detail == "waiting for matterjs-server" docker.is_answering = True await until(runtime, lambda: state(runtime, app) == PeripheralState.RUNNING) async def test_a_container_that_never_answers_fails_its_start(tmp_path, docker): docker.is_answering = False app, server = matter() server.start_timeout = 0.05 runtime = await run(tmp_path, Compose(), host(), server, app) await until(runtime, lambda: state(runtime, server) == PeripheralState.FAILED) assert runtime.status(server) == PeripheralStatus(PeripheralState.FAILED, K.GAVE_UP, "didn't start within 0.05 s") assert runtime.status(app).detail == "need matter/matter-server-ws: matterjs-server is failed" async def test_restarting_a_service_recreates_only_its_container(tmp_path, docker): app, server = matter() integration = zigbee() peripherals = (host(), stick("sky", MULTIPAN), builtin.silabs_multiprotocol(), integration, server, app) runtime = await run(tmp_path, Compose(), *peripherals) await until(runtime, lambda: state(runtime, app) == state(runtime, integration) == PeripheralState.RUNNING) before = compose(tmp_path) await runtime.restart(server) await until(runtime, lambda: state(runtime, server) == PeripheralState.RUNNING) assert compose(tmp_path) == before assert [call[-1] for call in docker.calls if "-f" in call][-2:] == ["--remove-orphans"] * 2 # without, with it assert (app.calls, integration.calls) == (["start"], ["start"]) async def test_a_container_whose_start_was_stopped_is_taken_down(tmp_path, docker): app, server = matter() plain = Service("plain", {"image": "plain"}, [Need("ip")], [Endpoint("plain")]) user = FakePeripheral("user", [Need("plain")]) runtime = await run(tmp_path, Compose(), host(), server, app) await until(runtime, lambda: state(runtime, app) == PeripheralState.RUNNING) docker.gate = asyncio.Event() runtime.given += [plain, user] refresh = asyncio.ensure_future(runtime.refresh()) await until(runtime, lambda: docker.applied[-1] == {"matterjs-server", "plain"}, settled=False) asyncio.get_running_loop().call_later(0.05, docker.gate.set) # docker takes it after all await runtime.disable(user) await refresh await settle(runtime) assert docker.applied[-1] == {"matterjs-server"} ================================================================================ # FILE: tests/runtime/test_thread.py ================================================================================ import asyncio import contextlib import json import threading from collections.abc import Mapping from dataclasses import replace from http.server import BaseHTTPRequestHandler from socketserver import ThreadingTCPServer from typing import Any, cast import pytest from majordom_integration_sdk import Endpoint, Peripheral, Peripherals, Service from majordom_integration_sdk.runtime.peripherals.services import builtin as services from majordom_integration_sdk.runtime.peripherals.services.builtin import ( active_dataset, join_network, move_channel, network_channel, otbr, silabs_multiprotocol, ) from majordom_integration_sdk.testing import RecordingPeripheralOutput, build_test_platform def dataset(network: str, channel: int = 15) -> str: """An active dataset's hex TLVs: its timestamp, channel and Extended PAN ID (the network).""" return f"0e080000000000010000000300{channel:04x}0208{network}" HUB, OTHER = dataset("dead00beef00cafe"), dataset("0123456789abcdef") ENABLE, DISABLE = ("/node/state", json.dumps("enable")), ("/node/state", json.dumps("disable")) PENDING = "/node/dataset/pending" def rest(url: str) -> Endpoint: return Endpoint("thread", "otbr-rest", url, is_shared=True) @pytest.fixture def border_router(): """A border router's REST API with no network until one is put, and no change of it pending: one put lands at once, one pending while ``landing`` lands right after its active dataset is read. It refuses puts to the path ``refused`` names, and fails each put in ``failing`` once.""" state: dict[str, Any] = {"dataset": "", "pending": "", "thread": "leader", "puts": [], "failing": []} class Handler(BaseHTTPRequestHandler): def do_GET(self): read = {PENDING: state["pending"], "/node/state": json.dumps(state["thread"])} body = read.get(self.path, state["dataset"]).encode() self.send_response(200 if body else 204) self.end_headers() self.wfile.write(body) if self.path == "/node/dataset/active" and state.get("landing"): state["dataset"], state["pending"], state["landing"] = state["pending"], "", False def do_PUT(self): body = self.rfile.read(int(self.headers["Content-Length"])).decode() state["puts"].append((self.path, body)) if self.path == state.get("refused") or (self.path, body) in state["failing"]: with contextlib.suppress(ValueError): state["failing"].remove((self.path, body)) self.send_response(409) self.end_headers() return if self.path == "/node/state": state["thread"] = "disabled" if body == json.dumps("disable") else "leader" if self.path == "/node/dataset/active" and not state.get("stuck"): state["dataset"] = body if body.startswith("0e") else "0e08newnetwork" elif self.path == PENDING: state["dataset"] = body # its delay passed self.send_response(200) self.end_headers() def log_message(self, format, *args): pass server = ThreadingTCPServer(("127.0.0.1", 0), Handler) # HTTPServer would resolve the host name first threading.Thread(target=server.serve_forever, args=(0.01,), daemon=True).start() yield f"http://127.0.0.1:{server.server_address[1]}", state server.shutdown() server.server_close() async def test_returns_the_network_someone_else_formed(border_router): url, state = border_router state["dataset"] = "0e08existing" assert await active_dataset(url) == "0e08existing" await join_network(url, None) assert state["puts"] == [] async def test_forms_a_network_when_none_appears(border_router): url, state = border_router await join_network(url, None, patience=0) assert await active_dataset(url) == "0e08newnetwork" assert state["puts"] == [("/node/dataset/active", json.dumps({"NetworkName": "MajorDom"})), ENABLE] async def test_joins_the_given_network(border_router): url, state = border_router await join_network(url, "0e08given", patience=0) assert await active_dataset(url) == "0e08given" async def test_joins_the_given_network_in_place_of_another_it_has(border_router): url, state = border_router state["dataset"] = OTHER # its container formed one before the hub's was known await join_network(url, HUB) assert state["puts"] == [DISABLE, ("/node/dataset/active", HUB), ENABLE] # written only while Thread is off async def test_a_join_whose_enable_failed_once_turns_thread_on_when_tried_again(border_router): url, state = border_router state["dataset"], state["failing"] = OTHER, [ENABLE] # otbr-agent busy a moment await join_network(url, HUB) assert state["puts"] == [DISABLE, ("/node/dataset/active", HUB), ENABLE, ENABLE] assert state["thread"] == "leader" async def test_a_forming_whose_enable_failed_once_turns_thread_on_when_tried_again(border_router): url, state = border_router state["thread"], state["failing"] = "disabled", [ENABLE] # no network yet: Thread is off await join_network(url, None, patience=0) assert state["puts"][-2:] == [ENABLE, ENABLE] and state["thread"] == "leader" async def test_keeps_the_given_network_after_it_moved(border_router): url, state = border_router state["dataset"] = dataset("dead00beef00cafe", channel=20) # the same network, on another channel since await join_network(url, HUB) assert state["puts"] == [] async def test_forms_only_once(border_router): url, state = border_router state["stuck"] = True # forming takes a while: the dataset doesn't appear yet await asyncio.wait_for(join_network(url, None, patience=0), 3) assert len(state["puts"]) == 2 # one dataset, one enable with pytest.raises(TimeoutError): await asyncio.wait_for(active_dataset(url), 0.2) @pytest.mark.parametrize(("router", "formed"), [(otbr, ""), (silabs_multiprotocol, OTHER)]) async def test_a_border_router_is_provisioned_onto_the_hubs_thread_network(border_router, monkeypatch, router, formed): url, state = border_router monkeypatch.setattr(services, "FORM_PATIENCE", 0) state["dataset"] = formed # the multiprotocol container forms one of its own, as it warms the radio up service = serving(router(), url, thread_dataset=HUB) # learned from the stick before await asyncio.wait_for(service.start(), 3) assert await active_dataset(url) == HUB assert PENDING not in [path for path, _ in state["puts"]] # on the same channel async def test_a_multiprotocol_router_moves_the_network_it_joins_to_zigbees_channel(border_router): url, state = border_router state["dataset"] = dataset("0123456789abcdef", channel=15) # its container formed it on Zigbee's channel service = serving(silabs_multiprotocol(), url, thread_dataset=dataset("dead00beef00cafe", channel=20)) await asyncio.wait_for(service.start(), 3) assert state["puts"][1] == ("/node/dataset/active", service.platform.thread_dataset) # joined pending = dict(state["puts"])[PENDING] # the devices on it follow: new active and pending timestamps, a delay assert "000300000f" in pending and "0208dead00beef00cafe" in pending and "3308" in pending and "3404" in pending async def test_a_change_pending_on_another_network_moves_nothing_of_the_one_it_joins(border_router): url, state = border_router restored = dataset("0123456789abcdef", channel=15) state["dataset"] = state["pending"] = restored # a move of the network it restored, left pending service = serving(silabs_multiprotocol(), url, thread_dataset=dataset("dead00beef00cafe", channel=20)) await asyncio.wait_for(service.start(), 3) assert "000300000f" in dict(state["puts"])[PENDING] # the hub's network moved to Zigbee's channel all the same assert learned(service) == [(service, {"thread_dataset": state["dataset"]})] async def test_a_channel_move_that_cant_land_fails_the_start(border_router, monkeypatch): url, state = border_router monkeypatch.setattr(services, "FORM_PATIENCE", 0.1) state["dataset"], state["refused"] = dataset("0123456789abcdef", channel=15), PENDING # e.g. not attached service = serving(silabs_multiprotocol(), url, thread_dataset=dataset("dead00beef00cafe", channel=20)) with pytest.raises(TimeoutError, match="channel 15"): await asyncio.wait_for(service.start(), 3) assert learned(service) == [] async def test_a_standalone_router_keeps_the_channel_of_the_network_it_joins(border_router): url, state = border_router state["dataset"] = dataset("0123456789abcdef", channel=15) service = serving(otbr(), url, thread_dataset=dataset("dead00beef00cafe", channel=20)) await asyncio.wait_for(service.start(), 3) assert PENDING not in [path for path, _ in state["puts"]] def test_a_move_is_stamped_after_the_network_it_moves_with_the_clock_behind(monkeypatch): monkeypatch.setattr(services.time, "time", lambda: 1000) # a Pi without a clock of its own, before NTP stamped = (2_000_000_000 << 16).to_bytes(8).hex() # by an earlier move, with the clock right moved = services._tlvs(services._moved(f"0e08{stamped}000300000f0208dead00beef00cafe", 20)) assert int.from_bytes(moved[services._ACTIVE_TIMESTAMP]) >> 16 == 2_000_000_001 # newer: the devices take it assert moved[services._PENDING_TIMESTAMP] == moved[services._ACTIVE_TIMESTAMP] async def test_the_channel_is_the_one_its_network_is_on_or_moving_to(border_router): url, state = border_router reading = asyncio.create_task(network_channel(url)) await asyncio.sleep(0.05) assert not reading.done() # no network yet state["dataset"] = dataset("dead00beef00cafe", channel=20) assert await asyncio.wait_for(reading, 3) == 20 state["pending"] = dataset("dead00beef00cafe", channel=15) assert await network_channel(url) == 15 async def test_a_channel_move_is_tried_again_until_the_border_router_takes_it(border_router): url, state = border_router state["dataset"], state["refused"] = dataset("dead00beef00cafe", channel=20), PENDING # not attached yet moving = asyncio.create_task(move_channel(url, 15)) await asyncio.sleep(0.05) state["refused"] = None await asyncio.wait_for(moving, 3) assert [path for path, _ in state["puts"]].count(PENDING) > 1 and "000300000f" in state["dataset"] async def test_learns_the_network_only_once_a_channel_move_landed(border_router): url, state = border_router moved = dataset("dead00beef00cafe", channel=15) state["dataset"], state["pending"] = dataset("dead00beef00cafe", channel=20), moved learning = asyncio.create_task(active_dataset(url)) await asyncio.sleep(0.2) assert not learning.done() # Matter would commission devices onto the channel it leaves state["dataset"], state["pending"] = moved, "" assert await asyncio.wait_for(learning, 3) == moved async def test_a_move_landing_between_two_reads_is_learned_once_landed(border_router): url, state = border_router moved = dataset("dead00beef00cafe", channel=15) state["dataset"], state["pending"], state["landing"] = dataset("dead00beef00cafe", channel=20), moved, True assert await asyncio.wait_for(active_dataset(url), 3) == moved class Answering: """Runs nothing: the border router at ``url`` answers already, and is set up as the runtime's containers are.""" def __init__(self, url: str): self.url = url def provided(self, service: Service) -> list[Endpoint]: return [replace(endpoint, url=self.url) for endpoint in service.templates] async def up(self, service: Service): for endpoint in service.provides: await service.provision(endpoint) async def down(self, service: Service): pass def is_current(self, service: Service) -> bool: return True def serving[S: Service](service: S, url: str, **facts: Any) -> S: """``service`` on the border router at ``url``, the platform holding ``facts``; what it tells recorded.""" service.platform = build_test_platform(**facts) service.peripherals = Peripherals({"container": Endpoint("container", "compose", instance=Answering(url))}) service.output = RecordingPeripheralOutput() return service def learned(service: Service) -> list[tuple[Peripheral, Mapping[str, Any]]]: return cast(RecordingPeripheralOutput, service.output).learned @pytest.mark.parametrize("router", [otbr, silabs_multiprotocol]) async def test_a_border_router_tells_its_thread_network_once_it_serves(border_router, router): url, state = border_router state["dataset"] = dataset("0123456789abcdef") service = serving(router(), url) await asyncio.wait_for(service.start(), 3) assert learned(service) == [(service, {"thread_dataset": dataset("0123456789abcdef")})] ================================================================================ # FILE: tests/runtime/test_thread_source.py ================================================================================ import json import os import subprocess import sys from pathlib import Path import pytest from majordom_integration_sdk.runtime.peripherals.services import builtin as services SCRIPT = services._IMAGES / "thread-source" / "run" # A stand-in for iproute2: answers the queries the script makes from a JSON state and applies its route changes. FAKE_IP = f"""#!{sys.executable} import ipaddress, json, sys from pathlib import Path state_file = Path(__file__).with_name("state.json") state = json.loads(state_file.read_text()) args = sys.argv[1:] if args[:5] == ["-o", "-6", "addr", "show", "dev"]: if args[5] not in state["addr"]: sys.exit(f'Device "{{args[5]}}" does not exist.') print("\\n".join(state["addr"][args[5]])) elif args[:4] == ["-6", "route", "show", "match"]: address = ipaddress.ip_address(args[4]) for dst, line in state["routes"].get(args[6], {{}}).items(): if dst != "default" and address in ipaddress.ip_network(dst): print(f"{{dst}} {{line}}") elif args[:3] == ["-6", "route", "replace"]: state["replaced"].append(args[3:]) state["routes"][args[5]][args[3]] = " ".join(args[6:]) state_file.write_text(json.dumps(state)) else: sys.exit(f"unexpected: ip {{' '.join(args)}}") """ ETH0 = [ "2: eth0 inet6 fdc0:ca84:d7e3:0:ce47:229:37f5:dc98/64 scope global temporary dynamic", "2: eth0 inet6 2a0a:a548:cced:0:8aa2:9eff:fea7:d66d/64 scope global dynamic mngtmpaddr proto kernel_ra", "2: eth0 inet6 fdc0:ca84:d7e3:0:8aa2:9eff:fea7:d66d/64 scope global dynamic mngtmpaddr proto kernel_ra", ] WPAN0 = [ "7: wpan0 inet6 fd4c:60e5:af3f:4111:0:ff:fe00:fc11/64 scope global nodad deprecated", "7: wpan0 inet6 fd11:ec6a:d233:1:5465:34b9:c5b4:2b7c/64 scope global nodad", "7: wpan0 inet6 fd4c:60e5:af3f:4111:f746:74ed:1eb7:e84/64 scope global nodad deprecated", ] OMR, MESH_LOCAL = "fd11:ec6a:d233:1::/64", "fd4c:60e5:af3f:4111::/64" STABLE_ULA = "fdc0:ca84:d7e3:0:8aa2:9eff:fea7:d66d" KERNEL_ROUTE = "proto kernel metric 256 pref medium" @pytest.fixture def host(tmp_path: Path): """The border router's host as `ip` shows it: Thread routes as the kernel adds them for wpan0's addresses.""" (tmp_path / "ip").write_text(FAKE_IP) (tmp_path / "ip").chmod(0o755) state = { "addr": {"eth0": ETH0, "wpan0": WPAN0}, "routes": {"wpan0": {OMR: KERNEL_ROUTE, MESH_LOCAL: KERNEL_ROUTE}}, "replaced": [], } (tmp_path / "state.json").write_text(json.dumps(state)) return tmp_path def sync(host: Path) -> dict: env = {"PATH": f"{host}{os.pathsep}{os.environ['PATH']}", "OT_THREAD_IF": "wpan0", "BACKBONE_IF": "eth0"} subprocess.run(["bash", "-c", f'source "{SCRIPT}" && sync_sources'], env=env, check=True, timeout=10) return json.loads((host / "state.json").read_text()) def edit(host: Path, change): state = json.loads((host / "state.json").read_text()) change(state) (host / "state.json").write_text(json.dumps(state)) def test_routes_to_the_border_routers_own_thread_addresses_take_a_stable_backbone_ula(host): state = sync(host) assert state["replaced"] == [[OMR, "dev", "wpan0", *KERNEL_ROUTE.split(), "src", STABLE_ULA]] assert MESH_LOCAL not in {r[0] for r in state["replaced"]} # only deprecated addresses of ours there def test_a_route_with_the_source_already_is_left_alone(host): sync(host) assert len(sync(host)["replaced"]) == 1 def test_follows_the_border_router_re_adding_its_route(host): sync(host) edit(host, lambda s: s["routes"]["wpan0"].update({OMR: KERNEL_ROUTE})) assert len(sync(host)["replaced"]) == 2 def test_follows_the_backbone_renumbering(host): sync(host) renumbered = "fdc0:ca84:d7e3:0:1111:2222:3333:4444" edit(host, lambda s: s["addr"].update(eth0=[ETH0[2].replace(STABLE_ULA, renumbered)])) assert sync(host)["replaced"][-1][-2:] == ["src", renumbered] def test_a_temporary_ula_when_there_is_no_stable_one(host): edit(host, lambda s: s["addr"].update(eth0=ETH0[:2])) assert sync(host)["replaced"][0][-1] == "fdc0:ca84:d7e3:0:ce47:229:37f5:dc98" def test_without_a_backbone_ula_nothing_changes(host): edit(host, lambda s: s["addr"].update(eth0=[ETH0[1]])) # a GUA: nodes may have no route back to it assert sync(host)["replaced"] == [] def test_without_a_thread_interface_nothing_changes(host): edit(host, lambda s: s["addr"].pop("wpan0")) assert sync(host)["replaced"] == [] def test_both_border_routers_run_it(): assert f"{SCRIPT.parent}:/etc/services.d/thread-source:ro" in services.otbr().compose["volumes"] # s6 starts it assert f"{SCRIPT}:/thread-source:ro" in services.silabs_multiprotocol().compose["volumes"] assert "bash /thread-source &" in (services._IMAGES / "multiprotocol" / "entrypoint.sh").read_text() ================================================================================ # FILE: tests/runtime/test_zeroconf.py ================================================================================ """The runtime's DNS-SD browser, over fakes of zeroconf's: no multicast socket is opened.""" from typing import cast import pytest from majordom_integration_sdk.runtime.peripherals.providers import zeroconf as module from majordom_integration_sdk.runtime.peripherals.providers.zeroconf import ZeroconfDiscoveryService class Browser: def __init__(self, zeroconf: object, services: list[str], listener: object): self.cancels = 0 async def async_cancel(self): self.cancels += 1 class AsyncZeroconf: zeroconf = None async def async_close(self): pass @pytest.fixture(autouse=True) def fakes(monkeypatch): monkeypatch.setattr(module, "AsyncZeroconf", AsyncZeroconf) monkeypatch.setattr(module, "AsyncServiceBrowser", Browser) async def test_a_registration_cancelled_after_it_stopped_is_gone_already(): zeroconf = ZeroconfDiscoveryService() await zeroconf.start() cancel = zeroconf.register(object(), {"_esphomelib._tcp.local."}) [browser] = cast(set[Browser], zeroconf._browsers) await zeroconf.stop() # before a user that cancels only then cancel() assert browser.cancels == 1 and zeroconf._adapters == [] ================================================================================ # FILE: tests/test_ble_security.py ================================================================================ """Secure channels: credentials are written to a BLE device only over a link secured first (LE Secure Connections), through a radio that can pair, or over an unsecured one only when asked for by name.""" import logging from unittest.mock import AsyncMock, Mock import pytest from majordom_integration_sdk.capabilities import ( BLEConnection, BLEPairingError, LESecureConnections, PairableBLEConnection, Unsecured, ) from majordom_integration_sdk.runtime.peripherals.providers.ble.router import BLEService from majordom_integration_sdk.testing import FakeBLESource def pairable(calls: list[str] | None = None) -> Mock: connection = Mock(spec=PairableBLEConnection) connection.pair = AsyncMock(side_effect=lambda: calls.append("pair") if calls is not None else None) connection.unpair = AsyncMock(side_effect=lambda: calls.append("unpair") if calls is not None else None) connection.write = AsyncMock(side_effect=lambda *_, **__: calls.append("write") if calls is not None else None) return connection async def test_le_secure_connections_pairs_before_any_write_and_unpairs_after(): calls: list[str] = [] connection = pairable(calls) async with LESecureConnections().secure(connection) as secured: await secured.write(1, b"secret") assert calls == ["pair", "write", "unpair"] async def test_le_secure_connections_refuses_a_connection_that_cannot_pair(): connection = Mock(spec=BLEConnection) with pytest.raises(BLEPairingError, match="can't pair"): async with LESecureConnections().secure(connection): pytest.fail("credentials would cross an unencrypted link") connection.write.assert_not_called() async def test_a_failed_pairing_yields_nothing(): connection = pairable() connection.pair.side_effect = BLEPairingError("authentication failed") with pytest.raises(BLEPairingError): async with LESecureConnections().secure(connection): pytest.fail("credentials would cross an unencrypted link") connection.write.assert_not_called() async def test_the_bond_is_kept_when_asked(): connection = pairable() async with LESecureConnections(is_pairing_kept=True).secure(connection): pass connection.unpair.assert_not_called() async def test_unsecured_writes_as_is_and_says_so(caplog): connection = Mock(spec=BLEConnection) with caplog.at_level(logging.WARNING): async with Unsecured().secure(connection) as secured: assert secured is connection assert "unencrypted" in caplog.text assert not Unsecured.is_pairing_needed and LESecureConnections.is_pairing_needed @pytest.fixture async def radios(): proxy = FakeBLESource("proxy", connection=Mock(spec=BLEConnection)) # stronger, can't pair adapter = FakeBLESource("adapter", connection=pairable(), is_pairable=True) ble = BLEService(sources=[proxy, adapter]) await ble.start() proxy.advertise("AA", rssi=-40) adapter.advertise("AA", rssi=-70) yield ble, proxy, adapter await ble.stop() async def test_a_pairing_lease_takes_a_radio_that_can_pair_over_a_stronger_one(radios): ble, proxy, adapter = radios async with ble.exclusive("AA", owner="test", is_pairing_needed=True) as lease: assert lease.source == "adapter" async with ble.exclusive("AA", owner="test") as lease: assert lease.source == "proxy" async def test_a_pairing_lease_fails_when_no_radio_hearing_the_device_can_pair(radios): ble, proxy, adapter = radios adapter.is_pairable = False with pytest.raises(BLEPairingError, match="can pair"): async with ble.exclusive("AA", owner="test", is_pairing_needed=True, timeout=0.1): pytest.fail("leased a radio that can't pair") @pytest.fixture def adapter_client(monkeypatch): from majordom_integration_sdk.runtime.peripherals.providers.ble import bluez as module client = Mock(connect=AsyncMock(), pair=AsyncMock(), unpair=AsyncMock(), address="AA:BB:CC:DD:EE:FF") monkeypatch.setattr(module, "BleakClient", lambda *args, **kwargs: client) return client async def test_on_linux_a_local_adapter_pairs_through_its_own_bluez_agent(adapter_client, monkeypatch): from majordom_integration_sdk.runtime.peripherals.providers.ble import bluez as module from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter monkeypatch.setattr(module.sys, "platform", "linux") paired = AsyncMock() monkeypatch.setattr(module, "pair_through_agent", paired) adapter = LocalAdapter("hci1") assert adapter.is_pairable connection = await adapter.connect("AA:BB:CC:DD:EE:FF", lambda: None) assert isinstance(connection, PairableBLEConnection) await connection.pair() paired.assert_awaited_once_with("hci1", "AA:BB:CC:DD:EE:FF") adapter_client.pair.assert_not_called() # bleak's brings no agent: Secure Connections fails without one await connection.unpair() adapter_client.unpair.assert_awaited_once() paired.side_effect = ConnectionError("org.bluez.Error.AuthenticationFailed: Authentication Failed") with pytest.raises(BLEPairingError, match="AuthenticationFailed"): await connection.pair() async def test_elsewhere_the_os_pairs_on_its_own(adapter_client, monkeypatch): from bleak.exc import BleakError from majordom_integration_sdk.runtime.peripherals.providers.ble import bluez as module from majordom_integration_sdk.runtime.peripherals.providers.ble.bluez import LocalAdapter monkeypatch.setattr(module.sys, "platform", "darwin") connection = await LocalAdapter().connect("AA:BB:CC:DD:EE:FF", lambda: None) assert isinstance(connection, PairableBLEConnection) await connection.pair() adapter_client.pair.assert_awaited_once() adapter_client.pair.side_effect = BleakError("refused") with pytest.raises(BLEPairingError, match="refused"): await connection.pair() DEVICE = "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF" @pytest.mark.parametrize( ("member", "body", "answer"), [ ("RequestAuthorization", [DEVICE], ("", [])), # Just Works on LE Secure Connections ("RequestConfirmation", [DEVICE, 1234], ("", [])), ("RequestPasskey", [DEVICE], "org.bluez.Error.Rejected"), ("RequestAuthorization", ["/org/bluez/hci0/dev_11_22_33_44_55_66"], "org.bluez.Error.Rejected"), ("RequestPinCode", [DEVICE], "org.bluez.Error.Rejected"), ("AuthorizeService", [DEVICE, "0000110b-0000-1000-8000-00805f9b34fb"], "org.bluez.Error.Rejected"), ("Release", [], ("", [])), ], ) def test_the_agent_answers_only_for_the_device_being_paired(member, body, answer): from majordom_integration_sdk.runtime.peripherals.providers.ble import bluez as bluez_pairing assert bluez_pairing.device_path("hci0", "aa:bb:cc:dd:ee:ff") == DEVICE assert bluez_pairing.agent_answer(member, body, DEVICE) == answer ================================================================================ # FILE: tests/test_cli.py ================================================================================ """Exercises the interactive CLI's controller-driving core (`_CliSession`) against a fake controller wired with the offline test platform — no REPL, no network. The typer-shell wiring on top is a thin layer over these same calls.""" from __future__ import annotations import asyncio from uuid import UUID, uuid4 import pytest from majordom_integration_sdk import Endpoint, IntegrationError, Need, Peripherals from majordom_integration_sdk.controller import AbstractController from majordom_integration_sdk.dev.cli import _CliControllerOutput, _CliSession, _print from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import ( CredentialsType, Device, DeviceState, Discovery, ProvidedCredentials, ) from majordom_integration_sdk.schemas.event import DeviceParameterChange from majordom_integration_sdk.schemas.notification import Notification, NotificationType from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterState, ParameterVisibility, ) from majordom_integration_sdk.testing import build_test_platform INTEGRATION = "Fake" def _param(role: ParameterRole = ParameterRole.control) -> ParameterState: return ParameterState( id=uuid4(), name="On", data_type=ParameterDataType.bool, role=role, visibility=ParameterVisibility.user, integration_data=None, ) class FakeController(AbstractController): """Minimal controller: pairing persists a device with one control parameter; every other method just records that it was called with the resolved object.""" name = INTEGRATION def __init__(self, dependencies, *, param_role: ParameterRole = ParameterRole.control): super().__init__(dependencies) self._discoveries: dict[UUID, Discovery] = {} self._param_role = param_role self.paired: list[UUID] = [] self.sent: list[tuple] = [] self.identified: list[UUID] = [] self.fetched: list[UUID] = [] self.unpaired: list[UUID] = [] @property def discoveries(self) -> dict[UUID, Discovery]: return self._discoveries async def start(self): pass async def stop(self): pass async def pair_device( self, discovery: Discovery, draft: DeviceState, credentials: ProvidedCredentials | None ) -> DeviceState: draft.physical_id = uuid4() draft.parameters = [_param(self._param_role)] draft.available = True self.paired.append(draft.physical_id) return draft async def unpair(self, device: Device): self.unpaired.append(device.physical_id) async def identify(self, device: Device): self.identified.append(device.physical_id) async def fetch(self, device: Device): self.fetched.append(device.physical_id) async def send_command(self, command: DeviceCommand, device: Device, parameter): self.sent.append((command.device_id, command.parameter_id, command.value)) def _discovery() -> Discovery: return Discovery( id=uuid4(), integration=INTEGRATION, expected_credentials_options=[CredentialsType.none], transport="test", device_manufacturer=None, device_name="Bulb", device_category=None, device_icon=None, ) @pytest.fixture def session_and_controller(): deps = build_test_platform() controller = FakeController(deps) return _CliSession(controller), controller async def test_pair_list_control_unpair_flow(session_and_controller): session, controller = session_and_controller discovery = _discovery() controller.discoveries[discovery.id] = discovery # pair -> persists the filled draft, then reports it connected and fetches it, as the Hub does device_id = await session.pair(discovery.id, "none", "") assert device_id in controller.paired assert controller.fetched == [device_id] # devices -> lists it devices = await session.list_devices() assert [d.physical_id for d in devices] == [device_id] # device -> shows its (single control) parameter state = await session.device_state(device_id) assert state is not None assert len(state.parameters) == 1 parameter = state.parameters[0] assert parameter.role == ParameterRole.control # control -> resolves device+parameter and reaches the controller assert await session.control(device_id, parameter.id, True) == "Command sent" assert controller.sent == [(devices[0].id, parameter.id, True)] # the command carries the Hub's id # identify / fetch reach the controller with the resolved device assert await session.identify(device_id) is True assert await session.fetch(device_id) is True assert controller.identified == [device_id] assert controller.fetched == [device_id, device_id] # unpair assert await session.unpair(device_id) is True assert controller.unpaired == [device_id] async def test_pair_unknown_discovery_returns_none(session_and_controller): session, _ = session_and_controller assert await session.pair(uuid4()) is None async def test_actions_on_missing_device(session_and_controller): session, controller = session_and_controller missing = uuid4() assert (await session.control(missing, uuid4(), True)).startswith("No device") assert await session.identify(missing) is False assert await session.fetch(missing) is False assert await session.unpair(missing) is False assert controller.sent == controller.identified == [] async def test_control_rejects_non_control_parameter(): deps = build_test_platform() controller = FakeController(deps, param_role=ParameterRole.sensor) session = _CliSession(controller) discovery = _discovery() controller.discoveries[discovery.id] = discovery device_id = await session.pair(discovery.id) parameter = (await session.device_state(device_id)).parameters[0] message = await session.control(device_id, parameter.id, True) assert "not controllable" in message assert controller.sent == [] # never reached the controller async def test_output_delegate_persists_event_values(): deps = build_test_platform() controller = FakeController(deps) session = _CliSession(controller) discovery = _discovery() controller.discoveries[discovery.id] = discovery device_id = await session.pair(discovery.id) parameter = (await session.device_state(device_id)).parameters[0] output = _CliControllerOutput() await output.controller_did_receive_events( controller, [DeviceParameterChange(physical_id=device_id, parameter_id=parameter.id, value=True)] ) async with controller.platform.device_repository(controller) as repo: stored = await repo.get_parameter_state(physical_id=device_id, parameter_id=parameter.id) assert stored is not None assert stored.value # a (non-empty, encoded) value was written back by the event async def test_output_delegate_prints_reported_and_resolved_errors(capsys): output, controller = _CliControllerOutput(), FakeController(build_test_platform()) await output.controller_did_encounter_error(controller, IntegrationError("stick-unplugged", "Re-plug it")) await output.controller_did_resolve_error(controller, "stick-unplugged") out = capsys.readouterr().out assert "[error] stick-unplugged: Re-plug it" in out and out.rstrip().endswith("[error resolved] stick-unplugged") async def test_output_delegate_prints_notifications(capsys): output, controller = _CliControllerOutput(), FakeController(build_test_platform()) notification = Notification(message="Firmware update available", type=NotificationType.warning) await output.controller_did_emit_notification(controller, notification) assert "[notification] warning/normal: Firmware update available" in capsys.readouterr().out def test_prompt_safe_print_is_a_noop_safe_call(capsys): # Not a TTY under pytest, so _print falls back to a plain print (no escape codes leaking). _print("hello", "world") out = capsys.readouterr().out assert "hello" in out and "world" in out assert "\x1b[" not in out # no cursor-magic when stdout isn't a terminal def test_run_cli_is_lazily_exported(): from majordom_integration_sdk import dev assert callable(dev.run_cli) def test_capturing_handler_buffers_then_dumps(capsys): import logging from majordom_integration_sdk.dev.cli import _CapturingHandler handler = _CapturingHandler() handler.setFormatter(logging.Formatter("%(levelname)s %(message)s")) log = logging.getLogger("test.capture") log.addHandler(handler) log.setLevel(logging.DEBUG) log.propagate = False log.warning("chatty controller noise") # buffered, not printed — the TUI stays clean during the session assert capsys.readouterr().err == "" assert len(handler.records) == 1 # dumped to stderr on exit for debugging handler.dump() err = capsys.readouterr().err assert "chatty controller noise" in err assert "captured logs" in err # --- needs --------------------------------------------------------------------------------- class _ZigbeeController(FakeController): name = "Fake Zigbee" needs = [Need("zigbee", ["ezsp", "znp"]), Need("ble", ["bluez"], is_required=False)] @pytest.fixture async def needs_session(tmp_path): from majordom_integration_sdk.dev import Runner, build_runtime from majordom_integration_sdk.runtime.peripherals.services.builtin import silabs_multiprotocol from majordom_integration_sdk.testing import FakeBLERouter, FakeBLESource, FakeCompose, FakePeripheral adapter = FakePeripheral( "bluetooth-adapters", provides=[Endpoint("ble", "bluez", "hci0", instance=FakeBLESource())] ) matter = FakePeripheral("matter", [Need("ble", ["router"])]) # runs the router: it takes the adapter controller = _ZigbeeController(build_test_platform()) runtime = build_runtime( [controller], tmp_path / "runtime", runtime_peripherals=[adapter, FakeCompose(), silabs_multiprotocol(), FakeBLERouter(), matter], platform=controller.platform, ) runner = Runner(controller, runtime) await runner.start() yield _CliSession(controller, runtime), runner await runner.stop() async def _until_running(runner, is_running: bool = True): async with asyncio.timeout(2): while runner.is_running != is_running: await asyncio.sleep(0.01) async def test_needs_show_what_is_unbound_and_why(needs_session): session, runner = needs_session assert session.needs() == [ "zigbee/ezsp|znp unbound: need zigbee/ezsp|znp: silabs-multiprotocol can't run (need multipan/silabs-cpc: " "nothing offers it)", "ble/bluez (optional) unbound: need ble/bluez: every provider taken by ble-router" ' — use Need("ble", ["router"])', ] assert not runner.is_running async def test_a_pinned_endpoint_binds_the_need_and_starts_the_integration(needs_session): session, runner = needs_session await session.pin("zigbee", "socket://192.168.1.5:6638") # the need's first dialect assert session.needs()[0] == "zigbee/ezsp|znp -> socket://192.168.1.5:6638 by pinned" await _until_running(runner) assert runner.controller.peripherals.endpoint("zigbee") == Endpoint( "zigbee", "ezsp", "socket://192.168.1.5:6638", is_shared=True ) await session.unpin("zigbee") assert session.needs()[0].startswith("zigbee/ezsp|znp unbound") assert not runner.is_running await session.resolve() # nothing new: still waiting async def test_needs_without_a_runtime_list_what_was_given(): controller = _ZigbeeController(build_test_platform()) controller.peripherals = Peripherals({"zigbee": Endpoint("zigbee", "ezsp", "/dev/ttyUSB0")}) session = _CliSession(controller) assert session.needs()[0] == "zigbee/ezsp|znp -> /dev/ttyUSB0 by you" with pytest.raises(RuntimeError, match="by hand"): await session.resolve() ================================================================================ # FILE: tests/test_controller.py ================================================================================ """A minimal concrete controller exercises the framework end to end with test doubles.""" import inspect import subprocess import sys from pathlib import Path from uuid import UUID, uuid4, uuid5 import pytest from factories import make_device_state from pydantic import ValidationError from majordom_integration_sdk import DeviceIdTakenError, NoSettings, Platform from majordom_integration_sdk.controller import AbstractController, ControllerOutput, LoggingControllerOutput from majordom_integration_sdk.controller.output import AnyController from majordom_integration_sdk.repository import DeviceRepositoryMemory from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import Device, DeviceState, Discovery, Parameter, ProvidedCredentials from majordom_integration_sdk.schemas.event import DeviceParameterChange from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform class _MinimalController(AbstractController[Device, Parameter]): name = "Example Protocol" @property def discoveries(self) -> dict[UUID, Discovery]: return {} async def start(self): pass async def stop(self): pass async def pair_device( self, discovery: Discovery, draft: DeviceState, credentials: ProvidedCredentials | None ) -> DeviceState: await self.check_device_id(self.device_uuid("serial-1"), draft) draft.physical_id = self.device_uuid("serial-1") return draft async def unpair(self, device: Device): pass async def identify(self, device: Device): pass async def fetch(self, device: Device): pass async def send_command(self, command: DeviceCommand, device: Device, parameter: Parameter): pass def test_key_and_uuid_helpers(): controller = _MinimalController(build_test_platform()) assert controller.key == "example-protocol" # Deterministic, namespaced, and hierarchical. device_uuid = controller.device_uuid("abc") assert controller.device_uuid("abc") == device_uuid assert controller.parameter_uuid(device_uuid, "p1") != device_uuid @pytest.mark.parametrize("raw", ["AA:BB-cc", "aabbcc", " aa bb\tcc\n", "a-a:b-b:c-c"]) def test_device_uuid_normalises_a_string(raw): controller = _MinimalController(build_test_platform()) assert controller.device_uuid(raw) == controller.device_uuid("aabbcc") @pytest.mark.parametrize("other", ["aa.bb.cc", "aa_bb_cc", "aa/bb/cc"]) def test_device_uuid_keeps_other_separators(other): controller = _MinimalController(build_test_platform()) assert controller.device_uuid(other) != controller.device_uuid("aabbcc") def test_device_uuid_strips_only_the_chars_given(): controller = _MinimalController(build_test_platform()) assert controller.device_uuid("aa.bb", strip=".") == controller.device_uuid("aabb") assert controller.device_uuid("aa:bb", strip="") != controller.device_uuid("aabb") def test_device_uuid_takes_bytes_as_they_are(): controller = _MinimalController(build_test_platform()) mac = bytes.fromhex("aabbccddeeff") assert controller.device_uuid(mac) == uuid5(controller.integration_uuid(), mac) assert controller.device_uuid(b"AA") != controller.device_uuid(b"aa") assert controller.device_uuid(mac) != controller.device_uuid("aabbccddeeff") def test_parameter_uuid_is_seeded_by_the_physical_id_and_normalised(): controller = _MinimalController(build_test_platform()) physical_id = controller.device_uuid("aabbcc") assert controller.parameter_uuid(physical_id, "On-Off") == controller.parameter_uuid(physical_id, "onoff") assert controller.parameter_uuid(physical_id, "On-Off") == uuid5(physical_id, "onoff") assert controller.parameter_uuid(physical_id, b"\x01") == uuid5(physical_id, b"\x01") def test_its_documents_folder_is_its_own_under_the_platforms(tmp_path): controller = _MinimalController(build_test_platform(documents_root=tmp_path)) assert controller.platform.documents_folder(controller) == tmp_path / "example-protocol" assert (tmp_path / "example-protocol").is_dir() LEAVES = """ from majordom_integration_sdk.testing import build_test_platform for platform in (build_test_platform(), build_test_platform()): (platform.documents_root / "zigbee").mkdir() (platform.documents_root / "zigbee" / "app.db").write_text("devices") print(platform.documents_root) """ def test_a_platform_built_without_a_root_leaves_no_folder_behind(): # a folder each, never removed, piled up in the temp folder run after run roots = subprocess.run([sys.executable, "-c", LEAVES], capture_output=True, text=True, check=True).stdout.split() assert len(set(roots)) == 2 and not any(Path(root).exists() for root in roots) async def test_its_device_repository_holds_only_its_own_devices(): controller = _MinimalController(build_test_platform()) device = make_device_state(integration=controller.key) # its slug, "example-protocol" async with controller.platform.device_repository(controller) as repo: await repo.save(device) stored = await repo.state(physical_id=device.physical_id) assert stored is not None and stored.id == device.id with pytest.raises(PermissionError): await repo.save(make_device_state(integration="Other")) async def test_recording_output_captures_reports(): controller = _MinimalController(build_test_platform()) output = controller.output = RecordingControllerOutput() device = make_device_state() change = DeviceParameterChange(physical_id=device.physical_id, parameter_id=device.parameters[0].id, value=1) await output.controller_did_connect_device(controller, physical_id=device.physical_id) await output.controller_did_receive_events(controller, [change]) assert output.connected_devices == [device.physical_id] assert output.events == [change] def test_name_is_autoderived_from_class_name(): """`name` defaults to the class name (CamelCase → spaced), overridable with an explicit `name`.""" class HueController(AbstractController[Device, Parameter]): pass class ZigBeeController(AbstractController[Device, Parameter]): name = "ZigBee" # override the "Zig Bee" default assert HueController.name == "Hue" assert HueController.slug() == "hue" assert ZigBeeController.name == "ZigBee" assert ZigBeeController.slug() == "zigbee" async def test_the_pairing_window_opens_without_credentials(): # the Hub broadcasts `start_pairing_window(duration)`: credentials are only for the one integration that needs them controller = _MinimalController(build_test_platform()) await controller.start_pairing_window(5) async def test_changed_settings_restart_it_unless_handled_and_the_platform_facts_dont(): controller = _MinimalController(build_test_platform()) assert await controller.settings_did_change(NoSettings()) is False assert await controller.platform_facts_did_change(build_test_platform(region="Europe")) is True async def test_a_test_platform_holds_the_facts_given_and_its_store_every_device(): store: dict = {} platform = build_test_platform(region="Europe", thread_dataset="0e08", store=store) controller = _MinimalController(platform) async with platform.device_repository(controller) as repo: await repo.save(make_device_state(integration=controller.key)) assert (platform.region, platform.wifi, platform.thread_dataset) == ("Europe", None, "0e08") async with DeviceRepositoryMemory(store=store).session() as everything: assert [device.integration for device in await everything.get_all()] == ["example-protocol"] def test_the_output_annotations_evaluate(): """A host reads them, e.g. the Hub's null output: each names the controller it hears from.""" for output in (ControllerOutput, LoggingControllerOutput): for name, method in inspect.getmembers(output, inspect.isfunction): if name.startswith("controller_did_"): assert inspect.get_annotations(method, eval_str=True)["controller"] is AnyController, name def _discovery(controller: AbstractController) -> Discovery: return Discovery( id=uuid4(), integration=controller.key, expected_credentials_options=[], transport="wifi", device_manufacturer=None, device_name="Lamp", device_category=None, device_icon=None, ) async def test_pairing_fills_and_returns_the_draft_without_saving_it(): store: dict = {} controller = _MinimalController(build_test_platform(store=store)) discovery = _discovery(controller) draft = make_device_state(id=discovery.id, integration=controller.key) device = await controller.pair_device(discovery, draft, None) assert device is draft and device.physical_id == controller.device_uuid("serial-1") assert store == {} async def test_the_physical_id_held_by_another_record_is_taken(): store: dict = {} platform = build_test_platform(store=store) controller = _MinimalController(platform) taken = controller.device_uuid("serial-1") async with platform.device_repository(controller) as repo: old = make_device_state(physical_id=taken, integration=controller.key, name="Old lamp") await repo.save(old) store[old.id]["is_paired"] = False discovery = _discovery(controller) with pytest.raises(DeviceIdTakenError) as raised: await controller.pair_device(discovery, make_device_state(id=discovery.id, integration=controller.key), None) error = raised.value assert (error.physical_id, error.device_id, error.name, error.is_paired) == (taken, old.id, "Old lamp", False) async def test_the_record_paired_onto_is_not_another(): store: dict = {} platform = build_test_platform(store=store) controller = _MinimalController(platform) picked = make_device_state(physical_id=controller.device_uuid("serial-1"), integration=controller.key) async with platform.device_repository(controller) as repo: await repo.save(picked) device = await controller.pair_device(_discovery(controller), picked, None) assert device.id == picked.id and device.physical_id == picked.physical_id def test_the_hub_id_is_read_only(device_state): with pytest.raises(ValidationError): device_state.id = uuid4() async def test_library_mode_takes_every_id_for_free(): controller = _MinimalController(Platform(documents_root=Path("."))) await controller.check_device_id(uuid4(), make_device_state()) def test_the_device_state_type_defaults_to_device_state(): assert _MinimalController(build_test_platform()).device_state_type is DeviceState ================================================================================ # FILE: tests/test_credentials.py ================================================================================ """Pairing credentials: what a discovery expects (CredentialsOption) vs. what a pairing supplies.""" import warnings from uuid import uuid4 import pytest from pydantic import BaseModel from majordom_integration_sdk.schemas.credentials import WifiCredentials from majordom_integration_sdk.schemas.device import ( CredentialsOption, CredentialsType, Discovery, ProvidedCredentials, ) def _discovery(options: list) -> Discovery: return Discovery( id=uuid4(), integration="test", expected_credentials_options=options, transport="test", device_manufacturer=None, device_name="Bulb", device_category=None, device_icon=None, ) def test_the_mask_is_serialized(): discovery = _discovery([CredentialsOption(type=CredentialsType.code, mask="DDDD-DDD-DDDD")]) dumped = discovery.model_dump(mode="json")["expected_credentials_options"] assert dumped == [{"type": "code", "mask": "DDDD-DDD-DDDD", "hint": None}] assert Discovery.model_validate_json(discovery.model_dump_json()) == discovery @pytest.mark.parametrize("legacy", [[CredentialsType.code, CredentialsType.qr], ["code", "qr"]]) def test_bare_types_are_accepted_for_stored_discoveries_and_older_integrations(legacy: list): discovery = _discovery(legacy) assert discovery.expected_credentials_options == [ CredentialsOption(type=CredentialsType.code), CredentialsOption(type=CredentialsType.qr), ] def test_a_stored_legacy_discovery_loads_from_json(): stored = _discovery([CredentialsOption(type=CredentialsType.secret)]).model_dump(mode="json") stored["expected_credentials_options"] = ["secret"] loaded = Discovery.model_validate(stored) assert loaded.expected_credentials_options == [CredentialsOption(type=CredentialsType.secret)] def test_with_mask_no_longer_mutates_the_shared_enum_member(): with warnings.catch_warnings(): warnings.simplefilter("error") option = CredentialsType.code.with_mask("DDD-DD-DDD") assert option == CredentialsOption(type=CredentialsType.code, mask="DDD-DD-DDD") assert not hasattr(CredentialsType.code, "code_mask") # the mask now survives the trip to the Hub assert _discovery([option]).model_dump(mode="json")["expected_credentials_options"][0]["mask"] == "DDD-DD-DDD" def test_with_hint_returns_an_option_with_the_hint(): with warnings.catch_warnings(): warnings.simplefilter("error") option = CredentialsType.button.with_hint("Press the button") assert option == CredentialsOption(type=CredentialsType.button, hint="Press the button") assert not hasattr(CredentialsType.button, "hint") def test_with_mask_can_carry_a_hint(): option = CredentialsType.code.with_mask("DDD-DD-DDD", hint="On the box") assert option == CredentialsOption(type=CredentialsType.code, mask="DDD-DD-DDD", hint="On the box") dumped = _discovery([option]).model_dump(mode="json")["expected_credentials_options"] assert dumped == [{"type": "code", "mask": "DDD-DD-DDD", "hint": "On the box"}] def test_each_call_returns_a_new_option_and_leaves_the_type_untouched(): assert CredentialsType.code.with_hint("x") is not CredentialsType.code.with_hint("x") assert CredentialsType.code.with_mask("DDDD") is not CredentialsType.code.with_mask("DDDD") assert CredentialsType.code == "code" def test_option_is_a_plain_data_model_without_builders(): option = CredentialsOption(type=CredentialsType.code) assert not hasattr(option, "with_mask") assert not hasattr(option, "with_hint") def test_existing_membership_checks_against_bare_types_keep_working(): # integrations do `credentials.type not in discovery.expected_credentials_options` discovery = _discovery([CredentialsOption(type=CredentialsType.code, mask="DDD-DD-DDD")]) assert CredentialsType.code in discovery.expected_credentials_options assert CredentialsType.qr not in discovery.expected_credentials_options @pytest.mark.parametrize( ("credentials", "accepted"), [ (ProvidedCredentials(type=CredentialsType.code, value="123-45-678"), True), (ProvidedCredentials(type=CredentialsType.button), True), (ProvidedCredentials(type=CredentialsType.secret, value="key"), False), (None, False), ], ) def test_accepts_matches_the_provided_type_against_the_options(credentials: ProvidedCredentials | None, accepted: bool): discovery = _discovery([CredentialsType.button, CredentialsOption(type=CredentialsType.code, mask="DDD-DD-DDD")]) assert discovery.accepts(credentials) is accepted def test_no_credentials_are_accepted_only_where_none_is_an_option(): assert _discovery([CredentialsType.none]).accepts(None) assert _discovery([CredentialsType.none]).accepts(ProvidedCredentials(type=CredentialsType.none)) def test_button_is_a_confirmation_without_a_value(): credentials = ProvidedCredentials(type=CredentialsType.button) assert credentials.value is None assert ProvidedCredentials.model_validate({"type": "button"}) == credentials assert CredentialsType.button != CredentialsType.none def test_a_discovery_can_offer_button_or_qr(): discovery = _discovery([CredentialsType.button, CredentialsType.qr]) assert [o.type for o in discovery.expected_credentials_options] == [CredentialsType.button, CredentialsType.qr] def test_a_wifi_password_is_written_never_read_back(): # settings holding a network (the Hub's saved ones) never return its password: their schema says so class Saved(BaseModel): wifi: list[WifiCredentials] = [] schema = Saved.model_json_schema() assert schema["$defs"]["WifiCredentials"]["properties"]["password"]["writeOnly"] is True assert "writeOnly" not in schema["$defs"]["WifiCredentials"]["properties"]["ssid"] assert WifiCredentials("home") == WifiCredentials("home", "") ================================================================================ # FILE: tests/test_dev.py ================================================================================ """Smoke tests for the standalone dev runner (``majordom_integration_sdk.dev``). ``run_controller`` binds needs through the runtime and then blocks forever, so it is never run whole against real radios in CI. These tests cover the parts that can break without a device on the network: ``build_platform`` assembles a correctly-scoped platform, the `Runner` runs a controller under the runtime as the Hub does (among fake peripherals), and ``run_controller`` starts and stops cleanly. """ import asyncio from dataclasses import replace from uuid import UUID import pytest from factories import make_device_state import majordom_integration_sdk.dev as dev from majordom_integration_sdk import Endpoint, Need, PeripheralChange from majordom_integration_sdk.capabilities import BLE_ROUTER from majordom_integration_sdk.controller import AbstractController from majordom_integration_sdk.dev import LoggingControllerOutput, Runner, build_platform, build_runtime, run_controller from majordom_integration_sdk.runtime import Pinned, Runtime from majordom_integration_sdk.runtime.output import HostOutput from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import Device, DeviceState, Discovery, Parameter, ProvidedCredentials from majordom_integration_sdk.testing import FakeBLERouter, FakePeripheral, FakeSSDP ZWAVE = Endpoint("zwave", "zwave-js-server", "ws://127.0.0.1:3000", is_shared=True) class _RecordingController(AbstractController[Device, Parameter]): """Minimal controller that records that it was started and stopped, and the peripheral changes it saw.""" name = "Dev Example" needs = [Need("zwave", ["zwave-js-server"]), Need("ble", ["router"], is_required=False)] instances: list["_RecordingController"] = [] handles_changes = True def __init__(self, platform): super().__init__(platform) self.started = self.stopped = 0 self.changes: list[PeripheralChange] = [] _RecordingController.instances.append(self) @property def discoveries(self) -> dict[UUID, Discovery]: return {} async def start(self): self.started += 1 async def stop(self): self.stopped += 1 async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: self.changes.append(change) return self.handles_changes async def pair_device( self, discovery: Discovery, draft: DeviceState, credentials: ProvidedCredentials | None ) -> DeviceState: return draft async def unpair(self, device: Device): pass async def identify(self, device: Device): pass async def fetch(self, device: Device): pass async def send_command(self, command: DeviceCommand, device: Device, parameter: Parameter): pass def peripherals(platform) -> list[_RecordingController]: """What its integration package exports.""" return [_RecordingController(platform)] @pytest.fixture def router() -> FakeBLERouter: return FakeBLERouter() def runner(tmp_path, router: FakeBLERouter, pinned=()) -> tuple[Runner, _RecordingController, Runtime]: """A controller under the runtime, among peripherals without radios or sockets.""" controller = _RecordingController(build_platform(storage_root=tmp_path)) runtime = build_runtime( [controller], tmp_path / "runtime", runtime_peripherals=[router, FakeSSDP()], pinned=pinned, platform=controller.platform, ) return Runner(controller, runtime), controller, runtime async def until(condition): async with asyncio.timeout(2): while not condition(): await asyncio.sleep(0.01) # --- build_platform ----------------------------------------------------------------------- def test_build_platform_roots_every_peripherals_documents_folder(tmp_path): platform = build_platform(storage_root=tmp_path) assert platform.documents_root == tmp_path and tmp_path.is_dir() async def test_build_platform_memory_repository_round_trips_in_its_scope(tmp_path): platform = build_platform(storage_root=tmp_path) device = make_device_state(integration="example") async with platform.make_device_repository("example") as repo: await repo.save(device) async with platform.make_device_repository("example") as repo: assert (await repo.state(physical_id=device.physical_id)) is not None async with platform.make_device_repository("other") as repo: assert (await repo.state(physical_id=device.physical_id)) is None async def test_build_platform_sqlite_persists_to_file(tmp_path): db_path = tmp_path / "dev.sqlite" device = make_device_state(integration="example") platform = build_platform(storage_root=tmp_path, db_path=db_path) async with platform.make_device_repository("example") as repo: await repo.save(device) assert db_path.exists(), "a db_path should select the file-backed sqlite repository" # A fresh platform over the same file sees the persisted device (survives 'restarts'). again = build_platform(storage_root=tmp_path, db_path=db_path) async with again.make_device_repository("example") as repo: assert (await repo.state(physical_id=device.physical_id)) is not None # --- the runtime -------------------------------------------------------------------------- def test_without_the_runtime_extra_the_runner_says_what_to_install(tmp_path, monkeypatch): monkeypatch.setattr(dev.importlib.util, "find_spec", lambda name: None) platform = build_platform(storage_root=tmp_path) with pytest.raises(ImportError, match=r"majordom-integration-sdk\[runtime"): build_runtime([_RecordingController(platform)], tmp_path, platform=platform) async def test_the_runner_starts_the_controller_once_its_needs_are_bound(tmp_path, router): runner_, controller, runtime = runner(tmp_path, router) await runner_.start() assert not controller.started # nothing offers zwave-js-server here assert "zwave" in runtime.unbound(controller) pinned = runtime.peripherals[0] assert isinstance(pinned, Pinned) await pinned.pin(ZWAVE) await until(lambda: runner_.is_running) assert controller.peripherals.endpoint("zwave") == ZWAVE assert controller.peripherals.instance(BLE_ROUTER) is router # the router, as under the Hub await pinned.unpin("zwave") # a required need lost: stopped until it's back assert controller.stopped == 1 and not runner_.is_running await runner_.stop() async def test_the_runner_hands_a_moved_peripheral_over_or_restarts(tmp_path, router): runner_, controller, runtime = runner(tmp_path, router, pinned=[ZWAVE]) await runner_.start() await until(lambda: runner_.is_running) pinned = runtime.peripherals[0] assert isinstance(pinned, Pinned) moved = Endpoint("zwave", "zwave-js-server", "ws://192.168.1.9:3000", is_shared=True) await pinned.pin(moved) appeared = PeripheralChange("ble", None, router.endpoint) # the router started beside it, at boot assert controller.changes == [appeared, PeripheralChange("zwave", ZWAVE, moved)] assert (controller.started, controller.stopped) == (1, 0) # handled in place controller.handles_changes = False await pinned.pin(ZWAVE) await until(lambda: controller.started == 2) assert controller.stopped == 1 await runner_.stop() async def test_run_controller_with_peripherals_given_runs_without_the_runtime(tmp_path): _RecordingController.instances.clear() task = asyncio.create_task(run_controller(peripherals, storage_root=tmp_path, peripherals={"zwave": ZWAVE})) async with asyncio.timeout(5): while not (_RecordingController.instances and _RecordingController.instances[-1].started): await asyncio.sleep(0.01) task.cancel() await task # run_controller swallows the cancellation after cleaning up controller = _RecordingController.instances[-1] assert controller.started and controller.stopped assert controller.peripherals.endpoint("zwave") == ZWAVE assert controller.platform.documents_folder(controller) == tmp_path / "dev-example" # by its key, as by the Hub assert isinstance(controller.output, LoggingControllerOutput) # what it reports is logged assert not (tmp_path / "runtime").exists() async def test_run_controller_wants_one_controller_among_what_an_integration_exports(tmp_path): with pytest.raises(ValueError, match="one controller, not 2"): await run_controller(lambda platform: peripherals(platform) * 2, storage_root=tmp_path) async def test_run_controller_starts_and_stops_cleanly_under_the_runtime(tmp_path): _RecordingController.instances.clear() task = asyncio.create_task( run_controller( peripherals, storage_root=tmp_path, runtime_peripherals=[FakeSSDP()], pinned=[ZWAVE], region="Europe", ) ) async with asyncio.timeout(5): while not (_RecordingController.instances and _RecordingController.instances[-1].started): await asyncio.sleep(0.01) task.cancel() await task controller = _RecordingController.instances[-1] assert controller.started and controller.stopped assert controller.peripherals.endpoint("zwave") == ZWAVE # bound by the runtime assert controller.platform.region == "Europe" # the platform it was given, its overrides too output = controller.output # the runtime's, which logs what it reports assert isinstance(output, HostOutput) and isinstance(output.controller_output, LoggingControllerOutput) async def test_what_a_peripheral_learns_reaches_the_controllers_platform(tmp_path, router): border_router = FakePeripheral("my-border-router") controller = _RecordingController(replace(build_platform(storage_root=tmp_path), region="Europe")) runtime = build_runtime( [controller], tmp_path / "runtime", runtime_peripherals=[border_router], platform=controller.platform ) await runtime.start() await border_router.output.peripheral_did_learn(border_router, {"thread_dataset": "0e08"}) assert (controller.platform.region, controller.platform.thread_dataset) == ("Europe", "0e08") await runtime.stop() ================================================================================ # FILE: tests/test_errors.py ================================================================================ """MissingCredentialsError: what the Hub lacks to pair a device.""" from uuid import UUID import pytest from majordom_integration_sdk import DeviceIdTakenError, MissingCredentialsError def test_the_type_defaults_to_wifi(): assert MissingCredentialsError().type == MissingCredentialsError.WIFI == "wifi" def test_the_known_types(): assert MissingCredentialsError.THREAD == "thread" def test_the_message_carries_the_type(): assert str(MissingCredentialsError("thread")) == "Missing credentials: thread" def test_a_custom_type_is_accepted(): assert MissingCredentialsError("zigbee_network_key").type == "zigbee_network_key" @pytest.mark.parametrize("type_", ["", "WiFi", "wi-fi", "thread network", "_wifi", "wifi_", "1wifi"]) def test_the_type_is_lower_snake_case(type_: str): with pytest.raises(ValueError): MissingCredentialsError(type_) def test_the_hub_already_handles_it_as_a_lookup_error(): assert issubclass(MissingCredentialsError, LookupError) def test_a_taken_device_id_carries_the_record_holding_it(): physical_id, device_id = UUID(int=1), UUID(int=2) error = DeviceIdTakenError(physical_id, device_id, "Lamp", is_paired=True) assert (error.physical_id, error.device_id, error.name, error.is_paired) == (physical_id, device_id, "Lamp", True) assert str(error) == f"Physical id {physical_id} is taken by 'Lamp' ({device_id}, paired)" ================================================================================ # FILE: tests/test_files.py ================================================================================ """What the SDK and integrations keep on disk themselves: JSON, written whole or not at all, for its owner alone.""" import importlib import pytest from majordom_integration_sdk.files import read_json, write_json def test_json_is_written_whole_for_its_owner_alone(tmp_path): path = tmp_path / "esphome" / "keys.json" # an integration's own: the keys it set on its nodes write_json(path, {"node": "secret"}) assert read_json(path) == {"node": "secret"} assert path.stat().st_mode & 0o777 == 0o600 and not path.with_name("keys.json.tmp").exists() def test_missing_or_unreadable_json_reads_as_nothing(tmp_path): (tmp_path / "broken.json").write_text("{") assert read_json(tmp_path / "missing.json") == read_json(tmp_path / "broken.json") == {} def test_one_import_path_outside_the_runtime(): with pytest.raises(ImportError): importlib.import_module("majordom_integration_sdk.runtime.files") ================================================================================ # FILE: tests/test_main_parameter.py ================================================================================ from uuid import uuid4 from majordom_integration_sdk.schemas.parameter import ( Parameter, ParameterDataType, ParameterRole, ParameterVisibility, next_main_parameter_value, ) def _p(*, data_type, valid_values=None, default_value=None, cls=Parameter): return cls( id=uuid4(), name="p", data_type=data_type, role=ParameterRole.control, visibility=ParameterVisibility.user, valid_values=valid_values, default_value=default_value, integration_data=None, ) def test_cycle_toggles_between_two_values(): assert next_main_parameter_value(0, [0, 4]) == 4 assert next_main_parameter_value(4, [0, 4]) == 0 def test_cycle_rotates_and_wraps(): assert next_main_parameter_value(1, [0, 1, 2]) == 2 assert next_main_parameter_value(2, [0, 1, 2]) == 0 def test_single_value_cycle_is_a_button(): assert next_main_parameter_value(99, [3]) == 3 # always sets to 3 regardless of current def test_unknown_current_starts_at_first(): assert next_main_parameter_value(None, [0, 4]) == 0 assert next_main_parameter_value(7, [0, 4]) == 0 def test_empty_cycle_returns_none(): assert next_main_parameter_value(0, []) is None assert next_main_parameter_value(0, None) is None def test_enum_with_valid_values_can_be_main(): assert _p(data_type=ParameterDataType.enum, valid_values={0: "off", 4: "on"}).can_be_main_parameter def test_enum_without_valid_values_cannot_be_main(): assert not _p(data_type=ParameterDataType.enum).can_be_main_parameter def test_default_value_makes_any_type_main(): assert _p(data_type=ParameterDataType.integer, default_value=5).can_be_main_parameter def test_valid_values_makes_any_type_main(): assert _p(data_type=ParameterDataType.integer, valid_values={0: "off", 80: "bright"}).can_be_main_parameter def test_main_cycle_from_valid_values(): p = _p(data_type=ParameterDataType.integer, valid_values={80: "bright", 0: "off"}) assert p.main_cycle == [0, 80] # numeric order def test_main_cycle_from_set_default_value(): p = _p(data_type=ParameterDataType.integer, valid_values={0: "off", 40: "dim", 80: "bright"}, default_value={0, 80}) assert p.main_cycle == [0, 80] # the curated default_value subset wins over full valid_values assert p.default_value == {0, 80} # a pythonic set (serializes to a JSON array) def test_main_cycle_single_default_is_button(): p = _p(data_type=ParameterDataType.integer, default_value=5) assert p.main_cycle == [5] def test_main_cycle_bool_toggles(): assert _p(data_type=ParameterDataType.bool).main_cycle == [False, True] def test_main_cycle_none_command_is_not_a_cycle(): assert _p(data_type=ParameterDataType.none).main_cycle is None def test_value_is_pythonic(): from majordom_integration_sdk.schemas.parameter import ParameterState p = _p(data_type=ParameterDataType.integer) state = ParameterState.model_validate(p, from_attributes=True) state.value = 42 assert state.value == 42 assert ParameterState.model_validate_json(state.model_dump_json()).value == 42 def test_non_user_visibility_cannot_be_main(): p = _p(data_type=ParameterDataType.bool) p.visibility = ParameterVisibility.setting assert not p.can_be_main_parameter p.visibility = ParameterVisibility.system assert not p.can_be_main_parameter class _UnparametrizedParameter(Parameter): # integrations subclass without a type argument pass def _roundtrip_from_json_data(p: Parameter) -> Parameter: # The repositories' read path: a JSON-mode dict validated back (not model_validate_json) return type(p).model_validate(p.model_dump(mode="json")) def test_set_default_value_survives_roundtrip(): p = _p(data_type=ParameterDataType.integer, default_value={0, 100}, cls=_UnparametrizedParameter) assert _roundtrip_from_json_data(p).default_value == {0, 100} def test_main_cycle_survives_roundtrip(): p = _p(data_type=ParameterDataType.integer, default_value={0, 100}, cls=_UnparametrizedParameter) assert _roundtrip_from_json_data(p).main_cycle == [0, 100] ================================================================================ # FILE: tests/test_notification.py ================================================================================ import asyncio from typing import Any, cast from majordom_integration_sdk import IntegrationError from majordom_integration_sdk.schemas.notification import Notification, NotificationPriority, NotificationType from majordom_integration_sdk.testing import RecordingControllerOutput def test_notification_defaults(): n = Notification(message="Firmware update available") assert n.type is NotificationType.info assert n.priority is NotificationPriority.normal assert n.ttl is None def test_output_records_notification(): out = RecordingControllerOutput() n = Notification( message="Re-plug the radio", type=NotificationType.warning, priority=NotificationPriority.urgent, ttl=30, ) asyncio.run(out.controller_did_emit_notification(cast(Any, None), n)) assert out.notifications == [n] def test_output_keeps_the_active_errors_by_id(): out = RecordingControllerOutput() lost, again = ( IntegrationError("server-unreachable", "Server lost"), IntegrationError("server-unreachable", "Still lost"), ) unplugged = IntegrationError("stick-unplugged", "Re-plug the stick") async def report(): for error in (lost, unplugged, again): await out.controller_did_encounter_error(cast(Any, None), error) await out.controller_did_resolve_error(cast(Any, None), "stick-unplugged") await out.controller_did_resolve_error(cast(Any, None), "never-reported") asyncio.run(report()) assert out.errors == {"server-unreachable": again} assert out.error_log == [lost, unplugged, again, "stick-unplugged", "never-reported"] ================================================================================ # FILE: tests/test_parameter_audit.py ================================================================================ from uuid import uuid4 from majordom_integration_sdk.parameter_audit import audit_device_parameters from majordom_integration_sdk.schemas.parameter import ( Parameter, ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) def _p(name, *, vis=ParameterVisibility.user, unit=ParameterUnit.plain, role=ParameterRole.sensor): return Parameter( id=uuid4(), name=name, data_type=ParameterDataType.integer, unit=unit, role=role, visibility=vis, integration_data=None, ) def test_clean_device_has_no_warnings(): params = [ _p("temperature", unit=ParameterUnit.celsius), _p("humidity", unit=ParameterUnit.percentage), _p("battery", unit=ParameterUnit.percentage, role=ParameterRole.sensor), ] assert audit_device_parameters("Sensor", params) == [] def test_flags_over_exposure(): params = [_p(f"attr_{i}") for i in range(12)] warnings = audit_device_parameters("Flooded", params) assert any("over-exposed" in w for w in warnings) def test_ignores_non_user_params_in_count(): params = [_p(f"attr_{i}", vis=ParameterVisibility.system) for i in range(20)] + [_p("on_off")] assert audit_device_parameters("Lean", params) == [] def test_flags_near_duplicate_names(): params = [_p("current_x", unit=ParameterUnit.percentage), _p("current_y", unit=ParameterUnit.percentage)] assert any("near-duplicate" in w for w in audit_device_parameters("Light", params)) def test_similar_name_whitelist_suppresses(): params = [ _p("occupied_heating_setpoint", unit=ParameterUnit.celsius, role=ParameterRole.control), _p("occupied_cooling_setpoint", unit=ParameterUnit.celsius, role=ParameterRole.control), ] warnings = audit_device_parameters( "Thermostat", params, ignore_similar_pairs=[("occupied_heating_setpoint", "occupied_cooling_setpoint")], ) assert not any("near-duplicate" in w for w in warnings) def test_flags_redundant_representation_group(): params = [ _p("current_hue", unit=ParameterUnit.percentage), _p("current_saturation", unit=ParameterUnit.percentage), _p("current_x", unit=ParameterUnit.percentage), _p("current_y", unit=ParameterUnit.percentage), ] assert any("redundant representations" in w for w in audit_device_parameters("Light", params)) ================================================================================ # FILE: tests/test_peripherals.py ================================================================================ from typing import Any, cast from uuid import UUID import pytest from pydantic import BaseModel, ValidationError from majordom_integration_sdk import ( AbstractController, Endpoint, Need, NoSettings, Peripheral, PeripheralChange, Peripherals, Service, UsbDriver, ) from majordom_integration_sdk.capabilities import BLE_ROUTER from majordom_integration_sdk.peripherals.peripheral import START_TIMEOUT from majordom_integration_sdk.schemas.device import Device, Discovery, Parameter from majordom_integration_sdk.testing import build_test_platform def test_need_accepts_family_and_dialect(): assert Need("zigbee").accepts(Endpoint("zigbee", "znp")) assert Need("zigbee", ["ezsp", "znp"]).accepts(Endpoint("zigbee", "znp")) assert not Need("zigbee", ["ezsp"]).accepts(Endpoint("zigbee", "znp")) assert not Need("thread").accepts(Endpoint("zigbee", "ezsp")) class Host(Peripheral): name = "host" provides = [Endpoint("ip", is_shared=True)] async def test_a_peripheral_needs_provides_and_is_bound_nothing_by_default(): host = Host() assert (host.needs, host.provides, host.peripherals.bound) == ((), [Endpoint("ip", is_shared=True)], {}) with pytest.raises(TypeError): cast(Any, host.peripherals.bound)["ip"] = Endpoint("ip") # shared by every peripheral until bound: read-only assert not host.is_on_demand and host.start_timeout == START_TIMEOUT assert host.Settings is NoSettings # it takes none await host.start() await host.stop() await host.output.peripheral_did_change_provided(host) # nothing runs it: logged assert await host.needed_peripheral_did_change(PeripheralChange("ip", None, None)) is False # restart it assert await host.settings_did_change(NoSettings()) is False assert await host.platform_facts_did_change(build_test_platform()) is True # the facts concern few def test_peripherals_hand_out_one_endpoint_many_or_an_instance(): router = object() adapters = [Endpoint("ble", "bluez", "hci0"), Endpoint("ble", "bluez", "hci1")] peripherals = Peripherals({"zigbee": Endpoint("zigbee", "ezsp", "/dev/ttyUSB0"), "raw": adapters}) assert peripherals.endpoint("zigbee").url == "/dev/ttyUSB0" assert peripherals.endpoints("zigbee") == [peripherals.bound["zigbee"]] assert peripherals.endpoints("raw") == adapters with pytest.raises(TypeError, match="endpoints"): peripherals.endpoint("raw") assert peripherals.endpoints("thread") == [] assert peripherals.instance(BLE_ROUTER) is None with pytest.raises(KeyError): peripherals.endpoint("thread") peripherals = Peripherals({"ble": Endpoint("ble", "router", "router", is_shared=True, instance=router)}) assert peripherals.instance(BLE_ROUTER) is router def test_an_endpoint_is_the_same_whatever_instance_it_carries(): assert Endpoint("ble", "esphome-proxy", "esphome:aa", instance=object()) == Endpoint( "ble", "esphome-proxy", "esphome:aa", instance=object() ) assert not Need("ble").is_many def test_endpoint_params_say_how_to_talk_to_it(): stick = Endpoint("zigbee", "ezsp", "/dev/ttyUSB0", params={"baud": 115200, "flow_control": True}) assert stick.params["baud"] == 115200 assert Endpoint("zigbee").params == {} assert hash(stick) == hash(Endpoint("zigbee", "ezsp", "/dev/ttyUSB0")) SERVER = Service("server", compose={}, provides=[Endpoint("matter", "matter-server", "ws://127.0.0.1:{ports.api}")]) async def test_a_service_runs_on_demand_and_hooks_in_doing_nothing(): assert SERVER.is_on_demand and SERVER.start_timeout == 30 * 60 # long enough to pull its image first assert SERVER.ports == {} and SERVER.Settings is NoSettings assert await SERVER.provision(Endpoint("matter", "matter-server", "ws://127.0.0.1:5580")) is None assert await SERVER.is_healthy() async def test_without_a_runtime_a_service_provides_its_templates_and_doesnt_run(): assert SERVER.provides == SERVER.templates with pytest.raises(NotImplementedError, match="run server yourself"): await SERVER.start() class Silabs(UsbDriver): name = "silabs" firmwares = {"zigbee-ncp": [Endpoint("zigbee", "ezsp", "{device}", params={"baud": 115200})]} def test_a_usb_driver_says_what_a_firmware_serves_and_offers_itself(): driver = Silabs() assert driver.serves("zigbee-ncp", "/dev/ttyUSB0", {"flow_control": False}) == [ Endpoint("zigbee", "ezsp", "/dev/ttyUSB0", params={"baud": 115200, "flow_control": False}) ] assert driver.serves(None, "/dev/ttyUSB0") == [] assert driver.provides[0].instance is driver and driver.is_on_demand assert driver.flashable("/dev/ttyUSB0", "dev") == [] class ExampleController(AbstractController[Device, Parameter, "ExampleController.Settings"]): needs = [Need("example")] class Settings(BaseModel): channel: int = 11 @property def discoveries(self) -> dict[UUID, Discovery]: return {} async def start(self): pass async def stop(self): pass async def pair_device(self, discovery, draft, credentials): return draft async def unpair(self, device): pass async def identify(self, device): pass async def fetch(self, device): pass async def send_command(self, command, device, parameter): pass async def test_a_controller_is_a_peripheral_with_its_settings_and_its_peripherals(): controller = ExampleController(build_test_platform()) controller.peripherals = Peripherals({"example": Endpoint("example", "echo", "ws://x")}) # library mode assert controller.settings.channel == 11 # its defaults until the runtime hands over the saved ones assert controller.peripherals.endpoint("example").url == "ws://x" assert not controller.is_on_demand and controller.provides == () assert await controller.needed_peripheral_did_change(PeripheralChange("example", None, None)) is False assert await controller.platform_facts_did_change(build_test_platform()) is True # it reads them when it does def test_a_controller_without_settings_takes_none(): class Plain(ExampleController): Settings = NoSettings assert Plain(build_test_platform()).settings == NoSettings() with pytest.raises(ValidationError): NoSettings.model_validate({"channel": 11}) assert AbstractController.needs == () ================================================================================ # FILE: tests/test_repository.py ================================================================================ """Both first-class repositories must satisfy the same protocol behaviour.""" import sqlite3 from uuid import uuid4 import pytest from factories import make_device_state from majordom_integration_sdk.repository import ( DeviceRepositoryMemory, DeviceRepositoryProtocol, SqliteDeviceRepository, ) from majordom_integration_sdk.schemas.base import Base from majordom_integration_sdk.schemas.device import Device, DeviceState from majordom_integration_sdk.schemas.parameter import ParameterVisibility class _PairingData(Base): """An integration's own typed `integration_data` (e.g. HomeKit pairing data).""" token: str class _Endpoint(Base): """A parameter's own typed `integration_data`.""" endpoint: int class _Learned(Base): """Typed `integration_data` an unpaired device can hold: every field has a default.""" firmware: str | None = None class _MyDevice(Device[_PairingData]): pass def make_my_device(device_id=None, token: str = "secret", integration: str = "example", physical_id=None) -> _MyDevice: return _MyDevice( id=device_id or uuid4(), physical_id=physical_id or uuid4(), name="Lamp", room_id=uuid4(), transport="wifi", integration=integration, manufacturer="ACME", integration_data=_PairingData(token=token), ) @pytest.fixture(params=["memory", "sqlite"]) def repository(request, tmp_path) -> DeviceRepositoryProtocol: if request.param == "memory": return DeviceRepositoryMemory() return SqliteDeviceRepository(tmp_path / "devices.db") async def test_save_and_read_back(repository, device_state): async with repository.session() as repo: await repo.save(device_state) state = await repo.state(physical_id=device_state.physical_id) got = await repo.get(physical_id=device_state.physical_id) assert state is not None and state.id == device_state.id assert got is not None and got.id == device_state.id assert [d.id for d in await repo.get_all()] == [device_state.id] async def test_get_unknown_is_none(repository): async with repository.session() as repo: assert await repo.state(physical_id=uuid4()) is None assert await repo.get(physical_id=uuid4()) is None async def test_parameter_state_round_trip(repository, device_state): parameter = device_state.parameters[0] async with repository.session() as repo: await repo.save(device_state) fetched = await repo.get_parameter_state(physical_id=device_state.physical_id, parameter_id=parameter.id) assert fetched is not None and fetched.id == parameter.id parameter.value = 7 await repo.save_parameter_state(physical_id=device_state.physical_id, parameter_state=parameter) updated = await repo.get_parameter_state(physical_id=device_state.physical_id, parameter_id=parameter.id) assert updated is not None and updated.value == 7 async def test_update_visibility(repository, device_state): parameter = device_state.parameters[0] async with repository.session() as repo: await repo.save(device_state) await repo.update_parameter_visibility(parameter.id, ParameterVisibility.system) fetched = await repo.get_parameter_state(physical_id=device_state.physical_id, parameter_id=parameter.id) assert fetched is not None and fetched.visibility is ParameterVisibility.system async def test_reads_are_keyed_by_physical_id(repository, device_state): async with repository.session() as repo: await repo.save(device_state) assert await repo.get(physical_id=device_state.id) is None assert await repo.state(physical_id=device_state.id) is None async def test_a_physical_id_held_by_another_record_is_refused(repository, device_state): other = make_device_state(physical_id=device_state.physical_id) async with repository.session() as repo: await repo.save(device_state) with pytest.raises((ValueError, sqlite3.IntegrityError)): await repo.save(other) async def test_a_new_physical_id_updates_the_same_record(repository, device_state): """Pairing onto a kept record: its Hub id stays, its physical id moves.""" async with repository.session() as repo: await repo.save(device_state) moved = device_state.model_copy(update={"physical_id": uuid4()}) await repo.save(moved) assert await repo.state(physical_id=device_state.physical_id) is None state = await repo.state(physical_id=moved.physical_id) assert state is not None and state.id == device_state.id assert [d.id for d in await repo.get_all()] == [device_state.id] async def test_delete(repository, device_state): async with repository.session() as repo: await repo.save(device_state) await repo.delete(device_state.id) assert await repo.state(physical_id=device_state.physical_id) is None async def test_typed_read_returns_typed_integration_data(repository): device = make_my_device(token="secret") async with repository.session() as repo: await repo.save(device) got = await repo.get(physical_id=device.physical_id, as_=_MyDevice) assert got is not None assert isinstance(got.integration_data, _PairingData) assert got.integration_data.token == "secret" listed = await repo.get_all(as_=_MyDevice) assert [d.integration_data.token for d in listed] == ["secret"] async def test_a_typed_state_reads_the_data_of_the_device_and_its_parameters(repository, device_state): device_state.parameters[0].integration_data = {"endpoint": 1} async with repository.session() as repo: await repo.save(device_state) await repo.save( make_my_device( device_id=device_state.id, physical_id=device_state.physical_id, integration=device_state.integration ) ) state = await repo.state(physical_id=device_state.physical_id, as_=DeviceState[_PairingData, _Endpoint]) assert state is not None and state.integration_data.token == "secret" assert state.parameters[0].integration_data.endpoint == 1 untyped = await repo.state(physical_id=device_state.physical_id) # a bare name means any data assert untyped is not None and untyped.parameters[0].integration_data == {"endpoint": 1} async def test_device_and_state_views_merge(repository, device_state): """Device carries integration_data, DeviceState parameters too — saving one must not clobber the other's half of the record, nor a DeviceState that wasn't given integration_data the stored one.""" device = make_my_device( device_id=device_state.id, physical_id=device_state.physical_id, token="t", integration=device_state.integration ) async with repository.session() as repo: await repo.save(device_state) # info + parameters await repo.save(device) # info + integration_data state = await repo.state(physical_id=device_state.physical_id) typed = await repo.get(physical_id=device_state.physical_id, as_=_MyDevice) assert state is not None and len(state.parameters) == 1, "parameters must survive a Device save" assert typed is not None and typed.integration_data.token == "t" # ...and the reverse order. await repo.save(device_state) typed_again = await repo.get(physical_id=device_state.physical_id, as_=_MyDevice) assert typed_again is not None, "integration_data must survive a DeviceState save" assert typed_again.integration_data.token == "t" async def test_a_typed_state_without_data_holds_its_own_model_and_keeps_the_stored_one(repository, device_state): """Built without `integration_data`, a typed device holds its own model validated from `{}`; the field stays unset, so saving it leaves the stored data as it is.""" state = DeviceState[_Learned](**device_state.model_dump(exclude={"integration_data"})) assert isinstance(state.integration_data, _Learned) async with repository.session() as repo: await repo.save(make_my_device(device_id=state.id, token="t", integration=state.integration)) await repo.save(state) typed = await repo.get(physical_id=state.physical_id, as_=_MyDevice) assert typed is not None and typed.integration_data.token == "t" async def test_data_filled_in_place_on_a_device_saved_without_any_is_kept(repository): """Read back from a record without data, a typed device holds its own model, unset; filled in place (a pairing on the record the Hub seeded), it is saved: the record has no data to keep.""" seeded = Device( id=uuid4(), physical_id=uuid4(), name="Lamp", room_id=uuid4(), transport="wifi", integration="example", manufacturer=None, ) # fmt: skip async with repository.session() as repo: await repo.save(seeded) device = await repo.get(physical_id=seeded.physical_id, as_=Device[_Learned]) assert device is not None device.integration_data.firmware = "1.2" await repo.save(device) kept = await repo.get(physical_id=seeded.physical_id, as_=Device[_Learned]) assert kept is not None and kept.integration_data.firmware == "1.2" @pytest.mark.parametrize("stored", [{}, None]) async def test_data_filled_in_place_on_a_state_saved_onto_a_record_holding_none_is_kept(repository, stored): """The `{}` (or null) the Hub stores a device with before pairing is no data to keep: a typed state built without any and filled in place (a pairing) is saved, as the Hub's own repository does.""" seeded = Device( id=uuid4(), physical_id=uuid4(), name="Lamp", room_id=uuid4(), transport="wifi", integration="example", manufacturer=None, integration_data=stored, ) # fmt: skip async with repository.session() as repo: await repo.save(seeded) state = DeviceState[_Learned](**seeded.model_dump(exclude={"integration_data"}), parameters=[]) state.integration_data.firmware = "1.2" await repo.save(state) kept = await repo.get(physical_id=seeded.physical_id, as_=Device[_Learned]) assert kept is not None and kept.integration_data.firmware == "1.2" def test_optional_data_is_none_until_paired(device_state): """`Device[X | None]`: unset, or the `{}` the Hub stores a device with before pairing, is None.""" optional = DeviceState[_PairingData | None] assert optional(**device_state.model_dump(exclude={"integration_data"})).integration_data is None assert optional(**device_state.model_dump()).integration_data is None @pytest.fixture(params=["memory", "sqlite"]) def make_scoped(request, tmp_path): """Factory building repositories that share one backing store, scoped per call.""" store: dict = {} path = tmp_path / "scoped.db" def make(integration): if request.param == "memory": return DeviceRepositoryMemory(integration=integration, store=store) return SqliteDeviceRepository(path, integration=integration) return make async def test_scope_limits_get_all(make_scoped): admin = make_scoped(None) # full access async with admin.session() as repo: await repo.save(make_device_state(integration="mine")) await repo.save(make_device_state(integration="other")) async with make_scoped("mine").session() as repo: assert {d.integration for d in await repo.get_all()} == {"mine"} async with make_scoped(None).session() as repo: assert {d.integration for d in await repo.get_all()} == {"mine", "other"} async def test_scope_rejects_foreign_save(make_scoped): async with make_scoped("mine").session() as repo: with pytest.raises(PermissionError): await repo.save(make_device_state(integration="other")) async def test_scope_hides_foreign_reads(make_scoped): foreign = make_device_state(integration="other") async with make_scoped(None).session() as repo: await repo.save(foreign) async with make_scoped("mine").session() as repo: assert await repo.state(physical_id=foreign.physical_id) is None assert await repo.get(physical_id=foreign.physical_id) is None assert ( await repo.get_parameter_state(physical_id=foreign.physical_id, parameter_id=foreign.parameters[0].id) is None ) async def test_sqlite_persists_across_sessions(tmp_path, device_state): repo = SqliteDeviceRepository(tmp_path / "devices.db") async with repo.session() as session: await session.save(device_state) # A brand-new repository object over the same file still sees the device. reopened = SqliteDeviceRepository(tmp_path / "devices.db") async with reopened.session() as session: persisted = await session.state(physical_id=device_state.physical_id) assert persisted is not None and persisted.id == device_state.id async def test_lookups_are_keyword_only(repository, device_state): async with repository.session() as repo: with pytest.raises(TypeError): await repo.get(device_state.physical_id) ================================================================================ # FILE: tests/test_schemas.py ================================================================================ """Schema behaviour that the SDK owns — pythonic parameter values, generic over the value type V.""" from uuid import uuid4 from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterState, ParameterVisibility, ) def _state(data_type: ParameterDataType, **kw) -> ParameterState: return ParameterState( id=uuid4(), name="p", data_type=data_type, role=ParameterRole.control, visibility=ParameterVisibility.user, integration_data=None, **kw, ) def test_scalar_value_is_pythonic_and_roundtrips(): for dt, v in [ (ParameterDataType.integer, 5), (ParameterDataType.bool, True), (ParameterDataType.decimal, 1.5), (ParameterDataType.string, "hi"), ]: s = _state(dt, value=v) assert s.value == v assert ParameterState.model_validate_json(s.model_dump_json()).value == v def test_struct_value_is_a_plain_dict(): s = _state(ParameterDataType.struct, value={"a": 1, "b": [2, 3]}) assert s.value == {"a": 1, "b": [2, 3]} assert ParameterState.model_validate_json(s.model_dump_json()).value == {"a": 1, "b": [2, 3]} def test_value_valid_values_and_default_share_one_type(): # An int parameter: int value, int valid_values keys, int default_value — all V=int. s = _state(ParameterDataType.enum, value=0, valid_values={0: "off", 4: "on"}, default_value={0, 4}) assert (s.value, s.valid_values, s.default_value) == (0, {0: "off", 4: "on"}, {0, 4}) rt = ParameterState.model_validate_json(s.model_dump_json()) assert rt.default_value == {0, 4} # a set survives the JSON-array round-trip assert rt.valid_values == {0: "off", 4: "on"} # int keys survive def test_single_default_value_stays_scalar(): s = _state(ParameterDataType.integer, default_value=5) assert s.default_value == 5 # a lone value is the scalar branch of `set[V] | V`, not a set def test_a_parameter_compares_with_other_values_without_raising(): """Its equality is by id among parameters; anything else (a stored raw value, as an ORM compares it) is unequal.""" parameter = _state(ParameterDataType.integer, value=7) assert parameter == parameter.model_copy(update={"value": 8}) assert parameter != 7 ================================================================================ # FILE: tests/test_spec_drift.py ================================================================================ from majordom_integration_sdk.spec_drift import diff_specs def test_detects_each_tier(): baseline = {(1, 1): "user", (1, 2): "setting", (1, 3): "system"} current = {(1, 1): "user", (1, 2): "user", (1, 4): "setting"} # 1,2 reclassified; 1,3 removed; 1,4 added r = diff_specs(current, baseline) assert r.added == {(1, 4): "setting"} assert r.removed == {(1, 3): "system"} assert r.reclassified == {(1, 2): ("setting", "user")} def test_reclassify_is_high_risk(): r = diff_specs({(1, 1): "user"}, {(1, 1): "setting"}) assert r.has_high_risk assert not r.is_empty def test_add_only_is_not_high_risk(): r = diff_specs({(1, 1): "user", (2, 2): "setting"}, {(1, 1): "user"}) assert not r.has_high_risk assert r.added == {(2, 2): "setting"} def test_identical_is_empty(): spec = {(1, 1): "user"} r = diff_specs(spec, dict(spec)) assert r.is_empty assert "no drift" in r.render(source="zha") def test_render_lists_reclassify_first(): r = diff_specs({(1, 1): "user", (9, 9): "user"}, {(1, 1): "setting"}) out = r.render(source="zha") assert out.index("RECLASSIFY") < out.index("ADD") def test_render_key_label_annotates_each_change(): r = diff_specs({(0x0556, 1): "user"}, {}) out = r.render(source="matter-ha", key_label=lambda k: f"Chime.Attr{k[1]}") # the human name appears alongside the raw id on the change line assert "Chime.Attr1" in out assert "(1366, 1)" in out def test_render_key_label_failure_falls_back_to_id(): def boom(_key: object) -> str: raise KeyError("unknown") r = diff_specs({(0x0556, 1): "user"}, {}) out = r.render(source="matter-ha", key_label=boom) # must not raise assert "(1366, 1)" in out ================================================================================ # FILE: tests/test_version.py ================================================================================ from importlib.metadata import version import majordom_integration_sdk def test_version_matches_installed_distribution(): assert majordom_integration_sdk.__version__ == version("majordom-integration-sdk") # integration-template — full source # repo: https://github.com/MajorDom-Systems/integration-template branch: master commit: 504e5c7dc79fcea4cbf3aa167e7e2152f1209e00 # generated: 2026-11-16 — AUTO-GENERATED, do not edit by hand ## File tree .gitignore LICENSE README.md integration_template/__init__.py integration_template/controller.py pyproject.toml tests/conftest.py tests/test_controller.py tests/test_smoke.py ================================================================================ # FILE: .gitignore ================================================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[codz] *$py.class # C extensions *.so # Distribution / packaging build/ dist/ *.egg-info/ *.egg # Unit test / coverage reports .coverage .coverage.* coverage.xml htmlcov/ .pytest_cache/ .hypothesis/ # Environments .env .envrc .venv env/ venv/ # Poetry # poetry.lock # uncomment for applications, keep commented for libraries # Type checkers .mypy_cache/ .dmypy.json .pyre/ .pytype/ # Tools .ruff_cache/ .ropeproject # mkdocs (only relevant if you kept mkdocs.yml + docs/) /site .cache/ # IDEs .idea/ .vscode/ # OS .DS_Store Thumbs.db ================================================================================ # FILE: LICENSE ================================================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================================================ # FILE: README.md ================================================================================ Part of MajorDom — the next-gen smart home # Creating a new MajorDom integration from this template Click **Use this template → Create a new repository** (name it `integration-`, e.g. `integration-hue`), then: **1. Rename the placeholders** (find & replace across the repo) - `integration-template` → your distribution name, by convention `majordom-` (hyphens): in `pyproject.toml` (`[project].name`) and `.github/workflows/release.yml` (`pypi-package-name`). - `integration_template` → your import name `majordom_` (underscores): the `integration_template/` directory, plus the `--cov=` and `packages` references in `pyproject.toml`. - Rename `ExampleController` and fill in `integration_template/controller.py` with real protocol logic. `tests/test_controller.py` is prefilled to fail until you do — work the **Progress** checklist below and tick items off as your CI goes green. - In `.github/workflows/test.yml`, delete the `template-selfcheck` job and the `if:` guard on the `test` job — they exist only to keep the *template* repo green and aren't wanted in a real integration. - Fill in the **About this integration** section below (it doubles as your PR summary — a reviewer reads the checklist to see what's actually implemented). **2. Install + pre-commit hook** ```sh pip install poetry poethepoet && poe install ``` **3. Create the `develop` branch** ```sh git checkout -b develop && git push origin develop ``` **4. GitHub repo settings** — same as any package repo built on the shared workflows: - **General** → enable **Allow auto-merge**; - **Branches** → protect `master` (require the `test / check` status, restrict push to `github-actions[bot]`) and `develop` (require `test / check`); - **Environments** → create `release` (deployment branch `develop` only, required reviewer). Then configure PyPI trusted publishing for your package (Owner = the GitHub user or org that owns **this** repo, Repository = this repo, Workflow `release.yml`, Environment `release`). The reusable CI/CD lives in [ParkerIndustries/workflows](https://github.com/ParkerIndustries/workflows). # integration-template A [MajorDom](https://majordom.io) integration — bridges the Example protocol into the MajorDom language. Built for the **MajorDom Hub**, but it doesn't need it: this is a standalone, standardized library for the Example protocol that you can use on its own (see **Run it standalone** below). Built on the [MajorDom Integration SDK](https://github.com/MajorDom-Systems/integration-sdk). The integration's entry point is a `Controller` (`integration_template/controller.py`) that the Hub — or the SDK's dev runner — instantiates and drives through its lifecycle: discovery → pairing → commands → teardown. - **Other protocols:** browse the [MajorDom integrations](https://github.com/orgs/MajorDom-Systems/repositories?q=integration-). - **Create your own:** start from the [integration template](https://github.com/MajorDom-Systems/integration-template). ## Documentation Full integration-author docs — the controller lifecycle, data models, storing data, discovery, and a worked example — live at **[docs.majordom.io](https://docs.majordom.io/device-integration)**. ## Development ```sh poetry install && poetry run poe install ``` | Task | Description | |------|-------------| | `poe check` | Full quality pipeline (ruff, ty, pytest, poetry build/check) | | `poe check --ci` | Same, plus `git diff --exit-code` | Work lands on `develop`; `master` is protected and released via **Actions → Release**. Tests drive the controller with the SDK's test doubles (`majordom_integration_sdk.testing`) against a virtual/simulated device — see `tests/`. ## Run it standalone (without the Hub) Your integration is a standalone library — import it into another app, or run **just this integration** interactively (discover, pair, control, and inspect devices from a prompt) with no Hub. Note here whatever prerequisites your protocol needs to run on its own (a broker, a radio, a local server, …). See **[Standalone mode](https://docs.majordom.io/device-integration/standalone)** for the interactive CLI, watch mode, and the programmatic API. ## About this integration - **Protocol / platform:** _e.g. Philips Hue (Zigbee via a bridge)_ - **Transport(s):** _wifi / ble / zigbee / …_ - **Supported devices:** _…_ - **Credentials needed to pair:** _none / code / secret / qr_ ### Required harness - **Hardware adapters:** _e.g. an 802.15.4 radio (SkyConnect / a Thread or Zigbee dongle), a USB serial gateway …_ — the Hub assigns OS device paths through `dependencies.hardware_interfaces` (e.g. `/dev/ttyACM0`). - **Third-party software services:** _e.g. an OpenThread Border Router (OTBR), a vendor bridge/hub, an MQTT broker, a matter-server instance …_ — what must be running and reachable. - **OS / permissions:** _e.g. Bluetooth access, host networking, mDNS/SSDP on the LAN …_ ### Protocol stack Every integration is two things stacked: the **MajorDom integration layer** — mapping the protocol to MajorDom's domain model — sitting on top of the **protocol stack** it bridges. The top layer is *always this repo*. How much of the stack *below* it is also this repo's code varies: some integrations only map an existing application-level protocol (a vendor library / the OS / the harness provides everything under them), while others implement the protocol themselves, down to raw UDP or even a custom radio. | Layer | Protocol | Implemented by | |-------|----------|----------------| | **MajorDom integration** | maps the protocol ↔ MajorDom domain model | **this repo, always** | | Application (7) | _Matter clusters / data model_ | this integration (via `chip` lib) | | Session (5) | _CASE / PASE secure session_ | library | | Transport (4) | _UDP_ | OS | | Network (3) | _IPv6 · 6LoWPAN_ | OS · OTBR (harness) | | Data link / Physical (1–2) | _Thread · IEEE 802.15.4_ | radio adapter (harness) | If your integration implements the protocol itself (no vendor library), more of the lower rows become **this integration** — a custom-radio integration can own everything from the application layer down to the physical. ### Progress Two checklists — this README is where you track them (tick items as you implement them and the matching test in `tests/` goes green). The docs explain the *why* behind each item: [Implementation Checklist](https://docs.majordom.io/device-integration) (gets it working) and [Quality Checklist](https://docs.majordom.io/device-integration/quality) (gets it releasable). **Implementation** — makes the integration functional: - [ ] Discovery services registered via `self.dependencies.zeroconf_discovery_service`, `ssdp_discovery_service`, and/or `ble_discovery_service` as appropriate; cancel closures saved and called in `stop` - [ ] Discovery service listeners fire when devices are found, and the controller calls `self.dependencies.output.controller_did_receive_discovery` - [ ] Discovery of devices already paired to the Hub on reconnect, e.g. after a reboot (`self.dependencies.output.controller_did_connect_device` is called) - [ ] `start_pairing_window` is implemented but only if the protocol requires an explicit scan (like zigbee) - [ ] Device pairing - [ ] Device schema is properly mapped: device info, parameter list, and each parameter's metadata are translated to MajorDom's domain model - [ ] Hub → Device control (`send_command` is implemented) - [ ] Device → Hub event subscription (`self.dependencies.output.controller_did_receive_events` is called on incoming events) - [ ] `identify` is implemented - [ ] `unpair` is implemented - [ ] `fetch` is implemented - [ ] Paired devices going offline/coming back online *while the Hub is running* (not just on reboot) — set `device.available` accordingly (report `controller_did_lose_device`), and clear/set `last_error` to match - [ ] Graceful shutdown in `stop`, cancelling any running tasks, discovery stopped, all connections closed - [ ] Tests pass against a virtual/simulated device (`tests/test_controller.py`) - [ ] README fully filled in: delete the template-setup section above, complete **About this integration**, **Required harness**, **Protocol stack**, and **Notes** with real content **Quality** — makes it reliable and maintainable (the bar for release): - [ ] **Recovers automatically** from connection loss / offline device / restarted backend — retried with backoff, no manual restart - [ ] **No exception escapes the controller** — every background task, subscription loop, and callback catches its own errors; nothing raised into `self.dependencies.output.*` - [ ] **Failures are surfaced, not raised** — logged once (no spam) and reflected on the device (`available` / `last_error`), cleared on recovery - [ ] **Re-authenticates automatically** when credentials expire/are rejected (if the protocol uses credentials) - [ ] **Fully asynchronous** — no blocking I/O on the event loop; heavy/blocking work runs off-loop - [ ] **Stable identity** — device and parameter UUIDs derived through the SDK helpers, identical across restarts/re-pairs - [ ] **End-to-end tests** drive pair → command → fetch → events → `unpair` against a virtual device (`majordom_integration_sdk.testing`) - [ ] **Failure paths tested** — offline device, transport error, rejected credentials degrade gracefully (no raise) - [ ] **Broad device coverage** where the protocol has many device/parameter types (a virtual-device catalogue in CI is ideal) - [ ] **Fully typed** (`ty`, no package-wide ignores) and **clean** (`poe check`) with no warnings - [ ] **Readable & structured** — conversion logic in a mapper, models separated, comments where intent isn't obvious - [ ] **Efficient** — subscriptions over polling; batch/chunk reads; no redundant work - [ ] **Diagnosable** — logging at the right levels to debug a device problem from logs alone - [ ] **Rich parameter metadata** — correct `visibility` per parameter and a sensible `main_parameter`, so the app presents a clean control-center action and a tidy parameter list ([Parameter UX](https://docs.majordom.io/device-integration/parameter-ux)) - [ ] **Owned** — a listed maintainer who keeps it working as the protocol/library evolve - [ ] _nice-to-have:_ localizable naming · firmware/software updates (where supported) · user-facing supported-device docs ### Notes _e.g. "Hobby project, maintained best-effort." · "IP transport works; BLE pairing is not implemented yet." · "Help wanted: reliable re-pair after a bridge reboot." · known quirks, firmware versions tested against, limitations._ ## License See [LICENSE](LICENSE). Your integration code is yours to license as you choose. For commercial licensing or partnership inquiries regarding MajorDom, contact us via [parker-industries.org/partnership](https://parker-industries.org/partnership). ================================================================================ # FILE: integration_template/__init__.py ================================================================================ """integration_template — rename this package to majordom_ (see README). Exposes the integration's Controller, the entry point the Hub (or the SDK's standalone dev runner) instantiates and drives. """ from integration_template.controller import ExampleController __all__ = ["ExampleController"] ================================================================================ # FILE: integration_template/controller.py ================================================================================ """A minimal MajorDom integration controller. This is a worked skeleton — replace the TODO bodies with real protocol calls. It shows the full lifecycle the Hub drives: discovery -> pairing -> commands -> teardown. See the full guide at https://docs.majordom.io/device-integration. A Controller bridges one external protocol/platform into the MajorDom language. The Hub instantiates it with injected `Dependencies` and calls the methods below; the controller reports back to the Hub through `dependencies.output` (a `ControllerOutput`). """ from __future__ import annotations from uuid import UUID from majordom_integration_sdk.controller import AbstractController from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import Device, Discovery, Parameter, ProvidedCredentials # Output methods to call (see the docs): # async def controller_did_receive_discovery(self, controller: AbstractController, discovery: Discovery): ... # async def controller_did_update_discovery(self, controller: AbstractController, discovery: Discovery): ... # async def controller_did_lose_discovery(self, controller: AbstractController, discovery_id: UUID): ... # async def controller_did_connect_device(self, controller: AbstractController, device_id: UUID): ... # async def controller_did_lose_device(self, controller: AbstractController, device_id: UUID): ... # async def controller_did_receive_events(self, controller: AbstractController, events: Iterable[Event]): ... class ExampleController(AbstractController[Device, Parameter]): """Bridges the Example protocol into MajorDom.""" def __init__(self, dependencies: AbstractController.Dependencies): super().__init__(dependencies) self._discoveries: dict[UUID, Discovery] = {} name = "Example" @property def discoveries(self) -> dict[UUID, Discovery]: # Return the cached snapshot only — never scan here. return self._discoveries # Lifecycle ------------------------------------------------------------- async def start(self) -> None: # Register discovery services, subscribe to protocol events, and reconcile the # state of already-paired devices here. # e.g. self.dependencies.zeroconf_discovery_service.add_listener("_example._tcp.local.", self) ... async def stop(self) -> None: # Cancel tasks and release every held resource. ... # Hub -> device --------------------------------------------------------- async def pair_device(self, discovery: Discovery, credentials: ProvidedCredentials | None) -> None: # Establish a session with the device, then report success to the Hub: # await self.dependencies.output.controller_did_connect_device(self, self.device_uuid(...)) raise NotImplementedError async def unpair(self, device: Device) -> None: raise NotImplementedError async def identify(self, device: Device) -> None: # Ask the device to blink/beep so the user can locate it. raise NotImplementedError async def fetch(self, device: Device) -> None: # Refresh the device and its parameters, reporting changes via # self.dependencies.output.controller_did_receive_events(self, [...]). raise NotImplementedError async def send_command(self, command: DeviceCommand, device: Device, parameter: Parameter) -> None: # Translate the MajorDom command into a protocol-level write. raise NotImplementedError ================================================================================ # FILE: pyproject.toml ================================================================================ # Rename `integration-template` (PyPI/distribution name, hyphens) and the # `integration_template/` package directory (import name, underscores) to your own — by # convention `majordom-` / `majordom_` (e.g. majordom-homekit / # majordom_homekit). Keep them matching so poetry-core auto-detects the package, and update # `pypi-package-name` in the release stub + `--cov=` below to match. [project] name = "integration-template" version = "0.1.0" description = "A MajorDom integration." authors = [{ name = "Mark Parker", email = "mark@parker-programs.com" }] readme = "README.md" # The template scaffold is Apache-2.0. Relicense your integration as you see fit — note # that linking a copyleft (GPL/AGPL) protocol library may constrain your choice. license = "Apache-2.0" license-files = ["LICENSE"] keywords = ["majordom", "smart-home", "home-automation", "iot", "integration", "template", "scaffold"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Home Automation", "Programming Language :: Python :: 3", ] requires-python = ">=3.12" dependencies = [ "majordom-integration-sdk (>=0.1.5,<1.0)", ] [project.urls] Homepage = "https://majordom.io" Documentation = "https://docs.majordom.io/device-integration" Repository = "https://github.com/MajorDom-Systems/integration-template" [dependency-groups] dev = [ "poethepoet (>=0.36.0,<1.0.0)", "ty", # type checker; swap for mypy/pyright by editing the `check` task below "ruff", "pip-audit", # dependency vuln scan — gates release (not everyday CI); run locally with `poetry run pip-audit` "pytest", "pytest-asyncio", "pytest-cov", "pytest-timeout", "pytest-repeat", "pytest-benchmark", "pytest-profiling", "pytest-resource-usage", "coverage", "pympler", # object memory introspection, leak hunting "psutil", # process/system resource usage "faker", # realistic fake data for tests ] [build-system] requires = ["poetry-core>=2.0.0,<3.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] requires-poetry = ">=2.0" packages = [{ include = "integration_template" }] [tool.pytest.ini_options] asyncio_mode = "auto" pythonpath = ["."] filterwarnings = ["once"] [tool.coverage.run] omit = ["tests/*"] [tool.ruff] line-length = 120 indent-width = 4 [tool.ruff.lint] select = [ "E", # pycodestyle "F", # pyflakes "UP", # pyupgrade "B", # flake8-bugbear "SIM", # flake8-simplify "I", # isort ] fixable = ["ALL"] [tool.ruff.format] quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "tests/*" = ["E402"] [tool.poe.tasks.install] shell = """ poetry install echo '#!/bin/sh\npoetry run poe check' > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit echo "Pre-commit hook installed." """ [tool.poe.tasks.check] shell = """ code=0 echo "\nRunning ruff lint:" poetry run ruff check --fix || code=1 echo "\nRunning ruff format:" poetry run ruff format || code=1 echo "\nRunning ty:" poetry run ty check || code=1 echo "\nRunning pytest:" poetry run pytest --cov=integration_template --cov-report=xml || code=1 echo "\nRunning poetry build:" poetry build || code=1 echo "\nRunning poetry check:" poetry check || code=1 ${ci:+git diff --exit-code} exit $code """ args = [{ name = "ci", type = "boolean" }] ================================================================================ # FILE: tests/conftest.py ================================================================================ """Shared pytest fixtures for the whole suite live here. conftest.py is auto-discovered by pytest — no import needed. The fixtures wire the integration's Controller with the SDK's test doubles (a recording `ControllerOutput`, an in-memory device repository, and fake discovery services) and build sample `Discovery`/`DeviceState` objects, so tests can drive the controller exactly as the Hub would — without a running Hub. **Device persistence is the Hub's core business logic, not the integration's.** The Hub creates and stores device rows (name/room mapping, id assignment, the provisional→final id reconciliation on pairing); an integration only reads through the injected repository and writes parameter *state*. These fixtures therefore seed the repository the way the Hub would, so the controller sees realistic state — the tests never make the integration persist a device itself. """ from uuid import uuid4 import pytest from majordom_integration_sdk.controller import AbstractController from majordom_integration_sdk.schemas.device import CredentialsType, Device, DeviceState, Discovery from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterState, ParameterVisibility, ) from majordom_integration_sdk.testing import build_test_dependencies from integration_template import ExampleController INTEGRATION = "example" @pytest.fixture def deps() -> AbstractController.Dependencies: """SDK-provided test dependencies (recording output + in-memory repo + fake discovery).""" return build_test_dependencies(integration=INTEGRATION) @pytest.fixture def controller(deps: AbstractController.Dependencies) -> ExampleController: return ExampleController(deps) # A virtual / simulated device — a fake endpoint that speaks your protocol in-process (no # hardware, no network) so tests are deterministic and can assert what actually reached the # device. Stand one up here and have the controller talk to it (e.g. via a base URL / mock # transport injected through the controller). Tests then assert on both the controller's # reports (deps.output) and this object's observed state. # # @pytest.fixture # def virtual_device(): # dev = VirtualExampleDevice() # your in-process fake # dev.start() # yield dev # dev.stop() async def _seed(deps: AbstractController.Dependencies, device: DeviceState) -> None: """Persist a device the way the Hub would, before handing control to the integration.""" async with deps.make_device_repository() as repo: await repo.save(device) @pytest.fixture def discovery() -> Discovery: """A sample discovered-but-unpaired device (the controller surfaced this).""" return Discovery( id=uuid4(), integration=INTEGRATION, expected_credentials_options=[CredentialsType.none], transport="wifi", device_manufacturer="ACME", device_name="Example Lamp", device_category=None, device_icon=None, ) @pytest.fixture async def provisional_device(deps: AbstractController.Dependencies, discovery: Discovery) -> DeviceState: """The device as it exists when the Hub calls `pair_device`. Before pairing, the Hub has already created the row from the user's input: name and room mapped, and its id set to the discovery's (still provisional) id — but no parameters yet; the controller discovers/maps those while pairing. After pairing the controller reports the real device id and the Hub reconciles the row. We seed the repository to match. """ device = DeviceState( id=discovery.id, # provisional id == discovery id, until pairing assigns the real one name="Living Room Lamp", # mapped by the Hub from the user's input room_id=uuid4(), transport=discovery.transport, integration=INTEGRATION, manufacturer=discovery.device_manufacturer, parameters=[], ) await _seed(deps, device) return device @pytest.fixture async def device_state(deps: AbstractController.Dependencies) -> DeviceState: """An already-paired device with one on/off parameter, as the Hub *stores* it (the full state, with parameters). Seeded into the repository.""" power = ParameterState( id=uuid4(), name="Power", data_type=ParameterDataType.bool, role=ParameterRole.control, visibility=ParameterVisibility.user, integration_data=None, value=True, ) state = DeviceState( id=uuid4(), name="Living Room Lamp", room_id=uuid4(), transport="wifi", integration=INTEGRATION, manufacturer="ACME", parameters=[power], ) await _seed(deps, state) return state @pytest.fixture def device(device_state: DeviceState) -> Device: """The device as the Hub *passes* it to `fetch`/`identify`/`unpair`/`send_command` — a `Device` (info + integration_data), without the parameter list.""" return Device.model_validate(device_state.model_dump()) @pytest.fixture def parameter(device_state: DeviceState) -> ParameterState: """The target parameter for `send_command`, paired with `device`.""" return device_state.parameters[0] ================================================================================ # FILE: tests/test_controller.py ================================================================================ """Tests that drive the controller through its lifecycle. These are **prefilled to fail** against the unimplemented skeleton: every test below calls a method that still raises `NotImplementedError`, so CI stays red until you implement the controller. Run these against a **virtual / simulated device** — a fake endpoint that speaks your protocol in-process (no real hardware, no network), so CI is deterministic. Add a fixture for it in `conftest.py` and have the controller talk to it. Each test should then assert on **both sides**: what the controller reported back to the Hub (via `deps.output`) *and* what actually landed on the device (the virtual device observed the command / changed state) — don't just call the method and assume it worked. Persistence is the Hub's job (see `conftest.py`): the fixtures seed the repository the way the Hub would, so assert on the controller's protocol behaviour and reports — not that the integration created a device row. (The template's own CI excludes this file so the template repo stays green — see `.github/workflows/test.yml`. Your integration repo runs it in full, and it's red until you implement the controller.) """ from majordom_integration_sdk.controller import AbstractController from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import Device, Discovery from majordom_integration_sdk.schemas.parameter import ParameterState from integration_template import ExampleController async def test_pairs_a_discovered_device( controller: ExampleController, deps: AbstractController.Dependencies, discovery: Discovery, provisional_device: Device, # creates a device with discovery.id and saves it to the db ) -> None: # The Hub has already stored `provisional_device` (id == discovery.id) before this call. await controller.pair_device(discovery, credentials=None) # TODO: verify pairing actually completed — the controller established the session and # reported back (it does not persist the device itself): # - Hub side: `discovery.id` is in `deps.output.connected_devices`. # - Device side: the virtual device accepted the credentials / opened a session. # - Parameters: if you map parameters during pairing, assert their initial states were # written via the repository (`repo.save_parameter_state`). async def test_fetches_state( controller: ExampleController, deps: AbstractController.Dependencies, device: Device, ) -> None: await controller.fetch(device) # TODO: verify the refresh reached the device and propagated back: # - Set a known state on the virtual device first, then assert `deps.output.events` # (or the repository's parameter states) now reflect exactly that state — not stale # or default values. async def test_sends_a_command(controller: ExampleController, device: Device, parameter: ParameterState) -> None: command = DeviceCommand(device_id=device.id, parameter_id=parameter.id, value=False) await controller.send_command(command, device, parameter) # TODO: verify the command actually applied on the device, not just that the call # returned: assert the virtual device received this exact write and its state changed # to `value` (read it back). A no-op that silently succeeds must fail this test. async def test_identifies(controller: ExampleController, device: Device) -> None: await controller.identify(device) # TODO: assert the virtual device recorded an identify request (e.g. its identify counter # incremented / the identify command was received). async def test_unpairs(controller: ExampleController, device: Device) -> None: await controller.unpair(device) # TODO: verify removal took effect: # - Device side: the virtual device saw the session torn down / was de-registered. # - Controller: the device is gone — no more connections or commands should be accepted. ================================================================================ # FILE: tests/test_smoke.py ================================================================================ """Basic tests that pass out of the box — they don't depend on protocol logic. Kept separate from ``test_controller.py`` so the template repo's own CI (which excludes the prefilled, expected-to-fail controller suite) still has tests to run and stays green. """ from integration_template import ExampleController async def test_starts_and_stops(controller: ExampleController) -> None: await controller.start() await controller.stop() async def test_name_and_slug(controller: ExampleController) -> None: assert controller.name == "Example" assert controller.name_slug == "example" # integration-matter — full source # repo: https://github.com/MajorDom-Systems/integration-matter branch: master commit: e2f33fb144d62503d244bc7fa35bbc2e19ab4882 # generated: 2026-11-16 — AUTO-GENERATED, do not edit by hand ## File tree .gitignore LICENSE README.md docker/Dockerfile.test docker-compose.matter-tests.mac.yml docker-compose.matter-tests.yml majordom_matter/__init__.py majordom_matter/ble_delegate.py majordom_matter/client.py majordom_matter/config.py majordom_matter/controller.py majordom_matter/exceptions.py majordom_matter/mapper.py majordom_matter/matter_spec.py majordom_matter/matter_spec_ha.py majordom_matter/model.py majordom_matter/readme.md majordom_matter/testing/__init__.py majordom_matter/testing/fixtures/on_off_light_node.json pyproject.toml scripts/check_matter_ha_drift.py scripts/fetch_mvd.sh scripts/fetch_paa_certs.py scripts/harvest_matter_ha.py scripts/param_ux_audit.py tests/conftest.py tests/test_ble_delegate.py tests/test_ble_modes.py tests/test_client.py tests/test_command_parameters.py tests/test_config.py tests/test_controller.py tests/test_controller_stub.py tests/test_param_ux.py tests/test_smoke.py tests/test_state_toggles.py ================================================================================ # FILE: .gitignore ================================================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[codz] *$py.class # C extensions *.so # Distribution / packaging build/ dist/ *.egg-info/ *.egg # Unit test / coverage reports .coverage .coverage.* coverage.xml htmlcov/ .pytest_cache/ .hypothesis/ # Environments .env .envrc .venv env/ venv/ # Poetry # poetry.lock # uncomment for applications, keep commented for libraries # Type checkers .mypy_cache/ .dmypy.json .pyre/ .pytype/ # Tools .ruff_cache/ .ropeproject # mkdocs (only relevant if you kept mkdocs.yml + docs/) /site .cache/ # IDEs .idea/ .vscode/ # OS .DS_Store Thumbs.db # Matter Virtual Device (MVD) `chef` binaries + PAA certificates — NOT committed (they were # 77MB of opaque blobs in the Hub). CI fetches them as a versioned artifact and the test # jobs download that; see .github/workflows/mvd-artifact.yml (plan §3.5). tests/mvd/ tests/mvd-artifact/ # matter-server storage + PAA certs (fetched by CI, §3.5) matter_data/ paa/ # fetch_paa_certs.py / mvd-artifact.yml default cert output dir # The dev runner's settings and keys .majordom-dev/ ================================================================================ # FILE: LICENSE ================================================================================ # PolyForm Noncommercial License 1.0.0 ## Acceptance In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses. ## Copyright License The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license). ## Distribution License The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license). ## Notices You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example: > Required Notice: Copyright Yoyodyne, Inc. (http://example.com) ## Changes and New Works License The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose. ## Patent License The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software. ## Noncommercial Purposes Any noncommercial purpose is a permitted purpose. ## Personal Uses Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose. ## Noncommercial Organizations Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding. ## Fair Use You may have "fair use" rights for the software under the law. These terms do not limit them. ## No Other Rights These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses. ## Patent Defense If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company. ## Violations The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately. ## No Liability ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*** ## Definitions The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms. **You** refers to the individual or entity agreeing to these terms. **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. **Your licenses** are all the licenses granted to you for the software under these terms. **Use** means anything you do with the software requiring one of your licenses. ================================================================================ # FILE: README.md ================================================================================ Part of MajorDom — the next-gen smart home # integration-matter A [MajorDom](https://majordom.io) integration — bridges **Matter** (CSA Connectivity Standard) devices into the MajorDom language. Built for the **MajorDom Hub**, but it doesn't need it: this is a standalone, standardized library for Matter that you can use on its own (see **Run it standalone** below). Built on the [MajorDom Integration SDK](https://github.com/MajorDom-Systems/integration-sdk). The entry point is `MatterController` (`majordom_matter/controller.py`), which the Hub — or the SDK's dev runner — instantiates and drives through its lifecycle: discovery → pairing → commands → teardown. - **Other protocols:** browse the [MajorDom integrations](https://github.com/orgs/MajorDom-Systems/repositories?q=integration-). - **Create your own:** start from the [integration template](https://github.com/MajorDom-Systems/integration-template). ## Documentation Full integration-author docs — the controller lifecycle, data models, storing data, discovery, and a worked example — live at **[docs.majordom.io](https://docs.majordom.io/device-integration)**. ## Development ```sh poetry install && poetry run poe install ``` | Task | Description | |------|-------------| | `poe check` | Full quality pipeline (ruff, ty, pytest, poetry build/check) | | `poe check --ci` | Same, plus `git diff --exit-code` | Work lands on `develop`; `master` is protected and released via **Actions → Release**. The default suite drives the controller against a canned node with the SDK's test doubles — no matter-server, no docker (`tests/test_controller_stub.py`). The exhaustive real-device coverage commissions Google's Matter Virtual Devices in a dockerized matter-server (`tests/test_controller.py`, see `docker-compose.matter-tests.yml`); the MVD binaries + PAA certs are fetched, not committed. ## Run it standalone (without the Hub) `majordom-matter` is a standalone library — import it into your own app, or run **just this integration** interactively (discover, pair, control, and inspect devices from a prompt) with no Hub. It needs a running [python-matter-server](https://github.com/home-assistant-libs/python-matter-server) reachable over its WebSocket (`MATTER_SERVER_URL`, default `ws://localhost:5580/ws`); Thread devices also need an OpenThread Border Router. See **[Standalone mode](https://docs.majordom.io/device-integration/standalone)** for the interactive CLI, watch mode, and the programmatic API. ## About this integration - **Protocol / platform:** Matter (Connectivity Standards Alliance) via `python-matter-server` + `chip`. - **Transport(s):** IP over Thread / Wi-Fi / Ethernet; BLE for commissioning. - **Supported devices:** any Matter-certified device — lights, plugs, switches, sensors, locks, thermostats, covers, fans, appliances (verified against 30 Matter Virtual Device types). - **Credentials needed to pair:** `code` (manual pairing code) or `qr`. ### Required harness - **Hardware adapters:** an 802.15.4 radio (e.g. a SkyConnect / Thread dongle) for Thread devices — driven by matter-server / the OTBR, not this package directly. - **Third-party software services:** a **matter-server** instance reachable over WebSocket (`MATTER_SERVER_URL`), and an **OpenThread Border Router (OTBR)** for Thread devices. - **OS / permissions:** BLE access for commissioning; mDNS on the LAN for on-network discovery. ### Protocol stack (OSI) | OSI layer | Protocol | Implemented by | |-----------|----------|----------------| | Application (7) | Matter clusters / data model | **this integration** (via `chip` lib) | | Session (5) | CASE / PASE secure session | library (matter-server) | | Transport (4) | UDP | OS | | Network (3) | IPv6 · 6LoWPAN | OS · OTBR (harness) | | Data link / Physical (1–2) | Thread · IEEE 802.15.4 (or Wi-Fi / Ethernet) | radio adapter (harness) | ### Progress - [x] Discovery services registered (mDNS on-network via matter-server; BLE for commissionable devices); cancel closures called in `stop` - [x] Discovery listeners fire and call `controller_did_receive_discovery` - [x] Re-discovery of already-paired devices on reconnect (`controller_did_connect_device`) - [x] Device pairing (BLE→Thread and on-network commissioning) - [x] Device schema mapped: device info, parameter list, per-parameter metadata → MajorDom's domain model - [x] Hub → Device control (`send_command`) - [x] Device → Hub event subscription (`controller_did_receive_events`) - [x] `identify` - [x] `unpair` - [x] `fetch` - [x] Availability tracking while running (`controller_did_lose_device` / `last_error`) - [x] Graceful shutdown in `stop` - [x] Tests pass against virtual/simulated devices (stub + dockerized MVD suite) - [x] Owned — maintained by Parker Industries ### Parameter metadata sources & priority Every parameter's UX metadata is resolved from several sources. See also the [parameter-ux recipe](https://docs.majordom.io/device-integration/parameter-ux). **Visibility / role / unit** — resolved by `classify_attribute()` in `matter_spec.py` (first match wins): | # | Source | What it is | |---|--------|-----------| | — | system cluster / sensitive (`Aliro*` crypto) | forced **system** (safety, top priority) | | 1 | `OUR_ATTRIBUTE_UX` (`USER_READINGS`, `EVERYDAY_CONTROL_ATTRIBUTES`) | our hand curation | | 2 | `MATTER_HA_ATTRIBUTE_UX` | judgment **harvested** from Home Assistant's Matter discovery (`scripts/harvest_matter_ha.py`, AST-parsed, vendored — no `homeassistant` dep) | | 3 | **fallback policy** | writable → setting, else system; **logs a warning** on uncurated attrs. Flip `_FALLBACK_HIDE_UNCURATED` once coverage is validated. | Matter has no runtime quirk layer, so (unlike zigbee) there is no v2-quirk tier. The Matter Data Model (`chip`) already supplies names/types/bounds; the harvest adds only the `entity_category` (user/config/diagnostic) judgment the spec doesn't dictate. **Bounds** come from the device's own limit attributes (runtime) > spec tables > wire-type range — see `resolve_runtime_bounds()` / `METADATA_SOURCES`. **Drift.** `scripts/check_matter_ha_drift.py` re-runs the AST harvest against home-assistant/core and diffs vs the vendored artifact via the SDK's `diff_specs`, tiering ADD / REMOVE / **RECLASSIFY**. ### Notes The MVD `chef` binaries are x86-64 Linux only, so the real-device suite runs in an amd64 container (Rosetta on Apple Silicon). A monthly canary fetches the *latest* upstream MVD release and fails if it ships something unsupported — the signal to add support. The same drift machinery (the SDK's `diff_specs`) now also watches the harvested HA-Matter judgment. ## License See [LICENSE](LICENSE). For commercial licensing or partnership inquiries regarding MajorDom, contact us via [parker-industries.org/partnership](https://parker-industries.org/partnership). ================================================================================ # FILE: docker/Dockerfile.test ================================================================================ # Runs the Matter integration's virtual-device suite against real MVD `chef` binaries. # Build context is the repo root; the SDK is a published PyPI dependency # (majordom-integration-sdk), resolved by `poetry install` — nothing is copied from outside the repo. FROM python:3.13-slim WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential gcc python3-dev git \ avahi-daemon avahi-utils libavahi-client3 libavahi-common3 \ dbus libdbus-1-3 libdbus-1-dev libglib2.0-0 libglib2.0-dev \ && rm -rf /var/lib/apt/lists/* RUN sed -i 's/#enable-dbus=yes/enable-dbus=no/g; s/use-ipv6=no/use-ipv6=yes/g; s/#enable-chroot=yes/enable-chroot=no/g' \ /etc/avahi/avahi-daemon.conf RUN pip install poetry && poetry config virtualenvs.create false COPY pyproject.toml poetry.lock /app/ RUN poetry install --no-root COPY . /app/ RUN pip install -e . --no-deps CMD avahi-daemon --daemonize && sleep 2 && \ chmod +x tests/mvd/* && \ poetry run pytest tests/ -v ================================================================================ # FILE: docker-compose.matter-tests.mac.yml ================================================================================ # macOS (Apple-silicon) override: the MVD binaries are Linux x86-64, so pin the test # container to linux/amd64 and let Docker Desktop's Rosetta run them. # One-time: Docker Desktop -> Settings -> General -> "Use Rosetta for x86/amd64 emulation". # docker compose -f docker-compose.matter-tests.yml -f docker-compose.matter-tests.mac.yml \ # up --build --exit-code-from matter-integration-tests # matter-server runs no x86-64 binary (just mDNS/network), so it stays native arm64. services: matter-integration-tests: platform: linux/amd64 environment: - MATTER_DISCOVERY_WARMUP_S=180 ================================================================================ # FILE: docker-compose.matter-tests.yml ================================================================================ # Matter integration test stack: python-matter-server + a container that runs the # integration's virtual-device suite against real MVD `chef` binaries. # # Run: docker compose -f docker-compose.matter-tests.yml up --build \ # --exit-code-from matter-integration-tests # On Apple Silicon add the mac override (Rosetta): -f docker-compose.matter-tests.mac.yml services: matter-server: image: ghcr.io/matter-js/python-matter-server:stable restart: unless-stopped privileged: true sysctls: - net.ipv6.conf.all.disable_ipv6=0 - net.ipv6.conf.all.forwarding=1 volumes: - ./matter_data:/data command: --storage-path /data --paa-root-cert-dir /data/credentials --primary-interface eth0 networks: [matter-net] matter-integration-tests: build: context: . # repo root; the SDK is a published PyPI dependency dockerfile: docker/Dockerfile.test privileged: true depends_on: [matter-server] environment: - MATTER_SERVER_URL=ws://matter-server:5580 # the base URL: the suite adds /ws - MATTER_DISCOVERY_TIMEOUT_S=12 - MATTER_INTEGRATION_TESTS=1 sysctls: - net.ipv6.conf.all.disable_ipv6=0 networks: [matter-net] networks: matter-net: driver: bridge enable_ipv6: true ipam: config: - subnet: 172.16.238.0/24 - subnet: fd00:db8:1::/64 ================================================================================ # FILE: majordom_matter/__init__.py ================================================================================ """Matter integration for MajorDom. Bridges Matter devices into the MajorDom language via matterjs-server, through the python-matter-server client. `peripherals` is what the Hub (or the SDK's standalone dev runner) runs: matterjs-server and the `MatterController` that drives it. """ from majordom_integration_sdk import Peripheral, Platform from majordom_matter.config import matterjs_server from majordom_matter.controller import MatterController def peripherals(platform: Platform) -> list[Peripheral]: return [matterjs_server(), MatterController(platform)] __all__ = ["MatterController", "peripherals"] ================================================================================ # FILE: majordom_matter/ble_delegate.py ================================================================================ """Lends the hub's Bluetooth to matterjs-server, so commissioning reaches devices through every radio the Bluetooth router (``ble/router``) hears with — local adapters and ESPHome nodes alike. matterjs-server (``BLE_PROXY=true``) takes a Bluetooth client on ``/ble`` and drives it with the BLE proxy protocol v1: https://github.com/matter-js/matterjs-server/blob/main/docs/ble-proxy-protocol.md """ import asyncio import base64 import contextlib import json import logging import struct from collections.abc import Callable, Generator from dataclasses import dataclass, field from uuid import UUID from aiohttp import ClientSession, ClientWebSocketResponse, WSMsgType from majordom_integration_sdk.capabilities import BLEConnection, BLEDiscoveryInfo, BLEMatcher, BLERouter logger = logging.getLogger(__name__) _FRAME = struct.Struct(">BH") # opcode, connection handle; the payload follows _WRITE, _NOTIFICATION = 0x01, 0x02 _RECONNECT_SEC, _RECONNECT_MAX_SEC = 1, 10 # the first retry, then doubling up to the most class _Failure(Exception): def __init__(self, error: str, message: str = ""): super().__init__(message or error) self.error = error @dataclass class _Peripheral: connection: BLEConnection lease: contextlib.AsyncExitStack # holds the Bluetooth source leased for this connection characteristics: dict[str, int] = field(default_factory=dict) # uuid -> handle write_handle: int | None = None # where binary frames go: the characteristic last written def _uuid(text: str) -> UUID: """Short (``fff6``), 32-bit or full UUID text as a UUID.""" return UUID(text.rjust(8, "0") + "-0000-1000-8000-00805f9b34fb" if len(text) <= 8 else text) def _b64(data: bytes) -> str: return base64.b64encode(data).decode() @contextlib.contextmanager def _gatt(error: str) -> Generator[None]: """Answers a failing GATT operation as ``error``, however its source failed (bleak, aioesphomeapi, a lost link).""" try: yield except Exception as e: raise _Failure(error, str(e)) from e class MatterServerBLEDelegate: """Connects to matterjs-server's ``/ble`` endpoint and performs its BLE operations through the Bluetooth router. It reconnects whenever matterjs-server goes away. Run one per matterjs-server. """ def __init__(self, url: str, ble: BLERouter, session: ClientSession): self._url, self._ble, self._session = url, ble, session self._ws: ClientWebSocketResponse | None = None self._peripherals: dict[int, _Peripheral] = {} self._last_handle = 0 self._stop_scanning: Callable[[], None] | None = None self._tasks: set[asyncio.Task] = set() async def run(self): """Serves matterjs-server until cancelled, reconnecting whenever it goes away.""" delay = _RECONNECT_SEC while True: try: async with self._session.ws_connect(self._url) as ws: self._ws = ws if await self._serve(ws): delay = _RECONNECT_SEC reason = "closed" except Exception as e: # whatever broke, matterjs-server must get the hub's Bluetooth back reason = f"failed: {e!r}" finally: await self._release() log = logger.warning if delay == _RECONNECT_SEC else logger.debug # once per outage, not every retry log(f"matterjs-server's /ble endpoint {self._url} {reason}, reconnecting in {delay} s") await asyncio.sleep(delay) delay = min(delay * 2, _RECONNECT_MAX_SEC) async def _serve(self, ws: ClientWebSocketResponse) -> bool: """Serves one connection until it closes; False when matterjs-server refuses it.""" await ws.send_json({"type": "hello", "version": 1}) if error := (await ws.receive_json(timeout=10)).get("error"): logger.warning(f"matterjs-server refused the hub's Bluetooth: {error}") return False logger.info(f"Lending Bluetooth to matterjs-server at {self._url}") async for message in ws: if message.type == WSMsgType.TEXT: self._spawn(self._answer(ws, json.loads(message.data))) elif message.type == WSMsgType.BINARY: await self._forward(message.data) # in order: these are segments of one stream return True async def _answer(self, ws: ClientWebSocketResponse, command: dict): try: handler = getattr(self, f"_{command['command']}", None) if not handler: raise _Failure("internal_error", f"Unknown command {command['command']}") result = await handler(**command.get("args", {})) reply = {"id": command["id"], "success": True, "result": result or {}} except Exception as e: error = e.error if isinstance(e, _Failure) else "internal_error" reply = {"id": command["id"], "success": False, "error": error, "message": str(e)} await ws.send_json(reply) async def _forward(self, frame: bytes): opcode, handle = _FRAME.unpack_from(frame) peripheral = self._peripherals.get(handle) if opcode == _WRITE and peripheral and peripheral.write_handle is not None: try: await peripheral.connection.write( peripheral.write_handle, frame[_FRAME.size :], is_response_needed=True ) except Exception as e: # a BTP segment is no request to fail, and BTP can't skip one: end the connection logger.warning(f"Bluetooth write on connection {handle} failed, disconnecting: {e!r}") self._lost(handle) self._spawn(self._close(peripheral)) def _peripheral(self, connection_handle: int) -> _Peripheral: if peripheral := self._peripherals.get(connection_handle): return peripheral raise _Failure("not_connected") def _characteristic(self, connection_handle: int, uuid: str) -> tuple[_Peripheral, int]: peripheral = self._peripheral(connection_handle) if (handle := peripheral.characteristics.get(uuid.lower())) is None: raise _Failure("characteristic_not_found", uuid) return peripheral, handle # Commands async def _start_scan(self, service_uuids: list[str] | None = None, allow_duplicates: bool = False): await self._stop_scan() self._stop_scanning = self._ble.register( self, [BLEMatcher(_uuid(u)) for u in service_uuids or ()] or [BLEMatcher()] ) async def _stop_scan(self): if self._stop_scanning: self._stop_scanning() self._stop_scanning = None async def _connect(self, address: str, timeout: int = 30_000): self._last_handle = handle = self._last_handle % 0xFFFF + 1 async with contextlib.AsyncExitStack() as stack: # closed here on failure, kept for the connection otherwise try: lease = await stack.enter_async_context( self._ble.exclusive(address, owner="matter", timeout=timeout / 1000) ) connection = await asyncio.wait_for(lease.connect(lambda: self._lost(handle)), timeout / 1000) except TimeoutError as e: raise _Failure("timeout") from e except ConnectionError as e: # incl. BLEBusyError: every source that hears the device is leased raise _Failure("connection_failed", str(e)) from e self._peripherals[handle] = _Peripheral(connection, stack.pop_all()) return {"connection_handle": handle, "mtu": connection.mtu} async def _disconnect(self, connection_handle: int): peripheral = self._peripheral(connection_handle) del self._peripherals[connection_handle] await self._close(peripheral) async def _discover_services(self, connection_handle: int): peripheral = self._peripheral(connection_handle) with _gatt("discovery_failed"): services = await peripheral.connection.services() return {"services": [{"uuid": s.uuid} for s in services]} async def _discover_characteristics(self, connection_handle: int, service_uuid: str): peripheral = self._peripheral(connection_handle) with _gatt("discovery_failed"): services = await peripheral.connection.services() service = next((s for s in services if _uuid(s.uuid) == _uuid(service_uuid)), None) if not service: raise _Failure("service_not_found", service_uuid) peripheral.characteristics |= {c.uuid.lower(): c.handle for c in service.characteristics} return { "characteristics": [{"uuid": c.uuid, "properties": list(c.properties)} for c in service.characteristics] } async def _read_characteristic(self, connection_handle: int, characteristic_uuid: str): peripheral, handle = self._characteristic(connection_handle, characteristic_uuid) with _gatt("read_failed"): return {"value": _b64(await peripheral.connection.read(handle))} async def _write_characteristic( self, connection_handle: int, characteristic_uuid: str, value: str, response: bool = False ): peripheral, handle = self._characteristic(connection_handle, characteristic_uuid) peripheral.write_handle = handle with _gatt("write_failed"): await peripheral.connection.write(handle, base64.b64decode(value), response) async def _subscribe_characteristic(self, connection_handle: int, characteristic_uuid: str): peripheral, handle = self._characteristic(connection_handle, characteristic_uuid) with _gatt("subscribe_failed"): await peripheral.connection.start_notify(handle, lambda data: self._notify(connection_handle, data)) async def _write_and_subscribe( self, connection_handle: int, write_uuid: str, write_value: str, subscribe_uuid: str, write_response: bool = True, ): # the write must complete before notifications are on: the device answers the write by notifying await self._write_characteristic(connection_handle, write_uuid, write_value, write_response) await self._subscribe_characteristic(connection_handle, subscribe_uuid) async def _unsubscribe_characteristic(self, connection_handle: int, characteristic_uuid: str): peripheral, handle = self._characteristic(connection_handle, characteristic_uuid) await peripheral.connection.stop_notify(handle) async def _request_mtu(self, connection_handle: int, mtu: int): return {"mtu": self._peripheral(connection_handle).connection.mtu} # Events async def ble_did_discover_device(self, ble: BLERouter, info: BLEDiscoveryInfo): adv = info.advertisement await self._send_event("device_discovered", { "address": info.device.address, "connectable": True, # bleak doesn't say; matterjs-server ignores devices that aren't "name": adv.local_name, "rssi": adv.rssi, "service_uuids": adv.service_uuids, "service_data": {uuid: _b64(data) for uuid, data in adv.service_data.items()}, "manufacturer_data": {str(company): _b64(data) for company, data in adv.manufacturer_data.items()}, }) # fmt: skip ble_did_update_device = ble_did_discover_device async def ble_did_remove_device(self, ble: BLERouter, info: BLEDiscoveryInfo): ... def _notify(self, connection_handle: int, data: bytes): if self._ws and not self._ws.closed: self._spawn(self._ws.send_bytes(_FRAME.pack(_NOTIFICATION, connection_handle) + data)) def _lost(self, connection_handle: int): if peripheral := self._peripherals.pop(connection_handle, None): self._spawn(peripheral.lease.aclose()) self._spawn(self._send_event("disconnected", {"connection_handle": connection_handle})) async def _send_event(self, event: str, data: dict): if self._ws and not self._ws.closed: await self._ws.send_json({"event": event, "data": data}) async def _release(self): for task in self._tasks: task.cancel() await self._stop_scan() peripherals, self._peripherals = list(self._peripherals.values()), {} await asyncio.gather(*(self._close(p) for p in peripherals), return_exceptions=True) @staticmethod async def _close(peripheral: _Peripheral): """Ends the connection and gives its Bluetooth source back, whatever the disconnect does.""" try: await peripheral.connection.disconnect() finally: await peripheral.lease.aclose() def _spawn(self, coroutine): task = asyncio.create_task(coroutine) self._tasks.add(task) task.add_done_callback(self._on_task_done) def _on_task_done(self, task: asyncio.Task): self._tasks.discard(task) if not task.cancelled() and (e := task.exception()): logger.debug(f"Bluetooth delegate task failed: {e!r}") ================================================================================ # FILE: majordom_matter/client.py ================================================================================ from typing import override from matter_server.client import MatterClient as _MatterClient from matter_server.common.models import EventMessage, EventType class MatterClient(_MatterClient): @override def _handle_event_message(self, msg: EventMessage): # matterjs-server may report a just-commissioned node's attributes before announcing the node (whose # announcement carries them). Upstream raises KeyError on those, which ends listening and cancels the # commissioning call that's still waiting for its result. if msg.event == EventType.ATTRIBUTE_UPDATED and msg.data[0] not in self._nodes: return super()._handle_event_message(msg) ================================================================================ # FILE: majordom_matter/config.py ================================================================================ """matterjs-server: the Matter controller service this integration drives over its WebSocket API (``/ws``), lending it the hub's Bluetooth over its BLE proxy endpoint (``/ble``).""" from majordom_integration_sdk import Endpoint, Need, Service def matterjs_server() -> Service: """matterjs-server, a new one for each runtime.""" return Service( "matterjs-server", # Thread is optional: without a border router Matter still works over Wi-Fi and Ethernet. Bluetooth too: an # adapter of its own only when no Bluetooth router holds them (disabled, failed or absent). The router is an # in-process object a container can't bind: it reaches matterjs-server through the controller (ble_delegate, # over /ble) instead. needs=[Need("ip"), Need("thread", ["otbr-rest"], is_required=False), Need("ble", ["bluez"], is_required=False)], # the base URL: /ws, /ble; "adapter" tells the controller whether an adapter is bound here (empty: none) provides=[ Endpoint( "matter", "matter-server", "ws://127.0.0.1:{ports.api}", params={"adapter": "{peripherals.ble.url}"} ) ], ports={"api": 5580}, compose={ # :dev pinned by digest (2026-10-08); bump on purpose "image": "ghcr.io/matter-js/matterjs-server@sha256:bcaacf6b2b2df9ce2b929ad7469d5380a4d627f05f790e201d127e8b65af5b0e", # noqa: E501 "network_mode": "host", "userns_mode": "host", "user": "{host.uid}:{host.gid}", # its data folder belongs to the hub "environment": { "STORAGE_PATH": "/data", "PORT": "{ports.api}", # on the host network, with no authentication: anyone on the LAN could drive the fabric. Loopback # unless the host opens its services to the LAN (a lab harness) "LISTEN_ADDRESS": "{host.listen_address}", # Bluetooth comes from the hub (see ble_delegate) unless an adapter is bound to it. Then noble # drives it through the host's BlueZ over the system bus: its default HCI socket backend needs root "BLE_PROXY": "{peripherals.ble.url:!true}", "BLUETOOTH_ADAPTER": "{peripherals.ble.params[index]}", "NOBLE_BINDINGS": "{peripherals.ble.url:?dbus}", # matter.js logs every command's fields at info, the Thread network key included "LOG_LEVEL": "warning", }, "volumes": [ "{data}:/data", # the system bus only with an adapter: gone without one "{peripherals.ble.url:?/run/dbus:/run/dbus:ro}", ], }, ) ================================================================================ # FILE: majordom_matter/controller.py ================================================================================ import asyncio import base64 import contextlib import inspect import logging from collections.abc import Coroutine, Generator from dataclasses import replace from typing import Any, override from uuid import UUID from aiohttp import ClientError, ClientSession from chip.clusters.ClusterObjects import ClusterAttributeDescriptor, ClusterCommand from chip.clusters.Objects import ClosureControl, Identify, OperationalCredentials, OperationalState from majordom_integration_sdk import ( STABLE_RUN, AbstractController, IntegrationError, Need, NoSettings, PeripheralChange, Platform, ) from majordom_integration_sdk.capabilities import BLE_ROUTER, BLEDiscoveryInfo, BLERouter from majordom_integration_sdk.schemas.base import NonEmptyStr from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import CredentialsType, Discovery, ParameterState, ProvidedCredentials from majordom_integration_sdk.schemas.event import DeviceParameterChange from majordom_integration_sdk.schemas.parameter import ParameterDataType, ParameterRole, ParameterVisibility from matter_server.client.exceptions import InvalidState, NotConnected, TransportError from matter_server.client.models.node import MatterNode from matter_server.common.errors import UnknownError from matter_server.common.models import CommissionableNodeData, EventType, MatterNodeData from majordom_matter.ble_delegate import MatterServerBLEDelegate from majordom_matter.client import MatterClient from .exceptions import ( MatterConnectionError, MatterNotFoundParameter, MatterUnexpectedError, MatterUnsupportedParameter, ) from .mapper import MatterMapper from .matter_spec import ( CLOSURE_MAIN_STATE, MAIN_PARAMETER_BY_CLUSTER, STATE_TOGGLE_ATTRIBUTES, STATE_TOGGLE_COMMANDS, AttributeKey, DefaultParams, MainParameterSpec, ) from .model import ( MatterDevice, MatterDeviceState, MatterParameter, MatterParameterIntegrationData, MatterParameterState, MatterParameterTypeEnum, ) @contextlib.contextmanager def _server_call(call: str) -> Generator[None]: """A call matterjs-server answers. python-matter-server cancels every one still waiting once matterjs-server goes away (or Matter stops): such a cancel, one nobody asked of the task, is a lost connection.""" try: yield except asyncio.CancelledError: if (task := asyncio.current_task()) and task.cancelling(): raise raise MatterConnectionError(f"The connection to matterjs-server ended during {call}") from None UNSAVED_PAIRING_TIMEOUT = ( 120.0 # seconds a paired node waits for the Hub to save and fetch it before it is offered again ) _DAC_ATTEMPTS = 2 _DAC_REQUEST = OperationalCredentials.Commands.CertificateChainRequest( certificateType=OperationalCredentials.Enums.CertificateChainTypeEnum(1) # the DAC ) _DAC_RETRY_DELAY = 1.0 class MatterController(AbstractController[MatterDevice, MatterParameter, NoSettings, MatterDeviceState]): """Bridges the Hub to Matter devices through a Matter controller server (matterjs-server). matterjs-server owns the Matter fabric and commissioning, over the hub's Bluetooth (`MatterServerBLEDelegate`), or an adapter of its own when no Bluetooth router runs, and a Thread border router; this controller adapts it to the Hub's AbstractController contract, talking to it over its WebSocket API. On-network devices are discovered via matterjs-server; BLE-only commissionable devices are discovered via the Bluetooth router, or, with an adapter of its own, found by matterjs-server from the pairing code entered. See readme.md. """ # matter: matterjs-server's base URL (its API at /ws, its BLE proxy at /ble); # ble: the router, which MatterServerBLEDelegate lends matterjs-server for commissioning needs = [Need("matter", ["matter-server"]), replace(BLE_ROUTER, is_required=False)] _matter_client: MatterClient | None = None # once connected, until stop() _matter_client_session: ClientSession _majordom_descoveries: dict[UUID, Discovery] _mapper: MatterMapper # Matter commissionable BLE service (spec 5.4.2.5.6) — devices in commissioning mode advertise # this service + its service-data payload. discover_commissionable_nodes only surfaces IP/mDNS # devices, so BLE-only devices (a factory-fresh bulb not yet on any network) are discovered here # via the Bluetooth router instead. _MATTER_COMMISSIONABLE_SERVICE = UUID("0000fff6-0000-1000-8000-00805f9b34fb") _RECONNECT_DELAY = 1.0 # doubles per attempt until a connection holds, up to _RECONNECT_DELAY_MAX _RECONNECT_DELAY_MAX = 30.0 _UNREACHABLE_AFTER = 15.0 # of outage before the user hears of it: a container recreated on purpose is back by then # an outage is over only once a reconnect held this long, so drops in a row add up: a matterjs-server that sends its # node list and drops every time is reported _STABLE_CONNECTION = STABLE_RUN # what an outage raises: matterjs-server away, refusing the connection, or dropping it before it spoke _CONNECTION_ERRORS = (TransportError, NotConnected, InvalidState, MatterConnectionError, ClientError, OSError) def __init__(self, platform: Platform, *, settings: NoSettings | None = None): super().__init__(platform, settings=settings) # Instance state (not class-level): the mapper is wired with the framework's UUID # generators, and the discoveries dict must not be shared across instances. self._mapper = MatterMapper(self.device_uuid, self.parameter_uuid) self._majordom_descoveries = dict() # ------------------------------------------------------------------------- # AbstractController interface # ------------------------------------------------------------------------- @property def discoveries(self) -> dict[UUID, Discovery]: return self._majordom_descoveries @property @override def device_type(self) -> type[MatterDevice]: return MatterDevice @property @override def device_state_type(self) -> type[MatterDeviceState]: return MatterDeviceState @property @override def parameter_type(self) -> type[MatterParameter]: return MatterParameter # ------------------------------------------------------------------------- # Lifecycle # ------------------------------------------------------------------------- async def start(self): self._background_tasks: list[asyncio.Task] = [] self._node_availability: dict[UUID, bool] = {} self._unsaved_pairings: dict[int, asyncio.Task[None]] = {} # by node id: waiting for the Hub's fetch self._subscribed: dict[UUID, MatterClient] = {} # the client each device's callbacks are on self._matter_client_session = ClientSession() listener = await self._connect() self._background_tasks.append(listener) # stop() ends it also after a start that fails below self._background_tasks.append(asyncio.create_task(self._matter_discovery_loop())) # BLE discovery for commissionable devices not yet on any IP network (the mDNS-based # discovery loop above can't see them). None without the router (no Bluetooth on this hub). self._ble_addresses: dict[UUID, set[str]] = {} # discovery_id -> live BLE addresses self._ble_cancel = None if self.peripherals.endpoint("matter").params.get("adapter"): # matterjs-server holds an adapter of its own and scans inside commission_with_code; it can't list # commissionable BLE devices, so one generic discovery takes the pairing code await self._offer_commissioning_by_code() elif router := self.peripherals.instance(BLE_ROUTER): self._lend_router(router) await self._sync_with_server() self._background_tasks.append(asyncio.create_task(self._stay_connected(listener))) async def _sync_with_server(self): """Hands matterjs-server the networks and follows the devices on its fabric; on every (re)connect.""" # Networks new devices get commissioned onto. await self._hand_over_networks() client = self._require_matter_client() device_nodes: list[int] = [] nodes = {node.node_id: node for node in client.get_nodes()} # get_node raises for a missing one async with self.platform.device_repository(self) as device_repository: devices = await device_repository.get_all(as_=MatterDevice) for device in devices: if node := nodes.get(device.integration_data.node_id): self._subscription(device.physical_id, node) device_nodes.append(device.integration_data.node_id) else: # gone from the fabric: a commissioning that failed, a reset matterjs-server await self.output.controller_did_lose_device(self, physical_id=device.physical_id) for node in client.get_nodes(): if node.node_id not in device_nodes: await self._offer_fabric_node(node) # the Hub, or a lost server, made them unavailable; a copy: a pairing may land meanwhile for physical_id, available in list(self._node_availability.items()): if available: await self.output.controller_did_connect_device(self, physical_id=physical_id) async def _offer_fabric_node(self, node: MatterNode): """A node on the fabric without a device: pair_device adds it as it is, without a code.""" if (discovery := self._fabric_discovery(node)) is None: logging.info(f"[{self.name}] node {node.node_id} isn't interviewed yet: offered at the next start") return self._majordom_descoveries[discovery.id] = discovery await self.output.controller_did_receive_discovery(self, discovery) def _cancel_unsaved_pairing(self, node_id: int): if (waiting := self._unsaved_pairings.pop(node_id, None)) is not None: waiting.cancel() async def _offer_unless_saved(self, node: MatterNode): await asyncio.sleep(UNSAVED_PAIRING_TIMEOUT) self._unsaved_pairings.pop(node.node_id, None) await self._offer_fabric_node(node) def _fabric_discovery(self, node: MatterNode) -> Discovery | None: if 0 not in node.endpoints: return None return Discovery( id=self._fabric_discovery_id(node.node_id), integration=NonEmptyStr(self.key), expected_credentials_options=[CredentialsType.none], expiration=None, transport=NonEmptyStr("IP"), device_name=NonEmptyStr(node.device_info.productName or "Unknown"), device_manufacturer=node.device_info.vendorName or str(node.device_info.vendorID), device_category=None, device_icon=None, ) async def stop(self): self._majordom_descoveries.clear() getattr(self, "_unsaved_pairings", {}).clear() # the tasks are among the background ones client, self._matter_client = self._matter_client, None if cancel := getattr(self, "_ble_cancel", None): cancel() self._ble_cancel = None try: running_loop = asyncio.get_running_loop() except RuntimeError: running_loop = None # Cancel the discovery loop and listener started in start() — otherwise they keep # running against a matter client/event loop that stop() is about to tear down, # which surfaces as "Future attached to a different loop" once the next test/run # starts a fresh event loop. cancel() is safe to call across loops. # # Whether we then AWAIT them — and tear the matter client down — depends on the # loop. If stop() runs on a different loop than start() did (e.g. invoked via a sync # TestClient, whose portal runs on its own loop), awaiting any of these loop-bound # futures (the tasks, or the ws client's disconnect/close, which awaits the same # loop-A websocket) itself raises "attached to a different loop". There, cancel() # above is the meaningful cleanup and we skip the awaits; the normal same-loop # lifecycle does the full teardown. background_tasks = getattr(self, "_background_tasks", []) for task in background_tasks: task.cancel() on_owning_loop = running_loop is not None and ( not background_tasks or background_tasks[0].get_loop() is running_loop ) self._background_tasks = [] if not on_owning_loop: return # one may have ended with an error long ago (a listener _stay_connected got over): it must not cut stop() short await asyncio.gather(*background_tasks, return_exceptions=True) try: if client: # none before a first connection await client.disconnect() finally: if session := getattr(self, "_matter_client_session", None): # none before a first start await session.close() def _spawn(self, coroutine: Coroutine[Any, Any, None]) -> asyncio.Task[None]: """Runs it in a task stop() ends; kept, as the event loop holds its tasks only weakly.""" self._background_tasks = [task for task in self._background_tasks if not task.done()] task = asyncio.create_task(coroutine) self._background_tasks.append(task) return task async def _hand_over_networks(self): """A network matterjs-server refuses is only logged: Matter still serves every device it has, and still commissions Wi-Fi and Ethernet ones.""" try: client = self._require_matter_client() with _server_call("the networks' hand-over"): if wifi := self.platform.wifi: await client.set_wifi_credentials(wifi.ssid, wifi.password) if dataset := self.platform.thread_dataset: await client.set_thread_operational_dataset(dataset) except self._CONNECTION_ERRORS as e: # away: _stay_connected hands them over once it is back logging.info(f"[{self.name}] the networks wait for matterjs-server: {e!r}") except Exception as e: logging.warning(f"[{self.name}] matterjs-server refused the networks: {e!r}") def _lend_router(self, router: BLERouter): # matterjs-server commissions over Bluetooth through the hub's radios, not its own ble_delegate = MatterServerBLEDelegate(f"{self._server_url}/ble", router, self._matter_client_session) self._background_tasks.append(asyncio.create_task(ble_delegate.run())) self._ble_cancel = router.register(self, {self._MATTER_COMMISSIONABLE_SERVICE}) @property def _server_url(self) -> str: return self.peripherals.endpoint("matter").url.rstrip("/") async def _connect(self) -> asyncio.Task: """Connects a fresh client to matterjs-server, current once it is ready; the returned listener runs until matterjs-server goes away.""" client = MatterClient(f"{self._server_url}/ws", self._matter_client_session) await client.connect() init_ready = asyncio.Event() listener = asyncio.create_task(client.start_listening(init_ready=init_ready)) ready = asyncio.create_task(init_ready.wait()) try: await asyncio.wait({ready, listener}, return_when=asyncio.FIRST_COMPLETED) finally: ready.cancel() if not init_ready.is_set(): listener.cancel() if not init_ready.is_set(): raise MatterConnectionError("matterjs-server went away before it was ready") # not before: start_listening would take the answer to a call made meanwhile (a hand-over) for its node dump self._matter_client = client return listener async def _stay_connected(self, listener: asyncio.Task): """Reconnects whenever matterjs-server goes away (e.g. its container is recreated) until stop() cancels it, so the integration heals by itself instead of being restarted by the hub.""" loop = asyncio.get_running_loop() outage_since: float | None = None try: while True: connected_at = loop.time() try: await listener except Exception as e: logging.warning(f"[{self.name}] matterjs-server listener failed: {e!r}") failed_at = loop.time() if outage_since is None or failed_at - connected_at >= self._STABLE_CONNECTION: outage_since, delay = failed_at, self._RECONNECT_DELAY # a new outage, else its delay grows on for physical_id, available in list(self._node_availability.items()): # a pairing may land meanwhile if available: await self.output.controller_did_lose_device(self, physical_id=physical_id) self._node_availability = dict.fromkeys(self._node_availability, False) is_reported = False while True: # on each failure, the drop too: one soon after a reconnect is the same outage if not is_reported and failed_at - outage_since > self._UNREACHABLE_AFTER: error = IntegrationError( "server-unreachable", "Lost the connection to the Matter server, reconnecting." ) await self.output.controller_did_encounter_error(self, error) is_reported = True await asyncio.sleep(delay) delay = min(delay * 2, self._RECONNECT_DELAY_MAX) try: listener = await self._connect() break except self._CONNECTION_ERRORS as e: # also a connection dropped before matterjs-server spoke failed_at = loop.time() logging.info(f"[{self.name}] matterjs-server is not back yet: {e!r}") await self._sync_with_server() logging.info(f"[{self.name}] reconnected to matterjs-server") if is_reported: # the devices work again; the outage goes on until the connection held await self.output.controller_did_resolve_error(self, "server-unreachable") except Exception: # a bug rather than an outage: the runtime restarts Matter, then gives up on it logging.exception(f"[{self.name}] stopped following matterjs-server") message = "The connection to the Matter server broke unexpectedly." await self.output.controller_did_encounter_error( self, IntegrationError("crashed", message, is_still_running=False) ) finally: listener.cancel() # ------------------------------------------------------------------------- # Peripheral hooks # ------------------------------------------------------------------------- @override async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: """The router coming up once Matter runs is taken as at the start, in place, and with an adapter of its own matterjs-server doesn't use the router at all; anything else restarts Matter.""" if change.family != BLE_ROUTER.family: return False if self.peripherals.endpoint("matter").params.get("adapter"): return True if change.before is not None or (router := self.peripherals.instance(BLE_ROUTER)) is None: return False self._lend_router(router) return True @override async def platform_facts_did_change(self, before: Platform) -> bool: """A new Thread network or Wi-Fi reaches matterjs-server in place, for the devices commissioned next.""" if (self.platform.wifi, self.platform.thread_dataset) != (before.wifi, before.thread_dataset): # in a task: the runtime waits for this hook, while matterjs-server may be away or not answer self._spawn(self._hand_over_networks()) return True # ------------------------------------------------------------------------- # Hub -> device operations # ------------------------------------------------------------------------- async def _commission(self, value: str, network_only: bool) -> MatterNodeData: """Route by what the user typed, whichever credentials type the UI collected it under. `MT:` is a QR payload; 11 or 21 digits are a manual pairing code; 8 digits are the raw setup PIN, which only commission_on_network takes and which carries no discriminator for finding a BLE-only device. """ client = self._require_matter_client() if value.strip().upper().startswith("MT:"): return await client.commission_with_code(value.strip(), network_only=network_only) digits = "".join(char for char in value if char.isdigit()) match len(digits): case 8: if not network_only: raise ValueError( "A raw 8-digit setup PIN only works for devices already on the network; " "enter the 11-digit manual pairing code or scan the QR code for a Bluetooth device" ) return await client.commission_on_network(int(digits)) case 11 | 21: return await client.commission_with_code(digits, network_only=network_only) case _: raise ValueError( f"Unrecognised Matter pairing code ({len(digits)} digits): expected an 11- or 21-digit " "manual pairing code, an 8-digit setup PIN, or an MT: QR payload" ) @override async def pair_device( self, discovery: Discovery, draft: MatterDeviceState, credentials: ProvidedCredentials | None ) -> MatterDeviceState: client = self._require_matter_client() # a node on the fabric without a device (a pairing that ended before the save, a device deleted since) is # offered under an id of its node id and taken as it is; any other discovery is commissioned with its code on_fabric = {self._fabric_discovery_id(n.node_id): n for n in client.get_nodes()} if (node := on_fabric.get(discovery.id)) is not None: return await self._fill_draft(discovery, draft, node) with _server_call("the pairing"): commissioned = await self._commission_discovery(discovery, credentials) node = client.get_node(commissioned.node_id) try: return await self._fill_draft(discovery, draft, node) except Exception: # a taken id too. On the fabric now, no longer commissionable: offered as it is, to retry if discovery.id != self._by_code_id: self._majordom_descoveries.pop(discovery.id, None) await self.output.controller_did_lose_discovery(self, discovery.id) await self._offer_fabric_node(node) raise async def _fill_draft(self, discovery: Discovery, draft: MatterDeviceState, node: MatterNode) -> MatterDeviceState: """Maps a node on the fabric into the draft the Hub gave; the Hub saves it and follows the device after.""" if (physical_id := await self._resolve_node_device_id(node)) is None: raise MatterUnexpectedError( f"Node {node.node_id} reports neither a SerialNumber nor a UniqueID, and its attestation certificate " "couldn't be read" ) draft.physical_id = physical_id await self.check_device_id(physical_id, draft) draft.available = node.available # Manufacturer-provided, read-only description (BasicInformation product label). draft.description = getattr(node.device_info, "productLabel", None) or None # a record the user picked brings its old parameters: the node's own replace them draft.parameters = [] for endpoint_id, endpoint in node.endpoints.items(): for cluster_id, cluster in endpoint.clusters.items(): if hasattr(cluster, "Commands"): for parameter in self._mapper.parse_commands(physical_id, endpoint_id, cluster_id, cluster, node): draft.parameters.append(MatterParameterState(**parameter.__dict__, value=None)) if hasattr(cluster, "Attributes"): for parameter in self._mapper.parse_attributes( physical_id, endpoint_id, cluster_id, cluster, endpoint, node ): attribute_id = parameter.integration_data.attribute_id if attribute_id is None: raise MatterUnexpectedError( f"Attribute parameter {parameter.name!r} has no attribute_id " f"(endpoint {endpoint_id}, cluster {cluster_id})" ) value = node.get_attribute_value(endpoint_id, cluster_id, attribute_id) draft.parameters.append( MatterParameterState( **parameter.__dict__, value=self._mapper.attribute_value(cluster_id, attribute_id, value), ) ) main_parameter, default_value = self._get_main_parameter(draft.physical_id, node, draft.parameters) draft.main_parameter = main_parameter.id if main_parameter is not None else None if main_parameter is not None and default_value is not None: if main_parameter.integration_data.type is MatterParameterTypeEnum.attribute: main_parameter.default_value = self._mapper.normalize_value(default_value) elif isinstance(default_value, dict): # A command main parameter is tapped with a fixed argument set (a dict). main_parameter.integration_data.default_arguments = default_value else: raise MatterUnexpectedError( f"Command main parameter {main_parameter.id} expected dict default arguments, " f"got {type(default_value).__name__}: {default_value!r}" ) if main_parameter is not None and main_parameter.data_type is ParameterDataType.struct: # A struct is a one-tap main parameter only with a default_value: the id-keyed # arguments a tap sends. arguments = main_parameter.integration_data.default_arguments or {} main_parameter.default_value = { str(f.id): arguments[f.name] for f in main_parameter.fields or () if f.name in arguments } draft.integration_data.node_id = node.node_id self._majordom_descoveries.pop(discovery.id, None) # Not offered while the Hub saves the device (it fetches it then): one it never saves is offered as it is if self._matter_client is not None: self._cancel_unsaved_pairing(node.node_id) self._unsaved_pairings[node.node_id] = self._spawn(self._offer_unless_saved(node)) # a pairing landing after stop() keeps its device rather than failing: the node is commissioned onto the fabric if discovery.id == self._by_code_id and self._matter_client is not None: await self._offer_commissioning_by_code() # the next device is added the same way return draft async def _commission_discovery( self, discovery: Discovery, credentials: ProvidedCredentials | None ) -> MatterNodeData: if not credentials or credentials.type not in discovery.expected_credentials_options: raise MatterUnexpectedError( f"Credentials type {credentials.type if credentials else None!r} is not one of the " f"types this discovery advertised: {discovery.expected_credentials_options}" ) # Every commissioning path below needs the pairing code/QR payload; a missing value is an # unexpected caller error, not something to stringify into "None" or crash on int(None). if credentials.value is None: raise MatterUnexpectedError("Matter commissioning requires a pairing code, but none was provided") # matterjs-server may run without a Bluetooth adapter; then a non-network_only commission fails # with "Bluetooth commissioning is not available", so only BLE discoveries may use BLE. network_only = discovery.transport != "BLE" # Compare by value (==), not identity (is): `credentials.type` can arrive through a # schema layer that resolved CredentialsType via a different import path, yielding a # distinct enum class where `is` would never match. `==` on a str-enum compares the # underlying value and is robust to that (and semantically what we want anyway). if credentials.type not in (CredentialsType.qr, CredentialsType.code): raise MatterUnexpectedError("This credentials type is not supported") return await self._commission(str(credentials.value), network_only=network_only) async def unpair(self, device: MatterDevice): client = self._require_matter_client() self._subscribed.pop(device.physical_id, None) self._node_availability.pop(device.physical_id, None) if device.node_id in self._unsaved_pairings: # The Hub's rollback of a pairing it didn't save: the node stays on the fabric, offered at once to retry self._cancel_unsaved_pairing(device.node_id) for node in client.get_nodes(): if node.node_id == device.node_id: await self._offer_fabric_node(node) return if self._fabric_discovery_id(device.node_id) in self._majordom_descoveries: return # rolled back already: offered as its fabric node, not a device to remove # a device that never finished commissioning (or that matterjs-server lost) has no node to remove if any(node.node_id == device.node_id for node in client.get_nodes()): with _server_call("the unpairing"): await client.remove_node(device.node_id) async def identify(self, device: MatterDevice): command = Identify.Commands.Identify() node = self._require_node(device) with _server_call("the identification"): for endpoint_id in node.endpoints: if node.has_cluster(3, endpoint_id): await self._require_matter_client().send_device_command(device.node_id, endpoint_id, command) async def fetch(self, device: MatterDevice): self._cancel_unsaved_pairing(device.node_id) self._majordom_descoveries.pop(self._fabric_discovery_id(device.node_id), None) node = self._require_node(device) self._subscription(device.physical_id, node) if not node.available: return # asleep or away: the availability callback tells the Hub once it answers events = [] for endpoint_id, endpoint in node.endpoints.items(): for cluster_id, cluster in endpoint.clusters.items(): if not hasattr(cluster, "Attributes"): continue for _, attribute in inspect.getmembers(cluster.Attributes, inspect.isclass): if not issubclass(attribute, ClusterAttributeDescriptor): continue attribute_id = getattr(attribute, "attribute_id", -1) value = node.get_attribute_value(endpoint_id, cluster_id, attribute_id) parameter_id = self._mapper.attribute_parameter_uuid( device.physical_id, endpoint_id, cluster_id, attribute_id ) events.append( DeviceParameterChange( physical_id=device.physical_id, parameter_id=parameter_id, value=self._mapper.attribute_value(cluster_id, attribute_id, value), ) ) await self.output.controller_did_receive_events(self, events) async def send_command(self, command: DeviceCommand, device: MatterDevice, parameter: MatterParameter): try: node = self._require_node(device) endpoint_id = parameter.integration_data.endpoint_id endpoint = node.endpoints.get(endpoint_id) if not endpoint: raise MatterUnexpectedError(f"Endpoint {endpoint_id} not found on node {node.node_id}") cluster_id = parameter.integration_data.cluster_id cluster = endpoint.clusters.get(cluster_id) if not cluster: raise MatterUnexpectedError(f"Cluster {cluster_id} not found on endpoint {endpoint_id}") with _server_call("the command"): if parameter.integration_data.type is MatterParameterTypeEnum.command: await self._execute_cluster_command(device, node, endpoint_id, cluster, parameter, command) elif parameter.integration_data.type is MatterParameterTypeEnum.attribute: attribute_id = parameter.integration_data.attribute_id if attribute_id is not None and AttributeKey(cluster_id, attribute_id) in STATE_TOGGLE_ATTRIBUTES: cluster_command = self._state_toggle_command( node, endpoint_id, cluster, attribute_id, command.value ) await self._require_matter_client().send_device_command( node.node_id, endpoint_id, cluster_command, timed_request_timeout_ms=1000 if cluster_command.must_use_timed_invoke else None, ) else: await self._write_cluster_attribute(node, endpoint_id, cluster_id, parameter, command) except UnknownError as e: error = str(e) error_map = { "0x8b": (MatterNotFoundParameter, "not found on device"), "0x81": (MatterUnsupportedParameter, "not supported by device"), } match = next(((exc, msg) for code, (exc, msg) in error_map.items() if code in error), None) if match is None: # Unknown/unmapped Matter error (e.g. Busy 0x9c) — don't swallow it logging.error(f"Command '{parameter.name}' failed with unmapped error: {error}") raise exception_class, message = match async with self.platform.device_repository(self) as device_repository: device_state = await device_repository.state(physical_id=device.physical_id, as_=MatterDeviceState) if device_state is not None: # state() returns None only if the device was unpaired/removed out from under us; # nothing to prune then — just surface the original command error below. device_state.parameters = [p for p in device_state.parameters if p.id != parameter.id] device.integration_data.black_list.append(parameter.id) await device_repository.save(device) else: logging.warning( f"Device {device.physical_id} is gone; skipped blacklisting parameter {parameter.id}" ) logging.error(f"Command '{parameter.name}' is {message} and will be removed") raise exception_class(f"Command '{parameter.name}' failed: {message}") from None # ------------------------------------------------------------------------- # Device -> Hub: discovery (mDNS / on-network) # ------------------------------------------------------------------------- async def _matter_discovery_loop(self, interval: int = 5): # On-network (mDNS) discovery is polled from matterjs-server rather than routed through the # Hub's shared Zeroconf service on purpose: matterjs-server already parses the Matter `_matterc` # TXT records into clean, structured CommissionableNodeData (discriminator, vendor/product, # commissioning mode, pairing hints). Re-deriving that on the raw Zeroconf service would just # duplicate matterjs-server's parser. BLE-only devices, which mDNS can't see, ARE discovered via # the Bluetooth router instead (see the BLE discovery section below) — so the "our # discovery + SDK for pairing" split is used exactly where it adds value. is_away = False # matterjs-server: an outage is logged once while True: try: client = self._require_matter_client() with _server_call("the discovery"): nodes: list[CommissionableNodeData] = await client.discover_commissionable_nodes() is_away = False for node in nodes: await self._async_matter_did_discover(node) except self._CONNECTION_ERRORS as e: if not is_away: logging.warning(f"[{self.name}] discovery waits for matterjs-server: {e!r}") is_away = True except Exception as e: logging.error(f"[{self.name}] discovery error: {e}") await asyncio.sleep(interval) async def _async_matter_did_discover(self, node: CommissionableNodeData): discovery_id = self._mapper.discovery_uuid( node.instance_name or f"{node.vendor_id}_{node.product_id}_{node.addresses[0] if node.addresses else 'unknown'}" ) discovery = Discovery( id=discovery_id, integration=NonEmptyStr(self.key), expected_credentials_options=self._mapper.define_credentials_options( node.commissioning_mode, node.pairing_hint, node.pairing_instruction, bool(node.addresses) ), expiration=None, transport=NonEmptyStr("IP" if node.addresses else "BLE"), device_name=NonEmptyStr(node.device_name or node.instance_name or "Unknown"), device_manufacturer=f"Vendor {node.vendor_id}" if node.vendor_id else None, device_category=str(node.device_type), device_icon=None, ) self._majordom_descoveries[discovery_id] = discovery await self.output.controller_did_receive_discovery(self, discovery) # ------------------------------------------------------------------------- # Device -> Hub: commissioning by code — matterjs-server holds an adapter of its own # ------------------------------------------------------------------------- @property def _by_code_id(self) -> UUID: return self._mapper.discovery_uuid("matter-ble-by-code") async def _offer_commissioning_by_code(self): """One discovery to pair with a manual pairing code or QR: matterjs-server finds the device over Bluetooth by the code's discriminator. Like any discovery, the Hub seeds its device row under this id when pairing starts, and pair_device renames it to the commissioned node's.""" discovery = Discovery( id=self._by_code_id, integration=NonEmptyStr(self.key), expected_credentials_options=[CredentialsType.code.with_mask("DDDD-DDD-DDDD"), CredentialsType.qr], expiration=None, transport=NonEmptyStr("BLE"), device_name=NonEmptyStr("Matter device (enter its pairing code)"), device_manufacturer=None, device_category=None, device_icon=None, ) self._majordom_descoveries[discovery.id] = discovery await self.output.controller_did_receive_discovery(self, discovery) # ------------------------------------------------------------------------- # Device -> Hub: BLE discovery (BLEDiscoveryListener) — commissionable devices not yet on IP, through the router # ------------------------------------------------------------------------- async def ble_did_discover_device(self, ble: BLERouter, info: BLEDiscoveryInfo): await self._matter_did_discover_ble(info) async def ble_did_update_device(self, ble: BLERouter, info: BLEDiscoveryInfo): await self._matter_did_discover_ble(info) async def ble_did_remove_device(self, ble: BLERouter, info: BLEDiscoveryInfo): # Intentionally keep the discovery. Commissionable devices rotate their BLE address while the # window is open (~minutes), so the scanner's short not-seen eviction (~11s) fires constantly # even while the device is very much present — dropping the discovery here would race # commissioning. pair_device removes it on success; stop() clears the rest. return async def _matter_did_discover_ble(self, info: BLEDiscoveryInfo): parsed = self._parse_commissionable_ble(info) if not parsed: return discriminator, vendor_id, product_id = parsed discovery_id = self._ble_discovery_id(discriminator, vendor_id, product_id) self._ble_addresses.setdefault(discovery_id, set()).add(info.device.address) if discovery_id in self._majordom_descoveries: return # already advertised; the device keeps beaconing while its window is open discovery = Discovery( id=discovery_id, integration=NonEmptyStr(self.key), # A commissionable device accepts its manual pairing code (or QR). pair_device's BLE # branch feeds the code to commission_with_code, which does its own BLE scan by discriminator. expected_credentials_options=[CredentialsType.code.with_mask("DDDD-DDD-DDDD"), CredentialsType.qr], expiration=None, transport=NonEmptyStr("BLE"), device_name=NonEmptyStr(info.advertisement.local_name or f"Matter {vendor_id:04x}:{product_id:04x}"), device_manufacturer=f"Vendor {vendor_id}", device_category=None, device_icon=None, ) self._majordom_descoveries[discovery_id] = discovery await self.output.controller_did_receive_discovery(self, discovery) @staticmethod def _parse_commissionable_ble(info: BLEDiscoveryInfo) -> tuple[int, int, int] | None: """Decode a Matter commissionable BLE advert's service-data payload → (discriminator, vid, pid). Payload (Matter spec 5.4.2.5.6): [0]=opcode(0x00 Commissionable), [1:3]=discriminator (u16 LE, low 12 bits), [3:5]=vendor id (u16 LE), [5:7]=product id (u16 LE), [7]=additional-data flag. """ data = info.advertisement.service_data.get("0000fff6-0000-1000-8000-00805f9b34fb") if not data or len(data) < 7 or data[0] != 0x00: return None discriminator = (data[1] | (data[2] << 8)) & 0x0FFF vendor_id = data[3] | (data[4] << 8) product_id = data[5] | (data[6] << 8) return discriminator, vendor_id, product_id def _ble_discovery_id(self, discriminator: int, vendor_id: int, product_id: int) -> UUID: # Stable across the device's (possibly changing) BLE address and across mDNS re-discovery # after it joins Thread — keyed on the commissioning identity, not the transport address. return self._mapper.discovery_uuid(f"ble_{vendor_id:04x}_{product_id:04x}_{discriminator:03x}") # ------------------------------------------------------------------------- # Device -> Hub: subscriptions & availability # ------------------------------------------------------------------------- def _subscription(self, physical_id: UUID, node: MatterNode): """ Registers attribute-change callbacks for every attribute on the node. Uses _make_callback to capture (physical_id, parameter_id) by value — without it all callbacks would share the last loop iteration's values. """ client = self._require_matter_client() if self._subscribed.get(physical_id) is client: return self._subscribed[physical_id] = client for endpoint_id, endpoint in node.endpoints.items(): for cluster_id, cluster in endpoint.clusters.items(): if not hasattr(cluster, "Attributes"): continue for _, attribute in inspect.getmembers(cluster.Attributes, inspect.isclass): if not issubclass(attribute, ClusterAttributeDescriptor): continue attribute_path = f"{endpoint_id}/{cluster_id}/{attribute.attribute_id}" parameter_id = self._mapper.attribute_parameter_uuid( physical_id, endpoint_id, cluster_id, attribute.attribute_id ) client.subscribe_events( self._make_callback(physical_id, parameter_id, cluster_id, attribute.attribute_id), EventType.ATTRIBUTE_UPDATED, node.node_id, attribute_path, ) # node.available flips when the device drops off/rejoins the Matter fabric while # the Hub keeps running (not just at Hub startup) — NODE_UPDATED fires on that and # other node-info changes, so track the last known value and only act on a real # transition instead of re-signalling on every unrelated update. self._node_availability[physical_id] = node.available client.subscribe_events( self._make_availability_callback(physical_id), EventType.NODE_UPDATED, node.node_id, ) def _make_callback(self, physical_id: UUID, parameter_id: UUID, cluster_id: int, attribute_id: int): def callback(event_type, new_value): event = DeviceParameterChange( physical_id=physical_id, parameter_id=parameter_id, value=self._mapper.attribute_value( cluster_id, attribute_id, self._mapper.parse_raw_attribute(cluster_id, attribute_id, new_value) ), ) self._spawn(self.output.controller_did_receive_events(self, [event])) return callback def _make_availability_callback(self, physical_id: UUID): def callback(event_type, updated_node: MatterNode): was_available = self._node_availability.get(physical_id) is_available = updated_node.available if is_available == was_available: return self._node_availability[physical_id] = is_available if is_available: self._spawn(self.output.controller_did_connect_device(self, physical_id=physical_id)) else: self._spawn(self.output.controller_did_lose_device(self, physical_id=physical_id)) return callback # ------------------------------------------------------------------------- # Private helpers # ------------------------------------------------------------------------- def _require_matter_client(self) -> MatterClient: if not self._matter_client: raise MatterConnectionError("Matter client is not started") return self._matter_client def _node_device_id(self, node: MatterNode) -> UUID | None: """None for a node matterjs-server hasn't interviewed yet: without its attributes it has no device info.""" if 0 not in node.endpoints: return None info = node.device_info by_info = self._mapper.device_uuid(info.vendorID, info.productID, info.serialNumber, info.uniqueID) return by_info def _fabric_discovery_id(self, node_id: int) -> UUID: """A node on the fabric is offered under this, whatever its physical id: that is read (a DAC needs a call to the node) only when it is paired. Stable as long as the node is on the fabric.""" return self._mapper.discovery_uuid(f"matter-fabric-node-{node_id}") async def _resolve_node_device_id(self, node: MatterNode) -> UUID | None: """_node_device_id, else the node's Device Attestation Certificate: no serial, no unique id.""" if (device_id := self._node_device_id(node)) is not None or 0 not in node.endpoints: return device_id for attempt in range(_DAC_ATTEMPTS): try: # the first call right after a power loss may find the channel closed response = await self._require_matter_client().send_device_command(node.node_id, 0, _DAC_REQUEST) certificate = response["certificate"] if isinstance(response, dict) else response.certificate device_id = self._mapper.dac_uuid(base64.b64decode(certificate)) except Exception as e: logging.info( f"[{self.name}] node {node.node_id}: attestation certificate read {attempt + 1} failed: {e!r}" ) await asyncio.sleep(_DAC_RETRY_DELAY) else: return device_id return None def _require_node(self, device: MatterDevice) -> MatterNode: node = self._require_matter_client().get_node(device.node_id) if not node: raise MatterUnexpectedError(f"Node for device {device.node_id} not found") return node async def _execute_cluster_command( self, device: MatterDevice, node, endpoint_id: int, cluster, parameter: MatterParameter, command: DeviceCommand ): command_id = parameter.integration_data.command_id if command_id is None or command_id < 0: raise MatterUnexpectedError(f"Invalid command_id: {command_id}") if not hasattr(cluster, "Commands"): return # A value-less send (e.g. tapping the main parameter) falls back to the arguments this # command was set up with as a main parameter — see integration_data.default_arguments. arguments = command.value if command.value is not None else parameter.integration_data.default_arguments for _, cmd_class in inspect.getmembers(cluster.Commands, inspect.isclass): if not issubclass(cmd_class, ClusterCommand): continue if getattr(cmd_class, "command_id", -1) != command_id: continue # Only send client-side commands if not getattr(cmd_class, "is_client", True): continue time_requested_timeout = 1000 if cmd_class.must_use_timed_invoke else None if isinstance(arguments, dict): arguments = self._mapper.arguments_by_name( device.physical_id, endpoint_id, cluster.id, command_id, cmd_class, arguments ) data = self._mapper.parse_data_for_command(cmd_class, arguments) await self._require_matter_client().send_device_command( node.node_id, endpoint_id, cmd_class(**data), timed_request_timeout_ms=time_requested_timeout ) else: await self._require_matter_client().send_device_command( node.node_id, endpoint_id, cmd_class(), timed_request_timeout_ms=time_requested_timeout ) return @staticmethod def _state_toggle_command(node: MatterNode, endpoint_id: int, cluster, attribute_id: int, value) -> ClusterCommand: """The command that sets a read-only state attribute to `value` (see STATE_TOGGLE_ATTRIBUTES).""" current = node.get_attribute_value(endpoint_id, cluster.id, attribute_id) key = AttributeKey(cluster.id, attribute_id) if key == CLOSURE_MAIN_STATE: if current in ( ClosureControl.Enums.MainStateEnum.kMoving, ClosureControl.Enums.MainStateEnum.kWaitingForMotion, ): return ClosureControl.Commands.Stop() overall = node.get_attribute_value( endpoint_id, cluster.id, ClosureControl.Attributes.OverallCurrentState.attribute_id ) closed = getattr(overall, "position", None) == ClosureControl.Enums.CurrentPositionEnum.kFullyClosed target = ClosureControl.Enums.TargetPositionEnum return ClosureControl.Commands.MoveTo( position=target(target.kMoveToFullyOpen if closed else target.kMoveToFullyClosed) ) if key == AttributeKey( OperationalState.id, OperationalState.Attributes.OperationalState.attribute_id ) and current not in ( OperationalState.Enums.OperationalStateEnum.kRunning, OperationalState.Enums.OperationalStateEnum.kPaused, ): raise MatterUnexpectedError( "OperationalState only pauses or resumes a running cycle; it never starts one from idle" ) command_id = STATE_TOGGLE_COMMANDS[key].get(value) if command_id is None: raise MatterUnexpectedError(f"{cluster.__class__.__name__} state {value!r} cannot be set from MajorDom") return next( command_class for _, command_class in inspect.getmembers(cluster.Commands, inspect.isclass) if issubclass(command_class, ClusterCommand) and command_class.command_id == command_id )() async def _write_cluster_attribute( self, node, endpoint_id: int, cluster_id: int, parameter: MatterParameter, command: DeviceCommand ): if parameter.role != ParameterRole.control: raise MatterUnexpectedError(f"Parameter '{parameter.name}' is not writable") attribute_path = f"{endpoint_id}/{cluster_id}/{parameter.integration_data.attribute_id}" if attribute_path not in node.node_data.attributes: return endpoint = node.endpoints[endpoint_id] cluster = endpoint.clusters[cluster_id] attribute_cls = next( ( a for _, a in inspect.getmembers(cluster.Attributes, inspect.isclass) if issubclass(a, ClusterAttributeDescriptor) and getattr(a, "attribute_id", -1) == parameter.integration_data.attribute_id ), None, ) value = self._mapper.parse_data_for_attribute(attribute_cls, command.value) if attribute_cls else command.value await self._require_matter_client().write_attribute(node.node_id, attribute_path, value) def _get_main_parameter( self, physical_id: UUID, node: MatterNode, parameters: list[ParameterState[MatterParameterIntegrationData]] ) -> tuple[ParameterState[MatterParameterIntegrationData] | None, DefaultParams]: # Only `user` parameters can be main (see can_be_main_parameter, which also needs the # default_value set from these defaults) — skip hidden ones so they don't shadow a later match. candidates = {p.id: p for p in parameters if p.visibility is ParameterVisibility.user} for endpoint_id, endpoint in node.endpoints.items(): for cluster_id, cluster_spec in MAIN_PARAMETER_BY_CLUSTER.items(): if cluster_id not in endpoint.clusters: continue # An empty list means the device didn't report it: assume supported. supported_attribute_ids: list[int] = node.get_attribute_value(endpoint_id, cluster_id, 0xFFFB) or [] accepted_command_ids: list[int] = node.get_attribute_value(endpoint_id, cluster_id, 0xFFF9) or [] spec: MainParameterSpec | None = cluster_spec while spec is not None: spec_id = spec.command_or_attribute_id if spec.is_attribute: # A state toggle also needs every command it taps through. needed_command_ids = STATE_TOGGLE_COMMANDS.get(AttributeKey(cluster_id, spec_id), {}).values() supported = (not supported_attribute_ids or spec_id in supported_attribute_ids) and ( not accepted_command_ids or set(needed_command_ids) <= set(accepted_command_ids) ) parameter_id = self._mapper.attribute_parameter_uuid( physical_id, endpoint_id, cluster_id, spec_id ) else: supported = not accepted_command_ids or spec_id in accepted_command_ids parameter_id = self._mapper.command_parameter_uuid( physical_id, endpoint_id, cluster_id, spec_id ) if supported and parameter_id in candidates: return candidates[parameter_id], spec.default_params spec = spec.fallback return None, None ================================================================================ # FILE: majordom_matter/exceptions.py ================================================================================ class MatterConnectionError(Exception): """Raised when Matter client is not started or not available.""" class MatterUnexpectedError(Exception): """Raised when an unexpected internal error occurs.""" class MatterUnsupportedParameter(Exception): """Raised when a parameter is not supported by the device.""" class MatterNotFoundParameter(Exception): """Raised when a parameter was not found on the device.""" ================================================================================ # FILE: majordom_matter/mapper.py ================================================================================ import base64 import enum import hashlib import inspect import logging from collections.abc import Callable from dataclasses import fields, is_dataclass from math import floor, log10 from typing import Any, Union, get_args, get_origin, get_type_hints from uuid import UUID from chip.clusters.CHIPClusters import ChipClusters from chip.clusters.ClusterObjects import ALL_ATTRIBUTES, ALL_CLUSTERS, ClusterAttributeDescriptor, ClusterCommand from chip.clusters.Types import Nullable, NullValue from chip.tlv import TLVReader from majordom_integration_sdk.schemas.device import CredentialsOption, CredentialsType from majordom_integration_sdk.schemas.parameter import ( Parameter, ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from matter_server.client.models.node import MatterNode, get_object_params from matter_server.common.helpers.util import parse_value from .matter_spec import ( ATTRIBUTE_MIN_STEPS, ATTRIBUTE_SCALE, ATTRIBUTE_UNITS, COMMAND_FIELD_SCALE, EVERYDAY_COMMANDS, FIELD_TYPE_TO_DATA_TYPE, METADATA_SOURCES, MIN_MAX_VALUE, SYSTEM_ATTRIBUTES, SYSTEM_CLUSTERS, SYSTEM_COMMANDS, TEXT_BYTES_FIELDS, AttributeKey, classify_attribute, ) from .model import MatterParameter, MatterParameterIntegrationData, MatterParameterTypeEnum def _unwrap_optional(field_type: Any) -> Any: """Optional[X] / Union[X, Nullable] -> X; any other generic (e.g. list[X]) stays as-is.""" if get_origin(field_type) is not Union: return field_type args = [a for a in get_args(field_type) if a not in (type(None), Nullable)] return args[0] if args else field_type def _parse_bytes(raw: Any, text: bool) -> bytes: """A `string` field is UTF-8 text; a `data` one is base64, as normalize_value emits it.""" if isinstance(raw, str): return raw.encode("utf-8") if text else base64.b64decode(raw, validate=True) return bytes(raw) def _to_wire(raw: Any, scale: float | None) -> Any: """The inverse of apply_attribute_scale: a display-unit number back to its wire integer.""" if scale is None or not isinstance(raw, int | float) or isinstance(raw, bool): return raw return round(raw / scale) class MatterMapper: def __init__( self, device_uuid: Callable[[str | bytes], UUID], parameter_uuid: Callable[[UUID, str | bytes], UUID], ): # The controller's framework UUID generators (see AbstractController). Every Matter id — # a device from its node/product, a discovery from its commissioning identity, a parameter # from its endpoint/cluster/attribute path — is derived through these, so parameters are # namespaced under the device and stay identical across pairing, fetch, and live reports. self._device_uuid = device_uuid self._parameter_uuid = parameter_uuid # ------------------------------------------------------------------------- # Identity: Matter identifiers -> MajorDom UUIDs. # Single source of truth for the id string formats — keep every call site going through # these instead of formatting the f-strings inline. # ------------------------------------------------------------------------- def discovery_uuid(self, matter_id: str) -> UUID: """UUID for a discovery, keyed on its (pre-commissioning) Matter identity string.""" return self._device_uuid(matter_id) def device_uuid( self, vendor_id: int | None, product_id: int | None, serial_number: str | None, unique_id: str | None ) -> UUID | None: """Keyed on SerialNumber, else UniqueID (both survive a reset on some makers); never the node id. None when the node reports neither. Vendor and product ids keep serials of different makers apart. """ if not (stable := (serial_number or "").strip() or (unique_id or "").strip()): return None return self._device_uuid(f"{vendor_id or 0:04x}/{product_id or 0:04x}/{stable}") def dac_uuid(self, dac_der: bytes) -> UUID: """Last identity fallback: the Device Attestation Certificate is unique per unit: no vendor/product prefix.""" return self._device_uuid(hashlib.sha256(dac_der).digest()) def attribute_parameter_uuid(self, physical_id: UUID, endpoint_id: int, cluster_id: int, attribute_id: int) -> UUID: return self._parameter_uuid(physical_id, f"attribute_{endpoint_id}/{cluster_id}/{attribute_id}") def command_parameter_uuid(self, physical_id: UUID, endpoint_id: int, cluster_id: int, command_id: int) -> UUID: return self._parameter_uuid(physical_id, f"command_{endpoint_id}/{cluster_id}/{command_id}") def command_field_uuid( self, physical_id: UUID, endpoint_id: int, cluster_id: int, command_id: int, field_name: str ) -> UUID: return self._parameter_uuid(physical_id, f"field_{endpoint_id}/{cluster_id}/{command_id}/{field_name}") def define_credentials_options( self, commissioning_mode: int | None = None, pairing_hint: int | None = None, pairing_instruction: str | None = None, is_on_network: bool = False, ) -> list[CredentialsType | CredentialsOption]: """Every credentials type this node's pairing hint bitmap says it supports — a device can advertise more than one simultaneously (e.g. QR and a manual code), so this returns all of them instead of picking just one.""" if not commissioning_mode or commissioning_mode == 0: return [CredentialsType.none] hint = pairing_hint or 0 instruction = (pairing_instruction or "").lower() options: list[CredentialsType | CredentialsOption] = [] # Bitmask checks based on the Matter spec pairing hint bitmap. if is_on_network: options.append(CredentialsType.code.with_mask("DDDD-DDD-DDDD")) if hint & (0x0004 | 0x0020 | 0x0008): options.append(CredentialsType.qr) if ( hint & (0x0002 | 0x0010) or "code" in instruction or "pin" in instruction ) and CredentialsType.code not in options: options.append(CredentialsType.code.with_mask("DDDD-DDD-DDDD")) # bit 0x0001 (Power Cycle Commissioning Mode) isn't representable as a # CredentialsType — there's no code/QR/secret majordom can collect for it — # so it doesn't contribute an option here. return options or [CredentialsType.none] def normalize_value(self, value: Any): """Convert a chip runtime value to a plain, JSON-serializable python value. Parameter values are pythonic now (not byte-encoded), so anything the Hub stores/sends must serialize cleanly — recurse into lists/dicts and drop chip's ``Nullable``/``NullValue`` sentinels (→ ``None``); chip enums are ``IntEnum`` and already serialize as their int. """ if value is NullValue or isinstance(value, Nullable): return None if isinstance(value, (list, tuple)): return [self.normalize_value(v) for v in value] if isinstance(value, dict): return {k: self.normalize_value(v) for k, v in value.items()} if is_dataclass(value) and not isinstance(value, type): return {f.name: self.normalize_value(getattr(value, f.name)) for f in fields(value)} if isinstance(value, bytes | bytearray): return base64.b64encode(bytes(value)).decode() return value def get_parameter_data_type_from_value(self, value: Any) -> ParameterDataType: """Infers ParameterDataType from a Python runtime value.""" # Matter SDK uses a special sentinel for "no value", not Python None try: if value is NullValue or isinstance(value, Nullable): value = None return ParameterDataType.none except ImportError: pass if value is None: return ParameterDataType.none # bool must be checked before int because bool is a subclass of int. if isinstance(value, bool): return ParameterDataType.bool if isinstance(value, enum.Enum): return ParameterDataType.enum if isinstance(value, int): return ParameterDataType.integer if isinstance(value, float): return ParameterDataType.decimal if isinstance(value, str): return ParameterDataType.string if isinstance(value, (bytes, bytearray, memoryview)): return ParameterDataType.data if is_dataclass(value) or isinstance(value, dict): return ParameterDataType.struct if isinstance(value, (list, tuple, set)): return ParameterDataType.struct raise ValueError( f"Cannot infer ParameterDataType for value of type {type(value)!r}: {value!r}. " f"Extend get_parameter_data_type_from_value to handle this type explicitly." ) def apply_attribute_scale(self, cluster_id: int, attribute_id: int, value: Any) -> Any: """Converts a raw Matter attribute value into ATTRIBUTE_UNITS' base unit, per ATTRIBUTE_SCALE. Unwraps the cumulative-energy struct's `energy` field before scaling, since that's the only scaled attribute whose SDK value isn't already a plain number.""" scale = ATTRIBUTE_SCALE.get(AttributeKey(cluster_id, attribute_id)) if scale is None: return value if is_dataclass(value) and hasattr(value, "energy"): value = value.energy if isinstance(value, (int, float)) and not isinstance(value, bool): # Round off float noise (2183 * 0.01 = 21.830000000000002) to the scale's decimals. return round(value * scale, max(0, -floor(log10(scale)))) return value def parse_raw_attribute(self, cluster_id: int, attribute_id: int, raw: Any) -> Any: """A subscription update is matter-server's raw JSON (a struct keyed by field id); parse it into the chip type the node holds, as MatterEndpoint.set_attribute_value does.""" attribute_class = ALL_ATTRIBUTES.get(cluster_id, {}).get(attribute_id) if attribute_class is None: return raw name, attribute_type = get_object_params(ALL_CLUSTERS[cluster_id].descriptor, attribute_id) return parse_value(name, raw, attribute_type, attribute_class().value) def attribute_value(self, cluster_id: int, attribute_id: int, value: Any) -> Any: """A raw attribute value as the Hub stores it — one path for pairing, fetch and the subscription.""" return self.normalize_value(self.apply_attribute_scale(cluster_id, attribute_id, value)) def resolve_runtime_bounds( self, key, cluster_id: int, endpoint, name: str, default_min, default_max ) -> tuple[Any, Any]: """Metadata priority 1: override a parameter's min/max with the device's own limit attributes' runtime VALUES (the *_min/*_max we hide as metadata). Falls back to the passed defaults (spec/type) when the device doesn't report a source attribute, warning so a quirk or a new device that omits an expected limit shows up in the logs.""" source = METADATA_SOURCES.get(key) if source is None: return default_min, default_max min_v, max_v = default_min, default_max for attr_id, is_min in ((source.min_attr, True), (source.max_attr, False)): if attr_id is None: continue raw = endpoint.get_attribute_value(cluster_id, attr_id) resolved = self.normalize_value(raw) if resolved is not None: if is_min: min_v = resolved else: max_v = resolved else: logging.warning( f"Metadata source cluster {cluster_id:#x} attr {attr_id:#x} " f"({'min' if is_min else 'max'} for {name!r}) not reported — quirk or unsupported; " f"using spec/type default" ) return min_v, max_v def resolve_runtime_step(self, key: AttributeKey, endpoint, default: int | float | None) -> int | float | None: """A parameter's step from the device's own step attribute (in the parameter's wire unit), else the spec's ATTRIBUTE_MIN_STEPS default.""" source = METADATA_SOURCES.get(key) if source is None or source.step_attr is None: return default raw = self.normalize_value(endpoint.get_attribute_value(key.cluster_id, source.step_attr)) return default if raw is None else self.apply_attribute_scale(key.cluster_id, key.attribute_id, raw) def get_min_max_value(self, attribute, value) -> tuple[int | None, int | None]: """ Encodes the attribute value to TLV to discover its wire type, then looks up the valid numeric range for that type from matter_spec. Returns (None, None) if the type is unknown or encoding fails. """ try: tlv_bytes = attribute.ToTLV(None, value) reader = TLVReader(tlv_bytes) reader.get() tlv_type = reader.decoding[0]["type"] return MIN_MAX_VALUE.get(tlv_type, (None, None)) except Exception: return None, None def parse_data_for_command(self, cmd_class: type, data: dict) -> dict: import enum if not is_dataclass(cmd_class): raise TypeError(f"Expected a dataclass cluster-command class, got {cmd_class!r}") hints = get_type_hints(cmd_class) result = {} for field in fields(cmd_class): if field.name not in data: continue raw = data[field.name] field_type = _unwrap_optional(hints.get(field.name, field.type)) key = (getattr(cmd_class, "cluster_id", None), getattr(cmd_class, "command_id", None), field.name) if raw is None: result[field.name] = NullValue elif isinstance(field_type, type) and issubclass(field_type, enum.Enum): result[field.name] = field_type(int(raw)) elif field_type in (bytes, bytearray): result[field.name] = _parse_bytes(raw, key in TEXT_BYTES_FIELDS) else: scaled = COMMAND_FIELD_SCALE.get(key) result[field.name] = _to_wire(raw, scaled.scale if scaled else None) return result def arguments_by_name( self, physical_id: UUID, endpoint_id: int, cluster_id: int, command_id: int, cmd_class: type, arguments: dict ) -> dict: """A struct value is keyed by sub-parameter id (see parse_commands' `fields`), while `default_arguments` are keyed by field name — accept both, keyed by name.""" if not is_dataclass(cmd_class): raise TypeError(f"Expected a dataclass cluster-command class, got {cmd_class!r}") names = { str(self.command_field_uuid(physical_id, endpoint_id, cluster_id, command_id, f.name)): f.name for f in fields(cmd_class) } return {names.get(str(key), key): value for key, value in arguments.items()} def parse_data_for_attribute(self, attribute_cls: type, raw: Any) -> Any: if raw is None: return NullValue attr_type = getattr(attribute_cls, "attribute_type", None) field_type = getattr(attr_type, "Type", None) if attr_type else None field_type = _unwrap_optional(field_type) if isinstance(field_type, type) and issubclass(field_type, enum.Enum): return field_type(int(raw)) if field_type in (bytes, bytearray): return _parse_bytes(raw, text=False) key = AttributeKey(getattr(attribute_cls, "cluster_id", -1), getattr(attribute_cls, "attribute_id", -1)) return _to_wire(raw, ATTRIBUTE_SCALE.get(key)) # ------------------------------------------------------------------------- # Node parsing: matter SDK cluster data -> MatterParameter # ------------------------------------------------------------------------- def parse_commands( self, physical_id: UUID, endpoint_id: int, cluster_id: int, cluster, node: MatterNode ) -> list[MatterParameter]: params = [] on_system_cluster = cluster_id in SYSTEM_CLUSTERS # Only process commands actually supported by this device accepted_command_ids: list[int] = node.get_attribute_value(endpoint_id, cluster_id, 0xFFF9) or [] for name, command in inspect.getmembers(cluster.Commands, inspect.isclass): if not issubclass(command, ClusterCommand): continue # Skip response commands (server→client) — only keep client→server commands if not getattr(command, "is_client", True): continue command_id = getattr(command, "command_id", -1) # Skip commands not supported by this specific device if accepted_command_ids and command_id not in accepted_command_ids: continue # Command visibility: system-cluster commands hidden; everyday one-tap actions -> # user; every other command (schedule/credential/log management) -> setting. if on_system_cluster or (cluster_id, command_id) in SYSTEM_COMMANDS: visibility = ParameterVisibility.system elif (cluster_id, command_id) in EVERYDAY_COMMANDS: visibility = ParameterVisibility.user else: visibility = ParameterVisibility.setting # Reflect on dataclass fields to build typed argument descriptors args = [] if is_dataclass(command): command_types = get_type_hints(command) for field in fields(command): if field.name.startswith("_"): continue field_type = _unwrap_optional(command_types.get(field.name, field.type)) data_type = ParameterDataType.none valid_values = None # Nested structs and lists pass through as opaque JSON (name-keyed, as # matter-server parses them into the typed argument) if is_dataclass(field_type) or get_origin(field_type) is list: data_type = ParameterDataType.data elif isinstance(field_type, type): if issubclass(field_type, enum.Enum): data_type = ParameterDataType.enum # Keys are numeric values sent to device, values are display labels valid_values = {m.value: m.name for m in field_type if "unknown" not in m.name.lower()} else: # Exact match first, then subclass fallback (e.g. custom int wrappers) matched = FIELD_TYPE_TO_DATA_TYPE.get(field_type) if matched is None: for candidate_type, mapped_type in FIELD_TYPE_TO_DATA_TYPE.items(): if issubclass(field_type, candidate_type): matched = mapped_type break if matched is not None: data_type = matched if (cluster_id, command_id, field.name) in TEXT_BYTES_FIELDS: data_type = ParameterDataType.string scaled = COMMAND_FIELD_SCALE.get((cluster_id, command_id, field.name)) if scaled is not None: data_type = ParameterDataType.decimal args.append( Parameter( id=self.command_field_uuid(physical_id, endpoint_id, cluster_id, command_id, field.name), name=field.name, data_type=data_type, min_step=scaled.scale if scaled else None, unit=scaled.unit if scaled else ParameterUnit.plain, role=ParameterRole.control, valid_values=valid_values, visibility=ParameterVisibility.setting, integration_data=None, ) ) params.append( MatterParameter( id=self.command_parameter_uuid(physical_id, endpoint_id, cluster_id, command_id), name=name, data_type=ParameterDataType.struct if args else ParameterDataType.none, role=ParameterRole.control, visibility=visibility, fields=args or None, integration_data=MatterParameterIntegrationData( endpoint_id=endpoint_id, cluster_id=cluster_id, command_id=command_id, type=MatterParameterTypeEnum.command, ), ) ) return params def parse_attributes( self, physical_id: UUID, endpoint_id: int, cluster_id: int, cluster, endpoint, node: MatterNode ) -> list[MatterParameter]: params = [] # Only process attributes actually present on this device supported_attribute_ids: list[int] = node.get_attribute_value(endpoint_id, cluster_id, 0xFFFB) or [] for name, attribute in inspect.getmembers(cluster.Attributes, inspect.isclass): if not issubclass(attribute, ClusterAttributeDescriptor): continue attribute_id = getattr(attribute, "attribute_id", -1) # Skip system-level attributes (featureMap, clusterRevision, etc.) if attribute_id in SYSTEM_ATTRIBUTES: continue # Skip attributes not present on this specific device if supported_attribute_ids and attribute_id not in supported_attribute_ids: continue raw_value = endpoint.get_attribute_value(cluster_id, attribute_id) # Visibility (see the parameter-ux recipe in the docs). System clusters and # security material are always hidden. Otherwise: writable attrs are configure-once # `setting`s unless curated as everyday controls; read-only attrs are hidden `system` # unless curated as live readings (USER_READINGS). This inverts the old # "every read-only -> user" flood — uncurated read-onlys (bounds, capabilities, counts) # stay hidden and double as metadata sources; the user can still surface any of them. key = AttributeKey(cluster_id, attribute_id) writable = bool( ChipClusters(None) .GetClusterInfoById(cluster_id) .get("attributes", {}) .get(attribute_id, {}) .get("writable") ) # Classification via the priority ladder (see the matter README): safety (system # cluster / sensitive crypto) > our hand overrides > harvested HA judgment > fallback # (writable -> setting, else system), which WARNS on uncurated attributes. spec, source = classify_attribute( cluster_id, attribute_id, name, writable=writable, in_system_cluster=cluster_id in SYSTEM_CLUSTERS, ) visibility = spec.visibility role = spec.role if spec.role is not None else (ParameterRole.control if writable else ParameterRole.sensor) if source.startswith("fallback"): logging.warning( f"Uncurated attribute cluster {cluster_id:#x} attr {attribute_id:#x} ({name}) -> " f"{visibility.value} ({source}); add to OUR_ATTRIBUTE_UX or refresh the matter-HA harvest" ) valid_values = None attr_type = attribute.attribute_type if attr_type and hasattr(attr_type, "Type") and isinstance(attr_type.Type, type): t = attr_type.Type if issubclass(t, (enum.Enum, enum.Flag)): # Keys are numeric values sent to device, values are display labels valid_values = {m.value: m.name for m in t} min_value, max_value = self.get_min_max_value(attribute, raw_value) # priority 3: wire-type range min_value, max_value = self.resolve_runtime_bounds( # priority 1: device's own limit attrs key, cluster_id, endpoint, name, min_value, max_value ) min_value = self.apply_attribute_scale(cluster_id, attribute_id, min_value) max_value = self.apply_attribute_scale(cluster_id, attribute_id, max_value) value = self.apply_attribute_scale(cluster_id, attribute_id, raw_value) try: data_type = ( ParameterDataType.data if _unwrap_optional(getattr(attr_type, "Type", None)) is bytes else self.get_parameter_data_type_from_value(self.normalize_value(value)) ) except ValueError: # Value type isn't one we know how to represent yet. Skip just this attribute # rather than aborting the whole pairing — the device stays usable, only this # one parameter is unavailable. logging.warning( f"Could not infer data type for {name} " f"(cluster {cluster_id:#x}, attribute {attribute_id:#x}); skipping parameter" ) continue params.append( MatterParameter( id=self.attribute_parameter_uuid(physical_id, endpoint_id, cluster_id, attribute_id), name=name, data_type=data_type, visibility=visibility, min_value=min_value, max_value=max_value, valid_values=valid_values, min_step=self.resolve_runtime_step(key, endpoint, ATTRIBUTE_MIN_STEPS.get(key)), # Our spec table wins; the harvested HA unit fills gaps it leaves plain. unit=ATTRIBUTE_UNITS.get(key, spec.unit or ParameterUnit.plain), role=role, integration_data=MatterParameterIntegrationData( endpoint_id=endpoint_id, cluster_id=cluster_id, attribute_id=attribute_id, type=MatterParameterTypeEnum.attribute, ), ) ) return params ================================================================================ # FILE: majordom_matter/matter_spec.py ================================================================================ from typing import Any, NamedTuple from chip.tlv import ( INT8_MAX, INT8_MIN, INT16_MAX, INT16_MIN, INT32_MAX, INT32_MIN, INT64_MAX, INT64_MIN, UINT8_MAX, UINT16_MAX, UINT32_MAX, UINT64_MAX, ) from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from .matter_spec_ha import MATTER_HA_ATTRIBUTE_UX SYSTEM_CLUSTERS: set[int] = { 0x3, # Identify 0x4, # Groups 0x5, # Scenes 0x1D, # Descriptor 0x1E, # Binding 0x1F, # AccessControl 0x25, # Actions 0x28, # BasicInformation 0x29, # OtaSoftwareUpdateProvider 0x2A, # OtaSoftwareUpdateRequestor 0x2B, # LocalizationConfiguration 0x2C, # TimeFormatLocalization 0x2D, # UnitLocalization 0x2E, # PowerSourceConfiguration 0x9C, # PowerTopology 0x30, # GeneralCommissioning 0x31, # NetworkCommissioning 0x32, # DiagnosticLogs 0x33, # GeneralDiagnostics 0x34, # SoftwareDiagnostics 0x35, # ThreadNetworkDiagnostics 0x36, # WiFiNetworkDiagnostics 0x37, # EthernetNetworkDiagnostics 0x38, # TimeSynchronization 0x3C, # AdministratorCommissioning 0x3E, # OperationalCredentials 0x3F, # GroupKeyManagement 0x40, # FixedLabel 0x41, # UserLabel 0x62, # ScenesManagement 0x46, # IcdManagement 0x451, # WiFiNetworkManagement 0x452, # ThreadBorderRouterManagement 0x453, # ThreadNetworkDirectory 0x752, # JointFabricDatastore 0x753, # JointFabricAdministrator 0x801, # TlsCertificateManagement 0x802, # TlsClientManagement 0xFFF1FC05, # UnitTesting } # Commands hidden on otherwise user-facing clusters. SYSTEM_COMMANDS: set[tuple[int, int]] = { (0x101, 0x28), # DoorLock.SetAliroReaderConfig (Aliro crypto material, like the Aliro* attributes) (0x101, 0x29), # DoorLock.ClearAliroReaderConfig } SYSTEM_ATTRIBUTES: set[int] = { 0x0000FFF8, # generatedCommandList 0x0000FFF9, # acceptedCommandList 0x0000FFFA, # eventList 0x0000FFFB, # attributeList 0x0000FFFC, # featureMap 0x0000FFFD, # clusterRevision } class ValueRange(NamedTuple): min: int max: int MIN_MAX_VALUE: dict[str, ValueRange] = { "Unsigned Integer 1-byte value": ValueRange(0, UINT8_MAX), "Unsigned Integer 2-byte value": ValueRange(0, UINT16_MAX), "Unsigned Integer 4-byte value": ValueRange(0, UINT32_MAX), "Unsigned Integer 8-byte value": ValueRange(0, UINT64_MAX), "Signed Integer 1-byte value": ValueRange(INT8_MIN, INT8_MAX), "Signed Integer 2-byte value": ValueRange(INT16_MIN, INT16_MAX), "Signed Integer 4-byte value": ValueRange(INT32_MIN, INT32_MAX), "Signed Integer 8-byte value": ValueRange(INT64_MIN, INT64_MAX), } class AttributeKey(NamedTuple): """Identifies a single attribute on a cluster — the shared dict key shape for ATTRIBUTE_UNITS / ATTRIBUTE_SCALE / ATTRIBUTE_MIN_STEPS below.""" cluster_id: int attribute_id: int ATTRIBUTE_UNITS: dict[AttributeKey, ParameterUnit] = { AttributeKey(0x8, 0x0): ParameterUnit.percentage, # LevelControl.CurrentLevel AttributeKey(0x102, 0x8): ParameterUnit.percentage, # WindowCovering.LiftPercentage AttributeKey(0x102, 0x9): ParameterUnit.percentage, # WindowCovering.TiltPercentage AttributeKey(0x201, 0x0): ParameterUnit.celsius, # Thermostat.LocalTemperature AttributeKey(0x201, 0x11): ParameterUnit.celsius, # Thermostat.OccupiedCoolingSetpoint AttributeKey(0x201, 0x12): ParameterUnit.celsius, # Thermostat.OccupiedHeatingSetpoint AttributeKey(0x202, 0x2): ParameterUnit.percentage, # FanControl.PercentSetting AttributeKey(0x202, 0x3): ParameterUnit.percentage, # FanControl.PercentCurrent AttributeKey( 0x300, 0x0 ): ParameterUnit.arcdegree, # ColorControl.CurrentHue (raw 0-254, degrees = value * 360 / 254) AttributeKey(0x300, 0x1): ParameterUnit.percentage, # ColorControl.CurrentSaturation AttributeKey(0x300, 0x7): ParameterUnit.mired, # ColorControl.ColorTemperatureMireds AttributeKey(0x404, 0x0): ParameterUnit.m3h, # FlowMeasurement.MeasuredValue (deci-m3/h, see scale) AttributeKey(0x400, 0x0): ParameterUnit.lux, # IlluminanceMeasurement.MeasuredValue AttributeKey(0x402, 0x0): ParameterUnit.celsius, # TemperatureMeasurement.MeasuredValue AttributeKey(0x405, 0x0): ParameterUnit.percentage, # RelativeHumidityMeasurement.MeasuredValue AttributeKey(0x40C, 0x0): ParameterUnit.ppm, # CarbonMonoxideMeasurement.MeasuredValue AttributeKey(0x40D, 0x0): ParameterUnit.ppm, # CarbonDioxideMeasurement.MeasuredValue # Pm25Measurement.MeasuredValue: unit is device-configured (mass or molar concentration, # via the cluster's MeasurementUnit attribute) — not necessarily ppm. Left unmapped # (defaults to plain) rather than asserting a possibly-wrong unit. AttributeKey(0x56, 0x0): ParameterUnit.celsius, # TemperatureControl.TemperatureSetpoint AttributeKey(0x90, 0x8): ParameterUnit.watt, # ElectricalPowerMeasurement.ActivePower (raw mW, see ATTRIBUTE_SCALE) AttributeKey(0x90, 0x4): ParameterUnit.volt, # ElectricalPowerMeasurement.Voltage (raw mV, see ATTRIBUTE_SCALE) AttributeKey( 0x90, 0x5 ): ParameterUnit.ampere, # ElectricalPowerMeasurement.ActiveCurrent (raw mA, see ATTRIBUTE_SCALE) AttributeKey( 0x91, 0x1, # ElectricalEnergyMeasurement.CumulativeEnergyImported (struct; .energy in mWh, see ATTRIBUTE_SCALE) ): ParameterUnit.kwh, AttributeKey( 0x403, 0x0 ): ParameterUnit.pascal, # PressureMeasurement.MeasuredValue (raw deci-kPa, see ATTRIBUTE_SCALE) AttributeKey(0x2F, 0xC): ParameterUnit.percentage, # PowerSource.BatPercentRemaining # The remaining temperatures (scaled below); Outdoor/Calibration/OccupiedSetback get celsius from the HA harvest. AttributeKey(0x201, 0x3): ParameterUnit.celsius, # Thermostat.AbsMinHeatSetpointLimit AttributeKey(0x201, 0x4): ParameterUnit.celsius, # Thermostat.AbsMaxHeatSetpointLimit AttributeKey(0x201, 0x5): ParameterUnit.celsius, # Thermostat.AbsMinCoolSetpointLimit AttributeKey(0x201, 0x6): ParameterUnit.celsius, # Thermostat.AbsMaxCoolSetpointLimit AttributeKey(0x201, 0x13): ParameterUnit.celsius, # Thermostat.UnoccupiedCoolingSetpoint AttributeKey(0x201, 0x14): ParameterUnit.celsius, # Thermostat.UnoccupiedHeatingSetpoint AttributeKey(0x201, 0x15): ParameterUnit.celsius, # Thermostat.MinHeatSetpointLimit AttributeKey(0x201, 0x16): ParameterUnit.celsius, # Thermostat.MaxHeatSetpointLimit AttributeKey(0x201, 0x17): ParameterUnit.celsius, # Thermostat.MinCoolSetpointLimit AttributeKey(0x201, 0x18): ParameterUnit.celsius, # Thermostat.MaxCoolSetpointLimit AttributeKey(0x201, 0x19): ParameterUnit.celsius, # Thermostat.MinSetpointDeadBand AttributeKey(0x201, 0x31): ParameterUnit.celsius, # Thermostat.SetpointChangeAmount AttributeKey(0x201, 0x35): ParameterUnit.celsius, # Thermostat.OccupiedSetbackMin AttributeKey(0x201, 0x36): ParameterUnit.celsius, # Thermostat.OccupiedSetbackMax AttributeKey(0x201, 0x37): ParameterUnit.celsius, # Thermostat.UnoccupiedSetback AttributeKey(0x201, 0x38): ParameterUnit.celsius, # Thermostat.UnoccupiedSetbackMin AttributeKey(0x201, 0x39): ParameterUnit.celsius, # Thermostat.UnoccupiedSetbackMax AttributeKey(0x201, 0x3A): ParameterUnit.celsius, # Thermostat.EmergencyHeatDelta AttributeKey(0x201, 0x46): ParameterUnit.celsius, # Thermostat.ACCoilTemperature AttributeKey(0x56, 0x1): ParameterUnit.celsius, # TemperatureControl.MinTemperature AttributeKey(0x56, 0x2): ParameterUnit.celsius, # TemperatureControl.MaxTemperature AttributeKey(0x56, 0x3): ParameterUnit.celsius, # TemperatureControl.Step AttributeKey(0x402, 0x1): ParameterUnit.celsius, # TemperatureMeasurement.MinMeasuredValue AttributeKey(0x402, 0x2): ParameterUnit.celsius, # TemperatureMeasurement.MaxMeasuredValue AttributeKey(0x402, 0x3): ParameterUnit.celsius, # TemperatureMeasurement.Tolerance } # Multiplier applied to a raw attribute value to convert it into ATTRIBUTE_UNITS' base unit # (e.g. Matter reports power in mW; watt is the base unit, so scale = 0.001). ATTRIBUTE_SCALE: dict[AttributeKey, float] = { AttributeKey(0x90, 0x8): 0.001, # ElectricalPowerMeasurement.ActivePower: mW -> W AttributeKey(0x90, 0x4): 0.001, # ElectricalPowerMeasurement.Voltage: mV -> V AttributeKey(0x90, 0x5): 0.001, # ElectricalPowerMeasurement.ActiveCurrent: mA -> A AttributeKey(0x91, 0x1): 1e-6, # ElectricalEnergyMeasurement.CumulativeEnergyImported: mWh -> kWh AttributeKey(0x404, 0x0): 0.1, # FlowMeasurement.MeasuredValue: deci-m3/h -> m3/h AttributeKey(0x403, 0x0): 100, # PressureMeasurement.MeasuredValue: deci-kPa -> Pa # Matter's int16 temperatures are 0.01 °C; the 8-bit Signed/UnsignedTemperature ones are 0.1 °C. AttributeKey(0x201, 0x0): 0.01, # Thermostat.LocalTemperature AttributeKey(0x201, 0x1): 0.01, # Thermostat.OutdoorTemperature AttributeKey(0x201, 0x3): 0.01, # Thermostat.AbsMinHeatSetpointLimit AttributeKey(0x201, 0x4): 0.01, # Thermostat.AbsMaxHeatSetpointLimit AttributeKey(0x201, 0x5): 0.01, # Thermostat.AbsMinCoolSetpointLimit AttributeKey(0x201, 0x6): 0.01, # Thermostat.AbsMaxCoolSetpointLimit AttributeKey(0x201, 0x10): 0.1, # Thermostat.LocalTemperatureCalibration (int8) AttributeKey(0x201, 0x11): 0.01, # Thermostat.OccupiedCoolingSetpoint AttributeKey(0x201, 0x12): 0.01, # Thermostat.OccupiedHeatingSetpoint AttributeKey(0x201, 0x13): 0.01, # Thermostat.UnoccupiedCoolingSetpoint AttributeKey(0x201, 0x14): 0.01, # Thermostat.UnoccupiedHeatingSetpoint AttributeKey(0x201, 0x15): 0.01, # Thermostat.MinHeatSetpointLimit AttributeKey(0x201, 0x16): 0.01, # Thermostat.MaxHeatSetpointLimit AttributeKey(0x201, 0x17): 0.01, # Thermostat.MinCoolSetpointLimit AttributeKey(0x201, 0x18): 0.01, # Thermostat.MaxCoolSetpointLimit AttributeKey(0x201, 0x19): 0.1, # Thermostat.MinSetpointDeadBand (int8) AttributeKey(0x201, 0x31): 0.01, # Thermostat.SetpointChangeAmount (TemperatureDifference) AttributeKey(0x201, 0x34): 0.1, # Thermostat.OccupiedSetback (uint8) AttributeKey(0x201, 0x35): 0.1, # Thermostat.OccupiedSetbackMin (uint8) AttributeKey(0x201, 0x36): 0.1, # Thermostat.OccupiedSetbackMax (uint8) AttributeKey(0x201, 0x37): 0.1, # Thermostat.UnoccupiedSetback (uint8) AttributeKey(0x201, 0x38): 0.1, # Thermostat.UnoccupiedSetbackMin (uint8) AttributeKey(0x201, 0x39): 0.1, # Thermostat.UnoccupiedSetbackMax (uint8) AttributeKey(0x201, 0x3A): 0.1, # Thermostat.EmergencyHeatDelta (uint8) AttributeKey(0x201, 0x46): 0.01, # Thermostat.ACCoilTemperature AttributeKey(0x56, 0x0): 0.01, # TemperatureControl.TemperatureSetpoint AttributeKey(0x56, 0x1): 0.01, # TemperatureControl.MinTemperature AttributeKey(0x56, 0x2): 0.01, # TemperatureControl.MaxTemperature AttributeKey(0x56, 0x3): 0.01, # TemperatureControl.Step AttributeKey(0x402, 0x0): 0.01, # TemperatureMeasurement.MeasuredValue AttributeKey(0x402, 0x1): 0.01, # TemperatureMeasurement.MinMeasuredValue AttributeKey(0x402, 0x2): 0.01, # TemperatureMeasurement.MaxMeasuredValue AttributeKey(0x402, 0x3): 0.01, # TemperatureMeasurement.Tolerance } ATTRIBUTE_MIN_STEPS: dict[AttributeKey, int | float] = { AttributeKey(0x0008, 0x0000): 1, # CurrentLevel (uint8, 0-254) AttributeKey(0x0300, 0x0000): 1, # CurrentHue (verified: id 0x0000, uint8, step 1) AttributeKey(0x0300, 0x0001): 1, # CurrentSaturation (verified: id 0x0001, uint8, step 1) AttributeKey(0x0300, 0x0007): 1, # ColorTemperatureMireds (verified: id 0x0007, uint16, step 1) AttributeKey(0x0201, 0x0010): 0.1, # LocalTemperatureCalibration (SignedTemperature, -2.5°C to 2.5°C) AttributeKey(0x0201, 0x0011): 0.01, # OccupiedCoolingSetpoint (temperature type, 0.01°C resolution) AttributeKey(0x0201, 0x0012): 0.01, # OccupiedHeatingSetpoint (temperature type, 0.01°C resolution) AttributeKey(0x0201, 0x0013): 0.01, # UnoccupiedCoolingSetpoint (temperature type, 0.01°C resolution) AttributeKey(0x0201, 0x0014): 0.01, # UnoccupiedHeatingSetpoint (temperature type, 0.01°C resolution) AttributeKey(0x0201, 0x0015): 0.01, # MinHeatSetpointLimit (temperature type, 0.01°C resolution) AttributeKey(0x0201, 0x0016): 0.01, # MaxHeatSetpointLimit (temperature type, 0.01°C resolution) AttributeKey(0x0201, 0x0017): 0.01, # MinCoolSetpointLimit (temperature type, 0.01°C resolution) AttributeKey(0x0201, 0x0018): 0.01, # MaxCoolSetpointLimit (temperature type, 0.01°C resolution) AttributeKey(0x0201, 0x0019): 0.1, # MinSetpointDeadBand (SignedTemperature, 0.1°C resolution) AttributeKey(0x0201, 0x0034): 0.1, # OccupiedSetback (UnsignedTemperature, 0.1°C resolution) AttributeKey(0x0201, 0x0037): 0.1, # UnoccupiedSetback (UnsignedTemperature, 0.1°C resolution) AttributeKey( 0x0056, 0x0000 ): 0.01, # TemperatureSetpoint (temperature type; the device's Step wins, see METADATA_SOURCES) AttributeKey(0x0402, 0x0000): 0.01, # MeasuredValue (temperature type, 0.01°C resolution) AttributeKey(0x0405, 0x0000): 0.01, # MeasuredValue (0.01% resolution) AttributeKey(0x0403, 0x0000): 10, # MeasuredValue (raw step 0.1 deci-kPa, scaled x100 to Pa -> 10 Pa) AttributeKey(0x0102, 0x0008): 1, # CurrentPositionLiftPercentage (plain percent 0-100, not Percent100ths) AttributeKey(0x0102, 0x0009): 1, # CurrentPositionTiltPercentage (plain percent 0-100, not Percent100ths) AttributeKey(0x0102, 0x000B): 0.01, # TargetPositionLiftPercent100ths (percent100ths, 0.01%) AttributeKey(0x0102, 0x000C): 0.01, # TargetPositionTiltPercent100ths (percent100ths, 0.01%) } class MetadataSource(NamedTuple): """Sibling attributes whose runtime VALUES provide a parameter's min/max/step — the device's own limit attributes (the ones we hide from the UI as metadata). Priority 1 in the resolver: runtime sibling value > spec table > wire-type default.""" min_attr: int | None = None max_attr: int | None = None step_attr: int | None = None METADATA_SOURCES: dict[AttributeKey, MetadataSource] = { AttributeKey(0x008, 0x00): MetadataSource(0x02, 0x03), # LevelControl.CurrentLevel <- Min/MaxLevel AttributeKey(0x402, 0x00): MetadataSource(0x01, 0x02), # TemperatureMeasurement <- Min/MaxMeasuredValue AttributeKey(0x405, 0x00): MetadataSource(0x01, 0x02), # RelativeHumidity <- Min/MaxMeasuredValue AttributeKey(0x400, 0x00): MetadataSource(0x01, 0x02), # Illuminance <- Min/MaxMeasuredValue AttributeKey(0x403, 0x00): MetadataSource(0x01, 0x02), # Pressure <- Min/MaxMeasuredValue AttributeKey(0x404, 0x00): MetadataSource(0x01, 0x02), # Flow <- Min/MaxMeasuredValue AttributeKey(0x201, 0x11): MetadataSource(0x05, 0x06), # OccupiedCoolingSetpoint <- AbsMin/MaxCoolSetpointLimit AttributeKey(0x201, 0x12): MetadataSource(0x03, 0x04), # OccupiedHeatingSetpoint <- AbsMin/MaxHeatSetpointLimit AttributeKey(0x300, 0x07): MetadataSource(0x400B, 0x400C), # ColorTemperatureMireds <- physical min/max mireds AttributeKey(0x056, 0x00): MetadataSource(0x01, 0x02, 0x03), # TemperatureSetpoint <- Min/MaxTemperature, Step } FIELD_TYPE_TO_DATA_TYPE: dict[type, ParameterDataType] = { bool: ParameterDataType.bool, int: ParameterDataType.integer, float: ParameterDataType.decimal, str: ParameterDataType.string, bytes: ParameterDataType.data, } class ScaledField(NamedTuple): """A command field sent in a scaled wire unit, like ATTRIBUTE_SCALE: the user enters (and default_params give) `unit`; the wire value is that divided by `scale`.""" unit: ParameterUnit scale: float COMMAND_FIELD_SCALE: dict[tuple[int, int, str], ScaledField] = { (0x56, 0x0, "targetTemperature"): ScaledField(ParameterUnit.celsius, 0.01), # TemperatureControl.SetTemperature (0x201, 0x0, "amount"): ScaledField(ParameterUnit.celsius, 0.1), # Thermostat.SetpointRaiseLower } # `bytes` command fields the user types as text: a UTF-8 `string` instead of base64 `data`. TEXT_BYTES_FIELDS: set[tuple[int, int, str]] = { (0x101, 0x00, "PINCode"), # DoorLock.LockDoor (0x101, 0x01, "PINCode"), # DoorLock.UnlockDoor (0x101, 0x03, "PINCode"), # DoorLock.UnlockWithTimeout (0x101, 0x27, "PINCode"), # DoorLock.UnboltDoor (0x101, 0x22, "credentialData"), # DoorLock.SetCredential (a PIN; RFID/biometrics are enrolled at the lock) (0x802, 0x00, "hostname"), # TlsClientManagement.ProvisionEndpoint } # --- Visibility curation (see docs/device-integration/parameter-ux recipe) ------------ # The mapper defaults a read-only attribute to `system` (hidden) and only promotes it to `user` # if it's an explicitly curated live reading (USER_READINGS). Writable attributes default to # `setting`, promoted to `user` only if they're an everyday control (EVERYDAY_CONTROL_ATTRIBUTES). # This inverts the old "every read-only -> user" flood; anything not curated stays hidden and can # be surfaced by the user, or added here. Bounds/capabilities/counts fall through to `system` and # double as metadata sources (see ATTRIBUTE_MIN_STEPS / min-max resolution). # Writable attributes that are everyday, main-surface controls (-> user) rather than # configure-once settings. EVERYDAY_CONTROL_ATTRIBUTES: set[AttributeKey] = { AttributeKey(0x202, 0x0), # FanControl.FanMode (off/low/med/high/auto) AttributeKey(0x202, 0x2), # FanControl.PercentSetting AttributeKey(0x202, 0x5), # FanControl.SpeedSetting AttributeKey(0x201, 0x1C), # Thermostat.SystemMode (off/heat/cool/auto) AttributeKey(0x201, 0x11), # Thermostat.OccupiedCoolingSetpoint (the everyday "set the temp") AttributeKey(0x201, 0x12), # Thermostat.OccupiedHeatingSetpoint AttributeKey(0x056, 0x00), # TemperatureControl.TemperatureSetpoint } # Read-only attributes that ARE the live, everyday reading for their cluster (-> user). Anything # read-only and NOT listed here stays `system` (bounds, capabilities, counts, diagnostics). USER_READINGS: set[AttributeKey] = { AttributeKey(0x006, 0x00), # OnOff.OnOff AttributeKey(0x008, 0x00), # LevelControl.CurrentLevel AttributeKey(0x300, 0x00), # ColorControl.CurrentHue (human color model) AttributeKey(0x300, 0x01), # ColorControl.CurrentSaturation AttributeKey(0x300, 0x07), # ColorControl.ColorTemperatureMireds # CurrentX/CurrentY (0x03/0x04) are the CIE machine encoding of the same colour -> system # (redundant with hue/sat for the user; still available to patch to user if wanted). AttributeKey(0x201, 0x00), # Thermostat.LocalTemperature AttributeKey(0x202, 0x03), # FanControl.PercentCurrent AttributeKey(0x202, 0x06), # FanControl.SpeedCurrent (0x04 is SpeedMax, a bound -> stays system) AttributeKey(0x402, 0x00), # TemperatureMeasurement.MeasuredValue AttributeKey(0x405, 0x00), # RelativeHumidityMeasurement.MeasuredValue AttributeKey(0x400, 0x00), # IlluminanceMeasurement.MeasuredValue AttributeKey(0x403, 0x00), # PressureMeasurement.MeasuredValue AttributeKey(0x404, 0x00), # FlowMeasurement.MeasuredValue AttributeKey(0x406, 0x00), # OccupancySensing.Occupancy AttributeKey(0x045, 0x00), # BooleanState.StateValue (contact/water leak) AttributeKey(0x40C, 0x00), # CarbonMonoxideConcentrationMeasurement.MeasuredValue AttributeKey(0x40D, 0x00), # CarbonDioxideConcentrationMeasurement.MeasuredValue AttributeKey(0x42A, 0x00), # Pm25ConcentrationMeasurement.MeasuredValue AttributeKey(0x101, 0x00), # DoorLock.LockState AttributeKey(0x101, 0x03), # DoorLock.DoorState AttributeKey(0x102, 0x08), # WindowCovering.CurrentPositionLiftPercentage AttributeKey(0x102, 0x09), # WindowCovering.CurrentPositionTiltPercentage AttributeKey(0x02F, 0x0C), # PowerSource.BatPercentRemaining AttributeKey(0x02F, 0x0E), # PowerSource.BatChargeLevel AttributeKey(0x060, 0x04), # OperationalState.OperationalState AttributeKey(0x061, 0x04), # RvcOperationalState.OperationalState AttributeKey(0x05C, 0x00), # SmokeCoAlarm.ExpressedState AttributeKey(0x05C, 0x01), # SmokeCoAlarm.SmokeState AttributeKey(0x05C, 0x02), # SmokeCoAlarm.COState AttributeKey(0x050, 0x03), # ModeSelect.CurrentMode # Energy metering readings (the primaries; min/max/overload/phase variants stay system) AttributeKey(0x090, 0x04), # ElectricalPowerMeasurement.Voltage AttributeKey(0x090, 0x05), # ElectricalPowerMeasurement.ActiveCurrent AttributeKey(0x090, 0x08), # ElectricalPowerMeasurement.ActivePower AttributeKey(0x091, 0x01), # ElectricalEnergyMeasurement.CumulativeEnergyImported } # Attribute-name prefixes that carry security material and must never be shown to the user # (-> system regardless of role). Matter DoorLock's Aliro* attributes are cryptographic keys / # identifiers that the current "read-only -> user" rule was leaking straight into the tap-view. SENSITIVE_ATTRIBUTE_NAME_PREFIXES: tuple[str, ...] = ("Aliro",) # Commands that are everyday one-tap actions (-> user). Every other command on a non-system # cluster defaults to `setting` — advanced management (schedules, credentials, logs, calibration). EVERYDAY_COMMANDS: set[tuple[int, int]] = { (0x006, 0x0), (0x006, 0x1), (0x006, 0x2), # OnOff Off / On / Toggle (0x008, 0x0), (0x008, 0x4), # LevelControl MoveToLevel / MoveToLevelWithOnOff (0x300, 0x0), (0x300, 0x3), (0x300, 0x6), (0x300, 0x7), (0x300, 0xA), # ColorControl hue/sat/hue+sat/color/temp (0x102, 0x0), (0x102, 0x1), (0x102, 0x2), (0x102, 0x5), # WindowCovering up / down / stop / goToLift% (0x101, 0x0), (0x101, 0x1), # DoorLock Lock / Unlock (credential/schedule cmds stay setting) (0x201, 0x0), # Thermostat SetpointRaiseLower (0x056, 0x0), # TemperatureControl SetTemperature (0x060, 0x0), (0x060, 0x1), (0x060, 0x2), (0x060, 0x3), # OperationalState Pause/Stop/Start/Resume (0x061, 0x0), (0x061, 0x3), # RvcOperationalState Pause / Resume (0x050, 0x0), # ModeSelect ChangeToMode (0x506, 0x0), (0x506, 0x1), (0x506, 0x2), # MediaPlayback Play / Pause / Stop (0x104, 0x0), (0x104, 0x1), # ClosureControl Stop / MoveTo (0x556, 0x0), # Chime PlayChimeSound (0x081, 0x0), (0x081, 0x1), # ValveConfigurationAndControl Open / Close } # Read-only state attributes a main-parameter tap sets through a command: the attribute's # `default_value` is a two-value cycle, the Hub sends the next value, and the controller sends the # command for it. They are `control` (the Hub forwards commands for control parameters only). # A state outside the cycle taps to the cycle's first (lowest) value — the safer direction. STATE_TOGGLE_COMMANDS: dict[AttributeKey, dict[int, int]] = { AttributeKey(0x101, 0x0): {1: 0x00, 2: 0x01}, # DoorLock.LockState Locked→LockDoor, Unlocked→UnlockDoor AttributeKey(0x081, 0x4): {0: 0x01, 1: 0x00}, # Valve.CurrentState Closed→Close, Open→Open AttributeKey(0x102, 0x8): {0: 0x00, 100: 0x01}, # WindowCovering.LiftPercentage 0→UpOrOpen, 100→DownOrClose AttributeKey(0x506, 0x0): {0: 0x00, 1: 0x01}, # MediaPlayback.CurrentState Playing→Play, Paused→Pause AttributeKey(0x061, 0x4): {1: 0x03, 2: 0x00}, # RvcOperationalState Running→Resume, Paused→Pause AttributeKey(0x060, 0x4): {1: 0x03, 2: 0x00}, # OperationalState Running→Resume, Paused→Pause } # ClosureControl.MainState: a struct position can't cycle, so it's a one-value button and the # controller picks Stop / MoveTo from the current state (see MatterController._state_toggle_command). CLOSURE_MAIN_STATE = AttributeKey(0x104, 0x1) STATE_TOGGLE_ATTRIBUTES: set[AttributeKey] = {*STATE_TOGGLE_COMMANDS, CLOSURE_MAIN_STATE} # Arguments to send along with a main-parameter command/attribute when the parameter itself # doesn't carry an obvious "activate" value (e.g. a mode/setpoint command). None means the # command takes no arguments; for an attribute main parameter it's the `default_value`: an int is # a one-value button, a set a tap cycle. DefaultParams = dict[str, Any] | int | set[int] | None class MainParameterSpec(NamedTuple): """Value of MAIN_PARAMETER_BY_CLUSTER, keyed by cluster_id: which command (or, with `is_attribute`, attribute) makes a sensible main_parameter for that cluster, and what default_params to send with it if the parameter has no obvious "activate" value. Iteration order is priority order — the first cluster below that's present on the device wins. `fallback` is tried when the device lacks this one (an optional attribute or command).""" command_or_attribute_id: int default_params: DefaultParams is_attribute: bool = False fallback: "MainParameterSpec | None" = None MAIN_PARAMETER_BY_CLUSTER: dict[int, MainParameterSpec] = { 0x00000006: MainParameterSpec(0x00000002, None), # OnOff.Toggle # Thermostat intentionally has NO one-tap: "raise or lower?" isn't a sensible tile action — # tapping a thermostat should open its screen, not nudge a setpoint blind. 0x00000202: MainParameterSpec(0x00000000, {0x00, 0x04}, is_attribute=True), # FanControl.FanMode Off↔On 0x00000056: MainParameterSpec( 0x00000000, {"targetTemperature": 22}, # °C, see COMMAND_FIELD_SCALE # TemperatureControl.SetTemperature (targetTemperature/targetTemperatureLevel are # feature-gated & mutually exclusive; targetTemperature covers the common "TN" case) ), # OperationalState pauses/resumes a running cycle and never Starts one from idle (an oven or a # microwave must not start in one tap); without Pause/Resume there's no main parameter. 0x00000060: MainParameterSpec(0x00000004, {1, 2}, is_attribute=True), # OperationalState Running↔Paused 0x00000061: MainParameterSpec( 0x00000004, {1, 2}, is_attribute=True, fallback=MainParameterSpec(0x00000003, None), # RVCOperationalState.Resume ), # RvcOperationalState Running↔Paused # Unverified: OperationalState.Start wins on a Microwave Oven anyway; to verify on real devices. # 0x0000005F: MainParameterSpec(0x00000001, {"timeToAdd": 30}), # MicrowaveOvenControl.AddMoreTime 0x00000050: MainParameterSpec(0x00000000, {"newMode": 0}), # ModeSelect.ChangeToMode 0x00000101: MainParameterSpec(0x00000000, {1, 2}, is_attribute=True), # DoorLock.LockState Locked↔Unlocked # 0x0000005C: MainParameterSpec(0x00000000, None), # SmokeCoAlarm.SelfTestRequest 0x00000506: MainParameterSpec( 0x00000000, {0, 1}, is_attribute=True, fallback=MainParameterSpec(0x00000000, None), # MediaPlayback.Play ), # MediaPlayback.CurrentState Playing↔Paused # Unverified: a raw remote-key sender, shadowed by OnOff/MediaPlayback; to verify on real devices. # 0x00000509: MainParameterSpec(0x00000000, {"keyCode": 0x44}), # KeyPadInpud.SendKey.Play 0x00000102: MainParameterSpec( 0x00000008, {0, 100}, is_attribute=True, # WindowCovering.UpOrOpen — a cover without position awareness keeps the one-way open; # StopMotion (0x02) only matters mid-motion, so it's not the primary action fallback=MainParameterSpec(0x00000000, None), ), # WindowCovering.CurrentPositionLiftPercentage open↔closed # ClosureControl.MainState, a one-value button (Moving): MoveTo FullyClosed unless closed, # else FullyOpen; Stop while moving (see STATE_TOGGLE_ATTRIBUTES) 0x00000104: MainParameterSpec(0x00000001, 1, is_attribute=True), # Unverified: one-way (EnableCharging needs current limits) and stops a car charge; to verify on real devices. # 0x00000099: MainParameterSpec(0x00000001, None), # EnergyEvse.Disable # Unverified: mode 0 is vendor-defined and may not exist; to verify on real devices. # 0x0000009E: MainParameterSpec(0x00000000, {"newMode": 0}), # WaterHeaterMode.ChangeToMode # Unverified: needs a WebRTC requestor session on the hub; to verify on real devices. # 0x00000553: MainParameterSpec( # 0x00000000, {"streamUsage": 0, "originatingEndpointID": 0} # ), # WebRTCTransportProvider.SolicitOffer 0x00000556: MainParameterSpec(0x00000000, None), # Chime.PlayChimeSound 0x00000081: MainParameterSpec(0x00000004, {0, 1}, is_attribute=True), # Valve.CurrentState Closed↔Open } # --- Merged UX classification ladder (mirror of the zigbee integration; see the matter README) --- # Matter has no runtime quirk layer, so the ladder is: our hand overrides > harvested HA judgment > # fallback. Safety rules (system cluster, sensitive crypto material) are forced hidden on top. class UxSpec(NamedTuple): visibility: ParameterVisibility role: ParameterRole | None = None unit: ParameterUnit | None = None def _our_attribute_ux() -> dict[AttributeKey, UxSpec]: out: dict[AttributeKey, UxSpec] = {} for key in USER_READINGS: out[key] = UxSpec(ParameterVisibility.user, ParameterRole.sensor) for key in EVERYDAY_CONTROL_ATTRIBUTES | STATE_TOGGLE_ATTRIBUTES: out[key] = UxSpec(ParameterVisibility.user, ParameterRole.control) return out OUR_ATTRIBUTE_UX: dict[AttributeKey, UxSpec] = _our_attribute_ux() def _ha_uxspec(key: AttributeKey) -> UxSpec | None: t = MATTER_HA_ATTRIBUTE_UX.get((key.cluster_id, key.attribute_id)) if t is None: return None return UxSpec(ParameterVisibility(t[0]), ParameterRole(t[1]), ParameterUnit(t[2])) # Flip once harvested coverage is validated on real devices: unmatched writable attrs then hide # (system) instead of defaulting to a settings toggle. See the matter README (fallback). _FALLBACK_HIDE_UNCURATED = False def classify_attribute( cluster_id: int, attribute_id: int, name: str, *, writable: bool, in_system_cluster: bool, ) -> tuple[UxSpec, str]: """Resolve an attribute's (visibility, role, unit) by the priority ladder, returning the spec and a source tag. First match wins: - system cluster / sensitive crypto material -> system (safety, top priority) 1. OUR_ATTRIBUTE_UX — hand curation 2. MATTER_HA_ATTRIBUTE_UX — harvested HA entity judgment 3. fallback policy — writable -> setting, else system; WARNS (uncurated) """ if in_system_cluster: return UxSpec(ParameterVisibility.system), "system-cluster" if name.startswith(SENSITIVE_ATTRIBUTE_NAME_PREFIXES): return UxSpec(ParameterVisibility.system), "sensitive" key = AttributeKey(cluster_id, attribute_id) if (spec := OUR_ATTRIBUTE_UX.get(key)) is not None: return spec, "ours" if (spec := _ha_uxspec(key)) is not None: return spec, "ha" if not _FALLBACK_HIDE_UNCURATED and writable: return UxSpec(ParameterVisibility.setting, ParameterRole.control), "fallback-writable" return UxSpec(ParameterVisibility.system), "fallback-system" ================================================================================ # FILE: majordom_matter/matter_spec_ha.py ================================================================================ """GENERATED by scripts/harvest_matter_ha.py — DO NOT EDIT BY HAND. Source: home-assistant/core@dev homeassistant/components/matter (Apache-2.0), parsed via AST (no homeassistant dependency). Attribute ids resolved via chip. Harvested entity judgment only (entity_category -> visibility, platform -> role, unit); the Matter Data Model supplies names/types/bounds. Hand overrides live in matter_spec.py and win on merge. """ # (cluster_id, attribute_id) -> (visibility, role, unit) MATTER_HA_ATTRIBUTE_UX: dict[tuple[int, int], tuple[str, str, str]] = { (0x0003, 0x0001): ("setting", "control", "plain"), (0x0006, 0x0000): ("user", "control", "plain"), (0x0006, 0x4003): ("setting", "control", "plain"), (0x0008, 0x0000): ("user", "control", "percentage"), (0x0008, 0x0010): ("setting", "control", "plain"), (0x0008, 0x0011): ("setting", "control", "plain"), (0x0008, 0x0012): ("setting", "control", "plain"), (0x0008, 0x0013): ("setting", "control", "plain"), (0x0008, 0x4000): ("setting", "control", "plain"), (0x002F, 0x000B): ("setting", "sensor", "volt"), (0x002F, 0x000C): ("setting", "sensor", "percentage"), (0x002F, 0x000D): ("setting", "sensor", "plain"), (0x002F, 0x000E): ("setting", "sensor", "percentage"), (0x002F, 0x0013): ("setting", "sensor", "plain"), (0x002F, 0x001A): ("setting", "sensor", "plain"), (0x002F, 0x001B): ("setting", "sensor", "plain"), (0x0033, 0x0001): ("setting", "sensor", "plain"), (0x0033, 0x0002): ("setting", "sensor", "plain"), (0x0033, 0x0004): ("setting", "sensor", "plain"), (0x0033, 0x0005): ("setting", "sensor", "plain"), (0x0033, 0x0006): ("setting", "sensor", "plain"), (0x0033, 0x0007): ("setting", "sensor", "plain"), (0x0035, 0x0000): ("setting", "sensor", "plain"), (0x0035, 0x0001): ("setting", "sensor", "plain"), (0x0035, 0x0002): ("setting", "sensor", "plain"), (0x0036, 0x0004): ("setting", "sensor", "plain"), (0x003B, 0x0001): ("user", "sensor", "plain"), (0x0045, 0x0000): ("user", "sensor", "plain"), (0x0048, 0x0001): ("user", "sensor", "plain"), (0x0048, 0x0004): ("user", "sensor", "plain"), (0x0049, 0x0001): ("user", "control", "plain"), (0x0050, 0x0003): ("setting", "control", "plain"), (0x0051, 0x0001): ("user", "control", "plain"), (0x0052, 0x0001): ("user", "control", "plain"), (0x0053, 0x0001): ("user", "control", "plain"), (0x0053, 0x0002): ("user", "control", "plain"), (0x0055, 0x0001): ("user", "control", "plain"), (0x0056, 0x0000): ("user", "control", "celsius"), (0x0056, 0x0004): ("user", "control", "plain"), (0x0057, 0x0002): ("setting", "sensor", "plain"), (0x0059, 0x0001): ("user", "control", "plain"), (0x005B, 0x0000): ("user", "sensor", "plain"), (0x005C, 0x0001): ("user", "sensor", "plain"), (0x005C, 0x0002): ("user", "sensor", "plain"), (0x005C, 0x0003): ("setting", "sensor", "percentage"), (0x005C, 0x0004): ("setting", "sensor", "plain"), (0x005C, 0x0005): ("setting", "sensor", "plain"), (0x005C, 0x0006): ("setting", "sensor", "plain"), (0x005C, 0x0007): ("setting", "sensor", "plain"), (0x005C, 0x0008): ("user", "sensor", "plain"), (0x005C, 0x0009): ("user", "sensor", "plain"), (0x005C, 0x000A): ("user", "sensor", "plain"), (0x005C, 0x000B): ("setting", "control", "plain"), (0x005C, 0x000C): ("user", "sensor", "plain"), (0x005C, 0xFFF9): ("setting", "control", "plain"), (0x005D, 0x0002): ("setting", "sensor", "plain"), (0x005F, 0x0000): ("user", "control", "plain"), (0x005F, 0x0007): ("user", "control", "plain"), (0x0060, 0x0001): ("user", "sensor", "plain"), (0x0060, 0x0002): ("user", "sensor", "plain"), (0x0060, 0x0004): ("user", "sensor", "plain"), (0x0060, 0x0005): ("setting", "sensor", "plain"), (0x0060, 0xFFF9): ("user", "control", "plain"), (0x0061, 0x0001): ("user", "sensor", "plain"), (0x0061, 0x0004): ("user", "sensor", "plain"), (0x0061, 0x0005): ("setting", "sensor", "plain"), (0x0071, 0x0000): ("user", "sensor", "percentage"), (0x0071, 0xFFF9): ("user", "control", "plain"), (0x0072, 0x0000): ("user", "sensor", "percentage"), (0x0072, 0xFFF9): ("user", "control", "plain"), (0x0080, 0x0000): ("setting", "control", "plain"), (0x0080, 0x0005): ("setting", "control", "plain"), (0x0081, 0x0001): ("setting", "control", "plain"), (0x0081, 0x0002): ("user", "sensor", "plain"), (0x0081, 0x0009): ("setting", "sensor", "plain"), (0x0090, 0x0004): ("setting", "sensor", "volt"), (0x0090, 0x0005): ("setting", "sensor", "ampere"), (0x0090, 0x0006): ("setting", "sensor", "ampere"), (0x0090, 0x0007): ("setting", "sensor", "ampere"), (0x0090, 0x0008): ("user", "sensor", "watt"), (0x0090, 0x0009): ("setting", "sensor", "plain"), (0x0090, 0x000A): ("setting", "sensor", "plain"), (0x0090, 0x000B): ("setting", "sensor", "volt"), (0x0090, 0x000C): ("setting", "sensor", "ampere"), (0x0090, 0x000E): ("setting", "sensor", "hertz"), (0x0090, 0x0011): ("setting", "sensor", "percentage"), (0x0091, 0x0001): ("user", "sensor", "kwh"), (0x0091, 0x0002): ("user", "sensor", "kwh"), (0x0094, 0x0002): ("user", "sensor", "plain"), (0x0094, 0x0003): ("setting", "sensor", "kwh"), (0x0094, 0x0004): ("user", "sensor", "percentage"), (0x0094, 0x0005): ("user", "sensor", "plain"), (0x0094, 0xFFF9): ("user", "control", "plain"), (0x0098, 0x0002): ("setting", "sensor", "plain"), (0x0098, 0x0007): ("setting", "sensor", "plain"), (0x0099, 0x0000): ("user", "sensor", "plain"), (0x0099, 0x0001): ("user", "sensor", "plain"), (0x0099, 0x0002): ("setting", "sensor", "plain"), (0x0099, 0x0005): ("setting", "sensor", "ampere"), (0x0099, 0x0006): ("setting", "sensor", "ampere"), (0x0099, 0x0007): ("setting", "sensor", "ampere"), (0x0099, 0x0009): ("setting", "sensor", "ampere"), (0x0099, 0x0030): ("user", "sensor", "percentage"), (0x009D, 0x0001): ("user", "control", "plain"), (0x009F, 0x0001): ("user", "control", "plain"), (0x0101, 0x0000): ("user", "control", "plain"), (0x0101, 0x0002): ("setting", "sensor", "plain"), (0x0101, 0x0003): ("user", "sensor", "plain"), (0x0101, 0x0004): ("setting", "sensor", "plain"), (0x0101, 0x0005): ("setting", "sensor", "plain"), (0x0101, 0x0023): ("setting", "control", "plain"), (0x0101, 0x0024): ("setting", "control", "plain"), (0x0101, 0x0025): ("setting", "control", "plain"), (0x0101, 0x0029): ("setting", "control", "plain"), (0x0101, 0x002B): ("setting", "control", "plain"), (0x0101, 0x0030): ("setting", "control", "plain"), (0x0101, 0x0031): ("setting", "control", "plain"), (0x0102, 0x0007): ("setting", "sensor", "plain"), (0x0102, 0x000A): ("user", "control", "plain"), (0x0102, 0x000B): ("setting", "sensor", "percentage"), (0x0102, 0x0017): ("setting", "control", "plain"), (0x0150, 0x0004): ("user", "sensor", "plain"), (0x0200, 0x0010): ("user", "sensor", "plain"), (0x0200, 0x0014): ("user", "sensor", "plain"), (0x0200, 0x0020): ("user", "control", "plain"), (0x0200, 0x0021): ("user", "sensor", "plain"), (0x0201, 0x0000): ("user", "sensor", "celsius"), (0x0201, 0x0001): ("user", "sensor", "celsius"), (0x0201, 0x0002): ("user", "sensor", "plain"), (0x0201, 0x0008): ("setting", "sensor", "percentage"), (0x0201, 0x0010): ("setting", "control", "celsius"), (0x0201, 0x001A): ("setting", "sensor", "plain"), (0x0201, 0x0030): ("setting", "sensor", "plain"), (0x0201, 0x0031): ("setting", "sensor", "celsius"), (0x0201, 0x0032): ("setting", "sensor", "plain"), (0x0201, 0x0034): ("setting", "control", "celsius"), (0x0202, 0x0000): ("user", "control", "plain"), (0x0204, 0x0000): ("setting", "control", "plain"), (0x0204, 0x0001): ("setting", "control", "plain"), (0x0300, 0x4010): ("setting", "control", "kelvin"), (0x0400, 0x0000): ("user", "sensor", "lux"), (0x0402, 0x0000): ("user", "sensor", "celsius"), (0x0403, 0x0000): ("user", "sensor", "pascal"), (0x0404, 0x0000): ("user", "sensor", "plain"), (0x0405, 0x0000): ("user", "sensor", "percentage"), (0x0406, 0x0000): ("user", "sensor", "plain"), (0x0406, 0x0003): ("setting", "control", "plain"), (0x0406, 0x0010): ("setting", "control", "plain"), (0x0406, 0x0011): ("setting", "control", "plain"), (0x0406, 0x0012): ("setting", "control", "plain"), (0x040C, 0x0000): ("user", "sensor", "ppm"), (0x040D, 0x0000): ("user", "sensor", "ppm"), (0x0413, 0x0000): ("user", "sensor", "ppm"), (0x0415, 0x0000): ("user", "sensor", "ppm"), (0x042A, 0x0000): ("user", "sensor", "ugm3"), (0x042C, 0x0000): ("user", "sensor", "ugm3"), (0x042D, 0x0000): ("user", "sensor", "ugm3"), (0x042E, 0x0000): ("user", "sensor", "ppm"), (0x042E, 0x000A): ("user", "sensor", "plain"), (0x042F, 0x0000): ("user", "sensor", "plain"), (0x0430, 0x0001): ("user", "sensor", "percentage"), (0x0551, 0x0016): ("setting", "control", "plain"), (0x0556, 0x0001): ("setting", "control", "plain"), } ================================================================================ # FILE: majordom_matter/model.py ================================================================================ from enum import StrEnum from typing import Any from uuid import UUID from majordom_integration_sdk.schemas.base import Base from majordom_integration_sdk.schemas.device import Device, DeviceState, Parameter, ParameterState from pydantic import BaseModel, Field class MatterParameterTypeEnum(StrEnum): attribute = "attribute" command = "command" class MatterDeviceIntegrationData(Base): # Defaults to 0 (the "not yet commissioned" sentinel): the Hub builds the pairing draft # with empty integration_data before pair_device runs, and it must validate as a # MatterDeviceState. pair_device sets the real node_id once matterjs-server commissions the node. node_id: int = 0 black_list: list[UUID] = Field(default_factory=list) class MatterParameterIntegrationData(BaseModel): endpoint_id: int cluster_id: int is_client: bool = False command_id: int | None = None attribute_id: int | None = None type: MatterParameterTypeEnum # "command" or "attribute" # Args (keyed by field name) to send when this command is used as the device's one-tap main # parameter and needs them (e.g. a setpoint). A command with arguments is a `struct`, so it # also gets them as an id-keyed `default_value` to satisfy ParameterState.can_be_main_parameter; # send_command applies these when a command arrives with no value. See the zigbee model. default_arguments: dict[str, Any] | None = None class MatterDevice(Device[MatterDeviceIntegrationData]): @property def node_id(self) -> int: return self.integration_data.node_id class MatterParameter(Parameter[MatterParameterIntegrationData]): pass class MatterParameterState(ParameterState[MatterParameterIntegrationData]): pass class MatterDeviceState(MatterDevice, DeviceState[MatterDeviceIntegrationData, MatterParameterIntegrationData]): pass ================================================================================ # FILE: majordom_matter/readme.md ================================================================================ # Matter integration The hub talks to a **Matter controller server** over its WebSocket API (`ws://:5580/ws`) via `matter_server.client.MatterClient` (server URL overridable via the `MATTER_SERVER_URL` env var). The server owns the Matter fabric, the Thread/BLE radios, and commissioning; the hub discovers, commissions, and controls devices through it. ## Files | File | Responsibility | |---|---| | `controller.py` | `AbstractController` implementation — lifecycle, commissioning, control, and the mDNS + BLE discovery/subscription paths | | `mapper.py` | Matter ↔ MajorDom conversions: UUIDs (via the framework helpers), node/cluster → parameter parsing, data-type/unit/scale mapping, credentials options | | `model.py` | Typed `integration_data` schemas (`MatterDevice`, `MatterParameter`, …) | | `matter_spec.py` | Static spec metadata: system clusters/attributes, units/steps/scale, and the main-parameter map | | `exceptions.py` | Integration-specific exceptions | ## Discovery, pairing & availability - **Discovery** runs over two transports. On-network (mDNS) devices come from matter-server's `discover_commissionable_nodes()`; BLE-only commissionable devices (a factory-fresh device not yet on any network) are found via the Hub's shared **BLE discovery service** and matched by their commissioning identity. matter-server is kept for on-network discovery because it already parses the Matter TXT records into clean structured data (duplicating that on the raw Zeroconf service would add a second parser and, for BLE, a second scanner contending with the chip stack during commissioning). - **Pairing** validates the provided credentials type against the discovery's `expected_credentials_options`, then commissions through matter-server (`commission_with_code` for QR / BLE, `commission_on_network` for an on-network manual code). - **Availability** rides on `EventType.NODE_UPDATED`: `node.available` transitions emit the framework's connect/lose callbacks (deduped in `_make_availability_callback`). Every parameter id is derived through the framework UUID helpers as `parameter_uuid(device_id, "_//")`. Two test tiers: - **Virtual** — `tests/test_controllers/test_matter/test_matter_controller.py`, driven by `docker-compose.matter-tests.yml`. Prebuilt **x86-64** Matter Virtual Device (MVD) binaries under `bins/` act as fake devices, commissioned over the network (no BLE). Runs in CI on x86-64 runners. - **Hardware** — kept in a private repository and run manually: a real Thread bulb commissioned over **BLE → Thread** through a real OpenThread Border Router (OTBR + SkyConnect RCP), with its light verified physically. Both an IKEA and a Nanoleaf bulb pass. --- ## Issues we hit (and their true causes) - **Stale OTBR image was the whole ballgame.** A months-old cached `openthread/border-router:latest` had a broken RCP serial init: otbr-agent failed/hung at `spinel_driver.cpp:87`, `wpan0` never came up, and it crash-looped — producing red-herring `cp210x … -110` USB timeouts and uninterruptible `D`-state `open()` hangs. With no Thread network, **every** device's commissioning failed at `NetworkCommissioning.scanNetworks` ("Failure"). The RCP firmware/hardware were fine the whole time (the flasher + raw pyserial talked SPINEL reliably). - **`uart-init-deassert` breaks this build.** Adding it to `OT_RCP_DEVICE` makes otbr-agent reject the URL (`otSysInit … InvalidArgument`). It's a valid param in other OT builds — not this one. - **OTBR state isn't persisted by default** → the border router factory-resets on every restart. And mounting a volume over `/var/lib/thread` fails (`ln: cannot overwrite directory`) — the image symlinks `/var/lib/thread → /data`, so persist at **`/data`**. - **Docker `userns-remap`**: privileged containers are rejected without `--userns=host`, and the OTBR image's s6-overlay refuses to start unless `/run` is a fresh root-owned tmpfs. - **The x86-64 MVD binaries can't run on the Pi** (16 KB-page kernel; qemu-user can't map the 4 KB-aligned segments) → the virtual suite is x86-64 CI only. - **BLE discovery misses static-address devices.** Matter controllers discover by BlueZ's `InterfacesAdded` signal; a device with a *static* BLE address (IKEA) already in BlueZ's cache never re-fires it → "no commissionable device discovered." Nanoleaf uses a resolvable address, so it's fine. - **The hub does not push the Thread dataset.** `MatterController.pair_device` just calls `commission_with_code`; the server must *already* hold the operational dataset. - **The "Nanoleaf RX-wedge" was a broken-OTBR artifact, not firmware.** We'd blamed Nanoleaf fw 4.1.3 for wedging its Thread RX after one `Invoke`. Once the border router was healthy (fresh image, above), it never reproduced: 25 back-to-back Toggle+read+ping cycles with an active subscription, plus Level/Color commands and a 90 s idle soak, all clean — `ot-ctl ping` never dropped a packet. The old symptom was a degraded Thread mesh from the spinel-failing RCP. **Both the IKEA and the Nanoleaf are CI-usable.** ## What it takes to make it work 1. **Fresh OTBR image**: `docker pull openthread/border-router:latest`, then `OT_RCP_DEVICE=spinel+hdlc+uart:///dev/ttyUSB1?uart-baudrate=460800&uart-flow-control` (no `uart-init-deassert`), `--network host --privileged --cap-add NET_ADMIN --userns=host`, tmpfs `/run`+`/tmp`, `--device :/dev/ttyUSB1 --device /dev/net/tun`, and **`-v :/data`** for persistence. 2. **Form a network once**: `ot-ctl dataset init new; dataset commit active; ifconfig up; thread start` → `state: leader`. 3. **Give the Matter server the dataset** before commissioning: read it from OTBR (`ot-ctl dataset active -x`, or the OTBR REST `GET /node/dataset/active`) and `set_thread_dataset`. 4. **Flush the BlueZ cache immediately before each commission** and do not scan afterward: `for m in $(bluetoothctl devices | awk '{print $2}'); do bluetoothctl remove "$m"; done; systemctl restart bluetooth`. 5. **Power the device on** (IKEA opens a ~5-min pairing window on any power-on; a decommissioned Nanoleaf re-advertises on power-on). Both pass the full discover → pair → OnOff → unpair flow. See `otbr-skyconnect-fix` in the assistant memory for the exact commands and recovery steps. ================================================================================ # FILE: majordom_matter/testing/__init__.py ================================================================================ """In-process test doubles for the Matter integration — no matterjs-server, no MVD binaries. `FakeMatterClient` stands in for `matter_server.client.MatterClient`, backed by a single canned node captured from a real MVD on-off-light (`fixtures/on_off_light_node.json`). It rebuilds a **real** `MatterNode` exactly as the live client does — `MatterNode(dataclass_from_dict( MatterNodeData, ...))` — so the controller and mapper run against a faithful node; only the transport (the websocket to matterjs-server) is faked. Use it to exercise the controller's wiring — discovery, pairing/mapping, commands, events — in plain CI without docker. The heavy, real-device coverage stays in the dockerized MVD suite. from majordom_matter.testing import FakeMatterClient monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) To have the controller reconnect to the same fabric, share one `FakeMatterServer` between its clients: `partial(FakeMatterClient, server=FakeMatterServer())`. """ from __future__ import annotations import asyncio import json from pathlib import Path from typing import Any from uuid import UUID, uuid4 from majordom_integration_sdk.schemas.device import Discovery from matter_server.client.exceptions import CannotConnect, InvalidState from matter_server.client.models.node import MatterNode from matter_server.common.errors import NodeNotExists from matter_server.common.helpers.util import dataclass_from_dict from matter_server.common.models import CommissionableNodeData, EventType, MatterNodeData from majordom_matter.model import MatterDeviceState _FIXTURE = Path(__file__).parent / "fixtures" / "on_off_light_node.json" def draft_for(discovery: Discovery) -> MatterDeviceState: """The draft the Hub hands `pair_device`: a fresh id, the discovery id as physical id, the rest the user's form.""" return MatterDeviceState( id=uuid4(), physical_id=discovery.id, name="Test", room_id=UUID(int=1), transport=discovery.transport, integration=discovery.integration, manufacturer=None, parameters=[], ) def load_on_off_light_node(attributes: dict[str, Any] | None = None) -> MatterNode: """A real `MatterNode` for a captured MVD on-off-light — the same construction the live client applies to node data received over the websocket.""" data = json.loads(_FIXTURE.read_text()) data["attributes"].update(attributes or {}) return MatterNode(dataclass_from_dict(MatterNodeData, data)) class _Subscription: __slots__ = ("callback", "event_filter", "node_filter", "attr_path_filter") def __init__(self, callback, event_filter, node_filter, attr_path_filter): self.callback = callback self.event_filter = event_filter self.node_filter = node_filter self.attr_path_filter = attr_path_filter class FakeMatterServer: """matterjs-server's side of the fake: the fabric (the canned node) and whether the server is up.""" def __init__(self, node: MatterNode | None = None): self.node = node if node is not None else load_on_off_light_node() self.commissioned = False self.up = True self.is_answering = True # False: a call waits for its answer until the server goes away self.gone = asyncio.Event() # set when this run of the server goes away def lose(self): """Go away, like its container restarting: listening clients end, new ones can't connect.""" self.up = False self.gone.set() def restore(self): self.up = True self.gone = asyncio.Event() class FakeMatterClient: """Drop-in for `matter_server.client.MatterClient`, backed by one canned node. Constructed with the same `(url, session)` signature the controller uses. The node is not "on the fabric" until commissioned; before that it is advertised via `discover_commissionable_nodes()`, so the full discover → pair → map flow runs. Outgoing commands/attribute writes are recorded (`sent_commands`, `written_attributes`, `removed_nodes`) and `fire_attribute_update()` lets a test simulate a device-side change. """ def __init__( self, url: str | None = None, session: Any = None, *, node: MatterNode | None = None, server: FakeMatterServer | None = None, ): self._url = url self._session = session self.server = server if server is not None else FakeMatterServer(node) self._node = self.server.node self._subscriptions: list[_Subscription] = [] self.sent_commands: list[tuple[int, int, Any]] = [] self.written_attributes: list[tuple[int, str, Any]] = [] self.removed_nodes: list[int] = [] self.networks: dict[str, Any] = {} # credentials handed over for commissioning self._server_gone = self.server.gone # --- lifecycle --- async def connect(self): if not self.server.up: raise CannotConnect(ConnectionRefusedError("matterjs-server is down")) self._server_gone = self.server.gone async def start_listening(self, init_ready: asyncio.Event | None = None): if init_ready is not None: init_ready.set() # The real client runs its websocket loop until matterjs-server goes away (`lose_server()`); # block until then or until the controller's stop() cancels this task. await self._server_gone.wait() async def disconnect(self): return None async def set_wifi_credentials(self, ssid: str, credentials: str): await self._answer() self.networks["wifi"] = (ssid, credentials) async def set_thread_operational_dataset(self, dataset: str): await self._answer() self.networks["thread"] = dataset async def _answer(self): if not self.server.up or self._server_gone.is_set(): raise InvalidState("Not connected") # as the real client does once its matterjs-server went away if not self.server.is_answering: await self._server_gone.wait() raise asyncio.CancelledError # the real client's disconnect cancels the calls waiting for an answer # --- nodes --- def get_nodes(self) -> list[MatterNode]: return [self._node] if self.server.commissioned else [] def get_node(self, node_id: int) -> MatterNode: if self.server.commissioned and node_id == self._node.node_id: return self._node raise NodeNotExists(f"Node {node_id} does not exist or is not yet interviewed") # as the real client async def remove_node(self, node_id: int): await self._answer() if not (self.server.commissioned and node_id == self._node.node_id): raise NodeNotExists(f"Node {node_id} does not exist") # as matterjs-server answers self.removed_nodes.append(node_id) if node_id == self._node.node_id: self.server.commissioned = False # --- discovery --- async def discover_commissionable_nodes(self) -> list[CommissionableNodeData]: await self._answer() if self.server.commissioned: return [] info = self._node.device_info return [ CommissionableNodeData( instance_name="FAKEONOFF0001", vendor_id=getattr(info, "vendorID", None), product_id=getattr(info, "productID", None), commissioning_mode=1, # advertising for commissioning device_name=getattr(info, "productName", None) or "Fake On/Off Light", addresses=["fd00::1"], # on-network → commissioned with network_only=True ) ] # --- commissioning --- async def commission_with_code(self, code: str, network_only: bool = False) -> MatterNodeData: await self._answer() self.server.commissioned = True return self._node.node_data async def commission_on_network(self, setup_pin_code: int, *args: Any, **kwargs: Any) -> MatterNodeData: await self._answer() self.server.commissioned = True return self._node.node_data # --- commands / attributes --- async def send_device_command(self, node_id: int, endpoint_id: int, command: Any, **kwargs: Any): await self._answer() self.sent_commands.append((node_id, endpoint_id, command)) return None async def write_attribute(self, node_id: int, attribute_path: str, value: Any) -> Any: await self._answer() self.written_attributes.append((node_id, attribute_path, value)) # Reflect the write into the node so reads and subscribers see it, like a real device. self._node.update_attribute(attribute_path, value) self._emit(EventType.ATTRIBUTE_UPDATED, node_id, attribute_path, value) return value # --- subscriptions --- def subscribe_events(self, callback, event_filter=None, node_filter=None, attr_path_filter=None): sub = _Subscription(callback, event_filter, node_filter, attr_path_filter) self._subscriptions.append(sub) def unsubscribe(): if sub in self._subscriptions: self._subscriptions.remove(sub) return unsubscribe # --- test helpers --- def lose_server(self): """Simulate matterjs-server going away (its container restarting): listening ends, as the real client's does.""" self.server.lose() def fire_attribute_update(self, attribute_path: str, value: Any): """Simulate the device pushing a new attribute value to its subscribers.""" self._node.update_attribute(attribute_path, value) self._emit(EventType.ATTRIBUTE_UPDATED, self._node.node_id, attribute_path, value) def _emit(self, event_type: EventType, node_id: int, attribute_path: str, value: Any): for sub in list(self._subscriptions): if sub.event_filter is not None and sub.event_filter != event_type: continue if sub.node_filter is not None and sub.node_filter != node_id: continue if sub.attr_path_filter is not None and sub.attr_path_filter != attribute_path: continue sub.callback(event_type, value) __all__ = ["FakeMatterClient", "FakeMatterServer", "load_on_off_light_node"] ================================================================================ # FILE: majordom_matter/testing/fixtures/on_off_light_node.json ================================================================================ { "attribute_subscriptions": [], "attributes": { "0/29/0": [ { "0": 22, "1": 1 } ], "0/29/1": [ 29, 31, 40, 42, 48, 49, 50, 51, 52, 60, 62, 63, 64 ], "0/29/2": [ 41 ], "0/29/3": [ 13 ], "0/29/65528": [], "0/29/65529": [], "0/29/65531": [ 0, 1, 2, 3, 65528, 65529, 65531, 65532, 65533 ], "0/29/65532": 0, "0/29/65533": 2, "0/31/0": [ { "1": 5, "2": 2, "254": 1, "3": [ 112233 ], "4": null } ], "0/31/1": [], "0/31/2": 4, "0/31/3": 3, "0/31/4": 4, "0/31/65528": [], "0/31/65529": [], "0/31/65531": [ 0, 1, 2, 3, 4, 65528, 65529, 65531, 65532, 65533 ], "0/31/65532": 0, "0/31/65533": 2, "0/40/0": 18, "0/40/1": "TEST_VENDOR", "0/40/10": "1.0", "0/40/11": "20200101", "0/40/12": "", "0/40/13": "", "0/40/14": "", "0/40/15": "TEST_SN", "0/40/16": false, "0/40/18": "6D78CCBDAFD85AD1", "0/40/19": { "0": 3, "1": 65535 }, "0/40/2": 65521, "0/40/21": 17039616, "0/40/22": 1, "0/40/3": "TEST_PRODUCT", "0/40/4": 32768, "0/40/5": "", "0/40/6": "XX", "0/40/65528": [], "0/40/65529": [], "0/40/65531": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 21, 22, 65528, 65529, 65531, 65532, 65533 ], "0/40/65532": 0, "0/40/65533": 3, "0/40/7": 0, "0/40/8": "TEST_VERSION", "0/40/9": 1, "0/42/0": [], "0/42/1": true, "0/42/2": 0, "0/42/3": 0, "0/42/65528": [], "0/42/65529": [ 0 ], "0/42/65531": [ 0, 1, 2, 3, 65528, 65529, 65531, 65532, 65533 ], "0/42/65532": 0, "0/42/65533": 1, "0/48/0": 0, "0/48/1": { "0": 60, "1": 900 }, "0/48/2": 0, "0/48/3": 2, "0/48/4": true, "0/48/65528": [ 1, 3, 5 ], "0/48/65529": [ 0, 2, 4 ], "0/48/65531": [ 0, 1, 2, 3, 4, 65528, 65529, 65531, 65532, 65533 ], "0/48/65532": 0, "0/48/65533": 1, "0/49/0": 1, "0/49/1": [ { "0": "", "1": true } ], "0/49/2": 0, "0/49/3": 0, "0/49/4": true, "0/49/5": null, "0/49/6": null, "0/49/65528": [], "0/49/65529": [], "0/49/65531": [ 0, 1, 2, 3, 4, 5, 6, 7, 65528, 65529, 65531, 65532, 65533 ], "0/49/65532": 4, "0/49/65533": 2, "0/49/7": null, "0/50/65528": [ 1 ], "0/50/65529": [ 0 ], "0/50/65531": [ 65528, 65529, 65531, 65532, 65533 ], "0/50/65532": 0, "0/50/65533": 1, "0/51/0": [ { "0": "eth0", "1": true, "2": null, "3": null, "4": "AkKsEO4D", "5": [ "rBDuAw==" ], "6": [ "/QANuAABAAAAAAAAAAAAAw==", "/oAAAAAAAAAAQqz//hDuAw==" ], "7": 0 }, { "0": "ip6tnl0", "1": false, "2": null, "3": null, "4": "AAAAAAAA", "5": [], "6": [], "7": 0 }, { "0": "tunl0", "1": false, "2": null, "3": null, "4": "AAAAAAAA", "5": [], "6": [], "7": 0 }, { "0": "lo", "1": true, "2": null, "3": null, "4": "AAAAAAAA", "5": [ "fwAAAQ==" ], "6": [ "AAAAAAAAAAAAAAAAAAAAAQ==" ], "7": 0 } ], "0/51/1": 1, "0/51/2": 6, "0/51/3": 0, "0/51/4": 0, "0/51/5": [], "0/51/6": [], "0/51/65528": [ 2 ], "0/51/65529": [ 0, 1 ], "0/51/65531": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 65528, 65529, 65531, 65532, 65533 ], "0/51/65532": 0, "0/51/65533": 2, "0/51/7": [], "0/51/8": false, "0/52/0": [ { "0": 55, "1": "55" }, { "0": 54, "1": "54" }, { "0": 53, "1": "53" }, { "0": 52, "1": "52" }, { "0": 50, "1": "50" } ], "0/52/1": 358288, "0/52/2": 710768, "0/52/3": 710768, "0/52/65528": [], "0/52/65529": [ 0 ], "0/52/65531": [ 0, 1, 2, 3, 65528, 65529, 65531, 65532, 65533 ], "0/52/65532": 1, "0/52/65533": 1, "0/60/0": 0, "0/60/1": null, "0/60/2": null, "0/60/65528": [], "0/60/65529": [ 0, 1, 2 ], "0/60/65531": [ 0, 1, 2, 65528, 65529, 65531, 65532, 65533 ], "0/60/65532": 0, "0/60/65533": 1, "0/62/0": [ { "1": "FTABAQEkAgE3AyQTAhgmBIAigScmBYAlTTo3BiQVASQRLhgkBwEkCAEwCUEEY7W1K6kpx4vZWVLIU73qp/kW9pyLNDQuBV6RLpvdIkVTbb29I6Xzm7itl+MOnHXKMtlRHRkLh64D5XlIb7XRVTcKNQEoARgkAgE2AwQCBAEYMAQUjtcdbm56tODHaNoV/ioyU9SpxREwBRSo+UzPP0I0E1K8a1hlCujFdiWqzxgwC0BxmMahSG1S3y5vyKFL58777UBKPFwP66Qm3EV80n2LZbWy9nWWkYhWZCFr7Y6fkJ3a5wG5N6RJWdNXXMBZZnxLGA==", "2": "FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQTAhgkBwEkCAEwCUEE0RSu778u6pYZsH0NF1KbMVkRx6WCDubvsdq0FMGbdXjruqXkI2lQ6J4UPR6oR0ksaD2R2KvRQIzErBXbmIwHlzcKNQEpARgkAmAwBBSo+UzPP0I0E1K8a1hlCujFdiWqzzAFFNN+KRsnAn7+Qs9DAq38/3NJvWCVGDALQOIIDhZiG24xAI3J0yI4IHE7al9lIt/iEHhpWWlKqu4k3/o83hn3l/w9QeTi+/VmeexEnKdqgOHMxcWyM6PKjcQY", "254": 1 } ], "0/62/1": [ { "1": "BITlbMUi+wQk6xm6NN5escj+cIPQ1hBZmViEs4R9dzxzwP2RamKdP3Gyop8yGiIFCTGwWZIoiENYiRPloYymxZE=", "2": 65521, "254": 1, "3": 1, "4": 46, "5": "" } ], "0/62/2": 16, "0/62/3": 1, "0/62/4": [ "FTABAQEkAgE3AyQUARgmBIAigScmBYAlTTo3BiQUARgkBwEkCAEwCUEEhOVsxSL7BCTrGbo03l6xyP5wg9DWEFmZWISzhH13PHPA/ZFqYp0/cbKinzIaIgUJMbBZkiiIQ1iJE+WhjKbFkTcKNQEpARgkAmAwBBTTfikbJwJ+/kLPQwKt/P9zSb1glTAFFNN+KRsnAn7+Qs9DAq38/3NJvWCVGDALQPDg3Kj5rxI91fXdW2CvG+HsbMGtRBPIagmzYb4Mq4VUkyQfjrTZvLCHKcvRxwZmJDDGYr0EVUf5M4l377vPfjAY" ], "0/62/5": 1, "0/62/65528": [ 1, 3, 5, 8 ], "0/62/65529": [ 0, 2, 4, 6, 7, 9, 10, 11 ], "0/62/65531": [ 0, 1, 2, 3, 4, 5, 65528, 65529, 65531, 65532, 65533 ], "0/62/65532": 0, "0/62/65533": 1, "0/63/0": [], "0/63/1": [], "0/63/2": 4, "0/63/3": 3, "0/63/65528": [ 2, 5 ], "0/63/65529": [ 0, 1, 3, 4 ], "0/63/65531": [ 0, 1, 2, 3, 65528, 65529, 65531, 65532, 65533 ], "0/63/65532": 0, "0/63/65533": 2, "0/64/0": [ { "0": "room", "1": "bedroom 2" }, { "0": "orientation", "1": "North" }, { "0": "floor", "1": "2" }, { "0": "direction", "1": "up" } ], "0/64/65528": [], "0/64/65529": [], "0/64/65531": [ 0, 65528, 65529, 65531, 65532, 65533 ], "0/64/65532": 0, "0/64/65533": 1, "13/29/0": [ { "0": 256, "1": 1 } ], "13/29/1": [ 3, 4, 6, 8, 29 ], "13/29/2": [ 30 ], "13/29/3": [], "13/29/65528": [], "13/29/65529": [], "13/29/65531": [ 0, 1, 2, 3, 65528, 65529, 65531, 65532, 65533 ], "13/29/65532": 0, "13/29/65533": 2, "13/3/0": 0, "13/3/1": 0, "13/3/65528": [], "13/3/65529": [ 0 ], "13/3/65531": [ 0, 1, 65528, 65529, 65531, 65532, 65533 ], "13/3/65532": 0, "13/3/65533": 2, "13/4/0": 128, "13/4/65528": [ 0, 1, 2, 3 ], "13/4/65529": [ 0, 1, 2, 3, 4, 5 ], "13/4/65531": [ 0, 65528, 65529, 65531, 65532, 65533 ], "13/4/65532": 1, "13/4/65533": 3, "13/6/0": false, "13/6/16384": true, "13/6/16385": 0, "13/6/16386": 0, "13/6/16387": 0, "13/6/65528": [], "13/6/65529": [ 0, 1, 2 ], "13/6/65531": [ 0, 16384, 16385, 16386, 16387, 65528, 65529, 65531, 65532, 65533 ], "13/6/65532": 1, "13/6/65533": 5, "13/8/0": 1, "13/8/1": 0, "13/8/15": 1, "13/8/16384": 1, "13/8/17": 254, "13/8/2": 1, "13/8/3": 254, "13/8/65528": [], "13/8/65529": [ 0, 1, 2, 3, 4, 5, 6, 7 ], "13/8/65531": [ 0, 1, 2, 3, 15, 17, 16384, 65528, 65529, 65531, 65532, 65533 ], "13/8/65532": 3, "13/8/65533": 6 }, "available": true, "date_commissioned": "2026-07-18T00:41:44.182162", "interview_version": 6, "is_bridge": false, "last_interview": "2026-07-18T00:41:44.182176", "node_id": 46 } ================================================================================ # FILE: pyproject.toml ================================================================================ [project] name = "majordom-matter" version = "0.1.7" description = "Matter integration for MajorDom — bridges Matter devices into the MajorDom language." authors = [ { name = "Parker Industries" }, { name = "Ehor Lukianov @Hexa-Hexagon", email = "85293779+Hexa-Hexagon@users.noreply.github.com" }, { name = "Mark Parker @MarkParker5", email = "34688010+MarkParker5@users.noreply.github.com" }, ] readme = "README.md" license = "LicenseRef-PolyForm-Noncommercial-1.0.0" license-files = ["LICENSE"] keywords = ["majordom", "matter", "thread", "smart-home", "home-automation", "iot", "integration", "csa", "connectedhomeip"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Home Automation", "Programming Language :: Python :: 3", "Operating System :: POSIX :: Linux", ] requires-python = ">=3.13,<3.14" dependencies = [ "majordom-integration-sdk (>=0.4.0,<1.0)", "python-matter-server (>=8.1.2,<9.0.0)", "home-assistant-chip-core (>=2025.7.0)", "home-assistant-chip-clusters (>=2025.7.0)", ] [project.urls] Homepage = "https://majordom.io" Documentation = "https://docs.majordom.io/device-integration" Repository = "https://github.com/MajorDom-Systems/integration-matter" Issues = "https://github.com/MajorDom-Systems/integration-matter/issues" "Commercial licensing" = "https://parker-industries.org/partnership" "Parker Industries" = "https://parker-industries.org" [dependency-groups] dev = [ "poethepoet (>=0.49.0,<1.0.0)", "ty", "ruff", "pip-audit", "pytest", "pytest-asyncio", "pytest-cov", "pytest-timeout", "pytest-repeat", "pytest-benchmark", "pytest-profiling", "pytest-resource-usage", "coverage", "pytest-rerunfailures", "pympler", "psutil", "faker", "majordom-integration-sdk[ble] (>=0.4.0,<1.0)", # the SDK's Bluetooth fakes hear with bleak's types ] [build-system] requires = ["poetry-core>=2.0.0,<3.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] requires-poetry = ">=2.0" packages = [{ include = "majordom_matter" }] [tool.pytest.ini_options] asyncio_mode = "auto" pythonpath = ["."] filterwarnings = ["once"] markers = ["flaky: retried via pytest-rerunfailures (matter coverage tests are flaky under emulation load)"] [tool.coverage.run] omit = ["tests/*"] [tool.ruff] line-length = 120 indent-width = 4 [tool.ruff.lint] select = ["E", "F", "UP", "B", "SIM", "I"] fixable = ["ALL"] [tool.ruff.format] quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "tests/*" = ["E402"] [tool.poe.tasks.install] shell = """ poetry install echo '#!/bin/sh\npoetry run poe check' > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit echo "Pre-commit hook installed." """ [tool.poe.tasks.check] shell = """ code=0 echo "\nRunning ruff lint:" poetry run ruff check --fix || code=1 echo "\nRunning ruff format:" poetry run ruff format || code=1 echo "\nRunning ty:" poetry run ty check || code=1 echo "\nRunning pytest:" poetry run pytest --cov=majordom_matter --cov-report=xml || code=1 echo "\nRunning poetry build:" poetry build || code=1 echo "\nRunning poetry check:" poetry check || code=1 ${ci:+git diff --exit-code} || code=1 exit $code """ args = [{ name = "ci", type = "boolean" }] ================================================================================ # FILE: scripts/check_matter_ha_drift.py ================================================================================ #!/usr/bin/env python3 """CI drift check for the vendored matter-HA harvest — the Dependabot-style refresher. Re-runs the AST harvest against home-assistant/core and diffs vs the committed ``matter_spec_ha.py`` via the SDK's diff_specs. Exit 0 (none) / 1 (ADD/REMOVE) / 2 (RECLASSIFY). Run: python scripts/check_matter_ha_drift.py --ref dev """ from __future__ import annotations import argparse import enum import sys import typing import chip.clusters.ClusterObjects as co from majordom_integration_sdk.spec_drift import diff_specs from majordom_matter.matter_spec_ha import MATTER_HA_ATTRIBUTE_UX as COMMITTED from scripts.harvest_matter_ha import harvest def _mapped_data_type(attr: object) -> str: """MajorDom ``ParameterDataType`` for a chip attribute, from its declared TLV type. The unit in the harvested tuple is HA's semantic judgment; this is the orthogonal wire-type axis the Matter Data Model supplies. ``"unknown"`` when chip resolves the id but not a classifiable ``.Type`` (odd union, struct/list, non-class) — e.g. HA referencing an attribute ahead of these bindings.""" descriptor = getattr(attr, "attribute_type", None) tp = getattr(descriptor, "Type", None) if tp is None: return "unknown" union_args = typing.get_args(tp) # nullable attrs are Union[Nullable, X] -> classify X if union_args: members = [a for a in union_args if getattr(a, "__name__", "") != "Nullable"] tp = members[0] if members else union_args[0] if not isinstance(tp, type): return "unknown" if issubclass(tp, (enum.Enum, enum.Flag)): # chip enums/bitmaps are IntEnum/IntFlag return "enum" if issubclass(tp, bool): # before int — bool is an int subclass return "bool" if issubclass(tp, int): return "integer" if issubclass(tp, float): return "decimal" if issubclass(tp, str): return "string" if issubclass(tp, bytes | bytearray): return "data" return "unknown" def _key_label(key: tuple[int, int]) -> str: """Resolve a ``(cluster_id, attribute_id)`` key to ``Cluster.Attribute [data_type]`` via the chip bindings, so the drift PR names what changed (``Chime.SelectedChime [integer]``) instead of only ``(1366, 1)``. Falls back to the hex id / ``unknown`` for anything chip can't classify.""" cid, aid = key cluster = co.ALL_CLUSTERS.get(cid) cluster_name = getattr(cluster, "__name__", None) or f"0x{cid:04x}" attr = co.ALL_ATTRIBUTES.get(cid, {}).get(aid) qualname = getattr(attr, "__qualname__", "") # e.g. "Chime.Attributes.SelectedChime" attr_name = qualname.split(".")[-1] if qualname else f"0x{aid:04x}" return f"{cluster_name}.{attr_name} [{_mapped_data_type(attr)}]" def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--ref", default="dev") args = ap.parse_args() current, _skipped = harvest(args.ref) report = diff_specs(current, COMMITTED) print(report.render(source="matter-ha", key_label=_key_label), file=sys.stderr) if report.is_empty: return 0 return 2 if report.has_high_risk else 1 if __name__ == "__main__": raise SystemExit(main()) ================================================================================ # FILE: scripts/fetch_mvd.sh ================================================================================ #!/usr/bin/env bash # Fetch Google's Matter Virtual Device (MVD) `chef` binaries into tests/mvd/ (gitignored). # # Each binary is connectedhomeip's `chef` example app compiled per device type, shipped inside # Google's MVD package (https://developers.home.google.com/tools/virtual-device) as a GPG-signed # Debian archive. A .deb is a plain `ar` archive, so we extract without installing (portable — # works on macOS/CI without dpkg). Only an amd64 Linux build exists upstream (no arm64 Linux), # which is why the matter suite runs in an x86-64 container (Rosetta locally, native on CI). set -euo pipefail # The lowest version this integration is known to support. Probing for "latest" starts here, and # it is the default when no version is requested (reproducible PR/push runs pin to a known build). MVD_FLOOR="${MVD_FLOOR:-1.7.0}" MVD_VERSION="${MVD_VERSION:-$MVD_FLOOR}" BASE_URL="${MVD_BASE_URL:-https://dl.google.com/mvd}" GOOGLE_KEY_URL="${GOOGLE_KEY_URL:-https://dl.google.com/linux/linux_signing_key.pub}" # Google Inc. (Linux Packages Signing Authority) — the key the MVD .deb is signed with. EXPECTED_KEY_FPR="${MVD_KEY_FPR:-EB4C1BFD4F042F6DDDCCEC917721F63BD38B4796}" OUT="$(cd "$(dirname "$0")/.." && pwd)/tests/mvd" # Resolve MVD_VERSION=latest by probing the CDN. Google publishes no directory listing, `latest` # alias, or manifest — but every version lives at a deterministic `mvd__amd64.deb` URL # that returns 200 (exists) or 404. So walk major, then minor, then patch upward from the floor, # taking the highest that still exists. Bounded so a gap never loops forever. This is what lets # the monthly canary discover a NEW upstream release; the GPG check below still gates integrity. _exists() { [ "$(curl -s -o /dev/null -w '%{http_code}' "${BASE_URL}/mvd_${1}_amd64.deb")" = "200" ]; } if [ "$MVD_VERSION" = "latest" ]; then IFS=. read -r M m p <<<"$MVD_FLOOR" for _ in $(seq 1 5); do _exists "$((M+1)).0.0" && { M=$((M+1)); m=0; p=0; } || break; done for _ in $(seq 1 20); do _exists "${M}.$((m+1)).0" && { m=$((m+1)); p=0; } || break; done for _ in $(seq 1 50); do _exists "${M}.${m}.$((p+1))" && p=$((p+1)) || break; done MVD_VERSION="${M}.${m}.${p}" echo "Resolved latest MVD version: ${MVD_VERSION} (floor ${MVD_FLOOR})" fi DEB="mvd_${MVD_VERSION}_amd64.deb" work="$(mktemp -d)"; trap 'rm -rf "$work"' EXIT; cd "$work" echo "Downloading ${DEB} (+ signature)…" curl -fsSLO "${BASE_URL}/${DEB}" curl -fsSLO "${BASE_URL}/${DEB}.asc" echo "Verifying GPG signature against Google's Linux package key…" export GNUPGHOME="$work/gnupg"; mkdir -p "$GNUPGHOME"; chmod 700 "$GNUPGHOME" curl -fsSL "$GOOGLE_KEY_URL" | gpg --import 2>/dev/null gpg --list-keys --with-colons | grep -q "$EXPECTED_KEY_FPR" \ || { echo "ERROR: imported key does not match the pinned fingerprint ${EXPECTED_KEY_FPR}"; exit 1; } gpg --verify "${DEB}.asc" "${DEB}" # hard-fails on a bad/absent signature echo "Extracting (ar + tar — no dpkg needed)…" ar x "${DEB}" mkdir -p data && tar -xf data.tar.* -C data # The per-device chef binaries live under the Electron app's prebuilt tree, named # `rootnode__`. Map them to clean, hash-free names; device types that ship # twice (on-off-light, generic-switch) get a `-2` on the second. A device type we don't have a # nice name for is NOT an error — the integration maps device types flexibly, so we auto-name it # from its prefix and still ship it, letting the test sweep commission it like any other. That is # the point of the canary: a brand-new upstream device gets exercised automatically, and only a # genuine mapping/commissioning failure (surfaced by the tests) flags it for a human. python3 - "$OUT" <<'PY' import os, re, sys, shutil, pathlib out = pathlib.Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True) src = pathlib.Path("data/usr/lib/mvd/resources/app/prebuilt/linux_x64") NAME = { "airpurifier": "air-purifier", "airqualitysensor": "air-quality-sensor", "basicvideoplayer": "basic-video-player", "colortemperaturelight": "color-temperature-light", "contactsensor": "contact-sensor", "dimmablelight": "dimmable-light", "dimmablepluginunit": "dimmable-plug", "dishwasher": "dishwasher", "doorlock": "door-lock", "extendedcolorlight": "extended-color-light", "fan": "fan", "flowsensor": "flow-sensor", "genericswitch": "generic-switch", "humiditysensor": "humidity-sensor", "laundrywasher": "laundry-washer", "lightsensor": "light-sensor", "occupancysensor": "occupancy-sensor", "onofflight": "on-off-light", "onoffpluginunit": "on-off-plug", "pressuresensor": "pressure-sensor", "pump": "pump", "refrigerator_temperaturecontrolledcabinet_temperaturecontrolledcabinet": "refrigerator", "roboticvacuumcleaner": "robotic-vacuum", "roomairconditioner": "room-air-conditioner", "smokecoalarm": "smoke-co-alarm", "temperaturesensor": "temperature-sensor", "thermostat": "thermostat", "windowcovering": "window-covering", } # group by device-type prefix (strip the trailing _), sorted for deterministic -2 order groups: dict[str, list[str]] = {} for f in sorted(p.name for p in src.glob("rootnode_*")): prefix = re.sub(r"^rootnode_", "", f) prefix = re.sub(r"_[^_]+$", "", prefix) # drop the hash segment groups.setdefault(prefix, []).append(f) unknown = sorted(set(groups) - set(NAME)) if unknown: # Not fatal — auto-name and ship them so the flexible mapping is still exercised. Consider # adding a nice name to NAME above once the type is known-good. print(f"Note: auto-naming {len(unknown)} unmapped device type(s): {unknown}") n = 0 for prefix, files in groups.items(): base = NAME.get(prefix, prefix.replace("_", "-")) for i, f in enumerate(files): target = out / (base if i == 0 else f"{base}-{i+1}") shutil.copy(src / f, target) os.chmod(target, 0o755) n += 1 print(f"Extracted {n} MVD binaries -> {out}") PY count="$(find "$OUT" -type f | wc -l | tr -d ' ')" echo "Done: ${count} MVD binaries (MVD ${MVD_VERSION})" ================================================================================ # FILE: scripts/fetch_paa_certs.py ================================================================================ #!/usr/bin/env python3 """Fetch Matter PAA (Product Attestation Authority) root certificates. Uses python-matter-server's own fetcher — DCL production + test ledgers and the connectedhomeip git mirror — the same sources that produced the certificate store the matter tests run against (including the Chip-Test development PAA the MVD chef devices commission against). python scripts/fetch_paa_certs.py [dest_dir] # default: matter_data/credentials The DCL occasionally serves a single malformed certificate; upstream's fetcher aborts the whole source when one fails to parse. We wrap the per-cert writer to skip a malformed cert instead, so every source completes fully. """ import asyncio import sys from pathlib import Path import matter_server.server.helpers.paa_certificates as paa MIN_CERTS = 30 _orig_write = paa.write_paa_root_cert async def _resilient_write(*args, **kwargs): try: return await _orig_write(*args, **kwargs) except Exception as err: # noqa: BLE001 — skip a malformed cert, keep fetching the rest print(f" (skipping malformed certificate: {type(err).__name__})") return False paa.write_paa_root_cert = _resilient_write # ty: ignore[invalid-assignment] # monkeypatch, module global async def main(): dest = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("matter_data/credentials") dest.mkdir(parents=True, exist_ok=True) (dest / ".version").unlink(missing_ok=True) # force a full fetch total = await paa.fetch_certificates(dest) count = len(list(dest.glob("*.der"))) + len(list(dest.glob("*.pem"))) if count < MIN_CERTS: sys.exit(f"Only {count} PAA certs fetched (< {MIN_CERTS}) — treating as a failed fetch") print(f"PAA certificate store ready: {count} certs (fetcher counted {total}) -> {dest}") if __name__ == "__main__": asyncio.run(main()) ================================================================================ # FILE: scripts/harvest_matter_ha.py ================================================================================ #!/usr/bin/env python3 """Harvest Home Assistant's Matter entity judgment into ``majordom_matter/matter_spec_ha.py``. DEV / BUILD TOOL. Unlike zha, HA's Matter discovery is **not** a standalone library — it lives in `homeassistant.components.matter`. So instead of importing it (which would drag in all of HA core), this downloads only the handful of platform files and parses them with **AST** (no execution, no `homeassistant` install). Attribute references (``clusters.X.Attributes.Y``) are resolved to ``(cluster_id, attribute_id)`` via the ``chip`` bindings we already depend on. What it takes: the genuinely-additive judgment (``entity_category`` -> visibility, platform -> role, unit/device_class -> unit). The Matter Data Model already gives us names/types/bounds via ``chip``, so those are dropped. Value-transform lambdas (``device_to_ha``) can't be read statically and are logged as skipped. Usage: python scripts/harvest_matter_ha.py # writes the module (ref=dev) python scripts/harvest_matter_ha.py --ref 2025.1.0 # pin a HA release tag python scripts/harvest_matter_ha.py --stdout """ from __future__ import annotations import argparse import ast import subprocess import sys import urllib.request import chip.clusters as clusters _PLATFORM_FILES = ( "sensor", "binary_sensor", "switch", "number", "select", "climate", "cover", "fan", "light", "lock", "button", "event", ) _RAW = "https://raw.githubusercontent.com/home-assistant/core/{ref}/homeassistant/components/matter/{f}.py" # HA unit-enum leaf / device_class leaf -> our ParameterUnit value. Unmapped -> "plain". _UNIT_BY_LEAF = { "CELSIUS": "celsius", "PERCENTAGE": "percentage", "KELVIN": "kelvin", "WATT": "watt", "VOLT": "volt", "AMPERE": "ampere", "KILO_WATT_HOUR": "kwh", "HERTZ": "hertz", "LUX": "lux", "PASCAL": "pascal", "KILO_PASCAL": "pascal", "HECTOPASCAL": "pascal", "PARTS_PER_MILLION": "ppm", "MICROGRAMS_PER_CUBIC_METER": "ugm3", } _UNIT_BY_DEVICE_CLASS = { "TEMPERATURE": "celsius", "HUMIDITY": "percentage", "BATTERY": "percentage", "ILLUMINANCE": "lux", "POWER": "watt", "VOLTAGE": "volt", "CURRENT": "ampere", "ENERGY": "kwh", "PRESSURE": "pascal", "FREQUENCY": "hertz", } _CONTROL_PLATFORMS = {"switch", "number", "select", "climate", "cover", "fan", "light", "lock", "button"} def _leaf(node: ast.expr | None) -> str | None: """Leaf name of a node: ``Platform.SENSOR`` -> 'SENSOR', bare ``PERCENTAGE`` -> 'PERCENTAGE'.""" if isinstance(node, ast.Attribute): return node.attr if isinstance(node, ast.Name): return node.id if isinstance(node, ast.Constant) and isinstance(node.value, str): return node.value return None def _dotted(node: ast.expr) -> list[str] | None: """Flatten ``clusters.X.Attributes.Y`` (an Attribute chain) into ['clusters','X','Attributes','Y'].""" parts: list[str] = [] cur: ast.expr = node while isinstance(cur, ast.Attribute): parts.append(cur.attr) cur = cur.value if isinstance(cur, ast.Name): parts.append(cur.id) return list(reversed(parts)) return None def _resolve_attr(dotted: list[str]) -> tuple[int, int] | None: """['clusters','TemperatureMeasurement','Attributes','MeasuredValue'] -> (cluster_id, attr_id).""" if not dotted or dotted[0] != "clusters": return None obj: object = clusters for part in dotted[1:]: obj = getattr(obj, part, None) if obj is None: return None cid, aid = getattr(obj, "cluster_id", None), getattr(obj, "attribute_id", None) return (cid, aid) if cid is not None and aid is not None else None def _kwargs(call: ast.Call) -> dict[str, ast.expr]: return {kw.arg: kw.value for kw in call.keywords if kw.arg} def harvest(ref: str) -> tuple[dict[tuple[int, int], tuple[str, str, str]], list[str]]: out: dict[tuple[int, int], tuple[str, str, str]] = {} skipped: list[str] = [] for f in _PLATFORM_FILES: try: src = urllib.request.urlopen(_RAW.format(ref=ref, f=f), timeout=30).read().decode() except Exception as e: # noqa: BLE001 - a missing platform file is not fatal skipped.append(f"{f}.py: fetch failed ({e})") continue tree = ast.parse(src) for call in ast.walk(tree): if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Name)): continue if call.func.id != "MatterDiscoverySchema": continue kw = _kwargs(call) platform = (_leaf(kw.get("platform")) or "").lower() req = kw.get("required_attributes") if not isinstance(req, ast.Tuple) or not req.elts: skipped.append(f"{f}.py: schema with no required_attributes") continue key = _resolve_attr(_dotted(req.elts[0]) or []) if key is None: skipped.append(f"{f}.py: unresolved {ast.dump(req.elts[0])[:60]}") continue desc = kw.get("entity_description") dkw = _kwargs(desc) if isinstance(desc, ast.Call) else {} entity_category = _leaf(dkw.get("entity_category")) visibility = "user" if entity_category is None else "setting" role = "control" if platform in _CONTROL_PLATFORMS else "sensor" unit = _unit(_leaf(dkw.get("device_class")), _leaf(dkw.get("native_unit_of_measurement"))) # First writer wins; but a user (primary) classification upgrades a prior setting. prev = out.get(key) if prev is None or (prev[0] == "setting" and visibility == "user"): out[key] = (visibility, role, unit) return out, skipped def _unit(device_class: str | None, unit_leaf: str | None) -> str: if unit_leaf and unit_leaf in _UNIT_BY_LEAF: return _UNIT_BY_LEAF[unit_leaf] if device_class and device_class in _UNIT_BY_DEVICE_CLASS: return _UNIT_BY_DEVICE_CLASS[device_class] return "plain" def render(data: dict[tuple[int, int], tuple[str, str, str]], ref: str) -> str: lines = [ '"""GENERATED by scripts/harvest_matter_ha.py — DO NOT EDIT BY HAND.', "", f"Source: home-assistant/core@{ref} homeassistant/components/matter (Apache-2.0), parsed via", "AST (no homeassistant dependency). Attribute ids resolved via chip. Harvested entity", "judgment only (entity_category -> visibility, platform -> role, unit); the Matter Data Model", "supplies names/types/bounds. Hand overrides live in matter_spec.py and win on merge.", '"""', "", "# (cluster_id, attribute_id) -> (visibility, role, unit)", "MATTER_HA_ATTRIBUTE_UX: dict[tuple[int, int], tuple[str, str, str]] = {", ] for (cid, aid), (vis, role, unit) in sorted(data.items()): lines.append(f" ({cid:#06x}, {aid:#06x}): ({vis!r}, {role!r}, {unit!r}),") lines.append("}") return "\n".join(lines) + "\n" def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--ref", default="dev", help="home-assistant/core git ref (tag/branch)") ap.add_argument("--stdout", action="store_true") ap.add_argument("--out", default="majordom_matter/matter_spec_ha.py") args = ap.parse_args() data, skipped = harvest(args.ref) text = render(data, args.ref) if args.stdout: sys.stdout.write(text) else: with open(args.out, "w") as fh: fh.write(text) subprocess.run(["ruff", "format", "--quiet", args.out], check=True) # as `poe check` would leave it print(f"[harvest_matter_ha] ref={args.ref}: wrote {len(data)} entries -> {args.out}", file=sys.stderr) print(f"[harvest_matter_ha] {len(skipped)} schemas skipped (composite/transform/unresolved)", file=sys.stderr) return 0 if __name__ == "__main__": raise SystemExit(main()) ================================================================================ # FILE: scripts/param_ux_audit.py ================================================================================ """Run majordom's MATTER visibility mapping across the full chip data model (all clusters' attributes), replicating mapper.parse_attributes, and bucket like the iOS app: user/setting/system.""" import inspect from typing import cast import chip.clusters.Objects as M from chip.clusters.CHIPClusters import ChipClusters from chip.clusters.ClusterObjects import ClusterAttributeDescriptor from majordom_matter.matter_spec import ( EVERYDAY_CONTROL_ATTRIBUTES, MAIN_PARAMETER_BY_CLUSTER, SENSITIVE_ATTRIBUTE_NAME_PREFIXES, SYSTEM_ATTRIBUTES, SYSTEM_CLUSTERS, USER_READINGS, AttributeKey, ) CI = ChipClusters(None) def writable(cid, aid): try: return bool(CI.GetClusterInfoById(cid).get("attributes", {}).get(aid, {}).get("writable")) except Exception: return False clusters = [ c for _, c in inspect.getmembers(M, inspect.isclass) if hasattr(c, "id") and hasattr(c, "Attributes") and isinstance(c.id, int) ] clusters = sorted({c.id: c for c in clusters}.items()) tot = {"user": 0, "setting": 0, "system": 0} rows = [] for cid, cls in clusters: cid = cast("int", cid) # guaranteed by the isinstance guard above; inspect types it object is_sys = cid in SYSTEM_CLUSTERS b = {"user": [], "setting": [], "system": []} for name, attr in inspect.getmembers(cls.Attributes, inspect.isclass): if not issubclass(attr, ClusterAttributeDescriptor): continue aid = getattr(attr, "attribute_id", -1) if aid in SYSTEM_ATTRIBUTES: continue key = AttributeKey(cid, aid) if is_sys or name.startswith(SENSITIVE_ATTRIBUTE_NAME_PREFIXES): vis = "system" elif writable(cid, aid): vis = "user" if key in EVERYDAY_CONTROL_ATTRIBUTES else "setting" elif key in USER_READINGS: vis = "user" else: vis = "system" # read-only, uncurated -> hidden (inverted default) b[vis].append(name) for k in tot: tot[k] += len(b[k]) rows.append((cid, cls.__name__, is_sys, cid in MAIN_PARAMETER_BY_CLUSTER, b)) print(f"=== MATTER full-datamodel mapping: {len(rows)} clusters ===") print(f"total attr-params by bucket: user={tot['user']} setting={tot['setting']} system={tot['system']}") print(f"clusters providing a MAIN param: {sorted(hex(c) for c in MAIN_PARAMETER_BY_CLUSTER)}\n") SPOT = { 0x6: "OnOff", 0x8: "LevelControl", 0x300: "ColorControl", 0x201: "Thermostat", 0x202: "FanControl", 0x102: "WindowCovering", 0x101: "DoorLock", 0x402: "TempMeas", 0x405: "Humidity", 0x2F: "PowerSource", 0x50: "ModeSelect", } for cid, name, _is_sys, has_main, b in rows: if cid in SPOT: main = " [MAIN]" if has_main else "" print( f"--- 0x{cid:04X} {name}{main} — " f"user={len(b['user'])} setting={len(b['setting'])} system={len(b['system'])} ---" ) if b["user"]: print(f" user: {', '.join(b['user'][:16])}{' …' if len(b['user']) > 16 else ''}") # biggest user buckets (over-exposure hotspots) print("\n=== TOP over-exposed 'user' clusters (most read-only attrs shown to user) ===") for cid, name, _is_sys, _has_main, b in sorted(rows, key=lambda r: -len(r[4]["user"]))[:10]: print(f" 0x{cid:04X} {name}: user={len(b['user'])}") ================================================================================ # FILE: tests/conftest.py ================================================================================ """Unit tests for the Matter controller. Drive `MatterController` directly against a live python-matter-server and real MVD `chef` virtual devices — no Hub. The MVD binaries are Linux x86-64, so this runs in the test container (see docker/); on Apple Silicon via Rosetta. The Hub keeps the e2e and real-hardware coverage. """ import asyncio import contextlib import os import signal import subprocess import tempfile from pathlib import Path import pytest import pytest_asyncio from aiohttp import ClientSession from majordom_integration_sdk import Endpoint, Peripherals, Platform from majordom_integration_sdk.repository import DeviceRepositoryMemory from majordom_integration_sdk.testing import RecordingControllerOutput from matter_server.client import MatterClient from majordom_matter import MatterController # The matter-server the tests run against. matter_server_url = os.environ.get("MATTER_SERVER_URL", "ws://localhost:5580") # the base URL: /ws, /ble BIN_DIR = Path(__file__).parent / "mvd" _MVD_LIVENESS_CHECK_S = 0.3 async def _start_mvd(device_type: str = "on-off-light") -> subprocess.Popen: stderr_file = tempfile.TemporaryFile() # noqa: SIM115 (handed to Popen; outlives this fn) proc = subprocess.Popen( [ str(BIN_DIR / device_type), "--discriminator", "3840", "--passcode", "20202021", "--capabilities", "4", "--interface-id", "eth0", ], stdout=subprocess.DEVNULL, stderr=stderr_file, preexec_fn=os.setsid, ) await asyncio.sleep(_MVD_LIVENESS_CHECK_S) if proc.poll() is not None: stderr_file.seek(0) pytest.fail( f"MVD '{device_type}' exited immediately (code {proc.returncode}): " f"{stderr_file.read().decode(errors='replace')}" ) return proc def _kill_mvd(proc: subprocess.Popen): try: os.killpg(os.getpgid(proc.pid), signal.SIGTERM) except ProcessLookupError: return try: proc.wait(timeout=2) except subprocess.TimeoutExpired: try: os.killpg(os.getpgid(proc.pid), signal.SIGKILL) proc.wait(timeout=5) except (ProcessLookupError, subprocess.TimeoutExpired): pass async def _stop_mvd(proc: subprocess.Popen): await asyncio.get_running_loop().run_in_executor(None, _kill_mvd, proc) async def _unpair_all(): """Remove every node from matter-server so each test starts from a clean fabric.""" session = ClientSession() client = MatterClient(f"{matter_server_url}/ws", session) try: await client.connect() event = asyncio.Event() task = asyncio.create_task(client.start_listening(init_ready=event)) await event.wait() for node in list(client.get_nodes()): with contextlib.suppress(Exception): await client.remove_node(node.node_id) task.cancel() finally: await client.disconnect() await session.close() @pytest_asyncio.fixture async def mvd(request): """A running virtual device on the Matter network. Defaults to on-off-light; indirectly parametrize (`@pytest.mark.parametrize("mvd", [...], indirect=True)`) to sweep other device types — see test_all_devices.py. """ device_type = getattr(request, "param", "on-off-light") await _unpair_all() proc = await _start_mvd(device_type) yield proc await _unpair_all() await _stop_mvd(proc) @pytest_asyncio.fixture async def matter(mvd): """Started MatterController (connected to matter-server) + recording output + repository.""" repository = DeviceRepositoryMemory(integration=MatterController.slug()) platform = Platform( documents_root=Path(tempfile.mkdtemp()), make_device_repository=lambda key: repository.session(), ) controller = MatterController(platform) output = controller.output = RecordingControllerOutput() controller.peripherals = Peripherals({"matter": Endpoint("matter", "matter-server", matter_server_url)}) await controller.start() yield controller, output, repository, mvd await controller.stop() ================================================================================ # FILE: tests/test_ble_delegate.py ================================================================================ """matterjs-server commissions over Bluetooth through the hub's radios (BLE proxy protocol v1).""" import asyncio import struct import pytest from aiohttp import ClientSession, web from majordom_integration_sdk.capabilities import GattCharacteristic, GattService from majordom_integration_sdk.testing import FakeBLERouter, FakeBLESource from majordom_matter.ble_delegate import MatterServerBLEDelegate MATTER = "0000fff6-0000-1000-8000-00805f9b34fb" C1, C2 = "18ee2ef5-263d-4559-959f-4f9c429f9d11", "18ee2ef5-263d-4559-959f-4f9c429f9d12" FRAME = struct.Struct(">BH") class GattError(Exception): """What bleak's BleakError and aioesphomeapi's APIConnectionError have in common: not an OSError.""" class FakeConnection: mtu = 247 def __init__(self): self.writes: list[tuple[int, bytes, bool]] = [] self.notify = None self.disconnected = False self.error: Exception | None = None # raised by writes async def services(self): characteristics = (GattCharacteristic(C1, 3, ("write",)), GattCharacteristic(C2, 5, ("indicate",))) return [GattService(MATTER, 1, characteristics)] async def read(self, handle): return b"" async def write(self, handle, data, is_response_needed=True): if self.error: raise self.error self.writes.append((handle, data, is_response_needed)) async def start_notify(self, handle, callback): self.notify = callback async def stop_notify(self, handle): ... async def disconnect(self): self.disconnected = True @pytest.fixture async def matter_server(): """A stand-in for matterjs-server's /ble endpoint; yields its URL and the backends that connect.""" backends: asyncio.Queue[web.WebSocketResponse] = asyncio.Queue() done = asyncio.Event() async def ble(request): ws = web.WebSocketResponse() await ws.prepare(request) await backends.put(ws) await done.wait() return ws app = web.Application() app.router.add_get("/ble", ble) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, "127.0.0.1", 0) await site.start() yield f"http://127.0.0.1:{runner.addresses[0][1]}/ble", backends done.set() await runner.cleanup() @pytest.fixture def radios() -> list[FakeBLESource]: return [FakeBLESource("hci0", connection=FakeConnection()), FakeBLESource("hci1", connection=FakeConnection())] @pytest.fixture async def backend(matter_server, radios): url, backends = matter_server radio = radios[0] ble = FakeBLERouter(sources=radios) await ble.start() async with ClientSession() as session: task = asyncio.create_task(MatterServerBLEDelegate(url, ble, session).run()) ws = await asyncio.wait_for(backends.get(), 5) assert await ws.receive_json() == {"type": "hello", "version": 1} await ws.send_json({"type": "hello_response", "version": 1}) yield ws, radio task.cancel() await ble.stop() async def command(ws, id: int, name: str, **args) -> dict: await ws.send_json({"id": id, "command": name, "args": args}) return await ws.receive_json(timeout=5) async def test_commissioning_runs_through_the_hub_radio(backend): ws, radio = backend radio.advertise("AA:BB", service_data={MATTER: bytes(8)}) await asyncio.sleep(0) await ws.send_json({"id": 0, "command": "start_scan", "args": {"service_uuids": ["fff6"]}}) messages = [await ws.receive_json(timeout=5) for _ in range(2)] assert {"id": 0, "success": True, "result": {}} in messages discovered = next(m["data"] for m in messages if m.get("event") == "device_discovered") assert discovered["address"] == "AA:BB" and discovered["service_data"] == {MATTER: "AAAAAAAAAAA="} assert (await command(ws, 1, "connect", address="AA:BB"))["result"] == {"connection_handle": 1, "mtu": 247} assert (await command(ws, 2, "discover_services", connection_handle=1))["result"] == { "services": [{"uuid": MATTER}] } characteristics = await command(ws, 3, "discover_characteristics", connection_handle=1, service_uuid=MATTER) assert [c["uuid"] for c in characteristics["result"]["characteristics"]] == [C1, C2] reply = await command( ws, 4, "write_and_subscribe", connection_handle=1, write_uuid=C1, write_value="aHM=", subscribe_uuid=C2 ) assert reply["success"] connection = radio.connection assert connection.writes == [(3, b"hs", True)] connection.notify(b"handshake") assert await ws.receive_bytes(timeout=5) == FRAME.pack(0x02, 1) + b"handshake" await ws.send_bytes(FRAME.pack(0x01, 1) + b"segment") async with asyncio.timeout(5): while len(connection.writes) < 2: await asyncio.sleep(0.01) assert connection.writes[1] == (3, b"segment", True) assert (await command(ws, 5, "disconnect", connection_handle=1))["success"] assert connection.disconnected async def test_failures_are_answered_with_protocol_errors(backend, radios): ws, radio = backend radio.connection = None radios[1].connection = None assert (await command(ws, 0, "connect", address="CC:DD"))["error"] == "connection_failed" assert (await command(ws, 1, "discover_services", connection_handle=9))["error"] == "not_connected" assert (await command(ws, 2, "reboot"))["error"] == "internal_error" async def test_a_failed_write_is_answered_and_the_backend_keeps_serving(backend): ws, radio = backend connection = radio.connection assert (await command(ws, 0, "connect", address="AA:BB"))["success"] assert (await command(ws, 1, "discover_characteristics", connection_handle=1, service_uuid=MATTER))["success"] connection.error = GattError("link lost") reply = await command(ws, 2, "write_characteristic", connection_handle=1, characteristic_uuid=C1, value="aHM=") assert reply["error"] == "write_failed" # a BTP segment is no request: its failure ends the connection, which matterjs-server is told about await ws.send_bytes(FRAME.pack(0x01, 1) + b"segment") assert await ws.receive_json(timeout=5) == {"event": "disconnected", "data": {"connection_handle": 1}} assert connection.disconnected connection.error = None assert (await command(ws, 3, "connect", address="AA:BB"))["result"] == {"connection_handle": 2, "mtu": 247} async def test_a_dropped_websocket_reconnects(backend, matter_server): ws, _ = backend _, backends = matter_server await ws.close() ws = await asyncio.wait_for(backends.get(), 5) assert await ws.receive_json(timeout=5) == {"type": "hello", "version": 1} async def test_a_connection_leases_the_strongest_source_until_it_is_gone(backend, radios): ws, hci0 = backend hci1 = radios[1] hci0.advertise("AA:BB", rssi=-80) hci1.advertise("AA:BB", rssi=-40) await asyncio.sleep(0) assert (await command(ws, 0, "connect", address="AA:BB"))["success"] assert hci1.connected == ["AA:BB"] and hci0.connected == [] assert hci1.on_advertisement is None and hci0.on_advertisement assert (await command(ws, 1, "disconnect", connection_handle=1))["success"] assert hci1.on_advertisement async def test_a_busy_source_fails_the_connect_and_a_lost_link_releases_it(backend, radios): ws, hci0 = backend hci0.advertise("AA:BB") await asyncio.sleep(0) assert (await command(ws, 0, "connect", address="AA:BB", timeout=300))["success"] reply = await command(ws, 1, "connect", address="AA:BB", timeout=300) assert reply["error"] == "connection_failed" await command(ws, 2, "discover_characteristics", connection_handle=1, service_uuid=MATTER) await command(ws, 3, "write_characteristic", connection_handle=1, characteristic_uuid=C1, value="aHM=") hci0.connection.error = GattError("link lost") await ws.send_bytes(FRAME.pack(0x01, 1) + b"segment") assert (await ws.receive_json(timeout=5))["event"] == "disconnected" async with asyncio.timeout(5): while not hci0.on_advertisement: await asyncio.sleep(0.01) async def test_a_dropped_websocket_releases_the_leased_source(backend, matter_server): ws, radio = backend radio.advertise("AA:BB") await asyncio.sleep(0) assert (await command(ws, 0, "connect", address="AA:BB"))["success"] assert radio.on_advertisement is None await ws.close() async with asyncio.timeout(5): while not radio.on_advertisement: await asyncio.sleep(0.01) assert radio.connection.disconnected ================================================================================ # FILE: tests/test_ble_modes.py ================================================================================ """Bluetooth for commissioning: the hub's router, or matterjs-server's own adapter when no router holds the adapters.""" import asyncio import json from dataclasses import replace from functools import partial from pathlib import Path from typing import Any, cast import pytest from majordom_integration_sdk import Endpoint, PeripheralChange, Peripherals from majordom_integration_sdk.runtime import MemoryDisabledStore, PeripheralState, Runtime from majordom_integration_sdk.schemas.device import CredentialsType, ProvidedCredentials from majordom_integration_sdk.testing import ( FakeBLERouter, FakeBLESource, FakeCompose, FakePeripheral, RecordingControllerOutput, RecordingRuntimeOutput, build_test_platform, ) from matter_server.common.errors import NodeCommissionFailed import majordom_matter from majordom_matter import MatterController from majordom_matter.testing import FakeMatterClient, FakeMatterServer, draft_for SERVER = Endpoint("matter", "matter-server", "ws://matter-server") COMMISSIONABLE = "0000fff6-0000-1000-8000-00805f9b34fb" BY_CODE = "Matter device (enter its pairing code)" @pytest.fixture def fake_server(monkeypatch): monkeypatch.setattr("majordom_matter.controller.MatterClient", partial(FakeMatterClient, server=FakeMatterServer())) monkeypatch.setattr("majordom_matter.controller.MatterServerBLEDelegate.run", lambda self: asyncio.sleep(3600)) async def started(router: FakeBLERouter | None, server: Endpoint = SERVER) -> MatterController: controller = MatterController(build_test_platform()) controller.peripherals = Peripherals({"matter": server} | ({"ble": router.endpoint} if router else {})) controller.output = RecordingControllerOutput() await controller.start() return controller def by_ble(controller: MatterController) -> list[str]: return [d.device_name for d in controller.discoveries.values() if d.transport == "BLE"] async def test_through_the_router_it_lists_the_devices_waiting_over_bluetooth(fake_server): radio = FakeBLESource("hci0") router = FakeBLERouter([radio]) await router.start() controller = await started(router) # opcode 0, discriminator 0xF00, vendor 0xFFF1, product 0x8000 radio.advertise("AA", local_name="bulb", service_data={COMMISSIONABLE: bytes([0, 0, 0x0F, 0xF1, 0xFF, 0, 0x80, 0])}) await asyncio.sleep(0.05) assert by_ble(controller) == ["bulb"] await controller.stop() await router.stop() async def test_without_the_router_or_an_adapter_it_hears_no_bluetooth(fake_server): controller = await started(None, replace(SERVER, params={"adapter": ""})) # our matterjs-server, no adapter bound assert by_ble(controller) == [] await controller.stop() async def test_with_an_adapter_of_its_own_it_takes_a_pairing_code_for_matterjs_server_to_find_the_device(fake_server): radio = FakeBLESource("hci0") router = FakeBLERouter([radio]) await router.start() controller = await started(router, replace(SERVER, params={"adapter": "hci1"})) output = cast(RecordingControllerOutput, controller.output) assert by_ble(controller) == [BY_CODE] radio.advertise("AA", local_name="bulb", service_data={COMMISSIONABLE: bytes([0, 0, 0x0F, 0xF1, 0xFF, 0, 0x80, 0])}) await asyncio.sleep(0.05) assert by_ble(controller) == [BY_CODE] # the router isn't used (by_code,) = (d for d in controller.discoveries.values() if d.transport == "BLE") draft = await controller.pair_device( by_code, draft_for(by_code), ProvidedCredentials(type=CredentialsType.code, value="3497-011-2332") ) assert draft.parameters and output.connected_devices == [] # the Hub reports it once saved assert by_code.id in controller.discoveries # offered again for the next device assert [d.id for d in output.received_discoveries].count(by_code.id) == 2 await controller.stop() await router.stop() async def test_a_failed_pairing_by_code_keeps_its_discovery(fake_server, monkeypatch): async def not_found(self: FakeMatterClient, code: str, network_only: bool = False): raise NodeCommissionFailed("no device answers this code") monkeypatch.setattr(FakeMatterClient, "commission_with_code", not_found) controller = await started(None, replace(SERVER, params={"adapter": "hci0"})) (by_code,) = (d for d in controller.discoveries.values() if d.transport == "BLE") with pytest.raises(NodeCommissionFailed): await controller.pair_device( by_code, draft_for(by_code), ProvidedCredentials(type=CredentialsType.code, value="3497-011-2332") ) assert by_ble(controller) == [BY_CODE] await controller.stop() async def test_a_pairing_by_code_that_lands_after_stop_still_returns_its_device(fake_server, monkeypatch): controller = await started(None, replace(SERVER, params={"adapter": "hci0"})) (by_code,) = (d for d in controller.discoveries.values() if d.transport == "BLE") is_answered = asyncio.Event() commission_with_code = FakeMatterClient.commission_with_code async def answered_late(self: FakeMatterClient, code: str, network_only: bool = False): await is_answered.wait() return await commission_with_code(self, code, network_only) monkeypatch.setattr(FakeMatterClient, "commission_with_code", answered_late) credentials = ProvidedCredentials(type=CredentialsType.code, value="3497-011-2332") pairing = asyncio.create_task(controller.pair_device(by_code, draft_for(by_code), credentials)) await asyncio.sleep(0.05) await controller.stop() is_answered.set() draft = await pairing assert draft.integration_data.node_id # the Hub saves it: Matter's next start follows it assert cast(RecordingControllerOutput, controller.output).connected_devices == [] assert controller.discoveries == {} # nothing offered by a stopped Matter async def test_through_the_router_losing_it_restarts_matter_and_stop_lets_it_go(fake_server): router = FakeBLERouter([FakeBLESource("hci0")]) await router.start() controller = await started(router) assert len(router.registrations) == 1 assert not await controller.needed_peripheral_did_change(PeripheralChange("ble", router.endpoint, None)) await controller.stop() assert router.registrations == [] await router.stop() async def test_with_an_adapter_of_its_own_it_keeps_running_as_the_router_it_doesnt_use_goes(fake_server): router = FakeBLERouter([FakeBLESource("hci1")]) await router.start() controller = await started(router, replace(SERVER, params={"adapter": "hci0"})) controller.peripherals = Peripherals({"matter": controller.peripherals.endpoint("matter")}) assert await controller.needed_peripheral_did_change(PeripheralChange("ble", router.endpoint, None)) await controller.stop() await router.stop() async def hub( tmp_path: Path, router: FakeBLERouter, *, is_router_disabled: bool = False, adapter: str = "" ) -> tuple[Runtime, MatterController]: """A hub with hci0 running Matter, once its controller runs.""" hci0 = Endpoint("ble", "bluez", "hci0", params={"index": "0"}, instance=FakeBLESource("hci0")) host = FakePeripheral("host", provides=[Endpoint("ip", is_shared=True), hci0]) exported = majordom_matter.peripherals(build_test_platform(tmp_path / "peripherals")) (controller,) = (p for p in exported if isinstance(p, MatterController)) runtime = Runtime( tmp_path, [host, FakeCompose(), router, *exported], platform=controller.platform, output=RecordingRuntimeOutput(), disabled=MemoryDisabledStore([router.key] if is_router_disabled else []), retry_delays=(0.01,), ) await runtime.start() async with asyncio.timeout(2): while not ( runtime.status(controller).state == PeripheralState.RUNNING and controller.peripherals.endpoint("matter").params.get("adapter") == adapter ): await asyncio.sleep(0.01) return runtime, controller async def matterjs_server(tmp_path: Path, *, is_router_disabled: bool) -> tuple[dict[str, Any], Endpoint]: """matterjs-server's compose as the runtime renders it on a hub with hci0, and the endpoint the controller gets.""" adapter = "hci0" if is_router_disabled else "" runtime, controller = await hub(tmp_path, FakeBLERouter(), is_router_disabled=is_router_disabled, adapter=adapter) compose = json.loads((tmp_path / "peripherals" / "compose" / "compose.json").read_text()) await runtime.stop() return compose["services"]["matterjs-server"], controller.peripherals.endpoint("matter") async def test_through_the_router_matterjs_server_proxies_bluetooth_and_stays_off_the_system_bus(tmp_path, fake_server): service, matter = await matterjs_server(tmp_path, is_router_disabled=False) environment = service["environment"] assert (environment.get("BLE_PROXY"), environment.get("BLUETOOTH_ADAPTER"), environment.get("NOBLE_BINDINGS")) == ( "true", None, # empty: left out None, ) assert service["volumes"] == [f"{tmp_path}/peripherals/matterjs-server:/data"] assert matter.params["adapter"] == "" async def test_without_the_router_matterjs_server_drives_an_adapter_through_bluez(tmp_path, fake_server): service, matter = await matterjs_server(tmp_path, is_router_disabled=True) environment = service["environment"] assert (environment.get("BLE_PROXY"), environment.get("BLUETOOTH_ADAPTER"), environment.get("NOBLE_BINDINGS")) == ( None, "0", "dbus", ) assert service["volumes"] == [f"{tmp_path}/peripherals/matterjs-server:/data", "/run/dbus:/run/dbus:ro"] assert matter.params["adapter"] == "hci0" async def test_disabling_the_router_hands_matterjs_server_an_adapter_and_enabling_it_takes_it_back( tmp_path, fake_server ): router = FakeBLERouter() runtime, controller = await hub(tmp_path, router) def runs_with(adapter: str) -> bool: is_running = runtime.status(controller).state == PeripheralState.RUNNING return is_running and controller.peripherals.endpoint("matter").params.get("adapter") == adapter await runtime.disable(router) async with asyncio.timeout(2): while not runs_with("hci0"): await asyncio.sleep(0.01) assert by_ble(controller) == [BY_CODE] await runtime.enable(router) async with asyncio.timeout(2): while not runs_with(""): await asyncio.sleep(0.01) assert by_ble(controller) == [] assert controller._ble_cancel is not None # the router is lent again await runtime.stop() async def test_a_router_that_fails_hands_matterjs_server_an_adapter(tmp_path, fake_server): class Broken(FakeBLERouter): async def start(self): raise RuntimeError("no D-Bus") router = Broken() runtime, controller = await hub(tmp_path, router, adapter="hci0") async with asyncio.timeout(2): # the router's retries, then Matter's restart with the adapter, settle in turn while not (runtime.status(router).state == PeripheralState.FAILED and by_ble(controller) == [BY_CODE]): await asyncio.sleep(0.01) await runtime.stop() class LateRouter(FakeBLERouter): """A router that comes up only once let: after Matter runs.""" def __init__(self, sources: list[FakeBLESource]): super().__init__(sources) self.is_let = asyncio.Event() async def start(self): await self.is_let.wait() await super().start() async def test_a_router_coming_up_after_matter_is_taken_without_a_restart(tmp_path, fake_server): radio = FakeBLESource("hci1") router = LateRouter([radio]) runtime, controller = await hub(tmp_path, router) router.is_let.set() async with asyncio.timeout(2): while "ble" not in controller.peripherals.bound: await asyncio.sleep(0.01) radio.advertise("AA", local_name="bulb", service_data={COMMISSIONABLE: bytes([0, 0, 0x0F, 0xF1, 0xFF, 0, 0x80, 0])}) await asyncio.sleep(0.05) assert by_ble(controller) == ["bulb"] statuses = cast(RecordingRuntimeOutput, runtime.output).statuses assert [status.state for key, status in statuses if key == "matter"].count(PeripheralState.STARTING) == 1 await runtime.stop() ================================================================================ # FILE: tests/test_client.py ================================================================================ """The controller's matter-server client, in the order matterjs-server sends events.""" from unittest.mock import Mock from aiohttp import ClientSession from matter_server.common.models import EventMessage, EventType from majordom_matter.controller import MatterClient from majordom_matter.testing import load_on_off_light_node def test_an_attribute_update_may_come_before_its_node(): client = MatterClient("ws://matter-server/ws", Mock(spec=ClientSession)) node = load_on_off_light_node() client._nodes[node.node_id] = node updated = [] client.subscribe_events(lambda event, data: updated.append(data), EventType.ATTRIBUTE_UPDATED) # a node just commissioned, announced only after its first attributes client._handle_event_message(EventMessage(EventType.ATTRIBUTE_UPDATED, [node.node_id + 1, "0/40/5", "new"])) client._handle_event_message(EventMessage(EventType.ATTRIBUTE_UPDATED, [node.node_id, "0/40/5", "known"])) assert updated == ["known"] ================================================================================ # FILE: tests/test_command_parameters.py ================================================================================ """Command -> Parameter mapping: a command with arguments is a `struct` whose `fields` are its arguments, and its value is keyed by those sub-parameter ids (see the SDK's ParameterDataType).""" import base64 import inspect from typing import cast, get_type_hints from uuid import UUID, uuid4, uuid5 from chip.clusters import Objects from chip.clusters.ClusterObjects import Cluster, ClusterCommand from chip.clusters.Objects import ( AccessControl, ApplicationLauncher, CameraAvStreamManagement, DoorLock, Identify, Messages, OnOff, ServiceArea, TemperatureControl, TemperatureMeasurement, Thermostat, ThreadNetworkDirectory, TlsClientManagement, ) from majordom_integration_sdk.schemas.parameter import ParameterDataType, ParameterUnit, ParameterVisibility from matter_server.client.models.node import MatterNode from majordom_matter.mapper import MatterMapper, _unwrap_optional from majordom_matter.matter_spec import ATTRIBUTE_UNITS, MAIN_PARAMETER_BY_CLUSTER, AttributeKey from majordom_matter.matter_spec_ha import MATTER_HA_ATTRIBUTE_UX DEVICE_ID = UUID(int=1) class _FakeNode: def get_attribute_value(self, endpoint_id, cluster_id, attribute_id): return None # no AcceptedCommandList -> every client command maps def _mapper() -> MatterMapper: return MatterMapper(lambda s: uuid4(), uuid5) def _command(cluster, command_cls): params = _mapper().parse_commands(DEVICE_ID, 1, cluster.id, cluster, cast(MatterNode, _FakeNode())) return next(p for p in params if p.integration_data.command_id == command_cls.command_id) def _field(cluster, command_cls, name: str): return next(f for f in _command(cluster, command_cls).fields if f.name == name) def test_command_with_arguments_is_a_struct_of_its_fields(): param = _command(Identify, Identify.Commands.Identify) assert param.data_type == ParameterDataType.struct assert [(f.name, f.data_type) for f in param.fields] == [("identifyTime", ParameterDataType.integer)] assert param.fields[0].id == _mapper().command_field_uuid(DEVICE_ID, 1, Identify.id, 0x00, "identifyTime") def test_command_without_arguments_stays_a_button(): param = _command(OnOff, OnOff.Commands.Toggle) assert param.data_type == ParameterDataType.none assert param.fields is None def test_nested_struct_and_list_arguments_are_opaque_data(): assert _field(ApplicationLauncher, ApplicationLauncher.Commands.HideApp, "application").data_type == ( ParameterDataType.data ) assert _field(DoorLock, DoorLock.Commands.ClearCredential, "credential").data_type == ParameterDataType.data assert _field(AccessControl, AccessControl.Commands.ReviewFabricRestrictions, "arl").data_type == ( ParameterDataType.data ) assert _field(Messages, Messages.Commands.PresentMessagesRequest, "responses").data_type == ParameterDataType.data assert _field(ServiceArea, ServiceArea.Commands.SelectAreas, "newAreas").data_type == ParameterDataType.data def test_nullable_argument_maps_to_its_value_type(): assert _field(DoorLock, DoorLock.Commands.SetCredential, "userIndex").data_type == ParameterDataType.integer def test_struct_value_by_field_id_or_name(): mapper = _mapper() field_id = mapper.command_field_uuid(DEVICE_ID, 1, Identify.id, 0x00, "identifyTime") by_id = mapper.arguments_by_name(DEVICE_ID, 1, Identify.id, 0x00, Identify.Commands.Identify, {str(field_id): 5}) by_name = mapper.arguments_by_name(DEVICE_ID, 1, Identify.id, 0x00, Identify.Commands.Identify, {"identifyTime": 5}) assert by_id == by_name == {"identifyTime": 5} def test_list_argument_round_trips_as_is(): command = CameraAvStreamManagement.Commands.SetStreamPriorities data = _mapper().parse_data_for_command(command, {"streamPriorities": [1, 2]}) assert data == {"streamPriorities": [1, 2]} def test_bytes_argument_is_base64_data(): command = Thermostat.Commands.SetActivePresetRequest assert _field(Thermostat, command, "presetHandle").data_type == ParameterDataType.data data = _mapper().parse_data_for_command(command, {"presetHandle": base64.b64encode(b"\x00\xff").decode()}) assert data == {"presetHandle": b"\x00\xff"} def _pin_code_commands() -> list[tuple[type[Cluster], type]]: return [ (cluster, command) for _, cluster in inspect.getmembers(Objects, inspect.isclass) if issubclass(cluster, Cluster) and hasattr(cluster, "Commands") for _, command in inspect.getmembers(cluster.Commands, inspect.isclass) if issubclass(command, ClusterCommand) and getattr(command, "is_client", True) and _unwrap_optional(get_type_hints(command).get("PINCode")) is bytes ] def test_typed_bytes_arguments_are_utf8_text(): typed = [(cluster, command, "PINCode") for cluster, command in _pin_code_commands()] assert len(typed) >= 4 # DoorLock Lock/Unlock/UnlockWithTimeout/Unbolt typed += [ (DoorLock, DoorLock.Commands.SetCredential, "credentialData"), (TlsClientManagement, TlsClientManagement.Commands.ProvisionEndpoint, "hostname"), ] for cluster, command, name in typed: assert _field(cluster, command, name).data_type == ParameterDataType.string, (command, name) assert _mapper().parse_data_for_command(command, {name: "1234"}) == {name: b"1234"} def test_bytes_attribute_is_data_and_round_trips(): attribute = ThreadNetworkDirectory.Attributes.PreferredExtendedPanID raw = b"\xde\xad\x00\xbe\xef\x00\x01\x02" class _Node: def get_attribute_value(self, endpoint_id, cluster_id, attribute_id): return [attribute.attribute_id] if attribute_id == 0xFFFB else None class _Endpoint: def get_attribute_value(self, cluster_id, attribute_id): return raw mapper = _mapper() params = mapper.parse_attributes( DEVICE_ID, 1, ThreadNetworkDirectory.id, ThreadNetworkDirectory, _Endpoint(), cast(MatterNode, _Node()) ) assert [p.data_type for p in params] == [ParameterDataType.data] assert mapper.parse_data_for_attribute(attribute, mapper.normalize_value(raw)) == raw def test_infrastructure_commands_are_hidden(): clusters = ( Objects.IcdManagement, Objects.WiFiNetworkManagement, Objects.ThreadBorderRouterManagement, ThreadNetworkDirectory, Objects.JointFabricDatastore, Objects.JointFabricAdministrator, Objects.TlsCertificateManagement, TlsClientManagement, Objects.UnitTesting, ) for cluster in clusters: params = _mapper().parse_commands(DEVICE_ID, 1, cluster.id, cluster, cast(MatterNode, _FakeNode())) assert params and {p.visibility for p in params} == {ParameterVisibility.system}, cluster.__name__ def test_aliro_reader_commands_are_hidden(): for command in (DoorLock.Commands.SetAliroReaderConfig, DoorLock.Commands.ClearAliroReaderConfig): assert _command(DoorLock, command).visibility == ParameterVisibility.system assert _command(DoorLock, DoorLock.Commands.UnlockDoor).visibility == ParameterVisibility.user # Matter's int16 temperature types are 0.01 °C; the 8-bit Signed/UnsignedTemperature ones are 0.1 °C. TEMPERATURE_SCALES: dict[AttributeKey, float] = { **{ AttributeKey(Thermostat.id, attribute_id): 0.01 for attribute_id in (0x00, 0x01, 0x03, 0x04, 0x05, 0x06, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x31) }, AttributeKey(Thermostat.id, 0x46): 0.01, # ACCoilTemperature **{ AttributeKey(Thermostat.id, attribute_id): 0.1 for attribute_id in (0x10, 0x19, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A) }, **{AttributeKey(TemperatureControl.id, attribute_id): 0.01 for attribute_id in (0x00, 0x01, 0x02, 0x03)}, **{AttributeKey(TemperatureMeasurement.id, attribute_id): 0.01 for attribute_id in (0x00, 0x01, 0x02, 0x03)}, } def test_temperature_attributes_read_and_write_in_celsius(): mapper = _mapper() celsius = {key for key, unit in ATTRIBUTE_UNITS.items() if unit is ParameterUnit.celsius} | { AttributeKey(*key) for key, (_visibility, _role, unit) in MATTER_HA_ATTRIBUTE_UX.items() if unit == "celsius" } assert celsius == TEMPERATURE_SCALES.keys() for key, scale in TEMPERATURE_SCALES.items(): raw, expected = (3, 0.3) if scale == 0.1 else (2183, 21.83) assert mapper.apply_attribute_scale(key.cluster_id, key.attribute_id, raw) == expected, key assert mapper.parse_data_for_attribute(Thermostat.Attributes.OccupiedHeatingSetpoint, 21.83) == 2183 assert mapper.parse_data_for_attribute(Thermostat.Attributes.UnoccupiedHeatingSetpoint, 21.83) == 2183 assert mapper.parse_data_for_attribute(Thermostat.Attributes.LocalTemperatureCalibration, -0.3) == -3 assert mapper.parse_data_for_attribute(Thermostat.Attributes.MinSetpointDeadBand, 0.3) == 3 def _temperature_setpoint(values: dict[int, int]): class _Node: def get_attribute_value(self, endpoint_id, cluster_id, attribute_id): return list(values) if attribute_id == 0xFFFB else None class _Endpoint: def get_attribute_value(self, cluster_id, attribute_id): return values.get(attribute_id) params = _mapper().parse_attributes( DEVICE_ID, 1, TemperatureControl.id, TemperatureControl, _Endpoint(), cast(MatterNode, _Node()) ) return next(p for p in params if p.integration_data.attribute_id == 0x00) def test_temperature_setpoint_takes_bounds_and_step_from_the_device(): param = _temperature_setpoint({0x00: 2200, 0x01: 1600, 0x02: 3000, 0x03: 50}) assert (param.min_value, param.max_value, param.min_step, param.unit) == (16, 30, 0.5, ParameterUnit.celsius) assert _temperature_setpoint({0x00: 2200}).min_step == 0.01 def test_temperature_bounds_are_celsius(): values = {0x12: 2000, 0x03: 700, 0x04: 3000} # OccupiedHeatingSetpoint <- AbsMin/MaxHeatSetpointLimit class _Node: def get_attribute_value(self, endpoint_id, cluster_id, attribute_id): return [0x12] if attribute_id == 0xFFFB else None class _Endpoint: def get_attribute_value(self, cluster_id, attribute_id): return values.get(attribute_id) [param] = _mapper().parse_attributes( DEVICE_ID, 1, Thermostat.id, Thermostat, _Endpoint(), cast(MatterNode, _Node()) ) assert (param.min_value, param.max_value, param.unit) == (7, 30, ParameterUnit.celsius) def test_temperature_command_fields_are_celsius(): set_temperature = TemperatureControl.Commands.SetTemperature field = _field(TemperatureControl, set_temperature, "targetTemperature") assert (field.data_type, field.unit) == (ParameterDataType.decimal, ParameterUnit.celsius) default = MAIN_PARAMETER_BY_CLUSTER[TemperatureControl.id].default_params assert isinstance(default, dict) assert _mapper().parse_data_for_command(set_temperature, default) == {"targetTemperature": 2200} assert _mapper().parse_data_for_command(set_temperature, {"targetTemperature": 21.83}) == { "targetTemperature": 2183 } raise_lower = Thermostat.Commands.SetpointRaiseLower # amount is in 0.1 °C steps assert _field(Thermostat, raise_lower, "amount").unit == ParameterUnit.celsius assert _mapper().parse_data_for_command(raise_lower, {"mode": 0, "amount": 1.5})["amount"] == 15 ================================================================================ # FILE: tests/test_config.py ================================================================================ """matterjs-server's port is the runtime's to choose: the compose and the endpoint follow it.""" from types import SimpleNamespace from majordom_integration_sdk import Endpoint from majordom_matter.config import matterjs_server from majordom_matter.controller import MatterController PORTS = SimpleNamespace(api=45812) def test_prefers_its_usual_port(): assert matterjs_server().ports == {"api": 5580} def test_listens_on_the_allocated_port(): assert matterjs_server().compose["environment"]["PORT"].format(ports=PORTS) == "45812" def test_provides_its_base_url_on_the_allocated_port(): (provided,) = matterjs_server().provides assert (provided.family, provided.dialect) == ("matter", "matter-server") assert provided.url.format(ports=PORTS) == "ws://127.0.0.1:45812" # the API at /ws, BLE at /ble def test_listens_where_the_host_says(): listening = matterjs_server().compose["environment"]["LISTEN_ADDRESS"] assert listening.format(host=SimpleNamespace(listen_address="0.0.0.0")) == "0.0.0.0" # a lab harness: loopback else def test_the_controller_needs_the_router_not_the_hosts_bluetooth(): ble = next(need for need in MatterController.needs if need.family == "ble") assert ble.accepts(Endpoint("ble", "router", "router", is_shared=True)) assert not ble.accepts(Endpoint("ble", "bluez", "hci0")) assert not ble.is_required def test_keeps_credentials_out_of_its_logs(): assert matterjs_server().compose["environment"]["LOG_LEVEL"] == "warning" ================================================================================ # FILE: tests/test_controller.py ================================================================================ """Unit tests driving MatterController against a live matter-server + real MVD devices. Skipped unless MATTER_INTEGRATION_TESTS=1 (set in docker/); they need a running matter-server and the x86-64 MVD binaries, so they don't run on a bare dev machine. """ import asyncio import os import pathlib import pytest pytestmark = pytest.mark.skipif( os.environ.get("MATTER_INTEGRATION_TESTS") != "1", reason="needs matter-server + x86-64 MVD binaries — run via docker/ (plan §3.5)", ) from majordom_integration_sdk.schemas.device import CredentialsType, ProvidedCredentials async def _wait_for(predicate, timeout: float | None = None): timeout = timeout or float(os.environ.get("MATTER_DISCOVERY_TIMEOUT_S", "12")) async with asyncio.timeout(timeout): while not predicate(): await asyncio.sleep(0.1) async def test_discovers_a_matter_device(matter): controller, output, _repo, _mvd = matter await _wait_for(lambda: bool(output.received_discoveries)) discovery = output.received_discoveries[-1] assert discovery.integration == "matter" assert discovery.transport == "IP" async def _pair_draft(controller, repository, discovery): """The Hub's side: the draft in, the filled one saved, the device followed.""" from majordom_matter.testing import draft_for draft = await controller.pair_device( discovery, draft_for(discovery), ProvidedCredentials(type=CredentialsType.code, value="20202021") ) async with repository.session() as repo: await repo.save(draft) await controller.fetch(draft) return draft async def test_pairs_a_discovered_device(matter): from majordom_matter.model import MatterDevice controller, output, repository, _mvd = matter await _wait_for(lambda: bool(controller.discoveries)) discovery = next(iter(controller.discoveries.values())) draft = await _pair_draft(controller, repository, discovery) # the draft comes back under the real physical id (derived from the commissioned node) device_id = draft.physical_id assert device_id != discovery.id async with repository.session() as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) state = await repo.state(physical_id=device_id) assert device is not None and device.integration_data.node_id assert state is not None and len(state.parameters) > 0 async def test_unpairs_a_device(matter): from majordom_matter.model import MatterDevice controller, output, repository, _mvd = matter await _wait_for(lambda: bool(controller.discoveries)) discovery = next(iter(controller.discoveries.values())) draft = await _pair_draft(controller, repository, discovery) async with repository.session() as repo: device = await repo.get(physical_id=draft.physical_id, as_=MatterDevice) assert device is not None await controller.unpair(device) # removes the node from the fabric without error async def _pair(controller, output, repository): from majordom_matter.model import MatterDevice await _wait_for(lambda: bool(controller.discoveries)) discovery = next(iter(controller.discoveries.values())) draft = await _pair_draft(controller, repository, discovery) async with repository.session() as repo: return await repo.get(physical_id=draft.physical_id, as_=MatterDevice) async def test_fetch_emits_events(matter): controller, output, repository, _mvd = matter device = await _pair(controller, output, repository) before = len(output.events) await controller.fetch(device) assert len(output.events) > before, "fetch should re-read the device and emit parameter-change events" async def test_identify_runs_against_the_device(matter): controller, output, repository, _mvd = matter device = await _pair(controller, output, repository) # The on-off-light carries the Identify cluster; identify() should complete without error. await controller.identify(device) def _all_device_types() -> list[str]: """Every MVD binary fetch_mvd.sh dropped into tests/mvd — the full upstream device set.""" d = pathlib.Path(__file__).parent / "mvd" return sorted(p.name for p in d.iterdir() if p.is_file()) if d.is_dir() else [] @pytest.mark.parametrize("mvd", _all_device_types(), indirect=True) async def test_commissions_every_device_type(matter): """Commission every MVD device the canary fetched — known types and any brand-new one Google ships — so the integration's flexible mapping is exercised across the full set automatically. A new binary added by fetch_mvd.sh is covered here with no code change; the canary goes red only on a genuine commissioning/mapping failure, which is the signal to go look. (See §3.5.)""" from majordom_matter.model import MatterDevice controller, output, repository, _mvd = matter await _wait_for(lambda: bool(controller.discoveries)) discovery = next(iter(controller.discoveries.values())) draft = await _pair_draft(controller, repository, discovery) device_id = draft.physical_id async with repository.session() as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) state = await repo.state(physical_id=device_id) assert device is not None and device.integration_data.node_id, "device should commission" assert state is not None and len(state.parameters) > 0, "mapping should yield parameters" await controller.unpair(device) ================================================================================ # FILE: tests/test_controller_stub.py ================================================================================ """Controller wiring tests against the in-process FakeMatterClient — no matterjs-server, no MVD. These run in the default (non-docker) CI. They exercise discovery, pairing + parameter mapping, commands, and attribute events through the REAL controller and mapper against a faithful canned on-off-light node. The heavy real-device coverage (all 30 device types, real commissioning) lives in the dockerized MVD suite, test_controller.py. """ import asyncio import base64 import hashlib import logging from dataclasses import replace from functools import partial from typing import Any, cast from unittest.mock import AsyncMock from uuid import UUID, uuid4 import pytest import pytest_asyncio from majordom_integration_sdk import ( AbstractController, DeviceIdTakenError, Endpoint, IntegrationError, Peripherals, Platform, WifiCredentials, ) from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import CredentialsOption, CredentialsType, Discovery, ProvidedCredentials from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from matter_server.client.exceptions import CannotConnect, InvalidState from matter_server.client.models.node import MatterNode from matter_server.common.errors import UnknownError from majordom_matter import MatterController from majordom_matter.exceptions import MatterConnectionError, MatterUnexpectedError from majordom_matter.mapper import MatterMapper from majordom_matter.model import MatterDevice, MatterDeviceIntegrationData, MatterDeviceState, MatterParameterTypeEnum from majordom_matter.testing import FakeMatterClient, FakeMatterServer, draft_for, load_on_off_light_node FAKE_NODE_ID = 46 # matches fixtures/on_off_light_node.json SERVER = Peripherals({"matter": Endpoint("matter", "matter-server", "ws://matter-server")}) def _matter(platform: Platform) -> MatterController: controller = MatterController(platform) controller.peripherals = SERVER controller.output = RecordingControllerOutput() return controller @pytest_asyncio.fixture async def controller(monkeypatch): """A started MatterController whose matterjs-server client is the in-process fake.""" monkeypatch.setattr("majordom_matter.controller.MatterClient", partial(FakeMatterClient, server=FakeMatterServer())) monkeypatch.setattr(MatterController, "_RECONNECT_DELAY", 0.01) monkeypatch.setattr(MatterController, "_UNREACHABLE_AFTER", 0.0) # at the first failed reconnect controller = _matter(build_test_platform()) await controller.start() yield controller, controller.output await controller.stop() async def _wait(predicate, timeout: float = 5.0): async with asyncio.timeout(timeout): while not predicate(): await asyncio.sleep(0.02) async def _commission(controller) -> UUID: """Pair as the Hub does: returns the real device id.""" await _wait(lambda: bool(controller.discoveries)) discovery = next(iter(controller.discoveries.values())) draft = await _pair(controller, discovery, ProvidedCredentials(type=CredentialsType.code, value="20202021")) return draft.physical_id async def _pair(controller, discovery: Discovery, credentials: ProvidedCredentials | None) -> MatterDeviceState: """The Hub's side of a pairing: the draft goes in, then it saves what comes back, connects and fetches.""" draft = await controller.pair_device(discovery, draft_for(discovery), credentials) async with controller.platform.device_repository(controller) as repo: await repo.save(draft) if draft.available: await controller.output.controller_did_connect_device(controller, physical_id=draft.physical_id) await controller.fetch(draft) return draft async def test_discovers_the_canned_node(controller): ctrl, _output = controller await _wait(lambda: bool(ctrl.discoveries)) discovery = next(iter(ctrl.discoveries.values())) assert discovery.integration == "matter" assert discovery.transport == "IP" assert CredentialsType.code in discovery.expected_credentials_options async def test_pairs_and_maps_parameters(controller): ctrl, output = controller device_id = await _commission(ctrl) assert output.connected_devices == [device_id] async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) state = await repo.state(physical_id=device_id) assert device is not None and device.integration_data.node_id == FAKE_NODE_ID # The on-off-light exposes the OnOff cluster (endpoint 13) → at least a toggle command maps. assert state is not None and len(state.parameters) > 0 async def test_send_command_reaches_the_client(controller): ctrl, _output = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) state = await repo.state(physical_id=device_id, as_=MatterDeviceState) command_param = next(p for p in state.parameters if p.integration_data.type is MatterParameterTypeEnum.command) await ctrl.send_command( DeviceCommand(device_id=device_id, parameter_id=command_param.id, value=None), device, command_param ) # The fake records the outgoing command against the node's endpoint. assert ctrl._matter_client.sent_commands, "send_command should reach the matter client" node_id, endpoint_id, _cmd = ctrl._matter_client.sent_commands[-1] assert node_id == FAKE_NODE_ID and endpoint_id == command_param.integration_data.endpoint_id async def test_attribute_update_becomes_an_event(controller): ctrl, output = controller device_id = await _commission(ctrl) before = len(output.events) # Simulate the device pushing a new OnOff value; the subscription should surface an event. ctrl._matter_client.fire_attribute_update("13/6/0", True) await _wait(lambda: len(output.events) > before) event = output.events[-1] assert event.physical_id == device_id async def test_unpair_removes_the_node(controller): ctrl, _output = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) await ctrl.unpair(device) assert FAKE_NODE_ID in ctrl._matter_client.removed_nodes async def test_fetch_emits_events(controller): ctrl, output = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) before = len(output.events) await ctrl.fetch(device) assert len(output.events) > before, "fetch should emit a DeviceParameterChange per attribute" async def test_identify_sends_identify_command(controller): from chip.clusters.Objects import Identify ctrl, _output = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) await ctrl.identify(device) # The on-off-light carries the Identify cluster (3) on its application endpoint. assert any(isinstance(cmd, Identify.Commands.Identify) for _n, _ep, cmd in ctrl._matter_client.sent_commands), ( "identify should send an Identify command to the node's Identify cluster" ) async def test_start_populates_discoveries_and_stop_clears(controller): # start() ran in the fixture and should have surfaced the canned node as a discovery; # stop() must clear that state (background tasks + discoveries) without error. ctrl, _output = controller await _wait(lambda: bool(ctrl.discoveries)) assert ctrl.discoveries, "start() should surface the discovered node" await ctrl.stop() assert ctrl.discoveries == {}, "stop() should clear discoveries" async def _move_to_level_parameter(ctrl, device_id: UUID): from chip.clusters.Objects import LevelControl async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) state = await repo.state(physical_id=device_id, as_=MatterDeviceState) param_id = ctrl._mapper.command_parameter_uuid( device_id, 13, LevelControl.id, LevelControl.Commands.MoveToLevel.command_id ) return device, state, next(p for p in state.parameters if p.id == param_id) async def test_command_with_arguments_is_a_struct(controller): from majordom_integration_sdk.schemas.parameter import ParameterDataType ctrl, _output = controller device_id = await _commission(ctrl) _device, _state, param = await _move_to_level_parameter(ctrl, device_id) assert param.data_type == ParameterDataType.struct assert param.fields async def test_struct_value_reaches_the_device_by_field_id_or_name(controller): from chip.clusters.Objects import LevelControl from chip.tlv import uint ctrl, _output = controller device_id = await _commission(ctrl) device, _state, param = await _move_to_level_parameter(ctrl, device_id) field_id = ctrl._mapper.command_field_uuid(device_id, 13, LevelControl.id, 0x00, "level") for value in ({str(field_id): 7}, {"level": 7}): await ctrl.send_command(DeviceCommand(device_id=device_id, parameter_id=param.id, value=value), device, param) _node_id, _endpoint_id, cmd = ctrl._matter_client.sent_commands[-1] assert cmd == LevelControl.Commands.MoveToLevel(level=uint(7)) async def test_struct_command_main_parameter_taps_its_default_arguments(controller, monkeypatch): from chip.clusters.Objects import LevelControl from chip.tlv import uint from majordom_matter.matter_spec import MainParameterSpec monkeypatch.setattr( "majordom_matter.controller.MAIN_PARAMETER_BY_CLUSTER", {LevelControl.id: MainParameterSpec(0x00, {"level": 9})}, ) ctrl, _output = controller device_id = await _commission(ctrl) device, state, param = await _move_to_level_parameter(ctrl, device_id) assert state.main_parameter == param.id and state.can_set_main_parameter(param.id) field_id = ctrl._mapper.command_field_uuid(device_id, 13, LevelControl.id, 0x00, "level") assert param.default_value == {str(field_id): 9} assert MatterDeviceState.model_validate(state.model_dump(mode="json")).parameters_dict[param.id].default_value == ( {str(field_id): 9} ) tap = param.main_cycle[0] await ctrl.send_command(DeviceCommand(device_id=device_id, parameter_id=param.id, value=tap), device, param) assert ctrl._matter_client.sent_commands[-1][2] == LevelControl.Commands.MoveToLevel(level=uint(9)) async def _discovery_over(ctrl, transport: str) -> Discovery: """The canned node's discovery re-advertised over `transport`, offering both code and QR.""" await _wait(lambda: bool(ctrl.discoveries)) discovery = next(iter(ctrl.discoveries.values())).model_copy( update={"transport": transport, "expected_credentials_options": [CredentialsType.code, CredentialsType.qr]} ) ctrl._majordom_descoveries[discovery.id] = discovery return discovery def _spy_commissioning(ctrl) -> tuple[AsyncMock, AsyncMock]: client = ctrl._matter_client client.commission_with_code = AsyncMock(wraps=client.commission_with_code) client.commission_on_network = AsyncMock(wraps=client.commission_on_network) return client.commission_with_code, client.commission_on_network async def test_qr_on_network_discovery_commissions_network_only(controller): # matterjs-server may run without Bluetooth; a non-network_only QR # commission fails there with "Bluetooth commissioning is not available". ctrl, _output = controller discovery = await _discovery_over(ctrl, "IP") with_code, _on_network = _spy_commissioning(ctrl) await _pair(ctrl, discovery, ProvidedCredentials(type=CredentialsType.qr, value="MT:Y.K9042C00KA0648G00")) with_code.assert_awaited_once_with("MT:Y.K9042C00KA0648G00", network_only=True) async def test_qr_on_ble_discovery_keeps_ble_commissioning(controller): ctrl, _output = controller discovery = await _discovery_over(ctrl, "BLE") with_code, _on_network = _spy_commissioning(ctrl) await _pair(ctrl, discovery, ProvidedCredentials(type=CredentialsType.qr, value="MT:Y.K9042C00KA0648G00")) with_code.assert_awaited_once() assert with_code.await_args is not None and with_code.await_args.kwargs.get("network_only", False) is False async def test_code_on_network_discovery_commissions_manual_code_network_only(controller): # commission_on_network takes the raw setup PIN, not the 11-digit manual pairing code. ctrl, _output = controller discovery = await _discovery_over(ctrl, "IP") with_code, on_network = _spy_commissioning(ctrl) await _pair(ctrl, discovery, ProvidedCredentials(type=CredentialsType.code, value="3497-011-2332")) with_code.assert_awaited_once_with("34970112332", network_only=True) on_network.assert_not_awaited() @pytest.mark.parametrize(("pairing_hint", "is_on_network"), [(None, True), (0x0002, False)]) def test_code_option_offers_the_matter_manual_code_mask(pairing_hint: int | None, is_on_network: bool): mapper = MatterMapper(lambda s: uuid4(), lambda d, s: uuid4()) options = mapper.define_credentials_options(1, pairing_hint, is_on_network=is_on_network) assert options == [CredentialsType.code] assert isinstance(options[0], CredentialsOption) assert options[0].mask == "DDDD-DDD-DDDD" async def test_raw_setup_pin_on_network_discovery_commissions_on_network(controller): # 8 digits is the raw setup PIN, which only commission_on_network accepts. ctrl, _output = controller discovery = await _discovery_over(ctrl, "IP") with_code, on_network = _spy_commissioning(ctrl) await _pair(ctrl, discovery, ProvidedCredentials(type=CredentialsType.code, value="2020-2021")) on_network.assert_awaited_once_with(20202021) with_code.assert_not_awaited() async def test_raw_setup_pin_on_ble_discovery_is_rejected(controller): # A BLE-only device has no IP yet, and a raw PIN carries no discriminator for a BLE scan. ctrl, _output = controller discovery = await _discovery_over(ctrl, "BLE") with_code, on_network = _spy_commissioning(ctrl) with pytest.raises(ValueError, match="setup PIN"): await _pair(ctrl, discovery, ProvidedCredentials(type=CredentialsType.code, value="20202021")) with_code.assert_not_awaited() on_network.assert_not_awaited() @pytest.mark.parametrize( ("transport", "value", "expected_code"), [ ("BLE", "3497-011-2332", "34970112332"), ("IP", "3497 0112 3320 0000 0001 2", "349701123320000000012"), ("IP", "MT:Y.K9042C00KA0648G00", "MT:Y.K9042C00KA0648G00"), ], ) async def test_manual_and_qr_codes_entered_as_code_commission_with_code( controller, transport: str, value: str, expected_code: str ): ctrl, _output = controller discovery = await _discovery_over(ctrl, transport) with_code, on_network = _spy_commissioning(ctrl) await _pair(ctrl, discovery, ProvidedCredentials(type=CredentialsType.code, value=value)) with_code.assert_awaited_once_with(expected_code, network_only=transport != "BLE") on_network.assert_not_awaited() @pytest.mark.parametrize("value", ["12345", "123456789012", "not a code"]) async def test_pairing_code_of_unknown_length_is_rejected(controller, value: str): ctrl, _output = controller discovery = await _discovery_over(ctrl, "IP") with_code, on_network = _spy_commissioning(ctrl) with pytest.raises(ValueError, match="pairing code"): await _pair(ctrl, discovery, ProvidedCredentials(type=CredentialsType.code, value=value)) with_code.assert_not_awaited() on_network.assert_not_awaited() async def test_timed_invoke_follows_the_command(controller, monkeypatch): from chip.clusters.Objects import AdministratorCommissioning, OnOff ctrl, _output = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) state = await repo.state(physical_id=device_id, as_=MatterDeviceState) timeouts: list[int | None] = [] async def send_device_command(node_id, endpoint_id, command, timed_request_timeout_ms=None, **kwargs): timeouts.append(timed_request_timeout_ms) monkeypatch.setattr(ctrl._matter_client, "send_device_command", send_device_command) for endpoint_id, cluster_id, command_id in ( (0, AdministratorCommissioning.id, AdministratorCommissioning.Commands.RevokeCommissioning.command_id), (13, OnOff.id, OnOff.Commands.Toggle.command_id), ): param_id = ctrl._mapper.command_parameter_uuid(device_id, endpoint_id, cluster_id, command_id) param = next(p for p in state.parameters if p.id == param_id) await ctrl.send_command(DeviceCommand(device_id=device_id, parameter_id=param.id, value=None), device, param) assert timeouts == [1000, None] async def test_hidden_main_candidate_does_not_block_a_visible_one(controller, monkeypatch): from chip.clusters.Objects import LevelControl, OnOff from majordom_matter.matter_spec import MainParameterSpec monkeypatch.setattr( "majordom_matter.controller.MAIN_PARAMETER_BY_CLUSTER", { LevelControl.id: MainParameterSpec(LevelControl.Commands.Step.command_id, None), # a `setting` OnOff.id: MainParameterSpec(OnOff.Commands.Toggle.command_id, None), }, ) ctrl, _output = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: state = await repo.state(physical_id=device_id, as_=MatterDeviceState) assert state.main_parameter == ctrl._mapper.command_parameter_uuid(device_id, 13, OnOff.id, 0x02) assert state.can_set_main_parameter(state.main_parameter) async def test_fetch_normalizes_values_like_the_subscription(controller): from chip.clusters.Objects import BasicInformation, Descriptor, NetworkCommissioning ctrl, output = controller device_id = await _commission(ctrl) output.events.clear() # the pairing's fetch async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) last_network_id = ctrl._mapper.attribute_parameter_uuid(device_id, 0, NetworkCommissioning.id, 0x06) server_list = ctrl._mapper.attribute_parameter_uuid(device_id, 0, Descriptor.id, 0x01) capability_minima = ctrl._mapper.attribute_parameter_uuid(device_id, 0, BasicInformation.id, 0x13) ctrl._matter_client.fire_attribute_update("0/49/6", b"\x01\x02\xff") # bytes await _wait(lambda: any(e.parameter_id == last_network_id for e in output.events)) subscribed = next(e.value for e in output.events if e.parameter_id == last_network_id) before = len(output.events) await ctrl.fetch(device) fetched = {e.parameter_id: e.value for e in output.events[before:]} assert fetched[last_network_id] == subscribed == "AQL/" assert fetched[server_list] == [29, 31, 40, 42, 48, 49, 50, 51, 52, 60, 62, 63, 64] assert fetched[capability_minima] == {"caseSessionsPerFabric": 3, "subscriptionsPerFabric": 65535} async def test_subscription_parses_raw_json_like_fetch(controller): from chip.clusters.Objects import BasicInformation, ElectricalEnergyMeasurement from matter_server.common.models import EventType ctrl, output = controller device_id = await _commission(ctrl) output.events.clear() # the pairing's fetch async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) def subscribed(parameter_id: UUID): return next((e.value for e in reversed(output.events) if e.parameter_id == parameter_id), None) # matterjs-server pushes raw JSON: a struct keyed by field id, not by name. capability_minima = ctrl._mapper.attribute_parameter_uuid(device_id, 0, BasicInformation.id, 0x13) ctrl._matter_client.fire_attribute_update("0/40/19", {"0": 4, "1": 3}) await _wait(lambda: subscribed(capability_minima) is not None) pushed = subscribed(capability_minima) before = len(output.events) await ctrl.fetch(device) fetched = {e.parameter_id: e.value for e in output.events[before:]} assert pushed == fetched[capability_minima] assert fetched[capability_minima] == {"caseSessionsPerFabric": 4, "subscriptionsPerFabric": 3} # A scaled struct: the energy (mWh) is unwrapped and scaled to kWh, as pairing/fetch do. cluster_id = ElectricalEnergyMeasurement.id energy = ctrl._mapper.attribute_parameter_uuid(device_id, 1, cluster_id, 0x01) ctrl._make_callback(device_id, energy, cluster_id, 0x01)(EventType.ATTRIBUTE_UPDATED, {"0": 5_000_000}) await _wait(lambda: subscribed(energy) is not None) parsed = ElectricalEnergyMeasurement.Structs.EnergyMeasurementStruct(energy=5_000_000) assert subscribed(energy) == ctrl._mapper.attribute_value(cluster_id, 0x01, parsed) == 5 async def test_start_hands_the_hub_networks_to_matter_server(monkeypatch): monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) controller = _matter(build_test_platform(wifi=WifiCredentials("home", "secret"), thread_dataset="0e08abcd")) await controller.start() assert cast(FakeMatterClient, controller._matter_client).networks == { "wifi": ("home", "secret"), "thread": "0e08abcd", } await controller.stop() async def _refuse(self: FakeMatterClient, *args: Any): raise UnknownError("refused") # matterjs-server answers with an error async def test_a_network_matterjs_server_refuses_at_start_leaves_matter_running(monkeypatch): monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) monkeypatch.setattr(FakeMatterClient, "set_thread_operational_dataset", _refuse) controller = _matter(build_test_platform(thread_dataset="0e08abcd")) await controller.start() # it still serves every device it has, and Wi-Fi and Ethernet ones await _wait(lambda: bool(controller.discoveries)) await controller.stop() async def test_a_network_matterjs_server_refuses_on_reconnect_leaves_matter_connected(controller, monkeypatch): ctrl, output = controller device_id = await _commission(ctrl) monkeypatch.setattr(FakeMatterClient, "set_wifi_credentials", _refuse) before, ctrl.platform = ctrl.platform, replace(ctrl.platform, wifi=WifiCredentials("home", "secret")) assert await ctrl.platform_facts_did_change(before) # in place output.connected_devices.clear() lost = cast(FakeMatterClient, ctrl._matter_client) lost.lose_server() lost.server.restore() # its container recreated await _wait(lambda: output.connected_devices == [device_id]) assert ctrl._matter_client is not lost assert output.error_log == [] @pytest.mark.parametrize( ("facts", "networks"), [ ({"thread_dataset": "0e08abcd"}, {"thread": "0e08abcd"}), ({"wifi": WifiCredentials("home", "secret")}, {"wifi": ("home", "secret")}), ], ) async def test_a_new_network_reaches_matter_server_in_place( controller, facts: dict[str, Any], networks: dict[str, Any] ): ctrl, _ = controller before, ctrl.platform = ctrl.platform, replace(ctrl.platform, **facts) assert await ctrl.platform_facts_did_change(before) await _wait(lambda: cast(FakeMatterClient, ctrl._matter_client).networks == networks) async def test_a_new_network_matter_server_doesnt_answer_holds_neither_the_hook_nor_matter(controller): ctrl, output = controller server = cast(FakeMatterClient, ctrl._matter_client).server server.is_answering = False # busy or hung, its connection open before, ctrl.platform = ctrl.platform, replace(ctrl.platform, thread_dataset="0e08abcd") assert await asyncio.wait_for(ctrl.platform_facts_did_change(before), 1) server.lose() # with the call still waiting for its answer await _wait(lambda: "server-unreachable" in output.errors) server.is_answering = True server.restore() await _wait(lambda: "server-unreachable" not in output.errors) assert cast(FakeMatterClient, ctrl._matter_client).networks == {"thread": "0e08abcd"} async def test_a_new_network_during_a_reconnect_reaches_the_new_connection(controller, monkeypatch): ctrl, _ = controller lost = cast(FakeMatterClient, ctrl._matter_client) is_listening, is_dumped = asyncio.Event(), asyncio.Event() # the node dump makes a new connection ready start_listening = FakeMatterClient.start_listening async def dumping_nodes(self: FakeMatterClient, init_ready: asyncio.Event | None = None): is_listening.set() await is_dumped.wait() await start_listening(self, init_ready) monkeypatch.setattr(FakeMatterClient, "start_listening", dumping_nodes) lost.lose_server() lost.server.restore() await asyncio.wait_for(is_listening.wait(), 1) before, ctrl.platform = ctrl.platform, replace(ctrl.platform, thread_dataset="0e08abcd") assert await ctrl.platform_facts_did_change(before) assert ctrl._matter_client is lost # not the new connection before it is ready: its node dump comes first is_dumped.set() await _wait(lambda: cast(FakeMatterClient, ctrl._matter_client).networks == {"thread": "0e08abcd"}) assert lost.networks == {} async def test_a_new_thread_network_reaches_a_lost_matter_server_once_it_is_back(controller): ctrl, output = controller lost = cast(FakeMatterClient, ctrl._matter_client) lost.lose_server() await _wait(lambda: "server-unreachable" in output.errors) before, ctrl.platform = ctrl.platform, replace(ctrl.platform, thread_dataset="0e08abcd") assert await ctrl.platform_facts_did_change(before) lost.server.restore() await _wait(lambda: "server-unreachable" not in output.errors) assert cast(FakeMatterClient, ctrl._matter_client).networks == {"thread": "0e08abcd"} async def test_a_device_whose_node_is_gone_doesnt_stop_matter_from_starting(monkeypatch): monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) controller = _matter(build_test_platform()) # left by a commissioning that failed, or a reset matterjs-server async with controller.platform.device_repository(controller) as repo: await repo.save( MatterDeviceState( id=UUID(int=7), physical_id=UUID(int=70), name="Bulb", room_id=UUID(int=1), transport="BLE", integration="matter", manufacturer=None, parameters=[], integration_data=MatterDeviceIntegrationData(node_id=0), ) ) await controller.start() assert cast(RecordingControllerOutput, controller.output).lost_devices == [UUID(int=70)] # the app hears it too await controller.stop() @pytest.mark.parametrize("credentials", [None, ProvidedCredentials(type=CredentialsType.none)]) async def test_a_node_on_the_fabric_without_a_device_is_added_as_it_is(monkeypatch, credentials): server = FakeMatterServer() server.commissioned = True # by a pairing that ended before its device was saved, or a device deleted since monkeypatch.setattr("majordom_matter.controller.MatterClient", partial(FakeMatterClient, server=server)) controller = _matter(build_test_platform()) await controller.start() (discovery,) = controller.discoveries.values() assert discovery.expected_credentials_options == [CredentialsType.none] paired = await _pair(controller, discovery, credentials) async with controller.platform.device_repository(controller) as repo: device = await repo.get(physical_id=paired.physical_id, as_=MatterDevice) assert device is not None and device.integration_data.node_id == FAKE_NODE_ID assert paired.physical_id != discovery.id assert cast(RecordingControllerOutput, controller.output).connected_devices == [paired.physical_id] assert controller.discoveries == {} await controller.stop() async def test_a_device_that_never_finished_commissioning_unpairs(controller): controller, _ = controller device = MatterDevice( id=UUID(int=8), physical_id=UUID(int=80), name="Bulb", room_id=UUID(int=1), transport="BLE", integration="matter", manufacturer=None, integration_data=MatterDeviceIntegrationData(node_id=0), ) await controller.unpair(device) assert controller._matter_client.removed_nodes == [] async def test_matter_reconnects_once_a_lost_matter_server_is_back(controller): ctrl, output = controller device_id = await _commission(ctrl) output.connected_devices.clear() lost = cast(FakeMatterClient, ctrl._matter_client) lost.lose_server() await _wait(lambda: output.lost_devices == [device_id]) await asyncio.sleep(0.1) # a few failed attempts lost.server.restore() await _wait(lambda: output.connected_devices == [device_id]) lost_server = IntegrationError("server-unreachable", "Lost the connection to the Matter server, reconnecting.") assert output.error_log == [lost_server, "server-unreachable"] # reported, then resolved output.events.clear() cast(FakeMatterClient, ctrl._matter_client).fire_attribute_update("13/6/0", True) await _wait(lambda: bool(output.events)) # subscribed again on the new connection async def test_a_matter_server_back_at_the_first_reconnect_reports_no_error(controller): ctrl, output = controller device_id = await _commission(ctrl) output.connected_devices.clear() lost = cast(FakeMatterClient, ctrl._matter_client) lost.lose_server() lost.server.restore() # e.g. its container recreated await _wait(lambda: output.connected_devices == [device_id]) assert output.error_log == [] async def test_a_lost_matter_server_is_reported_only_once_the_outage_lasted(controller, monkeypatch): ctrl, output = controller monkeypatch.setattr(MatterController, "_UNREACHABLE_AFTER", 0.3) # 15 s on a hub lost = cast(FakeMatterClient, ctrl._matter_client) lost_at = asyncio.get_running_loop().time() lost.lose_server() await asyncio.sleep(0.1) # a few failed attempts: an outage, yet maybe a container recreated assert output.error_log == [] await _wait(lambda: "server-unreachable" in output.errors) assert asyncio.get_running_loop().time() - lost_at >= 0.3 lost.server.restore() await _wait(lambda: "server-unreachable" not in output.errors) async def test_a_matter_server_dropping_every_connection_after_its_node_list_is_reported(controller, monkeypatch): """Each connection holds for a moment only: the drops add up to one outage, until a connection holds.""" ctrl, output = controller monkeypatch.setattr(MatterController, "_UNREACHABLE_AFTER", 0.3) async def dropping(self: FakeMatterClient, init_ready: asyncio.Event | None = None): if init_ready is not None: init_ready.set() # its node list await asyncio.sleep(0.05) monkeypatch.setattr(FakeMatterClient, "start_listening", dropping) server = cast(FakeMatterClient, ctrl._matter_client).server server.lose() server.restore() await _wait(lambda: "server-unreachable" in output.error_log) # reported, and cleared at the next reconnect lost_server = IntegrationError("server-unreachable", "Lost the connection to the Matter server, reconnecting.") assert output.error_log[:2] == [lost_server, "server-unreachable"] async def test_a_matter_server_dropping_every_connection_is_tried_less_and_less_often(controller, monkeypatch): ctrl, _ = controller connections = 0 async def dropping(self: FakeMatterClient, init_ready: asyncio.Event | None = None): nonlocal connections connections += 1 if init_ready is not None: init_ready.set() # its node list, then it drops monkeypatch.setattr(FakeMatterClient, "start_listening", dropping) server = cast(FakeMatterClient, ctrl._matter_client).server server.lose() server.restore() await asyncio.sleep(0.3) assert connections <= 6 # one outage: back after 0.01, 0.03, 0.07, 0.15 s, not every 10 ms async def test_a_matter_server_lost_again_soon_after_it_came_back_is_reported_at_once(controller, monkeypatch): ctrl, output = controller monkeypatch.setattr(MatterController, "_UNREACHABLE_AFTER", 0.3) server = cast(FakeMatterClient, ctrl._matter_client).server server.lose() await _wait(lambda: "server-unreachable" in output.errors) server.restore() await _wait(lambda: "server-unreachable" not in output.errors) # the devices work again server.lose() # the same outage: the connection didn't hold await asyncio.sleep(0.05) assert "server-unreachable" in output.errors async def test_a_matter_server_lost_long_after_it_came_back_is_a_new_outage(controller, monkeypatch): ctrl, output = controller monkeypatch.setattr(MatterController, "_UNREACHABLE_AFTER", 0.3) monkeypatch.setattr(MatterController, "_STABLE_CONNECTION", 0.2) # STABLE_RUN (5 min) on a hub server = cast(FakeMatterClient, ctrl._matter_client).server server.lose() await _wait(lambda: "server-unreachable" in output.errors) server.restore() await _wait(lambda: "server-unreachable" not in output.errors) await asyncio.sleep(0.3) # held: the outage ended server.lose() await asyncio.sleep(0.05) assert "server-unreachable" not in output.errors # not yet: this outage only began async def test_a_matter_server_dropping_every_connection_before_it_speaks_is_unreachable(controller, monkeypatch): ctrl, output = controller device_id = await _commission(ctrl) output.connected_devices.clear() start_listening = FakeMatterClient.start_listening async def dropped(self: FakeMatterClient, init_ready: asyncio.Event | None = None): return None # accepted, then closed before its node dump monkeypatch.setattr(FakeMatterClient, "start_listening", dropped) lost = cast(FakeMatterClient, ctrl._matter_client) lost.lose_server() lost.server.restore() await _wait(lambda: "server-unreachable" in output.errors) assert output.lost_devices == [device_id] and output.connected_devices == [] monkeypatch.setattr(FakeMatterClient, "start_listening", start_listening) await _wait(lambda: "server-unreachable" not in output.errors) assert output.connected_devices == [device_id] async def test_a_start_reports_the_devices_on_the_fabric_connected(controller): ctrl, output = controller device_id = await _commission(ctrl) await ctrl.stop() # the Hub marks its devices unavailable output.connected_devices.clear() await ctrl.start() assert output.connected_devices == [device_id] async def test_a_start_leaves_a_device_matterjs_server_cant_reach_as_the_hub_marked_it(controller): ctrl, output = controller await _commission(ctrl) server = cast(FakeMatterClient, ctrl._matter_client).server await ctrl.stop() # the Hub marks its devices unavailable, and every device at boot output.connected_devices.clear() server.node.node_data.available = False # unplugged meanwhile await ctrl.start() assert output.connected_devices == [] and output.lost_devices == [] # reported once it is back async def test_stopping_matter_while_it_reconnects(monkeypatch): server = FakeMatterServer() monkeypatch.setattr("majordom_matter.controller.MatterClient", partial(FakeMatterClient, server=server)) monkeypatch.setattr(MatterController, "_RECONNECT_DELAY", 0.01) monkeypatch.setattr(MatterController, "_UNREACHABLE_AFTER", 0.0) controller = _matter(build_test_platform()) await controller.start() server.lose() output = cast(RecordingControllerOutput, controller.output) await _wait(lambda: bool(output.errors)) await asyncio.sleep(0.1) # a few failed attempts await asyncio.wait_for(controller.stop(), 2) assert list(output.errors) == ["server-unreachable"] async def test_a_matter_server_gone_before_it_is_ready_fails_the_start(monkeypatch): class GoneAtOnce(FakeMatterClient): async def start_listening(self, init_ready: asyncio.Event | None = None): return None monkeypatch.setattr("majordom_matter.controller.MatterClient", GoneAtOnce) controller = _matter(build_test_platform()) with pytest.raises(MatterConnectionError): await asyncio.wait_for(controller.start(), 2) await controller.stop() # as the runtime does after a failed start async def test_stopping_matter_after_a_start_that_failed_late_leaves_nothing_running(monkeypatch): def unreadable(self: FakeMatterClient) -> list: raise RuntimeError("unreadable node dump") monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) monkeypatch.setattr(FakeMatterClient, "get_nodes", unreadable) controller = _matter(build_test_platform()) before = asyncio.all_tasks() with pytest.raises(RuntimeError): await controller.start() await controller.stop() assert [task for task in asyncio.all_tasks() - before if not task.done()] == [] async def test_stopping_matter_after_its_first_listener_failed(monkeypatch): class FailingListener(FakeMatterClient): async def start_listening(self, init_ready: asyncio.Event | None = None): await super().start_listening(init_ready) raise RuntimeError("listening failed") # once its matterjs-server went away server = FakeMatterServer() monkeypatch.setattr("majordom_matter.controller.MatterClient", partial(FailingListener, server=server)) monkeypatch.setattr(MatterController, "_RECONNECT_DELAY", 0.01) controller = _matter(build_test_platform()) await controller.start() first = controller._matter_client server.lose() server.restore() await _wait(lambda: controller._matter_client is not first) await asyncio.wait_for(controller.stop(), 2) async def test_stopping_matter_reports_no_error(monkeypatch): monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) controller = _matter(build_test_platform()) await controller.start() await controller.stop() await asyncio.sleep(0.1) assert cast(RecordingControllerOutput, controller.output).error_log == [] async def test_stopping_matter_ends_the_reports_a_device_started(controller): ctrl, _ = controller await _commission(ctrl) is_reporting, is_ended = asyncio.Event(), asyncio.Event() class Hung(RecordingControllerOutput): async def controller_did_receive_events(self, controller: AbstractController, events: Any): is_reporting.set() try: await asyncio.Event().wait() finally: is_ended.set() ctrl.output = Hung() cast(FakeMatterClient, ctrl._matter_client).fire_attribute_update("13/6/0", True) await asyncio.wait_for(is_reporting.wait(), 1) await ctrl.stop() assert is_ended.is_set() async def test_stopping_matter_after_a_first_start_that_couldnt_connect_closes_its_session(monkeypatch): server = FakeMatterServer() server.up = False # its port answers, its /ws doesn't yet monkeypatch.setattr("majordom_matter.controller.MatterClient", partial(FakeMatterClient, server=server)) controller = _matter(build_test_platform()) with pytest.raises(CannotConnect): await controller.start() session = controller._matter_client_session await controller.stop() # as the runtime does after a failed start assert session.closed async def test_stopping_matter_before_it_started(monkeypatch): monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) await _matter(build_test_platform()).stop() # the runtime stops one whose start never ran async def test_stopping_matter_closes_its_session_though_the_client_fails_to_disconnect(monkeypatch): async def failing(self: FakeMatterClient): raise ConnectionResetError("matterjs-server reset the connection") monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) monkeypatch.setattr(FakeMatterClient, "disconnect", failing) controller = _matter(build_test_platform()) await controller.start() session = controller._matter_client_session with pytest.raises(ConnectionResetError): await controller.stop() assert session.closed async def test_a_stopped_matter_says_it_isnt_started(controller): ctrl, _ = controller await _wait(lambda: bool(ctrl.discoveries)) discovery = next(iter(ctrl.discoveries.values())) await ctrl.stop() with pytest.raises(MatterConnectionError): await ctrl.pair_device( discovery, draft_for(discovery), ProvidedCredentials(type=CredentialsType.code, value="20202021") ) async def test_a_reconnect_that_breaks_reports_matter_crashed(controller): ctrl, _ = controller await _commission(ctrl) class Locked(RecordingControllerOutput): async def controller_did_lose_device( self, controller: AbstractController, *, physical_id: UUID | None = None, device_id: UUID | None = None ): raise RuntimeError("database is locked") # the Hub's output = ctrl.output = Locked() cast(FakeMatterClient, ctrl._matter_client).lose_server() await _wait(lambda: "crashed" in output.errors) assert not output.errors["crashed"].is_still_running # the runtime restarts Matter async def test_a_failure_other_than_an_outage_on_reconnect_reports_matter_crashed(controller, monkeypatch): ctrl, output = controller lost = cast(FakeMatterClient, ctrl._matter_client) def unreadable(self: FakeMatterClient) -> list: raise RuntimeError("unreadable node dump") monkeypatch.setattr(FakeMatterClient, "get_nodes", unreadable) lost.lose_server() lost.server.restore() await _wait(lambda: "crashed" in output.errors) assert "server-unreachable" not in output.errors # not an outage: no reconnecting forever async def test_a_pairing_landing_while_matter_reports_its_losses_leaves_it_reconnecting(controller, monkeypatch): ctrl, output = controller first = await _commission(ctrl) second = load_on_off_light_node({"0/40/15": "OTHER_SN"}) second.node_data.node_id = FAKE_NODE_ID + 1 # on the fabric without a device: added as it is on_fabric = FakeMatterClient.get_nodes monkeypatch.setattr(FakeMatterClient, "get_nodes", lambda self: [*on_fabric(self), second]) second_id = ctrl._fabric_discovery_id(second.node_id) discovery = output.received_discoveries[0].model_copy( update={"id": second_id, "expected_credentials_options": [CredentialsType.none]} ) ctrl.discoveries[second_id] = discovery # as offered at a start is_reporting = asyncio.Event() class Slow(RecordingControllerOutput): async def controller_did_lose_device( self, controller: AbstractController, *, physical_id: UUID | None = None, device_id: UUID | None = None ): is_reporting.set() await asyncio.sleep(0.1) # the Hub's write and send output = ctrl.output = Slow() lost = cast(FakeMatterClient, ctrl._matter_client) lost.lose_server() await asyncio.wait_for(is_reporting.wait(), 1) draft = await ctrl.pair_device(discovery, draft_for(discovery), None) # quick: nothing to commission assert draft.physical_id == ctrl._node_device_id(second) lost.server.restore() await _wait(lambda: set(output.connected_devices) == {first} and ctrl._matter_client is not lost) assert output.error_log == [] async def _pairing_in_flight(ctrl: MatterController) -> asyncio.Task: """A pairing whose commissioning waits for matterjs-server (a Thread one takes a minute).""" await _wait(lambda: bool(ctrl.discoveries)) discovery = next(iter(ctrl.discoveries.values())) cast(FakeMatterClient, ctrl._matter_client).server.is_answering = False credentials = ProvidedCredentials(type=CredentialsType.code, value="20202021") pairing = asyncio.create_task(_pair(ctrl, discovery, credentials)) await asyncio.sleep(0.05) return pairing async def test_a_pairing_cut_short_by_a_lost_matterjs_server_says_why(controller): ctrl, _ = controller pairing = await _pairing_in_flight(ctrl) cast(FakeMatterClient, ctrl._matter_client).lose_server() # the client cancels the calls waiting for an answer with pytest.raises(MatterConnectionError, match="ended during the pairing"): # the app says why await pairing async def test_a_pairing_cancelled_itself_stays_cancelled(controller): ctrl, _ = controller pairing = await _pairing_in_flight(ctrl) pairing.cancel() # the Hub's request ended with pytest.raises(asyncio.CancelledError): await pairing @pytest.mark.parametrize( ("call", "during"), [("send_command", "the command"), ("identify", "the identification"), ("unpair", "the unpairing")], ) async def test_a_call_cut_short_by_a_lost_matterjs_server_says_why(controller, call: str, during: str): ctrl, _ = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) state = await repo.state(physical_id=device_id, as_=MatterDeviceState) toggle = next(p for p in state.parameters if p.integration_data.type is MatterParameterTypeEnum.command) command = DeviceCommand(device_id=device_id, parameter_id=toggle.id, value=None) calls = { "send_command": lambda: ctrl.send_command(command, device, toggle), "identify": lambda: ctrl.identify(device), "unpair": lambda: ctrl.unpair(device), } server = cast(FakeMatterClient, ctrl._matter_client).server server.is_answering = False waiting = asyncio.create_task(calls[call]()) await asyncio.sleep(0.05) server.lose() # the client cancels the calls waiting for an answer with pytest.raises(MatterConnectionError, match=f"ended during {during}$"): await waiting async def test_a_matter_server_gone_during_the_hand_over_on_reconnect_is_reconnected(monkeypatch): server = FakeMatterServer() monkeypatch.setattr("majordom_matter.controller.MatterClient", partial(FakeMatterClient, server=server)) monkeypatch.setattr(MatterController, "_RECONNECT_DELAY", 0.01) controller = _matter(build_test_platform(thread_dataset="0e08abcd")) await controller.start() first = controller._matter_client server.is_answering = False server.lose() server.restore() await _wait(lambda: controller._matter_client is not first) # its hand-over waits for an answer second = controller._matter_client server.is_answering = True server.lose() # the client cancels the hand-over server.restore() await _wait(lambda: controller._matter_client is not second) assert cast(FakeMatterClient, controller._matter_client).networks == {"thread": "0e08abcd"} await controller.stop() async def test_mdns_discovery_goes_on_after_matter_server_went_away_mid_call(controller): ctrl, _ = controller server = cast(FakeMatterClient, ctrl._matter_client).server server.is_answering = False discovering = asyncio.create_task(ctrl._matter_discovery_loop(interval=0.01)) await asyncio.sleep(0.05) server.lose() # the client cancels the listing waiting for an answer await asyncio.sleep(0.05) assert not discovering.done() discovering.cancel() async def test_mdns_discovery_logs_each_outage_once_as_a_warning(controller, caplog): ctrl, _ = controller server = cast(FakeMatterClient, ctrl._matter_client).server server.lose() discovering = asyncio.create_task(ctrl._matter_discovery_loop(interval=0.01)) await asyncio.sleep(0.1) # some listings fail server.restore() await asyncio.sleep(0.1) # reconnected: listed again server.lose() await asyncio.sleep(0.1) discovering.cancel() assert [r.levelno for r in caplog.records if "discovery" in r.getMessage()] == [logging.WARNING] * 2 @pytest.fixture def uninterviewed(monkeypatch) -> MatterNode: """A node on the fabric matterjs-server hasn't interviewed yet: no attributes, so no device info.""" node = MatterNode(replace(load_on_off_light_node().node_data, node_id=9, attributes={})) on_fabric = FakeMatterClient.get_nodes monkeypatch.setattr(FakeMatterClient, "get_nodes", lambda self: [*on_fabric(self), node]) return node async def test_a_node_matterjs_server_hasnt_interviewed_is_left_out_at_start(monkeypatch, uninterviewed): monkeypatch.setattr("majordom_matter.controller.MatterClient", FakeMatterClient) controller = _matter(build_test_platform()) await controller.start() await _wait(lambda: bool(controller.discoveries)) assert [d.device_name for d in controller.discoveries.values()] == ["TEST_PRODUCT"] # the commissionable one await controller.stop() async def test_a_node_matterjs_server_hasnt_interviewed_doesnt_stop_a_pairing(controller, uninterviewed): ctrl, output = controller await _commission(ctrl) assert output.connected_devices async def test_a_pairing_reports_and_saves_nothing_it_is_the_hubs_to_do(controller): ctrl, output = controller await _wait(lambda: bool(ctrl.discoveries)) (discovery,) = ctrl.discoveries.values() draft = await ctrl.pair_device( discovery, draft_for(discovery), ProvidedCredentials(type=CredentialsType.code, value="20202021") ) node = cast(FakeMatterClient, ctrl._matter_client).get_node(FAKE_NODE_ID) assert draft.physical_id == ctrl._node_device_id(node) assert draft.integration_data.node_id == FAKE_NODE_ID and draft.parameters and draft.available assert output.connected_devices == [] and output.events == [] async with ctrl.platform.device_repository(ctrl) as repo: assert await repo.get(physical_id=draft.physical_id) is None async def test_a_failure_after_the_commissioning_leaves_the_node_on_the_fabric_to_retry(controller, monkeypatch): ctrl, output = controller await _wait(lambda: bool(ctrl.discoveries)) (discovery,) = ctrl.discoveries.values() def broken(*args: Any): raise MatterUnexpectedError("mapping failed") with monkeypatch.context() as patched: patched.setattr(MatterController, "_get_main_parameter", broken) with pytest.raises(MatterUnexpectedError): await ctrl.pair_device( discovery, draft_for(discovery), ProvidedCredentials(type=CredentialsType.code, value="20202021") ) client = cast(FakeMatterClient, ctrl._matter_client) assert client.removed_nodes == [] # nothing undone: the node stays on the fabric (fabric,) = ctrl.discoveries.values() # no longer commissionable: offered as it is assert fabric.id != discovery.id and output.lost_discoveries == [discovery.id] device = await _pair(ctrl, fabric, None) # the retry, from a Hub-side clean state assert device.integration_data.node_id == FAKE_NODE_ID and device.parameters assert ctrl.discoveries == {} and client.removed_nodes == [] async def test_a_paired_node_is_not_offered_while_the_hub_saves_it(controller): ctrl, _ = controller await _wait(lambda: bool(ctrl.discoveries)) (discovery,) = ctrl.discoveries.values() await ctrl.pair_device( discovery, draft_for(discovery), ProvidedCredentials(type=CredentialsType.code, value="20202021") ) assert ctrl.discoveries == {} async def test_a_pairing_the_hub_never_saved_is_offered_again_as_its_fabric_node(controller, monkeypatch): ctrl, output = controller monkeypatch.setattr("majordom_matter.controller.UNSAVED_PAIRING_TIMEOUT", 0.05) await _wait(lambda: bool(ctrl.discoveries)) (discovery,) = ctrl.discoveries.values() first = await ctrl.pair_device( discovery, draft_for(discovery), ProvidedCredentials(type=CredentialsType.code, value="20202021") ) # the Hub refused the id or failed to save: nothing saved, nothing undone fabric_id = ctrl._fabric_discovery_id(FAKE_NODE_ID) await _wait(lambda: fabric_id in ctrl.discoveries) assert fabric_id != first.physical_id again = await _pair(ctrl, ctrl.discoveries[fabric_id], None) assert again.physical_id == first.physical_id and again.integration_data.node_id == FAKE_NODE_ID assert ctrl.discoveries == {} # saved and fetched: offered no more assert cast(FakeMatterClient, ctrl._matter_client).removed_nodes == [] async def test_a_rolled_back_pairing_is_offered_again_at_once_as_its_fabric_node(controller): ctrl, _ = controller await _wait(lambda: bool(ctrl.discoveries)) (discovery,) = ctrl.discoveries.values() first = await ctrl.pair_device( discovery, draft_for(discovery), ProvidedCredentials(type=CredentialsType.code, value="20202021") ) await ctrl.unpair(MatterDevice.model_validate(first.model_dump())) # the Hub failed to save it await ctrl.unpair(MatterDevice.model_validate(first.model_dump())) # and again: nothing more fabric_id = ctrl._fabric_discovery_id(FAKE_NODE_ID) assert fabric_id in ctrl.discoveries and not ctrl._unsaved_pairings assert cast(FakeMatterClient, ctrl._matter_client).removed_nodes == [] again = await _pair(ctrl, ctrl.discoveries[fabric_id], None) assert again.physical_id == first.physical_id async def test_a_fetch_of_the_paired_node_means_the_hub_saved_it(controller, monkeypatch): ctrl, _ = controller monkeypatch.setattr("majordom_matter.controller.UNSAVED_PAIRING_TIMEOUT", 0.05) await _commission(ctrl) # pairs and fetches await asyncio.sleep(0.15) assert ctrl.discoveries == {} async def test_an_id_another_record_holds_is_refused_before_anything_is_mapped(controller): ctrl, output = controller await _wait(lambda: bool(ctrl.discoveries)) (commissionable,) = ctrl.discoveries.values() node = load_on_off_light_node() taken = ctrl._node_device_id(node) holder = uuid4() ctrl.platform = build_test_platform( store={holder: {"name": "Old bulb", "is_paired": False, "physical_id": str(taken)}} ) draft = draft_for(commissionable) draft_id = draft.id with pytest.raises(DeviceIdTakenError) as refusal: await ctrl.pair_device(commissionable, draft, ProvidedCredentials(type=CredentialsType.code, value="20202021")) assert (refusal.value.physical_id, refusal.value.device_id, refusal.value.name, refusal.value.is_paired) == ( taken, holder, "Old bulb", False, ) assert draft.id == draft_id and draft.parameters == [] # on the fabric now, no longer commissionable: offered as it is, for the user to merge into the record (offered,) = ctrl.discoveries.values() assert offered.id == ctrl._fabric_discovery_id(FAKE_NODE_ID) and offered.expected_credentials_options == [ CredentialsType.none ] assert output.lost_discoveries == [commissionable.id] async def test_the_record_the_user_picked_takes_the_node_in_place_of_its_old_one(controller): ctrl, _ = controller await _wait(lambda: bool(ctrl.discoveries)) (commissionable,) = ctrl.discoveries.values() node = load_on_off_light_node() taken = ctrl._node_device_id(node) holder = uuid4() ctrl.platform = build_test_platform(store={holder: {"name": "Old bulb", "physical_id": str(taken)}}) picked = draft_for(commissionable).model_copy(update={"id": holder, "physical_id": taken, "name": "Old bulb"}) picked.integration_data.node_id = 7 # the node it had before a factory reset draft = await ctrl.pair_device( commissionable, picked, ProvidedCredentials(type=CredentialsType.code, value="20202021") ) assert (draft.id, draft.physical_id, draft.name, draft.integration_data.node_id) == ( holder, taken, "Old bulb", FAKE_NODE_ID, ) async def test_fetch_follows_the_device_once_however_often_it_runs(controller): ctrl, output = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) client = cast(FakeMatterClient, ctrl._matter_client) subscriptions = len(client._subscriptions) assert subscriptions # the first fetch subscribed await ctrl.fetch(device) await ctrl.fetch(device) assert len(client._subscriptions) == subscriptions output.events.clear() client.fire_attribute_update("13/6/0", True) await _wait(lambda: bool(output.events)) await asyncio.sleep(0.05) assert len(output.events) == 1 # not once per fetch async def test_fetch_of_a_node_that_does_not_answer_is_not_a_failure(controller): ctrl, output = controller device_id = await _commission(ctrl) async with ctrl.platform.device_repository(ctrl) as repo: device = await repo.get(physical_id=device_id, as_=MatterDevice) ctrl._matter_client.get_node(FAKE_NODE_ID).node_data.available = False output.events.clear() await ctrl.fetch(device) assert output.events == [] async def test_hand_overs_in_place_leave_no_ended_tasks_behind(controller): ctrl, _ = controller running = len(ctrl._background_tasks) for dataset in ("0e08aaaa", "0e08bbbb", "0e08cccc"): before, ctrl.platform = ctrl.platform, replace(ctrl.platform, thread_dataset=dataset) assert await ctrl.platform_facts_did_change(before) await asyncio.sleep(0.02) assert len(ctrl._background_tasks) <= running + 1 async def test_identity_is_the_serial_number_and_survives_a_new_node_id(controller): ctrl, _ = controller node = load_on_off_light_node() before = ctrl._node_device_id(node) node.node_data.node_id += 1 assert ctrl._node_device_id(node) == before async def test_identity_falls_back_to_unique_id_without_a_serial_number(controller): ctrl, _ = controller with_serial = ctrl._node_device_id(load_on_off_light_node()) by_unique_id = ctrl._node_device_id(load_on_off_light_node({"0/40/15": ""})) assert by_unique_id is not None and by_unique_id != with_serial assert ctrl._node_device_id(load_on_off_light_node({"0/40/15": "", "0/40/18": ""})) is None async def test_the_same_serial_from_two_vendors_gets_two_ids(controller): ctrl, _ = controller assert ctrl._node_device_id(load_on_off_light_node()) != ctrl._node_device_id( load_on_off_light_node({"0/40/2": 4999}) ) def _dac_node() -> MatterNode: return load_on_off_light_node({"0/40/15": "", "0/40/18": ""}) def _serve_dac(monkeypatch, ctrl, answers: list[Any]): calls: list[Any] = [] async def send_device_command(node_id, endpoint_id, command, **kwargs): calls.append((node_id, endpoint_id, command)) answer = answers.pop(0) if len(answers) > 1 else answers[0] if isinstance(answer, Exception): raise answer return {"certificate": base64.b64encode(answer).decode()} monkeypatch.setattr(ctrl._matter_client, "send_device_command", send_device_command) monkeypatch.setattr("majordom_matter.controller._DAC_RETRY_DELAY", 0) return calls async def test_the_attestation_certificate_is_read_only_without_a_serial_number_and_unique_id(controller, monkeypatch): ctrl, _ = controller calls = _serve_dac(monkeypatch, ctrl, [b"dac"]) with_serial = load_on_off_light_node() assert await ctrl._resolve_node_device_id(with_serial) == ctrl._node_device_id(with_serial) assert await ctrl._resolve_node_device_id(load_on_off_light_node({"0/40/15": ""})) is not None assert calls == [] assert await ctrl._resolve_node_device_id(_dac_node()) == ctrl.device_uuid(hashlib.sha256(b"dac").digest()) assert len(calls) == 1 and calls[0][2].certificateType == 1 async def test_the_same_attestation_certificate_gives_the_same_id(controller, monkeypatch): ctrl, _ = controller _serve_dac(monkeypatch, ctrl, [b"dac-a"]) first = await ctrl._resolve_node_device_id(_dac_node()) assert await ctrl._resolve_node_device_id(_dac_node()) == first _serve_dac(monkeypatch, ctrl, [b"dac-b"]) other = _dac_node() other.node_data.node_id += 1 assert await ctrl._resolve_node_device_id(other) != first async def test_a_dac_only_node_on_the_fabric_is_offered_after_a_restart_and_paired_by_its_node_id( controller, monkeypatch ): ctrl, output = controller node = _dac_node() node.node_data.node_id = FAKE_NODE_ID + 1 on_fabric = FakeMatterClient.get_nodes monkeypatch.setattr(FakeMatterClient, "get_nodes", lambda self: [*on_fabric(self), node]) calls = _serve_dac(monkeypatch, ctrl, [b"dac"]) ctrl.discoveries.clear() await ctrl._sync_with_server() # what a controller restart runs offered = ctrl.discoveries[ctrl._fabric_discovery_id(node.node_id)] assert calls == [] # offering needs no certificate draft = await ctrl.pair_device(offered, draft_for(offered), None) assert draft.physical_id == ctrl.device_uuid(hashlib.sha256(b"dac").digest()) assert draft.integration_data.node_id == node.node_id async def test_a_first_attestation_read_failing_is_retried_once(controller, monkeypatch): ctrl, _ = controller calls = _serve_dac(monkeypatch, ctrl, [InvalidState("Channel is closed"), b"dac"]) assert await ctrl._resolve_node_device_id(_dac_node()) is not None assert len(calls) == 2 async def test_a_node_with_no_identity_at_all_is_refused(controller, monkeypatch): ctrl, _ = controller calls = _serve_dac(monkeypatch, ctrl, [InvalidState("Channel is closed")]) node = _dac_node() assert await ctrl._resolve_node_device_id(node) is None assert len(calls) == 2 with pytest.raises(MatterUnexpectedError): await ctrl._fill_draft(None, None, node) # type: ignore[arg-type] ================================================================================ # FILE: tests/test_param_ux.py ================================================================================ """Light probes for the parameter-UX mapping — exercise the code paths (visibility curation, metadata resolver) without re-hardcoding every device's expected parameters (that stays a manual review; see the audit script + the docs recipe).""" from uuid import uuid4 from majordom_matter.mapper import MatterMapper from majordom_matter.matter_spec import ( EVERYDAY_CONTROL_ATTRIBUTES, METADATA_SOURCES, USER_READINGS, AttributeKey, ) def _mapper() -> MatterMapper: return MatterMapper(lambda s: uuid4(), lambda d, s: uuid4()) class _FakeEndpoint: def __init__(self, values): self._values = values def get_attribute_value(self, cluster_id, attribute_id): return self._values.get((cluster_id, attribute_id)) def test_runtime_bounds_prefer_device_limit_attributes(): # priority 1: CurrentLevel's min/max come from the device's own Min/MaxLevel attrs ep = _FakeEndpoint({(0x008, 0x02): 5, (0x008, 0x03): 200}) lo, hi = _mapper().resolve_runtime_bounds(AttributeKey(0x008, 0x00), 0x008, ep, "CurrentLevel", 0, 254) assert (lo, hi) == (5, 200) def test_runtime_bounds_fall_back_to_defaults_when_device_silent(): ep = _FakeEndpoint({}) # device reports no limit attrs lo, hi = _mapper().resolve_runtime_bounds(AttributeKey(0x008, 0x00), 0x008, ep, "CurrentLevel", 0, 254) assert (lo, hi) == (0, 254) def test_no_metadata_source_returns_defaults_unchanged(): ep = _FakeEndpoint({(0x008, 0x02): 5}) lo, hi = _mapper().resolve_runtime_bounds(AttributeKey(0x999, 0x99), 0x999, ep, "X", 1, 2) assert (lo, hi) == (1, 2) def test_curation_sets_are_consistent(): # a parameter can't be both an everyday writable control and a read-only user reading assert USER_READINGS.isdisjoint(EVERYDAY_CONTROL_ATTRIBUTES) # every metadata source key is a curated user reading/control (we only resolve bounds for shown params) shown = USER_READINGS | EVERYDAY_CONTROL_ATTRIBUTES assert set(METADATA_SOURCES).issubset(shown) # --- classification ladder probes (see classify_attribute) -------------------------------------- def test_ladder_system_cluster_and_sensitive_forced_hidden(): from majordom_integration_sdk.schemas.parameter import ParameterVisibility from majordom_matter.matter_spec import classify_attribute spec, source = classify_attribute(0x0028, 0x0000, "VendorName", writable=False, in_system_cluster=True) assert source == "system-cluster" and spec.visibility is ParameterVisibility.system spec, source = classify_attribute( 0x0006, 0x0000, "AliroReaderVerificationKey", writable=True, in_system_cluster=False ) assert source == "sensitive" and spec.visibility is ParameterVisibility.system def test_ladder_our_override_beats_ha(): from majordom_matter.matter_spec import OUR_ATTRIBUTE_UX, classify_attribute key = next(iter(OUR_ATTRIBUTE_UX)) spec, source = classify_attribute(key.cluster_id, key.attribute_id, "x", writable=False, in_system_cluster=False) assert source == "ours" def test_ladder_harvested_ha_and_fallback(): from majordom_matter.matter_spec import MATTER_HA_ATTRIBUTE_UX, OUR_ATTRIBUTE_UX, classify_attribute assert len(MATTER_HA_ATTRIBUTE_UX) > 50 # the vendored HA harvest loaded our_keys = {(x.cluster_id, x.attribute_id) for x in OUR_ATTRIBUTE_UX} ha_only = next(k for k in MATTER_HA_ATTRIBUTE_UX if k not in our_keys) _, source = classify_attribute(ha_only[0], ha_only[1], "x", writable=True, in_system_cluster=False) assert source == "ha" # a wholly-uncurated attribute falls to the warning fallback _, source = classify_attribute(0x0ABC, 0x0001, "mystery", writable=True, in_system_cluster=False) assert source.startswith("fallback") def test_every_main_parameter_is_user_visible(): from majordom_matter.matter_spec import EVERYDAY_COMMANDS, MAIN_PARAMETER_BY_CLUSTER, STATE_TOGGLE_ATTRIBUTES for cluster_id, spec in MAIN_PARAMETER_BY_CLUSTER.items(): while spec is not None: key = (cluster_id, spec.command_or_attribute_id) if spec.is_attribute: assert AttributeKey(*key) in EVERYDAY_CONTROL_ATTRIBUTES | STATE_TOGGLE_ATTRIBUTES, hex(cluster_id) else: assert key in EVERYDAY_COMMANDS, hex(cluster_id) spec = spec.fallback def test_unverified_command_mains_are_disabled(): from majordom_matter.matter_spec import MAIN_PARAMETER_BY_CLUSTER # MicrowaveOvenControl, KeypadInput, EnergyEvse, WaterHeaterMode, WebRTCTransportProvider assert MAIN_PARAMETER_BY_CLUSTER.keys().isdisjoint({0x5F, 0x509, 0x99, 0x9E, 0x553}) def test_one_way_mains_have_their_counter_command_visible(): from majordom_matter.matter_spec import EVERYDAY_COMMANDS assert {(0x104, 0x0), (0x104, 0x1)} <= EVERYDAY_COMMANDS # ClosureControl Stop / MoveTo assert {(0x081, 0x0), (0x081, 0x1)} <= EVERYDAY_COMMANDS # ValveConfigurationAndControl Open / Close ================================================================================ # FILE: tests/test_smoke.py ================================================================================ """Smoke tests — no matterjs-server or binaries required (run everywhere).""" from majordom_integration_sdk import Service from majordom_integration_sdk.controller import AbstractController from majordom_integration_sdk.testing import build_test_platform import majordom_matter from majordom_matter import MatterController def test_is_an_integration_controller(): assert issubclass(MatterController, AbstractController) def test_integration_identity_is_class_level(): assert MatterController.name == "Matter" assert MatterController.slug() == "matter" def test_runs_its_controller_with_the_matterjs_server_it_needs(): server, controller = majordom_matter.peripherals(build_test_platform()) assert isinstance(server, Service) and server.name == "matterjs-server" assert isinstance(controller, MatterController) assert majordom_matter.peripherals(build_test_platform())[0] is not server # one of its own per runtime ================================================================================ # FILE: tests/test_state_toggles.py ================================================================================ """Main-parameter toggles driven by a state attribute, against the in-process FakeMatterClient. The canned on-off light's OnOff cluster is swapped for the cluster under test on the same endpoint, so that cluster's main parameter wins. A tap is simulated the way the Hub does it: `next_main_parameter_value(stored value, main_cycle)`, then `send_command` with that value. """ import asyncio import json from typing import Any import pytest from chip.clusters.Objects import ( ClosureControl, DoorLock, FanControl, MediaPlayback, OperationalState, RvcOperationalState, ValveConfigurationAndControl, WindowCovering, ) from majordom_integration_sdk import Endpoint, Peripherals from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import CredentialsType, ProvidedCredentials from majordom_integration_sdk.schemas.parameter import ParameterRole, ParameterVisibility, next_main_parameter_value from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from matter_server.client.models.node import MatterNode from matter_server.common.helpers.util import dataclass_from_dict from matter_server.common.models import MatterNodeData from majordom_matter import MatterController from majordom_matter.exceptions import MatterUnexpectedError from majordom_matter.model import MatterDevice, MatterDeviceState, MatterParameterTypeEnum from majordom_matter.testing import _FIXTURE, FakeMatterClient, draft_for ENDPOINT = 13 SERVER = Peripherals({"matter": Endpoint("matter", "matter-server", "ws://matter-server")}) def _node_with(cluster_id: int, attributes: dict[int, Any], accepted_commands: list[int]) -> MatterNode: """The canned node with its OnOff cluster replaced by `cluster_id` carrying `attributes`.""" data = json.loads(_FIXTURE.read_text()) paths = data["attributes"] for path in [p for p in paths if p.startswith(f"{ENDPOINT}/6/")]: del paths[path] prefix = f"{ENDPOINT}/{cluster_id}" paths |= {f"{prefix}/{attribute_id}": value for attribute_id, value in attributes.items()} paths |= { f"{prefix}/65529": accepted_commands, f"{prefix}/65531": [*attributes, 65529, 65531, 65532, 65533], f"{prefix}/65532": 0, f"{prefix}/65533": 1, } return MatterNode(dataclass_from_dict(MatterNodeData, data)) async def _pair( monkeypatch, node: MatterNode ) -> tuple[MatterController, FakeMatterClient, MatterDevice, MatterDeviceState]: fake = FakeMatterClient(node=node) monkeypatch.setattr("majordom_matter.controller.MatterClient", lambda url, session: fake) controller = MatterController(build_test_platform()) controller.peripherals = SERVER controller.output = RecordingControllerOutput() await controller.start() async with asyncio.timeout(5): while not controller.discoveries: await asyncio.sleep(0.02) discovery = next(iter(controller.discoveries.values())) state = await controller.pair_device( discovery, draft_for(discovery), ProvidedCredentials(type=CredentialsType.code, value="20202021") ) async with controller.platform.device_repository(controller) as repo: await repo.save(state) device = await repo.get(physical_id=state.physical_id, as_=MatterDevice) assert device is not None await controller.fetch(device) # the Hub's last step: it follows the device return controller, fake, device, state def _main(state: MatterDeviceState): assert state.main_parameter is not None, "the device should have a main parameter" return state.parameters_dict[state.main_parameter] async def _tap(controller: MatterController, fake: FakeMatterClient, device: MatterDevice, parameter) -> Any: """Send what the Hub sends for a main-parameter tap; return the command that reached the device.""" value = next_main_parameter_value(parameter.value, parameter.main_cycle) sent = fake.sent_commands before = len(sent) await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=parameter.id, value=value), device, parameter ) assert len(sent) == before + 1, "a tap should send exactly one command" return sent[-1][2] TOGGLES = [ # cluster, state attribute, accepted commands, cycle, current state, command the tap sends (DoorLock, DoorLock.Attributes.LockState, [0, 1], {1, 2}, 1, DoorLock.Commands.UnlockDoor()), (DoorLock, DoorLock.Attributes.LockState, [0, 1], {1, 2}, 2, DoorLock.Commands.LockDoor()), (DoorLock, DoorLock.Attributes.LockState, [0, 1], {1, 2}, 0, DoorLock.Commands.LockDoor()), (DoorLock, DoorLock.Attributes.LockState, [0, 1], {1, 2}, 3, DoorLock.Commands.LockDoor()), ( ValveConfigurationAndControl, ValveConfigurationAndControl.Attributes.CurrentState, [0, 1], {0, 1}, 0, ValveConfigurationAndControl.Commands.Open(), ), ( ValveConfigurationAndControl, ValveConfigurationAndControl.Attributes.CurrentState, [0, 1], {0, 1}, 1, ValveConfigurationAndControl.Commands.Close(), ), ( ValveConfigurationAndControl, ValveConfigurationAndControl.Attributes.CurrentState, [0, 1], {0, 1}, 2, ValveConfigurationAndControl.Commands.Close(), ), ( WindowCovering, WindowCovering.Attributes.CurrentPositionLiftPercentage, [0, 1, 2], {0, 100}, 0, WindowCovering.Commands.DownOrClose(), ), ( WindowCovering, WindowCovering.Attributes.CurrentPositionLiftPercentage, [0, 1, 2], {0, 100}, 100, WindowCovering.Commands.UpOrOpen(), ), ( WindowCovering, WindowCovering.Attributes.CurrentPositionLiftPercentage, [0, 1, 2], {0, 100}, 40, WindowCovering.Commands.UpOrOpen(), ), (MediaPlayback, MediaPlayback.Attributes.CurrentState, [0, 1, 2], {0, 1}, 0, MediaPlayback.Commands.Pause()), (MediaPlayback, MediaPlayback.Attributes.CurrentState, [0, 1, 2], {0, 1}, 1, MediaPlayback.Commands.Play()), (MediaPlayback, MediaPlayback.Attributes.CurrentState, [0, 1, 2], {0, 1}, 2, MediaPlayback.Commands.Play()), ( RvcOperationalState, RvcOperationalState.Attributes.OperationalState, [0, 3], {1, 2}, 1, RvcOperationalState.Commands.Pause(), ), ( RvcOperationalState, RvcOperationalState.Attributes.OperationalState, [0, 3], {1, 2}, 2, RvcOperationalState.Commands.Resume(), ), ( RvcOperationalState, RvcOperationalState.Attributes.OperationalState, [0, 3], {1, 2}, 0x42, RvcOperationalState.Commands.Resume(), ), ( OperationalState, OperationalState.Attributes.OperationalState, [0, 1, 2, 3], {1, 2}, 1, OperationalState.Commands.Pause(), ), ( OperationalState, OperationalState.Attributes.OperationalState, [0, 1, 2, 3], {1, 2}, 2, OperationalState.Commands.Resume(), ), ] @pytest.mark.parametrize(("cluster", "attribute", "accepted", "cycle", "current", "expected"), TOGGLES) async def test_state_attribute_main_parameter_toggles_through_its_command( monkeypatch, cluster, attribute, accepted: list[int], cycle: set[int], current: int, expected ): controller, fake, device, state = await _pair( monkeypatch, _node_with(cluster.id, {attribute.attribute_id: current}, accepted) ) try: main = _main(state) assert main.integration_data.type is MatterParameterTypeEnum.attribute assert (main.integration_data.cluster_id, main.integration_data.attribute_id) == ( cluster.id, attribute.attribute_id, ) # The Hub only forwards commands for control parameters. assert main.role is ParameterRole.control and main.visibility is ParameterVisibility.user assert main.default_value == cycle and state.can_set_main_parameter(main.id) assert await _tap(controller, fake, device, main) == expected finally: await controller.stop() async def test_door_lock_toggle_uses_timed_invoke(monkeypatch): node = _node_with(DoorLock.id, {DoorLock.Attributes.LockState.attribute_id: 1}, [0, 1]) controller, fake, device, state = await _pair(monkeypatch, node) timeouts: list[int | None] = [] async def send_device_command(node_id, endpoint_id, command, timed_request_timeout_ms=None, **kwargs): timeouts.append(timed_request_timeout_ms) monkeypatch.setattr(controller._matter_client, "send_device_command", send_device_command) try: main = _main(state) await controller.send_command(DeviceCommand(device_id=device.id, parameter_id=main.id, value=2), device, main) assert timeouts == [1000] finally: await controller.stop() async def test_fan_mode_main_parameter_toggles_off_and_on(monkeypatch): node = _node_with(FanControl.id, {FanControl.Attributes.FanMode.attribute_id: 0}, []) controller, fake, device, state = await _pair(monkeypatch, node) try: main = _main(state) assert main.integration_data.attribute_id == FanControl.Attributes.FanMode.attribute_id assert main.default_value == {0, 4} value = next_main_parameter_value(main.value, main.main_cycle) await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=main.id, value=value), device, main ) assert fake.written_attributes[-1][1:] == (f"{ENDPOINT}/{FanControl.id}/0", 4) finally: await controller.stop() async def test_idle_operational_state_is_never_started(monkeypatch): node = _node_with(OperationalState.id, {OperationalState.Attributes.OperationalState.attribute_id: 0}, [0, 1, 2, 3]) controller, fake, device, state = await _pair(monkeypatch, node) try: main = _main(state) assert main.integration_data.type is MatterParameterTypeEnum.attribute with pytest.raises(MatterUnexpectedError, match="never starts"): await _tap(controller, fake, device, main) assert fake.sent_commands == [] finally: await controller.stop() async def test_a_state_the_toggle_cannot_set_is_rejected(monkeypatch): node = _node_with(DoorLock.id, {DoorLock.Attributes.LockState.attribute_id: 1}, [0, 1]) controller, fake, device, state = await _pair(monkeypatch, node) try: main = _main(state) with pytest.raises(MatterUnexpectedError, match="cannot be set"): await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=main.id, value=3), device, main ) assert fake.sent_commands == [] finally: await controller.stop() @pytest.mark.parametrize( ("cluster", "attributes", "accepted", "expected_command_id"), [ # A cover without position awareness keeps the one-way UpOrOpen. (WindowCovering, {0: 0}, [0, 1, 2], WindowCovering.Commands.UpOrOpen.command_id), # A player without Pause, a vacuum without Pause keep their one-way command. (MediaPlayback, {0: 0}, [0, 2], MediaPlayback.Commands.Play.command_id), (RvcOperationalState, {4: 1}, [3], RvcOperationalState.Commands.Resume.command_id), # An appliance that can't pause gets no main parameter: Start is never a one-tap. (OperationalState, {4: 0}, [1, 2], None), ], ) async def test_unsupported_toggle_falls_back( monkeypatch, cluster, attributes: dict[int, Any], accepted: list[int], expected_command_id: int | None ): controller, _fake, _device, state = await _pair(monkeypatch, _node_with(cluster.id, attributes, accepted)) try: if expected_command_id is None: assert state.main_parameter is None return main = _main(state) assert main.integration_data.type is MatterParameterTypeEnum.command assert (main.integration_data.cluster_id, main.integration_data.command_id) == ( cluster.id, expected_command_id, ) finally: await controller.stop() CLOSURE_POSITION = ClosureControl.Enums.TargetPositionEnum @pytest.mark.parametrize( ("main_state", "overall", "expected"), [ ( 0, {"0": 0, "1": False}, ClosureControl.Commands.MoveTo(position=CLOSURE_POSITION(CLOSURE_POSITION.kMoveToFullyOpen)), ), ( 0, {"0": 1, "1": False}, ClosureControl.Commands.MoveTo(position=CLOSURE_POSITION(CLOSURE_POSITION.kMoveToFullyClosed)), ), ( 0, {"0": 2, "1": False}, ClosureControl.Commands.MoveTo(position=CLOSURE_POSITION(CLOSURE_POSITION.kMoveToFullyClosed)), ), (0, None, ClosureControl.Commands.MoveTo(position=CLOSURE_POSITION(CLOSURE_POSITION.kMoveToFullyClosed))), (1, {"0": 2, "1": False}, ClosureControl.Commands.Stop()), (2, {"0": 0, "1": False}, ClosureControl.Commands.Stop()), ], ) async def test_closure_main_parameter_toggles_by_current_state( monkeypatch, main_state: int, overall: dict | None, expected ): attributes = { ClosureControl.Attributes.MainState.attribute_id: main_state, ClosureControl.Attributes.OverallCurrentState.attribute_id: overall, } controller, fake, device, state = await _pair(monkeypatch, _node_with(ClosureControl.id, attributes, [0, 1])) try: main = _main(state) assert main.integration_data.attribute_id == ClosureControl.Attributes.MainState.attribute_id assert main.role is ParameterRole.control and main.visibility is ParameterVisibility.user # Structs can't cycle: a one-value button, and the controller picks the command by state. assert main.main_cycle == [ClosureControl.Enums.MainStateEnum.kMoving] assert await _tap(controller, fake, device, main) == expected finally: await controller.stop() # integration-zigbee — full source # repo: https://github.com/MajorDom-Systems/integration-zigbee branch: master commit: 64a95d0818581557387610a88ef9504c733be3b9 # generated: 2026-11-16 — AUTO-GENERATED, do not edit by hand ## File tree .gitignore LICENSE README.md majordom_zigbee/__init__.py majordom_zigbee/_serial.py majordom_zigbee/controller.py majordom_zigbee/exceptions.py majordom_zigbee/listener.py majordom_zigbee/mapper.py majordom_zigbee/model.py majordom_zigbee/radio.py majordom_zigbee/readme.md majordom_zigbee/zigbee_spec.py majordom_zigbee/zigbee_spec_zha.py pyproject.toml scripts/check_zha_drift.py scripts/harvest_zha.py scripts/param_ux_audit.py tests/conftest.py tests/test_controller.py tests/test_param_ux.py tests/test_radio.py tests/test_settings.py ================================================================================ # FILE: .gitignore ================================================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[codz] *$py.class # C extensions *.so # Distribution / packaging build/ dist/ *.egg-info/ *.egg # Unit test / coverage reports .coverage .coverage.* coverage.xml htmlcov/ .pytest_cache/ .hypothesis/ # Environments .env .envrc .venv env/ venv/ # Poetry # poetry.lock # uncomment for applications, keep commented for libraries # Type checkers .mypy_cache/ .dmypy.json .pyre/ .pytype/ # Tools .ruff_cache/ .ropeproject # mkdocs (only relevant if you kept mkdocs.yml + docs/) /site .cache/ # IDEs .idea/ .vscode/ # OS .DS_Store Thumbs.db # MajorDom dev runner (settings and keys) .majordom-dev/ ================================================================================ # FILE: LICENSE ================================================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================================================ # FILE: README.md ================================================================================ Part of MajorDom — the next-gen smart home # integration-zigbee A [MajorDom](https://majordom.io) integration — bridges **Zigbee** devices into the MajorDom language. Built for the **MajorDom Hub**, but it doesn't need it: this is a standalone, standardized library for Zigbee that you can use on its own (see **Run it standalone** below). Built on the [MajorDom Integration SDK](https://github.com/MajorDom-Systems/integration-sdk). The entry point is `ZigBeeController` (`majordom_zigbee/controller.py`), which the Hub — or the SDK's dev runner — instantiates and drives through its lifecycle: pairing → commands → teardown. - **Other protocols:** browse the [MajorDom integrations](https://github.com/orgs/MajorDom-Systems/repositories?q=integration-). - **Create your own:** start from the [integration template](https://github.com/MajorDom-Systems/integration-template). ## Documentation Full integration-author docs — the controller lifecycle, data models, storing data, discovery, and a worked example — live at **[docs.majordom.io](https://docs.majordom.io/device-integration)**. ## Development ```sh poetry install && poetry run poe install ``` | Task | Description | |------|-------------| | `poe check` | Full quality pipeline (ruff, ty, pytest, poetry build/check) | | `poe check --ci` | Same, plus `git diff --exit-code` | Work lands on `develop`; `master` is protected and released via **Actions → Release**. Tests drive the controller with the SDK's test doubles against a simulated `zigpy` device — no radio required (see `tests/`). ## Run it standalone (without the Hub) `majordom-zigbee` is a standalone library — import it into your own app, or run **just this integration** interactively (discover, pair, control, and inspect devices from a prompt) with no Hub. It needs a Zigbee coordinator radio (a SkyConnect, ConBee, or a zigpy-znp/bellows-supported dongle) at a serial path. See **[Standalone mode](https://docs.majordom.io/device-integration/standalone)** for the interactive CLI, watch mode, and the programmatic API. ## Coordinator radios (backend-agnostic) The integration is radio-backend-agnostic: it picks the right `zigpy` radio library for the attached coordinator, so swapping dongles needs **no source change**. - **Bundled by default:** Silicon Labs EmberZNet/EZSP (`bellows` — SkyConnect, Sonoff ZBDongle-E) and TI Z-Stack/ZNP (`zigpy-znp` — CC2652, Sonoff ZBDongle-P). - **Optional extras:** `pip install 'majordom-zigbee[deconz]'` (ConBee/RaspBee), `[xbee]` (Digi XBee), `[zigate]` (ZiGate), or `[all-radios]`. - **Selecting the backend:** by default the attached dongle is **auto-probed**. Pin one explicitly with the `MAJORDOM_ZIGBEE_RADIO` env var (`ezsp` / `znp` / `deconz` / `xbee` / `zigate`) or the `ZigBeeController.radio` attribute. See `majordom_zigbee/radio.py`. ## About this integration - **Protocol / platform:** Zigbee via `zigpy` (with `bellows` / `zigpy-znp` radio libraries). - **Transport(s):** Zigbee (IEEE 802.15.4). - **Supported devices:** Zigbee Home Automation devices — lights, plugs, switches, sensors. - **Credentials needed to pair:** none — devices join during an explicit pairing window. ### Required harness - **Hardware adapters:** a Zigbee coordinator radio (SkyConnect / ConBee / a `zigpy`-supported dongle) — the Hub assigns its OS device path via `dependencies.hardware_interfaces` (e.g. `/dev/ttyACM0`). - **Third-party software services:** none — `zigpy` speaks to the radio directly. - **OS / permissions:** serial-port access to the radio. ### Protocol stack (OSI) | OSI layer | Protocol | Implemented by | |-----------|----------|----------------| | Application (7) | Zigbee Cluster Library (ZCL) | **this integration** (via `zigpy`) | | Network (3) | Zigbee NWK / APS | library (`zigpy` · radio firmware) | | Data link / Physical (1–2) | IEEE 802.15.4 | radio adapter (harness) | ### Progress - [x] `start_pairing_window` implemented (Zigbee requires an explicit join window) - [x] Discovery of joining devices; `controller_did_receive_discovery` called - [x] Re-discovery of already-paired devices on reconnect (`controller_did_connect_device`) - [x] Device pairing - [x] Device schema mapped: endpoints/clusters → parameter list with per-parameter metadata - [x] Hub → Device control (`send_command` — commands and attribute writes) - [x] Device → Hub event subscription (`controller_did_receive_events`) - [x] `identify` - [x] `unpair` - [x] `fetch` - [x] Availability tracking while running (`controller_did_lose_device` / `last_error`) - [x] Graceful shutdown in `stop` - [x] Tests pass against a simulated `zigpy` device (`tests/`) - [x] Owned — maintained by Parker Industries ### Parameter metadata sources & priority Every parameter's UX metadata is resolved from several sources. Two independent axes, each with its own priority ladder (first match wins). See also the [parameter-ux recipe](https://docs.majordom.io/device-integration/parameter-ux). **Visibility / role / unit** — resolved by `classify_attribute()` in `zigbee_spec.py`: | # | Source | What it is | |---|--------|-----------| | 1 | `OUR_ATTRIBUTE_UX` (`VISIBILITY_OVERRIDES`, `USER_READINGS`, `EVERYDAY_CONTROL_ATTRIBUTES`) | our hand curation — a human's call wins over everything | | — | metadata / manufacturer-on-system-cluster | forced **system** (safety; scaling constants & bounds stay hidden) | | 2 | **v2 quirk entity metadata** | per-device judgment from a loaded `zhaquirks` `QuirkBuilder` (`quirk_ux_map()`), runtime | | 3 | `ZHA_ATTRIBUTE_UX` | standard-cluster judgment **harvested** from `zha` (`scripts/harvest_zha.py`, vendored — `zha` is not a runtime dep) | | 4 | **fallback policy** | heuristic (reportable → user, writable → setting); **logs a warning** so uncurated attrs surface. Flip `_FALLBACK_HIDE_UNCURATED` to hide-by-default once coverage is validated on real devices. | **Bounds (`min`/`max`/`step`)** — a separate ladder (`resolve_metadata_bounds()`): 1. the device's own limit attributes' **runtime values** (`METADATA_SOURCES`) — ground truth for *this* device; 2. spec tables (`ATTRIBUTE_MIN_STEP`, wire-type range); 3. wire-type default. A missing expected limit is logged (quirk detection). **Quirks.** `zhaquirks.setup()` runs once at controller startup so joined devices are presented in quirked form (manufacturer clusters decoded into named/typed attributes; v2 entity metadata attached). This requires the `zigpy` 2.x stack. **Drift.** `scripts/check_zha_drift.py` re-harvests `zha` and diffs against the vendored artifact via the SDK's `diff_specs`, tiering changes ADD / REMOVE / **RECLASSIFY** (high-risk — changes what current users already see). CI opens a Dependabot-style refresh PR on drift. ### Notes The device/parameter ids are derived from the device's IEEE address via the SDK's UUID helpers, so they're stable across restarts and namespaced per integration. ## License See [LICENSE](LICENSE). For commercial licensing or partnership inquiries regarding MajorDom, contact us via [parker-industries.org/partnership](https://parker-industries.org/partnership). ================================================================================ # FILE: majordom_zigbee/__init__.py ================================================================================ """Zigbee integration for MajorDom. Bridges Zigbee devices into the MajorDom language via zigpy. `peripherals` is what the Hub (or the SDK's standalone dev runner) runs: `ZigBeeController`, the entry point it drives, and `ZigpyDriver`, which identifies the sticks only zigpy knows. """ from majordom_integration_sdk import Peripheral, Platform from majordom_zigbee.controller import ZigBeeController from majordom_zigbee.radio import ZigpyDriver def peripherals(platform: Platform) -> list[Peripheral]: return [ZigpyDriver(), ZigBeeController(platform)] __all__ = ["ZigBeeController", "ZigpyDriver", "peripherals"] ================================================================================ # FILE: majordom_zigbee/_serial.py ================================================================================ import subprocess def port_holder(port: str) -> str: """Return human-readable description of which process holds the port, or empty string.""" try: # fuser prints the device name to stderr, PIDs to stdout — capture separately result = subprocess.run(["fuser", port], capture_output=True, text=True) out = result.stdout.strip() pids = [p for p in out.split() if p.isdigit()] names = [] for pid in pids: try: comm = subprocess.check_output(["cat", f"/proc/{pid}/comm"], text=True).strip() names.append(f"pid={pid} ({comm})") except (subprocess.CalledProcessError, FileNotFoundError): names.append(f"pid={pid}") return ", ".join(names) except (subprocess.CalledProcessError, FileNotFoundError): return "" ================================================================================ # FILE: majordom_zigbee/controller.py ================================================================================ import asyncio import contextlib import json import logging import time from collections.abc import Coroutine from enum import Enum from typing import Any, ClassVar, cast, override from uuid import UUID import zigpy.endpoint import zigpy.zcl from majordom_integration_sdk import STABLE_RUN, AbstractController, Endpoint, IntegrationError, Need, Platform from majordom_integration_sdk import SettingsExtraField as Extra from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import ( CredentialsType, Discovery, NonEmptyStr, ParameterState, ProvidedCredentials, ) from majordom_integration_sdk.schemas.event import DeviceParameterChange from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from pydantic import BaseModel, Field from zigpy.application import ControllerApplication from zigpy.config import ( CONF_DATABASE, CONF_DEVICE, CONF_DEVICE_BAUDRATE, CONF_DEVICE_FLOW_CONTROL, CONF_DEVICE_PATH, CONF_NWK, CONF_NWK_TX_POWER, ) from zigpy.device import Device as ZPDevice # ZP - ZigPy from zigpy.types import EUI64 from zigpy.zcl.clusters.general import Identify from zigpy.zcl.foundation import Status as ZCLStatus from zigpy.zcl.foundation import ZCLAttributeAccess, ZCLAttributeDef, ZCLCommandDef from majordom_zigbee._serial import port_holder from .exceptions import ZBConnectionError, ZBOperationError, ZBUnexpectedError from .listener import ZBAttributeUpdatedListener from .mapper import ZigBeeMapper from .model import ( Parameter, ZBDevice, ZBDeviceIntegrationData, ZBDeviceState, ZBParameter, ZBParameterIntegrationData, ZBParameterState, ZBParameterType, ) from .radio import ZIGPY_DIALECTS, application_class from .zigbee_spec import ( EVERYDAY_COMMANDS, MAIN_PARAMETER_BY_CLUSTER, SYSTEM_CLUSTERS, MainParameterSpec, UxSpec, classify_attribute, get_min_step, get_unit, resolve_metadata_bounds, unit_from_zha, ) log = logging.getLogger(__name__) # ZCL read_attributes request max payload: 254 bytes (EZSP LVBytes limit) # Header=3 bytes + 2 bytes/attr → theoretical max 125 attr IDs per request. # In practice, reading too many attributes at once keeps the serial line busy # long enough to trigger NCP ACK timeouts. _MAX_ATTRS_PER_REQUEST = 25 # Upper bound of one fetch: a sleeping device answers nothing, each cluster read then waits out its own timeout _FETCH_TIMEOUT = 60 def _log_task_exception(task: asyncio.Task[Any]): """Retrieves a fire-and-forget task's exception, so asyncio doesn't report it as never retrieved.""" if not task.cancelled() and (exc := task.exception()): log.error(f"background task {task.get_coro()!r} failed: {exc!r}", exc_info=exc) # Delay between attribute read chunks to let bellows send ASH ACKs. _INTER_CHUNK_DELAY = 0.05 _quirks_loaded = False # A cluster the device lists but doesn't implement answers a read with a Default Response carrying # UNSUPPORTED_CLUSTER, which zigpy fans out to every requested attribute. _UNSUPPORTED_STATUSES = frozenset({ZCLStatus.UNSUPPORTED_ATTRIBUTE, ZCLStatus.UNSUPPORTED_CLUSTER}) # Home Assistant's (ZHA's) rule: a device not heard from for this long is unavailable until its next message _CONSIDER_UNAVAILABLE_MAINS = 2 * 60 * 60 _CONSIDER_UNAVAILABLE_BATTERY = 6 * 60 * 60 _SETTING_ENTITY_TYPES = frozenset({"config", "diagnostic"}) _SENSOR_PLATFORMS = frozenset({"sensor", "binary_sensor"}) def quirk_ux_map(zbdevice: ZPDevice) -> dict[tuple[int, int, str], UxSpec]: """Per-attribute UX judgment carried by a v2 QuirkBuilder, keyed (endpoint_id, cluster_id, attribute_name). This is the runtime, device-specific tier of the classification ladder (above harvested zha, below our hand overrides). Empty for non-quirked / v1-only devices. entity_type (standard/config/diagnostic) -> visibility; entity_platform -> role; unit/ device_class -> ParameterUnit. Only metadata entries that target a single attribute are used. """ quirk_def = getattr(zbdevice, "_quirk_definition", None) if quirk_def is None: return {} out: dict[tuple[int, int, str], UxSpec] = {} for meta in getattr(quirk_def, "entity_metadata", ()): attr_name = getattr(meta, "attribute_name", None) if not attr_name: continue # command buttons / composite entities carry no single attribute entity_type = getattr(getattr(meta, "entity_type", None), "value", None) platform = getattr(getattr(meta, "entity_platform", None), "value", None) visibility = ParameterVisibility.setting if entity_type in _SETTING_ENTITY_TYPES else ParameterVisibility.user role = ParameterRole.sensor if platform in _SENSOR_PLATFORMS else ParameterRole.control unit = unit_from_zha( getattr(getattr(meta, "device_class", None), "value", getattr(meta, "device_class", None)), getattr(meta, "unit", None), ) out[(meta.endpoint_id, meta.cluster_id, attr_name)] = UxSpec(visibility, role, unit) return out async def _ensure_quirks_loaded(): """Register zhaquirks into zigpy's process-global registry, once. Must run before the radio interviews devices so a joined device is presented in its quirked form — manufacturer clusters decoded into named/typed attributes and v2 entity metadata attached. setup() imports every zhaquirks module, so guard against repeat cost.""" global _quirks_loaded if _quirks_loaded: return def setup(): import zhaquirks zhaquirks.setup() await asyncio.to_thread(setup) # seconds of imports, off the event loop the Hub shares (as Home Assistant does) _quirks_loaded = True log.debug("[QUIRKS] zhaquirks registered into zigpy registry") def _is_seen_lately(zbdevice: ZPDevice) -> bool: if zbdevice.last_seen is None: return False is_mains_powered = zbdevice.node_desc is not None and zbdevice.node_desc.is_mains_powered allowed = _CONSIDER_UNAVAILABLE_MAINS if is_mains_powered else _CONSIDER_UNAVAILABLE_BATTERY return time.time() - zbdevice.last_seen < allowed def _zb_path( device: ZBDevice | None = None, zbdevice: ZPDevice | None = None, endpoint: zigpy.endpoint.Endpoint | None = None, cluster: zigpy.zcl.Cluster | None = None, attr_id: int | None = None, attr_ids: list[int] | None = None, error: Exception | None = None, attr_only: bool = False, ) -> str: parts: list[str] = [] if device is not None: model = zbdevice.model if zbdevice is not None else None parts.append(f"device={device.physical_id}" + (f"({model})" if model else "")) if endpoint is not None: ep_type = getattr(endpoint.device_type, "name", None) parts.append(f"endpoint={endpoint.endpoint_id}" + (f"({ep_type})" if ep_type else "")) if cluster is not None and not attr_only: parts.append(f"cluster={cluster.cluster_id}({cluster.name})") if attr_id is not None: attr_name = getattr(cluster.attributes.get(attr_id) if cluster else None, "name", None) parts.append(f"attr={attr_id}" + (f"({attr_name})" if attr_name else "")) if error is not None: parts.append(f"error={type(error).__name__}{' details=' + str(error) if str(error) else ''}") if attr_ids is not None: attr_ids = sorted(attr_ids) names = [getattr(cluster.attributes.get(a) if cluster else None, "name", None) for a in attr_ids] long = len(names) > 1 glue = ",\n\t" if long else " " parts.append( f"attrs={'\n\t' if long else ''}" f"{glue.join(f'{a}({n})' if n else str(a) for a, n in zip(attr_ids, names, strict=False))}" ) return " ".join(parts) def _device_config(link: Endpoint) -> dict[str, Any]: """zigpy's config of the bound radio: its path, and the serial settings its endpoint carries.""" config: dict[str, Any] = {CONF_DEVICE_PATH: link.url} if (baud := link.params.get("baud")) is not None: config[CONF_DEVICE_BAUDRATE] = baud if (flow_control := link.params.get("flow_control")) is not None: config[CONF_DEVICE_FLOW_CONTROL] = "hardware" if flow_control else None # RTS/CTS, as the radios' params mean return config def _check_zcl_failures( failures: dict[int | None, ZCLStatus], cluster: zigpy.zcl.Cluster, log_prefix: str, *, device: "ZBDevice | None" = None, zbdevice: "ZPDevice | None" = None, endpoint: "zigpy.endpoint.Endpoint | None" = None, raise_errors: bool = True, ): """Handle ZCL-level failures from read_attributes or write_attributes. Registers unsupported attributes on the cluster and logs them at DEBUG. Raises ZBOperationError for any other non-SUCCESS status. Pass failures as {attr_id: status} (read_attributes) or {record.attrid: record.status for record in result[0]} (write_attributes). A None key means a global device-level status (write_attributes global failure). """ cluster_path = _zb_path(device, zbdevice, endpoint, cluster) unsupported = [ attr_id for attr_id, status in failures.items() if attr_id is not None and status in _UNSUPPORTED_STATUSES ] errors = { attr_id: status for attr_id, status in failures.items() if status != ZCLStatus.SUCCESS and status not in _UNSUPPORTED_STATUSES } for attr_id in unsupported: # zigpy 2.0 resolves the id via find_attribute, which raises for ids the cluster # definition doesn't know (a device can report unsupported for a nonstandard id). with contextlib.suppress(KeyError, ValueError): cluster.add_unsupported_attribute(attr_id) if unsupported: names = [_zb_path(cluster=cluster, attr_id=a, attr_only=True) for a in unsupported] long = len(names) > 1 log.debug( f"{log_prefix} unsupported attributes {cluster_path}: {'\n\t' if long else ''}{(',\n\t').join(names)}" ) if not errors: return details = ",\n\t".join( f"{_zb_path(cluster=cluster, attr_id=attr_id, attr_only=True) if attr_id is not None else 'global'}" f"={getattr(status, 'name', status)}" # ZCLStatus enum, or a raw int for unknown codes for attr_id, status in errors.items() ) if raise_errors: raise ZBOperationError(f"{log_prefix} ZCL failures:\n\t{details}") else: log.error(f"{log_prefix} ZCL failures:\n\t{details}") class ZigBeeController(AbstractController[ZBDevice, ZBParameter, "ZigBeeController.Settings", ZBDeviceState]): """Bridges the Hub to Zigbee devices through a USB coordinator radio via zigpy. zigpy owns the Zigbee network, the ZCL, and device interviews; this controller adapts it to the Hub's AbstractController contract. Zigbee has no separate discovery step — a device is on the network the moment it joins the permit-join window. See readme.md. """ class Settings(BaseModel): # The network the radio runs, filled in once it starts: moving it is a network takeover, not a setting channel: int | None = Field(None, title="Channel", json_schema_extra={Extra.read_only: True}) pan_id: str | None = Field(None, title="PAN ID", json_schema_extra={Extra.read_only: True}) extended_pan_id: str | None = Field(None, title="Extended PAN ID", json_schema_extra={Extra.read_only: True}) tx_power: int | None = Field( # zigpy's own range: it refuses to start outside it None, ge=-10, le=20, title="Transmit power, dBm", description="Empty uses the radio default." ) needs = [Need("zigbee", ZIGPY_DIALECTS)] # Seconds before each try to reopen a lost radio; once the last one fails, Zigbee can't go on RECONNECT_DELAYS: ClassVar[tuple[float, ...]] = (1, 2, 5, 10, 30) # Seconds a reopened radio must hold for its next loss to have every try again (the runtime's stable-run time) STABLE_RUN: ClassVar[float] = STABLE_RUN _zigbee_device_path: str _zigbe_db: str _majordom_discoveries: dict[UUID, Discovery] # discovery metadata surfaced to the Hub _awaiting_zb_discoveries: dict[UUID, ZPDevice] # on the network, discovered, not yet paired in majordom _connected_devices: dict[UUID, ZPDevice] # paired in majordom # (the ZPDevice values could be shrunk to just the IEEE address to save memory, if needed.) _mapper: ZigBeeMapper _tasks: set[asyncio.Task[Any]] def __init__(self, platform: Platform, *, settings: Settings | None = None): super().__init__(platform, settings=settings) # Mapper is wired with the framework's UUID generators so every Zigbee id is namespaced # consistently under the integration and device (see ZigBeeMapper). self._mapper = ZigBeeMapper(self.device_uuid, self.parameter_uuid) self._majordom_discoveries: dict[UUID, Discovery] = {} self._awaiting_zb_discoveries: dict[UUID, ZPDevice] = {} self._connected_devices: dict[UUID, ZPDevice] = {} self._availability: dict[UUID, bool] = {} # physical_id -> last signalled availability self._subscriptions: dict[UUID, list[tuple[zigpy.zcl.Cluster, ZBAttributeUpdatedListener]]] = {} self._tasks: set[asyncio.Task[Any]] = set() self._application: ControllerApplication | None = None # while started self._radio_lock = asyncio.Lock() # held while the radio opens, and through a reconnect: close, waits, reopens self._reconnecting: asyncio.Task[None] | None = None self._reopens = 0 # tries since the radio last held: drops in a row add up self._opened_at = 0.0 # monotonic, when the radio last opened # ------------------------------------------------------------------------- # AbstractController interface # ------------------------------------------------------------------------- name = "ZigBee" @property def discoveries(self) -> dict[UUID, Discovery]: return self._majordom_discoveries @property @override def device_type(self) -> type[ZBDevice]: return ZBDevice @property @override def parameter_type(self) -> type[ZBParameter]: return ZBParameter @property @override def device_state_type(self) -> type[ZBDeviceState]: return ZBDeviceState # ------------------------------------------------------------------------- # Lifecycle # ------------------------------------------------------------------------- async def start(self): self._reopens = 0 async with self._radio_lock: await self._open() async def stop(self): log.debug("[STOP] shutting down") while reconnecting := self._reconnecting: # the radio it opened may report a loss as it is cancelled self._reconnecting = None reconnecting.cancel() await asyncio.gather(reconnecting, return_exceptions=True) await self._close() async def _open(self): """Starts zigpy on the bound radio and takes over the devices on its network.""" link = self.peripherals.endpoint("zigbee") tx_power = self.settings.tx_power self._zigbee_device_path = link.url self._zigbe_db = str(self.platform.documents_folder(self) / "zigbee.db") log.debug(f"[START] port={self._zigbee_device_path} db={self._zigbe_db}") config: dict[str, Any] = { CONF_DEVICE: _device_config(link), CONF_DATABASE: self._zigbe_db, CONF_NWK: {} if tx_power is None else {CONF_NWK_TX_POWER: tx_power}, } # Register per-device quirks before the radio starts interviewing devices. await _ensure_quirks_loaded() # Start the zigpy application of the radio library the bound dialect names. application_cls = application_class(link.dialect) # Kept before it starts the radio: stop() then closes what a failed or cut short start opened self._application = await application_cls.new(config=config, start_radio=False) try: await self._application.startup(auto_form=True) except Exception as e: if "locked" in str(e).lower() or "permission" in str(e).lower(): holder = port_holder(self._zigbee_device_path) msg = f"{self._zigbee_device_path} is locked" if holder: msg += f" by: {holder}" raise PermissionError(msg) from e raise self._application.add_listener(self) self._opened_at = time.monotonic() log.debug(f"[READY] connected to {self._zigbee_device_path}") network = self._application.state.network_info self.settings.channel, self.settings.pan_id = int(network.channel), f"0x{int(network.pan_id):04X}" self.settings.extended_pan_id = str(network.extended_pan_id) self._availability.clear() # report every device's availability afresh async with self.platform.device_repository(self) as device_repo: # Subscribe to attribute updates and add the device to _connected_devices # if the Zigbee device is in the majordom database, otherwise start a discovery cycle. for zbdevice in self._application.devices.values(): if zbdevice.nwk == 0x0000: continue physical_id = self._mapper.device_uuid_from_ieee(zbdevice.ieee) if await device_repo.get(physical_id=physical_id, as_=ZBDevice): self._connected_devices[physical_id] = zbdevice await self._subscribe(physical_id, zbdevice) log.debug(f"[KNOWN] ieee={zbdevice.ieee} nwk=0x{zbdevice.nwk:04X}") else: self._create_task(self._disconnect_unpaired_discovery(physical_id, zbdevice.ieee)) log.debug( f"[UNKNOWN] ieee={zbdevice.ieee} nwk=0x{zbdevice.nwk:04X} — " "not in DB, starting disconnect timer" ) await zbdevice.initialize() # never raises: zigpy reports a failure as device_init_failure # Any device in our DB that isn't on the network anymore is marked unavailable on boot. for device in await device_repo.get_all(as_=ZBDevice): ieee = self._mapper.convert_str_to_eui64(device.integration_data.ieee) if self._application.get_device(ieee): continue device.available = False device.last_error = f"Device {device.name} is no longer connected to the ZigBee network" self._availability[device.physical_id] = False # baseline for mid-session transitions await device_repo.save(device) # the Hub marked them unavailable when Zigbee stopped for physical_id, zbdevice in list(self._connected_devices.items()): if _is_seen_lately(zbdevice): await self._set_availability(physical_id, True) else: self._availability[physical_id] = False # left or died: until its next message async def _close(self): """Lets go of the radio and of what was found on it.""" # Let go first: the runtime abandons a stop stuck on a vanished radio, cancelling it inside shutdown() application, self._application = self._application, None if application: application.remove_listener(self) # its shutdown closes the radio: no connection is lost for task in self._tasks: task.cancel() self._majordom_discoveries.clear() self._awaiting_zb_discoveries.clear() self._connected_devices.clear() self._subscriptions.clear() if application: # Shielded: a stop cancelling the reconnect while it closes a lost radio would leave zigpy's database open, # whose thread then keeps the process from exiting await asyncio.shield(application.shutdown()) if self._tasks: await asyncio.gather(*self._tasks, return_exceptions=True) self._tasks.clear() # ------------------------------------------------------------------------- # Hub -> device operations # ------------------------------------------------------------------------- async def start_pairing_window(self, duration_sec: int, credentials: ProvidedCredentials | None = None): if not self._application: raise self._not_started() log.debug(f"[PERMIT-JOIN] opening for {duration_sec}s") await self._application.permit(duration_sec) async def pair_device( self, discovery: Discovery, draft: ZBDeviceState, credentials: ProvidedCredentials | None ) -> ZBDeviceState: # Break down into submethods device = draft zbdevice = self._awaiting_zb_discoveries[discovery.id] device.physical_id = self._mapper.device_uuid_from_ieee(zbdevice.ieee) await self.check_device_id(device.physical_id, device) # Still offered until the Hub saves it (it fetches it then): joined, the node needs nothing undone, and a # failed or unsaved pairing is retried from the same discovery (the node leaves after the join timeout) device.integration_data = ZBDeviceIntegrationData(ieee=self._mapper.convert_eui64_to_str(zbdevice.ieee)) # Manufacturer-provided, read-only description — the ZCL model string. device.description = zbdevice.model or None parameters: list[ParameterState[ZBParameterIntegrationData]] = list() # v2 QuirkBuilder entity judgment for this device (empty for non-quirked devices). quirk_ux = quirk_ux_map(zbdevice) for endpoint in zbdevice.non_zdo_endpoints: # Only server (input) clusters: output clusters are client-side, so their attributes # live on the remote and fetch/send_command never reach them. for cluster in endpoint.in_clusters.values(): # Probe before mapping: a simple descriptor often lists clusters the firmware # doesn't implement (e.g. Tuya relays with Metering/ElectricalMeasurement). The # read marks unsupported attributes, so only what the device has gets exposed. await self._read_cluster_attributes( device, zbdevice, endpoint, cluster, self._readable_attribute_ids(cluster), log_prefix="[PAIR]", timeout=2, ) if self._is_unimplemented(cluster): log.debug(f"[PAIR] skipping unimplemented {_zb_path(endpoint=endpoint, cluster=cluster)}") continue for attribute_id, attribute in cluster.attributes.items(): if cluster.is_attribute_unsupported(attribute_id): continue value = None # Classification via the priority ladder (see the zigbee README): our hand # overrides > v2 quirk metadata > harvested zha judgment > fallback heuristic # (which warns). Metadata and manufacturer-on-system-cluster attrs are hidden. spec, source = classify_attribute( cluster.cluster_id, attribute_id, attribute.name, writable=bool(attribute.access & ZCLAttributeAccess.Write), reportable=bool(attribute.access & ZCLAttributeAccess.Report), quirk_ux=quirk_ux.get((endpoint.endpoint_id, cluster.cluster_id, attribute.name)), ) visibility = spec.visibility role = ( spec.role if spec.role is not None else self._mapper.parse_zigbee_attribute_access(attribute.access) ) if source.startswith("fallback"): log.warning( "[PAIR] uncurated attribute " f"{_zb_path(cluster=cluster, attr_id=attribute_id, attr_only=True)} -> " f"{visibility.value} ({source}); add to OUR_ATTRIBUTE_UX or refresh the zha harvest" ) data_type = self._mapper.parse_zigbee_data_type(attribute.zcl_type) min_value = None max_value = None # Annotated so the untyped-enum comprehension below (member.name is Unknown) # matches Parameter.valid_values' declared type. valid_values: dict[int | float | str, str] | None = None min_step = get_min_step(cluster.cluster_id, attribute_id) # Our spec tables win; the harvested/quirk unit fills gaps get_unit() leaves plain. unit = get_unit(cluster.cluster_id, attribute_id) if unit is ParameterUnit.plain and spec.unit is not None: unit = spec.unit if hasattr(attribute.type, "min_value"): min_value = attribute.type.min_value if hasattr(attribute.type, "max_value"): max_value = attribute.type.max_value # Metadata priority 1: the device's own limit attributes (runtime values) win # over the wire-type default. cluster.get returns the cached sibling value. min_value, max_value, missing_bounds = resolve_metadata_bounds( cluster.cluster_id, attribute_id, cluster.get, min_value, max_value ) for missing_attr in missing_bounds: log.debug( "[PAIR] metadata source " f"{_zb_path(cluster=cluster, attr_id=missing_attr, attr_only=True)} not reported for " f"{_zb_path(cluster=cluster, attr_id=attribute_id, attr_only=True)} — " "quirk or unsupported; using wire-type default" ) if issubclass(attribute.type, Enum) and data_type != ParameterDataType.bool: valid_values = {member.value: member.name for member in attribute.type} parameters.append( ZBParameterState( id=self._mapper.attribute_parameter_uuid( device.physical_id, endpoint.endpoint_id, cluster.cluster_id, attribute_id ), name=attribute.name, data_type=data_type, visibility=visibility, min_value=min_value, max_value=max_value, min_step=min_step, unit=unit, valid_values=valid_values, role=role, integration_data=ZBParameterIntegrationData( endpoint_id=endpoint.endpoint_id, cluster_id=cluster.cluster_id, attribute_id=attribute_id, type=ZBParameterType.attribute, ), value=value, ) ) for command in cluster.commands: fields: list[Parameter] = [] # Command visibility: system-cluster commands hidden; everyday one-tap # actions -> user; every other command (schedule/credential/log # management) -> setting. if cluster.cluster_id in SYSTEM_CLUSTERS: visibility = ParameterVisibility.system elif (cluster.cluster_id, command.id) in EVERYDAY_COMMANDS: visibility = ParameterVisibility.user else: visibility = ParameterVisibility.setting for i, field in enumerate(command.schema.fields): min_value = None max_value = None valid_values: dict[int | float | str, str] | None = None if hasattr(field.type, "min_value"): min_value = field.type.min_value if hasattr(field.type, "max_value"): max_value = field.type.max_value if isinstance(field.type, type) and issubclass(field.type, Enum): valid_values = {member.value: member.name for member in field.type} fields.append( Parameter( id=self._mapper.command_field_uuid( device.physical_id, endpoint.endpoint_id, cluster.cluster_id, command.id, i ), name=field.name, data_type=self._mapper.parse_zigbee_data_type(field.type), role=ParameterRole.control, visibility=ParameterVisibility.setting, min_value=min_value, max_value=max_value, valid_values=valid_values, integration_data=None, ) ) parameters.append( ZBParameterState( id=self._mapper.command_parameter_uuid( device.physical_id, endpoint.endpoint_id, cluster.cluster_id, command.id ), name=command.name, data_type=ParameterDataType.struct if fields else ParameterDataType.none, role=ParameterRole.control, fields=json.loads(json.dumps([f.model_dump(mode="json") for f in fields])) if fields else None, visibility=visibility, integration_data=ZBParameterIntegrationData( endpoint_id=endpoint.endpoint_id, cluster_id=cluster.cluster_id, command_id=command.id, type=ZBParameterType.command, ), value=None, ) ) device.parameters = parameters main_parameter_id, main_spec = self._get_device_main_parameter(device.physical_id, zbdevice) device.main_parameter = main_parameter_id if main_parameter_id and main_spec is not None: # Attach the one-tap send info to the chosen main parameter; drop the main parameter # if the target command/attribute wasn't actually exposed. main_parameter = next((p for p in parameters if p.id == main_parameter_id), None) if main_parameter is None: device.main_parameter = None elif main_spec.is_attribute and main_spec.cycle: # Attribute main (e.g. fan_mode): a tap cycles through a value subset. Store it # as the parameter's default_value — the generic, relay-readable cycle source # (the relay derives the next value via Parameter.main_cycle). A spec with no # explicit subset leaves the param to cycle its full valid_values, which the # relay already derives, so there's nothing to set here. main_parameter.default_value = set(main_spec.cycle) elif main_spec.default_arguments is not None: data = main_parameter.integration_data data.default_arguments = main_spec.default_arguments # The same arguments keyed by sub-parameter id (the SDK struct value) as a one-value # button: a `struct` command then passes can_be_main_parameter and the relay sends # them on a tap. default_arguments stays for devices stored before this. endpoint = cast(zigpy.endpoint.Endpoint, zbdevice.endpoints[data.endpoint_id]) zbcommand = endpoint.in_clusters[data.cluster_id].server_commands[main_spec.target_id] names = self._command_field_names(device.physical_id, data.endpoint_id, data.cluster_id, zbcommand) ids = {name: field_id for field_id, name in names.items()} main_parameter.default_value = { ids.get(name, name): value for name, value in main_spec.default_arguments.items() } log.debug( f"[PAIR] mapped schema {_zb_path(device, zbdevice)}\n\t" + "\n\t".join( f" {p.role.value:8} {p.visibility.value:8} {p.data_type.value:10} {p.name} id={p.id}" for p in parameters ), ) await self._subscribe(device.physical_id, zbdevice) # The Hub saves the draft, tells the app the device is connected and then fetches it device.available = True self._availability[device.physical_id] = True return device async def unpair(self, device: ZBDevice): if not self._application: raise self._not_started() if not device.integration_data.ieee: return # a record that never got its node log.debug(f"[UNPAIR] ieee={device.integration_data.ieee}") physical_id = self._mapper.device_uuid_from_ieee( self._mapper.convert_str_to_eui64(device.integration_data.ieee) ) try: # Still offered: the Hub's rollback of an unsaved pairing. The joined node needs no undo and stays the # discovery the Hub retries from (the unpaired timer removes it if nobody does) if physical_id not in self._majordom_discoveries: await self._application.remove(self._mapper.convert_str_to_eui64(device.integration_data.ieee)) finally: for cluster, listener in self._subscriptions.pop(physical_id, []): cluster.remove_listener(listener) self._connected_devices.pop(physical_id, None) self._availability.pop(physical_id, None) if physical_id not in self._majordom_discoveries: self._awaiting_zb_discoveries.pop(physical_id, None) async def identify(self, device: ZBDevice): if not self._application: raise self._not_started() ieee = self._mapper.convert_str_to_eui64(device.integration_data.ieee) if not (zbdevice := self._application.devices.get(ieee)): raise ZBUnexpectedError(f"Device {ieee} not found in ZigBee network") if not zbdevice.is_initialized: raise ZBUnexpectedError(f"Device {ieee} is not initialized") for endpoint in zbdevice.non_zdo_endpoints: cluster = endpoint.in_clusters.get(Identify.cluster_id) if not cluster: continue await cluster.identify(10) # 10 - identification time async def fetch(self, device: ZBDevice): if not self._application: raise self._not_started() ieee = self._mapper.convert_str_to_eui64(device.integration_data.ieee) if not (zbdevice := self._application.devices.get(ieee)): raise ZBUnexpectedError(f"Device {ieee} not found in ZigBee network") # The Hub saved it (it fetches only then): paired now, no longer offered self._connected_devices[device.physical_id] = zbdevice self._awaiting_zb_discoveries.pop(device.physical_id, None) self._majordom_discoveries.pop(device.physical_id, None) if not zbdevice.is_initialized: log.debug(f"[FETCH] device={device.physical_id} is still being interviewed, skipping") return if not self._is_subscribed( device.physical_id, zbdevice ): # zigpy rebuilt its clusters (a re-interview, a quirk) await self._subscribe(device.physical_id, zbdevice) events: list[DeviceParameterChange] = list() log.debug(f"[FETCH] start device={device.physical_id}({zbdevice.model})") t0 = asyncio.get_event_loop().time() try: async with asyncio.timeout(_FETCH_TIMEOUT): for endpoint in zbdevice.non_zdo_endpoints: for cluster_id, cluster in endpoint.in_clusters.items(): attr_values = await self._read_cluster_attributes( device, zbdevice, endpoint, cluster, self._readable_attribute_ids(cluster), log_prefix="[FETCH]", timeout=2, ) if self._is_unimplemented(cluster): continue # pairing exposed no parameters for it for attribute_id in cluster.attributes: if cluster.is_attribute_unsupported(attribute_id) or attribute_id not in attr_values: continue # unanswered: the device keeps its last known value events.append( DeviceParameterChange( physical_id=device.physical_id, parameter_id=self._mapper.attribute_parameter_uuid( device.physical_id, endpoint.endpoint_id, cluster_id, attribute_id ), value=self._mapper.normalize_zigbee_value(attr_values[attribute_id]), ) ) for command in cluster.commands: events.append( DeviceParameterChange( physical_id=device.physical_id, parameter_id=self._mapper.command_parameter_uuid( device.physical_id, endpoint.endpoint_id, cluster_id, command.id ), value=None, ) ) except TimeoutError: log.warning( f"[FETCH] device={device.physical_id}({zbdevice.model}) took over {_FETCH_TIMEOUT}s, " "reporting what it answered" ) duration = asyncio.get_event_loop().time() - t0 log.debug(f"[FETCH] done device={device.physical_id}({zbdevice.model}) duration={duration:.2f}s") await self.output.controller_did_receive_events(self, events) async def send_command(self, command: DeviceCommand, device: ZBDevice, parameter: ZBParameter): if not self._application: raise self._not_started() ieee = self._mapper.convert_str_to_eui64(device.integration_data.ieee) if not (zbdevice := self._application.devices.get(ieee)): raise ZBUnexpectedError(f"Device {ieee} not found in ZigBee network") if not (endpoint := zbdevice.endpoints.get(parameter.integration_data.endpoint_id)): raise ZBUnexpectedError(f"Endpoint {parameter.integration_data.endpoint_id} not found") # endpoints[0] is the device's ZDO; a real parameter always lives on a numbered Endpoint. # Narrowing here fixes it for every downstream use (in_clusters, _zb_path, _check_zcl_failures). if not isinstance(endpoint, zigpy.endpoint.Endpoint): raise ZBUnexpectedError( f"Endpoint {parameter.integration_data.endpoint_id} is the ZDO, not a device endpoint" ) if not (cluster := endpoint.in_clusters.get(parameter.integration_data.cluster_id)): raise ZBUnexpectedError(f"Cluster {parameter.integration_data.cluster_id} not found") if parameter.integration_data.type is ZBParameterType.attribute: if parameter.role != ParameterRole.control: raise ZBUnexpectedError(f"Parameter '{parameter.name}' is not a control parameter") attr_id = parameter.integration_data.attribute_id # The relay pre-derives a main-tap's value (bool / cycle / button) before dispatch, so # an attribute write just sends it — the cycle logic lives in the relay, not here. value = command.value if value is None: raise ZBUnexpectedError(f"No value to send for '{parameter.name}'") try: result = await cluster.write_attributes({attr_id: value}) except Exception as e: raise ZBConnectionError( f"[CMD] write_attributes transport error " f"{_zb_path(device, zbdevice, endpoint, cluster, attr_id, error=e)}" ) from None _check_zcl_failures( {r.attrid: r.status for r in result[0]}, cluster, "[CMD]", device=device, zbdevice=zbdevice, endpoint=endpoint, ) log.info(f"[CMD] write_attributes {_zb_path(device, zbdevice, endpoint, cluster, attr_id)}") else: zbcommand = cluster.commands_by_name.get(parameter.name) if not zbcommand: raise ZBUnexpectedError(f"Command {parameter.name} not found in cluster") # A value-less send (e.g. tapping the main parameter) falls back to the arguments this # command was set up with as a main parameter — see integration_data.default_arguments. arguments = command.value if command.value is not None else parameter.integration_data.default_arguments if isinstance(arguments, dict): # A struct value is keyed by sub-parameter id (SDK), zigpy takes field names. Name # keys (e.g. default_arguments) pass through as-is. names = self._command_field_names( device.physical_id, parameter.integration_data.endpoint_id, parameter.integration_data.cluster_id, zbcommand, ) arguments = {names.get(str(key), str(key)): value for key, value in arguments.items()} try: if isinstance(arguments, dict): result = await cluster.command(zbcommand.id, **arguments) elif arguments is not None: result = await cluster.command(zbcommand.id, arguments) else: result = await cluster.command(zbcommand.id) except Exception as e: raise ZBConnectionError( f"[CMD] command error {_zb_path(device, zbdevice, endpoint, cluster, error=e)}" ) from None # cluster.command returns the DefaultResponse or cluster-specific response; # check status field if present (DefaultResponse carries it) if hasattr(result, "status") and result.status != ZCLStatus.SUCCESS: raise ZBOperationError( f"[CMD] command failure {_zb_path(device, zbdevice, endpoint, cluster)}: " f"status={result.status.name}" ) # ------------------------------------------------------------------------- # Device -> Hub: Zigbee network events (zigpy listener) & availability # ------------------------------------------------------------------------- def connection_lost(self, exc: Exception | None): """zigpy lost the radio (the stick re-enumerated, or the service in front of it restarted) and doesn't reconnect by itself: reopen it in place. An unplugged stick stops Zigbee through its lost need instead.""" log.warning(f"[RADIO] connection lost: {exc!r}") if self._reconnecting: self._reconnecting.cancel() # lost again while it reopened: start over self._reconnecting = asyncio.create_task(self._reconnect()) self._reconnecting.add_done_callback(_log_task_exception) async def _reconnect(self): async with self._radio_lock: if time.monotonic() - self._opened_at >= self.STABLE_RUN: self._reopens = 0 for physical_id in list(self._connected_devices): # unreachable until the radio is back await self._set_availability(physical_id, False) lost = list(self._majordom_discoveries) await self._close() for discovery_id in lost: await self.output.controller_did_lose_discovery(self, discovery_id) for delay in self.RECONNECT_DELAYS[self._reopens :]: self._reopens += 1 await asyncio.sleep(delay) try: await self._open() except Exception as e: log.warning(f"[RADIO] reconnecting failed: {e!r}") await self._close() else: log.info("[RADIO] reconnected") if self._reconnecting is asyncio.current_task(): # unless a loss meanwhile started another self._reconnecting = None return error = IntegrationError("radio-lost", "Lost the connection to the Zigbee radio.", is_still_running=False) await self.output.controller_did_encounter_error(self, error) def device_joined(self, device: ZPDevice): """A device joined the Zigbee network (only happens while the permit-join window is open).""" log.debug(f"[JOIN] ieee={device.ieee} nwk=0x{device.nwk:04X}") physical_id = self._mapper.device_uuid_from_ieee(device.ieee) # Zigbee has no separate "discovery": a device is on the network as soon as it joins. # We hold it in the awaiting list and disconnect it if it isn't paired in majordom within # the window (see _disconnect_unpaired_discovery). An already-paired device that merely # rejoined is handled in device_initialized, not here. self._create_task(self._disconnect_unpaired_discovery(physical_id, device.ieee)) def device_initialized(self, device: ZPDevice): """A device finished interviewing and is ready to talk. Fires both for a brand-new join and when an already-paired device rejoins the network after being offline.""" log.debug( f"[INIT] ieee={device.ieee} nwk=0x{device.nwk:04X} " f"model={device.model!r} manufacturer={device.manufacturer!r}" ) physical_id = self._mapper.device_uuid_from_ieee(device.ieee) # Already paired in majordom -> a mid-session reconnect: re-subscribe and mark it back # online instead of surfacing it as a fresh discovery. if physical_id in self._connected_devices: self._connected_devices[physical_id] = device self._create_task(self._subscribe(physical_id, device)) self._create_task(self._set_availability(physical_id, True)) return # Awaiting pairing and re-initialized -> just (re)subscribe. if physical_id in self.discoveries: self._awaiting_zb_discoveries[physical_id] = device self._create_task(self._subscribe(physical_id, device)) return # Otherwise it's a new, not-yet-paired device -> surface it as a discovery. discovery = Discovery( id=physical_id, integration=NonEmptyStr(self.key), expected_credentials_options=[CredentialsType.none], expiration=None, transport=NonEmptyStr("ZIGBEE"), device_manufacturer=None, device_name=NonEmptyStr(device.name), device_category=None, device_icon=None, ) self._majordom_discoveries[physical_id] = discovery self._awaiting_zb_discoveries[physical_id] = device log.debug(f"[DISCOVERY] ieee={device.ieee} discovery_id={physical_id}") self._create_task(self.output.controller_did_receive_discovery(self, discovery)) def device_left(self, device: ZPDevice): """A device left the Zigbee network. If it's one of ours, mark it unavailable so the app reflects it; the pairing stays in the DB so it comes back online on rejoin.""" log.debug(f"[LEFT] ieee={device.ieee} nwk=0x{device.nwk:04X}") physical_id = self._mapper.device_uuid_from_ieee(device.ieee) if physical_id in self._connected_devices: self._create_task(self._set_availability(physical_id, False)) def handle_message(self, device: ZPDevice, *_): """Any message from a device: one held unavailable is back.""" physical_id = self._mapper.device_uuid_from_ieee(device.ieee) if self._availability.get(physical_id) is False and physical_id in self._connected_devices: self._create_task(self._set_availability(physical_id, True)) async def _set_availability(self, physical_id: UUID, available: bool): """Single funnel for availability transitions — dedupes so the Hub is only told on an actual change, and translates it into the framework's connect / lose callbacks.""" if self._availability.get(physical_id) == available: return self._availability[physical_id] = available if available: await self.output.controller_did_connect_device(self, physical_id=physical_id) else: await self.output.controller_did_lose_device(self, physical_id=physical_id) # ------------------------------------------------------------------------- # Private helpers # ------------------------------------------------------------------------- async def _read_cluster_attributes( self, device: ZBDevice, zbdevice: ZPDevice, endpoint: zigpy.endpoint.Endpoint, cluster: zigpy.zcl.Cluster, ids: list[int], *, only_cache: bool = False, log_prefix: str = "[READ]", timeout: float | None = None, ) -> dict[int, object]: attr_values: dict[int, object] = {} chunks = [ids[i : i + _MAX_ATTRS_PER_REQUEST] for i in range(0, len(ids), _MAX_ATTRS_PER_REQUEST)] for chunk in chunks: try: # read_attributes accepts attribute names/ids/defs; we only pass ids, and list # invariance is the only reason the plain list[int] doesn't fit the wider param type. values, failures = await cluster.read_attributes( cast("list[int | str | ZCLAttributeDef]", chunk), only_cache=only_cache, timeout=timeout ) except TimeoutError as e: log_level = log.error if cluster.cluster_id in MAIN_PARAMETER_BY_CLUSTER else log.warning # A listed but unanswered optional cluster (e.g. Metering on a Tuya relay): the # remaining chunks would time out too, so don't wait for each of them. log_level( f"{log_prefix} read_attributes timeout " f"{_zb_path(device, zbdevice, endpoint, cluster, attr_ids=chunk, error=e)}" ) await asyncio.sleep(_INTER_CHUNK_DELAY) # let bellows send pending ASH ACKs break except Exception as e: log.error( f"{log_prefix} read_attributes error " f"{_zb_path(device, zbdevice, endpoint, cluster, attr_ids=chunk, error=e)}" ) await asyncio.sleep(_INTER_CHUNK_DELAY) # let bellows send pending ASH ACKs continue await asyncio.sleep(_INTER_CHUNK_DELAY) # pace chunks to prevent NCP ACK timeout attr_values.update(values) _check_zcl_failures( failures, cluster, log_prefix, device=device, zbdevice=zbdevice, endpoint=endpoint, raise_errors=False, ) return attr_values @staticmethod def _readable_attribute_ids(cluster: zigpy.zcl.Cluster) -> list[int]: return [attr_id for attr_id in cluster.attributes if not cluster.is_attribute_unsupported(attr_id)] @classmethod def _is_unimplemented(cls, cluster: zigpy.zcl.Cluster) -> bool: """Listed in the simple descriptor, but the device reported every attribute unsupported.""" return bool(cluster.attributes) and not cls._readable_attribute_ids(cluster) def _not_started(self) -> ZBConnectionError: if self._reconnecting: return ZBConnectionError("The Zigbee radio is reconnecting") return ZBConnectionError("ZigBee application is not started") def _create_task[T](self, coro: Coroutine[Any, Any, T]) -> asyncio.Task[T]: task = asyncio.create_task(coro) self._tasks.add(task) task.add_done_callback(self._tasks.discard) task.add_done_callback(_log_task_exception) return task def _is_subscribed(self, physical_id: UUID, device: ZPDevice) -> bool: subscribed = {id(cluster) for cluster, _ in self._subscriptions.get(physical_id, [])} return subscribed == { id(cluster) for endpoint in device.non_zdo_endpoints for cluster in endpoint.in_clusters.values() } async def _subscribe(self, physical_id: UUID, device: ZPDevice): """Listens to the device's attribute reports, once: a rejoin keeps a plain device's clusters.""" for cluster, listener in self._subscriptions.pop(physical_id, []): cluster.remove_listener(listener) subscriptions = self._subscriptions[physical_id] = [] for endpoint in device.non_zdo_endpoints: for cluster in endpoint.in_clusters.values(): listener = ZBAttributeUpdatedListener(self, physical_id, cluster) cluster.add_listener(listener) subscriptions.append((cluster, listener)) async def _disconnect_unpaired_discovery(self, discovery_id: UUID, ieee: EUI64): await asyncio.sleep(300) # 5 minutes if discovery_id not in self._majordom_discoveries and discovery_id in self._connected_devices: # if the device was connected return log.info(f"[REMOVE] {ieee} wasn't paired within 5 minutes: removing it from the network") assert self._application # _close() cancels this task in the same step it lets go of the application await self._application.remove(ieee) self._awaiting_zb_discoveries.pop(discovery_id, None) if self._majordom_discoveries.pop(discovery_id, None) is not None: await self.output.controller_did_lose_discovery(self, discovery_id) def _command_field_names( self, physical_id: UUID, endpoint_id: int, cluster_id: int, zbcommand: ZCLCommandDef ) -> dict[str, str]: """Sub-parameter id (as str) -> zigpy field name, for a command parameter's fields.""" fields = enumerate(zbcommand.schema.fields) return { str(self._mapper.command_field_uuid(physical_id, endpoint_id, cluster_id, zbcommand.id, i)): field.name for i, field in fields } def _get_device_main_parameter( self, physical_id: UUID, zbdevice: ZPDevice ) -> tuple[UUID | None, MainParameterSpec | None]: """Pick the parameter used for the device's one-tap action on the room view, in cluster priority order (see MAIN_PARAMETER_BY_CLUSTER). Returns the parameter id and its spec (command or attribute main), or (None, None) if the device has no sensible one-tap action.""" for endpoint in zbdevice.non_zdo_endpoints: for cluster_id, spec in MAIN_PARAMETER_BY_CLUSTER.items(): if endpoint.in_clusters.get(cluster_id): if spec.is_attribute: param_id = self._mapper.attribute_parameter_uuid( physical_id, endpoint.endpoint_id, cluster_id, spec.target_id ) else: param_id = self._mapper.command_parameter_uuid( physical_id, endpoint.endpoint_id, cluster_id, spec.target_id ) return param_id, spec return None, None ================================================================================ # FILE: majordom_zigbee/exceptions.py ================================================================================ class ZBConnectionError(Exception): """Raised when ZigBee application is not started or not available.""" pass class ZBUnexpectedError(Exception): """Raised when an unexpected internal error occurs.""" pass class ZBOperationError(Exception): """Raised when a ZCL operation succeeds at the transport level but the device returns a non-SUCCESS status.""" pass ================================================================================ # FILE: majordom_zigbee/listener.py ================================================================================ from uuid import UUID from majordom_integration_sdk.schemas.event import DeviceParameterChange from zigpy.zcl import Cluster class ZBAttributeUpdatedListener: def __init__(self, controller, physical_id: UUID, cluster: Cluster): self._controller = controller self._physical_id = physical_id self._cluster = cluster def attribute_updated(self, attribute_id, value, time): cluster = self._cluster endpoint_id = cluster.endpoint.endpoint_id parameter_id = self._controller._mapper.attribute_parameter_uuid( self._physical_id, endpoint_id, cluster.cluster_id, attribute_id ) event = DeviceParameterChange( physical_id=self._physical_id, parameter_id=parameter_id, value=self._controller._mapper.normalize_zigbee_value(value), ) self._controller._create_task(self._controller.output.controller_did_receive_events(self._controller, [event])) ================================================================================ # FILE: majordom_zigbee/mapper.py ================================================================================ from collections.abc import Callable from enum import Enum, Flag from uuid import UUID import zigpy.types as t from majordom_integration_sdk.schemas.parameter import ParameterDataType, ParameterRole from zigpy.types import EUI64 from zigpy.zcl.foundation import DataTypeId, ZCLAttributeAccess from .exceptions import ZBUnexpectedError class ZigBeeMapper: def __init__( self, device_uuid: Callable[[bytes], UUID], parameter_uuid: Callable[[UUID, str], UUID], ): # The controller's framework UUID generators (see AbstractController). Every Zigbee # id — device from its IEEE address, parameters from their endpoint/cluster/attribute # path — is derived through these, so a device's parameters are namespaced under the # device and stay identical whether built at pairing, on fetch, or from a live report. self._device_uuid = device_uuid self._parameter_uuid = parameter_uuid # ------------------------------------------------------------------------- # Identity: Zigbee addresses/paths -> MajorDom UUIDs # ------------------------------------------------------------------------- def device_uuid_from_ieee(self, ieee: EUI64) -> UUID: return self._device_uuid(bytes(ieee.serialize())) def normalize_zigbee_value(self, value): """Coerce zigpy wire values to plain python types for the SDK's typed encoder. zigpy hands attribute values back as its own types — ``t.Bool`` is an int-enum (NOT a python bool), enum8/16 and bitmaps are int-enums, ints/floats/strings are subclasses. ``ParameterState`` values are pythonic, so coerce zigpys wire types here — the single choke point for both the fetch path and attribute reports. """ if value is None or isinstance(value, bool): return value if isinstance(value, t.Bool): return bool(value) if isinstance(value, Enum | Flag): return int(value) # zigpy ZCL enums/bitmaps are int-based if isinstance(value, int): return int(value) if isinstance(value, float): return float(value) if isinstance(value, str): return str(value) return value def attribute_parameter_uuid(self, physical_id: UUID, endpoint_id: int, cluster_id: int, attribute_id: int) -> UUID: return self._parameter_uuid(physical_id, f"attribute_{endpoint_id}/{cluster_id}/{attribute_id}") def command_parameter_uuid(self, physical_id: UUID, endpoint_id: int, cluster_id: int, command_id: int) -> UUID: return self._parameter_uuid(physical_id, f"command_{endpoint_id}/{cluster_id}/{command_id}") def command_field_uuid( self, physical_id: UUID, endpoint_id: int, cluster_id: int, command_id: int, field_index: int ) -> UUID: return self._parameter_uuid(physical_id, f"field_{endpoint_id}/{cluster_id}/{command_id}/{field_index}") # ------------------------------------------------------------------------- # Value / type conversions # ------------------------------------------------------------------------- def convert_eui64_to_str(self, data: EUI64) -> str: return EUI64.__str__(data) def convert_str_to_eui64(self, data: str | None) -> EUI64: # Same as device_uuid_from_ieee: the domain field is Optional but must be present here. if data is None: raise ZBUnexpectedError("Zigbee device is missing its IEEE address") return EUI64.convert(data) def parse_zigbee_attribute_access(self, access) -> ParameterRole: can_read = bool(access & ZCLAttributeAccess.Read) can_write = bool(access & ZCLAttributeAccess.Write) if can_write: return ParameterRole.control if can_read: return ParameterRole.sensor return ParameterRole.event def parse_zigbee_data_type(self, zcl_type: int | type) -> ParameterDataType: if isinstance(zcl_type, type): if issubclass(zcl_type, t.Bool): zcl_type = DataTypeId.bool_ elif issubclass(zcl_type, Flag): zcl_type = DataTypeId.map8 elif issubclass(zcl_type, Enum): zcl_type = DataTypeId.enum8 elif issubclass(zcl_type, t.FixedIntType): zcl_type = DataTypeId.uint8 elif issubclass(zcl_type, float): zcl_type = DataTypeId.single else: zcl_type = DataTypeId.nodata type_id = DataTypeId(zcl_type) if type_id in {DataTypeId.unk, DataTypeId.nodata}: return ParameterDataType.none # DataTypeId, not DataType — zigpy 2.0's DataType.bool_ is a rich descriptor that never # equals a DataTypeId, which silently sent every bool attribute to the `none` fallthrough. if type_id == DataTypeId.bool_: return ParameterDataType.bool if type_id in {DataTypeId.enum8, DataTypeId.enum16}: return ParameterDataType.enum if type_id in {DataTypeId.string, DataTypeId.string16}: return ParameterDataType.string if type_id in {DataTypeId.semi, DataTypeId.single, DataTypeId.double}: return ParameterDataType.decimal if type_id in { DataTypeId.uint8, DataTypeId.uint16, DataTypeId.uint24, DataTypeId.uint32, DataTypeId.uint40, DataTypeId.uint48, DataTypeId.uint56, DataTypeId.uint64, DataTypeId.int8, DataTypeId.int16, DataTypeId.int24, DataTypeId.int32, DataTypeId.int40, DataTypeId.int48, DataTypeId.int56, DataTypeId.int64, DataTypeId.map8, DataTypeId.map16, DataTypeId.map24, DataTypeId.map32, DataTypeId.map40, DataTypeId.map48, DataTypeId.map56, DataTypeId.map64, DataTypeId.ToD, DataTypeId.date, DataTypeId.UTC, DataTypeId.clusterId, DataTypeId.attribId, DataTypeId.bacOID, }: return ParameterDataType.integer if type_id in { DataTypeId.data8, DataTypeId.data16, DataTypeId.data24, DataTypeId.data32, DataTypeId.data40, DataTypeId.data48, DataTypeId.data56, DataTypeId.data64, DataTypeId.octstr, DataTypeId.octstr16, DataTypeId.array, DataTypeId.struct, DataTypeId.set, DataTypeId.bag, DataTypeId.EUI64, DataTypeId.key128, }: return ParameterDataType.data return ParameterDataType.none ================================================================================ # FILE: majordom_zigbee/model.py ================================================================================ from enum import StrEnum from typing import Any from majordom_integration_sdk.schemas.base import Base from majordom_integration_sdk.schemas.device import Device, DeviceState, Parameter, ParameterState from pydantic import BaseModel class ZBParameterType(StrEnum): attribute = "attribute" command = "command" class ZBDeviceIntegrationData(Base): ieee: str | None = None class ZBParameterIntegrationData(BaseModel): endpoint_id: int cluster_id: int attribute_id: int | None = None command_id: int | None = None type: ZBParameterType # Args to send when this command is the device's one-tap main parameter and needs them (e.g. a # brightness level), keyed by field name; a Hub-sent `struct` value is keyed by sub-parameter id, # and send_command accepts both. This only carries *what to send*. send_command applies it when a # command arrives with no value (i.e. the user tapped the main parameter). Mirrors Matter's # default_arguments. default_arguments: dict[str, Any] | None = None class ZBDevice(Device[ZBDeviceIntegrationData]): pass class ZBParameter(Parameter[ZBParameterIntegrationData]): pass class ZBParameterState(ParameterState[ZBParameterIntegrationData]): pass class ZBDeviceState(ZBDevice, DeviceState[ZBDeviceIntegrationData, ZBParameterIntegrationData]): pass ================================================================================ # FILE: majordom_zigbee/radio.py ================================================================================ """Backend-agnostic zigpy radio selection. zigpy talks to the coordinator dongle through a per-silicon *radio library* (bellows for Silicon Labs EZSP, zigpy-znp for TI Z-Stack, zigpy-deconz for deCONZ, ...). This module maps every supported radio to its zigpy ``ControllerApplication``: the controller takes the one the dialect the hub bound (``ezsp``, ``znp``, …) names, and ``ZigpyDriver`` probes the installed libraries to tell which one a stick speaks. Swapping dongles therefore needs only the matching library installed, never a source change. Add support for a new radio by appending one ``Radio`` entry below, and its key to ``PROBED`` when a stick speaks it. """ from __future__ import annotations import importlib import logging from dataclasses import dataclass from typing import Any from majordom_integration_sdk import Endpoint, UsbDriver from zigpy.application import ControllerApplication from zigpy.config import CONF_DEVICE_BAUDRATE, CONF_DEVICE_PATH, SCHEMA_DEVICE log = logging.getLogger(__name__) @dataclass(frozen=True) class Radio: """One supported zigpy radio backend.""" key: str #: short id, also the dialect of the hub's ``zigbee`` link application: str #: dotted path to its zigpy ControllerApplication package: str #: the pip package (and extra) that provides it description: str #: human-readable hardware hint RADIOS: tuple[Radio, ...] = ( Radio( "ezsp", "bellows.zigbee.application.ControllerApplication", "bellows", "Silicon Labs EmberZNet via EZSP (SkyConnect, Sonoff ZBDongle-E, ...)", ), Radio( "znp", "zigpy_znp.zigbee.application.ControllerApplication", "zigpy-znp", "Texas Instruments Z-Stack via ZNP (CC2652, Sonoff ZBDongle-P, ...)", ), Radio( "deconz", "zigpy_deconz.zigbee.application.ControllerApplication", "zigpy-deconz", "dresden elektronik deCONZ (ConBee, RaspBee)", ), Radio( "xbee", "zigpy_xbee.zigbee.application.ControllerApplication", "zigpy-xbee", "Digi XBee", ), Radio( "zigate", "zigpy_zigate.zigbee.application.ControllerApplication", "zigpy-zigate", "ZiGate", ), Radio( "ziggurat", "zigpy_ziggurat.zigbee.application.ControllerApplication", "zigpy-ziggurat", "Ziggurat, the open-source host-side Zigbee stack, through its server", ), Radio( "blz", "zigpy_blz.zigbee.application.ControllerApplication", "zigpy-blz", "Bouffalo Lab BL70x via BLZ", ), ) #: Every dialect a zigpy radio library speaks: what the controller's ``zigbee`` need accepts. ZIGPY_DIALECTS: tuple[str, ...] = tuple(r.key for r in RADIOS) _BY_KEY: dict[str, Radio] = {r.key: r for r in RADIOS} #: What ``ZigpyDriver`` probes a stick for, in order: the quickest to tell first, ezsp last for the EFR32 sticks the #: SDK's Silabs driver didn't identify. Not ziggurat: it speaks through a server's WebSocket, never a stick. PROBED: tuple[Radio, ...] = tuple(_BY_KEY[key] for key in ("deconz", "zigate", "xbee", "blz", "znp", "ezsp")) def _load(radio: Radio) -> type[ControllerApplication] | None: """Import a radio's ControllerApplication, or None if its library isn't installed.""" module_path, _, cls_name = radio.application.rpartition(".") try: module = importlib.import_module(module_path) except ImportError: log.debug(f"zigbee radio {radio.key!r} unavailable ({radio.package} not installed)") return None return getattr(module, cls_name) async def detect(device_config: dict[str, Any]) -> tuple[Radio, dict[str, Any]] | None: """The first installed radio library that answers on ``device_config``, and the device config it answered at.""" for radio in PROBED: if (app := _load(radio)) is None: continue # zigpy 2 probes only _probe_configs: zigpy-deconz 0.25 and zigpy-blz 0.1 still list their bauds the zigpy 1 way for overrides in getattr(app, "_probe_config_variants", None) or [{}]: config = {**device_config, **overrides} try: # A non-matching radio typically raises (wrong protocol on the port) rather than # returning False — either way we move on to the next candidate. if found := await app.probe(config): return radio, SCHEMA_DEVICE(found if isinstance(found, dict) else config) except Exception as exc: # noqa: BLE001 — any probe failure just means "not this radio" log.debug(f"zigbee radio {radio.key!r} did not match: {exc}") return None def application_class(dialect: str) -> type[ControllerApplication]: """The zigpy ``ControllerApplication`` of the radio library speaking ``dialect``, which the need took.""" radio = _BY_KEY[dialect] if (app := _load(radio)) is None: raise RuntimeError( f"Zigbee radio {radio.key!r} needs {radio.package!r}: pip install 'majordom-zigbee[{radio.key}]'." ) return app class ZigpyDriver(UsbDriver): """The sticks only zigpy tells apart (ConBee, ZiGate, XBee, ...), for the runtime's USB scanner: the first installed radio library that answers on a stick names its firmware, which serves that dialect of ``zigbee``.""" name = "zigpy" firmwares = {radio.key: [Endpoint("zigbee", radio.key, "{device}")] for radio in PROBED} async def identify(self, path: str) -> tuple[str, dict[str, Any]] | None: if not (found := await detect({CONF_DEVICE_PATH: path})): return None radio, config = found return radio.key, {"baud": config[CONF_DEVICE_BAUDRATE]} ================================================================================ # FILE: majordom_zigbee/readme.md ================================================================================ # Zigbee integration Bridges the Hub to Zigbee devices through a USB coordinator radio, built on [`zigpy`](https://github.com/zigpy/zigpy) with the `bellows` (EmberZNet/Silabs) stack by default (`znp`/Texas Instruments is selectable via `_ZIGBEE_STACK`). zigpy owns the Zigbee network, the ZCL, and device interviews; this integration adapts it to the Hub's `AbstractController` contract. The radio's serial port comes from `dependencies.hardware_interfaces[0]` (overridable via the `ZIGBEE_DEVICE_PATH` env var); zigpy's device database lives under the integration's `documents_folder` as `zigbee.db`. ## Files | File | Responsibility | |---|---| | `controller.py` | `AbstractController` implementation — lifecycle, pairing, control, fetch, and the zigpy network-event listener | | `mapper.py` | Zigbee ↔ MajorDom conversions: UUIDs (via the framework helpers), IEEE address handling, ZCL data-type and access-permission mapping | | `model.py` | Typed `integration_data` schemas (`ZBDevice`, `ZBParameter`, …) | | `listener.py` | Per-cluster attribute-report listener that forwards live changes to the Hub | | `zigbee_spec.py` | Static spec metadata: system clusters, attribute units/steps, and the main-parameter map | ## Discovery & pairing Zigbee has no separate discovery step — a device is on the network the moment it joins. `start_pairing_window` opens permit-join; a joining device is held as a discovery and **disconnected from the network if it isn't paired within 5 minutes** (`_disconnect_unpaired_discovery`). Pairing takes no credentials (`CredentialsType.none`). At pairing, the device's endpoints/clusters are walked to build the parameter list (attributes and commands), and a main (one-tap) parameter is chosen per `MAIN_PARAMETER_BY_CLUSTER`. ## Availability The zigpy listener drives availability: `device_left` marks a paired device unavailable, and `device_initialized` on a rejoin marks it back online (both via `_set_availability`, which dedupes and emits the framework's connect/lose callbacks). On boot, devices missing from the network are marked unavailable. The pairing always stays in the DB so a device comes back on rejoin. ## Parameter identity Every parameter id is derived through the framework UUID helpers as `parameter_uuid(device_id, "_//")`, so the id a parameter gets at pairing is identical to the one used on fetch and in live reports. ## Tests - `test_zigbee_controller_mocked.py` — an in-memory zigpy stub, no radio or devices needed (runs in CI). - Real-device tests are kept in a private repository and run manually. ## Notes - ZCL reads are chunked (`_MAX_ATTRS_PER_REQUEST`) and paced (`_INTER_CHUNK_DELAY`) to avoid NCP ACK timeouts on busy serial links. ================================================================================ # FILE: majordom_zigbee/zigbee_spec.py ================================================================================ from typing import Any, NamedTuple from majordom_integration_sdk.schemas.parameter import ParameterRole, ParameterUnit, ParameterVisibility from .zigbee_spec_zha import ZHA_ATTRIBUTE_UX class MainParameterSpec(NamedTuple): """Value of MAIN_PARAMETER_BY_CLUSTER, keyed by cluster_id: what makes a sensible one-tap main_parameter for a device exposing that cluster. Iteration order is priority order — the first cluster below that a device exposes wins. - command main (default): ``target_id`` is a command id; ``default_arguments`` are sent with it (None = the command takes no arguments, e.g. OnOff.toggle). - attribute main (``is_attribute=True``): ``target_id`` is an attribute id; a tap writes it. For an enum attribute (e.g. FanControl.fan_mode) ``cycle`` is the value subset the tap rotates through (e.g. off/on for a toggle); it's stored on the parameter's ``default_value`` at pairing so the relay derives the next value. ``None`` -> cycle the param's full valid_values. """ target_id: int default_arguments: dict[str, Any] | None = None is_attribute: bool = False cycle: list[int] | None = None # Command/field names are from zigpy's cluster definitions. FanControl (0x0202) has no commands — # it's driven by the fan_mode attribute, so its one-tap is an ATTRIBUTE main that cycles off/on. MAIN_PARAMETER_BY_CLUSTER: dict[int, MainParameterSpec] = { 0x0006: MainParameterSpec(0x02, None), # OnOff.toggle 0x0008: MainParameterSpec( 0x04, {"level": 254, "transition_time": 0} ), # LevelControl.move_to_level_with_on_off (full) 0x0300: MainParameterSpec( 0x06, {"hue": 0, "saturation": 254, "transition_time": 0, "options_mask": 0, "options_override": 0} ), # Color.move_to_hue_and_saturation 0x0102: MainParameterSpec(0x05, {"percentage_lift_value": 100}), # WindowCovering.go_to_lift_percentage (open) 0x0101: MainParameterSpec(0x00, {"pin_code": None}), # DoorLock.lock_door # FanControl.fan_mode attribute — tap cycles Off(0) <-> On(4) (a toggle). 0x0202: MainParameterSpec(0x0000, is_attribute=True, cycle=[0x00, 0x04]), } SYSTEM_CLUSTERS: set[int] = { 0x0000, # Basic 0x0003, # Identify 0x0004, # Groups 0x0005, # Scenes 0x000A, # Time 0x000B, # RSSI 0x0019, # OTA 0x1000, # Touchlink } # --- Visibility curation (see docs/device-integration/parameter-ux recipe) ------------ # Zigbee attributes carry a Report flag, which is a decent "this is a live reading" signal, so the # controller keeps `reportable -> user` as a fallback. Curation refines it: # - EVERYDAY_CONTROL_ATTRIBUTES: writable everyday controls -> user (+ forced control role, since # zigpy sometimes under-declares access, e.g. FanControl.fan_mode has no flags at all) # - USER_READINGS: readings that must show even if a device doesn't mark them reportable -> user # - metadata (divisors/multipliers/bounds/tolerances, see is_metadata_attribute) -> system, even # if reportable, and reused as metadata sources (min/max/step) for the real parameters EVERYDAY_CONTROL_ATTRIBUTES: set[tuple[int, int]] = { (0x0202, 0x0000), # FanControl.fan_mode (zigpy declares no access flags — force it) (0x0201, 0x0011), # Thermostat.occupied_cooling_setpoint (the everyday "set the temp") (0x0201, 0x0012), # Thermostat.occupied_heating_setpoint (0x0201, 0x001C), # Thermostat.system_mode (off/heat/cool/auto) } USER_READINGS: set[tuple[int, int]] = { (0x0006, 0x0000), # OnOff.on_off (0x0008, 0x0000), # LevelControl.current_level (0x0201, 0x0000), # Thermostat.local_temperature (0x0402, 0x0000), # TemperatureMeasurement.measured_value (0x0405, 0x0000), # RelativeHumidity.measured_value (0x0400, 0x0000), # IlluminanceMeasurement.measured_value (0x0102, 0x0008), # WindowCovering.current_position_lift_percentage (0x0102, 0x0009), # WindowCovering.current_position_tilt_percentage (0x0001, 0x0021), # PowerConfiguration.battery_percentage_remaining (0x0500, 0x0002), # IasZone.zone_status (0x0101, 0x0000), # DoorLock.lock_state (0x0101, 0x0003), # DoorLock.door_state # Energy: the primary readings only (see CONFIG_HEAVY_CLUSTERS); the min/max/overload/phase-B/C # variants stay hidden. (0x0B04, 0x0304), # ElectricalMeasurement.ac_frequency (0x0B04, 0x0505), # ElectricalMeasurement.rms_voltage (0x0B04, 0x0508), # ElectricalMeasurement.rms_current (0x0B04, 0x050B), # ElectricalMeasurement.active_power (0x0B04, 0x0510), # ElectricalMeasurement.power_factor (0x0702, 0x0000), # Metering.current_summation_delivered (0x0702, 0x0400), # Metering.instantaneous_demand } # Per-attribute visibility overrides (win over everything). For the handful of readings that would # otherwise land in the wrong bucket via the reportable fallback. VISIBILITY_OVERRIDES: dict[tuple[int, int], ParameterVisibility] = { (0x0300, 0x0003): ParameterVisibility.system, # Color.current_x (CIE machine encoding — redundant with hue/sat) (0x0300, 0x0004): ParameterVisibility.system, # Color.current_y (0x0201, 0x0007): ParameterVisibility.setting, # Thermostat.pi_cooling_demand (diagnostic, not everyday) (0x0201, 0x0008): ParameterVisibility.setting, # Thermostat.pi_heating_demand } # Clusters where `reportable` is a poor "user reading" signal because most reportable attributes # are config/security/metadata: DoorLock (enable_* flags, event masks, credential counts) and the # electrical clusters (dozens of min/max/overload/phase-B/C variants). Only curated USER_READINGS/ # EVERYDAY reach `user`; the rest fall to setting/system. CONFIG_HEAVY_CLUSTERS: set[int] = {0x0101, 0x0B04, 0x0702} # DoorLock, ElectricalMeasurement, Metering # Commands that are everyday one-tap actions (-> user). Every other command on a non-system cluster # defaults to `setting` (advanced: schedule/credential/log management). ids from zigpy definitions. EVERYDAY_COMMANDS: set[tuple[int, int]] = { (0x0006, 0x00), (0x0006, 0x01), (0x0006, 0x02), # OnOff off / on / toggle (0x0008, 0x00), (0x0008, 0x04), # LevelControl move_to_level / _with_on_off (0x0300, 0x06), (0x0300, 0x0A), # Color move_to_hue_and_saturation / move_to_color_temp (0x0102, 0x00), (0x0102, 0x01), (0x0102, 0x02), (0x0102, 0x05), # WindowCovering up/down/stop/go_to_lift% (0x0101, 0x00), (0x0101, 0x01), # DoorLock lock_door / unlock_door (credential/schedule cmds stay setting) } # Attributes that are scaling constants / bounds / counts rather than user-facing readings. They # go to `system` and feed the metadata resolver. Curated set first; a conservative name heuristic # (below) catches the long tail (e.g. ElectricalMeasurement's ~18 *_divisor/*_multiplier attrs). METADATA_ATTRIBUTES: set[tuple[int, int]] = { (0x0400, 0x0001), # Illuminance.min_measured_value (0x0400, 0x0002), # Illuminance.max_measured_value (0x0402, 0x0001), # Temperature.min_measured_value (0x0402, 0x0002), # Temperature.max_measured_value (0x0405, 0x0001), # Humidity.min_measured_value (0x0405, 0x0002), # Humidity.max_measured_value } _METADATA_NAME_SUFFIXES: tuple[str, ...] = ("_divisor", "_multiplier") _METADATA_NAME_EXACT: frozenset[str] = frozenset( {"min_measured_value", "max_measured_value", "tolerance", "min_level", "max_level"} ) def is_metadata_attribute(cluster_id: int, attribute_id: int, name: str) -> bool: """Whether an attribute is a scaling constant / bound / count (metadata) rather than a user-facing reading — curated set first, conservative name heuristic as fallback.""" if (cluster_id, attribute_id) in METADATA_ATTRIBUTES: return True return name.endswith(_METADATA_NAME_SUFFIXES) or name in _METADATA_NAME_EXACT # --- The merged UX classification (priority ladder; see the zigbee README) -------------------- # Every source of a parameter's (visibility, role, unit) judgment funnels through classify_attribute. # role/unit of None mean "keep what the caller derived from zigpy" (access flags / get_unit()). class UxSpec(NamedTuple): visibility: ParameterVisibility role: ParameterRole | None = None unit: ParameterUnit | None = None # zha unit strings / device_classes -> our ParameterUnit. Shared by the runtime quirk-v2 reader # and mirrored (standalone) in scripts/harvest_zha.py. Unmapped -> None (keep get_unit()). _ZHA_UNIT_BY_STRING: dict[str, ParameterUnit] = { "°C": ParameterUnit.celsius, "%": ParameterUnit.percentage, "V": ParameterUnit.volt, "A": ParameterUnit.ampere, "W": ParameterUnit.watt, "Hz": ParameterUnit.hertz, "lx": ParameterUnit.lux, "kWh": ParameterUnit.kwh, "ppm": ParameterUnit.ppm, "µg/m³": ParameterUnit.ugm3, "Pa": ParameterUnit.pascal, "hPa": ParameterUnit.pascal, "kPa": ParameterUnit.pascal, "K": ParameterUnit.kelvin, "mired": ParameterUnit.mired, "m³/h": ParameterUnit.m3h, "s": ParameterUnit.second, } _ZHA_UNIT_BY_DEVICE_CLASS: dict[str, ParameterUnit] = { "temperature": ParameterUnit.celsius, "humidity": ParameterUnit.percentage, "battery": ParameterUnit.percentage, "illuminance": ParameterUnit.lux, "power": ParameterUnit.watt, "voltage": ParameterUnit.volt, "current": ParameterUnit.ampere, "energy": ParameterUnit.kwh, "pressure": ParameterUnit.pascal, "frequency": ParameterUnit.hertz, } def unit_from_zha(device_class: str | None, unit: str | None) -> ParameterUnit | None: """Translate a zha/HA unit string or device_class to our ParameterUnit, or None if unknown.""" if unit and unit in _ZHA_UNIT_BY_STRING: return _ZHA_UNIT_BY_STRING[unit] if device_class and device_class in _ZHA_UNIT_BY_DEVICE_CLASS: return _ZHA_UNIT_BY_DEVICE_CLASS[device_class] return None def _our_attribute_ux() -> dict[tuple[int, int], UxSpec]: """Our hand curation as UX overrides — the single highest static-priority source (a human's call wins over harvested/quirk judgment). Built from the curated sets so there's one source of truth per attribute.""" out: dict[tuple[int, int], UxSpec] = {} for key in USER_READINGS: out[key] = UxSpec(ParameterVisibility.user, ParameterRole.sensor) for key in EVERYDAY_CONTROL_ATTRIBUTES: out[key] = UxSpec(ParameterVisibility.user, ParameterRole.control) for key, vis in VISIBILITY_OVERRIDES.items(): out[key] = UxSpec(vis) return out OUR_ATTRIBUTE_UX: dict[tuple[int, int], UxSpec] = _our_attribute_ux() def _zha_uxspec(key: tuple[int, int]) -> UxSpec | None: t = ZHA_ATTRIBUTE_UX.get(key) if t is None: return None return UxSpec(ParameterVisibility(t[0]), ParameterRole(t[1]), ParameterUnit(t[2])) # Flip to True once harvested + quirk coverage is validated on real devices: unmatched attributes # then hide (system) instead of the reportable->user heuristic. See the zigbee README (fallback). _FALLBACK_HIDE_UNCURATED = False def classify_attribute( cluster_id: int, attribute_id: int, name: str, *, writable: bool, reportable: bool, quirk_ux: UxSpec | None = None, ) -> tuple[UxSpec, str]: """Resolve an attribute's (visibility, role, unit) by the priority ladder, returning the spec and a source tag (for logging / drift). Ladder, first match wins: 1. OUR_ATTRIBUTE_UX — hand curation, a human's call wins over everything 2. metadata / manufacturer-on-system-cluster — forced system (safety) 3. quirk_ux — v2 QuirkBuilder entity metadata (runtime, device-specific) 4. ZHA_ATTRIBUTE_UX — harvested standard-spec judgment 5. fallback policy — heuristic; WARNS (uncurated attribute) """ key = (cluster_id, attribute_id) if (spec := OUR_ATTRIBUTE_UX.get(key)) is not None: return spec, "ours" if is_metadata_attribute(cluster_id, attribute_id, name): return UxSpec(ParameterVisibility.system), "metadata" # Manufacturer-specific attrs (>= 0xF000) on infrastructure clusters stay hidden. if attribute_id >= 0xF000 and cluster_id in SYSTEM_CLUSTERS: return UxSpec(ParameterVisibility.system), "mfr-on-system-cluster" if quirk_ux is not None: return quirk_ux, "quirk-v2" if (spec := _zha_uxspec(key)) is not None: return spec, "zha" # 5. Fallback policy (uncurated) — WARNS. Kept as a heuristic until coverage is validated. if _FALLBACK_HIDE_UNCURATED or cluster_id in SYSTEM_CLUSTERS: return UxSpec(ParameterVisibility.system), "fallback-system" if reportable and cluster_id not in CONFIG_HEAVY_CLUSTERS: return UxSpec(ParameterVisibility.user), "fallback-reportable" if writable: return UxSpec(ParameterVisibility.setting), "fallback-writable" return UxSpec(ParameterVisibility.system), "fallback-system" class MetadataSource(NamedTuple): """Sibling attributes whose runtime VALUES provide a parameter's min/max — the device's own limit attributes (the ones we hide as metadata via ``is_metadata_attribute``). Priority 1 in the resolver: runtime sibling value > wire-type default. Mirrors Matter's ``MetadataSource``.""" min_attr: int | None = None max_attr: int | None = None # (cluster_id, attribute_id) of a shown parameter -> the sibling min/max limit attributes on the # same cluster whose runtime values bound it. The mirror of Matter's METADATA_SOURCES. METADATA_SOURCES: dict[tuple[int, int], MetadataSource] = { (0x0008, 0x0000): MetadataSource(0x0002, 0x0003), # LevelControl.current_level <- min/max_level (0x0400, 0x0000): MetadataSource(0x0001, 0x0002), # Illuminance.measured_value <- min/max_measured_value (0x0402, 0x0000): MetadataSource(0x0001, 0x0002), # Temperature.measured_value <- min/max_measured_value (0x0403, 0x0000): MetadataSource(0x0001, 0x0002), # Pressure.measured_value <- min/max_measured_value (0x0404, 0x0000): MetadataSource(0x0001, 0x0002), # Flow.measured_value <- min/max_measured_value (0x0405, 0x0000): MetadataSource(0x0001, 0x0002), # Humidity.measured_value <- min/max_measured_value # Thermostat setpoints bounded by the device's absolute-limit attributes. (0x0201, 0x0011): MetadataSource(0x0007, 0x0008), # occupied_cooling_setpoint <- abs_min/max_cool_setpoint_limit (0x0201, 0x0012): MetadataSource(0x0003, 0x0004), # occupied_heating_setpoint <- abs_min/max_heat_setpoint_limit } def resolve_metadata_bounds( cluster_id: int, attribute_id: int, get_value, default_min, default_max, ) -> tuple[Any, Any, list[int]]: """Metadata priority 1: override a parameter's min/max with the device's own limit attributes' runtime VALUES. ``get_value(attr_id)`` returns the cached sibling value (or None if the device doesn't report it). Returns ``(min, max, missing)`` where ``missing`` lists the expected source attribute ids that had no value — the caller warns so a quirk / omitted limit surfaces in logs.""" source = METADATA_SOURCES.get((cluster_id, attribute_id)) if source is None: return default_min, default_max, [] min_v, max_v = default_min, default_max missing: list[int] = [] for attr_id, is_min in ((source.min_attr, True), (source.max_attr, False)): if attr_id is None: continue resolved = get_value(attr_id) if resolved is not None: if is_min: min_v = resolved else: max_v = resolved else: missing.append(attr_id) return min_v, max_v, missing # (cluster_id, attribute_id) -> ParameterUnit ATTRIBUTE_UNITS: dict[tuple[int, int], ParameterUnit] = { # ------------------------- # General # ------------------------- # Level Control (0x0008) (0x0008, 0x0000): ParameterUnit.percentage, # current_level (0x0008, 0x0011): ParameterUnit.percentage, # on_level (0x0008, 0x0014): ParameterUnit.percentage, # default_move_rate (0x0008, 0x4000): ParameterUnit.percentage, # start_up_current_level # ------------------------- # Lighting (0x0300) # ------------------------- # Color Control (0x0300) (0x0300, 0x0001): ParameterUnit.percentage, # current_hue (0x0300, 0x0003): ParameterUnit.percentage, # current_saturation (0x0300, 0x0007): ParameterUnit.mired, # color_temperature_mireds (0x0300, 0x4010): ParameterUnit.plain, # color_temp_physical_min_mireds (0x0300, 0x4011): ParameterUnit.plain, # color_temp_physical_max_mireds (0x0300, 0x4012): ParameterUnit.plain, # couple_color_temp_to_level_min_mireds (0x0300, 0x4013): ParameterUnit.plain, # start_up_color_temperature # ------------------------- # Measurement & Sensing # ------------------------- # Illuminance Measurement (0x0400) (0x0400, 0x0000): ParameterUnit.lux, (0x0400, 0x0001): ParameterUnit.lux, (0x0400, 0x0002): ParameterUnit.lux, # Temperature Measurement (0x0402) (0x0402, 0x0000): ParameterUnit.celsius, (0x0402, 0x0001): ParameterUnit.celsius, (0x0402, 0x0002): ParameterUnit.celsius, (0x0402, 0x0010): ParameterUnit.celsius, # tolerance # Pressure Measurement (0x0403) (0x0403, 0x0000): ParameterUnit.pascal, # hPa — nearest in enum (0x0403, 0x0001): ParameterUnit.pascal, (0x0403, 0x0002): ParameterUnit.pascal, (0x0403, 0x0010): ParameterUnit.pascal, (0x0403, 0x0011): ParameterUnit.pascal, (0x0403, 0x0012): ParameterUnit.pascal, # Flow Measurement (0x0404) (0x0404, 0x0000): ParameterUnit.m3h, # flow, m³/h (0x0404, 0x0001): ParameterUnit.mps, (0x0404, 0x0002): ParameterUnit.mps, # Relative Humidity (0x0405) (0x0405, 0x0000): ParameterUnit.percentage, (0x0405, 0x0001): ParameterUnit.percentage, (0x0405, 0x0002): ParameterUnit.percentage, (0x0405, 0x0010): ParameterUnit.percentage, # Leaf Wetness (0x0407) (0x0407, 0x0000): ParameterUnit.percentage, (0x0407, 0x0001): ParameterUnit.percentage, (0x0407, 0x0002): ParameterUnit.percentage, # Soil Moisture (0x0408) (0x0408, 0x0000): ParameterUnit.percentage, (0x0408, 0x0001): ParameterUnit.percentage, (0x0408, 0x0002): ParameterUnit.percentage, # Wind Speed (0x040C) (0x040C, 0x0000): ParameterUnit.mps, (0x040C, 0x0001): ParameterUnit.mps, (0x040C, 0x0002): ParameterUnit.mps, # Carbon Monoxide (0x040A) (0x040A, 0x0000): ParameterUnit.ppm, (0x040A, 0x0001): ParameterUnit.ppm, (0x040A, 0x0002): ParameterUnit.ppm, # Carbon Dioxide / TVOC (0x040D) (0x040D, 0x0000): ParameterUnit.ppm, (0x040D, 0x0001): ParameterUnit.ppm, (0x040D, 0x0002): ParameterUnit.ppm, # PM2.5 (0x042A) (0x042A, 0x0000): ParameterUnit.ugm3, # PM2.5, µg/m³ (0x042A, 0x0001): ParameterUnit.ppm, (0x042A, 0x0002): ParameterUnit.ppm, # Electrical Conductivity (0x040B) (0x040B, 0x0000): ParameterUnit.plain, # µS/cm — not in enum # ------------------------- # HVAC # ------------------------- # Thermostat (0x0201) (0x0201, 0x0000): ParameterUnit.celsius, # local_temperature (0x0201, 0x0001): ParameterUnit.celsius, # outdoor_temperature (0x0201, 0x0003): ParameterUnit.celsius, # abs_min_heat_setpoint_limit (0x0201, 0x0004): ParameterUnit.celsius, # abs_max_heat_setpoint_limit (0x0201, 0x0005): ParameterUnit.celsius, # abs_min_cool_setpoint_limit (0x0201, 0x0006): ParameterUnit.celsius, # abs_max_cool_setpoint_limit (0x0201, 0x0007): ParameterUnit.percentage, # pi_cooling_demand (0x0201, 0x0008): ParameterUnit.percentage, # pi_heating_demand (0x0201, 0x0010): ParameterUnit.celsius, # local_temperature_calibration (0x0201, 0x0011): ParameterUnit.celsius, # occupied_cooling_setpoint (0x0201, 0x0012): ParameterUnit.celsius, # occupied_heating_setpoint (0x0201, 0x0013): ParameterUnit.celsius, # unoccupied_cooling_setpoint (0x0201, 0x0014): ParameterUnit.celsius, # unoccupied_heating_setpoint (0x0201, 0x0015): ParameterUnit.celsius, # min_heat_setpoint_limit (0x0201, 0x0016): ParameterUnit.celsius, # max_heat_setpoint_limit (0x0201, 0x0017): ParameterUnit.celsius, # min_cool_setpoint_limit (0x0201, 0x0018): ParameterUnit.celsius, # max_cool_setpoint_limit (0x0201, 0x0019): ParameterUnit.celsius, # min_setpoint_dead_band # ------------------------- # Electrical Measurement (0x0B04) # ------------------------- (0x0B04, 0x0304): ParameterUnit.hertz, # ac_frequency (0x0B04, 0x0305): ParameterUnit.hertz, # ac_frequency_min (0x0B04, 0x0306): ParameterUnit.hertz, # ac_frequency_max (0x0B04, 0x0505): ParameterUnit.volt, # rms_voltage (0x0B04, 0x0506): ParameterUnit.volt, # rms_voltage_min (0x0B04, 0x0507): ParameterUnit.volt, # rms_voltage_max (0x0B04, 0x0508): ParameterUnit.ampere, # rms_current (0x0B04, 0x0509): ParameterUnit.ampere, # rms_current_min (0x0B04, 0x050A): ParameterUnit.ampere, # rms_current_max (0x0B04, 0x050B): ParameterUnit.watt, # active_power (0x0B04, 0x050C): ParameterUnit.watt, # active_power_min (0x0B04, 0x050D): ParameterUnit.watt, # active_power_max (0x0B04, 0x050E): ParameterUnit.watt, # reactive_power (0x0B04, 0x050F): ParameterUnit.watt, # apparent_power (VA → watt approximation) (0x0B04, 0x0510): ParameterUnit.percentage, # power_factor (0x0B04, 0x0605): ParameterUnit.volt, # phase_b rms_voltage (0x0B04, 0x0608): ParameterUnit.ampere, # phase_b rms_current (0x0B04, 0x060B): ParameterUnit.watt, # phase_b active_power (0x0B04, 0x0705): ParameterUnit.volt, # phase_c rms_voltage (0x0B04, 0x0708): ParameterUnit.ampere, # phase_c rms_current (0x0B04, 0x070B): ParameterUnit.watt, # phase_c active_power # ------------------------- # Metering (0x0702) # ------------------------- (0x0702, 0x0000): ParameterUnit.kwh, # current_summation_delivered (0x0702, 0x0001): ParameterUnit.joule, # current_summation_received (0x0702, 0x0002): ParameterUnit.joule, # current_max_demand_delivered (0x0702, 0x0003): ParameterUnit.joule, # current_max_demand_received (0x0702, 0x0400): ParameterUnit.watt, # instantaneous_demand (0x0702, 0x0200): ParameterUnit.joule, # current_day_consumption_delivered (0x0702, 0x0201): ParameterUnit.joule, # previous_day_consumption_delivered # ------------------------- # Closures # ------------------------- # Window Covering (0x0102) (0x0102, 0x0008): ParameterUnit.percentage, # current_position_lift_percentage (0x0102, 0x0009): ParameterUnit.percentage, # current_position_tilt_percentage (0x0102, 0x000E): ParameterUnit.percentage, # current_position_lift_percent100ths (0x0102, 0x000F): ParameterUnit.percentage, # current_position_tilt_percent100ths # ------------------------- # Device Temperature (0x0002) # ------------------------- (0x0002, 0x0000): ParameterUnit.celsius, # current_temperature (0x0002, 0x0001): ParameterUnit.celsius, # min_temp_experienced (0x0002, 0x0002): ParameterUnit.celsius, # max_temp_experienced (0x0002, 0x0010): ParameterUnit.celsius, # low_temp_threshold (0x0002, 0x0011): ParameterUnit.celsius, # high_temp_threshold # ------------------------- # Power Configuration (0x0001) # ------------------------- (0x0001, 0x0000): ParameterUnit.volt, # mains_voltage (0x0001, 0x0001): ParameterUnit.hertz, # mains_frequency (0x0001, 0x0010): ParameterUnit.volt, # mains_voltage_min_threshold (0x0001, 0x0011): ParameterUnit.volt, # mains_voltage_max_threshold (0x0001, 0x0020): ParameterUnit.volt, # battery_voltage (0x0001, 0x0021): ParameterUnit.percentage, # battery_percentage_remaining } # (cluster_id, attribute_id) -> min_step ATTRIBUTE_MIN_STEP: dict[tuple[int, int], int | float] = { # Level Control (0x0008) (0x0008, 0x0000): 1, # current_level # Color Control (0x0300) (0x0300, 0x0001): 1, # current_hue (0x0300, 0x0003): 1, # current_saturation (0x0300, 0x0007): 1, # color_temperature_mireds # Thermostat (0x0201) (0x0201, 0x0010): 0.1, # local_temperature_calibration (0x0201, 0x0011): 0.5, # occupied_cooling_setpoint (0x0201, 0x0012): 0.5, # occupied_heating_setpoint (0x0201, 0x0013): 0.5, # unoccupied_cooling_setpoint (0x0201, 0x0014): 0.5, # unoccupied_heating_setpoint # Temperature Measurement (0x0402) (0x0402, 0x0000): 0.01, # resolution 0.01°C в ZCL # Relative Humidity (0x0405) (0x0405, 0x0000): 0.01, # resolution 0.01% # Pressure Measurement (0x0403) (0x0403, 0x0000): 0.1, # Window Covering (0x0102) (0x0102, 0x0008): 1, (0x0102, 0x0009): 1, # Electrical Measurement (0x0B04) (0x0B04, 0x0505): 0.1, # rms_voltage (0x0B04, 0x0508): 0.01, # rms_current (0x0B04, 0x050B): 0.1, # active_power # Metering (0x0702) (0x0702, 0x0000): 0.001, # kWh (0x0702, 0x0400): 1, # instantaneous_demand W } def get_unit(cluster_id: int, attribute_id: int) -> ParameterUnit: return ATTRIBUTE_UNITS.get((cluster_id, attribute_id), ParameterUnit.plain) def get_min_step(cluster_id: int, attribute_id: int) -> int | float | None: return ATTRIBUTE_MIN_STEP.get((cluster_id, attribute_id)) ================================================================================ # FILE: majordom_zigbee/zigbee_spec_zha.py ================================================================================ """GENERATED by scripts/harvest_zha.py — DO NOT EDIT BY HAND. Source: zha==2.0.1 (Apache-2.0). Harvested standard-cluster entity judgment (entity_category -> visibility, platform -> role, unit). Refresh by re-running the harvester; put hand overrides in zigbee_spec.py (OUR_ATTRIBUTE_UX), which win on merge. """ # (cluster_id, attribute_id) -> (visibility, role, unit) ZHA_ATTRIBUTE_UX: dict[tuple[int, int], tuple[str, str, str]] = { (0x0000, 0x0007): ("setting", "sensor", "plain"), (0x0001, 0x0021): ("setting", "sensor", "percentage"), (0x0002, 0x0000): ("setting", "sensor", "celsius"), (0x0006, 0x0000): ("user", "control", "plain"), (0x0006, 0x4003): ("setting", "control", "plain"), (0x0008, 0x0010): ("setting", "control", "plain"), (0x0008, 0x0011): ("setting", "control", "plain"), (0x0008, 0x0012): ("setting", "control", "plain"), (0x0008, 0x0013): ("setting", "control", "plain"), (0x0008, 0x0014): ("setting", "control", "plain"), (0x0008, 0x4000): ("setting", "control", "plain"), (0x000C, 0x0055): ("user", "sensor", "plain"), (0x000F, 0x0055): ("user", "sensor", "plain"), (0x0102, 0x0000): ("setting", "sensor", "plain"), (0x0102, 0x0007): ("setting", "control", "plain"), (0x0201, 0x0008): ("setting", "sensor", "percentage"), (0x0201, 0x0010): ("setting", "control", "celsius"), (0x0201, 0x0015): ("setting", "control", "celsius"), (0x0201, 0x0016): ("setting", "control", "celsius"), (0x0201, 0x0030): ("setting", "sensor", "plain"), (0x0201, 0x0032): ("setting", "sensor", "plain"), (0x0204, 0x0001): ("setting", "control", "plain"), (0x0300, 0x4010): ("setting", "control", "plain"), (0x0301, 0x0010): ("setting", "control", "plain"), (0x0301, 0x0011): ("setting", "control", "plain"), (0x0400, 0x0000): ("user", "sensor", "lux"), (0x0402, 0x0000): ("user", "sensor", "celsius"), (0x0403, 0x0000): ("user", "sensor", "pascal"), (0x0404, 0x0000): ("user", "sensor", "m3h"), (0x0405, 0x0000): ("user", "sensor", "percentage"), (0x0406, 0x0000): ("user", "sensor", "plain"), (0x0406, 0x0010): ("setting", "control", "second"), (0x0406, 0x0011): ("setting", "control", "second"), (0x0406, 0x0020): ("setting", "control", "plain"), (0x0406, 0x0022): ("setting", "control", "plain"), (0x0407, 0x0000): ("user", "sensor", "percentage"), (0x0408, 0x0000): ("user", "sensor", "percentage"), (0x040A, 0x0000): ("user", "sensor", "plain"), (0x040B, 0x0000): ("user", "sensor", "plain"), (0x040C, 0x0000): ("user", "sensor", "ppm"), (0x040D, 0x0000): ("user", "sensor", "ppm"), (0x042A, 0x0000): ("user", "sensor", "plain"), (0x042B, 0x0000): ("user", "sensor", "ppm"), (0x0500, 0x0002): ("user", "sensor", "plain"), (0x0702, 0x0000): ("user", "sensor", "plain"), (0x0702, 0x0001): ("user", "sensor", "plain"), (0x0702, 0x0100): ("user", "sensor", "plain"), (0x0702, 0x0102): ("user", "sensor", "plain"), (0x0702, 0x0104): ("user", "sensor", "plain"), (0x0702, 0x0106): ("user", "sensor", "plain"), (0x0702, 0x0108): ("user", "sensor", "plain"), (0x0702, 0x010A): ("user", "sensor", "plain"), (0x0702, 0x0400): ("user", "sensor", "plain"), (0x0B04, 0x0100): ("user", "sensor", "volt"), (0x0B04, 0x0103): ("user", "sensor", "ampere"), (0x0B04, 0x0106): ("user", "sensor", "watt"), (0x0B04, 0x0300): ("user", "sensor", "hertz"), (0x0B04, 0x0304): ("user", "sensor", "watt"), (0x0B04, 0x0505): ("user", "sensor", "volt"), (0x0B04, 0x0508): ("user", "sensor", "ampere"), (0x0B04, 0x050B): ("user", "sensor", "watt"), (0x0B04, 0x050F): ("user", "sensor", "plain"), (0x0B04, 0x0510): ("user", "sensor", "percentage"), (0x0B04, 0x0905): ("user", "sensor", "volt"), (0x0B04, 0x0908): ("user", "sensor", "ampere"), (0x0B04, 0x090B): ("user", "sensor", "watt"), (0x0B04, 0x0910): ("user", "sensor", "percentage"), (0x0B04, 0x0A05): ("user", "sensor", "volt"), (0x0B04, 0x0A08): ("user", "sensor", "ampere"), (0x0B04, 0x0A0B): ("user", "sensor", "watt"), (0x0B04, 0x0A10): ("user", "sensor", "percentage"), } ================================================================================ # FILE: pyproject.toml ================================================================================ [project] name = "majordom-zigbee" version = "0.1.8" description = "Zigbee integration for MajorDom — bridges Zigbee devices into the MajorDom language." authors = [ { name = "Parker Industries" }, { name = "Ehor Lukianov @Hexa-Hexagon", email = "85293779+Hexa-Hexagon@users.noreply.github.com" }, { name = "Mark Parker @MarkParker5", email = "34688010+MarkParker5@users.noreply.github.com" }, ] readme = "README.md" # AGPL-3.0 is required, not chosen: this package is effectively a wrapper around the GPL-3.0 # zigpy / zigpy-znp / bellows stack, so the combined work must carry a compatible copyleft # license. Commercial (non-AGPL) terms are available separately — see the partnership link. license = "AGPL-3.0-or-later" license-files = ["LICENSE"] keywords = ["majordom", "zigbee", "zigpy", "smart-home", "home-automation", "iot", "integration", "coordinator", "802-15-4"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Home Automation", "Programming Language :: Python :: 3", "Operating System :: POSIX :: Linux", ] requires-python = ">=3.13,<3.14" dependencies = [ "majordom-integration-sdk (>=0.4.0,<1.0)", "zigpy (>=2.0.0,<3.0.0)", "zigpy-znp (>=1.1.0,<2.0.0)", "bellows (>=0.49.2,<0.50.0)", # zha-quirks (zhaquirks) applies per-device quirks at the zigpy layer: it decodes # manufacturer clusters into named/typed attributes and carries v2 entity metadata. # Requires zigpy>=2.0, which is why the stack was bumped off the 0.88 line. "zha-quirks (>=2.2.1,<3.0.0)", ] [project.optional-dependencies] # Extra coordinator radios. bellows (Silicon Labs EZSP) and zigpy-znp (TI Z-Stack) ship by # default; install the extra matching your dongle to switch backends with no source change, e.g. # pip install 'majordom-zigbee[deconz]' # The dialect the hub binds the stick with picks the backend (see majordom_zigbee.radio). deconz = ["zigpy-deconz (>=0.25.5,<1.0.0)"] # dresden elektronik ConBee/RaspBee xbee = ["zigpy-xbee (>=0.21.1,<1.0.0)"] # Digi XBee zigate = ["zigpy-zigate (>=0.14.0,<1.0.0)"] # ZiGate ziggurat = ["zigpy-ziggurat (>=1.0.1,<2.0.0)"] # Ziggurat server blz = ["zigpy-blz (>=0.1.0,<1.0.0)"] # Bouffalo Lab BL70x all-radios = [ "zigpy-deconz (>=0.25.5,<1.0.0)", "zigpy-xbee (>=0.21.1,<1.0.0)", "zigpy-zigate (>=0.14.0,<1.0.0)", "zigpy-ziggurat (>=1.0.1,<2.0.0)", "zigpy-blz (>=0.1.0,<1.0.0)", ] [project.urls] Homepage = "https://majordom.io" Documentation = "https://docs.majordom.io/device-integration" Repository = "https://github.com/MajorDom-Systems/integration-zigbee" Issues = "https://github.com/MajorDom-Systems/integration-zigbee/issues" "Commercial licensing" = "https://parker-industries.org/partnership" "Parker Industries" = "https://parker-industries.org" [dependency-groups] dev = [ "poethepoet (>=0.49.0,<1.0.0)", "ty", "ruff", "pip-audit", "pytest", "pytest-asyncio", "pytest-cov", "pytest-timeout", "pytest-repeat", "pytest-benchmark", "pytest-profiling", "pytest-resource-usage", "coverage", "pympler", "psutil", "faker", ] [build-system] requires = ["poetry-core>=2.0.0,<3.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] requires-poetry = ">=2.0" packages = [{ include = "majordom_zigbee" }] [tool.pytest.ini_options] asyncio_mode = "auto" pythonpath = ["."] filterwarnings = ["once"] [tool.coverage.run] omit = ["tests/*"] [tool.ruff] line-length = 120 indent-width = 4 [tool.ruff.lint] select = ["E", "F", "UP", "B", "SIM", "I"] fixable = ["ALL"] [tool.ruff.format] quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "tests/*" = ["E402"] # The zigpy ControllerApplication test double intentionally uses loose signatures — scoped to # conftest.py (the only test file that needs it) so the rest of the suite stays fully checked. [[tool.ty.overrides]] include = ["tests/conftest.py"] [tool.ty.overrides.rules] invalid-method-override = "ignore" invalid-assignment = "ignore" invalid-argument-type = "ignore" [tool.poe.tasks.install] shell = """ poetry install echo '#!/bin/sh\npoetry run poe check' > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit echo "Pre-commit hook installed." """ [tool.poe.tasks.check] shell = """ code=0 echo "\nRunning ruff lint:" poetry run ruff check --fix || code=1 echo "\nRunning ruff format:" poetry run ruff format || code=1 echo "\nRunning ty:" poetry run ty check || code=1 echo "\nRunning pytest:" poetry run pytest --cov=majordom_zigbee --cov-report=xml || code=1 echo "\nRunning poetry build:" poetry build || code=1 echo "\nRunning poetry check:" poetry check || code=1 ${ci:+git diff --exit-code} || code=1 exit $code """ args = [{ name = "ci", type = "boolean" }] ================================================================================ # FILE: scripts/check_zha_drift.py ================================================================================ #!/usr/bin/env python3 """CI drift check for the vendored zha harvest — the Dependabot-style refresher. Re-harvests zha (must be installed in the CI/throwaway venv) and diffs the result against the committed ``zigbee_spec_zha.py``. Exit codes let CI decide what to do: 0 no drift 1 drift, low/medium risk only (ADD/REMOVE) -> open an auto-refresh PR 2 drift includes RECLASSIFY (HIGH risk) -> PR flagged for human review Run: python scripts/check_zha_drift.py """ from __future__ import annotations import sys from uuid import UUID from majordom_integration_sdk.spec_drift import diff_specs from zigpy.zcl import Cluster from majordom_zigbee.mapper import ZigBeeMapper from majordom_zigbee.zigbee_spec_zha import ZHA_ATTRIBUTE_UX as COMMITTED from scripts.harvest_zha import harvest # parse_zigbee_data_type doesn't touch the uuid generators — pass no-ops so the report classifies # data types with the exact same logic the runtime mapper uses. _NIL = UUID(int=0) _MAPPER = ZigBeeMapper(device_uuid=lambda _s: _NIL, parameter_uuid=lambda _d, _s: _NIL) def _mapped_data_type(attr: object) -> str: """MajorDom ``ParameterDataType`` for a zigpy attribute, via the runtime mapper. The unit in the harvested tuple is HA's semantic judgment; this is the orthogonal ZCL wire-type axis zigpy supplies. ``"unknown"`` when zigpy resolves the id but not a classifiable type.""" zcl_type = getattr(attr, "zcl_type", None) or getattr(attr, "type", None) if zcl_type is None: return "unknown" try: return _MAPPER.parse_zigbee_data_type(zcl_type).value except Exception: # noqa: BLE001 - a type lookup must never break the drift report return "unknown" def _key_label(key: tuple[int, int]) -> str: """Resolve a ``(cluster_id, attribute_id)`` key to ``cluster.attribute [data_type]`` via the zigpy ZCL registry, so the drift PR names what changed (``temperature.measured_value [integer]``) instead of only ``(1026, 0)``. Falls back to the hex id / ``unknown`` for anything zigpy can't classify.""" cid, aid = key cluster = Cluster._registry.get(cid) cluster_name = getattr(cluster, "ep_attribute", None) or getattr(cluster, "name", None) or f"0x{cid:04x}" attr = getattr(cluster, "attributes", {}).get(aid) if cluster is not None else None attr_name = getattr(attr, "name", None) or f"0x{aid:04x}" return f"{cluster_name}.{attr_name} [{_mapped_data_type(attr)}]" def main() -> int: current, _skipped = harvest() report = diff_specs(current, COMMITTED) print(report.render(source="zha", key_label=_key_label), file=sys.stderr) if report.is_empty: return 0 return 2 if report.has_high_risk else 1 if __name__ == "__main__": raise SystemExit(main()) ================================================================================ # FILE: scripts/harvest_zha.py ================================================================================ #!/usr/bin/env python3 """Harvest zha's standard-cluster entity judgment into ``majordom_zigbee/zigbee_spec_zha.py``. DEV / BUILD TOOL — run in a throwaway venv that has ``zha`` installed. ``zha`` is **not** a runtime dependency of this integration: we consume it here as a data source and vendor the result. See the parameter-ux recipe and the zigbee README's priority ladder. What it takes (the genuinely additive "judgment" that isn't in zigpy): per standard ``(cluster_id, attribute_id)``, zha's ``entity_category`` (→ our visibility), the entity platform (→ our role), and unit/device_class (→ our ParameterUnit). What it drops: names, types, valid_values, raw bounds — we already derive those from zigpy directly. Usage: python scripts/harvest_zha.py # writes the generated module python scripts/harvest_zha.py --stdout # print instead (for CI diffing) """ from __future__ import annotations import argparse import importlib import sys from collections import defaultdict from importlib.metadata import version import zigpy.zcl _ZHA_VERSION = version("zha") # Platform modules whose import fires the @register_entity side effects into ENTITY_REGISTRY. _PLATFORMS = ( "sensor", "binary_sensor", "switch", "number", "select", "climate", "lock", "cover", "fan", "light", "button", "siren", ) # zha unit strings / device_classes -> our ParameterUnit value. Anything unmapped -> "plain". _UNIT_BY_STRING = { "°C": "celsius", "%": "percentage", "V": "volt", "A": "ampere", "W": "watt", "Hz": "hertz", "lx": "lux", "kWh": "kwh", "ppm": "ppm", "µg/m³": "ugm3", "Pa": "pascal", "hPa": "pascal", "kPa": "pascal", "K": "kelvin", "mired": "mired", "m³/h": "m3h", "s": "second", } _UNIT_BY_DEVICE_CLASS = { "temperature": "celsius", "humidity": "percentage", "battery": "percentage", "illuminance": "lux", "power": "watt", "voltage": "volt", "current": "ampere", "energy": "kwh", "pressure": "pascal", "frequency": "hertz", } # Platforms that write the device (control) vs. read it (sensor). _CONTROL_PLATFORMS = {"switch", "number", "select", "climate", "lock", "cover", "fan", "light", "button", "siren"} def _unit_for(dc: str | None, unit: str | None) -> str: if unit and unit in _UNIT_BY_STRING: return _UNIT_BY_STRING[unit] if dc and dc in _UNIT_BY_DEVICE_CLASS: return _UNIT_BY_DEVICE_CLASS[dc] return "plain" def _enum_value(x: object) -> str | None: # HA enums carry str values; plain strings pass through unchanged. return str(getattr(x, "value", x)) if x is not None else None def harvest() -> tuple[dict[tuple[int, int], tuple[str, str, str]], list[str]]: for p in _PLATFORMS: importlib.import_module(f"zha.application.platforms.{p}") from zha.application.platforms import ENTITY_REGISTRY reg = zigpy.zcl.Cluster._registry # Collect every (visibility, role, unit) vote per key, then reduce with a fixed policy. votes: dict[tuple[int, int], list[tuple[str, str, str]]] = defaultdict(list) skipped: list[str] = [] for cluster_id, classes in ENTITY_REGISTRY.items(): cluster_cls = reg.get(cluster_id) for cls in classes: attr_name = getattr(cls, "_attribute_name", None) platform = cls.__module__.split(".")[-1] if attr_name is None: # Composite entities (light/climate/cover) map a whole cluster, not one attr. skipped.append(f"{cluster_id:#06x} {platform}:{cls.__name__} (no single attribute)") continue if cluster_cls is None or attr_name not in cluster_cls.attributes_by_name: skipped.append(f"{cluster_id:#06x} {platform}:{attr_name} (id unresolved)") continue attr_id = cluster_cls.attributes_by_name[attr_name].id ec = _enum_value(getattr(cls, "_attr_entity_category", None)) visibility = "user" if ec is None else "setting" # config/diagnostic -> settings tap role = "control" if platform in _CONTROL_PLATFORMS else "sensor" unit = _unit_for( _enum_value(getattr(cls, "_attr_device_class", None)), getattr(cls, "_attr_native_unit_of_measurement", None), ) votes[(cluster_id, attr_id)].append((visibility, role, unit)) # Reduce collisions (one cluster attr can back several entities across device types): # visibility: most-visible wins (user > setting) role: control > sensor # unit: first non-plain out: dict[tuple[int, int], tuple[str, str, str]] = {} for key, vs in votes.items(): visibility = "user" if any(v[0] == "user" for v in vs) else "setting" role = "control" if any(v[1] == "control" for v in vs) else "sensor" unit = next((v[2] for v in vs if v[2] != "plain"), "plain") out[key] = (visibility, role, unit) return out, skipped def render(data: dict[tuple[int, int], tuple[str, str, str]]) -> str: lines = [ '"""GENERATED by scripts/harvest_zha.py — DO NOT EDIT BY HAND.', "", f"Source: zha=={_ZHA_VERSION} (Apache-2.0). Harvested standard-cluster entity", "judgment (entity_category -> visibility, platform -> role, unit). Refresh by re-running", "the harvester; put hand overrides in zigbee_spec.py (OUR_ATTRIBUTE_UX), which win on merge.", '"""', "", "# (cluster_id, attribute_id) -> (visibility, role, unit)", "ZHA_ATTRIBUTE_UX: dict[tuple[int, int], tuple[str, str, str]] = {", ] for (cid, aid), (vis, role, unit) in sorted(data.items()): lines.append(f" ({cid:#06x}, {aid:#06x}): ({vis!r}, {role!r}, {unit!r}),") lines.append("}") return "\n".join(lines) + "\n" def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--stdout", action="store_true", help="print instead of writing the module") ap.add_argument("--out", default="majordom_zigbee/zigbee_spec_zha.py") args = ap.parse_args() data, skipped = harvest() text = render(data) if args.stdout: sys.stdout.write(text) else: with open(args.out, "w") as f: f.write(text) print(f"[harvest_zha] zha=={_ZHA_VERSION}: wrote {len(data)} entries -> {args.out}", file=sys.stderr) print(f"[harvest_zha] {len(skipped)} composite/unresolved entities skipped", file=sys.stderr) return 0 if __name__ == "__main__": raise SystemExit(main()) ================================================================================ # FILE: scripts/param_ux_audit.py ================================================================================ """Run majordom's zigbee visibility/role mapping across the ENTIRE ZCL surface (all zigpy clusters), replicating controller.py's parameter-build rules, and bucket the result the way the iOS app would show it: main / user / setting / system. Read-only static audit — no hardware.""" import importlib import inspect from zigpy.zcl import Cluster from zigpy.zcl.foundation import ZCLAttributeAccess from majordom_zigbee.zigbee_spec import ( CONFIG_HEAVY_CLUSTERS, EVERYDAY_COMMANDS, EVERYDAY_CONTROL_ATTRIBUTES, MAIN_PARAMETER_BY_CLUSTER, SYSTEM_CLUSTERS, USER_READINGS, VISIBILITY_OVERRIDES, is_metadata_attribute, ) MODULES = [ "general", "measurement", "lighting", "hvac", "closures", "homeautomation", "security", "smartenergy", "protocol", "lightlink", "manufacturer_specific", ] def clusters(): seen = {} for m in MODULES: try: mod = importlib.import_module(f"zigpy.zcl.clusters.{m}") except Exception: continue for _, obj in inspect.getmembers(mod, inspect.isclass): if issubclass(obj, Cluster) and obj is not Cluster and getattr(obj, "cluster_id", None) is not None: seen.setdefault(obj.cluster_id, obj) return dict(sorted(seen.items())) def attr_visibility(cluster_id, attr_id, access, name): # replicate controller.py curated visibility policy key = (cluster_id, attr_id) if key in VISIBILITY_OVERRIDES: return VISIBILITY_OVERRIDES[key].value vis = "system" if attr_id < 0xF000 or cluster_id not in SYSTEM_CLUSTERS: if is_metadata_attribute(cluster_id, attr_id, name): vis = "system" elif ( key in EVERYDAY_CONTROL_ATTRIBUTES or key in USER_READINGS or access & ZCLAttributeAccess.Report and cluster_id not in CONFIG_HEAVY_CLUSTERS ): vis = "user" elif access & ZCLAttributeAccess.Write: vis = "setting" return vis def attr_role(access): r = bool(access & ZCLAttributeAccess.Read) w = bool(access & ZCLAttributeAccess.Write) return "control" if (r and w) else "sensor" if r else "event" buckets_total = {"user": 0, "setting": 0, "system": 0} main_clusters = set(MAIN_PARAMETER_BY_CLUSTER) rows = [] for cid, cls in clusters().items(): is_sys = cid in SYSTEM_CLUSTERS b = {"user": [], "setting": [], "system": []} attrs = getattr(cls, "attributes", {}) or {} for aid, adef in attrs.items(): if not isinstance(aid, int): continue access = getattr(adef, "access", None) if access is None: continue vis = attr_visibility(cid, aid, access, getattr(adef, "name", str(aid))) b[vis].append(getattr(adef, "name", str(aid))) # client-side commands -> user (or system if system cluster) cmds = getattr(cls, "server_commands", {}) or {} # sendable actions, matching controller for k, c in cmds.items(): if not isinstance(k, int): continue cv = "system" if is_sys else ("user" if (cid, k) in EVERYDAY_COMMANDS else "setting") b[cv].append(f"{getattr(c, 'name', str(k))}()") for k in buckets_total: buckets_total[k] += len(b[k]) rows.append((cid, cls.__name__, is_sys, cid in main_clusters, b)) print(f"=== ZIGBEE full-ZCL mapping: {len(rows)} clusters ===") print( f"total params by bucket: user={buckets_total['user']} " f"setting={buckets_total['setting']} system={buckets_total['system']}" ) print(f"clusters providing a MAIN parameter: {sorted(hex(c) for c in main_clusters)}\n") # spotlight: common device-facing clusters + anomalies SPOT = { 0x0006: "OnOff", 0x0008: "LevelControl", 0x0300: "Color", 0x0201: "Thermostat", 0x0202: "FanControl", 0x0102: "WindowCovering", 0x0101: "DoorLock", 0x0402: "TempMeas", 0x0405: "Humidity", 0x0400: "Illuminance", 0x0000: "Basic(SYS)", 0x0001: "PowerConfig", 0x0B04: "ElectricalMeas", 0x0500: "IAS_Zone", } for cid, name, is_sys, has_main, b in rows: if cid in SPOT: print(f"--- 0x{cid:04X} {name}{' [SYSTEM]' if is_sys else ''}{' [MAIN]' if has_main else ''} ---") for k in ("user", "setting", "system"): if b[k]: print(f" {k:7}({len(b[k])}): {', '.join(b[k][:12])}{' …' if len(b[k]) > 12 else ''}") # anomaly scan: standard attributes on SYSTEM clusters that leaked to user/setting (the `or` bug) print("\n=== ANOMALY: user/setting params on SYSTEM clusters (should arguably be system) ===") for cid, name, is_sys, _has_main, b in rows: if is_sys and (b["user"] or b["setting"]): print(f" 0x{cid:04X} {name}: user={b['user'][:6]} setting={b['setting'][:6]}") ================================================================================ # FILE: tests/conftest.py ================================================================================ """Unit tests for the Zigbee controller. Drive `ZigBeeController` directly — via the SDK's test platform, against an in-memory zigpy stub (no radio, no DB). The Hub keeps the e2e (mocked-radio) coverage and the real-hardware tests. """ import asyncio from collections.abc import Callable from typing import Any from unittest.mock import AsyncMock, patch from uuid import UUID import pytest import pytest_asyncio import zigpy.application import zigpy.device import zigpy.endpoint import zigpy.profiles import zigpy.state as app_state import zigpy.types as t import zigpy.zdo.types as zdo_t from majordom_integration_sdk import Endpoint, Peripherals from majordom_integration_sdk.repository import DeviceRepositoryMemory from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from majordom_zigbee import ZigBeeController # IEEE 00:11:22:33:44:55:66:77 -> discovery_id 915c8f1c-444b-5659-a997-7d59b59527d3 MOCK_IEEE = t.EUI64.convert("00:11:22:33:44:55:66:77") MOCK_NWK = t.NWK(0x1234) NCP_IEEE = t.EUI64.convert("aa:11:22:bb:33:44:be:ef") EXTENDED_PAN_ID = "dd:dd:dd:dd:dd:dd:dd:dd" # of the network the radio runs, on channel 15 with PAN ID 0x1234 DEVICE_ID = "915c8f1c-444b-5659-a997-7d59b59527d3" PARAM_COMMAND_ID = "4142c1f6-8696-5acf-a547-e46daf222444" # toggle command_1/6/2 PARAM_ATTRIBUTE_ID = "ca4b246f-9f31-52ec-9628-1a6dbac4a989" # on_time attribute_1/6/16385 (Read|Write) MOCK_INPUT_CLUSTERS: list[int] = [6, 8] # OnOff, LevelControl; tests may monkeypatch it MOCK_OUTPUT_CLUSTERS: list[int] = [] # client-side clusters; tests may monkeypatch it RADIO = Endpoint("zigbee", "ezsp", "/dev/null") # pinned backend: no probing of /dev/null async def wait_for(predicate: Callable[[], bool], timeout: float = 3.0): async with asyncio.timeout(timeout): while not predicate(): await asyncio.sleep(0.02) def _make_mock_zb_device(app: zigpy.application.ControllerApplication) -> zigpy.device.Device: dev = app.add_device(nwk=MOCK_NWK, ieee=MOCK_IEEE) dev.node_desc = zdo_t.NodeDescriptor( logical_type=zdo_t.LogicalType.Router, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=zdo_t.NodeDescriptor.FrequencyBand.Freq2400MHz, mac_capability_flags=zdo_t.NodeDescriptor.MACCapabilityFlags.AllocateAddress, manufacturer_code=4174, maximum_buffer_size=82, maximum_incoming_transfer_size=82, server_mask=0, maximum_outgoing_transfer_size=82, descriptor_capability_field=zdo_t.NodeDescriptor.DescriptorCapability.NONE, ) ep = dev.add_endpoint(1) ep.status = zigpy.endpoint.Status.ZDO_INIT ep.profile_id = 260 ep.device_type = zigpy.profiles.zha.DeviceType.ON_OFF_LIGHT for cluster_id in MOCK_INPUT_CLUSTERS: ep.add_input_cluster(cluster_id) for cluster_id in MOCK_OUTPUT_CLUSTERS: ep.add_output_cluster(cluster_id) return dev class _MockZigpyApp(zigpy.application.ControllerApplication): """In-memory zigpy stub — no hardware, no DB.""" _zb_controller = None # set to the controller after start() given_config: dict[str, Any] | None = None # what the controller started it with async def send_packet(self, *_): pass async def connect(self, *_): pass async def disconnect(self, *_): pass async def start_network(self, *_): pass async def force_remove(self, *_): pass async def add_endpoint(self, *_): pass async def permit_ncp(self, *_): pass async def write_network_info(self, *_): pass async def reset_network_info(self, *_): pass async def permit_with_link_key(self, *_): pass async def startup(self, *, auto_form: bool = False): pass async def shutdown(self, *, db: bool = True): pass async def load_network_info(self, *, load_devices=False): self.state.network_info.channel = 15 async def permit(self, time_s=60, node=None): """Simulate a device joining — triggers device_joined + device_initialized.""" if self._zb_controller is None: return dev = _make_mock_zb_device(self) self._zb_controller.device_joined(dev) await asyncio.sleep(0.05) self._zb_controller.device_initialized(dev) async def remove(self, ieee): if self.get_device(ieee): del self.devices[ieee] @pytest.fixture def zigpy_apps(): """The in-memory zigpy stubs the controller starts, in order.""" created: list[_MockZigpyApp] = [] async def _new(config, **_): app = _MockZigpyApp({"database_path": None, "device": {"path": "/dev/null"}}) app.state.node_info = app_state.NodeInfo( nwk=t.NWK(0x0000), ieee=NCP_IEEE, logical_type=zdo_t.LogicalType.Coordinator ) app.state.network_info = app_state.NetworkInfo( channel=15, pan_id=t.PanId(0x1234), extended_pan_id=t.ExtendedPanId.convert(EXTENDED_PAN_ID) ) app.given_config = config created.append(app) return app with ( patch("bellows.zigbee.application.ControllerApplication.new", side_effect=_new), patch("zigpy.zcl.Cluster.read_attributes", new_callable=AsyncMock, return_value=({}, {})), patch("zigpy.zcl.Cluster.write_attributes", new_callable=AsyncMock, return_value=[{}, {}]), patch("zigpy.zcl.Cluster.command", new_callable=AsyncMock, return_value=None), ): yield created @pytest_asyncio.fixture async def zigbee(zigpy_apps): """Started ZigBeeController wired to an in-memory zigpy stub, plus the recording output and repository so tests can assert on both sides.""" store: dict[UUID, dict[str, Any]] = {} # what every integration's repository shares, each scoped to its own devices repository = DeviceRepositoryMemory(integration="zigbee", store=store) controller = ZigBeeController(build_test_platform(store=store)) controller.output = output = RecordingControllerOutput() controller.peripherals = Peripherals({"zigbee": RADIO}) await controller.start() zigpy_apps[0]._zb_controller = controller yield controller, output, repository, zigpy_apps[0] await controller.stop() ================================================================================ # FILE: tests/test_controller.py ================================================================================ """Unit tests driving ZigBeeController directly against the in-memory zigpy stub.""" import asyncio import threading import time from dataclasses import replace from typing import Any, cast from unittest.mock import AsyncMock, patch from uuid import UUID, uuid4 import conftest import pytest import pytest_asyncio import zhaquirks import zigpy.application import zigpy.device import zigpy.state as app_state import zigpy.types as t import zigpy.zcl import zigpy.zdo.types as zdo_t from conftest import DEVICE_ID, PARAM_ATTRIBUTE_ID, PARAM_COMMAND_ID, wait_for from majordom_integration_sdk import DeviceIdTakenError, Peripherals from majordom_integration_sdk.runtime import PeripheralState, Pinned, Runtime, StatusKind from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.parameter import Parameter, ParameterDataType from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from zigpy.config import CONF_DEVICE, CONF_DEVICE_BAUDRATE, CONF_DEVICE_FLOW_CONTROL, CONF_DEVICE_PATH from zigpy.zcl.clusters.closures import DoorLock, WindowCovering from zigpy.zcl.clusters.general import LevelControl, OnOff from zigpy.zcl.clusters.homeautomation import ElectricalMeasurement from zigpy.zcl.clusters.hvac import Fan from zigpy.zcl.clusters.lighting import Color from zigpy.zcl.clusters.smartenergy import Metering from zigpy.zcl.foundation import Status as ZCLStatus import majordom_zigbee from majordom_zigbee import ZigBeeController, ZigpyDriver from majordom_zigbee.exceptions import ZBConnectionError from majordom_zigbee.listener import ZBAttributeUpdatedListener from majordom_zigbee.model import ZBDevice, ZBDeviceIntegrationData, ZBDeviceState, ZBParameter from majordom_zigbee.zigbee_spec import MAIN_PARAMETER_BY_CLUSTER _NO_RADIO = patch("bellows.zigbee.application.ControllerApplication.new", side_effect=OSError("no radio")) async def test_discovers_joining_device(zigbee): controller, output, _repo, _app = zigbee await controller.start_pairing_window(5) # permit-join -> the stub simulates a device joining await wait_for(lambda: bool(output.received_discoveries)) discovery = output.received_discoveries[-1] assert str(discovery.id) == DEVICE_ID assert discovery.integration == "zigbee" assert UUID(DEVICE_ID) in controller.discoveries async def _discover(controller, output): await controller.start_pairing_window(5) await wait_for(lambda: bool(output.received_discoveries)) return output.received_discoveries[-1] def _draft(discovery, **fields) -> ZBDeviceState: """What the Hub hands pair_device: the user's form fields, the discovery id.""" return ZBDeviceState.model_validate( { "id": uuid4(), "physical_id": discovery.id, "name": "Mock Device", "room_id": UUID(int=1), "transport": discovery.transport, "integration": "zigbee", "manufacturer": None, "parameters": [], "integration_data": ZBDeviceIntegrationData(), **fields, } ) async def _pair_as_the_hub(controller, output, repository, discovery, draft=None) -> ZBDeviceState: """pair_device, then the Hub's part: save, tell the app the device is connected, fetch.""" device = await controller.pair_device(discovery, draft or _draft(discovery), None) async with repository.session() as repo: await repo.save(device) if device.available: await output.controller_did_connect_device(controller, physical_id=device.physical_id) await controller.fetch(device) return device async def test_pairs_a_joined_device(zigbee): controller, output, repository, _app = zigbee discovery = await _discover(controller, output) draft = _draft(discovery, description="kept?") device = await controller.pair_device(discovery, draft, None) assert device is draft # filled in place and returned assert discovery.id in controller.discoveries # until the Hub saves it assert discovery.id not in controller._connected_devices assert device.physical_id == discovery.id assert device.integration_data.ieee == controller._mapper.convert_eui64_to_str(conftest.MOCK_IEEE) assert device.available assert device.name == "Mock Device" and device.room_id == UUID(int=1) # the user's fields survive assert len(device.parameters) > 0 async def test_pairing_reports_nothing_about_the_device_and_leaves_the_repository_alone(zigbee): controller, output, repository, _app = zigbee discovery = await _discover(controller, output) await controller.pair_device(discovery, _draft(discovery), None) await asyncio.sleep(0.05) # a background fetch would have reported by now assert output.connected_devices == [] and output.events == [] async with repository.session() as repo: assert await repo.get(physical_id=discovery.id, as_=ZBDevice) is None async def test_pairing_a_picked_record_never_changes_its_id(zigbee): controller, output, _repo, _app = zigbee discovery = await _discover(controller, output) picked = _draft(discovery, id=UUID(int=42)) # the record the user picked device = await controller.pair_device(discovery, picked, None) assert device.id == UUID(int=42) assert device.physical_id == discovery.id assert str(device.physical_id) == DEVICE_ID async def test_a_taken_id_stops_pairing_before_the_device_is_touched(zigbee): controller, output, repository, _app = zigbee discovery = await _discover(controller, output) async with repository.session() as repo: await repo.save(_draft(discovery)) # another record holds the id other = _draft(discovery) with pytest.raises(DeviceIdTakenError): await controller.pair_device(discovery, other, None) assert discovery.id in controller.discoveries # still pairable assert discovery.id not in controller._connected_devices async def _pair(zigbee): controller, output, repository, app = zigbee discovery = await _discover(controller, output) await _pair_as_the_hub(controller, output, repository, discovery) return discovery async def _param(repository, device_id, parameter_id): from majordom_zigbee.model import ZBDeviceState, ZBParameter async with repository.session() as repo: state = await repo.state(physical_id=device_id, as_=ZBDeviceState) param = next(p for p in state.parameters if str(p.id) == parameter_id) return ZBParameter.model_validate(param.model_dump()) async def _device(repository, device_id): from majordom_zigbee.model import ZBDevice async with repository.session() as repo: return await repo.get(physical_id=device_id, as_=ZBDevice) async def test_sends_a_command_parameter(zigbee): from majordom_integration_sdk.schemas.command import DeviceCommand controller, output, repository, _app = zigbee discovery = await _pair(zigbee) device = await _device(repository, discovery.id) parameter = await _param(repository, discovery.id, PARAM_COMMAND_ID) # a ZCL command parameter (toggle) — no exception means the command reached the cluster await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=UUID(PARAM_COMMAND_ID), value=None), device, parameter ) async def test_sends_an_attribute_write(zigbee): from majordom_integration_sdk.schemas.command import DeviceCommand controller, output, repository, _app = zigbee discovery = await _pair(zigbee) device = await _device(repository, discovery.id) parameter = await _param(repository, discovery.id, PARAM_ATTRIBUTE_ID) await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=UUID(PARAM_ATTRIBUTE_ID), value=0), device, parameter ) async def test_unpairs_a_device(zigbee): controller, output, repository, app = zigbee discovery = await _pair(zigbee) device = await _device(repository, discovery.id) await controller.unpair(device) # the device is gone from the zigpy network from conftest import MOCK_IEEE assert MOCK_IEEE not in app.devices async def test_unpair_tolerates_a_record_without_its_node(zigbee): controller, output, _repo, app = zigbee discovery = await _discover(controller, output) await controller.unpair(_draft(discovery)) # no ieee assert conftest.MOCK_IEEE in app.devices async def test_a_pairing_that_failed_halfway_is_retried_from_the_same_discovery(zigbee, monkeypatch): controller, output, repository, app = zigbee discovery = await _discover(controller, output) async def fail(*_args, **_kwargs): raise RuntimeError("boom") with monkeypatch.context() as patched: patched.setattr(controller, "_subscribe", fail) with pytest.raises(RuntimeError): await controller.pair_device(discovery, draft := _draft(discovery), None) await controller.unpair(draft) # the Hub's rollback await controller.unpair(draft) # and again: nothing more assert conftest.MOCK_IEEE in app.devices # nothing undone: it stays joined assert controller.discoveries.keys() == {discovery.id} device = await _pair_as_the_hub(controller, output, repository, controller.discoveries[discovery.id]) assert device.parameters and discovery.id in controller._connected_devices assert controller.discoveries == {} async def test_a_pairing_the_hub_never_saved_is_retried_from_the_same_discovery(zigbee): controller, output, repository, app = zigbee discovery = await _discover(controller, output) await controller.unpair(await controller.pair_device(discovery, _draft(discovery), None)) # the Hub failed to save it, and rolled it back: the node stays joined device = await _pair_as_the_hub(controller, output, repository, controller.discoveries[discovery.id]) assert device.physical_id == discovery.id and discovery.id in controller._connected_devices assert controller.discoveries == {} and conftest.MOCK_IEEE in app.devices output.events.clear() _flip_the_switch(app) await asyncio.sleep(0.05) assert len(output.events) == 1 # subscribed once async def test_fetch_resubscribes_only_when_the_subscription_is_gone(zigbee, monkeypatch): controller, output, repository, app = zigbee discovery = await _pair(zigbee) device = await _device(repository, discovery.id) subscribe = AsyncMock(wraps=controller._subscribe) monkeypatch.setattr(controller, "_subscribe", subscribe) await controller.fetch(device) await controller.fetch(device) subscribe.assert_not_awaited() # nothing lost: no second subscription controller._subscriptions.pop(discovery.id) # as after a rebuilt device await controller.fetch(device) subscribe.assert_awaited_once() await controller.fetch(device) subscribe.assert_awaited_once() async def test_fetch_of_a_sleeping_device_is_not_a_failure(zigbee, monkeypatch): controller, output, repository, _app = zigbee discovery = await _pair(zigbee) device = await _device(repository, discovery.id) async def asleep(*_args, **_kwargs): raise TimeoutError monkeypatch.setattr(zigpy.zcl.Cluster, "read_attributes", asleep) output.events.clear() await controller.fetch(device) on_off = controller._mapper.attribute_parameter_uuid( discovery.id, 1, OnOff.cluster_id, OnOff.AttributeDefs.on_off.id ) assert on_off not in {event.parameter_id for event in output.events} # no None over the last known value async def _restart_with_the_device_last_seen(zigbee, monkeypatch, hours_ago: float | None, *, mains: bool = False): """Pairs the mock device, then starts Zigbee again on a network whose database says when it last heard from it.""" controller, output, _repo, _app = zigbee discovery = await _pair(zigbee) await wait_for(lambda: discovery.id in output.connected_devices) await controller.stop() # the Hub marks its devices unavailable output.connected_devices.clear() async def startup(app, *, auto_form: bool = False): # zigpy loads the network's devices from its database device = conftest._make_mock_zb_device(app) if mains and (node_desc := device.node_desc): node_desc.mac_capability_flags |= zdo_t.NodeDescriptor.MACCapabilityFlags.MainsPowered device.last_seen = None if hours_ago is None else time.time() - hours_ago * 60 * 60 monkeypatch.setattr(conftest._MockZigpyApp, "startup", startup) await controller.start() return discovery @pytest.mark.parametrize( ("mains", "hours_ago", "connected"), [(True, 1, True), (True, 3, False), (False, 5, True), (False, 7, False), (False, None, False)], ) async def test_a_start_reports_the_paired_devices_seen_lately_connected( zigbee, monkeypatch, mains, hours_ago, connected ): """Home Assistant's rule: seen within 2 h (mains) or 6 h (battery). One that left or died stays unavailable.""" _controller, output, _repo, _app = zigbee discovery = await _restart_with_the_device_last_seen(zigbee, monkeypatch, hours_ago, mains=mains) assert output.connected_devices == ([discovery.id] if connected else []) assert output.lost_devices == [] # the Hub holds them unavailable already async def test_any_message_from_a_device_seen_long_ago_brings_it_back(zigbee, monkeypatch): controller, output, _repo, _app = zigbee discovery = await _restart_with_the_device_last_seen(zigbee, monkeypatch, 7) assert output.connected_devices == [] app = controller._application app.listener_event("handle_message", app.get_device(conftest.MOCK_IEEE), 260, OnOff.cluster_id, 1, 1, b"") await wait_for(lambda: output.connected_devices == [discovery.id]) def _flip_the_switch(app: zigpy.application.ControllerApplication): on_off = app.get_device(conftest.MOCK_IEEE).endpoints[1].in_clusters[OnOff.cluster_id] on_off._update_attribute(OnOff.AttributeDefs.on_off.id, t.Bool.true) async def test_a_freshly_paired_devices_reports_reach_the_hub(zigbee): _controller, output, _repo, app = zigbee discovery = await _pair(zigbee) await wait_for(lambda: discovery.id in output.connected_devices) # the fetch after pairing went through output.events.clear() _flip_the_switch(app) await wait_for(lambda: bool(output.events)) assert [event.physical_id for event in output.events] == [discovery.id] async def test_a_report_reaches_the_hub_once_however_often_the_device_rejoined(zigbee): controller, output, _repo, app = zigbee discovery = await _pair(zigbee) await wait_for(lambda: discovery.id in output.connected_devices) for _ in range(3): # power cuts, a parent router rebooting: zigpy keeps a plain device's object controller.device_initialized(app.get_device(conftest.MOCK_IEEE)) await asyncio.sleep(0.05) output.events.clear() _flip_the_switch(app) await asyncio.sleep(0.05) assert len(output.events) == 1 async def test_a_discovery_is_paired_as_zigpy_last_built_it(zigbee): controller, output, repository, app = zigbee discovery = await _discover(controller, output) rebuilt = conftest._make_mock_zb_device(app) # interviewed again, and built anew (as with a quirk) controller.device_initialized(rebuilt) await _pair_as_the_hub(controller, output, repository, discovery) assert controller._connected_devices[discovery.id] is rebuilt async def test_the_unpaired_timer_removes_a_device_that_never_became_a_discovery(zigbee): controller, output, _repo, app = zigbee # its interview failed at start, or it joined twice within the timer app.remove = remove = AsyncMock() with patch("majordom_zigbee.controller.asyncio.sleep", AsyncMock()): await controller._disconnect_unpaired_discovery(UUID(DEVICE_ID), conftest.MOCK_IEEE) remove.assert_awaited_once_with(conftest.MOCK_IEEE) assert output.lost_discoveries == [] # the Hub never heard of it async def test_the_unpaired_timer_removes_a_discovery_and_tells_the_hub(zigbee): controller, output, _repo, app = zigbee discovery = await _discover(controller, output) with patch("majordom_zigbee.controller.asyncio.sleep", AsyncMock()): await controller._disconnect_unpaired_discovery(discovery.id, conftest.MOCK_IEEE) assert conftest.MOCK_IEEE not in app.devices assert discovery.id not in controller.discoveries assert output.lost_discoveries == [discovery.id] async def test_stop_ends_an_attribute_report_in_flight(zigbee): controller, output, _repo, app = zigbee cluster = conftest._make_mock_zb_device(app).endpoints[1].in_clusters[OnOff.cluster_id] async def busy(*_): # the Hub still taking it await asyncio.Event().wait() output.controller_did_receive_events = busy before = asyncio.all_tasks() ZBAttributeUpdatedListener(controller, UUID(DEVICE_ID), cluster).attribute_updated(0, True, None) (report,) = asyncio.all_tasks() - before await controller.stop() assert report.cancelled() def _move_ids(controller) -> tuple[str, list[str]]: """LevelControl.move's parameter id and its field (sub-parameter) ids on the mock device's endpoint 1.""" device_id = UUID(DEVICE_ID) mapper = controller._mapper move = LevelControl.ServerCommandDefs.move return str(mapper.command_parameter_uuid(device_id, 1, LevelControl.cluster_id, move.id)), [ str(mapper.command_field_uuid(device_id, 1, LevelControl.cluster_id, move.id, i)) for i in range(len(move.schema.fields)) ] async def test_command_with_arguments_is_a_struct(zigbee): controller, _output, repository, _app = zigbee discovery = await _pair(zigbee) param_id, field_ids = _move_ids(controller) parameter = await _param(repository, discovery.id, param_id) assert parameter.data_type is ParameterDataType.struct fields = {f["name"]: f for f in parameter.fields} assert [str(f["id"]) for f in parameter.fields] == field_ids assert list(fields) == ["move_mode", "rate", "options_mask", "options_override"] # keys are the values sent to the device, values are display labels move_mode = Parameter.model_validate(fields["move_mode"]) assert move_mode.valid_values == {member.value: member.name for member in LevelControl.MoveMode} async def test_argument_less_command_stays_none(zigbee): _controller, _output, repository, _app = zigbee discovery = await _pair(zigbee) parameter = await _param(repository, discovery.id, PARAM_COMMAND_ID) # OnOff.toggle assert parameter.data_type is ParameterDataType.none assert parameter.fields is None async def _send_move(zigbee, value_by_field: dict[str, Any]) -> Any: controller, _output, repository, _app = zigbee discovery = await _pair(zigbee) device = await _device(repository, discovery.id) move = LevelControl.ServerCommandDefs.move param_id, _ = _move_ids(controller) parameter = await _param(repository, discovery.id, param_id) command_mock = cast(AsyncMock, zigpy.zcl.Cluster.command) command_mock.reset_mock() await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=UUID(param_id), value=value_by_field), device, parameter ) command_mock.assert_awaited_once() call = command_mock.await_args assert call is not None and call.args == (move.id,) # zigpy must accept the arguments as-is (it builds the wire struct from these kwargs) return move.schema(**call.kwargs) async def test_struct_command_value_keyed_by_field_id_reaches_device(zigbee): controller, *_ = zigbee _, (move_mode, rate, options_mask, options_override) = _move_ids(controller) down = LevelControl.MoveMode.Down.value sent = await _send_move(zigbee, {move_mode: down, rate: 5, options_mask: 0, options_override: 0}) assert sent.move_mode is LevelControl.MoveMode.Down assert sent.rate == 5 async def test_struct_command_value_keyed_by_field_name_still_works(zigbee): sent = await _send_move(zigbee, {"move_mode": 0, "rate": 7, "options_mask": 0, "options_override": 0}) assert sent.move_mode is LevelControl.MoveMode.Up assert sent.rate == 7 @pytest.mark.parametrize( ("cluster", "command_id"), [(LevelControl, 0x04), (Color, 0x06), (WindowCovering, 0x05), (DoorLock, 0x00)], ids=lambda v: v.__name__ if isinstance(v, type) else str(v), ) async def test_main_command_with_arguments_is_a_struct_button(zigbee, monkeypatch, cluster, command_id): monkeypatch.setattr(conftest, "MOCK_INPUT_CLUSTERS", [cluster.cluster_id]) controller, _output, repository, _app = zigbee discovery = await _pair(zigbee) device = await _device(repository, discovery.id) zbcommand = cluster.server_commands[command_id] mapper = controller._mapper param_id = str(mapper.command_parameter_uuid(discovery.id, 1, cluster.cluster_id, command_id)) names = { str(mapper.command_field_uuid(discovery.id, 1, cluster.cluster_id, command_id, i)): field.name for i, field in enumerate(zbcommand.schema.fields) } expected = MAIN_PARAMETER_BY_CLUSTER[cluster.cluster_id].default_arguments assert str(device.main_parameter) == param_id stored = await _param(repository, discovery.id, param_id) main = ZBParameter.model_validate(stored.model_dump(mode="json")) # the stored round trip assert main.data_type is ParameterDataType.struct assert main.can_be_main_parameter # a single dict default_value is a one-value button keyed by sub-parameter id assert isinstance(main.default_value, dict) assert {names[key]: value for key, value in main.default_value.items()} == expected cycle = main.main_cycle assert cycle is not None and len(cycle) == 1 command_mock = cast(AsyncMock, zigpy.zcl.Cluster.command) command_mock.reset_mock() await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=UUID(param_id), value=cycle[0]), device, main ) call = command_mock.await_args assert call is not None and call.args == (command_id,) and call.kwargs == expected zbcommand.schema(**call.kwargs) async def test_attribute_enum_valid_values_map_value_to_label(zigbee, monkeypatch): monkeypatch.setattr(conftest, "MOCK_INPUT_CLUSTERS", [Fan.cluster_id]) controller, _output, repository, _app = zigbee discovery = await _pair(zigbee) device = await _device(repository, discovery.id) fan_mode_id = Fan.AttributeDefs.fan_mode.id param_id = str(controller._mapper.attribute_parameter_uuid(discovery.id, 1, Fan.cluster_id, fan_mode_id)) stored = await _param(repository, discovery.id, param_id) fan_mode = ZBParameter.model_validate(stored.model_dump(mode="json")) # the stored round trip valid_values = fan_mode.valid_values assert valid_values is not None assert valid_values == {member.value: member.name for member in Fan.FanMode} # a reported value and the main off/on cycle both land on valid_values keys assert controller._mapper.normalize_zigbee_value(Fan.FanMode.On) in valid_values assert str(device.main_parameter) == param_id assert fan_mode.main_cycle == [Fan.FanMode.Off.value, Fan.FanMode.On.value] assert set(fan_mode.main_cycle or ()) <= set(valid_values) write_mock = cast(AsyncMock, zigpy.zcl.Cluster.write_attributes) write_mock.reset_mock() await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=UUID(param_id), value=Fan.FanMode.On.value), device, fan_mode, ) write_mock.assert_awaited_once_with({fan_mode_id: Fan.FanMode.On.value}) # Tuya TS0001 dry-contact relay: the simple descriptor lists Metering and ElectricalMeasurement, # but the firmware implements neither. Metering answers UNSUPPORTED_ATTRIBUTE per attribute, while # ElectricalMeasurement is rejected as a whole cluster (a Default Response with UNSUPPORTED_CLUSTER). _TS0001_INPUT_CLUSTERS = [0x0000, 0x0003, 0x0004, 0x0005, OnOff.cluster_id, Metering.cluster_id] _TS0001_INPUT_CLUSTERS += [ElectricalMeasurement.cluster_id, 0xE000, 0xE001] _TS0001_OUTPUT_CLUSTERS = [0x000A, 0x0019] # Time, Ota (client side) _TS0001_UNSUPPORTED_STATUS = { Metering.cluster_id: ZCLStatus.UNSUPPORTED_ATTRIBUTE, ElectricalMeasurement.cluster_id: ZCLStatus.UNSUPPORTED_CLUSTER, } async def _ts0001_read_attributes(cluster: zigpy.zcl.Cluster, attributes: list[int], **_kwargs): if (status := _TS0001_UNSUPPORTED_STATUS.get(cluster.cluster_id)) is not None: return {}, dict.fromkeys(attributes, status) return {}, {} async def test_ts0001_exposes_only_supported_clusters(zigbee, monkeypatch): monkeypatch.setattr(conftest, "MOCK_INPUT_CLUSTERS", _TS0001_INPUT_CLUSTERS) monkeypatch.setattr(conftest, "MOCK_OUTPUT_CLUSTERS", _TS0001_OUTPUT_CLUSTERS) controller, output, repository, _app = zigbee with patch.object(zigpy.zcl.Cluster, "read_attributes", new=_ts0001_read_attributes): discovery = await _pair(zigbee) await wait_for(lambda: bool(output.events)) # the background fetch after pairing device = await _device(repository, discovery.id) async with repository.session() as repo: parameters = (await repo.state(physical_id=discovery.id, as_=ZBDeviceState)).parameters clusters = {p.integration_data.cluster_id for p in parameters} # unimplemented clusters expose nothing, client-side (output) clusters have no attributes to read, # and the attribute-less Tuya clusters 0xE000/0xE001 (no quirk applied here) add nothing either assert clusters == {0x0000, 0x0003, 0x0004, 0x0005, OnOff.cluster_id} # fetch reports values only for the parameters pairing exposed assert {e.parameter_id for e in output.events} <= {p.id for p in parameters} # the relay itself stays exposed and controllable mapper = controller._mapper on_off_id = str(mapper.attribute_parameter_uuid(discovery.id, 1, OnOff.cluster_id, OnOff.AttributeDefs.on_off.id)) toggle_id = str(mapper.command_parameter_uuid(discovery.id, 1, OnOff.cluster_id, OnOff.ServerCommandDefs.toggle.id)) assert {on_off_id, toggle_id} <= {str(p.id) for p in parameters} toggle = await _param(repository, discovery.id, toggle_id) await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=UUID(toggle_id), value=None), device, toggle ) async def test_an_unanswered_optional_cluster_read_is_a_warning_not_an_error(zigbee, monkeypatch, caplog): monkeypatch.setattr(conftest, "MOCK_INPUT_CLUSTERS", _TS0001_INPUT_CLUSTERS) monkeypatch.setattr(conftest, "MOCK_OUTPUT_CLUSTERS", _TS0001_OUTPUT_CLUSTERS) _controller, output, _repository, _app = zigbee metering_reads = 0 async def read_attributes(cluster: zigpy.zcl.Cluster, attributes: list[int], **kwargs): nonlocal metering_reads if cluster.cluster_id == Metering.cluster_id: metering_reads += 1 raise TimeoutError # the relay never answers Metering return await _ts0001_read_attributes(cluster, attributes, **kwargs) with patch.object(zigpy.zcl.Cluster, "read_attributes", new=read_attributes), caplog.at_level("DEBUG"): caplog.clear() await _pair(zigbee) await wait_for(lambda: bool(output.events)) timeouts = [r for r in caplog.records if "read_attributes" in r.getMessage() and "Metering" in r.getMessage()] assert timeouts and all(r.levelname == "WARNING" for r in timeouts) assert metering_reads == 2 # one request each for pairing and the fetch, not one per chunk async def test_a_failed_background_task_is_logged_not_left_unretrieved(zigbee, caplog): controller, _output, _repository, _app = zigbee async def fail(): raise RuntimeError("boom") task = controller._create_task(fail()) await asyncio.gather(task, return_exceptions=True) await asyncio.sleep(0) assert task._log_traceback is False # retrieved: asyncio won't log "Task exception was never retrieved" assert any("boom" in r.getMessage() and r.levelname == "ERROR" for r in caplog.records) @pytest_asyncio.fixture async def running(zigpy_apps, tmp_path, monkeypatch): """Zigbee run by the runtime on a pinned radio, which it reopens without waiting.""" monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (0, 0, 0)) controller, pinned = ZigBeeController(build_test_platform()), Pinned(conftest.RADIO) output = RecordingControllerOutput() runtime = Runtime(tmp_path, [pinned, controller], platform=controller.platform, controller_output=output) await runtime.start() await wait_for(lambda: runtime.status(controller).state == PeripheralState.RUNNING) yield controller, runtime, pinned, output await runtime.stop() async def test_a_lost_radio_is_reopened_in_place(running, zigpy_apps): controller, runtime, _pinned, output = running controller.connection_lost(ConnectionResetError("the service in front of it restarted")) await wait_for(lambda: len(zigpy_apps) == 2 and controller._application is zigpy_apps[1]) assert runtime.status(controller).state == PeripheralState.RUNNING assert not output.error_log await wait_for(lambda: controller._reconnecting is None) async def test_a_call_while_the_radio_reconnects_says_so(zigbee, monkeypatch): controller, _output, _repo, _app = zigbee monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (10,)) controller.connection_lost(ConnectionResetError("the service in front of it restarted")) await wait_for(lambda: controller._application is None) with pytest.raises(ZBConnectionError, match="The Zigbee radio is reconnecting"): await controller.start_pairing_window(60) async def test_a_lost_radios_devices_are_unavailable_until_it_is_reopened(zigbee, monkeypatch): controller, output, _repo, _app = zigbee monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (0,)) discovery = await _pair(zigbee) await wait_for(lambda: discovery.id in output.connected_devices) output.connected_devices.clear() is_back = asyncio.Event() async def startup(app, *, auto_form: bool = False): # the radio answers again, and its devices with it await is_back.wait() conftest._make_mock_zb_device(app).last_seen = time.time() monkeypatch.setattr(conftest._MockZigpyApp, "startup", startup) controller.connection_lost(ConnectionResetError("the service in front of it restarted")) await wait_for(lambda: output.lost_devices == [discovery.id]) assert output.connected_devices == [] is_back.set() await wait_for(lambda: output.connected_devices == [discovery.id]) async def test_a_radio_that_drops_soon_after_each_reopen_fails_zigbee(zigbee, zigpy_apps, monkeypatch): controller, output, _repo, _app = zigbee monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (0, 0)) for opened in (2, 3): # a flaky hub or cable: the radio answers, then drops again a moment later controller.connection_lost(ConnectionResetError("dropped")) await wait_for(lambda opened=opened: len(zigpy_apps) == opened and controller._application is zigpy_apps[-1]) assert not output.error_log controller.connection_lost(ConnectionResetError("dropped")) await wait_for(lambda: bool(output.error_log)) assert [error.is_still_running for error in output.errors.values()] == [False] assert len(zigpy_apps) == 3 async def test_a_radio_that_held_after_its_reopen_has_every_try_again(zigbee, zigpy_apps, monkeypatch): controller, output, _repo, _app = zigbee monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (0,)) monkeypatch.setattr(ZigBeeController, "STABLE_RUN", 0) # each reopen held long enough for opened in (2, 3, 4): controller.connection_lost(ConnectionResetError("dropped")) await wait_for(lambda opened=opened: len(zigpy_apps) == opened and controller._application is zigpy_apps[-1]) assert not output.error_log async def test_a_radio_that_stays_lost_fails_zigbee(running): controller, runtime, _pinned, output = running with _NO_RADIO as new: controller.connection_lost(ConnectionResetError("gone")) await wait_for(lambda: runtime.status(controller).kind == StatusKind.RETRYING) assert runtime.status(controller).detail.startswith("Lost the connection to the Zigbee radio.") assert new.await_count == len(ZigBeeController.RECONNECT_DELAYS) assert [error.is_still_running for error in output.errors.values()] == [False] async def test_an_unplugged_radio_only_parks_zigbee(running, monkeypatch): controller, runtime, pinned, output = running monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (1,)) with _NO_RADIO: controller.connection_lost(ConnectionResetError("unplugged")) # zigpy at once, the USB scanner a poll later await pinned.unpin("zigbee") await wait_for(lambda: runtime.status(controller).kind == StatusKind.NEEDS_UNBOUND) await asyncio.sleep(0.1) assert not output.error_log await pinned.pin(conftest.RADIO) await wait_for(lambda: runtime.status(controller).state == PeripheralState.RUNNING) async def test_a_radio_lost_while_zigbee_starts_is_reopened_once_it_started(zigpy_apps, monkeypatch): async def startup(app, *, auto_form: bool = False): conftest._make_mock_zb_device(app) # a device the Hub doesn't know: the start interviews it async def initialize(zbdevice): # the radio goes while the start goes through the network's devices if len(zigpy_apps) == 1: zbdevice.application.connection_lost(ConnectionResetError("lost")) await asyncio.sleep(0.05) monkeypatch.setattr(conftest._MockZigpyApp, "startup", startup) monkeypatch.setattr(zigpy.device.Device, "initialize", initialize) controller = ZigBeeController(build_test_platform()) controller.output = output = RecordingControllerOutput() controller.peripherals = Peripherals({"zigbee": conftest.RADIO}) await controller.start() try: assert controller._application is zigpy_apps[0] # the start went on with it await wait_for(lambda: len(zigpy_apps) == 2 and controller._application is zigpy_apps[1]) assert not output.error_log finally: await controller.stop() async def test_a_radio_lost_again_while_it_reopens_is_reopened_afresh(zigbee, zigpy_apps, monkeypatch): controller, output, _repo, _app = zigbee monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (0, 0)) async def startup(app, *, auto_form: bool = False): if len(zigpy_apps) == 2: # the first reopen never gets through await asyncio.Event().wait() monkeypatch.setattr(conftest._MockZigpyApp, "startup", startup) controller.connection_lost(ConnectionResetError("lost")) await wait_for(lambda: len(zigpy_apps) == 2) reopening = controller._reconnecting controller.connection_lost(ConnectionResetError("lost again")) await wait_for(lambda: len(zigpy_apps) == 3 and controller._application is zigpy_apps[2]) assert reopening is not None and reopening.cancelled() assert not output.error_log async def test_a_radio_lost_while_zigbee_stops_isnt_reopened(zigbee, zigpy_apps, monkeypatch): controller, _output, _repo, app = zigbee monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (0,)) async def interview(): # cut short by the stop, as the radio goes try: await asyncio.Event().wait() finally: app.connection_lost(ConnectionResetError("lost while stopping")) controller._create_task(interview()) await asyncio.sleep(0) await controller.stop() await asyncio.sleep(0.05) assert controller._application is None assert len(zigpy_apps) == 1 async def test_stopping_is_not_reported_as_a_lost_radio(zigbee): controller, output, _repo, app = zigbee async def shutdown(*_, **__): # as with bellows: closing the radio reports the connection lost app.connection_lost(ConnectionResetError("closed")) app.shutdown = shutdown await controller.stop() await asyncio.sleep(0.05) assert not output.errors assert controller._reconnecting is None async def test_a_stop_cut_short_while_closing_the_radio_lets_go_of_it(zigbee): controller, output, _repo, app = zigbee await _discover(controller, output) async def shutdown(**_): # a vanished radio's I/O never returns await asyncio.Event().wait() app.shutdown = shutdown with pytest.raises(TimeoutError): async with asyncio.timeout(0.1): # as the runtime abandons a stop after its STOP_TIMEOUT await controller.stop() del app.shutdown # the fixture's own stop() returns assert controller._application is None assert not controller.discoveries async def test_a_start_that_cant_open_the_radio_stops_cleanly(): controller = ZigBeeController(build_test_platform()) controller.peripherals = Peripherals({"zigbee": conftest.RADIO}) with _NO_RADIO, pytest.raises(OSError): await controller.start() await controller.stop() # as the runtime does after a failed start async def test_a_restart_that_cant_open_the_radio_leaves_the_last_one_closed(zigbee): controller, _output, _repo, app = zigbee await controller.stop() app.shutdown = shutdown = AsyncMock() with _NO_RADIO, pytest.raises(OSError): await controller.start() await controller.stop() shutdown.assert_not_awaited() @pytest.mark.parametrize( ("params", "device"), [ ({}, {}), ({"baud": 460800, "flow_control": True}, {CONF_DEVICE_BAUDRATE: 460800, CONF_DEVICE_FLOW_CONTROL: "hardware"}), ({"baud": 38400, "flow_control": False}, {CONF_DEVICE_BAUDRATE: 38400, CONF_DEVICE_FLOW_CONTROL: None}), ], ) async def test_the_radio_opens_with_its_endpoints_serial_settings(zigpy_apps, params, device): controller = ZigBeeController(build_test_platform()) controller.peripherals = Peripherals({"zigbee": replace(conftest.RADIO, params=params)}) await controller.start() try: (app,) = zigpy_apps assert app.given_config and app.given_config[CONF_DEVICE] == {CONF_DEVICE_PATH: conftest.RADIO.url, **device} finally: await controller.stop() class _Radio(conftest._MockZigpyApp): """A radio started by zigpy's own new() and startup(), with its database: it refuses to connect, or hangs while zigpy starts the network.""" startup = zigpy.application.ControllerApplication.startup shutdown = zigpy.application.ControllerApplication.shutdown hangs = False is_connected = False async def connect(self, *_): if not self.hangs: raise OSError("radio refused") self.is_connected = True async def disconnect(self, *_): self.is_connected = False async def load_network_info(self, *, load_devices=False): await asyncio.Event().wait() @pytest.fixture async def radios(): """The radios the controller opens, in order; any left open is closed after the test.""" opened: list[_Radio] = [] class Radio(_Radio): def __init__(self, config: dict[str, Any]): super().__init__(config) opened.append(self) with patch("majordom_zigbee.controller.application_class", return_value=Radio): yield opened for radio in opened: if radio._dblistener is not None and radio._dblistener.running: await radio._dblistener.shutdown() # its thread would keep the test process alive async def test_a_start_the_radio_refuses_leaves_nothing_open_once_stopped(radios): controller = ZigBeeController(build_test_platform()) controller.peripherals = Peripherals({"zigbee": conftest.RADIO}) with pytest.raises(OSError): await controller.start() await controller.stop() (radio,) = radios assert radio._dblistener is not None and not radio._dblistener.running async def test_a_start_cut_short_leaves_nothing_open_once_stopped(radios, monkeypatch): monkeypatch.setattr(_Radio, "hangs", True) controller = ZigBeeController(build_test_platform()) controller.peripherals = Peripherals({"zigbee": conftest.RADIO}) start = asyncio.create_task(controller.start()) await wait_for(lambda: bool(radios) and radios[0].is_connected) start.cancel() # the start timeout, or the user restarting or disabling Zigbee meanwhile await asyncio.gather(start, return_exceptions=True) await controller.stop() (radio,) = radios assert not radio.is_connected assert radio._dblistener is not None and not radio._dblistener.running async def test_a_stop_while_the_reconnect_closes_the_lost_radio_still_closes_its_database(radios, monkeypatch): monkeypatch.setattr(ZigBeeController, "RECONNECT_DELAYS", (0,)) closing = asyncio.Event() async def startup(app, *, auto_form: bool = False): app.state.network_info = app_state.NetworkInfo( channel=t.uint8_t(15), pan_id=t.PanId(0x1234), extended_pan_id=t.ExtendedPanId.convert(conftest.EXTENDED_PAN_ID), ) async def disconnect(*_): # closing a port that just vanished takes a while closing.set() await asyncio.sleep(0.2) monkeypatch.setattr(_Radio, "startup", startup) monkeypatch.setattr(_Radio, "disconnect", disconnect) controller = ZigBeeController(build_test_platform()) controller.output = RecordingControllerOutput() controller.peripherals = Peripherals({"zigbee": conftest.RADIO}) await controller.start() (lost,) = radios assert lost._dblistener database = lost._dblistener._db # aiosqlite's thread, no daemon: left open, the process can't exit lost.connection_lost(ConnectionResetError("unplugged")) # zigpy at once await closing.wait() # the reconnect closes the lost radio await controller.stop() # the USB scanner noticed the unplug a poll later await wait_for(lambda: not database.is_alive()) async def test_the_quirks_load_off_the_event_loop(zigpy_apps, monkeypatch): monkeypatch.setattr(majordom_zigbee.controller, "_quirks_loaded", False) on_the_loop: list[bool] = [] # Seconds of imports (3 s on a Mac): on the loop they would stall the Hub's API and every other integration monkeypatch.setattr( zhaquirks, "setup", lambda: on_the_loop.append(threading.current_thread() is threading.main_thread()) ) controller = ZigBeeController(build_test_platform()) controller.peripherals = Peripherals({"zigbee": conftest.RADIO}) await controller.start() await controller.stop() assert on_the_loop == [False] def test_the_package_exports_its_controller_and_usb_driver(): driver, controller = majordom_zigbee.peripherals(build_test_platform()) assert isinstance(driver, ZigpyDriver) and isinstance(controller, ZigBeeController) ================================================================================ # FILE: tests/test_param_ux.py ================================================================================ """Light probes for the parameter-UX mapping — exercise the curation code paths without re-hardcoding every device's expected parameters (that stays manual review; see the audit script and the docs recipe).""" from uuid import uuid4 from majordom_integration_sdk.schemas.parameter import ParameterDataType, ParameterRole, ParameterVisibility from majordom_zigbee.zigbee_spec import ( CONFIG_HEAVY_CLUSTERS, EVERYDAY_COMMANDS, EVERYDAY_CONTROL_ATTRIBUTES, MAIN_PARAMETER_BY_CLUSTER, METADATA_SOURCES, OUR_ATTRIBUTE_UX, USER_READINGS, VISIBILITY_OVERRIDES, ZHA_ATTRIBUTE_UX, UxSpec, classify_attribute, is_metadata_attribute, resolve_metadata_bounds, ) def test_metadata_heuristic_catches_scaling_constants(): assert is_metadata_attribute(0x0B04, 0x0602, "ac_voltage_divisor") assert is_metadata_attribute(0x0B04, 0x0603, "ac_voltage_multiplier") assert is_metadata_attribute(0x0402, 0x0002, "max_measured_value") def test_metadata_heuristic_leaves_real_readings_alone(): assert not is_metadata_attribute(0x0402, 0x0000, "measured_value") assert not is_metadata_attribute(0x0B04, 0x050B, "active_power") def test_curation_sets_are_consistent(): # a parameter can't be both an everyday writable control and a read-only user reading assert USER_READINGS.isdisjoint(EVERYDAY_CONTROL_ATTRIBUTES) # overrides don't contradict the curated user lists (an override is for the *other* cases) assert set(VISIBILITY_OVERRIDES).isdisjoint(USER_READINGS | EVERYDAY_CONTROL_ATTRIBUTES) def test_config_heavy_and_commands_populated(): # DoorLock, ElectricalMeasurement, Metering are the config-heavy clusters assert {0x0101, 0x0B04, 0x0702} <= CONFIG_HEAVY_CLUSTERS # the everyday one-tap commands include lock/unlock and on/off assert {(0x0101, 0x00), (0x0101, 0x01), (0x0006, 0x02)} <= EVERYDAY_COMMANDS def test_fan_control_is_an_attribute_main_that_cycles(): spec = MAIN_PARAMETER_BY_CLUSTER[0x0202] # FanControl has no commands assert spec.is_attribute assert spec.target_id == 0x0000 # fan_mode assert spec.cycle == [0x00, 0x04] # off <-> on toggle def test_attribute_main_cycle_stored_as_default_value(): # Pairing stores an attribute main's cycle subset on default_value (not integration_data), so # the relay derives the next value via Parameter.main_cycle — the same path for every protocol. from majordom_zigbee.model import ZBParameterIntegrationData, ZBParameterState, ZBParameterType spec = MAIN_PARAMETER_BY_CLUSTER[0x0202] assert spec.cycle is not None param = ZBParameterState( id=uuid4(), name="fan_mode", data_type=ParameterDataType.enum, role=ParameterRole.control, visibility=ParameterVisibility.user, valid_values={0x00: "off", 0x01: "low", 0x02: "medium", 0x03: "high", 0x04: "on"}, integration_data=ZBParameterIntegrationData( endpoint_id=1, cluster_id=0x0202, attribute_id=0x0000, type=ZBParameterType.attribute ), default_value=set(spec.cycle), ) assert param.can_be_main_parameter assert param.main_cycle == [0x00, 0x04] # only the curated off/on subset, not the full enum assert not hasattr(param.integration_data, "main_cycle") def test_metadata_resolver_prefers_device_limit_values(): # LevelControl.current_level bounded by the device's own min/max_level runtime values values = {0x0002: 10, 0x0003: 200} lo, hi, missing = resolve_metadata_bounds(0x0008, 0x0000, values.get, 0, 254) assert (lo, hi) == (10, 200) assert not missing def test_metadata_resolver_reports_missing_sources(): lo, hi, missing = resolve_metadata_bounds(0x0008, 0x0000, {}.get, 0, 254) assert (lo, hi) == (0, 254) # falls back to wire-type defaults assert set(missing) == {0x0002, 0x0003} def test_metadata_resolver_passthrough_when_no_source(): assert resolve_metadata_bounds(0x0500, 0x0000, {}.get, 1, 2) == (1, 2, []) def test_metadata_sources_point_at_real_metadata(): # every declared source's target parameter is itself a real (non-metadata) reading key for cluster_id, attr_id in METADATA_SOURCES: assert not is_metadata_attribute(cluster_id, attr_id, "measured_value") # --- classification ladder probes (see classify_attribute) -------------------------------------- def test_our_override_beats_everything(): # OnOff.on_off is in USER_READINGS -> our layer forces user/sensor, even though zha also has it. spec, source = classify_attribute(0x0006, 0x0000, "on_off", writable=True, reportable=True) assert source == "ours" assert spec.visibility is ParameterVisibility.user def test_metadata_forced_system(): spec, source = classify_attribute(0x0402, 0x0002, "max_measured_value", writable=False, reportable=True) assert source == "metadata" assert spec.visibility is ParameterVisibility.system def test_harvested_zha_applied_when_uncurated(): # pick any harvested key that isn't in our hand layer, and check it flows through the zha tier zha_only = next(k for k in ZHA_ATTRIBUTE_UX if k not in OUR_ATTRIBUTE_UX) cid, aid = zha_only spec, source = classify_attribute(cid, aid, "x", writable=True, reportable=False) assert source in ("zha", "metadata") # metadata safety rule may pre-empt some keys def test_quirk_metadata_beats_zha(): # a v2 quirk spec is honored above the harvested zha layer (but below our hand overrides) q = UxSpec(ParameterVisibility.setting, ParameterRole.control, None) spec, source = classify_attribute( 0x0008, 0x0010, "on_off_transition_time", writable=True, reportable=False, quirk_ux=q ) assert source == "quirk-v2" assert spec is q def test_fallback_warns_for_uncurated(): # an attribute in no source falls to the heuristic and is tagged fallback-* spec, source = classify_attribute(0x0AAA, 0x1234, "mystery", writable=False, reportable=True) assert source.startswith("fallback") assert spec.visibility is ParameterVisibility.user # reportable heuristic (until coverage flip) def test_harvest_artifact_is_populated(): assert len(ZHA_ATTRIBUTE_UX) > 30 # the vendored zha harvest loaded ================================================================================ # FILE: tests/test_radio.py ================================================================================ """Unit tests for backend-agnostic radio selection (majordom_zigbee.radio).""" import importlib.util import sys import types from typing import Any from unittest.mock import AsyncMock import conftest import pytest from majordom_integration_sdk import Endpoint from zigpy.config import CONF_DEVICE, CONF_DEVICE_BAUDRATE, CONF_DEVICE_PATH from majordom_zigbee import radio as radio_mod from majordom_zigbee.controller import ZigBeeController def _fake_radio_module(monkeypatch, dotted_path: str, probe_result): """Install a fake module exposing a ControllerApplication with a stubbed async probe().""" module_path, _, cls_name = dotted_path.rpartition(".") app_cls = type(cls_name, (), {"probe": AsyncMock(return_value=probe_result)}) module = types.ModuleType(module_path) setattr(module, cls_name, app_cls) # register the (possibly dotted) module so importlib.import_module finds it parts = module_path.split(".") for i in range(1, len(parts) + 1): name = ".".join(parts[:i]) monkeypatch.setitem(sys.modules, name, sys.modules.get(name) or types.ModuleType(name)) monkeypatch.setitem(sys.modules, module_path, module) return app_cls def test_the_dialect_names_its_radio_library(monkeypatch): ezsp = next(r for r in radio_mod.RADIOS if r.key == "ezsp") app = _fake_radio_module(monkeypatch, ezsp.application, probe_result=True) assert radio_mod.application_class("ezsp") is app def test_a_radio_library_missing_says_what_to_install(monkeypatch): deconz = next(r for r in radio_mod.RADIOS if r.key == "deconz") monkeypatch.setitem(sys.modules, deconz.application.rpartition(".")[0], None) with pytest.raises(RuntimeError, match=r"majordom-zigbee\[deconz\]"): radio_mod.application_class("deconz") @pytest.mark.asyncio async def test_the_driver_names_the_first_radio_that_answers(monkeypatch): # deconz probe fails (raises), znp probe matches -> znp is chosen. deconz = next(r for r in radio_mod.RADIOS if r.key == "deconz") znp = next(r for r in radio_mod.RADIOS if r.key == "znp") deconz_app = _fake_radio_module(monkeypatch, deconz.application, probe_result=False) deconz_app.probe = AsyncMock(side_effect=RuntimeError("wrong protocol")) _fake_radio_module(monkeypatch, znp.application, probe_result=True) # make sure no other radio libs are importable so the loop only sees our two fakes for r in radio_mod.RADIOS: if r.key not in ("deconz", "znp"): monkeypatch.setitem(sys.modules, r.application.rpartition(".")[0], None) driver = radio_mod.ZigpyDriver() assert await driver.identify("/dev/x") == ("znp", {"baud": 115200}) assert driver.serves("znp", "/dev/x") == [Endpoint("zigbee", "znp", "/dev/x")] def _only(monkeypatch, key: str) -> Any: """The fake library of the radio ``key``, the only one installed.""" for r in radio_mod.RADIOS: if r.key != key: monkeypatch.setitem(sys.modules, r.application.rpartition(".")[0], None) return _fake_radio_module(monkeypatch, radio_mod._BY_KEY[key].application, probe_result=False) @pytest.mark.asyncio async def test_the_driver_tells_the_baud_the_stick_answered_at(monkeypatch): app = _only(monkeypatch, "ezsp") app.probe = AsyncMock(return_value={CONF_DEVICE_PATH: "/dev/x", CONF_DEVICE_BAUDRATE: 460800}) # bellows' second driver = radio_mod.ZigpyDriver() found = await driver.identify("/dev/x") assert found firmware, params = found assert driver.serves(firmware, "/dev/x", params) == [Endpoint("zigbee", "ezsp", "/dev/x", params={"baud": 460800})] @pytest.mark.asyncio async def test_the_driver_tries_the_bauds_a_library_lists_the_zigpy_1_way(monkeypatch): app = _only(monkeypatch, "deconz") # zigpy-deconz 0.25 and zigpy-blz 0.1, which zigpy 2 doesn't read app._probe_config_variants = [{CONF_DEVICE_BAUDRATE: 38400}, {CONF_DEVICE_BAUDRATE: 115200}] tried: list[int] = [] async def probe(config): # a ConBee I: 38400 only tried.append(config.get(CONF_DEVICE_BAUDRATE)) return config if config.get(CONF_DEVICE_BAUDRATE) == 38400 else False app.probe = probe assert await radio_mod.ZigpyDriver().identify("/dev/x") == ("deconz", {"baud": 38400}) assert tried == [38400] @pytest.mark.parametrize( ("probe_configs", "variants", "answers_at", "tried"), [ ([{CONF_DEVICE_BAUDRATE: 460800}], None, 460800, [115200, 460800]), # bellows: zigpy 2's way ([], [{CONF_DEVICE_BAUDRATE: 38400}, {CONF_DEVICE_BAUDRATE: 115200}], 115200, [38400, 115200]), # zigpy 1's ], ) @pytest.mark.asyncio async def test_zigpys_own_probe_tries_each_baud_a_library_lists( monkeypatch, probe_configs, variants, answers_at, tried ): opened_at: list[int] = [] class Library(conftest._MockZigpyApp): # zigpy's own probe(), which opens the stick at each config it merged _probe_configs = probe_configs _probe_config_variants = variants async def connect(self, *_): opened_at.append(self.config[CONF_DEVICE][CONF_DEVICE_BAUDRATE]) if opened_at[-1] != answers_at: raise OSError("no answer at this baud") _only(monkeypatch, "deconz") module_path, _, cls_name = radio_mod._BY_KEY["deconz"].application.rpartition(".") monkeypatch.setattr(sys.modules[module_path], cls_name, Library) assert await radio_mod.ZigpyDriver().identify("/dev/x") == ("deconz", {"baud": answers_at}) assert opened_at == tried @pytest.mark.asyncio async def test_the_driver_probes_the_cheapest_radios_first_and_ezsp_last(monkeypatch): probed: list[str] = [] for radio in radio_mod.RADIOS: app = _fake_radio_module(monkeypatch, radio.application, probe_result=False) app.probe = AsyncMock(side_effect=lambda _config, key=radio.key: probed.append(key)) driver = radio_mod.ZigpyDriver() assert await driver.identify("/dev/x") is None # ziggurat is a server's WebSocket, never a stick; ezsp last: the SDK's Silabs driver tried the stick first assert probed == ["deconz", "zigate", "xbee", "blz", "znp", "ezsp"] assert list(driver.firmwares) == probed def test_the_need_takes_every_zigpy_dialect_only(): (need,) = ZigBeeController.needs assert all(need.accepts(Endpoint("zigbee", r.key, "/dev/x")) for r in radio_mod.RADIOS) assert not need.accepts(Endpoint("zigbee", "zigbee2mqtt", "mqtt://127.0.0.1")) def test_the_need_takes_what_the_usb_driver_serves(): (need,) = ZigBeeController.needs served = [e for r in radio_mod.PROBED for e in radio_mod.ZigpyDriver().serves(r.key, "/dev/x")] assert [e.dialect for e in served] == [r.key for r in radio_mod.PROBED] assert all(need.accepts(e) for e in served) @pytest.mark.parametrize("radio", radio_mod.RADIOS, ids=lambda r: r.key) def test_installed_radio_libraries_load(radio): if importlib.util.find_spec(radio.application.partition(".")[0]) is None: pytest.skip(f"{radio.package} is not installed") assert radio_mod._load(radio) is not None ================================================================================ # FILE: tests/test_settings.py ================================================================================ """ZigBeeController.Settings: the user sets only what zigpy accepts; the network's own values are shown, never set.""" import pytest from conftest import EXTENDED_PAN_ID, RADIO, wait_for from majordom_integration_sdk import Peripherals from majordom_integration_sdk.runtime import PeripheralState, Pinned, Runtime from majordom_integration_sdk.testing import build_test_platform from pydantic import ValidationError from zigpy.config import CONF_NWK, CONF_NWK_TX_POWER from majordom_zigbee.controller import ZigBeeController @pytest.mark.parametrize("tx_power", [-10, 0, 20, None]) def test_transmit_power_within_zigpys_range_is_accepted(tx_power): assert ZigBeeController.Settings(tx_power=tx_power).tx_power == tx_power @pytest.mark.parametrize("tx_power", [-11, -20, 21]) def test_transmit_power_zigpy_rejects_is_refused(tx_power): with pytest.raises(ValidationError): ZigBeeController.Settings(tx_power=tx_power) def test_the_network_is_shown_read_only_and_its_key_never(): fields = ZigBeeController.Settings.model_json_schema()["properties"] assert [name for name, field in fields.items() if field.get("readOnly")] == ["channel", "pan_id", "extended_pan_id"] assert "network_key" not in fields async def test_the_radios_network_fills_in_the_settings(zigpy_apps): settings = ZigBeeController.Settings(channel=25, tx_power=8) # a channel kept from an older network controller = ZigBeeController(build_test_platform(), settings=settings) controller.peripherals = Peripherals({"zigbee": RADIO}) await controller.start() try: (app,) = zigpy_apps assert app.given_config and app.given_config[CONF_NWK] == {CONF_NWK_TX_POWER: 8} assert controller.settings == ZigBeeController.Settings( channel=15, pan_id="0x1234", extended_pan_id=EXTENDED_PAN_ID, tx_power=8 ) finally: await controller.stop() async def test_a_change_to_the_network_is_refused(zigpy_apps, tmp_path): controller = ZigBeeController(build_test_platform()) runtime = Runtime(tmp_path, [Pinned(RADIO), controller], platform=controller.platform) await runtime.start() try: await wait_for(lambda: runtime.status(controller).state == PeripheralState.RUNNING) with pytest.raises(ValidationError, match="frozen"): await runtime.update_settings(controller, {"channel": 25}) shown = controller.settings.model_dump(mode="json") await runtime.update_settings(controller, shown | {"tx_power": 4}) # the form sent back with a new power await wait_for(lambda: len(zigpy_apps) == 2 and runtime.status(controller).state == PeripheralState.RUNNING) assert controller.settings.channel == 15 and controller.settings.tx_power == 4 finally: await runtime.stop() # integration-homekit — full source # repo: https://github.com/MajorDom-Systems/integration-homekit branch: master commit: e4de21c217c28113ee823a7d3f5457056e8bf3a8 # generated: 2026-11-16 — AUTO-GENERATED, do not edit by hand ## File tree .gitignore LICENSE README.md majordom_homekit/__init__.py majordom_homekit/characteristics_storage.py majordom_homekit/controller.py majordom_homekit/mapper.py majordom_homekit/models.py majordom_homekit/pairings_storage.py majordom_homekit/parameters_map.py majordom_homekit/readme.md pyproject.toml tests/conftest.py tests/test_controller.py tests/test_peripherals.py ================================================================================ # FILE: .gitignore ================================================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[codz] *$py.class # C extensions *.so # Distribution / packaging build/ dist/ *.egg-info/ *.egg # Unit test / coverage reports .coverage .coverage.* coverage.xml htmlcov/ .pytest_cache/ .hypothesis/ # Environments .env .envrc .venv env/ venv/ # Poetry # poetry.lock # uncomment for applications, keep commented for libraries # Type checkers .mypy_cache/ .dmypy.json .pyre/ .pytype/ # Tools .ruff_cache/ .ropeproject # mkdocs (only relevant if you kept mkdocs.yml + docs/) /site .cache/ # IDEs .idea/ .vscode/ # OS .DS_Store Thumbs.db # The dev runner's settings and keys .majordom-dev/ ================================================================================ # FILE: LICENSE ================================================================================ # PolyForm Noncommercial License 1.0.0 ## Acceptance In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses. ## Copyright License The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license). ## Distribution License The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license). ## Notices You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example: > Required Notice: Copyright Yoyodyne, Inc. (http://example.com) ## Changes and New Works License The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose. ## Patent License The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software. ## Noncommercial Purposes Any noncommercial purpose is a permitted purpose. ## Personal Uses Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose. ## Noncommercial Organizations Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding. ## Fair Use You may have "fair use" rights for the software under the law. These terms do not limit them. ## No Other Rights These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses. ## Patent Defense If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company. ## Violations The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately. ## No Liability ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*** ## Definitions The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms. **You** refers to the individual or entity agreeing to these terms. **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. **Your licenses** are all the licenses granted to you for the software under these terms. **Use** means anything you do with the software requiring one of your licenses. ================================================================================ # FILE: README.md ================================================================================ Part of MajorDom — the next-gen smart home # integration-homekit A [MajorDom](https://majordom.io) integration — bridges **Apple HomeKit** accessories into the MajorDom language. Built for the **MajorDom Hub**, but it doesn't need it: this is a standalone, standardized library for HomeKit that you can use on its own (see **Run it standalone** below). Built on the [MajorDom Integration SDK](https://github.com/MajorDom-Systems/integration-sdk). The entry point is `HomeKitController` (`majordom_homekit/controller.py`), which the Hub — or the SDK's dev runner — instantiates and drives through its lifecycle: discovery → pairing → commands → teardown. - **Other protocols:** browse the [MajorDom integrations](https://github.com/orgs/MajorDom-Systems/repositories?q=integration-). - **Create your own:** start from the [integration template](https://github.com/MajorDom-Systems/integration-template). ## Documentation Full integration-author docs — the controller lifecycle, data models, storing data, discovery, and a worked example — live at **[docs.majordom.io](https://docs.majordom.io/device-integration)**. ## Development ```sh poetry install && poetry run poe install ``` | Task | Description | |------|-------------| | `poe check` | Full quality pipeline (ruff, ty, pytest, poetry build/check) | | `poe check --ci` | Same, plus `git diff --exit-code` | Work lands on `develop`; `master` is protected and released via **Actions → Release**. Tests drive the controller with the SDK's test doubles against an in-process fake HAP accessory server — no real accessory required (see `tests/`). ## Run it standalone (without the Hub) `majordom-homekit` is a standalone library — import it into your own app, or run **just this integration** interactively (discover, pair, control, and inspect devices from a prompt) with no Hub. It discovers IP accessories over mDNS; no external service is required. See **[Standalone mode](https://docs.majordom.io/device-integration/standalone)** for the interactive CLI, watch mode, and the programmatic API. ## About this integration - **Protocol / platform:** Apple HomeKit Accessory Protocol (HAP) via the [`parker-aiohomekit`](https://pypi.org/project/parker-aiohomekit/) fork of `aiohomekit`. - **Transport(s):** IP (Wi-Fi / Ethernet, discovered via mDNS). BLE is not supported yet: discovery and pairing are in progress, and the transport stays disabled until the encrypted session is verified on hardware. - **Supported devices:** HomeKit-compatible accessories — lights, plugs, switches, sensors, locks. - **Credentials needed to pair:** `code` (the accessory's 8-digit HomeKit setup code). ### Required harness - **Hardware adapters:** none. - **Third-party software services:** none — `aiohomekit` speaks HAP directly. - **OS / permissions:** mDNS on the LAN for discovery. ### Protocol stack (OSI) | OSI layer | Protocol | Implemented by | |-----------|----------|----------------| | Application (7) | HAP characteristics / services | **this integration** (via `aiohomekit`) | | Session (5) | Pair-Setup / Pair-Verify (SRP, Ed25519) | library (`aiohomekit`) | | Transport (4) | TCP (IP) | OS | | Network + below (1–3) | IP over Wi-Fi / Ethernet | OS | ### Progress - [x] Discovery services registered (mDNS via `zeroconf_discovery_service`); cancel closures called in `stop` - [x] Discovery listeners fire and call `controller_did_receive_discovery` - [x] Re-discovery of already-paired accessories on reconnect (`controller_did_connect_device`) - [x] Device pairing (HAP pair-setup with the setup code) - [x] Device schema mapped: services/characteristics → parameter list with per-parameter metadata - [x] Hub → Device control (`send_command`) - [x] Device → Hub event subscription (`controller_did_receive_events`) - [x] `identify` - [x] `unpair` - [x] `fetch` - [x] Availability tracking while running (`controller_did_lose_device` / `last_error`) - [x] Graceful shutdown in `stop` - [x] Tests pass against a fake HAP accessory server (`tests/`) - [x] Owned — maintained by Parker Industries - [ ] BLE accessories (discovery and pairing in progress; disabled until the encrypted session is verified on hardware) ### Notes Uses the `parker-aiohomekit` fork of `aiohomekit`; note its Python upper bound (`<3.14`). ## License See [LICENSE](LICENSE). For commercial licensing or partnership inquiries regarding MajorDom, contact us via [parker-industries.org/partnership](https://parker-industries.org/partnership). ================================================================================ # FILE: majordom_homekit/__init__.py ================================================================================ """HomeKit integration for MajorDom. Bridges HomeKit accessories into the MajorDom language. `peripherals` is what the Hub (or the SDK's standalone dev runner) runs: `HomeKitController`, which needs the runtime's zeroconf. """ from majordom_integration_sdk import Peripheral, Platform from majordom_homekit.controller import HomeKitController def peripherals(platform: Platform) -> list[Peripheral]: return [HomeKitController(platform)] __all__ = ["HomeKitController", "peripherals"] ================================================================================ # FILE: majordom_homekit/characteristics_storage.py ================================================================================ """ HomeKit-specific storage adapter. TLDR; aiohomekit manages pairing and characteristics data internally, but delegates persistence to a pluggable storage interface. This class implements that interface on top of MajorDom's DeviceRepository, so HomeKit state is stored in the Hub's database. """ from collections.abc import Callable from contextlib import AbstractAsyncContextManager from aiohomekit.model.accessories import AccessoriesState from aiohomekit.model.typed_dicts import HKDeviceID from aiohomekit.storage.characteristics_storage import CharacteristicsStorageProtocol from majordom_integration_sdk.repository import DeviceRepositoryProtocol from .mapper import HKMajorDomMapper from .models import HKDevice, HKDeviceIntegrationData, HKDeviceState def fill_from_accessories_state(device: HKDeviceState, item: AccessoriesState, mapper: HKMajorDomMapper): if not device.integration_data: device.integration_data = HKDeviceIntegrationData() # fill only the unique data from AccessoryState that isn't already passed from # Discovery or DeviceCreate by the core # TODO: check these values with real devices accessory = item.accessories[0] # TODO: add later support for multiple accessories device.manufacturer = accessory.manufacturer # Manufacturer-provided, read-only description — the HAP accessory model. device.description = getattr(accessory, "model", None) device.integration_data.characteristics_cache = item # map all homekit characteristics to majordom parameters # (rebuilt, not appended: a full state replaces the stored parameters, so what the accessory dropped goes) device.parameters = [ mapper.hap_char_to_majordom_parameter(device.physical_id, accessory.aid, characteristic) for accessory in item.accessories for service in accessory.services for characteristic in service.characteristics ] class HKCharacteristicsStorageMajorDom(CharacteristicsStorageProtocol): def __init__( self, make_device_repository: Callable[[], AbstractAsyncContextManager[DeviceRepositoryProtocol]], mapper: HKMajorDomMapper, ): self.make_device_repository = make_device_repository self.mapper = mapper # CharacteristicsStorageProtocol Implementation async def get_all(self) -> dict[HKDeviceID, AccessoriesState]: all = {} async with self.make_device_repository() as device_repository: for device in await device_repository.get_all(as_=HKDevice): if accessory := device.integration_data.characteristics_cache: all[device.hk_id] = accessory return all async def get(self, id: HKDeviceID) -> AccessoriesState | None: uuid = self.mapper.hap_id_to_uuid(id) async with self.make_device_repository() as device_repository: if (device := await device_repository.get(physical_id=uuid, as_=HKDevice)) and ( accessory := device.integration_data.characteristics_cache ): return accessory return None async def save(self, id: HKDeviceID, item: AccessoriesState): # NOTE: aiohomekit calls this only when data model (characteristics) is updated # which is detected by a change of config_num # usually after the accessory's software update; pair_device fills the first one into the draft async with self.make_device_repository() as device_repository: physical_id = self.mapper.hap_id_to_uuid(id) # No row while pairing: the draft isn't saved yet if not (device := await device_repository.state(physical_id=physical_id, as_=HKDeviceState)): return fill_from_accessories_state(device, item, self.mapper) await device_repository.save(device) async def delete(self, id: HKDeviceID): # TODO: check usage, remove vs unpair, allow fast re-pairing async with self.make_device_repository() as device_repository: uuid = self.mapper.hap_id_to_uuid(id) if device := await device_repository.get(physical_id=uuid, as_=HKDevice): device.integration_data.characteristics_cache = None # TODO: empty collection? await device_repository.save(device) ================================================================================ # FILE: majordom_homekit/controller.py ================================================================================ import asyncio import contextlib import logging from collections.abc import AsyncIterator, Callable, Coroutine, Iterable from typing import Any, override from uuid import UUID from aiohomekit.controller.abstract import ( AbstractController, AbstractDiscovery, AbstractPairing, ) from aiohomekit.controller.relay import Controller as AioHomeKitController from aiohomekit.controller.relay import controller as controller_module from aiohomekit.exceptions import AccessoryDisconnectedError, AccessoryNotFoundError, AuthenticationError from aiohomekit.model.characteristics import CharacteristicKey from aiohomekit.model.characteristics.characteristic_key import CharacteristicKeyValue from aiohomekit.model.characteristics.permissions import CharacteristicPermissions from aiohomekit.model.typed_dicts import HKDeviceID, Response from majordom_integration_sdk import DeviceRepositoryProtocol, DeviceUnreachableError, NoSettings, Platform from majordom_integration_sdk.capabilities import ZEROCONF from majordom_integration_sdk.controller import ( AbstractController as MajorDomController, # avoid collision with aiohomekit ) from majordom_integration_sdk.schemas.base import NonEmptyStr from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import ( CredentialsType, Discovery, ProvidedCredentials, ) from majordom_integration_sdk.schemas.event import DeviceParameterChange from .characteristics_storage import HKCharacteristicsStorageMajorDom, fill_from_accessories_state from .mapper import HKMajorDomMapper from .models import HKDevice, HKDeviceIntegrationData, HKDeviceState, HKParameter from .pairings_storage import HKPairingsStorageMajorDom logger = logging.getLogger(__name__) PAIR_SETUP_TIMEOUT = 30 # seconds for each pair-setup step: SRP takes several on a slow accessory MCU FETCH_TIMEOUT = 30 # seconds # TODO: make a better way to pass this controller_module.BLE_TRANSPORT_SUPPORTED = False controller_module.COAP_TRANSPORT_SUPPORTED = False controller_module.IP_TRANSPORT_SUPPORTED = True # TODO: what are Accessory.needs_polling chars? handle them class HomeKitController(MajorDomController[HKDevice, HKParameter, Any, HKDeviceState]): """Bridges the Hub to HomeKit (HAP) accessories over IP via aiohomekit. aiohomekit owns the HAP protocol, discovery, pairing crypto, and the live connection; this controller adapts it to the Hub's AbstractController contract and persists HomeKit state in the Hub DB through the two storage adapters. See readme.md. """ def __init__(self, platform: Platform, *, settings: NoSettings | None = None): super().__init__(platform, settings=settings) # A single mapper, wired with the framework's UUID generators, is shared with both # storage adapters so every HAP id maps to the same MajorDom UUID everywhere. self.mapper = HKMajorDomMapper(device_uuid=self.device_uuid, parameter_uuid=self.parameter_uuid) self._storage_lock = asyncio.Lock() self.hk_char_storage = HKCharacteristicsStorageMajorDom(self._storage_repository, self.mapper) self.hk_pairing_data_storage = HKPairingsStorageMajorDom(self._storage_repository, self.mapper) self._majordom_discoveries: dict[UUID, Discovery] = dict() self._hap_discoveries: dict[UUID, AbstractDiscovery] = dict() self._availability: dict[UUID, bool] = dict() # physical_id -> last signalled availability # Each pairing observed once, however often it's rediscovered; a re-paired accessory gets a new pairing self._characteristics_observers: dict[AbstractPairing, Callable[[], None]] = dict() self._aiohomekit_controller: AioHomeKitController | None = None self._availability_task: asyncio.Task[None] | None = None self._tasks: set[asyncio.Task[None]] = set() # what aiohomekit's callbacks handle in the background # ------------------------------------------------------------------------- # AbstractController interface # ------------------------------------------------------------------------- name = "HomeKit" needs = [ZEROCONF] # aiohomekit browses with the runtime's zeroconf @property def discoveries(self) -> dict[UUID, Discovery]: return self._majordom_discoveries # device_type / parameter_type let the Hub deserialize into our typed subclasses. @property @override def device_type(self) -> type[HKDevice]: return HKDevice @property @override def parameter_type(self) -> type[HKParameter]: return HKParameter @property @override def device_state_type(self) -> type[HKDeviceState]: return HKDeviceState # ------------------------------------------------------------------------- # Lifecycle # ------------------------------------------------------------------------- async def start(self): # aiohomekit already registers the `_hap._tcp` mDNS browser itself (given our # shared AsyncZeroconf below), so we don't register it on the zeroconf peripheral here. # TODO: BLE discovery and pairing (aiohomekit supports it; the hub only wires IP for now) zeroconf = self.peripherals.instance(ZEROCONF) # aiohomekit would open one of its own, never closed if zeroconf is None or (async_zeroconf := zeroconf.async_zeroconf) is None: raise RuntimeError("zeroconf isn't running") self._aiohomekit_controller = AioHomeKitController( zeroconf_instance=async_zeroconf, char_cache=self.hk_char_storage, pairing_data_storage=self.hk_pairing_data_storage, ) self._aiohomekit_controller.on_discovery(self._aiohomekit_did_discover) await self._aiohomekit_controller.start() # aiohomekit only pushes "became available"; it never pushes "became unavailable" # (see AbstractPairing.add_observer_for_availability). So we poll each paired # accessory's connection state to catch both directions — mid-session drops and # reconnects — and reconcile it through _set_availability. self._availability_task = asyncio.create_task(self._availability_loop()) async def stop(self): for task in self._tasks: task.cancel() if self._availability_task: self._availability_task.cancel() self._availability_task = None self._majordom_discoveries.clear() self._hap_discoveries.clear() self._availability.clear() for stop_observing in self._characteristics_observers.values(): stop_observing() self._characteristics_observers.clear() if aiohomekit_controller := self._aiohomekit_controller: self._aiohomekit_controller = None await aiohomekit_controller.stop() @property def _aiohomekit(self) -> AioHomeKitController: if self._aiohomekit_controller is None: raise RuntimeError(f"{self.name} isn't running") return self._aiohomekit_controller # ------------------------------------------------------------------------- # Public device operations (Hub -> device) # ------------------------------------------------------------------------- async def pair_device( self, discovery: Discovery, draft: HKDeviceState, credentials: ProvidedCredentials | None ) -> HKDeviceState: if not credentials or credentials.type not in discovery.expected_credentials_options: raise ValueError( f"Credentials type {credentials.type if credentials else None!r} is not one of the " f"types this discovery advertised: {discovery.expected_credentials_options}" ) hap_discovery = self._hap_discoveries[discovery.id] hk_id = hap_discovery.description.id.lower() # The HAP id is the physical id (see the mapper), and the accessory refuses a new pair-setup until its # pairing is removed, so a taken id has to be known before the setup draft.physical_id = self.mapper.hap_id_to_uuid(hk_id) await self.check_device_id(draft.physical_id, draft) # A picked record may carry the data of an earlier pairing: it isn't this one to undo draft.integration_data = HKDeviceIntegrationData() # A retry may find the pairing an earlier attempt left (no rollback reached it): confirmed, not set up again if pairing := self._aiohomekit.pairings.get(hk_id): draft.integration_data.pairing_data = pairing.pairing_data else: async with asyncio.timeout(PAIR_SETUP_TIMEOUT): finish_pairing = await hap_discovery.start_pairing() # TODO: check if pairing steps need to be split try: async with asyncio.timeout(PAIR_SETUP_TIMEOUT): await finish_pairing(str(credentials.value or "")) finally: # Even when it fails past the setup (it fetches too): the Hub's rollback, unpair(draft), then removes # the pairing from the accessory, which refuses a new setup until then if pairing := self._aiohomekit.pairings.get(hk_id): draft.integration_data.pairing_data = pairing.pairing_data # aiohomekit saves through the storages only what has a row, and the draft has none yet pairing = self._aiohomekit.pairings[hk_id] await pairing.fetch_accessories_and_characteristics() fill_from_accessories_state(draft, pairing.accessories_state, self.mapper) draft.available = True # it just answered; the Hub signals the connect after saving self._availability[draft.physical_id] = True return draft # still offered until the Hub saves it and fetches it: a rolled back one pairs again async def unpair(self, device: HKDevice): # Also the Hub's rollback of a failed or unsaved pairing: its draft may stop before the pair-setup, then # there is nothing on the accessory # Nor after an unpair that already ran: aiohomekit dropped its pairing then pairing = self._aiohomekit.pairings.get(device.hk_id) if device.integration_data.pairing_data else None if not pairing: self._availability.pop(device.physical_id, None) return try: await self._aiohomekit.remove_pairing(device.hk_id) # aiohomekit will cleanup the storage, so no need to do anything here except (AccessoryDisconnectedError, AccessoryNotFoundError, AuthenticationError) as error: # A dead accessory, or a reset one, must still be deletable: forget it here, as Home Assistant does logger.warning( f'{self.name} can\'t unpair "{device.name}" on the accessory, so it forgets it here only; ' f"the accessory may need a reset before it pairs again: {error!r}" ) await self.hk_char_storage.delete(device.hk_id) await self.hk_pairing_data_storage.delete(device.hk_id) if not isinstance(error, AuthenticationError): # a reset accessory holds no pairing, a dead one does raise DeviceUnreachableError(f'"{device.name}" is unreachable to unpair') from error finally: # aiohomekit drops the pairing before it reaches the accessory, and leaves a failed one reconnecting if pairing: if stop_observing := self._characteristics_observers.pop(pairing, None): stop_observing() await pairing.shutdown() self._availability.pop(device.physical_id, None) # paired again, it keeps its HAP id, so its physical id async def identify(self, device: HKDevice): await self._aiohomekit.identify(device.hk_id) async def fetch(self, device: HKDevice): # The Hub saved it (it fetches only then): it is offered no more self._hap_discoveries.pop(device.physical_id, None) self._majordom_discoveries.pop(device.physical_id, None) if not self._aiohomekit.pairings.get(device.hk_id): raise RuntimeError( f"Unexpected Error: Pairing {device.hk_id} for '{device.id}' aka '{device.name}' not found" ) # reads the values, and subscribes only if this pairing isn't observed yet (aiohomekit re-subscribes # after a reconnect by itself); aiohomekit saves the data model on change automatically async with asyncio.timeout(FETCH_TIMEOUT): await self._handle_connected_pairing(device.hk_id) async def send_command(self, command: DeviceCommand, device: HKDevice, parameter: HKParameter): hk_value = self.mapper.mj_value_to_hap(command.value) pairing = self._aiohomekit.pairings.get(device.hk_id) if not pairing: raise RuntimeError( f"Unexpected Error: Pairing {device.hk_id} for '{device.id}' aka '{device.name}' not found" ) key = CharacteristicKey(parameter.integration_data.aid, parameter.integration_data.iid) response = await pairing.put_characteristics([CharacteristicKeyValue(*key, hk_value)]) # A status comes back only for what failed: the written value reaches the Hub as an event if (failure := response.get(key)) and failure["status"] != 0: raise ValueError( f'{device.name} refused {command.value!r} for characteristic "{key.aid}.{key.iid}": ' f'status "{failure["status"]}", description: {failure.get("description", "none")}' ) # ------------------------------------------------------------------------- # Device -> Hub: discovery (aiohomekit delegate) # ------------------------------------------------------------------------- def _aiohomekit_did_discover(self, controller: AbstractController, hk_discovery: AbstractDiscovery): self._run_in_background(self._async_aiohomekit_did_discover(controller, hk_discovery)) async def _async_aiohomekit_did_discover(self, controller: AbstractController, hk_discovery: AbstractDiscovery): # Already paired to us -> a reconnect, not a new discovery. if hk_discovery.description.id in controller.pairings: logger.debug(f"{self.name} Discovered paired device...") await self._handle_connected_pairing(hk_discovery.description.id) return # Paired to some other controller -> can't offer for pairing here. if hk_discovery.paired: # TODO: handle this case # If device supports only one controller, show as unreachable (requires unpairing) # Some protocols support multiple controllers (like Matter, some HomeKit, Zigbee green with hacks, etc.) # In this case, accessory might need to be put in pairing mode using the first # controller to allow a second pairing with this controller logger.info(f'Device "{hk_discovery.description.name}" is paired to another controller') return # A new, unpaired accessory -> surface it as a discovery. logger.info(f"{self.name} Discovered new device...") desc = hk_discovery.description discovery_uuid = self.mapper.hap_id_to_uuid(hk_discovery.description.id) mj_discovery_info = Discovery( # technical id=discovery_uuid, integration=NonEmptyStr(self.key), expected_credentials_options=[CredentialsType.code.with_mask("DDD-DD-DDD")], expiration=None, # TODO: # UX transport=NonEmptyStr("IP"), device_name=desc.name, device_manufacturer=None, # looks like it needs device to be paired first device_category=desc.category, device_icon=None, # will be implemented later # device_model_id = None, # ? model_name: desc.model ) self._hap_discoveries[discovery_uuid] = hk_discovery self._majordom_discoveries[discovery_uuid] = mj_discovery_info await self.output.controller_did_receive_discovery(self, mj_discovery_info) # TODO: dismiss Discovery if discovery disapperd or expired # ------------------------------------------------------------------------- # Device -> Hub: parameter events & availability # ------------------------------------------------------------------------- def _run_handle_accessory_response(self, hk_device_id: HKDeviceID, responses: Response): self._run_in_background(self._handle_accessory_response(hk_device_id, responses)) async def _handle_accessory_response(self, hk_device_id: HKDeviceID, responses: Response): # TODO: review, test parameter_changed_events = [] for (aid, iid), response in responses.items(): if "value" in response: hk_value = response["value"] physical_id = self.mapper.hap_id_to_uuid(hk_device_id) device_parameter_id = self.mapper.hap_iid_to_param_uuid(hk_device_id, aid, iid) parameter_changed_events.append( DeviceParameterChange( physical_id=physical_id, parameter_id=device_parameter_id, value=hk_value, # TODO: self.mapper.hap_value_to_mj(pairing.characteristic_for_key((aid, iid))) ) ) if "status" in response and response["status"] != 0: # the other values of the batch still count logger.warning( f'Something\'s wrong with characteristic "{aid}.{iid}": ' f'status "{response["status"]}", description: {response.get("description", "none")}' ) await self.output.controller_did_receive_events(self, parameter_changed_events) async def _set_availability(self, physical_id: UUID, available: bool): """Single funnel for availability transitions — dedupes so the Hub is only told on an actual change, and translates it into the framework's connect / lose callbacks.""" if self._availability.get(physical_id) == available: return self._availability[physical_id] = available if available: await self.output.controller_did_connect_device(self, physical_id=physical_id) else: await self.output.controller_did_lose_device(self, physical_id=physical_id) async def _availability_loop(self, interval: float = 30): while True: await asyncio.sleep(interval) try: for hk_id, pairing in list(self._aiohomekit.pairings.items()): await self._set_availability(self.mapper.hap_id_to_uuid(hk_id), pairing.is_available) except Exception: logger.exception(f"{self.name} availability poll failed") # ------------------------------------------------------------------------- # Private helpers: connection setup # ------------------------------------------------------------------------- @contextlib.asynccontextmanager async def _storage_repository(self) -> AsyncIterator[DeviceRepositoryProtocol]: # Both storages rewrite the whole integration_data (pairing data, data model); aiohomekit saves the data # model from a task of its own while pair_device saves the pairing, so one at a time or one drops the other async with self._storage_lock, self.platform.device_repository(self) as repository: yield repository async def _handle_connected_pairing(self, pairing_id: HKDeviceID): pairing = self._aiohomekit.pairings[pairing_id.lower()] # aiohomekit loads a stored pairing without connecting; without a cached data model this fetches it await pairing.fetch_accessories_and_characteristics() # subscribe to events await self._observe_characteristics(pairing) # update state state = await pairing.get_characteristics( self._get_all_characteristics_keys(pairing, {CharacteristicPermissions.paired_read}) ) # Only a read reached it: the cached data model and its mDNS records answer while it's off or hung await self._set_availability(self.mapper.hap_id_to_uuid(pairing_id), True) await self._handle_accessory_response(pairing_id, state) async def _observe_characteristics(self, pairing: AbstractPairing): if pairing in self._characteristics_observers: return self._characteristics_observers[pairing] = pairing.add_observer_for_characteristics( self._run_handle_accessory_response ) # NOTE: intentionally NOT using pairing.add_observer_for_availability. In aiohomekit that # observer (`_callback_availability_changed`) is only ever fired with True — on (re)connect, # across IP/BLE/CoAP. A dropped connection (`_connection_lost`) silently clears the transport # and starts a reconnector without notifying, so the observer would surface "came back" but # never "went away". `pairing.is_available` (== connection.is_connected) DOES flip both ways, # so `_availability_loop` polls it as the single source of truth. If you ever wire the # observer, keep it only as a *supplement* for faster up-detection — never as the sole # availability signal, or devices will appear stuck online after they drop. response = await pairing.subscribe_characteristics( self._get_all_characteristics_keys(pairing, {CharacteristicPermissions.events}) ) await self._handle_accessory_response(pairing.id, response) def _run_in_background(self, coroutine: Coroutine[Any, Any, None]): task = asyncio.create_task(coroutine) self._tasks.add(task) # kept until it ends, so it isn't collected mid-run and stop() cancels it task.add_done_callback(self._background_task_did_end) def _background_task_did_end(self, task: asyncio.Task[None]): self._tasks.discard(task) if not task.cancelled() and (error := task.exception()): logger.error(f"{self.name} failed in the background: {error!r}", exc_info=error) def _get_all_characteristics_keys( self, pairing: AbstractPairing, perms: set[CharacteristicPermissions] ) -> Iterable[CharacteristicKey]: for accessory in pairing.accessories_state.accessories: for service in accessory.services: for characteristic in service.characteristics: if perms.issubset(characteristic.perms): yield CharacteristicKey(accessory.aid, characteristic.iid) ================================================================================ # FILE: majordom_homekit/mapper.py ================================================================================ """ Conversion logic between HAP (HomeKit Accessory Protocol) concepts and MajorDom's domain model. Isolated here to keep the Controller free of boilerplate — formats, units, permissions, and valid enum values are all mapped in one place. """ import inspect import re from collections.abc import Callable, Iterable from enum import Enum from typing import Any from uuid import UUID from aiohomekit.model.characteristics import ( Characteristic, CharacteristicFormats, CharacteristicUnits, ) from aiohomekit.model.characteristics import const as aiohomekit_consts from aiohomekit.model.characteristics.characteristic_types import CharacteristicsTypes from aiohomekit.model.characteristics.permissions import CharacteristicPermissions from aiohomekit.model.typed_dicts import HKDeviceID from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from majordom_homekit.models import ( HKParameterIntegrationData, HKParameterState, ) class HKMajorDomMapper: def __init__( self, device_uuid: Callable[[str], UUID], parameter_uuid: Callable[[UUID, str], UUID], ): # The controller's provided (framework) UUID generators — see AbstractController. # HAP identifiers are turned into MajorDom UUIDs exclusively through these, so physical # and parameter ids are namespaced under the integration consistently with every other # integration. self._device_uuid = device_uuid self._parameter_uuid = parameter_uuid # ------------------------------------------------------------------------- # Identity: HAP identifiers -> MajorDom UUIDs # ------------------------------------------------------------------------- def hap_id_to_uuid(self, hk_device_id: HKDeviceID) -> UUID: return self._device_uuid(hk_device_id.lower()) def hap_iid_to_param_uuid(self, hk_device_id: HKDeviceID, aid: int, iid: int) -> UUID: return self._parameter_uuid(self.hap_id_to_uuid(hk_device_id), f"{aid}.{iid}") # ------------------------------------------------------------------------- # MajorDom -> HAP # ------------------------------------------------------------------------- def mj_value_to_hap(self, value: Any): # TODO: implement conversion if needed # aiohomekit handle a lot of processing for us # use characteristic.format and characteristic.unit for correct conversion # checking existing mapping inside aiohomekit might be helpful return value # ------------------------------------------------------------------------- # HAP -> MajorDom # ------------------------------------------------------------------------- def hap_char_to_majordom_parameter( self, physical_id: UUID, aid: int, characteristic: Characteristic ) -> HKParameterState: return HKParameterState( id=self._parameter_uuid(physical_id, f"{aid}.{characteristic.iid}"), name=characteristic.description or "", data_type=self._hap_format_to_mj_data_type(characteristic.format), unit=self._hap_unit_to_mj(characteristic.unit), role=self._hap_perms_to_mj_role(characteristic.perms), visibility=ParameterVisibility.user, min_value=characteristic.minValue, max_value=characteristic.maxValue or characteristic.maxLen, min_step=characteristic.minStep, valid_values=self._valid_values(characteristic), integration_data=HKParameterIntegrationData( type=characteristic.type, aid=aid, iid=characteristic.iid, ), value=self.hap_value_to_mj(characteristic), ) # UNUSED: # Service.available # Characteristic.available # Characteristic.ev # Characteristic.maxDataLen # Characteristic.handle # Characteristic.broadcast_events # Characteristic.disconnected_events # Characteristic.valid_values_range def hap_value_to_mj(self, characteristic: Characteristic): # characteristic.value should already work in most cases since aiohomekit handle a lot of processing for us # otherwise use characteristic.format and characteristic.unit for correct conversion # checking existing mapping inside aiohomekit might be helpful return characteristic.value def _hap_format_to_mj_data_type(self, format: str | None) -> ParameterDataType: mapping: dict[str | None, ParameterDataType] = { CharacteristicFormats.bool: ParameterDataType.bool, CharacteristicFormats.uint8: ParameterDataType.integer, CharacteristicFormats.uint16: ParameterDataType.integer, CharacteristicFormats.uint32: ParameterDataType.integer, CharacteristicFormats.uint64: ParameterDataType.integer, CharacteristicFormats.int: ParameterDataType.integer, CharacteristicFormats.int32: ParameterDataType.integer, CharacteristicFormats.float: ParameterDataType.decimal, CharacteristicFormats.string: ParameterDataType.string, CharacteristicFormats.data: ParameterDataType.data, # TODO: review CharacteristicFormats.tlv8: ParameterDataType.data, CharacteristicFormats.array: ParameterDataType.data, CharacteristicFormats.dict: ParameterDataType.data, } return mapping[format] def _hap_unit_to_mj(self, unit: str | None) -> ParameterUnit: mapping: dict[str | None, ParameterUnit] = { CharacteristicUnits.celsius: ParameterUnit.celsius, CharacteristicUnits.percentage: ParameterUnit.percentage, CharacteristicUnits.arcdegrees: ParameterUnit.arcdegree, CharacteristicUnits.lux: ParameterUnit.lux, CharacteristicUnits.seconds: ParameterUnit.second, None: ParameterUnit.plain, } return mapping[unit] def _hap_perms_to_mj_role(self, perms: Iterable[str]) -> ParameterRole: # TODO: review all perms in specs if CharacteristicPermissions.paired_write in perms: return ParameterRole.control elif CharacteristicPermissions.paired_read in perms: return ParameterRole.sensor else: return ParameterRole.event def _valid_values(self, characteristic: Characteristic) -> dict[int | str | float, str] | None: # TODO: convert to codegen instead of runtime parsing if values_enum := self._search_values_enum_for_characteristic(characteristic): return {v.value: underscore_to_display_case(k) for k, v in values_enum.__members__.items()} else: return {key: str(key) for key in characteristic.valid_values or []} # scrapping def _search_values_enum_for_characteristic(self, characteristic: Characteristic) -> type[Enum] | None: # try get characteristic type name by id for char_type in CharacteristicsTypes: if char_type == characteristic.type and (values_enum := self._search_values_enum_by_name(char_type.name)): return values_enum # try using description as a type name if characteristic.description: possible_enum_name = "_".join(characteristic.description.split(" ")).upper() if values_enum := self._search_values_enum_by_name(possible_enum_name): return values_enum return None def _search_values_enum_by_name(self, char_uppercase_name: str) -> type[Enum] | None: # ignore = {'values', 'target', 'current', 'state', 'status', 'capabilities', 'units'} searched_char_name_set = set(word.lower() for word in char_uppercase_name.split("_")) for name, obj in inspect.getmembers(aiohomekit_consts, inspect.isclass): if not issubclass(obj, Enum): continue member_name_set = set(word.lower() for word in re.split(r"(? str: return " ".join([word.title() for word in name.split("_")]) ================================================================================ # FILE: majordom_homekit/models.py ================================================================================ """ MajorDom's Device and Parameter schemas expose an `integration_data` field for storing protocol-specific state. By default it is an untyped dict persisted as JSON. Integrations can subclass Device/DeviceState and Parameter/ParameterState to declare a typed schema for that field — Hub will then handle (de-)serialization automatically before passing Device instance to Controller's methods or when saving to the database. To make the Hub instantiate these custom types, the integration's Controller must override `device_type` and `parameter_type`. """ from typing import Any from uuid import UUID from aiohomekit.model.accessories import AccessoriesState from aiohomekit.model.typed_dicts import PairingData from majordom_integration_sdk.schemas.base import Base from majordom_integration_sdk.schemas.device import Device, DeviceState, ParameterState from majordom_integration_sdk.schemas.parameter import Parameter from pydantic import BaseModel, field_serializer, field_validator # Integration data class HKDeviceIntegrationData(Base): # NOTE: must be initializable without any arguments pairing_data: PairingData | None = None characteristics_cache: AccessoriesState | None = None # since AccessoriesState isn't a pydantic class, we need to implement (de)serialization model_config = { "arbitrary_types_allowed": True, } @field_serializer("characteristics_cache") def serialize_characteristics_cache(self, v: AccessoriesState, _info) -> dict[str, Any]: return v.as_dict() if v else {} @field_validator("characteristics_cache", mode="before") @classmethod def parse_characteristics_cache(cls, v: Any) -> AccessoriesState | None: if not v: return None if isinstance(v, AccessoriesState): return v if isinstance(v, dict): return AccessoriesState.from_dict(v) raise ValueError(f"Expected dict or AccessoriesState, got {type(v)}") class HKParameterIntegrationData(BaseModel): type: UUID aid: int iid: int # Overriding types for ease of use (shortcuts) class HKParameter(Parameter[HKParameterIntegrationData]): pass class HKParameterState(ParameterState[HKParameterIntegrationData]): pass class HKDevice(Device[HKDeviceIntegrationData]): integration_data: HKDeviceIntegrationData @property def hk_id(self) -> str: assert self.integration_data and self.integration_data.pairing_data return self.integration_data.pairing_data["AccessoryPairingID"].lower() class HKDeviceState(HKDevice, DeviceState[HKDeviceIntegrationData, HKParameterIntegrationData]): pass ================================================================================ # FILE: majordom_homekit/pairings_storage.py ================================================================================ """ TLDR: same purpose as characteristics_storage.py """ from collections.abc import Callable from contextlib import AbstractAsyncContextManager from aiohomekit.model.typed_dicts import HKDeviceID, PairingData from aiohomekit.storage.pairing_data_storage import PairingDataStorageProtocol from majordom_integration_sdk.repository import DeviceRepositoryProtocol from .mapper import HKMajorDomMapper from .models import HKDevice class HKPairingsStorageMajorDom(PairingDataStorageProtocol): def __init__( self, make_device_repository: Callable[[], AbstractAsyncContextManager[DeviceRepositoryProtocol]], mapper: HKMajorDomMapper, ): self.make_device_repository = make_device_repository self.mapper = mapper # aiohomekit.PairingsStorageType async def get_all(self) -> dict[HKDeviceID, PairingData]: # keyed by the HAP pairing id (HKDeviceID), matching HKCharacteristicsStorage.get_all # and what aiohomekit looks pairings up by — not the MajorDom device UUID. pairings: dict[HKDeviceID, PairingData] = {} async with self.make_device_repository() as device_repository: for device in await device_repository.get_all(as_=HKDevice): if pairing_data := device.integration_data.pairing_data: pairings[device.hk_id] = pairing_data return pairings async def get(self, id: str) -> PairingData | None: uuid = self.mapper.hap_id_to_uuid(id) async with self.make_device_repository() as device_repository: if (device := await device_repository.get(physical_id=uuid, as_=HKDevice)) and ( pairing_data := device.integration_data.pairing_data ): return pairing_data return None async def save(self, id: str, item: PairingData): uuid = self.mapper.hap_id_to_uuid(id) async with self.make_device_repository() as device_repository: if device := await device_repository.get(physical_id=uuid, as_=HKDevice): device.integration_data.pairing_data = item await device_repository.save(device) async def delete(self, id: HKDeviceID): # TODO: check usage uuid = self.mapper.hap_id_to_uuid(id) async with self.make_device_repository() as device_repository: if device := await device_repository.get(physical_id=uuid, as_=HKDevice): device.integration_data.pairing_data = None await device_repository.save(device) # TODO: check if should delete the device # Discussion: # this class is responsible solely for managing pairing data storage, and should # not be used for any other purpose. # However, we should ensure there is no case of aiohomekit disconnecting from the # device without notifying us. ================================================================================ # FILE: majordom_homekit/parameters_map.py ================================================================================ """ Supplemental metadata for parameters / characteristics that the API does not expose directly. Maps characteristic types to static values or callables that provide missing information — such as enum labels, value ranges, or units. """ parameters_map = {} ================================================================================ # FILE: majordom_homekit/readme.md ================================================================================ # HomeKit integration Bridges the Hub to HomeKit (HAP) accessories over IP, built on top of [`aiohomekit`](https://github.com/Jc2k/aiohomekit). `aiohomekit` owns the HAP protocol, discovery, pairing crypto, and the live connection; this integration adapts it to the Hub's `AbstractController` contract and persists HomeKit state in the Hub's database. ## Files | File | Responsibility | |---|---| | `controller.py` | `AbstractController` implementation — lifecycle, pairing, control, and the aiohomekit discovery/event delegates | | `mapper.py` | HAP ↔ MajorDom conversions: UUIDs (via the framework helpers), characteristic → parameter, formats/units/permissions/valid-values | | `models.py` | Typed `integration_data` schemas (`HKDevice`, `HKParameter`, …) | | `characteristics_storage.py` | Adapts aiohomekit's characteristics cache onto the Hub's `DeviceRepository` | | `pairings_storage.py` | Adapts aiohomekit's pairing-data storage onto the Hub's `DeviceRepository` | The two storage classes implement aiohomekit's storage protocols so that all HomeKit state lives in the Hub DB rather than aiohomekit's own files. They share the controller's single `HKMajorDomMapper` instance, so every HAP id maps to the same MajorDom UUID everywhere. ## Discovery & pairing - **Discovery** uses the Hub's shared Zeroconf service: aiohomekit browses `_hap._tcp` / `_hap._udp` using the `AsyncZeroconf` handed to it from `dependencies.zeroconf_discovery_service`, and calls back into `_aiohomekit_did_discover`. Already-paired accessories seen again trigger a reconnect; accessories paired to another controller are surfaced but not offered for pairing. - **Pairing** takes a HAP setup code (`CredentialsType.code`, `DDD-DD-DDD`). The credentials type is validated against the discovery's `expected_credentials_options` before pairing. ## Availability aiohomekit only pushes a *became-available* signal, never *became-unavailable*, so the controller polls each paired accessory's connection state (`_availability_loop`) and funnels both directions through `_set_availability`, which dedupes and emits the framework's `controller_did_connect_device` / `controller_did_lose_device`. ## Tests `tests/test_controllers/test_homekit/` runs against aiohomekit's in-process `AccessoryServer` (a fake accessory) — no real hardware needed. ## Not yet implemented - BLE discovery/pairing (aiohomekit supports it; the Hub wires IP only for now). - Multi-accessory bridges save only the first accessory's manufacturer. ================================================================================ # FILE: pyproject.toml ================================================================================ [project] name = "majordom-homekit" version = "0.1.10" description = "HomeKit integration for MajorDom — bridges HomeKit accessories into the MajorDom language." authors = [ { name = "Parker Industries" }, { name = "Ehor Lukianov @Hexa-Hexagon", email = "85293779+Hexa-Hexagon@users.noreply.github.com" }, { name = "Mark Parker @MarkParker5", email = "34688010+MarkParker5@users.noreply.github.com" }, ] readme = "README.md" license = "LicenseRef-PolyForm-Noncommercial-1.0.0" license-files = ["LICENSE"] keywords = ["majordom", "homekit", "hap", "apple", "smart-home", "home-automation", "iot", "integration", "accessory"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Home Automation", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.13", "Operating System :: OS Independent", ] requires-python = ">=3.13,<3.14" # upper bound comes from parker-aiohomekit dependencies = [ "majordom-integration-sdk (>=0.4.0,<1.0)", "parker-aiohomekit (>=4.1.2,<5.0.0)", ] [project.urls] Homepage = "https://majordom.io" Documentation = "https://docs.majordom.io/device-integration" Repository = "https://github.com/MajorDom-Systems/integration-homekit" Issues = "https://github.com/MajorDom-Systems/integration-homekit/issues" "Commercial licensing" = "https://parker-industries.org/partnership" "Parker Industries" = "https://parker-industries.org" [dependency-groups] dev = [ "majordom-integration-sdk[discovery] (>=0.4.0,<1.0)", # the tests browse over the SDK's DNS-SD provider "poethepoet (>=0.49.0,<1.0.0)", "ty", "ruff", "pip-audit", "pytest", "pytest-asyncio", "pytest-cov", "pytest-timeout", "pytest-repeat", "pytest-benchmark", "pytest-profiling", "pytest-resource-usage", "coverage", "pympler", "psutil", "faker", ] [build-system] requires = ["poetry-core>=2.0.0,<3.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] requires-poetry = ">=2.0" packages = [{ include = "majordom_homekit" }] [tool.pytest.ini_options] asyncio_mode = "auto" pythonpath = ["."] filterwarnings = ["once"] [tool.coverage.run] omit = ["tests/*"] [tool.ruff] line-length = 120 indent-width = 4 [tool.ruff.lint] select = ["E", "F", "UP", "B", "SIM", "I"] fixable = ["ALL"] [tool.ruff.format] quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "tests/*" = ["E402"] [tool.poe.tasks.install] shell = """ poetry install echo '#!/bin/sh\npoetry run poe check' > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit echo "Pre-commit hook installed." """ [tool.poe.tasks.check] shell = """ code=0 echo "\nRunning ruff lint:" poetry run ruff check --fix || code=1 echo "\nRunning ruff format:" poetry run ruff format || code=1 echo "\nRunning ty:" poetry run ty check || code=1 echo "\nRunning pytest:" poetry run pytest --cov=majordom_homekit --cov-report=xml || code=1 echo "\nRunning poetry build:" poetry build || code=1 echo "\nRunning poetry check:" poetry check || code=1 ${ci:+git diff --exit-code} || code=1 exit $code """ args = [{ name = "ci", type = "boolean" }] ================================================================================ # FILE: tests/conftest.py ================================================================================ """Unit tests for the HomeKit controller. These drive `HomeKitController` directly — via the SDK's test platform, against aiohomekit's in-process virtual accessory server with a mocked zeroconf — so they test the integration on its own, with no Hub. The Hub keeps the e2e coverage (Coordinator + API/ws). """ import socket import tempfile import threading from unittest.mock import AsyncMock, MagicMock, patch from uuid import UUID, uuid5 import pytest import pytest_asyncio from aiohomekit.model.accessories import Accessory from aiohomekit.model.characteristics import CharacteristicsTypes from aiohomekit.model.services import ServicesTypes from aiohomekit.testing.accessoryserver import AccessoryServer from aiohomekit.testing.mock_zeroconf import ( AsyncServiceBrowserStub, DNSCache, MockedAsyncServiceInfo, install_mock_service_info, ) from aiohomekit.testing.utils import next_available_port, wait_for_server_online from majordom_integration_sdk import Peripherals from majordom_integration_sdk.runtime.peripherals.providers.zeroconf import ZeroconfDiscoveryService from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from majordom_homekit import HomeKitController from majordom_homekit.models import HKDeviceIntegrationData, HKDeviceState HAP_TYPE_TCP = "_hap._tcp.local." ZEROCONF = "majordom_integration_sdk.runtime.peripherals.providers.zeroconf" # The physical id the accessory (pairing id 12:34:56:00:01:0A) maps to under HomeKit's slug — # uuid5(uuid5(namespace, "homekit"), "12345600010a"). Computed the same way the SDK does (":" dropped). INTEGRATION_UUID = uuid5(UUID(int=0), "homekit") PHYSICAL_ID = uuid5(INTEGRATION_UUID, "1234560001" + "0a") DEVICE_ID = UUID(int=100) # the Hub's own id of the device: never derived from the accessory ON_PARAM_ID = uuid5(PHYSICAL_ID, "1.9") BRIGHTNESS_PARAM_ID = uuid5(PHYSICAL_ID, "1.10") HK_ID = "12:34:56:00:01:0a" # aiohomekit's pairing key def provisional_device(pairing_data=None) -> HKDeviceState: """A device row as the Hub has it *before* handing control to the integration: identity and integration_data present, parameters still empty (the controller fills them).""" return HKDeviceState( id=DEVICE_ID, physical_id=PHYSICAL_ID, name="Testlicht", room_id=UUID(int=1), transport="IP", integration=HomeKitController.slug(), manufacturer="", parameters=[], integration_data=HKDeviceIntegrationData(pairing_data=pairing_data, characteristics_cache=None), ) def get_mock_service_info(port: int, is_paired: bool) -> MockedAsyncServiceInfo: desc = { b"c#": b"1", b"id": b"12:34:56:00:01:0A", b"md": b"Demoserver", b"s#": b"1", b"ci": b"5", b"sf": b"0" if is_paired else b"1", } return MockedAsyncServiceInfo( HAP_TYPE_TCP, f"Testlicht.{HAP_TYPE_TCP}", addresses=[socket.inet_aton("127.0.0.1")], port=port, properties=desc, weight=0, priority=0, ) @pytest.fixture(autouse=True) def mock_zeroconf(): with ( patch(f"{ZEROCONF}.AsyncServiceBrowser", AsyncServiceBrowserStub), patch(f"{ZEROCONF}.AsyncZeroconf") as mock_zc, patch("zeroconf.asyncio.AsyncServiceBrowser", AsyncServiceBrowserStub), patch("zeroconf.asyncio.AsyncZeroconf", mock_zc), patch("aiohomekit.controller.zeroconf.controller.AsyncServiceInfo", MockedAsyncServiceInfo), ): zc = mock_zc.return_value zc.register_service = AsyncMock() zc.async_close = AsyncMock() zeroconf = MagicMock(name="zeroconf_mock") zeroconf.cache = DNSCache() zeroconf.async_wait_for_start = AsyncMock() zeroconf.listeners = [AsyncServiceBrowserStub()] zc.zeroconf = zeroconf with patch("aiohomekit.testing.accessoryserver.Zeroconf", zc): yield zc @pytest.fixture def id_factory(): counter = 0 def _get_id(): nonlocal counter counter += 1 return counter return _get_id PAIRING_DATA = { "AccessoryPairingID": "12:34:56:00:01:0A", "AccessoryLTPK": "7986cf939de8986f428744e36ed72d86189bea46b4dcdc8d9d79a3e4fceb92b9", "AccessoryLTSK": "3d99f3e959a1f93af4056966f858074b2a1fdec1c5fd84a51ea96f9fa004156a", "iOSDeviceId": "decc6fa3-de3e-41c9-adba-ef7409821bfc", "iOSDeviceLTPK": "d708df2fbf4a8779669f0ccd43f4962d6d49e4274f88b1292f822edc3bcf8ed8", "iOSDeviceLTSK": "fa45f082ef87efc6c8c8d043d74084a3ea923a2253e323a7eb9917b4090c2fcc", "Connection": "IP", "AccessoryAddress": "127.0.0.1", } _ACCESSORY_CONFIG = b"""{ "accessory_ltpk": "7986cf939de8986f428744e36ed72d86189bea46b4dcdc8d9d79a3e4fceb92b9", "accessory_ltsk": "3d99f3e959a1f93af4056966f858074b2a1fdec1c5fd84a51ea96f9fa004156a", "accessory_pairing_id": "12:34:56:00:01:0A", "accessory_pin": "031-45-154", "c#": 1, "category": "Lightbulb", "host_ip": "127.0.0.1", "host_port": %port%, "name": "unittestLight", "peers": %peers%, "unsuccessful_tries": 0 }""" def _make_accessory_server(id_factory, port: int, peers: bytes, with_brightness: bool) -> AccessoryServer: config_file = tempfile.NamedTemporaryFile(delete=False) # noqa: SIM115 (outlives fn; AccessoryServer reads it by path) config_file.write(_ACCESSORY_CONFIG.replace(b"%port%", str(port).encode()).replace(b"%peers%", peers)) config_file.close() server = AccessoryServer(config_file.name, None) accessory = Accessory.create_with_info( aid=id_factory(), name="Testlicht", manufacturer="lusiardi.de", model="Demoserver", serial_number="0001", firmware_revision="0.1", ) bulb = accessory.add_service(ServicesTypes.LIGHTBULB) bulb.add_char(CharacteristicsTypes.ON, value=False) if with_brightness: bulb.add_char(CharacteristicsTypes.BRIGHTNESS, value=0) server.add_accessory(accessory) return server @pytest.fixture def repository(platform): """A unit of work on the in-memory device repository, scoped to HomeKit as the controller's.""" return lambda: platform.make_device_repository(HomeKitController.slug()) @pytest_asyncio.fixture async def zeroconf(mock_zeroconf): zeroconf_service = ZeroconfDiscoveryService() await zeroconf_service.start() # under mock_zeroconf, so async_zeroconf yields the mock yield zeroconf_service await zeroconf_service.stop() @pytest.fixture def platform(tmp_path): return build_test_platform(tmp_path) @pytest.fixture def output(): return RecordingControllerOutput() @pytest_asyncio.fixture async def controller(platform, zeroconf, output): controller = HomeKitController(platform) controller.output = output controller.peripherals = Peripherals({"mdns": zeroconf.endpoint}) await controller.start() yield controller await controller.stop() @pytest_asyncio.fixture async def unpaired_server(id_factory, mock_zeroconf): port = next_available_port() server = _make_accessory_server(id_factory, port, peers=b"{}", with_brightness=False) thread = threading.Thread(target=server.serve_forever, daemon=True) service_info = get_mock_service_info(port, is_paired=False) async def start(): thread.start() await wait_for_server_online(port) assert not server.data.is_paired return server with install_mock_service_info(mock_zeroconf, service_info): yield start server.shutdown() thread.join() @pytest_asyncio.fixture async def paired_accessory(id_factory, repository): """A pre-paired accessory + a HomeKit device seeded into the repository the way the Hub would have after pairing, not advertised over zeroconf.""" port = next_available_port() peers = ( b'{"decc6fa3-de3e-41c9-adba-ef7409821bfc": {"admin": true,' b' "key": "d708df2fbf4a8779669f0ccd43f4962d6d49e4274f88b1292f822edc3bcf8ed8"}}' ) server = _make_accessory_server(id_factory, port, peers=peers, with_brightness=True) pairing_data = {**PAIRING_DATA, "AccessoryPort": port} async with repository() as repo: await repo.save(provisional_device(pairing_data)) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() await wait_for_server_online(port) assert server.data.is_paired yield server, pairing_data server.shutdown() thread.join() @pytest.fixture def paired_server(paired_accessory, mock_zeroconf): """The pre-paired accessory, advertised over zeroconf.""" _, pairing_data = paired_accessory with install_mock_service_info(mock_zeroconf, get_mock_service_info(pairing_data["AccessoryPort"], is_paired=True)): yield paired_accessory ================================================================================ # FILE: tests/test_controller.py ================================================================================ """Unit tests driving HomeKitController directly (no Hub). Each asserts on both sides: what the controller reported back via the recording output, and what actually happened on the virtual accessory / in the repository. """ import asyncio from typing import Any from unittest.mock import ANY, AsyncMock, patch from uuid import UUID as _UUID import pytest from aiohomekit.controller.zeroconf.ip import IpPairing from aiohomekit.exceptions import AccessoryDisconnectedError from aiohomekit.model.characteristics import CharacteristicKey from aiohomekit.model.transport_type import TransportType from aiohomekit.testing.mock_zeroconf import AsyncServiceBrowserStub, DNSCache, MockedAsyncServiceInfo from aiohomekit.testing.utils import next_available_port from conftest import ( BRIGHTNESS_PARAM_ID, DEVICE_ID, HAP_TYPE_TCP, HK_ID, ON_PARAM_ID, PAIRING_DATA, PHYSICAL_ID, provisional_device, ) from majordom_integration_sdk import DeviceIdTakenError, DeviceUnreachableError, Peripherals from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import CredentialsType, ProvidedCredentials from majordom_integration_sdk.testing import FakeZeroconf from majordom_homekit import HomeKitController from majordom_homekit.models import ( HKDevice, HKDeviceIntegrationData, HKDeviceState, HKParameter, HKParameterIntegrationData, ) UUID_ONE = _UUID(int=1) CONNECT_TIMEOUT = "aiohomekit.controller.zeroconf.ip.pairing.asyncio_timeout" # its 10 s wait for an accessory async def _wait_for(predicate, timeout: float = 2.0): async with asyncio.timeout(timeout): while not predicate(): await asyncio.sleep(0.02) def _reconnect_loops() -> list[asyncio.Task[Any]]: return [task for task in asyncio.all_tasks() if "_reconnect" in repr(task.get_coro())] async def _cut_off(server, pairing): """The accessory's HAP server is gone (unplugged, hung), its mDNS records are not.""" await _wait_for(lambda: pairing.is_connected) server.shutdown() server.server_close() pairing.connection.transport.close() await _wait_for(lambda: not pairing.is_connected) def test_has_no_discoveries_before_it_starts(platform): # The runtime starts it only once its zeroconf runs; the Hub may list discoveries before. assert HomeKitController(platform).discoveries == {} async def test_stops_after_a_start_that_failed_early(platform): # The runtime stops it after any failed start; here its zeroconf was never bound controller = HomeKitController(platform) with pytest.raises(RuntimeError, match="zeroconf"): await controller.start() await controller.stop() async def test_refuses_a_zeroconf_that_isnt_running(platform): controller = HomeKitController(platform) controller.peripherals = Peripherals({"mdns": FakeZeroconf().endpoint}) # holds no AsyncZeroconf with patch("aiohomekit.controller.relay.controller.AsyncZeroconf") as own: # what aiohomekit opens instead own.return_value.zeroconf.cache = DNSCache() own.return_value.zeroconf.listeners = [AsyncServiceBrowserStub()] own.return_value.async_close = AsyncMock() with pytest.raises(RuntimeError, match="zeroconf"): await controller.start() await controller.stop() assert not own.called async def test_restarts_on_the_same_instance(paired_server, controller, output, repository): # what the runtime does on a restart, a retry or zeroconf coming back await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) before = controller._aiohomekit.pairings[HK_ID] await controller.stop() output.connected_devices.clear() await controller.start() await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) assert controller._aiohomekit.pairings[HK_ID] is not before async with repository() as repo: device = await repo.state(physical_id=PHYSICAL_ID, as_=HKDeviceState) assert device is not None ids = [p.id for p in device.parameters] assert len(ids) == len(set(ids)) async def test_stop_closes_the_accessory_sessions(paired_server, controller, output): await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) pairing = controller._aiohomekit.pairings[HK_ID] await _wait_for(lambda: pairing.is_connected) await controller.stop() assert not pairing.is_connected # each restart would open one more of the accessory's few sessions async def test_starts_with_a_paired_accessory_offline(platform, zeroconf, output, repository): async with repository() as repo: await repo.save(provisional_device({**PAIRING_DATA, "AccessoryPort": next_available_port()})) # none there controller = HomeKitController(platform) controller.output = output controller.peripherals = Peripherals({"mdns": zeroconf.endpoint}) async with asyncio.timeout(2): # its reachability is the device's state, not the start's await controller.start() await controller.stop() assert PHYSICAL_ID not in output.connected_devices async def test_discovers_unpaired_accessory(unpaired_server, controller, output): await unpaired_server() await _wait_for(lambda: bool(output.received_discoveries)) assert PHYSICAL_ID in controller.discoveries discovery = controller.discoveries[PHYSICAL_ID] assert discovery.integration == "homekit" assert discovery.transport == "IP" assert discovery.device_name == "Testlicht" assert CredentialsType.code in discovery.expected_credentials_options assert output.received_discoveries[-1].id == PHYSICAL_ID CODE = ProvidedCredentials(type=CredentialsType.code, value="031-45-154") async def test_pairs_a_discovered_device(unpaired_server, controller, output, repository): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) discovery = controller.discoveries[PHYSICAL_ID] device = await controller.pair_device(discovery, provisional_device(), CODE) # device side: the accessory is now paired assert server.data.is_paired # the draft comes back filled: pairing data, data model, parameters assert device.physical_id == PHYSICAL_ID and device.id == DEVICE_ID and device.available assert device.name == "Testlicht" # the user's fields stay assert device.integration_data.pairing_data assert device.integration_data.pairing_data["AccessoryPairingID"] == "12:34:56:00:01:0A" assert device.integration_data.characteristics_cache assert ON_PARAM_ID in {p.id for p in device.parameters} assert PHYSICAL_ID in controller.discoveries # until the Hub saves it: a rolled back one pairs again # nothing is reported or saved: the Hub does both after its write assert output.connected_devices == [] and output.events == [] async with repository() as repo: assert await repo.get(physical_id=PHYSICAL_ID, as_=HKDevice) is None async def test_pairing_a_picked_record_takes_the_discovery_id_and_drops_its_stale_pairing(unpaired_server, controller): await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) picked = provisional_device({**PAIRING_DATA, "AccessoryPairingID": "aa:aa:aa:aa:aa:aa"}).model_copy( update={"id": _UUID(int=7), "physical_id": _UUID(int=8)} ) device = await controller.pair_device(controller.discoveries[PHYSICAL_ID], picked, CODE) assert device.physical_id == PHYSICAL_ID and device.id == _UUID(int=7) assert device.integration_data.pairing_data["AccessoryPairingID"] == "12:34:56:00:01:0A" async def test_pairs_an_accessory_slower_than_a_second(unpaired_server, controller): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) hap_discovery = controller._hap_discoveries[PHYSICAL_ID] start_pairing = hap_discovery.start_pairing async def slow_start_pairing(): # SRP takes seconds on a slow accessory MCU await asyncio.sleep(1.2) return await start_pairing() with patch.object(hap_discovery, "start_pairing", slow_start_pairing): discovery = controller.discoveries[PHYSICAL_ID] await controller.pair_device(discovery, provisional_device(), CODE) assert server.data.is_paired async def test_a_taken_id_refuses_before_the_pair_setup(unpaired_server, controller): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) taken = DeviceIdTakenError(PHYSICAL_ID, _UUID(int=9), "Other", True) with ( patch.object(controller, "check_device_id", AsyncMock(side_effect=taken)) as check, pytest.raises(DeviceIdTakenError), ): await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) check.assert_awaited_once_with(PHYSICAL_ID, ANY) assert not server.data.is_paired # an irreversible setup would have locked the accessory async def _hub_saves(controller, repository, device: HKDeviceState): """What the Hub does with a returned device: save it, then fetch it.""" async with repository() as repo: await repo.save(device) await controller.fetch(HKDevice.model_validate(device.model_dump())) async def test_rolling_back_a_failure_after_the_pair_setup_frees_the_accessory(unpaired_server, controller, repository): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) draft = provisional_device() fetch = AsyncMock(side_effect=AccessoryDisconnectedError("gone")) with ( patch.object(IpPairing, "fetch_accessories_and_characteristics", fetch), pytest.raises(AccessoryDisconnectedError), ): await controller.pair_device(controller.discoveries[PHYSICAL_ID], draft, CODE) assert server.data.is_paired await controller.unpair( HKDevice.model_validate(draft.model_dump()) ) # the Hub's rollback, the draft being all it has assert not server.data.is_paired and HK_ID not in controller._aiohomekit.pairings device = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) await _hub_saves(controller, repository, device) assert server.data.is_paired and PHYSICAL_ID not in controller.discoveries async def test_rolling_back_an_unsaved_pairing_frees_the_accessory(unpaired_server, controller, repository): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) draft = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) await controller.unpair(draft) # the Hub failed to save it assert not server.data.is_paired device = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) await _hub_saves(controller, repository, device) assert server.data.is_paired async def test_rolling_back_an_unreachable_pairing_forgets_it_here(unpaired_server, controller): await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) draft = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) unreachable = AsyncMock(side_effect=AccessoryDisconnectedError("gone")) with patch.object(controller._aiohomekit, "remove_pairing", unreachable), pytest.raises(DeviceUnreachableError): await controller.unpair(draft) assert PHYSICAL_ID in controller.discoveries async def test_rolling_back_a_draft_before_the_pair_setup_does_nothing(unpaired_server, controller): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) draft = provisional_device() draft.integration_data = HKDeviceIntegrationData() await controller.unpair(draft) assert not server.data.is_paired async def test_a_retry_confirms_the_pairing_an_earlier_attempt_left(unpaired_server, controller, repository): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) # no rollback device = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) assert device.integration_data.pairing_data["AccessoryPairingID"] == "12:34:56:00:01:0A" await _hub_saves(controller, repository, device) assert server.data.is_paired async def test_rolling_back_twice_does_nothing_more(unpaired_server, controller): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) draft = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) await controller.unpair(draft) await controller.unpair(draft) assert not server.data.is_paired async def test_pair_device_rejects_wrong_credentials_type(unpaired_server, controller): await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) discovery = controller.discoveries[PHYSICAL_ID] with pytest.raises(ValueError): await controller.pair_device( discovery, provisional_device(), ProvidedCredentials(type=CredentialsType.qr, value="x") ) async def test_drops_its_discoveries_when_it_stops(unpaired_server, controller): server = await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) discovery = controller.discoveries[PHYSICAL_ID] await controller.stop() assert controller.discoveries == {} # a discovery the Hub still holds can't pair through the stopped controller with pytest.raises(KeyError): await controller.pair_device(discovery, provisional_device(), CODE) assert not server.data.is_paired async def test_stop_cancels_a_discovery_still_being_handled(unpaired_server, controller, output): await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) (discovery,) = controller._aiohomekit.discoveries.values() output.received_discoveries.clear() controller._aiohomekit_did_discover(controller._aiohomekit, discovery) # aiohomekit's callback, handled in a task await controller.stop() await asyncio.sleep(0.1) assert output.received_discoveries == [] and controller.discoveries == {} async def test_ignores_a_discovery_aiohomekit_resolves_after_the_stop(unpaired_server, controller, output): await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) output.received_discoveries.clear() class SlowInfo(MockedAsyncServiceInfo): async def async_request(self, *args, **kwargs): await asyncio.sleep(0.3) # the accessory answers late; aiohomekit waits up to 3 s return await super().async_request(*args, **kwargs) # what aiohomekit spawns, untracked, for a zeroconf update whose records aren't all cached transport = controller._aiohomekit._transports[TransportType.IP] info = SlowInfo(HAP_TYPE_TCP, f"Testlicht.{HAP_TYPE_TCP}") resolving = asyncio.create_task(transport._handle_discovery_service(info)) await asyncio.sleep(0.05) await controller.stop() await resolving await asyncio.sleep(0.1) assert output.received_discoveries == [] and controller.discoveries == {} async def test_logs_what_fails_in_the_background(controller, output, caplog): output.controller_did_receive_events = AsyncMock(side_effect=RuntimeError("the Hub is gone")) controller._run_handle_accessory_response(PAIRING_DATA["AccessoryPairingID"], {(1, 9): {"value": True}}) await _wait_for(lambda: output.controller_did_receive_events.await_count == 1) await asyncio.sleep(0) assert any(r.name == "majordom_homekit.controller" and "the Hub is gone" in r.getMessage() for r in caplog.records) def _brightness_parameter() -> HKParameter: return HKParameter( id=BRIGHTNESS_PARAM_ID, name="Brightness", data_type="integer", unit="plain", role="control", visibility="user", integration_data=HKParameterIntegrationData(type=UUID_ONE, aid=1, iid=10), ) def _hk_device(pairing_data) -> HKDevice: return HKDevice( id=DEVICE_ID, physical_id=PHYSICAL_ID, name="Testlicht", room_id=UUID_ONE, transport="IP", integration=HomeKitController.slug(), manufacturer="lusiardi.de", integration_data=HKDeviceIntegrationData(pairing_data=pairing_data, characteristics_cache=None), ) async def test_unpairs_a_device(paired_server, controller, output, repository): server, pairing_data = paired_server await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) assert server.data.is_paired await controller.unpair(_hk_device(pairing_data)) assert not server.data.is_paired # the Hub's soft delete keeps the row: a pairing left in it would be loaded again on the next start async with repository() as repo: device = await repo.get(physical_id=PHYSICAL_ID, as_=HKDevice) assert device is not None and device.integration_data.pairing_data is None async def test_forgets_an_accessory_it_cant_reach_to_unpair(paired_server, controller, output, repository, caplog): server, pairing_data = paired_server await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) await _cut_off(server, controller._aiohomekit.pairings[HK_ID]) # the bulb broke or went in the bin with patch(CONNECT_TIMEOUT, lambda _: asyncio.timeout(0.3)), pytest.raises(DeviceUnreachableError): await controller.unpair(_hk_device(pairing_data)) # the user deletes it in the app assert "reset" in caplog.text assert _reconnect_loops() == [] # its session doesn't come back if the bulb does async with repository() as repo: device = await repo.get(physical_id=PHYSICAL_ID, as_=HKDevice) assert device is not None assert device.integration_data.pairing_data is None and device.integration_data.characteristics_cache is None async def test_forgets_an_accessory_that_no_longer_knows_it(paired_server, controller, output, repository, caplog): server, pairing_data = paired_server await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) pairing = controller._aiohomekit.pairings[HK_ID] server.data.remove_peer(PAIRING_DATA["iOSDeviceId"].encode()) # factory-reset: it answers, but not to us pairing.connection.transport.close() await _wait_for(lambda: not pairing.is_connected) await controller.unpair(_hk_device(pairing_data)) # the user deletes it in the app assert "AuthenticationError" in caplog.text assert _reconnect_loops() == [] async with repository() as repo: device = await repo.get(physical_id=PHYSICAL_ID, as_=HKDevice) assert device is not None assert device.integration_data.pairing_data is None and device.integration_data.characteristics_cache is None async def test_pairs_again_after_an_unpair(unpaired_server, controller): await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) device = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) await controller.unpair(device) assert controller._characteristics_observers == {} (discovery,) = controller._aiohomekit.discoveries.values() await controller._async_aiohomekit_did_discover(controller._aiohomekit, discovery) # offered again again = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) assert again.physical_id == PHYSICAL_ID # it keeps its HAP id, so its physical id async def test_sends_a_command_to_the_device(paired_server, controller, output): _, pairing_data = paired_server await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) value = 42 brightness = _brightness_parameter() await controller.send_command( DeviceCommand(device_id=DEVICE_ID, parameter_id=BRIGHTNESS_PARAM_ID, value=value), _hk_device(pairing_data), brightness, ) # device side: the accessory actually took the new brightness got = await IpPairing(pairing_data).get_characteristics([CharacteristicKey(1, 10)]) assert got == {CharacteristicKey(1, 10): {"value": value}} async def test_a_command_the_device_refuses_fails(paired_server, controller, output): _, pairing_data = paired_server await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) with pytest.raises(ValueError, match="1.10"): await controller.send_command( DeviceCommand(device_id=DEVICE_ID, parameter_id=BRIGHTNESS_PARAM_ID, value=1000), # brightness is 0-100 _hk_device(pairing_data), _brightness_parameter(), ) async def test_names_a_device_whose_pairing_isnt_loaded(controller): device = _hk_device(PAIRING_DATA) # e.g. its stored pairing failed to load with pytest.raises(RuntimeError, match=HK_ID): await controller.fetch(device) with pytest.raises(RuntimeError, match=HK_ID): command = DeviceCommand(device_id=DEVICE_ID, parameter_id=BRIGHTNESS_PARAM_ID, value=1) await controller.send_command(command, device, _brightness_parameter()) async def test_reports_the_good_values_of_a_batch_with_a_bad_status(controller, output, caplog): await controller._handle_accessory_response( PAIRING_DATA["AccessoryPairingID"], {(1, 9): {"value": True}, (1, 10): {"status": -70402}} ) assert [(e.parameter_id, e.value) for e in output.events] == [(ON_PARAM_ID, True)] assert '"1.10"' in caplog.text async def test_reports_device_state_as_events_on_connect(paired_server, controller, output): # The device -> Hub reporting path: on connecting to a paired accessory the controller # reads its characteristics and reports each as a DeviceParameterChange. (This is what the # Hub's e2e test_events actually exercises — it uses value == the initial, so it never # distinguished a pushed change; the mock accessory server doesn't deliver async pushes # to the observer in-process. The reporting *channel* is what matters and is covered here.) _, pairing_data = paired_server await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) await _wait_for(lambda: any(e.parameter_id == ON_PARAM_ID for e in output.events)) on_events = [e for e in output.events if e.parameter_id == ON_PARAM_ID] assert on_events[-1].value is False # the accessory's ON characteristic starts False async def test_reports_an_accessory_connected_only_once_it_answers(paired_server, controller, output): server, _ = paired_server await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) await _cut_off(server, controller._aiohomekit.pairings[HK_ID]) await controller._set_availability(PHYSICAL_ID, False) # what the availability poll reports within 30 s output.connected_devices.clear() (discovery,) = controller._aiohomekit.discoveries.values() with patch(CONNECT_TIMEOUT, lambda _: asyncio.timeout(0.3)), pytest.raises(AccessoryDisconnectedError): await controller._async_aiohomekit_did_discover(controller._aiohomekit, discovery) # its mDNS answers on assert PHYSICAL_ID not in output.connected_devices async def test_reports_a_pushed_change_once_however_often_rediscovered(paired_server, controller, output): await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) (discovery,) = controller._aiohomekit.discoveries.values() for _ in range(3): # each zeroconf update of the accessory (s#, c#, address) reports it again await controller._async_aiohomekit_did_discover(controller._aiohomekit, discovery) pairing = controller._aiohomekit.pairings[HK_ID] pairing._callback_characteristic_changed({CharacteristicKey(1, 9): {"value": True}}) # what a push from it runs await _wait_for(lambda: any(e.parameter_id == ON_PARAM_ID and e.value is True for e in output.events)) await asyncio.sleep(0.1) assert [e.value for e in output.events if e.parameter_id == ON_PARAM_ID].count(True) == 1 async def test_saves_the_data_model_without_duplicating_parameters(paired_server, controller, output, repository): await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) accessories = controller._aiohomekit.pairings[HK_ID].accessories_state for _ in range(2): # aiohomekit saves it on every newer c# of the accessory, e.g. after each start await controller.hk_char_storage.save(HK_ID, accessories) async with repository() as repo: device = await repo.state(physical_id=PHYSICAL_ID, as_=HKDeviceState) assert device is not None ids = [p.id for p in device.parameters] assert ON_PARAM_ID in ids and len(ids) == len(set(ids)) async def test_fetch_reports_the_device_state(paired_accessory, controller, output): # Not advertised: aiohomekit loads stored pairings without connecting, so this read fetches the data model first _, pairing_data = paired_accessory await controller.fetch(_hk_device(pairing_data)) assert any(e.parameter_id == ON_PARAM_ID and e.value is False for e in output.events) async def test_fetch_after_pairing_subscribes_once(unpaired_server, controller, output): await unpaired_server() await _wait_for(lambda: PHYSICAL_ID in controller.discoveries) device = await controller.pair_device(controller.discoveries[PHYSICAL_ID], provisional_device(), CODE) pairing = controller._aiohomekit.pairings[HK_ID] assert pairing not in controller._characteristics_observers # pair_device reports nothing, so it observes nothing with patch.object(pairing, "subscribe_characteristics", wraps=pairing.subscribe_characteristics) as subscribe: await controller.fetch(device) await controller.fetch(device) # idempotent assert subscribe.await_count == 1 assert pairing in controller._characteristics_observers assert output.connected_devices == [] # the Hub fired the connect itself assert any(e.parameter_id == ON_PARAM_ID and e.value is False for e in output.events) async def test_identify(paired_server, controller, output): _, pairing_data = paired_server await _wait_for(lambda: PHYSICAL_ID in output.connected_devices) # smoke: identify reaches the accessory without error await controller.identify(_hk_device(pairing_data)) ================================================================================ # FILE: tests/test_peripherals.py ================================================================================ """What the package exports, run as the Hub runs it: under the SDK's runtime, beside its zeroconf.""" import asyncio from collections.abc import Callable from pathlib import Path from conftest import PAIRING_DATA, provisional_device from majordom_integration_sdk import Platform from majordom_integration_sdk.capabilities import ZEROCONF from majordom_integration_sdk.runtime import PeripheralState, Runtime, StatusKind from majordom_integration_sdk.runtime.peripherals.providers.zeroconf import ZeroconfDiscoveryService from majordom_integration_sdk.testing import RecordingRuntimeOutput import majordom_homekit from majordom_homekit import HomeKitController async def _wait_for(predicate: Callable[[], bool], timeout: float = 2.0): async with asyncio.timeout(timeout): while not predicate(): await asyncio.sleep(0.02) def _run_beside_zeroconf(platform: Platform, data: Path) -> tuple[Runtime, ZeroconfDiscoveryService, HomeKitController]: (controller,) = majordom_homekit.peripherals(platform) assert isinstance(controller, HomeKitController) zeroconf = ZeroconfDiscoveryService() return ( Runtime(data, [zeroconf, controller], platform=platform, output=RecordingRuntimeOutput()), zeroconf, controller, ) async def test_runs_the_controller_once_zeroconf_serves(platform, tmp_path): runtime, zeroconf, controller = _run_beside_zeroconf(platform, tmp_path / "data") await runtime.start() try: await _wait_for(lambda: runtime.status(controller).state == PeripheralState.RUNNING) assert controller.platform is platform assert controller.key == "homekit" assert controller.peripherals.instance(ZEROCONF) is zeroconf finally: await runtime.stop() async def test_waits_while_zeroconf_is_disabled(platform, tmp_path): runtime, zeroconf, controller = _run_beside_zeroconf(platform, tmp_path / "data") await runtime.start() try: await _wait_for(lambda: runtime.status(controller).state == PeripheralState.RUNNING) await runtime.disable(zeroconf) await _wait_for(lambda: runtime.status(controller).kind == StatusKind.NEEDS_UNBOUND) assert runtime.status(controller).state == PeripheralState.WAITING await runtime.enable(zeroconf) await _wait_for(lambda: runtime.status(controller).state == PeripheralState.RUNNING) finally: await runtime.stop() async def test_starts_again_on_a_restarted_zeroconf(platform, tmp_path): # its AsyncZeroconf closes with it: HomeKit must browse on the new one runtime, zeroconf, controller = _run_beside_zeroconf(platform, tmp_path / "data") await runtime.start() try: await _wait_for(lambda: runtime.status(controller).state == PeripheralState.RUNNING) before = controller._aiohomekit await runtime.restart(zeroconf) await _wait_for( lambda: ( runtime.status(controller).state == PeripheralState.RUNNING and controller._aiohomekit_controller not in (None, before) ) ) finally: await runtime.stop() async def test_keeps_running_beside_an_accessory_that_dropped_us(unpaired_server, platform, repository, tmp_path): server = await unpaired_server() # answers, but holds no pairing for us any more async with repository() as repo: await repo.save(provisional_device({**PAIRING_DATA, "AccessoryPort": server.data.port})) runtime, _, controller = _run_beside_zeroconf(platform, tmp_path / "data") await runtime.start() try: await _wait_for(lambda: runtime.status(controller).state == PeripheralState.RUNNING) await asyncio.sleep(0.5) # it rediscovers the accessory, which refuses to verify the pairing assert runtime.status(controller).state == PeripheralState.RUNNING finally: await runtime.stop() # integration-esphome — full source # repo: https://github.com/MajorDom-Systems/integration-esphome branch: master commit: 0b9028e944ba22dcb4c225829f34af1b14b8d60e # generated: 2026-11-16 — AUTO-GENERATED, do not edit by hand ## File tree .gitignore LICENSE README.md majordom_esphome/__init__.py majordom_esphome/bluetooth.py majordom_esphome/connection.py majordom_esphome/controller.py majordom_esphome/esphome_spec.py majordom_esphome/generic.py majordom_esphome/improv.py majordom_esphome/mapper.py majordom_esphome/models.py majordom_esphome/thread_provisioning.py pyproject.toml tests/__init__.py tests/conftest.py tests/helpers.py tests/test_addresses.py tests/test_bluetooth.py tests/test_catalogue.py tests/test_commands.py tests/test_controller.py tests/test_discovery.py tests/test_encryption.py tests/test_enum_commands.py tests/test_fallback.py tests/test_improv.py tests/test_key_provisioning.py tests/test_lifecycle.py tests/test_pairing.py tests/test_state.py tests/test_thread_provisioning.py tests/test_unhosted_fields.py tests/virtual/__init__.py tests/virtual/build.py tests/virtual/catalogue.py tests/virtual/mdns.py tests/virtual/runner.py tests/virtual/sketches/encrypted.yaml tests/virtual/sketches/extras.yaml tests/virtual/sketches/keyless.yaml tests/virtual/sketches/virtual.yaml ================================================================================ # FILE: .gitignore ================================================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[codz] *$py.class # C extensions *.so # Distribution / packaging build/ dist/ *.egg-info/ *.egg # Unit test / coverage reports .coverage .coverage.* coverage.xml htmlcov/ .pytest_cache/ .hypothesis/ # Environments .env .envrc .venv env/ venv/ # Poetry # poetry.lock # uncomment for applications, keep commented for libraries # Type checkers .mypy_cache/ .dmypy.json .pyre/ .pytype/ # Tools .ruff_cache/ .ropeproject # mkdocs (only relevant if you kept mkdocs.yml + docs/) /site .cache/ # IDEs .idea/ .vscode/ # OS .DS_Store Thumbs.db # Virtual ESPHome device build output (esphome also writes its own .gitignore next to the sketches) .esphome tests/virtual/sketches/.gitignore # Generated virtual nodes of the entity catalogue tests/virtual/nodes/ # The dev runner's settings and keys .majordom-dev/ ================================================================================ # FILE: LICENSE ================================================================================ # PolyForm Noncommercial License 1.0.0 ## Acceptance In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses. ## Copyright License The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license). ## Distribution License The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license). ## Notices You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example: > Required Notice: Copyright Yoyodyne, Inc. (http://example.com) ## Changes and New Works License The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose. ## Patent License The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software. ## Noncommercial Purposes Any noncommercial purpose is a permitted purpose. ## Personal Uses Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose. ## Noncommercial Organizations Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding. ## Fair Use You may have "fair use" rights for the software under the law. These terms do not limit them. ## No Other Rights These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses. ## Patent Defense If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company. ## Violations The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately. ## No Liability ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*** ## Definitions The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms. **You** refers to the individual or entity agreeing to these terms. **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. **Your licenses** are all the licenses granted to you for the software under these terms. **Use** means anything you do with the software requiring one of your licenses. ================================================================================ # FILE: README.md ================================================================================ Part of MajorDom — the next-gen smart home # integration-esphome A [MajorDom](https://majordom.io) integration — bridges **ESPHome** devices into the MajorDom language. Built for the **MajorDom Hub**, but it doesn't need it: this is a standalone, standardized library for ESPHome that you can use on its own (see **Run it standalone** below). Built on the [MajorDom Integration SDK](https://github.com/MajorDom-Systems/integration-sdk). The entry point is `ESPHomeController` (`majordom_esphome/controller.py`), which the Hub — or the SDK's dev runner — instantiates and drives through its lifecycle: discovery → pairing → commands → teardown. - **Other protocols:** browse the [MajorDom integrations](https://github.com/orgs/MajorDom-Systems/repositories?q=integration-). - **Create your own:** start from the [integration template](https://github.com/MajorDom-Systems/integration-template). ## Documentation Full integration-author docs — the controller lifecycle, data models, storing data, discovery, and a worked example — live at **[docs.majordom.io](https://docs.majordom.io/device-integration)**. ## Development ```sh poetry install && poetry run poe install ``` | Task | Description | |------|-------------| | `poe check` | Full quality pipeline (ruff, ty, pytest, poetry build/check) | | `poe check --ci` | Same, plus `git diff --exit-code` | Work lands on `develop`; `master` is protected and released via **Actions → Release**. Tests drive the controller with the SDK's test doubles against a **virtual ESPHome device**: a native binary built from `tests/virtual/sketches/*.yaml` (ESPHome `host` platform, one entity of every supported kind, with and without API encryption) — no physical hardware required. The binaries are built on first use and need the ESPHome CLI: ```sh pipx install esphome && poetry run python -m tests.virtual.build ``` Host nodes have no BLE, so the Improv tests run the real client against a scripted Improv GATT service. End-to-end tests on real hardware are kept in a private repository. ## Run it standalone (without the Hub) `majordom-esphome` is a standalone library — import it into your own app, or run **just this integration** interactively (discover, pair, control, and inspect devices from a prompt) with no Hub. It needs ESPHome devices reachable on the local network (Wi-Fi or Ethernet). See **[Standalone mode](https://docs.majordom.io/device-integration/standalone)** for the interactive CLI, watch mode, and the programmatic API. ## Supported transports The integration speaks the **ESPHome native API** over TCP (port `6053` by default), with or without Noise encryption. Devices must have the `api:` component enabled in their YAML; an API-less device (e.g. web server only) is not supported. ## About this integration - **Protocol / platform:** ESPHome native API (`aioesphomeapi`). - **Transport(s):** TCP/IP (Wi-Fi, Ethernet); devices are found via mDNS (`_esphomelib._tcp`). Nodes without Wi-Fi yet are found over BLE (Improv) and set up onto the Hub's Wi-Fi (see below). - **Supported entities:** light (on/off, brightness, RGB), switch, sensor, binary sensor, text sensor, number, select, button, cover (position), fan (on/off), climate (mode, targets). Every other entity the library knows (lock, valve, text, alarm panel, update, ...) is mapped generically from the library's own types (see below); cameras and events are skipped. - **Credentials needed to pair:** the API encryption key (type `secret`) if the node has one configured in its YAML; otherwise none. - **Encryption keys:** a node with `api: encryption:` but no `key:` (it announces `api_encryption_supported`) is given a key of the integration's own at pairing: generated, stored on the device record, then set with `noise_encryption_set_key` over a Noise session with the well-known all-zeros PSK (in plaintext on firmware that does not announce `api_provisioning=zero-psk`). From then on the node accepts only that key, so the user never types one; the key is stored before it is set, so a failed attempt (or a Hub restart in between) does not lock the Hub out. A node without `encryption:` still pairs in plaintext, with a warning in the log to turn encryption on. - **Wi-Fi setup over BLE (Improv):** a node built with `esp32_improv` (`improv_ble` from ESPHome 2026.11) and no Wi-Fi networks advertises the Improv service; it is offered as a `ble` discovery named (and identified) by its node name. Pairing it gives it the Hub's Wi-Fi with [`py-improv-ble-client`](https://github.com/home-assistant-libs/py-improv-ble-client) (asking the user to press its button when it has an `authorizer`), waits for it to announce itself over mDNS (matched by the name it advertised, which ESPHome cuts to 20 characters), then pairs it like any other node, keyless key included. The Hub's device takes the node's own identity (`pair_device` returns it). The Wi-Fi comes from the Hub's `wifi_credentials` dependency (SDK `feature/wifi-credentials`); a Hub without one cannot set nodes up over BLE. ### Required harness - **Hardware adapters:** none — ESPHome devices are self-contained and connect over the network. - **Third-party software services:** none — the integration speaks directly to ESPHome devices. - **OS / permissions:** network access to the ESPHome devices (same LAN or routable subnet); mDNS/SSDP may be required for discovery depending on configuration. ### Protocol stack (OSI) Every integration is two things stacked: the **MajorDom integration layer** — mapping the protocol to MajorDom's domain model — sitting on top of the **protocol stack** it bridges. The top layer is *always this repo*. | Layer | Protocol | Implemented by | |-------|----------|----------------| | **MajorDom integration** | maps ESPHome ↔ MajorDom domain model | **this repo, always** | | Application (7) | ESPHome Native API | [`aioesphomeapi`](https://github.com/esphome/aioesphomeapi) | | Transport (4) | TCP | OS / device firmware | | Network (3) | IP (IPv4 / IPv6) | OS / device firmware | | Data link / Physical (1–2) | Wi-Fi (802.11) or Ethernet | device hardware | ### Progress Two checklists. An item is ticked only when a test in `tests/` proves it. **Implementation** — makes the integration functional: - [x] Discovery service registered via `self.dependencies.zeroconf_discovery_service`; the cancel closure is called in `stop` - [x] Discovery listener methods fire when nodes appear, change and leave, and the controller calls the matching `self.dependencies.output.controller_did_*_discovery` - [x] Paired devices reconnect when the Hub restarts (`controller_did_connect_device` is called) - [x] `start_pairing_window`: not needed, mDNS and BLE discovery are always on (SDK default is a no-op) - [x] Device pairing, including the encryption key (`CredentialsType.secret`), and a generated key for keyless nodes - [x] Device schema is mapped from the entities the device reports: parameters, units, limits and valid values - [x] Hub → Device control (`send_command`) - [x] Device → Hub event subscription (`controller_did_receive_events` on every state change) - [x] `identify`: ESPHome has no identify action, so it is a documented no-op - [x] `unpair` - [x] `fetch` reports the current value of every parameter in one batch - [x] Paired devices going offline / coming back online while the Hub is running update `device.available` and `last_error`, and call `controller_did_lose_device` / `controller_did_connect_device` - [x] Graceful shutdown in `stop`: discovery stopped, connections closed, no tasks left running - [x] Tests pass against a virtual ESPHome device (`tests/`) - [x] README matches the code **Quality** — makes it reliable and maintainable (the bar for release): - [x] **Recovers automatically** from connection loss / offline device / restarted device: retried with exponential backoff (1 s up to 30 s), no manual restart - [x] **No exception escapes** discovery handlers, state callbacks or background tasks - [x] **Failures are surfaced** on the device (`available` / `last_error`) in plain language and cleared on recovery; a rejected encryption key is reported as such - [x] **Fully asynchronous**: no blocking I/O on the event loop - [x] **Stable identity**: device and parameter UUIDs derive through the SDK helpers (`device_uuid`, `parameter_uuid`) from the node's MAC address and the entity's `object_id` - [x] **End-to-end tests** drive discovery (over a stubbed zeroconf, never the real network) → pair → state → command → fetch → restart → outage → `unpair` against a virtual device, with and without encryption - [x] **Failure paths tested**: unreachable device, wrong or missing key, a key the node refuses, a node unreachable after it took its key, unsupported credentials, command on a read-only parameter, out-of-range values, offline device - [x] **Broad device coverage**: the entities above by hand, every other entity generically (tested with a lock, valve, text, date and alarm panel) - [x] **Readable & structured**: conversion logic in a mapper, models separated - [x] **Efficient**: subscriptions instead of polling; states are delivered in order - [x] **Diagnosable**: connection failures and unexpected errors are logged with their cause - [x] **Parameter metadata**: `visibility` follows the entity category, and `main_parameter` is a one-tap toggle - [x] **Owned**: maintained by Parker Industries, who keep it working as ESPHome and the library evolve ### Parameter mapping Parameters are built from what the device reports (`list_entities_services`), never from fixed defaults: | Entity | Parameters | |--------|------------| | switch, fan | `state` (bool) | | light | `state`, `brightness` (%) if the light dims, `color_hue` (°) and `color_saturation` (%) if it supports RGB; settings: `transition_length` (s, kept by the integration and added to every later command of the light) and `flash` (a `struct` command with its `length` as argument) | | cover | `position` (%), `operation` (`IDLE` / `IS_OPENING` / `IS_CLOSING`, read-only) | | climate | `mode` (`enum` of the modes it supports), `current_temperature`, `target_temperature` or `target_temperature_low/high` | | number | `state` with the device's `min` / `max` / `step` | | select | `state` as the option index (`enum`, `valid_values` labels are the options) | | sensor, binary sensor, text sensor | `state` (read-only) | | button | `state` (fires the press) | Brightness, positions and saturation are percentages (0–100, ESPHome reports 0–1); colour is hue in degrees plus saturation, the model the Matter and Zigbee integrations use, converted from ESPHome's RGB. Enums are integers with string labels in `valid_values`, labelled by the ESPHome enum names. A command may give an enum value as its key or its label (the option or member name). Units come from the entity's own unit string, else from its device class. Entities in the `config` / `diagnostic` category are `setting`, and entities disabled by default are `system`. ### Remaining fields The hand-written mapping above gives the everyday parameters. Every other state or command field an entity supports is added by the generic mapping as a `setting` parameter (`majordom_esphome/generic.py`), so nothing the library reports is dropped silently: a fan's speed level, direction, oscillation and presets; a cover's tilt and stop; a light's colour temperature, white and effects; a climate's action, fan, swing and preset modes and humidity. A water heater's state bit mask becomes `on` and `away` switches; a date or time is one `struct` parameter whose fields are its parts; a command that needs a code (a lock or alarm panel that requires one) is a `command_with_code` `struct` command with the command and the code as arguments, next to a `code` setting holding a default code: a code typed with the command wins, else the default is sent with every command of the entity, so one-tap actions and automations work once the user opts in. Commands with arguments are `struct` parameters with the arguments as `fields`, as the SDK describes. A field is only added when the entity says it supports it, enums are limited to the supported members, option lists (effects, presets) become enums like a select, and the limits the entity reports (speed count, mireds, humidity) are used. The few fields that are exposed under another name or not at all (RGB channels, deprecated fields) are listed with the reason in `UNMAPPED` in the catalogue, which fails when a new field appears that is neither mapped nor explained. ### Generic mapping Entities without a hand-written mapping get parameters from `aioesphomeapi`'s own types (`majordom_esphome/generic.py`): one parameter per field of the entity's state (read-only, unless the entity's command accepts it) and one per command argument that can be sent on its own. `bool`, `int`, `float` and `str` map directly, the library's integer enums become `enum` parameters labelled with their member names, fractions such as a position or volume become percentages, and a command-only flag (a valve's `stop`) becomes a button. Commands with several required arguments (a date) are read-only. A hand-written mapping wins wherever the generic result is not good enough for the user. ### Entity catalogue `tests/test_catalogue.py` and `tests/virtual/catalogue.py` mirror the Matter integration's virtual-device catalogue. The list of entity kinds is whatever the installed `aioesphomeapi` knows. Fast checks (always run) fail when a kind is neither mapped by the integration nor skipped on purpose, or has neither a recipe nor a reason it cannot run on the host node. Recipes are written by hand, never guessed: each one switches on every capability of its entity and comes with the exact parameters it must produce (`EXPECTED`) and every state or command field that is deliberately not exposed, with the reason (`UNMAPPED`), so a field ESPHome adds later fails the sweep until it is mapped or explained. The sweep (`poetry run pytest -m catalogue`) builds one virtual node per recipe in parallel, pairs it, checks its parameters against `EXPECTED` and `UNMAPPED`, reads its states, sends a valid command to every control parameter and checks that the connection survives and every value has the declared type. `.github/workflows/canary.yml` runs everything monthly against the latest ESPHome and `aioesphomeapi` and goes red when upstream adds something unsupported. ### Notes The device id derives from the node's MAC address (mDNS `mac` TXT record) via the SDK's UUID helpers, so ids are stable across restarts and namespaced per integration. ESPHome devices must have the `api:` component enabled in their YAML. Connecting: a node is reached through its hostname first, then through the IP addresses it announced. The first address that works moves to the front and the ones that failed move to the end, so the next connection starts with what worked last time. When a paired node announces itself again (e.g. after a DHCP change) its address list is refreshed. ## License See [LICENSE](LICENSE). For commercial licensing or partnership inquiries regarding MajorDom, contact us via [parker-industries.org/partnership](https://parker-industries.org/partnership). ================================================================================ # FILE: majordom_esphome/__init__.py ================================================================================ from majordom_integration_sdk import Peripheral, Platform from .controller import ESPhomeController __all__ = ["ESPhomeController", "peripherals"] def peripherals(platform: Platform) -> list[Peripheral]: return [ESPhomeController(platform)] ================================================================================ # FILE: majordom_esphome/bluetooth.py ================================================================================ """ESPHome nodes with ``bluetooth_proxy`` as Bluetooth sources: the hub hears and reaches BLE devices through them as if through its own adapter. A node serves one API connection at a time (the newest subscriber wins), so it can't serve this hub and another one together. """ import contextlib from collections.abc import Awaitable, Callable from aioesphomeapi import ( APIClient, APIConnectionError, BluetoothGATTService, BluetoothLERawAdvertisementsResponse, BluetoothProxyFeature, ) from bleak.backends.device import BLEDevice from bleak.backends.scanner import AdvertisementData from bluetooth_data_tools import int_to_bluetooth_address, parse_advertisement_data_bytes from majordom_integration_sdk.capabilities import GattCharacteristic, GattService, OnAdvertisement _PROPERTIES = {0x02: "read", 0x04: "write-without-response", 0x08: "write", 0x10: "notify", 0x20: "indicate"} _CCCD = "00002902-0000-1000-8000-00805f9b34fb" _CONNECTS = BluetoothProxyFeature.ACTIVE_CONNECTIONS | BluetoothProxyFeature.REMOTE_CACHING _REMEMBERED = 1024 # devices kept merged; phones rotate their address, so the oldest are dropped class ESPhomeBLEConnection: def __init__(self, client: APIClient, address: int, mtu: int, unsubscribe: Callable[[], None]): self._client, self._address, self.mtu, self._unsubscribe = client, address, mtu or 23, unsubscribe self._services: list[BluetoothGATTService] | None = None self._notifying: dict[int, Callable[[], Awaitable[None]]] = {} # handle -> stop async def _gatt_services(self) -> list[BluetoothGATTService]: if self._services is None: # the proxy forgets them once sent self._services = (await self._client.bluetooth_gatt_get_services(self._address)).services return self._services async def services(self) -> list[GattService]: return [ GattService(s.uuid, s.handle, tuple( GattCharacteristic(c.uuid, c.handle, tuple(n for bit, n in _PROPERTIES.items() if c.properties & bit)) for c in s.characteristics )) for s in await self._gatt_services() ] # fmt: skip async def read(self, handle: int) -> bytes: return bytes(await self._client.bluetooth_gatt_read(self._address, handle)) async def write(self, handle: int, data: bytes, is_response_needed: bool = True): await self._client.bluetooth_gatt_write(self._address, handle, data, is_response_needed) async def start_notify(self, handle: int, callback: Callable[[bytes], None]): characteristics = (c for s in await self._gatt_services() for c in s.characteristics) if (characteristic := next((c for c in characteristics if c.handle == handle), None)) is None: raise LookupError(f"The device has no characteristic {handle}") stop, _ = await self._client.bluetooth_gatt_start_notify(self._address, handle, lambda _, d: callback(bytes(d))) self._notifying[handle] = stop # the proxy leaves the client characteristic configuration to the client if cccd := next((d.handle for d in characteristic.descriptors if d.uuid == _CCCD), None): indicate = characteristic.properties & 0x20 and not characteristic.properties & 0x10 await self._client.bluetooth_gatt_write_descriptor( self._address, cccd, b"\x02\x00" if indicate else b"\x01\x00" ) async def stop_notify(self, handle: int): if stop := self._notifying.pop(handle, None): await stop() async def disconnect(self): # the library drops the notify handlers once told the device disconnected, which unsubscribing stops self._client.bluetooth_gatt_stop_notify_for_address(self._address) self._unsubscribe() await self._client.bluetooth_device_disconnect(self._address) class ESPhomeBLESource: """An ESPHome node lends its Bluetooth radio to the hub: what it hears and the connections it makes become one more source of the hub's Bluetooth router, offered to it as ``ble/esphome-proxy``.""" def __init__(self, client: APIClient, mac: str, features: BluetoothProxyFeature): self.mac = mac # of its Bluetooth radio self.name = f"esphome:{mac}" self._client, self._features = client, features self._unsubscribe: Callable[[], None] | None = None self._unsubscribe_slots: Callable[[], None] | None = None self._paused = False self.free_slots: int | None = None # connections it can still open, as the node last said # its loss shows through the node's API connection: the router never resubscribes it for hearing no one self.is_loss_reported = True self._heard: dict[str, tuple[AdvertisementData, int]] = {} # address -> merged advertisement, address type async def start(self, on_advertisement: OnAdvertisement): def on_advertisements(response: BluetoothLERawAdvertisementsResponse): advertisements = response.advertisements for i in range(len(advertisements)): # iterating the protobuf directly costs a debug log per batch raw = advertisements[i] address = int_to_bluetooth_address(raw.address) device, adv = self._merge(address, raw.address_type, raw.rssi, raw.data) if not self._paused: on_advertisement(device, adv) self._unsubscribe = self._client.subscribe_bluetooth_le_raw_advertisements(on_advertisements) if self._features & _CONNECTS == _CONNECTS: self._unsubscribe_slots = self._client.subscribe_bluetooth_connections_free(self._on_slots) def _on_slots(self, free: int, limit: int, allocated: list[int]): self.free_slots = free def _merge(self, address: str, address_type: int, rssi: int, data: bytes) -> tuple[BLEDevice, AdvertisementData]: # packets and scan responses arrive apart; merged like BlueZ does, so they don't read as changes name, uuids, service_data, manufacturer_data, tx_power = parse_advertisement_data_bytes(data) if previous := self._heard.pop(address, None): # re-added last: the dict stays oldest first before = previous[0] name = name or before.local_name uuids = sorted({*before.service_uuids, *uuids}) service_data = before.service_data | service_data manufacturer_data = before.manufacturer_data | manufacturer_data tx_power = before.tx_power if tx_power is None else tx_power adv = AdvertisementData(name, dict(manufacturer_data), dict(service_data), list(uuids), tx_power, rssi, ()) self._heard[address] = adv, address_type if len(self._heard) > _REMEMBERED: del self._heard[next(iter(self._heard))] return BLEDevice(address, name, {"source": self.name}), adv async def stop(self): for unsubscribe in (self._unsubscribe, self._unsubscribe_slots): if unsubscribe: with contextlib.suppress(APIConnectionError): unsubscribe() self._unsubscribe = self._unsubscribe_slots = None async def pause_scanning(self): # muted, not unsubscribed: the node answers connects only to its subscriber, and stops scanning itself # while it connects self._paused = True async def resume_scanning(self): self._paused = False async def connect(self, address: str, on_disconnect: Callable[[], None]) -> ESPhomeBLEConnection: if self._features & _CONNECTS != _CONNECTS: raise ConnectionError(f"{self.name} only listens") handle = int(address.replace(":", ""), 16) states: list[tuple[bool, int, int]] = [] def on_state(connected: bool, mtu: int, error: int): states.append((connected, mtu, error)) if len(states) > 1 and not connected: on_disconnect() unsubscribe = await self._client.bluetooth_device_connect( handle, on_state, feature_flags=self._features, address_type=self._heard.get(address, (None, 0))[1] ) # returns once the proxy answered: connected or not connected, mtu, error = states[0] if not connected: unsubscribe() raise ConnectionError(f"{self.name} can't connect to {address} (error {error})") return ESPhomeBLEConnection(self._client, handle, mtu, unsubscribe) async def ble_source_of(client: APIClient) -> ESPhomeBLESource | None: """The node's source, if it lends Bluetooth this hub can use.""" info = await client.device_info() if (version := client.api_version) is None: # the connection closed meanwhile return None features = BluetoothProxyFeature(info.bluetooth_proxy_feature_flags_compat(version)) if not features & BluetoothProxyFeature.RAW_ADVERTISEMENTS: # no proxy, or firmware too old to stream them return None return ESPhomeBLESource(client, info.bluetooth_mac_address or info.mac_address, features) ================================================================================ # FILE: majordom_esphome/connection.py ================================================================================ import asyncio import contextlib import logging from collections.abc import Awaitable, Callable from typing import Any from uuid import UUID from aioesphomeapi import ( APIClient, APIConnectionError, EntityInfo, EntityState, InvalidEncryptionKeyAPIError, RequiresEncryptionAPIError, ) logger = logging.getLogger(__name__) class _HideKeySetting(logging.Filter): """The library logs every message it sends at DEBUG: never let the one carrying a new key through.""" def filter(self, record: logging.LogRecord) -> bool: return "NoiseEncryptionSetKeyRequest" not in record.getMessage() logging.getLogger("aioesphomeapi.connection").addFilter(_HideKeySetting()) ADDRESS_TIMEOUT = 3.0 # seconds, per address: a dead address must not delay the next one WAIT_READY_TIMEOUT = 30.0 RECONNECT_DELAY_FIRST = 1.0 RECONNECT_DELAY_MAX = 30.0 StateCallback = Callable[[UUID, EntityInfo, EntityState], Awaitable[None]] AvailabilityCallback = Callable[[UUID, bool, str | None], Awaitable[None]] # (device id, available, reason if not) AddressesCallback = Callable[[UUID, list[str]], Awaitable[None]] ClientCallback = Callable[[UUID, APIClient | None], Awaitable[None]] # (device id, its client if connected, else None) class KeyRefusedError(ConnectionError): """A keyless node did not take the encryption key it was given.""" def describe_error(exc: BaseException) -> str: """Plain-language reason for the user; the technical detail stays in the logs.""" if isinstance(exc, KeyRefusedError): return "The device refused the new encryption key" if isinstance(exc, RequiresEncryptionAPIError): return "The device requires an encryption key: enter it, or factory reset the device" if isinstance(exc, InvalidEncryptionKeyAPIError): return "The device rejected the encryption key" if isinstance(exc, TimeoutError): return "The device did not respond in time" return "The device is not reachable" class ESPhomeDeviceConnection: """One device's native-API session: connects, keeps reconnecting with backoff, and feeds states to a callback.""" def __init__( self, device_id: UUID, addresses: list[str], port: int, encryption_key: str | None, on_state: StateCallback, on_availability: AvailabilityCallback | None = None, on_addresses: AddressesCallback | None = None, on_client: ClientCallback | None = None, ): self.device_id = device_id self.addresses = list(addresses) # hostname and IPs, tried in order; reordered by what worked self.port = port self.encryption_key = encryption_key self.on_state_callback = on_state self.on_availability_callback = on_availability self.on_addresses_callback = on_addresses self.on_client_callback = on_client self.last_error: Exception | None = None self._client: APIClient | None = None self._task: asyncio.Task[None] | None = None self._consumer: asyncio.Task[None] | None = None self._entities: dict[int, EntityInfo] = {} self._states: asyncio.Queue[EntityState] = asyncio.Queue() self._ready = asyncio.Event() self._failed = asyncio.Event() self._disconnected = asyncio.Event() self._available: bool | None = None # what the callback was last told self._reported_client: APIClient | None = None # what the client callback was last told @property def ready(self) -> bool: return self._ready.is_set() @property def running(self) -> bool: """Connected or retrying: started and not stopped since.""" return self._task is not None and not self._task.done() async def start(self): self._failed.clear() self.last_error = None self._consumer = asyncio.create_task(self._consume_states()) self._task = asyncio.create_task(self._run()) async def stop(self): for task in (self._task, self._consumer): if task is not None: task.cancel() with contextlib.suppress(asyncio.CancelledError): await task self._task = self._consumer = None await self._close_client() self._ready.clear() async def wait_ready(self, timeout: float = WAIT_READY_TIMEOUT): """Wait for the first successful connection; fail as soon as an attempt fails (no endless retrying).""" waiters = {asyncio.create_task(self._ready.wait()), asyncio.create_task(self._failed.wait())} try: await asyncio.wait(waiters, timeout=timeout, return_when=asyncio.FIRST_COMPLETED) finally: for waiter in waiters: waiter.cancel() if self._ready.is_set(): return if self.last_error is not None: raise ConnectionError(describe_error(self.last_error)) from self.last_error raise TimeoutError("The device did not respond in time") async def provision_key(self, key: str, session_psk: str | None): """Give a keyless node its key over a short-lived session (`session_psk`: the zero PSK, or None for plaintext on older firmware). The node stores it and accepts only connections with it from then on.""" error: Exception = ConnectionError("The device has no address") for address in self.addresses: try: accepted = await self._set_key_at(address, key, session_psk) except Exception as exc: logger.info(f"Device {self.device_id} is not reachable at {address}: {exc!r}") error = exc continue if not accepted: raise KeyRefusedError(f"Device {self.device_id} refused the encryption key") self.encryption_key = key return raise error async def _set_key_at(self, address: str, key: str, session_psk: str | None) -> bool: dropped = asyncio.Event() async def on_stop(expected_disconnect: bool): dropped.set() client = APIClient(address, self.port, None, noise_psk=session_psk) accepted = False try: async with asyncio.timeout(ADDRESS_TIMEOUT): await client.connect(login=True, on_stop=on_stop) accepted = await client.noise_encryption_set_key(key.encode()) if accepted: # the node switches to the key a moment later, then drops every session: connecting with contextlib.suppress(TimeoutError): # before that would still meet the old (zero) PSK async with asyncio.timeout(ADDRESS_TIMEOUT): await dropped.wait() return accepted finally: if accepted: # the node drops (or is about to drop) this session: a disconnect request would fail client.force_disconnect() else: with contextlib.suppress(Exception): await client.disconnect() def get_entities(self) -> dict[int, EntityInfo]: return self._entities.copy() async def send_command(self, entity_key: int, component_type: str, command_args: dict[str, Any]): if self._client is None or not self.ready: raise ConnectionError("Device not connected") method = getattr(self._client, f"{component_type}_command", None) if method is None: raise ValueError(f"Unknown component type: {component_type}") try: method(**command_args) # fire-and-forget: the device answers with a state update except APIConnectionError as exc: raise ConnectionError("Device not connected") from exc async def _run(self): delay = RECONNECT_DELAY_FIRST while True: try: await self._connect() delay = RECONNECT_DELAY_FIRST await self._disconnected.wait() raise ConnectionError("connection lost") except asyncio.CancelledError: raise except Exception as exc: logger.warning(f"Connection to {self.device_id} ({self.addresses}, port {self.port}) failed: {exc!r}") self.last_error = exc self._ready.clear() self._failed.set() await self._close_client() await self._report_availability(False, describe_error(exc)) await asyncio.sleep(delay) delay = min(delay * 2, RECONNECT_DELAY_MAX) async def _connect(self): """Connect through the first address that works; remember what worked for the next connection.""" self._disconnected.clear() failed: list[str] = [] error: Exception = ConnectionError("The device has no address") for address in list(self.addresses): try: async with asyncio.timeout(ADDRESS_TIMEOUT): await self._connect_to(address) except Exception as exc: logger.info(f"Device {self.device_id} is not reachable at {address}: {exc!r}") error = exc failed.append(address) await self._close_client() continue await self._remember(address, failed) await self._report_client(self._client) return raise error async def _connect_to(self, address: str): client = APIClient(address, self.port, None, noise_psk=self.encryption_key) self._client = client await client.connect(login=True, on_stop=self._on_stop) entities, _services = await client.list_entities_services() self._entities = {entity.key: entity for entity in entities} client.subscribe_states(self._state_received) self.last_error = None self._ready.set() logger.info(f"Connected to ESPHome device {self.device_id} at {address}:{self.port}") async def _remember(self, address: str, failed: list[str]): """Working address first, addresses that failed this time last.""" untried = [a for a in self.addresses if a != address and a not in failed] remembered = [address, *untried, *failed] if remembered != self.addresses: self.addresses = remembered if self.on_addresses_callback is not None: try: await self.on_addresses_callback(self.device_id, remembered) except Exception: logger.exception(f"Error saving the addresses of {self.device_id}") await self._report_availability(True, None) async def _on_stop(self, expected_disconnect: bool): logger.info(f"Device {self.device_id} disconnected (expected={expected_disconnect})") self._ready.clear() self._disconnected.set() def _state_received(self, state: EntityState): self._states.put_nowait(state) async def _consume_states(self): """Deliver states one at a time, in the order the device sent them.""" while True: state = await self._states.get() entity = self._entities.get(state.key) if entity is None: continue try: await self.on_state_callback(self.device_id, entity, state) except Exception: logger.exception(f"Error handling state of {entity.name} on {self.device_id}") async def _report_availability(self, available: bool, reason: str | None): if self.on_availability_callback is None or self._available == available: return self._available = available try: await self.on_availability_callback(self.device_id, available, reason) except Exception: logger.exception(f"Error reporting availability of {self.device_id}") async def report_client(self): """Tell the client callback the current client again, as if it had just connected.""" self._reported_client = None await self._report_client(self._client) async def _report_client(self, client: APIClient | None): if self.on_client_callback is None or self._reported_client is client: return self._reported_client = client try: await self.on_client_callback(self.device_id, client) except Exception: logger.exception(f"Error reporting the client of {self.device_id}") async def _close_client(self): await self._report_client(None) client, self._client = self._client, None if client is not None: with contextlib.suppress(Exception): await client.disconnect() ================================================================================ # FILE: majordom_esphome/controller.py ================================================================================ """ESPHome integration controller for MajorDom.""" from __future__ import annotations import asyncio import base64 import functools import logging import secrets from collections.abc import Callable, Coroutine from dataclasses import dataclass, replace from typing import Any from uuid import UUID from aioesphomeapi import ZERO_NOISE_PSK, APIClient, ButtonInfo, EntityInfo, EntityState from majordom_integration_sdk import ( AbstractController, DeviceIdTakenError, DeviceUnreachableError, MissingCredentialsError, Need, PeripheralChange, Platform, WifiCredentials, ) from majordom_integration_sdk.capabilities import ( BLE_ROUTER, ZEROCONF, BLEDiscoveryInfo, BLERouter, Zeroconf, ZeroconfDiscoveryInfo, ) from majordom_integration_sdk.peripherals import BLEProxy from majordom_integration_sdk.schemas import ( CredentialsType, DeviceParameterChange, ProvidedCredentials, ) from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.schemas.parameter import ParameterState, ParameterVisibility from pydantic import BaseModel, Field from . import improv, mapper, thread_provisioning from .bluetooth import ble_source_of from .connection import ESPhomeDeviceConnection, KeyRefusedError, describe_error from .models import ( ESPhomeDevice, ESPhomeDeviceIntegrationData, ESPhomeDeviceState, ESPhomeParameter, ESPhomeParameterIntegrationData, ParameterSpec, ) logger = logging.getLogger(__name__) UNSAVED_PAIRING_TIMEOUT = 120.0 # seconds a paired node waits for the Hub to save it (and fetch it) before it is let go FACTORY_RESET_TIMEOUT = 5.0 # seconds unpair waits to reach the node and have the press taken FACTORY_RESET_GRACE = ( 0.5 # the node erases and reboots on its own; this lets the frame leave before the link is dropped ) NODE_APPEAR_TIMEOUT = 60.0 # seconds for a node to announce itself over mDNS once it has joined Wi-Fi or Thread @dataclass class _DiscoveryData: addresses: list[str] port: int mac: str | None keyless: bool # encryption is on but no key is set: the integration gives the node one at pairing zero_psk: bool # the keyless node takes its key over the zero PSK (older firmware: only in plaintext) @dataclass class _Paired: """A node paired but not yet saved by the Hub: its connection reports nothing until `fetch` takes it in.""" connection: ESPhomeDeviceConnection expiry: asyncio.Task[None] | None = None @dataclass class _ImprovNode: """An unprovisioned node, waiting for its network over BLE: Wi-Fi (Improv) or Thread (`thread_provisioning`).""" name: str # its node name, as far as BLE carries it address: str thread: bool = False class ESPhomeController( AbstractController[ESPhomeDevice, ESPhomeParameter, "ESPhomeController.Settings", ESPhomeDeviceState] ): name = "ESPHome" # its key, the slug "esphome", scopes its devices # Nodes are found over mDNS. Devices on Thread reach the hub through a border router; Wi-Fi devices need nothing. # The router sets unprovisioned nodes up over Improv BLE; the nodes that proxy Bluetooth are offered back to it. needs = [ ZEROCONF, Need("thread", ["otbr-rest"], is_required=False), replace(BLE_ROUTER, is_required=False), ] class Settings(BaseModel): is_bluetooth_proxy_enabled: bool = Field( True, title="Bluetooth proxies", description="Reach Bluetooth devices through ESPHome devices with bluetooth_proxy. A device serves one hub " "at a time: turn this off only if another hub needs its Bluetooth proxy.", ) def __init__(self, platform: Platform, *, settings: ESPhomeController.Settings | None = None): super().__init__(platform, settings=settings) self._connections: dict[UUID, ESPhomeDeviceConnection] = {} self._proxies: dict[UUID, BLEProxy] = {} # the nodes lending their Bluetooth radio to the hub self._discoveries: dict[UUID, Discovery] = {} self._discovery_data: dict[UUID, _DiscoveryData] = {} self._discovery_names: dict[str, UUID] = {} # mDNS record name -> discovery id, for goodbyes self._zeroconf_cancel: Callable[[], None] | None = None self._ble_cancel: Callable[[], None] | None = None self._improv_nodes: dict[UUID, _ImprovNode] = {} self._ble_names: dict[str, str] = {} # BLE address -> advertised name: ESPHome sends it in few adverts self._joining: dict[str, asyncio.Future[Discovery]] = {} # BLE name -> the node's mDNS discovery, once seen self._paired: set[UUID] = set() self._just_paired: dict[UUID, _Paired] = {} self._given_keys: set[UUID] = set() # nodes this run gave a key that no saved device holds yet self._tasks: set[asyncio.Task[Any]] = set() self._states: dict[UUID, dict[int, EntityState]] = {} self._run: object | None = None # from start() to stop(): a pairing finishing in another run adopts nothing @property def discoveries(self) -> dict[UUID, Discovery]: return self._discoveries.copy() @property def provides(self) -> list[BLEProxy]: return list(self._proxies.values()) @property def device_type(self) -> type[ESPhomeDevice]: return ESPhomeDevice @property def parameter_type(self) -> type[ESPhomeParameter]: return ESPhomeParameter @property def device_state_type(self) -> type[ESPhomeDeviceState]: return ESPhomeDeviceState # Lifecycle async def start(self): logger.info("Starting ESPHome integration") self._run = object() await self._load_paired_devices() # first: DNS-SD tells the nodes in its cache at once, the paired ones too if (zeroconf := self.peripherals.instance(ZEROCONF)) is None: raise RuntimeError("zeroconf isn't bound") self._zeroconf_cancel = zeroconf.register(self, services={"_esphomelib._tcp.local."}) self._listen_for_improv() async def stop(self): logger.info("Stopping ESPHome integration") self._run = None if self._zeroconf_cancel: self._zeroconf_cancel() self._zeroconf_cancel = None if self._ble_cancel: self._ble_cancel() self._ble_cancel = None tasks = list(self._tasks) # the setups over Bluetooth too for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) for connection in list(self._connections.values()): await connection.stop() self._connections.clear() for paired in self._just_paired.values(): await paired.connection.stop() self._just_paired.clear() for device_id in list(self._proxies): await self._on_client(device_id, None) self._states.clear() self._paired.clear() # heard anew after a start, which reports them again; a node that left meanwhile says no goodbye self._discoveries.clear() self._discovery_data.clear() self._discovery_names.clear() self._improv_nodes.clear() self._ble_names.clear() async def needed_peripheral_did_change(self, change: PeripheralChange) -> bool: """The router is followed in place, and a border router only carries the Thread devices to the hub: neither restarts it. Another DNS-SD does.""" if change.family == "ble": await self._let_go_of_router() self._listen_for_improv() return change.family in ("ble", "thread") # Hub -> device async def pair_device( self, discovery: Discovery, draft: ESPhomeDeviceState, credentials: ProvidedCredentials | None ) -> ESPhomeDeviceState: run = self._run if discovery.id in self._improv_nodes: return await self._pair_over_ble(discovery, draft, run) return await self._pair_over_api(discovery, draft, credentials, run) async def unpair(self, device: ESPhomeDevice | ESPhomeDeviceState): """Also the rollback of a pairing at any stage, best effort. A reachable node given a key by this pairing, or a saved one, is factory reset, so it pairs again keyless (the key lives only in the device record the Hub deletes); a node given the network over BLE keeps it.""" paired = self._unpark(device.physical_id) connection = self._connections.pop(device.physical_id, None) given_key = device.physical_id in self._given_keys self._given_keys.discard(device.physical_id) self._states.pop(device.physical_id, None) self._paired.discard(device.physical_id) live = connection or (paired.connection if paired else None) reached = live is not None and live.ready if reached: await self._factory_reset(device.physical_id, live) elif given_key: # the failed pairing already dropped its connection reached = await self._factory_reset_anew(device) for conn in (paired.connection if paired else None, connection): if conn is not None: await conn.stop() if not reached and (given_key or isinstance(device, ESPhomeDevice) and device.integration_data.encryption_key): raise DeviceUnreachableError(f"{device.physical_id} is unreachable to factory reset") # The Hub removes the device record after unpair; the repository protocol # intentionally does not expose delete() to integrations. async def identify(self, device: ESPhomeDevice): # ESPHome has no identify action, so there is nothing to send to the device logger.info(f"Identify called for {device.physical_id}: not supported by ESPHome") async def fetch(self, device: ESPhomeDevice): """Take a just paired node in, or connect a paired one whose connection is gone; report its values if it is connected. The connection retries by itself: nothing here waits for it.""" if (paired := self._unpark(device.physical_id)) is not None: await self._take_in(device.physical_id, paired) elif device.physical_id not in self._connections and device.integration_data.addresses: self._paired.add(device.physical_id) self._connect(device) elif (connection := self._connections.get(device.physical_id)) is not None and not connection.running: await connection.start() connection = self._connections.get(device.physical_id) if connection is None or not connection.ready: raise ConnectionError("Device not connected") await self._report_snapshot(device.physical_id) async def send_command( self, command: DeviceCommand, device: ESPhomeDevice, parameter: ESPhomeParameter, ): data = parameter.integration_data if mapper.is_local(parameter): # a setting kept here: stored, and echoed so the Hub stores it too await self._keep_setting( device.physical_id, data.object_id or "", data.sub_field or "", parameter, command.value ) return connection = self._connections.get(device.physical_id) if connection is None or not connection.ready: await self._update_device( device.physical_id, last_error=f"{parameter.name} could not be set: device not connected" ) raise ConnectionError("Device not connected") stored = await self._update_device(device.physical_id) settings = stored.integration_data.settings.get(data.object_id or "", {}) if stored is not None else {} args = mapper.build_command_args(parameter, command.value, self._states.get(device.physical_id, {}), settings) try: await connection.send_command(args["key"], data.component_type, args) except ConnectionError: await self._update_device( device.physical_id, last_error=f"{parameter.name} could not be set: device not connected" ) raise await self._update_device(device.physical_id, last_error=None) # ZeroconfDiscoveryListener: called by the SDK's discovery service async def zeroconf_did_discover_service(self, zeroconf: Zeroconf, info: ZeroconfDiscoveryInfo): await self._on_zeroconf_service(info) async def zeroconf_did_update_service(self, zeroconf: Zeroconf, info: ZeroconfDiscoveryInfo): await self._on_zeroconf_service(info) async def zeroconf_did_remove_service(self, zeroconf: Zeroconf, type_: str, name: str): device_id = self._discovery_names.pop(name, None) if device_id is not None and self._discoveries.pop(device_id, None) is not None: self._discovery_data.pop(device_id, None) await self.output.controller_did_lose_discovery(self, device_id) # BLEDiscoveryListener: unprovisioned nodes advertising Improv async def ble_did_discover_device(self, ble: BLERouter, info: BLEDiscoveryInfo): await self._on_improv_advert(info) async def ble_did_update_device(self, ble: BLERouter, info: BLEDiscoveryInfo): await self._on_improv_advert(info) async def ble_did_remove_device(self, ble: BLERouter, info: BLEDiscoveryInfo): if self._ble_names.get(info.device.address) in self._joining: # set up: it stops advertising once on Wi-Fi return await self._lose_improv_node(info.device.address) # Private: discovery async def _on_zeroconf_service(self, service_info: ZeroconfDiscoveryInfo): try: node_name = service_info.name.removesuffix(f".{service_info.type_}") properties = service_info.decoded_properties mac = properties.get("mac") device_id = self._node_uuid(mac, node_name) addresses = self._announced_addresses(service_info, node_name) if device_id in self._paired: await self._refresh_addresses(device_id, addresses) self._refuse_setup(node_name, device_id, properties.get("friendly_name") or node_name) return port = service_info.port or 6053 # a key is configured: the user's, unless it is one a saved device holds. # Even then the user may enter one: the node may have been reflashed with a key of its own since. if "api_encryption" not in properties: credentials_options = [CredentialsType.none] elif await self._kept_key(device_id) is None: credentials_options = [CredentialsType.secret] else: credentials_options = [CredentialsType.none, CredentialsType.secret] discovery = Discovery( id=device_id, integration=self.key, transport="tcp", device_manufacturer="esphome", device_name=properties.get("friendly_name") or node_name, device_category=None, # a node may host anything device_icon=None, expected_credentials_options=credentials_options, ) keyless = "api_encryption_supported" in properties zero_psk = properties.get("api_provisioning") == "zero-psk" self._discovery_data[device_id] = _DiscoveryData(addresses, port, mac, keyless, zero_psk) self._discovery_names[service_info.name] = device_id for ble_name, joined in self._joining.items(): if improv.is_node(ble_name, node_name) and not joined.done(): joined.set_result(discovery) known = self._discoveries.get(device_id) if known == discovery: return self._discoveries[device_id] = discovery if known is None: await self.output.controller_did_receive_discovery(self, discovery) else: await self.output.controller_did_update_discovery(self, discovery) logger.debug(f"Discovered ESPHome node {node_name} at {addresses}:{port}") except Exception: logger.exception("Error handling zeroconf discovery") @property def _router(self) -> BLERouter | None: return self.peripherals.instance(BLE_ROUTER) async def _let_go_of_router(self): """Stop listening to the router, and lose the nodes it heard: the next one tells what it hears.""" if self._ble_cancel: self._ble_cancel() self._ble_cancel = None lost = [device_id for device_id in self._improv_nodes if self._discoveries.pop(device_id, None) is not None] self._improv_nodes.clear() self._ble_names.clear() for device_id in lost: await self.output.controller_did_lose_discovery(self, device_id) def _listen_for_improv(self): """Hear unprovisioned nodes through the router bound now, if there is one.""" router = self._router self._ble_cancel = ( router.register(self, {UUID(improv.SERVICE_UUID), UUID(thread_provisioning.SERVICE_UUID)}) if router else None ) async def _lose_improv_node(self, address: str): name = self._ble_names.pop(address, None) device_id = self.device_uuid(f"improv:{name}", strip="") if name else None if device_id is not None and self._discoveries.pop(device_id, None) is not None: self._improv_nodes.pop(device_id, None) await self.output.controller_did_lose_discovery(self, device_id) async def _on_improv_advert(self, info: BLEDiscoveryInfo): """Offer a node waiting for Wi-Fi or Thread. Neither service carries an identity but the node name, so the discovery is keyed by it (the BLE address may be random, and differs from the MAC the node is known by once on the network).""" try: name = info.advertisement.local_name or self._ble_names.get(info.device.address) thread = thread_provisioning.waits_for_thread(info.advertisement) if name is None or not (thread or improv.waits_for_wifi(info.advertisement)): return self._ble_names[info.device.address] = name device_id = self.device_uuid(f"improv:{name}", strip="") self._improv_nodes[device_id] = _ImprovNode(name, info.device.address, thread) if device_id in self._discoveries: # adverts repeat all the time: keep the discovery (and its last error) return discovery = Discovery( id=device_id, integration=self.key, transport="ble", device_manufacturer="esphome", device_name=name, device_category=None, device_icon=None, expected_credentials_options=[CredentialsType.none], # the Hub gives it its own network ) self._discoveries[device_id] = discovery await self.output.controller_did_receive_discovery(self, discovery) logger.debug(f"Discovered unprovisioned ESPHome node {name} over BLE") except Exception: logger.exception("Error handling BLE discovery") def _node_uuid(self, mac: str | None, node_name: str) -> UUID: """A node is known by its MAC (raw bytes); one that announces none, by its name (dashes are significant).""" if mac: try: return self.device_uuid(bytes.fromhex(mac.replace(":", ""))) except ValueError: return self.device_uuid(mac) return self.device_uuid(node_name, strip="") @staticmethod def _announced_addresses(info: ZeroconfDiscoveryInfo, node_name: str) -> list[str]: """Hostname first (it follows the device through DHCP changes), then the announced IPs.""" hostname = info.server.rstrip(".") if info.server else None addresses = [hostname, *(info.parsed_addresses or [])] if hostname else list(info.parsed_addresses or []) return list(dict.fromkeys(addresses)) or [f"{node_name}.local"] async def _refresh_addresses(self, device_id: UUID, announced: list[str]): """A paired device announced itself again: learn its new addresses, forget the ones it left.""" device = await self._update_device(device_id) if device is None: return known = device.integration_data.addresses refreshed = [a for a in announced if a not in known] + [a for a in known if a in announced] if refreshed == known: return logger.info(f"Addresses of {device_id} changed: {known} -> {refreshed}") await self._save_integration_data(device_id, addresses=refreshed) if connection := self._connections.get(device_id): connection.addresses = refreshed def _refuse_setup(self, node_name: str, device_id: UUID, device_name: str): """A node set up over BLE announced itself as a paired one (its Wi-Fi was reset): it is back, and its device reconnects. Its setup ends with that id, which `_pair_over_ble` refuses rather than replace that device.""" returned = Discovery( id=device_id, integration=self.key, transport="tcp", device_manufacturer="esphome", device_name=device_name, device_category=None, device_icon=None, expected_credentials_options=[CredentialsType.none], ) for ble_name, joined in self._joining.items(): if improv.is_node(ble_name, node_name) and not joined.done(): joined.set_result(returned) # Private: connections and state async def _load_paired_devices(self): async with self.platform.device_repository(self) as repo: devices = await repo.get_all(ESPhomeDevice) for device in devices: if device.integration_data.addresses: # else the Hub created it, but its pairing never completed self._paired.add(device.physical_id) self._connect(device) def _connect(self, device: ESPhomeDevice): data = device.integration_data connection = self._make_connection(device.physical_id, data.addresses, data.port, data.encryption_key) self._connections[device.physical_id] = connection self._spawn(connection.start()) def _make_connection( self, device_id: UUID, addresses: list[str], port: int, encryption_key: str | None ) -> ESPhomeDeviceConnection: return ESPhomeDeviceConnection( device_id=device_id, addresses=addresses, port=port, encryption_key=encryption_key, on_state=self._on_state, on_availability=self._on_availability, on_addresses=self._on_addresses, on_client=self._on_client if self.settings.is_bluetooth_proxy_enabled else None, ) def _spawn[T](self, coroutine: Coroutine[Any, Any, T]) -> asyncio.Task[T]: """Run in the background, keeping a reference so the task is neither collected nor left behind on stop().""" task = asyncio.create_task(coroutine) self._tasks.add(task) task.add_done_callback(self._tasks.discard) return task async def _on_availability(self, device_id: UUID, available: bool, reason: str | None): if device_id not in self._connections: # still pairing, or already unpaired return await self._update_device(device_id, available=available, last_error=None if available else reason) if available: await self.output.controller_did_connect_device(self, physical_id=device_id) else: await self.output.controller_did_lose_device(self, physical_id=device_id) async def _on_client(self, device_id: UUID, client: APIClient | None): """A paired node connected: lend its Bluetooth radio, if it has one to lend, as a ``ble/esphome-proxy`` the router takes; a node being paired serves no one until it is. A node gone: take the radio back.""" if client is None: if self._proxies.pop(device_id, None): await self.output.controller_did_change_provided(self) elif device_id in self._connections and (source := await ble_source_of(client)): self._proxies[device_id] = BLEProxy(source, name=source.mac) await self.output.controller_did_change_provided(self) async def _on_addresses(self, device_id: UUID, addresses: list[str]): if device_id in self._connections: # not while pairing: the device is saved with the final order await self._save_integration_data(device_id, addresses=addresses) async def _update_device(self, device_id: UUID, **changes: Any) -> ESPhomeDevice | None: async with self.platform.device_repository(self) as repo: device = await repo.get(physical_id=device_id, as_=ESPhomeDevice) if device is None: return None if any(getattr(device, field) != value for field, value in changes.items()): device = device.model_copy(update=changes) await repo.save(device) return device async def _save_integration_data(self, device_id: UUID, **changes: Any): async with self.platform.device_repository(self) as repo: device = await repo.get(physical_id=device_id, as_=ESPhomeDevice) if device is not None: data = device.integration_data.model_copy(update=changes) await repo.save(device.model_copy(update={"integration_data": data})) async def _on_state(self, device_id: UUID, entity: EntityInfo, state: EntityState): self._states.setdefault(device_id, {})[state.key] = state # kept while pairing: the snapshot then reports them if device_id not in self._connections: # still pairing, or already unpaired: the Hub does not know the device return try: events = self._events(device_id, entity, state) if events: await self.output.controller_did_receive_events(self, events) except Exception: logger.exception(f"Error handling state for {entity.name}") def _events(self, device_id: UUID, entity: EntityInfo, state: EntityState) -> list[DeviceParameterChange]: component = mapper.component_type_of(entity) if component is None: return [] exposed = {spec.sub_field: spec for spec in mapper.parameter_specs(entity, component)} events = [] for sub_field, value in mapper.state_values(entity, state).items(): spec = exposed.get(sub_field) if spec is None: continue if spec.fields: # a struct value: keyed by the sub-parameter ids, as the SDK specifies value = { str(self._parameter_id(device_id, entity, f"{sub_field}.{name}")): v for name, v in value.items() } parameter_id = self._parameter_id(device_id, entity, sub_field) events.append(DeviceParameterChange(physical_id=device_id, parameter_id=parameter_id, value=value)) return events @staticmethod def _visibility(entity: EntityInfo, spec: ParameterSpec) -> ParameterVisibility: """The entity's own visibility, unless the spec asks for a less prominent one (and the entity allows it).""" visibility = mapper.visibility_of(entity) if spec.visibility == ParameterVisibility.system: # infrastructure is hidden whatever the entity says return spec.visibility return spec.visibility if visibility == ParameterVisibility.user and spec.visibility else visibility def _parameter_id(self, device_id: UUID, entity: EntityInfo, sub_field: str) -> UUID: return self.parameter_uuid(device_id, f"{entity.object_id}_{sub_field}") async def _report_snapshot(self, device_id: UUID): """Report the last known value of every parameter in a single batch, the kept settings included.""" connection = self._connections[device_id] entities = connection.get_entities() events = [ event for key, state in self._states.get(device_id, {}).items() if key in entities for event in self._events(device_id, entities[key], state) ] device = await self._update_device(device_id) settings = device.integration_data.settings if device is not None else {} for entity in entities.values(): for field, value in settings.get(entity.object_id, {}).items(): if value is None: # a cleared setting continue parameter_id = self._parameter_id(device_id, entity, field) events.append(DeviceParameterChange(physical_id=device_id, parameter_id=parameter_id, value=value)) if events: await self.output.controller_did_receive_events(self, events) def _build_parameter( self, device_id: UUID, entity: EntityInfo, component: str, spec: ParameterSpec, parent: str | None = None ) -> ESPhomeParameter: path = ( f"{parent}.{spec.sub_field}" if parent else spec.sub_field ) # a sub-parameter's id is scoped to its parent label = spec.sub_field.replace("_", " ") name = label.capitalize() if parent else entity.name if spec.sub_field == "state" else f"{entity.name} {label}" return ESPhomeParameter( id=self._parameter_id(device_id, entity, path), name=name, data_type=spec.data_type, role=spec.role, unit=spec.unit, min_value=spec.min_value, max_value=spec.max_value, min_step=spec.min_step, valid_values=spec.valid_values, visibility=self._visibility(entity, spec), fields=[self._build_parameter(device_id, entity, component, child, path) for child in spec.fields] or None, integration_data=ESPhomeParameterIntegrationData( entity_name=entity.name, object_id=entity.object_id, component_type=component, parameter_type=mapper.PARAMETER_TYPE.get(component, mapper.ESPhomeParameterType.STATE), service_key=entity.key, sub_field=spec.sub_field, ), ) async def _keep_setting(self, device_id: UUID, object_id: str, field: str, parameter: ESPhomeParameter, value: Any): kept = mapper.local_value(parameter, value) async with self.platform.device_repository(self) as repo: device = await repo.get(physical_id=device_id, as_=ESPhomeDevice) if device is None: raise ValueError(f"Unknown device {device_id}") settings = {**device.integration_data.settings} settings[object_id] = {**settings.get(object_id, {}), field: kept} data = device.integration_data.model_copy(update={"settings": settings}) await repo.save(device.model_copy(update={"integration_data": data})) event = DeviceParameterChange(physical_id=device_id, parameter_id=parameter.id, value=kept) await self.output.controller_did_receive_events(self, [event]) # Private: pairing async def _pair_over_ble( self, discovery: Discovery, draft: ESPhomeDeviceState, run: object | None ) -> ESPhomeDeviceState: """Give the node the Hub's Wi-Fi or Thread network, wait for it on the network, then pair it like any other node. The device takes the node's own identity (from its MAC), which is what it is found by from then on.""" logger.info(f"Setting up ESPHome device {discovery.device_name} over BLE") node = self._improv_nodes[discovery.id] try: network = self._thread_dataset() if node.thread else self._wifi_credentials() if (router := self._router) is None: raise LookupError("The Hub has no Bluetooth to set the device up with") setup = self._spawn(self._join_network(router, node, network, discovery.id)) # stop() ends it at once try: on_network = await setup except asyncio.CancelledError: self._refuse_if_stopped(run) # stop() ended it raise # the Hub's request went away self._refuse_if_stopped(run) if on_network.id in self._paired: await self.check_device_id(on_network.id, draft) # another record: refused as taken raise ValueError("The device is already paired: it is back on the network") draft = await self._pair_over_api(on_network, draft, None, run) except MissingCredentialsError: raise # the Hub returns it to the app's pairing request except Exception as exc: logger.exception(f"Setting up {discovery.device_name} over BLE failed") reason = ( str(exc) if isinstance(exc, ValueError | LookupError | TimeoutError | improv.SetupError | DeviceIdTakenError) else None ) await self._report_error(discovery.id, reason or describe_error(exc.__cause__ or exc)) router = self._router if router is None or node.address not in {info.device.address for info in router.devices()}: await self._lose_improv_node(node.address) # its removal came while it was set up: none comes again raise self._discoveries.pop(discovery.id, None) self._improv_nodes.pop(discovery.id, None) # the Hub paired the node through its BLE discovery: the one it announced over mDNS is gone too await self.output.controller_did_lose_discovery(self, on_network.id) return draft async def _join_network( self, router: BLERouter, node: _ImprovNode, network: WifiCredentials | bytes, discovery_id: UUID ) -> Discovery: """Give the node the Hub's Wi-Fi over Improv, or its Thread dataset, then wait for it on the network: its mDNS discovery.""" joined = self._joining[node.name] = asyncio.get_running_loop().create_future() on_authorization_required = functools.partial(self._report_error, discovery_id, improv.PRESS_BUTTON) name = "the Hub's Thread network" if isinstance(network, bytes) else network.ssid try: if isinstance(network, bytes): await thread_provisioning.provision(router, node.address, network, on_authorization_required) else: await improv.provision(router, node.address, network.ssid, network.password, on_authorization_required) async with asyncio.timeout(NODE_APPEAR_TIMEOUT): return await joined except TimeoutError: raise TimeoutError(f"The device joined {name} but did not show up on the network") from None finally: self._joining.pop(node.name, None) def _wifi_credentials(self) -> WifiCredentials: if (wifi := self.platform.wifi) is None: raise MissingCredentialsError(MissingCredentialsError.WIFI) return wifi def _thread_dataset(self) -> bytes: """The Hub's active operational dataset; it holds the network key, so it is never logged.""" if not (dataset := self.platform.thread_dataset): raise MissingCredentialsError(MissingCredentialsError.THREAD) return bytes.fromhex(dataset) async def _report_error(self, discovery_id: UUID, reason: str): """Show the user why pairing a discovery failed (or what it waits for), while it is still offered.""" if (known := self._discoveries.get(discovery_id)) is not None: failed = known.model_copy(update={"last_error": reason}) self._discoveries[discovery_id] = failed await self.output.controller_did_update_discovery(self, failed) async def _pair_over_api( self, discovery: Discovery, draft: ESPhomeDeviceState, credentials: ProvidedCredentials | None, run: object | None, ) -> ESPhomeDeviceState: logger.info(f"Pairing ESPHome device: {discovery.id}") known = self._discoveries.get(discovery.id, discovery) conn: ESPhomeDeviceConnection | None = None try: integration_data = self._discovery_data.get(discovery.id) if integration_data is None: raise ValueError("Unknown device: it is no longer discovered") credentials_type = credentials.type if credentials else CredentialsType.none if credentials_type not in known.expected_credentials_options: raise ValueError(f"Unsupported credentials for this device: {credentials_type}") encryption_key = credentials.value if credentials and credentials_type == CredentialsType.secret else None if credentials_type == CredentialsType.secret and not encryption_key: raise ValueError("The encryption key is required for this device") # a picked record of another node holds nothing that fits this one kept = draft.integration_data if draft.physical_id == discovery.id else ESPhomeDeviceIntegrationData() draft.physical_id = discovery.id # the discovery id is this node's device_uuid, made in _node_uuid await self.check_device_id(draft.physical_id, draft) encryption_key = encryption_key or kept.encryption_key draft.integration_data = ESPhomeDeviceIntegrationData( device_name=discovery.device_name, unique_id=integration_data.mac, mac_address=integration_data.mac, addresses=integration_data.addresses, port=integration_data.port, encryption_key=encryption_key, settings=kept.settings, ) conn = self._make_connection( discovery.id, integration_data.addresses, integration_data.port, encryption_key ) if integration_data.keyless: await self._provision_key(conn, integration_data, draft) elif encryption_key is None: logger.warning( f"{discovery.device_name} accepts unencrypted API connections only: " "add `api: encryption:` to its YAML" ) await conn.start() await conn.wait_ready() parameters = [ self._build_parameter(discovery.id, entity, component, spec) for entity in conn.get_entities().values() if (component := mapper.component_type_of(entity)) is not None for spec in mapper.parameter_specs(entity, component) ] draft.parameters = [ ParameterState[ESPhomeParameterIntegrationData].model_validate(p.model_dump()) for p in parameters ] draft.main_parameter = next( (p.id for p in parameters if p.can_be_main_parameter and p.role == "control"), None ) draft.available = True draft.last_error = None draft.integration_data.addresses = conn.addresses self._refuse_if_stopped(run) previous = self._unpark(discovery.id) # an earlier attempt the Hub never saved if previous is not None: await previous.connection.stop() paired = _Paired(conn) paired.expiry = self._spawn(self._let_go_unless_saved(discovery.id, paired)) self._just_paired[discovery.id] = paired return draft except asyncio.CancelledError: # no one waits for the outcome: let go of the node await self._let_go_of_pairing(discovery.id, conn) raise except Exception as exc: await self._let_go_of_pairing(discovery.id, conn) logger.exception(f"Pairing {discovery.id} failed") if self._is_current(run): # a stopped controller offers nothing reason = ( str(exc) if isinstance(exc, ValueError | LookupError | DeviceIdTakenError) else describe_error(exc.__cause__ or exc) ) failed = known.model_copy(update={"last_error": reason}) self._discoveries[discovery.id] = failed await self.output.controller_did_update_discovery(self, failed) raise def _unpark(self, device_id: UUID) -> _Paired | None: paired = self._just_paired.pop(device_id, None) if paired is not None and paired.expiry is not None: paired.expiry.cancel() return paired async def _let_go_unless_saved(self, device_id: UUID, paired: _Paired): """The Hub may refuse the id after pairing and never call unpair (the id may be another working device's): a node no fetch took in is let go of.""" await asyncio.sleep(UNSAVED_PAIRING_TIMEOUT) if self._just_paired.get(device_id) is paired: del self._just_paired[device_id] self._states.pop(device_id, None) if device_id in self._given_keys: # nothing keeps the key it requires now self._given_keys.discard(device_id) await self._factory_reset(device_id, paired.connection) await paired.connection.stop() async def _take_in(self, device_id: UUID, paired: _Paired): """The Hub saved a just paired node: its connection reports from now on.""" self._connections[device_id] = paired.connection self._paired.add(device_id) self._discoveries.pop(device_id, None) self._discovery_data.pop(device_id, None) self._given_keys.discard(device_id) await paired.connection.report_client() # paired: its radio may serve the hub now async def _let_go_of_pairing(self, device_id: UUID, conn: ESPhomeDeviceConnection | None): """Undo a pairing that didn't finish: its node connection goes, also once taken in, so it can be tried again.""" if conn is not None: await conn.stop() if self._connections.get(device_id) is conn: del self._connections[device_id] self._paired.discard(device_id) self._states.pop(device_id, None) def _refuse_if_stopped(self, run: object | None): """A pairing that finishes after stop() takes nothing, also once ESPHome runs again (that run may have other settings): the next start() connects what is paired anew. Adopting it into the new run may come later.""" if not self._is_current(run): raise ConnectionError("ESPHome stopped while pairing") def _is_current(self, run: object | None) -> bool: return run is not None and run is self._run # Private: encryption keys async def _kept_key(self, device_id: UUID) -> str | None: device = await self._update_device(device_id) return device.integration_data.encryption_key if device is not None else None async def _provision_key(self, conn: ESPhomeDeviceConnection, data: _DiscoveryData, draft: ESPhomeDeviceState): """Give a keyless node a key of our own (or the one its saved record holds). It is kept in the draft before it is set: from then on the node accepts nothing else, so a pairing that fails is rolled back by a factory reset (see `unpair`).""" key = draft.integration_data.encryption_key or base64.b64encode(secrets.token_bytes(32)).decode() draft.integration_data.encryption_key = key self._given_keys.add(draft.physical_id) try: await conn.provision_key(key, ZERO_NOISE_PSK if data.zero_psk else None) except KeyRefusedError: # it stays keyless: nothing to undo self._given_keys.discard(draft.physical_id) raise data.keyless = False # whatever mDNS still announces, the node requires the key now async def _factory_reset_anew(self, device: ESPhomeDevice | ESPhomeDeviceState) -> bool: """Reach the node with the key of a draft whose pairing dropped its connection, to factory reset it; whether it was reached.""" data = device.integration_data conn = self._make_connection(device.physical_id, data.addresses, data.port, data.encryption_key) try: await conn.start() await conn.wait_ready(FACTORY_RESET_TIMEOUT) await self._factory_reset(device.physical_id, conn) return True except Exception as exc: logger.debug(f"Could not reach {device.physical_id} to factory reset it: {exc}") return False finally: await conn.stop() async def _factory_reset(self, device_id: UUID, connection: ESPhomeDeviceConnection): """Press the node's Factory Reset button: it forgets Wi-Fi/Thread and the API key and pairs from scratch. Best effort: an offline node, a node without the button or a failed press never blocks unpairing.""" button = next( ( entity for entity in connection.get_entities().values() if isinstance(entity, ButtonInfo) and entity.object_id == "factory_reset" ), None, ) if button is None or not connection.ready: logger.debug(f"Not resetting {device_id}: offline or no Factory Reset button") return try: await asyncio.wait_for( connection.send_command(button.key, "button", {"key": button.key}), FACTORY_RESET_TIMEOUT ) await asyncio.sleep(FACTORY_RESET_GRACE) except Exception as exc: logger.debug(f"Factory reset of {device_id} failed: {exc}") ================================================================================ # FILE: majordom_esphome/esphome_spec.py ================================================================================ from majordom_integration_sdk.schemas.parameter import ParameterUnit # ESPHome reports a unit string per entity; it is exact, so it wins over the device class. UNITS_BY_SYMBOL: dict[str, ParameterUnit] = { "°c": ParameterUnit.celsius, "k": ParameterUnit.kelvin, "%": ParameterUnit.percentage, "pa": ParameterUnit.pascal, "lx": ParameterUnit.lux, "w": ParameterUnit.watt, "kwh": ParameterUnit.kwh, "j": ParameterUnit.joule, "a": ParameterUnit.ampere, "v": ParameterUnit.volt, "hz": ParameterUnit.hertz, "ppm": ParameterUnit.ppm, "µg/m³": ParameterUnit.ugm3, "μg/m³": ParameterUnit.ugm3, "ug/m3": ParameterUnit.ugm3, "m": ParameterUnit.meters, "m/s": ParameterUnit.mps, "s": ParameterUnit.second, "kg": ParameterUnit.kilogram, "rpm": ParameterUnit.rpm, } # Used only when the entity declares no unit of its own. UNITS_BY_DEVICE_CLASS: dict[str, ParameterUnit] = { "temperature": ParameterUnit.celsius, "humidity": ParameterUnit.percentage, "moisture": ParameterUnit.percentage, "battery": ParameterUnit.percentage, "illuminance": ParameterUnit.lux, "power": ParameterUnit.watt, "voltage": ParameterUnit.volt, "current": ParameterUnit.ampere, "frequency": ParameterUnit.hertz, "pm25": ParameterUnit.ugm3, "pm10": ParameterUnit.ugm3, "carbon_dioxide": ParameterUnit.ppm, "carbon_monoxide": ParameterUnit.ppm, } def get_unit(device_class: str | None = None, unit_of_measurement: str | None = None) -> ParameterUnit: if unit_of_measurement: return UNITS_BY_SYMBOL.get(unit_of_measurement.lower(), ParameterUnit.plain) return UNITS_BY_DEVICE_CLASS.get(device_class or "", ParameterUnit.plain) ================================================================================ # FILE: majordom_esphome/generic.py ================================================================================ """Generic mapping for entities without a hand-written one, derived from `aioesphomeapi`'s own types. A parameter is made for every field of the entity's state class (read-only, unless the entity's command accepts that field on its own) and for every other command argument that can be sent on its own. Value types come from the annotations: bool, int, float, str and the library's integer enums (labelled with their member names). Beyond single fields: - an integer state that is a bit mask of a `StateFlag` (a water heater's ON, AWAY) becomes one bool per flag; - a command that needs several arguments at once (a date: year, month, day) becomes one `struct` parameter whose sub-parameters are the arguments, readable and writable; - an optional argument that can only be sent together with a required one (a lock's `code` next to its `command`) becomes a `struct` command whose sub-parameters are both arguments, plus a `setting` holding a default for it (a default code) that every command of the entity falls back to when it is sent without one. Commands with arguments are `struct` parameters with the arguments as `fields`, as the SDK describes. Hand-written mappings (`mapper.py`) win where the generic result is not good enough for the user. """ import dataclasses import inspect import math import typing from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass from enum import IntEnum, IntFlag from functools import cache from types import UnionType from typing import Any import aioesphomeapi from aioesphomeapi import COMPONENT_TYPE_TO_INFO, APIClient, EntityState, LightColorCapability, WaterHeaterFeature from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from .models import ESPhomeParameter, ParameterSpec # No parameters make sense for these: a camera stream, one-shot events, raw infrared / radio frames SKIPPED = {"camera", "event", "infrared", "radio_frequency"} STATE_NOISE = {"key", "device_id", "missing_state"} # ESPHome reports these as fractions (0-1); MajorDom expresses them as percentages FRACTIONS = {"position", "tilt", "volume", "brightness", "white", "color_brightness"} # Already percentages (0-100) in ESPHome PERCENT_VALUES = {"current_humidity", "target_humidity"} UNITS = { "color_temperature": ParameterUnit.mired, "current_humidity": ParameterUnit.percentage, "target_humidity": ParameterUnit.percentage, # ESPHome works in °C (as the hand-written climate mapping assumes) "current_temperature": ParameterUnit.celsius, "target_temperature": ParameterUnit.celsius, "target_temperature_low": ParameterUnit.celsius, "target_temperature_high": ParameterUnit.celsius, } # Kinds that are infrastructure, not a device feature: hidden (docs, Parameter UX: "firmware update -> system") SYSTEM_KINDS = {"update"} def _caps(entity: Any) -> int: """ColorMode values are bit masks of LightColorCapability, e.g. 35 = ON_OFF | BRIGHTNESS | RGB.""" mask = 0 for mode in entity.supported_color_modes: mask |= int(mode) return mask # What an entity can do is declared on its info, not on its state: a parameter is only made when the entity says it # supports the field. Keyed by (component, field); fields without an entry are always made. GATES: dict[tuple[str, str], Callable[[Any], bool]] = { ("fan", "speed_level"): lambda e: e.supports_speed, ("fan", "oscillating"): lambda e: e.supports_oscillation, ("fan", "direction"): lambda e: e.supports_direction, ("fan", "preset_mode"): lambda e: bool(e.supported_preset_modes), ("cover", "tilt"): lambda e: e.supports_tilt, ("cover", "stop"): lambda e: e.supports_stop, ("cover", "stop_tilt"): lambda e: e.supports_stop_tilt, ("cover", "toggle"): lambda e: e.supports_toggle, # cold/warm white lights are driven through the colour temperature, their two channels are an implementation detail ("light", "color_temperature"): lambda e: bool( _caps(e) & (LightColorCapability.COLOR_TEMPERATURE | LightColorCapability.COLD_WARM_WHITE) ), ("light", "white"): lambda e: bool(_caps(e) & LightColorCapability.WHITE), # the colour part's own brightness only matters when colour and white channels mix ("light", "color_brightness"): lambda e: ( bool(_caps(e) & LightColorCapability.RGB) and bool(_caps(e) & (LightColorCapability.WHITE | LightColorCapability.COLD_WARM_WHITE)) ), ("light", "effect"): lambda e: bool(e.effects), ("climate", "action"): lambda e: e.supports_action, ("climate", "fan_mode"): lambda e: bool(e.supported_fan_modes), ("climate", "swing_mode"): lambda e: bool(e.supported_swing_modes), ("climate", "preset"): lambda e: bool(e.supported_presets), ("climate", "custom_fan_mode"): lambda e: bool(e.supported_custom_fan_modes), ("climate", "custom_preset"): lambda e: bool(e.supported_custom_presets), ("climate", "current_humidity"): lambda e: e.supports_current_humidity, ("climate", "target_humidity"): lambda e: e.supports_target_humidity, ("water_heater", "current_temperature"): lambda e: bool( e.supported_features & WaterHeaterFeature.SUPPORTS_CURRENT_TEMPERATURE ), ("water_heater", "target_temperature"): lambda e: ( bool(e.supported_features & WaterHeaterFeature.SUPPORTS_TARGET_TEMPERATURE) and not e.supported_features & WaterHeaterFeature.SUPPORTS_TWO_POINT_TARGET_TEMPERATURE ), ("water_heater", "target_temperature_low"): lambda e: bool( e.supported_features & WaterHeaterFeature.SUPPORTS_TWO_POINT_TARGET_TEMPERATURE ), ("water_heater", "target_temperature_high"): lambda e: bool( e.supported_features & WaterHeaterFeature.SUPPORTS_TWO_POINT_TARGET_TEMPERATURE ), ("water_heater", "mode"): lambda e: bool(e.supported_features & WaterHeaterFeature.SUPPORTS_OPERATION_MODE), ("water_heater", "away"): lambda e: bool(e.supported_features & WaterHeaterFeature.SUPPORTS_AWAY_MODE), ("water_heater", "on"): lambda e: bool(e.supported_features & WaterHeaterFeature.SUPPORTS_ON_OFF), # a command with a code is only offered where the entity asks for one ("lock", "command_with_code"): lambda e: e.requires_code, ("alarm_control_panel", "command_with_code"): lambda e: e.requires_code or e.requires_code_to_arm, } # String fields that are a choice from a list on the info: made as enums (index <-> option), like a select OPTIONS: dict[tuple[str, str], Callable[[Any], list[str]]] = { ("fan", "preset_mode"): lambda e: list(e.supported_preset_modes), ("light", "effect"): lambda e: list(e.effects), ("climate", "custom_fan_mode"): lambda e: list(e.supported_custom_fan_modes), ("climate", "custom_preset"): lambda e: list(e.supported_custom_presets), } # Enum fields of which the entity supports only some members SUBSETS: dict[tuple[str, str], Callable[[Any], Iterable[IntEnum]]] = { ("climate", "fan_mode"): lambda e: e.supported_fan_modes, ("climate", "swing_mode"): lambda e: e.supported_swing_modes, ("climate", "preset"): lambda e: e.supported_presets, ("water_heater", "mode"): lambda e: e.supported_modes, } def _range(low: float, high: float) -> tuple[float | None, float | None]: """Limits an entity reports, or none when it reports nothing (both zero).""" return (low, high) if high > low else (None, None) # Limits the entity reports LIMITS: dict[tuple[str, str], Callable[[Any], tuple[float | None, float | None]]] = { ("fan", "speed_level"): lambda e: (0, e.supported_speed_count), ("light", "color_temperature"): lambda e: (e.min_mireds, e.max_mireds), ("climate", "target_humidity"): lambda e: (e.visual_min_humidity, e.visual_max_humidity), ("water_heater", "target_temperature"): lambda e: _range(e.min_temperature, e.max_temperature), ("water_heater", "target_temperature_low"): lambda e: _range(e.min_temperature, e.max_temperature), ("water_heater", "target_temperature_high"): lambda e: _range(e.min_temperature, e.max_temperature), } # Bounds of calendar and clock fields, whatever the entity FIELD_LIMITS: dict[str, tuple[float, float]] = { "month": (1, 12), "day": (1, 31), "hour": (0, 23), "minute": (0, 59), "second": (0, 59), } @dataclass(frozen=True) class Field: name: str kind: type # bool, int, float, str, an IntEnum, or dict for a group of arguments (see `children`) in_state: bool in_command: bool # the command accepts it on its own is_flag: bool = False # a command-only bool: "do it" bit: tuple[str, int] | None = None # a flag inside an integer state field: (that field, the flag's mask) children: tuple["Field", ...] = () # the arguments sent together: a `struct` value or a command with arguments @property def is_group(self) -> bool: return bool(self.children) @property def fraction(self) -> bool: return self.kind is float and self.name in FRACTIONS def _hints(obj: Any) -> dict[str, Any]: try: return typing.get_type_hints(obj) except Exception: # annotations that only resolve inside the library's own namespace return { name: eval(annotation, vars(aioesphomeapi)) if isinstance(annotation, str) else annotation for name, annotation in getattr(obj, "__annotations__", {}).items() } def _kind(annotation: Any) -> type | None: if typing.get_origin(annotation) in (typing.Union, UnionType): options = [a for a in typing.get_args(annotation) if a is not type(None)] else: options = [annotation] if len(options) != 1: return None kind = options[0] if kind in (bool, int, float, str): return kind if isinstance(kind, type) and issubclass(kind, IntEnum): return kind return None def _state_class(component: str) -> type[EntityState] | None: base = COMPONENT_TYPE_TO_INFO[component].__name__.removesuffix("Info") for name in (f"{base}State", f"{base}EntityState"): candidate = getattr(aioesphomeapi, name, None) if dataclasses.is_dataclass(candidate) and issubclass(candidate, EntityState): return candidate return None def api_fields(component: str) -> tuple[set[str], set[str]]: """Every field of the entity's state and every argument of its command, whether or not it is mapped.""" state_class = _state_class(component) state = ( {f.name for f in dataclasses.fields(typing.cast(Any, state_class)) if f.name not in STATE_NOISE} if state_class is not None else set() ) command = getattr(APIClient, f"{component}_command", None) arguments = ( {name for name in inspect.signature(command).parameters if name not in ("self", "key", "device_id")} if command is not None else set() ) return state, arguments @cache def fields_of(component: str) -> tuple[Field, ...]: state_class = _state_class(component) state_kinds: dict[str, type | None] = {} if state_class is not None: hints = _hints(state_class) state_kinds = { f.name: _kind(hints.get(f.name)) for f in dataclasses.fields(typing.cast(Any, state_class)) if f.name not in STATE_NOISE } command = getattr(APIClient, f"{component}_command", None) command_kinds: dict[str, type | None] = {} required: set[str] = set() if command is not None: hints = _hints(command) for name, parameter in inspect.signature(command).parameters.items(): if name in ("self", "key", "device_id"): continue command_kinds[name] = _kind(hints.get(name)) if parameter.default is inspect.Parameter.empty: required.add(name) # an argument can only be sent alone if it is the only one the command insists on sendable = {name for name, kind in command_kinds.items() if kind is not None and required <= {name}} simple_required = all(command_kinds[name] is not None for name in required) # several required arguments that are also the state (a date: year, month, day): one struct value grouped: set[str] = set() result: list[Field] = [] if len(required) > 1 and simple_required: children = tuple(Field(n, command_kinds[n] or int, n in state_kinds, True) for n in _ordered(command, required)) result.append(Field(component, dict, all(c.in_state for c in children), True, children=children)) grouped = set(required) # an integer state that is a bit mask of flags the command sets one by one (a water heater's ON, AWAY) flags = _flag_class(component) flagged: set[str] = set() for name, kind in state_kinds.items(): if kind is int and flags is not None: for member in flags: flag = (member.name or "").lower() if command_kinds.get(flag) is bool: result.append(Field(flag, bool, True, flag in sendable, bit=(name, int(member)))) flagged |= {name, flag} skip = grouped | flagged result += [ Field(name, kind, True, name in sendable) for name, kind in state_kinds.items() if kind is not None and name not in skip ] for name in sendable - set(state_kinds) - skip: kind = command_kinds[name] assert kind is not None result.append(Field(name, kind, False, True, is_flag=kind is bool)) # an optional argument that can only travel with the required one (a lock's code): a command with arguments if required and len(required) == 1 and simple_required: (main,) = required for name, kind in command_kinds.items(): if name not in sendable and name not in required and kind is not None and name not in state_kinds: main_field = Field(main, command_kinds[main] or int, False, True) children = (main_field, Field(name, kind, False, True)) result.append(Field(f"{main}_with_{name}", dict, False, True, children=children)) return tuple(result) def _ordered(command: Any, names: set[str]) -> list[str]: return [name for name in inspect.signature(command).parameters if name in names] def _flag_class(component: str) -> type[IntFlag] | None: base = COMPONENT_TYPE_TO_INFO[component].__name__.removesuffix("Info") candidate = getattr(aioesphomeapi, f"{base}StateFlag", None) return candidate if isinstance(candidate, type) and issubclass(candidate, IntFlag) else None def is_mapped(component: str) -> bool: return component not in SKIPPED and bool(fields_of(component)) def specs(component: str, entity: Any = None, skip: frozenset[str] = frozenset()) -> list[ParameterSpec]: """Parameters of the entity's fields, except `skip` (what a hand-written mapping already covers). With the entity, what it does not support is left out, enums are limited to what it supports, option lists become enums and the limits it reports are used. """ result = [] for field in fields_of(component): if field.name not in skip and (spec := _spec(component, field, entity)) is not None: result.append(spec) result += _defaults(field, spec) if component in SYSTEM_KINDS: result = [dataclasses.replace(spec, visibility=ParameterVisibility.system) for spec in result] return result def _defaults(field: Field, spec: ParameterSpec) -> list[ParameterSpec]: """The kept default of a command's optional argument (a lock's default code), offered next to that command.""" if not field.is_group or field.in_state or len(spec.fields) < 2: return [] optional = spec.fields[-1] return [ dataclasses.replace(optional, role=ParameterRole.control, visibility=ParameterVisibility.setting, local=True) ] def _spec(component: str, field: Field, entity: Any) -> ParameterSpec | None: key = (component, field.name) if entity is not None and key in GATES and not GATES[key](entity): return None role = ParameterRole.control if field.in_command else ParameterRole.sensor if field.is_group: children = tuple(spec for child in field.children if (spec := _spec(component, child, entity)) is not None) return ParameterSpec(field.name, ParameterDataType.struct, role, fields=children) unit = UNITS.get(field.name, ParameterUnit.plain) low, high = ( LIMITS[key](entity) if entity is not None and key in LIMITS else FIELD_LIMITS.get(field.name, (None, None)) ) if field.is_flag: return ParameterSpec(field.name, ParameterDataType.none, role) if entity is not None and key in OPTIONS: return ParameterSpec( field.name, ParameterDataType.enum, role, valid_values=dict(enumerate(OPTIONS[key](entity))) ) if issubclass(field.kind, IntEnum): members = SUBSETS[key](entity) if entity is not None and key in SUBSETS else field.kind return ParameterSpec(field.name, ParameterDataType.enum, role, valid_values={int(m): m.name for m in members}) if field.kind is bool: return ParameterSpec(field.name, ParameterDataType.bool, role) if field.kind is int: return ParameterSpec(field.name, ParameterDataType.integer, role, unit, low, high) if field.kind is float and field.fraction: return ParameterSpec(field.name, ParameterDataType.decimal, role, ParameterUnit.percentage, 0, 100) if field.kind is float: return ParameterSpec(field.name, ParameterDataType.decimal, role, unit, low, high) return ParameterSpec(field.name, ParameterDataType.string, role) def state_values( component: str, state: EntityState, skip: frozenset[str] = frozenset(), entity: Any = None ) -> dict[str, Any]: """Current values by field name; a `struct` value is a dict of its fields by name.""" if getattr(state, "missing_state", False): return {} values: dict[str, Any] = {} for field in fields_of(component): if not field.in_state or field.name in skip: continue if field.is_group: group = { child.name: _to_hub(component, child, getattr(state, child.name, None), entity) for child in field.children } if all(value is not None for value in group.values()): values[field.name] = group continue source = field.bit[0] if field.bit else field.name value = _to_hub(component, field, getattr(state, source, None), entity) if value is not None: values[field.name] = value return values def _to_hub(component: str, field: Field, value: Any, entity: Any) -> Any: """A state value as the parameter's plain value, or None when there is nothing to report.""" if value is None: return None key = (component, field.name) if field.bit is not None: return bool(int(value) & field.bit[1]) if key in OPTIONS and entity is not None: options = OPTIONS[key](entity) return options.index(value) if value in options else None # an empty choice: nothing selected if field.kind is float: if math.isnan(value): return None return round(value * 100, 2) if field.fraction else float(value) if field.kind is bool: return bool(value) if field.kind is str: return str(value) value = int(value) # int and the library's integer enums: plain int if key in SUBSETS and entity is not None and value not in {int(m) for m in SUBSETS[key](entity)}: return None # e.g. "no preset": not one of the choices the entity offers return value def as_bool(value: Any) -> bool: if value not in (True, False): # also accepts 0 and 1 raise ValueError(f"Expected a boolean, got {value!r}") return bool(value) def as_number(value: Any, parameter: ESPhomeParameter) -> float: try: number = float(value) except (TypeError, ValueError) as exc: raise ValueError(f"Expected a number, got {value!r}") from exc low, high = parameter.min_value, parameter.max_value if (low is not None and number < low) or (high is not None and number > high): raise ValueError(f"{parameter.name}: {number} is outside {low}..{high}") return number def enum_key(parameter: ESPhomeParameter, value: Any) -> int: """The `valid_values` key a command value names: the key (also as a numeric string, as JSON may carry it) or its label, the option or member name. A string is a label first: an option named "2" is that option, not the third. """ options = parameter.valid_values or {} if isinstance(value, str): labels = {label: key for key, label in options.items()} if value in labels: return labels[value] value = int(value) if value.isdecimal() else value # True equals 1, yet names no option if isinstance(value, bool) or not isinstance(value, int | float) or value not in options: raise ValueError(f"{parameter.name}: no option {value!r}") return int(value) def command_args( component: str, parameter: ESPhomeParameter, value: Any, settings: Mapping[str, Any] | None = None ) -> dict[str, Any]: """Keyword arguments (without the key) of the `_command` method that applies `value`. `settings` are the entity's kept defaults (field -> value): an optional argument left out falls back to them. """ settings = settings or {} name = parameter.integration_data.sub_field or "" field = next((f for f in fields_of(component) if f.name == name and f.in_command), None) if field is None: raise ValueError(f"{parameter.name} cannot be set") if field.is_group: return _group_args(component, field, parameter, value, settings) args = {name: _to_device(component, field, parameter, value)} for group in fields_of(component): # e.g. a plain lock command still carries the default code if group.is_group and not group.in_state and group.children[0].name == name: args |= {o.name: settings[o.name] for o in group.children[1:] if settings.get(o.name) is not None} return args def _group_args( component: str, field: Field, parameter: ESPhomeParameter, value: Any, settings: Mapping[str, Any] ) -> dict[str, Any]: """The arguments of a group: the value is a dict keyed by sub-parameter id (as the SDK specifies) or name. In a command with an optional argument (`
_with_`) the optional one may be left out: its kept default is used, if any. """ if not isinstance(value, dict): raise ValueError(f"{parameter.name}: expected the values of {[c.name for c in field.children]}, got {value!r}") children = {sub.integration_data.sub_field: sub for sub in sub_parameters(parameter)} by_key = {str(key): item for key, item in value.items()} args = {} for child in field.children: sub = children.get(child.name) if sub is None: continue # not offered by this entity raw = by_key.get(str(sub.id), by_key.get(child.name)) if raw is None and not field.in_state and child is not field.children[0]: # an optional argument if settings.get(child.name) is not None: args[child.name] = settings[child.name] continue if raw is None: raise ValueError(f"{parameter.name}: {child.name} is missing") args[child.name] = _to_device(component, child, sub, raw) return args def sub_parameters(parameter: ESPhomeParameter) -> list[ESPhomeParameter]: """The parameter's sub-parameters, also when they come back from storage as plain dicts.""" return [ sub if isinstance(sub, ESPhomeParameter) else ESPhomeParameter.model_validate(sub) for sub in parameter.fields or [] ] def _to_device(component: str, field: Field, parameter: ESPhomeParameter, value: Any) -> Any: """A parameter value as the argument the library's command takes.""" if field.is_flag: return True if (component, field.name) in OPTIONS: return (parameter.valid_values or {})[enum_key(parameter, value)] if issubclass(field.kind, IntEnum): return field.kind(enum_key(parameter, value)) if field.kind is bool: return as_bool(value) if field.kind is float: number = as_number(value, parameter) return number / 100 if field.fraction else number if field.kind is int: return int(as_number(value, parameter)) return str(value) ================================================================================ # FILE: majordom_esphome/improv.py ================================================================================ """Wi-Fi setup of unprovisioned ESPHome nodes over Improv BLE, through the SDK's `BLERouter`, so a node is reached by whichever radio hears it best: the Hub's own adapter or another ESPHome node lending its Bluetooth. `py-improv-ble-client` (the library HA uses) supplies only the protocol: the advert filter and the frames. A node built with `esp32_improv` (`improv_ble` from ESPHome 2026.11) and no Wi-Fi networks advertises the Improv service; it is given the Hub's Wi-Fi over BLE, joins the LAN and then announces itself over mDNS like any other node. """ import asyncio import contextlib from collections.abc import Awaitable, Callable from aioesphomeapi import APIConnectionError from bleak.exc import BleakError from improv_ble_client import SERVICE_UUID, Error, State from improv_ble_client import device_filter as waits_for_wifi from improv_ble_client.errors import ImprovError from improv_ble_client.protocol import ( CHARACTERISTIC_UUID_ERROR, CHARACTERISTIC_UUID_RPC_COMMAND, CHARACTERISTIC_UUID_RPC_RESULT, CHARACTERISTIC_UUID_STATE, WiFiSettingsCmd, WiFiSettingsRes, parse_result, ) from majordom_integration_sdk.capabilities import BLEBusyError, BLEConnection, BLERouter __all__ = ["SERVICE_UUID", "SetupError", "is_node", "provision", "waits_for_wifi"] AUTHORIZATION_TIMEOUT = 60.0 # for the user to press the node's button PROVISION_TIMEOUT = 90.0 # from giving the node the Wi-Fi to its answer LEASE_TIMEOUT = 30.0 # for a radio that hears the node to free up BLE_NAME_LENGTH = 20 # ESPHome cuts the name it advertises to this, keeping a `-xxxxxx` MAC suffix OWNER = "esphome-improv" NOTIFYING = (CHARACTERISTIC_UUID_STATE, CHARACTERISTIC_UUID_ERROR, CHARACTERISTIC_UUID_RPC_RESULT) PRESS_BUTTON = "Press the button on the device to let the Hub set it up" NO_ANSWER = "The device did not answer over Bluetooth: move it closer to the Hub" BUSY = "The Hub's Bluetooth is busy with another device: try again in a minute" class SetupError(Exception): """The node could not be set up over BLE; the message is meant for the user.""" def is_node(ble_name: str, node_name: str) -> bool: """Whether the name a node advertises over BLE is its node name (the one it announces over mDNS).""" if len(node_name) <= BLE_NAME_LENGTH: return ble_name == node_name return ble_name in (node_name[:BLE_NAME_LENGTH], node_name[:13] + node_name[-7:]) async def provision( ble: BLERouter, address: str, ssid: str, password: str, on_authorization_required: Callable[[], Awaitable[None]], ): """Give the node the Wi-Fi network; returns once it has joined it (ESPHome reports a failure after its `wifi_timeout`). The radio that hears the node best is held for the whole exchange. Raises `SetupError`.""" try: async with ble.exclusive(address, owner=OWNER, timeout=LEASE_TIMEOUT) as lease: connection = await lease.connect() try: await _provision(connection, ssid, password, on_authorization_required) finally: with contextlib.suppress(Exception): await connection.disconnect() except BLEBusyError as exc: raise SetupError(BUSY) from exc # BleakError and APIConnectionError: what a local adapter's and an ESPHome node's connections raise, until the SDK # normalises them except (ConnectionError, TimeoutError, LookupError, ValueError, ImprovError, BleakError, APIConnectionError) as exc: raise SetupError(NO_ANSWER) from exc async def _provision( connection: BLEConnection, ssid: str, password: str, on_authorization_required: Callable[[], Awaitable[None]] ): (service,) = (s for s in await connection.services() if s.uuid.lower() == SERVICE_UUID) handles = {c.uuid.lower(): c.handle for c in service.characteristics} events: asyncio.Queue[tuple[str, bytes]] = asyncio.Queue() for uuid in NOTIFYING: await connection.start_notify(handles[uuid], lambda data, uuid=uuid: events.put_nowait((uuid, data))) if State((await connection.read(handles[CHARACTERISTIC_UUID_STATE]))[0]) == State.AUTHORIZATION_REQUIRED: await on_authorization_required() authorized = (CHARACTERISTIC_UUID_STATE, bytes([State.AUTHORIZED])) try: async with asyncio.timeout(AUTHORIZATION_TIMEOUT): while await events.get() != authorized: pass except TimeoutError: raise SetupError(f"{PRESS_BUTTON}, then pair it again") from None command = WiFiSettingsCmd(ssid.encode(), password.encode()).as_bytes() await connection.write(handles[CHARACTERISTIC_UUID_RPC_COMMAND], command, is_response_needed=True) async with asyncio.timeout(PROVISION_TIMEOUT): while True: uuid, data = await events.get() if uuid == CHARACTERISTIC_UUID_ERROR and (error := Error(data[0])) != Error.NO_ERROR: raise SetupError(_describe(error, ssid)) if uuid == CHARACTERISTIC_UUID_RPC_RESULT and isinstance(parse_result(data), WiFiSettingsRes): return def _describe(error: Error, ssid: str) -> str: if error == Error.UNABLE_TO_CONNECT: return f"The device could not join the Wi-Fi network {ssid}: check that it is a 2.4 GHz network in range" if error == Error.NOT_AUTHORIZED: return f"{PRESS_BUTTON}, then pair it again" return "The device could not be set up over Bluetooth" ================================================================================ # FILE: majordom_esphome/mapper.py ================================================================================ """Translation between ESPHome entities/states/commands and MajorDom parameters/values/commands.""" import colorsys import math from collections.abc import Mapping from dataclasses import replace from enum import IntEnum from typing import Any from aioesphomeapi import ( COMPONENT_TYPE_TO_INFO, BinarySensorState, ClimateInfo, ClimateMode, ClimateState, CoverInfo, CoverState, EntityCategory, EntityInfo, EntityState, FanState, LightColorCapability, LightInfo, LightState, NumberInfo, NumberState, SelectInfo, SelectState, SensorInfo, SensorState, SwitchState, TextSensorState, ) from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from . import generic from .esphome_spec import get_unit from .generic import as_bool as _as_bool from .generic import as_number as _as_number from .models import ESPhomeComponentType, ESPhomeParameter, ESPhomeParameterType, ParameterSpec # The library's own registry covers every entity ESPHome knows; only the types in ESPhomeComponentType are mapped. _COMPONENT_BY_INFO: dict[type[EntityInfo], str] = {info: name for name, info in COMPONENT_TYPE_TO_INFO.items()} PERCENT = ParameterUnit.percentage # MajorDom expresses levels, positions and saturation as 0-100 PARAMETER_TYPE: dict[ESPhomeComponentType, ESPhomeParameterType] = { ESPhomeComponentType.SENSOR: ESPhomeParameterType.SENSOR, ESPhomeComponentType.BINARY_SENSOR: ESPhomeParameterType.SENSOR, ESPhomeComponentType.TEXT_SENSOR: ESPhomeParameterType.SENSOR, ESPhomeComponentType.NUMBER: ESPhomeParameterType.NUMBER, ESPhomeComponentType.SELECT: ESPhomeParameterType.SELECT, ESPhomeComponentType.BUTTON: ESPhomeParameterType.BUTTON, } COVER_OPERATIONS = { 0: "IDLE", 1: "IS_OPENING", 2: "IS_CLOSING", } # labels are the enum names, as in the other integrations _HAND_WRITTEN = {component.value for component in ESPhomeComponentType} # Fields of the state and command that the hand-written mapping covers (under the same or another name) or that are # no values; the generic mapping adds every other field the entity supports, as `setting` parameters. HANDLED: dict[str, frozenset[str]] = { "binary_sensor": frozenset({"state"}), "sensor": frozenset({"state"}), "text_sensor": frozenset({"state"}), "switch": frozenset({"state"}), "number": frozenset({"state"}), "select": frozenset({"state"}), "button": frozenset(), "fan": frozenset({"state", "speed"}), # `speed` is the legacy three-step enum, speed_level replaces it "cover": frozenset({"position", "current_operation", "legacy_state"}), "light": frozenset( {"state", "brightness", "red", "green", "blue", "rgb", "color_mode"} | {"cold_white", "warm_white"} # the channels behind color_temperature | {"flash_length", "transition_length"} # the flash command and the transition setting below ), "climate": frozenset( {"mode", "current_temperature", "target_temperature", "target_temperature_low", "target_temperature_high"} | {"unused_legacy_away"} ), } def component_type_of(entity: EntityInfo) -> str | None: """The library's name of an entity's kind, or None if it has nothing to map (a camera, an event, ...).""" component = _COMPONENT_BY_INFO.get(type(entity)) if component in _HAND_WRITTEN or (component is not None and generic.is_mapped(component)): return component return None def visibility_of(entity: EntityInfo) -> ParameterVisibility: if entity.disabled_by_default: return ParameterVisibility.system if entity.entity_category != EntityCategory.NONE: # configuration and diagnostics return ParameterVisibility.setting return ParameterVisibility.user def parameter_specs(entity: EntityInfo, component: str) -> list[ParameterSpec]: if component not in _HAND_WRITTEN: return generic.specs(component, entity) extra = generic.specs(component, entity, skip=HANDLED[component]) return _hand_written_specs(entity, ESPhomeComponentType(component)) + [ replace(spec, visibility=ParameterVisibility.setting) for spec in extra ] def _hand_written_specs(entity: EntityInfo, component: ESPhomeComponentType) -> list[ParameterSpec]: control, sensor = ParameterRole.control, ParameterRole.sensor decimal, boolean = ParameterDataType.decimal, ParameterDataType.bool unit = get_unit(getattr(entity, "device_class", None), getattr(entity, "unit_of_measurement", None)) match component, entity: case ESPhomeComponentType.SWITCH | ESPhomeComponentType.FAN, _: return [ParameterSpec("state", boolean, control)] case ESPhomeComponentType.BINARY_SENSOR, _: return [ParameterSpec("state", boolean, sensor)] case ESPhomeComponentType.TEXT_SENSOR, _: return [ParameterSpec("state", ParameterDataType.string, sensor)] case ESPhomeComponentType.SENSOR, SensorInfo(): return [ParameterSpec("state", decimal, sensor, unit)] case ESPhomeComponentType.BUTTON, _: return [ParameterSpec("state", ParameterDataType.none, control)] case ESPhomeComponentType.NUMBER, NumberInfo(): return [ ParameterSpec("state", decimal, control, unit, entity.min_value, entity.max_value, entity.step or None) ] case ESPhomeComponentType.SELECT, SelectInfo(): options: dict[int, str] = dict(enumerate(entity.options)) return [ParameterSpec("state", ParameterDataType.enum, control, valid_values=options)] case ESPhomeComponentType.LIGHT, LightInfo(): # ColorMode values are bit masks of LightColorCapability, e.g. 35 = ON_OFF | BRIGHTNESS | RGB capabilities = 0 for mode in entity.supported_color_modes: capabilities |= int(mode) specs = [ParameterSpec("state", boolean, control)] if capabilities & LightColorCapability.BRIGHTNESS: specs.append(ParameterSpec("brightness", decimal, control, PERCENT, 0, 100)) if capabilities & LightColorCapability.RGB: specs += [ ParameterSpec("color_hue", decimal, control, ParameterUnit.arcdegree, 0, 360), ParameterSpec("color_saturation", decimal, control, PERCENT, 0, 100), ] setting = ParameterVisibility.setting seconds = ParameterUnit.second specs += [ # how long every later change of this light fades: kept here, added to each light command ParameterSpec("transition_length", decimal, control, seconds, 0, None, visibility=setting, local=True), # flash the light for a while: a command with one argument ParameterSpec( "flash", ParameterDataType.struct, control, visibility=setting, fields=(ParameterSpec("length", decimal, control, seconds, 0, None),), ), ] return specs case ESPhomeComponentType.COVER, CoverInfo(): return [ ParameterSpec("position", decimal, control, PERCENT, 0, 100), ParameterSpec("operation", ParameterDataType.enum, sensor, valid_values=COVER_OPERATIONS), ] case ESPhomeComponentType.CLIMATE, ClimateInfo(): celsius = ParameterUnit.celsius low, high = entity.visual_min_temperature, entity.visual_max_temperature step = entity.visual_target_temperature_step or None modes: dict[int, str] = {int(mode): mode.name for mode in entity.supported_modes} specs = [ParameterSpec("mode", ParameterDataType.enum, control, valid_values=modes)] if entity.supports_current_temperature: specs.append(ParameterSpec("current_temperature", decimal, sensor, celsius)) targets = ("target_temperature_low", "target_temperature_high") if not entity.supports_two_point_target_temperature: targets = ("target_temperature",) return specs + [ParameterSpec(t, decimal, control, celsius, low, high, step) for t in targets] return [] def _number(value: float | None) -> float | None: return None if value is None or math.isnan(value) else float(value) def _percent(value: float | None) -> float | None: """ESPHome levels are 0-1.""" number = _number(value) return None if number is None else round(number * 100, 2) def _hue_saturation(state: LightState) -> dict[str, float]: """Colour as the human model MajorDom uses (hue in degrees, saturation in percent), from ESPHome's RGB. Brightness is a parameter of its own, so only the colour is kept; black has no hue and reports nothing. """ if state.red is None or state.green is None or state.blue is None: return {} hue, saturation, value = colorsys.rgb_to_hsv(state.red, state.green, state.blue) if value == 0: return {} return {"color_hue": round(hue * 360, 1), "color_saturation": round(saturation * 100, 1)} def _index(value: IntEnum | None) -> int | None: return None if value is None else int(value) def state_values(entity: EntityInfo, state: EntityState) -> dict[str, Any]: """Current values by sub-field, as plain Python values of the type the parameters declare.""" values: dict[str, Any] match state: case _ if getattr(state, "missing_state", False): values = {} case LightState(): values = { "state": bool(state.state), "brightness": _percent(state.brightness), **_hue_saturation(state), } case CoverState(): values = {"position": _percent(state.position), "operation": _index(state.current_operation)} case ClimateState(): values = { "mode": _index(state.mode), "current_temperature": _number(state.current_temperature), "target_temperature": _number(state.target_temperature), "target_temperature_low": _number(state.target_temperature_low), "target_temperature_high": _number(state.target_temperature_high), } case SelectState(): options = entity.options if isinstance(entity, SelectInfo) else [] values = {"state": options.index(state.state) if state.state in options else None} case SensorState() | NumberState(): values = {"state": _number(state.state)} case TextSensorState(): values = {"state": str(state.state)} case SwitchState() | BinarySensorState() | FanState(): values = {"state": bool(state.state)} case _: values = {} component = _COMPONENT_BY_INFO.get(type(entity)) if component in _HAND_WRITTEN: values.update(generic.state_values(component, state, HANDLED[component], entity)) elif component: values = generic.state_values(component, state, entity=entity) return {sub_field: value for sub_field, value in values.items() if value is not None} # Settings the integration keeps (nothing is sent to the device when they change), by (component, field) LOCAL_SETTINGS = {("light", "transition_length"), ("lock", "code"), ("alarm_control_panel", "code")} DEFAULT_FLASH_LENGTH = 2.0 # seconds, for a tap that sends no length def is_local(parameter: ESPhomeParameter) -> bool: data = parameter.integration_data return (data.component_type, data.sub_field) in LOCAL_SETTINGS def local_value(parameter: ESPhomeParameter, value: Any) -> Any: """A setting's value as it is kept, validated like a command value; an empty value clears it.""" if value is None or value == "": return None if parameter.data_type == ParameterDataType.decimal: return _as_number(value, parameter) return str(value) if parameter.data_type == ParameterDataType.string else value def build_command_args( parameter: ESPhomeParameter, value: Any, states: Mapping[int, EntityState], settings: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Keyword arguments of the `aioesphomeapi` `_command` method that applies `value`. `settings` are the kept settings of the parameter's entity (field -> value), e.g. a light's transition. """ if parameter.role != ParameterRole.control: raise ValueError(f"{parameter.name} is read-only") if is_local(parameter): raise ValueError(f"{parameter.name} is a setting: nothing is sent to the device") data = parameter.integration_data sub_field = data.sub_field assert data.service_key is not None args: dict[str, Any] = {"key": data.service_key} match data.component_type, sub_field: case ESPhomeComponentType.SWITCH | ESPhomeComponentType.FAN, "state": args["state"] = _as_bool(value) case ESPhomeComponentType.LIGHT, "state": args["state"] = _as_bool(value) case ESPhomeComponentType.LIGHT, "brightness": args["brightness"] = _as_number(value, parameter) / 100 case ESPhomeComponentType.LIGHT, "flash": (length,) = generic.sub_parameters(parameter) given = value.get(str(length.id), value.get("length")) if isinstance(value, dict) else value args["state"] = True args["flash_length"] = DEFAULT_FLASH_LENGTH if given is None else _as_number(given, length) case ESPhomeComponentType.LIGHT, "color_hue" | "color_saturation": current = states.get(data.service_key) colour = _hue_saturation(current) if isinstance(current, LightState) else {} hue = colour.get("color_hue", 0.0) saturation = colour.get("color_saturation", 100.0) if sub_field == "color_hue": hue = _as_number(value, parameter) else: saturation = _as_number(value, parameter) args["rgb"] = colorsys.hsv_to_rgb(hue / 360, saturation / 100, 1.0) case ESPhomeComponentType.COVER, "position": args["position"] = _as_number(value, parameter) / 100 case ESPhomeComponentType.NUMBER, "state": args["state"] = _as_number(value, parameter) case ESPhomeComponentType.SELECT, "state": args["state"] = (parameter.valid_values or {})[generic.enum_key(parameter, value)] case ESPhomeComponentType.BUTTON, "state": pass case ESPhomeComponentType.CLIMATE, "mode": args["mode"] = ClimateMode(generic.enum_key(parameter, value)) case ESPhomeComponentType.CLIMATE, str() as target if target.startswith("target_temperature"): args[target] = _as_number(value, parameter) case _: # a field the hand-written mapping does not cover: the generic one does args.update(generic.command_args(data.component_type, parameter, value, settings)) transition = (settings or {}).get("transition_length") if data.component_type == ESPhomeComponentType.LIGHT and sub_field != "flash" and transition: args["transition_length"] = float(transition) return args ================================================================================ # FILE: majordom_esphome/models.py ================================================================================ from dataclasses import dataclass from enum import StrEnum from typing import Any from majordom_integration_sdk.schemas.device import Device, DeviceState, Parameter from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from pydantic import BaseModel, Field class ESPhomeParameterType(StrEnum): STATE = "state" SENSOR = "sensor" NUMBER = "number" SELECT = "select" BUTTON = "button" class ESPhomeComponentType(StrEnum): LIGHT = "light" SWITCH = "switch" SENSOR = "sensor" BINARY_SENSOR = "binary_sensor" NUMBER = "number" SELECT = "select" BUTTON = "button" COVER = "cover" FAN = "fan" CLIMATE = "climate" TEXT_SENSOR = "text_sensor" class ESPhomeDeviceIntegrationData(BaseModel): device_name: str | None = None unique_id: str | None = None addresses: list[str] = Field(default_factory=list) # hostname first, then IPs; ordered by past success port: int = 6053 encryption_key: str | None = None mac_address: str | None = None # settings the integration keeps itself (a light's transition): entity object_id -> field -> value settings: dict[str, dict[str, Any]] = Field(default_factory=dict) class ESPhomeParameterIntegrationData(BaseModel): entity_name: str object_id: str | None = None # ESPHome's stable slug of the entity name; parameter ids derive from it component_type: str # the library's name of the entity kind: an ESPhomeComponentType, or any other it reports parameter_type: ESPhomeParameterType service_key: int | None = None sub_field: str | None = None class ESPhomeDevice(Device[ESPhomeDeviceIntegrationData]): parameters: list["ESPhomeParameter"] = Field(default_factory=list) class ESPhomeParameter(Parameter[ESPhomeParameterIntegrationData]): pass class ESPhomeDeviceState(DeviceState[ESPhomeDeviceIntegrationData, ESPhomeParameterIntegrationData]): """The pairing draft the Hub hands over and takes back filled in.""" @dataclass(frozen=True) class ParameterSpec: """What one MajorDom parameter of an entity looks like (everything except identity).""" sub_field: str data_type: ParameterDataType role: ParameterRole unit: ParameterUnit = ParameterUnit.plain min_value: float | None = None max_value: float | None = None min_step: float | None = None valid_values: dict[int, str] | None = None visibility: ParameterVisibility | None = None # None: from the entity # sub-parameters: the fields of a `struct` value, or the arguments of a `none` command that needs several fields: tuple["ParameterSpec", ...] = () local: bool = False # a setting the integration keeps and applies to later commands; nothing is sent for it ================================================================================ # FILE: majordom_esphome/thread_provisioning.py ================================================================================ """Thread setup of unprovisioned ESPHome nodes over BLE, through the SDK's `BLERouter`: the Hub's active operational dataset is written to the node, which joins the Hub's Thread network and then announces itself over mDNS (SRP, through the border router) like any other node. The node side is the `thread_provisioning` external component (ESPHome has no runtime dataset provisioning of its own): an Improv-style GATT service, advertised while the node has no Thread network. Its frames are Improv's: command, length, data, then a checksum (the sum of the previous bytes); a command is written in chunks that fit the connection. """ import asyncio import contextlib from collections.abc import Awaitable, Callable from enum import IntEnum from aioesphomeapi import APIConnectionError from bleak.backends.scanner import AdvertisementData from bleak.exc import BleakError from majordom_integration_sdk.capabilities import BLEBusyError, BLEConnection, BLERouter from .improv import BUSY, NO_ANSWER, PRESS_BUTTON, SetupError __all__ = ["SERVICE_UUID", "provision", "waits_for_thread"] SERVICE_UUID = "aeb52169-9cc0-4883-8ee7-e3d075fbe600" STATE_UUID = "aeb52169-9cc0-4883-8ee7-e3d075fbe601" ERROR_UUID = "aeb52169-9cc0-4883-8ee7-e3d075fbe602" RPC_UUID = "aeb52169-9cc0-4883-8ee7-e3d075fbe603" RESULT_UUID = "aeb52169-9cc0-4883-8ee7-e3d075fbe604" SET_DATASET = 0x01 AUTHORIZATION_TIMEOUT = 60.0 # for the user to press the node's button ATTACH_TIMEOUT = 90.0 # the node gives up after its own `attach_timeout` (60 s by default) and says so LEASE_TIMEOUT = 30.0 # for a radio that hears the node to free up ATT_HEADER = 3 # bytes of a write request that are not its value OWNER = "esphome-thread" NOTIFYING = (STATE_UUID, ERROR_UUID, RESULT_UUID) class State(IntEnum): AWAITING_AUTHORIZATION = 0x01 AUTHORIZED = 0x02 ATTACHING = 0x03 ATTACHED = 0x04 class Error(IntEnum): NONE = 0x00 INVALID_RPC = 0x01 UNKNOWN_RPC = 0x02 UNABLE_TO_ATTACH = 0x03 NOT_AUTHORIZED = 0x04 INVALID_DATASET = 0x05 UNKNOWN = 0xFF def waits_for_thread(advertisement: AdvertisementData) -> bool: """The node advertises the service only while it has no Thread network.""" return SERVICE_UUID in advertisement.service_uuids def frame(command: int, data: bytes) -> bytes: body = bytes([command, len(data)]) + data return body + bytes([sum(body) & 0xFF]) async def provision( ble: BLERouter, address: str, dataset: bytes, on_authorization_required: Callable[[], Awaitable[None]], ): """Give the node the Thread network; returns once it has attached to it. The radio that hears the node best is held for the whole exchange. Raises `SetupError`.""" try: async with ble.exclusive(address, owner=OWNER, timeout=LEASE_TIMEOUT) as lease: connection = await lease.connect() try: await _provision(connection, dataset, on_authorization_required) finally: with contextlib.suppress(Exception): await connection.disconnect() except BLEBusyError as exc: raise SetupError(BUSY) from exc # BleakError and APIConnectionError: what a local adapter's and an ESPHome node's connections raise, until the SDK # normalises them except (ConnectionError, TimeoutError, LookupError, ValueError, BleakError, APIConnectionError) as exc: raise SetupError(NO_ANSWER) from exc async def _provision( connection: BLEConnection, dataset: bytes, on_authorization_required: Callable[[], Awaitable[None]] ): (service,) = (s for s in await connection.services() if s.uuid.lower() == SERVICE_UUID) handles = {c.uuid.lower(): c.handle for c in service.characteristics} events: asyncio.Queue[tuple[str, bytes]] = asyncio.Queue() for uuid in NOTIFYING: await connection.start_notify(handles[uuid], lambda data, uuid=uuid: events.put_nowait((uuid, data))) if State((await connection.read(handles[STATE_UUID]))[0]) == State.AWAITING_AUTHORIZATION: await on_authorization_required() authorized = (STATE_UUID, bytes([State.AUTHORIZED])) try: async with asyncio.timeout(AUTHORIZATION_TIMEOUT): while await events.get() != authorized: pass except TimeoutError: raise SetupError(f"{PRESS_BUTTON}, then pair it again") from None command = frame(SET_DATASET, dataset) size = connection.mtu - ATT_HEADER for start in range(0, len(command), size): await connection.write(handles[RPC_UUID], command[start : start + size], is_response_needed=True) async with asyncio.timeout(ATTACH_TIMEOUT): while True: uuid, data = await events.get() if uuid == ERROR_UUID and (error := Error(data[0])) != Error.NONE: raise SetupError(_describe(error)) if uuid == STATE_UUID and data[0] == State.ATTACHED: return def _describe(error: Error) -> str: if error == Error.UNABLE_TO_ATTACH: return "The device could not join the Hub's Thread network: check that the Hub's border router is in range" if error == Error.INVALID_DATASET: return "The device refused the Hub's Thread network settings" if error == Error.NOT_AUTHORIZED: return f"{PRESS_BUTTON}, then pair it again" return "The device could not be set up over Bluetooth" ================================================================================ # FILE: pyproject.toml ================================================================================ [project] name = "majordom-esphome" version = "0.1.5" description = "ESPHome integration for MajorDom — bridges ESPHome devices into the MajorDom language." authors = [ { name = "Parker Industries" }, { name = "Artem Novosolov @Artem333333", email = "82451512+Artem333333@users.noreply.github.com" }, { name = "Mark Parker @MarkParker5", email = "34688010+MarkParker5@users.noreply.github.com" }, ] readme = "README.md" license = "LicenseRef-PolyForm-Noncommercial-1.0.0" license-files = ["LICENSE"] keywords = [ "majordom", "smart-home", "home-automation", "iot", "esphome", "integration", ] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Home Automation", "Programming Language :: Python :: 3", ] requires-python = ">=3.13" dependencies = [ "majordom-integration-sdk[ble] (>=0.4.0,<1.0)", # a node's Bluetooth reaches the router in bleak's types "aioesphomeapi >=46.26.0", "bluetooth-data-tools >=1.29.24", "pydantic (>=2.14.3,<3.0.0)", "py-improv-ble-client (>=2.0.1,<3)", "bleak-retry-connector (>=4.0)", # py-improv-ble-client imports it without declaring it ] [tool.poetry.dependencies] python = "^3.13" noiseprotocol = ">=0.3.1,<1.0" [project.urls] Homepage = "https://majordom.io" Documentation = "https://docs.majordom.io/device-integration" Repository = "https://github.com/MajorDom-Systems/integration-esphome" "Parker Industries" = "https://parker-industries.org" [dependency-groups] dev = [ "poethepoet (>=0.49.0,<1.0.0)", "majordom-integration-sdk[discovery] (>=0.4.0,<1.0)", # the tests browse over the SDK's DNS-SD provider "ty", "ruff", "pip-audit", "pytest", "pytest-asyncio", "pytest-cov", "pytest-timeout", "pytest-repeat", "pytest-benchmark", "pytest-profiling", "pytest-resource-usage", "coverage", "pympler", "psutil", "faker", ] [build-system] requires = ["poetry-core>=2.0.0,<3.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] requires-poetry = ">=2.0" packages = [{ include = "majordom_esphome" }] [tool.pytest.ini_options] asyncio_mode = "auto" pythonpath = ["."] filterwarnings = ["once"] timeout = 30 # the catalogue sweep builds a node per entity kind: opt in with `-m catalogue` (the monthly canary does) addopts = '-m "not catalogue"' [tool.coverage.run] omit = ["tests/*"] [tool.ruff] line-length = 120 indent-width = 4 [tool.ruff.lint] select = ["E", "F", "UP", "B", "SIM", "I"] fixable = ["ALL"] [tool.ruff.format] quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "tests/*" = ["E402"] [tool.poe.tasks.install] shell = """ poetry install echo '#!/bin/sh\\npoetry run poe check' > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit echo "Pre-commit hook installed." """ [tool.poe.tasks.check] shell = """ code=0 echo "\\nRunning ruff lint:" poetry run ruff check --fix || code=1 echo "\\nRunning ruff format:" poetry run ruff format || code=1 echo "\\nRunning ty:" poetry run ty check || code=1 echo "\\nRunning pytest:" poetry run pytest -v --cov=majordom_esphome --cov-report=xml || code=1 echo "\\nRunning poetry build:" poetry build || code=1 echo "\\nRunning poetry check:" poetry check || code=1 ${ci:+git diff --exit-code} || code=1 exit $code """ args = [{ name = "ci", type = "boolean" }] ================================================================================ # FILE: tests/__init__.py ================================================================================ ================================================================================ # FILE: tests/conftest.py ================================================================================ """Shared pytest fixtures for the MajorDom ESPHome integration.""" from collections.abc import AsyncIterator, Callable, Iterator from typing import Any from unittest.mock import AsyncMock, MagicMock, patch import pytest import pytest_asyncio from aioesphomeapi import EntityInfo from majordom_integration_sdk import Platform from majordom_integration_sdk.peripherals import Peripherals from majordom_integration_sdk.runtime.peripherals.providers.zeroconf import ZeroconfDiscoveryService from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.schemas.parameter import ParameterRole from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests import helpers from tests.helpers import hub_pairs, user_picks from tests.virtual import catalogue from tests.virtual.mdns import Advert, FakeMDNS, fake_mdns from tests.virtual.runner import ENCRYPTED, PLAIN, SKETCHES, VirtualDevice, build, release_ports def pytest_configure(config: pytest.Config): config.addinivalue_line("markers", "catalogue: sweep over one virtual node per entity kind (run with -m catalogue)") @pytest.fixture(scope="session") def build_errors() -> dict[str, str | None]: """Why a catalogue node could not be built (kind -> error), filled in by the collection hook.""" return _BUILD_ERRORS _BUILD_ERRORS: dict[str, str | None] = {} def pytest_collection_finish(session: pytest.Session): """Build the virtual devices before the first test that needs one, outside any test timeout.""" if any( {"device", "encrypted_device", "extras_device", "keyless_device"} & set(getattr(item, "fixturenames", ())) for item in session.items ): for sketch in SKETCHES: if not sketch.binary.exists(): build(sketch) if any(item.get_closest_marker("catalogue") for item in session.items): _BUILD_ERRORS.update(catalogue.build_all()) @pytest.fixture(autouse=True) def _virtual_device_ports() -> Iterator[None]: """Set up first, torn down last: the ports stay this run's until every device of the test has stopped.""" yield release_ports() @pytest.fixture def mdns() -> Iterator[FakeMDNS]: """Zeroconf stubbed out: tests announce nodes explicitly, and nothing touches the network.""" with fake_mdns() as fake: yield fake @pytest.fixture def platform() -> Platform: return build_test_platform() @pytest_asyncio.fixture async def zeroconf(mdns: FakeMDNS) -> AsyncIterator[ZeroconfDiscoveryService]: """The SDK's real DNS-SD provider, running over the stubbed zeroconf.""" service = ZeroconfDiscoveryService() await service.start() yield service await service.stop() @pytest.fixture def peripherals(zeroconf: ZeroconfDiscoveryService) -> Peripherals: return Peripherals({"mdns": zeroconf.endpoint}) @pytest.fixture def output() -> RecordingControllerOutput: return RecordingControllerOutput() @pytest_asyncio.fixture async def controller( platform: Platform, peripherals: Peripherals, output: RecordingControllerOutput ) -> AsyncIterator[ESPhomeController]: ctrl = ESPhomeController(platform) ctrl.peripherals = peripherals ctrl.output = output await ctrl.start() yield ctrl await ctrl.stop() @pytest.fixture def mock_connection() -> Any: """Patch ESPhomeDeviceConnection where it is used (in the controller module).""" with patch("majordom_esphome.controller.ESPhomeDeviceConnection", autospec=True) as MockConn: instance = MockConn.return_value instance.start = AsyncMock(return_value=None) instance.stop = AsyncMock(return_value=None) instance.wait_ready = AsyncMock(return_value=None) instance.send_command = AsyncMock(return_value=None) instance.get_entities = MagicMock(return_value={}) instance.addresses = ["127.0.0.1"] yield MockConn, instance @pytest.fixture def make_entity() -> Callable[..., EntityInfo]: """Build a real `aioesphomeapi` entity description, i.e. exactly what a device reports.""" def _make(info_type: Any, key: int, name: str, **kwargs: Any) -> EntityInfo: return info_type(object_id=name.lower().replace(" ", "_"), key=key, name=name, **kwargs) return _make @pytest_asyncio.fixture async def device() -> AsyncIterator[VirtualDevice]: virtual = VirtualDevice(PLAIN) await virtual.start() yield virtual await virtual.stop() @pytest_asyncio.fixture async def encrypted_device() -> AsyncIterator[VirtualDevice]: virtual = VirtualDevice(ENCRYPTED) await virtual.start() yield virtual await virtual.stop() @pytest_asyncio.fixture async def discovery(controller: ESPhomeController, mdns: FakeMDNS, device: VirtualDevice) -> Discovery: """The plain virtual device, discovered over mDNS and picked by the user (so the Hub has created the device).""" await mdns.announce(Advert(port=device.port)) (found,) = controller.discoveries.values() user_picks(found) return found @pytest_asyncio.fixture async def paired(controller: ESPhomeController, discovery: Discovery) -> ESPhomeDevice: """The plain virtual device, paired and connected.""" await hub_pairs(controller, discovery, credentials=None) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=discovery.id, as_=ESPhomeDevice) assert stored is not None return stored def controls(device: ESPhomeDevice) -> list[Any]: return [p for p in device.parameters if p.role == ParameterRole.control] @pytest.fixture(autouse=True) def _forget_forms(): yield helpers._forms.clear() ================================================================================ # FILE: tests/helpers.py ================================================================================ """Test helpers shared by the unit and virtual-device suites.""" import asyncio import contextlib import time from collections.abc import Callable from typing import Any from uuid import UUID, uuid4 from majordom_integration_sdk import DeviceIdTakenError, Platform from majordom_integration_sdk.schemas import DeviceParameterChange, ProvidedCredentials from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.schemas.parameter import ParameterDataType from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice, ESPhomeDeviceState, ESPhomeParameter ROOM = UUID(int=42) _forms: dict[UUID, ESPhomeDeviceState] = {} def user_picks(discovery: Discovery, name: str = "Kitchen relay", room: UUID = ROOM): """What the user fills in when picking a discovery: the Hub builds the pairing draft from it.""" _forms[discovery.id] = draft_of(discovery, name, room) def draft_of(discovery: Discovery, name: str = "Kitchen relay", room: UUID = ROOM) -> ESPhomeDeviceState: return ESPhomeDeviceState( id=uuid4(), physical_id=discovery.id, name=name, room_id=room, transport=discovery.transport, integration=discovery.integration, manufacturer=discovery.device_manufacturer, parameters=[], ) async def hub_pairs( controller: ESPhomeController, discovery: Discovery, credentials: ProvidedCredentials | None = None, draft: ESPhomeDeviceState | None = None, ) -> UUID: """What the Hub does (`DeviceProvider`): pair into a draft, roll back with `unpair` on a failure, else save the device, report it connected and fetch it.""" draft = draft or _forms.get(discovery.id, draft_of(discovery)).model_copy(deep=True) try: device = await controller.pair_device(discovery, draft, credentials) except DeviceIdTakenError: raise except BaseException: await controller.unpair(draft) raise async with controller.platform.device_repository(controller) as repo: await repo.save(ESPhomeDevice.model_validate(device.model_dump())) if device.available: await controller.output.controller_did_connect_device(controller, physical_id=device.physical_id) with contextlib.suppress(Exception): await controller.fetch(ESPhomeDevice.model_validate(device.model_dump())) return device.physical_id async def wait_until(predicate: Callable[[], Any], timeout: float = 10.0, message: str = "condition"): deadline = time.monotonic() + timeout while time.monotonic() < deadline: if predicate(): return await asyncio.sleep(0.05) raise TimeoutError(f"timed out after {timeout}s waiting for {message}") def param(device: ESPhomeDevice, entity: str, sub_field: str = "state") -> ESPhomeParameter: matches = [ p for p in device.parameters if p.integration_data.entity_name == entity and p.integration_data.sub_field == sub_field ] assert len(matches) == 1, f"expected one parameter for {entity}.{sub_field}, got {len(matches)}" return matches[0] def changes(output: RecordingControllerOutput) -> list[DeviceParameterChange]: return [e for e in output.events if isinstance(e, DeviceParameterChange)] def values(output: RecordingControllerOutput, parameter_id: UUID) -> list[Any]: return [e.value for e in changes(output) if e.parameter_id == parameter_id] async def wait_for_value( output: RecordingControllerOutput, parameter: ESPhomeParameter, predicate: Callable[[Any], bool] = lambda _: True, timeout: float = 5.0, ) -> Any: """Wait for a state event of `parameter` that satisfies `predicate`; returns its value.""" await wait_until( lambda: any(predicate(v) for v in values(output, parameter.id)), timeout, f"event of {parameter.name} (seen: {values(output, parameter.id)})", ) return next(v for v in reversed(values(output, parameter.id)) if predicate(v)) def assert_values_match_parameters(output: RecordingControllerOutput, device: ESPhomeDevice): """Every reported value has exactly the plain type its parameter declares (no IntEnums, protobuf objects, ...). A `struct` value is a dict keyed by its sub-parameter ids (as the SDK specifies), each value of its sub-type. """ parameters = {p.id: p for p in device.parameters} for event in changes(output): assert event.parameter_id in parameters, f"event for unknown parameter {event.parameter_id}" _assert_value_type(parameters[event.parameter_id], event.value) def _assert_value_type(parameter: ESPhomeParameter, value: Any): expected: dict[ParameterDataType, tuple[type, ...]] = { ParameterDataType.bool: (bool,), ParameterDataType.integer: (int,), ParameterDataType.decimal: (float,), ParameterDataType.enum: (int,), ParameterDataType.string: (str,), ParameterDataType.struct: (dict,), } assert type(value) in expected[parameter.data_type], ( f"{parameter.name}: {type(value).__name__} {value!r} is not {parameter.data_type}" ) if parameter.data_type == ParameterDataType.enum: assert parameter.valid_values and value in parameter.valid_values, ( f"{parameter.name}: {value!r} not in {parameter.valid_values}" ) if parameter.data_type == ParameterDataType.struct: subs = {str(sub.id): sub for sub in (ESPhomeParameter.model_validate(f) for f in parameter.fields or [])} assert set(value) == set(subs), f"{parameter.name}: keys {sorted(value)} are not its sub-parameter ids" for key, item in value.items(): _assert_value_type(subs[key], item) def leaked_tasks() -> list[asyncio.Task[Any]]: """Still-running tasks started by this package: after `stop()`/failed pairing there must be none.""" leaked = [] for task in asyncio.all_tasks(): coro = task.get_coro() code = getattr(coro, "cr_code", None) if task is not asyncio.current_task() and code is not None and "majordom_esphome" in code.co_filename: leaked.append(task) return leaked async def assert_not_paired(platform: Platform, device_id: UUID): """A failed pairing leaves no device (the Hub saves only what pairing returned) and nothing kept on the side.""" async with platform.make_device_repository(ESPhomeController.slug()) as repo: assert await repo.get(physical_id=device_id) is None assert_no_side_storage(platform) def assert_no_side_storage(platform: Platform): """Whatever the integration keeps about a device lives in its record (`integration_data`), never in a file.""" folder = platform.documents_root / ESPhomeController.slug() assert not folder.exists() or not any(folder.iterdir()) ================================================================================ # FILE: tests/test_addresses.py ================================================================================ """Where to reach a node: hostname first, then the announced IPs; what worked is remembered and refreshed by mDNS. Only loopback addresses are used: `127.0.0.1` reaches the virtual device, `::1` is refused at once. """ import pytest from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import hub_pairs, param, user_picks, wait_for_value, wait_until from tests.virtual.mdns import Advert, FakeMDNS from tests.virtual.runner import VirtualDevice async def pair(controller: ESPhomeController, mdns: FakeMDNS, advert: Advert) -> ESPhomeDevice: await mdns.announce(advert) (discovery,) = controller.discoveries.values() user_picks(discovery) await hub_pairs(controller, discovery, credentials=None) return await stored(controller, discovery.id) async def stored(controller: ESPhomeController, device_id) -> ESPhomeDevice: async with controller.platform.device_repository(controller) as repo: device = await repo.get(physical_id=device_id, as_=ESPhomeDevice) assert device is not None return device async def test_hostname_comes_first_then_the_announced_addresses( controller: ESPhomeController, mdns: FakeMDNS, device: VirtualDevice ): paired = await pair(controller, mdns, Advert(port=device.port, server="localhost.", addresses=["::1", "127.0.0.1"])) assert paired.integration_data.addresses == ["localhost", "::1", "127.0.0.1"] async def test_pairing_falls_back_to_the_next_address_and_remembers_what_worked( controller: ESPhomeController, mdns: FakeMDNS, device: VirtualDevice ): paired = await pair(controller, mdns, Advert(port=device.port, server=None, addresses=["::1", "127.0.0.1"])) assert paired.integration_data.addresses == ["127.0.0.1", "::1"] # the working one first, the failed one last async def test_pairing_uses_the_latest_announcement( controller: ESPhomeController, mdns: FakeMDNS, device: VirtualDevice ): await mdns.announce(Advert(port=device.port, server=None, addresses=["::1"])) # the node's old address await mdns.announce(Advert(port=device.port, server=None, addresses=["127.0.0.1"])) # DHCP moved it (discovery,) = controller.discoveries.values() user_picks(discovery) await hub_pairs(controller, discovery, credentials=None) assert (await stored(controller, discovery.id)).integration_data.addresses == ["127.0.0.1"] @pytest.mark.timeout(90) async def test_address_changes_are_followed_while_paired( controller: ESPhomeController, mdns: FakeMDNS, device: VirtualDevice, output: RecordingControllerOutput, ): advert = Advert(port=device.port, server="localhost.", addresses=["127.0.0.1"]) paired = await pair(controller, mdns, advert) assert paired.integration_data.addresses == ["localhost", "127.0.0.1"] # DHCP hands the node a new address: mDNS announces it, the old one is forgotten, the new one is tried first await mdns.announce(Advert(port=device.port, server="localhost.", addresses=["::1"])) assert (await stored(controller, paired.physical_id)).integration_data.addresses == ["::1", "localhost"] # the next connection (the node reboots) tries `::1`, fails, and then remembers the hostname that worked output.connected_devices.clear() await device.restart() await wait_until(lambda: paired.physical_id in output.connected_devices, 40, "the device to reconnect") await wait_for_value(output, param(paired, "Temperature")) assert (await stored(controller, paired.physical_id)).integration_data.addresses == ["localhost", "::1"] async def test_announcement_of_a_paired_node_without_changes_leaves_addresses_alone( controller: ESPhomeController, mdns: FakeMDNS, device: VirtualDevice ): advert = Advert(port=device.port, server="localhost.", addresses=["127.0.0.1"]) paired = await pair(controller, mdns, advert) await mdns.announce(advert) assert ( await stored(controller, paired.physical_id) ).integration_data.addresses == paired.integration_data.addresses ================================================================================ # FILE: tests/test_bluetooth.py ================================================================================ """ESPHome nodes lending their Bluetooth as sources of the hub's Bluetooth router.""" import asyncio from collections.abc import AsyncIterator, Awaitable, Callable from pathlib import Path from typing import Any, cast from unittest.mock import AsyncMock, Mock from uuid import UUID import pytest from aioesphomeapi import ( APIClient, APIConnectionError, BluetoothLERawAdvertisementsResponse, BluetoothProxyFeature, DeviceInfo, ) from aioesphomeapi.model import APIVersion, BluetoothGATTService, ESPHomeBluetoothGATTServices from majordom_integration_sdk import Endpoint, Platform from majordom_integration_sdk.capabilities import BLEDiscoveryInfo, BLERouter from majordom_integration_sdk.peripherals import BLEProxy, Peripherals from majordom_integration_sdk.repository.memory import DeviceRepositoryMemory from majordom_integration_sdk.runtime import PeripheralState, Runtime from majordom_integration_sdk.runtime.peripherals.providers.ble.router import BLEService from majordom_integration_sdk.runtime.peripherals.providers.zeroconf import ZeroconfDiscoveryService from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.testing import FakePeripheral, RecordingControllerOutput from majordom_esphome.bluetooth import ESPhomeBLEConnection, ESPhomeBLESource, ble_source_of from majordom_esphome.connection import WAIT_READY_TIMEOUT, ESPhomeDeviceConnection from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import assert_not_paired, draft_of, hub_pairs, leaked_tasks, user_picks, wait_until from tests.virtual.mdns import Advert, FakeMDNS PROXY = ( BluetoothProxyFeature.PASSIVE_SCAN | BluetoothProxyFeature.ACTIVE_CONNECTIONS | BluetoothProxyFeature.REMOTE_CACHING | BluetoothProxyFeature.RAW_ADVERTISEMENTS ) MATTER = "0000fff6-0000-1000-8000-00805f9b34fb" DEVICE = 0xAABBCCDDEEFF MATTER_ADV = bytes.fromhex("0b16f6ff00000fa1f7ff0180") # service data: a commissionable Matter device NAME = bytes.fromhex("0509") + b"Bulb" # scan response: complete local name TX_POWER = bytes.fromhex("020a08") # 8 dBm NODES = {"kitchen": "11:22:33:44:55:01", "garage": "11:22:33:44:55:02"} # node name -> its Bluetooth MAC class FakeAPIClient: api_version: APIVersion | None = APIVersion(1, 12) def __init__( self, features: int = PROXY, answers: tuple[bool, int, int] = (True, 247, 0), mac: str = "11:22:33:44:55:66", device_info_error: Exception | None = None, unsubscribe_error: Exception | None = None, ): self.features, self.answers, self.mac = features, answers, mac self.device_info_error, self.unsubscribe_error = device_info_error, unsubscribe_error self.on_advertisements: Callable[[BluetoothLERawAdvertisementsResponse], None] | None = None self.on_stop: Callable[[bool], Awaitable[None]] | None = None self.disconnected = False self.writes: list[tuple[int, bytes]] = [] self.descriptors: list[tuple[int, bytes]] = [] self.on_notify: Callable[[int, bytearray], None] | None = None self.on_slots: Callable[[int, int, list[int]], None] | None = None self.unsubscribed = 0 self.connected: tuple[int, int | None] | None = None # the device it connected to, and its address type self.on_state: Callable[[bool, int, int], None] | None = None # of the device it connected to self.notifying: set[int] = set() self.disconnects: list[int] = [] async def device_info(self) -> DeviceInfo: if self.device_info_error: raise self.device_info_error return DeviceInfo.from_dict({"mac_address": self.mac, "bluetooth_proxy_feature_flags": self.features}) def subscribe_bluetooth_le_raw_advertisements( self, callback: Callable[[BluetoothLERawAdvertisementsResponse], None] ) -> Callable[[], None]: self.on_advertisements = callback def unsubscribe(): self.on_advertisements = None self.unsubscribed += 1 if self.unsubscribe_error: raise self.unsubscribe_error return unsubscribe def subscribe_bluetooth_connections_free( self, callback: Callable[[int, int, list[int]], None] ) -> Callable[[], None]: self.on_slots = callback def unsubscribe(): self.on_slots = None return unsubscribe # what the device connection asks of a node besides Bluetooth async def connect(self, login: bool, on_stop: Callable[[bool], Awaitable[None]]): self.on_stop = on_stop async def list_entities_services(self) -> tuple[list[Any], list[Any]]: return [], [] def subscribe_states(self, callback: Callable[[Any], None]): ... async def disconnect(self): self.disconnected = True async def drop(self): assert self.on_stop await self.on_stop(False) def advertise(self, data: bytes, rssi: int = -60): response = BluetoothLERawAdvertisementsResponse() response.advertisements.add(address=DEVICE, rssi=rssi, address_type=1, data=data) assert self.on_advertisements self.on_advertisements(response) async def bluetooth_device_connect( self, address: int, on_state: Callable[[bool, int, int], None], feature_flags: int = 0, address_type: int | None = None, **kwargs: Any, ) -> Callable[[], None]: self.connected = (address, address_type) self.on_state = on_state on_state(*self.answers) def unsubscribe(): self.on_state = None return unsubscribe async def bluetooth_gatt_get_services(self, address: int) -> ESPHomeBluetoothGATTServices: cccd = {"uuid": "00002902-0000-1000-8000-00805f9b34fb", "handle": 6} characteristics = [ {"uuid": "c1", "handle": 3, "properties": 0x08}, {"uuid": "c2", "handle": 5, "properties": 0x20, "descriptors": [cccd]}, ] service = BluetoothGATTService.from_dict({"uuid": MATTER, "handle": 1, "characteristics": characteristics}) # a dataclass made by functools.partial, which ty can't see into return ESPHomeBluetoothGATTServices(address, [service]) # ty: ignore[too-many-positional-arguments] async def bluetooth_gatt_write(self, address: int, handle: int, data: bytes, response: bool): self.writes.append((handle, data)) async def bluetooth_gatt_read(self, address: int, handle: int) -> bytearray: return bytearray(b"value") async def bluetooth_gatt_start_notify( self, address: int, handle: int, callback: Callable[[int, bytearray], None] ) -> tuple[Callable[[], Awaitable[None]], Callable[[], None]]: self.on_notify = callback self.notifying.add(handle) async def stop(): self.notifying.discard(handle) return stop, (lambda: None) def bluetooth_gatt_stop_notify_for_address(self, address: int): ... async def bluetooth_gatt_write_descriptor(self, address: int, handle: int, data: bytes): self.descriptors.append((handle, data)) async def bluetooth_device_disconnect(self, address: int): self.disconnects.append(address) async def source_of(client: FakeAPIClient) -> ESPhomeBLESource | None: return await ble_source_of(cast(APIClient, client)) class Listener: def __init__(self): self.heard: list[BLEDiscoveryInfo] = [] async def ble_did_discover_device(self, ble: BLERouter, info: BLEDiscoveryInfo): self.heard.append(info) ble_did_update_device = ble_did_discover_device async def ble_did_remove_device(self, ble: BLERouter, info: BLEDiscoveryInfo): ... @pytest.fixture async def ble_and_node() -> AsyncIterator[tuple[BLEService, FakeAPIClient]]: client = FakeAPIClient() ble = BLEService(sources=[]) await ble.start() source = await source_of(client) assert source await ble.add_source(source) yield ble, client await ble.stop() async def test_only_nodes_streaming_raw_advertisements_are_sources(): assert await source_of(FakeAPIClient(features=0)) is None source = await source_of(FakeAPIClient()) assert source and source.name == "esphome:11:22:33:44:55:66" async def test_a_node_that_closed_its_api_connection_meanwhile_lends_nothing(): client = FakeAPIClient() client.api_version = None # what the client knows once the connection closed assert await source_of(client) is None async def test_advertisements_and_scan_responses_merge_into_one_device(ble_and_node: tuple[BLEService, FakeAPIClient]): ble, client = ble_and_node listener = Listener() ble.register(listener, {UUID(MATTER)}) client.advertise(MATTER_ADV) client.advertise(NAME) client.advertise(MATTER_ADV) await asyncio.sleep(0.01) first, second = listener.heard # found, then named; the repeat changed nothing assert first.device.address == "AA:BB:CC:DD:EE:FF" and first.source == "esphome:11:22:33:44:55:66" assert second.advertisement.local_name == "Bulb" assert second.advertisement.service_data == {MATTER: bytes.fromhex("00000fa1f7ff0180")} async def test_a_scan_response_keeps_the_tx_power_its_advertisement_carried( ble_and_node: tuple[BLEService, FakeAPIClient], ): ble, client = ble_and_node listener = Listener() ble.register(listener, {UUID(MATTER)}) client.advertise(MATTER_ADV + TX_POWER) client.advertise(NAME) await asyncio.sleep(0.01) assert [info.advertisement.tx_power for info in listener.heard] == [8, 8] async def test_connects_and_speaks_gatt_by_handle(ble_and_node: tuple[BLEService, FakeAPIClient]): ble, client = ble_and_node client.advertise(MATTER_ADV) await asyncio.sleep(0.01) connection = await ble.connect("AA:BB:CC:DD:EE:FF") assert client.connected == (DEVICE, 1) and connection.mtu == 247 services = await connection.services() assert [(c.uuid, c.properties) for c in services[0].characteristics] == [("c1", ("write",)), ("c2", ("indicate",))] await connection.write(3, b"hs") notes = [] await connection.start_notify(5, notes.append) assert client.on_notify client.on_notify(5, bytearray(b"ok")) assert client.writes == [(3, b"hs")] and client.descriptors == [(6, b"\x02\x00")] and notes == [b"ok"] async def test_a_closed_connection_leaves_no_notify_handler_on_the_node(): """The library cleans a device's notify handlers up only once told it disconnected, which the connection stops listening for as it disconnects: a handler left behind would feed a later connection to the same handle.""" handlers: list[Callable[..., None]] = [] class NodeConnection: # what the real client talks through is_connected = True def add_message_callback(self, callback: Callable[..., None], types: Any) -> Callable[[], None]: handlers.append(callback) return lambda: handlers.remove(callback) def send_message(self, message: Any): ... class Client(APIClient): def _get_connection(self) -> Any: return NodeConnection() client = Client("node", 6053, None) client._send_bluetooth_message_await_response = AsyncMock() client._bluetooth_device_request = AsyncMock() connection = ESPhomeBLEConnection(client, DEVICE, 247, lambda: None) characteristic = {"uuid": "c", "handle": 5} connection._services = [ BluetoothGATTService.from_dict({"uuid": MATTER, "handle": 1, "characteristics": [characteristic]}) ] await connection.start_notify(5, lambda data: None) await connection.disconnect() assert handlers == [] async def test_a_proxied_connection_reads_stops_notifying_and_disconnects( ble_and_node: tuple[BLEService, FakeAPIClient], ): ble, client = ble_and_node client.advertise(MATTER_ADV) await asyncio.sleep(0.01) connection = await ble.connect("AA:BB:CC:DD:EE:FF") assert await connection.read(3) == b"value" await connection.start_notify(5, lambda data: None) await connection.stop_notify(5) assert client.notifying == set() await connection.disconnect() assert client.on_state is None and client.disconnects == [DEVICE] async def test_a_device_dropping_its_proxied_connection_is_told(ble_and_node: tuple[BLEService, FakeAPIClient]): ble, client = ble_and_node client.advertise(MATTER_ADV) await asyncio.sleep(0.01) dropped: list[bool] = [] await ble.connect("AA:BB:CC:DD:EE:FF", on_disconnect=lambda: dropped.append(True)) assert client.on_state client.on_state(False, 0, 0x13) # the device went away assert dropped == [True] async def test_notifying_an_unknown_handle_is_a_lookup_error(ble_and_node: tuple[BLEService, FakeAPIClient]): ble, client = ble_and_node client.advertise(MATTER_ADV) await asyncio.sleep(0.01) connection = await ble.connect("AA:BB:CC:DD:EE:FF") with pytest.raises(LookupError): await connection.start_notify(99, lambda data: None) async def test_a_refused_connection_is_an_error(ble_and_node: tuple[BLEService, FakeAPIClient]): ble, client = ble_and_node client.answers = (False, 0, 133) with pytest.raises(ConnectionError, match="error 133"): await ble.connect("AA:BB:CC:DD:EE:FF") async def test_a_leased_node_stays_subscribed_but_mutes_its_advertisements( ble_and_node: tuple[BLEService, FakeAPIClient], ): ble, client = ble_and_node listener = Listener() ble.register(listener, {UUID(MATTER)}) client.advertise(MATTER_ADV) await asyncio.sleep(0.01) async with ble.exclusive("AA:BB:CC:DD:EE:FF", owner="matter") as lease: assert client.on_advertisements, "the node answers connects only to its subscriber" client.advertise(NAME) await asyncio.sleep(0.01) assert len(listener.heard) == 1 await lease.connect() assert client.connected == (DEVICE, 1) client.advertise(MATTER_ADV) await asyncio.sleep(0.01) assert listener.heard[-1].advertisement.local_name == "Bulb" # heard again, the muted name kept async def test_a_lease_mutes_a_lent_node_and_resumes_it_without_unsubscribing(): """A node lent through its proxy, as the runtime binds it: a lease pauses it (it stays subscribed, or it would refuse the leaseholder's connect) and the release resumes it.""" client = FakeAPIClient() source = await source_of(client) assert source ble = BLEService() ble.peripherals = Peripherals({"ble": [*BLEProxy(source).provides]}) await ble.start() listener = Listener() ble.register(listener, {UUID(MATTER)}) client.advertise(MATTER_ADV) await asyncio.sleep(0.01) subscribed = client.on_advertisements async with ble.exclusive("AA:BB:CC:DD:EE:FF", owner="matter") as lease: assert lease.source == source.name client.advertise(MATTER_ADV, rssi=-30) await asyncio.sleep(0.01) assert len(listener.heard) == 1 # muted assert client.on_advertisements is subscribed client.advertise(NAME) await asyncio.sleep(0.01) assert len(listener.heard) == 2 # resumed assert client.on_advertisements is subscribed and client.unsubscribed == 0 await ble.stop() async def test_a_node_hears_again_after_a_router_restart_cut_its_lease_short(): """The router stops while the node is leased (a restart, a failed hook): the release can't resume it then.""" client = FakeAPIClient() source = await source_of(client) assert source ble = BLEService(sources=[source]) await ble.start() listener = Listener() ble.register(listener, {UUID(MATTER)}) async with ble.exclusive("AA:BB:CC:DD:EE:FF", owner="esphome-improv"): await ble.stop() await ble.start() client.advertise(MATTER_ADV) await asyncio.sleep(0.01) assert len(listener.heard) == 1, "a started source hears" await ble.stop() async def test_a_node_reconnecting_while_its_radio_is_leased_hears_once_released(): """Its API connection drops during the lease (Matter commissioning through it): ESPHome takes the radio back, then lends the one of the new connection under the same name.""" first = FakeAPIClient() old = await source_of(first) assert old ble = BLEService(sources=[old]) await ble.start() listener = Listener() ble.register(listener, {UUID(MATTER)}) first.advertise(MATTER_ADV) await asyncio.sleep(0.01) async with ble.exclusive("AA:BB:CC:DD:EE:FF", owner="matter"): await ble.remove_source(old.name) second = FakeAPIClient() new = await source_of(second) assert new await ble.add_source(new) assert second.on_advertisements, "the node answers the lease's connects only to its subscriber" second.advertise(NAME) await asyncio.sleep(0.01) assert len(listener.heard) == 1, "muted while leased" second.advertise(MATTER_ADV) await asyncio.sleep(0.01) assert len(listener.heard) == 2 await ble.stop() async def test_a_quiet_node_stays_subscribed(ble_and_node: tuple[BLEService, FakeAPIClient]): """A node in a quiet place hears no one for a while; its loss shows through its API connection, and resubscribing it would drop the replies of the connections it proxies.""" ble, client = ble_and_node subscribed = client.on_advertisements ble._silence_sec = 0.01 await asyncio.sleep(0.02) await ble._revive_silent() assert client.on_advertisements is subscribed and client.unsubscribed == 0 async def test_a_node_says_how_many_connections_it_can_still_open(ble_and_node: tuple[BLEService, FakeAPIClient]): _, client = ble_and_node source = await source_of(client) assert source await source.start(lambda device, adv: None) assert source.free_slots is None # until the node says assert client.on_slots client.on_slots(1, 3, [0xAABBCCDDEEFF, 0x112233445566]) assert source.free_slots == 1 await source.stop() assert client.on_slots is None async def test_a_node_that_only_listens_has_no_slots_to_report(): client = FakeAPIClient(features=BluetoothProxyFeature.PASSIVE_SCAN | BluetoothProxyFeature.RAW_ADVERTISEMENTS) source = await source_of(client) assert source await source.start(lambda device, adv: None) assert client.on_slots is None async def test_rotating_addresses_dont_grow_the_memory( ble_and_node: tuple[BLEService, FakeAPIClient], monkeypatch: pytest.MonkeyPatch ): ble, client = ble_and_node monkeypatch.setattr("majordom_esphome.bluetooth._REMEMBERED", 2) source = ble._sources["esphome:11:22:33:44:55:66"] assert isinstance(source, ESPhomeBLESource) and client.on_advertisements for address in range(3): response = BluetoothLERawAdvertisementsResponse() response.advertisements.add(address=address, rssi=-60, address_type=1, data=MATTER_ADV) client.on_advertisements(response) assert list(source._heard) == ["00:00:00:00:00:01", "00:00:00:00:00:02"] class Nodes: """Stands for `APIClient` where the device connections open one: each node the hub connects to is a fake.""" def __init__(self): self.clients: list[FakeAPIClient] = [] self.options: dict[str, Any] = {} # what the nodes are like from now on: features, device_info_error, … def __call__(self, address: str, port: int, password: str | None, noise_psk: str | None = None) -> FakeAPIClient: self.clients.append(FakeAPIClient(mac=NODES[address.removesuffix(".local")], **self.options)) return self.clients[-1] def connection_of(self, node: str) -> FakeAPIClient: """The newest connection to the node.""" return next(client for client in reversed(self.clients) if client.mac == NODES[node]) def lent(node: str) -> str: return f"esphome:{NODES[node]}" def sources(ble: BLEService) -> list[str]: return sorted(ble._sources) def proxies(runtime: Runtime) -> list[str]: return [p.key for p in runtime.peripherals if isinstance(p, BLEProxy)] def zeroconf_of(runtime: Runtime) -> ZeroconfDiscoveryService: (zeroconf,) = [p for p in runtime.peripherals if isinstance(p, ZeroconfDiscoveryService)] return zeroconf @pytest.fixture def ble() -> BLEService: """The Hub's Bluetooth router: the runtime runs it while ESPHome binds it.""" return BLEService() @pytest.fixture def nodes(monkeypatch: pytest.MonkeyPatch) -> Nodes: nodes = Nodes() monkeypatch.setattr("majordom_esphome.connection.APIClient", nodes) monkeypatch.setattr("majordom_esphome.connection.RECONNECT_DELAY_FIRST", 0.3) return nodes @pytest.fixture def settings() -> ESPhomeController.Settings: return ESPhomeController.Settings() @pytest.fixture async def runtime( platform: Platform, settings: ESPhomeController.Settings, ble: BLEService, nodes: Nodes, mdns: FakeMDNS, output: RecordingControllerOutput, tmp_path: Path, ) -> AsyncIterator[Runtime]: """ESPHome run as by the Hub, beside the Bluetooth router and DNS-SD it binds.""" peripherals = [ble, ZeroconfDiscoveryService(), ESPhomeController(platform, settings=settings)] runtime = Runtime(tmp_path / "data", peripherals, platform=platform, controller_output=output) await runtime.start() await wait_until(lambda: all(runtime.status(p).state == PeripheralState.RUNNING for p in runtime.peripherals)) yield runtime await runtime.stop() @pytest.fixture def esphome(runtime: Runtime) -> ESPhomeController: (controller,) = [p for p in runtime.peripherals if isinstance(p, ESPhomeController)] return controller async def announce(controller: ESPhomeController, mdns: FakeMDNS, node: str) -> Discovery: mac = NODES[node].replace(":", "") await mdns.announce(Advert(name=node, mac=mac, server=f"{node}.local.", addresses=[])) return controller.discoveries[controller.device_uuid(bytes.fromhex(mac))] async def pair(controller: ESPhomeController, mdns: FakeMDNS, node: str) -> ESPhomeDevice: discovery = await announce(controller, mdns, node) user_picks(discovery, name=node) await hub_pairs(controller, discovery, None) async with controller.platform.device_repository(controller) as repo: device = await repo.get(physical_id=discovery.id, as_=ESPhomeDevice) assert device is not None return device async def test_a_paired_node_with_a_proxy_lends_its_radio( esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): listener = Listener() ble.register(listener, {UUID(MATTER)}) await pair(esphome, mdns, "kitchen") await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent") nodes.connection_of("kitchen").advertise(MATTER_ADV) await asyncio.sleep(0.01) assert [info.source for info in listener.heard] == [lent("kitchen")] async def test_a_lent_radio_is_a_proxy_esphome_brings_along( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes ): await pair(esphome, mdns, "kitchen") await wait_until(lambda: len(esphome.provides) == 1, message="the node to be lent") proxy = runtime.peripheral(f"esphome/{NODES['kitchen']}") # known by its Bluetooth MAC assert isinstance(proxy, BLEProxy) and proxy.contributor is esphome assert runtime.status(proxy).state == PeripheralState.RUNNING def test_the_setting_is_on_by_default(): assert ESPhomeController.Settings().is_bluetooth_proxy_enabled is True async def test_a_node_without_a_proxy_lends_nothing( esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): nodes.options["features"] = 0 await pair(esphome, mdns, "kitchen") await asyncio.sleep(0.05) assert sources(ble) == [] @pytest.mark.parametrize("settings", [ESPhomeController.Settings(is_bluetooth_proxy_enabled=False)]) async def test_nothing_is_lent_while_the_setting_is_off( esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): await pair(esphome, mdns, "kitchen") await asyncio.sleep(0.05) assert sources(ble) == [] and esphome.provides == [] async def test_turning_the_proxies_off_restarts_it_and_takes_every_radio_back( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): await pair(esphome, mdns, "kitchen") await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent") first = nodes.connection_of("kitchen") await runtime.update_settings(esphome, {"is_bluetooth_proxy_enabled": False}) await wait_until(lambda: nodes.connection_of("kitchen") is not first, message="the node to reconnect") await asyncio.sleep(0.05) assert sources(ble) == [] and proxies(runtime) == [] async def test_unpairing_a_node_takes_back_only_its_radio( esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): kitchen = await pair(esphome, mdns, "kitchen") await pair(esphome, mdns, "garage") await wait_until(lambda: sources(ble) == [lent("kitchen"), lent("garage")], message="both nodes to be lent") await esphome.unpair(kitchen) assert sources(ble) == [lent("garage")] assert nodes.connection_of("kitchen").on_advertisements is None async def test_a_node_that_drops_is_taken_back_and_lent_once_when_it_returns( esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): await pair(esphome, mdns, "kitchen") await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent") dropped = nodes.connection_of("kitchen") await dropped.drop() await wait_until(lambda: sources(ble) == [], message="the dropped node to be taken back") assert dropped.on_advertisements is None await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent again") assert nodes.connection_of("kitchen") is not dropped and dropped.on_advertisements is None async def test_stop_takes_back_every_radio( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): await pair(esphome, mdns, "kitchen") await pair(esphome, mdns, "garage") await wait_until(lambda: len(sources(ble)) == 2, message="both nodes to be lent") await runtime.disable(esphome) assert proxies(runtime) == [] and esphome.provides == [] assert all(client.on_advertisements is None and client.disconnected for client in nodes.clients) assert leaked_tasks() == [] async def test_a_restarted_controller_lends_each_node_once( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): listener = Listener() ble.register(listener, {UUID(MATTER)}) await pair(esphome, mdns, "kitchen") await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent") first = nodes.connection_of("kitchen") await runtime.restart(esphome) await wait_until(lambda: nodes.connection_of("kitchen") is not first, message="the node to reconnect") await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent again") nodes.connection_of("kitchen").advertise(MATTER_ADV) await asyncio.sleep(0.01) assert first.on_advertisements is None and len(listener.heard) == 1 async def test_a_failed_pairing_leaves_no_radio_lent( esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService, output: RecordingControllerOutput, monkeypatch: pytest.MonkeyPatch, ): discovery = await announce(esphome, mdns, "kitchen") user_picks(discovery, name="kitchen") # the pairing fails after connecting monkeypatch.setattr(esphome, "_refuse_if_stopped", Mock(side_effect=RuntimeError("the Hub went away"))) with pytest.raises(RuntimeError): await hub_pairs(esphome, discovery, None) assert sources(ble) == [] assert nodes.connection_of("kitchen").on_advertisements is None assert leaked_tasks() == [] async def test_a_pairing_that_failed_once_connected_can_be_tried_again( esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, output: RecordingControllerOutput, monkeypatch: pytest.MonkeyPatch, ): discovery = await announce(esphome, mdns, "kitchen") user_picks(discovery, name="kitchen") with monkeypatch.context() as hub: hub.setattr(esphome, "_refuse_if_stopped", Mock(side_effect=RuntimeError("the Hub went away"))) with pytest.raises(RuntimeError): await hub_pairs(esphome, discovery, None) await hub_pairs(esphome, esphome.discoveries[discovery.id], None) assert output.connected_devices == [discovery.id] assert [client.disconnected for client in nodes.clients] == [True, False] async def test_a_node_whose_bluetooth_fails_to_set_up_stays_connected( esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService, output: RecordingControllerOutput ): nodes.options["device_info_error"] = APIConnectionError("the node went quiet") device = await pair(esphome, mdns, "kitchen") await asyncio.sleep(0.05) assert device.available and output.lost_devices == [] assert sources(ble) == [] async def test_stop_finishes_when_a_radio_cannot_be_taken_back( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): nodes.options["unsubscribe_error"] = RuntimeError("the node is gone") await pair(esphome, mdns, "kitchen") await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent") await runtime.disable(esphome) assert nodes.connection_of("kitchen").disconnected assert proxies(runtime) == [] and leaked_tasks() == [] # A stop meeting a pairing in flight @pytest.fixture def slow_nodes(monkeypatch: pytest.MonkeyPatch) -> asyncio.Event: """The nodes list their entities only once it is set: a pairing waits for its node meanwhile.""" answered = asyncio.Event() async def list_entities_services(self: FakeAPIClient) -> tuple[list[Any], list[Any]]: await answered.wait() return [], [] monkeypatch.setattr(FakeAPIClient, "list_entities_services", list_entities_services) return answered async def start_pairing( controller: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, node: str ) -> tuple[Discovery, asyncio.Task[UUID | None]]: """The user pairs the node; returns once the pairing waits for it.""" discovery = await announce(controller, mdns, node) user_picks(discovery, name=node) pairing = asyncio.create_task(hub_pairs(controller, discovery, None)) await wait_until(lambda: nodes.clients and nodes.clients[-1].on_stop, message="the node to answer the connect") return discovery, pairing async def test_a_pairing_that_outlives_a_stop_is_refused_and_leaves_nothing_behind( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, slow_nodes: asyncio.Event ): discovery, pairing = await start_pairing(esphome, mdns, nodes, "kitchen") await runtime.disable(esphome) slow_nodes.set() with pytest.raises(ConnectionError, match="stopped"): await pairing assert esphome._connections == {} and nodes.connection_of("kitchen").disconnected await assert_not_paired(esphome.platform, discovery.id) assert leaked_tasks() == [] async def test_a_pairing_across_a_restart_is_refused_and_lends_nothing( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService, slow_nodes: asyncio.Event, ): """The user turns the proxies off (another hub needs the node's Bluetooth) while the node is paired: the pairing, made with the proxies on, finishes once ESPHome runs again.""" discovery, pairing = await start_pairing(esphome, mdns, nodes, "kitchen") await runtime.update_settings(esphome, {"is_bluetooth_proxy_enabled": False}) await wait_until(lambda: runtime.status(esphome).state == PeripheralState.RUNNING, message="ESPHome to run") slow_nodes.set() with pytest.raises(ConnectionError, match="stopped"): await pairing await asyncio.sleep(0.05) assert sources(ble) == [] and esphome.provides == [] assert esphome._connections == {} and nodes.connection_of("kitchen").disconnected await assert_not_paired(esphome.platform, discovery.id) async def test_a_stop_before_the_hub_saved_the_device_lets_go_of_the_node( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, output: RecordingControllerOutput ): discovery = await announce(esphome, mdns, "kitchen") await esphome.pair_device(discovery, draft_of(discovery, name="kitchen"), None) await runtime.disable(esphome) assert esphome._connections == {} and esphome._just_paired == {} assert nodes.connection_of("kitchen").disconnected assert output.connected_devices == [] and leaked_tasks() == [] async def test_a_stop_reaching_a_node_connection_from_inside_it_ends_it( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): """A node drops while the runtime is busy: its connection task tells the runtime its radio is gone and waits for the runtime to act, which stops ESPHome (the Hub removed DNS-SD meanwhile). That stop ends the waiting task too.""" await pair(esphome, mdns, "kitchen") await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent") opened = len(nodes.clients) async with runtime._lock: # the runtime is busy await nodes.connection_of("kitchen").drop() await asyncio.sleep(0.05) removing = asyncio.create_task(runtime.remove(zeroconf_of(runtime))) await asyncio.sleep(0.05) await removing await wait_until(lambda: runtime.status(esphome).state == PeripheralState.WAITING, message="ESPHome to stop") await asyncio.sleep(1) # past the reconnect delay assert esphome._connections == {} and len(nodes.clients) == opened, "a stopped controller doesn't reconnect" assert leaked_tasks() == [] async def test_a_node_lends_its_radio_only_once_it_is_paired( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService, monkeypatch: pytest.MonkeyPatch, ): held = asyncio.Event() wait_ready = ESPhomeDeviceConnection.wait_ready async def wait_ready_then_hold(self: ESPhomeDeviceConnection, timeout: float = WAIT_READY_TIMEOUT): await wait_ready(self, timeout) await held.wait() # the node is connected, its pairing not done yet monkeypatch.setattr(ESPhomeDeviceConnection, "wait_ready", wait_ready_then_hold) discovery = await announce(esphome, mdns, "kitchen") user_picks(discovery, name="kitchen") pairing = asyncio.create_task(hub_pairs(esphome, discovery, None)) await wait_until(lambda: nodes.clients and nodes.clients[-1].on_stop, message="the node to answer the connect") await asyncio.sleep(0.1) assert sources(ble) == [] and esphome.provides == [], "a node being paired serves no one yet" held.set() await pairing await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the paired node to be lent") async def test_a_cancelled_pairing_lets_go_of_the_node( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService, slow_nodes: asyncio.Event, ): discovery, pairing = await start_pairing(esphome, mdns, nodes, "kitchen") pairing.cancel() # the Hub's request went away with pytest.raises(asyncio.CancelledError): await pairing slow_nodes.set() await asyncio.sleep(0.1) assert nodes.connection_of("kitchen").disconnected and sources(ble) == [] await assert_not_paired(esphome.platform, discovery.id) assert leaked_tasks() == [] # DNS-SD going away or restarting under it async def test_dns_sd_removed_first_still_lets_it_stop_cleanly( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): await pair(esphome, mdns, "kitchen") await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent") await runtime.remove(zeroconf_of(runtime)) # stopped before ESPHome, its registration gone with it await wait_until(lambda: runtime.status(esphome).state == PeripheralState.WAITING, message="ESPHome to stop") assert esphome._connections == {} and nodes.connection_of("kitchen").disconnected assert leaked_tasks() == [] async def test_nodes_are_heard_after_dns_sd_restarts(runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS): await runtime.restart(zeroconf_of(runtime)) await wait_until(lambda: runtime.status(esphome).state == PeripheralState.RUNNING, message="ESPHome to run") assert await announce(esphome, mdns, "kitchen"), "a node announced after the restart is discovered" # Discoveries across a stop async def test_a_stopped_controller_offers_nothing_to_pair( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes ): discovery = await announce(esphome, mdns, "kitchen") user_picks(discovery, name="kitchen") await runtime.disable(esphome) assert esphome.discoveries == {} with pytest.raises(ValueError, match="no longer discovered"): await hub_pairs(esphome, discovery, None) assert esphome._connections == {} and nodes.clients == [] assert esphome.discoveries == {}, "not even with the reason it failed" async def test_a_restarted_controller_reports_what_it_hears_again( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, output: RecordingControllerOutput ): await announce(esphome, mdns, "kitchen") await runtime.restart(esphome) await wait_until(lambda: runtime.status(esphome).state == PeripheralState.RUNNING, message="ESPHome to run") await announce(esphome, mdns, "kitchen") # heard anew assert len(output.received_discoveries) == 2 async def test_a_paired_node_heard_while_it_starts_is_no_discovery( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, monkeypatch: pytest.MonkeyPatch ): """On a restart DNS-SD's cache is warm: it tells the nodes it knows at once, maybe before the paired devices are read (a busy database at boot).""" await pair(esphome, mdns, "kitchen") get_all = DeviceRepositoryMemory.get_all async def slow_get_all(self: DeviceRepositoryMemory, as_: Any = None) -> Any: await asyncio.sleep(0.3) return await get_all(self, as_) monkeypatch.setattr(DeviceRepositoryMemory, "get_all", slow_get_all) kitchen = Advert(name="kitchen", mac=NODES["kitchen"].replace(":", ""), server="kitchen.local.", addresses=[]) restarting = asyncio.create_task(runtime.restart(esphome)) await asyncio.sleep(0.1) await mdns.announce(kitchen) await restarting await mdns.announce(kitchen) assert esphome.discoveries == {}, "picking it would open a second connection to the node" # Routers coming later async def test_a_bluetooth_router_starting_later_is_taken_in_place( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes, ble: BLEService ): await runtime.disable(ble) await pair(esphome, mdns, "kitchen") opened = len(nodes.clients) await runtime.enable(ble) await wait_until(lambda: sources(ble) == [lent("kitchen")], message="the node to be lent to it") assert runtime.status(esphome).state == PeripheralState.RUNNING assert len(nodes.clients) == opened, "ESPHome kept its node connections" async def test_a_border_router_coming_later_is_taken_in_place( runtime: Runtime, esphome: ESPhomeController, mdns: FakeMDNS, nodes: Nodes ): await pair(esphome, mdns, "kitchen") opened = len(nodes.clients) await runtime.add(FakePeripheral("otbr", provides=[Endpoint("thread", "otbr-rest", "http://otbr:8081")])) await wait_until(lambda: "thread" in esphome.peripherals.bound, message="the border router to be handed over") assert runtime.status(esphome).state == PeripheralState.RUNNING assert len(nodes.clients) == opened, "ESPHome kept its node connections" ================================================================================ # FILE: tests/test_catalogue.py ================================================================================ """The entity catalogue: every kind ESPHome's API knows is mapped, hosted by a virtual node, or explained. Two layers, as in the Matter integration: - fast checks over the installed `aioesphomeapi` (always run): a new kind that is neither mapped nor listed fails here, which is the signal to add support (or a recipe, or a reason); - a sweep over one virtual node per kind (`pytest -m catalogue`, run by the monthly canary): pair it, read its states, send a command to every control parameter, and check that nothing breaks. """ import asyncio from typing import Any import pytest from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.parameter import ParameterDataType, ParameterRole from majordom_esphome import generic, mapper from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice, ESPhomeParameter from tests.helpers import assert_values_match_parameters, hub_pairs, user_picks from tests.virtual import catalogue from tests.virtual.mdns import Advert, FakeMDNS from tests.virtual.runner import VirtualDevice def test_every_kind_the_library_knows_is_mapped_or_skipped_on_purpose(): unknown = [ kind for kind in catalogue.all_kinds() if kind not in mapper._HAND_WRITTEN and not generic.is_mapped(kind) and kind not in generic.SKIPPED ] assert unknown == [], ( f"new entity kinds with no mapping: map {unknown}, or add them to generic.SKIPPED with a reason" ) def test_every_kind_the_library_knows_has_a_recipe_or_a_reason(): recipe_kinds = {catalogue.kind_of(key) for key in catalogue.RECIPES} unexplained = [k for k in catalogue.all_kinds() if k not in recipe_kinds and k not in catalogue.UNHOSTABLE] assert unexplained == [], ( f"new entity kinds {unexplained}: write a recipe in catalogue.RECIPES (switch on every capability of the " "entity, so every field it exposes is tested), with its EXPECTED parameters and UNMAPPED fields, or explain in " "catalogue.UNHOSTABLE why the host node cannot run it" ) def test_the_catalogue_tables_agree(): kinds = set(catalogue.all_kinds()) named = {catalogue.kind_of(key) for key in (*catalogue.RECIPES, *catalogue.EXPECTED, *catalogue.UNMAPPED)} named |= set(catalogue.UNHOSTABLE) assert named - kinds == set(), f"kinds the library no longer knows: {sorted(named - kinds)}" assert {catalogue.kind_of(key) for key in catalogue.RECIPES} & set(catalogue.UNHOSTABLE) == set() assert set(catalogue.EXPECTED) == set(catalogue.RECIPES), "every recipe needs its EXPECTED parameters, and back" assert set(catalogue.UNMAPPED) <= set(catalogue.RECIPES) def sample_value(parameter: ESPhomeParameter) -> Any: """A value the parameter accepts, picked from what the parameter itself declares.""" if parameter.fields: # a struct, or a command with arguments: a value per sub-parameter, keyed by its id subs = [ESPhomeParameter.model_validate(sub) for sub in parameter.fields] return {str(sub.id): sample_value(sub) for sub in subs} low, high = parameter.min_value, parameter.max_value match parameter.data_type: case ParameterDataType.bool: return True case ParameterDataType.none: return None case ParameterDataType.enum: return next(iter(parameter.valid_values or {0: ""})) case ParameterDataType.integer: return int(low) if low is not None else 1 case ParameterDataType.decimal: return (low + high) / 2 if low is not None and high is not None else 1.0 case _: return "x" @pytest.mark.catalogue @pytest.mark.timeout(120) @pytest.mark.parametrize("recipe", catalogue.recipe_keys()) async def test_every_entity_kind_works_end_to_end( recipe: str, controller: ESPhomeController, mdns: FakeMDNS, output, build_errors: dict[str, str | None] ): kind = catalogue.kind_of(recipe) assert build_errors.get(recipe) is None, build_errors.get(recipe) sketch = catalogue.sketch_for(recipe) node = VirtualDevice(sketch) await node.start() try: await mdns.announce(Advert(name=sketch.name, mac=sketch.mac, port=sketch.port)) (discovery,) = controller.discoveries.values() user_picks(discovery) await hub_pairs(controller, discovery, credentials=None) async with controller.platform.device_repository(controller) as repo: device = await repo.get(physical_id=discovery.id, as_=ESPhomeDevice) assert device is not None assert {p.integration_data.component_type for p in device.parameters} <= {kind} assert len({p.id for p in device.parameters}) == len(device.parameters) # every parameter is the one the recipe's entity must produce ... actual = {p.integration_data.sub_field: (p.data_type, p.role) for p in device.parameters} assert actual == catalogue.EXPECTED[recipe] # ... and every field of the entity's state and command is either exposed or explained state, arguments = generic.api_fields(kind) sub_fields = { ESPhomeParameter.model_validate(sub).integration_data.sub_field for p in device.parameters for sub in p.fields or [] } unmapped = (state | arguments) - set(actual) - sub_fields # a date's year is mapped as a field of `date` explained = set(catalogue.UNMAPPED.get(recipe, {})) assert unmapped == explained, ( f"{kind}: fields neither mapped nor explained in UNMAPPED: {sorted(unmapped - explained)}; " f"explained but now mapped or gone: {sorted(explained - unmapped)}" ) await asyncio.sleep(1.5) # the node pushes its initial states assert_values_match_parameters(output, device) for parameter in device.parameters: if parameter.role != ParameterRole.control: continue command = DeviceCommand(device_id=device.id, parameter_id=parameter.id, value=sample_value(parameter)) await controller.send_command(command, device, parameter) await asyncio.sleep(0.2) await asyncio.sleep(0.5) await controller.fetch(device) # raises when the connection was lost assert node.running, f"the {kind} node died:\n{node.log[-1500:]}" assert_values_match_parameters(output, device) finally: await node.stop() ================================================================================ # FILE: tests/test_commands.py ================================================================================ """Hub -> device: commands sent through the controller reach a virtual ESPHome device and take effect.""" from typing import Any import pytest from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.parameter import ParameterVisibility from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import param, values, wait_for_value, wait_until from tests.virtual.runner import VirtualDevice async def command(controller: ESPhomeController, device: ESPhomeDevice, entity: str, sub_field: str, value: Any): target = param(device, entity, sub_field) await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=target.id, value=value), device, target ) async def test_switch_turns_on_and_off(controller: ESPhomeController, paired: ESPhomeDevice, output): relay = param(paired, "Relay") await command(controller, paired, "Relay", "state", True) await wait_for_value(output, relay, lambda v: v is True) await command(controller, paired, "Relay", "state", False) await wait_for_value(output, relay, lambda v: v is False) async def test_fan_turns_on(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "Virtual Fan", "state", True) await wait_for_value(output, param(paired, "Virtual Fan"), lambda v: v is True) async def test_light_switches_and_dims(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "Virtual Light", "state", True) await wait_for_value(output, param(paired, "Virtual Light"), lambda v: v is True) await command(controller, paired, "Virtual Light", "brightness", 0.5) await wait_for_value( output, param(paired, "Virtual Light", "brightness"), lambda v: v == pytest.approx(0.5, abs=0.02) ) async def test_changing_the_hue_keeps_the_saturation(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "RGB Light", "state", True) await command(controller, paired, "RGB Light", "color_saturation", 100) await wait_for_value( output, param(paired, "RGB Light", "color_saturation"), lambda v: v == pytest.approx(100, abs=1) ) await command(controller, paired, "RGB Light", "color_hue", 120) # green await wait_for_value(output, param(paired, "RGB Light", "color_hue"), lambda v: v == pytest.approx(120, abs=2)) latest = values(output, param(paired, "RGB Light", "color_saturation").id)[-1] assert latest == pytest.approx(100, abs=1), "setting the hue must not reset the saturation" async def test_cover_moves_to_a_position(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "Blinds", "position", 30) await wait_for_value(output, param(paired, "Blinds", "position"), lambda v: v == pytest.approx(30, abs=1)) async def test_number_is_set(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "Target Temp", "state", 20.5) await wait_for_value(output, param(paired, "Target Temp"), lambda v: v == 20.5) async def test_select_is_set_by_option_index(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "Mode", "state", 1) await wait_for_value(output, param(paired, "Mode"), lambda v: v == 1) async def test_select_is_set_by_option_name(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "Mode", "state", "MANUAL") await wait_for_value(output, param(paired, "Mode"), lambda v: v == 1) async def test_button_is_pressed(controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice): await command(controller, paired, "Reboot", "state", None) await device.wait_log("Reboot pressed") async def test_climate_mode_and_targets_are_set(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "HVAC", "mode", 3) # heat await wait_for_value(output, param(paired, "HVAC", "mode"), lambda v: v == 3) await command(controller, paired, "HVAC", "target_temperature_low", 19.0) await wait_for_value(output, param(paired, "HVAC", "target_temperature_low"), lambda v: v == 19.0) async def test_climate_mode_is_set_by_name(controller: ESPhomeController, paired: ESPhomeDevice, output): await command(controller, paired, "HVAC", "mode", "HEAT") await wait_for_value(output, param(paired, "HVAC", "mode"), lambda v: v == 3) @pytest.mark.parametrize( ("entity", "sub_field", "value"), [ ("Temperature", "state", 5.0), # sensors are read-only ("Mode", "state", 7), # no such option ("Mode", "state", "BOOST"), # no such option name ("Mode", "state", True), # not an option index, although it equals 1 ("Target Temp", "state", 99.0), # outside the device's 10..30 ("Virtual Light", "brightness", 150), # a percentage ("RGB Light", "color_hue", 400), # degrees ], ) async def test_invalid_commands_are_rejected_before_reaching_the_device( controller: ESPhomeController, paired: ESPhomeDevice, entity: str, sub_field: str, value: Any ): with pytest.raises(ValueError): await command(controller, paired, entity, sub_field, value) @pytest.mark.timeout(60) async def test_command_to_an_offline_device_fails_visibly( controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice, output: RecordingControllerOutput ): await device.stop() await wait_until(lambda: paired.physical_id in output.lost_devices, 15, "the device to be reported lost") with pytest.raises(ConnectionError): await command(controller, paired, "Relay", "state", True) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=paired.physical_id, as_=ESPhomeDevice) assert stored is not None assert stored.last_error async def test_the_transition_is_a_setting_kept_and_added_to_later_light_commands( controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice, output ): transition = param(paired, "Virtual Light", "transition_length") assert transition.visibility == ParameterVisibility.setting await command(controller, paired, "Virtual Light", "transition_length", 1.5) await wait_for_value(output, transition, lambda v: v == 1.5) # echoed, so the Hub stores it await command(controller, paired, "Virtual Light", "state", True) await device.wait_log("Transition length: 1.5s") output.events.clear() await controller.fetch(paired) await wait_for_value(output, transition, lambda v: v == 1.5) # kept across fetches async def test_the_flash_command_takes_its_length_as_an_argument( controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice ): flash = param(paired, "Virtual Light", "flash") (length,) = [type(flash).model_validate(f) for f in flash.fields or []] await command(controller, paired, "Virtual Light", "flash", {str(length.id): 1.0}) await device.wait_log("Flash length: 1.0s") ================================================================================ # FILE: tests/test_controller.py ================================================================================ """Controller behavior with the device connection mocked: pairing, commands, unpairing, error paths. Entities are real `aioesphomeapi` descriptions (what a device actually reports), not hand-made mocks. """ import asyncio from typing import Any from unittest.mock import AsyncMock from uuid import UUID import pytest from aioesphomeapi import CameraInfo, LightInfo, SwitchInfo from majordom_integration_sdk import DeviceIdTakenError, Endpoint, PeripheralChange, Peripherals, Platform from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.schemas.parameter import ParameterDataType, ParameterRole from majordom_integration_sdk.testing import RecordingControllerOutput import majordom_esphome from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice, ESPhomeDeviceIntegrationData from tests.helpers import ROOM, assert_not_paired, draft_of, hub_pairs, param, user_picks from tests.virtual.mdns import Advert, FakeMDNS, settle SWITCH_KEY = 7 # deliberately different from every other number in the tests @pytest.fixture async def mock_discovery(controller: ESPhomeController, mdns: FakeMDNS) -> Discovery: await mdns.announce(Advert()) (found,) = controller.discoveries.values() user_picks(found) return found @pytest.fixture async def mock_paired(controller: ESPhomeController, mock_discovery: Discovery, mock_connection: Any, make_entity: Any): _, connection = mock_connection connection.get_entities.return_value = { SWITCH_KEY: make_entity(SwitchInfo, SWITCH_KEY, "Relay"), 11: make_entity(LightInfo, 11, "Lamp", supported_color_modes=[3]), } await hub_pairs(controller, mock_discovery, credentials=None) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=mock_discovery.id, as_=ESPhomeDevice) assert stored is not None return stored async def test_pairing_stores_a_parameter_per_entity_capability( mock_paired: ESPhomeDevice, mock_connection: Any, output: RecordingControllerOutput, controller: ESPhomeController ): _, connection = mock_connection relay = param(mock_paired, "Relay") assert (relay.data_type, relay.role) == (ParameterDataType.bool, ParameterRole.control) assert param(mock_paired, "Lamp", "state").data_type == ParameterDataType.bool assert param(mock_paired, "Lamp", "brightness").data_type == ParameterDataType.decimal assert mock_paired.physical_id in output.connected_devices assert mock_paired.id not in controller.discoveries connection.start.assert_awaited_once() connection.wait_ready.assert_awaited_once() async def test_pairing_skips_entities_it_cannot_map( controller: ESPhomeController, mock_discovery: Discovery, mock_connection: Any, make_entity: Any ): _, connection = mock_connection connection.get_entities.return_value = { 1: make_entity(CameraInfo, 1, "Cam"), 2: make_entity(SwitchInfo, 2, "Relay"), } await hub_pairs(controller, mock_discovery, credentials=None) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=mock_discovery.id, as_=ESPhomeDevice) assert stored is not None assert {p.integration_data.entity_name for p in stored.parameters} == {"Relay"} async def test_failed_pairing_is_cleaned_up_and_reported( controller: ESPhomeController, mock_discovery: Discovery, mock_connection: Any, output: RecordingControllerOutput, ): _, connection = mock_connection connection.wait_ready.side_effect = TimeoutError("no answer") with pytest.raises(TimeoutError): await hub_pairs(controller, mock_discovery, credentials=None) connection.stop.assert_awaited_once() assert mock_discovery.id in controller.discoveries await assert_not_paired(controller.platform, mock_discovery.id) assert output.updated_discoveries[-1].last_error, "the user must see why pairing failed" assert output.connected_devices == [] async def test_command_reaches_the_connection_with_the_entity_key( controller: ESPhomeController, mock_paired: ESPhomeDevice, mock_connection: Any ): _, connection = mock_connection relay = param(mock_paired, "Relay") await controller.send_command( DeviceCommand(device_id=mock_paired.id, parameter_id=relay.id, value=True), mock_paired, relay ) connection.send_command.assert_awaited_once_with(SWITCH_KEY, "switch", {"key": SWITCH_KEY, "state": True}) async def test_command_to_disconnected_device_fails_visibly( controller: ESPhomeController, mock_paired: ESPhomeDevice, mock_connection: Any ): await controller.unpair(mock_paired) relay = param(mock_paired, "Relay") with pytest.raises(ConnectionError): await controller.send_command( DeviceCommand(device_id=mock_paired.id, parameter_id=relay.id, value=True), mock_paired, relay ) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=mock_paired.physical_id, as_=ESPhomeDevice) assert stored is not None assert stored.last_error, "a failed command must leave a user-readable last_error on the device" async def test_command_on_read_only_parameter_is_rejected( controller: ESPhomeController, mock_discovery: Discovery, mock_connection: Any, make_entity: Any ): from aioesphomeapi import SensorInfo _, connection = mock_connection connection.get_entities.return_value = {3: make_entity(SensorInfo, 3, "Temperature")} await hub_pairs(controller, mock_discovery, credentials=None) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=mock_discovery.id, as_=ESPhomeDevice) assert stored is not None temperature = param(stored, "Temperature") with pytest.raises(ValueError, match="read-only"): await controller.send_command( DeviceCommand(device_id=stored.id, parameter_id=temperature.id, value=1.0), stored, temperature ) connection.send_command.assert_not_awaited() async def test_unpair_closes_the_connection( controller: ESPhomeController, mock_paired: ESPhomeDevice, mock_connection: Any ): _, connection = mock_connection await controller.unpair(mock_paired) connection.stop.assert_awaited_once() assert controller._connections == {} async def test_identify_keeps_the_connection( controller: ESPhomeController, mock_paired: ESPhomeDevice, mock_connection: Any ): _, connection = mock_connection await controller.identify(mock_paired) # ESPHome has no identify action: nothing to send, nothing may break connection.stop.assert_not_awaited() await controller.fetch(mock_paired) async def test_pairing_refuses_an_id_another_record_holds_before_connecting( controller: ESPhomeController, mock_discovery: Discovery, mock_connection: Any ): MockConn, _ = mock_connection async with controller.platform.device_repository(controller) as repo: await repo.save( ESPhomeDevice( id=UUID(int=9), physical_id=mock_discovery.id, name="Old relay", room_id=ROOM, transport="tcp", integration=controller.key, manufacturer=None, ) ) with pytest.raises(DeviceIdTakenError) as taken: await controller.pair_device( mock_discovery, draft_of(mock_discovery).model_copy(update={"physical_id": UUID(int=7)}), None ) assert (taken.value.physical_id, taken.value.device_id, taken.value.name) == ( mock_discovery.id, UUID(int=9), "Old relay", ) MockConn.assert_not_called() async def test_pairing_onto_the_picked_record_keeps_only_what_is_this_nodes( controller: ESPhomeController, mock_discovery: Discovery, mock_connection: Any ): kept = ESPhomeDeviceIntegrationData(encryption_key="its-key", settings={"lamp": {"transition_length": 2.0}}) same = draft_of(mock_discovery).model_copy(update={"integration_data": kept}) other = same.model_copy(update={"physical_id": UUID(int=7)}) # a record of another node: its data is stale assert (await controller.pair_device(mock_discovery, same, None)).integration_data.settings == kept.settings filled = await controller.pair_device(mock_discovery, other, None) assert filled.physical_id == mock_discovery.id assert filled.id == other.id assert (filled.integration_data.settings, filled.integration_data.encryption_key) == ({}, None) async def test_fetch_connects_again_only_once_the_connection_is_gone( controller: ESPhomeController, mock_paired: ESPhomeDevice, mock_connection: Any ): MockConn, connection = mock_connection connection.running = True await controller.fetch(mock_paired) connection.start.assert_awaited_once() connection.running = False await controller.fetch(mock_paired) assert connection.start.await_count == 2 MockConn.assert_called_once() # the same connection: never a second subscription async def test_unpair_rolls_back_a_draft_that_got_nowhere(controller: ESPhomeController, mock_discovery: Discovery): await controller.unpair(draft_of(mock_discovery)) assert controller._connections == {} and controller._just_paired == {} async def test_a_paired_node_the_hub_never_saves_is_let_go_of( controller: ESPhomeController, mock_discovery: Discovery, mock_connection: Any, monkeypatch: pytest.MonkeyPatch, ): _, connection = mock_connection monkeypatch.setattr(majordom_esphome.controller, "UNSAVED_PAIRING_TIMEOUT", 0.01) await controller.pair_device(mock_discovery, draft_of(mock_discovery), None) await asyncio.sleep(0.05) assert controller._just_paired == {} connection.stop.assert_awaited_once() async def test_fetch_of_unknown_device_raises(controller: ESPhomeController, mock_paired: ESPhomeDevice): stranger = mock_paired.model_copy( update={"physical_id": UUID(int=1), "integration_data": ESPhomeDeviceIntegrationData()} ) with pytest.raises(ConnectionError): await controller.fetch(stranger) def test_it_needs_zeroconf_and_borrows_the_router_never_raw_bluetooth(): needs = {need.family: need for need in ESPhomeController.needs} assert needs["mdns"].dialects == ["zeroconf"] and needs["mdns"].is_required assert needs["ble"].accepts(Endpoint("ble", "router")) and not needs["ble"].is_required assert not needs["ble"].accepts(Endpoint("ble", "bluez", "hci0")) def test_the_package_provides_its_controller_alone(platform: Platform): (controller,) = majordom_esphome.peripherals(platform) assert isinstance(controller, ESPhomeController) and controller.platform is platform assert (controller.name, controller.key) == ("ESPHome", "esphome") async def test_a_border_router_coming_and_going_needs_no_restart(controller: ESPhomeController): border_router = Endpoint("thread", "otbr-rest", "http://otbr:8081") assert await controller.needed_peripheral_did_change(PeripheralChange("thread", None, border_router)) assert await controller.needed_peripheral_did_change(PeripheralChange("thread", border_router, None)) async def test_another_zeroconf_restarts_it(controller: ESPhomeController): zeroconf = controller.peripherals.endpoint("mdns") moved = PeripheralChange("mdns", zeroconf, Endpoint("mdns", "zeroconf", "other", instance=zeroconf.instance)) assert not await controller.needed_peripheral_did_change(moved) async def test_a_start_cut_short_stops_cleanly_and_starts_again( platform: Platform, peripherals: Peripherals, output: RecordingControllerOutput, mdns: FakeMDNS, monkeypatch: pytest.MonkeyPatch, ): controller = ESPhomeController(platform) controller.peripherals, controller.output = peripherals, output monkeypatch.setattr(ESPhomeController, "_load_paired_devices", AsyncMock(side_effect=RuntimeError("no database"))) with pytest.raises(RuntimeError): await controller.start() await controller.stop() # as the runtime does after a failed start, keeping the instance await settle() assert [browser for browser in mdns.browsers if not browser.cancelled] == [] monkeypatch.undo() await controller.start() try: await mdns.announce(Advert()) assert len(controller.discoveries) == 1 finally: await controller.stop() FACTORY_RESET_KEY = 77 @pytest.fixture def factory_reset_button(mock_connection: Any, make_entity: Any, monkeypatch: pytest.MonkeyPatch) -> Any: from aioesphomeapi import ButtonInfo monkeypatch.setattr("majordom_esphome.controller.FACTORY_RESET_GRACE", 0) _, connection = mock_connection entities = connection.get_entities.return_value connection.get_entities.return_value = { **entities, FACTORY_RESET_KEY: make_entity(ButtonInfo, FACTORY_RESET_KEY, "Factory Reset"), } return connection async def test_unpair_presses_factory_reset_before_dropping_the_connection( controller: ESPhomeController, mock_paired: ESPhomeDevice, factory_reset_button: Any ): calls: list[str] = [] factory_reset_button.send_command.side_effect = lambda *_: calls.append("press") factory_reset_button.stop.side_effect = lambda: calls.append("stop") await controller.unpair(mock_paired) factory_reset_button.send_command.assert_awaited_once_with(FACTORY_RESET_KEY, "button", {"key": FACTORY_RESET_KEY}) assert calls == ["press", "stop"] async def test_unpair_skips_factory_reset_of_an_offline_node( controller: ESPhomeController, mock_paired: ESPhomeDevice, factory_reset_button: Any ): factory_reset_button.ready = False await controller.unpair(mock_paired) factory_reset_button.send_command.assert_not_awaited() factory_reset_button.stop.assert_awaited_once() async def test_unpair_skips_factory_reset_without_the_button( controller: ESPhomeController, mock_paired: ESPhomeDevice, mock_connection: Any ): _, connection = mock_connection await controller.unpair(mock_paired) connection.send_command.assert_not_awaited() connection.stop.assert_awaited_once() async def test_unpair_completes_when_the_factory_reset_fails( controller: ESPhomeController, mock_paired: ESPhomeDevice, factory_reset_button: Any ): factory_reset_button.send_command.side_effect = ConnectionError("Device not connected") await controller.unpair(mock_paired) factory_reset_button.stop.assert_awaited_once() async def test_unpair_does_not_wait_forever_for_the_factory_reset( controller: ESPhomeController, mock_paired: ESPhomeDevice, factory_reset_button: Any, monkeypatch: pytest.MonkeyPatch, ): async def hang(*_: Any): await asyncio.sleep(3600) monkeypatch.setattr("majordom_esphome.controller.FACTORY_RESET_TIMEOUT", 0.05) factory_reset_button.send_command.side_effect = hang await controller.unpair(mock_paired) factory_reset_button.stop.assert_awaited_once() ================================================================================ # FILE: tests/test_discovery.py ================================================================================ """mDNS discovery: nodes announced through the SDK's zeroconf service become correct discoveries.""" import pytest from majordom_integration_sdk.schemas import CredentialsType from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_esphome.controller import ESPhomeController from tests.virtual.mdns import Advert, FakeMDNS, settle MAC = "983569abf679" async def test_announced_node_becomes_a_discovery( controller: ESPhomeController, mdns: FakeMDNS, output: RecordingControllerOutput ): await mdns.announce(Advert()) assert len(output.received_discoveries) == 1 discovered = output.received_discoveries[0] assert controller.discoveries == {discovered.id: discovered} assert discovered.integration == controller.key # the Hub creates its device in the controller's scope async def test_controller_stops_listening_on_stop(controller: ESPhomeController, mdns: FakeMDNS): await controller.stop() await settle() # the SDK cancels the browser in a task await mdns.announce(Advert()) assert controller.discoveries == {} async def test_discovery_id_is_the_sdk_hardware_identity(controller: ESPhomeController, mdns: FakeMDNS): await mdns.announce(Advert(mac=MAC)) assert list(controller.discoveries) == [controller.device_uuid(bytes.fromhex(MAC))] async def test_discovery_is_named_after_the_node_not_its_mdns_record(controller: ESPhomeController, mdns: FakeMDNS): await mdns.announce(Advert(name="kitchen_relay")) assert next(iter(controller.discoveries.values())).device_name == "kitchen_relay" async def test_friendly_name_is_preferred_when_the_node_has_one(controller: ESPhomeController, mdns: FakeMDNS): await mdns.announce(Advert(name="kitchen_relay", friendly_name="Kitchen Relay")) assert next(iter(controller.discoveries.values())).device_name == "Kitchen Relay" async def test_discovery_does_not_claim_a_device_category(controller: ESPhomeController, mdns: FakeMDNS): await mdns.announce(Advert()) assert next(iter(controller.discoveries.values())).device_category is None # a node may host anything async def test_plain_node_needs_no_credentials(controller: ESPhomeController, mdns: FakeMDNS): await mdns.announce(Advert(encrypted=False)) assert next(iter(controller.discoveries.values())).expected_credentials_options == [CredentialsType.none] async def test_encrypted_node_asks_for_its_key(controller: ESPhomeController, mdns: FakeMDNS): await mdns.announce(Advert(encrypted=True)) assert next(iter(controller.discoveries.values())).expected_credentials_options == [CredentialsType.secret] async def test_repeated_announcement_is_not_a_new_discovery( controller: ESPhomeController, mdns: FakeMDNS, output: RecordingControllerOutput ): await mdns.announce(Advert()) await mdns.announce(Advert()) assert len(output.received_discoveries) == 1 assert output.updated_discoveries == [] async def test_changed_announcement_updates_the_discovery( controller: ESPhomeController, mdns: FakeMDNS, output: RecordingControllerOutput ): await mdns.announce(Advert(encrypted=False)) await mdns.announce(Advert(encrypted=True)) assert len(output.updated_discoveries) == 1 assert output.updated_discoveries[0].expected_credentials_options == [CredentialsType.secret] assert list(controller.discoveries.values()) == output.updated_discoveries async def test_vanished_node_is_lost(controller: ESPhomeController, mdns: FakeMDNS, output: RecordingControllerOutput): advert = Advert() await mdns.announce(advert) (discovery_id,) = controller.discoveries await mdns.goodbye(advert) assert output.lost_discoveries == [discovery_id] assert controller.discoveries == {} @pytest.mark.parametrize( "incomplete", [Advert(mac=None), Advert(server=None, addresses=[])], ids=["no-mac", "no-address"] ) async def test_incomplete_announcement_never_raises( controller: ESPhomeController, mdns: FakeMDNS, output: RecordingControllerOutput, incomplete: Advert ): await mdns.announce(incomplete) # must not break the SDK's discovery loop assert output.error_log == [] ================================================================================ # FILE: tests/test_encryption.py ================================================================================ """Devices with Noise API encryption: the key is requested, validated, used, kept and never leaked.""" import logging import pytest from majordom_integration_sdk.schemas import CredentialsType, ProvidedCredentials from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import assert_not_paired, hub_pairs, leaked_tasks, param, user_picks, wait_for_value, wait_until from tests.virtual.mdns import Advert, FakeMDNS from tests.virtual.runner import ENCRYPTION_KEY as KEY from tests.virtual.runner import VirtualDevice WRONG_KEY = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" @pytest.fixture async def encrypted_discovery( controller: ESPhomeController, mdns: FakeMDNS, encrypted_device: VirtualDevice ) -> Discovery: await mdns.announce(Advert(name="test_node_enc", port=encrypted_device.port, encrypted=True)) (found,) = controller.discoveries.values() user_picks(found) return found def secret(value: str | None) -> ProvidedCredentials: return ProvidedCredentials(type=CredentialsType.secret, value=value) async def test_discovery_asks_for_the_key(encrypted_discovery: Discovery): assert encrypted_discovery.expected_credentials_options == [CredentialsType.secret] @pytest.mark.parametrize("credentials", [None, ProvidedCredentials(type=CredentialsType.none)]) async def test_pairing_without_the_key_is_refused( controller: ESPhomeController, encrypted_discovery: Discovery, credentials: ProvidedCredentials | None ): with pytest.raises(ValueError): await hub_pairs(controller, encrypted_discovery, credentials) await assert_not_paired(controller.platform, encrypted_discovery.id) async def test_pairing_with_a_code_instead_of_the_key_is_refused( controller: ESPhomeController, encrypted_discovery: Discovery ): with pytest.raises(ValueError): await hub_pairs(controller, encrypted_discovery, ProvidedCredentials(type=CredentialsType.code, value=KEY)) @pytest.mark.timeout(60) async def test_pairing_with_a_wrong_key_fails_cleanly( controller: ESPhomeController, encrypted_discovery: Discovery, output: RecordingControllerOutput ): with pytest.raises((ConnectionError, TimeoutError, ValueError)): await hub_pairs(controller, encrypted_discovery, secret(WRONG_KEY)) await assert_not_paired(controller.platform, encrypted_discovery.id) assert output.connected_devices == [] assert "key" in (output.updated_discoveries[-1].last_error or "").lower(), ( "the user must be told the key was rejected" ) assert leaked_tasks() == [] async def test_pairing_with_the_key_works_like_a_plain_device( controller: ESPhomeController, encrypted_discovery: Discovery, output: RecordingControllerOutput ): await hub_pairs(controller, encrypted_discovery, secret(KEY)) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=encrypted_discovery.id, as_=ESPhomeDevice) assert stored is not None assert len(stored.parameters) == 33 assert stored.integration_data.encryption_key == KEY await wait_for_value(output, param(stored, "Temperature"), lambda v: v == 21.5) @pytest.mark.timeout(60) async def test_encrypted_device_reconnects_after_hub_restart( controller: ESPhomeController, encrypted_discovery: Discovery, output: RecordingControllerOutput ): await hub_pairs(controller, encrypted_discovery, secret(KEY)) await controller.stop() output.connected_devices.clear() restarted = ESPhomeController(controller.platform) restarted.peripherals = controller.peripherals restarted.output = controller.output await restarted.start() try: await wait_until( lambda: encrypted_discovery.id in output.connected_devices, 15, "the encrypted device to reconnect" ) finally: await restarted.stop() async def test_the_key_is_never_logged( controller: ESPhomeController, encrypted_discovery: Discovery, caplog: pytest.LogCaptureFixture ): caplog.set_level(logging.DEBUG) await hub_pairs(controller, encrypted_discovery, secret(KEY)) with pytest.raises((ConnectionError, TimeoutError, ValueError)): await hub_pairs(controller, encrypted_discovery, secret(WRONG_KEY)) assert KEY not in caplog.text assert WRONG_KEY not in caplog.text ================================================================================ # FILE: tests/test_enum_commands.py ================================================================================ """Enum parameters (a select, option lists, the library's integer enums): the value the Hub sends and the one reported. An enum's value is the integer key of `valid_values`, its label the option or member name. The Hub may send either: the key (also as a numeric string, as JSON may carry it) or the label. Both must reach the device as the same command, and the device's state must come back as the key. """ from typing import Any import pytest from aioesphomeapi import ( ClimateFanMode, ClimateInfo, ClimateMode, EntityInfo, FanInfo, LightInfo, SelectInfo, SelectState, ) from majordom_esphome import mapper from majordom_esphome.models import ESPhomeParameter from tests.test_unhosted_fields import parameter_of, spec_of # the library's dataclasses are not typed for construction Select: Any = SelectInfo Climate: Any = ClimateInfo Fan: Any = FanInfo Light: Any = LightInfo Selected: Any = SelectState MODE = Select(object_id="mode", key=9, name="Mode", options=["Eco", "Comfort", "Boost"]) THERMOSTAT = Climate( object_id="hvac", key=7, name="HVAC", supported_modes=[ClimateMode.OFF, ClimateMode.HEAT], supported_fan_modes=[ClimateFanMode.LOW, ClimateFanMode.HIGH], supported_custom_fan_modes=["Breeze", "Gust"], ) FAN = Fan(object_id="fan", key=5, name="Fan", supported_preset_modes=["eco", "turbo"]) LIGHT = Light(object_id="light", key=3, name="Light", supported_color_modes=[1], effects=["None", "Rainbow"]) def parameter(entity: EntityInfo, sub_field: str) -> ESPhomeParameter: spec = spec_of(entity, sub_field) assert spec is not None return parameter_of(entity, spec) def stored(parameter: ESPhomeParameter) -> ESPhomeParameter: """The parameter as it comes back from storage: JSON object keys are strings.""" return ESPhomeParameter.model_validate_json(parameter.model_dump_json()) # (entity, sub_field, key, label, the argument the library's command gets) CASES = [ pytest.param(MODE, "state", 2, "Boost", "Boost", id="select"), pytest.param(THERMOSTAT, "mode", int(ClimateMode.HEAT), "HEAT", ClimateMode.HEAT, id="climate mode"), pytest.param(THERMOSTAT, "fan_mode", int(ClimateFanMode.HIGH), "HIGH", ClimateFanMode.HIGH, id="climate fan mode"), pytest.param(THERMOSTAT, "custom_fan_mode", 1, "Gust", "Gust", id="climate custom fan mode"), pytest.param(FAN, "preset_mode", 1, "turbo", "turbo", id="fan preset"), pytest.param(LIGHT, "effect", 1, "Rainbow", "Rainbow", id="light effect"), ] @pytest.mark.parametrize(("entity", "sub_field", "key", "label", "sent"), CASES) @pytest.mark.parametrize("given", ["key", "numeric string", "label"]) def test_an_enum_is_set_by_its_key_or_its_label( entity: EntityInfo, sub_field: str, key: int, label: str, sent: Any, given: str ): value = {"key": key, "numeric string": str(key), "label": label}[given] for target in (parameter(entity, sub_field), stored(parameter(entity, sub_field))): args = mapper.build_command_args(target, value, {}) assert args == {"key": entity.key, sub_field: sent} assert type(args[sub_field]) is type(sent) @pytest.mark.parametrize(("entity", "sub_field", "key", "label", "sent"), CASES) @pytest.mark.parametrize("value", [99, "99", "no such option", True, None, 1.5]) def test_an_enum_value_that_names_no_option_is_rejected( entity: EntityInfo, sub_field: str, key: int, label: str, sent: Any, value: Any ): with pytest.raises(ValueError): mapper.build_command_args(parameter(entity, sub_field), value, {}) def test_a_select_state_is_reported_as_the_key_of_its_option(): assert mapper.state_values(MODE, Selected(key=9, state="Boost")) == {"state": 2} assert mapper.state_values(MODE, Selected(key=9, state="Eco")) == {"state": 0} assert mapper.state_values(MODE, Selected(key=9, state="Unknown")) == {} # not an option: nothing to report ================================================================================ # FILE: tests/test_fallback.py ================================================================================ """Entities without a hand-written mapping (lock, valve, text, ...) are mapped generically from the library's types. The virtual node `extras.yaml` hosts them. What has no meaningful mapping (events, multi-argument commands) is skipped without breaking pairing. """ from collections.abc import AsyncIterator from typing import Any import pytest import pytest_asyncio from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.parameter import ParameterDataType as T from majordom_integration_sdk.schemas.parameter import ParameterRole as R from majordom_integration_sdk.schemas.parameter import ParameterUnit, ParameterVisibility from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import assert_values_match_parameters, hub_pairs, param, user_picks, wait_for_value from tests.virtual.mdns import Advert, FakeMDNS from tests.virtual.runner import EXTRAS, VirtualDevice pytestmark = pytest.mark.timeout(60) @pytest_asyncio.fixture async def extras_device() -> AsyncIterator[VirtualDevice]: virtual = VirtualDevice(EXTRAS) await virtual.start() yield virtual await virtual.stop() @pytest_asyncio.fixture async def extras(controller: ESPhomeController, mdns: FakeMDNS, extras_device: VirtualDevice) -> ESPhomeDevice: await mdns.announce(Advert(name=EXTRAS.name, mac=EXTRAS.mac, port=EXTRAS.port)) (discovery,) = controller.discoveries.values() user_picks(discovery) await hub_pairs(controller, discovery, credentials=None) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=discovery.id, as_=ESPhomeDevice) assert stored is not None return stored async def send(controller: ESPhomeController, device: ESPhomeDevice, entity: str, sub_field: str, value): target = param(device, entity, sub_field) await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=target.id, value=value), device, target ) async def test_unmapped_entities_get_parameters_from_the_library_types(extras: ESPhomeDevice): actual = { (p.integration_data.entity_name, p.integration_data.sub_field): (p.data_type, p.role) for p in extras.parameters } assert actual == { ("Door", "state"): (T.enum, R.sensor), ("Door", "command"): (T.enum, R.control), ("Garden Valve", "position"): (T.decimal, R.control), ("Garden Valve", "current_operation"): (T.enum, R.sensor), ("Garden Valve", "stop"): (T.none, R.control), # a flag that only means "do it": a button ("Label", "state"): (T.string, R.control), ("House Alarm", "state"): (T.enum, R.sensor), ("House Alarm", "command"): (T.enum, R.control), ("House Alarm", "command_with_code"): (T.struct, R.control), # the panel requires a code ("House Alarm", "code"): (T.string, R.control), # its default code, a setting ("Date", "date"): (T.struct, R.control), # year, month and day as its fields } # the doorbell (an event) is skipped async def test_enums_are_integers_labelled_with_the_library_enum_names(extras: ESPhomeDevice): assert param(extras, "Door", "command").valid_values == {0: "UNLOCK", 1: "LOCK", 2: "OPEN"} assert param(extras, "Door", "state").valid_values == { 0: "NONE", 1: "LOCKED", 2: "UNLOCKED", 3: "JAMMED", 4: "LOCKING", 5: "UNLOCKING", 6: "OPENING", 7: "OPEN", } assert param(extras, "Garden Valve", "current_operation").valid_values == { 0: "IDLE", 1: "IS_OPENING", 2: "IS_CLOSING", } async def test_fractions_are_percentages_like_in_the_hand_written_mapping(extras: ESPhomeDevice): position = param(extras, "Garden Valve", "position") assert (position.unit, position.min_value, position.max_value) == (ParameterUnit.percentage, 0, 100) async def test_states_are_reported_with_the_declared_types(extras: ESPhomeDevice, output): await wait_for_value(output, param(extras, "Door", "state")) await wait_for_value(output, param(extras, "Garden Valve", "position"), lambda v: v == 100) assert_values_match_parameters(output, extras) async def test_text_is_set(controller: ESPhomeController, extras: ESPhomeDevice, output): await send(controller, extras, "Label", "state", "hello") await wait_for_value(output, param(extras, "Label"), lambda v: v == "hello") async def test_lock_is_locked_by_an_enum_command(controller: ESPhomeController, extras: ESPhomeDevice, output): await send(controller, extras, "Door", "command", 1) # LOCK await wait_for_value(output, param(extras, "Door", "state"), lambda v: v == 1) # LOCKED async def test_valve_moves_to_a_position_in_percent(controller: ESPhomeController, extras: ESPhomeDevice, output): await send(controller, extras, "Garden Valve", "position", 40) await wait_for_value(output, param(extras, "Garden Valve", "position"), lambda v: v == pytest.approx(40, abs=1)) async def test_a_flag_command_is_a_button( controller: ESPhomeController, extras: ESPhomeDevice, extras_device: VirtualDevice ): await send(controller, extras, "Garden Valve", "stop", None) await extras_device.wait_log("Valve stop") @pytest.mark.parametrize(("entity", "sub_field", "value"), [("Door", "state", 1), ("Door", "command", 9)]) async def test_invalid_generic_commands_are_rejected( controller: ESPhomeController, extras: ESPhomeDevice, entity: str, sub_field: str, value: int ): with pytest.raises(ValueError): await send(controller, extras, entity, sub_field, value) def subs(parameter) -> dict[str, Any]: """Sub-parameters by name.""" return { sub.integration_data.sub_field: sub for sub in (type(parameter).model_validate(f) for f in parameter.fields) } async def test_a_date_is_one_struct_value_set_and_reported_by_its_fields( controller: ESPhomeController, extras: ESPhomeDevice, output ): date = param(extras, "Date", "date") fields = subs(date) value = {str(fields["year"].id): 2026, str(fields["month"].id): 10, str(fields["day"].id): 2} await send(controller, extras, "Date", "date", value) await wait_for_value(output, date, lambda v: v == value) assert (fields["month"].min_value, fields["month"].max_value) == (1, 12) async def test_a_command_that_needs_a_code_takes_it_as_an_argument( controller: ESPhomeController, extras: ESPhomeDevice, output ): command = param(extras, "House Alarm", "command_with_code") fields = subs(command) await send( controller, extras, "House Alarm", "command_with_code", { str(fields["command"].id): 1, # ARM_AWAY str(fields["code"].id): "1234", }, ) await wait_for_value(output, param(extras, "House Alarm", "state"), lambda v: v != 0) # no longer DISARMED async def test_a_kept_default_code_lets_a_plain_command_through( controller: ESPhomeController, extras: ESPhomeDevice, output ): code, state = param(extras, "House Alarm", "code"), param(extras, "House Alarm", "state") assert code.visibility == ParameterVisibility.setting await send(controller, extras, "House Alarm", "command", 1) # ARM_AWAY: arming needs no code on this panel await wait_for_value(output, state, lambda v: v == 2, timeout=10) # ARMED_AWAY after its arming time await send(controller, extras, "House Alarm", "code", "1234") await wait_for_value(output, code, lambda v: v == "1234") # echoed, so the Hub stores it await send(controller, extras, "House Alarm", "command", 0) # DISARM, typed without a code: it needs one await wait_for_value(output, state, lambda v: v == 0, timeout=10) # DISARMED: the kept code was sent ================================================================================ # FILE: tests/test_improv.py ================================================================================ """Unprovisioned nodes over Improv BLE: found by their advert, given the Hub's Wi-Fi, then paired over the network. ESPHome host nodes have no BLE, so the node's Improv GATT service is scripted below as the connection a Bluetooth source hands out; the SDK's real Bluetooth router routes its adverts and connections. Once the node "joins" Wi-Fi, the compiled keyless virtual node appears over mDNS. """ import asyncio import logging from collections.abc import AsyncIterator, Awaitable, Callable from dataclasses import replace import pytest import pytest_asyncio from bleak.backends.device import BLEDevice from bleak.backends.scanner import AdvertisementData from improv_ble_client import SERVICE_DATA_UUID, SERVICE_UUID, Error, State from improv_ble_client.protocol import ( CHARACTERISTIC_UUID_CAPABILITIES, CHARACTERISTIC_UUID_ERROR, CHARACTERISTIC_UUID_RPC_COMMAND, CHARACTERISTIC_UUID_RPC_RESULT, CHARACTERISTIC_UUID_STATE, IMPROV_CHARACTERISTICS, WiFiSettingsCmd, WiFiSettingsRes, ) from majordom_integration_sdk import DeviceIdTakenError, MissingCredentialsError, Platform, WifiCredentials from majordom_integration_sdk.capabilities import BLE_ROUTER, BLEDiscoveryInfo, GattCharacteristic, GattService from majordom_integration_sdk.peripherals import PeripheralChange, Peripherals from majordom_integration_sdk.runtime.peripherals.providers.ble.router import BLEService from majordom_integration_sdk.schemas import CredentialsType from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.testing import FakeBLESource, RecordingControllerOutput from majordom_esphome import controller as controller_module from majordom_esphome import improv from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import ( assert_not_paired, hub_pairs, leaked_tasks, user_picks, wait_until, ) from tests.virtual.mdns import Advert, FakeMDNS from tests.virtual.runner import KEYLESS, VirtualDevice pytestmark = pytest.mark.timeout(60) def router_of(controller: ESPhomeController) -> BLEService: router = controller.peripherals.instance(BLE_ROUTER) assert isinstance(router, BLEService) return router HOME = WifiCredentials("Home", "correct horse battery") HANDLES = {uuid: 0x11 + i for i, uuid in enumerate(IMPROV_CHARACTERISTICS)} class FakeImprovNode: """An unprovisioned ESPHome node's Improv GATT service, as the `BLEConnection` a Bluetooth source hands out.""" def __init__(self, name: str = KEYLESS.name, address: str = "AA:BB:CC:DD:EE:01"): self.name, self.address = name, address self.state = State.AUTHORIZED self.password = HOME.password # of the network it can join self.fails_with: Error | None = None self.received: list[WifiCredentials] = [] self.on_joined: Callable[[], Awaitable[None]] | None = None # it shows up on the network self._callbacks: dict[int, Callable[[bytes], None]] = {} def advertisement(self, named: bool = True) -> AdvertisementData: return AdvertisementData( local_name=self.name if named else None, manufacturer_data={}, service_data={SERVICE_DATA_UUID: self._service_data()}, service_uuids=[SERVICE_UUID], tx_power=None, rssi=-60, platform_data=(), ) def info(self, named: bool = True) -> BLEDiscoveryInfo: return BLEDiscoveryInfo(BLEDevice(self.address, None, None), self.advertisement(named)) async def advertise(self, source: FakeBLESource, named: bool = True, rssi: int = -60): """Heard by ``source``; returns once the SDK has passed the advert on.""" name = self.name if named else None source.advertise(self.address, rssi, name, [SERVICE_UUID], {SERVICE_DATA_UUID: self._service_data()}) await asyncio.sleep(0.05) async def press_button(self): self.state = State.AUTHORIZED self._notify(CHARACTERISTIC_UUID_STATE, self.state) def _service_data(self) -> bytes: return bytes([self.state, 0, 0, 0, 0, 0]) # BLEConnection @property def mtu(self) -> int: return 247 async def services(self) -> list[GattService]: characteristics = tuple(GattCharacteristic(uuid, handle, ("read",)) for uuid, handle in HANDLES.items()) return [GattService(SERVICE_UUID, 0x10, characteristics)] async def read(self, handle: int) -> bytes: values = {HANDLES[CHARACTERISTIC_UUID_STATE]: self.state, HANDLES[CHARACTERISTIC_UUID_CAPABILITIES]: 0} return bytes([values.get(handle, Error.NO_ERROR)]) async def write(self, handle: int, data: bytes, is_response_needed: bool = True): assert handle == HANDLES[CHARACTERISTIC_UUID_RPC_COMMAND] command = WiFiSettingsCmd.from_bytes(data) asyncio.get_running_loop().create_task( self._join(WifiCredentials(command.ssid.decode(), command.password.decode())) ) async def start_notify(self, handle: int, callback: Callable[[bytes], None]): self._callbacks[handle] = callback async def stop_notify(self, handle: int): self._callbacks.pop(handle, None) async def disconnect(self): self._callbacks.clear() async def _join(self, wifi: WifiCredentials): if self.state == State.AUTHORIZATION_REQUIRED: self._notify(CHARACTERISTIC_UUID_ERROR, Error.NOT_AUTHORIZED) return self.received.append(wifi) self._notify(CHARACTERISTIC_UUID_ERROR, Error.NO_ERROR) self._notify(CHARACTERISTIC_UUID_STATE, State.PROVISIONING) error = self.fails_with or (Error.UNABLE_TO_CONNECT if wifi.password != self.password else None) if error is not None: self._notify(CHARACTERISTIC_UUID_ERROR, error) self._notify(CHARACTERISTIC_UUID_STATE, State.AUTHORIZED) return self.state = State.PROVISIONED self._notify(CHARACTERISTIC_UUID_STATE, self.state) if callback := self._callbacks.get(HANDLES[CHARACTERISTIC_UUID_RPC_RESULT]): callback(WiFiSettingsRes(b"http://127.0.0.1", []).as_bytes()) if self.on_joined is not None: await self.on_joined() def _notify(self, uuid: str, value: int): if callback := self._callbacks.get(HANDLES[uuid]): callback(bytes([value])) @pytest.fixture def node(monkeypatch: pytest.MonkeyPatch) -> FakeImprovNode: monkeypatch.setattr(improv, "AUTHORIZATION_TIMEOUT", 1.0) monkeypatch.setattr(improv, "LEASE_TIMEOUT", 0.5) monkeypatch.setattr(controller_module, "NODE_APPEAR_TIMEOUT", 1.0) return FakeImprovNode() @pytest.fixture def radio(node: FakeImprovNode) -> FakeBLESource: """The Hub's own Bluetooth adapter.""" return FakeBLESource("hci0", connection=node) @pytest.fixture def platform(platform: Platform) -> Platform: return replace(platform, wifi=HOME) @pytest_asyncio.fixture async def router(radio: FakeBLESource) -> AsyncIterator[BLEService]: ble = BLEService(sources=[radio]) await ble.start() yield ble await ble.stop() @pytest.fixture def peripherals(peripherals: Peripherals, router: BLEService) -> Peripherals: return Peripherals({**peripherals.bound, "ble": router.endpoint}) @pytest_asyncio.fixture async def ble_discovery(controller: ESPhomeController, node: FakeImprovNode, radio: FakeBLESource) -> Discovery: await node.advertise(radio) (found,) = controller.discoveries.values() user_picks(found) return found @pytest_asyncio.fixture async def keyless_device() -> AsyncIterator[VirtualDevice]: virtual = VirtualDevice(KEYLESS) await virtual.start() yield virtual await virtual.stop() def joins_as_keyless_device(node: FakeImprovNode, mdns: FakeMDNS): async def appear(): await mdns.announce(Advert(name=KEYLESS.name, mac=KEYLESS.mac, port=KEYLESS.port, keyless=True)) node.on_joined = appear async def last_error(output: RecordingControllerOutput, discovery: Discovery) -> str: return next((d.last_error or "" for d in reversed(output.updated_discoveries) if d.id == discovery.id), "") # Discovery async def test_a_node_waiting_for_wifi_is_discovered_by_its_name( controller: ESPhomeController, node: FakeImprovNode, radio: FakeBLESource, output: RecordingControllerOutput ): await node.advertise(radio) (discovery,) = output.received_discoveries assert discovery.id == controller.device_uuid(f"improv:{node.name}", strip="") assert (discovery.transport, discovery.device_name) == ("ble", node.name) assert discovery.expected_credentials_options == [CredentialsType.none], "the Hub gives it its own Wi-Fi" async def test_the_discovery_id_follows_the_name_not_the_ble_address( controller: ESPhomeController, node: FakeImprovNode, radio: FakeBLESource ): await node.advertise(radio) first = set(controller.discoveries) await controller.ble_did_remove_device(router_of(controller), node.info()) node.address = "AA:BB:CC:DD:EE:02" # a random (resolvable private) address changes await node.advertise(radio) assert set(controller.discoveries) == first async def test_the_name_is_remembered_for_the_adverts_that_do_not_carry_it( controller: ESPhomeController, node: FakeImprovNode, radio: FakeBLESource, output: RecordingControllerOutput ): await node.advertise(radio, named=False) assert controller.discoveries == {}, "without its name the node has no stable identity yet" await node.advertise(radio) node.state = State.AUTHORIZATION_REQUIRED await node.advertise(radio, named=False) assert len(output.received_discoveries) == 1 assert list(controller.discoveries) == [output.received_discoveries[0].id] @pytest.mark.parametrize("state", [State.PROVISIONING, State.PROVISIONED]) async def test_a_node_that_already_has_wifi_is_not_offered( controller: ESPhomeController, node: FakeImprovNode, radio: FakeBLESource, state: State ): node.state = state await node.advertise(radio) assert controller.discoveries == {} async def test_a_node_that_stops_advertising_is_lost( controller: ESPhomeController, node: FakeImprovNode, radio: FakeBLESource, output: RecordingControllerOutput ): await node.advertise(radio) await controller.ble_did_remove_device(router_of(controller), node.info(named=False)) assert controller.discoveries == {} assert output.lost_discoveries == [output.received_discoveries[0].id] async def test_ble_discovery_stops_with_the_controller( controller: ESPhomeController, node: FakeImprovNode, radio: FakeBLESource ): await controller.stop() await node.advertise(radio) assert controller.discoveries == {} async def test_a_router_handed_over_once_it_runs_is_listened_to_without_a_restart( platform: Platform, peripherals: Peripherals, router: BLEService, node: FakeImprovNode, radio: FakeBLESource ): controller = ESPhomeController(platform) controller.peripherals = Peripherals({"mdns": peripherals.endpoint("mdns")}) await controller.start() try: controller.peripherals = peripherals assert await controller.needed_peripheral_did_change(PeripheralChange("ble", None, router.endpoint)) await node.advertise(radio) assert len(controller.discoveries) == 1 finally: await controller.stop() async def test_a_lost_router_is_let_go_without_a_restart( controller: ESPhomeController, router: BLEService, node: FakeImprovNode, radio: FakeBLESource ): controller.peripherals = Peripherals({"mdns": controller.peripherals.endpoint("mdns")}) assert await controller.needed_peripheral_did_change(PeripheralChange("ble", router.endpoint, None)) await node.advertise(radio) assert controller.discoveries == {} async def test_the_nodes_heard_through_a_lost_router_are_lost_with_it( controller: ESPhomeController, router: BLEService, node: FakeImprovNode, radio: FakeBLESource, output: RecordingControllerOutput, ): await node.advertise(radio) controller.peripherals = Peripherals({"mdns": controller.peripherals.endpoint("mdns")}) assert await controller.needed_peripheral_did_change(PeripheralChange("ble", router.endpoint, None)) assert controller.discoveries == {}, "nothing can set them up without a router" assert output.lost_discoveries == [output.received_discoveries[0].id] # Pairing: Wi-Fi over BLE, then the node over the network async def test_pairing_gives_the_node_the_hubs_wifi_then_pairs_it_with_a_key_of_its_own( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, mdns: FakeMDNS, keyless_device: VirtualDevice, output: RecordingControllerOutput, ): joins_as_keyless_device(node, mdns) device_id = await hub_pairs(controller, ble_discovery, credentials=None) assert node.received == [HOME] assert device_id is not None assert device_id == controller.device_uuid(bytes.fromhex(KEYLESS.mac)), "the device takes the node's own identity" async with controller.platform.device_repository(controller) as repo: device = await repo.get(physical_id=device_id, as_=ESPhomeDevice) assert await repo.get(physical_id=ble_discovery.id) is None, "the Hub's device moved to the node's identity" assert device is not None assert device.name == "Kitchen relay", "what the user chose is kept" assert device.integration_data.encryption_key and device.parameters assert (device.available, device.last_error) == (True, None) assert output.connected_devices == [device_id] assert controller.discoveries == {} assert device_id in output.lost_discoveries, "the node's mDNS discovery was paired through its BLE one" async def test_a_paired_node_set_up_again_fails_fast_as_already_paired( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, radio: FakeBLESource, mdns: FakeMDNS, keyless_device: VirtualDevice, output: RecordingControllerOutput, ): """Its Wi-Fi was reset: it waits for Wi-Fi again, joins, and turns out to be a device the Hub has.""" joins_as_keyless_device(node, mdns) await hub_pairs(controller, ble_discovery, credentials=None) await node.advertise(radio) # provisioned node.state = State.AUTHORIZED # its Wi-Fi reset: it left the network, and waits for Wi-Fi again await mdns.goodbye(Advert(name=KEYLESS.name)) await node.advertise(radio) (again,) = controller.discoveries.values() user_picks(again, name="Another relay") with pytest.raises(DeviceIdTakenError) as taken: async with asyncio.timeout(controller_module.NODE_APPEAR_TIMEOUT / 2): await hub_pairs(controller, again, credentials=None) assert (taken.value.name, taken.value.is_paired) == ("Kitchen relay", True) assert "Kitchen relay" in await last_error(output, again) await assert_not_paired(controller.platform, again.id) async def test_a_node_waiting_for_its_button_tells_the_user_then_carries_on( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, output: RecordingControllerOutput, ): node.state = State.AUTHORIZATION_REQUIRED pairing = asyncio.create_task(hub_pairs(controller, ble_discovery, credentials=None)) await wait_until( lambda: "button" in (controller.discoveries[ble_discovery.id].last_error or ""), 5, "the instruction" ) await node.press_button() with pytest.raises(TimeoutError): # the node is given Wi-Fi, but never shows up in this test await pairing assert node.received == [HOME] async def unheard_once_given_wifi(router: BLEService, node: FakeImprovNode): """Given Wi-Fi, the node stops advertising Improv: the router says it is gone while it is awaited on the network.""" router._removal_grace_sec = 0.2 await wait_until(lambda: node.received, message="the node to be given Wi-Fi") await asyncio.sleep(0.3) # the lease ended, nothing heard since await router.perform_scan() # the eviction loop's check assert router.devices() == [] async def test_a_node_being_set_up_stays_offered_though_no_radio_hears_it( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, router: BLEService, output: RecordingControllerOutput, ): pairing = asyncio.create_task(hub_pairs(controller, ble_discovery, credentials=None)) await unheard_once_given_wifi(router, node) assert ble_discovery.id in controller.discoveries and output.lost_discoveries == [] with pytest.raises(TimeoutError): # given Wi-Fi, but it never shows up in this test await pairing async def test_a_failed_setup_loses_a_node_no_radio_hears_any_more( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, router: BLEService, output: RecordingControllerOutput, ): """Its removal came while it was set up: none comes again.""" pairing = asyncio.create_task(hub_pairs(controller, ble_discovery, credentials=None)) await unheard_once_given_wifi(router, node) with pytest.raises(TimeoutError): await pairing assert ble_discovery.id not in controller.discoveries and output.lost_discoveries == [ble_discovery.id] async def test_a_button_never_pressed_fails_with_the_instruction( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, output: RecordingControllerOutput ): node.state = State.AUTHORIZATION_REQUIRED with pytest.raises(improv.SetupError): await hub_pairs(controller, ble_discovery, credentials=None) assert node.received == [] assert "press the button" in (await last_error(output, ble_discovery)).lower() await assert_not_paired(controller.platform, ble_discovery.id) assert leaked_tasks() == [] @pytest.mark.parametrize( ("error", "told"), [ (Error.UNABLE_TO_CONNECT, "could not join the wi-fi network home"), (Error.NOT_AUTHORIZED, "press the button"), (Error.UNKNOWN_ERROR, "could not be set up"), ], ) async def test_an_improv_error_fails_pairing_with_a_clear_reason( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, output: RecordingControllerOutput, error: Error, told: str, ): node.fails_with = error with pytest.raises(improv.SetupError): await hub_pairs(controller, ble_discovery, credentials=None) assert told in (await last_error(output, ble_discovery)).lower() await assert_not_paired(controller.platform, ble_discovery.id) assert ble_discovery.id in controller.discoveries, "the user can try again" async def test_a_wrong_wifi_password_is_reported_and_never_logged( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, output: RecordingControllerOutput, caplog: pytest.LogCaptureFixture, ): caplog.set_level(logging.DEBUG) node.password = "another password" with pytest.raises(improv.SetupError): await hub_pairs(controller, ble_discovery, credentials=None) assert "wi-fi network home" in (await last_error(output, ble_discovery)).lower() assert HOME.password not in caplog.text assert HOME.password.encode().hex() not in caplog.text async def test_a_node_out_of_ble_range_fails_with_a_clear_reason( controller: ESPhomeController, ble_discovery: Discovery, radio: FakeBLESource, output: RecordingControllerOutput ): radio.connection = None with pytest.raises(improv.SetupError): await hub_pairs(controller, ble_discovery, credentials=None) assert "bluetooth" in (await last_error(output, ble_discovery)).lower() async def test_bluetooth_held_by_another_integration_fails_with_a_clear_reason( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, output: RecordingControllerOutput ): async with router_of(controller).exclusive(node.address, owner="matter"): with pytest.raises(improv.SetupError): await hub_pairs(controller, ble_discovery, credentials=None) assert node.received == [] assert "busy" in (await last_error(output, ble_discovery)).lower() async def test_a_node_heard_best_through_another_esphome_node_is_set_up_through_it( controller: ESPhomeController, node: FakeImprovNode, radio: FakeBLESource, mdns: FakeMDNS, keyless_device: VirtualDevice, ): proxy = FakeBLESource("esphome:a0b1c2d3e4f5", connection=node) router = router_of(controller) await router.add_source(proxy) radio.connection = None # the Hub's adapter barely hears it: only the ESPHome node can connect await node.advertise(radio, rssi=-95) await node.advertise(proxy, rssi=-50) (discovery,) = controller.discoveries.values() user_picks(discovery) joins_as_keyless_device(node, mdns) assert await hub_pairs(controller, discovery, credentials=None) == controller.device_uuid( bytes.fromhex(KEYLESS.mac) ) assert node.received == [HOME] assert (proxy.connected, radio.connected) == ([node.address], []) async def test_a_node_that_never_shows_up_on_the_network_times_out_with_a_clear_reason( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, output: RecordingControllerOutput ): with pytest.raises(TimeoutError): await hub_pairs(controller, ble_discovery, credentials=None) assert node.received == [HOME] assert "did not show up on the network" in await last_error(output, ble_discovery) await assert_not_paired(controller.platform, ble_discovery.id) assert leaked_tasks() == [] async def test_a_hub_without_wifi_cannot_set_up_the_node( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, radio: FakeBLESource, ): """A Hub on Ethernet: told apart from any other failure, before the node is touched, so the app can ask for the Wi-Fi the node should join (the Hub saves it for the next attempt). The Hub returns the error to the app's pairing request, so the discovery's last_error is left as it was.""" controller.platform = replace(controller.platform, wifi=None) radio.connection = None # any BLE step would fail with another error with pytest.raises(MissingCredentialsError) as raised: await hub_pairs(controller, ble_discovery, credentials=None) assert raised.value.type == MissingCredentialsError.WIFI assert node.received == [] assert controller.discoveries[ble_discovery.id].last_error is None await assert_not_paired(controller.platform, ble_discovery.id) async def test_the_reason_stays_on_the_discovery_while_the_node_keeps_advertising( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, radio: FakeBLESource ): node.fails_with = Error.UNKNOWN_ERROR with pytest.raises(improv.SetupError): await hub_pairs(controller, ble_discovery, credentials=None) await node.advertise(radio, named=False) # a changed advert: the SDK passes it on assert controller.discoveries[ble_discovery.id].last_error # A stop meeting a setup: nothing can hear the node any more, and a run started meanwhile didn't begin it async def test_a_setup_waiting_for_the_node_on_the_network_ends_with_a_stop( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode ): joined = asyncio.Event() async def appear(): joined.set() # on Wi-Fi, not announced yet node.on_joined = appear pairing = asyncio.create_task(hub_pairs(controller, ble_discovery, credentials=None)) await asyncio.wait_for(joined.wait(), 5) await controller.stop() with pytest.raises(ConnectionError, match="stopped"): await asyncio.wait_for(pairing, 0.5) # not after NODE_APPEAR_TIMEOUT await assert_not_paired(controller.platform, ble_discovery.id) assert controller._joining == {} and leaked_tasks() == [] async def test_a_setup_waiting_for_the_button_ends_with_a_stop( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, router: BLEService ): node.state = State.AUTHORIZATION_REQUIRED pairing = asyncio.create_task(hub_pairs(controller, ble_discovery, credentials=None)) await wait_until( lambda: "button" in (controller.discoveries[ble_discovery.id].last_error or ""), 5, "the instruction" ) await controller.stop() with pytest.raises(ConnectionError, match="stopped"): await asyncio.wait_for(pairing, 0.5) # not after AUTHORIZATION_TIMEOUT assert router._leased == {}, "the node's radio is free again" assert node.received == [] and leaked_tasks() == [] async def test_a_setup_whose_request_went_away_lets_go_of_the_node( controller: ESPhomeController, ble_discovery: Discovery, node: FakeImprovNode, router: BLEService ): node.state = State.AUTHORIZATION_REQUIRED pairing = asyncio.create_task(hub_pairs(controller, ble_discovery, credentials=None)) await wait_until( lambda: "button" in (controller.discoveries[ble_discovery.id].last_error or ""), 5, "the instruction" ) pairing.cancel() with pytest.raises(asyncio.CancelledError): await pairing assert router._leased == {} and controller._joining == {} assert leaked_tasks() == [] @pytest.mark.parametrize( ("ble_name", "node_name", "same"), [ ("kitchen-relay", "kitchen-relay", True), ("kitchen-relay", "kitchen-relay-2", False), ("a-very-long-node-nam", "a-very-long-node-name", True), # cut to 20 characters ("a-very-long-n-a1b2c3", "a-very-long-node-name-a1b2c3", True), # cut, keeping the MAC suffix ("a-very-long-node-nam", "a-very-long-node-name-a1b2c3", True), # cut without keeping the suffix ("a-very-long-n-ffffff", "a-very-long-node-name-a1b2c3", False), ], ) def test_a_node_is_recognised_on_the_network_by_the_name_it_advertised(ble_name: str, node_name: str, same: bool): assert improv.is_node(ble_name, node_name) == same ================================================================================ # FILE: tests/test_key_provisioning.py ================================================================================ """Keyless nodes (`api: encryption:` without a key) are given a key of the integration's own at pairing. The key is generated, kept, then set over a Noise session with the well-known all-zeros PSK; from then on the node requires it. The user never types (or sees) a key. """ import asyncio import base64 import logging from collections.abc import AsyncIterator, Callable, Coroutine from dataclasses import dataclass, field from pathlib import Path from typing import Any from unittest.mock import patch from uuid import UUID import pytest import pytest_asyncio from aioesphomeapi import ( ZERO_NOISE_PSK, APIClient, APIConnectionError, ButtonInfo, EntityInfo, InvalidEncryptionKeyAPIError, ) from majordom_integration_sdk import DeviceUnreachableError, Platform from majordom_integration_sdk.schemas import CredentialsType, ProvidedCredentials from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import ( assert_no_side_storage, assert_not_paired, draft_of, hub_pairs, leaked_tasks, param, user_picks, wait_for_value, wait_until, ) from tests.virtual.mdns import Advert, FakeMDNS from tests.virtual.runner import KEYLESS, VirtualDevice pytestmark = pytest.mark.timeout(60) NEW_KEY = base64.b64encode(bytes(range(32))).decode() # set in the YAML of a reflashed node FACTORY_RESET_KEY = 77 button: Any = ButtonInfo # its dataclass constructor is not typed FACTORY_RESET: EntityInfo = button(object_id="factory_reset", key=FACTORY_RESET_KEY, name="Factory Reset") KEYLESS_ADVERT = Advert(name=KEYLESS.name, mac=KEYLESS.mac, port=KEYLESS.port, keyless=True) @pytest.fixture def store() -> dict[UUID, dict[str, Any]]: """The Hub's device records: a test deletes one as the Hub does.""" return {} @pytest.fixture def platform(store: dict[UUID, dict[str, Any]], tmp_path: Path) -> Platform: return build_test_platform(tmp_path, store=store) @pytest_asyncio.fixture async def keyless_device() -> AsyncIterator[VirtualDevice]: virtual = VirtualDevice(KEYLESS) await virtual.start() yield virtual await virtual.stop() async def discover(controller: ESPhomeController, mdns: FakeMDNS, advert: Advert) -> Discovery: await mdns.announce(advert) (found,) = controller.discoveries.values() return found @pytest_asyncio.fixture async def keyless_discovery(controller: ESPhomeController, mdns: FakeMDNS, keyless_device: VirtualDevice) -> Discovery: found = await discover(controller, mdns, KEYLESS_ADVERT) user_picks(found) return found async def stored(controller: ESPhomeController, device_id: Any) -> ESPhomeDevice: async with controller.platform.device_repository(controller) as repo: device = await repo.get(physical_id=device_id, as_=ESPhomeDevice) assert device is not None return device def assert_is_a_key(key: str | None): assert key is not None and key != ZERO_NOISE_PSK assert len(base64.b64decode(key, validate=True)) == 32 async def connects(device: VirtualDevice, psk: str | None) -> bool: client = APIClient(device.address, device.port, "", noise_psk=psk) try: async with asyncio.timeout(5): await client.connect(login=True) except (APIConnectionError, TimeoutError): return False finally: await client.disconnect() return True # Against the compiled keyless node async def test_keyless_node_needs_no_credentials(keyless_discovery: Discovery): assert keyless_discovery.expected_credentials_options == [CredentialsType.none] async def test_pairing_gives_the_node_a_key_it_requires_from_then_on( controller: ESPhomeController, keyless_discovery: Discovery, keyless_device: VirtualDevice, output: RecordingControllerOutput, ): assert await connects(keyless_device, None), "a keyless node accepts plaintext until it has a key" await hub_pairs(controller, keyless_discovery, credentials=None) device = await stored(controller, keyless_discovery.id) key = device.integration_data.encryption_key assert_is_a_key(key) assert (device.available, device.last_error) == (True, None) await wait_for_value(output, param(device, "Temperature"), lambda v: v == 21.5) assert not await connects(keyless_device, None), "plaintext must be refused once the node has its key" assert not await connects(keyless_device, ZERO_NOISE_PSK), "the zero PSK must be refused once the node has its key" assert await connects(keyless_device, key) async def test_the_node_keeps_its_key_across_its_restart_and_the_hubs( controller: ESPhomeController, keyless_discovery: Discovery, keyless_device: VirtualDevice, output: RecordingControllerOutput, ): await hub_pairs(controller, keyless_discovery, credentials=None) await keyless_device.restart() await wait_until(lambda: output.connected_devices.count(keyless_discovery.id) == 2, 15, "the node to reconnect") await controller.stop() output.connected_devices.clear() restarted = ESPhomeController(controller.platform) restarted.peripherals = controller.peripherals restarted.output = controller.output await restarted.start() try: await wait_until(lambda: keyless_discovery.id in output.connected_devices, 15, "the Hub to reconnect") finally: await restarted.stop() async def test_the_generated_key_is_never_logged( controller: ESPhomeController, keyless_discovery: Discovery, caplog: pytest.LogCaptureFixture ): caplog.set_level(logging.DEBUG) await hub_pairs(controller, keyless_discovery, credentials=None) key = (await stored(controller, keyless_discovery.id)).integration_data.encryption_key assert key and key not in caplog.text async def test_a_node_without_encryption_still_pairs_in_plaintext_with_a_warning( controller: ESPhomeController, discovery: Discovery, caplog: pytest.LogCaptureFixture ): caplog.set_level(logging.WARNING) await hub_pairs(controller, discovery, credentials=None) assert (await stored(controller, discovery.id)).integration_data.encryption_key is None warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] assert any("api: encryption:" in w for w in warnings), "the node's owner should be told how to encrypt it" # Failure paths, against a scripted node behind the library's client @dataclass class FakeNode: """Just enough of a keyless node's native API to be given a key, refuse it, or be unreachable afterwards.""" accepts_key: bool = True reachable_with_key: bool = True key: str | None = None set_key_sessions: list[str | None] = field(default_factory=list) # the PSK of every session a key was sent over failed_disconnect_requests: int = 0 # sent over a session the node already dropped: aioesphomeapi logs an ERROR fails_listing: int = 0 # entity listings that fail before one succeeds resets: int = 0 def client(self, address: str, port: int, password: str | None, noise_psk: str | None = None) -> "FakeClient": return FakeClient(self, noise_psk) class FakeClient: def __init__(self, node: FakeNode, psk: str | None): self.node, self.psk = node, psk self.on_stop: Callable[[bool], Coroutine[Any, Any, None]] | None = None self.dropped = False async def connect(self, login: bool = False, on_stop: Callable[[bool], Coroutine[Any, Any, None]] | None = None): self.on_stop = on_stop if self.psk != self.node.key and not (self.node.key is None and self.psk == ZERO_NOISE_PSK): raise InvalidEncryptionKeyAPIError("handshake failed") if self.node.key is not None and not self.node.reachable_with_key: raise APIConnectionError("connection refused") async def noise_encryption_set_key(self, key: bytes) -> bool: self.node.set_key_sessions.append(self.psk) if self.node.accepts_key: self.node.key = key.decode() self.dropped = True if self.on_stop is not None: # like a real node: it drops every session once it uses the new key asyncio.get_running_loop().call_later(0.1, asyncio.ensure_future, self.on_stop(False)) return self.node.accepts_key async def list_entities_services(self) -> tuple[list[EntityInfo], list[Any]]: if self.node.fails_listing: self.node.fails_listing -= 1 raise APIConnectionError("listing failed") return [FACTORY_RESET], [] def button_command(self, key: int): assert key == FACTORY_RESET_KEY self.node.key = None self.node.resets += 1 def subscribe_states(self, on_state: Callable[..., None]): pass async def disconnect(self): if self.dropped: self.node.failed_disconnect_requests += 1 def force_disconnect(self): pass @pytest.fixture def node() -> Any: fake = FakeNode() with patch("majordom_esphome.connection.APIClient", fake.client): yield fake async def test_older_firmware_is_given_its_key_in_plaintext_newer_over_the_zero_psk( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode ): newer = await discover(controller, mdns, Advert(keyless=True)) user_picks(newer) await hub_pairs(controller, newer, credentials=None) await controller.unpair(await stored(controller, newer.id)) node.key = None older = await discover(controller, mdns, Advert(keyless=True, zero_psk=False, addresses=["127.0.0.2"])) await hub_pairs(controller, older, credentials=None) assert node.set_key_sessions == [ZERO_NOISE_PSK, None] async def test_the_session_the_node_drops_after_taking_its_key_is_closed_without_a_disconnect_request( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode ): found = await discover(controller, mdns, Advert(keyless=True)) user_picks(found) await hub_pairs(controller, found, credentials=None) assert node.key is not None assert node.failed_disconnect_requests == 0 async def test_a_refused_key_fails_pairing_cleanly( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode, output: RecordingControllerOutput ): node.accepts_key = False found = await discover(controller, mdns, Advert(keyless=True)) user_picks(found) with pytest.raises(ConnectionError): await hub_pairs(controller, found, credentials=None) assert node.key is None await assert_not_paired(controller.platform, found.id) assert output.connected_devices == [] assert "key" in (output.updated_discoveries[-1].last_error or "").lower(), "the user must be told why" assert found.id in controller.discoveries assert leaked_tasks() == [] async def test_a_pairing_failing_after_the_key_is_set_is_rolled_back_by_a_factory_reset( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode ): """The key lives only in the draft the Hub drops: the node must pair again keyless.""" node.fails_listing = 2 # at the hostname, then at the IP found = await discover(controller, mdns, Advert(keyless=True)) user_picks(found) with pytest.raises(ConnectionError): await hub_pairs(controller, found, credentials=None) assert (node.key, node.resets) == (None, 1) await assert_not_paired(controller.platform, found.id) reset = await discover(controller, mdns, Advert(keyless=True, addresses=["127.0.0.2"])) # announced anew await hub_pairs(controller, reset, credentials=None) assert node.set_key_sessions == [ZERO_NOISE_PSK, ZERO_NOISE_PSK] async def test_rolling_back_a_keyed_node_it_cant_reach_reports_it_unreachable( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode ): node.fails_listing, node.reachable_with_key = 2, False found = await discover(controller, mdns, Advert(keyless=True)) user_picks(found) draft = draft_of(found) with pytest.raises(ConnectionError): await controller.pair_device(found, draft, None) with pytest.raises(DeviceUnreachableError): await controller.unpair(draft) assert (node.resets, controller._given_keys) == (0, set()) async def test_a_pairing_the_hub_fails_to_save_is_rolled_back_by_a_factory_reset( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode ): found = await discover(controller, mdns, Advert(keyless=True)) user_picks(found) draft = await controller.pair_device(found, draft_of(found), None) assert node.key is not None await controller.unpair(draft) assert (node.key, node.resets) == (None, 1) assert controller._just_paired == {} async def test_a_keyed_node_the_hub_never_saves_is_factory_reset_when_let_go( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode, monkeypatch: pytest.MonkeyPatch ): monkeypatch.setattr("majordom_esphome.controller.UNSAVED_PAIRING_TIMEOUT", 0.01) found = await discover(controller, mdns, Advert(keyless=True)) await controller.pair_device(found, draft_of(found), None) await wait_until(lambda: controller._just_paired == {}, 5, "the node to be let go") assert (node.key, node.resets) == (None, 1) async def test_a_paired_node_keeps_its_key_in_its_record_alone( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode ): found = await discover(controller, mdns, Advert(keyless=True)) user_picks(found) await hub_pairs(controller, found, credentials=None) assert (await stored(controller, found.id)).integration_data.encryption_key == node.key assert node.resets == 0 assert_no_side_storage(controller.platform) async def test_unpairing_a_saved_node_factory_resets_it(controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode): found = await discover(controller, mdns, Advert(keyless=True)) user_picks(found) await hub_pairs(controller, found, credentials=None) await controller.unpair(await stored(controller, found.id)) assert (node.key, node.resets) == (None, 1) async def test_a_node_reflashed_with_a_key_of_its_own_after_the_hub_kept_one_can_be_paired_with_the_new_key( controller: ESPhomeController, mdns: FakeMDNS, node: FakeNode, output: RecordingControllerOutput ): """Paired with the Hub's key, unpaired (the Hub keeps the device record, and so the key), then reflashed with a key in its YAML: the kept key is refused, so the user must be able to enter the new one.""" found = await discover(controller, mdns, Advert(keyless=True)) user_picks(found) await hub_pairs(controller, found, credentials=None) kept = (await stored(controller, found.id)).integration_data.encryption_key await controller.unpair(await stored(controller, found.id)) node.key = NEW_KEY again = await discover(controller, mdns, Advert(encrypted=True)) assert again.expected_credentials_options == [CredentialsType.none, CredentialsType.secret] with pytest.raises(ConnectionError): # the kept key is the wrong one now await hub_pairs(controller, again, credentials=None) assert "key" in (output.updated_discoveries[-1].last_error or "").lower() await hub_pairs( controller, controller.discoveries[again.id], ProvidedCredentials(type=CredentialsType.secret, value=NEW_KEY) ) device = await stored(controller, found.id) assert device.integration_data.encryption_key == NEW_KEY != kept assert (device.available, device.last_error) == (True, None) assert node.set_key_sessions == [ZERO_NOISE_PSK], "a node with a key of its own is not given ours" ================================================================================ # FILE: tests/test_lifecycle.py ================================================================================ """Controller lifecycle with a virtual ESPHome device: restarts, outages, shutdown.""" import asyncio import pytest from aioesphomeapi import APIClient from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import leaked_tasks, param, wait_for_value, wait_until from tests.virtual.runner import VirtualDevice async def stored_device(controller: ESPhomeController, device_id) -> ESPhomeDevice: async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=device_id, as_=ESPhomeDevice) assert stored is not None return stored async def flip_relay(device: VirtualDevice): client = APIClient(device.address, device.port, "") await client.connect(login=True) try: entities, _ = await client.list_entities_services() client.switch_command(next(e.key for e in entities if e.name == "Relay"), True) await asyncio.sleep(0.2) finally: await client.disconnect() @pytest.mark.timeout(60) async def test_paired_devices_reconnect_when_the_hub_restarts( controller: ESPhomeController, paired: ESPhomeDevice, output: RecordingControllerOutput ): await controller.stop() output.connected_devices.clear() output.events.clear() restarted = ESPhomeController(controller.platform) restarted.peripherals = controller.peripherals restarted.output = controller.output await restarted.start() try: await wait_until(lambda: paired.physical_id in output.connected_devices, 15, "the paired device to reconnect") await wait_for_value(output, param(paired, "Temperature")) assert (await stored_device(restarted, paired.physical_id)).available finally: await restarted.stop() @pytest.mark.timeout(90) async def test_outage_and_recovery_are_reported( controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice, output: RecordingControllerOutput ): await wait_for_value(output, param(paired, "Temperature")) output.connected_devices.clear() await device.stop() await wait_until(lambda: paired.physical_id in output.lost_devices, 15, "the outage to be reported") assert not (await stored_device(controller, paired.physical_id)).available await device.start() await wait_until(lambda: paired.physical_id in output.connected_devices, 40, "the recovery to be reported") recovered = await stored_device(controller, paired.physical_id) assert recovered.available assert recovered.last_error is None output.events.clear() await wait_for_value(output, param(paired, "Temperature")) @pytest.mark.timeout(90) async def test_startup_with_an_offline_device_does_not_block_and_recovers( controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice, output: RecordingControllerOutput, ): await controller.stop() await device.stop() output.connected_devices.clear() restarted = ESPhomeController(controller.platform) restarted.peripherals = controller.peripherals restarted.output = controller.output async with asyncio.timeout(5): await restarted.start() # a dead device must not hold the Hub's startup try: await wait_until(lambda: paired.physical_id not in output.connected_devices, 1) await _wait_unavailable(restarted, paired) assert (await stored_device(restarted, paired.physical_id)).last_error await device.start() await wait_until( lambda: paired.physical_id in output.connected_devices, 40, "the device to connect once it is up" ) assert (await stored_device(restarted, paired.physical_id)).last_error is None finally: await restarted.stop() async def _wait_unavailable(controller: ESPhomeController, paired: ESPhomeDevice): deadline = asyncio.get_running_loop().time() + 20 while asyncio.get_running_loop().time() < deadline: stored = await stored_device(controller, paired.physical_id) if not stored.available: return await asyncio.sleep(0.2) raise TimeoutError("device never reported unavailable") async def test_stop_closes_everything( controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice, output: RecordingControllerOutput ): await wait_for_value(output, param(paired, "Temperature")) await controller.stop() output.events.clear() await flip_relay(device) await asyncio.sleep(1.5) assert output.events == [] assert leaked_tasks() == [] async def test_unpair_stops_the_flow_of_events( controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice, output: RecordingControllerOutput ): await wait_for_value(output, param(paired, "Temperature")) await controller.unpair(paired) output.events.clear() await flip_relay(device) await asyncio.sleep(1.5) assert output.events == [] assert leaked_tasks() == [] async def test_identify_leaves_a_working_device( controller: ESPhomeController, paired: ESPhomeDevice, device: VirtualDevice, output: RecordingControllerOutput ): await controller.identify(paired) # ESPHome has no identify action: it must be a harmless no-op await flip_relay(device) await wait_for_value(output, param(paired, "Relay"), lambda v: v is True) ================================================================================ # FILE: tests/test_pairing.py ================================================================================ """Pairing against a virtual ESPHome device: what gets stored, and how pairing fails.""" import asyncio import pytest from majordom_integration_sdk.schemas import CredentialsType, ProvidedCredentials from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.schemas.parameter import ( ParameterDataType as T, ) from majordom_integration_sdk.schemas.parameter import ( ParameterRole as R, ) from majordom_integration_sdk.schemas.parameter import ( ParameterUnit, ParameterVisibility, ) from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import ROOM, assert_not_paired, changes, draft_of, hub_pairs, leaked_tasks, param, wait_for_value from tests.virtual.mdns import Advert, FakeMDNS from tests.virtual.runner import VirtualDevice # (entity name, sub-field) -> (data type, role): the parameters the Hub must see for the virtual device EXPECTED_PARAMETERS: dict[tuple[str, str], tuple[T, R]] = { ("Relay", "state"): (T.bool, R.control), ("Virtual Fan", "state"): (T.bool, R.control), ("Virtual Light", "state"): (T.bool, R.control), ("Virtual Light", "brightness"): (T.decimal, R.control), # brightness-only light: no colour channels ("RGB Light", "state"): (T.bool, R.control), ("RGB Light", "brightness"): (T.decimal, R.control), ("RGB Light", "color_hue"): (T.decimal, R.control), # colour as hue and saturation, like Matter and Zigbee ("RGB Light", "color_saturation"): (T.decimal, R.control), ("Virtual Light", "transition_length"): (T.decimal, R.control), # a setting kept by the integration ("Virtual Light", "flash"): (T.struct, R.control), # a command with its length as argument ("RGB Light", "transition_length"): (T.decimal, R.control), ("RGB Light", "flash"): (T.struct, R.control), ("Blinds", "position"): (T.decimal, R.control), ("Blinds", "operation"): (T.enum, R.sensor), ("Blinds", "stop"): (T.none, R.control), ("Virtual Fan", "speed_level"): (T.integer, R.control), ("Virtual Fan", "oscillating"): (T.bool, R.control), ("Virtual Fan", "direction"): (T.enum, R.control), ("HVAC", "action"): (T.enum, R.sensor), ("HVAC", "custom_preset"): (T.enum, R.control), ("HVAC", "mode"): (T.enum, R.control), ("HVAC", "current_temperature"): (T.decimal, R.sensor), ("HVAC", "target_temperature_low"): (T.decimal, R.control), # the thermostat is two-point ("HVAC", "target_temperature_high"): (T.decimal, R.control), ("Target Temp", "state"): (T.decimal, R.control), ("Mode", "state"): (T.enum, R.control), ("Reboot", "state"): (T.none, R.control), ("Temperature", "state"): (T.decimal, R.sensor), ("Humidity", "state"): (T.decimal, R.sensor), ("Dust", "state"): (T.decimal, R.sensor), ("Distance", "state"): (T.decimal, R.sensor), ("Motion", "state"): (T.bool, R.sensor), ("Status", "state"): (T.string, R.sensor), } async def test_pairing_exposes_exactly_the_capabilities_of_each_entity(paired: ESPhomeDevice): actual = { (p.integration_data.entity_name, p.integration_data.sub_field): (p.data_type, p.role) for p in paired.parameters } assert actual == EXPECTED_PARAMETERS async def test_parameter_metadata_comes_from_the_device(paired: ESPhomeDevice): target = param(paired, "Target Temp") assert (target.min_value, target.max_value, target.min_step) == (10, 30, 0.5) assert param(paired, "Temperature").unit == ParameterUnit.celsius assert param(paired, "Humidity").unit == ParameterUnit.percentage assert param(paired, "Dust").unit == ParameterUnit.ugm3 assert param(paired, "Distance").unit == ParameterUnit.meters # enums are integers with string labels (`valid_values`), labelled by the enum names like the other integrations assert param(paired, "Mode").valid_values == {0: "AUTO", 1: "MANUAL"} assert param(paired, "Blinds", "operation").valid_values == {0: "IDLE", 1: "IS_OPENING", 2: "IS_CLOSING"} assert param(paired, "HVAC", "mode").valid_values == {0: "OFF", 2: "COOL", 3: "HEAT"} # the modes it supports # levels, positions and colour channels are percentages, as everywhere in MajorDom (ESPHome reports 0-1) for entity, sub_field in [ ("Virtual Light", "brightness"), ("RGB Light", "color_saturation"), ("Blinds", "position"), ]: level = param(paired, entity, sub_field) assert (level.unit, level.min_value, level.max_value) == (ParameterUnit.percentage, 0, 100), entity hue = param(paired, "RGB Light", "color_hue") assert (hue.unit, hue.min_value, hue.max_value) == (ParameterUnit.arcdegree, 0, 360) async def test_the_remaining_fields_are_settings_with_the_limits_the_entity_reports(paired: ESPhomeDevice): speed = param(paired, "Virtual Fan", "speed_level") assert (speed.min_value, speed.max_value) == (0, 3) # speed_count: 3 assert param(paired, "Virtual Fan", "direction").valid_values == {0: "FORWARD", 1: "REVERSE"} assert param(paired, "HVAC", "custom_preset").valid_values == {0: "Default"} # the presets the thermostat has extras = [("Blinds", "stop"), ("Virtual Fan", "oscillating"), ("HVAC", "action"), ("Virtual Fan", "direction")] for entity, sub_field in extras: assert param(paired, entity, sub_field).visibility == ParameterVisibility.setting, (entity, sub_field) assert param(paired, "Relay").visibility == ParameterVisibility.user # the hand-written parameters stay on top assert not [p for p in paired.parameters if p.integration_data.sub_field == "tilt"] # the blinds cannot tilt async def test_identity_is_derived_through_the_sdk_helpers(controller: ESPhomeController, paired: ESPhomeDevice): assert paired.physical_id == controller.device_uuid(bytes.fromhex("983569abf679")) for parameter in paired.parameters: key = ( f"{parameter.integration_data.entity_name.lower().replace(' ', '_')}_{parameter.integration_data.sub_field}" ) assert parameter.id == controller.parameter_uuid(paired.physical_id, key) async def test_device_has_a_one_tap_main_parameter(paired: ESPhomeDevice): main = next((p for p in paired.parameters if p.id == paired.main_parameter), None) assert main is not None, "main_parameter must reference one of the device's parameters" assert main.can_be_main_parameter async def test_pairing_keeps_what_the_hub_already_knows_about_the_device( controller: ESPhomeController, discovery: Discovery ): await hub_pairs(controller, discovery, credentials=None) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=discovery.id, as_=ESPhomeDevice) assert stored is not None assert (stored.room_id, stored.name) == (ROOM, "Kitchen relay") # the user's choices, saved by the Hub async def test_pairing_fills_the_draft_and_saves_nothing_itself( controller: ESPhomeController, mdns: FakeMDNS, device, output: RecordingControllerOutput ): await mdns.announce(Advert(port=device.port)) (discovery,) = controller.discoveries.values() draft = draft_of(discovery) hub_id = draft.id filled = await controller.pair_device(discovery, draft, None) assert (filled.physical_id, filled.name, filled.available) == (discovery.id, "Kitchen relay", True) assert filled.id == hub_id, "the Hub's id is not touched" assert filled.parameters and filled.integration_data.addresses async with controller.platform.device_repository(controller) as repo: assert await repo.get(physical_id=discovery.id) is None # the Hub saves it await asyncio.sleep(0.1) assert output.connected_devices == [] and changes(output) == [], "nothing is reported before the Hub saved it" async def test_pairing_reports_the_device_and_forgets_the_discovery( controller: ESPhomeController, discovery: Discovery, output: RecordingControllerOutput ): await hub_pairs(controller, discovery, credentials=None) assert output.connected_devices == [discovery.id] assert controller.discoveries == {} async def test_pairing_accepts_explicit_no_credentials(controller: ESPhomeController, discovery: Discovery): await hub_pairs(controller, discovery, ProvidedCredentials(type=CredentialsType.none)) async def test_pairing_rejects_credentials_the_discovery_did_not_ask_for( controller: ESPhomeController, discovery: Discovery ): with pytest.raises(ValueError): await hub_pairs(controller, discovery, ProvidedCredentials(type=CredentialsType.secret, value="a-key")) assert discovery.id in controller.discoveries async def test_device_can_be_paired_again_after_unpairing( controller: ESPhomeController, mdns: FakeMDNS, device: VirtualDevice, paired: ESPhomeDevice ): await controller.unpair(paired) await mdns.announce(Advert(name="test_node", port=device.port, addresses=["127.0.0.1", "::1"])) (discovery,) = controller.discoveries.values() await hub_pairs(controller, discovery, credentials=None) async with controller.platform.device_repository(controller) as repo: again = await repo.get(physical_id=discovery.id, as_=ESPhomeDevice) assert again is not None assert [p.id for p in again.parameters] == [p.id for p in paired.parameters] @pytest.mark.timeout(60) async def test_pairing_an_unreachable_device_fails_fast_and_cleanly( controller: ESPhomeController, discovery: Discovery, device: VirtualDevice, output: RecordingControllerOutput ): await device.stop() async with asyncio.timeout(25): with pytest.raises((ConnectionError, TimeoutError)): await hub_pairs(controller, discovery, credentials=None) await assert_not_paired(controller.platform, discovery.id) assert output.connected_devices == [] assert output.updated_discoveries[-1].last_error, "the user must see why pairing failed" assert discovery.id in controller.discoveries await asyncio.sleep(0.1) assert leaked_tasks() == [] async def test_pairing_is_retryable_after_the_device_comes_back( controller: ESPhomeController, discovery: Discovery, device: VirtualDevice, output: RecordingControllerOutput ): await device.stop() with pytest.raises((ConnectionError, TimeoutError)): await hub_pairs(controller, discovery, credentials=None) await device.start() await hub_pairs(controller, output.updated_discoveries[-1], credentials=None) async with controller.platform.device_repository(controller) as repo: stored = await repo.get(physical_id=discovery.id, as_=ESPhomeDevice) assert stored is not None assert stored.last_error is None await wait_for_value(output, param(stored, "Temperature")) ================================================================================ # FILE: tests/test_state.py ================================================================================ """Device -> Hub: states pushed by a virtual ESPHome device become typed parameter events.""" import pytest from aioesphomeapi import APIClient from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from tests.helpers import assert_values_match_parameters, changes, param, values, wait_for_value, wait_until from tests.virtual.runner import VirtualDevice @pytest.fixture async def settled(paired: ESPhomeDevice, output: RecordingControllerOutput) -> ESPhomeDevice: """Paired device whose initial states have all arrived.""" for entity in ("Temperature", "Humidity", "Dust", "Distance", "Motion", "Status", "Target Temp", "Mode"): await wait_for_value(output, param(paired, entity)) return paired async def test_initial_states_are_reported_with_device_values( settled: ESPhomeDevice, output: RecordingControllerOutput ): expected = {"Temperature": 21.5, "Humidity": 55.0, "Dust": 12.0, "Distance": 1.5, "Motion": True, "Status": "OK"} for entity, value in expected.items(): assert values(output, param(settled, entity).id)[-1] == value, entity assert values(output, param(settled, "Target Temp").id)[-1] == 10.0 assert values(output, param(settled, "Mode").id)[-1] == 0 # "AUTO": enums are reported as their index async def test_every_value_has_the_type_its_parameter_declares( settled: ESPhomeDevice, output: RecordingControllerOutput ): await wait_for_value(output, param(settled, "HVAC", "mode")) await wait_for_value(output, param(settled, "Blinds", "operation")) assert_values_match_parameters(output, settled) async def test_two_point_climate_reports_both_targets(settled: ESPhomeDevice, output: RecordingControllerOutput): low = await wait_for_value(output, param(settled, "HVAC", "target_temperature_low")) high = await wait_for_value(output, param(settled, "HVAC", "target_temperature_high")) assert low < high async def test_changes_made_on_the_device_are_pushed( settled: ESPhomeDevice, output: RecordingControllerOutput, device: VirtualDevice ): relay = param(settled, "Relay") client = APIClient(device.address, device.port, "") await client.connect(login=True) try: entities, _ = await client.list_entities_services() relay_key = next(e.key for e in entities if e.name == "Relay") client.switch_command(relay_key, True) assert await wait_for_value(output, relay, lambda v: v is True) finally: await client.disconnect() async def test_fetch_reports_the_current_value_of_every_readable_parameter( controller: ESPhomeController, settled: ESPhomeDevice, output: RecordingControllerOutput ): output.events.clear() await controller.fetch(settled) reported = {e.parameter_id for e in changes(output)} for entity in ("Temperature", "Humidity", "Dust", "Distance", "Motion", "Status", "Target Temp", "Mode"): assert param(settled, entity).id in reported, entity assert_values_match_parameters(output, settled) async def test_fetch_reports_in_one_batch(controller: ESPhomeController, settled: ESPhomeDevice, output): batches: list[int] = [] original = output.controller_did_receive_events async def spy(controller, events): events = list(events) batches.append(len(events)) await original(controller, events) output.controller_did_receive_events = spy # type: ignore[method-assign] await wait_until(lambda: True) batches.clear() await controller.fetch(settled) assert len(batches) == 1 and batches[0] >= 8 ================================================================================ # FILE: tests/test_thread_provisioning.py ================================================================================ """Unprovisioned Thread nodes over BLE: found by the `thread_provisioning` service, given the Hub's Thread dataset, then paired over the network (Thread, through the border router) like any other node. The node's GATT service is scripted below as the connection a Bluetooth source hands out; the SDK's real Bluetooth router routes its adverts and connections. Once the node "attaches", the compiled keyless virtual node appears over mDNS. """ import asyncio import logging from collections.abc import AsyncIterator, Awaitable, Callable from dataclasses import replace import pytest import pytest_asyncio from majordom_integration_sdk import MissingCredentialsError, Platform from majordom_integration_sdk.capabilities import GattCharacteristic, GattService from majordom_integration_sdk.peripherals import Peripherals from majordom_integration_sdk.runtime.peripherals.providers.ble.router import BLEService from majordom_integration_sdk.schemas import CredentialsType from majordom_integration_sdk.schemas.device import Discovery from majordom_integration_sdk.testing import FakeBLESource, RecordingControllerOutput from majordom_esphome import controller as controller_module from majordom_esphome import improv, thread_provisioning from majordom_esphome.controller import ESPhomeController from majordom_esphome.models import ESPhomeDevice from majordom_esphome.thread_provisioning import ( ERROR_UUID, RESULT_UUID, RPC_UUID, SERVICE_UUID, STATE_UUID, Error, State, ) from tests.helpers import assert_not_paired, hub_pairs, leaked_tasks, user_picks, wait_until from tests.virtual.mdns import Advert, FakeMDNS from tests.virtual.runner import KEYLESS, VirtualDevice pytestmark = pytest.mark.timeout(60) NETWORK_KEY = "00112233445566778899aabbccddeeff" # made up; what a real one must never be: logged DATASET = ( "0e080000000000010000" # active timestamp "000300000f" # channel 15 "0102abcd" # PAN ID "0208dead00beef00cafe" # extended PAN ID "0708fd11ec6ad2330001" # mesh-local prefix f"0510{NETWORK_KEY}" "030a4d616a6f72446f6d31" # network name ) HANDLES = {uuid: 0x21 + i for i, uuid in enumerate((STATE_UUID, ERROR_UUID, RPC_UUID, RESULT_UUID))} class FakeThreadNode: """An unprovisioned ESPHome node's `thread_provisioning` GATT service, as the `BLEConnection` a source hands out.""" def __init__(self, name: str = KEYLESS.name, address: str = "AA:BB:CC:DD:EE:03"): self.name, self.address = name, address self.state = State.AUTHORIZED self.mtu = 247 self.fails_with: Error | None = None self.writes: list[bytes] = [] self.received: list[str] = [] # datasets, hex self.on_attached: Callable[[], Awaitable[None]] | None = None # it shows up on the network self._incoming = b"" self._callbacks: dict[int, Callable[[bytes], None]] = {} async def advertise(self, source: FakeBLESource, named: bool = True, rssi: int = -60): source.advertise(self.address, rssi, self.name if named else None, [SERVICE_UUID]) await asyncio.sleep(0.05) async def press_button(self): self.state = State.AUTHORIZED self._notify(STATE_UUID, self.state) # BLEConnection async def services(self) -> list[GattService]: characteristics = tuple(GattCharacteristic(uuid, handle, ("read",)) for uuid, handle in HANDLES.items()) return [GattService(SERVICE_UUID, 0x20, characteristics)] async def read(self, handle: int) -> bytes: return bytes([self.state if handle == HANDLES[STATE_UUID] else Error.NONE]) async def write(self, handle: int, data: bytes, is_response_needed: bool = True): assert handle == HANDLES[RPC_UUID] and is_response_needed assert len(data) <= self.mtu - 3, "a write must fit in one ATT packet" self.writes.append(data) self._incoming += data if len(self._incoming) < 3 or len(self._incoming) < self._incoming[1] + 3: return # more chunks to come frame, self._incoming = self._incoming, b"" assert frame[0] == thread_provisioning.SET_DATASET and sum(frame[:-1]) & 0xFF == frame[-1] asyncio.get_running_loop().create_task(self._attach(frame[2:-1].hex())) async def start_notify(self, handle: int, callback: Callable[[bytes], None]): self._callbacks[handle] = callback async def stop_notify(self, handle: int): self._callbacks.pop(handle, None) async def disconnect(self): self._callbacks.clear() async def _attach(self, dataset: str): if self.state == State.AWAITING_AUTHORIZATION: self._notify(ERROR_UUID, Error.NOT_AUTHORIZED) return self.received.append(dataset) self._notify(ERROR_UUID, Error.NONE) self._notify(STATE_UUID, State.ATTACHING) if self.fails_with is not None: self._notify(ERROR_UUID, self.fails_with) self._notify(STATE_UUID, State.AUTHORIZED) return self.state = State.ATTACHED self._notify(STATE_UUID, self.state) if callback := self._callbacks.get(HANDLES[RESULT_UUID]): callback(bytes([thread_provisioning.SET_DATASET, 0, thread_provisioning.SET_DATASET])) if self.on_attached is not None: await self.on_attached() def _notify(self, uuid: str, value: int): if callback := self._callbacks.get(HANDLES[uuid]): callback(bytes([value])) @pytest.fixture def node(monkeypatch: pytest.MonkeyPatch) -> FakeThreadNode: monkeypatch.setattr(thread_provisioning, "AUTHORIZATION_TIMEOUT", 1.0) monkeypatch.setattr(thread_provisioning, "LEASE_TIMEOUT", 0.5) monkeypatch.setattr(controller_module, "NODE_APPEAR_TIMEOUT", 1.0) return FakeThreadNode() @pytest.fixture def radio(node: FakeThreadNode) -> FakeBLESource: return FakeBLESource("hci0", connection=node) @pytest.fixture def platform(platform: Platform) -> Platform: return replace(platform, thread_dataset=DATASET) @pytest_asyncio.fixture async def router(radio: FakeBLESource) -> AsyncIterator[BLEService]: ble = BLEService(sources=[radio]) await ble.start() yield ble await ble.stop() @pytest.fixture def peripherals(peripherals: Peripherals, router: BLEService) -> Peripherals: return Peripherals({**peripherals.bound, "ble": router.endpoint}) @pytest_asyncio.fixture async def ble_discovery(controller: ESPhomeController, node: FakeThreadNode, radio: FakeBLESource) -> Discovery: await node.advertise(radio) (found,) = controller.discoveries.values() user_picks(found) return found @pytest_asyncio.fixture async def keyless_device() -> AsyncIterator[VirtualDevice]: virtual = VirtualDevice(KEYLESS) await virtual.start() yield virtual await virtual.stop() def attaches_as_keyless_device(node: FakeThreadNode, mdns: FakeMDNS): async def appear(): await mdns.announce(Advert(name=KEYLESS.name, mac=KEYLESS.mac, port=KEYLESS.port, keyless=True)) node.on_attached = appear async def last_error(output: RecordingControllerOutput, discovery: Discovery) -> str: return next((d.last_error or "" for d in reversed(output.updated_discoveries) if d.id == discovery.id), "") def test_a_command_is_an_improv_style_frame(): assert thread_provisioning.frame(0x01, b"\x0e\x08") == bytes([0x01, 0x02, 0x0E, 0x08, 0x19]) async def test_a_node_waiting_for_a_thread_network_is_discovered_by_its_name( controller: ESPhomeController, node: FakeThreadNode, radio: FakeBLESource, output: RecordingControllerOutput ): await node.advertise(radio) (discovery,) = output.received_discoveries assert (discovery.transport, discovery.device_name) == ("ble", node.name) assert discovery.expected_credentials_options == [CredentialsType.none], "the Hub gives it its own network" async def test_pairing_gives_the_node_the_hubs_thread_network_then_pairs_it_with_a_key_of_its_own( controller: ESPhomeController, ble_discovery: Discovery, node: FakeThreadNode, mdns: FakeMDNS, keyless_device: VirtualDevice, output: RecordingControllerOutput, ): attaches_as_keyless_device(node, mdns) device_id = await hub_pairs(controller, ble_discovery, credentials=None) assert node.received == [DATASET] assert device_id is not None assert device_id == controller.device_uuid(bytes.fromhex(KEYLESS.mac)), "the device takes the node's own identity" async with controller.platform.device_repository(controller) as repo: device = await repo.get(physical_id=device_id, as_=ESPhomeDevice) assert device is not None and device.integration_data.encryption_key and device.parameters assert (device.available, device.last_error) == (True, None) assert output.connected_devices == [device_id] assert controller.discoveries == {} async def test_the_dataset_is_written_in_chunks_that_fit_the_connection( controller: ESPhomeController, ble_discovery: Discovery, node: FakeThreadNode ): node.mtu = 23 # the BLE minimum: 20 bytes per write with pytest.raises(TimeoutError): # attached, but never shows up in this test await hub_pairs(controller, ble_discovery, credentials=None) assert node.received == [DATASET] assert len(node.writes) > 1 async def test_a_hub_without_a_thread_network_asks_for_one_before_touching_the_node( controller: ESPhomeController, ble_discovery: Discovery, node: FakeThreadNode, radio: FakeBLESource, ): controller.platform = replace(controller.platform, thread_dataset=None) with pytest.raises(MissingCredentialsError) as raised: await hub_pairs(controller, ble_discovery, credentials=None) assert raised.value.type == MissingCredentialsError.THREAD assert radio.connected == [] and node.received == [] async def test_a_node_waiting_for_its_button_tells_the_user_then_carries_on( controller: ESPhomeController, ble_discovery: Discovery, node: FakeThreadNode ): node.state = State.AWAITING_AUTHORIZATION pairing = asyncio.create_task(hub_pairs(controller, ble_discovery, credentials=None)) await wait_until( lambda: "button" in (controller.discoveries[ble_discovery.id].last_error or ""), 5, "the instruction" ) await node.press_button() with pytest.raises(TimeoutError): await pairing assert node.received == [DATASET] @pytest.mark.parametrize( ("error", "told"), [ (Error.UNABLE_TO_ATTACH, "could not join the hub's thread network"), (Error.INVALID_DATASET, "refused the hub's thread network"), (Error.NOT_AUTHORIZED, "press the button"), (Error.UNKNOWN, "could not be set up"), ], ) async def test_a_node_error_fails_pairing_with_a_clear_reason( controller: ESPhomeController, ble_discovery: Discovery, node: FakeThreadNode, output: RecordingControllerOutput, error: Error, told: str, ): node.fails_with = error with pytest.raises(improv.SetupError): await hub_pairs(controller, ble_discovery, credentials=None) assert told in (await last_error(output, ble_discovery)).lower() await assert_not_paired(controller.platform, ble_discovery.id) assert ble_discovery.id in controller.discoveries, "the user can try again" assert leaked_tasks() == [] async def test_a_node_that_never_shows_up_on_the_network_times_out_with_a_clear_reason( controller: ESPhomeController, ble_discovery: Discovery, node: FakeThreadNode, output: RecordingControllerOutput ): with pytest.raises(TimeoutError): await hub_pairs(controller, ble_discovery, credentials=None) assert "joined the hub's thread network but did not show up" in (await last_error(output, ble_discovery)).lower() await assert_not_paired(controller.platform, ble_discovery.id) async def test_the_network_key_is_never_logged( controller: ESPhomeController, ble_discovery: Discovery, node: FakeThreadNode, mdns: FakeMDNS, keyless_device: VirtualDevice, caplog: pytest.LogCaptureFixture, ): caplog.set_level(logging.DEBUG) attaches_as_keyless_device(node, mdns) await hub_pairs(controller, ble_discovery, credentials=None) assert NETWORK_KEY not in caplog.text.lower() assert DATASET not in caplog.text.lower() ================================================================================ # FILE: tests/test_unhosted_fields.py ================================================================================ """Fields no virtual node can exercise, tested on library objects built directly (not end to end). The host thermostat has no custom fan modes, so a climate with some cannot be hosted. The mapping of such a field is still checked here: the parameter an entity description produces, the value a state maps to, and the command a value becomes, with the same functions the controller calls. """ from typing import Any from uuid import uuid4 import pytest from aioesphomeapi import ( ClimateInfo, ClimateMode, ClimateState, EntityInfo, LightInfo, LockCommand, LockInfo, UpdateInfo, WaterHeaterInfo, WaterHeaterState, ) from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from majordom_esphome import mapper from majordom_esphome.models import ( ESPhomeParameter, ESPhomeParameterIntegrationData, ESPhomeParameterType, ParameterSpec, ) # the library's dataclasses are not typed for construction Info: Any = ClimateInfo State: Any = ClimateState def thermostat(**kwargs: Any) -> EntityInfo: return Info( object_id="probe", key=77, name="Probe", supported_modes=[ClimateMode.OFF, ClimateMode.HEAT], supports_two_point_target_temperature=False, **kwargs, ) def spec_of(entity: EntityInfo, sub_field: str) -> ParameterSpec | None: component = mapper.component_type_of(entity) assert component is not None return next((s for s in mapper.parameter_specs(entity, component) if s.sub_field == sub_field), None) def parameter_of(entity: EntityInfo, spec: ParameterSpec) -> ESPhomeParameter: return ESPhomeParameter( id=uuid4(), name=spec.sub_field, data_type=spec.data_type, role=spec.role, visibility=spec.visibility or ParameterVisibility.user, valid_values=spec.valid_values, min_value=spec.min_value, max_value=spec.max_value, fields=[parameter_of(entity, child) for child in spec.fields] or None, integration_data=ESPhomeParameterIntegrationData( entity_name=entity.name, object_id=entity.object_id, component_type=mapper.component_type_of(entity) or "", parameter_type=ESPhomeParameterType.STATE, service_key=entity.key, sub_field=spec.sub_field, ), ) def test_custom_fan_modes_become_an_enum_of_the_offered_modes(): spec = spec_of(thermostat(supported_custom_fan_modes=["Breeze", "Gust"]), "custom_fan_mode") assert spec is not None assert (spec.data_type, spec.role) == (ParameterDataType.enum, ParameterRole.control) assert spec.valid_values == {0: "Breeze", 1: "Gust"} assert spec.visibility == ParameterVisibility.setting def test_no_custom_fan_modes_no_parameter(): assert spec_of(thermostat(), "custom_fan_mode") is None def test_a_custom_fan_mode_state_is_reported_as_the_index_of_the_option(): entity = thermostat(supported_custom_fan_modes=["Breeze", "Gust"]) assert mapper.state_values(entity, State(key=77, custom_fan_mode="Gust"))["custom_fan_mode"] == 1 assert "custom_fan_mode" not in mapper.state_values(entity, State(key=77, custom_fan_mode="")) # none set def test_a_custom_fan_mode_command_sends_the_option_name(): entity = thermostat(supported_custom_fan_modes=["Breeze", "Gust"]) spec = spec_of(entity, "custom_fan_mode") assert spec is not None parameter = parameter_of(entity, spec) assert mapper.build_command_args(parameter, 1, {}) == {"key": 77, "custom_fan_mode": "Gust"} with pytest.raises(ValueError): mapper.build_command_args(parameter, 5, {}) def test_a_lock_that_requires_a_code_offers_a_command_with_the_code_and_a_default_code(): lock: Any = LockInfo entity = lock(object_id="door", key=5, name="Door", requires_code=True) spec = spec_of(entity, "command_with_code") default = spec_of(entity, "code") assert spec is not None and default is not None assert spec.data_type == ParameterDataType.struct # a command with arguments: fields of a struct assert [child.sub_field for child in spec.fields] == ["command", "code"] assert (default.data_type, default.visibility, default.local) == ( ParameterDataType.string, ParameterVisibility.setting, True, ) parameter = parameter_of(entity, spec) command, code = parameter.fields or [] typed = mapper.build_command_args(parameter, {str(command.id): 1, str(code.id): "1234"}, {}, {"code": "9999"}) fallback = mapper.build_command_args(parameter, {str(command.id): 1}, {}, {"code": "9999"}) without = mapper.build_command_args(parameter, {str(command.id): 1}, {}) assert typed == {"key": 5, "command": LockCommand.LOCK, "code": "1234"} # a typed code wins assert fallback == {"key": 5, "command": LockCommand.LOCK, "code": "9999"} # else the kept default assert without == {"key": 5, "command": LockCommand.LOCK} # else none: the lock decides plain = spec_of(entity, "command") assert plain is not None assert mapper.build_command_args(parameter_of(entity, plain), 0, {}, {"code": "9999"}) == { "key": 5, "command": LockCommand.UNLOCK, "code": "9999", } assert spec_of(lock(object_id="door", key=5, name="Door", requires_code=False), "command_with_code") is None assert spec_of(lock(object_id="door", key=5, name="Door", requires_code=False), "code") is None def test_water_heater_flags_are_switches_of_the_state_bit_mask(): heater: Any = WaterHeaterInfo state: Any = WaterHeaterState entity = heater(object_id="boiler", key=9, name="Boiler", supported_features=8 | 16) # away, on/off on, away = spec_of(entity, "on"), spec_of(entity, "away") assert on is not None and away is not None assert (on.data_type, on.role) == (ParameterDataType.bool, ParameterRole.control) assert {k: v for k, v in mapper.state_values(entity, state(key=9, state=2)).items() if k in ("on", "away")} == { "on": True, "away": False, } assert mapper.build_command_args(parameter_of(entity, on), False, {}) == {"key": 9, "on": False} assert spec_of(heater(object_id="boiler", key=9, name="Boiler", supported_features=0), "away") is None def test_the_colour_brightness_is_only_offered_where_colour_and_white_mix(): light: Any = LightInfo rgb_only = light(object_id="l", key=1, name="L", supported_color_modes=[35]) # RGB rgbw = light(object_id="l", key=1, name="L", supported_color_modes=[39]) # RGB + WHITE assert spec_of(rgb_only, "color_brightness") is None assert spec_of(rgbw, "color_brightness") is not None def test_firmware_update_parameters_are_hidden(): update: Any = UpdateInfo specs = mapper.parameter_specs(update(object_id="fw", key=3, name="Firmware"), "update") assert specs, "an update entity is still mapped" assert {spec.visibility for spec in specs} == {ParameterVisibility.system} def test_water_heater_temperatures_are_in_celsius(): heater: Any = WaterHeaterInfo entity = heater(object_id="boiler", key=9, name="Boiler", supported_features=1 | 2) # current and target for field in ("current_temperature", "target_temperature"): spec = spec_of(entity, field) assert spec is not None and spec.unit == ParameterUnit.celsius, field def test_a_two_point_water_heater_offers_low_and_high_targets_within_its_limits(): heater: Any = WaterHeaterInfo entity = heater( object_id="boiler", key=9, name="Boiler", supported_features=2 | 32, min_temperature=30.0, max_temperature=70.0 ) # target temperature, two-point assert spec_of(entity, "target_temperature") is None for field in ("target_temperature_low", "target_temperature_high"): spec = spec_of(entity, field) assert spec is not None and (spec.min_value, spec.max_value) == (30.0, 70.0), field ================================================================================ # FILE: tests/virtual/__init__.py ================================================================================ ================================================================================ # FILE: tests/virtual/build.py ================================================================================ """Compile every virtual device sketch: `poetry run python -m tests.virtual.build`.""" from tests.virtual.runner import SKETCHES, build if __name__ == "__main__": for sketch in SKETCHES: build(sketch) ================================================================================ # FILE: tests/virtual/catalogue.py ================================================================================ """The catalogue: one virtual node per entity kind ESPHome's API knows, generated and built from recipes. Modelled on the Matter integration's virtual-device catalogue. The list of kinds comes from the installed `aioesphomeapi`, so a library upgrade that adds a kind is noticed (`test_catalogue.py`) and fails until someone writes a recipe (or explains in `UNHOSTABLE` why the kind cannot run on the host node). A recipe is never guessed: a good one switches on every capability of the entity (position, speed, colour modes, ...), and every field it exposes must be accounted for in `EXPECTED` (mapped, with its type and role) or `UNMAPPED` (not mapped, with the reason), so the more a recipe configures, the more of the mapping is tested. python -m tests.virtual.catalogue # generate, validate and build every node (in parallel) python -m tests.virtual.catalogue generate # only write the yaml files """ import shutil import subprocess import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path from aioesphomeapi import COMPONENT_TYPE_TO_INFO from majordom_integration_sdk.schemas.parameter import ParameterDataType as T from majordom_integration_sdk.schemas.parameter import ParameterRole as R from tests.virtual.runner import Sketch NODES_DIR = Path(__file__).parent / "nodes" # generated, git-ignored API_PORT = 6060 # one node runs at a time HEADER = """\ esphome: name: {name} host: mac_address: "{mac}" api: port: {port} logger: """ # The entity of each kind, as the body of a node. Most use the `template` platform with optimistic writes, so a # command is visible as a state change. RECIPES: dict[str, str] = { "binary_sensor": """\ binary_sensor: - platform: template name: "Probe" lambda: "return true;" """, "sensor": """\ sensor: - platform: template name: "Probe" lambda: "return 21.5;" update_interval: 1s """, "text_sensor": """\ text_sensor: - platform: template name: "Probe" lambda: 'return {"OK"};' update_interval: 1s """, "switch": """\ switch: - platform: template name: "Probe" optimistic: true """, "button": """\ button: - platform: template name: "Probe" on_press: - logger.log: "pressed" """, "number": """\ number: - platform: template name: "Probe" min_value: 10 max_value: 30 step: 0.5 optimistic: true """, "select": """\ select: - platform: template name: "Probe" options: ["A", "B", "C"] optimistic: true """, "text": """\ text: - platform: template name: "Probe" optimistic: true min_length: 0 max_length: 20 mode: text """, "lock": """\ lock: - platform: template name: "Probe" optimistic: true lock_action: - logger.log: "lock" unlock_action: - logger.log: "unlock" open_action: - logger.log: "open" """, "valve": """\ valve: - platform: template name: "Probe" optimistic: true has_position: true open_action: - logger.log: "open" close_action: - logger.log: "close" stop_action: - logger.log: "stop" position_action: - logger.log: "position" """, "cover": """\ cover: - platform: template name: "Probe" optimistic: true has_position: true open_action: - logger.log: "open" close_action: - logger.log: "close" stop_action: - logger.log: "stop" position_action: - logger.log: "position" tilt_action: - logger.log: "tilt" tilt_lambda: "return 0.5;" """, "fan": """\ fan: - platform: template name: "Probe" speed_count: 3 has_direction: true has_oscillating: true preset_modes: ["eco", "turbo"] """, "light": """\ output: - platform: template id: out_r type: float write_action: - logger.log: "r" - platform: template id: out_g type: float write_action: - logger.log: "g" - platform: template id: out_b type: float write_action: - logger.log: "b" - platform: template id: out_cw type: float write_action: - logger.log: "cw" - platform: template id: out_ww type: float write_action: - logger.log: "ww" light: - platform: rgbww name: "Probe" red: out_r green: out_g blue: out_b cold_white: out_cw warm_white: out_ww cold_white_color_temperature: 153 mireds warm_white_color_temperature: 500 mireds effects: - random: - strobe: """, "climate": """\ sensor: - platform: template id: room lambda: "return 21.5;" update_interval: 1s - platform: template id: room_humidity lambda: "return 40.0;" update_interval: 1s climate: - platform: thermostat name: "Probe" sensor: room humidity_sensor: room_humidity default_preset: Home preset: - name: Home default_target_temperature_low: 20 default_target_temperature_high: 24 - name: Away default_target_temperature_low: 16 default_target_temperature_high: 28 - name: Night default_target_temperature_low: 17 default_target_temperature_high: 19 heat_action: - logger.log: "heat" cool_action: - logger.log: "cool" idle_action: - logger.log: "idle" fan_only_action: - logger.log: "fan only" humidity_control_humidify_action: - logger.log: "humidify" humidity_control_off_action: - logger.log: "humidity off" fan_mode_auto_action: - logger.log: "fan auto" fan_mode_on_action: - logger.log: "fan on" swing_both_action: - logger.log: "swing both" swing_off_action: - logger.log: "swing off" min_idle_time: 1s min_heating_off_time: 1s min_heating_run_time: 1s min_cooling_off_time: 1s min_cooling_run_time: 1s min_fanning_off_time: 1s min_fanning_run_time: 1s min_fan_mode_switching_time: 1s """, "light/rgbw": """\ output: - platform: template id: out_r type: float write_action: - logger.log: "r" - platform: template id: out_g type: float write_action: - logger.log: "g" - platform: template id: out_b type: float write_action: - logger.log: "b" - platform: template id: out_w type: float write_action: - logger.log: "w" light: - platform: rgbw name: "Probe" red: out_r green: out_g blue: out_b white: out_w """, "climate/single-point": """\ sensor: - platform: template id: room lambda: "return 21.5;" update_interval: 1s climate: - platform: thermostat name: "Probe" sensor: room heat_action: - logger.log: "heat" idle_action: - logger.log: "idle" min_idle_time: 1s min_heating_off_time: 1s min_heating_run_time: 1s """, "date": """\ datetime: - platform: template name: "Probe" type: date optimistic: true """, "time": """\ datetime: - platform: template name: "Probe" type: time optimistic: true """, "datetime": """\ datetime: - platform: template name: "Probe" type: datetime optimistic: true """, "alarm_control_panel": """\ alarm_control_panel: - platform: template name: "Probe" codes: ["1234"] requires_code_to_arm: false arming_home_time: 1s arming_away_time: 1s pending_time: 1s trigger_time: 1s """, "event": """\ event: - platform: template name: "Probe" event_types: - "ring" """, "water_heater": """\ water_heater: - platform: template name: "Probe" supported_modes: [ECO, ELECTRIC, PERFORMANCE] # a lambda per feature switches it on; `{}` keeps the value commands set (optimistic) current_temperature: "return 45.0;" target_temperature: "return {};" mode: "return {};" away: "return {};" is_on: "return {};" """, } # Kinds the host node cannot run, and why (each reason was checked with `esphome config` / `esphome compile`) UNHOSTABLE: dict[str, str] = { "siren": "ESPHome has no siren component: the kind exists in the API only", "radio_frequency": "needs ir_rf_proxy with a remote_transmitter, which has no host implementation (fails to link)", "infrared": "needs ir_rf_proxy with a remote_transmitter, which has no host implementation (fails to link)", "camera": "needs camera hardware: the only platform is esp32_camera", "media_player": "needs a speaker platform: i2s_audio is hardware, mixer and resampler wrap another speaker", "update": "the http_request platform is incompatible with the host framework; esp32_hosted needs hardware", } # What the integration must expose for the recipe's entity: sub-field -> (data type, role) EXPECTED: dict[str, dict[str, tuple[T, R]]] = { "binary_sensor": {"state": (T.bool, R.sensor)}, "sensor": {"state": (T.decimal, R.sensor)}, "text_sensor": {"state": (T.string, R.sensor)}, "switch": {"state": (T.bool, R.control)}, "button": {"state": (T.none, R.control)}, "number": {"state": (T.decimal, R.control)}, "select": {"state": (T.enum, R.control)}, "text": {"state": (T.string, R.control)}, "lock": {"state": (T.enum, R.sensor), "command": (T.enum, R.control)}, "valve": { "position": (T.decimal, R.control), "current_operation": (T.enum, R.sensor), "stop": (T.none, R.control), }, "cover": { "position": (T.decimal, R.control), "operation": (T.enum, R.sensor), "tilt": (T.decimal, R.control), "stop": (T.none, R.control), }, "fan": { "state": (T.bool, R.control), "speed_level": (T.integer, R.control), "oscillating": (T.bool, R.control), "direction": (T.enum, R.control), "preset_mode": (T.enum, R.control), }, "light": { "state": (T.bool, R.control), "brightness": (T.decimal, R.control), "color_hue": (T.decimal, R.control), "color_saturation": (T.decimal, R.control), "color_temperature": (T.decimal, R.control), "effect": (T.enum, R.control), "color_brightness": (T.decimal, R.control), "transition_length": (T.decimal, R.control), "flash": (T.struct, R.control), }, "climate": { "mode": (T.enum, R.control), "action": (T.enum, R.sensor), "current_temperature": (T.decimal, R.sensor), "target_temperature_low": (T.decimal, R.control), "target_temperature_high": (T.decimal, R.control), "fan_mode": (T.enum, R.control), "swing_mode": (T.enum, R.control), "preset": (T.enum, R.control), "custom_preset": (T.enum, R.control), "current_humidity": (T.decimal, R.sensor), "target_humidity": (T.decimal, R.control), }, "light/rgbw": { "state": (T.bool, R.control), "brightness": (T.decimal, R.control), "color_hue": (T.decimal, R.control), "color_saturation": (T.decimal, R.control), "white": (T.decimal, R.control), "color_brightness": (T.decimal, R.control), "transition_length": (T.decimal, R.control), "flash": (T.struct, R.control), }, "climate/single-point": { "mode": (T.enum, R.control), "action": (T.enum, R.sensor), "current_temperature": (T.decimal, R.sensor), "target_temperature": (T.decimal, R.control), }, "date": {"date": (T.struct, R.control)}, # year, month, day as its fields "time": {"time": (T.struct, R.control)}, # hour, minute, second as its fields "datetime": {"epoch_seconds": (T.integer, R.control)}, "alarm_control_panel": { "state": (T.enum, R.sensor), "command": (T.enum, R.control), "command_with_code": (T.struct, R.control), # command and code as its fields: this panel requires a code "code": (T.string, R.control), # the default code, a setting the commands fall back to }, "event": {}, # one-shot events have no parameters yet "water_heater": { "on": (T.bool, R.control), # a flag of the state bit mask "away": (T.bool, R.control), "mode": (T.enum, R.control), "current_temperature": (T.decimal, R.sensor), "target_temperature": (T.decimal, R.control), }, } # Fields of the entity's state or command that no parameter exposes, each with the reason. A field the library adds # later is not listed: the sweep fails until it is mapped or explained here. UNMAPPED: dict[str, dict[str, str]] = { "cover": { "current_operation": "exposed as operation", "legacy_state": "deprecated: position and operation replace it", }, "fan": {"speed": "the legacy three-step speed: speed_level replaces it"}, "light": { "red": "exposed as color_hue and color_saturation", "green": "exposed as color_hue and color_saturation", "blue": "exposed as color_hue and color_saturation", "rgb": "exposed as color_hue and color_saturation", "color_mode": "derived from the capabilities the light reports", "cold_white": "the channel behind color_temperature", "warm_white": "the channel behind color_temperature", "white": "only on RGBW lights: the light/rgbw recipe covers it", "flash_length": "exposed as the length of the flash command", }, "climate": { "target_temperature": "two-point thermostat: low and high are exposed (climate/single-point covers the other)", "unused_legacy_away": "deprecated", "custom_fan_mode": "the host thermostat platform has none: tests/test_unhosted_fields.py covers it", }, "light/rgbw": { **{f: "exposed as color_hue and color_saturation" for f in ("red", "green", "blue", "rgb")}, "color_mode": "derived from the capabilities the light reports", "flash_length": "exposed as the length of the flash command", **{ f: "the channels behind a colour temperature, which this light has not" for f in ("cold_white", "warm_white") }, "color_temperature": "this light has no colour temperature", "effect": "this light has no effects", }, "climate/single-point": { "target_temperature_low": "this thermostat is single-point: target_temperature is exposed instead", "target_temperature_high": "this thermostat is single-point: target_temperature is exposed instead", "unused_legacy_away": "deprecated", **{ f: "this thermostat does not support it" for f in ( "fan_mode", "swing_mode", "preset", "custom_preset", "custom_fan_mode", "current_humidity", "target_humidity", ) }, }, "lock": {"code": "only offered when the lock requires a code: tests/test_unhosted_fields.py covers it"}, "water_heater": { "state": "exposed as on and away, the flags of this bit mask", "target_temperature_low": "single-point: tests/test_unhosted_fields.py covers two-point", "target_temperature_high": "single-point: tests/test_unhosted_fields.py covers two-point", }, } def kind_of(key: str) -> str: """The entity kind of a recipe key: `light` and `light/rgbw` are both lights.""" return key.split("/")[0] def all_kinds() -> list[str]: """Every entity kind the installed `aioesphomeapi` knows.""" return list(COMPONENT_TYPE_TO_INFO) def sketch_for(key: str) -> Sketch: index = list(RECIPES).index(key) name = "cat_" + key.replace("/", "_").replace("-", "_") return Sketch(f"{name}.yaml", name, API_PORT, f"983569{index:06x}", directory=NODES_DIR) def recipe_keys() -> list[str]: """Every recipe: a kind's default one (`light`) and its variants (`light/rgbw`).""" return list(RECIPES) def generate(kinds: list[str] | None = None) -> list[str]: """Write the node yaml of every kind that has a recipe; returns the kinds written.""" NODES_DIR.mkdir(exist_ok=True) written = [] for kind in kinds or recipe_keys(): sketch = sketch_for(kind) body = RECIPES[kind] (NODES_DIR / sketch.yaml).write_text( HEADER.format(name=sketch.name, mac=_colon(sketch.mac), port=API_PORT) + body ) written.append(kind) return written def _colon(mac: str) -> str: return ":".join(mac[i : i + 2] for i in range(0, 12, 2)) def compile_node(sketch: Sketch) -> str | None: """Compile a node; returns None, or the compiler's last lines when it fails (the reason for the test failure).""" result = subprocess.run( ["esphome", "compile", str(sketch.directory / sketch.yaml)], capture_output=True, text=True, check=False ) if result.returncode == 0: return None noise = ("blake2", "hashlib", "Traceback", "File ", "raise ", "~~", "^^", "globals(") lines = [ line for line in (result.stdout + result.stderr).splitlines() if line.strip() and not any(n in line for n in noise) ] return f"esphome compile failed ({result.returncode}):\n" + "\n".join(lines[-15:]) def build_all(kinds: list[str] | None = None, workers: int = 3) -> dict[str, str | None]: """Generate and build the nodes in parallel; returns kind -> why it could not be built (None when built).""" if shutil.which("esphome") is None: raise RuntimeError("`esphome` CLI not found: install it (e.g. `pipx install esphome`)") todo = generate(kinds) def one(kind: str) -> tuple[str, str | None]: sketch = sketch_for(kind) return kind, None if sketch.binary.exists() else compile_node(sketch) with ThreadPoolExecutor(max_workers=workers) as pool: return dict(pool.map(one, todo)) if __name__ == "__main__": if sys.argv[1:] == ["generate"]: print("generated:", ", ".join(generate())) else: results = build_all() for kind, error in results.items(): print(f"{'ok ' if error is None else 'FAIL'} {kind}" + (f": {error}" if error else "")) sys.exit(any(results.values())) ================================================================================ # FILE: tests/virtual/mdns.py ================================================================================ """Zeroconf without a network: the SDK's real `ZeroconfDiscoveryService` runs over a stubbed zeroconf. Same approach as the homekit integration's tests: the browser and service-info classes are replaced, so announcements are delivered on demand and nothing is ever sent to (or heard from) the LAN. """ import asyncio import socket from collections.abc import Generator from contextlib import contextmanager from dataclasses import dataclass, field from typing import Any from unittest.mock import AsyncMock, MagicMock, patch MDNS_TYPE = "_esphomelib._tcp.local." NOISE_PROTOCOL = "Noise_NNpsk0_25519_ChaChaPoly_SHA256" SDK_MODULE = "majordom_integration_sdk.runtime.peripherals.providers.zeroconf" @dataclass class Advert: """What a real ESPHome node announces (TXT keys as published by ESPHome's mdns component).""" name: str = "test_node" mac: str | None = "983569abf679" server: str | None = "localhost." # a real node announces `.local.` addresses: list[str] = field(default_factory=lambda: ["127.0.0.1"]) port: int = 6053 encrypted: bool = False # a key is configured keyless: bool = False # encryption is on but no key is set yet: the key is given at pairing zero_psk: bool = True # a keyless node takes its key over the zero PSK (older firmware: only in plaintext) friendly_name: str | None = None @property def fqdn(self) -> str: return f"{self.name}.{MDNS_TYPE}" @property def properties(self) -> dict[bytes, bytes | None]: properties: dict[bytes, bytes | None] = {b"version": b"2026.3.3", b"board": b"host"} if self.mac: properties[b"mac"] = self.mac.encode() if self.friendly_name: properties[b"friendly_name"] = self.friendly_name.encode() if self.encrypted: properties[b"api_encryption"] = NOISE_PROTOCOL.encode() elif self.keyless: properties[b"api_encryption_supported"] = NOISE_PROTOCOL.encode() if self.zero_psk: properties[b"api_provisioning"] = b"zero-psk" return properties class _BrowserStub: def __init__(self, zeroconf: Any, types: list[str], listener: Any): self.types = types self.listener = listener self.cancelled = False async def async_cancel(self): self.cancelled = True class FakeMDNS: def __init__(self): self.adverts: dict[str, Advert] = {} self.browsers: list[_BrowserStub] = [] self._zeroconf = MagicMock(name="zeroconf") def _browser(self, zeroconf: Any, types: list[str], listener: Any) -> _BrowserStub: browser = _BrowserStub(zeroconf, types, listener) self.browsers.append(browser) return browser def _service_info(self, type_: str, name: str) -> Any: adverts = self.adverts class ServiceInfoStub: def __init__(self, type_: str, name: str): self.type, self.name = type_, name self.weight = self.priority = 0 self.host_ttl, self.other_ttl, self.interface_index, self.text = 120, 4500, None, b"" def load_from_cache(self, zeroconf: Any) -> bool: advert = adverts.get(self.name) if advert is None: return False self.port, self.server = advert.port, advert.server self.properties = advert.properties self.decoded_properties = {k.decode(): v.decode() if v else None for k, v in advert.properties.items()} self._addresses = advert.addresses return True async def async_request(self, zeroconf: Any, timeout: float) -> bool: return self.load_from_cache(zeroconf) @property def addresses(self) -> list[bytes]: return [socket.inet_pton(socket.AF_INET6 if ":" in a else socket.AF_INET, a) for a in self._addresses] def parsed_addresses(self) -> list[str]: return list(self._addresses) return ServiceInfoStub(type_, name) async def announce(self, advert: Advert): """The node appears, or announces itself again with changed records.""" known = advert.fqdn in self.adverts self.adverts[advert.fqdn] = advert for browser in self._listening(): if known: browser.listener.update_service(self._zeroconf, MDNS_TYPE, advert.fqdn) else: browser.listener.add_service(self._zeroconf, MDNS_TYPE, advert.fqdn) await settle() async def goodbye(self, advert: Advert): self.adverts.pop(advert.fqdn, None) for browser in self._listening(): browser.listener.remove_service(self._zeroconf, MDNS_TYPE, advert.fqdn) await settle() def _listening(self) -> list[_BrowserStub]: return [b for b in self.browsers if not b.cancelled and MDNS_TYPE in b.types] async def settle(): """Let the SDK resolve, deliver and the controller handle an announcement: no I/O is involved.""" for _ in range(20): await asyncio.sleep(0) @contextmanager def fake_mdns() -> Generator[FakeMDNS]: fake = FakeMDNS() async_zeroconf = MagicMock(name="AsyncZeroconf") async_zeroconf.return_value.zeroconf = fake._zeroconf async_zeroconf.return_value.async_close = AsyncMock() with ( patch(f"{SDK_MODULE}.AsyncServiceBrowser", fake._browser), patch(f"{SDK_MODULE}.AsyncZeroconf", async_zeroconf), patch(f"{SDK_MODULE}.AsyncServiceInfo", fake._service_info), patch(f"{SDK_MODULE}._RESOLVE_DELAY", 0), ): yield fake ================================================================================ # FILE: tests/virtual/runner.py ================================================================================ """Runs a compiled virtual ESPHome device (host platform) as a subprocess, for end-to-end tests. Adapted from the integration drafts' `ESPHomeRunner`: same idea (compiled binary + log buffer), reshaped as an async, typed helper that can be killed and restarted mid-test. It never touches mDNS: see `mdns.py`. """ import asyncio import contextlib import fcntl import os import shutil import signal import socket import subprocess import tempfile import threading import time from dataclasses import dataclass from pathlib import Path SKETCHES_DIR = Path(__file__).parent / "sketches" @dataclass(frozen=True) class Sketch: yaml: str name: str # `esphome.name` inside the yaml; also the build directory name port: int mac: str # as advertised in mDNS TXT: lowercase hex, no separators encryption_key: str | None = None directory: Path = SKETCHES_DIR # where the yaml lives; esphome builds next to it @property def binary(self) -> Path: return self.directory / ".esphome" / "build" / self.name / ".pioenvs" / self.name / "program" ENCRYPTION_KEY = "kiO8WgmbyiIdaQ9fAFcZCdFTzRj6dzmfG/Pu3pbU9JI=" # `api.encryption.key` of encrypted.yaml PLAIN = Sketch("virtual.yaml", "test_node", 6053, "983569abf679") ENCRYPTED = Sketch("encrypted.yaml", "test_node_enc", 6054, "983569abf679", ENCRYPTION_KEY) EXTRAS = Sketch("extras.yaml", "test_node_extras", 6055, "983569abf680") # entities without a hand-written mapping KEYLESS = Sketch("keyless.yaml", "test_node_keyless", 6056, "983569abf679") # encryption on, key set at pairing SKETCHES = (PLAIN, ENCRYPTED, EXTRAS, KEYLESS) def build(sketch: Sketch): """Compile the sketch to a native binary (needs the `esphome` CLI on PATH). Takes a minute or two.""" if shutil.which("esphome") is None: raise RuntimeError("`esphome` CLI not found: install it (e.g. `pipx install esphome`) to build virtual devices") subprocess.run(["esphome", "compile", str(sketch.directory / sketch.yaml)], check=True) # The API port is compiled into each binary (ESPHome host builds read no port override at runtime), so two test runs # on one machine (worktrees, a dev and an agent) would bind the same ports and talk to each other's nodes. A run takes # this machine-wide lock when a test starts its first virtual device and keeps it until the test ends (`release_ports`), # also across a device's stop/start: parallel runs take turns per test instead of colliding. One lock for all ports, so # two runs can never deadlock on a test with two devices. _LOCK_PATH = Path(tempfile.gettempdir()) / "majordom-esphome-virtual-devices.lock" _lock_fd: int | None = None async def _acquire_ports(): global _lock_fd if _lock_fd is None: fd = os.open(_LOCK_PATH, os.O_RDWR | os.O_CREAT, 0o666) await asyncio.to_thread(fcntl.flock, fd, fcntl.LOCK_EX) _lock_fd = fd def release_ports(): global _lock_fd if _lock_fd is not None: os.close(_lock_fd) # closing drops the flock _lock_fd = None class VirtualDevice: def __init__(self, sketch: Sketch = PLAIN): self.sketch = sketch self._proc: subprocess.Popen[str] | None = None self._reader: threading.Thread | None = None self._workdir = Path(tempfile.mkdtemp(prefix="virtual-esphome-")) self._lines: list[str] = [] @property def address(self) -> str: return "127.0.0.1" @property def port(self) -> int: return self.sketch.port @property def log(self) -> str: return "".join(self._lines) @property def running(self) -> bool: return self._proc is not None and self._proc.poll() is None async def start(self, timeout: float = 10.0): if not self.sketch.binary.exists(): raise FileNotFoundError( f"{self.sketch.binary} is not built: run `poetry run python -m tests.virtual.build`" ) await _acquire_ports() line_buffered = shutil.which("stdbuf") or shutil.which("gstdbuf") # piped stdout is block-buffered otherwise cmd = [line_buffered, "-oL", str(self.sketch.binary)] if line_buffered else [str(self.sketch.binary)] # the node's flash (a provisioned key) lives in its own workdir: kept across restarts, never across tests env = {**os.environ, "ESPHOME_PREFDIR": str(self._workdir)} self._proc = subprocess.Popen( cmd, cwd=self._workdir, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 ) self._reader = threading.Thread(target=self._read_output, args=(self._proc,), daemon=True) self._reader.start() await self._wait_for_port(timeout) async def stop(self): proc, self._proc = self._proc, None if proc is not None: if proc.poll() is None: proc.send_signal(signal.SIGINT) with contextlib.suppress(subprocess.TimeoutExpired): await asyncio.to_thread(proc.wait, 5) if proc.poll() is None: proc.kill() await asyncio.to_thread(proc.wait) if self._reader is not None: self._reader.join(timeout=2) self._reader = None if proc.stdout is not None: proc.stdout.close() async def restart(self): await self.stop() await self.start() async def wait_log(self, text: str, timeout: float = 5.0): deadline = time.monotonic() + timeout while time.monotonic() < deadline: if text in self.log: return await asyncio.sleep(0.05) raise TimeoutError(f"{text!r} not found in device log:\n{self.log[-2000:]}") def _read_output(self, proc: subprocess.Popen[str]): assert proc.stdout is not None for line in proc.stdout: self._lines.append(line) async def _wait_for_port(self, timeout: float): deadline = time.monotonic() + timeout while time.monotonic() < deadline: if not self.running: raise RuntimeError(f"virtual device exited early:\n{self.log}") with contextlib.suppress(OSError), socket.create_connection((self.address, self.port), timeout=0.2): return await asyncio.sleep(0.1) raise TimeoutError(f"virtual device did not open port {self.port}:\n{self.log}") ================================================================================ # FILE: tests/virtual/sketches/encrypted.yaml ================================================================================ # Same device with Noise API encryption on, on its own name and port so both can run at once. packages: base: !include virtual.yaml esphome: name: test_node_enc api: port: 6054 encryption: key: "kiO8WgmbyiIdaQ9fAFcZCdFTzRj6dzmfG/Pu3pbU9JI=" ================================================================================ # FILE: tests/virtual/sketches/extras.yaml ================================================================================ # Virtual node with the entity kinds that have no hand-written mapping: they are mapped generically. esphome: name: test_node_extras host: mac_address: "98:35:69:ab:f6:80" api: port: 6055 logger: lock: - platform: template name: "Door" id: door_lock optimistic: true lock_action: - logger.log: "Lock" unlock_action: - logger.log: "Unlock" open_action: - logger.log: "Open" valve: - platform: template name: "Garden Valve" id: garden_valve optimistic: true has_position: true open_action: - logger.log: "Valve open" close_action: - logger.log: "Valve close" stop_action: - logger.log: "Valve stop" position_action: - logger.log: "Valve position" text: - platform: template name: "Label" id: label_text optimistic: true min_length: 0 max_length: 20 mode: text datetime: - platform: template name: "Date" id: a_date type: date optimistic: true alarm_control_panel: - platform: template name: "House Alarm" id: house_alarm codes: ["1234"] requires_code_to_arm: false arming_home_time: 1s arming_away_time: 1s pending_time: 1s trigger_time: 1s event: - platform: template name: "Doorbell" id: doorbell event_types: - "ring" ================================================================================ # FILE: tests/virtual/sketches/keyless.yaml ================================================================================ # Same device with API encryption on but no key: it advertises `api_encryption_supported` and is given its key at # pairing, over a Noise session with the well-known all-zeros PSK (modelled on ESPHome's api_zero_psk_provisioning). packages: base: !include virtual.yaml esphome: name: test_node_keyless api: port: 6056 encryption: {} ================================================================================ # FILE: tests/virtual/sketches/virtual.yaml ================================================================================ # Virtual ESPHome device (host platform): one native-API node, no hardware, no wifi. # Build once: poetry run python -m tests.virtual.build # Entities mirror the integration drafts' sketch, with optimistic writes so commands are observable as state. esphome: name: test_node host: mac_address: "98:35:69:ab:f6:79" api: port: 6053 logger: level: VERBOSE # light calls log their transition and flash lengths at VERBOSE since ESPHome 2026.x sensor: - platform: template name: "Temperature" id: temp device_class: temperature unit_of_measurement: "°C" lambda: "return 21.5;" update_interval: 1s - platform: template name: "Humidity" id: humidity device_class: humidity unit_of_measurement: "%" lambda: "return 55.0;" update_interval: 1s - platform: template name: "Dust" id: dust device_class: pm25 unit_of_measurement: "µg/m³" lambda: "return 12.0;" update_interval: 1s - platform: template name: "Distance" id: distance device_class: distance unit_of_measurement: "m" lambda: "return 1.5;" update_interval: 1s binary_sensor: - platform: template name: "Motion" id: motion device_class: motion lambda: "return true;" text_sensor: - platform: template name: "Status" id: status lambda: 'return {"OK"};' update_interval: 1s switch: - platform: template name: "Relay" id: relay_switch optimistic: true output: - platform: template id: fake_output type: float write_action: - logger.log: format: "Light brightness: %.2f" args: ["state"] - platform: template id: fake_red type: float write_action: - logger.log: "red" - platform: template id: fake_green type: float write_action: - logger.log: "green" - platform: template id: fake_blue type: float write_action: - logger.log: "blue" light: - platform: monochromatic name: "Virtual Light" id: virtual_light output: fake_output - platform: rgb name: "RGB Light" id: rgb_light red: fake_red green: fake_green blue: fake_blue fan: - platform: template name: "Virtual Fan" id: virtual_fan speed_count: 3 has_direction: true has_oscillating: true on_turn_on: - logger.log: "Fan ON" on_turn_off: - logger.log: "Fan OFF" cover: - platform: template name: "Blinds" id: blinds optimistic: true has_position: true position_action: - logger.log: "Position" open_action: - logger.log: "Open" close_action: - logger.log: "Close" stop_action: - logger.log: "Stop" number: - platform: template name: "Target Temp" id: target_temp min_value: 10 max_value: 30 step: 0.5 optimistic: true select: - platform: template name: "Mode" id: mode_select options: - "AUTO" - "MANUAL" optimistic: true button: - platform: template name: "Reboot" id: reboot_button on_press: - logger.log: "Reboot pressed" climate: - platform: thermostat name: HVAC id: hvac sensor: temp default_preset: Default preset: - name: Default default_target_temperature_low: 20 default_target_temperature_high: 24 heat_action: - logger.log: Heating cool_action: - logger.log: Cooling idle_action: - logger.log: Idle min_idle_time: 1s min_heating_off_time: 1s min_heating_run_time: 1s min_cooling_off_time: 1s min_cooling_run_time: 1s # integration-zwave — full source # repo: https://github.com/MajorDom-Systems/integration-zwave branch: master commit: 59c0d0a8a1da32aa03a2152b5d763299c929e435 # generated: 2026-11-16 — AUTO-GENERATED, do not edit by hand ## File tree .gitignore LICENSE README.md main.py majordom_zwave/__init__.py majordom_zwave/config.py majordom_zwave/controller.py majordom_zwave/device_configs/0x0460/qnsw-001X16.json majordom_zwave/mapper.py majordom_zwave/model.py majordom_zwave/zwave_spec.py pyproject.toml tests/catalogue.py tests/conftest.py tests/helpers.py tests/mock/package.json tests/network.py tests/test_catalogue.py tests/test_commands.py tests/test_config.py tests/test_device_configs.py tests/test_identify.py tests/test_lifecycle.py tests/test_notifications.py tests/test_pairing.py tests/test_sleeping.py tests/test_smart_start.py tests/test_smoke.py tests/test_state.py tests/test_unpair.py ================================================================================ # FILE: .gitignore ================================================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[codz] *$py.class # C extensions *.so # Distribution / packaging build/ dist/ *.egg-info/ *.egg # Unit test / coverage reports .coverage .coverage.* coverage.xml htmlcov/ .pytest_cache/ .hypothesis/ # Environments .env .envrc .venv env/ venv/ # Poetry # poetry.lock # uncomment for applications, keep commented for libraries # Type checkers .mypy_cache/ .dmypy.json .pyre/ .pytype/ # Tools .ruff_cache/ .ropeproject # the dev runner's settings and network keys .majordom-dev/ # mkdocs (only relevant if you kept mkdocs.yml + docs/) /site .cache/ # IDEs .idea/ .vscode/ # OS .DS_Store Thumbs.db node_modules/ ================================================================================ # FILE: LICENSE ================================================================================ # PolyForm Noncommercial License 1.0.0 ## Acceptance In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses. ## Copyright License The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license). ## Distribution License The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license). ## Notices You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example: > Required Notice: Copyright Yoyodyne, Inc. (http://example.com) ## Changes and New Works License The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose. ## Patent License The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software. ## Noncommercial Purposes Any noncommercial purpose is a permitted purpose. ## Personal Uses Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose. ## Noncommercial Organizations Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding. ## Fair Use You may have "fair use" rights for the software under the law. These terms do not limit them. ## No Other Rights These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses. ## Patent Defense If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company. ## Violations The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately. ## No Liability ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*** ## Definitions The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms. **You** refers to the individual or entity agreeing to these terms. **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. **Your licenses** are all the licenses granted to you for the software under these terms. **Use** means anything you do with the software requiring one of your licenses. ================================================================================ # FILE: README.md ================================================================================ Part of MajorDom — the next-gen smart home # integration-zwave A [MajorDom](https://majordom.io) integration — bridges **Z-Wave** devices into the MajorDom language. Built for the **MajorDom Hub**, but it doesn't need it: this is a standalone, standardized library for Z-Wave that you can use on its own (see **Run it standalone** below). Built on the [MajorDom Integration SDK](https://github.com/MajorDom-Systems/integration-sdk). The entry point is `ZwaveController` (`majordom_zwave/controller.py`), which the Hub — or the SDK's dev runner — instantiates and drives through its lifecycle: pairing → commands → teardown. - **Other protocols:** browse the [MajorDom integrations](https://github.com/orgs/MajorDom-Systems/repositories?q=integration-). - **Create your own:** start from the [integration template](https://github.com/MajorDom-Systems/integration-template). ## Documentation Full integration-author docs — the controller lifecycle, data models, storing data, discovery, and a worked example — live at **[docs.majordom.io](https://docs.majordom.io/device-integration)**. ## Development ```sh poetry install && poetry run poe install ``` | Task | Description | |------|-------------| | `poe check` | Full quality pipeline (ruff, ty, pytest, poetry build/check) | | `poe check --ci` | Same, plus `git diff --exit-code` | Work lands on `develop`; `master` is protected and released via **Actions → Release**. Tests drive the controller with the SDK's test doubles against a **mock Z-Wave network**: zwave-js's own mock controller and mock devices, with a real zwave-js driver and a real `zwave-js-server` in front (`tests/mock`) — the integration connects to it exactly as to a real server, no radio or stick required. It needs Node.js 20+: ```sh npm ci --prefix tests/mock && poetry run pytest ``` ### Command-class catalogue and canary `tests/test_catalogue.py` accounts for every command class zwave-js knows (125 today): each is hosted by a mock device (a recipe in `tests/mock/catalogue.mjs`: 34 of them, all their capabilities switched on), is protocol plumbing, or is listed in `tests/catalogue.py` with the reason the mock cannot host it. Each hosted one must map exactly as `EXPECTED` says — name, type, role, visibility, unit, main parameter, reviewed value by value against the docs' [parameter UX](https://docs.majordom.io/device-integration/parameter-ux) — pass the SDK's `parameter_audit`, and round-trip every writable value through the device. Seven more mock devices carry *every* variant zwave-js knows (88 sensor types and their scales, 14 binary sensors, 5 meters with all their scales, 22 notification types with all their states and events, 12 setpoints, 16 thermostat modes), checked against rules. Fast checks fail on a new command class, value metadata type or unit. The monthly **canary** (`.github/workflows/canary.yml`) runs all of it against the latest zwave-js, zwave-js-server and zwave-js-server-python: red means upstream shipped something to support, or to explain. ## Run it standalone (without the Hub) `majordom-zwave` is a standalone library — import it into your own app, or run **just this integration** interactively (discover, pair, control, and inspect devices from a prompt) with no Hub. It needs a reachable `zwave-js-server` instance (see below). See **[Standalone mode](https://docs.majordom.io/device-integration/standalone)** for the interactive CLI, watch mode, and the programmatic API. ## Connecting to zwave-js-server Unlike a radio-based integration, this one never talks to the Z-Wave stick directly. It connects over WebSocket, via [`zwave-js-server-python`](https://github.com/home-assistant-libs/zwave-js-server-python), to a running **[zwave-js-server](https://github.com/zwave-js/zwave-js-server)** process (Node.js) — the same server Home Assistant's Z-Wave JS integration uses. `zwave-js-server` is what actually owns the serial connection to the Z-Wave USB controller and speaks the Z-Wave protocol; this integration just talks JSON over a WebSocket to it. - Run `zwave-js-server` yourself (commonly via Docker) on whatever machine has the Z-Wave USB controller attached. - Point this integration at it with the `ZWAVE_SERVER_URL` environment variable (default `ws://localhost:3000`) — see `majordom_zwave/config.py`. - The integration keeps reconnecting (1 → 30 s backoff) while the server is unreachable; paired devices are reported unavailable meanwhile, with the reason as their `last_error`. ## About this integration - **Protocol / platform:** Z-Wave, via [`zwave-js-server`](https://github.com/zwave-js/zwave-js-server) / [`zwave-js-server-python`](https://github.com/home-assistant-libs/zwave-js-server-python). - **Transport(s):** Z-Wave (sub-GHz RF mesh). - **Supported devices:** any Z-Wave / Z-Wave Plus device exposing standard Command Classes (Binary/Multilevel Switch, Indicator, etc.) that Z-Wave JS supports. - **Credentials needed to pair:** given when *opening the pairing window* (`start_pairing_window`), not at `pair_device` time — Z-Wave needs them during inclusion, before the device exists as a discovery; the discovery itself always expects `CredentialsType.none`. - `code` — the S2 PIN (the first 5 digits of the DSK on the device's label), or the whole DSK. - `qr` — the device's QR code (`90…`); malformed codes are rejected. An S2 code includes the device in the window; a **SmartStart** code provisions it instead: zwave-js includes it securely, with no PIN, whenever it is powered on (hours later, after installation), and it then arrives as a discovery. Unpairing removes it from the provisioning list, or it would join again. - none — the device joins, but without the S2 Authenticated / Access Control classes (they need the PIN); its discovery's `last_error` says so. - `secret` — not supported. The Hub does not pass credentials to `start_pairing_window` yet (the SDK's `develop` has the parameter). ### Required harness - **Hardware adapters:** a Z-Wave USB controller (e.g. Aeotec/Zooz Z-Stick) — but it's attached to whatever host runs `zwave-js-server`, not necessarily the Hub. This integration doesn't use `dependencies.hardware_interfaces`; the radio is abstracted behind the server. - **Third-party software services:** [`zwave-js-server`](https://github.com/zwave-js/zwave-js-server) (Node.js) must be running and reachable at `ZWAVE_SERVER_URL`. - **OS / permissions:** network reachability (TCP) to the `zwave-js-server` host:port. No special permissions needed on the Hub's own host. ### Protocol stack | Layer | Protocol | Implemented by | |-------|----------|----------------| | **MajorDom integration** | maps Z-Wave devices/values ↔ MajorDom domain model | **this repo, always** | | Z-Wave JS Server API | `zwave-js-server`'s WebSocket/JSON-RPC protocol | library (`zwave-js-server-python`) | | Application | Z-Wave Command Classes (CC) | `zwave-js-server` (external Node.js service) | | Network / MAC / PHY | Z-Wave mesh, sub-GHz RF | Z-Wave USB controller + its driver (harness) | ### Manual testing (real hardware) Verified against real hardware, on the version before the rework of 2026-10 (the rework is tested against the mock network only; to be re-run on hardware before release): - **Z-Wave controller:** Z-Stick 7 (ZWA010) - **Test device:** HKZW-RGB01 v1.0 (RGB bulb) ### Mapping | Z-Wave | MajorDom | |--------|----------| | Device | `device_uuid("-")` (SDK helper): node ids repeat across networks and are reused after a device leaves | | Value | One parameter, `parameter_uuid(device, value id)`; a current/target pair (`currentValue`/`targetValue`, `currentMode`/`targetMode`, …) is **one** parameter: commanded through the target, state from the current one | | Multilevel Switch / Basic level, Window Covering position (0–99) | Percentage 0–100 (99 is 100) | | Multilevel Sensor, Meter, setpoints, Energy Production | `decimal` (scaled decimals by spec), whatever the first reading | | `states` | `enum` with labels in `valid_values` (`integer` when the device allows other values too, or when they only label special values: sound volume, wake-up interval) | | Write-only action (`"Reset"`, `"Identify"`, `"Restore previous value"`) | `none`: a button | | Units | Every zwave-js scale unit is mapped, converted (°F → °C, imperial → metric, Wh → kWh, mV → V, …) or deliberately `plain`; a few CCs give units only in labels (Door Lock times, wake-up interval) | | Central Scene, Scene Activation, `stateful: false` | `event` role (sent by zwave-js as "value notification"); their settings stay controls | | Notifications (zwave-js "notification" events) | Read-only `event` parameters: **Keypad** (the event type: Enter, Away, …) and **Keypad code** (what was typed, `system`); one **`` event** per Notification CC type with events (Access control, Home security, …) and its **details** (user id…, JSON, `system`); a remote's **Level change**; **Battery replacement**; **Powerlevel test**. Enum labels are what the device announced; events it did not are dropped | | Visibility | "When in doubt, hide it": a curated list of everyday controls and live readings is `user` (switches, levels, colour, sensors, meters, locks, thermostats, covers, garage doors, battery, …); every other value of a reviewed CC is a `setting`; wiring, metadata, secrets, durations and opaque data are `system`, and so is every value of a CC nobody reviewed (still usable by automations and the API) | | Names | Written for people, not zwave-js's labels: `Power`, `Level`, `Color`, `Lock`, `Electric energy` (not `Electric Consumption [kWh]`), `Motion` (not `Sensor state (Motion)`), `Heating setpoint`, `Scene 1`; a name several values share gets what tells them apart (`Sensor status (Water alarm)`); camelCase enum labels become words (`Unsecured with timeout`) | | Unsupervised set (delivered, not confirmed) | Read back from the device ~6 s later unless zwave-js already did: the Hub sees what the device did | | Main parameter | Binary Switch (toggle) › Multilevel Switch (off / 100 %) › Barrier (closed / open) › Door Lock (unsecured / secured) › Lock (toggle) › Window Covering (closed / open) › Basic, when it is the only control (off / 100 %) | ### Progress **Implementation** — makes the integration functional: - [x] Discovery of joining devices (`"node added"`), and of nodes already on the network but not paired - [x] Discovery of already-paired devices on (re)connect — matched by home id and node id, and checked against the device's fingerprint (a node id reused by another device is not taken for the paired one) - [x] `start_pairing_window` (default, S2 PIN or DSK, S2 QR, SmartStart) - [x] Device pairing (completes the device the Hub created; fails cleanly and stays discovered when the device does not finish its interview) - [x] Device schema mapped (see **Mapping**) - [x] Hub → Device control (`send_command`); the state comes back as the device's report, never echoed - [x] Device → Hub events (`"value updated"`, `"value notification"`, `"notification"`: keypads, Notification CC events, remote dimming, low battery, radio tests) - [x] `identify` — Indicator CC v3 identify; a light blinks; any other device is left alone (a relay or a motor may drive a heater, a pump or a blind) - [x] `unpair` — a failed node is removed without the device; a live one when *this* device confirms the exclusion - [x] `fetch` - [x] Availability — `"dead"`/`"alive"`, the server connection, a device removed with another tool - [x] Graceful shutdown in `stop` - [x] Tests pass against a simulated network (mock zwave-js controller and devices) **Quality** — makes it reliable and maintainable (the bar for release): - [x] **Recovers automatically** from a lost or restarted `zwave-js-server` (reconnects with backoff) - [x] **No exception escapes background work** — event handlers run as logged tasks; Hub calls raise after recording the reason - [x] **Failures are surfaced, not swallowed** — the reason is the device's or discovery's `last_error`; an unreachable server at start is reported through `controller_did_encounter_error` - [x] **Re-authenticates automatically** — not applicable (Z-Wave has no expiring credential) - [x] **Fully asynchronous** - [x] **Stable identity** — the SDK helpers, scoped by the network's home id - [x] **End-to-end tests** drive pair → command → fetch → events → `unpair` against the mock network - [x] **Failure paths tested** — unreachable or lost server, unresponsive and refusing devices, interview timeout, exclusion timeout, the wrong device excluded, a reused node id, a missing PIN - [x] **Broad device coverage** — the catalogue hosts 33 command classes (switches, dimmers, lights, sensors, meters, locks, thermostats, covers, garage doors, scene controllers, sirens, user codes, child locks, humidifiers, keypads, smoke/CO alarms, sleeping devices, …); S2 by PIN, DSK, QR and SmartStart. The others are plumbing or explained (see **Command-class catalogue and canary**) - [x] **Fully typed** (`ty`) and **clean** (`poe check`) - [x] **Readable & structured** — mapping in `mapper.py`, static tables in `zwave_spec.py` - [x] **Efficient** — subscription-based, not polling - [x] **Diagnosable** — per-area log tags (`[PAIR]`, `[CONNECT]`, …), reasons in `last_error`, causes chained - [x] **Rich parameter metadata** — role, visibility, units, limits, enum labels, main parameter; names and buckets reviewed against the docs' parameter UX for every hosted CC, and audited (`parameter_audit`) - [x] **Owned** — maintained by Parker Industries - [ ] _nice-to-have:_ localizable naming · firmware updates · user-facing supported-device docs ### Notes - Z-Wave discovery doesn't use `zeroconf`/`ssdp`/`ble`: nodes are surfaced from `zwave-js-server`'s own events. - Command classes zwave-js's mock cannot host (rare ones: tariffs, IP gateways, AV, schedules, irrigation) are not reviewed: their values map by the generic rules and are hidden (`system`), still usable by automations and the API. - What zwave-js's mock cannot do, so the catalogue does not round-trip it: decode a Color Switch Set, keep an Indicator's state; its Thermostat Setpoint Set refuses every value above the minimum, so the harness replaces it. ## License See [LICENSE](LICENSE). For commercial licensing or partnership inquiries regarding MajorDom, contact us via [parker-industries.org/partnership](https://parker-industries.org/partnership). ================================================================================ # FILE: main.py ================================================================================ import asyncio import logging from majordom_integration_sdk.dev import run_controller import majordom_zwave logging.getLogger("majordom_zwave").setLevel(logging.DEBUG) # The runtime finds the stick and runs zwave-js-server for it; without Docker, pin a zwave-js-server you run instead: # from majordom_integration_sdk import Endpoint # run_controller(majordom_zwave.peripherals, pinned=[Endpoint("zwave", "zwave-js-ws", "ws://localhost:3000")]) asyncio.run(run_controller(majordom_zwave.peripherals)) ================================================================================ # FILE: majordom_zwave/__init__.py ================================================================================ """MajorDom Z-Wave integration. Bridges a Z-Wave network (via a running `zwave-js-server` instance) to a MajorDom Hub. The Hub runs what `peripherals` exports: zwave-js-server on the stick, and the controller (`controller.py`) that drives it. """ from majordom_integration_sdk import Peripheral, Platform from .config import zwave_js_server from .controller import ZwaveController def peripherals(platform: Platform) -> list[Peripheral]: return [zwave_js_server(), ZwaveController(platform)] __all__ = ["ZwaveController", "peripherals"] ================================================================================ # FILE: majordom_zwave/config.py ================================================================================ """zwave-js-server: the service that owns the Z-Wave stick; this integration drives it over WebSocket.""" import secrets from pathlib import Path from typing import Any from majordom_integration_sdk import Endpoint, Need, Service from majordom_integration_sdk import SettingsExtraField as Extra from pydantic import BaseModel, Field KEY = r"^[0-9A-Fa-f]{32}$" # 16 bytes in hex: zwave-js-server exits on any other key def _key() -> str: return secrets.token_hex(16).upper() def _key_field(title: str) -> Any: """Generated once; write-only: the Hub never reads it back through its API, and a change without it keeps it.""" return Field(default_factory=_key, title=title, pattern=KEY, json_schema_extra={Extra.write_only: True}) class ZwaveNetwork(BaseModel): """Security keys of the Z-Wave network, generated once. Back them up: without them, securely included devices have to be re-included on a new controller.""" s0_legacy: str = _key_field("S0 Legacy key") s2_unauthenticated: str = _key_field("S2 Unauthenticated key") s2_authenticated: str = _key_field("S2 Authenticated key") s2_access_control: str = _key_field("S2 Access Control key") lr_s2_authenticated: str = _key_field("Long Range S2 Authenticated key") lr_s2_access_control: str = _key_field("Long Range S2 Access Control key") def zwave_js_server() -> Service[ZwaveNetwork]: """One for each runtime, which keeps on it what it is bound to and its settings.""" return Service( "zwave-js-server", needs=[Need("zwave", ["serial-api"])], provides=[Endpoint("zwave", "zwave-js-ws", "ws://127.0.0.1:{ports.api}")], ports={"api": 3000}, settings=ZwaveNetwork, compose={ # :latest pinned by digest (2026-10-08); bump on purpose "image": "ghcr.io/kpine/zwave-js-server@sha256:19592f8e979525ac6f4e6cac22b28324edfaa757c9d2da3d6fec9c4b2ddd18a8", # noqa: E501 "network_mode": "host", # the image's own command, with a port it doesn't take from the environment; on loopback unless the host # opens its services to the LAN: the server has no authentication, and on the host network it would take # commands from anyone on the LAN "command": [ "server", "/dev/zwave", "--config", "options.js", "--disable-dns-sd", "--host", "{host.listen_address}", "--port", "{ports.api}", ], "userns_mode": "host", # a remapped user can't open the stick on hosts with userns-remap "devices": ["{peripherals.zwave.url}:/dev/zwave"], # our device files take precedence over zwave-js's own (the image's priority dir) "volumes": ["{data}:/cache", f"{Path(__file__).parent / 'device_configs'}:/cache/config:ro"], "environment": { "S0_LEGACY_KEY": "{settings.s0_legacy}", "S2_UNAUTHENTICATED_KEY": "{settings.s2_unauthenticated}", "S2_AUTHENTICATED_KEY": "{settings.s2_authenticated}", "S2_ACCESS_CONTROL_KEY": "{settings.s2_access_control}", "LR_S2_AUTHENTICATED_KEY": "{settings.lr_s2_authenticated}", "LR_S2_ACCESS_CONTROL_KEY": "{settings.lr_s2_access_control}", "RF_REGION": "{platform.region}", }, }, ) ================================================================================ # FILE: majordom_zwave/controller.py ================================================================================ import asyncio import logging import re import time from collections.abc import Callable, Coroutine from typing import Any, ClassVar, override from uuid import UUID from aiohttp import ClientSession from majordom_integration_sdk import ( STABLE_RUN, AbstractController, DeviceUnreachableError, IntegrationError, Need, NoSettings, Platform, ) from majordom_integration_sdk.schemas import DeviceCommand, Discovery, ProvidedCredentials from majordom_integration_sdk.schemas.device import CredentialsType, NonEmptyStr from majordom_integration_sdk.schemas.event import DeviceParameterChange from majordom_integration_sdk.schemas.parameter import ParameterRole, ParameterState from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.const import ( CommandClass, InclusionStrategy, NodeStatus, RemoveNodeReason, SecurityClass, SetValueStatus, ) from zwave_js_server.model.controller import Controller from zwave_js_server.model.controller.inclusion_and_provisioning import InclusionGrant from zwave_js_server.model.node import Node from zwave_js_server.model.value import Value from . import mapper from .model import ( ZwaveDevice, ZwaveDeviceIntegrationData, ZwaveDeviceState, ZwaveParameter, ZwaveParameterIntegrationData, ) log = logging.getLogger(__name__) PIN = re.compile(r"\d{5}") # the S2 PIN: the first 5 digits of the DSK, printed on the device DSK = re.compile(r"\d{5}(-\d{5}){7}") # the full DSK SMART_START_QR = re.compile(r"9001\d+") # a QR code's version digits: 00 is S2, 01 is SmartStart APPLIED = {SetValueStatus.SUCCESS, SetValueStatus.SUCCESS_UNSUPERVISED, SetValueStatus.WORKING} # Security classes that need the device's PIN; granted only when the PIN (or DSK) was given AUTHENTICATED = {SecurityClass.S2_AUTHENTICATED, SecurityClass.S2_ACCESS_CONTROL} S2 = {SecurityClass.S2_UNAUTHENTICATED, *AUTHENTICATED} class _Client(ZwaveClient): """zwave-js-server's client cancels every call still waiting when its connection drops. In the caller (the Hub's task, which nobody cancelled) that cancel would pass by every error handler, the Hub's too: it raises a ConnectionError instead. A cancel of the caller itself stays one.""" @override async def async_send_command(self, message: dict[str, Any], require_schema: int | None = None) -> dict: try: return await super().async_send_command(message, require_schema) except asyncio.CancelledError: if (task := asyncio.current_task()) is not None and task.cancelling(): raise raise ConnectionError("the connection to zwave-js-server was lost") from None class ZwaveController(AbstractController[ZwaveDevice, ZwaveParameter, Any, ZwaveDeviceState]): """Bridges the Hub to Z-Wave devices through zwave-js-server.""" needs = [Need("zwave", ["zwave-js-ws"])] name = "ZWave" RECONNECT_DELAYS: ClassVar[tuple[float, ...]] = (1, 2, 5, 10, 30) # then 30 s between attempts # An outage lasts from the lost connection until a new one held as long as the runtime's stable run, so drops in # a row add up (a connection dropped before the driver was ready is a failed attempt); it is reported once it # lasted this long, on each failure from then on REPORT_OUTAGE_AFTER: ClassVar[float] = 15 STABLE_CONNECTION: ClassVar[float] = STABLE_RUN READY_TIMEOUT: ClassVar[float] = 120 # a device's interview; a sleeping device finishes it when it wakes up EXCLUSION_TIMEOUT: ClassVar[float] = 60 # for the user to put the device into exclusion mode IDENTIFY_BLINKS: ClassVar[int] = 5 IDENTIFY_PERIOD: ClassVar[float] = 0.6 # After an unsupervised set (delivered, not confirmed), zwave-js re-reads some values ~5 s later; past this delay # the value is read back here when it has not changed, so the Hub learns what the device actually did VERIFY_DELAY: ClassVar[float] = 6 def __init__(self, platform: Platform, *, settings: NoSettings | None = None): super().__init__(platform, settings=settings) self._session: ClientSession | None = None self._zwave_client: ZwaveClient | None = None self._supervisor: asyncio.Task | None = None self._first_connection = asyncio.Event() self._tasks: set[asyncio.Task] = set() self._discoveries: dict[UUID, Discovery] = {} self._joined: dict[UUID, Node] = {} # nodes behind the discoveries self._nodes: dict[UUID, Node] = {} # nodes of paired devices self._routes: dict[UUID, dict[str, str | None]] = {} # value id → value id of the parameter it reports self._events: dict[UUID, dict[str, Any]] = {} # event parameters' value ids → their enum labels (or None) self._unsubscribe: dict[UUID, list[Callable[[], None]]] = {} # per paired device self._listeners: list[Callable[[], None]] = [] # on the driver's controller, gone with the connection self._available: dict[UUID, bool] = {} self._credentials: ProvidedCredentials | None = None # of the open pairing window self._closing_window: asyncio.Task | None = None self._is_including = False # an inclusion this run began may still run on the server self._removal: asyncio.Future[int] | None = None # the node id the running exclusion removed self._interviews: set[asyncio.Future[None]] = set() # the ones pairings wait for # ------------------------------------------------------------------------- # AbstractController interface # ------------------------------------------------------------------------- @property def discoveries(self) -> dict[UUID, Discovery]: return self._discoveries @property @override def device_type(self) -> type[ZwaveDevice]: return ZwaveDevice @property @override def device_state_type(self) -> type[ZwaveDeviceState]: return ZwaveDeviceState @property @override def parameter_type(self) -> type[ZwaveParameter]: return ZwaveParameter @property def connected(self) -> bool: return self._zwave_client is not None and self._zwave_client.connected # ------------------------------------------------------------------------- # Lifecycle # ------------------------------------------------------------------------- async def start(self): """Connects to zwave-js-server, and raises when it can't; a connection lost later is reconnected.""" self._session = ClientSession() self._first_connection.clear() url = self.peripherals.endpoint("zwave").url supervisor = self._supervisor = asyncio.create_task(self._run(url, self._session)) connected = asyncio.create_task(self._first_connection.wait()) try: await asyncio.wait({supervisor, connected}, return_when=asyncio.FIRST_COMPLETED) finally: connected.cancel() if supervisor.done(): supervisor.result() # raises why it couldn't connect async def stop(self): await self._end_inclusion_and_exclusion() for task in [self._supervisor, *self._tasks]: if task is not None: task.cancel() await asyncio.gather(*[t for t in [self._supervisor, *self._tasks] if t is not None], return_exceptions=True) self._supervisor = None self._tasks.clear() self._credentials = None self._is_including = False await self._release() if self._session is not None: await self._session.close() self._session = None self._discoveries.clear() self._available.clear() # last, so a pairing or an unpairing waiting on the network resumes with nothing left to take for waiting in [self._removal, *self._interviews]: if waiting is not None and not waiting.done(): waiting.set_exception(ConnectionError("Z-Wave stopped")) async def _end_inclusion_and_exclusion(self): """Ends the inclusion or exclusion this run began, while still connected: zwave-js-server outlives the controller, and would go on including (the next device to join is paired by nobody, the next window doesn't open) or excluding (the next button pressed removes a device).""" if not self.connected: return controller = self._controller() try: async with asyncio.timeout(5): # well within the runtime's time for a stop if self._is_including: await controller.async_stop_inclusion() if self._removal is not None: await controller.async_stop_exclusion() except Exception: # noqa: BLE001 the stop goes on: a server that doesn't answer can't be told log.warning("[STOP] ending the inclusion or exclusion failed", exc_info=True) async def _run(self, url: str, session: ClientSession): attempt = 0 outage_since: float | None = None unreachable = f"zwave-js-server at {url} is unreachable" while True: listening: asyncio.Task | None = None connected_at: float | None = None failing = unreachable try: client = _Client(url, session) await client.connect() ready = asyncio.Event() listening = asyncio.create_task(client.listen(ready)) waiting = asyncio.create_task(ready.wait()) await asyncio.wait({listening, waiting}, return_when=asyncio.FIRST_COMPLETED) waiting.cancel() if listening.done(): listening.result() # raises what made it stop raise ConnectionError("the connection closed before the driver was ready") self._zwave_client = client failing = "Z-Wave failed to start" # the server answered: what fails now is the Hub's side await self._attach() log.info(f"[READY] connected to {url}") await self.output.controller_did_resolve_error(self, "server-unreachable") self._first_connection.set() failing = unreachable connected_at = time.monotonic() await listening raise ConnectionError("the connection to zwave-js-server closed") except Exception as exc: # noqa: BLE001 any failure means: reconnect reason = f"{failing}: {exc or type(exc).__name__}" if not self._first_connection.is_set(): raise ConnectionError(reason) from exc # start() raises it: the runtime starts it again later log.warning(f"[CONNECT] {reason}") now = time.monotonic() if outage_since is None or (connected_at is not None and now - connected_at >= self.STABLE_CONNECTION): outage_since, attempt = now, 0 # a new outage # the devices show unavailable meanwhile try: await self._detach(reason) if now - outage_since >= self.REPORT_OUTAGE_AFTER: error = IntegrationError("server-unreachable", reason) await self.output.controller_did_encounter_error(self, error) except Exception: # noqa: BLE001 the Hub's side failed: reconnect all the same log.exception("[CONNECT] reporting the lost server failed") finally: if listening is not None: listening.cancel() await asyncio.sleep(self.RECONNECT_DELAYS[min(attempt, len(self.RECONNECT_DELAYS) - 1)]) attempt += 1 async def _disconnect(self): client, self._zwave_client = self._zwave_client, None if client is not None and client.connected: try: await client.disconnect() except Exception: # noqa: BLE001 log.debug("[CONNECT] disconnect failed", exc_info=True) async def _attach(self): """Binds the paired devices to the (new) driver's nodes and offers the other nodes as discoveries.""" controller = self._controller() self._available.clear() # report every device's availability afresh self._track(controller.on("node added", lambda data: self._spawn(self._node_added(data["node"], data)))) self._track( controller.on("node removed", lambda data: self._spawn(self._node_removed(data["node"], data["reason"]))) ) self._track( controller.on("grant security classes", lambda data: self._spawn(self._grant(data["requested_grant"]))) ) self._track(controller.on("validate dsk and enter pin", lambda data: self._spawn(self._enter_pin()))) async with self.platform.device_repository(self) as repo: devices = [d for d in await repo.get_all(as_=ZwaveDevice) if d.integration_data is not None] claimed: set[int] = set() for device in devices: data = device.integration_data assert data is not None node = controller.nodes.get(data.node_id) if data.home_id == controller.home_id else None if data.home_id == controller.home_id: claimed.add(data.node_id) # its id is taken even when another device now has the node if node is None: await self._set_available(device.physical_id, False, "The device is no longer on this Z-Wave network") elif data.fingerprint and (found := self._fingerprint(node)) and found != data.fingerprint: reason = f"Node {data.node_id} is now another device ({found}): pair that one anew" await self._set_available(device.physical_id, False, reason) else: events = { p.integration_data.value_id: p.valid_values for p in device.parameters if p.integration_data.value_id not in node.values # an event parameter (of a notification) } self._bind(device.physical_id, node, events) await self._update_availability(device.physical_id, node) if node.status != NodeStatus.DEAD: await self._report_snapshot(device.physical_id, node) for node in controller.nodes.values(): # on the network, not paired (yet): offered for pairing if node.node_id != controller.own_node_id and node.node_id not in claimed: await self._offer(node) async def _detach(self, reason: str): devices = list(self._nodes) await self._release() lost = "The connection to zwave-js-server was lost: pair the device again" for waiting in self._interviews: # on the lost connection's nodes, which never hear the interview end if not waiting.done(): waiting.set_exception(ConnectionError(lost)) for physical_id in devices: await self._set_available(physical_id, False, reason) async def _release(self): """Lets go of the connection and everything bound to it, silently.""" for physical_id in list(self._nodes): self._unbind(physical_id) for unsubscribe in self._listeners: unsubscribe() self._listeners.clear() self._joined.clear() await self._disconnect() # ------------------------------------------------------------------------- # Hub -> device operations # ------------------------------------------------------------------------- async def start_pairing_window(self, duration_sec: int, credentials: ProvidedCredentials | None = None): controller = self._controller() connection = self._zwave_client # the run token: a window opened across a stop gets no closing task kind = credentials.type if credentials else CredentialsType.none value = (credentials.value if credentials else None) or "" if kind == CredentialsType.secret: raise ValueError("Z-Wave devices are paired with their PIN, DSK or QR code, not a secret") if kind == CredentialsType.code and not DSK.fullmatch(value) and not PIN.fullmatch(value): raise ValueError("The PIN is the first 5 digits of the device's DSK (or give the whole DSK)") if kind == CredentialsType.qr and SMART_START_QR.fullmatch(value): # SmartStart: no window to open. zwave-js keeps the device on its provisioning list and includes it, # securely, whenever it is powered on — hours later, after installation; it then joins as a discovery await controller.async_provision_smart_start_node(value) log.debug("[PAIRING] SmartStart device provisioned: it joins when powered on") return self._credentials = credentials # before inclusion starts: a device can ask for its grant right away self._is_including = True # before too: a stop() meanwhile ends it try: if kind == CredentialsType.qr: # a malformed code is rejected here (ValueError); the server parses the rest await controller.async_begin_inclusion(InclusionStrategy.SECURITY_S2, provisioning=value) elif kind == CredentialsType.code and DSK.fullmatch(value): await controller.async_begin_inclusion(InclusionStrategy.SECURITY_S2, dsk=value) elif kind == CredentialsType.code: await controller.async_begin_inclusion(InclusionStrategy.SECURITY_S2) # the PIN is entered when asked else: await controller.async_begin_inclusion(InclusionStrategy.DEFAULT) except Exception: self._credentials = None raise if self._zwave_client is not connection: # stop() ended the inclusion meanwhile raise ConnectionError("Z-Wave stopped while opening the pairing window") log.debug(f"[PAIRING] inclusion window opened for {duration_sec}s ({kind})") if self._closing_window is not None: self._closing_window.cancel() self._closing_window = self._spawn(self._close_pairing_window(duration_sec)) async def pair_device( self, discovery: Discovery, draft: ZwaveDeviceState, credentials: ProvidedCredentials | None ) -> ZwaveDeviceState: known = self._discoveries.get(discovery.id) node = self._joined.get(discovery.id) if known is None or node is None: raise ValueError("Unknown device: it is no longer discovered") draft.physical_id = self._physical_id(node) await self.check_device_id(draft.physical_id, draft) connection = self._zwave_client # the run token: the node is this connection's try: if credentials is not None and credentials.type != CredentialsType.none: raise ValueError("Z-Wave credentials are given when opening the pairing window") await self._wait_until_ready(node) events = mapper.event_parameters(node, await self._supported_notification_events(node)) parameters = self._build_parameters(draft.physical_id, node, events) main = mapper.main_value(node) main_id = self._parameter_id(draft.physical_id, main[0].value_id) if main else None for parameter in parameters: if main and parameter.id == main_id: parameter.default_value = main[1] if self._zwave_client is not connection: # Stopped, restarted or reconnected meanwhile: refused, and the next connection offers the node again raise ConnectionError("Z-Wave stopped or lost zwave-js-server while pairing: pair the device again") schema = "\n\t".join( f"{p.role:8} {p.visibility:8} {p.data_type:8} {p.name} ({p.integration_data.value_id})" for p in parameters ) log.debug(f"[PAIR] node_id={node.node_id} mapped schema\n\t{schema}") except Exception as exc: log.warning(f"[PAIR] pairing {discovery.id} failed: {exc}") if discovery.id in self._discoveries: # not lost meanwhile, nor gone with a stop failed = known.model_copy(update={"last_error": str(exc)}) self._discoveries[discovery.id] = failed await self.output.controller_did_update_discovery(self, failed) raise # The node is bound, and the discovery given up, by fetch: the Hub has saved the device by then, so no value # reaches it before the device exists return draft.model_copy( update={ "parameters": parameters, "main_parameter": main_id if any(p.id == main_id and p.can_be_main_parameter for p in parameters) else None, "available": True, "last_error": None, "integration_data": ZwaveDeviceIntegrationData( home_id=self._controller().home_id or 0, node_id=node.node_id, fingerprint=self._fingerprint(node), dsk=node.dsk, ), } ) async def unpair(self, device: ZwaveDevice | ZwaveDeviceState): """The user's unpair only. A failed or unsaved pairing needs no undo: pairing here changes nothing on the network (the device joined before it), and its discovery stays offered until fetch, so it is retried as is.""" controller = self._controller() if device.integration_data is None: log.debug(f"[UNPAIR] {device.physical_id} was never paired: nothing to remove") self._unbind(device.physical_id) return node = self._nodes.get(device.physical_id) if node is None: # not on the network anymore: only a SmartStart entry may be left, it would join again data = device.integration_data if data.dsk and await controller.async_get_provisioning_entry(data.dsk): await controller.async_unprovision_smart_start_node(data.dsk) self._unbind(device.physical_id) return # A SmartStart device stays provisioned unless removed from the list: it would join again when powered on provisioning = await controller.async_get_provisioning_entry(node.node_id) if failed := await controller.async_is_failed_node(node): await controller.async_remove_failed_node(node) else: # A live node leaves only when the device itself confirms (its button, per the manufacturer) await self._update_device(device.physical_id, last_error="Put the device into exclusion mode to remove it") self._removal = asyncio.get_running_loop().create_future() try: await controller.async_begin_exclusion() removed = await asyncio.wait_for(self._removal, self.EXCLUSION_TIMEOUT) except TimeoutError: reason = "The device was not put into exclusion mode in time: it is still on the network" await self._update_device(device.physical_id, last_error=reason) raise TimeoutError(reason) from None except Exception: await self._update_device(device.physical_id, last_error=None) # no longer waiting for the device raise finally: self._removal = None try: await controller.async_stop_exclusion() except Exception: # noqa: BLE001 already stopped by the removal log.debug("[UNPAIR] stop exclusion failed", exc_info=True) if removed != node.node_id: reason = f"another device (node {removed}) was excluded instead: it left the network" await self._update_device(device.physical_id, last_error=f"Not removed: {reason}") raise LookupError(reason) if provisioning is not None: await controller.async_unprovision_smart_start_node(provisioning.dsk) self._unbind(device.physical_id) self._available.pop(device.physical_id, None) if failed: # it still believes it is included: it must be excluded or reset before it joins again raise DeviceUnreachableError(f"Node {node.node_id} is unreachable to exclude") async def identify(self, device: ZwaveDevice): node = self._require_node(device) indicator = next( # Indicator CC v3 "identify": the device's own identify pattern, cross-vendor ( v for v in node.values.values() if v.command_class == CommandClass.INDICATOR and v.property_ == "identify" ), None, ) if indicator is not None: await node.async_set_value(indicator, True) log.debug(f"[IDENTIFY] node_id={node.node_id} via Indicator CC") return if any(v.command_class == CommandClass.SWITCH_COLOR for v in node.values.values()): await self._blink(node) # a light: blinking it is harmless, unlike toggling a relay's load return log.info(f"[IDENTIFY] node_id={node.node_id} has no identify indicator and is not a light: nothing to show") async def _blink(self, node: Node): level = next( ( v for v in node.values.values() if v.command_class == CommandClass.SWITCH_MULTILEVEL and v.property_ == "targetValue" ), None, ) if level is None: return current = node.values.get(level.value_id.replace("targetValue", "currentValue")) restore = current.value if current is not None and isinstance(current.value, int) else 0 for _ in range(self.IDENTIFY_BLINKS): await node.async_set_value(level, 99 if restore == 0 else 0) await asyncio.sleep(self.IDENTIFY_PERIOD) await node.async_set_value(level, restore) await asyncio.sleep(self.IDENTIFY_PERIOD) log.debug(f"[IDENTIFY] node_id={node.node_id} blinked") async def fetch(self, device: ZwaveDevice): node = self._nodes.get(device.physical_id) or self._adoptable(device) if node is None: raise ConnectionError(f"Device {device.name} is not connected") if device.physical_id not in self._unsubscribe: # just paired or its subscription is gone: never twice self._available.setdefault(device.physical_id, device.available) # the Hub's own record of it self._joined.pop(device.physical_id, None) self._discoveries.pop(device.physical_id, None) events = { p.integration_data.value_id: p.valid_values for p in device.parameters if p.integration_data.value_id not in node.values # an event parameter (of a notification) } self._bind(device.physical_id, node, events) await self._update_availability(device.physical_id, node) if node.status != NodeStatus.DEAD: # a sleeping node answers from what it last reported await self._report_snapshot(device.physical_id, node) async def send_command(self, command: DeviceCommand, device: ZwaveDevice, parameter: ZwaveParameter): node = self._nodes.get(device.physical_id) if node is None: reason = f"{parameter.name} could not be set: the device is not connected" await self._update_device(device.physical_id, last_error=reason) raise ConnectionError(reason) value = node.values.get(parameter.integration_data.value_id) if value is None: raise ValueError(f"{parameter.name} is not a value of this device") if not value.metadata.writeable: raise ValueError(f"{parameter.name} is read-only") awake = node.status != NodeStatus.ASLEEP # a sleeping device gets the command when it wakes up try: result = await node.async_set_value(value, mapper.to_device(value, command.value), wait_for_result=awake) except Exception as exc: reason = f"{parameter.name} could not be set: {exc or type(exc).__name__}" await self._update_device(device.physical_id, last_error=reason) raise ConnectionError(reason) from exc if awake and (result is None or result.status not in APPLIED): reason = f"{parameter.name} could not be set: the device refused it ({result})" await self._update_device(device.physical_id, last_error=reason) raise RuntimeError(reason) # no echo: the device's report (or zwave-js's verification of it) comes back as "value updated" await self._update_device(device.physical_id, last_error=None) if awake and result is not None and result.status == SetValueStatus.SUCCESS_UNSUPERVISED: state = node.values.get(parameter.integration_data.state_value_id or value.value_id, value) self._spawn(self._verify(node, value, state, mapper.to_device(value, command.value))) async def _verify(self, node: Node, value: Value, state: Value, sent: Any): """After an unconfirmed set: sends it again over a renewed S2 session when the old one is dead, or reads the value back unless zwave-js already did (its value then is the sent one).""" await asyncio.sleep(self.VERIFY_DELAY) if node.status == NodeStatus.DEAD: return if node.highest_security_class in S2 and not await self._answers_securely(node): # A device that lost power can keep a dead S2 session and never ask for a new one (seen on a Shelly # Wave): it takes commands without acting on them, and zwave-js reports them applied. A nonce from the # controller starts a new session log.info(f"[S2] node_id={node.node_id} doesn't answer securely: renewing its session") await node.async_invoke_cc_api(CommandClass.SECURITY_2, "sendNonce") await node.async_set_value(value, sent) elif state.metadata.readable and state.value != sent: await node.async_poll_value(state) @staticmethod async def _answers_securely(node: Node) -> bool: try: supported = await node.async_invoke_cc_api( CommandClass.SECURITY_2, "getSupportedCommands", node.highest_security_class ) except Exception: # noqa: BLE001 no answer, however zwave-js puts it return False return supported is not None # ========================================================================= # Private helpers # ========================================================================= def _controller(self) -> Controller: if self._zwave_client is None or self._zwave_client.driver is None: raise ConnectionError("Not connected to zwave-js-server") return self._zwave_client.driver.controller def _spawn(self, coro: Coroutine[Any, Any, Any]) -> asyncio.Task: """Runs a handler in the background; its failure is logged, never lost or raised into the library.""" task = asyncio.create_task(coro) self._tasks.add(task) task.add_done_callback(self._done) return task def _done(self, task: asyncio.Task): self._tasks.discard(task) if not task.cancelled() and (exc := task.exception()) is not None: log.error(f"[TASK] {task.get_coro()} failed", exc_info=exc) def _track(self, unsubscribe: Callable[[], None]): self._listeners.append(unsubscribe) def _require_node(self, device: ZwaveDevice) -> Node: node = self._nodes.get(device.physical_id) if node is None: raise ConnectionError(f"Device {device.name} is not connected") return node def _adoptable(self, device: ZwaveDevice) -> Node | None: """The node a just paired device (not bound yet) is on: the one it was offered as.""" node = self._joined.get(device.physical_id) data = device.integration_data if node is None and data is not None and data.home_id == self._controller().home_id: node = self._controller().nodes.get(data.node_id) return node def _parameter_id(self, physical_id: UUID, value_id: str) -> UUID: return self.parameter_uuid(physical_id, value_id, strip="") # '-' separates the parts of a value id @staticmethod def _fingerprint(node: Node) -> str | None: ids = (node.manufacturer_id, node.product_type, node.product_id) return ":".join(f"{i:04x}" for i in ids) if all(i is not None for i in ids) else None async def _update_device(self, physical_id: UUID, **changes: Any): async with self.platform.device_repository(self) as repo: device = await repo.get(physical_id=physical_id, as_=ZwaveDevice) if device is not None and any(getattr(device, k) != v for k, v in changes.items()): await repo.save(device.model_copy(update=changes)) # ------------------------------------------------------------------------- # Pairing # ------------------------------------------------------------------------- def _physical_id(self, node: Node) -> UUID: return self.device_uuid(f"{self._controller().home_id or 0:08x}-{node.node_id}") async def _offer(self, node: Node, low_security: bool = False): physical_id = self._physical_id(node) self._joined[physical_id] = node if physical_id in self._discoveries: return discovery = Discovery( id=physical_id, integration=NonEmptyStr(self.key), expected_credentials_options=[CredentialsType.none], expiration=None, transport=NonEmptyStr("ZWAVE"), device_manufacturer=None, device_name=NonEmptyStr(node.name or node.device_config.description or f"Z-Wave node {node.node_id}"), device_category=None, device_icon=None, last_error=( "Joined without S2 authentication: open the pairing window with the device's PIN to include it securely" if low_security else None ), ) self._discoveries[physical_id] = discovery log.debug(f"[DISCOVERY] node_id={node.node_id} discovery_id={physical_id}") await self.output.controller_did_receive_discovery(self, discovery) async def _close_pairing_window(self, duration_sec: int): await asyncio.sleep(duration_sec) self._credentials = None controller = self._controller() await controller.async_stop_inclusion() self._is_including = False log.debug("[PAIRING] inclusion window closed") # Joined but never paired: a node that failed is removed (it can't be paired anymore); a live one stays a # discovery: it is a real Z-Wave node, and the user must still be able to pair or remove it for node in list(self._joined.values()): if await controller.async_is_failed_node(node): await controller.async_remove_failed_node(node) log.debug(f"[PAIRING] node_id={node.node_id} removed after failing before it was paired") async def _wait_until_ready(self, node: Node): """Waits for the interview that fills node.values.""" if not node.ready: await self._wait_for(node, "ready") if node.manufacturer_id is None and CommandClass.MANUFACTURER_SPECIFIC in { cc.id for cc in node.command_classes }: # It didn't answer in time (seen right after S2 bootstrapping). Without its identity zwave-js loads no # device file for it (parameter definitions, fixes), and a reused node id can't be told apart log.debug(f"[PAIR] node_id={node.node_id} interviewed again: its identity is missing") await node.async_refresh_info() await self._wait_for(node, "ready") # carries the node's state; "interview completed" doesn't async def _wait_for(self, node: Node, event: str): happened: asyncio.Future[None] = asyncio.get_running_loop().create_future() unsubscribe = node.on(event, lambda _: happened.done() or happened.set_result(None)) self._interviews.add(happened) try: await asyncio.wait_for(happened, self.READY_TIMEOUT) except TimeoutError: raise TimeoutError( "The device did not finish its interview: wake it up (or move it closer) and pair it again" ) from None finally: self._interviews.discard(happened) unsubscribe() async def _supported_notification_events(self, node: Node) -> list[dict[str, Any]]: """The keypad and Notification CC events the node supports, as zwave-js knows them from its interview.""" client = self._controller().client # raises when the connection is gone try: result = await client.async_send_command( {"command": "node.get_supported_notification_events", "nodeId": node.node_id}, require_schema=43 ) except Exception: # noqa: BLE001 an older server: no keypad or Notification CC event parameters log.warning(f"[PAIR] node_id={node.node_id}: supported notification events unknown", exc_info=True) return [] return result.get("events", []) def _build_parameters( self, physical_id: UUID, node: Node, events: list[mapper.EventParameter] ) -> list[ParameterState[ZwaveParameterIntegrationData]]: """The device's parameters; their values reach the Hub as events (the snapshot after pairing).""" parameters: list[ParameterState[ZwaveParameterIntegrationData]] = [] pairs = mapper.parameter_values(node) for (value, state), name in zip(pairs, mapper.names(pairs), strict=True): low, high, step = mapper.limits(value) parameters.append( ParameterState[ZwaveParameterIntegrationData]( id=self._parameter_id(physical_id, value.value_id), name=name, data_type=mapper.data_type(value), role=mapper.role(value), visibility=mapper.visibility(value, node), min_value=low, max_value=high, min_step=step, unit=mapper.unit(value), valid_values=mapper.valid_values(value), integration_data=ZwaveParameterIntegrationData( value_id=value.value_id, state_value_id=state.value_id if state else None ), ) ) parameters += [ ParameterState[ZwaveParameterIntegrationData]( id=self._parameter_id(physical_id, event.value_id), name=event.name, data_type=event.data_type, role=ParameterRole.event, visibility=event.visibility, unit=event.unit, valid_values=event.valid_values, integration_data=ZwaveParameterIntegrationData(value_id=event.value_id), ) for event in events ] return parameters async def _grant(self, requested: InclusionGrant): """Grants what the joining device requested, except what needs a PIN nobody gave: then it joins with less security, and says so, instead of waiting for a PIN that never comes.""" classes = requested.security_classes if self._credentials is None: classes = [c for c in classes if c not in AUTHENTICATED] grant = InclusionGrant(security_classes=classes, client_side_auth=requested.client_side_auth) await self._controller().async_grant_security_classes(grant) log.debug(f"[S2] granted {classes} of {requested.security_classes}") async def _enter_pin(self): credentials = self._credentials if credentials is None or credentials.type != CredentialsType.code or not credentials.value: log.warning("[S2] the device asks for its PIN, but none was given") return await self._controller().async_validate_dsk_and_enter_pin(credentials.value[:5]) # ------------------------------------------------------------------------- # Device <-> Hub: Z-Wave network events & availability # ------------------------------------------------------------------------- async def _node_added(self, node: Node, data: dict): log.debug(f"[JOIN] node_id={node.node_id}") result = data.get("result") or {} await self._offer(node, low_security=bool(result.get("lowSecurity"))) async def _node_removed(self, node: Node, reason: RemoveNodeReason): log.debug(f"[REMOVED] node_id={node.node_id} ({reason})") controller = self._controller() if reason == RemoveNodeReason.RESET and node.dsk and await controller.async_get_provisioning_entry(node.dsk): # a factory reset means leaving: on the SmartStart list, it would join again the moment it starts await controller.async_unprovision_smart_start_node(node.dsk) if self._removal is not None and not self._removal.done(): self._removal.set_result(node.node_id) for physical_id, joined in list(self._joined.items()): if joined.node_id == node.node_id: self._joined.pop(physical_id) if self._discoveries.pop(physical_id, None) is not None: await self.output.controller_did_lose_discovery(self, physical_id) for physical_id, bound in list(self._nodes.items()): if bound.node_id == node.node_id: self._unbind(physical_id) await self._set_available(physical_id, False, "The device was removed from the Z-Wave network") def _bind(self, physical_id: UUID, node: Node, events: dict[str, Any]): self._unbind(physical_id) self._nodes[physical_id] = node self._routes[physical_id] = mapper.reported_parameters(node) self._events[physical_id] = events self._unsubscribe[physical_id] = [ node.on("notification", lambda data: self._spawn(self._notified(physical_id, data["notification"]))), node.on("value updated", lambda data: self._spawn(self._value_updated(physical_id, data["value"]))), node.on( "value notification", lambda data: self._spawn(self._value_updated(physical_id, data["value_notification"])), ), node.on("dead", lambda _: self._spawn(self._update_availability(physical_id, node))), node.on("alive", lambda _: self._spawn(self._update_availability(physical_id, node))), ] def _unbind(self, physical_id: UUID): self._nodes.pop(physical_id, None) self._routes.pop(physical_id, None) self._events.pop(physical_id, None) for unsubscribe in self._unsubscribe.pop(physical_id, []): unsubscribe() async def _update_availability(self, physical_id: UUID, node: Node): dead = node.status == NodeStatus.DEAD await self._set_available(physical_id, not dead, "The device does not respond" if dead else None) async def _set_available(self, physical_id: UUID, available: bool, reason: str | None = None): """Reports a change of availability (with its reason as the device's last error).""" if self._available.get(physical_id) == available: if not available and reason: # a better reason for the same state (not answering, then removed) await self._update_device(physical_id, last_error=reason) return self._available[physical_id] = available await self._update_device(physical_id, available=available, last_error=None if available else reason) if available: await self.output.controller_did_connect_device(self, physical_id=physical_id) else: await self.output.controller_did_lose_device(self, physical_id=physical_id) async def _value_updated(self, physical_id: UUID, value: Value): routes = self._routes.get(physical_id, {}) parameter_value_id = routes.get(value.value_id, value.value_id) if parameter_value_id is None: # a target: the state is its current value return if value.value_id not in routes: # appeared after pairing: no parameter for it log.debug(f"[VALUE] {value.value_id} has no parameter") return event = DeviceParameterChange( physical_id=physical_id, parameter_id=self._parameter_id(physical_id, parameter_value_id), value=mapper.to_hub(value, value.value), ) await self.output.controller_did_receive_events(self, [event]) async def _notified(self, physical_id: UUID, notification: Any): known = self._events.get(physical_id, {}) changes = [] for value_id, value in mapper.notification_events(notification): if value_id not in known or (known[value_id] and value not in known[value_id]): log.debug(f"[EVENT] {value_id}={value!r}: not an event the device announced") continue parameter_id = self._parameter_id(physical_id, value_id) changes.append(DeviceParameterChange(physical_id=physical_id, parameter_id=parameter_id, value=value)) if changes: await self.output.controller_did_receive_events(self, changes) async def _report_snapshot(self, physical_id: UUID, node: Node): events = [ DeviceParameterChange( physical_id=physical_id, parameter_id=self._parameter_id(physical_id, value.value_id), value=mapper.to_hub(state or value, (state or value).value), ) for value, state in mapper.parameter_values(node) if mapper.role(value) != ParameterRole.event and (value.metadata.readable or state is not None) ] if events: await self.output.controller_did_receive_events(self, events) ================================================================================ # FILE: majordom_zwave/device_configs/0x0460/qnsw-001X16.json ================================================================================ // MajorDom override of zwave-js's file (taken from its priority dir): Shelly confirmed that firmware <= 10.13 and // 11.6-12.1 take parameter 120 as 4 bytes and reset only on 0x55555555 (the 1-byte value 1 is refused). // Remove once zwave-js ships #9364/#9425 and the zwave-js-server image digest is bumped. // Based on zwave-js (https://github.com/zwave-js/zwave-js), Copyright (c) 2018-2024 AlCalzone, MIT License. { "manufacturer": "Shelly Europe Ltd.", "manufacturerId": "0x0460", "label": "QNSW-001X16", "description": "Wave 1", "devices": [ { "productType": "0x0002", "productId": "0x0083", "zwaveAllianceId": [4922, 5005, 5020] } ], "firmwareVersion": { "min": "0.0", "max": "255.255" }, "associations": { "1": { "label": "Lifeline", "maxNodes": 9, "isLifeline": true }, "2": { "label": "SW1: On/Off", "maxNodes": 9 }, "3": { "label": "SW1: Start/Stop Level Change", "maxNodes": 9 } }, "paramInformation": [ { "#": "1", "$import": "~/0x0460/templates/wave_template.json#switch_type", "label": "SW1 Switch Type" }, { "#": "7", "$if": "firmwareVersion >= 13.0", "$import": "~/0x0460/templates/wave_template.json#detached_mode", "label": "Detach O Output" }, { "#": "17", "$import": "~/templates/master_template.json#state_after_power_failure_prev_off", "label": "O1: State After Power Failure" }, { "#": "19", "$import": "~/0x0460/templates/wave_template.json#auto_off_timer", "label": "O1: Auto-Off Timer" }, { "#": "20", "$import": "~/0x0460/templates/wave_template.json#auto_on_timer", "label": "O1: Auto-On Timer" }, { "#": "25", "$import": "~/0x0460/templates/wave_template.json#timer_unit", "label": "O1: Auto-On/Off Timer Unit" }, { "#": "23", "$import": "~/0x0460/templates/wave_template.json#out_relay_type", "label": "O1: Relay Type" }, { "#": "91", "$if": "firmwareVersion < 13.0", "$import": "~/0x0460/templates/wave_template.json#alarm_configuration", "label": "Alarm Configuration: Water" }, { "#": "92", "$if": "firmwareVersion < 13.0", "$import": "~/0x0460/templates/wave_template.json#alarm_configuration", "label": "Alarm Configuration: Smoke" }, { "#": "93", "$if": "firmwareVersion < 13.0", "$import": "~/0x0460/templates/wave_template.json#alarm_configuration", "label": "Alarm Configuration: CO" }, { "#": "94", "$if": "firmwareVersion < 13.0", "$import": "~/0x0460/templates/wave_template.json#alarm_configuration", "label": "Alarm Configuration: Heat" }, { "#": "120", "$if": "firmwareVersion <= 10.13 || firmwareVersion >= 11.6 && firmwareVersion <= 12.1", // Inlined #factory_reset_4_bytes of #9425, which the pinned zwave-js does not ship yet "$import": "~/0x0460/templates/wave_template.json#factory_reset", "valueSize": 4, "options": [ { "label": "Idle", "value": 0 }, { "label": "Factory reset", "value": 1431655765 } ] }, { "#": "120", "$import": "~/0x0460/templates/wave_template.json#factory_reset" }, { "#": "201", "$import": "~/0x0460/templates/wave_template.json#serial_number", "label": "Serial Number: Part 1" }, { "#": "202", "$import": "~/0x0460/templates/wave_template.json#serial_number", "label": "Serial Number: Part 2" }, { "#": "203", "$import": "~/0x0460/templates/wave_template.json#serial_number", "label": "Serial Number: Part 3" } ], "metadata": { "$import": "~/0x0460/templates/wave_template.json#default_metadata" } } ================================================================================ # FILE: majordom_zwave/mapper.py ================================================================================ """Z-Wave values → MajorDom parameters, and value conversion both ways. A parameter is one Z-Wave value, except for current/target pairs (`currentValue`/`targetValue`, `currentMode`/`targetMode`, ...): those are one parameter, commanded through the target and reporting the current one, so the user sees one switch rather than a "Current value" sensor next to a "Target value" control. """ import json import logging import re from collections import Counter from dataclasses import dataclass from typing import Any from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from zwave_js_server.const import CommandClass from zwave_js_server.const.command_class.multilevel_switch import MultilevelSwitchCommand from zwave_js_server.model.duration import Duration from zwave_js_server.model.node import Node from zwave_js_server.model.notification import ( BatteryNotification, EntryControlNotification, MultilevelSwitchNotification, NotificationNotification, PowerLevelNotification, ) from zwave_js_server.model.value import AllowedRangeValue, Value, ValueType from .zwave_spec import ( CONVERTED_UNITS, DECIMAL_COMMAND_CLASSES, DIAGNOSTIC_COMMAND_CLASSES, EVENT_COMMAND_CLASSES, LEVEL_COMMAND_CLASSES, LEVEL_PROPERTIES, MAIN_VALUE_BY_COMMAND_CLASS, METER_QUANTITIES, NOTIFICATION_SETTING_VARIABLES, NOTIFICATION_SHARED_VARIABLES, NUMERIC_VALUES, PLAIN_UNITS, REVIEWED_COMMAND_CLASSES, SETTING_VALUES, SYSTEM_COMMAND_CLASSES, SYSTEM_VALUES, UNIT_MAP, USER_VALUES, VALUE_NAMES, VALUE_UNITS, ) log = logging.getLogger(__name__) # zwave-js's value metadata types (ValueType in @zwave-js/core); test_catalogue fails when it gains one KNOWN_VALUE_TYPES = frozenset( { "number", "boolean", "string", "number[]", "boolean[]", "string[]", "duration", "timeout", "color", "buffer", "any", } ) def parameter_values(node: Node) -> list[tuple[Value, Value | None]]: """(value commanded and identifying the parameter, value its state comes from when another one) per parameter.""" states = {target.value_id: current for target in node.values.values() if (current := _current_of(node, target))} merged = {current.value_id for current in states.values()} return [(value, states.get(value.value_id)) for value in node.values.values() if value.value_id not in merged] def reported_parameters(node: Node) -> dict[str, str | None]: """Value id → the value id of the parameter it reports, None for a target whose state comes from its current.""" routes: dict[str, str | None] = {} for value, state in parameter_values(node): routes[value.value_id] = None if state else value.value_id if state: routes[state.value_id] = value.value_id return routes def _current_of(node: Node, target: Value) -> Value | None: prop = target.property_ if not isinstance(prop, str) or not prop.startswith("target") or prop == "target": return None current = f"current{prop.removeprefix('target')}" return next( ( v for v in node.values.values() if v.command_class == target.command_class and v.endpoint == target.endpoint and v.property_ == current and v.property_key == target.property_key ), None, ) def _sentence(text: str) -> str: """'Warm White' → 'Warm white': the words after the first in lower case, acronyms (CO, RGB) as they are.""" first, *rest = text.split(" ") return " ".join([first, *(word if sum(c.isupper() for c in word) > 1 else word.lower() for word in rest)]) def _readable(text: str) -> str: """A camelCase word ("wakeUpInterval", "UnsecuredWithTimeout") → words; anything else as it is.""" if " " in text or not re.search(r"[a-z][A-Z]", text): return text words = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[a-z])(?=[0-9])", " ", text) return _sentence(words[0].upper() + words[1:]) def _clean(label: str) -> str: """zwave-js labels written for its UI or logs → a parameter's name.""" if match := re.fullmatch(r"Sensor state \((.+)\)", label): # Binary Sensor: "Sensor state (Motion)" return _sentence(match[1]) if label == "Reset accumulated values": # Meter: every scale's reset at once return "Reset all meters" if match := re.fullmatch(r"Setpoint \((.+)\)", label): # "Setpoint (Heating)" return f"{match[1]} setpoint" if match := re.fullmatch(r"(Reset )?(.+) Consumption \[(.+)\]", label): # Meter: "Electric Consumption [kWh]" reset, meter, scale = match.groups() named = f"{meter} {METER_QUANTITIES.get(scale, scale)}" return f"Reset {named.lower()}" if reset else named if match := re.fullmatch(r"(.+) - (.+)", label): # Window Covering: "Open - Outbound Bottom" return f"{_sentence(match[2])}: {match[1][0].lower()}{match[1][1:]}" if match := re.fullmatch(r"Scene 0*(\d+)", label): # Central Scene: "Scene 001" return f"Scene {match[1]}" if match := re.fullmatch(r"Signaling State \((.+)\)", label): # Barrier Operator: "Signaling State (Audible)" return f"{match[1]} warning" return _sentence(_readable(label)) def name(value: Value, state: Value | None) -> str: key = value.property_key_name or ("" if value.property_key is None else str(value.property_key)) template = VALUE_NAMES.get((value.command_class, value.property_, value.property_key)) or VALUE_NAMES.get( (value.command_class, value.property_) ) if template is not None and "{key}" in template and not key: # the CC's keyless value (all channels at once) template = None label = value.metadata.label or value.property_name or str(value.property_) variable = _notification_variable(value) if template is not None: base = template.format(key=_sentence(key), label=_clean(label)) elif state: # a pair with no name of its own: named by its CC base = value.command_class_name elif variable and variable[1] in NOTIFICATION_SHARED_VARIABLES: # "Sensor status": of which notification type base = f"{variable[1]} ({_sentence(variable[0])})" else: base = _clean(label) return f"{base} {value.endpoint}" if value.endpoint else base def names(pairs: list[tuple[Value, Value | None]]) -> list[str]: """Each parameter's name. A name several values share gets what tells them apart: a Notification variable its notification type ("Sensor status (Smoke Alarm)"), anything else its CC ("Remaining duration (Color Switch)").""" plain = [name(value, state) for value, state in pairs] shared = {n for n, count in Counter(plain).items() if count > 1} return [f"{n} ({_context(value)})" if n in shared else n for n, (value, _) in zip(plain, pairs, strict=True)] def _notification_variable(value: Value) -> tuple[str, str] | None: """A Notification CC state's (notification type, variable): zwave-js's property and property key.""" kind, variable = value.property_, value.property_key if value.command_class != CommandClass.NOTIFICATION or not isinstance(kind, str) or not isinstance(variable, str): return None return kind, variable def _context(value: Value) -> str: variable = _notification_variable(value) return _sentence(variable[0]) if variable else value.command_class_name def _is_level(value: Value) -> bool: return value.command_class in LEVEL_COMMAND_CLASSES and value.property_ in LEVEL_PROPERTIES def _is_duration(value: Value) -> bool: # zwave-js-server-python's ValueType has no "duration": it is told by the metadata type string (not by the # property's name: an Alarm Sensor's "duration" is a number of seconds) return value.metadata.type == "duration" def _is_button(value: Value) -> bool: """A write-only action ("Reset", "Identify", "Restore previous value"): its only state is `true`, the trigger. Start/stop pairs (`true`/`false`, like "Up"/"Down" dimming) stay booleans.""" metadata = value.metadata return ( metadata.type == ValueType.BOOLEAN and bool(metadata.writeable) and not metadata.readable and set(metadata.states or {}) <= {"true"} ) def data_type(value: Value) -> ParameterDataType: metadata = value.metadata kind = metadata.type if kind not in KNOWN_VALUE_TYPES: log.warning(f"[MAP] {value.value_id} has the unknown value type {kind!r}: hidden as data") return ParameterDataType.data if _is_button(value): return ParameterDataType.none if kind == ValueType.BOOLEAN: return ParameterDataType.bool if kind in ("string", "string[]", "color", "timeout") or _is_duration(value): # a list of strings: as text return ParameterDataType.string if kind in ("number[]", "boolean[]", "buffer"): return ParameterDataType.data if kind == ValueType.NUMBER: if _is_level(value) or (value.command_class, value.property_) in NUMERIC_VALUES: return ParameterDataType.integer if metadata.states and not metadata.allow_manual_entry: return ParameterDataType.enum return ( ParameterDataType.decimal if value.command_class in DECIMAL_COMMAND_CLASSES else ParameterDataType.integer ) raw = value.value # ValueType.ANY: only the value itself tells if isinstance(raw, bool): return ParameterDataType.bool if isinstance(raw, int): return ParameterDataType.integer if isinstance(raw, float): return ParameterDataType.decimal if isinstance(raw, str): return ParameterDataType.string return ParameterDataType.data # an opaque CC-specific object: exposed as data rather than a guessed shape def role(value: Value) -> ParameterRole: if value.metadata.stateful is False or (value.command_class in EVENT_COMMAND_CLASSES and not _is_setting(value)): return ParameterRole.event return ParameterRole.control if value.metadata.writeable else ParameterRole.sensor def _is_setting(value: Value) -> bool: variable = _notification_variable(value) if variable and variable[1] in NOTIFICATION_SETTING_VARIABLES: # a diagnostic, like "Maintenance status" return True properties = SETTING_VALUES.get(value.command_class, frozenset()) return properties is None or value.property_ in properties def _is_user(value: Value) -> bool: properties = USER_VALUES.get(value.command_class, frozenset()) return properties is None or value.property_ in properties def visibility(value: Value, node: Node) -> ParameterVisibility: command_class = value.command_class if ( command_class in SYSTEM_COMMAND_CLASSES or (command_class, value.property_) in SYSTEM_VALUES or value.metadata.secret or _is_duration(value) or data_type(value) == ParameterDataType.data or (command_class == CommandClass.BASIC and _has_other_application_values(node)) ): return ParameterVisibility.system if _is_setting(value): return ParameterVisibility.setting if _is_user(value): return ParameterVisibility.user if command_class in REVIEWED_COMMAND_CLASSES: return ParameterVisibility.setting return ParameterVisibility.system # a CC nobody reviewed: hidden ("when in doubt, hide it"), still usable def _has_other_application_values(node: Node) -> bool: """Basic CC only mirrors the device's real CCs (for old controllers): shown only when nothing else is.""" ignored = SYSTEM_COMMAND_CLASSES | DIAGNOSTIC_COMMAND_CLASSES | {CommandClass.BASIC} return any(v.command_class not in ignored for v in node.values.values()) def unit(value: Value) -> ParameterUnit: if _is_level(value): return ParameterUnit.percentage if (value.command_class, value.property_) in VALUE_UNITS: return VALUE_UNITS[value.command_class, value.property_] raw = value.metadata.unit or "" if raw in CONVERTED_UNITS: return CONVERTED_UNITS[raw][0] if raw and raw not in UNIT_MAP and raw not in PLAIN_UNITS: log.warning(f"[MAP] {value.value_id} has the unknown unit {raw!r}: reported as plain") return UNIT_MAP.get(raw, ParameterUnit.plain) def limits(value: Value) -> tuple[Any, Any, Any]: """(min, max, step) in MajorDom's units.""" if data_type(value) not in (ParameterDataType.integer, ParameterDataType.decimal): return None, None, None if _is_level(value): return 0, 100, 1 step = next((a.step for a in value.metadata.allowed or [] if isinstance(a, AllowedRangeValue) and a.step), None) return to_hub(value, value.metadata.min), to_hub(value, value.metadata.max), step def valid_values(value: Value) -> dict[int | float | str, str] | None: """Enum labels: zwave-js `states` (`{"0": "Off"}`), keyed by the integer the value takes.""" if data_type(value) != ParameterDataType.enum or not value.metadata.states: return None result: dict[int | float | str, str] = {} for key, raw in value.metadata.states.items(): label = _readable(raw) if value.command_class == CommandClass.CENTRAL_SCENE: # "Key pressed", "Key held down": a key's anyway label = label.removeprefix("Key ") label = label[:1].upper() + label[1:] # "idle", "off" as the other labels try: result[int(key)] = label except ValueError: result[key] = label return result def to_hub(value: Value, raw: Any) -> Any: """A value as the device reports it → as MajorDom expresses it.""" if _is_duration(value): return str(Duration(raw)) if raw is not None else "unknown" if value.metadata.type == "timeout" and raw is not None: return str(raw) if value.metadata.type == "string[]" and isinstance(raw, list): return ", ".join(str(item) for item in raw) if raw is None or isinstance(raw, bool) or not isinstance(raw, int | float): return raw if _is_level(value): return 100 if raw == 99 else int(raw) # 99 is fully on; above it are special values (255: last level) converted = CONVERTED_UNITS.get(value.metadata.unit or "") if converted: _, factor, offset = converted return round(raw * factor + offset, 6) return raw def to_device(value: Value, hub: Any) -> Any: """A value as MajorDom commands it → as the device takes it.""" if _is_button(value): return True # a button parameter (`none`) is commanded without a value if hub is None or isinstance(hub, bool) or not isinstance(hub, int | float): return hub if _is_level(value): return 99 if hub >= 99 else int(hub) converted = CONVERTED_UNITS.get(value.metadata.unit or "") if converted: _, factor, offset = converted return round((hub - offset) / factor, 6) return hub def main_value(node: Node) -> tuple[Value, Any] | None: """The value of the device's one-tap action and what a tap sends, by MAIN_VALUE_BY_COMMAND_CLASS priority.""" for command_class, spec in MAIN_VALUE_BY_COMMAND_CLASS.items(): for value in node.values.values(): if value.command_class == command_class and value.property_ == spec.property_name: return value, spec.default_value return None # Notifications ------------------------------------------------------------------------------------------------------ # What devices send as one-off events rather than values (zwave-js "notification" events). They have no value id, so # their parameters get one of the same shape, `---`; zwave-js says which keypad and # Notification CC events a device supports (node.get_supported_notification_events), so those are exact enums. LEVEL_CHANGES: dict[int | float | str, str] = {0: "Stopped", 1: "Started up", 2: "Started down"} BATTERY_REPLACEMENT: dict[int | float | str, str] = {0: "Not needed", 1: "Soon", 2: "Now"} POWERLEVEL_TEST: dict[int | float | str, str] = {0: "Failed", 1: "Success", 2: "In progress"} @dataclass(frozen=True) class EventParameter: value_id: str name: str data_type: ParameterDataType visibility: ParameterVisibility unit: ParameterUnit = ParameterUnit.plain valid_values: dict[int | float | str, str] | None = None def _labels(supported: dict[str, str]) -> dict[int | float | str, str]: return {int(key): label for key, label in supported.items()} def event_parameters(node: Node, supported: list[dict[str, Any]]) -> list[EventParameter]: """The event parameters of what a node sends as notifications; `supported`: its supported notification events.""" def value_id(command_class: int, endpoint: int, prop: str) -> str: return f"{node.node_id}-{command_class}-{endpoint}-{prop}" def named(name: str, endpoint: int) -> str: return f"{name} {endpoint}" if endpoint else name events: list[EventParameter] = [] for capability in supported: command_class, endpoint = capability["commandClass"], capability["endpoint"] if command_class == CommandClass.ENTRY_CONTROL: events += [ EventParameter( value_id(command_class, endpoint, "event"), named("Keypad", endpoint), ParameterDataType.enum, ParameterVisibility.user, valid_values=_labels(capability["supportedEventTypes"]), ), # what was typed with it: for automations (checking a code), never shown EventParameter( value_id(command_class, endpoint, "code"), named("Keypad code", endpoint), ParameterDataType.string, ParameterVisibility.system, ), ] elif command_class == CommandClass.NOTIFICATION: for kind, notification in capability["supportedNotificationTypes"].items(): label = _sentence(notification["label"]) events += [ EventParameter( value_id(command_class, endpoint, f"event-{kind}"), named(f"{label} event", endpoint), ParameterDataType.enum, ParameterVisibility.user, valid_values=_labels(notification["supportedEvents"]), ), # what came with it (a user id, a code...): for automations, never shown EventParameter( value_id(command_class, endpoint, f"details-{kind}"), named(f"{label} event details", endpoint), ParameterDataType.string, ParameterVisibility.system, ParameterUnit.json, ), ] for endpoint in node.endpoints.values(): supports = {info.id for info in endpoint.command_classes} if CommandClass.SWITCH_MULTILEVEL in supports: # dimming started or stopped on the device (or a remote) itself events.append( EventParameter( value_id(CommandClass.SWITCH_MULTILEVEL, endpoint.index, "levelChange"), named("Level change", endpoint.index), ParameterDataType.enum, ParameterVisibility.system, # for automations (a remote's dimming), not a state to show valid_values=LEVEL_CHANGES, ) ) if CommandClass.BATTERY in supports: # "battery low" events.append( EventParameter( value_id(CommandClass.BATTERY, endpoint.index, "replacement"), named("Battery replacement", endpoint.index), ParameterDataType.enum, ParameterVisibility.user, # "replace the battery": what people need to see valid_values=BATTERY_REPLACEMENT, ) ) if CommandClass.POWERLEVEL in supports: # a radio test's result, when one is run events.append( EventParameter( value_id(CommandClass.POWERLEVEL, endpoint.index, "test"), named("Powerlevel test", endpoint.index), ParameterDataType.enum, ParameterVisibility.setting, valid_values=POWERLEVEL_TEST, ) ) return events def notification_events(notification: Any) -> list[tuple[str, Any]]: """A notification → (value id of its event parameter, value) for each of its parameters it reports.""" def value_id(prop: str) -> str: return f"{notification.node_id}-{notification.command_class}-{notification.endpoint_idx}-{prop}" if isinstance(notification, EntryControlNotification): events: list[tuple[str, Any]] = [(value_id("event"), notification.event_type)] if notification.event_data not in (None, ""): data = notification.event_data events.append((value_id("code"), data if isinstance(data, str) else json.dumps(data, sort_keys=True))) return events if isinstance(notification, NotificationNotification): events = [(value_id(f"event-{notification.type_}"), notification.event)] if notification.parameters: events.append( (value_id(f"details-{notification.type_}"), json.dumps(notification.parameters, sort_keys=True)) ) return events if isinstance(notification, MultilevelSwitchNotification): started = notification.event_type == MultilevelSwitchCommand.START_LEVEL_CHANGE change = (1 if notification.direction == "up" else 2) if started else 0 return [(value_id("levelChange"), change)] if isinstance(notification, BatteryNotification): return [(value_id("replacement"), int(notification.urgency))] if isinstance(notification, PowerLevelNotification): return [(value_id("test"), int(notification.status))] return [] ================================================================================ # FILE: majordom_zwave/model.py ================================================================================ from majordom_integration_sdk.schemas import Device, Parameter from majordom_integration_sdk.schemas.device import DeviceState from pydantic import BaseModel, Field class ZwaveDeviceIntegrationData(BaseModel): home_id: int node_id: int # manufacturer:product type:product id: tells a node id reused by another device from the paired one fingerprint: str | None = None dsk: str | None = None # an S2 device's key: its SmartStart entry outlives the node when it leaves by itself class ZwaveParameterIntegrationData(BaseModel): value_id: str # the value commands go to (and the parameter's identity) state_value_id: str | None = None # the value the state is read from, when it is another one (current vs target) class ZwaveDevice(Device[ZwaveDeviceIntegrationData | None]): # None for a record that is not paired parameters: list["ZwaveParameter"] = Field(default_factory=list) class ZwaveDeviceState(DeviceState[ZwaveDeviceIntegrationData | None, ZwaveParameterIntegrationData]): """The pairing draft: what the Hub knows of the device before it exists, filled in by `pair_device`.""" class ZwaveParameter(Parameter[ZwaveParameterIntegrationData]): pass ================================================================================ # FILE: majordom_zwave/zwave_spec.py ================================================================================ """Static Z-Wave classification data. Unlike Zigbee, zwave-js already reports `min`/`max`/`unit`/`states` directly on `ValueMetadata`, so this module only needs to cover what the wire format *doesn't* give us: which command classes are protocol plumbing or diagnostics-only, which report decimals or levels, how to normalize zwave-js's unit strings, and which property is a device's one-tap "main" action. Pure data only — the functions that use these tables live in mapper.py. """ from dataclasses import dataclass from majordom_integration_sdk.schemas.parameter import ParameterUnit from zwave_js_server.const import CommandClass # Protocol/network plumbing: never shown to the user, regardless of read/write access. # (association & multi channel wiring, security/transport encapsulation, inclusion, S2, etc.) SYSTEM_COMMAND_CLASSES: frozenset[CommandClass] = frozenset( { CommandClass.NO_OPERATION, CommandClass.CONTROLLER_REPLICATION, CommandClass.APPLICATION_STATUS, CommandClass.ZIP, CommandClass.NETWORK_MANAGEMENT_INCLUSION, CommandClass.NETWORK_MANAGEMENT_BASIC, CommandClass.NETWORK_MANAGEMENT_PROXY, CommandClass.NETWORK_MANAGEMENT_PRIMARY, CommandClass.NETWORK_MANAGEMENT_INSTALLATION_MAINTENANCE, CommandClass.TRANSPORT_SERVICE, CommandClass.CRC_16_ENCAP, CommandClass.APPLICATION_CAPABILITY, CommandClass.ASSOCIATION, CommandClass.ASSOCIATION_GRP_INFO, CommandClass.MULTI_CHANNEL, CommandClass.MULTI_CHANNEL_ASSOCIATION, CommandClass.MULTI_CMD, CommandClass.SUPERVISION, CommandClass.ZWAVEPLUS_INFO, CommandClass.INCLUSION_CONTROLLER, CommandClass.NODE_NAMING, CommandClass.NODE_PROVISIONING, CommandClass.MANUFACTURER_PROPRIETARY, CommandClass.PROPRIETARY, CommandClass.SECURITY, CommandClass.SECURITY_2, CommandClass.SECURITY_SCHEME0_MARK, CommandClass.MARK, CommandClass.TIME, CommandClass.TIME_PARAMETERS, CommandClass.CLOCK, CommandClass.GEOGRAPHIC_LOCATION, CommandClass.FIRMWARE_UPDATE_MD, CommandClass.GROUPING_NAME, CommandClass.REMOTE_ASSOCIATION_ACTIVATE, CommandClass.REMOTE_ASSOCIATION, CommandClass.SCREEN_MD, CommandClass.SCREEN_ATTRIBUTES, CommandClass.DEVICE_RESET_LOCALLY, } ) # Technically readable/reportable, but the "settings/advanced" kind of reading (battery %, # firmware version, RSSI-ish diagnostics, wake-up interval) rather than a main everyday control. # ParameterVisibility.setting explicitly covers this case per its docstring. DIAGNOSTIC_COMMAND_CLASSES: frozenset[CommandClass] = frozenset( { CommandClass.BATTERY, CommandClass.VERSION, CommandClass.MANUFACTURER_SPECIFIC, CommandClass.POWERLEVEL, CommandClass.WAKE_UP, CommandClass.INDICATOR, CommandClass.PROTECTION, CommandClass.CONFIGURATION, # device settings behind an "advanced" tap, not main interaction } ) # CCs that report one-shot occurrences (button presses, scene activations) rather than a state — modeled as # ParameterRole.event (except their settings, see SETTING_VALUES). zwave-js marks such values `stateful: false` and # sends them as "value notification". Notification CC is not one: zwave-js models its variables as states. EVENT_COMMAND_CLASSES: frozenset[CommandClass] = frozenset( { CommandClass.CENTRAL_SCENE, CommandClass.SCENE_ACTIVATION, } ) # Values these CCs report are scaled decimals by spec (a reading of 21.0 is still a decimal), so the type does not # depend on the value seen at pairing DECIMAL_COMMAND_CLASSES: frozenset[CommandClass] = frozenset( { CommandClass.SENSOR_MULTILEVEL, CommandClass.METER, CommandClass.THERMOSTAT_SETPOINT, CommandClass.ENERGY_PRODUCTION, CommandClass.HUMIDITY_CONTROL_SETPOINT, } ) # Levels 0-99 (99 is fully on) are percentages in MajorDom, as with Matter, Zigbee and ESPHome: 0-98 stay, 99 is 100. # A window covering's position is one too (its 0 "closed" and 99 "open" labels are the ends of the range). LEVEL_COMMAND_CLASSES: frozenset[CommandClass] = frozenset( {CommandClass.SWITCH_MULTILEVEL, CommandClass.BASIC, CommandClass.WINDOW_COVERING} ) LEVEL_PROPERTIES: frozenset[str] = frozenset({"currentValue", "targetValue"}) # The device's configuration within a CC that is otherwise everyday use: shown as settings (None: the whole CC) SETTING_VALUES: dict[CommandClass, frozenset[str] | None] = { CommandClass.DOOR_LOCK: frozenset( { "operationType", "lockTimeoutConfiguration", "autoRelockTime", "holdAndReleaseTime", "twistAssist", "blockToBlock", "insideHandlesCanOpenDoorConfiguration", "outsideHandlesCanOpenDoorConfiguration", } ), CommandClass.CENTRAL_SCENE: frozenset({"slowRefresh"}), # "send held down notifications" CommandClass.BARRIER_OPERATOR: frozenset({"signalingState"}), # audible / visual warning while moving CommandClass.SOUND_SWITCH: frozenset({"defaultToneId", "defaultVolume"}), CommandClass.NOTIFICATION: frozenset({"alarmType", "alarmLevel"}), # legacy (V1) vendor alarm codes CommandClass.USER_CODE: None, # user slots and keypad mode (the codes themselves are secrets: system) CommandClass.ENTRY_CONTROL: None, # a keypad's key cache (its key presses arrive as notifications, not values) } # Values that describe another value rather than a state of the device, or protocol wiring: hidden SYSTEM_VALUES: frozenset[tuple[int, int | str]] = frozenset( { (CommandClass.HUMIDITY_CONTROL_SETPOINT, "setpointScale"), # the setpoint's unit (CommandClass.THERMOSTAT_SETPOINT, "setpointScale"), (CommandClass.WAKE_UP, "controllerNodeId"), # which node gets the wake-ups: the controller } ) # Notification CC variables (`-`) that are diagnostics, not states people look at: settings NOTIFICATION_SETTING_VARIABLES: frozenset[str] = frozenset( { "Maintenance status", "Periodic inspection status", "Dust in device status", "Test status", "Hardware status", "Software status", "Battery maintenance status", "Device configuration status", "Barrier performing initialization process status", "Barrier UL disabling status", "Barrier vacation mode status", } ) # Notification CC variables several notification types have: named with their type ("Sensor status (Water Alarm)") NOTIFICATION_SHARED_VARIABLES: frozenset[str] = frozenset( { "Sensor status", "Alarm status", "Cover status", "Maintenance status", "Periodic inspection status", "Dust in device status", "Test status", } ) # The everyday controls and live readings: `user` (None: every value of the CC). Following the docs' "when in doubt, # hide it", every other value of a REVIEWED_COMMAND_CLASSES CC is a `setting`, and a CC nobody reviewed is `system` # (still usable by automations and the API). USER_VALUES: dict[CommandClass, frozenset[str] | None] = { CommandClass.BASIC: frozenset({"targetValue"}), # when it is the device's only control CommandClass.SWITCH_BINARY: frozenset({"targetValue"}), CommandClass.SWITCH_MULTILEVEL: frozenset({"targetValue"}), CommandClass.SWITCH_COLOR: frozenset({"hexColor"}), # one colour control; the channels are settings CommandClass.SENSOR_BINARY: None, CommandClass.SENSOR_MULTILEVEL: None, CommandClass.METER: frozenset({"value"}), # the readings; their resets are settings CommandClass.NOTIFICATION: None, # its states (but see NOTIFICATION_SETTING_VARIABLES) CommandClass.SENSOR_ALARM: frozenset({"state"}), CommandClass.DOOR_LOCK: frozenset({"targetMode", "doorStatus", "latchStatus", "boltStatus"}), CommandClass.LOCK: frozenset({"locked"}), CommandClass.BARRIER_OPERATOR: frozenset({"targetState", "position"}), CommandClass.WINDOW_COVERING: frozenset({"targetValue"}), CommandClass.THERMOSTAT_MODE: frozenset({"mode"}), CommandClass.THERMOSTAT_SETPOINT: frozenset({"setpoint"}), CommandClass.THERMOSTAT_OPERATING_STATE: frozenset({"state"}), CommandClass.THERMOSTAT_FAN_MODE: frozenset({"mode"}), CommandClass.THERMOSTAT_FAN_STATE: frozenset({"state"}), CommandClass.HUMIDITY_CONTROL_SETPOINT: frozenset({"setpoint"}), CommandClass.HUMIDITY_CONTROL_MODE: frozenset({"mode"}), CommandClass.HUMIDITY_CONTROL_OPERATING_STATE: frozenset({"state"}), CommandClass.BATTERY: frozenset({"level"}), # a live reading (the docs' example), despite the CC's diagnostics CommandClass.CENTRAL_SCENE: frozenset({"scene"}), CommandClass.SCENE_ACTIVATION: frozenset({"sceneId"}), CommandClass.SOUND_SWITCH: frozenset({"toneId"}), CommandClass.ENERGY_PRODUCTION: frozenset({"value"}), } # CCs whose values were reviewed one by one (the catalogue hosts each): what is not `user` is a `setting` REVIEWED_COMMAND_CLASSES: frozenset[int] = ( frozenset(USER_VALUES) | DIAGNOSTIC_COMMAND_CLASSES | { CommandClass.SCHEDULE_ENTRY_LOCK, CommandClass.USER_CODE, CommandClass.ENTRY_CONTROL, CommandClass.THERMOSTAT_SETBACK, CommandClass.HUMIDITY_CONTROL_SETPOINT, 0x83, # User Credential (newer than zwave-js-server-python's CommandClass) } ) # Names for values whose zwave-js label reads as protocol, not as a control, by (CC, property[, property key]); # {key}: the value's key (a colour channel, a covering) VALUE_NAMES: dict[tuple[int, int | str] | tuple[int, int | str, int | str | None], str] = { (CommandClass.BASIC, "targetValue"): "Level", (CommandClass.BASIC, "restorePrevious"): "Restore last level", (CommandClass.SWITCH_BINARY, "targetValue"): "Power", (CommandClass.SWITCH_MULTILEVEL, "targetValue"): "Level", (CommandClass.SWITCH_MULTILEVEL, "Up"): "Level up", (CommandClass.SWITCH_MULTILEVEL, "Down"): "Level down", (CommandClass.SWITCH_MULTILEVEL, "restorePrevious"): "Restore last level", (CommandClass.SWITCH_COLOR, "hexColor"): "Color", (CommandClass.SWITCH_COLOR, "targetColor"): "{key}", (CommandClass.WINDOW_COVERING, "targetValue"): "{key}", (CommandClass.DOOR_LOCK, "targetMode"): "Lock", (CommandClass.DOOR_LOCK, "doorStatus"): "Door", (CommandClass.DOOR_LOCK, "latchStatus"): "Latch", (CommandClass.DOOR_LOCK, "boltStatus"): "Bolt", (CommandClass.DOOR_LOCK, "lockTimeout"): "Time until relock", (CommandClass.DOOR_LOCK, "operationType"): "Operation type", (CommandClass.DOOR_LOCK, "lockTimeoutConfiguration"): "Timed mode duration", (CommandClass.DOOR_LOCK, "autoRelockTime"): "Auto-relock time", (CommandClass.DOOR_LOCK, "holdAndReleaseTime"): "Hold and release time", (CommandClass.DOOR_LOCK, "twistAssist"): "Twist assist", (CommandClass.DOOR_LOCK, "blockToBlock"): "Block to block", (CommandClass.DOOR_LOCK, "insideHandlesCanOpenDoorConfiguration"): "Inside handles that open the door", (CommandClass.DOOR_LOCK, "outsideHandlesCanOpenDoorConfiguration"): "Outside handles that open the door", (CommandClass.DOOR_LOCK, "insideHandlesCanOpenDoor"): "Inside handles open the door", (CommandClass.DOOR_LOCK, "outsideHandlesCanOpenDoor"): "Outside handles open the door", (CommandClass.BARRIER_OPERATOR, "targetState"): "Door", (CommandClass.BARRIER_OPERATOR, "position"): "Position", (CommandClass.VERSION, "firmwareVersions"): "Firmware version", (CommandClass.VERSION, "libraryType"): "Z-Wave library type", (CommandClass.WAKE_UP, "wakeUpInterval"): "Wake-up interval", (CommandClass.WAKE_UP, "controllerNodeId"): "Wake-up destination", (CommandClass.CENTRAL_SCENE, "slowRefresh"): "Slow refresh while held", (CommandClass.SCENE_ACTIVATION, "sceneId"): "Scene", (CommandClass.SCENE_ACTIVATION, "dimmingDuration"): "Scene dimming duration", (CommandClass.USER_CODE, "userIdStatus"): "User {key} status", (CommandClass.USER_CODE, "userCode"): "User {key} code", (CommandClass.SOUND_SWITCH, "toneId"): "Play tone", (CommandClass.SOUND_SWITCH, "volume"): "Tone volume", (CommandClass.SOUND_SWITCH, "defaultToneId"): "Default tone", (CommandClass.PROTECTION, "local"): "Local protection", (CommandClass.PROTECTION, "rf"): "Remote protection", (CommandClass.PROTECTION, "exclusiveControlNodeId"): "Exclusive control", (CommandClass.PROTECTION, "timeout"): "Remote protection timeout", (CommandClass.THERMOSTAT_FAN_MODE, "mode"): "Fan mode", (CommandClass.THERMOSTAT_FAN_MODE, "off"): "Fan off", (CommandClass.THERMOSTAT_FAN_STATE, "state"): "Fan state", (CommandClass.HUMIDITY_CONTROL_MODE, "mode"): "Humidity mode", (CommandClass.HUMIDITY_CONTROL_OPERATING_STATE, "state"): "Humidity operating state", (CommandClass.ENERGY_PRODUCTION, "value", 1): "Total production", (CommandClass.ENERGY_PRODUCTION, "value", 2): "Production today", (CommandClass.ENERGY_PRODUCTION, "value", 3): "Operating time", } # A meter value's quantity, by the scale in its label ("Electric Consumption [kWh]" → "Electric energy") METER_QUANTITIES: dict[str, str] = { "kWh": "energy", "kVAh": "apparent energy", "W": "power", "Pulse count": "pulses", "V": "voltage", "A": "current", "Power Factor": "power factor", "kVar": "reactive power", "kVarh": "reactive energy", "Cubic meters": "volume", "Cubic feet": "volume (ft³)", "US gallons": "volume (gal)", } # Numbers whose `states` label special values of a range, not the only values: integers, not enums NUMERIC_VALUES: frozenset[tuple[int, int | str]] = frozenset( { (CommandClass.SOUND_SWITCH, "volume"), # 0 is "the default volume" (CommandClass.WAKE_UP, "wakeUpInterval"), # 0 is "disabled" } ) # Units zwave-js puts only in a value's label ("Duration in seconds …"), not in its metadata VALUE_UNITS: dict[tuple[int, int | str], ParameterUnit] = { (CommandClass.DOOR_LOCK, "lockTimeoutConfiguration"): ParameterUnit.second, (CommandClass.DOOR_LOCK, "lockTimeout"): ParameterUnit.second, (CommandClass.DOOR_LOCK, "autoRelockTime"): ParameterUnit.second, (CommandClass.DOOR_LOCK, "holdAndReleaseTime"): ParameterUnit.second, (CommandClass.WAKE_UP, "wakeUpInterval"): ParameterUnit.second, } # zwave-js's ValueMetadata.unit is the unit string of the CC's scale (its sensor, meter and named-scale registries, # plus a few CC-specific ones). Every registry unit is mapped, converted, or deliberately plain (test_catalogue checks). UNIT_MAP: dict[str, ParameterUnit] = { "%": ParameterUnit.percentage, "s": ParameterUnit.second, "seconds": ParameterUnit.second, # Energy Production's total time "Hz": ParameterUnit.hertz, "kg": ParameterUnit.kilogram, "°": ParameterUnit.arcdegree, "°N": ParameterUnit.arcdegree, # a direction "°S": ParameterUnit.arcdegree, "m": ParameterUnit.meters, "m/s": ParameterUnit.mps, "m/s²": ParameterUnit.mps2, "m³/h": ParameterUnit.m3h, "rpm": ParameterUnit.rpm, "N": ParameterUnit.newton, "J": ParameterUnit.joule, "kWh": ParameterUnit.kwh, "W": ParameterUnit.watt, "°C": ParameterUnit.celsius, "K": ParameterUnit.kelvin, "V": ParameterUnit.volt, "A": ParameterUnit.ampere, "lx": ParameterUnit.lux, "Lux": ParameterUnit.lux, "Pa": ParameterUnit.pascal, "ppm": ParameterUnit.ppm, "µg/m³": ParameterUnit.ugm3, "b": ParameterUnit.bytes, "B": ParameterUnit.bytes, } # Units MajorDom has no unit for, converted to one it has: (unit, factor, offset), hub value = raw * factor + offset CONVERTED_UNITS: dict[str, tuple[ParameterUnit, float, float]] = { "°F": (ParameterUnit.celsius, 5 / 9, -32 * 5 / 9), "kPa": (ParameterUnit.pascal, 1000, 0), "inHg": (ParameterUnit.pascal, 3386.389, 0), "mmHg": (ParameterUnit.pascal, 133.322, 0), "psi": (ParameterUnit.pascal, 6894.757, 0), "Wh": (ParameterUnit.kwh, 0.001, 0), "Btu/h": (ParameterUnit.watt, 0.29307107, 0), "mV": (ParameterUnit.volt, 0.001, 0), "mA": (ParameterUnit.ampere, 0.001, 0), "kHz": (ParameterUnit.hertz, 1000, 0), "cm": (ParameterUnit.meters, 0.01, 0), "ft": (ParameterUnit.meters, 0.3048, 0), "lb": (ParameterUnit.kilogram, 0.45359237, 0), "Mph": (ParameterUnit.mps, 0.44704, 0), "cfm": (ParameterUnit.m3h, 1.699011, 0), } # Units MajorDom has no unit for, and no unit it has to convert them to: reported as they are, unit `plain` PLAIN_UNITS: frozenset[str] = frozenset( { "g/m³", # absolute humidity "W/m²", # solar radiation "mm/h", # rain rate "in/h", "l", # volume "m³", "gallon", "gal", "ft³", "l/h", # water flow "Ωm", # soil / water conductivity "S/m", "kΩ", "dB", # sound level "dBA", "dBm", # signal strength "m³/m³", # soil moisture "aw", # water activity "mol/m³", "bq/m³", # radon "pCi/l", "pH", "bpm", # heart rate "mg/l", "kVAh", # apparent energy, reactive power and energy "kVar", "kVarh", } ) @dataclass(frozen=True) class MainValueSpec: """Identifies a device's one-tap main parameter and what a tap does (`Parameter.default_value`). Z-Wave has no invokable "commands" the way Zigbee/Matter clusters do — every action is a property set — so every main parameter is a value. `default_value` follows the SDK: None lets the data type decide (a bool toggles), a set is cycled through (two values: a toggle), a single value is a button that always sends it. """ property_name: str default_value: set[int] | None # Priority order matters: the first command class present on the node wins, same as # ZigBeeController's MAIN_PARAMETER_BY_CLUSTER. Only CCs with an unambiguous "main" action are # listed — e.g. Thermostat Mode is deliberately left out, since there's no single mode that's # the obviously-correct one-tap action across vendors. MAIN_VALUE_BY_COMMAND_CLASS: dict[CommandClass, MainValueSpec] = { CommandClass.SWITCH_BINARY: MainValueSpec("targetValue", None), # Off and fully on, as percentages (see LEVEL_COMMAND_CLASSES). CommandClass.SWITCH_MULTILEVEL: MainValueSpec("targetValue", {0, 100}), # BarrierState CLOSED = 0, OPEN = 255. CommandClass.BARRIER_OPERATOR: MainValueSpec("targetState", {0, 255}), # DoorLockMode UNSECURED = 0, SECURED = 255: not a cycle through every mode the lock has. CommandClass.DOOR_LOCK: MainValueSpec("targetMode", {0, 255}), # Lock CC (older locks): a bool, so a tap toggles it. CommandClass.LOCK: MainValueSpec("locked", None), # A window covering's position: closed and fully open, as percentages. CommandClass.WINDOW_COVERING: MainValueSpec("targetValue", {0, 100}), # Basic CC, when it is the only control the device has: off and fully on, as percentages. CommandClass.BASIC: MainValueSpec("targetValue", {0, 100}), } ================================================================================ # FILE: pyproject.toml ================================================================================ [project] name = "majordom-zwave" version = "0.1.5" description = "Z-Wave integration for MajorDom — bridges Z-Wave devices into the MajorDom language." authors = [ { name = "Parker Industries" }, { name = "Ehor Lukianov @Hexa-Hexagon", email = "85293779+Hexa-Hexagon@users.noreply.github.com" }, { name = "Mark Parker @MarkParker5", email = "34688010+MarkParker5@users.noreply.github.com" }, ] readme = "README.md" license = "LicenseRef-PolyForm-Noncommercial-1.0.0" license-files = ["LICENSE"] keywords = ["majordom", "zwave", "z-wave", "zwave-js", "zwave-js-server-python", "smart-home", "home-automation", "iot", "integration"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Home Automation", "Programming Language :: Python :: 3", ] requires-python = ">=3.13,<4.0" dependencies = [ "majordom-integration-sdk (>=0.4.0,<1.0)", "zwave-js-server-python (>=0.74.0,<0.75.0)", ] [project.urls] Homepage = "https://majordom.io" Documentation = "https://docs.majordom.io/device-integration" Repository = "https://github.com/MajorDom-Systems/integration-zwave" "Parker Industries" = "https://parker-industries.org" [dependency-groups] dev = [ "poethepoet (>=0.49.0,<1.0.0)", "ty", # type checker; swap for mypy/pyright by editing the `check` task below "ruff", "pip-audit", # dependency vuln scan — gates release (not everyday CI); run locally with `poetry run pip-audit` "pytest", "pytest-asyncio", "pytest-cov", "pytest-timeout", "pytest-xdist", # parallel tests: `-n auto`; every mock network is a process of its own "pytest-repeat", "pytest-benchmark", "pytest-profiling", "pytest-resource-usage", "coverage", "pympler", # object memory introspection, leak hunting "psutil", # process/system resource usage "faker", # realistic fake data for tests ] [build-system] requires = ["poetry-core>=2.0.0,<3.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] requires-poetry = ">=2.0" packages = [{ include = "majordom_zwave" }] include = [{ path = "majordom_zwave/device_configs", format = ["sdist", "wheel"] }] [tool.pytest.ini_options] asyncio_mode = "auto" pythonpath = ["."] filterwarnings = ["once"] [tool.coverage.run] omit = ["tests/*"] [tool.ruff] line-length = 120 indent-width = 4 [tool.ruff.lint] select = [ "E", # pycodestyle "F", # pyflakes "UP", # pyupgrade "B", # flake8-bugbear "SIM", # flake8-simplify "I", # isort ] fixable = ["ALL"] [tool.ruff.format] quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "tests/*" = ["E402"] [tool.poe.tasks.install] shell = """ poetry install echo '#!/bin/sh\npoetry run poe check' > .git/hooks/pre-commit chmod +x .git/hooks/pre-commit echo "Pre-commit hook installed." """ [tool.poe.tasks.check] shell = """ code=0 echo "\nRunning ruff lint:" poetry run ruff check --fix || code=1 echo "\nRunning ruff format:" poetry run ruff format || code=1 echo "\nRunning ty:" poetry run ty check || code=1 echo "\nRunning pytest:" poetry run pytest -n auto --cov=majordom_zwave --cov-report=xml || code=1 echo "\nRunning poetry build:" poetry build || code=1 echo "\nRunning poetry check:" poetry check || code=1 ${ci:+git diff --exit-code} || code=1 exit $code """ args = [{ name = "ci", type = "boolean" }] ================================================================================ # FILE: tests/catalogue.py ================================================================================ """The command-class catalogue: every CC zwave-js knows is hosted by a mock device (a recipe, tests/mock/catalogue.mjs), is protocol plumbing, or is explained here — and what each hosted CC must map to. Spec terms: "plumbing" CCs carry no user-facing value (they map to `system`); "unhostable" ones have no zwave-js mock (their values still go through the generic mapping, checked shape by shape in test_value_shapes). """ from majordom_integration_sdk.schemas.parameter import ( ParameterDataType as T, ) from majordom_integration_sdk.schemas.parameter import ( ParameterRole as R, ) from majordom_integration_sdk.schemas.parameter import ( ParameterUnit as U, ) from majordom_integration_sdk.schemas.parameter import ( ParameterVisibility as V, ) from majordom_zwave.zwave_spec import SYSTEM_COMMAND_CLASSES # recipe → the command classes it hosts (beyond the ones every mock device has, see BASE) RECIPES: dict[str, set[int]] = { "basic": {0x20}, "binary_sensor": {0x30}, "binary_switch": {0x25}, "color_switch": {0x33, 0x26}, "configuration": {0x70}, "door_lock": {0x62}, "energy_production": {0x90}, "indicator": {0x87}, "lock": {0x76}, "meter": {0x32}, "multilevel_sensor": {0x31}, "multilevel_switch": {0x26}, "node_naming": {0x77}, "notification": {0x71}, "scene_activation": {0x2B}, "schedule_entry_lock": {0x4E, 0x63}, "sound_switch": {0x79}, "thermostat_mode": {0x40}, "thermostat_setback": {0x47}, "thermostat_setpoint": {0x43}, "user_code": {0x63}, "user_credential": {0x83}, "window_covering": {0x6A}, # not mocked by zwave-js: the harness answers for them (BEHAVIORS in catalogue.mjs) "central_scene": {0x5B}, "thermostat_fan_mode": {0x44}, "thermostat_fan_state": {0x45}, "thermostat_operating_state": {0x42}, "barrier_operator": {0x66}, "protection": {0x75, 0x25}, "humidity_control": {0x64, 0x6D, 0x6E}, "entry_control": {0x6F}, "alarm_sensor": {0x9C}, "powerlevel": {0x73, 0x25}, "sleeping": {0x80, 0x84, 0x25}, # Battery and Wake Up, on a switch } # On every mock device (identity, interview), or used by the scenario tests (endpoints, supervision, S2) BASE = {0x5E, 0x72, 0x86} INFRASTRUCTURE = BASE | {0x60, 0x6C, 0x9F} # Not in zwave-js-server-python's CommandClass yet: newer than the library NEWER_THAN_THE_LIBRARY = { 0x01: "Z-Wave Protocol: the protocol's own frames, no values", 0x04: "Z-Wave Long Range: the protocol's own frames, no values", 0x83: "User Credential: hosted (recipe user_credential); compared by its number", } PLUMBING = {int(cc) for cc in SYSTEM_COMMAND_CLASSES} | {0x01, 0x04} _NO_MOCK = "zwave-js has no mock for it; its values go through the generic mapping (test_value_shapes)" _RARE = "no mock, and rare in homes (commercial metering, IP gateways, AV): generic mapping (test_value_shapes)" UNHOSTABLE: dict[int, str] = { **dict.fromkeys( [ 0x27, # All Switch 0x28, # Binary Toggle Switch 0x29, # Multilevel Toggle Switch 0x2C, # Scene Actuator Configuration 0x2D, # Scene Controller Configuration 0x46, # Climate Control Schedule 0x4C, # Door Lock Logging 0x50, # Basic Window Covering 0x51, # Move To Position Window Covering 0x53, # Schedule 0x5D, # Anti-Theft 0x6B, # Irrigation 0x7E, # Anti-Theft Unlock 0x82, # Hail 0x89, # Language 0x9D, # Alarm Silence 0x9E, # Sensor Configuration 0xA3, # Generic Schedule ], _NO_MOCK, ), **dict.fromkeys( [ 0x35, # Pulse Meter 0x36, # Basic Tariff Information 0x37, # HRV Status 0x39, # HRV Control 0x3A, # Demand Control Plan Configuration 0x3B, # Demand Control Plan Monitor 0x3C, # Meter Table Configuration 0x3D, # Meter Table Monitor 0x3E, # Meter Table Push Configuration 0x3F, # Prepayment 0x41, # Prepayment Encapsulation 0x48, # Rate Table Configuration 0x49, # Rate Table Monitor 0x4A, # Tariff Table Configuration 0x4B, # Tariff Table Monitor 0x4F, # Z/IP 6LoWPAN 0x58, # Z/IP ND 0x5F, # Z/IP Gateway 0x61, # Z/IP Portal 0x68, # Z/IP Naming and Location 0x5C, # IP Association 0x69, # Mailbox 0x94, # Simple AV Control 0x9A, # IP Configuration 0x9B, # Association Command Configuration 0xA0, # IR Repeater 0xA1, # Authentication 0xA2, # Authentication Media Write ], _RARE, ), } # What each hosted CC maps to, reviewed value by value against the docs' parameter UX (docs/device-integration/ # parameter-ux.md): everyday controls and live readings `user` (the main tile among them), a CC's configuration and # diagnostics `setting`, wiring, metadata, secrets and durations `system`; names for people, not zwave-js's labels. Row = tuple[str, T, R, V, U] # (name, data type, role, visibility, unit) # Every device's identity values (Manufacturer Specific, Version): checked once, the same on every recipe COMMON: dict[str, Row] = { "114-0-productId": ("Product ID", T.integer, R.sensor, V.setting, U.plain), "114-0-productType": ("Product type", T.integer, R.sensor, V.setting, U.plain), "114-0-manufacturerId": ("Manufacturer ID", T.integer, R.sensor, V.setting, U.plain), "134-0-firmwareVersions": ("Firmware version", T.string, R.sensor, V.setting, U.plain), "134-0-protocolVersion": ("Z-Wave protocol version", T.string, R.sensor, V.setting, U.plain), "134-0-libraryType": ("Z-Wave library type", T.enum, R.sensor, V.setting, U.plain), } # key (value id without the node: --[-]) → (name, data type, role, visibility, unit) EXPECTED: dict[str, dict[str, Row]] = { "alarm_sensor": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "156-0-state-1": ("Smoke state", T.bool, R.sensor, V.user, U.plain), "156-0-severity-1": ("Smoke severity", T.integer, R.sensor, V.setting, U.percentage), "156-0-duration-1": ("Smoke duration", T.integer, R.sensor, V.setting, U.second), "156-0-state-2": ("CO state", T.bool, R.sensor, V.user, U.plain), "156-0-severity-2": ("CO severity", T.integer, R.sensor, V.setting, U.percentage), "156-0-duration-2": ("CO duration", T.integer, R.sensor, V.setting, U.second), }, "barrier_operator": { "102-0-signalingState-1": ("Audible warning", T.enum, R.control, V.setting, U.plain), "102-0-signalingState-2": ("Visual warning", T.enum, R.control, V.setting, U.plain), "102-0-position": ("Position", T.integer, R.sensor, V.user, U.percentage), "102-0-targetState": ("Door", T.enum, R.control, V.user, U.plain), }, "basic": { "32-0-targetValue": ("Level", T.integer, R.control, V.user, U.percentage), "32-0-duration": ("Remaining duration", T.string, R.sensor, V.system, U.plain), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.setting, U.plain), }, "binary_sensor": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "48-0-General Purpose": ("General purpose", T.bool, R.sensor, V.user, U.plain), "48-0-Door/Window": ("Door/Window", T.bool, R.sensor, V.user, U.plain), "48-0-Motion": ("Motion", T.bool, R.sensor, V.user, U.plain), }, "binary_switch": { "37-0-duration": ("Remaining duration", T.string, R.sensor, V.system, U.plain), "37-0-targetValue": ("Power", T.bool, R.control, V.user, U.plain), }, "central_scene": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "91-0-scene-001": ("Scene 1", T.enum, R.event, V.user, U.plain), "91-0-scene-002": ("Scene 2", T.enum, R.event, V.user, U.plain), "91-0-slowRefresh": ("Slow refresh while held", T.bool, R.control, V.setting, U.plain), }, "color_switch": { "38-0-duration": ("Remaining duration (Multilevel Switch)", T.string, R.sensor, V.system, U.plain), "38-0-targetValue": ("Level", T.integer, R.control, V.user, U.percentage), "38-0-Up": ("Level up", T.bool, R.control, V.setting, U.plain), "38-0-Down": ("Level down", T.bool, R.control, V.setting, U.plain), "38-0-restorePrevious": ("Restore last level", T.none, R.control, V.setting, U.plain), "51-0-hexColor": ("Color", T.string, R.control, V.user, U.plain), "51-0-targetColor-0": ("Warm white", T.integer, R.control, V.setting, U.plain), "51-0-targetColor-1": ("Cold white", T.integer, R.control, V.setting, U.plain), "51-0-targetColor-2": ("Red", T.integer, R.control, V.setting, U.plain), "51-0-targetColor-3": ("Green", T.integer, R.control, V.setting, U.plain), "51-0-targetColor-4": ("Blue", T.integer, R.control, V.setting, U.plain), "51-0-targetColor": ("Color Switch", T.data, R.control, V.system, U.plain), "51-0-duration": ("Remaining duration (Color Switch)", T.string, R.sensor, V.system, U.plain), "38-0-levelChange": ("Level change", T.enum, R.event, V.system, U.plain), }, "configuration": { "32-0-targetValue": ("Level", T.integer, R.control, V.user, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.setting, U.plain), "112-0-1": ("Brightness on power-up", T.integer, R.control, V.setting, U.plain), "112-0-2": ("LED mode", T.integer, R.control, V.setting, U.plain), "112-0-3": ("Offset", T.integer, R.control, V.setting, U.plain), "112-0-4": ("Firmware flags", T.integer, R.sensor, V.setting, U.plain), }, "door_lock": { "98-0-targetMode": ("Lock", T.enum, R.control, V.user, U.plain), "98-0-operationType": ("Operation type", T.enum, R.control, V.setting, U.plain), "98-0-doorStatus": ("Door", T.string, R.sensor, V.user, U.plain), "98-0-latchStatus": ("Latch", T.string, R.sensor, V.user, U.plain), "98-0-boltStatus": ("Bolt", T.string, R.sensor, V.user, U.plain), "98-0-insideHandlesCanOpenDoorConfiguration": ( "Inside handles that open the door", T.data, R.control, V.system, U.plain, ), "98-0-outsideHandlesCanOpenDoorConfiguration": ( "Outside handles that open the door", T.data, R.control, V.system, U.plain, ), "98-0-autoRelockTime": ("Auto-relock time", T.integer, R.control, V.setting, U.second), "98-0-holdAndReleaseTime": ("Hold and release time", T.integer, R.control, V.setting, U.second), "98-0-twistAssist": ("Twist assist", T.bool, R.control, V.setting, U.plain), "98-0-blockToBlock": ("Block to block", T.bool, R.control, V.setting, U.plain), "98-0-insideHandlesCanOpenDoor": ("Inside handles open the door", T.data, R.sensor, V.system, U.plain), "98-0-outsideHandlesCanOpenDoor": ("Outside handles open the door", T.data, R.sensor, V.system, U.plain), "98-0-duration": ("Remaining duration until target lock mode", T.string, R.sensor, V.system, U.plain), "98-0-lockTimeoutConfiguration": ("Timed mode duration", T.integer, R.control, V.setting, U.second), "98-0-lockTimeout": ("Time until relock", T.integer, R.sensor, V.setting, U.second), }, "energy_production": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "144-0-value-0": ("Power", T.decimal, R.sensor, V.user, U.watt), "144-0-value-1": ("Total production", T.decimal, R.sensor, V.user, U.kwh), "144-0-value-2": ("Production today", T.decimal, R.sensor, V.user, U.kwh), "144-0-value-3": ("Operating time", T.decimal, R.sensor, V.user, U.second), }, "entry_control": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "111-0-keyCacheSize": ("Key cache size", T.integer, R.control, V.setting, U.plain), "111-0-keyCacheTimeout": ("Key cache timeout", T.integer, R.control, V.setting, U.second), "111-0-event": ("Keypad", T.enum, R.event, V.user, U.plain), "111-0-code": ("Keypad code", T.string, R.event, V.system, U.plain), }, "humidity_control": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "100-0-setpointScale-1": ("Setpoint scale (humidifier)", T.enum, R.sensor, V.system, U.plain), "100-0-setpoint-1": ("Humidifier setpoint", T.decimal, R.control, V.user, U.percentage), "100-0-setpointScale-2": ("Setpoint scale (de-humidifier)", T.enum, R.sensor, V.system, U.plain), "100-0-setpoint-2": ("De-humidifier setpoint", T.decimal, R.control, V.user, U.percentage), "109-0-mode": ("Humidity mode", T.enum, R.control, V.user, U.plain), "110-0-state": ("Humidity operating state", T.enum, R.sensor, V.user, U.plain), }, "indicator": { "32-0-targetValue": ("Level", T.integer, R.control, V.user, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.setting, U.plain), "135-0-67-2": ("Button 1 indication", T.bool, R.control, V.setting, U.plain), "135-0-value": ("Indicator value", T.integer, R.control, V.setting, U.plain), "135-0-identify": ("Identify", T.none, R.control, V.setting, U.plain), }, "lock": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "118-0-locked": ("Locked", T.bool, R.control, V.user, U.plain), }, "meter": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "50-0-value-65537": ("Electric energy", T.decimal, R.sensor, V.user, U.kwh), "50-0-value-66049": ("Electric power", T.decimal, R.sensor, V.user, U.watt), "50-0-value-66561": ("Electric voltage", T.decimal, R.sensor, V.user, U.volt), "50-0-value-66817": ("Electric current", T.decimal, R.sensor, V.user, U.ampere), "50-0-reset-65537": ("Reset electric energy", T.none, R.control, V.setting, U.plain), "50-0-reset": ("Reset all meters", T.none, R.control, V.setting, U.plain), }, "multilevel_sensor": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "49-0-Air temperature": ("Air temperature", T.decimal, R.sensor, V.user, U.celsius), "49-0-Illuminance": ("Illuminance", T.decimal, R.sensor, V.user, U.lux), "49-0-Humidity": ("Humidity", T.decimal, R.sensor, V.user, U.percentage), }, "multilevel_switch": { "38-0-duration": ("Remaining duration", T.string, R.sensor, V.system, U.plain), "38-0-targetValue": ("Level", T.integer, R.control, V.user, U.percentage), "38-0-Up": ("Level up", T.bool, R.control, V.setting, U.plain), "38-0-Down": ("Level down", T.bool, R.control, V.setting, U.plain), "38-0-restorePrevious": ("Restore last level", T.none, R.control, V.setting, U.plain), "38-0-levelChange": ("Level change", T.enum, R.event, V.system, U.plain), }, "node_naming": { "32-0-targetValue": ("Level", T.integer, R.control, V.user, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.setting, U.plain), "119-0-name": ("Node name", T.string, R.control, V.system, U.plain), "119-0-location": ("Node location", T.string, R.control, V.system, U.plain), }, "notification": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "113-0-Water Alarm-Sensor status": ("Sensor status (Water alarm)", T.enum, R.sensor, V.user, U.plain), "113-0-Home Security-Cover status": ("Cover status (Home security)", T.enum, R.sensor, V.user, U.plain), "113-0-Home Security-Motion sensor status": ("Motion sensor status", T.enum, R.sensor, V.user, U.plain), "113-0-alarmType": ("Alarm type", T.integer, R.sensor, V.setting, U.plain), "113-0-alarmLevel": ("Alarm level", T.integer, R.sensor, V.setting, U.plain), "113-0-event-6": ("Access control event", T.enum, R.event, V.user, U.plain), "113-0-details-6": ("Access control event details", T.string, R.event, V.system, U.json), }, "powerlevel": { "37-0-duration": ("Remaining duration", T.string, R.sensor, V.system, U.plain), "37-0-targetValue": ("Power", T.bool, R.control, V.user, U.plain), "115-0-test": ("Powerlevel test", T.enum, R.event, V.setting, U.plain), }, "protection": { "37-0-duration": ("Remaining duration", T.string, R.sensor, V.system, U.plain), "37-0-targetValue": ("Power", T.bool, R.control, V.user, U.plain), "117-0-local": ("Local protection", T.enum, R.control, V.setting, U.plain), "117-0-rf": ("Remote protection", T.enum, R.control, V.setting, U.plain), "117-0-exclusiveControlNodeId": ("Exclusive control", T.integer, R.control, V.setting, U.plain), "117-0-timeout": ("Remote protection timeout", T.string, R.control, V.setting, U.plain), }, "scene_activation": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "43-0-sceneId": ("Scene", T.integer, R.event, V.user, U.plain), "43-0-dimmingDuration": ("Scene dimming duration", T.string, R.event, V.system, U.plain), }, "schedule_entry_lock": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "99-0-adminCode": ("Admin code", T.string, R.control, V.system, U.plain), "99-0-userIdStatus-1": ("User 1 status", T.enum, R.control, V.setting, U.plain), "99-0-userCode-1": ("User 1 code", T.string, R.control, V.system, U.plain), "99-0-userIdStatus-2": ("User 2 status", T.enum, R.control, V.setting, U.plain), "99-0-userCode-2": ("User 2 code", T.string, R.control, V.system, U.plain), "99-0-keypadMode": ("Keypad mode", T.integer, R.sensor, V.setting, U.plain), }, "sleeping": { "37-0-duration": ("Remaining duration", T.string, R.sensor, V.system, U.plain), "37-0-targetValue": ("Power", T.bool, R.control, V.user, U.plain), "128-0-level": ("Battery level", T.integer, R.sensor, V.user, U.percentage), "132-0-wakeUpInterval": ("Wake-up interval", T.integer, R.control, V.setting, U.second), "132-0-controllerNodeId": ("Wake-up destination", T.integer, R.sensor, V.system, U.plain), "128-0-replacement": ("Battery replacement", T.enum, R.event, V.user, U.plain), }, "sound_switch": { "121-0-defaultToneId": ("Default tone", T.enum, R.control, V.setting, U.plain), "121-0-defaultVolume": ("Default volume", T.integer, R.control, V.setting, U.percentage), "121-0-toneId": ("Play tone", T.enum, R.control, V.user, U.plain), "121-0-volume": ("Tone volume", T.integer, R.control, V.setting, U.percentage), }, "thermostat_fan_mode": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "68-0-mode": ("Fan mode", T.enum, R.control, V.user, U.plain), "68-0-off": ("Fan off", T.bool, R.control, V.setting, U.plain), }, "thermostat_fan_state": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "69-0-state": ("Fan state", T.enum, R.sensor, V.user, U.plain), }, "thermostat_mode": { "64-0-mode": ("Thermostat mode", T.enum, R.control, V.user, U.plain), "64-0-manufacturerData": ("Manufacturer data", T.data, R.sensor, V.system, U.plain), }, "thermostat_operating_state": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "66-0-state": ("Operating state", T.enum, R.sensor, V.user, U.plain), }, "thermostat_setback": { "32-0-targetValue": ("Level", T.integer, R.control, V.user, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.setting, U.plain), }, "thermostat_setpoint": { "67-0-setpoint-1": ("Heating setpoint", T.decimal, R.control, V.user, U.celsius), "67-0-setpoint-2": ("Cooling setpoint", T.decimal, R.control, V.user, U.celsius), }, "user_code": { "32-0-targetValue": ("Level", T.integer, R.control, V.system, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.system, U.plain), "99-0-adminCode": ("Admin code", T.string, R.control, V.system, U.plain), "99-0-userIdStatus-1": ("User 1 status", T.enum, R.control, V.setting, U.plain), "99-0-userCode-1": ("User 1 code", T.string, R.control, V.system, U.plain), "99-0-userIdStatus-2": ("User 2 status", T.enum, R.control, V.setting, U.plain), "99-0-userCode-2": ("User 2 code", T.string, R.control, V.system, U.plain), "99-0-keypadMode": ("Keypad mode", T.integer, R.sensor, V.setting, U.plain), }, "user_credential": { "32-0-targetValue": ("Level", T.integer, R.control, V.user, U.percentage), "32-0-restorePrevious": ("Restore last level", T.none, R.control, V.setting, U.plain), }, "window_covering": { "106-0-targetValue-13": ("Outbound bottom", T.integer, R.control, V.user, U.percentage), "106-0-duration-13": ("Outbound bottom: remaining duration", T.string, R.sensor, V.system, U.plain), "106-0-targetValue-23": ("Horizontal slats angle", T.integer, R.control, V.user, U.percentage), "106-0-duration-23": ("Horizontal slats angle: remaining duration", T.string, R.sensor, V.system, U.plain), "106-0-levelChangeUp-13": ("Outbound bottom: open", T.bool, R.control, V.setting, U.plain), "106-0-levelChangeDown-13": ("Outbound bottom: close", T.bool, R.control, V.setting, U.plain), "106-0-levelChangeUp-23": ( "Horizontal slats angle: change tilt (down inside)", T.bool, R.control, V.setting, U.plain, ), "106-0-levelChangeDown-23": ( "Horizontal slats angle: change tilt (up inside)", T.bool, R.control, V.setting, U.plain, ), }, } # The device's one-tap main parameter (None: nothing has an unambiguous one-tap action) MAIN: dict[str, str | None] = { "barrier_operator": "102-0-targetState", "basic": "32-0-targetValue", "binary_switch": "37-0-targetValue", "color_switch": "38-0-targetValue", "configuration": "32-0-targetValue", "door_lock": "98-0-targetMode", "indicator": "32-0-targetValue", "lock": "118-0-locked", "multilevel_switch": "38-0-targetValue", "node_naming": "32-0-targetValue", "powerlevel": "37-0-targetValue", "protection": "37-0-targetValue", "sleeping": "37-0-targetValue", "thermostat_setback": "32-0-targetValue", "user_credential": "32-0-targetValue", "window_covering": "106-0-targetValue-13", } # Writable values whose new value does not come back as a report from the mock device, and why NO_REPORT: dict[str, str] = { "32-0-targetValue": "Basic Set gets no report back from the mock (zwave-js verifies with a Get later)", "51-0-hexColor": "a combined view of the channels: the channels report, not this", **dict.fromkeys( [f"51-0-targetColor-{c}" for c in range(5)], "zwave-js's mock cannot decode a Color Switch Set (TypeError in its parser): the mock drops it, unanswered", ), "98-0-insideHandlesCanOpenDoorConfiguration": "an object value: not writable from MajorDom (system)", "98-0-outsideHandlesCanOpenDoorConfiguration": "an object value: not writable from MajorDom (system)", "119-0-name": "system: the Hub keeps the name", "119-0-location": "system: the Hub keeps the location", "99-0-adminCode": "a secret: never written from MajorDom", "99-0-userCode-1": "a secret", "99-0-userCode-2": "a secret", "121-0-toneId": "playing a tone: the mock reports it finished (0), not the tone", "121-0-volume": "only used with a tone being played", "135-0-67-2": "zwave-js's Indicator mock takes the Set but does not keep the indicator's state", "135-0-value": "zwave-js's Indicator mock takes the Set but does not keep the indicator's state", "117-0-exclusiveControlNodeId": "the device does not support exclusive control (as many do not)", "98-0-operationType": "zwave-js sets the lock configuration as a whole: timed mode needs its timeout with it", "98-0-lockTimeoutConfiguration": "zwave-js sets the lock configuration as a whole: a timeout needs timed mode", "99-0-userIdStatus-1": "a user slot is enabled together with its code (a secret): zwave-js rejects it alone", "99-0-userIdStatus-2": "a user slot is enabled together with its code (a secret): zwave-js rejects it alone", } # Every variant zwave-js knows (recipes *_all): too many values to list, so each value of the CC must follow its rule # (key pattern → (data type, role, visibilities, unit; None: any, the drift check covers units)), at least `minimum` VARIANTS: dict[str, tuple[int, dict[str, tuple[T, R, set[V], U | None]]]] = { "binary_sensor_all": (13, {r"48-0-.+": (T.bool, R.sensor, {V.user}, U.plain)}), "multilevel_sensor_all": (88, {r"49-0-.+": (T.decimal, R.sensor, {V.user}, None)}), "multilevel_sensor_scales": (40, {r"49-0-.+": (T.decimal, R.sensor, {V.user}, None)}), "meter_all": ( 36, { r"50-\d-value-\d+": (T.decimal, R.sensor, {V.user}, None), r"50-\d-reset(-\d+)?": (T.none, R.control, {V.setting}, U.plain), }, ), "notification_all": ( 120, { r"113-0-alarm(Type|Level)": (T.integer, R.sensor, {V.setting}, U.plain), r"113-0-event-\d+": (T.enum, R.event, {V.user}, U.plain), r"113-0-details-\d+": (T.string, R.event, {V.system}, U.json), # diagnostics, not states people look at r"113-0-.+-(Maintenance|Periodic inspection|Dust in device|Test) status": ( T.enum, R.sensor, {V.setting}, U.plain, ), r"113-0-.+": (T.enum, R.sensor, {V.user, V.setting}, U.plain), # states; diagnostics as settings }, ), "thermostat_setpoint_all": (11, {r"67-0-setpoint-\d+": (T.decimal, R.control, {V.user}, U.celsius)}), "thermostat_mode_all": (1, {r"64-0-mode": (T.enum, R.control, {V.user}, U.plain)}), } # `user` parameters whose names are alike on purpose (the SDK's audit flags near-duplicates) SIMILAR_NAMES: list[tuple[str, str]] = [ ("Humidifier setpoint", "De-humidifier setpoint"), ("Heating setpoint", "Cooling setpoint"), ("Smoke state", "CO state"), ("Scene 1", "Scene 2"), ("Electric energy", "Electric power"), ("Production today", "Total production"), ] ================================================================================ # FILE: tests/conftest.py ================================================================================ """Shared fixtures: a fresh controller and Hub doubles per test, and the mock Z-Wave network it connects to.""" from collections.abc import AsyncIterator from typing import Any import pytest from majordom_integration_sdk import Endpoint, Peripherals, Platform from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from majordom_zwave import ZwaveController from tests.network import MakeNetwork, MockNetwork @pytest.fixture def platform() -> Platform: return build_test_platform() @pytest.fixture def output() -> RecordingControllerOutput: return RecordingControllerOutput() @pytest.fixture def fast(monkeypatch: pytest.MonkeyPatch): """Shorten the waits meant for people and radios, so failure paths run in seconds.""" monkeypatch.setattr(ZwaveController, "RECONNECT_DELAYS", (0.2, 0.5)) monkeypatch.setattr(ZwaveController, "EXCLUSION_TIMEOUT", 2.0) monkeypatch.setattr(ZwaveController, "READY_TIMEOUT", 3.0) monkeypatch.setattr(ZwaveController, "IDENTIFY_BLINKS", 2) monkeypatch.setattr(ZwaveController, "IDENTIFY_PERIOD", 0.05) @pytest.fixture def patient(fast: None, monkeypatch: pytest.MonkeyPatch): """Interviewing every capability of a CC takes the mock a few seconds (Notification, User Code).""" monkeypatch.setattr(ZwaveController, "READY_TIMEOUT", 90.0) @pytest.fixture async def controller( platform: Platform, output: RecordingControllerOutput, fast: None ) -> AsyncIterator[ZwaveController]: controller = ZwaveController(platform) controller.output = output yield controller await controller.stop() @pytest.fixture async def make_network(controller: ZwaveController) -> AsyncIterator[MakeNetwork]: """Start a mock network (with the given nodes already included) and bind the integration's need to it.""" networks: list[MockNetwork] = [] async def make(nodes: list[dict[str, Any]] | None = None, serve: bool = True) -> MockNetwork: network = MockNetwork(nodes or []) networks.append(network) await network.start(serve=serve) controller.peripherals = Peripherals({"zwave": Endpoint("zwave", "zwave-js-ws", network.url)}) return network yield make for network in networks: await network.stop() @pytest.fixture async def network(make_network: MakeNetwork) -> MockNetwork: """An empty network: devices join it during the test.""" return await make_network() ================================================================================ # FILE: tests/helpers.py ================================================================================ """Helpers shared by the tests: what the Hub does around pairing, and waiting for what the integration reports.""" import asyncio import time from collections.abc import Callable from typing import Any from uuid import UUID, uuid4 from majordom_integration_sdk.schemas import DeviceParameterChange from majordom_integration_sdk.schemas.command import DeviceCommand from majordom_integration_sdk.schemas.device import Discovery, ProvidedCredentials from majordom_integration_sdk.schemas.parameter import ParameterDataType from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_zwave import ZwaveController from majordom_zwave.model import ZwaveDevice, ZwaveDeviceState, ZwaveParameter from tests.network import MockNetwork ROOM = UUID(int=42) async def wait_until(predicate: Callable[[], Any], timeout: float = 10.0, message: str = "condition"): deadline = time.monotonic() + timeout while time.monotonic() < deadline: if predicate(): return await asyncio.sleep(0.05) raise TimeoutError(f"timed out after {timeout}s waiting for {message}") def hub_draft(discovery: Discovery, name: str = "Hall lamp") -> ZwaveDeviceState: """What the Hub builds before it asks to pair: the user's fields and the discovery's id, no record.""" return ZwaveDeviceState( id=uuid4(), physical_id=discovery.id, name=name, room_id=ROOM, transport=discovery.transport, integration=discovery.integration, manufacturer=discovery.device_manufacturer, parameters=[], ) async def hub_pairs( controller: ZwaveController, discovery: Discovery, name: str = "Hall lamp", draft: ZwaveDeviceState | None = None ) -> ZwaveDevice: """Pairs as the Hub does: saves what `pair_device` returns, reports it connected, then fetches it.""" paired = await controller.pair_device(discovery, draft or hub_draft(discovery, name), None) async with controller.platform.device_repository(controller) as repo: await repo.save(paired) await controller.output.controller_did_connect_device(controller, physical_id=paired.physical_id) device = await stored(controller, paired.physical_id) await controller.fetch(device) return device async def discover( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, node: int, kind: str, credentials: Callable[[dict[str, str]], ProvidedCredentials | None] = lambda _: None, duration: int = 60, **options: Any, ) -> Discovery: """Open the pairing window and let a device join; returns its discovery.""" label = await network.join(node, kind, **options) seen = len(output.received_discoveries) await controller.start_pairing_window(duration, credentials(label)) await wait_until(lambda: len(output.received_discoveries) > seen, 20, f"discovery of node {node}") return output.received_discoveries[-1] async def pair( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, node: int = 5, kind: str = "switch", **options: Any, ) -> ZwaveDevice: """Include a device and pair it as the Hub does; returns the stored device.""" discovery = await discover(controller, output, network, node, kind, **options) return await hub_pairs(controller, discovery) async def stored(controller: ZwaveController, device_id: UUID) -> ZwaveDevice: async with controller.platform.device_repository(controller) as repo: device = await repo.get(physical_id=device_id, as_=ZwaveDevice) assert device is not None, f"device {device_id} is not stored" return device def param(device: ZwaveDevice, key: str) -> ZwaveParameter: """The parameter of a Z-Wave value, by its key without the node: `--[-]`.""" matches = [p for p in device.parameters if p.integration_data.value_id.split("-", 1)[1] == key] assert len(matches) == 1, ( f"expected one parameter for {key}, got {[p.integration_data.value_id for p in device.parameters]}" ) return ZwaveParameter.model_validate(matches[0].model_dump()) def changes(output: RecordingControllerOutput) -> list[DeviceParameterChange]: return [e for e in output.events if isinstance(e, DeviceParameterChange)] def values(output: RecordingControllerOutput, parameter_id: UUID) -> list[Any]: return [e.value for e in changes(output) if e.parameter_id == parameter_id] async def wait_for_value( output: RecordingControllerOutput, parameter: ZwaveParameter, predicate: Callable[[Any], bool], timeout: float = 10.0, ) -> Any: await wait_until( lambda: any(predicate(v) for v in values(output, parameter.id)), timeout, f"a value of {parameter.name} (seen: {values(output, parameter.id)})", ) return next(v for v in reversed(values(output, parameter.id)) if predicate(v)) async def command(controller: ZwaveController, device: ZwaveDevice, parameter: ZwaveParameter, value: Any): await controller.send_command( DeviceCommand(device_id=device.id, parameter_id=parameter.id, value=value), device, parameter ) PYTHON_TYPES: dict[ParameterDataType, tuple[type, ...]] = { ParameterDataType.bool: (bool,), ParameterDataType.integer: (int,), ParameterDataType.decimal: (int, float), ParameterDataType.enum: (int,), ParameterDataType.string: (str,), } def assert_values_match_parameters(output: RecordingControllerOutput, device: ZwaveDevice): """Every reported value has the type its parameter declares, and lies within its limits.""" by_id = {p.id: p for p in device.parameters} for change in changes(output): parameter = by_id.get(change.parameter_id) assert parameter is not None, f"event for unknown parameter {change.parameter_id}" if change.value is None or parameter.data_type not in PYTHON_TYPES: continue assert isinstance(change.value, PYTHON_TYPES[parameter.data_type]), ( f"{parameter.name}: {change.value!r} is not {parameter.data_type}" ) if parameter.data_type is not ParameterDataType.bool and isinstance(change.value, int | float): assert parameter.min_value is None or change.value >= parameter.min_value, ( f"{parameter.name}: {change.value}" ) assert parameter.max_value is None or change.value <= parameter.max_value, ( f"{parameter.name}: {change.value}" ) if parameter.data_type is ParameterDataType.enum: assert parameter.valid_values and change.value in parameter.valid_values, ( f"{parameter.name}: {change.value}" ) ================================================================================ # FILE: tests/mock/package.json ================================================================================ { "name": "majordom-zwave-mock-network", "private": true, "description": "Mock Z-Wave network for the end-to-end tests: zwave-js's mock controller and nodes behind a real zwave-js-server", "type": "module", "dependencies": { "@zwave-js/server": "3.11.0", "zwave-js": "15.31.0" } } ================================================================================ # FILE: tests/network.py ================================================================================ """Runs the mock Z-Wave network (tests/mock/network.mjs) as a subprocess and talks to it. The network is zwave-js's own mock controller and mock nodes, with a real zwave-js driver and a real zwave-js-server in front: the integration connects to it exactly as to a real server. Needs Node.js and `npm ci --prefix tests/mock`. """ import asyncio import contextlib import itertools import json import socket from collections.abc import Awaitable, Callable from pathlib import Path from typing import Any, Self MOCK_DIR = Path(__file__).parent / "mock" HOME_ID = 0x7E570001 # the mock controller's home id def free_port() -> int: with socket.socket() as s: s.bind(("127.0.0.1", 0)) return s.getsockname()[1] class MockNetwork: def __init__(self, nodes: list[dict[str, Any]]): self.nodes = nodes self.port = free_port() self.url = f"ws://127.0.0.1:{self.port}" self._process: asyncio.subprocess.Process | None = None self._ids = itertools.count(1) self._lock = asyncio.Lock() async def start(self, serve: bool = True) -> Self: if not (MOCK_DIR / "node_modules").exists(): raise RuntimeError("mock network not installed: run `npm ci --prefix tests/mock`") self._process = await asyncio.create_subprocess_exec( "node", str(MOCK_DIR / "network.mjs"), json.dumps({"nodes": self.nodes}), stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, limit=2**20, ) line = await asyncio.wait_for(self._stdout.readline(), 60) if json.loads(line or b"{}").get("ready") is not True: raise RuntimeError(f"mock network did not start: {line!r}") if serve: await self.serve() return self @property def _stdout(self) -> asyncio.StreamReader: assert self._process is not None and self._process.stdout is not None return self._process.stdout async def call(self, cmd: str, **args: Any) -> dict[str, Any]: assert self._process is not None and self._process.stdin is not None async with self._lock: request_id = next(self._ids) self._process.stdin.write(json.dumps({"id": request_id, "cmd": cmd, **args}).encode() + b"\n") await self._process.stdin.drain() reply = json.loads(await asyncio.wait_for(self._stdout.readline(), 30)) if not reply.get("ok"): raise RuntimeError(f"mock network {cmd} failed: {reply.get('error')}") return reply["result"] async def serve(self): """Start (or restart) zwave-js-server on this network's port.""" await self.call("server", port=self.port) async def drop_server(self): """Stop zwave-js-server: connected clients lose their connection, the network itself keeps running.""" await self.call("drop_server") async def join(self, node: int, kind: str, **options: Any) -> dict[str, str]: """Make a node wait for inclusion; returns its S2 `pin` and `dsk`, as printed on a real device's label.""" return await self.call("join", node=node, kind=kind, **options) async def report(self, node: int, kind: str, value: Any): await self.call("report", node=node, kind=kind, value=value) async def silence(self, node: int): await self.call("silence", node=node) async def wake(self, node: int): """A sleeping device wakes up: it takes its queued commands, then sleeps again.""" await self.call("wake", node=node) async def power_on(self, node: int): """A provisioned (SmartStart) device is powered on: it asks to join, and is included by its DSK.""" await self.call("power_on", node=node) async def awake(self, node: int) -> bool: return (await self.call("awake", node=node))["awake"] async def reject(self, node: int): """The node refuses the commands it gets (a supervised command is answered with a Fail status).""" await self.call("reject", node=node) async def desync(self, node: int): """The node's S2 session dies (a power cut): it ignores S2 until the controller sends it a nonce.""" await self.call("desync", node=node) async def switch(self, node: int) -> bool: """What the device's relay really is, whatever zwave-js assumes.""" return (await self.call("switch", node=node))["value"] async def fail(self, node: int): await self.call("fail", node=node) async def revive(self, node: int): await self.call("revive", node=node) async def exclude(self, node: int): await self.call("exclude", node=node) async def reset(self, node: int): """The device is factory reset: it tells the controller it left, and goes silent.""" await self.call("reset", node=node) async def node_ids(self) -> list[int]: return (await self.call("nodes"))["nodes"] async def frames(self, node: int) -> list[str]: """The CC commands the node received, by class name (e.g. `IndicatorCCSet`).""" return (await self.call("frames", node=node))["frames"] async def stop(self): if self._process is None or self._process.returncode is not None: return with contextlib.suppress(RuntimeError, ConnectionError, TimeoutError, json.JSONDecodeError): await self.call("stop") try: await asyncio.wait_for(self._process.wait(), 10) except TimeoutError: self._process.kill() await self._process.wait() type MakeNetwork = Callable[..., Awaitable[MockNetwork]] # the `make_network` fixture ================================================================================ # FILE: tests/test_catalogue.py ================================================================================ """The catalogue: every command class zwave-js knows is hosted, plumbing, or explained (fast checks); one mock device per hosted CC maps exactly as expected and round-trips every writable value (the sweep). The monthly canary runs it against the latest zwave-js, zwave-js-server and zwave-js-server-python: new CCs, values, value types and units fail here until they are supported or explained. """ import json import logging import re import subprocess from collections import Counter from types import SimpleNamespace from typing import Any, cast import pytest from majordom_integration_sdk.parameter_audit import audit_device_parameters from majordom_integration_sdk.schemas.parameter import ParameterDataType, ParameterRole, ParameterVisibility from majordom_integration_sdk.testing import RecordingControllerOutput from zwave_js_server.const import CommandClass from zwave_js_server.model.value import Value, ValueMetadata from majordom_zwave import ZwaveController, mapper from majordom_zwave.model import ZwaveDevice from majordom_zwave.zwave_spec import CONVERTED_UNITS, PLAIN_UNITS, UNIT_MAP from tests.catalogue import ( COMMON, EXPECTED, INFRASTRUCTURE, MAIN, NEWER_THAN_THE_LIBRARY, NO_REPORT, PLUMBING, RECIPES, SIMILAR_NAMES, UNHOSTABLE, VARIANTS, ) from tests.helpers import command, pair, values, wait_for_value from tests.network import MOCK_DIR, MockNetwork @pytest.fixture(scope="module") def registry() -> dict[str, Any]: """What the installed zwave-js knows (tests/mock/registry.mjs).""" result = subprocess.run(["node", str(MOCK_DIR / "registry.mjs")], capture_output=True, text=True, check=True) return json.loads(result.stdout) pytestmark = pytest.mark.usefixtures("patient") def key(value_id: str) -> str: return value_id.split("-", 1)[1] # Fast checks: what zwave-js knows is supported or explained --------------------------------------------------------- def test_every_command_class_is_hosted_plumbing_or_explained(registry: dict[str, Any]): known = {int(cc): name for cc, name in registry["commandClasses"].items()} hosted = set().union(*RECIPES.values()) | INFRASTRUCTURE unexplained = { f"{name} (0x{cc:02x})" for cc, name in known.items() if cc not in hosted | PLUMBING | UNHOSTABLE.keys() } assert not unexplained, ( f"new command classes {sorted(unexplained)}: write a recipe (tests/mock/catalogue.mjs, tests/catalogue.py), " "or say in tests/catalogue.py why the mock network cannot host it" ) assert not hosted & UNHOSTABLE.keys(), "a hosted CC is listed as unhostable" def test_command_classes_newer_than_the_library_are_known(registry: dict[str, Any]): library = {int(cc) for cc in CommandClass} newer = {int(cc) for cc in registry["commandClasses"]} - library assert newer <= NEWER_THAN_THE_LIBRARY.keys(), ( f"zwave-js knows CCs zwave-js-server-python does not: {sorted(hex(cc) for cc in newer)}" ) def test_every_value_type_is_mapped(registry: dict[str, Any]): assert set(registry["valueTypes"]) == mapper.KNOWN_VALUE_TYPES, ( "zwave-js's value metadata types changed: map the new ones in mapper.data_type" ) def test_every_unit_is_mapped_converted_or_deliberately_plain(registry: dict[str, Any]): handled = UNIT_MAP.keys() | CONVERTED_UNITS.keys() | PLAIN_UNITS assert set(registry["units"]) <= handled, ( f"new units {sorted(set(registry['units']) - handled)}: map, convert, or list them in zwave_spec.PLAIN_UNITS" ) def test_the_catalogue_tables_agree(registry: dict[str, Any]): assert set(registry["recipes"]) >= RECIPES.keys() | VARIANTS.keys(), "a recipe is missing in catalogue.mjs" assert EXPECTED.keys() == RECIPES.keys() assert MAIN.keys() <= RECIPES.keys() # Value shapes, for the CCs the mock network cannot host -------------------------------------------------------------- def shape(metadata: dict[str, Any], value: Any = None, command_class: int = 0x99) -> Value: """A value of a CC with no mock, with the given metadata: only what the mapper reads.""" stand_in = SimpleNamespace( value_id=f"5-{command_class}-0-value", command_class=command_class, endpoint=0, property_="value", property_key=None, property_name="value", value=value, metadata=ValueMetadata(cast(Any, {"readable": True, "writeable": False, **metadata})), ) return cast(Value, stand_in) @pytest.mark.parametrize( ("metadata", "value", "data_type"), [ ({"type": "number"}, 4, ParameterDataType.integer), ({"type": "number", "states": {"0": "Off", "1": "On"}}, 0, ParameterDataType.enum), ({"type": "number", "states": {"0": "Off"}, "allowManualEntry": True}, 0, ParameterDataType.integer), ({"type": "boolean"}, True, ParameterDataType.bool), ( {"type": "boolean", "readable": False, "writeable": True, "states": {"true": "Go"}}, None, ParameterDataType.none, ), ({"type": "string"}, "text", ParameterDataType.string), ({"type": "color"}, "ff0000", ParameterDataType.string), ({"type": "duration"}, {"value": 2, "unit": "seconds"}, ParameterDataType.string), ({"type": "timeout"}, {"value": 2, "unit": "seconds"}, ParameterDataType.string), ({"type": "number[]"}, [1, 2], ParameterDataType.data), ({"type": "boolean[]"}, [True], ParameterDataType.data), ({"type": "string[]"}, ["a"], ParameterDataType.string), # shown as text: "1.0, 2.3" ({"type": "buffer"}, "AQI=", ParameterDataType.data), ({"type": "any"}, 1.5, ParameterDataType.decimal), ({"type": "any"}, {"a": 1}, ParameterDataType.data), ], ) def test_every_value_shape_maps(metadata: dict[str, Any], value: Any, data_type: ParameterDataType): mapped = shape(metadata, value) assert mapper.data_type(mapped) == data_type if data_type == ParameterDataType.data: assert mapper.visibility(mapped, cast(Any, SimpleNamespace(values={}))) == ParameterVisibility.system def test_a_command_class_nobody_reviewed_is_hidden_but_kept(): """ "When in doubt, hide it": a value of a CC not in the catalogue is `system` (automations and the API still see it); the same value of a reviewed CC is a `setting`.""" node = cast(Any, SimpleNamespace(values={})) reading = {"type": "number", "label": "Reading"} irrigation, configuration = 0x6B, 0x70 assert mapper.visibility(shape(reading, 4, command_class=irrigation), node) == ParameterVisibility.system assert mapper.visibility(shape(reading, 4, command_class=configuration), node) == ParameterVisibility.setting def test_an_unknown_value_type_is_hidden_and_logged(caplog: pytest.LogCaptureFixture): mapped = shape({"type": "quaternion"}, [1, 0, 0, 0]) with caplog.at_level(logging.WARNING): assert mapper.data_type(mapped) == ParameterDataType.data assert "quaternion" in caplog.text def test_an_unknown_unit_is_plain_and_logged(caplog: pytest.LogCaptureFixture): with caplog.at_level(logging.WARNING): assert mapper.unit(shape({"type": "number", "unit": "furlongs"}, 1)) == "plain" assert "furlongs" in caplog.text # The sweep: one mock device per hosted CC ---------------------------------------------------------------------------- @pytest.mark.parametrize("recipe", sorted(RECIPES)) async def test_every_hosted_command_class_maps_as_expected_and_round_trips_its_values( recipe: str, controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): """One test per recipe: pairing it (and starting its network) is most of its cost.""" await controller.start() device = await pair(controller, output, network, 5, recipe) mapped = { key(p.integration_data.value_id): (p.name, p.data_type, p.role, p.visibility, p.unit) for p in device.parameters } expected = {**COMMON, **EXPECTED[recipe]} differences = { k: (mapped.get(k), expected.get(k)) for k in mapped.keys() | expected.keys() if mapped.get(k) != expected.get(k) } assert not differences, "value: (mapped, expected)\n" + "\n".join(f" {k}: {v}" for k, v in differences.items()) main = next((key(p.integration_data.value_id) for p in device.parameters if p.id == device.main_parameter), None) assert main == MAIN.get(recipe) # the SDK's advisory audit: no over-exposed device screen, no near-duplicate user names assert not audit_device_parameters(recipe, device.parameters, ignore_similar_pairs=SIMILAR_NAMES) assert_readable(device) await assert_writable_values_round_trip(controller, output, device) @pytest.mark.parametrize("recipe", sorted(VARIANTS)) async def test_every_variant_maps_by_its_rules( recipe: str, controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, recipe) minimum, rules = VARIANTS[recipe] checked = 0 for parameter in device.parameters: k = key(parameter.integration_data.value_id) rule = next((r for pattern, r in rules.items() if re.fullmatch(pattern, k)), None) if rule is None: continue data_type, role, visibilities, unit = rule assert (parameter.data_type, parameter.role) == (data_type, role), f"{k}: {parameter}" assert parameter.visibility in visibilities, f"{k}: {parameter.visibility}" assert unit is None or parameter.unit == unit, f"{k}: {parameter.unit}" checked += 1 assert checked >= minimum assert_readable(device) def assert_readable(device: Any): """Names and enum labels are for people: unique, without zwave-js's protocol wording, words not camelCase.""" names = Counter(p.name for p in device.parameters) assert not [n for n, count in names.items() if count > 1], f"parameters share a name: {names}" for parameter in device.parameters: assert parameter.name.strip(), parameter assert not re.search(r"\[|Consumption|Sensor state|Setpoint \(|\(Notification\)", parameter.name), ( parameter.name ) assert not re.fullmatch(r"\S*[a-z][A-Z]\S*", parameter.name), parameter.name for label in (parameter.valid_values or {}).values(): assert not re.fullmatch(r"\S*([a-z][A-Z]|[a-z][0-9])\S*", label), label assert not label[:1].islower(), label def new_value(parameter: Any, current: Any) -> Any: """A valid value other than the current one.""" if parameter.data_type == ParameterDataType.bool: return not current if parameter.data_type == ParameterDataType.enum: return next(v for v in sorted(parameter.valid_values, reverse=True) if v != current) middle = (parameter.min_value + parameter.max_value) / 2 # inside the range: some devices refuse its ends if parameter.data_type == ParameterDataType.integer: middle = round(middle) return middle if middle != current else middle + 1 async def assert_writable_values_round_trip( controller: ZwaveController, output: RecordingControllerOutput, device: ZwaveDevice ): """Every writable value the user sees goes through the device and comes back.""" for parameter in device.parameters: k = key(parameter.integration_data.value_id) if parameter.role != ParameterRole.control or parameter.visibility == ParameterVisibility.system: continue if parameter.data_type == ParameterDataType.none: # a button: it is sent, nothing comes back await command(controller, device, parameter, None) continue if k in NO_REPORT or parameter.data_type not in ( ParameterDataType.bool, ParameterDataType.integer, ParameterDataType.decimal, ParameterDataType.enum, ): continue reported = values(output, parameter.id) if not reported: # write-only (start/stop a movement): no state to come back continue target = new_value(parameter, reported[-1]) await command(controller, device, parameter, target) # the device's report, or zwave-js's own check of the value (`refreshValue`) after an unsupervised set await wait_for_value(output, parameter, lambda v, t=target: v == t, timeout=10) ================================================================================ # FILE: tests/test_commands.py ================================================================================ """Commands: Hub → device, and what is reported back.""" import asyncio import pytest from majordom_integration_sdk.schemas.device import CredentialsType, ProvidedCredentials from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_zwave import ZwaveController from tests.helpers import command, pair, param, stored, values, wait_for_value from tests.network import MockNetwork SWITCH = "37-0-targetValue" LEVEL = "38-0-targetValue" async def test_a_command_switches_the_device_and_its_report_comes_back( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) switch = param(device, SWITCH) await command(controller, device, switch, True) assert await wait_for_value(output, switch, lambda v: v is True) is True assert "BinarySwitchCCSet" in await network.frames(5) async def test_a_level_command_is_a_percentage( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "dimmer") level = param(device, LEVEL) await command(controller, device, level, 100) # Z-Wave's top level is 99 assert await wait_for_value(output, level, lambda v: v == 100) == 100 await command(controller, device, level, 40) assert await wait_for_value(output, level, lambda v: v == 40) == 40 async def test_a_failed_command_is_surfaced_and_not_reported_as_applied( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) switch = param(device, SWITCH) await network.silence(5) output.events.clear() with pytest.raises(ConnectionError): await command(controller, device, switch, True) assert True not in values(output, switch.id) assert (await stored(controller, device.physical_id)).last_error async def test_a_command_cut_short_by_the_lost_server_fails_with_a_reason( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): """zwave-js-server's client cancels every pending call when the connection drops; as a cancel, it would pass by the Hub's error handling (the Hub's task was never cancelled).""" await controller.start() device = await pair(controller, output, network) await network.silence(5) # out of range: zwave-js retries the command for a while sending = asyncio.create_task(command(controller, device, param(device, SWITCH), True)) await asyncio.sleep(0.3) await network.drop_server() with pytest.raises(ConnectionError, match="could not be set: the connection to zwave-js-server was lost"): await sending async def test_a_command_the_device_refuses_is_surfaced_and_not_reported_as_applied( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "supervised") switch = param(device, SWITCH) await network.reject(5) output.events.clear() with pytest.raises(RuntimeError): await command(controller, device, switch, True) assert True not in values(output, switch.id) assert (await stored(controller, device.physical_id)).last_error async def test_a_successful_command_clears_the_last_error( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) switch = param(device, SWITCH) await network.silence(5) with pytest.raises(ConnectionError): await command(controller, device, switch, True) await network.revive(5) await command(controller, device, switch, True) assert (await stored(controller, device.physical_id)).last_error is None async def test_a_read_only_parameter_cannot_be_commanded( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sensor") with pytest.raises(ValueError): await command(controller, device, param(device, "49-0-Air temperature"), 30) async def test_a_secure_device_that_ignored_a_command_gets_a_fresh_session_and_the_command_again( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, monkeypatch: pytest.MonkeyPatch, ): """A device that lost power can keep a dead S2 session and never ask for a new one (seen on a Shelly Wave): it takes commands without acting on them. A nonce from the controller starts a new session.""" monkeypatch.setattr(ZwaveController, "VERIFY_DELAY", 0.5) await controller.start() pin = lambda label: ProvidedCredentials(type=CredentialsType.code, value=label["pin"]) # noqa: E731 device = await pair(controller, output, network, 5, "secure", credentials=pin) switch = param(device, SWITCH) await network.desync(5) await command(controller, device, switch, True) for _ in range(50): if await network.switch(5): break await asyncio.sleep(0.1) assert await network.switch(5) is True ================================================================================ # FILE: tests/test_config.py ================================================================================ """zwave-js-server: run on the stick, in the Hub's region, for the controller that needs it; its port is the runtime's to choose: the compose and the endpoint follow it.""" import json from pathlib import Path import pytest from majordom_integration_sdk import Endpoint from majordom_integration_sdk.runtime import Pinned, Runtime, StatusKind from majordom_integration_sdk.testing import FakeCompose, build_test_platform import majordom_zwave from majordom_zwave import ZwaveController from majordom_zwave.config import ZwaveNetwork from tests.helpers import wait_until def test_a_malformed_network_key_is_refused(): with pytest.raises(ValueError, match="pattern"): # zwave-js-server would exit on it, again and again ZwaveNetwork(s2_authenticated="not a key") def test_the_generated_network_keys_are_valid(): keys = ZwaveNetwork().model_dump() assert ZwaveNetwork.model_validate(keys).model_dump() == keys def test_the_network_keys_are_write_only(): """The Hub never reads a write-only field back through its API: with the keys, anyone could decrypt and forge the network's secure traffic.""" fields = ZwaveNetwork.model_json_schema()["properties"] assert fields assert [name for name, field in fields.items() if not field.get("writeOnly")] == [] @pytest.mark.parametrize("listen_address", ["127.0.0.1", "0.0.0.0"]) # the Hub only, or a lab harness on the LAN # none: left out, the stick keeps its own @pytest.mark.parametrize(("region", "rendered"), [("Europe", "Europe"), (None, None)]) async def test_runs_on_the_stick_in_the_hubs_region_for_the_controller( tmp_path: Path, region: str | None, rendered: str | None, listen_address: str ): platform = build_test_platform(tmp_path / "peripherals", region=region) stick = Endpoint("zwave", "serial-api", "/dev/serial/by-id/usb-0658_0200-if00") exported = majordom_zwave.peripherals(platform) [controller] = [peripheral for peripheral in exported if isinstance(peripheral, ZwaveController)] runtime = Runtime(tmp_path, [Pinned(stick), FakeCompose(listen_address), *exported], platform=platform) await runtime.start() try: # started once the server runs; FakeCompose runs none, so it fails to connect and is started again later await wait_until(lambda: runtime.status(controller).kind == StatusKind.RETRYING, 10, "the controller's start") assert runtime.providers(controller) == {"zwave": "zwave-js-server"} compose = json.loads((tmp_path / "peripherals" / "compose" / "compose.json").read_text()) container = compose["services"]["zwave-js-server"] assert container["devices"] == [f"{stick.url}:/dev/zwave"] assert container["environment"].get("RF_REGION") == rendered port = container["command"][container["command"].index("--port") + 1] assert controller.peripherals.endpoint("zwave").url == f"ws://127.0.0.1:{port}" # on the host network, unauthenticated: anyone on the LAN could drive the stick (unlock doors, wipe it) assert container["command"][container["command"].index("--host") + 1] == listen_address finally: await runtime.stop() ================================================================================ # FILE: tests/test_device_configs.py ================================================================================ """Our device files, mounted as zwave-js's priority dir: what zwave-js reads from them.""" import json import subprocess from pathlib import Path import pytest import majordom_zwave CONFIGS = Path(majordom_zwave.__file__).parent / "device_configs" SHELLY_WAVE_1 = (0x0460, 0x0002, 0x0083) def parameter(device: tuple[int, int, int], firmware: str, number: int) -> dict: args = ["node", "device_config.mjs", str(CONFIGS), *map(str, device), firmware, str(number)] done = subprocess.run(args, cwd=Path(__file__).parent / "mock", capture_output=True, text=True, check=True) return json.loads(done.stdout.splitlines()[-1]) @pytest.mark.parametrize( ("firmware", "size", "reset"), [ ("10.13", 4, 0x55555555), ("10.14", 1, 1), ("11.5", 1, 1), ("11.6", 4, 0x55555555), ("12.1", 4, 0x55555555), ("12.2", 1, 1), ("13.1", 1, 1), ], ) def test_the_shelly_wave_1_factory_reset_follows_its_firmware(firmware: str, size: int, reset: int): factory_reset = parameter(SHELLY_WAVE_1, firmware, 120) assert str(CONFIGS) in factory_reset["file"] assert (factory_reset["valueSize"], max(factory_reset["options"])) == (size, reset) ================================================================================ # FILE: tests/test_identify.py ================================================================================ """Identify: make the device show itself, without switching what it controls.""" import pytest from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_zwave import ZwaveController from tests.helpers import pair from tests.network import MockNetwork async def test_a_device_with_the_identify_indicator_identifies_itself( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "identifiable") await controller.identify(device) frames = await network.frames(5) assert "IndicatorCCSet" in frames assert "BinarySwitchCCSet" not in frames async def test_a_light_without_the_indicator_blinks_and_returns_to_its_level( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "bulb") await controller.identify(device) frames = await network.frames(5) assert frames.count("MultilevelSwitchCCSet") >= 3 # off/on blinks, then back to the level it had @pytest.mark.parametrize("kind", ["switch", "dimmer"]) async def test_a_device_not_known_to_be_a_light_is_not_toggled( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, kind: str ): await controller.start() device = await pair(controller, output, network, 5, kind) # a relay or a motor: a heater, a pump, a blind await controller.identify(device) frames = await network.frames(5) assert "BinarySwitchCCSet" not in frames assert "MultilevelSwitchCCSet" not in frames ================================================================================ # FILE: tests/test_lifecycle.py ================================================================================ """Lifecycle: start, restart, availability, losing the server, and devices that change behind the Hub's back.""" import asyncio import contextlib import sqlite3 from pathlib import Path from uuid import UUID import aiohttp import pytest from majordom_integration_sdk import Endpoint, IntegrationError, Platform from majordom_integration_sdk.runtime import Pinned, Runtime, StatusKind from majordom_integration_sdk.schemas.device import CredentialsType, ProvidedCredentials from majordom_integration_sdk.testing import RecordingControllerOutput from zwave_js_server.client import Client from majordom_zwave import ZwaveController from tests.helpers import command, pair, param, stored, wait_for_value, wait_until from tests.network import MakeNetwork, MockNetwork, free_port SWITCH = "37-0-targetValue" async def restart(controller: ZwaveController, platform: Platform) -> ZwaveController: """Stop and start the integration again, with the Hub's data kept (a Hub restart).""" await controller.stop() again = ZwaveController(platform) again.peripherals, again.output = controller.peripherals, controller.output await again.start() return again async def test_paired_devices_are_reconnected_after_a_restart( controller: ZwaveController, platform: Platform, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) output.connected_devices.clear() again = await restart(controller, platform) try: assert device.physical_id in output.connected_devices await network.report(5, "switch", True) assert await wait_for_value(output, param(device, SWITCH), lambda v: v is True) assert device.physical_id not in again.discoveries # paired, not offered again finally: await again.stop() async def test_a_device_that_stops_answering_is_lost_and_found_again( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) switch = param(device, SWITCH) await network.silence(5) with contextlib.suppress(ConnectionError): # it does not answer await command(controller, device, switch, True) await wait_until(lambda: device.physical_id in output.lost_devices, 10, "the device to be lost") lost = await stored(controller, device.physical_id) assert lost.available is False assert lost.last_error output.connected_devices.clear() await network.revive(5) await wait_until(lambda: device.physical_id in output.connected_devices, 10, "the device to come back") back = await stored(controller, device.physical_id) assert back.available is True assert back.last_error is None async def test_a_dead_device_is_reported_unavailable_after_a_restart( controller: ZwaveController, platform: Platform, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) await network.silence(5) with contextlib.suppress(ConnectionError): await command(controller, device, param(device, SWITCH), True) await wait_until(lambda: device.physical_id in output.lost_devices, 10, "the device to be lost") output.lost_devices.clear() output.connected_devices.clear() again = await restart(controller, platform) try: assert device.physical_id in output.lost_devices assert device.physical_id not in output.connected_devices finally: await again.stop() async def test_losing_the_server_loses_the_devices_and_it_reconnects_when_back( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) await network.drop_server() await wait_until(lambda: device.physical_id in output.lost_devices, 10, "the devices to be lost with the server") output.connected_devices.clear() await network.serve() await wait_until(lambda: device.physical_id in output.connected_devices, 15, "the reconnection") await network.report(5, "switch", True) assert await wait_for_value(output, param(device, SWITCH), lambda v: v is True) async def test_it_reconnects_though_reporting_the_lost_server_failed( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, monkeypatch: pytest.MonkeyPatch, ): await controller.start() device = await pair(controller, output, network) lose_device = output.controller_did_lose_device failures = [sqlite3.OperationalError("database is locked")] # the Hub's store, busy once async def busy_once(controller: ZwaveController, *, physical_id: UUID): if failures: raise failures.pop() await lose_device(controller, physical_id=physical_id) monkeypatch.setattr(output, "controller_did_lose_device", busy_once) await network.drop_server() await wait_until(lambda: not controller.connected, 10, "the server to be lost") output.connected_devices.clear() await network.serve() await wait_until(lambda: device.physical_id in output.connected_devices, 15, "the reconnection") def reported(output: RecordingControllerOutput) -> list[str]: return [e.id for e in output.error_log if isinstance(e, IntegrationError)] async def test_a_server_that_stays_lost_is_reported_until_it_is_back( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, monkeypatch: pytest.MonkeyPatch, ): monkeypatch.setattr(ZwaveController, "REPORT_OUTAGE_AFTER", 1.0) await controller.start() device = await pair(controller, output, network) await network.drop_server() await wait_until(lambda: device.physical_id in output.lost_devices, 10, "the devices to be lost with the server") assert not output.errors # one failed reconnect is no outage yet await wait_until(lambda: output.errors, 10, "the lost server to be reported") await asyncio.sleep(1.5) # a few more failed reconnects assert list(output.errors) == ["server-unreachable"] await network.serve() await wait_until(lambda: not output.errors, 15, "the reconnection to resolve it") async def test_a_server_that_keeps_dropping_the_connection_is_reported( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, monkeypatch: pytest.MonkeyPatch, ): """Each connection holds for a moment only: the drops add up to one outage, until a connection holds.""" monkeypatch.setattr(ZwaveController, "REPORT_OUTAGE_AFTER", 1.0) await controller.start() for _ in range(6): await network.drop_server() await wait_until(lambda: not controller.connected, 10, "the drop") await network.serve() await wait_until(lambda: controller.connected, 10, "the reconnection") assert "server-unreachable" in reported(output) async def test_a_server_lost_long_after_it_came_back_is_a_new_outage( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, monkeypatch: pytest.MonkeyPatch, ): monkeypatch.setattr(ZwaveController, "REPORT_OUTAGE_AFTER", 1.0) monkeypatch.setattr(ZwaveController, "STABLE_CONNECTION", 0.5) await controller.start() await network.drop_server() await wait_until(lambda: not controller.connected, 10, "the drop") await network.serve() await wait_until(lambda: controller.connected, 10, "the reconnection") await asyncio.sleep(1.5) # held: the outage ended (and began longer ago than its report delay) await network.drop_server() await wait_until(lambda: not controller.connected, 10, "the second drop") await asyncio.sleep(0.1) assert reported(output) == [] # not yet: this outage only began async def test_starting_without_the_server_fails_and_a_later_start_connects( controller: ZwaveController, output: RecordingControllerOutput, make_network: MakeNetwork ): network = await make_network(serve=False) with pytest.raises(ConnectionError, match="unreachable"): await controller.start() assert not output.errors # the runtime says why it failed, and starts it again later await controller.stop() # as the runtime does after a failed start await network.serve() await controller.start() assert controller.connected async def test_a_start_the_hub_cut_short_doesnt_blame_the_server( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, monkeypatch: pytest.MonkeyPatch, ): async def busy(controller: ZwaveController, error_id: str): raise sqlite3.OperationalError("database is locked") # the Hub's store monkeypatch.setattr(output, "controller_did_resolve_error", busy) with pytest.raises(ConnectionError, match="^Z-Wave failed to start: database is locked$"): await controller.start() async def test_the_runtime_starts_again_a_controller_whose_server_doesnt_answer( controller: ZwaveController, tmp_path: Path ): server = Endpoint("zwave", "zwave-js-ws", f"ws://127.0.0.1:{free_port()}") # nothing listens there runtime = Runtime(tmp_path, [Pinned(server), controller], platform=controller.platform) await runtime.start() try: await wait_until(lambda: runtime.status(controller).kind == StatusKind.RETRYING, 10, "the retry") assert "unreachable" in runtime.status(controller).detail finally: await runtime.stop() async def test_stop_is_clean_without_a_connection(controller: ZwaveController, make_network: MakeNetwork): await make_network(serve=False) with pytest.raises(ConnectionError): await controller.start() await controller.stop() await controller.stop() async def test_the_same_controller_started_again_keeps_nothing_of_its_last_run( controller: ZwaveController, output: RecordingControllerOutput, make_network: MakeNetwork ): """The runtime starts the instance it stopped (a retry, a moved need), here on another stick without the device.""" network = await make_network() await controller.start() device = await pair(controller, output, network) await controller.start_pairing_window(60, ProvidedCredentials(type=CredentialsType.code, value="12345")) await controller.stop() await make_network() await controller.start() # zwave-js-server asks every client for the PIN of an inclusion no client started: an old one would answer it assert controller._credentials is None with pytest.raises(ConnectionError): await controller.fetch(device) await asyncio.wait_for(controller.unpair(device), 1) # gone: nothing to exclude async def test_a_device_excluded_elsewhere_is_lost_with_a_reason( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) # removed with another tool (e.g. Z-Wave JS UI, another client of the same server) while the integration runs async with aiohttp.ClientSession() as session: other_tool = Client(network.url, session) await other_tool.connect() ready = asyncio.Event() listening = asyncio.create_task(other_tool.listen(ready)) await ready.wait() assert other_tool.driver is not None await other_tool.driver.controller.async_begin_exclusion() await network.exclude(5) await other_tool.disconnect() listening.cancel() await wait_until(lambda: device.physical_id in output.lost_devices, 10, "the excluded device to be lost") assert (await stored(controller, device.physical_id)).last_error async def test_a_dead_device_that_then_leaves_says_it_left( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): """A factory reset first looks like a device that stopped answering; the reason must then say it left.""" await controller.start() device = await pair(controller, output, network) await network.silence(5) with contextlib.suppress(ConnectionError): await command(controller, device, param(device, SWITCH), True) await wait_until(lambda: device.physical_id in output.lost_devices, 10, "the silent device to be lost") await network.reset(5) for _ in range(100): if "removed" in ((await stored(controller, device.physical_id)).last_error or ""): break await asyncio.sleep(0.1) assert "removed" in ((await stored(controller, device.physical_id)).last_error or "") async def test_another_device_reusing_a_node_id_is_not_taken_for_the_paired_one( controller: ZwaveController, platform: Platform, output: RecordingControllerOutput, make_network: MakeNetwork ): network = await make_network() await controller.start() device = await pair(controller, output, network) await controller.stop() await network.stop() # while the Hub was off, the device was replaced: another product now has node id 5 await make_network([{"node": 5, "kind": "switch", "productId": 2}]) output.connected_devices.clear() again = ZwaveController(platform) again.peripherals, again.output = controller.peripherals, controller.output await again.start() try: assert device.physical_id not in output.connected_devices assert device.physical_id in output.lost_devices assert (await stored(again, device.physical_id)).last_error finally: await again.stop() ================================================================================ # FILE: tests/test_notifications.py ================================================================================ """Notifications: what devices send as one-off events rather than values (zwave-js "notification" events) — a keypad's entries, Notification CC events, a remote's dimming, a low battery, a radio test's result.""" import json import pytest from majordom_integration_sdk.schemas.parameter import ParameterRole from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_zwave import ZwaveController from tests.helpers import pair, param, values, wait_for_value from tests.network import MockNetwork from tests.test_sleeping import wait_for_asleep pytestmark = pytest.mark.usefixtures("patient") async def test_a_keypad_entry_reports_its_event_and_the_code( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "entry_control") event, code = param(device, "111-0-event"), param(device, "111-0-code") assert event.role == code.role == ParameterRole.event assert event.valid_values == {2: "Enter", 3: "Disarm all", 5: "Away", 6: "Home", 25: "Cancel"} # what it supports await network.report(5, "keypad", {"eventType": 2, "code": "1234"}) # 1234, then Enter assert await wait_for_value(output, event, lambda v: v == 2) == 2 assert await wait_for_value(output, code, lambda v: v == "1234") == "1234" async def test_a_keypad_event_without_a_code_reports_no_code( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "entry_control") event, code = param(device, "111-0-event"), param(device, "111-0-code") await network.report(5, "keypad", {"eventType": 5}) # the Away button assert await wait_for_value(output, event, lambda v: v == 5) == 5 assert values(output, code.id) == [] async def test_a_notification_event_reports_the_event_and_its_details( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 6, "notification") event, details = param(device, "113-0-event-6"), param(device, "113-0-details-6") # Access Control assert event.name == "Access control event" assert event.valid_values == { 1: "Manual lock operation", 2: "Manual unlock operation", 5: "Keypad lock operation", 6: "Keypad unlock operation", } await network.report(6, "notification", {"type": 6, "event": 5, "parameters": [3]}) # locked with user 3's code assert await wait_for_value(output, event, lambda v: v == 5) == 5 reported = await wait_for_value(output, details, lambda v: v is not None) assert json.loads(reported) == {"userId": 3} async def test_a_notification_event_without_details_reports_none( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 6, "notification") event, details = param(device, "113-0-event-6"), param(device, "113-0-details-6") await network.report(6, "notification", {"type": 6, "event": 1}) # locked by hand assert await wait_for_value(output, event, lambda v: v == 1) == 1 assert values(output, details.id) == [] async def test_an_event_the_device_did_not_announce_is_not_reported( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 6, "notification") event = param(device, "113-0-event-6") await network.report(6, "notification", {"type": 6, "event": 3}) # auto lock: not in its supported events await network.report(6, "notification", {"type": 6, "event": 2}) await wait_for_value(output, event, lambda v: v == 2) assert values(output, event.id) == [2] # a value outside the enum would not be a valid state async def test_dimming_from_the_device_reports_start_and_stop( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 7, "multilevel_switch") change = param(device, "38-0-levelChange") assert change.valid_values == {0: "Stopped", 1: "Started up", 2: "Started down"} await network.report(7, "level_change", "up") await wait_for_value(output, change, lambda v: v == 1) await network.report(7, "level_change", "stop") await wait_for_value(output, change, lambda v: v == 0) await network.report(7, "level_change", "down") await wait_for_value(output, change, lambda v: v == 2) async def test_a_low_battery_reports_that_it_needs_replacing( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 8, "sleeping") replacement = param(device, "128-0-replacement") await wait_for_asleep(network, 8) await network.wake(8) await network.report(8, "battery_low", None) assert await wait_for_value(output, replacement, lambda v: v == 1) == 1 # soon async def test_a_radio_test_result_is_reported( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 9, "powerlevel") result = param(device, "115-0-test") await network.report(9, "powerlevel", 1) # success assert await wait_for_value(output, result, lambda v: v == 1) == 1 ================================================================================ # FILE: tests/test_pairing.py ================================================================================ """Pairing: inclusion through the pairing window, S2 credentials, and what pairing leaves in the Hub.""" import asyncio from typing import Any from uuid import UUID import pytest from majordom_integration_sdk import DeviceIdTakenError, Endpoint, Peripherals from majordom_integration_sdk.schemas.device import CredentialsType, ProvidedCredentials from majordom_integration_sdk.schemas.parameter import ParameterRole, ParameterVisibility from majordom_integration_sdk.testing import RecordingControllerOutput, build_test_platform from zwave_js_server.const import InclusionState from zwave_js_server.model.controller import Controller from majordom_zwave import ZwaveController from tests.helpers import ROOM, discover, hub_draft, hub_pairs, pair, param, stored, wait_until from tests.network import HOME_ID, MockNetwork BINARY_SWITCH = "37-0-targetValue" async def test_a_device_included_in_the_pairing_window_is_discovered( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() discovery = await discover(controller, output, network, 5, "switch") assert discovery.integration == controller.key assert discovery.transport == "ZWAVE" assert discovery.expected_credentials_options == [CredentialsType.none] assert discovery.id in controller.discoveries async def test_pairing_completes_the_device_the_hub_saved( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) assert (device.name, device.room_id) == ("Hall lamp", ROOM) # kept from the Hub assert device.available is True assert device.last_error is None assert device.integration_data is not None assert (device.integration_data.home_id, device.integration_data.node_id) == (HOME_ID, 5) assert device.parameters assert device.physical_id in output.connected_devices assert device.physical_id not in controller.discoveries async def test_identity_is_derived_through_the_sdk_helpers( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) # the home id scopes the node id: node ids repeat across networks and are reused after a device leaves assert device.physical_id == controller.device_uuid(f"{HOME_ID:08x}-5") for parameter in device.parameters: assert parameter.id == controller.parameter_uuid( device.physical_id, parameter.integration_data.value_id, strip="" ) async def test_the_switch_is_one_parameter_and_the_main_one( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) switch = param(device, BINARY_SWITCH) # commands go to targetValue, the state comes from currentValue assert switch.integration_data.state_value_id == "5-37-0-currentValue" assert (switch.role, switch.visibility) == (ParameterRole.control, ParameterVisibility.user) assert not [p for p in device.parameters if p.integration_data.value_id.endswith("-37-0-currentValue")] assert device.main_parameter == switch.id assert switch.default_value is None # a bool: a tap toggles it (a single value would be an always-on button) async def test_pair_device_fills_the_draft_and_changes_nothing_in_the_hub( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() discovery = await discover(controller, output, network, 5, "switch") events = len(output.events) paired = await controller.pair_device(discovery, hub_draft(discovery, "Porch"), None) assert (paired.physical_id, paired.name, paired.room_id) == (discovery.id, "Porch", ROOM) assert paired.integration_data is not None assert (paired.integration_data.home_id, paired.integration_data.node_id) == (HOME_ID, 5) assert paired.parameters assert paired.main_parameter assert paired.available is True async with controller.platform.device_repository(controller) as repo: assert await repo.get(physical_id=discovery.id) is None assert discovery.id not in output.connected_devices assert len(output.events) == events # the Hub reports the device after it saved it assert discovery.id in controller.discoveries # a refused save leaves the node to pair again async def test_pair_device_refuses_an_id_another_record_holds(output: RecordingControllerOutput, fast: None): store: dict[UUID, dict[str, Any]] = {} controller = ZwaveController(build_test_platform(store=store)) controller.output = output held = controller.device_uuid(f"{HOME_ID:08x}-5") store[UUID(int=7)] = {"name": "Old lamp", "physical_id": str(held)} # paired: the default network = MockNetwork([]) await network.start() controller.peripherals = Peripherals({"zwave": Endpoint("zwave", "zwave-js-ws", network.url)}) try: await controller.start() discovery = await discover(controller, output, network, 5, "switch") picked = hub_draft(discovery).model_copy(update={"id": UUID(int=9)}) with pytest.raises(DeviceIdTakenError) as taken: await controller.pair_device(discovery, picked, None) assert (taken.value.name, taken.value.is_paired) == ("Old lamp", True) assert discovery.id in controller.discoveries assert not output.updated_discoveries # the id is not the device's fault finally: await controller.stop() await network.stop() async def test_a_device_that_never_becomes_ready_fails_pairing_and_stays_discovered( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() discovery = await discover(controller, output, network, 5, "switch", silent=True) # joins, then never answers with pytest.raises(TimeoutError): await controller.pair_device(discovery, hub_draft(discovery), None) assert output.updated_discoveries[-1].last_error assert discovery.id in controller.discoveries async def test_a_failed_pairing_is_retried_from_the_same_discovery( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, monkeypatch: pytest.MonkeyPatch, ): await controller.start() discovery = await discover(controller, output, network, 5, "switch") with monkeypatch.context() as patched: patched.setattr(controller, "_wait_until_ready", _raise(TimeoutError("not ready"))) with pytest.raises(TimeoutError): await controller.pair_device(discovery, hub_draft(discovery), None) assert 5 in await network.node_ids() # nothing undone: it stays included assert controller._controller().inclusion_state == InclusionState.IDLE # no exclusion begun device = await hub_pairs(controller, controller.discoveries[discovery.id]) assert device.parameters and discovery.id not in controller.discoveries async def test_a_pairing_the_hub_never_saved_is_retried_from_the_same_discovery( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() discovery = await discover(controller, output, network, 5, "switch") draft = await controller.pair_device(discovery, hub_draft(discovery), None) # the Hub failed to save it, and rolled it back, twice: nothing undone await controller.unpair(draft) await controller.unpair(draft) assert controller._controller().inclusion_state == InclusionState.IDLE # no exclusion begun assert discovery.id in controller.discoveries device = await hub_pairs(controller, controller.discoveries[discovery.id]) assert device.physical_id == discovery.id and discovery.id not in controller.discoveries assert 5 in await network.node_ids() def _raise(error: Exception): async def fail(*_args: Any): raise error return fail async def test_pairing_an_unknown_discovery_fails( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() discovery = await discover(controller, output, network, 5, "switch") stale = discovery.model_copy(update={"id": controller.device_uuid("nothing")}) with pytest.raises(ValueError): await controller.pair_device(stale, hub_draft(stale), None) async def test_stopping_ends_a_pairing_that_waits_for_the_interview( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() discovery = await discover(controller, output, network, 5, "switch", silent=True) pairing = asyncio.create_task(controller.pair_device(discovery, hub_draft(discovery), None)) await asyncio.sleep(0.3) await controller.stop() with pytest.raises(ConnectionError): # at once, not when the interview times out await asyncio.wait_for(pairing, 1) assert not controller.discoveries # not offered again by a pairing that outlived the stop async def test_losing_the_server_ends_a_pairing_that_waits_for_the_interview( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): """The lost connection's node never hears the interview end (the next connection has nodes of its own).""" await controller.start() discovery = await discover(controller, output, network, 5, "switch", silent=True) pairing = asyncio.create_task(controller.pair_device(discovery, hub_draft(discovery), None)) await asyncio.sleep(0.3) await network.drop_server() with pytest.raises(ConnectionError, match="lost"): # at once, not when the interview times out with other advice await asyncio.wait_for(pairing, 2) assert "pair the device again" in (output.updated_discoveries[-1].last_error or "") assert discovery.id in controller.discoveries async def test_a_pairing_that_outlives_a_stop_returns_nothing( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork, monkeypatch: pytest.MonkeyPatch, ): """Stopped while the node is read: refused, and the next start offers the node again.""" await controller.start() discovery = await discover(controller, output, network, 5, "switch") reading = asyncio.Event() async def slow_read(node: Any) -> list[dict[str, Any]]: reading.set() await asyncio.sleep(0.5) return [] monkeypatch.setattr(controller, "_supported_notification_events", slow_read) pairing = asyncio.create_task(controller.pair_device(discovery, hub_draft(discovery), None)) await reading.wait() await controller.stop() with pytest.raises(ConnectionError, match="pair the device again"): await pairing assert discovery.id not in output.connected_devices async def test_fetch_after_the_save_binds_the_node_once( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) assert device.physical_id in controller._nodes subscriptions = list(controller._unsubscribe[device.physical_id]) await controller.fetch(device) await controller.fetch(device) assert controller._unsubscribe[device.physical_id] == subscriptions # never a second subscription assert device.physical_id not in controller.discoveries async def test_a_pairing_window_opening_across_a_stop_is_refused( controller: ZwaveController, network: MockNetwork, monkeypatch: pytest.MonkeyPatch ): """Stopped after the server opened it, before the Hub's call resumed: its closing task would outlive the stop.""" await controller.start() begin = Controller.async_begin_inclusion answered = asyncio.Event() async def late(self: Controller, *args: Any, **kwargs: Any) -> bool: answer = await begin(self, *args, **kwargs) answered.set() await asyncio.sleep(0.3) # the Hub's task resumes after the stop return answer monkeypatch.setattr(Controller, "async_begin_inclusion", late) opening = asyncio.create_task(controller.start_pairing_window(60)) await answered.wait() await controller.stop() with pytest.raises(ConnectionError): await opening assert not controller._tasks async def test_stopping_closes_the_pairing_window(controller: ZwaveController, network: MockNetwork): """zwave-js-server outlives the controller: an inclusion left running would take the next device for nobody, and keep the next window from opening.""" await controller.start() await controller.start_pairing_window(120) await controller.stop() await controller.start() # the same instance on the same server, as the runtime starts it again assert controller._controller().inclusion_state == InclusionState.IDLE async def test_the_s2_pin_entered_with_the_pairing_window_includes_securely( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() pin = lambda label: ProvidedCredentials(type=CredentialsType.code, value=label["pin"]) # noqa: E731 device = await pair(controller, output, network, 5, "secure", credentials=pin) param(device, BINARY_SWITCH) # only supported securely: present only if S2 bootstrapping succeeded assert output.received_discoveries[-1].last_error is None async def test_the_full_dsk_works_as_the_pin( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() dsk = lambda label: ProvidedCredentials(type=CredentialsType.code, value=label["dsk"]) # noqa: E731 device = await pair(controller, output, network, 5, "secure", credentials=dsk) param(device, BINARY_SWITCH) async def test_the_s2_qr_code_includes_securely( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() qr = lambda label: ProvidedCredentials(type=CredentialsType.qr, value=label["qr"]) # noqa: E731 device = await pair(controller, output, network, 5, "secure", credentials=qr) param(device, BINARY_SWITCH) # only supported securely: present only if S2 bootstrapping succeeded async def test_without_the_pin_a_secure_device_joins_with_lower_security_and_says_so( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() discovery = await asyncio.wait_for(discover(controller, output, network, 5, "secure"), 30) # no waiting for a PIN assert discovery.last_error and "PIN" in discovery.last_error async def test_a_malformed_qr_code_is_rejected(controller: ZwaveController, network: MockNetwork): await controller.start() with pytest.raises(ValueError): await controller.start_pairing_window(60, ProvidedCredentials(type=CredentialsType.qr, value="not a code")) async def test_secret_credentials_are_rejected(controller: ZwaveController, network: MockNetwork): await controller.start() with pytest.raises(ValueError): await controller.start_pairing_window(60, ProvidedCredentials(type=CredentialsType.secret, value="key")) async def test_closing_the_window_keeps_live_unclaimed_devices_and_removes_failed_ones( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() alive = await discover(controller, output, network, 5, "switch", duration=1) await asyncio.sleep(1.5) assert alive.id in controller.discoveries failed = await discover(controller, output, network, 6, "switch", duration=3) for _ in range(100): # joined and interviewed (its state read) — then it fails, before anyone pairs it if "BinarySwitchCCGet" in await network.frames(6): break await asyncio.sleep(0.05) await network.fail(6) await wait_until(lambda: failed.id in output.lost_discoveries, 10, "the failed node's discovery to be dropped") assert 6 not in await network.node_ids() async def test_a_paired_device_can_be_found_again_after_its_discovery( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) assert (await stored(controller, device.physical_id)).id == device.id assert not output.lost_devices async def test_a_device_that_missed_its_identity_is_interviewed_again( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, missIdentity=True) # busy right after joining assert device.integration_data is not None assert device.integration_data.fingerprint # known: its device file applies, and a reused node id is told apart ================================================================================ # FILE: tests/test_sleeping.py ================================================================================ """A sleeping (battery) device: awake only at its wake-ups, so commands wait for the next one.""" import asyncio from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_zwave import ZwaveController from tests.helpers import command, pair, param, stored, values, wait_for_value from tests.network import MockNetwork SWITCH = "37-0-targetValue" async def test_a_sleeping_device_pairs_and_reports_its_battery( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sleeping") # awake while it is included assert values(output, param(device, "128-0-level").id) == [87] async def test_a_command_to_a_sleeping_device_waits_for_its_wake_up( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sleeping") switch = param(device, SWITCH) await wait_for_asleep(network) await command(controller, device, switch, True) # queued by zwave-js: no error, and not applied yet assert True not in values(output, switch.id) assert (await stored(controller, device.physical_id)).last_error is None await network.wake(5) assert await wait_for_value(output, switch, lambda v: v is True) is True async def test_a_sleeping_device_is_not_lost( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sleeping") await wait_for_asleep(network) assert device.physical_id not in output.lost_devices assert (await stored(controller, device.physical_id)).available is True async def test_fetching_a_sleeping_device_is_not_a_failure( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sleeping") await wait_for_asleep(network) await controller.fetch(device) assert device.physical_id not in output.lost_devices async def wait_for_asleep(network: MockNetwork, node: int = 5): """zwave-js sends the device back to sleep once its interview is done.""" for _ in range(100): if not await network.awake(node): return await asyncio.sleep(0.05) raise TimeoutError("the device did not go back to sleep") ================================================================================ # FILE: tests/test_smart_start.py ================================================================================ """SmartStart: a device provisioned from its QR code joins by itself when it is powered on, securely, without a PIN.""" import asyncio import aiohttp from majordom_integration_sdk.schemas.device import CredentialsType, ProvidedCredentials from majordom_integration_sdk.testing import RecordingControllerOutput from zwave_js_server.client import Client from majordom_zwave import ZwaveController from tests.helpers import hub_pairs, param, stored, wait_until from tests.network import MockNetwork SWITCH = "37-0-targetValue" async def provisioned(network: MockNetwork) -> list[str]: """The DSKs zwave-js keeps in its SmartStart provisioning list (read as another client of the server would).""" async with aiohttp.ClientSession() as session: client = Client(network.url, session) await client.connect() ready = asyncio.Event() listening = asyncio.create_task(client.listen(ready)) await ready.wait() assert client.driver is not None entries = await client.driver.controller.async_get_provisioning_entries() await client.disconnect() listening.cancel() return [entry.dsk for entry in entries] async def provision(controller: ZwaveController, network: MockNetwork, duration: int = 60) -> dict[str, str]: label = await network.join(5, "secure", smartStart=True) await controller.start_pairing_window(duration, ProvidedCredentials(type=CredentialsType.qr, value=label["qr"])) return label async def test_a_provisioned_device_joins_when_powered_on_and_pairs_securely( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() label = await provision(controller, network) assert label["dsk"] in await provisioned(network) assert not output.received_discoveries # nothing joins before the device is powered on await network.power_on(5) await wait_until(lambda: output.received_discoveries, 20, "the device to join") discovery = output.received_discoveries[-1] assert discovery.last_error is None # S2 from its QR code: no PIN needed device = await hub_pairs(controller, discovery) param(device, SWITCH) # only supported securely: present only if S2 bootstrapping succeeded async def test_provisioning_outlives_the_pairing_window( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() await provision(controller, network, duration=1) await asyncio.sleep(1.5) # the window closed long before the device is installed and powered await network.power_on(5) await wait_until(lambda: output.received_discoveries, 20, "the device to join") async def test_unpairing_a_smart_start_device_removes_its_provisioning( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() label = await provision(controller, network) await network.power_on(5) await wait_until(lambda: output.received_discoveries, 20, "the device to join") discovery = output.received_discoveries[-1] device = await hub_pairs(controller, discovery) unpairing = asyncio.create_task(controller.unpair(device)) await asyncio.sleep(0.3) await network.exclude(5) await asyncio.wait_for(unpairing, 10) assert label["dsk"] not in await provisioned(network) # or zwave-js would include it again at its next power-up async def test_an_s2_qr_code_is_not_provisioned(controller: ZwaveController, network: MockNetwork): await controller.start() label = await network.join(5, "secure") # an S2 code: included now, in the window await controller.start_pairing_window(60, ProvidedCredentials(type=CredentialsType.qr, value=label["qr"])) assert label["dsk"] not in await provisioned(network) async def test_unpairing_a_smart_start_device_that_reset_itself_removes_its_provisioning( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() label = await provision(controller, network) await network.power_on(5) await wait_until(lambda: output.received_discoveries, 20, "the device to join") discovery = output.received_discoveries[-1] device = await hub_pairs(controller, discovery) await network.reset(5) # it left by itself: no node is left to remove await wait_until(lambda: device.physical_id in output.lost_devices, 10, "the device to leave") await controller.unpair(await stored(controller, device.physical_id)) assert label["dsk"] not in await provisioned(network) # or it would join again at its next power-up async def test_a_smart_start_device_that_reset_itself_is_not_taken_back_in( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): """A factory reset means leaving the network: on the SmartStart list, it would join again the moment it starts.""" await controller.start() label = await provision(controller, network) await network.power_on(5) await wait_until(lambda: output.received_discoveries, 20, "the device to join") discovery = output.received_discoveries[-1] device = await hub_pairs(controller, discovery) await network.reset(5) await wait_until(lambda: device.physical_id in output.lost_devices, 10, "the device to leave") assert label["dsk"] not in await provisioned(network) ================================================================================ # FILE: tests/test_smoke.py ================================================================================ from majordom_zwave import ZwaveController async def test_name_and_key(controller: ZwaveController): assert controller.name == "ZWave" assert controller.key == "zwave" # its identity under the runtime: keep it stable ================================================================================ # FILE: tests/test_state.py ================================================================================ """State: what a paired device reports, in which shape, and how it maps Z-Wave values to parameters.""" from majordom_integration_sdk.schemas.parameter import ( ParameterDataType, ParameterRole, ParameterUnit, ParameterVisibility, ) from majordom_integration_sdk.testing import RecordingControllerOutput from majordom_zwave import ZwaveController from tests.helpers import assert_values_match_parameters, changes, pair, param, values, wait_for_value from tests.network import MockNetwork SWITCH = "37-0-targetValue" LEVEL = "38-0-targetValue" TEMPERATURE = "49-0-Air temperature" async def test_pairing_reports_the_current_value_of_every_readable_parameter( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sensor") temperature = param(device, TEMPERATURE) assert values(output, temperature.id) == [21] assert_values_match_parameters(output, device) async def test_changes_made_on_the_device_are_reported( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) switch = param(device, SWITCH) await network.report(5, "switch", True) # e.g. toggled by hand assert await wait_for_value(output, switch, lambda v: v is True) is True async def test_a_sensor_reading_is_a_decimal_with_its_unit( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sensor") # paired while reading a whole 21 temperature = param(device, TEMPERATURE) assert (temperature.data_type, temperature.unit, temperature.role) == ( ParameterDataType.decimal, ParameterUnit.celsius, ParameterRole.sensor, ) await network.report(5, "sensor", 23.25) await wait_for_value(output, temperature, lambda v: v == 23.25) assert_values_match_parameters(output, device) async def test_fahrenheit_readings_are_reported_in_celsius( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sensor_fahrenheit") temperature = param(device, TEMPERATURE) assert temperature.unit == ParameterUnit.celsius assert values(output, temperature.id) == [21] # 69.8 °F async def test_a_level_is_a_percentage( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "dimmer") level = param(device, LEVEL) assert (level.data_type, level.unit, level.min_value, level.max_value) == ( ParameterDataType.integer, ParameterUnit.percentage, 0, 100, ) assert level.integration_data.state_value_id is not None assert device.main_parameter == level.id assert level.default_value == {0, 100} # a tap toggles off / fully on, within the declared range assert level.main_cycle == [0, 100] async def test_scene_activations_are_events( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "scene") await network.report(5, "scene", 3) # a scene button pressed: stateless, sent as a value notification scene = next(p for p in device.parameters if p.role == ParameterRole.event) assert await wait_for_value(output, scene, lambda v: v == 3) == 3 async def test_compatibility_and_transition_values_are_not_shown( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "sensor") switch = await pair(controller, output, network, 6, "switch") # Basic CC mirrors the real CCs for old controllers; a transition's remaining time is not a state of its own basic = [p for p in device.parameters if p.integration_data.value_id.split("-")[1] == "32"] durations = [p for p in switch.parameters if p.integration_data.value_id.endswith("-duration")] assert basic and durations assert {p.visibility for p in basic + durations} == {ParameterVisibility.system} async def test_parameters_of_another_endpoint_are_told_apart( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "two_switches") names = [p.name for p in device.parameters] assert len(names) == len(set(names)), names assert {"37-1-targetValue", "37-2-targetValue"} <= { p.integration_data.value_id.split("-", 1)[1] for p in device.parameters } async def test_fetch_reports_the_current_values( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) switch = param(device, SWITCH) output.events.clear() await controller.fetch(device) assert values(output, switch.id) == [False] assert {c.parameter_id for c in changes(output)} <= {p.id for p in device.parameters} assert_values_match_parameters(output, device) ================================================================================ # FILE: tests/test_unpair.py ================================================================================ """Unpairing: removing the device from the Z-Wave network.""" import asyncio import pytest from majordom_integration_sdk import DeviceUnreachableError from majordom_integration_sdk.testing import RecordingControllerOutput from zwave_js_server.const import InclusionState from majordom_zwave import ZwaveController from tests.helpers import pair, stored from tests.network import MockNetwork async def test_a_failed_device_is_removed_without_the_device( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) await network.fail(5) with pytest.raises(DeviceUnreachableError): await controller.unpair(device) assert 5 not in await network.node_ids() async def test_a_live_device_is_removed_once_it_confirms_the_exclusion( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) unpairing = asyncio.create_task(controller.unpair(device)) await asyncio.sleep(0.3) assert not unpairing.done() # waits for the user to press the device's button await network.exclude(5) await asyncio.wait_for(unpairing, 10) assert 5 not in await network.node_ids() async def test_stopping_ends_an_unpairing_that_waits_for_the_device( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) unpairing = asyncio.create_task(controller.unpair(device)) await asyncio.sleep(0.3) await controller.stop() with pytest.raises(ConnectionError): # at once, not when the exclusion times out await asyncio.wait_for(unpairing, 1) assert (await stored(controller, device.physical_id)).last_error is None # no button to press any more await controller.start() # on the same server, which outlived the controller assert controller._controller().inclusion_state == InclusionState.IDLE # the next button pressed removes nothing async def test_excluding_another_device_does_not_count_as_removing_this_one( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network, 5, "switch") other = await pair(controller, output, network, 6, "switch") unpairing = asyncio.create_task(controller.unpair(device)) await asyncio.sleep(0.3) await network.exclude(6) # the user pressed the button of the wrong device with pytest.raises(LookupError, match="another device"): await asyncio.wait_for(unpairing, 10) assert other.physical_id in output.lost_devices assert 5 in await network.node_ids() async def test_an_unconfirmed_exclusion_times_out_with_a_reason( controller: ZwaveController, output: RecordingControllerOutput, network: MockNetwork ): await controller.start() device = await pair(controller, output, network) with pytest.raises(TimeoutError): await controller.unpair(device) assert (await stored(controller, device.physical_id)).last_error assert 5 in await network.node_ids() await controller.start_pairing_window(1) # the exclusion was stopped: inclusion can start