Skip to content

Architecture

barneyonline edited this page Nov 10, 2026 · 9 revisions
HomePod Sensor Link — Architecture

Architecture

The homepod_sensor_link integration uses one config entry to manage per-device private records and recovery policies.

Layers

Module Responsibility
config_flow.py Discovery, per-device recovery defaults, native credential forms, cancellable progress, device selection and confirmed management actions
ui.py, config_flow.py Local administrator-only native CSV/JSON/field forms and flow ownership
importer.py Strict CSV/JSON parsing, typed irestore decoding on current main, derived public-key validation and exact accessory-ID spelling
vault.py, secure_storage.py Owner-checked private journal, atomic drained writes, cancellation checkpoints and automatic purge
provisioning.py Read-only identity matching and persisted-before-write dedicated User commissioning
backend.py Fresh HAP sessions, pinned identity/private-key checks, add-only preservation, cleanup classification
engine.py, audit.py Per-device recovery policy, grace, rolling limits, persisted owned sensor publication and administrator audits
__init__.py Setup, globally registered actions, unload and explicit removal
coordinator.py, entity.py, models.py Typed runtime, shared entity, startup probes, dynamic selected-device publication and private/state lifecycle
repairs.py Entry-linked issues through HA’s public Repairs API
sensor.py Integration-owned measurements and per-device diagnostics
watchdog.py Independent stalled-check timer, Repairs issue and persistent notification

All active devices use this integration’s sensor platform and dedicated regular User controllers. Native HomeKit entries and storage are not read.

Input boundary

Credential entry uses standard Home Assistant config-flow forms for pasted CSV/JSON or manual fields. There is no custom credential panel, upload endpoint or URL-fragment grant. ui.local_admin checks the authenticated user, administrator permission, HA-resolved local peer and non-Cloud context. Each credential step must use the same administrator who started the flow.

Selected HAP CSV and existing pairing JSON formats are capped at 128 KiB. Current main also accepts typed irestore v0.4.0 dumps up to 2 MiB of UTF-8 input; this addition is not in the published v0.2.0 release as of 9 November 2026. Raw form input is removed from the submitted dictionary during parsing. Normalized HAP credentials stay in memory until consumed or flow removal; raw dumps and unrelated credentials are not retained. Overlapping submissions reuse the existing verification task.

The parser supports typed JSON, a single complete pairing record, aiohomekit pairing dictionaries keyed by accessory ID, and selected HAP CSV rows. Current main's irestore parser reads non-deleted HAP records from General, decodes attributes using _fieldOrder/_fieldTypes, and discards unrelated groups and categories. Selected CSV rows must all belong to the HAP group. Invalid HomeKit records, mismatched key pairs, conflicting records and binary placeholders fail with a controlled error. Source identities are tried at most three per selected device. Only read-only probes run during matching. Discovery endpoints are untrusted hints; Pair Verify checks the supplied accessory pin before trusting a peer. Canonical IDs deduplicate; exact exported ID spelling is retained in the actual HAP pairing dictionary.

Durable onboarding

The private journal is .storage/homepod_sensor_link/data.json, in a process-owned 0700 directory with a 0600 regular file. It contains per-device controller credentials, administrator credentials when needed, public pins, transaction phases and recovery state in one atomic document. Credentials and cooldown/blocked/pending history cannot be independently reset by losing a separate state file. Public identity/admin pins are mirrored in the integration’s public config-entry data; private key material never enters flow results or core config data. The journal uses no-follow descriptor reads and atomic replace/fsync writes. Cancellation drains a committed write before releasing the store lock, preventing a late executor from recreating deleted credentials.

Each new device gets one generated User controller identity, saved before any pairing operation. It is reused across retries and restarts. Phases distinguish prepared, needs-credentials, write-uncertain, accepted, verified, active and blocked outcomes. Initial writes are authorised only in the HA process that completed the guided flow. A new boot can perform read-only authentication; further writes require Resume. Cancellation stops in-flight setup and persists a pause without replacing the saved key.

Before adding, authenticated administrator access and the complete pairing table are checked. Only the absent pinned HA row is added, with User permissions for new devices. Every existing row must remain unchanged. The original rows and expected HA row are checkpointed in the private journal before the write. A lost reply retains that checkpoint across restart; subsequent fresh sensor authentication must also verify the preserved table before clearing it or reporting success. A present row that rejects the saved key or has changed permission blocks further writes. An ambiguous response remains journalled; it does not cause blind re-addition. Provisioning attempt timestamps feed the same rolling per-device limits used by recovery.

Successful and pending devices coexist in one entry. New measurement values are published only after fresh characteristic reads, directly to that device’s measurement listeners; setup completes only after both actual HA sensor entities report those samples. The final coordinator update publishes health and inventory once per poll. This publication checkpoint controls deletion of administrator credentials for completed monitoring-only devices. Recovery-on devices retain their verified administrator identity.

Recovery and lifecycle

An integration-owned coordinator listener keeps checks active even when all entity listeners are disabled. Independent device probes run concurrently. The five-minute engine requires three confirmed authentication failures spanning ten minutes, with a ten-minute startup grace, one repair attempt per hour and three per rolling day. Pending owned sensor publication work is persisted and retries at most three times per rolling hour. An accepted pairing is not re-added because entity publication failed. Network/discovery and cleanup-only errors cannot authorise repair. Restart preserves failure evidence, counters and blocked states, and begins a fresh ten-minute startup grace; removal clears history.

From v0.2.0, HeartbeatWatchdog supervises completed checks using a separate five-minute timer and monotonic timestamps, independent of the coordinator's update lock. Each eligible device gets fifteen minutes after monitoring starts or resumes. A missing completion then raises one Repairs issue and a persistent notification; completed checks, including failed checks, refresh the heartbeat. Paused, blocked and needs-credentials devices are excluded, and monitoring is suspended during HA startup/shutdown or a competing recovery engine. Alerts clear when eligible devices recover or monitoring stops. This timer makes no pairing changes. Diagnostics expose last_completed separately from the attempt-start timestamp last_checked.

A single runtime owner is claimed before awaits and released after successful shutdown. An active homepod_recovery entry blocks this engine. Stop gates protect queued checks/audits. Conflicts are checked during operation and immediately before add-pairing; a conflict pauses this engine and clears stale authentication streak evidence while retaining rate-limit history. Unknown or corrupt persisted cooldown/blocked state blocks writes. Connector cleanup preserves the primary failure classification and cancellation while closing remaining transports.

Administrator audits persist results only when a check runs; skipped weekly/hourly checks create no duplicate journal commit. Single-device operations copy only that private record. Pairing checkpoints remain unconditional durable writes. Device removal clears its notification signatures, persistent notifications and measurement listeners; inventory reconciliation permits re-adding the same key.

Actions remain registered when entries unload and resolve the active runtime at call time. Fresh read-only preflight runs before platform creation: an all-network failure retries setup, while per-device authentication/pin failures stay isolated without permitting writes. Reauthentication re-imports the same pinned identities and retains repair history. New devices update the running coordinator/entity set without reloading healthy peers. Repairs link directly to the integration’s config entry, survive unload, and clear on resolution or removal.

Per-device removal first stops that device’s work, deletes its private record/history and public references, and lets HA remove the integration-owned diagnostic/measurement device. Integration removal stops work, revokes pending imports/flows and automatically removes all owned files and recovery state. A delayed cancelled-flow checkpoint cannot recreate an empty store after purge. Cleanup never follows a symlink into foreign data, changes native entries, revokes an accessory pairing or deletes unrelated storage. A registry device still referenced by a foreign entity is retained; only our entities and private state are deleted. Unload/reload alone preserves data.

Testing

Tests exercise HA classes and entity publication with networking disabled and generated disposable identities. See the development guide for the runtime matrix, coverage policy and validation commands.

Directed discovery from explicit export address hints uses bounded temporary UDP reply sockets. It decodes fresh HAP DNS-SD records without altering HA’s shared zeroconf cache; normal multicast discovery and HAP sessions continue to use HA’s instance. All temporary sockets close on success, timeout, error or cancellation.

Clone this wiki locally