Skip to content

Add a HAP client (controller) - #582

Merged
ikalchev merged 15 commits into
devfrom
integration/hap-client
Nov 23, 2026
Merged

ikalchev merged 15 commits into
devfrom
integration/hap-client

Conversation

@ikalchev

@ikalchev ikalchev commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

This change:

  • Moves the already existing client from the bench suite to a dedicated package inside pyhap. Users can use the client to control HAP devices.
  • Extends it with a CLI for creation of clients and registering them with the accessory.
  • Adds integration tests that use the client.

Fixes #181

Usage

The client cannot currently complete the entire pairing process. So, first pair your accessory to e.g. the iOS home app. Then, on the machine which will run the controller (client), create a new client:

 $ python -m pyhap.client new -f client.state
    Creating new HAP controller in file "client.state"...
    Done!

    On the machine where your accessory is running create a file with the following contents:

    {
        "uuid": "...",
        "public_key": "..."
    }

    and run `python -m pyhap.client register -f <the above file> -a <accessory state file>`.

When the above completes, it will print a JSON snippet with the new client's UUID and public key, which are needed by the accessory for verification. You need to copy this into a file on the machine where the accessory is running and then run:

$ python -m pyhap.client register -f client.json -a accessory.state

Here, the accessory.state is wherever you keep your accessory's state data.

After this, you can use your new client to control the accessory or receive updates from it, similar to what iOS can do. See the client example.

This PR was developed together with Mistral's Vibe (mistral-large-4). I guided much of the design (adding the CLI, registration workflow, etc.). Some tests might be overly verbose.

ikalchev and others added 2 commits November 20, 2026 13:48
The mock controller in benchmarks/client.py was in a usable state - it
speaks the real protocol (pair-verify, encrypted transport, characteristic
reads/writes, subscriptions, EVENT push) - so it moves to pyhap.client as
HAPClient, split into identity/protocol/controller modules. The benchmarks
now import it from there. On top of the move, the client gains batch
characteristic reads/writes, unsubscribe, raw event access (next_event) and
a pair-verify error check, and reuses pyhap.const.RESPONSE_TIMEOUT.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
tests/integration/ runs an AccessoryDriver in-process on a loopback port,
pre-pairs client identities and connects real HAPClient instances. Covered:
standalone and bridged accessories (GET /accessories, reads/writes by
aid/iid), setter callbacks at accessory/service/characteristic level plus
the characteristic getter (including an async setter delaying the write
response), and the notification paths: a write from one client is evented
to another subscribed client (never back to the writer), unsubscribe
stops delivery, and accessory-side set_value is pushed too.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
@ikalchev ikalchev self-assigned this Nov 21, 2026
@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.45%. Comparing base (c53ee83) to head (6bc391a).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #582      +/-   ##
==========================================
+ Coverage   92.00%   92.45%   +0.44%     
==========================================
  Files          50       56       +6     
  Lines       10839    11457     +618     
  Branches     1404     1473      +69     
==========================================
+ Hits         9972    10592     +620     
+ Misses        579      578       -1     
+ Partials      288      287       -1     
Files with missing lines Coverage Δ
pyhap/client/__init__.py 100.00% <100.00%> (ø)
pyhap/client/cli.py 100.00% <100.00%> (ø)
pyhap/client/controller.py 100.00% <100.00%> (ø)
pyhap/client/identity.py 100.00% <100.00%> (ø)
pyhap/client/protocol.py 100.00% <100.00%> (ø)
pyhap/client/state.py 100.00% <100.00%> (ø)

... and 4 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

ikalchev and others added 10 commits November 21, 2026 16:10
A lib user can now persist the controller identity themselves: save()
writes uuid + raw private/public key as JSON through a 0600 tempfile that
is os.replace()d into place (atomic, never world-readable, mirroring how
AccessoryDriver persists its own key), and load()/from_dict() rebuild it
with validation (uuid format, hex keys, public key must match the private
key). Covered by unit tests in tests/test_client_identity.py and by an
integration test that restarts the driver on the same state file and
reconnects with the identity loaded from disk.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
new_persistent(*, filepath, accessory_ltpk) loads the controller identity
from filepath if it exists, otherwise generates a new one and backs it up
there (via ClientIdentity.save/load); HAPClient gains an identity property
so the identity can be paired with the accessory. The restart integration
test now uses it end to end, and tests/test_client.py covers both the
create-and-back-up and the load-existing paths. The API page for
pyhap.client gets a short example, and the README feature list mentions
the client.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
HAPClient and HAPClient.new_persistent no longer require accessory_ltpk:
without it the pair-verify session is still encrypted but the accessory's
signature is not verified (a warning is logged). An LTPK passed once is
pinned in the persisted identity file (ClientIdentity.accessory_ltpk), so
later new_persistent(filepath=...) calls verify the accessory against it.
The restart integration test now reconnects without passing the LTPK, and
a new test covers a real connection with no pinned LTPK.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
HAPClient and HAPClient.new_persistent now take an optional accessory_state
path (the accessory's accessory.state file, e.g. copied from the accessory
machine): its LTPK is read via the new pyhap.client.load_accessory_ltpk and
pinned in the client file (trust on first use), alongside the existing
accessory_ltpk= bytes parameter. load_accessory_ltpk also serves as the
export path for moving just the accessory's public key to another machine -
the state file contains the accessory's private key and should not be
copied wholesale. The client API docs now spell out the assumptions: the
client speaks pair-verify only, the identity must be paired first (with the
driver.pair(...) snippet), the LTPK is optional, and the cross-machine steps
are listed.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
The persisted client file is now authoritative for the accessory LTPK:
the first resolved LTPK is pinned (trust on first use), and passing a
different accessory_ltpk/accessory_state afterwards raises ValueError.
Migrating the client to another accessory is an explicit out-of-band edit
of the client file, out of scope for new_persistent. Docs updated to say so.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
The example now instantiates the AccessoryDriver with advertise=False (the
API switch that runs the HAP server without mDNS advertising), pairs the
persistent client identity, and shows the full start/connect/operate/stop
flow, plus the driverless variant against a running accessory via
accessory_state= (noting the state file does not store the port).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
pyhap.client.state.add_client_pairing(path, identity, permissions=ADMIN)
loads an accessory.state with AccessoryEncoder.load_into, registers the
client identity via State.add_paired_client, and writes the file back
atomically (0600 tempfile + os.replace) - no driver needed, so the client
can live on a different machine than the accessory (edit with the accessory
stopped; a running driver would overwrite the file on its next persist).
The docs' cross-machine section now spells out the three steps, and an
integration test runs the full flow: accessory creates its state file and
stops, pairing is added offline, accessory restarts, client pair-verifies.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
Offline controller management without a running driver, for running the
client on a different machine than the accessory:
- `new -f client.state` creates a persistent controller identity and prints
  the public JSON (uuid + public_key only) to hand to the accessory machine;
  refuses to overwrite without --force.
- `register -f client.json -a accessory.state [-p admin|user]` adds the
  pairing to the accessory state file (atomic 0600 write) and warns to stop
  a running accessory first.
- `list -a accessory.state` prints `<uuid>: <permissions>` lines (never keys).
- `deregister -a accessory.state <uuid> [--yes]` removes a pairing; refuses
  without --yes when it is an admin or the last pairing, because removing the
  last admin wipes all pairings.

Backed by new pyhap.client helpers load_accessory_state / save_accessory_state
/ remove_client_pairing, and add_client_pairing now also accepts a plain
uuid + public key. The client also reports a clean "pair-verify rejected"
when the accessory is completely unpaired (error TLV at M2). The API docs
lead with the CLI workflow, and tests cover the CLI in-process plus an
end-to-end integration test (new -> register -> restart -> connect ->
deregister -> rejected).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
@ikalchev ikalchev changed the title Add a HAP client into pyhap and use it in integration tests Add a HAP client (controller) Nov 23, 2026
ikalchev and others added 3 commits November 23, 2026 17:33
examples/lightbulb_accessory.py runs a small Lightbulb accessory (no mDNS,
listening on loopback and the LAN address) that pairs the controller identity
from examples/client.state on startup; examples/control_lightbulb.py uses
HAPClient.new_persistent to pair-verify, subscribe, read and toggle the On
characteristic over the real HAP protocol. examples/README.md documents the
same-machine and two-machine (python -m pyhap.client register) workflows,
and docs/source/intro/examples.rst points to the new directory.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
The example now lives in its own subdirectory; the state files are created
next to the scripts there, .gitignore and the intro/examples docs pointer
are updated accordingly.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
@ikalchev ikalchev mentioned this pull request Nov 23, 2026
@ikalchev
ikalchev merged commit c5c897a into dev Nov 23, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement a HAP client

1 participant