Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@ pip-selfcheck.json
# HAP-python-generated files
accessory.pickle
/*.state
examples/client/*.state
8 changes: 8 additions & 0 deletions .skills/pyhap-testing/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ carries a pre-existing baseline of diagnostics (mostly in `tests/`): capture
it before your changes and ensure your edits add no new findings. Otherwise
report the findings.

## sphinx (docs)

Check the documentation compiles fine by running:

```sh
python -m sphinx -W -b html source build/html
```

## Reporting

When asked to "test everything", run **pytest, ruff check/format, and ty** in that
Expand Down
34 changes: 34 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,40 @@ Sections

## [Unreleased]

### Added

- `pyhap.client`: a HAP client (controller) package speaking the real
protocol - pair-verify, encrypted transport, characteristic reads/writes,
event subscriptions and `EVENT` push frames. Moved out of
`benchmarks/client.py` (now `pyhap.client.HAPClient`) and extended with
batch reads/writes, unsubscribe, raw event access and
`ClientIdentity.save`/`load` for persisting the controller identity (UUID
+ private key, written atomically with 0600 permissions), plus the
`HAPClient.new_persistent(filepath=...)` convenience that loads the
identity from a file or creates and backs it up there. The accessory LTPK
is optional: pass it once (raw bytes via `accessory_ltpk=`, or read from
the accessory's state file via `accessory_state=` /
`load_accessory_ltpk`) to pin it in the file (trust on first use; a
conflicting pinned LTPK raises `ValueError` — migrating to another
accessory means editing the client file), or
omit it for an encrypted but unauthenticated session. Also
`add_client_pairing(state_file, identity)` registers a client identity in
the accessory's `accessory.state` offline (atomic write, no driver
needed), for running the client on a different machine than the
accessory. The API docs spell
out the pairing assumptions (pair-verify only; pair the identity with
`AccessoryDriver.pair` first) and the cross-machine steps. Covered by the
new integration tests in `tests/integration/`.
- `python -m pyhap.client` CLI for offline controller management:
`new -f client.state` creates a persistent controller identity and prints
the public (uuid + public key) JSON to register elsewhere; `register -f
client.json -a accessory.state` adds the pairing to the accessory's state
file without a running driver; `list -a accessory.state` prints
`<uuid>: <permissions>`; `deregister -a accessory.state <uuid> [--yes]`
removes a pairing (guarded, since removing the last admin wipes all
pairings). Also `load_accessory_state`/`save_accessory_state`/
`remove_client_pairing` in `pyhap.client` for the programmatic equivalent.

### Fixed

- Drop the write response of a coroutine setter that answers only after its
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Main features:
* **asyncio support** — run various tasks or accessories in the event loop.
* **Out of the box support for Apple-defined services** — see them in [the resources folder](pyhap/resources).
* **Secure pairing** — just scan a QR code, no manual codes to type in.
* **HAP client included** — [pyhap/client](pyhap/client) is a controller that speaks the real protocol against a running accessory.
* **Proven in production** — HAP-python powers the HomeKit integration of the home automation framework [Home Assistant](https://github.com/home-assistant/home-assistant).

Full API documentation is available on [readthedocs](http://hap-python.readthedocs.io/).
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

See ``benchmarks/README.md`` for usage. The modules are:

* ``benchmarks.client``: a mock HAP controller (client) speaking the real
* ``pyhap.client``: the mock HAP controller (client) speaking the real
protocol: pair-verify, encrypted transport and EVENT push events.
* ``benchmarks.server``: the benchmark accessory server, run as a child
process by the orchestrator.
Expand Down
10 changes: 5 additions & 5 deletions benchmarks/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@
REPO_ROOT = Path(__file__).resolve().parent.parent

try:
from benchmarks.client import BenchController, ClientIdentity
except ImportError: # running as a plain script, not ``-m benchmarks.run``
from pyhap.client import ClientIdentity, HAPClient
except ImportError: # running as a plain script without the package installed
sys.path.insert(0, str(REPO_ROOT))
from benchmarks.client import BenchController, ClientIdentity
from pyhap.client import ClientIdentity, HAPClient

try:
import psutil
Expand Down Expand Up @@ -489,10 +489,10 @@ async def run_scenario(scenario: Scenario, args: argparse.Namespace) -> dict[str

# ### Connect and pair-verify ###
sampler.mark("connect")
clients: list[BenchController] = []
clients: list[HAPClient] = []
pair_verify_ms: list[float] = []
for identity in identities:
controller = BenchController(identity, ltpk)
controller = HAPClient(identity, ltpk)
started = time.perf_counter()
await controller.connect("127.0.0.1", port)
pair_verify_ms.append((time.perf_counter() - started) * 1000)
Expand Down
163 changes: 163 additions & 0 deletions docs/source/api/client.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
.. _api-client:

======
Client
======

`pyhap` also ships a HAP controller (client) under `pyhap.client.HAPClient`.
The client uses the HAP protocol to control an accessory similarly to how you
can control it through the Home app on iOS. Event subscribtion is also supported.

The client can be persistent, i.e. after it is started it can persist its
identity (what the accesory remembers and later verifies) into a file for
subsequent reuse.

The main limitation of the client currently is that it does not support pairing up
from scratch (see below).

The client is used in the integration tests and in the benchmark suite, in case
you are looking for examples.

Pairing and trust assumptions
=============================

The client assumes a pyhap accessory has already completed `pair-setup`. That is,
the client does not support pairing from scratch right now - this is mainly because of
a missing part of the server-side crypto protocol.

Two things must therefore already exist when you connect:

1. **The client identity must be paired with the accessory.** Pairings are
per controller identity: an existing iPhone pairing does not cover the
client. When you run the accessory yourself (the usual case for this
library), pair the identity before connecting::

client = HAPClient.new_persistent(filepath="controller.key")
# Safe to do multiple times, it's idempotent.
driver.pair(
client.identity.uuid_bytes,
client.identity.public_key_bytes,
HAP_PERMISSIONS.ADMIN,
)
await client.connect("127.0.0.1", port)

Against a remote accessory you do not control, a pairing can only be
added by pair-setup (not implemented in the client) or by an
already-paired admin through the ``/pairings`` endpoint (also not
implemented) — otherwise pair-verify is rejected. To pair a client with
an accessory on another machine without a running driver, use the
command line interface (``python -m pyhap.client``, see the first
example below) or :func:`pyhap.client.add_client_pairing`.

2. **The accessory LTPK is optional, but recommended.** The LTPK is the
accessory's long-term public key, used to verify the accessory during
pair-verify. This is not available from pair-verify itself (a real
controller learns it from pair-setup's M6 response). Pass it once — as
raw bytes (``accessory_ltpk=...``) or read from the accessory's state
file (``accessory_state="accessory.state"``) — and it is pinned in the
client file and verified on every later run. If the client file already
pins a *different* LTPK, ``new_persistent`` raises ``ValueError``:
migrating the client to another accessory is done by updating (or
deleting) the client file yourself, not via the method. Without any LTPK
the session is still encrypted, but the accessory is not authenticated.

Running the client on a different machine than the accessory
-------------------------------------------------------------

Use the command line interface (see the first example below): on the client
machine ``python -m pyhap.client new -f client.state`` creates the identity
and prints a small JSON file (uuid + public key only — copy *that* to the
accessory machine, never ``client.state`` itself, it holds the private key);
on the accessory machine, with the accessory **stopped** (a running driver
would overwrite the edit on its next persist), run ``python -m pyhap.client
register -f client.json -a accessory.state``. Then start the accessory again
and connect from the client machine. The programmatic equivalent of
``register`` is :func:`pyhap.client.add_client_pairing`.

Example
=======

Command line (recommended when the client runs on another machine)
------------------------------------------------------------------

Create a persistent controller identity on the client machine — the command
prints the JSON to hand to the accessory machine:

.. code-block:: console

$ 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>`.
...

On the accessory machine (accessory stopped), register the controller, and
list or remove paired controllers:

.. code-block:: console

$ python -m pyhap.client register -f client.json -a accessory.state
$ python -m pyhap.client list -a accessory.state
123e4567-e89b-12d3-a456-426614174000: admin
$ python -m pyhap.client deregister -a accessory.state 123e4567-e89b-12d3-a456-426614174000 --yes

Programmatic (same machine, or full control)
--------------------------------------------

Host an accessory and drive it with a client in the same process.
``advertise=False`` runs the HAP server *without* the mDNS advertisement
(a real deployment advertises, so the Home app can discover it; tests and
local setups can skip it):

.. code-block:: python

from pyhap.accessory_driver import AccessoryDriver
from pyhap.client import HAPClient
from pyhap.const import HAP_PERMISSIONS

driver = AccessoryDriver(port=51827, advertise=False) # HAP server only, no mDNS
driver.add_accessory(MyAccessory(driver, "My Accessory")) # your Accessory subclass

# Loads controller.key if it exists, otherwise creates a new identity
# and saves it there. Pair the identity once (bypasses the slow SRP
# pair-setup); the pairing is stored in the accessory's own state file.
client = HAPClient.new_persistent(filepath="controller.key")
driver.pair(
client.identity.uuid_bytes,
client.identity.public_key_bytes,
HAP_PERMISSIONS.ADMIN,
)

await driver.async_start() # start the HAP server
await client.connect("127.0.0.1", 51827) # pair-verify + encryption
await client.get_accessories() # GET /accessories
await client.subscribe(1, on_iid) # EVENT notifications on
await client.write_characteristic(1, on_iid, True)
await client.wait_event(1, on_iid, True) # an update arrives as EVENT
await client.close()
await driver.async_stop()

Against an already-running accessory (e.g. on another machine) there is no
driver to instantiate: pass the accessory's state file once to pin its LTPK
(see the section above), and connect to its host:port explicitly — the state
file stores the keys and pairings but not the port:

.. code-block:: python

client = HAPClient.new_persistent(
filepath="controller.key",
accessory_state="accessory.state", # copied from the accessory machine
)
await client.connect("192.168.1.50", 51827)

.. automodule:: pyhap.client
:members:
14 changes: 13 additions & 1 deletion docs/source/intro/examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,16 @@ of the tutorial's sensor.

For cameras, start from ``accessories/camera_main.py``: the options dict
describes what the camera supports, and HAP-python negotiates the sessions
(see :doc:`/media/camera`).
(see :doc:`/media/camera`).

Driving an accessory from Python
--------------------------------

The ``examples/client`` directory of the repository shows the other
direction: a :doc:`HAP client </api/client>` (``pyhap.client.HAPClient``)
connecting to an accessory over the real HAP protocol.
``examples/client/lightbulb_accessory.py`` runs a small Lightbulb accessory
and ``examples/client/control_lightbulb.py`` toggles its ``On``
characteristic from a controller with a persistent identity — see
``examples/client/README.md`` for the same-machine and two-machine
workflows.
36 changes: 36 additions & 0 deletions examples/client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Client examples

## Driving an accessory with a HAP client (`pyhap.client`)

`lightbulb_accessory.py` runs a small Lightbulb accessory;
`control_lightbulb.py` toggles its `On` characteristic over the real HAP
protocol (pair-verify, encrypted transport) using a persistent controller
identity. See the [pyhap.client API docs](../../docs/source/api/client.rst)
for the pairing and trust details.

Same machine (paths below are relative to this directory; the state files
always land next to the scripts):

```sh
cd examples/client
python -m pyhap.client new -f client.state # once; prints client.json
python lightbulb_accessory.py # pairs client.state automatically
python control_lightbulb.py # toggles the light
```

Client on a different machine than the accessory: on the client machine run
`python -m pyhap.client new -f client.state` and copy only the printed JSON
(`client.json`, uuid + public key) to the accessory machine. With the
accessory stopped, run there:

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

then start the accessory again and run `control_lightbulb.py` on the client
machine (adjust `HOST`/`PORT` in the script). Use
`python -m pyhap.client list -a accessory.state` and
`python -m pyhap.client deregister -a accessory.state <uuid> --yes` to manage
pairings on the accessory machine.

The `*.state` files created here are gitignored.
70 changes: 70 additions & 0 deletions examples/client/control_lightbulb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Toggle the example Lightbulb accessory with a pyhap HAP client.

Start ``lightbulb_accessory.py`` first, then run this script. The controller
identity in ``client.state`` (created once with
``python -m pyhap.client new -f client.state``) is paired by the accessory on
startup; the accessory's LTPK is pinned from ``accessory.state`` on first use.
See README.md in this directory for the two-machine variant.
"""

from __future__ import annotations

import asyncio
import json
from pathlib import Path
import sys
from typing import Any

from pyhap.client import HAPClient

HERE = Path(__file__).resolve().parent
HOST, PORT = "127.0.0.1", 51827

LIGHTBULB_SERVICE_TYPE = "43" # 00000043-0000-1000-8000-0026BB765291, short HAP form
ON_CHARACTERISTIC_TYPE = "25" # 00000025-0000-1000-8000-0026BB765291, short HAP form


def find_on_characteristic(accessories: Any) -> tuple[int, int] | None:
"""The (aid, iid) of the On characteristic of the first Lightbulb service."""
for acc in accessories:
for service in acc["services"]:
if service["type"] != LIGHTBULB_SERVICE_TYPE:
continue
for char in service["characteristics"]:
if char["type"] == ON_CHARACTERISTIC_TYPE:
return acc["aid"], char["iid"]
return None


async def main() -> int:
"""Connect, find the lightbulb's On characteristic, toggle it, read back."""
client = HAPClient.new_persistent(
filepath=HERE / "client.state",
accessory_state=HERE / "accessory.state", # pins the accessory LTPK once
)
await client.connect(HOST, PORT)
try:
frame = await client.get_accessories()
on = find_on_characteristic(json.loads(frame.body)["accessories"])
if on is None:
print("no Lightbulb with an On characteristic found", file=sys.stderr)
return 1
aid, iid = on
# EVENT pushes arrive here when the value changes from another
# controller or from the accessory itself (not for our own writes).
await client.subscribe(aid, iid)

frame = await client.read_characteristic(aid, iid)
current = json.loads(frame.body)["characteristics"][0]["value"]
await client.write_characteristic(aid, iid, not current)

frame = await client.read_characteristic(aid, iid)
value = json.loads(frame.body)["characteristics"][0]["value"]
print(f"Lightbulb On (aid={aid}, iid={iid}) is now {'on' if value else 'off'}")
finally:
await client.close()
return 0


if __name__ == "__main__":
sys.exit(asyncio.run(main()))
Loading
Loading