diff --git a/CHANGELOG.md b/CHANGELOG.md index f0d3e09d..ed5e817b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,6 @@ 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 @@ -63,16 +62,37 @@ Sections awaitables zeroconf returns (the [#580](https://github.com/ikalchev/HAP-python/pull/580) bug class). `tests/test_asyncio_guards.py` guards the `filterwarnings` config itself. - -### Fixed - -- Drop the write response of a coroutine setter that answers only after its - connection closed. The per-connection response was kept under the closed - connection's address forever, where a later connection reusing the address - could read it, e.g. a Setup Endpoints answer with its session's SRTP keys. -- Cancel tasks still pending on the loop before `AccessoryDriver.start` - closes it, so e.g. a `run_at_interval` wrapper is not destroyed pending at - shutdown ("Task was destroyed but it is pending!"). +- Characteristic and service delegates (`pyhap.delegates`) with request + contexts (`pyhap.context`): the reads, writes and event subscriptions of a + characteristic dispatch to a delegate — every call an awaited coroutine + function under a request deadline, with a frozen context carrying the + controller's connection, identity and privileges. A service delegate is + the pre-check of the grouped writes of its service: it may refuse them by + raising `HapStatusError`, which restores the previous values and notifies + nobody. `delegate` is never `None`: without an assigned one the default + delegate — the wrapper of the legacy callbacks without any — answers, + and reading the legacy callbacks of a delegate-wired object raises + `ValueError`. +- `HapStatusError` (`pyhap.errors`): a callback answers a curated HAP status + code by raising it, so a busy or refusing accessory no longer fails with + the generic `-70402`. A legacy callback may raise it too. + [#75](https://github.com/ikalchev/HAP-python/issues/75) +- Async getters: `GET /characteristics` and `GET /accessories` await the + `on_get` of every readable characteristic under the request deadline — a + legacy getter wrapped into the delegate — so a getter may do IO. A getter + that fails or misses the deadline answers per characteristic + (`-70402` / `-70408`). +- Connection lifecycle hooks on `Accessory`: `client_connected` and + `client_verified`, async and isolated like the existing + `client_disconnected`. +- A stable per-connection identity (`HAPConnectionHandle`, + `pyhap.connection`), which camera streaming sessions are keyed by: a new + connection reusing a closed one's address can no longer control its + sessions. +- `accessories/busy_lock.py`, an example accessory that refuses a lock with + `RESOURCE_BUSY` instead of answering a silent failure. +- `accessories/delegate_lightbulb.py`, an example accessory built on + delegates, contexts and `HapStatusError`. ### Changed @@ -85,6 +105,75 @@ Sections `pyhap.hap_handler`). `pyhap.camera` now imports the multi-tier and WebRTC stream services at the top, which makes the cycle gone instead of hidden in a deferred import. +- A failing getter answers its own status per characteristic instead of + failing the whole `/accessories` response. +- One dispatch pipeline for every write and read: the legacy callbacks run + wrapped inside the delegate calls, so a characteristic without a delegate + and one with one take the same path — the values are stored, the written + services' pre-checks run first (a legacy grouped setter of a service or an + accessory among them), then each written characteristic's `on_set`, and + a refused or failed write is restored and notifies nobody. An explicit + `null` write answers `-70410`, like before, without reaching a callback. +- A camera delegate hook gets at most `hook_timeout` seconds, or as long as + the request has left: whichever ends first, the answer still fits in the + request. +- The camera stack (stream management, recording, operating mode, multi-tier + and WebRTC) dispatches through delegates and contexts internally; the + author-facing camera methods keep their signatures. +- The driver's per-controller state is keyed by the connection, not by its + address: event subscriptions, prepared timed writes, write responses and + the server's connections, all by `HAPConnectionHandle`. Nothing of a + closed connection reaches a later one that reuses its address, and a + write response that arrives only after its connection closed is dropped + instead of kept. A direct call (`driver.set_characteristics` and + friends) without a connection acts as a virtual connection of its + client address, so its prepared writes and read-backs pair up across + calls as before. + +### Deprecated + +- The legacy callbacks: assigning `setter_callback` or `getter_callback` on + a characteristic, `setter_callback` on a service or an accessory, or + passing them to `configure_char`, warns `DeprecationWarning`. They keep + working, wrapped into the delegate calls; move new code to the delegates. + +### Fixed + +- Drop the write response of a coroutine setter that answers only after its + connection closed. The per-connection response was kept under the closed + connection's address forever, where a later connection reusing the address + could read it, e.g. a Setup Endpoints answer with its session's SRTP keys. +- Cancel tasks still pending on the loop before `AccessoryDriver.start` + closes it, so e.g. a `run_at_interval` wrapper is not destroyed pending at + shutdown ("Task was destroyed but it is pending!"). + +### Breaking Changes + +- Direct calls answer at once, optimistically: `driver.set_characteristics` + answers a plain success and runs the setters as a job, and + `driver.get_characteristics` / `driver.get_accessories` answer the stored + values and run the reads as a job — a write response or a getter's fresh + value is no longer part of the synchronous answer. The HAP representation + (`to_HAP`) answers the stored value; a fresh answer comes from the read + path. +- A legacy grouped setter — `Service.setter_callback` or + `Accessory.setter_callback` — runs *before* the per-characteristic + setters, as the pre-check of its service or accessory, and its + `HapStatusError` now refuses the writes (restores the values, notifies + nobody) instead of answering a status after they were applied. +- The notify chain takes the writing connection, not its address: the + third parameter of `Accessory.publish` and `Camera.publish` and the + second of `Characteristic.client_update_value`, + `Characteristic.client_update_finished` and `Characteristic.notify` + is a `HAPConnectionHandle` (or `None`), so a controller is not sent its + own write back even while another connection reuses its address. + `AccessoryDriver.derive_session_key` takes the connection instead of its + address (`AccessoryDriver.prepare` and the other direct-call entry points + keep their signatures, taking an optional `connection`). +- A legacy setter is always called with the value alone: the + `(value, sender_client_addr)` two-argument form, detected by parameter + name, is gone. What a callback needs to know about the writer arrives + through a delegate's context instead. ## [5.2.0] - 2026-11-07 diff --git a/accessories/busy_lock.py b/accessories/busy_lock.py new file mode 100644 index 00000000..2234c0ab --- /dev/null +++ b/accessories/busy_lock.py @@ -0,0 +1,108 @@ +"""Starts a bridge with a lock that refuses commands while its bolt moves, +and a sensor that is offline, both answering with a HAP status. +""" +import logging +import signal +import time + +from pyhap.accessory import Accessory, Bridge +from pyhap.accessory_driver import AccessoryDriver +from pyhap.const import ( + CATEGORY_DOOR_LOCK, + CATEGORY_SENSOR, + HAP_SERVER_STATUS, +) +from pyhap.errors import HapStatusError + + +logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s") + +LOCK_SECURED = 1 +LOCK_UNSECURED = 0 + + +class BusyLock(Accessory): + """A lock whose bolt takes a few seconds to reach its end. + + While it is moving, a controller's command to change the target state + is refused with a HAP status instead of the generic failure: the Home + app tells that the lock is busy, and does not pretend the command + worked. The refused target is put back, so the lock does not promise + a state it will not reach. + """ + + category = CATEGORY_DOOR_LOCK + + MOVE_SECONDS = 5 + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self._moving_until = 0.0 + service = self.add_preload_service("LockMechanism") + self.char_current_state = service.configure_char( + "LockCurrentState", value=LOCK_SECURED) + self.char_target_state = service.configure_char( + "LockTargetState", value=LOCK_SECURED, + setter_callback=self.set_target_state) + self.set_info_service(serial_number="busy lock") + + @Accessory.run_at_interval(1) + async def run(self): + """End a move once the bolt reached its end.""" + if time.monotonic() >= self._moving_until: + if self.char_current_state.value != self.char_target_state.value: + logging.info("The bolt reached its end") + self.char_current_state.set_value(self.char_target_state.value) + + def set_target_state(self, value): + """Accept a command, or refuse it while the bolt is still moving.""" + if time.monotonic() < self._moving_until: + # The command came while the bolt has not reached its end. Answer + # with the resource busy status, and take the refused target back + # so the lock's own state stays consistent. + self.char_target_state.set_value( + self.char_current_state.value, should_notify=False) + logging.info("Refusing to move the bolt again, it is still moving") + raise HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + + logging.info("Moving the bolt to %s", "secure" if value else "unsecure") + self._moving_until = time.monotonic() + self.MOVE_SECONDS + + +class OfflineSensor(Accessory): + """A temperature sensor that is currently unreachable. + + Its getter raises a HAP status, so reads answer with that status + instead of a value that would be a lie. When it is back online, + raise nothing and return the temperature. + """ + + category = CATEGORY_SENSOR + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + serv_temp = self.add_preload_service("TemperatureSensor") + self.char_temp = serv_temp.configure_char( + 'CurrentTemperature', getter_callback=self.get_temperature) + + def get_temperature(self): + """Answer with a status while the sensor cannot be reached.""" + logging.info("The temperature cannot be read right now") + raise HapStatusError(HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE) + + +def get_bridge(driver): + bridge = Bridge(driver, 'Bridge') + + bridge.add_accessory(BusyLock(driver, 'Busy Lock')) + bridge.add_accessory(OfflineSensor(driver, 'Offline Sensor')) + + return bridge + + +driver = AccessoryDriver(port=51826, persist_file='busy_lock.state') +driver.add_accessory(accessory=get_bridge(driver)) +signal.signal(signal.SIGTERM, driver.signal_handler) +driver.start() diff --git a/accessories/delegate_lightbulb.py b/accessories/delegate_lightbulb.py new file mode 100644 index 00000000..eb06b18c --- /dev/null +++ b/accessories/delegate_lightbulb.py @@ -0,0 +1,114 @@ +"""A lightbulb driven entirely by delegates and their contexts. + +The modern counterpart of ``busy_lock.py``: instead of legacy +``setter_callback``/``getter_callback`` attributes, one +:class:`~pyhap.delegates.CharacteristicDelegate` serves the bulb's +characteristics — the context of each call says which one — and a +:class:`~pyhap.delegates.ServiceDelegate` is the pre-check of the service's +grouped writes. Every delegate method is a coroutine function that may do +IO under the request deadline, and a refusal is a +:class:`~pyhap.errors.HapStatusError`, not the generic ``-70402``. +""" + +import asyncio +from collections.abc import Mapping +import logging +import signal +import time +from typing import Any + +from pyhap.accessory import Accessory +from pyhap.accessory_driver import AccessoryDriver +from pyhap.characteristic import Characteristic +from pyhap.const import CATEGORY_LIGHTBULB, HAP_SERVER_STATUS +from pyhap.context import CharReadContext, CharWriteContext, ServiceWriteContext +from pyhap.delegates import CharacteristicDelegate, ServiceDelegate +from pyhap.errors import HapStatusError + +logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s") + + +class BulbDelegate(CharacteristicDelegate): + """One delegate for every characteristic of the bulb. + + The context carries ``characteristic``, so a single instance can serve + them all. The bulb here is simulated: applying a command takes + ``COMMAND_SECONDS``, and a command that arrives while the bulb is still + applying the previous one is refused with RESOURCE_BUSY. + """ + + COMMAND_SECONDS = 0.5 + READ_SECONDS = 0.05 + + def __init__(self) -> None: + # What the bulb itself reports, by characteristic display name. + self._state: dict[str, Any] = {"On": False, "Brightness": 100} + self._busy_until = 0.0 + + async def on_get(self, context: CharReadContext) -> Any: + # Reading the bulb is IO, and a delegate's read may await it: the + # driver runs on_get under the request deadline, off the sync path. + await asyncio.sleep(self.READ_SECONDS) + return self._state[context.characteristic.display_name] + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + char = context.characteristic + if time.monotonic() < self._busy_until: + # The bulb is still applying the previous command: refuse this + # one with a status the Home app can show, the driver restores + # the previous value and notifies nobody. + logging.info("Refusing %s = %s, the bulb is busy", char.display_name, value) + raise HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + self._busy_until = time.monotonic() + self.COMMAND_SECONDS + logging.info( + "%s (admin: %s) sets %s to %s", + context.client_addr, + context.is_admin, + char.display_name, + value, + ) + await asyncio.sleep(self.COMMAND_SECONDS) + self._state[char.display_name] = value + + +class BulbGate(ServiceDelegate): + """The pre-check of the bulb service's grouped writes. + + A request that writes several characteristics of the service runs this + first, with every written value: turning the light off while also + setting a brightness makes no sense, so the whole group is refused — + unless the writer is an admin. + """ + + async def on_set( + self, values: Mapping[Characteristic, Any], context: ServiceWriteContext + ) -> None: + service = context.service + on_char = service.get_characteristic("On") + brightness_char = service.get_characteristic("Brightness") + turns_off = on_char in values and not values[on_char] + if turns_off and brightness_char in values and not context.is_admin: + logging.info("Refusing to set a brightness while turning the light off") + raise HapStatusError(HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST) + + +class DelegateLightbulb(Accessory): + """A light with On and Brightness, wired to delegates only.""" + + category = CATEGORY_LIGHTBULB + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + service = self.add_preload_service("Lightbulb", ["Brightness"]) + self.bulb = BulbDelegate() + service.delegate = BulbGate() + service.configure_char("On", delegate=self.bulb) + service.configure_char("Brightness", delegate=self.bulb) + self.set_info_service(serial_number="delegate lightbulb") + + +driver = AccessoryDriver(port=51826, persist_file="delegate_lightbulb.state") +driver.add_accessory(accessory=DelegateLightbulb(driver, "Delegate Lightbulb")) +signal.signal(signal.SIGTERM, driver.signal_handler) +driver.start() diff --git a/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index d9abaf9a..cfdd1056 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -94,6 +94,17 @@ Your accessory's code started — e.g. its camera streams; a controller that just walks away never sends anything else. +``client_connected`` / ``client_verified`` + The other two connection hooks, async by design like the delegates. + ``client_connected`` runs when a controller's TCP connection is + accepted — before it has proven anything about itself — and + ``client_verified`` when it finishes pair verify, with its UUID as the + second argument: the same identity as the context's + :attr:`~pyhap.context.Context.client_uuid`, stable across all of that + controller's connections. Both run as isolated jobs: their exceptions + are logged, and the connection or the pair verify response never waits + for them. + Characteristic callbacks ======================== @@ -107,10 +118,49 @@ Characteristic callbacks in about 10 seconds: a setter must finish quickly, or start its heavy work as a task (``asyncio.create_task`` / ``driver.add_job``) and return. -A setter may opt into receiving the writer's address by declaring a -parameter literally named ``sender_client_addr`` — useful when a write must -be tied to the connection that made it, e.g. Setup Endpoints. Any other -signature is called with just the value. +A legacy setter is always called with just the value. What a callback +needs to know about the request — the writer's connection, its privileges, +the deadline — arrives through the delegate interface below instead; the +former ``sender_client_addr`` parameter-name opt-in is gone with it. + +**The legacy callbacks are deprecated.** They keep working, wrapped +into the delegate calls below: a sync setter runs inside the awaited +``on_set``, a coroutine setter is awaited, and the grouped callbacks of a +service or an accessory run as its pre-check. But assigning one — a +characteristic's +:attr:`~pyhap.characteristic.Characteristic.setter_callback` or +:attr:`~pyhap.characteristic.Characteristic.getter_callback`, the +``setter_callback``/``getter_callback`` parameters of +:meth:`~pyhap.service.Service.configure_char`, or a service's or an +accessory's ``setter_callback`` — announces a ``DeprecationWarning`` +that names the assigning line. Watch for it in your test runs and move +new code to the delegates below. + +**Answering a HAP status.** A callback that fails does not have to answer +the generic ``-70402`` (service communication failure): raise +:class:`pyhap.errors.HapStatusError` with a status the controller can act +on, and the characteristic answers with it instead — + +.. code-block:: python + + from pyhap.const import HAP_SERVER_STATUS + from pyhap.errors import HapStatusError + + def set_lock_target_state(value): + if not lock.is_ready(): + raise HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + lock.set_state(value) + +The status set is curated — see :ref:`api-errors` for which statuses a +callback may decide and why the rest belong to the driver. Every other +exception keeps answering ``-70402``. + +Getters answer the same way: a read of the characteristic returns the +status instead of a value, while the other characteristics of the request +keep their own results. The accessories list carries no per-characteristic +status, so there a failing getter — whatever it raises — answers by listing +its characteristic without a value, and one broken accessory cannot break +another one's pairing. A setter's return value is used as the *write response* for characteristics with the ``wr`` permission — the value the writing controller reads back in @@ -120,6 +170,146 @@ it wins over the getter and a later ``set_value`` for that connection only, and it is dropped when the connection closes — also when a coroutine setter answers only after the connection already closed. +Delegate writes +================ + +Every write runs through the delegates, see :ref:`api-delegates` — a +legacy callback above is wrapped into one, so one pipeline serves both: + +1. Validation, privileges and timed-write checks — the same ones as + before. An explicit ``null`` value answers ``-70410``: nothing is + applied and no callback runs. +2. The values are stored, but subscribers are not told yet — and the + request of a *private* write (a write response or a + ``read_back_response`` characteristic) is put back at once, so no + other controller reads it while the setters run. A controller's write + is recorded as a *client update* of the characteristic's value: the + legacy :meth:`Characteristic.client_update_value + ` runs the + whole update in one call, while this path splits it into storing the + value, the delegates' ``on_set`` and step 5's + :meth:`Characteristic.client_update_finished + `: + +.. code-block:: python + + class MyLock(CharacteristicDelegate): + async def on_set(self, value, context): + ... + + char = service.configure_char("LockTargetState", delegate=MyLock()) + # is the same as + service.get_characteristic("LockTargetState").delegate = MyLock() + +The assignment stores the delegate, that is all: using something else +than a :class:`CharacteristicDelegate`, or a method that is not a +coroutine function, fails at runtime when the driver calls it. + +A runnable accessory built this way ships with the repository: +``accessories/delegate_lightbulb.py`` (listed in :doc:`/intro/examples`). + +``delegate`` is never ``None``: without an assigned one it is the +default delegate — the wrapper of the legacy callbacks without any — +which answers the reads with the stored value and checks nothing on +writes. ``None`` resets to it. + +A characteristic or service has either a delegate or the legacy +callbacks, never both: assigning one to an object that has the other +raises :class:`ValueError` in both directions, because there would be +no telling at dispatch which of the two should run. ``None`` clears +one side, and the other can then be assigned. Reading +``getter_callback``/``setter_callback`` of an object with an assigned +delegate raises :class:`ValueError` too - there is no legacy callback +behind it to return. + +One instance may serve many characteristics: the context of a call +carries :attr:`~pyhap.context.CharReadContext.characteristic` and says +which one a call is about, e.g. one delegate per accessory rather than +one per characteristic. + +**Rollout state.** Every write, read and subscription dispatches +through the delegates: the write path runs its service-level +pre-checks and its ``on_set`` calls as described above and answers with +the per-characteristic statuses; the reads run ``on_get`` under the +read deadline; ``on_subscribe`` and ``on_unsubscribe`` run when a +controller (un)subscribes, isolated from the request, and +``on_unsubscribe`` again when its connection closes while subscribed. +The legacy callbacks run wrapped inside those calls: a sync setter +inside the awaited ``on_set``, a grouped service or accessory setter as +its pre-check, a getter inside ``on_get``. pyhap's own camera stack +assigns delegates outright - its reads, writes, its stream sessions +belong to the connection that set them up, by +:class:`~pyhap.connection.HAPConnectionHandle`. Assigning a legacy +:attr:`~pyhap.characteristic.Characteristic.setter_callback` / +:attr:`~pyhap.characteristic.Characteristic.getter_callback`, or a +service's or accessory's ``setter_callback``, warns +``DeprecationWarning`` (see :doc:`/advanced/async`). + +Dispatch +======== + +The driver never calls a delegate's methods directly: it dispatches +through the target object's own methods - +:meth:`~pyhap.characteristic.Characteristic.dispatch_get`, +:meth:`~pyhap.characteristic.Characteristic.dispatch_set` and +:meth:`~pyhap.characteristic.Characteristic.subscription_hook` on a +characteristic, :meth:`~pyhap.service.Service.dispatch_set` on a +service. Those build the call's context (see +:meth:`~pyhap.context.CharReadContext.of` and its siblings) and await +the hook. Wire a delegate to the characteristic or service; do not +override the ``dispatch_*`` methods - an override would silently take +the delegate's place. diff --git a/docs/source/api/errors.rst b/docs/source/api/errors.rst new file mode 100644 index 00000000..d19ce2a4 --- /dev/null +++ b/docs/source/api/errors.rst @@ -0,0 +1,23 @@ +.. _api-errors: + +======= +Errors +======= + +Errors raised by accessory callbacks to answer a HAP request with a status. + +.. currentmodule:: pyhap.errors + +.. autoclass:: HapStatusError + :members: + +Which statuses a callback may answer with +========================================= + +.. data:: CALLBACK_STATUSES + + The frozenset of HAP statuses a callback may raise + :class:`HapStatusError` with. Everything else - privileges and + permission failures, read-only and write-only characteristics, + unsupported notifications and timeouts - is enforced or answered by + the accessory driver itself and reserved. diff --git a/docs/source/api/mdns.rst b/docs/source/api/mdns.rst new file mode 100644 index 00000000..923a57e4 --- /dev/null +++ b/docs/source/api/mdns.rst @@ -0,0 +1,12 @@ +.. _api-mdns: + +==== +mDNS +==== + +The mDNS advertisement of an accessory, registered with zeroconf when the +driver starts and re-advertised when the configuration version or pairing +state changes. + +.. autoclass:: pyhap.mdns.AccessoryMDNSServiceInfo + :members: diff --git a/docs/source/intro/examples.rst b/docs/source/intro/examples.rst index 28c11d2e..1a01ba21 100644 --- a/docs/source/intro/examples.rst +++ b/docs/source/intro/examples.rst @@ -43,6 +43,18 @@ device. - An accessory that fetches its state over HTTP. * - ``busy_home.py`` - A bridge with many accessories of mixed kinds. + * - ``busy_lock.py`` + - Answering with a HAP status: a lock that refuses commands with + RESOURCE_BUSY while its bolt is moving, and an offline sensor whose + reads answer a status instead of a value + (:class:`pyhap.errors.HapStatusError`). + * - ``delegate_lightbulb.py`` + - The delegate interface end to end: one + :class:`~pyhap.delegates.CharacteristicDelegate` serving several + characteristics through the context, a + :class:`~pyhap.delegates.ServiceDelegate` gate refusing a grouped + write, async ``on_get``/``on_set`` and ``HapStatusError`` refusals + (see :doc:`/api/delegates`). To run one, install the repository and run the file with the project's virtualenv active — or copy it into your own script and adapt it. The diff --git a/docs/source/intro/overview.rst b/docs/source/intro/overview.rst index 7041fe1d..21f2e6ea 100644 --- a/docs/source/intro/overview.rst +++ b/docs/source/intro/overview.rst @@ -127,6 +127,25 @@ done. Other subscribers then learn the new value as an event. D->>H: EVENT for the other subscribers of aid.iid H-->>C: EVENT aid.iid = value +A write runs through the delegates (see :ref:`api-delegates`): the +values are stored without notifying anyone, the written services' +pre-checks run first and may refuse their writes as a group — the +legacy grouped setter of a service or an accessory runs there too — +then each written characteristic's ``on_set`` applies its write, and a +refused or failed write restores the previous value and answers its +status. The full contract lives in :doc:`/advanced/async`. + +A controller's read +------------------- + +Reads are served by the same interface: the ``on_get`` of every +readable characteristic is awaited — concurrently with the rest of the +request, under a deadline, a legacy getter wrapped into the delegate — +so a getter may do IO without blocking the loop. Its answer is +validated, stored on the characteristic and sent to the reading +controller; a read that fails answers its status, and one bad +characteristic never fails the whole request. + A value change to subscribers ----------------------------- diff --git a/docs/source/intro/tutorial.rst b/docs/source/intro/tutorial.rst index 88b92c34..ffdfbb38 100644 --- a/docs/source/intro/tutorial.rst +++ b/docs/source/intro/tutorial.rst @@ -177,10 +177,13 @@ Give the characteristic a setter callback: logging.info("Switch turned %s", "on" if value else "off") # drive the relay here -The callback runs when a controller writes. It may also be a coroutine -function — the write is answered once it completes, so it must be quick; -start slow work as a task. To know *which* controller wrote, declare a -parameter named ``sender_client_addr`` — see :doc:`/advanced/async`. +The callback runs when a controller writes, with the written value. It +may also be a coroutine function — the write is answered once it +completes, so it must be quick; start slow work as a task. To know *which* +controller wrote — its connection, privileges, the deadline — use a +delegate instead, see :doc:`/advanced/async`. The legacy +``setter_callback`` keeps working, but assigning one warns +``DeprecationWarning``; new code should use the delegates. Bridging several accessories ============================ diff --git a/docs/source/media/camera.rst b/docs/source/media/camera.rst index 9c709eb3..8477e5f0 100644 --- a/docs/source/media/camera.rst +++ b/docs/source/media/camera.rst @@ -217,9 +217,11 @@ machine per session: Three rules shape the lifecycle: -* **A session belongs to the connection that set it up.** Only that - connection may control it, and when the connection closes, its sessions - end (the camera calls your ``handle_end`` for them). +* **A session belongs to the connection that set it up.** Its + :class:`~pyhap.connection.HAPConnectionHandle` identifies the connection — + stable even when a later connection reuses the same address — and only + that connection may control the session. When the connection closes, its + sessions end (the camera calls your ``handle_end`` for them). * **A hook runs as a task the session owns**, with a deadline; a HAP request waits for it until the deadline and is then answered — a slow hook does not stall the camera forever. diff --git a/pyhap/accessory.py b/pyhap/accessory.py index 78538e20..dcd7e396 100644 --- a/pyhap/accessory.py +++ b/pyhap/accessory.py @@ -1,13 +1,16 @@ """Module for the Accessory classes.""" from collections.abc import Callable, Iterable +import inspect import itertools import logging from typing import TYPE_CHECKING, Any from uuid import UUID +import warnings from . import SUPPORT_QR_CODE, util from .characteristic import Characteristic +from .connection import HAPConnectionHandle from .const import ( CATEGORY_BRIDGE, CATEGORY_OTHER, @@ -35,6 +38,18 @@ logger = logging.getLogger(__name__) +def _close_unsupported_coroutine(result: Any, name: str | None) -> None: + """Close a coroutine a legacy grouped setter returned. + + Only characteristic setters may be coroutine functions. + """ + if inspect.iscoroutine(result): + result.close() + logger.warning( + "%s: only characteristic setters may be coroutine functions", name + ) + + class Accessory: """A representation of a HAP accessory. @@ -66,7 +81,7 @@ def __init__( self.driver = driver self.services: list[Service] = [] self.iid_manager = iid_manager or IIDManager() - self.setter_callback: Callable[[Any], None] | None = None + self._setter_callback: Callable[[Any], None] | None = None self.add_info_service() if aid == STANDALONE_AID: @@ -77,6 +92,47 @@ def __repr__(self) -> str: services = [s.display_name for s in self.services] return f"" + @property + def setter_callback(self) -> Callable[[Any], None] | None: + """The legacy grouped setter, called with the request's values by name. + + Called with the values of every written service of the accessory, + before its characteristics apply the writes - a pre-check that may + refuse them. Deprecated: a + :class:`~pyhap.delegates.ServiceDelegate` checks the grouped writes of + its service instead. + """ + return self._setter_callback + + @setter_callback.setter + def setter_callback(self, callback: Callable[[Any], None] | None) -> None: + """Assign the legacy grouped setter; ``None`` removes it.""" + if callback is not None: + warnings.warn( + "The legacy setter_callback is deprecated, use a ServiceDelegate" + " instead", + DeprecationWarning, + stacklevel=2, + ) + self._setter_callback = callback + + async def _dispatch_legacy_setter( + self, updates_by_service: dict[Service, dict[Characteristic, Any]] + ) -> None: + """Run the legacy grouped setter of this accessory, see ``setter_callback``. + + Called by the driver's write path as the accessory's pre-check, with + the written values of every written service of the accessory. The + call is unchanged: a coroutine the setter returns is closed with a + warning, like before. Its exceptions surface to the pre-check, which + refuses the writes of the accessory with the status it answers. + """ + callback = self._setter_callback + assert callback is not None # noqa: S101 - only sent accessories with one + display_name = self.display_name + assert display_name is not None # noqa: S101 - an accessory has a name + _close_unsupported_coroutine(callback(updates_by_service), display_name) + @property def available(self) -> bool: """Accessory is available. @@ -337,7 +393,43 @@ def client_disconnected(self, client_addr: tuple[str, int]) -> None: """Called in the event loop when a controller's connection closed. Override to end what the controller started, e.g. its streams. Does - nothing by default. + nothing by default. Exceptions are logged by the driver, so an + accessory cannot fail a connection by handling its close. + + .. seealso:: :meth:`client_connected` and :meth:`client_verified`, + the other connection hooks. + """ + + async def client_connected(self, client_addr: tuple[str, int] | None) -> None: + """Called in the event loop when a controller's connection is accepted. + + Runs as an isolated task when the TCP connection is made, before the + controller has proven anything about itself: it may never pair. + Override it to prepare for a controller's requests, e.g. to count + connections. Does nothing by default. + + Exceptions are logged by the driver and never affect the connection, + and the hook never delays it: the driver does not wait for it. + + .. seealso:: :meth:`client_verified` follows once the controller + proves its identity, and :meth:`client_disconnected` when the + connection closes. + """ + + async def client_verified( + self, client_addr: tuple[str, int] | None, client_uuid: UUID + ) -> None: + """Called in the event loop when a controller finishes pair verify. + + The controller proved its identity: its requests on the connection + are encrypted from now on and ``client_uuid`` says who it is - one + identity per pairing, the same one for every connection of that + controller. Override it to keep per-controller state, e.g. to answer + requests differently for known controllers. Does nothing by default. + + Exceptions are logged by the driver and never affect the connection, + and the hook never delays the pair verify response: the driver does + not wait for it. """ def reset_accessory_state(self) -> None: @@ -353,15 +445,17 @@ def publish( self, value: Any, sender: Service | Characteristic, - sender_client_addr: Any = None, + connection: HAPConnectionHandle | None = None, immediate: bool = False, ) -> None: """Append AID and IID of the sender and forward it to the driver. - Characteristics call this method to send updates. + Characteristics call this method to send updates. The connection + ``connection`` the change came over, if any, is not told its own + write back. - :param data: Data to publish, usually from a Characteristic. - :type data: dict + :param value: Data to publish, usually from a Characteristic. + :type value: dict :param sender: The Service or Characteristic from which the call originated. :type: Service or Characteristic @@ -371,7 +465,7 @@ def publish( HAP_REPR_IID: self.iid_manager.get_iid(sender), HAP_REPR_VALUE: value, } - self.driver.publish(acc_data, sender_client_addr, immediate) + self.driver.publish(acc_data, connection, immediate) class Bridge(Accessory): @@ -473,6 +567,28 @@ def client_disconnected(self, client_addr: tuple[str, int]) -> None: "%s failed to handle a closed connection", acc.display_name ) + async def client_connected(self, client_addr: tuple[str, int] | None) -> None: + """Tell each bridged accessory about the new connection.""" + for acc in self.accessories.values(): + try: + await acc.client_connected(client_addr) + except Exception: + logger.exception( + "%s failed to handle a new connection", acc.display_name + ) + + async def client_verified( + self, client_addr: tuple[str, int] | None, client_uuid: UUID + ) -> None: + """Tell each bridged accessory about the verified controller.""" + for acc in self.accessories.values(): + try: + await acc.client_verified(client_addr, client_uuid) + except Exception: + logger.exception( + "%s failed to handle a verified connection", acc.display_name + ) + def reset_accessory_state(self) -> None: """Reset the state of each bridged accessory.""" for acc in self.accessories.values(): diff --git a/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index 790b8da9..dc3859ae 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -1,6 +1,54 @@ """AccessoryDriver - glues together the HAP Server, accessories and mDNS advertising. +The :class:`AccessoryDriver` is the server side of a pyhap accessory: it answers +the controller requests that arrive over the HAP server (reads and writes of +characteristics, prepared timed writes, pairing), advertises the accessory over +mDNS, persists its state and fans value changes out to subscribed controllers. + +Request flow +------------ + +Every request enters through a public entry point - ``get_accessories``, +``get_characteristics``, ``set_characteristics``, ``prepare`` - and then splits +by caller: + +- A controller's request comes from the ``HAPServerHandler`` through the + ``*_for_controller`` variants. They return an awaitable which the handler + schedules as the response task: the driver runs the delegates in-request, + under a deadline (``RESPONSE_TIMEOUT``), and answers per-characteristic + statuses - ``-70408`` for any call still running when the deadline passes. +- A direct call (tests, embedders) answers at once, optimistically with the + stored values, and runs the delegates as a background job without a + deadline. + +Write flow (``PUT /characteristics``):: + + handle_set_characteristics + -> _set_characteristics_for_controller (or set_characteristics) + -> _apply_characteristic_writes validate + store + collect + -> _dispatch_delegates awaited in-request, or a job + -> _run_pre_checks service-level gates, may veto + -> _run_char_writes per-characteristic on_set + -> _finish_task_write per write status, write response, notify + -> _set_characteristics_response + +Read flow (``GET /characteristics``, ``GET /accessories``):: + + handle_get_characteristics / handle_accessories + -> _get_characteristics_for_controller / _get_accessories_for_controller + -> _collect_characteristic_reads stored value + collect the reads + -> _read_delegate_values on_get under the deadline + -> _finish_read + an answer callback fill the characteristic's rep + +Every delegate call receives a frozen context - client address and uuid, +connection handle, deadline - see ``pyhap.context``. The driver's +per-connection state (event topics, prepared writes, write responses) is keyed +by the connection handle, not by the address, so a connection that reuses a +closed one's address inherits none of its state, see +``pyhap.connection.HAPConnectionHandle``. + Sending updates to clients +-------------------------- The process of sending value changes to clients happens in two parts - on one hand, the value change is indicated by a Characteristic and, on the other, that change is @@ -18,16 +66,14 @@ """ import asyncio -import base64 from collections import defaultdict -from collections.abc import Awaitable, Coroutine +from collections.abc import Awaitable, Callable from concurrent.futures import ThreadPoolExecutor import hashlib -import inspect import ipaddress import logging +import math import os -import re import sys import tempfile import threading @@ -49,33 +95,37 @@ CharacteristicWrite, HAPValue, ) +from pyhap.connection import HAPConnectionHandle from pyhap.const import ( HAP_PERMISSION_NOTIFY, HAP_PERMISSION_READ, HAP_PERMISSION_TIMED_WRITE, HAP_PERMISSION_WRITE, HAP_PERMISSION_WRITE_RESPONSE, - HAP_PROTOCOL_SHORT_VERSION, HAP_REPR_ACCS, HAP_REPR_AID, HAP_REPR_CHARS, HAP_REPR_IID, HAP_REPR_PID, + HAP_REPR_SERVICES, HAP_REPR_STATUS, HAP_REPR_TTL, HAP_REPR_VALUE, HAP_REPR_WRITE_RESPONSE, STANDALONE_AID, ) +from pyhap.context import Context from pyhap.encoder import AccessoryEncoder from pyhap.hap_server import HAPServer from pyhap.hsrp import Server as SrpServer from pyhap.loader import Loader +from pyhap.mdns import AccessoryMDNSServiceInfo from pyhap.params import get_srp_context from pyhap.service import Service from pyhap.state import State from .const import HAP_SERVER_STATUS +from .errors import HapStatusError from .util import callback logger = logging.getLogger(__name__) @@ -83,10 +133,6 @@ SERVICE_CALLBACK = "callback" SERVICE_CHARS = "chars" SERVICE_IIDS = "iids" -HAP_SERVICE_TYPE = "_hap._tcp.local." -VALID_MDNS_REGEX = re.compile(r"[^A-Za-z0-9\-]+") -LEADING_TRAILING_SPACE_DASH = re.compile(r"^[ -]+|[ -]+$") -DASH_REGEX = re.compile(r"[-]+") KEYS_TO_EXCLUDE = {HAP_REPR_IID, HAP_REPR_AID} # Consecutive failed pair-setup proofs (each is a setup-code guess) before @@ -115,100 +161,100 @@ def _stored_value(char: Characteristic, value: HAPValue) -> HAPValue: return stored -def _wrap_char_setter( - char: Any, value: Any, client_addr: Any, notify: bool = True -) -> tuple[int, Any]: - """Process an characteristic setter callback trapping and logging all exceptions.""" - try: - # The driver finishes the update of a coroutine setter once it is done. - response = char.client_update_value( - value, client_addr, notify=notify, defer_notify=True - ) - except Exception: - logger.exception( - "%s: Error while setting characteristic %s to %s", - client_addr, - char.display_name, - value, - ) - return HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE, None - return HAP_SERVER_STATUS.SUCCESS, response +class _DelegateRead(NamedTuple): + """A delegate-backed read of one characteristic. + ``rep`` is the HAP entry the read answers; the caller's ``answer`` + callback fills it with the value or the failure status. + """ -def _close_unsupported_coroutine(result: Any, name: str) -> None: - """Close a coroutine an accessory or service setter returned. + rep: dict[str, Any] + char: Characteristic + + +def _ignore_read_answer(read: _DelegateRead, value: Any, status: int | None) -> None: + """Drop the rep answer of a background read of a direct call. - Only characteristic setters may be coroutine functions. + A direct call answers the stored values at once; the background job + only refreshes them, so its per-read answer has nothing left to fill. """ - if inspect.iscoroutine(result): - result.close() - logger.warning( - "%s: only characteristic setters may be coroutine functions", name - ) -def _wrap_acc_setter(acc: Any, updates_by_service: Any, client_addr: Any) -> Any: - """Process an accessory setter callback trapping and logging all exceptions.""" - try: - _close_unsupported_coroutine( - acc.setter_callback(updates_by_service), acc.display_name - ) - except Exception: - logger.exception( - "%s: Error while setting characteristics to %s for the %s accessory", - updates_by_service, - client_addr, - acc, - ) - return HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE - return HAP_SERVER_STATUS.SUCCESS +class _DelegateWrite(NamedTuple): + """A characteristic write the delegates of a request apply. + ``value`` is the validated value ``on_set`` receives, already + stored: a write the pre-checks or ``on_set`` refuse is restored. + """ -def _wrap_service_setter(service: Any, chars: Any, client_addr: Any) -> Any: - """Process a service setter callback trapping and logging all exceptions.""" - # Ideally this would pass the chars as is without converting - # them to the display_name, but that would break existing - # consumers of the data. - service_chars = {char.display_name: value for char, value in chars.items()} - try: - _close_unsupported_coroutine( - service.setter_callback(service_chars), service.display_name - ) - except Exception: - logger.exception( - "%s: Error while setting characteristics to %s for the %s service", - service_chars, - client_addr, - service.display_name, - ) - return HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE - return HAP_SERVER_STATUS.SUCCESS + char: Characteristic + value: Any + previous_value: Any + result: dict[str, Any] # The result entry to complete. + write_response: bool + private_write: bool + service: Service -class _PendingWrite(NamedTuple): - """A characteristic write whose setter returned a coroutine.""" +class _ReadRequest(NamedTuple): + """One read request's collected delegate reads and its base context.""" - result: dict[str, Any] # The result entry to complete. - coro: Coroutine[Any, Any, Any] - write_response: bool # Whether the controller asked for a write response. - char: Characteristic - previous_value: Any # The value before the write, to tell if it changed. - notify: bool # Whether subscribers learn the value once the setter is done. + reads: list[_DelegateRead] + context: Context -class _ConnectionWrites: - """The pending writes of one controller connection. +class _WriteRequest: + """One write request's collected delegate work. - ``connection_lost`` marks them dead, so a response that a setter - delivered only after the connection closed is dropped instead of being - kept for a later connection that reuses the address. The connection's - per-connection responses do not outlive it, whatever a setter does. + Carries the request's base context its delegate calls share, plus the + writes collected while validating: every written service gets a + pre-check first - the ``on_set`` of its delegate with every written + value of the request, which may refuse them as a group - and the + per-characteristic ``on_set`` calls apply the surviving writes. """ - __slots__ = ("alive",) + __slots__ = ("context", "is_admin", "pre_checks", "writes") + + def __init__(self, context: Context, is_admin: bool) -> None: + self.context = context + self.is_admin = is_admin + self.pre_checks: dict[Service, dict[Characteristic, Any]] = {} + self.writes: list[_DelegateWrite] = [] + + def __bool__(self) -> bool: + """Whether the request has any write for the delegates to apply.""" + return bool(self.pre_checks or self.writes) - def __init__(self) -> None: - self.alive = True + +class _CallOutcome(NamedTuple): + """The outcome of a finished delegate call: its answer or its status.""" + + value: Any + status: int | None + error: BaseException | None + + +def _settle_private_write( + char: Characteristic, previous_value: Any, request_value: Any, response: Any +) -> Any: + """Settle a write that only its connection may read back. + + The written value of such a write is a request, e.g. a Setup + Endpoints offer. What the callback answered is the state; whatever + it leaves in the value is an answer for the writer only. Neither + the former value of a refused write nor the request the callback + left alone is an answer. Returns the answer, if there is one. + """ + if char.read_back_response: + if response is None and char.value not in ( + previous_value, + _stored_value(char, request_value), + ): + response = char.value + char.value = previous_value + elif char.value == _stored_value(char, request_value): + char.value = previous_value + return response def _retrieve_late_result(task: asyncio.Future[Any]) -> None: @@ -237,81 +283,30 @@ def _set_characteristics_response( return {HAP_REPR_CHARS: characteristics} if nonempty_results_exist else None -class AccessoryMDNSServiceInfo(ServiceInfo): - """A mDNS service info representation of an accessory.""" - - def __init__( - self, accessory: Any, state: State, zeroconf_server: Any = None - ) -> None: - self.accessory = accessory - self.state: State = state - - adv_data = self._get_advert_data() - valid_name = self._valid_name() - short_mac = self.state.mac[-8:].replace(":", "") - # Append part of MAC address to prevent name conflicts - name = f"{valid_name} {short_mac}.{HAP_SERVICE_TYPE}" - valid_host_name = self._valid_host_name() - server = zeroconf_server or f"{valid_host_name}-{short_mac}.local." - super().__init__( - HAP_SERVICE_TYPE, - name=name, - server=server, - port=self.state.port, - weight=0, - priority=0, - properties=adv_data, - parsed_addresses=self.state.addresses, - ) - - def _valid_name(self) -> str: - return re.sub( - LEADING_TRAILING_SPACE_DASH, - "", - re.sub(VALID_MDNS_REGEX, " ", self.accessory.display_name), - ) - - def _valid_host_name(self) -> str: - return re.sub( - DASH_REGEX, - "-", - re.sub(VALID_MDNS_REGEX, " ", self.accessory.display_name) - .strip() - .replace(" ", "-") - .strip("-"), - ) - - def _setup_hash(self) -> str: - setup_hash_material = self.state.setup_id + self.state.mac - temp_hash = hashlib.sha512() - temp_hash.update(setup_hash_material.encode()) - return base64.b64encode(temp_hash.digest()[:4]).decode() - - def _get_advert_data(self) -> dict[str, str]: - """Generate advertisement data from the accessory.""" - return { - "md": self._valid_name(), - "pv": HAP_PROTOCOL_SHORT_VERSION, - "id": self.state.mac, - # represents the 'configuration version' of an Accessory. - # Increasing this 'version number' signals iOS devices to - # re-fetch accessories data. - "c#": str(self.state.config_version), - "s#": "1", # 'accessory state' - "ff": "0", - "ci": str(self.accessory.category), - # 'sf == 1' means "discoverable by HomeKit iOS clients" - "sf": "0" if self.state.paired else "1", - "sh": self._setup_hash(), - } - - class AccessoryDriver: """An AccessoryDriver mediates between incoming requests from the HAPServer and the Accessory. The driver starts and stops the HAPServer, the mDNS advertisements and responds - to events from the HAPServer. + to events from the HAPServer. Concretely, it: + + - answers the controller requests of the HAP server: reads and writes of + characteristics (``GET``/``PUT /characteristics``, ``GET /accessories``), + prepared timed writes (``PUT /prepare``) and pairing; + - runs the delegates of the accessory tree for those requests - the + read/write flow is sketched in this module's docstring; + - keeps the per-connection state of controllers - event subscriptions + (``topics``), prepared writes and write responses - keyed by + :class:`~pyhap.connection.HAPConnectionHandle`, so a connection that + reuses a closed one's address inherits none of its state; + - publishes value changes to the subscribed connections, skipping the + connection a write came over; + - persists the accessory state and advertises the accessory over mDNS. + + A controller's request runs its delegates in-request under a deadline and + is answered once they are done; a direct call, e.g. to + :meth:`set_characteristics`, is answered optimistically with the stored + values and runs the delegates as a background job. """ def __init__( @@ -358,6 +353,16 @@ def __init__( :param encoder: The encoder to use when persisting/loading the Accessory state. :type encoder: AccessoryEncoder + :param loader: The loader to use when loading the Accessory state. + :type loader: Loader + + :param loop: The asyncio event loop to run on. If not given, a new loop + is created and a default executor is set on it, so plain callables + added with :meth:`add_job` run in a thread pool and the driver owns + the loop (see :meth:`start`). When a loop is given, the driver runs + on it as-is - typical for embedders - and sets no executor. + :type loop: asyncio.AbstractEventLoop + :param mac: The MAC address which will be used to identify the accessory. If not given, the driver will try to select a MAC address. :type mac: str @@ -419,7 +424,9 @@ def __init__( self.persist_file = os.path.expanduser(persist_file) self.encoder = encoder or AccessoryEncoder() - self.topics = {} # topic: set of (address, port) of subscribed clients + # Topics ("aid.iid") with the connections subscribed to them, see + # HAPConnectionHandle. + self.topics: dict[str, set[HAPConnectionHandle]] = {} self.loader = loader or Loader() self.aio_stop_event: asyncio.Event | None = None self.stop_event = threading.Event() @@ -446,15 +453,16 @@ def __init__( self._listen_address: str | list[str] = listen_address or address network_tuple = (self._listen_address, self.state.port) self.http_server = HAPServer(network_tuple, self) - self.prepared_writes = {} - # Write responses of readable characteristics, per client. + # Timed writes pending their request, per connection. + self.prepared_writes: dict[HAPConnectionHandle, dict[int, float]] = {} + # Write responses of readable characteristics, per connection. self._write_responses: dict[ - tuple[str, int], dict[Characteristic, HAPValue] - ] = {} - # The writes still waiting for their connection's coroutine setters. - self._pending_connection_writes: dict[ - tuple[str, int], set[_ConnectionWrites] + HAPConnectionHandle, dict[Characteristic, HAPValue] ] = {} + # The virtual handles of direct calls, see ``_connection_of``. + self._direct_connections: dict[tuple[str, int] | None, HAPConnectionHandle] = {} + # The identity of the next connection, see HAPConnectionHandle. + self._connection_generation = 0 def listen_address(self) -> str | list[str]: """Return the address, or list of addresses, the HAP server listens on.""" @@ -513,27 +521,33 @@ def _cancel_pending_tasks(self) -> None: ) def start_service(self) -> None: - """Start the service.""" + """Start the accessory on an already running event loop. + + Validates the driver and schedules :meth:`async_start` on its loop. + Use this instead of :meth:`start` when the caller runs the loop, e.g. + an embedder. + """ self._validate_start() self.add_job(self.async_start) def _validate_start(self) -> None: - """Validate we can start.""" + """Raise ValueError when no accessory is assigned to the driver yet.""" if self.accessory is None: raise ValueError( "You must assign an accessory to the driver, before you can start it." ) async def async_start(self) -> None: - """Starts the accessory. + """Starts the accessory. Must run in the event loop. - - Call the accessory's run method. - - Start handling accessory events. - Start the HAP server. - - Publish a mDNS advertisement. + - Update the accessories hash (persisting the state when it changed, + so iOS drops its cached ``/accessories``). + - Publish a mDNS advertisement (unless ``advertise`` is False). - Print the setup QR code if the accessory is not paired. + - Call the accessory's run method as a job. - All of the above are started in separate threads. Accessory thread is set as + All of the above are started as separate jobs. Accessory thread is set as daemon. """ self._validate_start() @@ -588,11 +602,19 @@ async def async_start(self) -> None: ) def stop(self) -> None: - """Method to stop pyhap.""" + """Stop the driver, from any thread. + + Schedules :meth:`async_stop` on the event loop. + """ self.add_job(self.async_stop) async def async_stop(self) -> None: - """Stops the AccessoryDriver and shutdown all remaining tasks.""" + """Stops the AccessoryDriver and shutdown all remaining tasks. + + Must run in the event loop. Unregisters the mDNS advertisement, stops + the HAP server and the accessory, and - when the driver created its + loop - shuts the executor down and stops the loop. + """ self.stop_event.set() accessory = self.accessory assert accessory is not None # noqa: S101 @@ -633,14 +655,26 @@ async def async_stop(self) -> None: logger.debug("Stop completed") def add_job(self, target: Any, *args: Any) -> None: - """Add job to executor pool.""" + """Add a job to the event loop, from any thread. + + The target may be a coroutine, a :func:`~pyhap.util.callback` + function, a coroutine function - called with ``args`` - or a plain + callable, which runs in the loop's executor. See :meth:`async_add_job` + for the dispatch. + """ if target is None: raise ValueError("Don't call add_job with None.") self.loop.call_soon_threadsafe(self.async_add_job, target, *args) @util.callback def async_add_job(self, target: Any, *args: Any) -> Any: - """Add job from within the event loop.""" + """Add a job from within the event loop, dispatching on the target's kind. + + A coroutine becomes a task; a :func:`~pyhap.util.callback` function is + scheduled with ``loop.call_soon``; a coroutine function is called with + ``args`` and becomes a task; anything else runs in the executor. + Returns the task, or None for a callback. + """ task = None if asyncio.iscoroutine(target): @@ -655,7 +689,13 @@ def async_add_job(self, target: Any, *args: Any) -> Any: return task def add_accessory(self, accessory: Accessory) -> None: - """Add top level accessory to driver.""" + """Add the top level accessory to the driver. + + The top-level accessory must have the standalone AID (1); it is + assigned automatically when the accessory has none. When a persist + file exists, the accessory state is loaded from it and restored into + the accessory; otherwise the current state is persisted. + """ self.accessory = accessory if accessory.aid is None: accessory.aid = STANDALONE_AID @@ -672,14 +712,15 @@ def add_accessory(self, accessory: Accessory) -> None: @util.callback def async_subscribe_client_topic( - self, client: Any, topic: str, subscribe: bool = True + self, client: HAPConnectionHandle, topic: str, subscribe: bool = True ) -> None: """(Un)Subscribe the given client from the given topic. This method must be run in the event loop. - :param client: A client (address, port) tuple that should be subscribed. - :type client: tuple + :param client: The connection that should be subscribed, see + :class:`~pyhap.connection.HAPConnectionHandle`. + :type client: HAPConnectionHandle :param topic: The topic to which to subscribe. :type topic: str @@ -704,34 +745,112 @@ def async_subscribe_client_topic( if not subscribed_clients: del self.topics[topic] - def connection_lost(self, client: Any) -> None: + def client_connected(self, client_addr: tuple[str, int] | None) -> None: + """Tell the accessory that a controller's connection was accepted. + + Schedules the accessory's + :meth:`~pyhap.accessory.Accessory.client_connected` as an isolated + job: the connection never waits for it and its exception is logged, + not raised. Called by the HAP server in the event loop. + """ + accessory = self.accessory + if accessory is None: + return + self.add_job( + self._run_isolated_hook, + accessory.client_connected, + (client_addr,), + "client_connected", + client_addr, + ) + + def client_verified( + self, client_addr: tuple[str, int] | None, client_uuid: UUID + ) -> None: + """Tell the accessory that a controller finished pair verify on a connection. + + Schedules the accessory's + :meth:`~pyhap.accessory.Accessory.client_verified` as an isolated + job: the pair verify response never waits for it and its exception + is logged, not raised. Called by the HAP server in the event loop. + """ + accessory = self.accessory + if accessory is None: + return + self.add_job( + self._run_isolated_hook, + accessory.client_verified, + (client_addr, client_uuid), + "client_verified", + client_addr, + ) + + async def _run_isolated_hook( + self, + hook: Callable[..., Awaitable[None]], + hook_args: tuple[Any, ...], + name: str, + client_addr: tuple[str, int] | None, + ) -> None: + """Await a lifecycle or subscription hook, logging its failure. + + The hook is called here, not by the scheduling caller, so it only + runs once its job does. It runs isolated from what caused it: an + accessory's exception never reaches the connection or the request, + it is only logged. + """ + try: + await hook(*hook_args) + except Exception: + accessory = self.accessory + logger.exception( + "%s failed to run %s for %s", + accessory.display_name if accessory else "the accessory", + name, + client_addr, + ) + + def connection_lost( + self, + client: Any, + connection: HAPConnectionHandle | None = None, + client_uuid: UUID | None = None, + ) -> None: """Called when a connection is lost to a client. This method must be run in the event loop. :param client: A client (address, port) tuple that should be unsubscribed. :type client: tuple + + :param connection: The identity of the closed connection. Its + per-connection state is dropped; without it, the virtual handle + of ``client`` that a direct call uses is dropped instead, see + :meth:`_connection_of`. + :type connection: HAPConnectionHandle or None + + :param client_uuid: The paired controller of the closed connection, + or None when it never finished pair verify or the caller does + not know it. + :type client_uuid: uuid.UUID or None """ + connection = connection or self._connection_of(client) client_topics = [] for topic, subscribed_clients in self.topics.items(): - if client in subscribed_clients: + if connection in subscribed_clients: # Make a copy to avoid changing # self.topics during iteration client_topics.append(topic) - for topic in client_topics: - self.async_subscribe_client_topic(client, topic, subscribe=False) - self.prepared_writes.pop(client, None) - # Writes whose setters still run answer with their response after - # this; mark them so it is dropped instead of kept for a connection - # that reuses the address. - pending_writes = self._pending_connection_writes.pop(client, None) - if pending_writes is not None: - for writes in pending_writes: - writes.alive = False - # Deferred, so a write response that is already on its way is dropped too. - self.loop.call_soon(self._write_responses.pop, client, None) accessory = self.accessory + for topic in client_topics: + self.async_subscribe_client_topic(connection, topic, subscribe=False) + if accessory is not None: + self._dispatch_close_unsubscribe( + topic, accessory, client, client_uuid, connection + ) + self.prepared_writes.pop(connection, None) + self._write_responses.pop(connection, None) if accessory is None: return try: @@ -741,43 +860,73 @@ def connection_lost(self, client: Any) -> None: "%s failed to handle a closed connection", accessory.display_name ) + def _dispatch_close_unsubscribe( + self, + topic: str, + accessory: Accessory, + client_addr: Any, + client_uuid: UUID | None, + connection: HAPConnectionHandle, + ) -> None: + """Run ``on_unsubscribe`` of a topic a closed connection was subscribed to.""" + aid, iid = (int(i) for i in topic.split(".")) + char = accessory.get_characteristic(aid, iid) + if char is not None: + self._dispatch_subscription( + char, False, client_addr, client_uuid, connection + ) + def publish( self, data: dict[str, Any], - sender_client_addr: Any = None, + connection: HAPConnectionHandle | None = None, immediate: bool = False, ) -> None: - """Publishes an event to the client. + """Publishes an event to the subscribed clients. - The publishing occurs only if the current client is subscribed to the topic for - the aid and iid contained in the data. + The event is sent only to the connections subscribed to the topic of + the aid and iid contained in the data; the connection ``connection`` + - the one a write came over - is not sent its own write back. Safe to + call from any thread: called from another thread, the send is + scheduled onto the event loop. :param data: The data to publish. It must at least contain the keys "aid" and "iid". :type data: dict + + :param connection: The connection that caused the change, skipped in + the fan-out, see :class:`~pyhap.connection.HAPConnectionHandle`. + :type connection: HAPConnectionHandle or None + + :param immediate: Whether the server should send the event at once + instead of batching it with the next one. + :type immediate: bool """ topic = get_topic(data[HAP_REPR_AID], data[HAP_REPR_IID]) if topic not in self.topics: return if threading.current_thread() == self.tid: - self.async_send_event(topic, data, sender_client_addr, immediate) + self.async_send_event(topic, data, connection, immediate) return self.loop.call_soon_threadsafe( - self.async_send_event, topic, data, sender_client_addr, immediate + self.async_send_event, topic, data, connection, immediate ) def async_send_event( self, topic: str, data: dict[str, Any], - sender_client_addr: Any, + sender: HAPConnectionHandle | None, immediate: bool, ) -> None: - """Send an event to a client. + """Send an event to every connection subscribed to ``topic``. - Must be called in the event loop + Must be called in the event loop. The ``sender`` connection, when + given, is skipped - a controller is not sent its own write back. A + connection whose socket turns out to be stale is unsubscribed from + the topic. Does nothing once the driver is stopping. """ assert self.aio_stop_event is not None # noqa: S101 if self.aio_stop_event.is_set(): @@ -785,33 +934,33 @@ def async_send_event( subscribed_clients = self.topics.get(topic, []) logger.debug( - "Send event: topic(%s), data(%s), sender_client_addr(%s)", + "Send event: topic(%s), data(%s), sender(%s)", topic, data, - sender_client_addr, + sender, ) unsubs = [] - for client_addr in subscribed_clients: - if sender_client_addr and sender_client_addr == client_addr: + for connection in subscribed_clients: + if sender is not None and sender == connection: logger.debug( "Skip sending event to client since " "its the client that made the characteristic change: %s", - client_addr, + connection, ) continue logger.debug( - "Sending event to client: %s, immediate: %s", client_addr, immediate + "Sending event to client: %s, immediate: %s", connection, immediate ) - pushed = self.http_server.push_event(data, client_addr, immediate) + pushed = self.http_server.push_event(data, connection, immediate) if not pushed: logger.debug( - "Could not send event to %s, probably stale socket.", client_addr + "Could not send event to %s, probably stale socket.", connection ) - unsubs.append(client_addr) + unsubs.append(connection) # Maybe consider removing the client_addr from every topic? - for client_addr in unsubs: - self.async_subscribe_client_topic(client_addr, topic, False) + for connection in unsubs: + self.async_subscribe_client_topic(connection, topic, False) def config_changed(self) -> None: """Notify the driver that the accessory's configuration has changed. @@ -825,12 +974,20 @@ def config_changed(self) -> None: self.update_advertisement() def update_advertisement(self) -> None: - """Updates the mDNS service info for the accessory.""" + """Update the mDNS advertisement, from any thread. + + Schedules :meth:`async_update_advertisement` on the event loop. + """ self.loop.call_soon_threadsafe(self.async_update_advertisement) @callback def async_update_advertisement(self) -> None: - """Updates the mDNS service info for the accessory from the event loop.""" + """Update the mDNS service info for the accessory, from the event loop. + + Rebuilds the advertisement from the current state - configuration + version, pairing state, setup hash - so HomeKit sees the change, and + re-registers it with the advertiser. + """ logger.debug("Updating mDNS advertisement") if not self.advertise: logger.debug("Not updating mDNS advertisement: advertising is disabled") @@ -867,9 +1024,11 @@ def async_persist(self) -> None: util.async_create_background_task(self.loop.run_in_executor(None, self.persist)) def persist(self) -> None: - """Saves the state of the accessory. + """Save the state of the accessory to the persist file. - Must run in executor. + Must run in executor. Writes to a temporary file first and then + atomically replaces the persist file, so a crash mid-write cannot + corrupt the stored state. """ logger.debug("Writing of accessory state to disk") tmp_filename = None @@ -901,7 +1060,7 @@ def persist(self) -> None: os.remove(tmp_filename) def load(self) -> None: - """Load the persist file. + """Load the persist file into the driver's state via the encoder. Must run in executor. """ @@ -1016,7 +1175,13 @@ def srp_verifier(self) -> SrpServer: return self._srp_verifier def setup_srp_verifier(self) -> None: - """Create an SRP verifier for the accessory's info.""" + """Create the SRP verifier for pair-setup, stored as :attr:`srp_verifier`. + + The verifier uses the 3072-bit group with SHA-512 and the pincode as + the password. Each pair-setup regenerates it, which is part of why + failed attempts are rate limited, see + :meth:`register_failed_pairing_attempt`. + """ # TODO: Move the below hard-coded values somewhere nice. ctx = get_srp_context(3072, hashlib.sha512, 16) verifier = SrpServer(ctx, b"Pair-Setup", self.state.pincode) @@ -1024,20 +1189,39 @@ def setup_srp_verifier(self) -> None: @property def accessories_hash(self) -> str: - """Hash the get_accessories response to track configuration changes.""" - # We pass include_value=False to avoid including the value - # of the characteristics in the hash. This is because the - # value of the characteristics is not used by iOS to determine - # if the accessory configuration has changed. It only uses the - # characteristics metadata. If we included the value in the hash - # then iOS would think the accessory configuration has changed - # every time a characteristic value changed. + """Hash of the ``/accessories`` metadata, to track configuration changes. + + The hash covers the accessories' metadata only + (``get_accessories(include_value=False)``): iOS decides from the + metadata whether its cached configuration is stale, and a changed + characteristic value must not look like a configuration change. A + changed hash makes :meth:`async_start` persist the state, so the new + configuration version reaches the mDNS advertisement. + """ return hashlib.sha512( util.to_sorted_hap_json(self.get_accessories(include_value=False)) ).hexdigest() + def _hap_reps(self, include_value: bool = True) -> list[dict[str, Any]]: + """The HAP reps of the accessory tree, as a list. + + A standalone accessory answers a single rep; a Bridge answers one per + accessory, including the bridge itself. + """ + assert self.accessory is not None # noqa: S101 + hap_rep = self.accessory.to_HAP(include_value=include_value) + if not isinstance(hap_rep, list): + hap_rep = [ + hap_rep, + ] + return hap_rep + def get_accessories(self, include_value: bool = True) -> dict[str, Any]: - """Returns the accessory in HAP format. + """Return the accessory tree in HAP format. + + :param include_value: Whether to include the characteristics' current + values. + :type include_value: bool :return: An example HAP representation is: @@ -1045,31 +1229,119 @@ def get_accessories(self, include_value: bool = True) -> dict[str, Any]: { "accessories": [ - "aid": 1, - "services": [ - "iid": 1, - "type": ..., - "characteristics": [{ - "iid": 2, - "type": ..., - "description": "CurrentTemperature", - ... - }] - ] + { + "aid": 1, + "services": [ + { + "iid": 1, + "type": ..., + "characteristics": [{ + "iid": 2, + "type": ..., + "description": "CurrentTemperature", + ... + }] + } + ] + } ] } :rtype: dict + + A direct call answers the stored values and runs the delegate reads + as a background job without a deadline, like a direct write runs its + setters; a controller's request awaits them through their ``on_get`` + instead, see :meth:`_get_accessories_for_controller`. """ - assert self.accessory is not None # noqa: S101 - hap_rep = self.accessory.to_HAP(include_value=include_value) - if not isinstance(hap_rep, list): - hap_rep = [ - hap_rep, - ] + hap_rep = self._hap_reps(include_value=include_value) + if include_value: + # A direct call answers the stored values of delegate-backed + # characteristics and runs their reads as a job, like a direct + # write runs its setters; a controller's request awaits them + # instead, see ``_get_accessories_for_controller``. + reads = self._collect_accessory_reads(hap_rep) + if reads: + self.add_job( + self._read_delegate_values, + _ReadRequest( + reads, + self._build_request_context( + None, None, self._connection_of(None), None + ), + ), + _ignore_read_answer, + ) logger.debug("Get accessories response: %s", hap_rep) return {HAP_REPR_ACCS: hap_rep} + def _get_accessories_for_controller( + self, + client_addr: tuple[str, int], + timeout: float, + *, + client_uuid: UUID | None = None, + connection: HAPConnectionHandle | None = None, + ) -> Awaitable[dict[str, Any]]: + """Answer a controller's accessories request, awaiting the reads. + + Returns an awaitable of the response. Every readable + characteristic's ``on_get`` runs under the deadline like a + write's callbacks, and a read that fails or misses it answers + its characteristic without a value, like a failing getter does. + """ + connection = connection or self._connection_of(client_addr) + hap_rep = self._hap_reps() + reads = self._collect_accessory_reads(hap_rep) + return self._read_accessories_response( + hap_rep, + _ReadRequest( + reads, + self._build_request_context( + client_addr, client_uuid, connection, timeout + ), + ), + ) + + async def _read_accessories_response( + self, + hap_rep: list[dict[str, Any]], + request: _ReadRequest, + ) -> dict[str, Any]: + """Answer the delegate reads of an accessories request.""" + await self._read_delegate_values(request, self._answer_accessory_read) + return {HAP_REPR_ACCS: hap_rep} + + def _collect_accessory_reads( + self, hap_rep: list[dict[str, Any]] + ) -> list[_DelegateRead]: + """Pair the delegate-backed readable characteristics with their reps.""" + accessory = self.accessory + reads: list[_DelegateRead] = [] + if accessory is None: + return reads + reps_by_iid: dict[tuple[Any, Any], dict[str, Any]] = {} + for acc_rep in hap_rep: + for service_rep in acc_rep.get(HAP_REPR_SERVICES, ()): + for rep in service_rep.get(HAP_REPR_CHARS, ()): + reps_by_iid[(acc_rep[HAP_REPR_AID], rep[HAP_REPR_IID])] = rep + accessories: list[Accessory] = ( + [accessory, *accessory.accessories.values()] + if isinstance(accessory, Bridge) + else [accessory] + ) + for acc in accessories: + for service in acc.services: + for char in service.characteristics: + if HAP_PERMISSION_READ not in char.properties[PROP_PERMISSIONS]: + continue + # An unpublished accessory has no (AID, IID) pair in the + # response, so it has no rep to answer either. + rep = reps_by_iid.get((acc.aid, acc.iid_manager.get_iid(char))) + if rep is not None: + reads.append(_DelegateRead(rep, char)) + return reads + def get_characteristics( self, char_ids: Any, client_addr: tuple[str, int] | None = None ) -> dict[str, Any]: @@ -1095,12 +1367,83 @@ def get_characteristics( } :rtype: dict + + A direct call answers the stored values at once and runs the + reads as a job without a deadline, like a direct write runs its + setters - a legacy getter is wrapped into the delegate the job + calls. A controller's read goes through + ``_get_characteristics_for_controller`` instead and awaits them. """ - assert self.accessory is not None # noqa: S101 - write_responses = ( - self._write_responses.get(client_addr, {}) if client_addr else {} + connection = self._connection_of(client_addr) + chars, reads = self._collect_characteristic_reads(char_ids, connection) + if reads: + self.add_job( + self._read_delegate_values, + _ReadRequest( + reads, + self._build_request_context(client_addr, None, connection, None), + ), + _ignore_read_answer, + ) + logger.debug("Get chars response: %s", chars) + return {HAP_REPR_CHARS: chars} + + def _get_characteristics_for_controller( + self, + char_ids: Any, + client_addr: tuple[str, int], + timeout: float, + *, + client_uuid: UUID | None = None, + connection: HAPConnectionHandle | None = None, + ) -> Awaitable[dict[str, Any]]: + """Read characteristics for a controller, awaiting the reads. + + Returns an awaitable of the response. Every read characteristic's + ``on_get`` runs under the deadline - a legacy getter is wrapped + into the delegate - and a read not done by it answers ``-70408``. + Cancelling the awaitable, e.g. because the connection closed, + cancels the reads. + """ + connection = connection or self._connection_of(client_addr) + chars, reads = self._collect_characteristic_reads(char_ids, connection) + return self._read_characteristics_response( + chars, + _ReadRequest( + reads, + self._build_request_context( + client_addr, client_uuid, connection, timeout + ), + ), ) + + async def _read_characteristics_response( + self, + chars: list[dict[str, Any]], + request: _ReadRequest, + ) -> dict[str, Any]: + """Answer the delegate reads of a characteristics request.""" + await self._read_delegate_values(request, self._answer_char_read) + return {HAP_REPR_CHARS: chars} + + def _collect_characteristic_reads( + self, char_ids: Any, connection: HAPConnectionHandle + ) -> tuple[list[dict[str, Any]], list[_DelegateRead]]: + """Answer a read per requested characteristic, collecting the reads. + + Every readable characteristic answers its stored value + optimistically, and its read is collected for the caller to run + through the delegate's ``on_get`` - a legacy getter is wrapped + into one: a controller's request awaits it, a direct call runs + it as a background job. A characteristic the connection wrote + reads its write response back, which wins over any read callback. + Unknown ids and unreadable characteristics keep the per-read + failure status of their rep. + """ + assert self.accessory is not None # noqa: S101 + write_responses = self._write_responses.get(connection, {}) chars = [] + reads: list[_DelegateRead] = [] for aid_iid in char_ids: aid, iid = (int(i) for i in aid_iid.split(".")) rep = { @@ -1111,22 +1454,21 @@ def get_characteristics( try: if aid == STANDALONE_AID: - char = self.accessory.iid_manager.get_obj(iid) - available = self.accessory.available + acc = self.accessory else: # Accessory IIDs other than the standalone one only exist # on bridged accessories; anything else is unknown and # keeps the per-characteristic failure status. - bridge = self.accessory - if isinstance(bridge, Bridge): - acc = bridge.accessories.get(aid) - if acc is None: - continue - char = acc.iid_manager.get_obj(iid) - available = acc.available - else: - char = None - available = False + acc = self._bridged_accessory(aid) + if acc is None and isinstance(self.accessory, Bridge): + # An unknown bridged aid gets no rep at all. + continue + if acc is not None: + char = acc.iid_manager.get_obj(iid) + available = acc.available + else: + char = None + available = False # A characteristic IID may resolve to a Service or be unknown; # only a Characteristic can report a value, and only when it @@ -1137,12 +1479,17 @@ def get_characteristics( HAP_SERVER_STATUS.WRITE_ONLY_CHARACTERISTIC ) elif available: - rep[HAP_REPR_VALUE] = ( - write_responses[char] - if char in write_responses - else char.get_value() - ) - rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS + if char in write_responses: + # The connection that wrote reads its write + # response back; it wins over any read callback. + rep[HAP_REPR_VALUE] = write_responses[char] + rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS + else: + # The stored value, optimistically: the read + # runs the delegate's ``on_get`` and refreshes it. + rep[HAP_REPR_VALUE] = char.value + rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS + reads.append(_DelegateRead(rep, char)) except CharacteristicError: logger.error( "%s: Error getting value for characteristic %s.", @@ -1157,28 +1504,27 @@ def get_characteristics( ) chars.append(rep) - logger.debug("Get chars response: %s", chars) - return {HAP_REPR_CHARS: chars} + return chars, reads def derive_session_key( - self, client_addr: tuple[str, int] | None, salt: bytes, info: bytes + self, connection: HAPConnectionHandle | None, salt: bytes, info: bytes ) -> bytes | None: - """Derive a key from the pair-verify session key of ``client_addr``. + """Derive a key from the pair-verify session key of ``connection``. For transports set up from the HAP session, e.g. HomeKit Data Stream. Never returns the session key itself, see :meth:`HAPServerProtocol.derive_key`. Returns ``None`` when the connection is unknown or not encrypted. """ - if client_addr is None: - return None - connection = self.http_server.connections.get(client_addr) if connection is None: return None - return connection.derive_key(salt, info) + protocol = self.http_server.connections.get(connection) + if protocol is None: + return None + return protocol.derive_key(salt, info) def _local_address( - self, client_addr: tuple[str, int] | None, ipv6: bool + self, connection: HAPConnectionHandle | None, ipv6: bool ) -> str | None: """The accessory's address on a controller's connection. @@ -1186,10 +1532,8 @@ def _local_address( the asked IP version. An IPv4 address mapped into IPv6 counts as IPv4, a scope ID is dropped. """ - connection = ( - self.http_server.connections.get(client_addr) if client_addr else None - ) - transport = connection.transport if connection else None + protocol = self.http_server.connections.get(connection) if connection else None + transport = protocol.transport if protocol else None sockname = transport.get_extra_info("sockname") if transport else None if not sockname: return None @@ -1207,20 +1551,19 @@ def set_characteristics( client_addr: tuple[str, int], *, client_uuid: UUID | None = None, + connection: HAPConnectionHandle | None = None, ) -> dict[str, Any] | None: """Called from ``HAPServerHandler`` when iOS configures the characteristics. Returns ``None`` when every write succeeded without a write response, otherwise the per-characteristic results. - A characteristic setter may be a coroutine function. Writes from a - controller wait for it before they are answered. Called directly, this - method only schedules the coroutine and does not wait for it. Either - way subscribers learn the value once the coroutine succeeded, and it - should use its argument, not the characteristic's value, which a write - response request has already put back. Accessory and service setters - must not be coroutine functions. A coroutine they return is closed - with a warning. + Every write runs through the delegates of its characteristic and its + service: the service-level pre-checks first, then the + per-characteristic ``on_set``. Called directly, this method answers + at once, optimistically, and runs the delegates as a job without a + deadline; a controller's request awaits them instead, see + :meth:`_set_characteristics_for_controller`. :param chars_query: A configuration query. For example: @@ -1242,31 +1585,20 @@ def set_characteristics( to characteristics restricted to admins are refused with -70401 unless it is an admin. :type client_uuid: uuid.UUID or None + + :param connection: The connection the write came over, see + :class:`~pyhap.connection.HAPConnectionHandle`. ``None`` for a + call without one: it acts as the virtual connection of + ``client_addr``, see :meth:`_connection_of`. """ - results, pending = self._apply_characteristic_writes( - chars_query, client_addr, client_uuid + connection = connection or self._connection_of(client_addr) + results, request = self._apply_characteristic_writes( + chars_query, client_addr, client_uuid, connection, None ) - for write in pending: - self.add_job(self._finish_pending_write(write, client_addr)) + if request: + self.add_job(self._dispatch_delegates(request)) return _set_characteristics_response(results) - async def _finish_pending_write( - self, write: _PendingWrite, client_addr: tuple[str, int] - ) -> None: - """Run a coroutine setter of a direct call, then tell subscribers.""" - try: - await write.coro - except Exception: - logger.exception( - "%s: Error while setting characteristic %s", - client_addr, - write.char.display_name, - ) - return - write.char.client_update_finished( - write.previous_value, client_addr, notify=write.notify - ) - def _set_characteristics_for_controller( self, chars_query: dict[str, Any], @@ -1274,59 +1606,75 @@ def _set_characteristics_for_controller( timeout: float, *, client_uuid: UUID | None = None, - ) -> dict[str, Any] | None | Awaitable[dict[str, Any] | None]: - """Apply a controller's write, waiting for coroutine setters. - - Returns an awaitable of the response if a characteristic setter is a - coroutine function. Accessory and service setters run before those - coroutines start. A setter still running after ``timeout`` seconds is - cancelled and its characteristic answers -70408. Cancelling the - awaitable, e.g. because the connection closed, cancels the setters. - A setter that answers its write response only after the connection - closed does not get it kept: it would never be read. - """ - results, pending = self._apply_characteristic_writes( - chars_query, client_addr, client_uuid + connection: HAPConnectionHandle | None = None, + ) -> Awaitable[dict[str, Any] | None]: + """Apply a controller's write through its delegates, awaiting them. + + Returns an awaitable of the response. The service-level pre-checks + run first, each with every written value of its service, then the + per-characteristic ``on_set`` calls apply the surviving writes, all + under the request deadline: a call still running after ``timeout`` + seconds is cancelled and its characteristic answers -70408, a + refused or failed write is restored and notifies nobody. Cancelling + the awaitable, e.g. because the connection closed, cancels the + calls. A setter that answers its write response only after the + connection closed does not get it kept: the store drops it, see + :meth:`_store_write_response`. + """ + connection = connection or self._connection_of(client_addr) + results, request = self._apply_characteristic_writes( + chars_query, client_addr, client_uuid, connection, timeout ) - if pending: - writes = _ConnectionWrites() - self._pending_connection_writes.setdefault(client_addr, set()).add(writes) - return self._async_finish_set_characteristics( - results, pending, client_addr, timeout, writes - ) - return _set_characteristics_response(results) + return self._apply_delegate_writes(results, request) def _apply_characteristic_writes( self, chars_query: dict[str, Any], client_addr: tuple[str, int], client_uuid: UUID | None, - ) -> tuple[dict[int, dict[int, dict[str, Any]]], list[_PendingWrite]]: - """Run the setters of a write and collect the per-characteristic results.""" - pending: list[_PendingWrite] = [] - try: - return self._run_characteristic_writes( - chars_query, client_addr, client_uuid, pending - ) - except BaseException: - # A malformed later entry must not leave a setter coroutine - # un-awaited. - for write in pending: - write.coro.close() - raise + connection: HAPConnectionHandle, + timeout: float | None, + ) -> tuple[dict[int, dict[int, dict[str, Any]]], _WriteRequest]: + """Validate and store the writes, collecting them for the delegates. + + The values are only stored here: the delegates of the request + apply them, see :meth:`_dispatch_delegates` - a write its + pre-checks or its ``on_set`` refuse is restored. + """ + context = self._build_request_context( + client_addr, client_uuid, connection, timeout + ) + request = _WriteRequest(context, self.state.is_admin(client_uuid)) + results = self._run_characteristic_writes( + chars_query, client_addr, client_uuid, connection, request + ) + return results, request def _run_characteristic_writes( self, chars_query: dict[str, Any], client_addr: tuple[str, int], client_uuid: UUID | None, - pending: list[_PendingWrite], - ) -> tuple[dict[int, dict[int, dict[str, Any]]], list[_PendingWrite]]: + connection: HAPConnectionHandle, + request: _WriteRequest, + ) -> dict[int, dict[int, dict[str, Any]]]: + """Validate the writes of a request, storing them and collecting the work. + + A timed write (the request carries a ``pid``) first consumes its + prepared write: one that was never prepared, was used already or has + expired is ignored as a whole with -70410, as the spec requires. The + ``ev`` flags of the request then (un)subscribe the connection and + dispatch the subscribe hooks, see :meth:`_notify`; characteristics + without the notify permission are reported -70406. Every remaining + write is checked and stored per query, see :meth:`_store_write_query`. + The delegates apply the collected writes later, see + :meth:`_dispatch_delegates` - a write they refuse is restored. + """ queries: list[CharacteristicWrite] = chars_query[HAP_REPR_CHARS] timed_write = HAP_REPR_PID in chars_query if timed_write and not self._take_prepared_write( - chars_query[HAP_REPR_PID], client_addr + chars_query[HAP_REPR_PID], connection ): # The spec requires a timed write that was never prepared, was # already used or has expired to be ignored as a whole. @@ -1335,306 +1683,684 @@ def _run_characteristic_writes( ignored[query[HAP_REPR_AID]][query[HAP_REPR_IID]] = { HAP_REPR_STATUS: HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST } - return ignored, [] + return ignored - not_notifiable = self._notify(queries, client_addr) + not_notifiable = self._notify(queries, client_addr, client_uuid, connection) - updates_by_accessories_services: dict[ - Accessory, dict[Service, dict[Characteristic, Any]] - ] = defaultdict(lambda: defaultdict(dict)) results: dict[int, dict[int, dict[str, Any]]] = defaultdict( lambda: defaultdict(dict) ) - char_to_iid: dict[Characteristic, int] = {} - - primary_accessory = self.accessory - assert primary_accessory is not None # noqa: S101 - primary_aid = primary_accessory.aid - for aid, iid in not_notifiable: results[aid][iid] = { HAP_REPR_STATUS: HAP_SERVER_STATUS.NOTIFICATION_NOT_SUPPORTED } - is_admin = self.state.is_admin(client_uuid) for query in queries: - aid = query[HAP_REPR_AID] - iid = query[HAP_REPR_IID] - if (aid, iid) in not_notifiable: - continue - if HAP_REPR_VALUE not in query: - # Listed with status 0 if the response has other results. - results[aid][iid] = {HAP_REPR_STATUS: HAP_SERVER_STATUS.SUCCESS} - continue - value = query.get(HAP_REPR_VALUE) + self._store_write_query( + results, + request, + query, + not_notifiable, + timed_write, + connection, + client_addr, + ) - if aid == primary_aid: - acc = primary_accessory - else: - # Accessory IIDs other than the primary one only exist on - # bridged accessories. - bridge = self.accessory - if not isinstance(bridge, Bridge): - continue - acc = bridge.accessories.get(aid) - if acc is None: - continue - char = acc.get_characteristic(aid, iid) - if char is None: - continue + return results - # Privileges are checked before the permissions, so a controller - # that may not write the characteristic learns nothing else. - # Also for an explicit null, so no setter sees the characteristic. - if not is_admin and ADMIN_ONLY_WRITE in char.properties.get( - PROP_ADMIN_ONLY_ACCESS, () - ): - results[aid][iid] = { - HAP_REPR_STATUS: HAP_SERVER_STATUS.INSUFFICIENT_PRIVILEGES - } - continue + def _bridged_accessory(self, aid: int) -> Accessory | None: + """The bridged accessory ``aid`` addresses, None when there is none. - if ( - value is not None - and HAP_PERMISSION_WRITE not in char.properties[PROP_PERMISSIONS] - ): - results[aid][iid] = { - HAP_REPR_STATUS: HAP_SERVER_STATUS.READ_ONLY_CHARACTERISTIC - } - continue + Accessory IIDs other than the primary accessory's only exist on + bridged accessories. + """ + accessory = self.accessory + if isinstance(accessory, Bridge): + return accessory.accessories.get(aid) + return None - if ( - value is not None - and not timed_write - and HAP_PERMISSION_TIMED_WRITE in char.properties[PROP_PERMISSIONS] - ): - if self.enforce_timed_writes: - results[aid][iid] = { - HAP_REPR_STATUS: HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST - } - continue - logger.debug( - "%s: %s requires a timed write but was written without one", - client_addr, - char.display_name, - ) + def _store_write_query( + self, + results: dict[int, dict[int, dict[str, Any]]], + request: _WriteRequest, + query: CharacteristicWrite, + not_notifiable: set[tuple[int, int]], + timed_write: bool, + connection: HAPConnectionHandle, + client_addr: tuple[str, int], + ) -> None: + """Validate one write of a request, store its value, collect its delegates. + + A query without a value - a plain (un)subscribe - is listed with + status 0, so the response reports it when other results exist. A + query whose characteristic is unknown gets no result entry at all. + What survives the checks - privileges, write permission, timed-write + requirement, see :meth:`_write_permission_status` - is stored and + collected for the delegates, see :meth:`_collect_delegate_write`. + """ + aid = query[HAP_REPR_AID] + iid = query[HAP_REPR_IID] + if (aid, iid) in not_notifiable: + return + if HAP_REPR_VALUE not in query: + # Listed with status 0 if the response has other results. + results[aid][iid] = {HAP_REPR_STATUS: HAP_SERVER_STATUS.SUCCESS} + return + value = query.get(HAP_REPR_VALUE) - # Only characteristics with the write response permission answer - # a write with a value, and only when the controller asks for it. - write_response = ( - bool(query.get(HAP_REPR_WRITE_RESPONSE)) - and HAP_PERMISSION_WRITE_RESPONSE in char.properties[PROP_PERMISSIONS] - ) - # A new write replaces a former response of this connection. The - # request of a readable write response or read back characteristic - # is not shared, whatever the setter does, also not with ev - # subscribers. - if value is not None: - self._write_responses.get(client_addr, {}).pop(char, None) - private_write = ( - (write_response or char.read_back_response) - and value is not None - and HAP_PERMISSION_READ in char.properties[PROP_PERMISSIONS] - ) - previous_value = char.value + primary_accessory = self.accessory + assert primary_accessory is not None # noqa: S101 + if aid == primary_accessory.aid: + acc = primary_accessory + else: + acc = self._bridged_accessory(aid) + if acc is None: + return + char = acc.get_characteristic(aid, iid) + if char is None: + return + + status = self._write_permission_status( + char, value, request.is_admin, timed_write, client_addr + ) + if status is not None: + results[aid][iid] = {HAP_REPR_STATUS: status} + return - set_result = HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST - set_result_value = None + # Only characteristics with the write response permission answer + # a write with a value, and only when the controller asks for it. + write_response = ( + bool(query.get(HAP_REPR_WRITE_RESPONSE)) + and HAP_PERMISSION_WRITE_RESPONSE in char.properties[PROP_PERMISSIONS] + ) + # A new write replaces a former response of this connection. The + # request of a readable write response or read back characteristic + # is not shared, whatever the setter does, also not with ev + # subscribers. + if value is not None: + self._write_responses.get(connection, {}).pop(char, None) + private_write = ( + (write_response or char.read_back_response) + and value is not None + and HAP_PERMISSION_READ in char.properties[PROP_PERMISSIONS] + ) + previous_value = char.value + service = char.service + assert service is not None # noqa: S101 - if value is not None: - set_result, set_result_value = _wrap_char_setter( - char, value, client_addr, notify=not private_write - ) - # A write with ``r`` to a readable characteristic is a request, - # e.g. a Setup Endpoints offer with the writer's SRTP keys. Only - # the writer reads the answer back, see _store_write_response. - # client_update_value stored the request as the value, so put - # back the former one unless the setter set a value of its own. - # Whatever the setter of a read back characteristic leaves in the - # value is an answer for the writer only, e.g. the Setup Endpoints - # answer of a subclass that calls super() and returns nothing. - # Neither the former value of a refused write nor the request the - # setter left alone is an answer. - if private_write: - own_value = char.value - if char.read_back_response: - if set_result_value is None and own_value not in ( - previous_value, - _stored_value(char, value), - ): - set_result_value = own_value - char.value = previous_value - elif own_value == _stored_value(char, value): - char.value = previous_value - - result: dict[str, Any] = {HAP_REPR_STATUS: set_result} - if inspect.iscoroutine(set_result_value): - pending.append( - _PendingWrite( - result, - set_result_value, - write_response, - char, - previous_value, - not private_write, - ) - ) - elif set_result_value is not None: - self._keep_response( - result, char, set_result_value, write_response, client_addr - ) + results[aid][iid] = self._collect_delegate_write( + request, + client_addr, + char, + service, + value, + previous_value, + write_response, + private_write, + ) + + def _write_permission_status( + self, + char: Characteristic, + value: Any, + is_admin: bool, + timed_write: bool, + client_addr: tuple[str, int], + ) -> int | None: + """The status a write is refused with before any callback runs, or None. - results[aid][iid] = result - char_to_iid[char] = iid - service = char.service - assert service is not None # noqa: S101 - updates_by_accessories_services[acc][service][char] = value + Privileges are checked before the permissions, so a controller that + may not write the characteristic learns nothing else. Also for an + explicit null, so no setter sees the characteristic. + """ + if not is_admin and ADMIN_ONLY_WRITE in char.properties.get( + PROP_ADMIN_ONLY_ACCESS, () + ): + return HAP_SERVER_STATUS.INSUFFICIENT_PRIVILEGES + if ( + value is not None + and HAP_PERMISSION_WRITE not in char.properties[PROP_PERMISSIONS] + ): + return HAP_SERVER_STATUS.READ_ONLY_CHARACTERISTIC + if ( + value is not None + and not timed_write + and HAP_PERMISSION_TIMED_WRITE in char.properties[PROP_PERMISSIONS] + ): + if self.enforce_timed_writes: + return HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST + logger.debug( + "%s: %s requires a timed write but was written without one", + client_addr, + char.display_name, + ) + return None + + async def _apply_delegate_writes( + self, + results: dict[int, dict[int, dict[str, Any]]], + request: _WriteRequest, + ) -> dict[str, Any] | None: + """Apply the writes of a request through their delegates, build its response. - # Proccess accessory and service level setter callbacks - for acc, updates_by_service in updates_by_accessories_services.items(): - aid = acc.aid - assert aid is not None # noqa: S101 - aid_results = results[aid] + This is the awaitable body of :meth:`_set_characteristics_for_controller`: + once :meth:`_dispatch_delegates` is done, every write has its status and + optional write response, and the response is built from them. + """ + await self._dispatch_delegates(request) + return _set_characteristics_response(results) - # Accessory level setter callbacks - acc_set_result = None - if acc.setter_callback: - acc_set_result = _wrap_acc_setter(acc, updates_by_service, client_addr) + def _next_connection_generation(self) -> int: + """The identity number of the next connection, see HAPConnectionHandle.""" + self._connection_generation += 1 + return self._connection_generation + + def _connection_of( + self, client_addr: tuple[str, int] | None + ) -> HAPConnectionHandle: + """The handle a direct call without a connection acts as. + + One per client address, memoized: the state of separate direct + calls with the same address must pair up - a prepared timed write + with the request that consumes it, a stored write response with the + read that reads it back. A controller's requests carry the handle of + their connection instead, minted when it was made. + """ + connection = self._direct_connections.get(client_addr) + if connection is None: + connection = self._direct_connections[client_addr] = HAPConnectionHandle( + client_addr, self._next_connection_generation() + ) + return connection - # Service level setter callbacks - for service, chars in updates_by_service.items(): - char_set_result = None - if service.setter_callback: - char_set_result = _wrap_service_setter(service, chars, client_addr) - set_result = char_set_result or acc_set_result + def _is_open(self, connection: HAPConnectionHandle) -> bool: + """Whether ``connection`` is a connection the server may still answer. - if not set_result: - continue + The virtual handle of a direct call (see :meth:`_connection_of`) + has no connection and is always open. A handle of a closed + connection is not: its protocol is gone from the server's + connections, so a late answer of it is dropped instead of kept, + see :meth:`_store_write_response`. + """ + return ( + connection in self._direct_connections.values() + or connection in self.http_server.connections + ) - for char in chars: - aid_results[char_to_iid[char]][HAP_REPR_STATUS] = set_result + def _build_request_context( + self, + client_addr: tuple[str, int] | None, + client_uuid: UUID | None, + connection: HAPConnectionHandle, + timeout: float | None, + ) -> Context: + """The context of a request: what its delegate calls share. + + A direct call has no controller waiting on a timeout, so a + ``timeout`` of ``None`` means no deadline. ``connection`` is the + handle of the request's connection - a controller's the one of its + connection, a direct call the virtual handle of its address, see + :meth:`_connection_of`. + """ + deadline = math.inf if timeout is None else time.monotonic() + timeout + return Context( + client_addr=client_addr, + client_uuid=client_uuid, + connection=connection, + deadline=deadline, + ) - return results, pending + @staticmethod + def _remaining(deadline: float) -> float | None: + """Seconds left of the deadline, or None when it is infinite.""" + if math.isinf(deadline): + return None + return max(0.0, deadline - time.monotonic()) - async def _async_finish_set_characteristics( + async def _await_calls( self, - results: dict[int, dict[int, dict[str, Any]]], - pending: list[_PendingWrite], - client_addr: tuple[str, int], - timeout: float, - writes: _ConnectionWrites, - ) -> dict[str, Any] | None: - """Wait for the coroutine setters, then build the response.""" - tasks = {asyncio.ensure_future(write.coro): write for write in pending} + tasks: dict[asyncio.Future[Any], Any], + deadline: float, + on_cancel: Callable[[asyncio.Future[Any]], None] | None = None, + ) -> tuple[set[asyncio.Future[Any]], set[asyncio.Future[Any]]]: + """Wait for ``tasks`` until ``deadline``, cancelling the ones not done. + + Returns the (done, not done) sets; every not-done task is cancelled + with a late-result retriever attached. When the wait itself is + cancelled, every task is cancelled the same way - or settled with + ``on_cancel`` when it is already done - and the CancelledError + re-raised. + """ try: - try: - done, not_done = await asyncio.wait(tasks, timeout=timeout) - except asyncio.CancelledError: - for task, write in tasks.items(): - if task.done(): - self._finish_done_write(task, write, client_addr) - continue + done, not_done = await asyncio.wait( + tasks, timeout=self._remaining(deadline) + ) + except asyncio.CancelledError: + for task in tasks: + if on_cancel is not None and task.done(): + on_cancel(task) + else: task.cancel() task.add_done_callback(_retrieve_late_result) - raise - for task in not_done: - task.cancel() - task.add_done_callback(_retrieve_late_result) - write = tasks[task] - logger.warning( - "%s: Timed out setting characteristic %s", - client_addr, - write.char.display_name, - ) - write.result[HAP_REPR_STATUS] = HAP_SERVER_STATUS.OPERATION_TIMED_OUT - for task in done: - write = tasks[task] - try: - outcome = task.result() - except (Exception, asyncio.CancelledError): - logger.exception( - "%s: Error while setting characteristic %s", - client_addr, - write.char.display_name, + raise + for task in not_done: + task.cancel() + task.add_done_callback(_retrieve_late_result) + return done, not_done + + @staticmethod + def _outcome_of(task: asyncio.Future[Any]) -> _CallOutcome: + """The outcome of a finished delegate call. + + A curated :class:`~pyhap.errors.HapStatusError` answers with its + status; any other failure answers ``-70402``, like the legacy + callbacks do. + """ + try: + return _CallOutcome(task.result(), None, None) + except HapStatusError as e: + return _CallOutcome(None, e.status, e) + except (Exception, asyncio.CancelledError) as e: # noqa: BLE001 - carried for the caller to log + return _CallOutcome( + None, HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE, e + ) + + async def _read_delegate_values( + self, + request: _ReadRequest, + answer: Callable[[_DelegateRead, Any, int | None], None], + ) -> None: + """Run the delegate reads of a request concurrently, answering each. + + Every read runs under the context's deadline; one that is not done + by it is cancelled and answers ``-70408``. Its answer is validated + and stored like a legacy getter's, then handed to ``answer`` with + the rep it fills - a failure arrives with its status instead of + a value. + """ + context = request.context + tasks: dict[asyncio.Future[Any], _DelegateRead] = {} + for read in request.reads: + tasks[asyncio.ensure_future(read.char.dispatch_get(context))] = read + if not tasks: + return + done, not_done = await self._await_calls(tasks, context.deadline) + for task in not_done: + read = tasks[task] + logger.warning( + "%s: Timed out getting characteristic %s", + context.client_addr, + read.char.display_name, + ) + self._finish_read(read, answer, HAP_SERVER_STATUS.OPERATION_TIMED_OUT) + for task in done: + read = tasks[task] + outcome = self._outcome_of(task) + if outcome.error is not None: + if isinstance(outcome.error, HapStatusError): + # The read answers the controller with its own HAP status. + logger.debug( + "%s: Characteristic %s answered status %s", + context.client_addr, + read.char.display_name, + outcome.status, ) - write.result[HAP_REPR_STATUS] = ( - HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + else: + logger.error( + "%s: Error getting value for characteristic %s", + context.client_addr, + read.char.display_name, + exc_info=outcome.error, ) - continue - write.char.client_update_finished( - write.previous_value, client_addr, notify=write.notify + self._finish_read(read, answer, outcome.status) + else: + self._finish_read(read, answer, None, outcome.value) + + @staticmethod + def _finish_read( + read: _DelegateRead, + answer: Callable[[_DelegateRead, Any, int | None], None], + status: int | None, + value: Any = None, + ) -> None: + """Validate and store a delegate's read answer, then shape its rep. + + Like a legacy getter's answer, the value is stored on the + characteristic - subscribers are not told, a read is not a change. + An answer that does not fit the characteristic's format fails with + ``-70402``, like a getter's would. + """ + if status is None: + try: + if read.char._always_null or value is None: + value = None + else: + value = read.char.to_valid_value(value) + read.char.value = value + except Exception: + logger.exception( + "Error while storing the value read of characteristic %s", + read.char.display_name, ) - if outcome is not None and writes.alive: - # A response of a connection that closed meanwhile is - # dropped, so it cannot wait for one that reuses the - # address. It would never be read: the response of a - # request is answered once, to the writing connection. - self._keep_response( - write.result, - write.char, - outcome, - write.write_response, - client_addr, - ) - return _set_characteristics_response(results) - finally: - batches = self._pending_connection_writes.get(client_addr) - if batches is not None: - batches.discard(writes) - if not batches: - del self._pending_connection_writes[client_addr] + value = None + status = HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + answer(read, value, status) @staticmethod - def _finish_done_write( - task: asyncio.Future[Any], write: _PendingWrite, client_addr: tuple[str, int] + def _answer_char_read(read: _DelegateRead, value: Any, status: int | None) -> None: + """Answer a characteristics read: the value or the failure status.""" + if status is None: + read.rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS + read.rep[HAP_REPR_VALUE] = value + else: + read.rep.pop(HAP_REPR_VALUE, None) + read.rep[HAP_REPR_STATUS] = status + + @staticmethod + def _answer_accessory_read( + read: _DelegateRead, value: Any, status: int | None ) -> None: - """Tell subscribers about a setter done before the write was cancelled.""" - if task.cancelled(): + """Answer an accessories read, which carries no per-char status. + + A failure lists the characteristic without a value, like a failing + getter does. + """ + if status is None: + read.rep[HAP_REPR_VALUE] = value + else: + read.rep.pop(HAP_REPR_VALUE, None) + + async def _dispatch_delegates(self, request: _WriteRequest) -> None: + """Call the delegates of the writes of a request. + + The service-level pre-checks run first, concurrently, each with + every written value of its service: a curated + :class:`~pyhap.errors.HapStatusError` refuses the writes of its + service - values are restored, subscribers are told nothing - and + so does a timeout or any other pre-check failure, with its status. + The surviving writes run concurrently, each under the context's + deadline; one that fails or misses it restores the previous value + and notifies nobody. + """ + if request.pre_checks: + await self._run_pre_checks(request) + if request.writes: + await self._run_char_writes(request) + + async def _run_pre_checks(self, request: _WriteRequest) -> None: + """Run the pre-checks of the request, refusing the writes they refuse. + + Every written service gets one: the ``on_set`` of its delegate, + with every written value of the service - the legacy grouped + setter of a service without a delegate runs here too, wrapped. + An accessory with a legacy grouped setter gets one as well, with + the values of all its written services. + """ + context = request.context + client_addr = context.client_addr + # The services each pre-check refuses the writes of: its own for a + # service pre-check, all written services of the accessory for an + # accessory one. + tasks: dict[asyncio.Future[Any], tuple[Service, ...]] = {} + for service, values in request.pre_checks.items(): + tasks[ + asyncio.ensure_future( + service.dispatch_set(values, context, is_admin=request.is_admin) + ) + ] = (service,) + accessories: dict[Accessory, dict[Service, dict[Characteristic, Any]]] = {} + for service, values in request.pre_checks.items(): + acc = service.broker + if acc is not None and acc.setter_callback: + accessories.setdefault(acc, {})[service] = values + for acc, updates_by_service in accessories.items(): + services = tuple(updates_by_service) + tasks[ + asyncio.ensure_future(acc._dispatch_legacy_setter(updates_by_service)) + ] = services + if not tasks: + return + done, not_done = await self._await_calls(tasks, context.deadline) + for task in not_done: + services = tasks[task] + logger.warning( + "%s: Timed out checking the writes of %s", + client_addr, + ", ".join(service.display_name or "" for service in services), + ) + self._veto_writes(request, services, HAP_SERVER_STATUS.OPERATION_TIMED_OUT) + for task in done: + services = tasks[task] + outcome = self._outcome_of(task) + if outcome.error is not None: + status = outcome.status + assert status is not None # noqa: S101 - an error outcome carries a status + if isinstance(outcome.error, HapStatusError): + # The pre-check answers the controller with its own status. + logger.debug( + "%s: A pre-check refused the writes of %s with status %s", + client_addr, + ", ".join(service.display_name or "" for service in services), + status, + ) + else: + logger.error( + "%s: Error checking the writes of %s", + client_addr, + ", ".join(service.display_name or "" for service in services), + exc_info=outcome.error, + ) + self._veto_writes(request, services, status) + + async def _run_char_writes(self, request: _WriteRequest) -> None: + """Apply the writes the gates left standing, concurrently. + + Every write's delegate call runs under the request's deadline, see + :meth:`_await_calls`: one still running when it passes is cancelled, + answers -70408 and has its previous value restored. A finished call + is settled by :meth:`_finish_task_write`. When the wait itself is + cancelled, e.g. because the connection closed, finished calls are + still settled and the rest are cancelled. + """ + context = request.context + client_addr = context.client_addr + tasks: dict[asyncio.Future[Any], _DelegateWrite] = {} + for write in request.writes: + tasks[ + asyncio.ensure_future( + write.char.dispatch_set( + write.value, context, is_admin=request.is_admin + ) + ) + ] = write + if not tasks: return - if (err := task.exception()) is not None: - logger.error( - "%s: Error while setting characteristic %s", + done, not_done = await self._await_calls( + tasks, + context.deadline, + on_cancel=lambda task: self._finish_task_write(task, tasks[task], context), + ) + for task in not_done: + write = tasks[task] + logger.warning( + "%s: Timed out setting characteristic %s", client_addr, write.char.display_name, - exc_info=err, ) + write.result[HAP_REPR_STATUS] = HAP_SERVER_STATUS.OPERATION_TIMED_OUT + self._restore_write_value(write) + for task in done: + self._finish_task_write(task, tasks[task], context) + + def _finish_task_write( + self, + task: asyncio.Future[Any], + write: _DelegateWrite, + context: Context, + ) -> None: + """Settle one finished write: its status, its response, its notify. + + A failed write answers its status - a curated + :class:`~pyhap.errors.HapStatusError` status, else -70402 - and puts + the previous value back, notifying nobody. An applied write settles + its private read-back bookkeeping, keeps the response for the + writing connection (dropped when it closed meanwhile, see + :meth:`_store_write_response`) and notifies the subscribers of the + new value, unless the write is private. + """ + client_addr = context.client_addr + outcome = self._outcome_of(task) + if outcome.error is not None: + if isinstance(outcome.error, HapStatusError): + # The delegate answers the controller with its own HAP status. + logger.debug( + "%s: Characteristic %s answered status %s", + client_addr, + write.char.display_name, + outcome.status, + ) + else: + logger.error( + "%s: Error while setting characteristic %s", + client_addr, + write.char.display_name, + exc_info=outcome.error, + ) + write.result[HAP_REPR_STATUS] = outcome.status + self._restore_write_value(write) return + # Complete the applied write: read back bookkeeping, response, notify. + response = outcome.value + if write.private_write: + response = _settle_private_write( + write.char, write.previous_value, write.value, response + ) + if response is not None: + # A response of a connection that closed meanwhile is dropped by + # the store: the response of a request is answered once, to the + # writing connection. + self._keep_response( + write.result, + write.char, + response, + write.write_response, + context.connection, + ) write.char.client_update_finished( - write.previous_value, client_addr, notify=write.notify + write.previous_value, context.connection, notify=not write.private_write ) + @staticmethod + def _restore_write_value(write: _DelegateWrite) -> None: + """Put back what a refused write changed.""" + if write.char.value != write.previous_value: + write.char.value = write.previous_value + + def _veto_writes( + self, + request: _WriteRequest, + services: tuple[Service, ...], + status: int, + ) -> None: + """Refuse the writes of ``services``: restore, tell nobody, answer status.""" + kept: list[_DelegateWrite] = [] + for write in request.writes: + if write.service not in services: + kept.append(write) + continue + write.result[HAP_REPR_STATUS] = status + self._restore_write_value(write) + request.writes = kept + + def _collect_delegate_write( + self, + request: _WriteRequest, + client_addr: tuple[str, int], + char: Characteristic, + service: Service, + value: Any, + previous_value: Any, + write_response: bool, + private_write: bool, + ) -> dict[str, Any]: + """Store a write and collect it for its delegates, return its result. + + The written service gets a pre-check whatever the characteristic + itself uses, so the pre-check sees every value of the request. + The value is validated and stored now: the delegates apply it once + the pre-checks accepted, and a write they refuse is restored. An + explicit null answers invalid, like the legacy path - nothing is + applied and no callback runs. + """ + request.pre_checks.setdefault(service, {})[char] = value + result: dict[str, Any] = {HAP_REPR_STATUS: HAP_SERVER_STATUS.SUCCESS} + if value is None: + result[HAP_REPR_STATUS] = HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST + return result + try: + previous_value = char._store_client_update(value) + except Exception: + logger.exception( + "%s: Error while setting characteristic %s to %s", + client_addr, + char.display_name, + value, + ) + result[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + return result + value = char.value + if private_write: + # The request of a readable write response or read back + # characteristic is not shared, whatever the delegates do: it + # never lives in the value while they run, they receive it as + # their argument, and the finish settles what they answer, see + # ``_settle_private_write``. + char.value = previous_value + request.writes.append( + _DelegateWrite( + char, + value, + previous_value, + result, + write_response, + private_write, + service, + ) + ) + return result + def _keep_response( self, result: dict[str, Any], char: Characteristic, response: HAPValue, write_response: bool, - client_addr: tuple[str, int] | None, + connection: HAPConnectionHandle | None, ) -> None: """Keep what a setter returned as a write response or read back value.""" if write_response: result[HAP_REPR_VALUE] = self._store_write_response( - char, response, client_addr + char, response, connection ) elif ( char.read_back_response and HAP_PERMISSION_READ in char.properties[PROP_PERMISSIONS] ): - self._store_write_response(char, response, client_addr) + self._store_write_response(char, response, connection) - def _take_prepared_write(self, pid: Any, client_addr: tuple[str, int]) -> bool: + def _take_prepared_write(self, pid: Any, connection: HAPConnectionHandle) -> bool: """Consume the prepared write ``pid`` and return whether it is still valid.""" if not _is_hap_int(pid): # Controller input. A list or dict is not even hashable. return False - expires_at = self.prepared_writes.get(client_addr, {}).pop(pid, None) + expires_at = self.prepared_writes.get(connection, {}).pop(pid, None) return expires_at is not None and time.monotonic() <= expires_at def _store_write_response( self, char: Characteristic, response: HAPValue, - client_addr: tuple[str, int] | None, + connection: HAPConnectionHandle | None, ) -> HAPValue: """Keep the write response and return what to send. @@ -1643,12 +2369,12 @@ def _store_write_response( characteristic is readable, only the connection that wrote reads the response back, until it closes, and it wins over the getter and a later ``set_value``. A setter that answers after the connection closed does - not get its response kept, whatever it returns. Other connections read - the characteristic's own value, which the write leaves as it was. A - write without ``r`` stays readable for everyone and notifies ``ev`` - subscribers as any write does, unless the characteristic has - ``read_back_response``, which keeps the response the same way without - a write response. + not get its response kept - the store drops it, see ``_is_open`` - + whatever it returns. Other connections read the characteristic's own + value, which the write leaves as it was. A write without ``r`` stays + readable for everyone and notifies ``ev`` subscribers as any write + does, unless the characteristic has ``read_back_response``, which + keeps the response the same way without a write response. """ readable = HAP_PERMISSION_READ in char.properties[PROP_PERMISSIONS] try: @@ -1661,14 +2387,18 @@ def _store_write_response( ) return response if readable: - if client_addr is not None: - self._write_responses.setdefault(client_addr, {})[char] = valid + if connection is not None and self._is_open(connection): + self._write_responses.setdefault(connection, {})[char] = valid else: char.value = valid return valid def prepare( - self, prepare_query: dict[str, Any], client_addr: tuple[str, int] + self, + prepare_query: dict[str, Any], + client_addr: tuple[str, int], + *, + connection: HAPConnectionHandle | None = None, ) -> dict[str, int]: """Called from ``HAPServerHandler`` when iOS wants to prepare a write. @@ -1682,7 +2412,17 @@ def prepare( } :type prepare_query: dict + + :param client_addr: The client that prepares the write. + :type client_addr: tuple + + :param connection: The connection the prepare came over, see + :class:`~pyhap.connection.HAPConnectionHandle`. ``None`` for a + call without one: it acts as the virtual connection of + ``client_addr``, see :meth:`_connection_of`. + :type connection: HAPConnectionHandle or None """ + connection = connection or self._connection_of(client_addr) if not isinstance(prepare_query, dict): return {HAP_REPR_STATUS: HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST} ttl = prepare_query.get(HAP_REPR_TTL) @@ -1691,7 +2431,7 @@ def prepare( return {HAP_REPR_STATUS: HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST} try: now = time.monotonic() - pending = self.prepared_writes.setdefault(client_addr, {}) + pending = self.prepared_writes.setdefault(connection, {}) # Prune expired entries and cap the number of pending writes so a # paired client cannot grow prepared_writes without bound by # registering endless unique pids with arbitrary TTLs. @@ -1702,7 +2442,7 @@ def prepare( ]: del pending[stale_pid] if len(pending) >= MAX_PREPARED_WRITES_PER_CLIENT: - del pending[min(pending, key=pending.get)] + del pending[min(pending, key=pending.__getitem__)] pending[pid] = now + min(ttl / 1000, MAX_PREPARED_WRITE_TTL_SECONDS) except OverflowError: return {HAP_REPR_STATUS: HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST} @@ -1727,13 +2467,20 @@ def signal_handler(self, _signal: Any, _frame: Any) -> None: raise def _notify( - self, queries: list[CharacteristicWrite], client_addr: tuple[str, int] + self, + queries: list[CharacteristicWrite], + client_addr: tuple[str, int], + client_uuid: UUID | None, + connection: HAPConnectionHandle, ) -> set[tuple[int, int]]: """Notify the driver that the client has subscribed or unsubscribed. Characteristics without the notify permission are left alone; their ``(aid, iid)`` pairs are returned so the request can report - -70406 for them. + -70406 for them. A characteristic with a delegate also gets its + ``on_subscribe`` / ``on_unsubscribe`` hook, on the transition: a + request that subscribes an already subscribed controller, or + unsubscribes one that is not, runs no hook. """ assert self.accessory is not None # noqa: S101 not_notifiable: set[tuple[int, int]] = set() @@ -1753,7 +2500,39 @@ def _notify( continue char_topic = get_topic(aid, iid) + was_subscribed = connection in self.topics.get(char_topic, ()) action = "Subscribed" if ev else "Unsubscribed" logger.debug("%s client %s to topic %s", action, client_addr, char_topic) - self.async_subscribe_client_topic(client_addr, char_topic, ev) + self.async_subscribe_client_topic(connection, char_topic, ev) + if char is not None and ev != was_subscribed: + self._dispatch_subscription( + char, ev, client_addr, client_uuid, connection + ) return not_notifiable + + def _dispatch_subscription( + self, + characteristic: Characteristic, + subscribe: bool, + client_addr: tuple[str, int] | None, + client_uuid: UUID | None, + connection: HAPConnectionHandle, + ) -> None: + """Run a characteristic's ``on_subscribe`` or ``on_unsubscribe``, isolated. + + The hook runs as a job without a deadline: the request, or the + connection close, that caused it never waits for it. Its exception + is logged, and the subscription itself has already registered by + the time the hook runs. + """ + context = self._build_request_context( + client_addr, client_uuid, connection, None + ) + hook, args = characteristic.subscription_hook(subscribe, context) + self.add_job( + self._run_isolated_hook, + hook, + args, + "on_subscribe" if subscribe else "on_unsubscribe", + client_addr, + ) diff --git a/pyhap/camera.py b/pyhap/camera.py index 28eb218d..ed177534 100644 --- a/pyhap/camera.py +++ b/pyhap/camera.py @@ -21,6 +21,7 @@ import contextlib import functools import hashlib +import inspect import ipaddress import logging import os @@ -43,7 +44,10 @@ from pyhap.camera_talkback import TalkbackReceiver, TalkbackReceiverProtocol from pyhap.camera_webrtc import WebRTCConfig, WebRTCController from pyhap.characteristic import Characteristic +from pyhap.connection import HAPConnectionHandle from pyhap.const import CATEGORY_CAMERA +from pyhap.context import CharReadContext, CharWriteContext +from pyhap.delegates import CharacteristicDelegate from pyhap.service import Service from pyhap.util import ( base64_to_bytes, @@ -279,6 +283,61 @@ ) +class _CameraDelegate(CharacteristicDelegate): + """Serves the camera's own characteristics through their handlers. + + One instance serves every characteristic the camera itself answers - + the context identifies the one being read or written, and each has its + handler in ``handlers`` and, for a read of a derived value, in + ``get_handlers``. A write handler runs as part of ``on_set`` and returns + the write response of a write-response characteristic; the driver restores + the previous value and tells nobody when it raises. + """ + + def __init__(self) -> None: + self.handlers: dict[Characteristic, Callable[[Any, CharWriteContext], Any]] = {} + self.get_handlers: dict[Characteristic, Callable[[CharReadContext], Any]] = {} + + def wire( + self, char: Characteristic, handler: Callable[[Any, CharWriteContext], Any] + ) -> None: + """Serve ``char``'s writes with ``handler(value, context)``. + + Wiring again replaces the handler, e.g. to wrap one that first + checks the written value. + """ + self.handlers[char] = handler + char.delegate = self + + def wire_get( + self, char: Characteristic, handler: Callable[[CharReadContext], Any] + ) -> None: + """Serve ``char``'s reads with ``handler(context)``. + + Wiring again replaces the handler. A characteristic without a read + handler answers its stored value. + """ + self.get_handlers[char] = handler + char.delegate = self + + async def on_get(self, context: CharReadContext) -> Any: + handler = self.get_handlers.get(context.characteristic) + if handler is None: + # Reads answer the stored value, like the camera always has. + return context.characteristic.value + result = handler(context) + if inspect.isawaitable(result): + result = await result + return result + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + handler = self.handlers[context.characteristic] + response = handler(value, context) + if inspect.isawaitable(response): + response = await response + return response + + def _decode_setup_endpoints( session_id: UUID, objs: dict[bytes, Any] ) -> tuple[str, bool, int, int, tuple[bytes, bytes], tuple[bytes, bytes]]: @@ -647,6 +706,7 @@ def __init__(self, options: dict[str, Any], *args: Any, **kwargs: Any) -> None: self.has_srtp = options.get("srtp", False) self.support_talkback = options.get("talkback", False) self.start_stream_cmd = options.get("start_stream_cmd", FFMPEG_CMD) + self._camera_delegate = _CameraDelegate() self.stream_address = options["address"] try: @@ -771,9 +831,9 @@ def _create_stream_management( # management service (value 1 = active); iOS' camera validation expects # it, and it is required for Secure Video eligibility. management.configure_char("Active", value=1) - management.configure_char( - "StreamingStatus", - getter_callback=lambda: self._get_streaming_status(stream_idx), + self._wire_get( + management.configure_char("StreamingStatus"), + lambda context: self._get_streaming_status(stream_idx), ) management.configure_char( "SupportedRTPConfiguration", @@ -787,15 +847,14 @@ def _create_stream_management( "SupportedAudioStreamConfiguration", value=self.get_supported_audio_stream_config(options["audio"]), ) - management.configure_char( - "SelectedRTPStreamConfiguration", - setter_callback=self.set_selected_stream_configuration, + self._wire( + management.configure_char("SelectedRTPStreamConfiguration"), + lambda value, context: self.set_selected_stream_configuration(value), ) - setup_endpoints = management.configure_char( - "SetupEndpoints", - setter_callback=lambda value: self.set_endpoints( - value, stream_idx=stream_idx - ), + setup_endpoints = management.configure_char("SetupEndpoints") + self._wire( + setup_endpoints, + lambda value, context: self.set_endpoints(value, stream_idx=stream_idx), ) # The answer has the session's SRTP keys, only its controller reads it. setup_endpoints.read_back_response = True @@ -887,14 +946,14 @@ def _update_stream_status(self) -> None: controller.update_status() def _stream_address_for( - self, client_addr: tuple[str, int] | None, is_ipv6: bool + self, connection: HAPConnectionHandle | None, is_ipv6: bool ) -> str | None: """The address to stream from to a controller, in the given IP version. The accessory's address on the controller's connection, else the ``address`` option if it has that version. """ - address = self.driver._local_address(client_addr, is_ipv6) + address = self.driver._local_address(connection, is_ipv6) if address is not None: return address if (self.stream_address_isv6 == b"\x01") == is_ipv6: @@ -965,7 +1024,10 @@ def _setup_recording_management(self, options: dict[str, Any]) -> None: homekit_camera_active = operating_mode.configure_char( "HomeKitCameraActive", value=1 ) - homekit_camera_active.setter_callback = self._handle_homekit_camera_active + self._wire( + homekit_camera_active, + lambda value, context: self._handle_homekit_camera_active(value), + ) self._homekit_camera_active_char = homekit_camera_active self._classic_camera_active_char = homekit_camera_active operating_mode.configure_char("PeriodicSnapshotsActive", value=1) @@ -982,7 +1044,11 @@ def _setup_recording_management(self, options: dict[str, Any]) -> None: # HAP-NodeJS marks the HKSV event-trigger sensor as active; iOS expects it. # A restored HomeKitCameraActive bypasses the setter, so reads derive it. self._motion_status_active_char = motion.configure_char( - "StatusActive", value=True, getter_callback=self._homekit_camera_on + "StatusActive", value=True + ) + self._wire_get( + self._motion_status_active_char, + lambda context: self._homekit_camera_on(), ) general, video, audio = self._default_recording_configs(options) @@ -1006,9 +1072,9 @@ def _setup_recording_management(self, options: dict[str, Any]) -> None: "SupportedAudioRecordingConfiguration", value=to_base64_str(hksv_recording.encode_supported_audio(audio)), ) - service.configure_char( - "SelectedCameraRecordingConfiguration", - setter_callback=self.set_selected_recording_configuration, + self._wire( + service.configure_char("SelectedCameraRecordingConfiguration"), + lambda value, context: self.set_selected_recording_configuration(value), ) self._recording_service = service for service_name, char_name in PERSISTED_RECORDING_CHARS: @@ -1063,7 +1129,10 @@ def _setup_camera_capabilities(self) -> None: ): self._persist_hksv3_char(char, key, handler) # Check the zones before they count as written. - zones.get_characteristic("CameraZones").setter_callback = self._set_camera_zones + self._wire( + zones.get_characteristic("CameraZones"), + lambda value, context: self._set_camera_zones(value), + ) @property def camera_zones(self) -> hksv3.CameraZones | None: @@ -1100,8 +1169,8 @@ def _set_camera_zones(self, value: str) -> None: if value: hksv3.CameraZones.decode(base64_to_bytes(value)) except ValueError: - # Fail the write and keep the zones the camera had. - char.value = self._hksv3_seen[char] + # Fail the write: the driver puts back the previous value and + # keeps the zones the camera had. raise self._hksv3_written(char, value) @@ -1139,9 +1208,9 @@ def _setup_data_stream_transport(self) -> None: "SupportedDataStreamTransportConfiguration", value=to_base64_str(self._supported_data_stream_transport()), ) - transport.configure_char( - "SetupDataStreamTransport", - setter_callback=self.set_data_stream_transport, + self._wire( + transport.configure_char("SetupDataStreamTransport"), + self.set_data_stream_transport, ) # HKSV requires the recording management service to link the data stream # transport it records over; without the link the controller rejects @@ -1176,25 +1245,27 @@ def _on_hds_connection(self, connection: hds_server.HDSConnection) -> None: connection, self._recording_delegate, open_gate=self._recording_open_gate ) - def set_data_stream_transport( - self, value: str, sender_client_addr: Any = None - ) -> str: + def set_data_stream_transport(self, value: str, context: CharWriteContext) -> str: """Handle a write to SetupDataStreamTransport (HDS session setup). SetupDataStreamTransport is a write-response ('wr') characteristic: the controller writes with ``r: true`` and reads the encoded setup response (TCP listening port + accessory key salt) straight back from the write - response. That means the value MUST be RETURNED from the setter so the + response. That means the value MUST be RETURNED from the handler so the HAP layer includes it in the write response — setting it on the characteristic is not delivered to the controller and leaves it without the port, so it can never open the HDS connection. + + :param context: The write's context; the HDS session keys are derived + from the writing connection, see + :meth:`pyhap.accessory_driver.AccessoryDriver.derive_session_key`. """ request = hds.SetupRequest.decode(base64_to_bytes(value)) listener = self._hds_listener accessory_salt = None if listener is not None: accessory_salt = listener.register_session_transport( - functools.partial(self.driver.derive_session_key, sender_client_addr), + functools.partial(self.driver.derive_session_key, context.connection), request.controller_key_salt, ) if listener is None or accessory_salt is None: @@ -1282,8 +1353,12 @@ def _setup_global_operating_mode(self, chars: Sequence[str]) -> None: handler = self._handle_global_camera_active # The last write to either HomeKit Camera Active decides. if self._classic_camera_active_char is not None: - self._classic_camera_active_char.setter_callback = ( - self._handle_classic_camera_active + classic = self._classic_camera_active_char + self._wire( + classic, + lambda value, context: self._handle_classic_camera_active( + value + ), ) self._homekit_camera_active_char = char else: @@ -1396,11 +1471,11 @@ def publish( self, value: Any, sender: Service | Characteristic, - sender_client_addr: Any = None, + connection: HAPConnectionHandle | None = None, immediate: bool = False, ) -> None: """Forward the update and store recording and HKSV 17.99 state changes.""" - super().publish(value, sender, sender_client_addr, immediate) + super().publish(value, sender, connection, immediate) if sender in self._hksv3_defaults: # Local changes too, so a later write of the same value is no change. self._hksv3_seen[sender] = value @@ -1458,6 +1533,26 @@ def _save_state(self) -> None: self._arm_recording_media() self.recording_state_changed() + def _wire( + self, char: Characteristic, handler: Callable[[Any, CharWriteContext], Any] + ) -> None: + """Serve ``char``'s writes with ``handler(value, context)``. + + All of the camera's own characteristics go through one + :class:`_CameraDelegate`; wiring again replaces the handler. + """ + self._camera_delegate.wire(char, handler) + + def _wire_get( + self, char: Characteristic, handler: Callable[[CharReadContext], Any] + ) -> None: + """Serve ``char``'s reads with ``handler(context)``. + + All of the camera's own characteristics go through one + :class:`_CameraDelegate`; wiring again replaces the handler. + """ + self._camera_delegate.wire_get(char, handler) + def _persist_hksv3_char( self, char: Characteristic, key: str, handler: Callable[[Any], None] ) -> None: @@ -1468,7 +1563,10 @@ def _persist_hksv3_char( the stored values afterwards. """ self._hksv3_defaults[char] = (key, char.value, handler) - char.setter_callback = functools.partial(self._hksv3_written, char) + self._wire( + char, + lambda value, context, char=char: self._hksv3_written(char, value), + ) def _hksv3_written(self, char: Characteristic, value: Any) -> None: """Call the handler of ``char`` if the write changed its value.""" diff --git a/pyhap/camera_multi_tier.py b/pyhap/camera_multi_tier.py index d35815c9..badb8f17 100644 --- a/pyhap/camera_multi_tier.py +++ b/pyhap/camera_multi_tier.py @@ -31,10 +31,14 @@ config_from_option, failure_status, ) +from pyhap.connection import HAPConnectionHandle +from pyhap.context import CharReadContext, CharWriteContext +from pyhap.delegates import CharacteristicDelegate from pyhap.util import base64_to_bytes, parse_setup_address, to_base64_str if TYPE_CHECKING: from pyhap.camera import Camera + from pyhap.characteristic import Characteristic __all__ = [ "DEFAULT_IDLE_TIMEOUT", @@ -222,6 +226,27 @@ def _supported_video_tiers(tiers: list[hksv3.VideoStreamTier]) -> bytes: ).encode() +class _WriteDelegate(CharacteristicDelegate): + """Answers the service's control writes through the controller. + + Setup Endpoints and RTP Streaming Control are write-response + characteristics: ``on_set`` returns the answer the writing connection + reads back, and the stored value it sees is the request it wrote, put + back once the answer was kept for the writer. + """ + + def __init__(self, controller: MultiTierController) -> None: + self._controller = controller + + async def on_get(self, context: CharReadContext) -> Any: + # The stored value, like the reads of these characteristics + # always answered. + return context.characteristic.value + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + return await self._controller._write(context.characteristic, value, context) + + class MultiTierController(StreamController[MultiTierSession]): """The Camera Multi-Tier RTP Stream Management service of one sensor.""" @@ -258,15 +283,17 @@ def __init__( ) self.streaming_enabled = service.configure_char("StreamingEnabled", value=True) self._status_active = service.get_characteristic("StatusActive") - setup_endpoints = service.configure_char( - "SetupEndpoints", setter_callback=self._set_setup_endpoints + write_delegate = _WriteDelegate(self) + self._setup_endpoints = setup_endpoints = service.configure_char( + "SetupEndpoints" ) # The answer has the session's SRTP keys, only its controller reads it. setup_endpoints.read_back_response = True # Neither the request nor the status is shared with other connections. - service.configure_char( - "RTPStreamingControl", setter_callback=self._set_streaming_control - ).read_back_response = True + self._control_char = control = service.configure_char("RTPStreamingControl") + control.read_back_response = True + setup_endpoints.delegate = write_delegate + control.delegate = write_delegate @property def active(self) -> bool: @@ -305,18 +332,30 @@ def _delegate(self) -> MultiTierDelegate: async def _release_hook(self, session: MultiTierSession) -> None: await self._delegate.handle_end(session) + async def _write( + self, char: Characteristic, value: Any, context: CharWriteContext + ) -> str: + """Answer a write of the service's control characteristics.""" + if char is self._setup_endpoints: + return await self._set_setup_endpoints( + value, context.connection, context.deadline + ) + assert char is self._control_char # noqa: S101 + return await self._set_streaming_control( + value, context.connection, context.deadline + ) + async def _set_setup_endpoints( - self, value: str, sender_client_addr: tuple[str, int] | None = None + self, value: str, connection: HAPConnectionHandle, deadline: float ) -> str: """Set up a session, only the writing connection reads the answer.""" - deadline = self._deadline() try: request = hksv3.SetupEndpoints.decode(base64_to_bytes(value)) except ValueError: logger.warning("Ignoring a malformed Setup Endpoints write") status = hksv3.SetupEndpointsStatus.ERROR return to_base64_str(hksv3.SetupEndpointsResponse(None, status).encode()) - result = await self._setup(request, sender_client_addr, deadline) + result = await self._setup(request, connection, deadline) if isinstance(result, MultiTierSession): return to_base64_str(_answer(result).encode()) response = hksv3.SetupEndpointsResponse(request.session_id, result) @@ -325,7 +364,7 @@ async def _set_setup_endpoints( async def _setup( self, request: hksv3.SetupEndpoints, - client_addr: tuple[str, int] | None, + connection: HAPConnectionHandle, deadline: float, ) -> MultiTierSession | hksv3.SetupEndpointsStatus: session_id = request.session_id @@ -347,13 +386,13 @@ async def _setup( endpoint.video_port, endpoint.audio_port, ) - existing = self._owned(session_id, client_addr) + existing = self._owned(session_id, connection) if existing is None and session_id in self._sessions: return error if not self.active: logger.warning("[%s] Streaming is turned off, refusing it", session_id) return error - if existing is None and (no_room := self._no_room(client_addr)): + if existing is None and (no_room := self._no_room(connection)): logger.warning("[%s] %s", session_id, no_room) # Busy asks to try again, a closed service never takes one. return error if self._closed else hksv3.SetupEndpointsStatus.BUSY @@ -361,7 +400,7 @@ async def _setup( logger.warning("[%s] No multi-tier delegate, refusing", session_id) return error accessory_address = self.camera._stream_address_for( - client_addr, endpoint.is_ipv6 + connection, endpoint.is_ipv6 ) if accessory_address is None: logger.warning( @@ -383,13 +422,13 @@ async def _setup( if not self.active: logger.warning("[%s] Streaming is turned off, refusing it", session_id) return error - if no_room := self._no_room(client_addr): + if no_room := self._no_room(connection): logger.warning("[%s] %s", session_id, no_room) return error if self._closed else hksv3.SetupEndpointsStatus.BUSY session = MultiTierSession( id=session_id, sensor=self.sensor, - client_addr=client_addr, + connection=connection, address=address, is_ipv6=endpoint.is_ipv6, video_port=endpoint.video_port, @@ -444,10 +483,9 @@ async def _setup( return session async def _set_streaming_control( - self, value: str, sender_client_addr: tuple[str, int] | None = None + self, value: str, connection: HAPConnectionHandle, deadline: float ) -> str: """Start, change or end a stream, the write response is the status.""" - deadline = self._deadline() try: request = hksv3.RTPStreamingControl.decode(base64_to_bytes(value)) except ValueError: @@ -455,17 +493,17 @@ async def _set_streaming_control( status = hksv3.encode_streaming_status(None, _STATUS.ERROR) return to_base64_str(status) logger.debug("RTP Streaming Control: %s", request) - result = await self._streaming_control(request, sender_client_addr, deadline) + result = await self._streaming_control(request, connection, deadline) logger.debug("[%s] RTP Streaming Control: %s", request.session_id, result) return to_base64_str(hksv3.encode_streaming_status(request.session_id, result)) async def _streaming_control( self, request: hksv3.RTPStreamingControl, - client_addr: tuple[str, int] | None, + connection: HAPConnectionHandle, deadline: float, ) -> hksv3.RTPStreamingStatus: - session = self._owned(request.session_id, client_addr) + session = self._owned(request.session_id, connection) if session is None: return _STATUS.UNKNOWN_SESSION if request.command == hksv3.RTPStreamingCommand.END: diff --git a/pyhap/camera_stream.py b/pyhap/camera_stream.py index 847a155b..1f1c5aec 100644 --- a/pyhap/camera_stream.py +++ b/pyhap/camera_stream.py @@ -15,8 +15,9 @@ -> ENDED, from any state A delegate hook runs as a task the session owns. A HAP request waits for it -until one deadline, ``hook_timeout`` after the write, which leaves time to -answer within the HAP response timeout. A hook that takes longer is +until one deadline, the request's write deadline (see +:attr:`pyhap.context.Context.deadline`), which leaves time to answer within +the HAP response timeout. A hook that takes longer is cancelled and its session ends. Once a session ended, the delegate releases it exactly once, in the background, if it saw the session at all. Until its release finished or timed out, the session still counts towards the session @@ -41,6 +42,7 @@ from uuid import UUID from pyhap import hksv3 +from pyhap.connection import HAPConnectionHandle from pyhap.const import RESPONSE_TIMEOUT if TYPE_CHECKING: @@ -101,13 +103,16 @@ class SessionState(Enum): class StreamSession: """A stream session of one controller connection and one sensor. - Only ``client_addr``, the connection that set the session up, may control - it. ``data`` is free for the delegate. + Only the connection that set the session up, identified by its + :class:`~pyhap.connection.HAPConnectionHandle`, may control it. Two + connections never share a handle, not even two that reuse the same + address, so a session cannot leak to a later connection. ``data`` is free + for the delegate. """ id: UUID sensor: hksv3.SensorConfiguration - client_addr: tuple[str, int] | None + connection: HAPConnectionHandle state: SessionState = SessionState.NEW data: dict[str, Any] = field(default_factory=dict) _tasks: set[asyncio.Task[Any]] = field(default_factory=set, init=False, repr=False) @@ -122,6 +127,11 @@ class StreamSession: def sensor_uuid(self) -> UUID: return self.sensor.sensor_uuid + @property + def client_addr(self) -> tuple[str, int] | None: + """The address of the connection that owns the session.""" + return self.connection.client_addr + @property def ended(self) -> bool: return self.state is SessionState.ENDED @@ -220,10 +230,6 @@ def sessions(self) -> Mapping[UUID, _S]: def _loop(self) -> asyncio.AbstractEventLoop: return cast(asyncio.AbstractEventLoop, self.camera.driver.loop) - def _deadline(self) -> float: - """The deadline of the hooks of a request that arrives now.""" - return self._loop.time() + self.hook_timeout - def _add(self, session: _S) -> None: """Register a new session, it may end itself from now on. @@ -234,27 +240,26 @@ def _add(self, session: _S) -> None: session._controller = self self._sessions[session.id] = session - def _no_room(self, client_addr: tuple[str, int] | None) -> str | None: - """Why a new session of ``client_addr`` does not fit, None if it does.""" + def _no_room(self, connection: HAPConnectionHandle) -> str | None: + """Why a new session of ``connection`` does not fit, None if it does.""" if self._closed: return f"The {self.kind} service is closed" sessions = [*self._sessions.values(), *self._releasing] if len(sessions) >= self.max_sessions: return f"Too many {self.kind} sessions" - owned = sum(session.client_addr == client_addr for session in sessions) + owned = sum(session.connection == connection for session in sessions) if owned >= self.max_sessions_per_connection: return f"Too many {self.kind} sessions of the connection" return None - def _owned( - self, session_id: UUID, client_addr: tuple[str, int] | None - ) -> _S | None: - """Return the session if ``client_addr`` owns it. + def _owned(self, session_id: UUID, connection: HAPConnectionHandle) -> _S | None: + """Return the session if ``connection`` owns it. - A session of another connection is unknown to it. + A session of another connection is unknown to it, also one of a former + connection that reused its address. """ session = self._sessions.get(session_id) - if session is not None and session.client_addr != client_addr: + if session is not None and session.connection != connection: logger.debug("[%s] Not the controller of the session", session_id) return None return session @@ -270,9 +275,11 @@ async def _run_hook( ) -> _T: """Run a delegate hook as a task of ``session`` until ``deadline``. - A hook that is still running then is cancelled and its session ends. - ``first`` marks the hook that introduces the session to the delegate, - which then releases it when it ends. + A hook gets at most ``hook_timeout`` seconds, or as long as the + request has left: whichever ends first, the answer still fits in + the request. A hook that is still running then is cancelled and + its session ends. ``first`` marks the hook that introduces the + session to the delegate, which then releases it when it ends. :raises HookFailed: If the hook failed or took too long, or the session ended meanwhile. @@ -282,6 +289,10 @@ async def _run_hook( raise HookFailed if first: session._delegated = True + # A hook gets ``hook_timeout`` seconds, or as long as the request + # has left: whichever ends first, the answer fits in the request, + # see ``MAX_HOOK_TIMEOUT``. + deadline = min(deadline, self._loop.time() + self.hook_timeout) task = self._loop.create_task(hook) session._tasks.add(task) task.add_done_callback(session._tasks.discard) @@ -460,7 +471,15 @@ def _end_sessions(self, reason: str) -> None: self._end(session, reason) def client_disconnected(self, client_addr: tuple[str, int]) -> None: - """End the sessions of a connection that closed.""" + """End the sessions of a connection that closed. + + The address still names the sessions here: the accessory's + ``client_disconnected`` lifecycle reports a closed connection by + address, and ending by it is the conservative choice - a live + connection has its own sessions under its own handle, so an end + by address can only end too much, never a session of another + connection. + """ for session in list(self._sessions.values()): if session.client_addr == client_addr: self._end(session, "the controller disconnected") diff --git a/pyhap/camera_webrtc.py b/pyhap/camera_webrtc.py index a2fb64a3..433aa072 100644 --- a/pyhap/camera_webrtc.py +++ b/pyhap/camera_webrtc.py @@ -15,7 +15,7 @@ from __future__ import annotations -from collections.abc import Callable, Mapping +from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass import logging from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast @@ -32,11 +32,15 @@ config_from_option, failure_status, ) +from pyhap.connection import HAPConnectionHandle +from pyhap.context import CharReadContext, CharWriteContext +from pyhap.delegates import CharacteristicDelegate from pyhap.util import base64_to_bytes, to_base64_str if TYPE_CHECKING: from pyhap.camera import Camera from pyhap.camera_multi_tier import MultiTierController + from pyhap.characteristic import Characteristic __all__ = [ "WEBRTC_MIN_SESSIONS", @@ -201,6 +205,27 @@ def _status(session_id: UUID | None, status: hksv3.WebRTCStreamingStatus) -> str return to_base64_str(hksv3.WebRTCSessionStatus(session_id, status).encode()) +class _WriteDelegate(CharacteristicDelegate): + """Answers the service's control writes through the controller. + + Every controlled characteristic is a write-response one: ``on_set`` + returns the answer the writing connection reads back, and the stored + value it sees is the request it wrote, put back once the answer was kept + for the writer. + """ + + def __init__(self, controller: WebRTCController) -> None: + self._controller = controller + + async def on_get(self, context: CharReadContext) -> Any: + # The stored value, like the reads of these characteristics + # always answered. + return context.characteristic.value + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + return await self._controller._write(context.characteristic, value, context) + + class WebRTCController(StreamController[WebRTCSession]): """The Camera WebRTC Stream Management service of one sensor.""" @@ -241,6 +266,10 @@ def __init__( service.configure_char(name, value=value) self.streaming_enabled = service.configure_char("StreamingEnabled", value=True) self._session_count = service.get_characteristic("WebRTCNumberOfActiveSessions") + write_delegate = _WriteDelegate(self) + self._writers: dict[ + Characteristic, Callable[[str, HAPConnectionHandle, float], Awaitable[str]] + ] = {} for name, setter in ( ("WebRTCSolicitOffer", self._set_solicit_offer), ("WebRTCProvideAnswer", self._set_provide_answer), @@ -250,9 +279,10 @@ def __init__( ): # The requests carry SDPs with ICE passwords and SFrame keys, so # neither they nor the answers are shared with other connections. - service.configure_char( - name, setter_callback=setter - ).read_back_response = True + char = service.configure_char(name) + char.read_back_response = True + char.delegate = write_delegate + self._writers[char] = setter def _refusal(self) -> hksv3.WebRTCSolicitOfferStatus | None: """Why the sensor may not stream now, None if it may.""" @@ -286,19 +316,23 @@ def _delegate(self) -> WebRTCDelegate: async def _release_hook(self, session: WebRTCSession) -> None: await self._delegate.handle_end(session) + async def _write( + self, char: Characteristic, value: Any, context: CharWriteContext + ) -> str: + """Answer a write of the service's control characteristics.""" + writer = self._writers[char] + return await writer(value, context.connection, context.deadline) + async def _set_solicit_offer( - self, value: str, sender_client_addr: tuple[str, int] | None = None + self, value: str, connection: HAPConnectionHandle, deadline: float ) -> str: - deadline = self._deadline() request = _decode("Solicit Offer", hksv3.WebRTCSolicitOffer.decode, value) if request is None: response = hksv3.WebRTCSolicitOfferResponse( hksv3.WebRTCSolicitOfferStatus.ERROR ) else: - response = await self._solicit_offer( - request.options, sender_client_addr, deadline - ) + response = await self._solicit_offer(request.options, connection, deadline) logger.debug( "[%s] WebRTC Solicit Offer: %s", response.session_id, response.status ) @@ -307,7 +341,7 @@ async def _set_solicit_offer( async def _solicit_offer( self, options: hksv3.WebRTCOfferOptions, - client_addr: tuple[str, int] | None, + connection: HAPConnectionHandle, deadline: float, ) -> hksv3.WebRTCSolicitOfferResponse: error = hksv3.WebRTCSolicitOfferStatus.ERROR @@ -316,7 +350,7 @@ async def _solicit_offer( logger.info("Refusing a WebRTC offer, streaming is off: %s", refusal) return hksv3.WebRTCSolicitOfferResponse(refusal) # The guide has no Busy for an offer. - if no_room := self._no_room(client_addr): + if no_room := self._no_room(connection): logger.warning("%s, refusing an offer", no_room) return hksv3.WebRTCSolicitOfferResponse(error) if self.delegate is None: @@ -325,7 +359,7 @@ async def _solicit_offer( session = WebRTCSession( id=uuid4(), sensor=self.sensor, - client_addr=client_addr, + connection=connection, sframe=options.sframe_enabled is not False, video_tier=self.video_tier, audio_tier=self.audio_tier, @@ -373,13 +407,12 @@ async def _solicit_offer( ) async def _set_provide_answer( - self, value: str, sender_client_addr: tuple[str, int] | None = None + self, value: str, connection: HAPConnectionHandle, deadline: float ) -> str: - deadline = self._deadline() request = _decode("Provide Answer", hksv3.WebRTCProvideAnswer.decode, value) if request is None: return _status(None, _STATUS.ERROR) - session = self._owned(request.session_id, sender_client_addr) + session = self._owned(request.session_id, connection) if session is None: return _status(request.session_id, _STATUS.UNKNOWN_SESSION) if session.state is SessionState.ANSWERING: @@ -405,15 +438,14 @@ async def _set_provide_answer( return _status(session.id, _STATUS.SUCCESS) async def _set_streaming_control( - self, value: str, sender_client_addr: tuple[str, int] | None = None + self, value: str, connection: HAPConnectionHandle, deadline: float ) -> str: - deadline = self._deadline() request = _decode( "Streaming Control", hksv3.WebRTCStreamingControl.decode, value ) if request is None: return _status(None, _STATUS.ERROR) - session = self._owned(request.session_id, sender_client_addr) + session = self._owned(request.session_id, connection) if session is None: return _status(request.session_id, _STATUS.UNKNOWN_SESSION) if request.command != hksv3.WebRTCStreamingCommand.END: @@ -422,10 +454,10 @@ async def _set_streaming_control( return _status(session.id, _STATUS.SUCCESS if ended else _STATUS.ERROR) def _active_session( - self, session_id: UUID, client_addr: tuple[str, int] | None + self, session_id: UUID, connection: HAPConnectionHandle ) -> WebRTCSession | hksv3.WebRTCStreamingStatus: """The session to renegotiate or update, else the status to answer.""" - session = self._owned(session_id, client_addr) + session = self._owned(session_id, connection) if session is None: return _STATUS.UNKNOWN_SESSION if session.state is not SessionState.ACTIVE: @@ -435,23 +467,22 @@ def _active_session( return session async def _set_reoffer( - self, value: str, sender_client_addr: tuple[str, int] | None = None + self, value: str, connection: HAPConnectionHandle, deadline: float ) -> str: - deadline = self._deadline() request = _decode("Reoffer", hksv3.WebRTCReoffer.decode, value) if request is None: response = hksv3.WebRTCReofferResponse(None, _STATUS.ERROR) else: - response = await self._reoffer(request, sender_client_addr, deadline) + response = await self._reoffer(request, connection, deadline) return to_base64_str(response.encode()) async def _reoffer( self, request: hksv3.WebRTCReoffer, - client_addr: tuple[str, int] | None, + connection: HAPConnectionHandle, deadline: float, ) -> hksv3.WebRTCReofferResponse: - session = self._active_session(request.session_id, client_addr) + session = self._active_session(request.session_id, connection) if not isinstance(session, WebRTCSession): return hksv3.WebRTCReofferResponse(request.session_id, session) hook = self._delegate.handle_reoffer( @@ -481,13 +512,12 @@ async def _reoffer( ) async def _set_update_session( - self, value: str, sender_client_addr: tuple[str, int] | None = None + self, value: str, connection: HAPConnectionHandle, deadline: float ) -> str: - deadline = self._deadline() request = _decode("Update Session", hksv3.WebRTCUpdateSession.decode, value) if request is None: return _status(None, _STATUS.ERROR) - session = self._active_session(request.session_id, sender_client_addr) + session = self._active_session(request.session_id, connection) if not isinstance(session, WebRTCSession): return _status(request.session_id, session) hook = self._delegate.handle_update_session( diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index d72313dd..2ff68928 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -4,12 +4,14 @@ a temperature measuring or a device status. """ -from collections.abc import Callable +from collections.abc import Awaitable, Callable import inspect import logging from typing import TYPE_CHECKING, Any, TypedDict from uuid import UUID +import warnings +from .connection import HAPConnectionHandle from .const import ( HAP_PERMISSION_READ, HAP_REPR_DESC, @@ -21,6 +23,8 @@ HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) +from .context import Context +from .delegates import CharacteristicDelegate, CharReadContext, CharWriteContext from .util import hap_type_to_uuid, uuid_to_hap_type if TYPE_CHECKING: @@ -30,22 +34,6 @@ logger = logging.getLogger(__name__) -def _setter_wants_client_addr(setter: Callable[..., Any]) -> bool: - """Whether ``setter`` opts in to receiving the sender's client address. - - A setter opts in by declaring a parameter literally named - ``sender_client_addr`` (used e.g. for HDS transport setup that needs the HAP - session). Every other setter - including the common two-argument - default-value closures ``lambda value, option=option: ...`` - is called with - the value alone, unchanged. - """ - try: - parameters = inspect.signature(setter).parameters - except (TypeError, ValueError): - return False - return "sender_client_addr" in parameters - - # ### HAP Format ### # A characteristic value as HAP JSON carries it. HAPValue = bool | int | float | str | None @@ -162,6 +150,47 @@ def _validate_properties(properties: dict[str, Any]) -> None: raise ValueError(f"{HAP_REPR_MAX_LEN} may not exceed {ABSOLUTE_MAX_LENGTH}") +class _LegacyCallbackDelegateWrapper(CharacteristicDelegate): + """Adapt the legacy callbacks of a characteristic to the delegate interface. + + One wrapper is the delegate of a characteristic with legacy callbacks: + ``on_get`` answers what its ``getter_callback`` answers, ``on_set`` + applies its ``setter_callback``. A coroutine the setter returns is + awaited, like the legacy write path awaits a coroutine-function + setter. It is also the default delegate of a characteristic without + callbacks: both ``None``, it answers the reads with the stored value + and applies nothing on writes. + """ + + __slots__ = ("characteristic", "getter_callback", "setter_callback") + + def __init__( + self, + *, + characteristic: "Characteristic", + getter_callback: Callable[[], Any] | None = None, + setter_callback: Callable[..., Any] | None = None, + ) -> None: + self.characteristic = characteristic + self.getter_callback = getter_callback + self.setter_callback = setter_callback + + async def on_get(self, context: CharReadContext) -> Any: + if self.getter_callback is not None: + return self.getter_callback() + return self.characteristic.value + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + if self.setter_callback is None: + # Without a setter there is nothing to apply and answer - the + # unoverridden base method does the same. + return None + result = self.setter_callback(value) + if inspect.iscoroutine(result): + result = await result + return result + + class Characteristic: """Represents a HAP characteristic, the smallest unit of the smart home. @@ -184,8 +213,7 @@ class Characteristic: "_properties", "type_id", "_value", - "getter_callback", - "setter_callback", + "_delegate", "service", "_uuid_str", "_loader_display_name", @@ -194,8 +222,6 @@ class Characteristic: "_to_hap_cache_with_value", "_to_hap_cache", "_always_null", - "_setter_addr_cache", - "_setter_addr_cache_for", "read_back_response", ) @@ -236,17 +262,14 @@ def __init__( self._properties: dict[str, Any] = properties self.type_id = type_id self._value = self._get_default_value() - self.getter_callback: Callable[[], Any] | None = None - # Setters may take just the value or (value, sender_client_addr); see - # ``_setter_wants_addr``. The return value is sent back as the write - # response when the characteristic has the "wr" permission and the - # controller asked for one. A setter may also be a coroutine function; - # a controller's write is answered once it is done. - self.setter_callback: Callable[..., Any] | None = None - # Cache of whether ``setter_callback`` opts into the client address, - # recomputed only when the setter object itself changes. - self._setter_addr_cache: bool = False - self._setter_addr_cache_for: Callable[..., Any] | None = None + # The delegate of the reads, writes and subscriptions of this + # characteristic, see ``CharacteristicDelegate``. Never ``None``: + # without an assigned delegate this is the default one, the legacy + # callback wrapper without callbacks, see + # ``_LegacyCallbackDelegateWrapper``. + self._delegate: CharacteristicDelegate = _LegacyCallbackDelegateWrapper( + characteristic=self + ) self.service: Service | None = None self.unique_id = unique_id self._uuid_str = uuid_to_hap_type(type_id) @@ -269,6 +292,134 @@ def display_name(self, value: str) -> None: self._display_name = value self._clear_cache() + @property + def delegate(self) -> CharacteristicDelegate: + """The characteristic's delegate, never ``None``. + + Without an assigned delegate this is the default one: the legacy + callback wrapper without callbacks, which answers the reads with + the stored value and applies nothing on writes. A real delegate + takes over the reads of the characteristic, see + :class:`~pyhap.delegates.CharacteristicDelegate`. + """ + return self._delegate + + @delegate.setter + def delegate(self, delegate: CharacteristicDelegate | None) -> None: + """Assign the delegate; ``None`` resets to the default one.""" + legacy = self._legacy + if legacy is not None and ( + legacy.getter_callback is not None or legacy.setter_callback is not None + ): + raise ValueError( + f"{self._display_name} has a legacy callback, remove it before" + " assigning a delegate" + ) + self._delegate = ( + _LegacyCallbackDelegateWrapper(characteristic=self) + if delegate is None + else delegate + ) + + @property + def _legacy(self) -> _LegacyCallbackDelegateWrapper | None: + """The legacy callback wrapper, or ``None`` when a delegate is assigned. + + The one place that tells the two interfaces apart: the wrapper is + the delegate of a characteristic without an assigned one. + """ + delegate = self._delegate + if isinstance(delegate, _LegacyCallbackDelegateWrapper): + return delegate + return None + + @property + def getter_callback(self) -> Callable[[], Any] | None: + """The legacy getter, called with nothing on every read of the value. + + Deprecated: a delegate's :meth:`~pyhap.delegates.CharacteristicDelegate.on_get` + answers the reads instead. + """ + legacy = self._legacy + if legacy is not None: + return legacy.getter_callback + raise ValueError( + f"{self._display_name} has a CharacteristicDelegate instead of a" + " legacy getter_callback" + ) + + @getter_callback.setter + def getter_callback(self, callback: Callable[[], Any] | None) -> None: + """Assign the legacy getter. ``None`` removes it. + + Deprecated: a delegate's :meth:`~pyhap.delegates.CharacteristicDelegate.on_get` + answers the reads instead. + """ + self._assign_legacy_callback("getter_callback", callback) + + @property + def setter_callback(self) -> Callable[..., Any] | None: + """The legacy setter, called with the value on a controller's write. + + The return value is sent back as the write response when the + characteristic has the "wr" permission and the controller asked + for one. May also be a coroutine function; a controller's write is + answered once it is done. What a callback needs to know about the + request comes through a delegate instead, see + :class:`~pyhap.delegates.CharacteristicDelegate`. + """ + legacy = self._legacy + if legacy is not None: + return legacy.setter_callback + raise ValueError( + f"{self._display_name} has a CharacteristicDelegate instead of a" + " legacy setter_callback" + ) + + @setter_callback.setter + def setter_callback(self, callback: Callable[..., Any] | None) -> None: + """Assign the legacy setter; ``None`` removes it. + + Deprecated: what a callback needs to know about the request comes + through a delegate instead, see + :class:`~pyhap.delegates.CharacteristicDelegate`. + """ + self._assign_legacy_callback("setter_callback", callback) + + def _assign_legacy_callback( + self, + name: str, + callback: Callable[..., Any] | None, + *, + warn_stacklevel: int = 3, + ) -> None: + """Store a legacy callback, wrapping it into the delegate interface. + + A characteristic without an assigned delegate has the default noop + one; assigning a legacy callback wraps it. A characteristic with + an assigned delegate takes no legacy callback - the driver would + never run one - so assigning one raises ``ValueError``. + + Both the property setters and + :meth:`~pyhap.service.Service.configure_char` call this one frame + below themselves, so ``warn_stacklevel`` names the assigning user + code. + """ + if callback is not None: + warnings.warn( + f"The legacy {name} is deprecated, use a CharacteristicDelegate" + " instead.", + DeprecationWarning, + stacklevel=warn_stacklevel, + ) + legacy = self._legacy + if legacy is None: + raise ValueError( + f"{self._display_name} has a delegate, remove it before" + " assigning a legacy callback" + ) + setattr(legacy, name, callback) + @property def value(self) -> Any: """Return the value of the characteristic.""" @@ -311,10 +462,16 @@ def _get_default_value(self) -> Any: def get_value(self) -> Any: """This is to allow for calling `getter_callback` + The legacy read: runs ``getter_callback`` when one is set and stores + its answer. A delegate-backed characteristic answers its stored value + here — the driver's read path calls its ``on_get`` instead, see + :class:`~pyhap.delegates.CharacteristicDelegate`. + :return: Current Characteristic Value """ - if self.getter_callback: - self.value = self.to_valid_value(value=self.getter_callback()) + legacy = self._legacy + if legacy is not None and (getter := legacy.getter_callback) is not None: + self.value = self.to_valid_value(value=getter()) return self._value def valid_value_or_raise(self, value: Any) -> None: @@ -438,7 +595,7 @@ def set_value(self, value: Any, should_notify: bool = True) -> None: def client_update_value( self, value: Any, - sender_client_addr: tuple[str, int] | None = None, + connection: HAPConnectionHandle | None = None, *, notify: bool = True, defer_notify: bool = False, @@ -446,12 +603,18 @@ def client_update_value( """Called from broker for value change in Home app. Change self.value to value and call callback. Returns what the callback - returned. With ``notify`` False, subscribers are not told about the - written value, e.g. for a request that only the writing connection may - read back. With ``defer_notify``, a coroutine the callback returns is - for the caller to await, and the caller then calls - :meth:`client_update_finished`, so subscribers only learn the value - once the setter succeeded. + returned. This is the one-call form of a client update - a + controller's write recorded on the characteristic: the driver's + delegate write path splits it into storing the value, running the + delegate's ``on_set`` and finishing with :meth:`client_update_finished`. + ``connection`` is the identity of the connection the write + came over, see :class:`~pyhap.connection.HAPConnectionHandle`; that + connection is not told its own write back. With ``notify`` False, + subscribers are not told about the written value, e.g. for a request + that only the writing connection may read back. With ``defer_notify``, + a coroutine the callback returns is for the caller to await, and the + caller then calls :meth:`client_update_finished`, so subscribers only + learn the value once the setter succeeded. """ original_value = value if not self._always_null or original_value is not None: @@ -463,57 +626,122 @@ def client_update_value( self._display_name, value, original_value, - sender_client_addr, + connection, ) previous_value = self._value self.value = value response = None - if self.setter_callback: - if self._setter_wants_addr(): - response = self.setter_callback(value, sender_client_addr) - else: - response = self.setter_callback(value) + # The legacy setter, wrapped into the delegate interface. Reading + # ``setter_callback`` would raise for a characteristic without one. + legacy = self._legacy + if legacy is not None and (setter := legacy.setter_callback) is not None: + response = setter(value) if not (defer_notify and inspect.iscoroutine(response)): - self.client_update_finished( - previous_value, sender_client_addr, notify=notify - ) + self.client_update_finished(previous_value, connection, notify=notify) return response + def _store_client_update(self, value: Any) -> Any: + """Store a client update without running any callback. + + The store step of a client update - a controller's write recorded + on the characteristic, see :meth:`client_update_value` and + :meth:`client_update_finished`: validate and store the value like + :meth:`client_update_value` does, tell no subscriber and call no + callback. The driver's delegate write path runs the + characteristic's ``on_set`` after this and notifies through + :meth:`client_update_finished` once it succeeded, or restores + this value if the write is refused. Returns the value's previous + state. + """ + if not self._always_null or value is not None: + value = self.to_valid_value(value) + if not self.allow_invalid_client_values: + self.valid_value_or_raise(value) + previous_value = self._value + self.value = value + return previous_value + def client_update_finished( self, previous_value: Any, - sender_client_addr: tuple[str, int] | None, + connection: HAPConnectionHandle | None, *, notify: bool = True, ) -> None: - """Finish a client's write, e.g. after awaiting its coroutine setter. + """Finish a client update, e.g. after awaiting its coroutine setter. - Tells subscribers about the new value if it differs from - ``previous_value``, see :meth:`client_update_value`. + The notify step of a client update: tells subscribers about the + new value if it differs from ``previous_value``, the value stored + before the update, see :meth:`client_update_value`. The connection + ``connection`` the write came over is not told its own write back. """ if notify and self._value != previous_value: - self.notify(sender_client_addr) + self.notify(connection) if self._always_null: self.value = None - def _setter_wants_addr(self) -> bool: - """Whether the current setter opts into the sender's client address. + async def dispatch_get(self, context: Context) -> Any: + """Answer a read of this characteristic through its delegate. - Signature introspection is done once per setter object and cached, so - the common write path does not call :func:`inspect.signature` on every - client write. + Called by the driver's read path with the request's base + :class:`~pyhap.context.Context`: builds this characteristic's + :class:`~pyhap.context.CharReadContext` and awaits the delegate's + ``on_get``. Assign a :class:`~pyhap.delegates.CharacteristicDelegate` + instead of overriding this method - an override would silently + take the delegate's place. """ - setter = self.setter_callback - if setter is not self._setter_addr_cache_for: - self._setter_addr_cache_for = setter - self._setter_addr_cache = setter is not None and _setter_wants_client_addr( - setter - ) - return self._setter_addr_cache + return await self.delegate.on_get( + CharReadContext.of(context, characteristic=self) + ) - def notify(self, sender_client_addr: tuple[str, int] | None = None) -> None: + async def dispatch_set( + self, value: Any, context: Context, *, is_admin: bool + ) -> Any: + """Apply a controller's write of ``value`` through its delegate. + + Called by the driver's write path with the request's base + :class:`~pyhap.context.Context`: builds this characteristic's + :class:`~pyhap.context.CharWriteContext` and awaits the delegate's + ``on_set``. Assign a :class:`~pyhap.delegates.CharacteristicDelegate` + instead of overriding this method - an override would silently + take the delegate's place. + + :param value: The validated value the write stored. + :param context: The base context of the write request. + :param is_admin: Whether the writing controller has admin privileges. + """ + return await self.delegate.on_set( + value, + CharWriteContext.of(context, characteristic=self, is_admin=is_admin), + ) + + def subscription_hook( + self, subscribe: bool, context: Context + ) -> tuple[Callable[[CharReadContext], Awaitable[None]], tuple[CharReadContext]]: + """The delegate's (un)subscribe hook of this characteristic, with its context. + + Called by the driver when a controller (un)subscribes. Returns the + hook and its args rather than a started coroutine, so a hook whose + job never runs does not warn about a never-awaited coroutine. + Assign a :class:`~pyhap.delegates.CharacteristicDelegate` instead of + overriding this method. + + :param subscribe: Whether the controller subscribed or unsubscribed. + :param context: The base context of the request or connection close + that caused the transition; the hook itself runs without a + deadline. + """ + char_context = CharReadContext.of(context, characteristic=self) + if subscribe: + return self.delegate.on_subscribe, (char_context,) + return self.delegate.on_unsubscribe, (char_context,) + + def notify(self, connection: HAPConnectionHandle | None = None) -> None: """Notify clients about a value change. Sends the value. + The connection ``connection`` the change came over, if any, is not + told its own write back. + .. seealso:: accessory.publish .. seealso:: accessory_driver.publish """ @@ -522,7 +750,7 @@ def notify(self, sender_client_addr: tuple[str, int] | None = None) -> None: if TYPE_CHECKING: assert self.broker is not None # noqa: S101 immediate = self.type_id in IMMEDIATE_NOTIFY - self.broker.publish(self.value, self, sender_client_addr, immediate) + self.broker.publish(self.value, self, connection, immediate) def to_HAP(self, include_value: bool = True) -> dict[str, Any]: """Create a HAP representation of this Characteristic. @@ -533,7 +761,7 @@ def to_HAP(self, include_value: bool = True) -> dict[str, Any]: :rtype: dict """ if include_value: - if self._to_hap_cache_with_value is not None and not self.getter_callback: + if self._to_hap_cache_with_value is not None and self._reads_stored(): return self._to_hap_cache_with_value elif self._to_hap_cache is not None: return self._to_hap_cache @@ -571,15 +799,30 @@ def to_HAP(self, include_value: bool = True) -> dict[str, Any]: hap_rep[HAP_REPR_MAX_LEN] = max_length if include_value and HAP_PERMISSION_READ in permissions: - hap_rep[HAP_REPR_VALUE] = self.get_value() + # The stored value: a fresh answer comes from the read path, + # the delegate's ``on_get`` - which also isolates a failing + # read to its own characteristic, see the driver. + hap_rep[HAP_REPR_VALUE] = self.value if not include_value: self._to_hap_cache = hap_rep - elif not self.getter_callback: - # Only cache if there is no getter_callback + elif self._reads_stored(): + # Only cache if nothing answers reads dynamically: an + # ``on_get`` or a legacy getter may answer something else + # than the stored value. self._to_hap_cache_with_value = hap_rep return hap_rep + def _reads_stored(self) -> bool: + """Whether reads answer the stored value, so it can be cached. + + A delegate's ``on_get`` or a legacy getter may answer something + else; the default delegate - the callback wrapper without a + getter - answers the stored value. + """ + legacy = self._legacy + return legacy is not None and legacy.getter_callback is None + @classmethod def from_dict( cls, name: str, json_dict: dict[str, Any], from_loader: bool = False diff --git a/pyhap/connection.py b/pyhap/connection.py new file mode 100644 index 00000000..4cf1e848 --- /dev/null +++ b/pyhap/connection.py @@ -0,0 +1,74 @@ +"""The identity of a controller connection.""" + +from __future__ import annotations + + +class HAPConnectionHandle: + """The stable identity of one controller connection. + + Contexts pass this to delegate and lifecycle calls, so a callback can + tie what it does to the connection that caused it, e.g. a camera may + let only the connection that set a session up control it. Beyond + ``client_addr`` it is opaque on purpose: the address of a connection + is unique only while it lives, a later connection may reuse the same + ``(address, port)`` pair, so equality and hashing are by the + connection's identity - two handles are equal only for the same + connection. Anything kept per connection, a write response, a camera + session, cannot leak to a connection that reused the address of a + closed one. + + The driver's per-connection state - event subscriptions, prepared + writes, write responses and the server's connections - is keyed by + the handle, so nothing of a closed connection reaches a later one, + and an answer that arrives only after its connection closed is + dropped instead of kept. A direct call without a connection acts as + a virtual handle of its client address, see + ``AccessoryDriver._connection_of``. + """ + + __slots__ = ("_client_addr", "_generation") + + def __init__(self, client_addr: tuple[str, int] | None, generation: int) -> None: + """Initialise with the connection's address and its generation. + + :param client_addr: The connection's ``(address, port)``, or + ``None`` for a call without a connection, e.g. a + programmatic write through the legacy API. A controller's + request always has one. + :param generation: A driver-internal number that differs between + two connections with the same address; part of what makes + the handle unique, but not part of its interface. + """ + self._client_addr = client_addr + self._generation = generation + + @property + def client_addr(self) -> tuple[str, int] | None: + """The connection's ``(address, port)``, ``None`` without one.""" + return self._client_addr + + def __eq__(self, other: object) -> bool: + """Equal only for the same connection, never for a reused address.""" + if not isinstance(other, HAPConnectionHandle): + return NotImplemented + return self._key == other._key + + def __ne__(self, other: object) -> bool: + """Not equal for anything but the same connection.""" + result = self.__eq__(other) + if result is NotImplemented: + return NotImplemented + return not result + + @property + def _key(self) -> tuple[tuple[str, int] | None, int]: + """What identifies the handle, also for hashing.""" + return (self._client_addr, self._generation) + + def __hash__(self) -> int: + """Hash by the same key :meth:`__eq__` compares.""" + return hash(self._key) + + def __repr__(self) -> str: + """Show the connection's address and identity.""" + return f"{self.__class__.__name__}({self._client_addr!r}, {self._generation})" diff --git a/pyhap/context.py b/pyhap/context.py new file mode 100644 index 00000000..debb4dbc --- /dev/null +++ b/pyhap/context.py @@ -0,0 +1,137 @@ +"""The contexts passed to delegate and lifecycle calls.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING +from uuid import UUID + +from .connection import HAPConnectionHandle + +if TYPE_CHECKING: + from .characteristic import Characteristic + from .service import Service + + +@dataclass(frozen=True) +class Context: + """What a delegate call knows about the controller it serves. + + Contexts are the input side of the callback interface: new input data + arrives as new fields of this class, so a callback's signature never + changes - watch this class instead of callback parameters. Instances + are frozen; a callback must not try to change one. + + :ivar client_addr: The controller's ``(address, port)``, ``None`` + without a connection. + :ivar client_uuid: The identity of the paired controller, ``None`` + before pair-verify completes. + :ivar connection: The stable identity of the connection, see + :class:`~pyhap.connection.HAPConnectionHandle`. + :ivar deadline: Monotonic time; the driver answers ``-70408`` for a + callback that is not done by it. + + Contexts identify their target by the object itself, a + :class:`~pyhap.characteristic.Characteristic` or a + :class:`~pyhap.service.Service`, never by an id: iids are the wire + protocol's identity, assigned by the driver at publish time and + meaningless outside a running driver, while a delegate is wired at + construction time, before iids exist. The object is both the + identity for dispatch and the handle to what a callback needs - + display name, stored value, properties, the owning service. + """ + + client_addr: tuple[str, int] | None + client_uuid: UUID | None + connection: HAPConnectionHandle + deadline: float + + +@dataclass(frozen=True) +class CharReadContext(Context): + """The context of a read, e.g. of ``on_get``. + + :ivar characteristic: The characteristic being read. + """ + + characteristic: Characteristic + + @classmethod + def of(cls, base: Context, *, characteristic: Characteristic) -> CharReadContext: + """The read context of ``characteristic``, sharing a request's ``base``. + + :param base: The base :class:`Context` of the request the read + belongs to; its connection, client and deadline carry over. + :param characteristic: The characteristic being read. + """ + return cls( + client_addr=base.client_addr, + client_uuid=base.client_uuid, + connection=base.connection, + deadline=base.deadline, + characteristic=characteristic, + ) + + +@dataclass(frozen=True) +class CharWriteContext(Context): + """The context of a write of one characteristic, e.g. of ``on_set``. + + :ivar characteristic: The characteristic being written. + :ivar is_admin: Whether the writing controller has admin privileges. + """ + + characteristic: Characteristic + is_admin: bool + + @classmethod + def of( + cls, base: Context, *, characteristic: Characteristic, is_admin: bool + ) -> CharWriteContext: + """The write context of ``characteristic``, sharing a request's ``base``. + + :param base: The base :class:`Context` of the request the write + belongs to; its connection, client and deadline carry over. + :param characteristic: The characteristic being written. + :param is_admin: Whether the writing controller has admin privileges. + """ + return cls( + client_addr=base.client_addr, + client_uuid=base.client_uuid, + connection=base.connection, + deadline=base.deadline, + characteristic=characteristic, + is_admin=is_admin, + ) + + +@dataclass(frozen=True) +class ServiceWriteContext(Context): + """The context of a grouped write of a service, its ``on_set`` gate. + + :ivar service: The service whose characteristics are written. + :ivar is_admin: Whether the writing controller has admin privileges. + """ + + service: Service + is_admin: bool + + @classmethod + def of( + cls, base: Context, *, service: Service, is_admin: bool + ) -> ServiceWriteContext: + """The grouped-write context of ``service``, sharing a request's ``base``. + + :param base: The base :class:`Context` of the request the write + belongs to; its connection, client and deadline carry over. + :param service: The service whose characteristics are written. + :param is_admin: Whether the writing controller has admin privileges. + """ + return cls( + client_addr=base.client_addr, + client_uuid=base.client_uuid, + connection=base.connection, + deadline=base.deadline, + service=service, + is_admin=is_admin, + ) diff --git a/pyhap/delegates.py b/pyhap/delegates.py new file mode 100644 index 00000000..23584f47 --- /dev/null +++ b/pyhap/delegates.py @@ -0,0 +1,124 @@ +"""The delegate interfaces of the callback interface. + +A delegate is an object a characteristic or service is wired up with, +:class:`CharacteristicDelegate` for one characteristic or several shared +ones, :class:`ServiceDelegate` for a whole service. Unlike the legacy +``setter_callback``/``getter_callback`` attributes it replaces over time, +a delegate receives a context (:class:`~pyhap.context.Context`) that +carries what a callback needs to know about the request - and grows new +fields instead of new callback signatures. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +from .context import CharReadContext, CharWriteContext, ServiceWriteContext + +if TYPE_CHECKING: + from .characteristic import Characteristic + + +class CharacteristicDelegate: + """Delegate of a characteristic's reads, writes and subscriptions. + + Subclass and override what you need; the noop defaults do nothing. + One instance may serve many characteristics: the context carries + ``characteristic`` and identifies which one a call is about. + + Every method is a coroutine function BY DESIGN. The driver awaits + every call - there is no sync/async detection on this path - and + enforces the context's deadline: a call that is not done by it is + cancelled and answers ``-70408``. Heavy synchronous work still + blocks the loop and the request; keep such work in a task or an + executor and await it. + + An unoverridden ``on_set``, ``on_subscribe`` or ``on_unsubscribe`` + does nothing. An unoverridden ``on_get`` raises, see its docstring. + An overridden method that returns ``None`` is an answer - e.g. a + getter that answers the null value of a Programmable Switch Event. + A callback that fails answers with its status instead of the generic + ``-70402`` when it raises :class:`~pyhap.errors.HapStatusError`. + """ + + async def on_get(self, context: CharReadContext) -> Any: + """Answer a read of the characteristic with its value. + + There is no default answer: the base method raises + ``NotImplementedError``, so a delegate of a readable + characteristic implements this or its reads fail - a delegate + takes over the reads of its characteristics. The override runs + under the context's deadline and answers the read; return the + value, which must fit the characteristic's format like any + other value, or ``None`` for a null one. Like a legacy getter's + answer, the value is stored on the characteristic; subscribers + are not told, a read is not a change. A read that misses the + deadline, fails or raises + :class:`~pyhap.errors.HapStatusError` answers its status + instead of a value. + """ + raise NotImplementedError("on_get is not implemented") + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + """Apply a controller's write of ``value``. + + Runs after the write passed its service-level pre-checks, under + deadline. The value is already stored and subscribers are told + once this call is done. A return value is the write response for + a characteristic with the ``wr`` permission, else it is dropped; + raise :class:`~pyhap.errors.HapStatusError` to answer a status. + A write that raises, fails or misses its deadline restores the + characteristic's previous value and tells subscribers nothing. + """ + + async def on_subscribe(self, context: CharReadContext) -> None: + """A controller subscribed to the characteristic's events. + + Use this to start work only while someone listens, e.g. polling + a sensor that costs battery. The hook runs isolated, without a + deadline: the request never waits for it, its failure is only + logged, and the subscription itself has already registered. + + The hook runs on the change: subscribing a controller that is + already subscribed, or unsubscribing one that is not, runs + nothing. + """ + + async def on_unsubscribe(self, context: CharReadContext) -> None: + """A controller unsubscribed from the characteristic's events. + + This also runs when its connection closes while subscribed. The + hook runs isolated, without a deadline: the request or the + connection close never waits for it, its failure is only logged, + and the subscription itself is already gone. + """ + + +class ServiceDelegate: + """Delegate of a whole service. + + The service's ``on_set`` is the pre-check of its grouped writes: a + request + that writes several characteristics of the service runs it before + any per-characteristic ``on_set``, with every value of the request - + so a thermostat sees target mode and target temperature together. + Raise :class:`~pyhap.errors.HapStatusError` to refuse the writes + of the service before anything is applied: their values are + restored, subscribers are told nothing, and their + per-characteristic ``on_set`` calls do not run. Writes of other + services in the same request are not affected. + + One instance may serve many services, like a characteristic + delegate may serve many characteristics: the context carries + ``service`` and identifies which one a call is about. + """ + + async def on_set( + self, values: Mapping[Characteristic, Any], context: ServiceWriteContext + ) -> None: + """Veto or accept a grouped write before it is applied. + + :param values: Every written value of the request, by + :class:`~pyhap.characteristic.Characteristic`. + """ diff --git a/pyhap/errors.py b/pyhap/errors.py new file mode 100644 index 00000000..0b3ba480 --- /dev/null +++ b/pyhap/errors.py @@ -0,0 +1,74 @@ +"""Errors raised by accessory callbacks to answer a HAP request.""" + +from .const import HAP_SERVER_STATUS + +# The statuses a callback may answer with, as HAP status codes. The rest are +# reserved for the accessory driver: privileges and read-only, write-only and +# notification permissions are enforced before any callback runs, and a timed +# out callback is answered by the driver's watchdog. Constructing a +# HapStatusError with anything else fails fast with a ValueError, so a wrong +# status is caught at its source instead of silently altering a request. +CALLBACK_STATUSES = frozenset( + { + HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE, + HAP_SERVER_STATUS.RESOURCE_BUSY, + HAP_SERVER_STATUS.OUT_OF_RESOURCE, + HAP_SERVER_STATUS.RESOURCE_DOES_NOT_EXIST, + HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST, + HAP_SERVER_STATUS.INSUFFICIENT_AUTHORIZATION, + } +) + + +class HapStatusError(Exception): + """Raise from a callback to answer its request with a HAP status. + + A characteristic's setter or getter callback may raise this instead of + failing generically, and the controller receives the status for that + characteristic in the HAP response - so the Home app can tell a refusal + apart from a communication failure. Every other exception of a callback + keeps answering ``-70402`` (service communication failure). + + For example, the setter of a lock whose motor is busy:: + + from pyhap.const import HAP_SERVER_STATUS + from pyhap.errors import HapStatusError + + def set_lock_target_state(value): + if not lock.is_ready(): + raise HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + lock.set_state(value) + + A callback may answer with one of these statuses: + + * ``-70402`` service communication failure - the default for any other + exception, raise it only to be explicit. + * ``-70403`` resource busy - the device refuses the request, try again. + * ``-70407`` out of resource - e.g. no free streaming session. + * ``-70409`` resource does not exist - e.g. an unknown session id. + * ``-70410`` invalid value in a request - a value that passed the + format checks but is semantically wrong. + * ``-70411`` insufficient authorization - the accessory refuses this + controller. + + The other HAP statuses are reserved for the accessory driver and cannot + be raised: privileges and permissions are enforced before a callback + runs, and a callback that is too slow is answered by the driver itself. + + :param status: One of the statuses above, as a + :class:`~pyhap.const.HAP_SERVER_STATUS` value. + :raises ValueError: If ``status`` is reserved for the driver or unknown. + """ + + __slots__ = ("status",) + + def __init__(self, status: int) -> None: + """Initialise with the HAP status to answer with.""" + if status not in CALLBACK_STATUSES: + raise ValueError( + f"HAP status {status} is reserved for the accessory driver or" + " unknown; a callback may answer with one of:" + f" {', '.join(str(code) for code in sorted(CALLBACK_STATUSES))}" + ) + super().__init__(f"HAP status {status}") + self.status = status diff --git a/pyhap/hap_handler.py b/pyhap/hap_handler.py index 736f0227..2f956578 100644 --- a/pyhap/hap_handler.py +++ b/pyhap/hap_handler.py @@ -6,7 +6,6 @@ import asyncio from collections.abc import Awaitable from http import HTTPStatus -import inspect import logging from typing import TYPE_CHECKING, Any, cast from urllib.parse import ParseResult, parse_qs, urlparse @@ -20,6 +19,7 @@ from pyhap import tlv from pyhap.accessory import Bridge +from pyhap.connection import HAPConnectionHandle from pyhap.const import ( HAP_PERMISSIONS, HAP_REPR_CHARS, @@ -145,14 +145,23 @@ def __init__( self, accessory_handler: "AccessoryDriver", client_address: tuple[str, int] | str, + connection: HAPConnectionHandle | None = None, ) -> None: """@param accessory_handler: An object that controls an accessory's state. @type accessory_handler: AccessoryDriver + + :param connection: The connection the requests of this handler come + over, see :class:`~pyhap.connection.HAPConnectionHandle`. """ self.accessory_handler: AccessoryDriver = accessory_handler self.state: State = self.accessory_handler.state self.enc_context: dict[str, Any] | None = None self.client_address = client_address + # Without the connection of its protocol, a handler acts as the + # virtual connection of its address, like a direct call does. + self.connection = connection or self.accessory_handler._connection_of( + cast("tuple[str, int] | None", client_address) + ) self.is_encrypted = False self.client_uuid: uuid.UUID | None = None @@ -651,16 +660,32 @@ def _pair_verify_two(self, tlv_objects: dict[bytes, bytes]) -> None: self.is_encrypted = True self.client_uuid = client_uuid del self.enc_context + self.accessory_handler.client_verified( + cast("tuple[str, int] | None", self.client_address), client_uuid + ) def handle_accessories(self) -> None: """Handles a client request to get the accessories.""" if not self.is_encrypted: raise UnprivilegedRequestException - hap_rep = self.accessory_handler.get_accessories() + result = self.accessory_handler._get_accessories_for_controller( + cast("tuple[str, int]", self.client_address), + RESPONSE_TIMEOUT, + client_uuid=self.client_uuid, + connection=self.connection, + ) self.send_response(HTTPStatus.OK) self.send_header("Content-Type", self.JSON_RESPONSE_TYPE) - self.end_response(to_hap_json(hap_rep)) + # The reads run under the request deadline; answer once they are + # done. The driver times out slow getters itself. + assert self.response is not None # noqa: S101 + self.response.task = asyncio.ensure_future(self._accessories_body(result)) + + async def _accessories_body(self, result: Awaitable[dict[str, Any]]) -> bytes: + """Wait for the pending reads, then answer the accessories.""" + body: bytes = to_hap_json(await result) + return body def handle_get_characteristics(self) -> None: """Handles a client request to get certain characteristics.""" @@ -670,23 +695,47 @@ def handle_get_characteristics(self) -> None: # Check that char exists and ... assert self.parsed_url is not None # noqa: S101 params = parse_qs(self.parsed_url.query) - response = self.accessory_handler.get_characteristics( - params["id"][0].split(","), cast("tuple[str, int]", self.client_address) + result = self.accessory_handler._get_characteristics_for_controller( + params["id"][0].split(","), + cast("tuple[str, int]", self.client_address), + RESPONSE_TIMEOUT, + client_uuid=self.client_uuid, + connection=self.connection, + ) + assert self.response is not None # noqa: S101 + # The reads run under the request deadline; answer once they are + # done. The driver times out slow getters itself. + self.response.task = asyncio.ensure_future( + self._get_characteristics_body(self.response, result) ) - chars = response[HAP_REPR_CHARS] + + def _fill_get_characteristics_response( + self, response: HAPResponse, result: dict[str, Any] + ) -> None: + """Fill in the response to a characteristics read.""" + chars = result[HAP_REPR_CHARS] had_failure = any( - result[HAP_REPR_STATUS] != HAP_SERVER_STATUS.SUCCESS for result in chars + entry[HAP_REPR_STATUS] != HAP_SERVER_STATUS.SUCCESS for entry in chars ) if had_failure: - self.send_response(HTTPStatus.MULTI_STATUS) + response.status_code = HTTPStatus.MULTI_STATUS.value + response.reason = HTTPStatus.MULTI_STATUS.phrase else: - self.send_response(HTTPStatus.OK) - for result in chars: - del result[HAP_REPR_STATUS] + response.status_code = HTTPStatus.OK.value + response.reason = HTTPStatus.OK.phrase + for entry in chars: + del entry[HAP_REPR_STATUS] - self.send_header("Content-Type", self.JSON_RESPONSE_TYPE) - self.end_response(to_hap_json(response)) + response.headers.append(("Content-Type", self.JSON_RESPONSE_TYPE)) + response.body = to_hap_json(result) + + async def _get_characteristics_body( + self, response: HAPResponse, result: Awaitable[dict[str, Any]] + ) -> bytes: + """Wait for the pending delegate reads, then fill in the read response.""" + self._fill_get_characteristics_response(response, await result) + return response.body def handle_set_characteristics(self) -> None: """Handles a client request to update certain characteristics.""" @@ -708,16 +757,15 @@ def handle_set_characteristics(self) -> None: cast("tuple[str, int]", self.client_address), RESPONSE_TIMEOUT, client_uuid=self.client_uuid, + connection=self.connection, ) assert self.response is not None # noqa: S101 - if inspect.isawaitable(result): - # A setter is still running, answer once it is done. The driver - # times out slow setters itself. - self.response.task = asyncio.ensure_future( - self._async_set_characteristics_body(self.response, result) - ) - return - self._fill_set_characteristics_response(self.response, result) + # The writes run under the request deadline - their pre-checks, + # then their setters; answer once they are done. The driver times + # out slow setters itself. + self.response.task = asyncio.ensure_future( + self._set_characteristics_body(self.response, result) + ) def _fill_set_characteristics_response( self, response: HAPResponse, result: dict[str, Any] | None @@ -732,7 +780,7 @@ def _fill_set_characteristics_response( response.headers.append(("Content-Type", self.JSON_RESPONSE_TYPE)) response.body = to_hap_json(result) - async def _async_set_characteristics_body( + async def _set_characteristics_body( self, response: HAPResponse, result: Awaitable[dict[str, Any] | None] ) -> bytes: """Wait for the pending setters, then fill in the write response.""" @@ -753,7 +801,9 @@ def handle_prepare(self) -> None: logger.debug("%s: prepare content: %s", self.client_address, request) response = self.accessory_handler.prepare( - request, cast("tuple[str, int]", self.client_address) + request, + cast("tuple[str, int]", self.client_address), + connection=self.connection, ) self.send_response(HTTPStatus.OK) self.send_header("Content-Type", self.JSON_RESPONSE_TYPE) diff --git a/pyhap/hap_protocol.py b/pyhap/hap_protocol.py index 75da13a1..a3a7d409 100644 --- a/pyhap/hap_protocol.py +++ b/pyhap/hap_protocol.py @@ -13,6 +13,7 @@ import h11 from pyhap.accessory import get_topic +from pyhap.connection import HAPConnectionHandle from pyhap.const import HAP_REPR_AID, HAP_REPR_IID from .hap_crypto import HAPCrypto, hap_hkdf @@ -54,7 +55,7 @@ class HAPServerProtocol(asyncio.Protocol): def __init__( self, loop: asyncio.AbstractEventLoop, - connections: dict[tuple[str, int], "HAPServerProtocol"], + connections: dict[HAPConnectionHandle, "HAPServerProtocol"], accessory_driver: "AccessoryDriver", ) -> None: self.loop = loop @@ -63,6 +64,7 @@ def __init__( self.accessory_driver = accessory_driver self.handler: HAPServerHandler | None = None self.peername: tuple[str, int] | None = None + self.connection_handle: HAPConnectionHandle | None = None self.transport: asyncio.Transport | None = None self.request: h11.Request | None = None @@ -103,7 +105,11 @@ def connection_lost(self, exc: BaseException | None) -> None: accessory.display_name, exc, ) - self.accessory_driver.connection_lost(self.peername) + self.accessory_driver.connection_lost( + self.peername, + connection=self.connection_handle, + client_uuid=self._handler.client_uuid, + ) self.close() def connection_made(self, transport: asyncio.BaseTransport) -> None: @@ -126,8 +132,17 @@ def connection_made(self, transport: asyncio.BaseTransport) -> None: transport.set_write_buffer_limits(high=HIGH_WRITE_BUFFER_SIZE) self.transport = transport self.peername = peername - self.connections[peername] = self - self.handler = HAPServerHandler(self.accessory_driver, peername) + # The stable identity of this connection, passed to the delegate + # calls made for its requests and keying the driver's per-connection + # state, see ``HAPConnectionHandle``. + self.connection_handle = HAPConnectionHandle( + peername, self.accessory_driver._next_connection_generation() + ) + self.connections[self.connection_handle] = self + self.handler = HAPServerHandler( + self.accessory_driver, peername, self.connection_handle + ) + self.accessory_driver.client_connected(peername) def derive_key(self, salt: bytes, info: bytes) -> bytes | None: """Derive a key from this connection's pair-verify session key. @@ -162,12 +177,10 @@ def write(self, data: bytes) -> None: def close(self) -> None: """Remove the connection and close the transport.""" - # A newer connection may already be registered under the same peername, - # and a connection without a peername must still be removed. - if self.connections.get(self.peername) is self: - # The identity check above ensures the key belongs to this protocol; - # peername is None only for transports without a peername. - del self.connections[self.peername] # ty: ignore[invalid-argument-type] + # The handle is unique per connection, so this never removes a newer + # connection that reuses this one's address. + if self.connection_handle is not None: + self.connections.pop(self.connection_handle, None) self._shared_key = None # Nobody is left to answer; stop work for a delayed response. Cancel # on the next iteration so a task created in this one has started and @@ -323,7 +336,7 @@ def _event_queue_with_active_subscriptions(self) -> list[dict[str, Any]]: return [ event for event in self._event_queue.values() - if self.peername + if self.connection_handle in topics.get(get_topic(event[HAP_REPR_AID], event[HAP_REPR_IID]), []) ] diff --git a/pyhap/hap_server.py b/pyhap/hap_server.py index e427a2ba..c7b7eaff 100644 --- a/pyhap/hap_server.py +++ b/pyhap/hap_server.py @@ -8,6 +8,7 @@ import time from typing import TYPE_CHECKING, Any +from .connection import HAPConnectionHandle from .hap_protocol import HAPServerProtocol from .util import callback @@ -40,7 +41,8 @@ def __init__( ) -> None: """Create a HAP Server.""" self._addr_port = addr_port - self.connections: dict[tuple[str, int], HAPServerProtocol] = {} + # The live connections, keyed by their identity, see HAPConnectionHandle. + self.connections: dict[HAPConnectionHandle, HAPServerProtocol] = {} self.accessory_handler = accessory_handler self.server: asyncio.Server | None = None self._connection_cleanup: asyncio.TimerHandle | None = None @@ -84,7 +86,7 @@ def async_stop(self) -> None: def push_event( self, data: dict[str, Any], - client_addr: tuple[str, int], + connection: HAPConnectionHandle, immediate: bool = False, ) -> bool: """Queue an event to the current connection with the provided data. @@ -92,15 +94,16 @@ def push_event( :param data: The characteristic changes :type data: dict - :param client_addr: A client (address, port) tuple to which to send the data. - :type client_addr: tuple + :param connection: The identity of the connection to send the data to, + see :class:`~pyhap.connection.HAPConnectionHandle`. + :type connection: HAPConnectionHandle :return: True if sending was successful, False otherwise. :rtype: bool """ - hap_server_protocol = self.connections.get(client_addr) + hap_server_protocol = self.connections.get(connection) if hap_server_protocol is None: - logger.debug("No socket for %s", client_addr) + logger.debug("No socket for %s", connection) return False hap_server_protocol.queue_event(data, immediate) return True diff --git a/pyhap/mdns.py b/pyhap/mdns.py new file mode 100644 index 00000000..c47993ac --- /dev/null +++ b/pyhap/mdns.py @@ -0,0 +1,117 @@ +"""The mDNS advertisement of an accessory. + +When the driver starts (and whenever the configuration version or pairing +state changes), it registers an :class:`AccessoryMDNSServiceInfo` with +zeroconf so HomeKit controllers can discover the accessory on the network. +The advertisement carries the accessory's identity - service name, host +name, port, addresses - and the TXT record data (``c#``, ``sf``, ``sh``, +...) that tells a controller whether to re-fetch the accessory's +description. +""" + +import base64 +import hashlib +import re +from typing import Any + +from zeroconf import ServiceInfo + +from pyhap.const import HAP_PROTOCOL_SHORT_VERSION +from pyhap.state import State + +HAP_SERVICE_TYPE = "_hap._tcp.local." +VALID_MDNS_REGEX = re.compile(r"[^A-Za-z0-9\-]+") +LEADING_TRAILING_SPACE_DASH = re.compile(r"^[ -]+|[ -]+$") +DASH_REGEX = re.compile(r"[-]+") + + +class AccessoryMDNSServiceInfo(ServiceInfo): + """A mDNS service info representation of an accessory. + + Carries the accessory's identity (name, host, MAC-based setup hash) and + the advertisement data HomeKit reads to decide whether to (re-)discover + and (re-)fetch the accessory: the configuration version ``c#``, the + pairing state ``sf`` and the setup hash ``sh``. + """ + + def __init__( + self, accessory: Any, state: State, zeroconf_server: Any = None + ) -> None: + """Build the service info from the accessory and its persisted state. + + :param accessory: The accessory to advertise. + :param state: The driver's state, source of the port, MAC, addresses + and advertisement flags. + :param zeroconf_server: The server (host) name to advertise. Defaults + to one derived from the accessory's display name and MAC. + """ + self.accessory = accessory + self.state: State = state + + adv_data = self._get_advert_data() + valid_name = self._valid_name() + short_mac = self.state.mac[-8:].replace(":", "") + # Append part of MAC address to prevent name conflicts + name = f"{valid_name} {short_mac}.{HAP_SERVICE_TYPE}" + valid_host_name = self._valid_host_name() + server = zeroconf_server or f"{valid_host_name}-{short_mac}.local." + super().__init__( + HAP_SERVICE_TYPE, + name=name, + server=server, + port=self.state.port, + weight=0, + priority=0, + properties=adv_data, + parsed_addresses=self.state.addresses, + ) + + def _valid_name(self) -> str: + """The accessory's display name, sanitized for the mDNS service name.""" + return re.sub( + LEADING_TRAILING_SPACE_DASH, + "", + re.sub(VALID_MDNS_REGEX, " ", self.accessory.display_name), + ) + + def _valid_host_name(self) -> str: + """The display name as a DNS-safe host name (no leading/trailing dashes).""" + return re.sub( + DASH_REGEX, + "-", + re.sub(VALID_MDNS_REGEX, " ", self.accessory.display_name) + .strip() + .replace(" ", "-") + .strip("-"), + ) + + def _setup_hash(self) -> str: + """The base64 setup hash advertised as ``sh``, from setup id and MAC.""" + setup_hash_material = self.state.setup_id + self.state.mac + temp_hash = hashlib.sha512() + temp_hash.update(setup_hash_material.encode()) + return base64.b64encode(temp_hash.digest()[:4]).decode() + + def _get_advert_data(self) -> dict[str, str]: + """Generate the mDNS TXT advertisement data from the accessory and state. + + The keys are the HAP advertisement fields: ``md`` (model name), + ``pv`` (protocol version), ``id`` (MAC), ``c#`` (configuration + version), ``s#`` (state), ``ff`` (flags), ``ci`` (category), ``sf`` + (discoverable while unpaired) and ``sh`` (setup hash). + """ + return { + "md": self._valid_name(), + "pv": HAP_PROTOCOL_SHORT_VERSION, + "id": self.state.mac, + # represents the 'configuration version' of an Accessory. + # Increasing this 'version number' signals iOS devices to + # re-fetch accessories data. + "c#": str(self.state.config_version), + "s#": "1", # 'accessory state' + "ff": "0", + "ci": str(self.accessory.category), + # 'sf == 1' means "discoverable by HomeKit iOS clients" + "sf": "0" if self.state.paired else "1", + "sh": self._setup_hash(), + } diff --git a/pyhap/service.py b/pyhap/service.py index d4171ef7..43628fc7 100644 --- a/pyhap/service.py +++ b/pyhap/service.py @@ -1,8 +1,11 @@ """This module implements the HAP Service.""" -from collections.abc import Callable +from collections.abc import Callable, Mapping +import inspect +import logging from typing import TYPE_CHECKING, Any from uuid import UUID +import warnings from pyhap.const import ( HAP_REPR_CHARS, @@ -13,12 +16,51 @@ ) from .characteristic import Characteristic +from .context import Context, ServiceWriteContext +from .delegates import CharacteristicDelegate, ServiceDelegate from .util import hap_type_to_uuid, uuid_to_hap_type if TYPE_CHECKING: from .accessory import Accessory from .loader import Loader +logger = logging.getLogger(__name__) + + +class _LegacySetterDelegateWrapper(ServiceDelegate): + """Adapt the legacy setter of a service to the delegate interface. + + One wrapper is the delegate of a service with a legacy setter: ``on_set`` + applies what its ``setter`` answers, with the values by characteristic + display name, like the legacy write path calls it. It is also the + default delegate of a service without one: ``setter`` ``None``, it + checks nothing. + """ + + __slots__ = ("service", "setter") + + def __init__( + self, + *, + service: "Service", + setter: Callable[[dict[str, Any]], None] | None = None, + ) -> None: + self.service = service + self.setter = setter + + async def on_set(self, values: Any, context: Any) -> None: + if self.setter is None: + return + result = self.setter( + {char.display_name: value for char, value in values.items()} + ) + if inspect.iscoroutine(result): + result.close() + logger.warning( + "%s: only characteristic setters may be coroutine functions", + self.service.display_name, + ) + class Service: """A representation of a HAP service. @@ -34,7 +76,7 @@ class Service: "type_id", "linked_services", "is_primary_service", - "setter_callback", + "_delegate", "unique_id", "_uuid_str", ) @@ -52,10 +94,114 @@ def __init__( self.display_name = display_name self.type_id = type_id self.is_primary_service = None - self.setter_callback: Callable[[Any], None] | None = None + # The delegate of the grouped writes of this service, see + # ``ServiceDelegate``. Never ``None``: without an assigned one + # this is the default one, the legacy setter wrapper without a + # setter, see ``_LegacySetterDelegateWrapper``. + self._delegate: ServiceDelegate = _LegacySetterDelegateWrapper(service=self) self.unique_id = unique_id self._uuid_str = uuid_to_hap_type(type_id) + @property + def delegate(self) -> ServiceDelegate: + """The service's delegate, never ``None``. + + Without an assigned delegate this is the default one: the legacy + setter wrapper without a setter, which checks nothing. A service + has either a delegate or the legacy ``setter_callback``, never + both: assigning one to a service that has the other raises + ``ValueError``. + """ + return self._delegate + + @delegate.setter + def delegate(self, delegate: ServiceDelegate | None) -> None: + """Assign the delegate; ``None`` resets to the default one.""" + legacy = self._legacy + if legacy is not None and legacy.setter is not None: + raise ValueError( + f"{self.display_name} has a legacy setter_callback, remove it" + " before assigning a delegate" + ) + self._delegate = ( + _LegacySetterDelegateWrapper(service=self) if delegate is None else delegate + ) + + @property + def _legacy(self) -> _LegacySetterDelegateWrapper | None: + """The legacy setter wrapper, or ``None`` when a delegate is assigned. + + The one place that tells the two interfaces apart: the wrapper is + the delegate of a service without an assigned one. + """ + delegate = self._delegate + return delegate if isinstance(delegate, _LegacySetterDelegateWrapper) else None + + @property + def setter_callback(self) -> Callable[[dict[str, Any]], None] | None: + """The legacy setter, called with the request's values by name. + + Called with a ``{display_name: value}`` dict before the + per-characteristic setters apply the writes - a pre-check that + may refuse them. + + Deprecated: a delegate's :meth:`~pyhap.delegates.ServiceDelegate.on_set` + checks the writes of the service instead. + """ + legacy = self._legacy + if legacy is not None: + return legacy.setter + raise ValueError( + f"{self.display_name} has a ServiceDelegate instead of a" + " legacy setter_callback" + ) + + @setter_callback.setter + def setter_callback( + self, callback: Callable[[dict[str, Any]], None] | None + ) -> None: + """Assign the legacy setter; ``None`` removes it. + + Deprecated: a delegate's :meth:`~pyhap.delegates.ServiceDelegate.on_set` + checks the writes of the service instead. + """ + if callback is not None: + warnings.warn( + "The legacy setter_callback is deprecated, use a ServiceDelegate" + " instead", + DeprecationWarning, + stacklevel=2, + ) + legacy = self._legacy + if legacy is None: + raise ValueError( + f"{self.display_name} has a delegate, remove it before" + " assigning a legacy setter_callback" + ) + legacy.setter = callback + + async def dispatch_set( + self, values: Mapping[Characteristic, Any], context: Context, *, is_admin: bool + ) -> None: + """Check a grouped write of this service through its delegate. + + Called by the driver's write path before any per-characteristic + ``on_set`` runs, with every written value of the request: builds + this service's :class:`~pyhap.context.ServiceWriteContext` and + awaits the delegate's ``on_set``. Assign a + :class:`~pyhap.delegates.ServiceDelegate` instead of overriding + this method - an override would silently take the delegate's + place. + + :param values: Every written value of the request, by characteristic. + :param context: The base context of the write request. + :param is_admin: Whether the writing controller has admin privileges. + """ + await self.delegate.on_set( + values, + ServiceWriteContext.of(context, service=self, is_admin=is_admin), + ) + def __repr__(self) -> str: """Return the representation of the service.""" chars_dict = {c.display_name: c.value for c in self.characteristics} @@ -108,17 +254,30 @@ def configure_char( value: Any = None, setter_callback: Any = None, getter_callback: Any = None, + delegate: CharacteristicDelegate | None = None, ) -> Characteristic: - """Helper method to return fully configured characteristic.""" + """Helper method to return fully configured characteristic. + + :param char_name: The name of the characteristic to configure. + :param properties: Properties to override on the characteristic. + :param valid_values: Valid values to set on the characteristic. + :param value: The value to set on the characteristic. + :param setter_callback: The legacy setter of the characteristic. + :param getter_callback: The legacy getter of the characteristic. + :param delegate: The characteristic's + :class:`~pyhap.delegates.CharacteristicDelegate` instance. + """ char = self.get_characteristic(char_name) if properties or valid_values: char.override_properties(properties, valid_values) if value: char.set_value(value, should_notify=False) - if setter_callback: - char.setter_callback = setter_callback - if getter_callback: - char.getter_callback = getter_callback + if setter_callback is not None: + char._assign_legacy_callback("setter_callback", setter_callback) + if getter_callback is not None: + char._assign_legacy_callback("getter_callback", getter_callback) + if delegate is not None: + char.delegate = delegate return char def to_HAP(self, include_value: bool = True) -> dict[str, Any]: diff --git a/pyproject.toml b/pyproject.toml index a7a84495..71f58b37 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -175,4 +175,8 @@ asyncio_mode = "auto" filterwarnings = [ "error::RuntimeWarning", "error:Exception ignored.*coroutine:pytest.PytestUnraisableExceptionWarning", + # The legacy-semantics tests are the compatibility contract; they + # intentionally use the deprecated callbacks. Dedicated tests assert the + # warnings with pytest.warns, which sees through this filter. + "ignore:The legacy (setter|getter)_callback is deprecated:DeprecationWarning", ] diff --git a/tests/conftest.py b/tests/conftest.py index 65793154..3425e0cc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -17,8 +17,62 @@ from pyhap.camera_multi_tier import MultiTierDelegate from pyhap.camera_stream import StreamController, StreamSession from pyhap.camera_webrtc import WebRTCDelegate +from pyhap.connection import HAPConnectionHandle +from pyhap.const import RESPONSE_TIMEOUT +from pyhap.context import CharWriteContext from pyhap.loader import Loader +_TEST_CONNECTIONS: dict[tuple[str, int] | None, HAPConnectionHandle] = {} + + +def connection_of(client_addr: tuple[str, int] | None) -> HAPConnectionHandle: + """The stable handle of a test connection, one identity per address. + + A controller's requests come with the handle of their connection; a + test that writes twice as one connection gets the same handle here. + """ + handle = _TEST_CONNECTIONS.get(client_addr) + if handle is None: + handle = _TEST_CONNECTIONS[client_addr] = HAPConnectionHandle( + client_addr, len(_TEST_CONNECTIONS) + ) + return handle + + +async def client_write( + char: Any, value: Any, client_addr: tuple[str, int] | None = None +) -> Any: + """Write a characteristic like a controller's request. + + The write goes through the delegate, like the driver's write path + does: the value is stored, ``on_set`` runs under the write deadline - + a legacy setter is wrapped into the delegate - and the subscribers + are told once it succeeded. A handler that raises restores the + previous value, like the driver does. + """ + context = CharWriteContext( + client_addr=client_addr, + client_uuid=None, + connection=connection_of(client_addr), + deadline=asyncio.get_running_loop().time() + RESPONSE_TIMEOUT, + characteristic=char, + is_admin=True, + ) + previous = char._store_client_update(value) + try: + response = await char.delegate.on_set(value, context) + except Exception: + char.value = previous + raise + char.client_update_finished(previous, client_addr) + return response + + +async def run_scheduled_jobs(rounds: int = 8) -> None: + """Let jobs scheduled by the driver and their tasks run.""" + for _ in range(rounds): + await asyncio.sleep(0) + @pytest.fixture(scope="session") def mock_driver() -> Iterator["MockDriver"]: @@ -189,7 +243,9 @@ def add_session( def _add(client_addr: Any) -> StreamSession: session = StreamSession( - id=uuid4(), sensor=session_controller.sensor, client_addr=client_addr + id=uuid4(), + sensor=session_controller.sensor, + connection=connection_of(client_addr), ) session_controller._add(session) return session diff --git a/tests/media_fakes.py b/tests/media_fakes.py index 3cd53c75..e1f327da 100644 --- a/tests/media_fakes.py +++ b/tests/media_fakes.py @@ -14,6 +14,7 @@ from pyhap import hksv3 from pyhap.camera_webrtc import WebRTCSession +from pyhap.connection import HAPConnectionHandle from pyhap.media import MediaError from pyhap.media.pool import ChannelLease, SourcePool @@ -39,7 +40,7 @@ def make_session(sframe: bool = True) -> WebRTCSession: return WebRTCSession( id=uuid4(), sensor=SENSOR, - client_addr=None, + connection=HAPConnectionHandle(None, 0), sframe=sframe, video_tier=MEDIUM, audio_tier=AUDIO, diff --git a/tests/media_hap.py b/tests/media_hap.py index 6d453635..2912e3a8 100644 --- a/tests/media_hap.py +++ b/tests/media_hap.py @@ -87,7 +87,9 @@ async def write(camera: Camera, name: str, value: Any) -> bytes: } ] } - pending = camera.driver._set_characteristics_for_controller(query, CLIENT, 9.0) + pending = camera.driver._set_characteristics_for_controller( + query, CLIENT, 9.0, connection=camera.driver._connection_of(CLIENT) + ) assert inspect.isawaitable(pending) result = await pending assert result is not None diff --git a/tests/test_accessory.py b/tests/test_accessory.py index 18d5ca88..f47ea116 100644 --- a/tests/test_accessory.py +++ b/tests/test_accessory.py @@ -4,6 +4,7 @@ from io import StringIO from typing import Any from unittest.mock import AsyncMock, patch +import warnings import pytest @@ -48,6 +49,28 @@ def test_acc_init(mock_driver: Any) -> None: Accessory(mock_driver, "Test Accessory") +def test_legacy_setter_warns_deprecated(mock_driver: Any) -> None: + """Assigning a legacy grouped setter announces its deprecation.""" + acc = Accessory(mock_driver, "Test Accessory") + assert acc.setter_callback is None + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + acc.setter_callback = lambda values: None # noqa: E731 + (warning,) = caught + assert warning.category is DeprecationWarning + assert "legacy setter_callback is deprecated" in str(warning.message) + # The warning names the assigning code, not the library. + assert warning.filename == __file__ + + assert acc.setter_callback is not None + + # Removing stays silent. + with warnings.catch_warnings(): + warnings.simplefilter("error") + acc.setter_callback = None + + def test_acc_with_custom_iid_manager(mock_driver: Any) -> None: """Test Accessory with custom IIDManager.""" diff --git a/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index 7ecd4312..76c5a98e 100644 --- a/tests/test_accessory_driver.py +++ b/tests/test_accessory_driver.py @@ -7,7 +7,7 @@ import tempfile import time from typing import Any, NoReturn -from unittest.mock import ANY, AsyncMock, MagicMock, call, patch +from unittest.mock import ANY, AsyncMock, MagicMock, patch from uuid import uuid1 from cryptography.hazmat.primitives import serialization @@ -22,7 +22,6 @@ MAX_PREPARED_WRITES_PER_CLIENT, PAIRING_LOCKOUT_SECONDS, AccessoryDriver, - AccessoryMDNSServiceInfo, ) from pyhap.characteristic import ( HAP_FORMAT_INT, @@ -31,6 +30,7 @@ PROP_PERMISSIONS, Characteristic, ) +from pyhap.connection import HAPConnectionHandle from pyhap.const import ( HAP_PERMISSION_NOTIFY, HAP_PERMISSION_WRITE, @@ -47,10 +47,13 @@ HAP_REPR_WRITE_RESPONSE, HAP_SERVER_STATUS, ) +from pyhap.errors import HapStatusError from pyhap.hap_crypto import hap_hkdf from pyhap.hap_protocol import HAPServerProtocol +from pyhap.mdns import AccessoryMDNSServiceInfo from pyhap.service import Service from pyhap.state import State +from tests.conftest import run_scheduled_jobs CHAR_PROPS = { PROP_FORMAT: HAP_FORMAT_INT, @@ -100,7 +103,7 @@ def available(self) -> bool: @pytest.mark.parametrize("bridged", [False, True], ids=["standalone", "bridged"]) @pytest.mark.parametrize("available", [False, True], ids=["unavailable", "available"]) -def test_get_characteristics_honors_availability( +async def test_get_characteristics_honors_availability( driver: AccessoryDriver, bridged: bool, available: bool ) -> None: """Respect accessory availability for standalone and bridged reads.""" @@ -120,7 +123,9 @@ def test_get_characteristics_honors_availability( driver.add_accessory(acc) iid = acc.iid_manager.get_iid(char) - result = driver.get_characteristics([f"{acc.aid}.{iid}"]) + result = await driver._get_characteristics_for_controller( + [f"{acc.aid}.{iid}"], ("1.2.3.4", 5), ASYNC_TIMEOUT + ) expected = { HAP_REPR_AID: acc.aid, @@ -139,9 +144,9 @@ def test_get_characteristics_honors_availability( with patch.object(UnavailableAccessory, "available", True): expected[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS expected[HAP_REPR_VALUE] = 42 - assert driver.get_characteristics([f"{acc.aid}.{iid}"]) == { - HAP_REPR_CHARS: [expected] - } + assert await driver._get_characteristics_for_controller( + [f"{acc.aid}.{iid}"], ("1.2.3.4", 5), ASYNC_TIMEOUT + ) == {HAP_REPR_CHARS: [expected]} getter.assert_called_once_with() @@ -205,7 +210,7 @@ def _add_bridged_or_standalone( @pytest.mark.parametrize("bridged", [False, True], ids=["standalone", "bridged"]) @pytest.mark.parametrize(("permissions", "expected", "reads"), READ_PERMISSION_CASES) -def test_get_characteristics_requires_read_permission( +async def test_get_characteristics_requires_read_permission( driver: AccessoryDriver, bridged: bool, permissions: list[str], @@ -216,7 +221,9 @@ def test_get_characteristics_requires_read_permission( acc, char, getter = _add_bridged_or_standalone(driver, permissions, bridged) iid = acc.iid_manager.get_iid(char) - result = driver.get_characteristics([f"{acc.aid}.{iid}"]) + result = await driver._get_characteristics_for_controller( + [f"{acc.aid}.{iid}"], ("1.2.3.4", 5), ASYNC_TIMEOUT + ) assert result == { HAP_REPR_CHARS: [{HAP_REPR_AID: acc.aid, HAP_REPR_IID: iid, **expected}] @@ -224,6 +231,60 @@ def test_get_characteristics_requires_read_permission( assert getter.call_count == reads +def _raise_out_of_resource() -> NoReturn: + raise HapStatusError(HAP_SERVER_STATUS.OUT_OF_RESOURCE) + + +async def test_get_characteristics_hap_status_answers_request( + driver: AccessoryDriver, +) -> None: + """A getter's HapStatusError answers with its status, not -70402.""" + acc, char, _ = _add_bridged_or_standalone(driver, ["pr", "ev"], False) + char.getter_callback = _raise_out_of_resource + + iid = acc.iid_manager.get_iid(char) + result = await driver._get_characteristics_for_controller( + [f"{acc.aid}.{iid}"], ("1.2.3.4", 5), ASYNC_TIMEOUT + ) + + assert result == { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: iid, + HAP_REPR_STATUS: HAP_SERVER_STATUS.OUT_OF_RESOURCE, + } + ] + } + + +async def test_get_accessories_isolates_a_failing_getter( + driver: AccessoryDriver, +) -> None: + """A failing getter omits its value, and does not fail the whole list.""" + acc = Accessory(driver, "Test Accessory") + service = Service(uuid1(), "Test Service") + good = Characteristic("Good", uuid1(), CHAR_PROPS) + good.getter_callback = lambda: 1 + bad = Characteristic("Bad", uuid1(), CHAR_PROPS) + bad.getter_callback = _raise_out_of_resource + service.add_characteristic(good, bad) + acc.add_service(service) + driver.add_accessory(acc) + + (acc_rep,) = ( + await driver._get_accessories_for_controller(("1.2.3.4", 5), ASYNC_TIMEOUT) + )[HAP_REPR_ACCS] + reps = { + rep[HAP_REPR_IID]: rep for rep in acc_rep[HAP_REPR_SERVICES][-1][HAP_REPR_CHARS] + } + good_rep = reps[acc.iid_manager.get_iid(good)] + bad_rep = reps[acc.iid_manager.get_iid(bad)] + + assert good_rep[HAP_REPR_VALUE] == 1 + assert HAP_REPR_VALUE not in bad_rep + + @pytest.mark.parametrize( ("permissions", "values", "reads"), [ @@ -234,14 +295,17 @@ def test_get_characteristics_requires_read_permission( (["pw", "tw"], set(), 0), ], ) -def test_get_accessories_value_requires_read_permission( +async def test_get_accessories_value_requires_read_permission( driver: AccessoryDriver, permissions: list[str], values: set[str], reads: int ) -> None: """The accessory database only includes values the controller may read.""" + driver.loop = asyncio.get_running_loop() acc, char, getter = _add_bridged_or_standalone(driver, permissions, False) (acc_rep,) = driver.get_accessories()[HAP_REPR_ACCS] (char_rep,) = acc_rep[HAP_REPR_SERVICES][-1][HAP_REPR_CHARS] + # A direct call answers at once and runs the reads as a job. + await run_scheduled_jobs() assert char_rep[HAP_REPR_IID] == acc.iid_manager.get_iid(char) assert char_rep.keys() & {HAP_REPR_VALUE} == values @@ -262,7 +326,7 @@ def test_subscribe_with_notify_permission( subscribe = {HAP_REPR_AID: acc.aid, HAP_REPR_IID: iid, HAP_PERMISSION_NOTIFY: True} assert driver.set_characteristics({HAP_REPR_CHARS: [subscribe]}, client) is None - assert driver.topics == {f"{acc.aid}.{iid}": {client}} + assert driver.topics == {f"{acc.aid}.{iid}": {driver._connection_of(client)}} unsubscribe = {**subscribe, HAP_PERMISSION_NOTIFY: False} assert driver.set_characteristics({HAP_REPR_CHARS: [unsubscribe]}, client) is None @@ -353,7 +417,7 @@ def test_refused_subscription_lists_the_others(driver: AccessoryDriver) -> None: }, ] } - assert driver.topics == {f"{acc.aid}.{ok_iid}": {client}} + assert driver.topics == {f"{acc.aid}.{ok_iid}": {driver._connection_of(client)}} @pytest.mark.parametrize("ev", [True, False], ids=["subscribe", "unsubscribe"]) @@ -393,36 +457,37 @@ def test_write_with_subscribe_without_notify_permission( assert driver.topics == {} -def _write_value( +async def _write_value( driver: AccessoryDriver, acc: Accessory, char: Characteristic, **query: Any ) -> tuple[dict[str, Any] | None, MagicMock, MagicMock]: - """Write 5 to ``char`` and return the result and both setter mocks.""" + """Write 5 to ``char``, waiting for the setters, and return their mocks.""" setter = MagicMock() char.setter_callback = setter service_setter = MagicMock() assert char.service is not None char.service.setter_callback = service_setter iid = acc.iid_manager.get_iid(char) - result = driver.set_characteristics( + result = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ {HAP_REPR_AID: acc.aid, HAP_REPR_IID: iid, HAP_REPR_VALUE: 5, **query} ] }, ("1.2.3.4", 5), + ASYNC_TIMEOUT, ) return result, setter, service_setter @pytest.mark.parametrize("bridged", [False, True], ids=["standalone", "bridged"]) @pytest.mark.parametrize("permissions", [["pr"], ["pr", "ev"]]) -def test_write_without_write_permission( +async def test_write_without_write_permission( driver: AccessoryDriver, bridged: bool, permissions: list[str] ) -> None: """A write to a characteristic without paired write is refused.""" acc, char, _ = _add_bridged_or_standalone(driver, permissions, bridged) - result, setter, service_setter = _write_value(driver, acc, char) + result, setter, service_setter = await _write_value(driver, acc, char) assert result == { HAP_REPR_CHARS: [ @@ -440,13 +505,13 @@ def test_write_without_write_permission( @pytest.mark.parametrize("bridged", [False, True], ids=["standalone", "bridged"]) @pytest.mark.parametrize("permissions", [["pw"], ["pr", "pw"], ["pr", "pw", "ev"]]) -def test_write_with_write_permission( +async def test_write_with_write_permission( driver: AccessoryDriver, bridged: bool, permissions: list[str] ) -> None: """A write to a characteristic with paired write is applied.""" acc, char, _ = _add_bridged_or_standalone(driver, permissions, bridged) - result, setter, service_setter = _write_value(driver, acc, char) + result, setter, service_setter = await _write_value(driver, acc, char) assert result is None setter.assert_called_once_with(5) @@ -454,7 +519,7 @@ def test_write_with_write_permission( assert char.value == 5 -def test_write_with_subscribe_without_write_permission( +async def test_write_with_subscribe_without_write_permission( driver: AccessoryDriver, ) -> None: """A subscription is applied even when the write in the same entry is not.""" @@ -462,7 +527,9 @@ def test_write_with_subscribe_without_write_permission( client = ("1.2.3.4", 5) iid = acc.iid_manager.get_iid(char) - result, setter, _ = _write_value(driver, acc, char, **{HAP_PERMISSION_NOTIFY: True}) + result, setter, _ = await _write_value( + driver, acc, char, **{HAP_PERMISSION_NOTIFY: True} + ) assert result == { HAP_REPR_CHARS: [ @@ -474,10 +541,10 @@ def test_write_with_subscribe_without_write_permission( ] } setter.assert_not_called() - assert driver.topics == {f"{acc.aid}.{iid}": {client}} + assert driver.topics == {f"{acc.aid}.{iid}": {driver._connection_of(client)}} -def test_refused_write_does_not_block_others(driver: AccessoryDriver) -> None: +async def test_refused_write_does_not_block_others(driver: AccessoryDriver) -> None: """A refused write leaves the other characteristics of the request alone.""" acc = Accessory(driver, "Test Accessory", aid=STANDALONE_AID) service = Service(uuid1(), "Test Service") @@ -493,7 +560,7 @@ def test_refused_write_does_not_block_others(driver: AccessoryDriver) -> None: read_only_iid = acc.iid_manager.get_iid(read_only) writable_iid = acc.iid_manager.get_iid(writable) - result = driver.set_characteristics( + result = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ {HAP_REPR_AID: acc.aid, HAP_REPR_IID: read_only_iid, HAP_REPR_VALUE: 5}, @@ -501,6 +568,7 @@ def test_refused_write_does_not_block_others(driver: AccessoryDriver) -> None: ] }, ("1.2.3.4", 5), + ASYNC_TIMEOUT, ) assert result == { @@ -614,11 +682,25 @@ def test_listen_address(kwargs: dict[str, Any], expected: Any) -> None: OTHER_CONTROLLER = ("5.6.7.8", 9) -def _write( +def _query(acc: Accessory, char: Characteristic, **query: Any) -> dict[str, Any]: + """Return a write of 0 to ``char`` with extra query fields.""" + return { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char), + HAP_REPR_VALUE: 0, + **query, + } + ] + } + + +async def _write( driver: AccessoryDriver, acc: Accessory, char: Characteristic, **query: Any ) -> Any: - """Write 0 to ``char`` from a mock client with extra query fields.""" - return driver.set_characteristics( + """Write 0 to ``char`` from a mock client, waiting for the setters.""" + return await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -630,6 +712,7 @@ def _write( ] }, WRITER, + ASYNC_TIMEOUT, ) @@ -643,7 +726,7 @@ def _write( ], ) @pytest.mark.parametrize(("returned", "sent"), [(1, 1), (1.7, 1)]) -def test_write_response_returned_when_requested( +async def test_write_response_returned_when_requested( driver: AccessoryDriver, bridged: bool, permissions: list[str], @@ -656,9 +739,10 @@ def test_write_response_returned_when_requested( service_setter = MagicMock() assert char.service is not None char.service.setter_callback = service_setter - char.setter_callback = MagicMock(return_value=returned) + setter = MagicMock(return_value=returned) + char.setter_callback = setter - response = _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: True}) + response = await _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: True}) assert response == { HAP_REPR_CHARS: [ @@ -670,7 +754,7 @@ def test_write_response_returned_when_requested( } ] } - char.setter_callback.assert_called_once_with(0) + setter.assert_called_once_with(0) service_setter.assert_called_once_with({"Value": 0}) assert char.value == stored @@ -688,15 +772,16 @@ def test_write_response_returned_when_requested( pytest.param(["pw"], {HAP_REPR_WRITE_RESPONSE: True}, id="write-only"), ], ) -def test_write_response_not_returned( +async def test_write_response_not_returned( driver: AccessoryDriver, permissions: list[str], query: dict[str, Any] ) -> None: """Without a request or the wr permission the write has no response body.""" acc, char, _ = _add_bridged_or_standalone(driver, permissions, False) - char.setter_callback = MagicMock(return_value=1) + setter = MagicMock(return_value=1) + char.setter_callback = setter - assert _write(driver, acc, char, **query) is None - char.setter_callback.assert_called_once_with(0) + assert await _write(driver, acc, char, **query) is None + setter.assert_called_once_with(0) assert char.value == 0 @@ -707,14 +792,14 @@ def test_write_response_not_returned( pytest.param(["pw", "wr"], 5, id="write-only"), ], ) -def test_invalid_write_response_is_sent_but_not_kept( +async def test_invalid_write_response_is_sent_but_not_kept( driver: AccessoryDriver, permissions: list[str], stored: int ) -> None: """A response the char can't hold is still sent, but not kept as its value.""" acc, char, _ = _add_bridged_or_standalone(driver, permissions, False) char.setter_callback = MagicMock(return_value="not a number") - response = _write( + response = await _write( driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} ) @@ -723,7 +808,7 @@ def test_invalid_write_response_is_sent_but_not_kept( assert char.value == stored -def test_write_response_value_of_write_only_char_not_readable( +async def test_write_response_value_of_write_only_char_not_readable( driver: AccessoryDriver, ) -> None: """Neither the written nor the response value of a wr char without pr leaks.""" @@ -731,7 +816,7 @@ def test_write_response_value_of_write_only_char_not_readable( char.setter_callback = MagicMock(return_value=1) iid = acc.iid_manager.get_iid(char) - _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: True}) + await _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: True}) assert driver.get_characteristics([f"{acc.aid}.{iid}"]) == { HAP_REPR_CHARS: [ @@ -750,7 +835,14 @@ def test_write_response_value_of_write_only_char_not_readable( async def _controller_write( - driver: AccessoryDriver, acc: Accessory, char: Characteristic, **query: Any + driver: AccessoryDriver, + acc: Accessory, + char: Characteristic, + *, + # ``Any`` so the ``**query`` dicts of ``HAP_REPR_*`` keys type-check, + # ty cannot narrow their ``str`` keys away from this parameter. + connection: Any = None, + **query: Any, ) -> dict[str, Any] | None: """Write 0 to ``char`` like a controller and wait for the async setters.""" result = driver._set_characteristics_for_controller( @@ -766,17 +858,31 @@ async def _controller_write( }, WRITER, ASYNC_TIMEOUT, + connection=connection, ) assert inspect.isawaitable(result) return await result -async def _async_return_one(value: int) -> int: - await asyncio.sleep(0) - return 1 +def _live_connection(driver: AccessoryDriver) -> HAPConnectionHandle: + """A handle like a live connection's, registered like its protocol. + + A controller's write carries the handle of its connection; "closing" + one is the handle leaving ``http_server.connections``, as its + protocol's ``close()`` does. + """ + connection = HAPConnectionHandle(WRITER, driver._next_connection_generation()) + driver.http_server.connections[connection] = MagicMock() + return connection + + +def _close_connection(driver: AccessoryDriver, connection: HAPConnectionHandle) -> None: + """Close the connection of ``connection`` like its protocol does.""" + del driver.http_server.connections[connection] + driver.connection_lost(WRITER, connection=connection) -async def _async_return_one_with_addr(value: int, sender_client_addr: Any) -> int: +async def _async_return_one(value: int) -> int: await asyncio.sleep(0) return 1 @@ -801,13 +907,6 @@ async def _async_raise(value: int) -> NoReturn: 0, id="write-response", ), - pytest.param( - _async_return_one_with_addr, - ["pw", "wr"], - {HAP_REPR_STATUS: HAP_SERVER_STATUS.SUCCESS, HAP_REPR_VALUE: 1}, - 1, - id="write-response-with-addr", - ), pytest.param( _async_raise, ["pr", "pw", "wr"], @@ -845,6 +944,176 @@ async def test_async_setter_result( assert char.value == stored +def _raise_resource_busy(value: Any) -> None: + raise HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + + +async def _async_raise_out_of_resource(value: int) -> NoReturn: + await asyncio.sleep(0) + raise HapStatusError(HAP_SERVER_STATUS.OUT_OF_RESOURCE) + + +@pytest.mark.parametrize("bridged", [False, True], ids=["standalone", "bridged"]) +async def test_sync_setter_hap_status_answers_request( + driver: AccessoryDriver, bridged: bool +) -> None: + """A sync setter's HapStatusError answers with its status, not -70402.""" + acc, char, _ = _add_bridged_or_standalone(driver, ["pr", "pw"], bridged) + char.setter_callback = _raise_resource_busy + + result = await driver._set_characteristics_for_controller( + { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char), + HAP_REPR_VALUE: 5, + } + ] + }, + "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, + ) + + assert result == { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char), + HAP_REPR_STATUS: HAP_SERVER_STATUS.RESOURCE_BUSY, + } + ] + } + + +@pytest.mark.parametrize("bridged", [False, True], ids=["standalone", "bridged"]) +async def test_async_setter_hap_status_answers_request( + driver: AccessoryDriver, bridged: bool +) -> None: + """A coroutine setter's HapStatusError answers with its status.""" + acc, char, _ = _add_bridged_or_standalone(driver, ["pr", "pw", "wr"], bridged) + char.setter_callback = _async_raise_out_of_resource + + result = await _controller_write( + driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: True} + ) + + assert result == { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char), + HAP_REPR_STATUS: HAP_SERVER_STATUS.OUT_OF_RESOURCE, + } + ] + } + + +async def test_service_setter_hap_status_answers_all_its_chars( + driver: AccessoryDriver, +) -> None: + """A service setter's HapStatusError answers its chars, not the others.""" + acc = Accessory(driver, "TestAcc") + refused = Service(uuid1(), "Refused") + char_refused = Characteristic("RefusedValue", uuid1(), CHAR_PROPS) + refused.add_characteristic(char_refused) + other = Service(uuid1(), "Other") + char_other = Characteristic("OtherValue", uuid1(), CHAR_PROPS) + other.add_characteristic(char_other) + acc.add_service(refused, other) + driver.add_accessory(acc) + refused.setter_callback = _raise_resource_busy + + response = await driver._set_characteristics_for_controller( + { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char_refused), + HAP_REPR_VALUE: 3, + }, + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char_other), + HAP_REPR_VALUE: 4, + }, + ] + }, + "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, + ) + + assert response == { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char_refused), + HAP_REPR_STATUS: HAP_SERVER_STATUS.RESOURCE_BUSY, + }, + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char_other), + HAP_REPR_STATUS: HAP_SERVER_STATUS.SUCCESS, + }, + ] + } + + +async def test_accessory_setter_hap_status_answers_all_its_chars( + driver: AccessoryDriver, +) -> None: + """An accessory setter's HapStatusError answers its chars, not the others.""" + bridge = Bridge(driver, "mybridge") + acc = Accessory(driver, "TestAcc", aid=2) + acc2 = Accessory(driver, "TestAcc2", aid=3) + service = Service(uuid1(), "Service") + char_on = Characteristic("On", uuid1(), CHAR_PROPS) + service.add_characteristic(char_on) + acc.add_service(service) + service2 = Service(uuid1(), "Service") + char_on2 = Characteristic("On", uuid1(), CHAR_PROPS) + service2.add_characteristic(char_on2) + acc2.add_service(service2) + bridge.add_accessory(acc) + bridge.add_accessory(acc2) + driver.add_accessory(bridge) + acc.setter_callback = _raise_resource_busy + + response = await driver._set_characteristics_for_controller( + { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char_on), + HAP_REPR_VALUE: True, + }, + { + HAP_REPR_AID: acc2.aid, + HAP_REPR_IID: acc2.iid_manager.get_iid(char_on2), + HAP_REPR_VALUE: True, + }, + ] + }, + "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, + ) + + assert response == { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char_on), + HAP_REPR_STATUS: HAP_SERVER_STATUS.RESOURCE_BUSY, + }, + { + HAP_REPR_AID: acc2.aid, + HAP_REPR_IID: acc2.iid_manager.get_iid(char_on2), + HAP_REPR_STATUS: HAP_SERVER_STATUS.SUCCESS, + }, + ] + } + + @pytest.mark.parametrize( ("reader", "expected"), [ @@ -876,6 +1145,7 @@ async def test_async_write_response_dropped_when_closed_while_queued( # closes. The cancel in ``HAPServerProtocol.close()`` covers the rest. driver.loop = asyncio.get_running_loop() acc, char, _ = _add_write_response_char(driver, False) + connection = _live_connection(driver) release = asyncio.Event() async def _setter(value: int) -> int: @@ -885,7 +1155,11 @@ async def _setter(value: int) -> int: char.setter_callback = _setter write = asyncio.ensure_future( _controller_write( - driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + driver, + acc, + char, + connection=connection, + **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}, ) ) await asyncio.sleep(0) @@ -894,7 +1168,7 @@ async def _setter(value: int) -> int: await asyncio.sleep(0) await asyncio.sleep(0) - driver.connection_lost(WRITER) + _close_connection(driver, connection) await write await asyncio.sleep(0) @@ -906,11 +1180,13 @@ async def test_async_write_response_dropped_when_closed_before_setter_done( ) -> None: """A response of a setter finishing after the connection closed is dropped. - The deferred cleanup in ``connection_lost`` has already run when such a - setter answers, so without the guard the response would stay for a later - connection that reuses the address. + The store keeps a read back response only of a still-open connection, see + ``AccessoryDriver._is_open``, so an answer that arrives after its + connection closed is dropped - it could never be read by the closed + connection, and not by one that reuses its address either. """ acc, char, char_id = _add_write_response_char(driver, False) + connection = _live_connection(driver) release = asyncio.Event() async def _setter(value: int) -> int: @@ -920,19 +1196,23 @@ async def _setter(value: int) -> int: char.setter_callback = _setter write = asyncio.ensure_future( _controller_write( - driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + driver, + acc, + char, + connection=connection, + **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}, ) ) await asyncio.sleep(0) - driver.connection_lost(WRITER) - # Let the deferred cleanup run, then let the setter finish. - await asyncio.sleep(0) + _close_connection(driver, connection) release.set() - assert await write is None + # The response of the closed connection is answered to nobody - its + # task is cancelled - what matters is that its value is not kept for a + # connection that reuses the address. + await write assert driver._write_responses == {} - assert driver._pending_connection_writes == {} # A connection that reuses the address reads the shared value. assert _read(driver, char_id, WRITER) == 0 @@ -942,6 +1222,7 @@ async def test_async_read_back_dropped_when_closed_before_setter_done( ) -> None: """A Setup Endpoints style answer of a setter finishing late is dropped.""" acc, char = _add_read_back_char(driver) + connection = _live_connection(driver) release = asyncio.Event() async def _setter(value: int) -> int: @@ -950,12 +1231,13 @@ async def _setter(value: int) -> int: char.setter_callback = _setter write = asyncio.ensure_future( - _controller_write(driver, acc, char, **{HAP_REPR_VALUE: 5}) + _controller_write( + driver, acc, char, connection=connection, **{HAP_REPR_VALUE: 5} + ) ) await asyncio.sleep(0) - driver.connection_lost(WRITER) - await asyncio.sleep(0) + _close_connection(driver, connection) release.set() assert await write is None @@ -1056,7 +1338,7 @@ async def test_async_accessory_or_service_setter_is_closed( driver.add_accessory(acc) attach(acc, service) - result = driver._set_characteristics_for_controller( + result = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -1113,9 +1395,11 @@ async def test_async_and_sync_setters_in_one_write(driver: AccessoryDriver) -> N ASYNC_TIMEOUT, ) - service_setter.assert_called_once_with({"Async": 3, "Sync": 4}) assert inspect.isawaitable(result) - assert await result == { + response = await result + # The service setter ran as the pre-check, before the char setters. + service_setter.assert_called_once_with({"Async": 3, "Sync": 4}) + assert response == { HAP_REPR_CHARS: [ { HAP_REPR_AID: acc.aid, @@ -1243,14 +1527,14 @@ def __call__(self, value: int) -> Any: return self.coro -async def test_malformed_entry_closes_pending_setters(driver: AccessoryDriver) -> None: - """A write that fails on a later entry closes the coroutines it created.""" +async def test_malformed_entry_runs_no_setter(driver: AccessoryDriver) -> None: + """A write that fails on a later entry runs no setter of the request.""" acc, char, _ = _add_bridged_or_standalone(driver, ["pw"], False) setter = _CoroutineRecorder() char.setter_callback = setter with pytest.raises(KeyError): - driver._set_characteristics_for_controller( + await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -1265,7 +1549,7 @@ async def test_malformed_entry_closes_pending_setters(driver: AccessoryDriver) - ASYNC_TIMEOUT, ) - assert inspect.getcoroutinestate(setter.coro) == inspect.CORO_CLOSED + assert setter.coro is None async def test_public_set_characteristics_schedules_async_setters( @@ -1276,8 +1560,25 @@ async def test_public_set_characteristics_schedules_async_setters( acc, char, _ = _add_bridged_or_standalone(driver, ["pw", "wr"], False) setter = _RecordingSetter() char.setter_callback = setter + iid = acc.iid_manager.get_iid(char) - assert _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: True}) is None + # Answered at once, optimistically: the setter runs in the job. + assert ( + driver.set_characteristics( + { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: iid, + HAP_REPR_VALUE: 0, + HAP_REPR_WRITE_RESPONSE: True, + } + ] + }, + WRITER, + ) + is None + ) await asyncio.wait_for(setter.ran.wait(), ASYNC_TIMEOUT) @@ -1297,14 +1598,14 @@ async def __call__(self, value: int) -> None: @pytest.mark.parametrize( - ("fail", "calls"), + ("fail", "notified"), [ - pytest.param(False, [call(WRITER)], id="success"), - pytest.param(True, [], id="error"), + pytest.param(False, True, id="success"), + pytest.param(True, False, id="error"), ], ) async def test_async_setter_notifies_once_it_succeeded( - driver: AccessoryDriver, fail: bool, calls: list[Any] + driver: AccessoryDriver, fail: bool, notified: bool ) -> None: """Subscribers learn a written value only after the async setter succeeded.""" acc, char, _ = _add_bridged_or_standalone(driver, ["pr", "pw", "ev"], False) @@ -1316,7 +1617,10 @@ async def test_async_setter_notifies_once_it_succeeded( await _controller_write(driver, acc, char) assert setter.notified_before == [0] - assert notify.call_args_list == calls + if notified: + notify.assert_called_once_with(driver._connection_of(WRITER)) + else: + notify.assert_not_called() class _ValueSettingSetter: @@ -1354,12 +1658,13 @@ def test_direct_client_update_notifies_at_once(driver: AccessoryDriver) -> None: _, char, _ = _add_bridged_or_standalone(driver, ["pr", "pw", "ev"], False) char.value = 5 char.setter_callback = _async_return_none + connection = driver._connection_of(WRITER) with patch.object(Characteristic, "notify") as notify: - coro = char.client_update_value(0, WRITER) + coro = char.client_update_value(0, connection) coro.close() - notify.assert_called_once_with(WRITER) + notify.assert_called_once_with(connection) async def test_public_write_notifies_once_the_async_setter_ran( @@ -1379,11 +1684,11 @@ def _record(*_: Any) -> None: notified.set() with patch.object(Characteristic, "notify", side_effect=_record) as notify: - assert _write(driver, acc, char) is None + assert await _write(driver, acc, char) is None await asyncio.wait_for(notified.wait(), ASYNC_TIMEOUT) assert ran_when_notified == [True] - notify.assert_called_once_with(WRITER) + notify.assert_called_once_with(driver._connection_of(WRITER)) async def test_public_write_logs_a_failing_async_setter( @@ -1400,28 +1705,31 @@ async def test_public_write_logs_a_failing_async_setter( patch.object(Characteristic, "notify") as notify, patch.object( accessory_driver.logger, - "exception", - side_effect=lambda *_: logged.set(), - ) as log_exception, + "error", + side_effect=lambda *_args, **_kwargs: logged.set(), + ) as log_error, ): - assert _write(driver, acc, char) is None + assert driver.set_characteristics(_query(acc, char), WRITER) is None await asyncio.wait_for(logged.wait(), ASYNC_TIMEOUT) - log_exception.assert_called_once_with( - "%s: Error while setting characteristic %s", WRITER, char.display_name + log_error.assert_called_once_with( + "%s: Error while setting characteristic %s", + WRITER, + char.display_name, + exc_info=ANY, ) notify.assert_not_called() @pytest.mark.parametrize( - ("fast_setter", "calls"), + ("fast_setter", "notified"), [ - pytest.param(_async_return_none, [call(WRITER)], id="success"), - pytest.param(_async_raise, [], id="error"), + pytest.param(_async_return_none, True, id="success"), + pytest.param(_async_raise, False, id="error"), ], ) async def test_cancelled_write_notifies_setters_that_finished( - driver: AccessoryDriver, fast_setter: Any, calls: list[Any] + driver: AccessoryDriver, fast_setter: Any, notified: bool ) -> None: """A setter done before the write is cancelled tells subscribers if it worked.""" acc = Accessory(driver, "Test Accessory") @@ -1456,7 +1764,10 @@ async def test_cancelled_write_notifies_setters_that_finished( task.cancel() await asyncio.gather(task, return_exceptions=True) - assert notify.call_args_list == calls + if notified: + notify.assert_called_once_with(driver._connection_of(WRITER)) + else: + notify.assert_not_called() assert task.cancelled() @@ -1517,7 +1828,7 @@ async def test_public_private_write_with_own_value_does_not_notify( char.setter_callback = setter with patch.object(Characteristic, "notify") as notify: - _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: True}) + await _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: True}) await asyncio.wait_for(setter.done.wait(), ASYNC_TIMEOUT) await asyncio.sleep(0) @@ -1591,12 +1902,14 @@ async def test_setter_failing_after_its_cancellation_is_retrieved( @pytest.mark.parametrize("flag", [True, 1], ids=["true", "one"]) -def test_write_response_flag_is_truthy(driver: AccessoryDriver, flag: Any) -> None: +async def test_write_response_flag_is_truthy( + driver: AccessoryDriver, flag: Any +) -> None: """Any truthy "r" asks for a write response, as before.""" acc, char, _ = _add_bridged_or_standalone(driver, ["pw", "wr"], False) char.setter_callback = MagicMock(return_value=1) - response = _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: flag}) + response = await _write(driver, acc, char, **{HAP_REPR_WRITE_RESPONSE: flag}) assert response[HAP_REPR_CHARS][0][HAP_REPR_VALUE] == 1 @@ -1609,16 +1922,8 @@ async def test_setter_returning_a_task_is_not_awaited( task = asyncio.ensure_future(asyncio.sleep(10)) char.setter_callback = MagicMock(return_value=task) - result = driver._set_characteristics_for_controller( - { - HAP_REPR_CHARS: [ - { - HAP_REPR_AID: acc.aid, - HAP_REPR_IID: acc.iid_manager.get_iid(char), - HAP_REPR_VALUE: 0, - } - ] - }, + result = await driver._set_characteristics_for_controller( + _query(acc, char), ("1.2.3.4", 5), ASYNC_TIMEOUT, ) @@ -1654,19 +1959,22 @@ def _read(driver: AccessoryDriver, char_id: str, client_addr: Any) -> Any: pytest.param(None, 0, id="no-client"), ], ) -def test_write_response_readable_only_by_writer( +async def test_write_response_readable_only_by_writer( driver: AccessoryDriver, bridged: bool, reader: Any, expected: int ) -> None: """Only the controller that wrote reads its write response back.""" acc, char, char_id = _add_write_response_char(driver, bridged) - _write(driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}) + await _write( + driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + ) assert _read(driver, char_id, reader) == expected -def test_write_responses_kept_per_controller(driver: AccessoryDriver) -> None: +async def test_write_responses_kept_per_controller(driver: AccessoryDriver) -> None: """Each controller reads its own last write response.""" + driver.loop = asyncio.get_running_loop() acc, char, char_id = _add_write_response_char(driver, False) char.setter_callback = MagicMock(side_effect=[7, 8]) request = { @@ -1681,20 +1989,24 @@ def test_write_responses_kept_per_controller(driver: AccessoryDriver) -> None: } driver.set_characteristics(request, WRITER) + await run_scheduled_jobs() driver.set_characteristics(request, OTHER_CONTROLLER) + await run_scheduled_jobs() assert _read(driver, char_id, WRITER) == 7 assert _read(driver, char_id, OTHER_CONTROLLER) == 8 @pytest.mark.parametrize("bridged", [False, True], ids=["standalone", "bridged"]) -def test_write_response_not_in_accessories( +async def test_write_response_not_in_accessories( driver: AccessoryDriver, bridged: bool ) -> None: """The accessory database has the default value, not the write response.""" acc, char, _ = _add_write_response_char(driver, bridged) - _write(driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}) + await _write( + driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + ) acc_rep = driver.get_accessories()[HAP_REPR_ACCS][-1] assert acc_rep[HAP_REPR_SERVICES][-1][HAP_REPR_CHARS][0][HAP_REPR_VALUE] == 0 @@ -1704,22 +2016,22 @@ async def test_write_response_dropped_on_disconnect(driver: AccessoryDriver) -> """A write response is not read back after the connection closed.""" driver.loop = asyncio.get_running_loop() acc, char, char_id = _add_write_response_char(driver, False) - _write(driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}) + await _write( + driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + ) driver.connection_lost(WRITER) - assert _read(driver, char_id, WRITER) == 7 - # The response is dropped once the loop runs. - await asyncio.sleep(0) - assert _read(driver, char_id, WRITER) == 0 -def test_plain_write_replaces_write_response(driver: AccessoryDriver) -> None: +async def test_plain_write_replaces_write_response(driver: AccessoryDriver) -> None: """A write without ``r`` drops the writer's former response.""" acc, char, char_id = _add_write_response_char(driver, False) - _write(driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}) + await _write( + driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + ) - _write(driver, acc, char, **{HAP_REPR_VALUE: 9}) + await _write(driver, acc, char, **{HAP_REPR_VALUE: 9}) assert _read(driver, char_id, WRITER) == 9 assert _read(driver, char_id, OTHER_CONTROLLER) == 9 @@ -1732,7 +2044,7 @@ def test_plain_write_replaces_write_response(driver: AccessoryDriver) -> None: pytest.param({"side_effect": RuntimeError}, 3, id="raises"), ], ) -def test_write_response_keeps_accessory_value( +async def test_write_response_keeps_accessory_value( driver: AccessoryDriver, setter_kwargs: dict[str, Any], writer_reads: int ) -> None: """Other connections keep reading the value the accessory set.""" @@ -1740,13 +2052,17 @@ def test_write_response_keeps_accessory_value( char.setter_callback = MagicMock(**setter_kwargs) char.set_value(3) - _write(driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}) + await _write( + driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + ) assert _read(driver, char_id, WRITER) == writer_reads assert _read(driver, char_id, OTHER_CONTROLLER) == 3 -def test_write_response_keeps_value_set_by_setter(driver: AccessoryDriver) -> None: +async def test_write_response_keeps_value_set_by_setter( + driver: AccessoryDriver, +) -> None: """A value the setter sets on its own characteristic is kept.""" acc, char, char_id = _add_write_response_char(driver, False) @@ -1756,7 +2072,9 @@ def _setter(value: int) -> int: char.setter_callback = _setter - _write(driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}) + await _write( + driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + ) assert _read(driver, char_id, WRITER) == 7 assert _read(driver, char_id, OTHER_CONTROLLER) == 42 @@ -1769,7 +2087,7 @@ def _setter(value: int) -> int: pytest.param(False, [5], id="plain"), ], ) -def test_private_write_not_notified( +async def test_private_write_not_notified( driver: AccessoryDriver, write_response: bool, notified: list[int] ) -> None: """Subscribers are not told the request of a write with ``r``.""" @@ -1780,7 +2098,7 @@ def test_private_write_not_notified( with patch.object( acc, "publish", side_effect=lambda value, *_: published.append(value) ): - _write( + await _write( driver, acc, char, @@ -1799,14 +2117,16 @@ def test_private_write_not_notified( pytest.param(lambda: None, id="no-setter"), ], ) -def test_write_response_request_not_shared_without_response( +async def test_write_response_request_not_shared_without_response( driver: AccessoryDriver, reader: Any, make_setter: Any ) -> None: """The written request stays private when no response is kept.""" acc, char, char_id = _add_write_response_char(driver, False) char.setter_callback = make_setter() - _write(driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True}) + await _write( + driver, acc, char, **{HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} + ) assert _read(driver, char_id, reader) == 0 @@ -1819,20 +2139,25 @@ def test_write_response_request_not_shared_without_response( pytest.param(None, id="no-response"), ], ) -def test_stale_write_response_dropped(driver: AccessoryDriver, second: Any) -> None: +async def test_stale_write_response_dropped( + driver: AccessoryDriver, second: Any +) -> None: """A later write that keeps no response drops the former one.""" acc, char, char_id = _add_write_response_char(driver, False) char.setter_callback = MagicMock(side_effect=[7, second]) query = {HAP_REPR_VALUE: 5, HAP_REPR_WRITE_RESPONSE: True} - _write(driver, acc, char, **query) - _write(driver, acc, char, **query) + await _write(driver, acc, char, **query) + await _write(driver, acc, char, **query) assert _read(driver, char_id, WRITER) == 0 -def test_write_response_without_client_not_kept(driver: AccessoryDriver) -> None: - """A write response without a known connection is sent but not kept.""" +async def test_write_response_without_client_not_kept( + driver: AccessoryDriver, +) -> None: + """A direct write without a client is read back without one.""" + driver.loop = asyncio.get_running_loop() acc, char, _ = _add_write_response_char(driver, False) request = { HAP_REPR_CHARS: [ @@ -1846,11 +2171,12 @@ def test_write_response_without_client_not_kept(driver: AccessoryDriver) -> None } no_client: Any = None - response = driver.set_characteristics(request, no_client) - - assert response is not None - assert response[HAP_REPR_CHARS][0][HAP_REPR_VALUE] == 7 - assert driver._write_responses == {} + # Answered at once, optimistically: the answer is read back instead. + assert driver.set_characteristics(request, no_client) is None + await run_scheduled_jobs() + # The virtual connection of no client in particular pairs up the + # direct write and a direct read, like any client address does. + assert _read(driver, f"{acc.aid}.{acc.iid_manager.get_iid(char)}", None) == 7 @pytest.mark.parametrize("reader", [WRITER, OTHER_CONTROLLER], ids=["writer", "other"]) @@ -1861,18 +2187,18 @@ def test_write_response_without_client_not_kept(driver: AccessoryDriver) -> None pytest.param({HAP_REPR_WRITE_RESPONSE: False}, id="declined"), ], ) -def test_written_value_readable_without_write_response( +async def test_written_value_readable_without_write_response( driver: AccessoryDriver, reader: Any, query: dict[str, Any] ) -> None: """Without a write response the written value is read by every controller.""" acc, char, char_id = _add_write_response_char(driver, False) - _write(driver, acc, char, **{HAP_REPR_VALUE: 5, **query}) + await _write(driver, acc, char, **{HAP_REPR_VALUE: 5, **query}) assert _read(driver, char_id, reader) == 5 -def test_service_callbacks(driver: AccessoryDriver) -> None: +async def test_service_callbacks(driver: AccessoryDriver) -> None: bridge = Bridge(driver, "mybridge") acc = Accessory(driver, "TestAcc", aid=2) acc2 = UnavailableAccessory(driver, "TestAcc2", aid=3) @@ -1910,7 +2236,7 @@ def test_service_callbacks(driver: AccessoryDriver) -> None: driver.add_accessory(bridge) - response = driver.set_characteristics( + response = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -1936,14 +2262,17 @@ def test_service_callbacks(driver: AccessoryDriver) -> None: ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert response is None mock_callback2.assert_called_with({"On": True, "Brightness": 12}) mock_callback.assert_called_with({"On": True, "Brightness": 88}) - get_chars = driver.get_characteristics( - [f"{acc.aid}.{char_on_iid}", f"{acc2.aid}.{char_on2_iid}"] + get_chars = await driver._get_characteristics_for_controller( + [f"{acc.aid}.{char_on_iid}", f"{acc2.aid}.{char_on2_iid}"], + "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert get_chars == { "characteristics": [ @@ -1956,13 +2285,15 @@ def _fail_func() -> NoReturn: raise ValueError char_brightness.getter_callback = _fail_func - get_chars = driver.get_characteristics( + get_chars = await driver._get_characteristics_for_controller( [ f"{acc.aid}.{char_on_iid}", f"{acc2.aid}.{char_on2_iid}", f"{acc2.aid}.{char_brightness_iid}", f"{acc.aid}.{char_brightness2_iid}", - ] + ], + "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert get_chars == { "characteristics": [ @@ -1974,7 +2305,7 @@ def _fail_func() -> NoReturn: } -def test_service_callbacks_partial_failure(driver: AccessoryDriver) -> None: +async def test_service_callbacks_partial_failure(driver: AccessoryDriver) -> None: bridge = Bridge(driver, "mybridge") acc = Accessory(driver, "TestAcc", aid=2) acc2 = UnavailableAccessory(driver, "TestAcc2", aid=3) @@ -2014,7 +2345,7 @@ def fail_callback(*_: Any) -> NoReturn: driver.add_accessory(bridge) - response = driver.set_characteristics( + response = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -2040,6 +2371,7 @@ def fail_callback(*_: Any) -> NoReturn: ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) mock_callback2.assert_called_with({"On": True, "Brightness": 12}) @@ -2069,7 +2401,9 @@ def fail_callback(*_: Any) -> NoReturn: } -def test_mixing_service_char_callbacks_partial_failure(driver: AccessoryDriver) -> None: +async def test_mixing_service_char_callbacks_partial_failure( + driver: AccessoryDriver, +) -> None: bridge = Bridge(driver, "mybridge") acc = Accessory(driver, "TestAcc", aid=2) acc2 = UnavailableAccessory(driver, "TestAcc2", aid=3) @@ -2108,7 +2442,7 @@ def fail_callback(*_: Any) -> NoReturn: driver.add_accessory(bridge) - response = driver.set_characteristics( + response = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -2134,6 +2468,7 @@ def fail_callback(*_: Any) -> NoReturn: ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert response == { @@ -2190,7 +2525,7 @@ def setup_message(self) -> None: assert driver.loop.is_closed() -def test_accessory_level_callbacks(driver: AccessoryDriver) -> None: +async def test_accessory_level_callbacks(driver: AccessoryDriver) -> None: bridge = Bridge(driver, "mybridge") acc = Accessory(driver, "TestAcc", aid=2) acc2 = UnavailableAccessory(driver, "TestAcc2", aid=3) @@ -2234,7 +2569,7 @@ def test_accessory_level_callbacks(driver: AccessoryDriver) -> None: driver.add_accessory(bridge) - response = driver.set_characteristics( + response = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -2265,6 +2600,7 @@ def test_accessory_level_callbacks(driver: AccessoryDriver) -> None: ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert response is None @@ -2279,7 +2615,9 @@ def test_accessory_level_callbacks(driver: AccessoryDriver) -> None: ) -def test_accessory_level_callbacks_with_a_failure(driver: AccessoryDriver) -> None: +async def test_accessory_level_callbacks_with_a_failure( + driver: AccessoryDriver, +) -> None: bridge = Bridge(driver, "mybridge") acc = Accessory(driver, "TestAcc", aid=2) acc2 = UnavailableAccessory(driver, "TestAcc2", aid=3) @@ -2323,7 +2661,7 @@ def test_accessory_level_callbacks_with_a_failure(driver: AccessoryDriver) -> No driver.add_accessory(bridge) - response = driver.set_characteristics( + response = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -2354,6 +2692,7 @@ def test_accessory_level_callbacks_with_a_failure(driver: AccessoryDriver) -> No ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) mock_callback.assert_called_with( @@ -2549,7 +2888,9 @@ def get_pushed_events(self) -> set[Any]: # intentionally not a HAPServer subclass. driver.http_server = HapServerMock() # ty: ignore[invalid-assignment] driver.loop = LoopMock() - driver.topics = {"mocktopic": {"client1", "client2", "client3"}} + driver.topics = { # ty: ignore[invalid-assignment] + "mocktopic": {"client1", "client2", "client3"} + } driver.async_send_event("mocktopic", "bytedata", "client1", True) # ty: ignore[invalid-argument-type] # Only client2 and client3 get the event when client1 sent it @@ -2563,14 +2904,14 @@ def get_pushed_events(self) -> set[Any]: def test_async_subscribe_client_topic(driver: AccessoryDriver) -> None: """Test subscribe and unsubscribe.""" - addr_info = ("1.2.3.4", 5) + connection = driver._connection_of(("1.2.3.4", 5)) topic = "any" assert driver.topics == {} - driver.async_subscribe_client_topic(addr_info, topic, True) - assert driver.topics == {topic: {addr_info}} - driver.async_subscribe_client_topic(addr_info, topic, False) + driver.async_subscribe_client_topic(connection, topic, True) + assert driver.topics == {topic: {connection}} + driver.async_subscribe_client_topic(connection, topic, False) assert driver.topics == {} - driver.async_subscribe_client_topic(addr_info, "invalid", False) + driver.async_subscribe_client_topic(connection, "invalid", False) assert driver.topics == {} @@ -2917,20 +3258,25 @@ def test_derive_session_key(driver: AccessoryDriver, client: Any) -> None: """Test keys are derived only from the session key of an encrypted connection.""" driver.add_accessory(Accessory(driver, "TestAcc")) salt, info = b"salt", b"info" - assert driver.derive_session_key(client, salt, info) is None + unknown = HAPConnectionHandle(client, 4096) + assert driver.derive_session_key(unknown, salt, info) is None connection = _hap_connection(driver, client) - assert driver.derive_session_key(client, salt, info) is None + handle = connection.connection_handle + assert handle is not None + assert driver.derive_session_key(handle, salt, info) is None shared_key = os.urandom(32) connection._shared_key = shared_key - key = driver.derive_session_key(client, salt, info) + key = driver.derive_session_key(handle, salt, info) assert key == hap_hkdf(shared_key, salt, info) assert key != shared_key - assert driver.derive_session_key(("10.0.0.9", 5001), salt, info) is None + # A connection that reuses the address of another never matches it. + reused = HAPConnectionHandle(client, 8192) + assert driver.derive_session_key(reused, salt, info) is None connection.close() - assert driver.derive_session_key(client, salt, info) is None + assert driver.derive_session_key(handle, salt, info) is None def test_derive_session_key_without_client_addr(driver: AccessoryDriver) -> None: @@ -2938,6 +3284,9 @@ def test_derive_session_key_without_client_addr(driver: AccessoryDriver) -> None driver.add_accessory(Accessory(driver, "TestAcc")) _hap_connection(driver, None, os.urandom(32)) assert driver.derive_session_key(None, b"salt", b"info") is None + assert ( + driver.derive_session_key(driver._connection_of(None), b"salt", b"info") is None + ) def test_pairing_rate_limit_lockout_and_reset(driver: AccessoryDriver) -> None: @@ -2971,11 +3320,12 @@ def test_pairing_rate_limit_lockout_and_reset(driver: AccessoryDriver) -> None: def test_prepare_bounds_prepared_writes(driver: AccessoryDriver) -> None: """Verify the TTL is capped and pending writes per client are bounded.""" client_addr = ("1.2.3.4", 5) + connection = driver._connection_of(client_addr) # An absurd TTL is clamped to the maximum. driver.prepare({HAP_REPR_TTL: 10_000_000_000, HAP_REPR_PID: 1}, client_addr) assert ( - driver.prepared_writes[client_addr][1] - time.monotonic() + driver.prepared_writes[connection][1] - time.monotonic() <= MAX_PREPARED_WRITE_TTL_SECONDS ) @@ -2984,7 +3334,7 @@ def test_prepare_bounds_prepared_writes(driver: AccessoryDriver) -> None: for pid in range(MAX_PREPARED_WRITES_PER_CLIENT + 5): driver.prepare({HAP_REPR_TTL: 10_000, HAP_REPR_PID: pid}, client_addr) - pending = driver.prepared_writes[client_addr] + pending = driver.prepared_writes[connection] assert len(pending) == MAX_PREPARED_WRITES_PER_CLIENT # The earliest-registered pids were evicted, the latest kept. assert 0 not in pending @@ -3007,13 +3357,13 @@ def _add_read_back_char(driver: AccessoryDriver) -> tuple[Accessory, Characteris pytest.param(OTHER_CONTROLLER, 0, id="other-controller"), ], ) -def test_read_back_response_only_for_writer( +async def test_read_back_response_only_for_writer( driver: AccessoryDriver, reader: Any, expected: int ) -> None: """Only the writing controller reads back what the setter answered.""" acc, char = _add_read_back_char(driver) - assert _write(driver, acc, char, **{HAP_REPR_VALUE: 5}) is None + assert await _write(driver, acc, char, **{HAP_REPR_VALUE: 5}) is None assert _read(driver, f"{acc.aid}.{acc.iid_manager.get_iid(char)}", reader) == ( expected @@ -3022,7 +3372,7 @@ def test_read_back_response_only_for_writer( assert acc_rep[HAP_REPR_SERVICES][-1][HAP_REPR_CHARS][0][HAP_REPR_VALUE] == 0 -def test_read_back_prefers_the_returned_answer(driver: AccessoryDriver) -> None: +async def test_read_back_prefers_the_returned_answer(driver: AccessoryDriver) -> None: """The answer a setter returns wins over a value it sets itself.""" acc, char = _add_read_back_char(driver) @@ -3032,7 +3382,7 @@ def _setter(value: int) -> int: char.setter_callback = _setter - assert _write(driver, acc, char, **{HAP_REPR_VALUE: 5}) is None + assert await _write(driver, acc, char, **{HAP_REPR_VALUE: 5}) is None char_id = f"{acc.aid}.{acc.iid_manager.get_iid(char)}" assert _read(driver, char_id, WRITER) == 7 @@ -3046,7 +3396,7 @@ def _setter(value: int) -> int: pytest.param(OTHER_CONTROLLER, 0, id="other-controller"), ], ) -def test_read_back_value_set_by_setter_only_for_writer( +async def test_read_back_value_set_by_setter_only_for_writer( driver: AccessoryDriver, reader: Any, expected: int ) -> None: """A value the setter sets itself on a read back char stays with the writer.""" @@ -3057,7 +3407,7 @@ def _setter(value: int) -> None: char.setter_callback = _setter - assert _write(driver, acc, char, **{HAP_REPR_VALUE: 5}) is None + assert await _write(driver, acc, char, **{HAP_REPR_VALUE: 5}) is None assert _read(driver, f"{acc.aid}.{acc.iid_manager.get_iid(char)}", reader) == ( expected @@ -3085,14 +3435,14 @@ async def test_async_read_back_response(driver: AccessoryDriver) -> None: pytest.param(5, MagicMock(return_value=None), id="setter-does-nothing"), ], ) -def test_read_back_without_answer_keeps_nothing_for_writer( +async def test_read_back_without_answer_keeps_nothing_for_writer( driver: AccessoryDriver, value: Any, setter: MagicMock ) -> None: """Neither the former value nor the request is kept as the writer's answer.""" acc, char = _add_read_back_char(driver) char.setter_callback = setter - _write(driver, acc, char, **{HAP_REPR_VALUE: value}) + await _write(driver, acc, char, **{HAP_REPR_VALUE: value}) char.set_value(3) assert _read(driver, f"{acc.aid}.{acc.iid_manager.get_iid(char)}", WRITER) == 3 @@ -3105,14 +3455,15 @@ async def test_connection_lost_without_accessory(driver: AccessoryDriver) -> Non """Test a closed connection before an accessory was added is cleaned up.""" driver.loop = asyncio.get_running_loop() assert driver.accessory is None - driver.prepared_writes[CLIENT] = {1: 0.0} - driver._write_responses[CLIENT] = {} + connection = driver._connection_of(CLIENT) + driver.prepared_writes[connection] = {1: 0.0} + driver._write_responses[connection] = {} driver.connection_lost(CLIENT) await asyncio.sleep(0) - assert CLIENT not in driver.prepared_writes - assert CLIENT not in driver._write_responses + assert connection not in driver.prepared_writes + assert connection not in driver._write_responses def test_connection_lost_tells_the_accessory(driver: AccessoryDriver) -> None: @@ -3130,10 +3481,11 @@ def test_connection_lost_logs_accessory_errors( """Test a failing accessory does not break the connection cleanup.""" acc = Accessory(driver, "TestAcc") driver.add_accessory(acc) - driver.prepared_writes[CLIENT] = {} + connection = driver._connection_of(CLIENT) + driver.prepared_writes[connection] = {} with patch.object(acc, "client_disconnected", side_effect=RuntimeError): driver.connection_lost(CLIENT) - assert CLIENT not in driver.prepared_writes + assert connection not in driver.prepared_writes assert "TestAcc failed to handle a closed connection" in caplog.text diff --git a/tests/test_admin_only.py b/tests/test_admin_only.py index f63f2832..dd80632c 100644 --- a/tests/test_admin_only.py +++ b/tests/test_admin_only.py @@ -1,5 +1,6 @@ """Tests for characteristics restricted to admin controllers.""" +import asyncio from collections.abc import Callable, Iterator import io import json @@ -34,6 +35,7 @@ ) from pyhap.encoder import AccessoryEncoder from pyhap.service import Service +from tests.conftest import run_scheduled_jobs CLIENT = ("1.2.3.4", 5000) ADMIN = UUID("7d0d1ee9-46fe-4a56-a115-69df3f6860c1") @@ -153,7 +155,7 @@ def chars(driver: AccessoryDriver) -> Iterator[dict[str, SensorChar]]: "unrestricted_unknown_controller", ], ) -def test_admin_only_write( +async def test_admin_only_write( driver: AccessoryDriver, chars: dict[str, SensorChar], name: str, @@ -162,12 +164,16 @@ def test_admin_only_write( calls: int, ) -> None: """Test only admins may write a characteristic restricted to them.""" + driver.loop = asyncio.get_running_loop() char = chars[name] response = driver.set_characteristics(_write(char), CLIENT, client_uuid=client_uuid) + await run_scheduled_jobs() assert response == _response(char, status) assert char.setter.call_count == calls + if calls: + char.setter.assert_called_with(True) def _demote(driver: AccessoryDriver) -> None: @@ -179,12 +185,13 @@ def _remove(driver: AccessoryDriver) -> None: @pytest.mark.parametrize("change", [_demote, _remove], ids=["demoted", "removed"]) -def test_admin_change_applies_to_open_session( +async def test_admin_change_applies_to_open_session( driver: AccessoryDriver, chars: dict[str, SensorChar], change: Callable[[AccessoryDriver], None], ) -> None: """Test a controller that loses admin is refused on its next write.""" + driver.loop = asyncio.get_running_loop() driver.pair(str(OTHER_ADMIN).encode(), b"other-key", HAP_PERMISSIONS.ADMIN) char = chars["MotionEnabled"] assert driver.set_characteristics(_write(char), CLIENT, client_uuid=ADMIN) is None @@ -194,13 +201,15 @@ def test_admin_change_applies_to_open_session( assert driver.set_characteristics( _write(char), CLIENT, client_uuid=ADMIN ) == _response(char, REFUSED) + await run_scheduled_jobs() char.setter.assert_called_once_with(True) -def test_legacy_state_pairs_everyone_as_admin( +async def test_legacy_state_pairs_everyone_as_admin( driver: AccessoryDriver, chars: dict[str, SensorChar] ) -> None: """Test controllers from a state file without permissions are admins.""" + driver.loop = asyncio.get_running_loop() stored = io.StringIO() AccessoryEncoder.persist(stored, driver.state) legacy = json.loads(stored.getvalue()) @@ -209,18 +218,20 @@ def test_legacy_state_pairs_everyone_as_admin( char = chars["MotionEnabled"] assert driver.set_characteristics(_write(char), CLIENT, client_uuid=USER) is None + await run_scheduled_jobs() char.setter.assert_called_once_with(True) @pytest.mark.parametrize("name", ["Secret", "MotionEnabled"]) @pytest.mark.parametrize("client_uuid", [ADMIN, USER], ids=["admin", "user"]) -def test_admin_only_read_not_refused( +async def test_admin_only_read_not_refused( driver: AccessoryDriver, chars: dict[str, SensorChar], name: str, client_uuid: UUID, ) -> None: """Test reads are not restricted, also not when the restriction lists read.""" + driver.loop = asyncio.get_running_loop() char = chars[name] handler = hap_handler.HAPServerHandler(driver, CLIENT) handler.is_encrypted = True @@ -229,6 +240,8 @@ def test_admin_only_read_not_refused( handler.parsed_url = urlparse(f"/characteristics?id={char.aid}.{char.iid}") handler.handle_get_characteristics() + assert handler.response.task is not None + await handler.response.task assert handler.response.status_code == 200 assert json.loads(handler.response.body) == { @@ -260,7 +273,9 @@ def test_admin_only_event_subscription_allowed( response = driver.set_characteristics(query, CLIENT, client_uuid=client_uuid) assert response is None - subscribe.assert_called_once_with(CLIENT, get_topic(char.aid, char.iid), True) + subscribe.assert_called_once_with( + driver._connection_of(CLIENT), get_topic(char.aid, char.iid), True + ) char.setter.assert_not_called() @@ -295,8 +310,10 @@ def test_admin_only_null_write_reaches_no_setter( assert driver.accessory is not None service = driver.accessory.get_service("MotionSensor") assert service is not None - service.setter_callback = MagicMock() - driver.accessory.setter_callback = MagicMock() + service_setter = MagicMock() + service.setter_callback = service_setter + acc_setter = MagicMock() + driver.accessory.setter_callback = acc_setter query = { HAP_REPR_CHARS: [ {HAP_REPR_AID: char.aid, HAP_REPR_IID: char.iid, HAP_REPR_VALUE: None} @@ -307,11 +324,11 @@ def test_admin_only_null_write_reaches_no_setter( assert response == _response(char, REFUSED) char.setter.assert_not_called() - service.setter_callback.assert_not_called() - driver.accessory.setter_callback.assert_not_called() + service_setter.assert_not_called() + acc_setter.assert_not_called() -def _write_through_handler( +async def _write_through_handler( driver: AccessoryDriver, char: SensorChar, client_uuid: UUID ) -> hap_handler.HAPResponse: """Write True to ``char`` through a HAP handler of ``client_uuid``.""" @@ -321,29 +338,31 @@ def _write_through_handler( handler.response = hap_handler.HAPResponse() handler.request_body = json.dumps(_write(char)).encode() handler.handle_set_characteristics() + assert handler.response.task is not None + await handler.response.task return handler.response -def test_handler_writes_as_admin( +async def test_handler_writes_as_admin( driver: AccessoryDriver, chars: dict[str, SensorChar] ) -> None: """Test the HAP handler writes as the admin controller of its session.""" char = chars["MotionEnabled"] - response = _write_through_handler(driver, char, ADMIN) + response = await _write_through_handler(driver, char, ADMIN) assert response.status_code == 204 assert response.body == b"" char.setter.assert_called_once_with(True) -def test_handler_writes_as_user( +async def test_handler_writes_as_user( driver: AccessoryDriver, chars: dict[str, SensorChar] ) -> None: """Test the HAP handler writes as the regular controller of its session.""" char = chars["MotionEnabled"] - response = _write_through_handler(driver, char, USER) + response = await _write_through_handler(driver, char, USER) assert response.status_code == 207 assert json.loads(response.body) == _response(char, REFUSED) diff --git a/tests/test_camera.py b/tests/test_camera.py index 4ac62d27..60056531 100644 --- a/tests/test_camera.py +++ b/tests/test_camera.py @@ -2,6 +2,7 @@ import asyncio import base64 +import inspect import ipaddress import logging import socket @@ -9,12 +10,15 @@ from typing import Any, cast from unittest.mock import AsyncMock, Mock, PropertyMock, patch from uuid import UUID +import warnings import pylibsrtp import pytest from pyhap import camera, tlv from pyhap.camera_talkback import TalkbackReceiverProtocol +from pyhap.characteristic import _LegacyCallbackDelegateWrapper +from tests.conftest import client_write # A Setup Endpoints request of a controller at 192.168.1.114. _SETUP_ENDPOINTS_REQUEST = ( @@ -59,6 +63,29 @@ } +def test_camera_wiring_is_delegate_based(mock_driver: Any) -> None: + """The camera wires no legacy callbacks, so it never trips its warning.""" + options = {**_OPTIONS, "recording": True, "global_operating_mode": []} + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + acc = camera.Camera(options, mock_driver, "Camera") + + streaming_status = _char_of(acc, "CameraRTPStreamManagement", "StreamingStatus") + status_active = _char_of(acc, "MotionSensor", "StatusActive") + for char in (streaming_status, status_active): + # Not the legacy callback wrapper: the camera wires delegates only, + # so it never trips its own deprecation warning. + assert not isinstance(char.delegate, _LegacyCallbackDelegateWrapper) + assert char.delegate is not None + + +def _char_of(acc: Any, service_name: str, char_name: str) -> Any: + """The characteristic ``char_name`` of the camera's service.""" + service = acc.get_service(service_name) + assert service is not None # noqa: S101 + return service.get_characteristic(char_name) + + def test_init(mock_driver: Any) -> None: """Test that the camera init properly computes TLV values""" acc = camera.Camera(_OPTIONS, mock_driver, "Camera") @@ -82,7 +109,7 @@ def test_init(mock_driver: Any) -> None: ) -def test_setup_endpoints(mock_driver: Any) -> None: +async def test_setup_endpoints(mock_driver: Any) -> None: """Test that the SetupEndpoint response is computed correctly""" set_endpoint_res = ( "ARCszGzBBWNFFY2pdLRQkAaRAgEAAxoBAQACDTE5Mi4xNjguMS4yMjYDAjPFBAK" @@ -94,14 +121,14 @@ def test_setup_endpoints(mock_driver: Any) -> None: management = acc.get_service("CameraRTPStreamManagement") assert management is not None setup_endpoints = management.get_characteristic("SetupEndpoints") - response = setup_endpoints.client_update_value(_SETUP_ENDPOINTS_REQUEST) + response = await client_write(setup_endpoints, _SETUP_ENDPOINTS_REQUEST) assert response[:171] == set_endpoint_res[:171] # Without the driver nothing puts the former value back. assert setup_endpoints.get_value() == response -def test_setup_endpoints_does_not_log_srtp_keys( +async def test_setup_endpoints_does_not_log_srtp_keys( mock_driver: Any, caplog: pytest.LogCaptureFixture ) -> None: """Verify the negotiated SRTP key material is not written to the logs.""" @@ -111,7 +138,7 @@ def test_setup_endpoints_does_not_log_srtp_keys( setup_endpoints = management.get_characteristic("SetupEndpoints") with caplog.at_level(logging.DEBUG, logger="pyhap.camera"): - setup_endpoints.client_update_value(_SETUP_ENDPOINTS_REQUEST) + await client_write(setup_endpoints, _SETUP_ENDPOINTS_REQUEST) # The endpoint configuration was logged at DEBUG level, but without any # of the SRTP master key/salt material in it. @@ -180,7 +207,7 @@ async def subprocess_exec(*args: Any, **kwargs: Any) -> Mock: assert acc.streaming_status == camera.STREAMING_STATUS["AVAILABLE"] -def test_no_talkback_by_default(mock_driver: Any) -> None: +async def test_no_talkback_by_default(mock_driver: Any) -> None: """Without the ``talkback`` option, no Speaker service is added and SetupEndpoints keeps echoing the controller's port back (unchanged, pre-existing behavior for accessories that don't opt in). @@ -191,7 +218,7 @@ def test_no_talkback_by_default(mock_driver: Any) -> None: management = acc.get_service("CameraRTPStreamManagement") assert management is not None setup_endpoints = management.get_characteristic("SetupEndpoints") - setup_endpoints.client_update_value(_SETUP_ENDPOINTS_REQUEST) + await client_write(setup_endpoints, _SETUP_ENDPOINTS_REQUEST) session_id = list(acc.sessions)[0] assert acc.sessions[session_id]["audio_backchannel"] is None @@ -245,7 +272,7 @@ def test_talkback_enabled_adds_speaker_service(mock_driver: Any) -> None: assert speaker.get_characteristic("Mute").get_value() is False -def test_setup_endpoints_reports_real_port_when_talkback_enabled( +async def test_setup_endpoints_reports_real_port_when_talkback_enabled( mock_driver: Any, ) -> None: """The accessory must report a real local listening port for the audio @@ -258,7 +285,7 @@ def test_setup_endpoints_reports_real_port_when_talkback_enabled( management = acc.get_service("CameraRTPStreamManagement") assert management is not None setup_endpoints = management.get_characteristic("SetupEndpoints") - response = setup_endpoints.client_update_value(_SETUP_ENDPOINTS_REQUEST) + response = await client_write(setup_endpoints, _SETUP_ENDPOINTS_REQUEST) session_id = list(acc.sessions)[0] receiver = acc.sessions[session_id]["audio_backchannel"] @@ -290,7 +317,7 @@ def talkback_audio_received(self, session_id: Any, payload: Any) -> None: management = acc.get_service("CameraRTPStreamManagement") assert management is not None setup_endpoints = management.get_characteristic("SetupEndpoints") - setup_endpoints.client_update_value(_SETUP_ENDPOINTS_REQUEST) + await client_write(setup_endpoints, _SETUP_ENDPOINTS_REQUEST) session_id = list(acc.sessions)[0] receiver = acc.sessions[session_id]["audio_backchannel"] @@ -333,7 +360,7 @@ def talkback_audio_received(self, session_id: Any, payload: Any) -> None: receiver.stop() -def test_custom_talkback_receiver(mock_driver: Any) -> None: +async def test_custom_talkback_receiver(mock_driver: Any) -> None: local_port_mock = Mock() start_mock = Mock() stop_mock = Mock() @@ -365,7 +392,7 @@ def create_talkback_receiver( management = acc.get_service("CameraRTPStreamManagement") assert management is not None setup_endpoints = management.get_characteristic("SetupEndpoints") - setup_endpoints.client_update_value(_SETUP_ENDPOINTS_REQUEST) + await client_write(setup_endpoints, _SETUP_ENDPOINTS_REQUEST) session_id = list(acc.sessions)[0] receiver = acc.sessions[session_id]["audio_backchannel"] @@ -524,15 +551,16 @@ def _setup_request_with(address_tlv: bytes, crypto: bytes = b"\x00") -> str: (b"fd00:0:0:0:0:0:0:1", True, "fd00::1"), ], ) -def test_setup_endpoints_accepts_addresses( +async def test_setup_endpoints_accepts_addresses( mock_driver: Any, address: bytes, is_ipv6: bool, expected: str ) -> None: """Test addresses of the announced version are accepted in canonical form.""" acc = camera.Camera(_OPTIONS, mock_driver, "Camera") management = acc.get_service("CameraRTPStreamManagement") assert management is not None - management.get_characteristic("SetupEndpoints").client_update_value( - _setup_request(address, is_ipv6) + await client_write( + management.get_characteristic("SetupEndpoints"), + _setup_request(address, is_ipv6), ) assert acc.sessions[_SESSION_ID]["address"] == expected @@ -550,7 +578,7 @@ def test_setup_endpoints_accepts_addresses( (b"", False), ], ) -def test_setup_endpoints_refuses_addresses( +async def test_setup_endpoints_refuses_addresses( mock_driver: Any, address: bytes, is_ipv6: bool ) -> None: """Test other addresses answer an error and set up no session.""" @@ -558,7 +586,7 @@ def test_setup_endpoints_refuses_addresses( management = acc.get_service("CameraRTPStreamManagement") assert management is not None setup_endpoints = management.get_characteristic("SetupEndpoints") - answer = setup_endpoints.client_update_value(_setup_request(address, is_ipv6)) + answer = await client_write(setup_endpoints, _setup_request(address, is_ipv6)) assert acc.sessions == {} assert tlv.decode(answer, from_base64=True) == { camera.SETUP_TYPES["SESSION_ID"]: _SESSION_ID.bytes, @@ -595,7 +623,7 @@ def test_setup_endpoints_refuses_addresses( ], ids=["missing_audio_port", "short_video_port", "empty_crypto"], ) -def test_setup_endpoints_refuses_malformed( +async def test_setup_endpoints_refuses_malformed( mock_driver: Any, request_value: str ) -> None: """Test a malformed write answers an error and sets up no session.""" @@ -603,7 +631,7 @@ def test_setup_endpoints_refuses_malformed( management = acc.get_service("CameraRTPStreamManagement") assert management is not None setup_endpoints = management.get_characteristic("SetupEndpoints") - answer = setup_endpoints.client_update_value(request_value) + answer = await client_write(setup_endpoints, request_value) assert acc.sessions == {} assert tlv.decode(answer, from_base64=True) == { camera.SETUP_TYPES["SESSION_ID"]: _SESSION_ID.bytes, @@ -618,7 +646,7 @@ def test_setup_endpoints_refuses_malformed( (b"192.168.1.114", "Streaming is turned off"), ], ) -def test_setup_endpoints_refuses_address_before_streaming_off( +async def test_setup_endpoints_refuses_address_before_streaming_off( mock_driver: Any, caplog: pytest.LogCaptureFixture, address: bytes, @@ -630,12 +658,12 @@ def test_setup_endpoints_refuses_address_before_streaming_off( ) operating_mode = acc.get_service("CameraGlobalOperatingMode") assert operating_mode is not None - operating_mode.get_characteristic("HomeKitCameraActive").client_update_value(0) + await client_write(operating_mode.get_characteristic("HomeKitCameraActive"), 0) management = acc.get_service("CameraRTPStreamManagement") assert management is not None setup_endpoints = management.get_characteristic("SetupEndpoints") with caplog.at_level(logging.INFO): - answer = setup_endpoints.client_update_value(_setup_request(address, False)) + answer = await client_write(setup_endpoints, _setup_request(address, False)) assert message in caplog.text assert acc.sessions == {} assert tlv.decode(answer, from_base64=True) == { @@ -726,7 +754,7 @@ def _read_setup_endpoints(driver: Any, acc: camera.Camera, client_addr: Any) -> [camera.Camera, _WrappingCamera, _ReturningCamera, _SettingCamera], ids=["camera", "wrapping-subclass", "returning-subclass", "setting-subclass"], ) -def test_setup_endpoints_read_back_by_writer_only( +async def test_setup_endpoints_read_back_by_writer_only( driver: Any, camera_cls: type[camera.Camera], request_value: str, @@ -744,12 +772,11 @@ def test_setup_endpoints_read_back_by_writer_only( new_callable=PropertyMock, return_value=streaming_allowed, ): - assert ( - driver.set_characteristics( - _setup_endpoints_query(acc, request_value), _WRITER - ) - is None + result = driver._set_characteristics_for_controller( + _setup_endpoints_query(acc, request_value), _WRITER, 9.0 ) + assert inspect.isawaitable(result) + assert await result is None # The writer reads the answer, which carries a status, not its request. answer = tlv.decode(_read_setup_endpoints(driver, acc, _WRITER), from_base64=True) diff --git a/tests/test_camera_capabilities.py b/tests/test_camera_capabilities.py index ad7436fe..7d1e2e1c 100644 --- a/tests/test_camera_capabilities.py +++ b/tests/test_camera_capabilities.py @@ -22,6 +22,7 @@ HAP_SERVER_STATUS, ) from pyhap.util import base64_to_bytes, to_base64_str +from tests.conftest import client_write CAMERA_AID = 2 MAIN = UUID("00112233-4455-6677-8899-aabbccddeeff") @@ -187,7 +188,7 @@ async def test_motion_enabled(driver: Any) -> None: enabled = _char(camera, "MotionSensor", "MotionEnabled") camera.set_motion_detected(True) - enabled.client_update_value(False) + await client_write(enabled, False) camera.motion_enabled_changed.assert_called_once_with(False) assert camera.motion_enabled is False assert detected.value is False @@ -195,7 +196,7 @@ async def test_motion_enabled(driver: Any) -> None: assert detected.value is False assert _contributing(camera) == b"" - enabled.client_update_value(True) + await client_write(enabled, True) camera.motion_enabled_changed.assert_called_with(True) camera.set_motion_detected(True) assert detected.value is True @@ -207,13 +208,13 @@ async def test_motion_zones(driver: Any) -> None: camera.motion_zones_changed = MagicMock() zones = _char(camera, "CameraMotionZones", "CameraZones") - _char(camera, "CameraMotionZones", "Active").client_update_value(1) + await client_write(_char(camera, "CameraMotionZones", "Active"), 1) assert camera.motion_zones_active is True - zones.client_update_value(to_base64_str(ZONES.encode())) + await client_write(zones, to_base64_str(ZONES.encode())) assert camera.camera_zones == ZONES assert camera.motion_zones_changed.call_count == 2 - zones.client_update_value("") + await client_write(zones, "") assert camera.camera_zones is None assert camera.motion_zones_changed.call_count == 3 @@ -227,12 +228,12 @@ async def test_motion_zones_malformed( ) -> None: """Test a malformed zones write fails and keeps the previous zones.""" camera = _camera(driver, sensors=SENSORS) - _char(camera, "CameraMotionZones", "Active").client_update_value(1) + await client_write(_char(camera, "CameraMotionZones", "Active"), 1) zones = _char(camera, "CameraMotionZones", "CameraZones") - zones.client_update_value(kept) + await client_write(zones, kept) camera.motion_zones_changed = MagicMock() with pytest.raises(ValueError): - zones.client_update_value(value) + await client_write(zones, value) camera.motion_zones_changed.assert_not_called() assert zones.value == kept assert camera.camera_zones == previous @@ -254,15 +255,16 @@ async def test_motion_zones_malformed_write(driver: Any) -> None: zones = _char(camera, "CameraMotionZones", "CameraZones") iid = camera.iid_manager.get_iid(zones) kept = to_base64_str(ZONES.encode()) - zones.client_update_value(kept) + await client_write(zones, kept) - response = driver.set_characteristics( + response = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ {HAP_REPR_AID: 1, HAP_REPR_IID: iid, HAP_REPR_VALUE: "AQ=="} ] }, ("127.0.0.1", 5000), + 9.0, ) assert response is not None assert response[HAP_REPR_CHARS][0][HAP_REPR_STATUS] == ( @@ -275,11 +277,11 @@ async def test_motion_zones_malformed_write(driver: Any) -> None: async def test_settings_survive_restart(driver: Any) -> None: """Test zones and motion settings are restored.""" camera = _camera(driver, sensors=SENSORS) - _char(camera, "CameraMotionZones", "Active").client_update_value(1) - _char(camera, "CameraMotionZones", "CameraZones").client_update_value( - to_base64_str(ZONES.encode()) + await client_write(_char(camera, "CameraMotionZones", "Active"), 1) + await client_write( + _char(camera, "CameraMotionZones", "CameraZones"), to_base64_str(ZONES.encode()) ) - _char(camera, "MotionSensor", "MotionEnabled").client_update_value(False) + await client_write(_char(camera, "MotionSensor", "MotionEnabled"), False) camera = _camera(driver, sensors=SENSORS) assert camera.motion_zones_active is True @@ -290,11 +292,11 @@ async def test_settings_survive_restart(driver: Any) -> None: async def test_reset_calls_hooks(driver: Any) -> None: """Test removing the last pairing tells the integration what changed.""" camera = _camera(driver, sensors=SENSORS) - _char(camera, "CameraMotionZones", "Active").client_update_value(1) - _char(camera, "CameraMotionZones", "CameraZones").client_update_value( - to_base64_str(ZONES.encode()) + await client_write(_char(camera, "CameraMotionZones", "Active"), 1) + await client_write( + _char(camera, "CameraMotionZones", "CameraZones"), to_base64_str(ZONES.encode()) ) - _char(camera, "MotionSensor", "MotionEnabled").client_update_value(False) + await client_write(_char(camera, "MotionSensor", "MotionEnabled"), False) camera.motion_zones_changed = MagicMock() camera.motion_enabled_changed = MagicMock() @@ -340,9 +342,9 @@ async def test_repeated_write_calls_hook_once( setattr(camera, hook, mock) char = _char(camera, service, name) - char.client_update_value(value) - char.client_update_value(value) - char.client_update_value(value) + await client_write(char, value) + await client_write(char, value) + await client_write(char, value) mock.assert_called_once_with(*args) @@ -361,7 +363,7 @@ async def test_write_of_current_value_calls_no_hook( mock = MagicMock() setattr(camera, hook, mock) - _char(camera, service, name).client_update_value(value) + await client_write(_char(camera, service, name), value) mock.assert_not_called() @@ -369,7 +371,7 @@ async def test_reset_hooks_see_reset_recording(driver: Any) -> None: """Test the hooks run after the recording state is reset as well.""" camera = _camera(driver, sensors=SENSORS, recording=True) _char(camera, "CameraRecordingManagement", "Active").client_update_value(1) - _char(camera, "CameraMotionZones", "Active").client_update_value(1) + await client_write(_char(camera, "CameraMotionZones", "Active"), 1) seen: list[bool] = [] camera.motion_zones_changed = lambda: seen.append(camera.recording_active) diff --git a/tests/test_camera_multi_tier.py b/tests/test_camera_multi_tier.py index d3dd2001..d00a2e0b 100644 --- a/tests/test_camera_multi_tier.py +++ b/tests/test_camera_multi_tier.py @@ -15,6 +15,7 @@ from pyhap.camera_stream import SessionState, StreamError from pyhap.camera_webrtc import WebRTCController from pyhap.util import base64_to_bytes, to_base64_str +from tests.conftest import client_write, connection_of MULTI_TIER = "CameraMultiTierRTPStreamManagement" WEBRTC = "CameraWebRTCStreamManagement" @@ -149,7 +150,7 @@ async def test_status_active(stream_camera: Callable[..., Camera]) -> None: camera.set_manually_disabled(True) assert _char(camera, MULTI_TIER, "StatusActive").value is False camera.set_manually_disabled(False) - _char(camera, MULTI_TIER, "StreamingEnabled").client_update_value(False) + await client_write(_char(camera, MULTI_TIER, "StreamingEnabled"), False) assert _char(camera, MULTI_TIER, "StatusActive").value is True await asyncio.sleep(0) assert _char(camera, MULTI_TIER, "StatusActive").value is False @@ -160,7 +161,7 @@ async def test_streaming_enabled_persisted( ) -> None: """Test the services' Streaming Enabled survive a restart.""" camera = stream_camera() - _char(camera, WEBRTC, "StreamingEnabled").client_update_value(False) + await client_write(_char(camera, WEBRTC, "StreamingEnabled"), False) restored = stream_camera() assert _char(restored, WEBRTC, "StreamingEnabled").value is False assert _char(restored, MULTI_TIER, "StreamingEnabled").value is True @@ -224,12 +225,19 @@ def _setup_request( ) +def _deadline(controller: MultiTierController) -> float: + """The deadline of a write, like the request's context carries it.""" + return asyncio.get_running_loop().time() + controller.hook_timeout + + async def _setup( camera: Camera, request: str | None = None, client: Any = CLIENT ) -> dict[bytes, Any]: """Write Setup Endpoints and decode the answer the writer reads back.""" controller = _controller(camera) - answer = await controller._set_setup_endpoints(request or _setup_request(), client) + answer = await controller._set_setup_endpoints( + request or _setup_request(), connection_of(client), _deadline(controller) + ) return tlv.decode(answer, from_base64=True) @@ -260,7 +268,9 @@ async def _streaming_control( ) -> int: """Write RTP Streaming Control and return the status of the answer.""" controller = _controller(camera) - answer = await controller._set_streaming_control(_control(command, **tiers), client) + answer = await controller._set_streaming_control( + _control(command, **tiers), connection_of(client), _deadline(controller) + ) status = tlv.decode(base64_to_bytes(answer))[b"\x02"] return int(status[0]) @@ -543,7 +553,10 @@ async def test_setup_busy_per_connection(stream_camera: Callable[..., Camera]) - async def test_malformed_setup(stream_camera: Callable[..., Camera]) -> None: """Test a Setup Endpoints write that does not decode answers an error.""" - answer = await _controller(stream_camera())._set_setup_endpoints("AQ==", CLIENT) + controller = _controller(stream_camera()) + answer = await controller._set_setup_endpoints( + "AQ==", connection_of(CLIENT), _deadline(controller) + ) assert base64_to_bytes(answer) == bytes.fromhex("020102") @@ -1000,7 +1013,10 @@ async def test_setup_after_stop(stream_camera: Callable[..., Camera]) -> None: async def test_malformed_control(stream_camera: Callable[..., Camera]) -> None: """Test a write that does not decode answers an error.""" - answer = await _controller(stream_camera())._set_streaming_control("AQ==", CLIENT) + controller = _controller(stream_camera()) + answer = await controller._set_streaming_control( + "AQ==", connection_of(CLIENT), _deadline(controller) + ) assert base64_to_bytes(answer) == bytes.fromhex("020104") diff --git a/tests/test_camera_operating_mode.py b/tests/test_camera_operating_mode.py index fd3f3488..a40c0c8e 100644 --- a/tests/test_camera_operating_mode.py +++ b/tests/test_camera_operating_mode.py @@ -13,7 +13,8 @@ from pyhap import camera as camera_module, hds_recording, tlv from pyhap.accessory_driver import AccessoryDriver from pyhap.camera import SETUP_STATUS, SETUP_TYPES, STREAMING_STATUS, Camera -from pyhap.characteristic import PROP_PERMISSIONS +from pyhap.characteristic import PROP_PERMISSIONS, _LegacyCallbackDelegateWrapper +from tests.conftest import client_write CAMERA_AID = 2 GLOBAL = "CameraGlobalOperatingMode" @@ -121,7 +122,10 @@ async def test_third_party_camera_active(driver: Any) -> None: camera.global_operating_mode_changed = MagicMock() char = _char(camera, GLOBAL, "ThirdPartyCameraActive") assert char.properties[PROP_PERMISSIONS] == ["pr", "ev"] - assert char.setter_callback is None + # Nothing is wired: the camera wires no legacy callback on the char. + assert isinstance(char.delegate, _LegacyCallbackDelegateWrapper) + assert char.delegate.getter_callback is None + assert char.delegate.setter_callback is None camera.set_third_party_camera_active(False) assert char.value is False assert camera.streaming_allowed is True @@ -143,7 +147,7 @@ async def test_writes_call_hook( camera = _camera(driver, global_operating_mode=OPTIONAL) camera.global_operating_mode_changed = MagicMock() camera.homekit_camera_active_changed = MagicMock() - _char(camera, GLOBAL, name).client_update_value(value) + await client_write(_char(camera, GLOBAL, name), value) camera.global_operating_mode_changed.assert_called_once_with(name, value) camera.homekit_camera_active_changed.assert_not_called() assert camera.streaming_allowed is streaming_allowed @@ -169,7 +173,7 @@ async def test_stream_start_needs_streaming_allowed( camera = _camera(driver, video=VIDEO, audio=AUDIO, global_operating_mode=[]) camera.start_stream = AsyncMock(return_value=True) camera.sessions[SESSION_ID] = {"id": SESSION_ID, "stream_idx": 0} - _char(camera, GLOBAL, "StreamingEnabled").client_update_value(enabled) + await client_write(_char(camera, GLOBAL, "StreamingEnabled"), enabled) await camera._start_stream( tlv.decode(START_REQUEST, from_base64=True), reconfigure=False @@ -215,9 +219,9 @@ async def test_setup_endpoints_needs_streaming_allowed( refuse streams, as before. """ camera = _camera(driver, video=VIDEO, audio=AUDIO, **options) - _char(camera, service, "HomeKitCameraActive").client_update_value(enabled) + await client_write(_char(camera, service, "HomeKitCameraActive"), enabled) setup = _char(camera, "CameraRTPStreamManagement", "SetupEndpoints") - answer = setup.client_update_value(SETUP_REQUEST) + answer = await client_write(setup, SETUP_REQUEST) response = tlv.decode(answer, from_base64=True) assert response[SETUP_TYPES["SESSION_ID"]] == SESSION_ID.bytes @@ -229,7 +233,7 @@ async def test_homekit_camera_active(driver: Any) -> None: """Test turning the camera off without recording.""" camera = _camera(driver, global_operating_mode=[]) camera.homekit_camera_active_changed = MagicMock() - _char(camera, GLOBAL, "HomeKitCameraActive").client_update_value(0) + await client_write(_char(camera, GLOBAL, "HomeKitCameraActive"), 0) camera.homekit_camera_active_changed.assert_called_once_with(False) assert camera.homekit_camera_active is False assert camera.streaming_allowed is False @@ -243,7 +247,7 @@ async def test_global_operating_mode_decides(driver: Any) -> None: camera._recording_stream = stream status_active = _char(camera, "MotionSensor", "StatusActive") - _char(camera, GLOBAL, "HomeKitCameraActive").client_update_value(0) + await client_write(_char(camera, GLOBAL, "HomeKitCameraActive"), 0) camera.homekit_camera_active_changed.assert_called_once_with(False) assert camera.homekit_camera_active is False assert status_active.get_value() is False @@ -264,14 +268,14 @@ async def test_last_camera_active_write_decides(driver: Any) -> None: active = _char(camera, GLOBAL, "HomeKitCameraActive") legacy = _char(camera, "CameraOperatingMode", "HomeKitCameraActive") - legacy.client_update_value(0) + await client_write(legacy, 0) assert camera.homekit_camera_active is False assert camera.streaming_allowed is False assert active.get_value() == 0 assert status_active.get_value() is False stream.close.assert_called_once_with(hds_recording.RecordingReason.NOT_ALLOWED) - active.client_update_value(1) + await client_write(active, 1) assert camera.homekit_camera_active is True assert camera.streaming_allowed is True assert legacy.get_value() == 1 @@ -302,7 +306,7 @@ async def test_turning_streaming_off_ends_streams( camera.sessions[SESSION_ID] = session_info camera._streaming_status[0] = STREAMING_STATUS["STREAMING"] - _char(camera, service, name).client_update_value(value) + await client_write(_char(camera, service, name), value) await asyncio.sleep(0) await asyncio.sleep(0) @@ -335,8 +339,8 @@ async def test_streams_kept_while_allowed(driver: Any) -> None: camera.stop_stream = AsyncMock() camera.sessions[SESSION_ID] = {"id": SESSION_ID, "stream_idx": 0} - _char(camera, GLOBAL, "NightVision").client_update_value(1) - _char(camera, GLOBAL, "HomeKitCameraActive").client_update_value(1) + await client_write(_char(camera, GLOBAL, "NightVision"), 1) + await client_write(_char(camera, GLOBAL, "HomeKitCameraActive"), 1) await asyncio.sleep(0) await asyncio.sleep(0) @@ -347,10 +351,10 @@ async def test_streams_kept_while_allowed(driver: Any) -> None: async def test_settings_survive_restart(driver: Any) -> None: """Test controller writes are restored, the device state is not.""" camera = _camera(driver, global_operating_mode=OPTIONAL) - _char(camera, GLOBAL, "HomeKitCameraActive").client_update_value(0) - _char(camera, GLOBAL, "StreamingEnabled").client_update_value(False) - _char(camera, GLOBAL, "CameraOperatingModeIndicator").client_update_value(False) - _char(camera, GLOBAL, "NightVision").client_update_value(True) + await client_write(_char(camera, GLOBAL, "HomeKitCameraActive"), 0) + await client_write(_char(camera, GLOBAL, "StreamingEnabled"), False) + await client_write(_char(camera, GLOBAL, "CameraOperatingModeIndicator"), False) + await client_write(_char(camera, GLOBAL, "NightVision"), True) camera.set_manually_disabled(True) camera.set_third_party_camera_active(False) @@ -426,9 +430,9 @@ async def test_repeated_write_calls_hook_once( setattr(camera, hook, mock) char = _char(camera, GLOBAL, name) - char.client_update_value(value) - char.client_update_value(value) - char.client_update_value(value) + await client_write(char, value) + await client_write(char, value) + await client_write(char, value) mock.assert_called_once_with(*args) @@ -438,8 +442,8 @@ async def test_classic_writes_call_hook_every_time(driver: Any) -> None: camera.homekit_camera_active_changed = MagicMock() char = _char(camera, "CameraOperatingMode", "HomeKitCameraActive") - char.client_update_value(0) - char.client_update_value(0) + await client_write(char, 0) + await client_write(char, 0) assert camera.homekit_camera_active_changed.call_args_list == [call(False)] * 2 diff --git a/tests/test_camera_stream.py b/tests/test_camera_stream.py index 14ca3257..fc5f5020 100644 --- a/tests/test_camera_stream.py +++ b/tests/test_camera_stream.py @@ -24,11 +24,18 @@ config_from_option, failure_status, ) +from pyhap.connection import HAPConnectionHandle +from tests.conftest import connection_of CLIENT = ("192.168.1.114", 50000) OTHER = ("192.168.1.115", 50000) +def _deadline(controller: StreamController[StreamSession]) -> float: + """The deadline of a request that arrives now, like the write context carries.""" + return asyncio.get_running_loop().time() + controller.hook_timeout + + @dataclass(frozen=True) class _Config: max_sessions: int = 5 @@ -64,7 +71,7 @@ async def test_hook_result( ) -> None: """Test a hook's result comes back and the session stays.""" session = add_session(CLIENT) - deadline = session_controller._deadline() + deadline = _deadline(session_controller) assert await session_controller._run_hook(session, "test", _hook(5), deadline) == 5 @@ -80,7 +87,7 @@ async def test_hook_timeout_ends_the_session( ) -> None: """Test a slow hook is cancelled, then the session is released once.""" session = add_session(CLIENT) - deadline = session_controller._deadline() + deadline = _deadline(session_controller) with pytest.raises(HookFailed) as failed: await session_controller._run_hook( @@ -114,7 +121,7 @@ async def test_hook_errors( with pytest.raises(HookFailed) as failed: await session_controller._run_hook( - session, "test", _raise(error), session_controller._deadline() + session, "test", _raise(error), _deadline(session_controller) ) assert failed.value.status == status @@ -134,7 +141,7 @@ async def test_failed_hook_may_end_the_session( session, "test", _raise(RuntimeError()), - session_controller._deadline(), + _deadline(session_controller), end_on_failure=True, first=True, ) @@ -152,7 +159,7 @@ async def test_end_releases_once( """Test ending twice releases a session the delegate saw exactly once.""" session = add_session(CLIENT) await session_controller._run_hook( - session, "test", _hook(), session_controller._deadline(), first=True + session, "test", _hook(), _deadline(session_controller), first=True ) first = session_controller._end(session, "first") @@ -187,7 +194,7 @@ async def test_end_waits_for_cancelled_hooks( session._delegated = True hook = asyncio.ensure_future( session_controller._run_hook( - session, "test", _never(), session_controller._deadline() + session, "test", _never(), _deadline(session_controller) ) ) await asyncio.sleep(0) @@ -229,7 +236,7 @@ async def test_release_failure_is_logged( assert await release_task is True assert message in caplog.text assert "after its timeout" not in caplog.text - assert session_controller._no_room(CLIENT) is None + assert session_controller._no_room(connection_of(CLIENT)) is None async def test_cancelled_request_ends_the_session( @@ -240,7 +247,7 @@ async def test_cancelled_request_ends_the_session( session = add_session(CLIENT) request = asyncio.ensure_future( session_controller._run_hook( - session, "test", _never(), session_controller._deadline() + session, "test", _never(), _deadline(session_controller) ) ) await asyncio.sleep(0) @@ -263,7 +270,7 @@ async def test_hook_of_ended_session( with pytest.raises(HookFailed): await session_controller._run_hook( - session, "test", hook, session_controller._deadline() + session, "test", hook, _deadline(session_controller) ) assert hook.cr_frame is None @@ -308,19 +315,43 @@ async def test_ownership( session = add_session(CLIENT) caplog.set_level(logging.DEBUG, logger="pyhap.camera_stream") - assert session_controller._owned(session.id, CLIENT) is session - assert session_controller._owned(session.id, OTHER) is None - assert session_controller._owned(uuid4(), CLIENT) is None + assert session_controller._owned(session.id, connection_of(CLIENT)) is session + assert session_controller._owned(session.id, connection_of(OTHER)) is None + assert session_controller._owned(uuid4(), connection_of(CLIENT)) is None assert "Not the controller of the session" in caplog.text +async def test_ownership_of_a_reused_address( + session_controller: StreamController[StreamSession], + add_session: Callable[..., StreamSession], +) -> None: + """Test a later connection that reuses an address does not own a session. + + This is what the connection handle is for: the address alone identified + a connection only while it lived. + """ + session = add_session(CLIENT) + reused = HAPConnectionHandle(CLIENT, 4096) + + assert session.client_addr == CLIENT + assert session.connection != reused + assert session_controller._owned(session.id, reused) is None + assert session_controller._no_room(reused) is None + + # The disconnect guard still ends the session by address. + session_controller.client_disconnected(CLIENT) + assert session.state is SessionState.ENDED + + async def test_add_refuses_a_taken_id( session_controller: StreamController[StreamSession], add_session: Callable[..., StreamSession], ) -> None: """Test a session with the ID of another one is not registered.""" session = add_session(CLIENT) - twin = StreamSession(id=session.id, sensor=session.sensor, client_addr=CLIENT) + twin = StreamSession( + id=session.id, sensor=session.sensor, connection=connection_of(CLIENT) + ) with pytest.raises(RuntimeError, match="Another session has the ID"): session_controller._add(twin) @@ -414,7 +445,9 @@ def test_session_end_without_controller( stream_sensor: hksv3.SensorConfiguration, ) -> None: """Test a session no controller registered cannot end itself.""" - session = StreamSession(id=uuid4(), sensor=stream_sensor, client_addr=CLIENT) + session = StreamSession( + id=uuid4(), sensor=stream_sensor, connection=connection_of(CLIENT) + ) session.end() @@ -435,7 +468,7 @@ async def test_release_after_a_stuck_hook( hook = _stubborn(started, finished) request = asyncio.ensure_future( session_controller._run_hook( - session, "test", hook, session_controller._deadline() + session, "test", hook, _deadline(session_controller) ) ) await started.wait() @@ -459,17 +492,19 @@ async def test_no_room( """Test the limits of sessions in all and per connection.""" add_session(CLIENT) add_session(CLIENT) - assert session_controller._no_room(CLIENT) is None + assert session_controller._no_room(connection_of(CLIENT)) is None add_session(CLIENT) - assert session_controller._no_room(CLIENT) == ( + assert session_controller._no_room(connection_of(CLIENT)) == ( "Too many stream sessions of the connection" ) - assert session_controller._no_room(OTHER) is None + assert session_controller._no_room(connection_of(OTHER)) is None add_session(OTHER) add_session(OTHER) - assert session_controller._no_room(OTHER) == "Too many stream sessions" + assert ( + session_controller._no_room(connection_of(OTHER)) == "Too many stream sessions" + ) async def test_no_room_once_closed( @@ -478,7 +513,10 @@ async def test_no_room_once_closed( """Test a closed controller takes no new session.""" await session_controller.close() - assert session_controller._no_room(CLIENT) == "The stream service is closed" + assert ( + session_controller._no_room(connection_of(CLIENT)) + == "The stream service is closed" + ) async def test_releasing_session_keeps_its_room( @@ -500,13 +538,13 @@ async def _release(_session: StreamSession) -> None: release = session_controller._end(session, "test") - assert session_controller._no_room(CLIENT) == ( + assert session_controller._no_room(connection_of(CLIENT)) == ( "Too many stream sessions of the connection" ) released.set() assert release is not None assert await release is True - assert session_controller._no_room(CLIENT) is None + assert session_controller._no_room(connection_of(CLIENT)) is None async def test_cancelled_hook_ends_the_session( @@ -523,7 +561,7 @@ async def test_cancelled_hook_ends_the_session( session, "test", _raise(asyncio.CancelledError()), - session_controller._deadline(), + _deadline(session_controller), end_on_failure=True, first=True, ) @@ -664,5 +702,8 @@ async def _release(_session: StreamSession) -> None: assert unhandled == [] assert "Releasing the session timed out" in caplog.text assert "Closing the stream service while 1 tasks still run" in caplog.text - assert session_controller._no_room(OTHER) == "The stream service is closed" + assert ( + session_controller._no_room(connection_of(OTHER)) + == "The stream service is closed" + ) assert session_controller._releasing == set() diff --git a/tests/test_camera_webrtc.py b/tests/test_camera_webrtc.py index d326b231..aeff5b16 100644 --- a/tests/test_camera_webrtc.py +++ b/tests/test_camera_webrtc.py @@ -13,6 +13,7 @@ from pyhap.camera_stream import SessionState, StreamError from pyhap.camera_webrtc import WebRTCController, WebRTCSession, _remote_tier from pyhap.util import base64_to_bytes, to_base64_str +from tests.conftest import connection_of WEBRTC = "CameraWebRTCStreamManagement" SENSOR = UUID("00112233-4455-6677-8899-aabbccddeeff") @@ -34,12 +35,18 @@ def _count(camera: Camera) -> int: return int(service.get_characteristic("WebRTCNumberOfActiveSessions").value) +def _deadline(controller: WebRTCController) -> float: + """The deadline of a write, like the request's context carries it.""" + return asyncio.get_running_loop().time() + controller.hook_timeout + + async def _solicit( camera: Camera, sframe: bool | None = True, client: Any = CLIENT ) -> hksv3.WebRTCSolicitOfferResponse: + controller = _controller(camera) request = hksv3.WebRTCSolicitOffer(hksv3.WebRTCOfferOptions(sframe)) - response = await _controller(camera)._set_solicit_offer( - to_base64_str(request.encode()), client + response = await controller._set_solicit_offer( + to_base64_str(request.encode()), connection_of(client), _deadline(controller) ) return hksv3.WebRTCSolicitOfferResponse.decode(base64_to_bytes(response)) @@ -63,9 +70,12 @@ async def _answer( ANSWER, [hksv3.IceCandidate("candidate:1 1 udp 1 1.2.3.4 5 typ host")], ) + controller = _controller(camera) return _status( - await _controller(camera)._set_provide_answer( - to_base64_str(request.encode()), client + await controller._set_provide_answer( + to_base64_str(request.encode()), + connection_of(client), + _deadline(controller), ) ) @@ -73,10 +83,13 @@ async def _answer( async def _end( camera: Camera, session_id: UUID, client: Any = CLIENT, command: int = 1 ) -> hksv3.WebRTCSessionStatus: + controller = _controller(camera) request = hksv3.WebRTCStreamingControl(session_id, command) return _status( - await _controller(camera)._set_streaming_control( - to_base64_str(request.encode()), client + await controller._set_streaming_control( + to_base64_str(request.encode()), + connection_of(client), + _deadline(controller), ) ) @@ -573,9 +586,11 @@ async def test_malformed_writes(stream_camera: Callable[..., Camera]) -> None: """Test writes that do not decode answer an error without a session.""" controller = _controller(stream_camera()) value = "AQ==" - solicit = await controller._set_solicit_offer(value, CLIENT) - answer = await controller._set_provide_answer(value, CLIENT) - end = await controller._set_streaming_control(value, CLIENT) + deadline = _deadline(controller) + connection = connection_of(CLIENT) + solicit = await controller._set_solicit_offer(value, connection, deadline) + answer = await controller._set_provide_answer(value, connection, deadline) + end = await controller._set_streaming_control(value, connection, deadline) assert base64_to_bytes(solicit) == bytes.fromhex("040102") assert _status(answer) == hksv3.WebRTCSessionStatus(None, 3) assert _status(end) == hksv3.WebRTCSessionStatus(None, 3) @@ -600,8 +615,9 @@ async def test_oversized_answer( session = await _session(camera) request = hksv3.WebRTCProvideAnswer(session.id, sdp, candidates) - answer = await _controller(camera)._set_provide_answer( - to_base64_str(request.encode()), CLIENT + controller = _controller(camera) + answer = await controller._set_provide_answer( + to_base64_str(request.encode()), connection_of(CLIENT), _deadline(controller) ) assert _status(answer) == hksv3.WebRTCSessionStatus(None, 3) @@ -618,8 +634,9 @@ async def _reoffer( request = hksv3.WebRTCReoffer( session_id, "v=0\r\na=offer\r\n", hksv3.WebRTCOfferOptions(True) ) - response = await _controller(camera)._set_reoffer( - to_base64_str(request.encode()), client + controller = _controller(camera) + response = await controller._set_reoffer( + to_base64_str(request.encode()), connection_of(client), _deadline(controller) ) return hksv3.WebRTCReofferResponse.decode(base64_to_bytes(response)) @@ -628,9 +645,12 @@ async def _update( camera: Camera, session_id: UUID, client: Any = CLIENT ) -> hksv3.WebRTCSessionStatus: request = hksv3.WebRTCUpdateSession(session_id, [KEY], [5]) + controller = _controller(camera) return _status( - await _controller(camera)._set_update_session( - to_base64_str(request.encode()), client + await controller._set_update_session( + to_base64_str(request.encode()), + connection_of(client), + _deadline(controller), ) ) @@ -715,8 +735,9 @@ async def test_oversized_update_session( session = await _active(camera) request = hksv3.WebRTCUpdateSession(session.id, add_keys, remove_kids) - response = await _controller(camera)._set_update_session( - to_base64_str(request.encode()), CLIENT + controller = _controller(camera) + response = await controller._set_update_session( + to_base64_str(request.encode()), connection_of(CLIENT), _deadline(controller) ) assert _status(response) == hksv3.WebRTCSessionStatus(None, 3) @@ -803,8 +824,9 @@ async def test_oversized_reoffer( session = await _active(camera) request = hksv3.WebRTCReoffer(session.id, "a" * (hksv3.MAX_SDP_SIZE + 1)) - response = await _controller(camera)._set_reoffer( - to_base64_str(request.encode()), CLIENT + controller = _controller(camera) + response = await controller._set_reoffer( + to_base64_str(request.encode()), connection_of(CLIENT), _deadline(controller) ) assert hksv3.WebRTCReofferResponse.decode(base64_to_bytes(response)) == ( diff --git a/tests/test_camera_webrtc_hap.py b/tests/test_camera_webrtc_hap.py index ded26340..9946d487 100644 --- a/tests/test_camera_webrtc_hap.py +++ b/tests/test_camera_webrtc_hap.py @@ -55,7 +55,11 @@ async def _write( aid, iid = _char_id(camera, name, service_name) char = {"aid": aid, "iid": iid, "value": value, "r": response} query = {"characteristics": [char]} - result = driver._set_characteristics_for_controller(query, CLIENT, timeout) + # The write carries the driver's virtual handle of CLIENT, so the read + # back below pairs up with it through the driver's state. + result = driver._set_characteristics_for_controller( + query, CLIENT, timeout, connection=driver._connection_of(CLIENT) + ) assert inspect.isawaitable(result) body = await result # Without r a write that succeeds has no body. diff --git a/tests/test_characteristic.py b/tests/test_characteristic.py index ba10d027..c6a7e371 100644 --- a/tests/test_characteristic.py +++ b/tests/test_characteristic.py @@ -3,6 +3,7 @@ from typing import Any from unittest.mock import ANY, MagicMock, Mock, patch from uuid import uuid1 +import warnings import pytest @@ -18,6 +19,7 @@ HAP_PERMISSION_READ, Characteristic, ) +from pyhap.delegates import CharacteristicDelegate PROPERTIES: dict[str, Any] = { "Format": HAP_FORMAT_INT, @@ -348,12 +350,13 @@ def test_client_update_value() -> None: with patch(path_notify) as mock_notify: char.client_update_value(4) assert char.value == 4 - with patch.object(char, "setter_callback") as mock_callback: - char.client_update_value(3) + setter = MagicMock() + char.setter_callback = setter + char.client_update_value(3) assert char.value == 3 assert mock_notify.call_count == 2 - mock_callback.assert_called_with(3) + setter.assert_called_with(3) with patch(path_notify) as mock_notify: char.client_update_value(9, "mock_client_addr") # ty: ignore[invalid-argument-type] @@ -565,6 +568,8 @@ def test_getter_callback() -> None: "type": "A1", } char.getter_callback = lambda: 5 + # ``to_HAP`` answers the stored value: a fresh answer comes from the + # read path, the delegate's ``on_get`` - ``get_value`` for a direct call. assert char.to_HAP() == { "description": "Test Char", "format": "int", @@ -573,8 +578,9 @@ def test_getter_callback() -> None: "minValue": 4, "perms": ["pr"], "type": "A1", - "value": 5, + "value": 4, } + assert char.get_value() == 5 assert char.to_HAP(include_value=False) == { "description": "Test Char", "format": "int", @@ -584,3 +590,101 @@ def test_getter_callback() -> None: "perms": ["pr"], "type": "A1", } + + +class _AsyncGetter(CharacteristicDelegate): + """A delegate overriding on_get.""" + + +def test_to_HAP_cache_skips_delegate() -> None: + """A delegate-backed characteristic is not served from the value cache. + + Its ``on_get`` may answer something else than the stored value, like a + getter-backed one. + """ + char = Characteristic( + display_name="Test Char", type_id="A1", properties=PROPERTIES.copy() + ) + char.broker = Mock() + + # Without a delegate the representation is cached. + assert char.to_HAP() is char.to_HAP() + + char.delegate = _AsyncGetter() + + # With one it is rebuilt, so it always answers the current value. + assert char.to_HAP() is not char.to_HAP() + char.set_value(3) + assert char.to_HAP()["value"] == 3 + assert char.to_HAP(include_value=False) is char.to_HAP(include_value=False) + + +def test_delegate_conflicts_with_legacy_callbacks() -> None: + """Either a delegate or the legacy callbacks, never both.""" + char = get_char(PROPERTIES) + + char.setter_callback = lambda value: None # noqa: E731 + with pytest.raises(ValueError, match="has a legacy callback"): + char.delegate = _AsyncGetter() + + char.setter_callback = None + char.getter_callback = lambda: 1 # noqa: E731 + with pytest.raises(ValueError, match="has a legacy callback"): + char.delegate = _AsyncGetter() + + char.getter_callback = None + char.delegate = _AsyncGetter() + + with pytest.raises(ValueError, match="has a delegate"): + char.setter_callback = lambda value: None # noqa: E731 + with pytest.raises(ValueError, match="has a delegate"): + char.getter_callback = lambda: 1 # noqa: E731 + + +def test_removing_one_side_allows_the_other() -> None: + """Clearing one side with ``None`` frees the characteristic for the other.""" + char = get_char(PROPERTIES) + char.setter_callback = lambda value: None # noqa: E731 + + char.setter_callback = None + char.delegate = _AsyncGetter() + + assert char.delegate is not None + + char.delegate = None + char.getter_callback = lambda: 1 # noqa: E731 + + assert char.getter_callback is not None + + char.getter_callback = None + char.delegate = _AsyncGetter() + + assert char.delegate is not None + + char.delegate = None + char.setter_callback = lambda value: None # noqa: E731 + + assert char.setter_callback is not None + + +def test_legacy_callbacks_warn_deprecated() -> None: + """Assigning a legacy callback announces its deprecation.""" + char = get_char(PROPERTIES) + + with pytest.deprecated_call(match="legacy setter_callback is deprecated"): + char.setter_callback = lambda value: None # noqa: E731 + with pytest.deprecated_call(match="legacy getter_callback is deprecated"): + char.getter_callback = lambda: 1 # noqa: E731 + + # The warning names the assigning code, not the library. + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + char.setter_callback = lambda value: None # noqa: E731 + (warning,) = caught + assert warning.category is DeprecationWarning + assert warning.filename == __file__ + + # Removing stays silent. + with warnings.catch_warnings(): + warnings.simplefilter("error") + char.setter_callback = None diff --git a/tests/test_connection.py b/tests/test_connection.py new file mode 100644 index 00000000..9d8aa02e --- /dev/null +++ b/tests/test_connection.py @@ -0,0 +1,49 @@ +"""Tests for the connection handle.""" + +from pyhap.connection import HAPConnectionHandle + + +def test_same_connection_is_equal() -> None: + """Two handles of one connection, e.g. of a read and a write, are equal.""" + handle = HAPConnectionHandle(("1.2.3.4", 5), 3) + same = HAPConnectionHandle(("1.2.3.4", 5), 3) + + assert handle == same + assert hash(handle) == hash(same) + + +def test_reused_address_is_not_equal() -> None: + """A later connection reusing the address is a different identity.""" + handle = HAPConnectionHandle(("1.2.3.4", 5), 3) + reused = HAPConnectionHandle(("1.2.3.4", 5), 4) + other = HAPConnectionHandle(("1.2.3.4", 6), 3) + + assert handle != reused + assert handle != other + assert handle != ("1.2.3.4", 5) + assert not (handle == ("1.2.3.4", 5)) + + +def test_equal_handles_hash_equal() -> None: + """Equal handles hash equal, so they key a dict or set together.""" + handles = {HAPConnectionHandle(("1.2.3.4", 5), 3): "connection"} + assert handles[HAPConnectionHandle(("1.2.3.4", 5), 3)] == "connection" + assert HAPConnectionHandle(("1.2.3.4", 5), 4) not in handles + + +def test_exposes_client_addr() -> None: + """The handle's interface is the connection's address.""" + handle = HAPConnectionHandle(("1.2.3.4", 5), 7) + + assert handle.client_addr == ("1.2.3.4", 5) + assert not hasattr(handle, "generation") + assert "1.2.3.4" in repr(handle) + + +def test_unconnected_handle() -> None: + """A handle without a connection, e.g. of a direct call, is still a key.""" + handle = HAPConnectionHandle(None, 0) + + assert handle.client_addr is None + assert handle == HAPConnectionHandle(None, 0) + assert handle != HAPConnectionHandle(None, 1) diff --git a/tests/test_context.py b/tests/test_context.py new file mode 100644 index 00000000..a33ae57e --- /dev/null +++ b/tests/test_context.py @@ -0,0 +1,120 @@ +"""Tests for the callback contexts.""" + +from dataclasses import FrozenInstanceError +from uuid import UUID, uuid1, uuid4 + +import pytest + +from pyhap.characteristic import ( + HAP_FORMAT_INT, + HAP_PERMISSION_READ, + PROP_FORMAT, + PROP_PERMISSIONS, + Characteristic, +) +from pyhap.connection import HAPConnectionHandle +from pyhap.const import HAP_PERMISSION_WRITE +from pyhap.context import ( + CharReadContext, + CharWriteContext, + Context, + ServiceWriteContext, +) +from pyhap.service import Service + + +def _char() -> Characteristic: + return Characteristic( + "Value", + uuid1(), + { + PROP_FORMAT: HAP_FORMAT_INT, + PROP_PERMISSIONS: [HAP_PERMISSION_READ, HAP_PERMISSION_WRITE], + }, + ) + + +def _service() -> Service: + return Service(uuid1(), "Test Service") + + +def _handle() -> HAPConnectionHandle: + return HAPConnectionHandle(("1.2.3.4", 5), 3) + + +def test_context_fields() -> None: + """The context carries what a callback knows about the controller.""" + client_uuid = uuid4() + context = Context( + client_addr=("1.2.3.4", 5), + client_uuid=client_uuid, + connection=_handle(), + deadline=123.5, + ) + + assert context.client_addr == ("1.2.3.4", 5) + assert context.client_uuid == client_uuid + assert context.connection.client_addr == ("1.2.3.4", 5) + assert context.deadline == 123.5 + + +def test_contexts_are_frozen() -> None: + """A callback cannot change its context.""" + context = CharReadContext( + client_addr=("1.2.3.4", 5), + client_uuid=None, + connection=_handle(), + deadline=1.0, + characteristic=_char(), + ) + + with pytest.raises(FrozenInstanceError): + context.deadline = 2.0 # ty: ignore[invalid-assignment] + + +def test_write_context_of_one_characteristic() -> None: + """A per-characteristic write carries its characteristic.""" + characteristic = _char() + context = CharWriteContext( + client_addr=("1.2.3.4", 5), + client_uuid=None, + connection=_handle(), + deadline=1.0, + characteristic=characteristic, + is_admin=False, + ) + + assert context.characteristic is characteristic + assert context.is_admin is False + + +def test_service_write_context_carries_the_service() -> None: + """A grouped write carries the service it is about, and the admin flag.""" + service = _service() + context = ServiceWriteContext( + client_addr=("1.2.3.4", 5), + client_uuid=None, + connection=_handle(), + deadline=1.0, + service=service, + is_admin=True, + ) + + assert context.service is service + assert context.is_admin is True + assert not hasattr(context, "characteristic") + + +def test_read_context_carries_the_characteristic() -> None: + """A read carries the characteristic it is about.""" + characteristic = _char() + context = CharReadContext( + client_addr=("1.2.3.4", 5), + client_uuid=UUID(int=0), + connection=_handle(), + deadline=1.0, + characteristic=characteristic, + ) + + assert context.characteristic is characteristic + assert not hasattr(context, "is_admin") diff --git a/tests/test_delegate_dispatch.py b/tests/test_delegate_dispatch.py new file mode 100644 index 00000000..a0e4332a --- /dev/null +++ b/tests/test_delegate_dispatch.py @@ -0,0 +1,1131 @@ +"""Tests for the delegate dispatch of the driver.""" + +import asyncio +from collections.abc import Mapping +import inspect +import math +import time +from typing import Any +from unittest.mock import MagicMock, patch +from uuid import UUID, uuid1, uuid4 + +import pytest + +from pyhap.accessory import STANDALONE_AID, Accessory, Bridge +from pyhap.accessory_driver import AccessoryDriver +from pyhap.characteristic import ( + HAP_FORMAT_INT, + HAP_PERMISSION_READ, + PROP_FORMAT, + PROP_PERMISSIONS, + Characteristic, +) +from pyhap.connection import HAPConnectionHandle +from pyhap.const import ( + HAP_PERMISSION_NOTIFY, + HAP_PERMISSION_WRITE, + HAP_PERMISSION_WRITE_RESPONSE, + HAP_REPR_ACCS, + HAP_REPR_AID, + HAP_REPR_CHARS, + HAP_REPR_IID, + HAP_REPR_SERVICES, + HAP_REPR_STATUS, + HAP_REPR_VALUE, + HAP_REPR_WRITE_RESPONSE, + HAP_SERVER_STATUS, +) +from pyhap.context import CharReadContext, CharWriteContext, ServiceWriteContext +from pyhap.delegates import CharacteristicDelegate, ServiceDelegate +from pyhap.errors import HapStatusError +from pyhap.service import Service +from tests.conftest import connection_of + +WRITER = ("1.2.3.4", 5) +OTHER_CONTROLLER = ("5.6.7.8", 9) +ASYNC_TIMEOUT = 1.0 +CHAR_PROPS = { + PROP_FORMAT: HAP_FORMAT_INT, + PROP_PERMISSIONS: [ + HAP_PERMISSION_READ, + HAP_PERMISSION_WRITE, + HAP_PERMISSION_NOTIFY, + ], +} +NO_VALUE = object() + + +def _add_service_with_chars( + driver: AccessoryDriver, count: int = 1, permissions: list[str] | None = None +) -> tuple[Accessory, Service, list[Characteristic]]: + """Add an accessory with one service of ``count`` int characteristics.""" + acc = Accessory(driver, "Test Accessory", aid=STANDALONE_AID) + service = Service(uuid1(), "Test Service") + chars = [] + for index in range(count): + char = Characteristic( + f"Value{index}", + uuid1(), + { + PROP_FORMAT: HAP_FORMAT_INT, + PROP_PERMISSIONS: list(permissions or CHAR_PROPS[PROP_PERMISSIONS]), + }, + ) + service.add_characteristic(char) + chars.append(char) + acc.add_service(service) + driver.add_accessory(acc) + return acc, service, chars + + +async def _run_scheduled_jobs(rounds: int = 8) -> None: + """Let jobs scheduled by the driver and their tasks run.""" + for _ in range(rounds): + await asyncio.sleep(0) + + +async def _write_chars( + driver: AccessoryDriver, + acc: Accessory, + char_values: list[tuple[Characteristic, Any]], + client: Any = WRITER, + timeout: float = ASYNC_TIMEOUT, + client_uuid: UUID | None = None, + connection: HAPConnectionHandle | None = None, + write_response: bool = False, + ev: bool | None = None, +) -> dict[str, Any] | None: + """Write ``char_values`` like a controller and wait for the dispatch.""" + queries = [] + for char, value in char_values: + entry: dict[str, Any] = { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char), + } + if value is not NO_VALUE: + entry[HAP_REPR_VALUE] = value + if write_response: + entry[HAP_REPR_WRITE_RESPONSE] = True + if ev is not None: + entry[HAP_PERMISSION_NOTIFY] = ev + queries.append(entry) + result = driver._set_characteristics_for_controller( + {HAP_REPR_CHARS: queries}, + client, + timeout, + client_uuid=client_uuid, + connection=connection, + ) + if inspect.isawaitable(result): + result = await result + return result + + +def _status_of( + result: dict[str, Any] | None, acc: Accessory, char: Characteristic +) -> int: + """The status one characteristic was answered with.""" + assert result is not None + aid = acc.aid + assert aid is not None + iid = acc.iid_manager.get_iid(char) + for entry in result[HAP_REPR_CHARS]: + if entry[HAP_REPR_AID] == aid and entry[HAP_REPR_IID] == iid: + status: int = entry[HAP_REPR_STATUS] + return status + raise AssertionError(f"No result for {char}") + + +async def _read_chars( + driver: AccessoryDriver, + acc: Accessory, + chars: list[Characteristic], + client: Any = WRITER, + timeout: float = ASYNC_TIMEOUT, + client_uuid: UUID | None = None, + connection: HAPConnectionHandle | None = None, +) -> dict[str, Any]: + """Read ``chars`` like a controller and wait for the dispatch.""" + result = driver._get_characteristics_for_controller( + [f"{acc.aid}.{acc.iid_manager.get_iid(char)}" for char in chars], + client, + timeout, + client_uuid=client_uuid, + connection=connection, + ) + if inspect.isawaitable(result): + result = await result + return result + + +def _read_of( + result: dict[str, Any], acc: Accessory, char: Characteristic +) -> dict[str, Any]: + """The rep one characteristic was answered with.""" + aid = acc.aid + assert aid is not None + iid = acc.iid_manager.get_iid(char) + for entry in result[HAP_REPR_CHARS]: + if entry[HAP_REPR_AID] == aid and entry[HAP_REPR_IID] == iid: + return entry + raise AssertionError(f"No result for {char}") + + +def _accessories_rep_of( + response: dict[str, Any], acc: Accessory, char: Characteristic +) -> dict[str, Any]: + """The accessories rep of one characteristic.""" + aid = acc.aid + assert aid is not None + iid = acc.iid_manager.get_iid(char) + for acc_rep in response[HAP_REPR_ACCS]: + if acc_rep[HAP_REPR_AID] != aid: + continue + for service_rep in acc_rep[HAP_REPR_SERVICES]: + for rep in service_rep[HAP_REPR_CHARS]: + if rep[HAP_REPR_IID] == iid: + return rep + raise AssertionError(f"No rep for {char}") + + +class _CharDelegate(CharacteristicDelegate): + """A characteristic delegate that records its calls.""" + + def __init__( + self, answer: Any = None, release: asyncio.Event | None = None + ) -> None: + self.calls: list[tuple[Any, CharWriteContext]] = [] + self.answer = answer + self.release = release + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + self.calls.append((value, context)) + if isinstance(self.answer, Exception): + raise self.answer + if self.release is not None: + await self.release.wait() + return self.answer + + +class _GetDelegate(CharacteristicDelegate): + """A characteristic delegate that records its reads.""" + + def __init__( + self, answer: Any = None, release: asyncio.Event | None = None + ) -> None: + self.calls: list[CharReadContext] = [] + self.answer = answer + self.release = release + + async def on_get(self, context: CharReadContext) -> Any: + self.calls.append(context) + if isinstance(self.answer, Exception): + raise self.answer + if self.release is not None: + await self.release.wait() + return self.answer + + +class _SubDelegate(CharacteristicDelegate): + """A delegate that records its (un)subscription calls.""" + + def __init__(self, answer: Any = None) -> None: + self.subscribes: list[CharReadContext] = [] + self.unsubscribes: list[CharReadContext] = [] + self.answer = answer + + async def on_subscribe(self, context: CharReadContext) -> None: + self.subscribes.append(context) + if isinstance(self.answer, Exception): + raise self.answer + + async def on_unsubscribe(self, context: CharReadContext) -> None: + self.unsubscribes.append(context) + if isinstance(self.answer, Exception): + raise self.answer + + +class _GateDelegate(ServiceDelegate): + """A service gate that records its calls.""" + + def __init__( + self, answer: Any = None, release: asyncio.Event | None = None + ) -> None: + self.calls: list[tuple[Mapping[Characteristic, Any], ServiceWriteContext]] = [] + self.answer = answer + self.release = release + + async def on_set( + self, values: Mapping[Characteristic, Any], context: ServiceWriteContext + ) -> None: + self.calls.append((values, context)) + if isinstance(self.answer, Exception): + raise self.answer + if self.release is not None: + await self.release.wait() + + +class _OrderedChar(_CharDelegate): + """A char delegate that notes when it ran.""" + + def __init__(self, order: list[str], name: str) -> None: + super().__init__() + self.order = order + self.name = name + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + self.order.append(self.name) + return await super().on_set(value, context) + + +async def test_on_set_receives_value_and_context(driver: AccessoryDriver) -> None: + """A controller's write runs the char's on_set with a full context.""" + acc, _, (char,) = _add_service_with_chars(driver) + handle = HAPConnectionHandle(WRITER, 1) + delegate = _CharDelegate() + char.delegate = delegate + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char, 7)], connection=handle) + + ((value, context),) = delegate.calls + assert value == 7 + assert context.characteristic is char + assert context.client_addr == WRITER + assert context.client_uuid is None + assert context.connection is handle + assert context.is_admin is False + assert context.deadline > 0 + assert char.value == 7 + notify.assert_called_once_with(handle) + # Every write succeeded without a value to answer: no response body. + assert result is None + + +async def test_on_set_write_response(driver: AccessoryDriver) -> None: + """An on_set's return value is the write response of a wr char.""" + acc, _, (char,) = _add_service_with_chars( + driver, + permissions=[ + HAP_PERMISSION_READ, + HAP_PERMISSION_WRITE, + HAP_PERMISSION_WRITE_RESPONSE, + ], + ) + char.delegate = _CharDelegate(answer=7) + + result = await _write_chars(driver, acc, [(char, 5)], write_response=True) + assert result is not None + (entry,) = result[HAP_REPR_CHARS] + assert entry[HAP_REPR_VALUE] == 7 + + +async def test_on_set_read_back_answer(driver: AccessoryDriver) -> None: + """What on_set answers to a read back char is read back by the writer.""" + acc, _, (char,) = _add_service_with_chars( + driver, + permissions=[HAP_PERMISSION_READ, HAP_PERMISSION_WRITE, HAP_PERMISSION_NOTIFY], + ) + char.read_back_response = True + char.delegate = _CharDelegate(answer=7) + char_id = f"{STANDALONE_AID}.{acc.iid_manager.get_iid(char)}" + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char, 5)]) + + assert result is None + (writer_rep,) = driver.get_characteristics([char_id], WRITER)[HAP_REPR_CHARS] + (other_rep,) = driver.get_characteristics([char_id], OTHER_CONTROLLER)[ + HAP_REPR_CHARS + ] + assert writer_rep[HAP_REPR_VALUE] == 7 + assert other_rep[HAP_REPR_VALUE] == 0 + assert char.value == 0 + # The read back answer replaced the value; nothing to tell subscribers. + notify.assert_not_called() + + +async def test_on_set_hap_status_refused(driver: AccessoryDriver) -> None: + """A refused write answers its status, restores and notifies nobody.""" + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _CharDelegate( + answer=HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + ) + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char, 7)]) + + assert _status_of(result, acc, char) == HAP_SERVER_STATUS.RESOURCE_BUSY + assert char.value == 0 + notify.assert_not_called() + + +async def test_on_set_failure_answers_70402(driver: AccessoryDriver) -> None: + """Any other exception of on_set answers -70402, restores, notifies nobody.""" + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _CharDelegate(answer=RuntimeError("no")) + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char, 7)]) + + assert ( + _status_of(result, acc, char) == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + assert char.value == 0 + notify.assert_not_called() + + +async def test_on_set_raising_at_call_time_answers_70402( + driver: AccessoryDriver, +) -> None: + """A sync on_set that raises when called fails its write, not the request.""" + + class _SyncRaise(CharacteristicDelegate): + def on_set(self, value: Any, context: CharWriteContext) -> Any: + raise RuntimeError("no") + + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _SyncRaise() + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char, 7)]) + + assert ( + _status_of(result, acc, char) == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + assert char.value == 0 + notify.assert_not_called() + + +async def test_on_set_timeout_answers_70408(driver: AccessoryDriver) -> None: + """An on_set that misses the deadline answers -70408 and restores.""" + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _CharDelegate(release=asyncio.Event()) + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char, 7)], timeout=0.01) + + assert _status_of(result, acc, char) == HAP_SERVER_STATUS.OPERATION_TIMED_OUT + assert char.value == 0 + notify.assert_not_called() + + +async def test_invalid_value_answers_70402_without_on_set( + driver: AccessoryDriver, +) -> None: + """A value that does not fit the char answers -70402 and runs no on_set.""" + acc, _, (char,) = _add_service_with_chars(driver) + delegate = _CharDelegate() + char.delegate = delegate + + result = await _write_chars(driver, acc, [(char, "not an int")]) + + assert ( + _status_of(result, acc, char) == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + assert delegate.calls == [] + assert char.value == 0 + + +async def test_null_write_answers_invalid_and_runs_no_on_set( + driver: AccessoryDriver, +) -> None: + """A null write answers invalid and runs no on_set, like the legacy path.""" + acc, _, (char,) = _add_service_with_chars(driver) + delegate = _CharDelegate() + char.delegate = delegate + + result = await _write_chars(driver, acc, [(char, None)]) + + assert _status_of(result, acc, char) == HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST + assert delegate.calls == [] + assert char.value == 0 + + +async def test_gate_veto_restores_and_skips_on_set(driver: AccessoryDriver) -> None: + """A gate's refusal restores every write of its service, notifies nobody.""" + acc, service, (char_a, char_b) = _add_service_with_chars(driver, count=2) + gate = _GateDelegate(answer=HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY)) + service.delegate = gate + delegates = [_CharDelegate(), _CharDelegate()] + char_a.delegate = delegates[0] + char_b.delegate = delegates[1] + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char_a, 1), (char_b, 2)]) + + ((values, context),) = gate.calls + assert values == {char_a: 1, char_b: 2} + assert context.service is service + assert context.is_admin is False + assert context.client_addr == WRITER + assert _status_of(result, acc, char_a) == HAP_SERVER_STATUS.RESOURCE_BUSY + assert _status_of(result, acc, char_b) == HAP_SERVER_STATUS.RESOURCE_BUSY + assert char_a.value == 0 + assert char_b.value == 0 + assert delegates[0].calls == [] + assert delegates[1].calls == [] + notify.assert_not_called() + + +async def test_gate_timeout_answers_70408(driver: AccessoryDriver) -> None: + """A gate that misses the deadline refuses its writes with -70408.""" + acc, service, (char,) = _add_service_with_chars(driver) + service.delegate = _GateDelegate(release=asyncio.Event()) + delegate = _CharDelegate() + char.delegate = delegate + + result = await _write_chars(driver, acc, [(char, 7)], timeout=0.01) + + assert _status_of(result, acc, char) == HAP_SERVER_STATUS.OPERATION_TIMED_OUT + assert delegate.calls == [] + assert char.value == 0 + + +async def test_gate_failure_answers_70402(driver: AccessoryDriver) -> None: + """Any other gate exception refuses its writes with -70402.""" + acc, service, (char,) = _add_service_with_chars(driver) + service.delegate = _GateDelegate(answer=RuntimeError("no")) + delegate = _CharDelegate() + char.delegate = delegate + + result = await _write_chars(driver, acc, [(char, 7)]) + + assert ( + _status_of(result, acc, char) == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + assert delegate.calls == [] + assert char.value == 0 + + +async def test_gate_raising_at_call_time_refuses_70402( + driver: AccessoryDriver, +) -> None: + """A sync gate on_set raising at call time refuses the writes, not the request.""" + + class _SyncRaiseGate(ServiceDelegate): + def on_set(self, values: Any, context: Any) -> Any: + raise RuntimeError("no") + + acc, service, (char,) = _add_service_with_chars(driver) + service.delegate = _SyncRaiseGate() + delegate = _CharDelegate() + char.delegate = delegate + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char, 7)]) + + assert ( + _status_of(result, acc, char) == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + assert delegate.calls == [] + assert char.value == 0 + notify.assert_not_called() + + +async def test_gate_passes_then_writes_apply(driver: AccessoryDriver) -> None: + """An accepting gate lets the writes of its service apply and notify.""" + acc, service, (char,) = _add_service_with_chars(driver) + order: list[str] = [] + + class _OrderedGate(_GateDelegate): + async def on_set( + self, values: Mapping[Characteristic, Any], context: ServiceWriteContext + ) -> None: + order.append("gate") + await super().on_set(values, context) + + service.delegate = _OrderedGate() + char.delegate = _OrderedChar(order, "on_set") + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(char, 7)]) + + assert result is None + assert order == ["gate", "on_set"] + assert char.value == 7 + notify.assert_called_once_with(driver._connection_of(WRITER)) + + +async def test_gate_covers_legacy_chars_of_its_service(driver: AccessoryDriver) -> None: + """A gated service's legacy callback chars are applied after the gate.""" + acc, service, (delegate_char, legacy_char) = _add_service_with_chars( + driver, count=2 + ) + order: list[str] = [] + + class _OrderedGate(_GateDelegate): + async def on_set( + self, values: Mapping[Characteristic, Any], context: ServiceWriteContext + ) -> None: + order.append("gate") + await super().on_set(values, context) + + setter = MagicMock(side_effect=lambda value: order.append("setter")) + legacy_char.setter_callback = setter + gate = _OrderedGate() + service.delegate = gate + delegate_char.delegate = _OrderedChar(order, "on_set") + + result = await _write_chars(driver, acc, [(delegate_char, 1), (legacy_char, 2)]) + + assert result is None + ((values, _),) = gate.calls + assert values == {delegate_char: 1, legacy_char: 2} + assert order[0] == "gate" + assert "gate" not in order[1:] + setter.assert_called_once_with(2) + assert delegate_char.value == 1 + assert legacy_char.value == 2 + + +async def test_gate_veto_skips_legacy_setter(driver: AccessoryDriver) -> None: + """A gate's refusal never applies the legacy chars of its service.""" + acc, service, (_, legacy_char) = _add_service_with_chars(driver, count=2) + setter = MagicMock() + legacy_char.setter_callback = setter + service.delegate = _GateDelegate( + answer=HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + ) + + result = await _write_chars(driver, acc, [(legacy_char, 7)]) + + assert _status_of(result, acc, legacy_char) == HAP_SERVER_STATUS.RESOURCE_BUSY + setter.assert_not_called() + assert legacy_char.value == 0 + + +async def test_gate_veto_only_its_service(driver: AccessoryDriver) -> None: + """A gate's refusal does not touch the writes of other services.""" + acc, gated_service, (gated_char,) = _add_service_with_chars(driver) + plain_service = Service(uuid1(), "Plain Service") + plain_char = Characteristic("PlainValue", uuid1(), CHAR_PROPS) + plain_service.add_characteristic(plain_char) + acc.add_service(plain_service) + setter = MagicMock() + plain_char.setter_callback = setter + gated_service.delegate = _GateDelegate( + answer=HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + ) + + with patch.object(Characteristic, "notify") as notify: + result = await _write_chars(driver, acc, [(gated_char, 1), (plain_char, 2)]) + + assert _status_of(result, acc, gated_char) == HAP_SERVER_STATUS.RESOURCE_BUSY + assert _status_of(result, acc, plain_char) == HAP_SERVER_STATUS.SUCCESS + setter.assert_called_once_with(2) + assert plain_char.value == 2 + assert gated_char.value == 0 + notify.assert_called_once_with(driver._connection_of(WRITER)) + + +async def test_accessory_setter_sees_delegate_writes(driver: AccessoryDriver) -> None: + """The legacy accessory setter still learns every written value.""" + acc, service, (char,) = _add_service_with_chars(driver) + acc_setter = MagicMock() + acc.setter_callback = acc_setter + char.delegate = _CharDelegate() + + await _write_chars(driver, acc, [(char, 7)]) + + acc_setter.assert_called_once_with({service: {char: 7}}) + + +async def test_on_set_is_admin(driver: AccessoryDriver) -> None: + """The context says whether the writing controller is an admin.""" + acc, _, (char,) = _add_service_with_chars(driver) + delegate = _CharDelegate() + char.delegate = delegate + admin_uuid = uuid4() + plain_uuid = uuid4() + driver.state.add_paired_client(str(admin_uuid).encode(), b"pub", b"\x01") + driver.state.add_paired_client(str(plain_uuid).encode(), b"pub", b"\x00") + + await _write_chars(driver, acc, [(char, 7)], client_uuid=admin_uuid) + await _write_chars(driver, acc, [(char, 8)], client_uuid=plain_uuid) + + assert delegate.calls[0][1].is_admin is True + assert delegate.calls[0][1].client_uuid == admin_uuid + assert delegate.calls[1][1].is_admin is False + + +async def test_write_response_dropped_when_closed_before_on_set_done( + driver: AccessoryDriver, +) -> None: + """An on_set answering after its connection closed gets no response kept.""" + acc, _, (char,) = _add_service_with_chars( + driver, + permissions=[ + HAP_PERMISSION_READ, + HAP_PERMISSION_WRITE, + HAP_PERMISSION_WRITE_RESPONSE, + ], + ) + release = asyncio.Event() + char.delegate = _CharDelegate(answer=7, release=release) + handle = HAPConnectionHandle(WRITER, 1) + + write = asyncio.ensure_future( + _write_chars(driver, acc, [(char, 5)], connection=handle, write_response=True) + ) + await asyncio.sleep(0) + driver.connection_lost(WRITER, connection=handle) + await asyncio.sleep(0) + release.set() + + # The response of the closed connection is answered to nobody - its + # task is cancelled - and its value is not kept for a connection that + # reuses the address, see ``AccessoryDriver._is_open``. + await write + assert driver._write_responses == {} + + +async def test_on_subscribe_receives_a_full_context(driver: AccessoryDriver) -> None: + """A controller's subscription runs on_subscribe with a full context.""" + acc, _, (char,) = _add_service_with_chars(driver) + driver.loop = asyncio.get_running_loop() + handle = HAPConnectionHandle(WRITER, 1) + client_uuid = uuid4() + delegate = _SubDelegate() + char.delegate = delegate + char_topic = f"{acc.aid}.{acc.iid_manager.get_iid(char)}" + + result = await _write_chars( + driver, + acc, + [(char, NO_VALUE)], + ev=True, + client_uuid=client_uuid, + connection=handle, + ) + await _run_scheduled_jobs() + + assert result is None + (context,) = delegate.subscribes + assert context.characteristic is char + assert context.client_addr == WRITER + assert context.client_uuid == client_uuid + assert context.connection is handle + assert context.deadline == math.inf + assert driver.topics == {char_topic: {handle}} + + +async def test_on_unsubscribe_receives_the_context(driver: AccessoryDriver) -> None: + """A controller's unsubscription runs on_unsubscribe.""" + acc, _, (char,) = _add_service_with_chars(driver) + driver.loop = asyncio.get_running_loop() + delegate = _SubDelegate() + char.delegate = delegate + + await _write_chars(driver, acc, [(char, NO_VALUE)], ev=True) + await _run_scheduled_jobs() + result = await _write_chars(driver, acc, [(char, NO_VALUE)], ev=False) + await _run_scheduled_jobs() + + assert result is None + (context,) = delegate.unsubscribes + assert context.characteristic is char + assert context.client_addr == WRITER + assert driver.topics == {} + + +async def test_subscription_hooks_run_only_on_the_change( + driver: AccessoryDriver, +) -> None: + """Repeated (un)subscriptions of the same controller run no hook.""" + acc, _, (char,) = _add_service_with_chars(driver) + driver.loop = asyncio.get_running_loop() + delegate = _SubDelegate() + char.delegate = delegate + + await _write_chars(driver, acc, [(char, NO_VALUE)], ev=True) + await _write_chars(driver, acc, [(char, NO_VALUE)], ev=True) + await _write_chars(driver, acc, [(char, NO_VALUE)], ev=False) + await _write_chars(driver, acc, [(char, NO_VALUE)], ev=False) + await _run_scheduled_jobs() + + assert len(delegate.subscribes) == 1 + assert len(delegate.unsubscribes) == 1 + + +async def test_on_subscribe_failure_is_isolated( + driver: AccessoryDriver, caplog: pytest.LogCaptureFixture +) -> None: + """A failing on_subscribe is logged and the subscription registers.""" + acc, _, (char,) = _add_service_with_chars(driver) + driver.loop = asyncio.get_running_loop() + delegate = _SubDelegate(answer=RuntimeError("no")) + char.delegate = delegate + char_topic = f"{acc.aid}.{acc.iid_manager.get_iid(char)}" + + result = await _write_chars(driver, acc, [(char, NO_VALUE)], ev=True) + await _run_scheduled_jobs() + + assert result is None + assert driver.topics == {char_topic: {driver._connection_of(WRITER)}} + assert "failed to run on_subscribe" in caplog.text + + +async def test_close_runs_on_unsubscribe(driver: AccessoryDriver) -> None: + """A connection that closes while subscribed runs on_unsubscribe.""" + acc, _, (char,) = _add_service_with_chars(driver) + driver.loop = asyncio.get_running_loop() + handle = HAPConnectionHandle(WRITER, 1) + client_uuid = uuid4() + delegate = _SubDelegate() + char.delegate = delegate + + await _write_chars( + driver, + acc, + [(char, NO_VALUE)], + ev=True, + client_uuid=client_uuid, + connection=handle, + ) + await _run_scheduled_jobs() + driver.connection_lost(WRITER, connection=handle, client_uuid=client_uuid) + await _run_scheduled_jobs() + + (context,) = delegate.unsubscribes + assert context.characteristic is char + assert context.client_addr == WRITER + assert context.client_uuid == client_uuid + assert context.connection is handle + assert driver.topics == {} + + +async def test_close_without_connection_info_runs_on_unsubscribe( + driver: AccessoryDriver, +) -> None: + """A close without its connection's identity still runs on_unsubscribe.""" + acc, _, (char,) = _add_service_with_chars(driver) + driver.loop = asyncio.get_running_loop() + delegate = _SubDelegate() + char.delegate = delegate + + await _write_chars(driver, acc, [(char, NO_VALUE)], ev=True) + await _run_scheduled_jobs() + driver.connection_lost(WRITER) + await _run_scheduled_jobs() + + (context,) = delegate.unsubscribes + assert context.client_uuid is None + # Without the closed connection's handle the hook still learns the + # address, on a handle of its own. + assert context.connection.client_addr == WRITER + assert driver.topics == {} + + +async def test_direct_set_characteristics_schedules_delegates( + driver: AccessoryDriver, +) -> None: + """A direct call stores the values and runs the dispatch as a job.""" + driver.loop = asyncio.get_running_loop() + acc, _, (char,) = _add_service_with_chars(driver) + delegate = _CharDelegate() + char.delegate = delegate + notified = asyncio.Event() + + def _record(*_: Any) -> None: + notified.set() + + query = { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: acc.iid_manager.get_iid(char), + HAP_REPR_VALUE: 7, + } + ] + } + + with patch.object(Characteristic, "notify", side_effect=_record) as notify: + result = driver.set_characteristics(query, WRITER) + + # The optimistic answer of a direct call, like a coroutine setter's. + assert result is None + assert char.value == 7 + assert delegate.calls == [] + + await asyncio.wait_for(notified.wait(), ASYNC_TIMEOUT) + + ((value, context),) = delegate.calls + assert value == 7 + assert context.client_addr == WRITER + assert context.connection is driver._connection_of(WRITER) + assert context.deadline == math.inf + notify.assert_called_once_with(driver._connection_of(WRITER)) + + +async def test_on_get_receives_a_full_context(driver: AccessoryDriver) -> None: + """A controller read runs on_get and answers its value.""" + acc, _, (char,) = _add_service_with_chars(driver) + client_uuid = uuid4() + connection = connection_of(WRITER) + delegate = _GetDelegate(answer=11) + char.delegate = delegate + before = time.monotonic() + + result = await _read_chars( + driver, acc, [char], client_uuid=client_uuid, connection=connection + ) + + rep = _read_of(result, acc, char) + assert rep[HAP_REPR_VALUE] == 11 + assert rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SUCCESS + # The answer is stored on the characteristic, like a getter's. + assert char.value == 11 + (context,) = delegate.calls + assert context.characteristic is char + assert context.client_addr == WRITER + assert context.client_uuid == client_uuid + assert context.connection is connection + assert before <= context.deadline <= time.monotonic() + ASYNC_TIMEOUT + + +async def test_on_get_timeout_answers_70408(driver: AccessoryDriver) -> None: + """An on_get that misses the deadline answers -70408, keeping the value.""" + acc, _, (char,) = _add_service_with_chars(driver) + char.set_value(3) + char.delegate = _GetDelegate(release=asyncio.Event()) + + result = await _read_chars(driver, acc, [char], timeout=0.01) + + rep = _read_of(result, acc, char) + assert rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.OPERATION_TIMED_OUT + assert HAP_REPR_VALUE not in rep + assert char.value == 3 + + +async def test_on_get_hap_status_answers(driver: AccessoryDriver) -> None: + """A curated HapStatusError of on_get answers its status.""" + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _GetDelegate(answer=HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY)) + + result = await _read_chars(driver, acc, [char]) + + rep = _read_of(result, acc, char) + assert rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.RESOURCE_BUSY + assert HAP_REPR_VALUE not in rep + + +async def test_on_get_failure_answers_70402(driver: AccessoryDriver) -> None: + """Any other exception of on_get answers -70402.""" + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _GetDelegate(answer=RuntimeError("no")) + + result = await _read_chars(driver, acc, [char]) + + rep = _read_of(result, acc, char) + assert rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + assert HAP_REPR_VALUE not in rep + + +async def test_on_get_not_a_coroutine_function(driver: AccessoryDriver) -> None: + """An on_get that is not a coroutine function answers -70402.""" + + class _SyncGet(CharacteristicDelegate): + def on_get(self, context: CharReadContext) -> Any: + return 1 + + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _SyncGet() + + result = await _read_chars(driver, acc, [char]) + + rep = _read_of(result, acc, char) + assert rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + + +async def test_on_get_raising_at_call_time_answers_70402( + driver: AccessoryDriver, +) -> None: + """A sync on_get that raises when called fails its read, not the request.""" + + class _SyncRaiseGet(CharacteristicDelegate): + def on_get(self, context: CharReadContext) -> Any: + raise RuntimeError("no") + + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _SyncRaiseGet() + + result = await _read_chars(driver, acc, [char]) + + rep = _read_of(result, acc, char) + assert rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + assert HAP_REPR_VALUE not in rep + + +async def test_on_get_null_answer(driver: AccessoryDriver) -> None: + """An on_get returning None answers the null value.""" + acc, _, (char,) = _add_service_with_chars(driver) + char.delegate = _GetDelegate(answer=None) + + result = await _read_chars(driver, acc, [char]) + + rep = _read_of(result, acc, char) + assert rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SUCCESS + assert rep[HAP_REPR_VALUE] is None + assert char.value is None + + +async def test_on_get_answer_is_validated(driver: AccessoryDriver) -> None: + """An answer is coerced to the format; one that does not fit answers -70402.""" + acc, _, (coerced, broken) = _add_service_with_chars(driver, count=2) + coerced.delegate = _GetDelegate(answer=5.7) + broken.delegate = _GetDelegate(answer="not an int") + + result = await _read_chars(driver, acc, [coerced, broken]) + + coerced_rep = _read_of(result, acc, coerced) + assert coerced_rep[HAP_REPR_VALUE] == 5 + assert coerced_rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SUCCESS + broken_rep = _read_of(result, acc, broken) + assert ( + broken_rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + assert HAP_REPR_VALUE not in broken_rep + + +async def test_read_mixes_legacy_getter_and_delegate(driver: AccessoryDriver) -> None: + """A request reads its legacy chars inline, its delegate chars awaited.""" + acc, _, (legacy, delegated) = _add_service_with_chars(driver, count=2) + legacy.getter_callback = lambda: 7 # noqa: E731 + delegated.delegate = _GetDelegate(answer=11) + + result = await _read_chars(driver, acc, [legacy, delegated]) + + legacy_rep = _read_of(result, acc, legacy) + assert legacy_rep[HAP_REPR_VALUE] == 7 + assert legacy_rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SUCCESS + delegated_rep = _read_of(result, acc, delegated) + assert delegated_rep[HAP_REPR_VALUE] == 11 + assert delegated_rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SUCCESS + + +async def test_write_response_wins_over_on_get(driver: AccessoryDriver) -> None: + """The connection that wrote reads its write response back, not on_get.""" + acc, _, (char,) = _add_service_with_chars( + driver, + permissions=[ + HAP_PERMISSION_READ, + HAP_PERMISSION_WRITE, + HAP_PERMISSION_WRITE_RESPONSE, + ], + ) + char.read_back_response = True + char.delegate = _CharDelegate(answer=7) + await _write_chars(driver, acc, [(char, 5)], write_response=True) + char.delegate = _GetDelegate(answer=11) + + writer_result = await _read_chars(driver, acc, [char], client=WRITER) + other_result = await _read_chars(driver, acc, [char], client=OTHER_CONTROLLER) + + assert _read_of(writer_result, acc, char)[HAP_REPR_VALUE] == 7 + assert _read_of(other_result, acc, char)[HAP_REPR_VALUE] == 11 + + +async def test_direct_get_characteristics_answers_stored_and_schedules( + driver: AccessoryDriver, +) -> None: + """A direct read answers the stored value and runs the reads as a job.""" + driver.loop = asyncio.get_running_loop() + acc, _, (char,) = _add_service_with_chars(driver) + char.set_value(3) + delegate = _GetDelegate(answer=11) + char.delegate = delegate + char_id = f"{acc.aid}.{acc.iid_manager.get_iid(char)}" + + result = driver.get_characteristics([char_id]) + + (rep,) = result[HAP_REPR_CHARS] + # The optimistic answer of a direct call, like a coroutine setter's. + assert rep[HAP_REPR_VALUE] == 3 + assert rep[HAP_REPR_STATUS] == HAP_SERVER_STATUS.SUCCESS + assert delegate.calls == [] + + await _run_scheduled_jobs() + + assert char.value == 11 + (context,) = delegate.calls + assert context.characteristic is char + assert context.client_addr is None + assert context.connection.client_addr is None + assert context.deadline == math.inf + + +async def test_on_get_answers_an_accessories_request(driver: AccessoryDriver) -> None: + """An accessories request reads delegate-backed chars through on_get.""" + acc, _, (char,) = _add_service_with_chars(driver) + delegate = _GetDelegate(answer=11) + char.delegate = delegate + + result = driver._get_accessories_for_controller(WRITER, ASYNC_TIMEOUT) + assert inspect.isawaitable(result) + response = await result + + rep = _accessories_rep_of(response, acc, char) + assert rep[HAP_REPR_VALUE] == 11 + assert char.value == 11 + assert len(delegate.calls) == 1 + + +async def test_accessories_request_failure_lists_no_value( + driver: AccessoryDriver, +) -> None: + """A failing read of an accessories request lists the char without a value.""" + acc, _, (char,) = _add_service_with_chars(driver) + char.set_value(3) + char.delegate = _GetDelegate(answer=RuntimeError("no")) + + result = driver._get_accessories_for_controller(WRITER, ASYNC_TIMEOUT) + assert inspect.isawaitable(result) + response = await result + + rep = _accessories_rep_of(response, acc, char) + assert HAP_REPR_VALUE not in rep + assert char.value == 3 + + +async def test_accessories_request_reads_bridged_accessories( + driver: AccessoryDriver, +) -> None: + """A bridged accessories request reads the bridged delegate chars too.""" + bridge = Bridge(driver, "Test Bridge") + acc = Accessory(driver, "Bridged") + service = Service(uuid1(), "Test Service") + char = Characteristic("Value", uuid1(), CHAR_PROPS) + service.add_characteristic(char) + acc.add_service(service) + bridge.add_accessory(acc) + driver.add_accessory(bridge) + char.delegate = _GetDelegate(answer=11) + + result = driver._get_accessories_for_controller(WRITER, ASYNC_TIMEOUT) + assert inspect.isawaitable(result) + response = await result + + rep = _accessories_rep_of(response, acc, char) + assert rep[HAP_REPR_VALUE] == 11 + + +async def test_direct_get_accessories_answers_stored_and_schedules( + driver: AccessoryDriver, +) -> None: + """A direct accessories request answers stored values, then refreshes.""" + driver.loop = asyncio.get_running_loop() + acc, _, (char,) = _add_service_with_chars(driver) + char.set_value(3) + delegate = _GetDelegate(answer=11) + char.delegate = delegate + + response = driver.get_accessories() + + rep = _accessories_rep_of(response, acc, char) + assert rep[HAP_REPR_VALUE] == 3 + assert delegate.calls == [] + + await _run_scheduled_jobs() + + assert char.value == 11 diff --git a/tests/test_delegates.py b/tests/test_delegates.py new file mode 100644 index 00000000..bd86c4ee --- /dev/null +++ b/tests/test_delegates.py @@ -0,0 +1,134 @@ +"""Tests for the delegate base classes.""" + +import asyncio +from collections.abc import Awaitable, Mapping +import inspect +from typing import Any +from uuid import uuid1 + +import pytest + +from pyhap.characteristic import ( + HAP_FORMAT_INT, + HAP_PERMISSION_READ, + PROP_FORMAT, + PROP_PERMISSIONS, + Characteristic, +) +from pyhap.connection import HAPConnectionHandle +from pyhap.const import HAP_PERMISSION_WRITE +from pyhap.context import CharReadContext, CharWriteContext, ServiceWriteContext +from pyhap.delegates import CharacteristicDelegate, ServiceDelegate +from pyhap.service import Service + + +def _char() -> Characteristic: + return Characteristic( + "Value", + uuid1(), + { + PROP_FORMAT: HAP_FORMAT_INT, + PROP_PERMISSIONS: [HAP_PERMISSION_READ, HAP_PERMISSION_WRITE], + }, + ) + + +def _read_context() -> CharReadContext: + return CharReadContext( + client_addr=("1.2.3.4", 5), + client_uuid=None, + connection=HAPConnectionHandle(("1.2.3.4", 5), 3), + deadline=1.0, + characteristic=_char(), + ) + + +def _write_context() -> CharWriteContext: + return CharWriteContext( + client_addr=("1.2.3.4", 5), + client_uuid=None, + connection=HAPConnectionHandle(("1.2.3.4", 5), 3), + deadline=1.0, + characteristic=_char(), + is_admin=True, + ) + + +def _service_write_context() -> ServiceWriteContext: + return ServiceWriteContext( + client_addr=("1.2.3.4", 5), + client_uuid=None, + connection=HAPConnectionHandle(("1.2.3.4", 5), 3), + deadline=1.0, + service=Service(uuid1(), "Test Service"), + is_admin=True, + ) + + +async def _run(coro: Awaitable[object]) -> object: + return await coro + + +def test_noop_defaults_are_coroutine_functions() -> None: + """The noop defaults are awaited by the driver, so they are coroutines.""" + for delegate, method in ( + (CharacteristicDelegate, "on_get"), + (CharacteristicDelegate, "on_set"), + (CharacteristicDelegate, "on_subscribe"), + (CharacteristicDelegate, "on_unsubscribe"), + (ServiceDelegate, "on_set"), + ): + assert inspect.iscoroutinefunction(getattr(delegate, method)), method + + +async def test_noop_defaults_do_nothing_but_on_get_raises() -> None: + """An unoverridden delegate does nothing, except on_get which raises. + + A delegate takes over the reads of its characteristics: an + unoverridden on_get has no default answer, so a readable + characteristic whose delegate implements none fails its reads. + """ + delegate = CharacteristicDelegate() + + with pytest.raises(NotImplementedError): + await _run(delegate.on_get(_read_context())) + assert await _run(delegate.on_set(1, _write_context())) is None + assert await _run(delegate.on_subscribe(_read_context())) is None + assert await _run(delegate.on_unsubscribe(_read_context())) is None + service = ServiceDelegate() + assert await _run(service.on_set({}, _service_write_context())) is None + + +async def test_overrides_answer_values() -> None: + """A subclass overrides what it needs and awaits like the driver does.""" + value = object() + + class Getter(CharacteristicDelegate): + async def on_get(self, context: CharReadContext) -> object: + return value + + assert await _run(Getter().on_get(_read_context())) is value + + +async def test_on_get_may_answer_none() -> None: + """An overridden on_get returning None is an answer, a null value.""" + + class NullGetter(CharacteristicDelegate): + async def on_get(self, context: CharReadContext) -> int | None: + return None + + assert await _run(NullGetter().on_get(_read_context())) is None + + +async def test_an_override_may_await_inside() -> None: + """A delegate may await inside its methods, like a real device call.""" + done = asyncio.Event() + + class Setter(ServiceDelegate): + async def on_set( + self, values: Mapping[Characteristic, Any], context: ServiceWriteContext + ) -> None: + await done.wait() + + done.set() + assert await _run(Setter().on_set({}, _service_write_context())) is None diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 00000000..23b85b4e --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,59 @@ +"""Tests for the callback error protocol.""" + +import pytest + +from pyhap.const import HAP_SERVER_STATUS +from pyhap.errors import CALLBACK_STATUSES, HapStatusError + + +def test_allowed_status() -> None: + """Each callback status is kept as the status to answer with.""" + for status in CALLBACK_STATUSES: + error = HapStatusError(status) + assert error.status == status + assert str(status) in str(error) + + +def test_resource_busy_is_allowed() -> None: + """The common refusal status constructs and keeps its value.""" + error = HapStatusError(HAP_SERVER_STATUS.RESOURCE_BUSY) + assert error.status == HAP_SERVER_STATUS.RESOURCE_BUSY + + +def test_callback_statuses_are_curated() -> None: + """The curated set is exactly the codes a callback may decide.""" + assert CALLBACK_STATUSES == frozenset( + { + HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE, + HAP_SERVER_STATUS.RESOURCE_BUSY, + HAP_SERVER_STATUS.OUT_OF_RESOURCE, + HAP_SERVER_STATUS.RESOURCE_DOES_NOT_EXIST, + HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST, + HAP_SERVER_STATUS.INSUFFICIENT_AUTHORIZATION, + } + ) + + +@pytest.mark.parametrize( + "status", + [ + HAP_SERVER_STATUS.INSUFFICIENT_PRIVILEGES, + HAP_SERVER_STATUS.READ_ONLY_CHARACTERISTIC, + HAP_SERVER_STATUS.WRITE_ONLY_CHARACTERISTIC, + HAP_SERVER_STATUS.NOTIFICATION_NOT_SUPPORTED, + HAP_SERVER_STATUS.OPERATION_TIMED_OUT, + HAP_SERVER_STATUS.SUCCESS, + 42, + ], +) +def test_reserved_status_raises_value_error(status: int) -> None: + """A driver-reserved or unknown status fails at construction.""" + with pytest.raises(ValueError, match="reserved for the accessory driver"): + HapStatusError(status) + + +def test_is_an_exception() -> None: + """The error can be raised and caught as an exception.""" + with pytest.raises(HapStatusError) as raised: + raise HapStatusError(HAP_SERVER_STATUS.OUT_OF_RESOURCE) + assert raised.value.status == HAP_SERVER_STATUS.OUT_OF_RESOURCE diff --git a/tests/test_hap_handler.py b/tests/test_hap_handler.py index 02e8161f..7e1c57ae 100644 --- a/tests/test_hap_handler.py +++ b/tests/test_hap_handler.py @@ -27,6 +27,8 @@ CharacteristicError, ) from pyhap.const import HAP_PERMISSIONS, HAP_SERVER_STATUS +from pyhap.context import CharReadContext +from pyhap.delegates import CharacteristicDelegate from pyhap.service import Service CLIENT_UUID = UUID("7d0d1ee9-46fe-4a56-a115-69df3f6860c1") @@ -697,7 +699,7 @@ def test_handle_set_handle_set_characteristics_unencrypted( assert response.status_code == 401 -def test_handle_set_handle_set_characteristics_encrypted( +async def test_handle_set_handle_set_characteristics_encrypted( driver: AccessoryDriver, ) -> None: """Verify an encrypted set_characteristics.""" @@ -714,12 +716,14 @@ def test_handle_set_handle_set_characteristics_encrypted( handler.response = response handler.request_body = b'{"characteristics":[{"aid":1,"iid":10,"ev":true}]}' handler.handle_set_characteristics() + assert response.task is not None + await response.task assert response.status_code == 204 assert response.body == b"" -def test_handle_set_handle_set_characteristics_encrypted_pid_missing_prepare( +async def test_handle_set_handle_set_characteristics_encrypted_pid_missing_prepare( driver: AccessoryDriver, ) -> None: """Verify an encrypted set_characteristics with a missing prepare.""" @@ -738,12 +742,14 @@ def test_handle_set_handle_set_characteristics_encrypted_pid_missing_prepare( b'{"pid":123,"characteristics":[{"aid":1,"iid":11,"ev":true}]}' ) handler.handle_set_characteristics() + assert response.task is not None + await response.task assert response.status_code == 207 assert b"-70410" in response.body -def test_handle_set_handle_set_characteristics_encrypted_with_prepare( +async def test_handle_set_handle_set_characteristics_encrypted_with_prepare( driver: AccessoryDriver, ) -> None: """Verify an encrypted set_characteristics with a prepare.""" @@ -770,12 +776,14 @@ def test_handle_set_handle_set_characteristics_encrypted_with_prepare( b'{"pid":123,"characteristics":[{"aid":1,"iid":11,"ev":true}]}' ) handler.handle_set_characteristics() + assert response.task is not None + await response.task assert response.status_code == 204 assert response.body == b"" -def test_handle_set_handle_set_characteristics_encrypted_with_multiple_prepare( +async def test_handle_set_handle_set_characteristics_encrypted_with_multiple_prepare( driver: AccessoryDriver, ) -> None: """Verify an encrypted set_characteristics with multiple prepares.""" @@ -808,6 +816,8 @@ def test_handle_set_handle_set_characteristics_encrypted_with_multiple_prepare( b'{"pid":123,"characteristics":[{"aid":1,"iid":11,"ev":true}]}' ) handler.handle_set_characteristics() + assert response.task is not None + await response.task assert response.status_code == 204 assert response.body == b"" @@ -835,7 +845,7 @@ def test_handle_set_handle_encrypted_with_invalid_prepare( assert response.body == b'{"status":-70410}' -def test_handle_set_handle_set_characteristics_encrypted_with_expired_ttl( +async def test_handle_set_handle_set_characteristics_encrypted_with_expired_ttl( driver: AccessoryDriver, ) -> None: """Verify an encrypted set_characteristics with a prepare expired.""" @@ -862,12 +872,14 @@ def test_handle_set_handle_set_characteristics_encrypted_with_expired_ttl( b'{"pid":123,"characteristics":[{"aid":1,"iid":11,"ev":true}]}' ) handler.handle_set_characteristics() + assert response.task is not None + await response.task assert response.status_code == 207 assert b"-70410" in response.body -def test_handle_set_handle_set_characteristics_encrypted_with_wrong_pid( +async def test_handle_set_handle_set_characteristics_encrypted_with_wrong_pid( driver: AccessoryDriver, ) -> None: """Verify an encrypted set_characteristics with wrong pid.""" @@ -894,6 +906,8 @@ def test_handle_set_handle_set_characteristics_encrypted_with_wrong_pid( b'{"pid":456,"characteristics":[{"aid":1,"iid":11,"ev":true}]}' ) handler.handle_set_characteristics() + assert response.task is not None + await response.task assert response.status_code == 207 assert b"-70410" in response.body @@ -918,7 +932,7 @@ def test_handle_set_handle_prepare_not_encrypted(driver: AccessoryDriver) -> Non assert response.status_code == 401 -def test_handle_set_handle_set_characteristics_encrypted_with_exception( +async def test_handle_set_handle_set_characteristics_encrypted_with_exception( driver: AccessoryDriver, ) -> None: """Verify an encrypted set_characteristics.""" @@ -940,6 +954,8 @@ def _mock_failure(*_: Any) -> NoReturn: handler.response = response handler.request_body = b'{"characteristics":[{"aid":1,"iid":12,"value":1}]}' handler.handle_set_characteristics() + assert response.task is not None + await response.task assert response.status_code == 207 assert b"-70402" in response.body @@ -989,7 +1005,7 @@ async def test_attempt_to_pair_when_already_paired(driver: AccessoryDriver) -> N } -def test_handle_get_characteristics_encrypted(driver: AccessoryDriver) -> None: +async def test_handle_get_characteristics_encrypted(driver: AccessoryDriver) -> None: """Verify an encrypted get_characteristics.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -1006,6 +1022,8 @@ def test_handle_get_characteristics_encrypted(driver: AccessoryDriver) -> None: handler.parsed_url = urlparse(handler.path) handler.handle_get_characteristics() + assert response.task is not None + await response.task assert response.status_code == 200 decoded_response = json.loads(response.body.decode()) @@ -1018,6 +1036,8 @@ def test_handle_get_characteristics_encrypted(driver: AccessoryDriver) -> None: handler.response = response handler.path = "/characteristics?id=1.10" handler.handle_get_characteristics() + assert response.task is not None + await response.task assert response.status_code == 207 decoded_response = json.loads(response.body.decode()) @@ -1033,7 +1053,7 @@ def test_handle_get_characteristics_encrypted(driver: AccessoryDriver) -> None: pytest.param(("5.6.7.8", 9), b'"value":0', id="other-controller"), ], ) -def test_handle_get_characteristics_write_response_per_client( +async def test_handle_get_characteristics_write_response_per_client( driver: AccessoryDriver, reader: tuple[str, int], expected: bytes ) -> None: """Only the client that wrote reads the write response back.""" @@ -1057,6 +1077,8 @@ def test_handle_get_characteristics_write_response_per_client( b'{"characteristics":[{"aid":1,"iid":%d,"value":5,"r":true}]}' % iid ) writer.handle_set_characteristics() + assert writer.response.task is not None + await writer.response.task assert b'"value":7' in writer.response.body handler = hap_handler.HAPServerHandler(driver, reader) @@ -1066,6 +1088,8 @@ def test_handle_get_characteristics_write_response_per_client( handler.path = f"/characteristics?id=1.{iid}" handler.parsed_url = urlparse(handler.path) handler.handle_get_characteristics() + assert response.task is not None + await response.task assert response.status_code == 200 assert expected in response.body @@ -1329,3 +1353,84 @@ async def test_handle_set_characteristics_async_setter_timeout( b'{"characteristics":[{"status":-70408,"aid":1,"iid":9}]}' ) assert response.status_code == 207 + + +class _GetOneDelegate(CharacteristicDelegate): + """Answers reads with 1.""" + + async def on_get(self, context: CharReadContext) -> int: + return 1 + + +class _SlowGetDelegate(CharacteristicDelegate): + """Never answers a read in time.""" + + async def on_get(self, context: CharReadContext) -> None: + await asyncio.sleep(10) + + +def _dispatch_read_to_delegate( + driver: AccessoryDriver, delegate: CharacteristicDelegate, target: str +) -> hap_handler.HAPResponse: + """Dispatch a GET to a readable characteristic with ``delegate``.""" + acc = Accessory(driver, "TestAcc") + service = Service(uuid1(), "Test Service") + char = Characteristic( + "Value", uuid1(), {"Format": "int", "Permissions": ["pr", "pw"]} + ) + char.delegate = delegate + service.add_characteristic(char) + acc.add_service(service) + driver.add_accessory(acc) + assert acc.iid_manager.get_iid(char) == 9 + + handler = hap_handler.HAPServerHandler(driver, "peername") + handler.is_encrypted = True + request = h11.Request(method="GET", target=target, headers=[(b"host", b"t")]) + return handler.dispatch(request, None) + + +async def test_handle_get_characteristics_waits_for_delegate( + driver: AccessoryDriver, +) -> None: + """A read of a delegate char is answered once on_get is done.""" + response = _dispatch_read_to_delegate( + driver, _GetOneDelegate(), "/characteristics?id=1.9" + ) + + assert response.task is not None + assert await response.task == b'{"characteristics":[{"aid":1,"iid":9,"value":1}]}' + assert response.status_code == 200 + assert response.headers == [("Content-Type", "application/hap+json")] + + +async def test_handle_get_characteristics_delegate_timeout( + driver: AccessoryDriver, +) -> None: + """A slow on_get answers -70408 for its characteristic.""" + with patch.object(hap_handler, "RESPONSE_TIMEOUT", 0.01): + response = _dispatch_read_to_delegate( + driver, _SlowGetDelegate(), "/characteristics?id=1.9" + ) + assert response.task is not None + assert await response.task == ( + b'{"characteristics":[{"aid":1,"iid":9,"status":-70408}]}' + ) + assert response.status_code == 207 + + +async def test_handle_accessories_waits_for_delegate(driver: AccessoryDriver) -> None: + """An accessories request is answered once its delegate reads are done.""" + response = _dispatch_read_to_delegate(driver, _GetOneDelegate(), "/accessories") + + assert response.task is not None + body = json.loads(await response.task) + (rep,) = [ + rep + for acc_rep in body["accessories"] + for service_rep in acc_rep["services"] + for rep in service_rep["characteristics"] + if rep["iid"] == 9 + ] + assert rep["value"] == 1 + assert response.status_code == 200 diff --git a/tests/test_hap_protocol.py b/tests/test_hap_protocol.py index 22953be8..602fc74b 100644 --- a/tests/test_hap_protocol.py +++ b/tests/test_hap_protocol.py @@ -13,10 +13,12 @@ from pyhap.accessory import Accessory, Bridge, get_topic from pyhap.accessory_driver import AccessoryDriver from pyhap.characteristic import Characteristic +from pyhap.connection import HAPConnectionHandle from pyhap.const import HAP_REPR_AID, HAP_REPR_IID, HAP_REPR_VALUE from pyhap.hap_crypto import HAPCrypto, hap_hkdf from pyhap.hap_handler import HAPResponse from pyhap.service import Service +from tests.conftest import run_scheduled_jobs class MockTransport(asyncio.Transport): @@ -86,39 +88,43 @@ def test_connection_management(driver: AccessoryDriver) -> None: addr_info2 = ("1.2.3.5", 6) transport = MagicMock(get_extra_info=Mock(return_value=addr_info)) - connections = {} + connections: dict[Any, Any] = {} driver.add_accessory(Accessory(driver, "TestAcc")) - driver.async_subscribe_client_topic(addr_info, "1.1", True) - driver.async_subscribe_client_topic(addr_info, "2.2", True) - driver.async_subscribe_client_topic(addr_info2, "1.1", True) + + hap_proto = hap_protocol.HAPServerProtocol(loop, connections, driver) + hap_proto.connection_made(transport) + connection = hap_proto.connection_handle + assert connection is not None + other = HAPConnectionHandle(addr_info2, 4096) + driver.async_subscribe_client_topic(connection, "1.1", True) + driver.async_subscribe_client_topic(connection, "2.2", True) + driver.async_subscribe_client_topic(other, "1.1", True) assert "1.1" in driver.topics assert "2.2" in driver.topics - assert addr_info in driver.topics["1.1"] - assert addr_info in driver.topics["2.2"] - assert addr_info2 in driver.topics["1.1"] + assert connection in driver.topics["1.1"] + assert connection in driver.topics["2.2"] + assert other in driver.topics["1.1"] - hap_proto = hap_protocol.HAPServerProtocol(loop, connections, driver) - hap_proto.connection_made(transport) assert len(connections) == 1 - assert connections[addr_info] == hap_proto + assert connections[connection] == hap_proto hap_proto.connection_lost(None) assert len(connections) == 0 assert "1.1" in driver.topics assert "2.2" not in driver.topics - assert addr_info not in driver.topics["1.1"] - assert addr_info2 in driver.topics["1.1"] + assert connection not in driver.topics["1.1"] + assert other in driver.topics["1.1"] hap_proto.connection_made(transport) assert len(connections) == 1 - assert connections[addr_info] == hap_proto + assert connections[hap_proto.connection_handle] == hap_proto hap_proto.close() assert len(connections) == 0 hap_proto.connection_made(transport) assert len(connections) == 1 - assert connections[addr_info] == hap_proto + assert connections[hap_proto.connection_handle] == hap_proto hap_proto.connection_lost(None) assert len(connections) == 0 @@ -348,10 +354,11 @@ def test_get_accessories_without_crypto(driver: AccessoryDriver) -> None: assert b"-70401" in writer.call_args_list[0][0][0] -def test_get_accessories_with_crypto(driver: AccessoryDriver) -> None: +async def test_get_accessories_with_crypto(driver: AccessoryDriver) -> None: """Verify an encrypt accessories request.""" - loop = MagicMock() + loop = asyncio.get_running_loop() transport = MagicMock() + transport.is_closing = Mock(return_value=False) connections = {} driver.add_accessory(Accessory(driver, "TestAcc")) @@ -367,15 +374,17 @@ def test_get_accessories_with_crypto(driver: AccessoryDriver) -> None: b"\r\n" b"" ) + await run_scheduled_jobs() hap_proto.close() assert b"accessories" in b"".join(writelines.call_args_list[0][0]) -def test_get_characteristics_with_crypto(driver: AccessoryDriver) -> None: +async def test_get_characteristics_with_crypto(driver: AccessoryDriver) -> None: """Verify an encrypt characteristics request.""" - loop = MagicMock() + loop = asyncio.get_running_loop() transport = MagicMock() + transport.is_closing = Mock(return_value=False) connections = {} acc = Accessory(driver, "TestAcc", aid=1) @@ -396,12 +405,14 @@ def test_get_characteristics_with_crypto(driver: AccessoryDriver) -> None: b"\r\n" b"" ) + await run_scheduled_jobs() hap_proto.data_received( b"GET /characteristics?id=1.5 HTTP/1.1\r\n" b"Host: HASS\\032Bridge\\032YPHW\\032B223AD._hap._tcp.local\r\n" b"\r\n" b"" ) + await run_scheduled_jobs() hap_proto.close() joined0 = b"".join(writelines.call_args_list[0][0]) @@ -415,10 +426,11 @@ def test_get_characteristics_with_crypto(driver: AccessoryDriver) -> None: assert b"TestAcc" in joined1 -def test_set_characteristics_with_crypto(driver: AccessoryDriver) -> None: +async def test_set_characteristics_with_crypto(driver: AccessoryDriver) -> None: """Verify an encrypt characteristics request.""" - loop = MagicMock() + loop = asyncio.get_running_loop() transport = MagicMock() + transport.is_closing = Mock(return_value=False) connections = {} acc = Accessory(driver, "TestAcc", aid=1) @@ -441,6 +453,7 @@ def test_set_characteristics_with_crypto(driver: AccessoryDriver) -> None: b"\r\n" b'{"characteristics":[{"aid":1,"iid":11,"ev":true}]}' ) + await run_scheduled_jobs() hap_proto.close() assert ( @@ -461,17 +474,18 @@ def test_crypto_failure_closes_connection(driver: AccessoryDriver) -> None: hap_proto.connection_made(transport) _enable_encryption(hap_proto) - assert connections[addr_info] == hap_proto + assert connections[hap_proto.connection_handle] == hap_proto with patch.object(hap_proto.hap_crypto, "decrypt", side_effect=InvalidTag): hap_proto.data_received(b"any") assert len(connections) == 0 -def test_empty_encrypted_data(driver: AccessoryDriver) -> None: +async def test_empty_encrypted_data(driver: AccessoryDriver) -> None: """Verify an encrypt request when we start with an empty block.""" - loop = MagicMock() + loop = asyncio.get_running_loop() transport = MagicMock() + transport.is_closing = Mock(return_value=False) connections = {} driver.add_accessory(Accessory(driver, "TestAcc")) @@ -488,6 +502,7 @@ def test_empty_encrypted_data(driver: AccessoryDriver) -> None: b"\r\n" b"" ) + await run_scheduled_jobs() hap_proto.close() assert b"accessories" in b"".join(writelines.call_args_list[0][0]) @@ -750,7 +765,9 @@ async def test_events_wait_for_delayed_response(driver: AccessoryDriver) -> None release = asyncio.Event() hap_proto, acc, _ = _delayed_snapshot_protocol(driver, release) assert acc.aid is not None - driver.topics[get_topic(acc.aid, 9)] = {hap_proto.peername} + handle = hap_proto.connection_handle + assert handle is not None + driver.topics[get_topic(acc.aid, 9)] = {handle} with patch.object(hap_proto.transport, "writelines") as writelines: hap_proto.data_received(SNAPSHOT_REQUEST) @@ -850,7 +867,9 @@ async def test_events_coalesce_after_delayed_response( release = asyncio.Event() hap_proto, acc, _ = _delayed_snapshot_protocol(driver, release) assert acc.aid is not None - driver.topics[get_topic(acc.aid, 9)] = {hap_proto.peername} + handle = hap_proto.connection_handle + assert handle is not None + driver.topics[get_topic(acc.aid, 9)] = {handle} with patch.object(hap_proto.transport, "writelines") as writelines: hap_proto.data_received(SNAPSHOT_REQUEST) @@ -969,7 +988,12 @@ async def _setter(_value: int) -> int: driver.add_accessory(acc) assert acc.iid_manager.get_iid(char) == 9 - hap_proto = hap_protocol.HAPServerProtocol(MagicMock(), {}, driver) + # The server's connections, as a real protocol is given them: the + # driver keeps a write response only of a connection it may still + # answer, see ``AccessoryDriver._is_open``. + hap_proto = hap_protocol.HAPServerProtocol( + MagicMock(), driver.http_server.connections, driver + ) hap_proto.connection_made(transport) _enable_encryption(hap_proto) return hap_proto @@ -1007,7 +1031,7 @@ async def test_get_pipelined_behind_async_setter(driver: AccessoryDriver) -> Non writelines.assert_not_called() setter_done.set() await _await_response(hap_proto) - await asyncio.sleep(0) + await run_scheduled_jobs() hap_proto.close() assert writelines.call_count == 2 @@ -1099,11 +1123,13 @@ def test_close_keeps_newer_connection_with_same_peername( new_proto = hap_protocol.HAPServerProtocol(loop, connections, driver) new_proto.connection_made(transport) _pair_verify(new_proto, b"newkey") - assert connections[old_proto.peername] is new_proto + # The newer connection has its own handle, even on a reused address. + assert connections[new_proto.connection_handle] is new_proto old_proto.close() - assert connections[new_proto.peername] is new_proto + assert connections[new_proto.connection_handle] is new_proto + assert old_proto.connection_handle not in connections assert old_proto.derive_key(b"salt", b"info") is None assert new_proto.derive_key(b"salt", b"info") is not None @@ -1316,9 +1342,9 @@ async def test_does_not_timeout(driver: AccessoryDriver) -> None: assert hap_proto_close.called is False -def test_explicit_close(driver: AccessoryDriver) -> None: +async def test_explicit_close(driver: AccessoryDriver) -> None: """Test an explicit connection close.""" - loop = MagicMock() + loop = asyncio.get_running_loop() transport = MockTransport() connections = {} @@ -1344,6 +1370,7 @@ def test_explicit_close(driver: AccessoryDriver) -> None: b"\r\n" b"" ) + await run_scheduled_jobs() hap_proto.data_received( b"GET /characteristics?id=1.5 HTTP/1.1\r\n" b"Connection: close\r\n" @@ -1351,6 +1378,7 @@ def test_explicit_close(driver: AccessoryDriver) -> None: b"\r\n" b"" ) + await run_scheduled_jobs() join0 = b"".join(writelines.call_args_list[0][0]) assert b"Content-Length:" in join0 diff --git a/tests/test_hap_server.py b/tests/test_hap_server.py index a0bbb646..41e90718 100644 --- a/tests/test_hap_server.py +++ b/tests/test_hap_server.py @@ -6,6 +6,7 @@ from pyhap import hap_server from pyhap.accessory import Accessory from pyhap.accessory_driver import AccessoryDriver +from pyhap.connection import HAPConnectionHandle from pyhap.hap_protocol import HAPServerProtocol @@ -18,8 +19,8 @@ async def test_we_can_start_stop(driver: AccessoryDriver) -> None: server = hap_server.HAPServer(addr_info, driver) await server.async_start(loop) - server.connections[client_1_addr_info] = MagicMock() - server.connections[client_2_addr_info] = MagicMock() + server.connections[HAPConnectionHandle(client_1_addr_info, 1)] = MagicMock() + server.connections[HAPConnectionHandle(client_2_addr_info, 2)] = MagicMock() server.async_stop() @@ -66,7 +67,9 @@ async def test_idle_connection_cleanup() -> None: server = hap_server.HAPServer(addr_info, driver) await server.async_start(loop) check_idle = MagicMock() - server.connections[client_1_addr_info] = MagicMock(check_idle=check_idle) + server.connections[HAPConnectionHandle(client_1_addr_info, 1)] = MagicMock( + check_idle=check_idle + ) for _ in range(3): await asyncio.sleep(0) assert check_idle.called @@ -93,25 +96,26 @@ def _save_event(hap_event: bytes) -> None: # Patch the protocol to capture outgoing events instead of # writing them to a socket. hap_server_protocol.write = _save_event # ty: ignore[invalid-assignment] - hap_server_protocol.peername = addr_info - server.accessory_handler.topics["1.33"] = {addr_info} - server.accessory_handler.topics["2.33"] = {addr_info} - server.accessory_handler.topics["3.33"] = {addr_info} + connection = HAPConnectionHandle(addr_info, 1) + hap_server_protocol.connection_handle = connection + server.accessory_handler.topics["1.33"] = {connection} + server.accessory_handler.topics["2.33"] = {connection} + server.accessory_handler.topics["3.33"] = {connection} - assert server.push_event({"aid": 1, "iid": 33, "value": False}, addr_info) is False + assert server.push_event({"aid": 1, "iid": 33, "value": False}, connection) is False await asyncio.sleep(0) - server.connections[addr_info] = hap_server_protocol + server.connections[connection] = hap_server_protocol assert ( - server.push_event({"aid": 1, "iid": 33, "value": False}, addr_info, True) + server.push_event({"aid": 1, "iid": 33, "value": False}, connection, True) is True ) assert ( - server.push_event({"aid": 2, "iid": 33, "value": False}, addr_info, True) + server.push_event({"aid": 2, "iid": 33, "value": False}, connection, True) is True ) assert ( - server.push_event({"aid": 3, "iid": 33, "value": False}, addr_info, True) + server.push_event({"aid": 3, "iid": 33, "value": False}, connection, True) is True ) @@ -125,15 +129,15 @@ def _save_event(hap_event: bytes) -> None: hap_events = [] assert ( - server.push_event({"aid": 1, "iid": 33, "value": False}, addr_info, False) + server.push_event({"aid": 1, "iid": 33, "value": False}, connection, False) is True ) assert ( - server.push_event({"aid": 2, "iid": 33, "value": False}, addr_info, False) + server.push_event({"aid": 2, "iid": 33, "value": False}, connection, False) is True ) assert ( - server.push_event({"aid": 3, "iid": 33, "value": False}, addr_info, False) + server.push_event({"aid": 3, "iid": 33, "value": False}, connection, False) is True ) @@ -142,7 +146,7 @@ def _save_event(hap_event: bytes) -> None: # Ensure that a the event is not sent if its unsubscribed during # the coalesce delay - server.accessory_handler.topics["1.33"].remove(addr_info) + server.accessory_handler.topics["1.33"].remove(connection) await asyncio.sleep(0.55) assert hap_events == [ @@ -177,20 +181,22 @@ def _save_event(hap_event: bytes) -> None: # Patch the protocol to capture outgoing events instead of # writing them to a socket. hap_server_protocol.write = _save_event # ty: ignore[invalid-assignment] - hap_server_protocol.peername = addr_info - server.accessory_handler.topics["1.33"] = {addr_info} - server.accessory_handler.topics["2.33"] = {addr_info} - server.connections[addr_info] = hap_server_protocol + connection = HAPConnectionHandle(addr_info, 1) + hap_server_protocol.connection_handle = connection + server.accessory_handler.topics["1.33"] = {connection} + server.accessory_handler.topics["2.33"] = {connection} + server.connections[connection] = hap_server_protocol assert ( - server.push_event({"aid": 1, "iid": 33, "value": False}, addr_info, True) + server.push_event({"aid": 1, "iid": 33, "value": False}, connection, True) is True ) assert ( - server.push_event({"aid": 1, "iid": 33, "value": True}, addr_info, True) is True + server.push_event({"aid": 1, "iid": 33, "value": True}, connection, True) + is True ) assert ( - server.push_event({"aid": 2, "iid": 33, "value": False}, addr_info, True) + server.push_event({"aid": 2, "iid": 33, "value": False}, connection, True) is True ) diff --git a/tests/test_hksv_gating.py b/tests/test_hksv_gating.py index ccd1a3f2..3d038618 100644 --- a/tests/test_hksv_gating.py +++ b/tests/test_hksv_gating.py @@ -12,6 +12,7 @@ from pyhap.accessory_driver import AccessoryDriver from pyhap.camera import Camera from pyhap.hds_protocol import EVENT, REQUEST, RESPONSE, HDSStatus, Message +from tests.conftest import client_write Reason = hds_recording.RecordingReason @@ -184,9 +185,12 @@ async def test_camera_off_closes_running_recording(camera: Any) -> None: assert hub.open(1).status == HDSStatus.SUCCESS await camera.recording.wait() - camera.get_service("CameraOperatingMode").get_characteristic( - "HomeKitCameraActive" - ).client_update_value(0) + await client_write( + camera.get_service("CameraOperatingMode").get_characteristic( + "HomeKitCameraActive" + ), + 0, + ) await asyncio.wait_for(camera.cleaning.wait(), 1) camera.release.set() await asyncio.wait([camera._recording_stream._task]) @@ -205,9 +209,12 @@ async def test_camera_turned_on_keeps_running_recording( assert hub.open(1).status == HDSStatus.SUCCESS await camera.recording.wait() - camera.get_service("CameraOperatingMode").get_characteristic( - "HomeKitCameraActive" - ).client_update_value(1) + await client_write( + camera.get_service("CameraOperatingMode").get_characteristic( + "HomeKitCameraActive" + ), + 1, + ) assert camera._recording_stream.streaming assert not [m for m in hub.messages() if m.kind == EVENT and m.topic == "close"] diff --git a/tests/test_hksv_recording.py b/tests/test_hksv_recording.py index fd0e8e05..219a391b 100644 --- a/tests/test_hksv_recording.py +++ b/tests/test_hksv_recording.py @@ -6,7 +6,10 @@ test_hds_recording.py. """ +import inspect +import math import os +import time from typing import Any from unittest.mock import MagicMock, patch @@ -16,9 +19,18 @@ from pyhap.accessory import STANDALONE_AID from pyhap.accessory_driver import AccessoryDriver from pyhap.camera import Camera -from pyhap.const import HAP_REPR_AID, HAP_REPR_CHARS, HAP_REPR_IID, HAP_REPR_VALUE +from pyhap.connection import HAPConnectionHandle +from pyhap.const import ( + HAP_REPR_AID, + HAP_REPR_CHARS, + HAP_REPR_IID, + HAP_REPR_VALUE, + RESPONSE_TIMEOUT, +) +from pyhap.context import CharReadContext, CharWriteContext from pyhap.hap_protocol import HAPServerProtocol from pyhap.util import base64_to_bytes, to_base64_str +from tests.conftest import client_write @pytest.fixture(name="recording_camera") @@ -264,6 +276,21 @@ def test_data_stream_transport_service_present(recording_camera: Any) -> None: ) +def _write_context(camera: Any, client: tuple[str, int]) -> CharWriteContext: + """The write context of a SetupDataStreamTransport write of ``client``.""" + char = camera.get_service("DataStreamTransportManagement").get_characteristic( + "SetupDataStreamTransport" + ) + return CharWriteContext( + client_addr=client, + client_uuid=None, + connection=HAPConnectionHandle(client, 1), + deadline=time.monotonic() + RESPONSE_TIMEOUT, + characteristic=char, + is_admin=True, + ) + + def test_setup_data_stream_transport_without_session_errors( recording_camera: Any, ) -> None: @@ -271,10 +298,10 @@ def test_setup_data_stream_transport_without_session_errors( # No session key for this client, and no listener started. request = tlv.encode(hds.SETUP_TYPES["CONTROLLER_KEY_SALT"], b"\x11" * 32) # SetupDataStreamTransport is a write-response characteristic: the encoded - # response is RETURNED from the setter (so HAP puts it in the write + # response is RETURNED from the handler (so HAP puts it in the write # response), not stored on the characteristic. value = camera.set_data_stream_transport( - to_base64_str(request), sender_client_addr=("10.0.0.9", 5000) + to_base64_str(request), _write_context(camera, ("10.0.0.9", 5000)) ) objs = tlv.decode(base64_to_bytes(value)) assert objs[hds.SETUP_RESPONSE_TYPES["STATUS"]] == hds.SETUP_STATUS_GENERIC_ERROR @@ -296,15 +323,15 @@ def _hap_connection( return connection -def _write_setup( - camera: Any, client: tuple[str, int], controller_key_salt: bytes +async def _write_setup( + camera: Any, connection: HAPServerProtocol, controller_key_salt: bytes ) -> dict[bytes, Any]: """Write SetupDataStreamTransport through the HAP write-response path.""" char = camera.get_service("DataStreamTransportManagement").get_characteristic( "SetupDataStreamTransport" ) request = tlv.encode(hds.SETUP_TYPES["CONTROLLER_KEY_SALT"], controller_key_salt) - response = camera.driver.set_characteristics( + response = camera.driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -315,25 +342,31 @@ def _write_setup( } ] }, - client, + connection.peername, + RESPONSE_TIMEOUT, + connection=connection.connection_handle, ) - return tlv.decode(base64_to_bytes(response[HAP_REPR_CHARS][0][HAP_REPR_VALUE])) + assert inspect.isawaitable(response) + result = await response + assert result is not None + return tlv.decode(base64_to_bytes(result[HAP_REPR_CHARS][0][HAP_REPR_VALUE])) @pytest.mark.asyncio async def test_setup_data_stream_transport_write_response_plumbing( recording_camera: Any, ) -> None: - # The HAP write path hands the setter the sender's address and forwards its - # RETURN value. The HDS keys come from that connection's session key. + # The HAP write path hands the handler the writing connection and + # forwards its RETURN value. The HDS keys come from that connection's + # session key. camera = recording_camera await camera._ensure_hds_listener() try: client = ("10.0.0.9", 5000) shared_key, controller_key_salt = os.urandom(32), os.urandom(32) _hap_connection(camera, ("10.0.0.8", 5000), os.urandom(32)) - _hap_connection(camera, client, shared_key) - objs = _write_setup(camera, client, controller_key_salt) + connection = _hap_connection(camera, client, shared_key) + objs = await _write_setup(camera, connection, controller_key_salt) assert objs[hds.SETUP_RESPONSE_TYPES["STATUS"]] == hds.SETUP_STATUS_SUCCESS accessory_key_salt = objs[hds.SETUP_RESPONSE_TYPES["ACCESSORY_KEY_SALT"]] (pending,) = camera._hds_listener._pending @@ -353,8 +386,8 @@ async def test_setup_data_stream_transport_unencrypted_connection_errors( await camera._ensure_hds_listener() try: client = ("10.0.0.9", 5000) - _hap_connection(camera, client) - objs = _write_setup(camera, client, os.urandom(32)) + connection = _hap_connection(camera, client) + objs = await _write_setup(camera, connection, os.urandom(32)) assert ( objs[hds.SETUP_RESPONSE_TYPES["STATUS"]] == hds.SETUP_STATUS_GENERIC_ERROR ) @@ -372,7 +405,6 @@ def test_single_argument_setter_still_called_with_one_argument( mute = recording_camera.get_service("Microphone").get_characteristic("Mute") seen = [] mute.setter_callback = seen.append - assert mute._setter_wants_addr() is False mute.client_update_value(True, ("10.0.0.9", 5000)) assert seen == [True] @@ -388,7 +420,7 @@ async def test_setup_data_stream_transport_with_session( _hap_connection(camera, client, os.urandom(32)) request = tlv.encode(hds.SETUP_TYPES["CONTROLLER_KEY_SALT"], os.urandom(32)) value = camera.set_data_stream_transport( - to_base64_str(request), sender_client_addr=client + to_base64_str(request), _write_context(camera, client) ) objs = tlv.decode(base64_to_bytes(value)) assert objs[hds.SETUP_RESPONSE_TYPES["STATUS"]] == hds.SETUP_STATUS_SUCCESS @@ -406,7 +438,7 @@ async def test_setup_data_stream_transport_with_session( await camera.stop() -def test_camera_off_in_home_app_marks_sensor_inactive( +async def test_camera_off_in_home_app_marks_sensor_inactive( recording_camera: Any, ) -> None: camera_active = recording_camera.get_service( @@ -418,7 +450,7 @@ def test_camera_off_in_home_app_marks_sensor_inactive( recording_camera.homekit_camera_active_changed = MagicMock() with patch.object(recording_camera, "publish") as publish: - camera_active.client_update_value(0) + await client_write(camera_active, 0) # Subscribed controllers learn about the inactive sensor, exactly once. events = [ call.args[0] for call in publish.call_args_list if call.args[1] is status_active @@ -427,25 +459,42 @@ def test_camera_off_in_home_app_marks_sensor_inactive( assert status_active.get_value() is False recording_camera.homekit_camera_active_changed.assert_called_once_with(False) - camera_active.client_update_value(1) + await client_write(camera_active, 1) assert status_active.get_value() is True recording_camera.homekit_camera_active_changed.assert_called_with(True) -def test_sensor_follows_camera_active_set_without_write( +async def test_sensor_follows_camera_active_set_without_write( recording_camera: Any, ) -> None: - """E.g. a restored or locally set value, which runs no setter.""" - recording_camera.get_service("CameraOperatingMode").get_characteristic( + """E.g. a restored or locally set value, which runs no setter. + + A sync ``get_value`` answers the stored value until a read runs: a + delegate answers the reads, deriving the sensor status from the + camera's active state. + """ + camera = recording_camera + camera.get_service("CameraOperatingMode").get_characteristic( "HomeKitCameraActive" ).set_value(0) - status_active = recording_camera.get_service("MotionSensor").get_characteristic( + status_active = camera.get_service("MotionSensor").get_characteristic( "StatusActive" ) - assert status_active.get_value() is False + + assert status_active.get_value() is True + + context = CharReadContext( + client_addr=None, + client_uuid=None, + connection=HAPConnectionHandle(None, 1), + deadline=math.inf, + characteristic=status_active, + ) + assert status_active.delegate is not None + assert await status_active.delegate.on_get(context) is False -def test_sensor_event_after_restored_camera_off(recording_camera: Any) -> None: +async def test_sensor_event_after_restored_camera_off(recording_camera: Any) -> None: """A restore sets the value without a write, the next write still notifies.""" camera_active = recording_camera.get_service( "CameraOperatingMode" @@ -456,7 +505,7 @@ def test_sensor_event_after_restored_camera_off(recording_camera: Any) -> None: camera_active.set_value(0, should_notify=False) with patch.object(recording_camera, "publish") as publish: - camera_active.client_update_value(1) + await client_write(camera_active, 1) events = [ call.args[0] for call in publish.call_args_list if call.args[1] is status_active ] diff --git a/tests/test_hksv_state.py b/tests/test_hksv_state.py index 6cb21f96..6115c4c3 100644 --- a/tests/test_hksv_state.py +++ b/tests/test_hksv_state.py @@ -4,6 +4,7 @@ from collections.abc import AsyncIterator import io import json +import math import pathlib from typing import Any from unittest.mock import MagicMock, patch @@ -18,6 +19,7 @@ from pyhap.encoder import AccessoryEncoder from pyhap.state import State from pyhap.util import base64_to_bytes, to_base64_str +from tests.conftest import client_write CAMERA_AID = 2 SELECTED_CHAR = ("CameraRecordingManagement", "SelectedCameraRecordingConfiguration") @@ -95,7 +97,7 @@ def _char(camera: Any, service: str, name: str) -> Any: async def _write_recording_state(camera: Any) -> None: """Simulate the hub enabling recording through HAP writes.""" for (service, name), value in WRITES.items(): - _char(camera, service, name).client_update_value(value) + await client_write(_char(camera, service, name), value) await _drain() @@ -119,7 +121,7 @@ async def test_hub_burst_is_saved_once(driver: Any) -> None: _char(camera, "CameraRecordingManagement", "Active").setter_callback = app_setter for (service, name), value in WRITES.items(): - _char(camera, service, name).client_update_value(value) + await client_write(_char(camera, service, name), value) assert driver.async_persist.call_count == 0 await _drain() @@ -132,10 +134,10 @@ async def test_hub_burst_is_saved_once(driver: Any) -> None: } # An unchanged write saves nothing, a later change is saved again. - _char(camera, "CameraRecordingManagement", "Active").client_update_value(1) + await client_write(_char(camera, "CameraRecordingManagement", "Active"), 1) await _drain() assert driver.async_persist.call_count == 1 - _char(camera, "CameraRecordingManagement", "Active").client_update_value(0) + await client_write(_char(camera, "CameraRecordingManagement", "Active"), 0) await _drain() assert driver.async_persist.call_count == 2 assert driver.state.accessory_states[CAMERA_AID]["recording"]["Active"] == 0 @@ -147,7 +149,7 @@ async def test_other_characteristics_are_not_stored( camera = Camera(_options(), driver, "Cam", aid=CAMERA_AID) camera.set_motion_detected(True) # Same name as the recording Active, on the streaming service. - _char(camera, "CameraRTPStreamManagement", "Active").client_update_value(0) + await client_write(_char(camera, "CameraRTPStreamManagement", "Active"), 0) await _drain() assert driver.async_persist.call_count == 0 assert not any(driver.state.accessory_states.values()) @@ -158,7 +160,7 @@ async def test_camera_rebuilt_before_save_restores_change( ) -> None: camera = Camera(_options(), driver, "Cam", aid=CAMERA_AID) for (service, name), value in WRITES.items(): - _char(camera, service, name).client_update_value(value) + await client_write(_char(camera, service, name), value) rebuilt = Camera(_options(), driver, "Cam", aid=CAMERA_AID) _assert_state(rebuilt, WRITES, selected=True) @@ -187,7 +189,7 @@ async def test_stale_selected_configuration_dropped(driver: Any) -> None: _assert_state(camera, {**WRITES, SELECTED_CHAR: ""}, selected=False) -@pytest.mark.parametrize("value", [None, 7, "1", float("inf"), float("nan")]) +@pytest.mark.parametrize("value", [None, 7, "1", math.inf, float("nan")]) async def test_invalid_stored_value_keeps_its_default( driver: Any, caplog: pytest.LogCaptureFixture, value: Any ) -> None: @@ -234,7 +236,7 @@ async def test_no_selection_restores_without_warning( driver: Any, caplog: pytest.LogCaptureFixture ) -> None: camera = Camera(_options(), driver, "Cam", aid=CAMERA_AID) - _char(camera, "CameraRecordingManagement", "Active").client_update_value(1) + await client_write(_char(camera, "CameraRecordingManagement", "Active"), 1) Camera(_options(), driver, "Cam", aid=CAMERA_AID) assert "Ignoring" not in caplog.text @@ -245,7 +247,7 @@ async def test_restored_selection_survives_a_later_write( ) -> None: await _write_recording_state(Camera(_options(), driver, "Cam", aid=CAMERA_AID)) restored = Camera(_options(), driver, "Cam", aid=CAMERA_AID) - _char(restored, "CameraOperatingMode", "HomeKitCameraActive").client_update_value(1) + await client_write(_char(restored, "CameraOperatingMode", "HomeKitCameraActive"), 1) rebuilt = Camera(_options(), driver, "Cam", aid=CAMERA_AID) hk_active = ("CameraOperatingMode", "HomeKitCameraActive") @@ -275,8 +277,8 @@ async def test_rejected_selection_write_is_not_stored( await _write_recording_state(camera) # pyhap sets the value before the setter rejects it. with pytest.raises(KeyError): - _char(camera, *SELECTED_CHAR).client_update_value(to_base64_str(b"\xff\x00")) - _char(camera, "CameraOperatingMode", "HomeKitCameraActive").client_update_value(1) + await client_write(_char(camera, *SELECTED_CHAR), to_base64_str(b"\xff\x00")) + await client_write(_char(camera, "CameraOperatingMode", "HomeKitCameraActive"), 1) rebuilt = Camera(_options(), driver, "Cam", aid=CAMERA_AID) hk_active = ("CameraOperatingMode", "HomeKitCameraActive") @@ -290,13 +292,13 @@ async def test_closed_loop_does_not_fail_the_write( loop = driver.loop driver.loop = MagicMock() driver.loop.call_soon_threadsafe.side_effect = RuntimeError("Event loop is closed") - _char(camera, "CameraRecordingManagement", "Active").client_update_value(1) + await client_write(_char(camera, "CameraRecordingManagement", "Active"), 1) assert driver.state.accessory_states[CAMERA_AID]["recording"]["Active"] == 1 assert "Could not schedule saving the recording state" in caplog.text # The next change schedules the save again. driver.loop = loop - _char(camera, "CameraRecordingManagement", "Active").client_update_value(0) + await client_write(_char(camera, "CameraRecordingManagement", "Active"), 0) await _drain() assert driver.async_persist.call_count == 1 @@ -446,7 +448,7 @@ async def test_last_unpair_resets_recording_state(driver: Any, bridged: bool) -> restored = Camera(_options(), driver, "Cam", aid=CAMERA_AID) _assert_state(restored, DEFAULTS, selected=False) # The new home's first write does not bring the old selection back. - _char(camera, "CameraRecordingManagement", "Active").client_update_value(1) + await client_write(_char(camera, "CameraRecordingManagement", "Active"), 1) stored = driver.state.accessory_states[CAMERA_AID]["recording"] assert stored["SelectedCameraRecordingConfiguration"] is None diff --git a/tests/test_lifecycle.py b/tests/test_lifecycle.py new file mode 100644 index 00000000..30e8783d --- /dev/null +++ b/tests/test_lifecycle.py @@ -0,0 +1,262 @@ +"""Tests for the accessory connection lifecycle hooks.""" + +import asyncio +import inspect +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch +from uuid import UUID + +from chacha20poly1305_reuseable import ChaCha20Poly1305Reusable as ChaCha20Poly1305 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ed25519 +import pytest + +from pyhap import hap_handler, tlv +from pyhap.accessory import STANDALONE_AID, Accessory, Bridge +from pyhap.accessory_driver import AccessoryDriver +from pyhap.const import HAP_PERMISSIONS +from pyhap.hap_protocol import HAPServerProtocol + +CLIENT_UUID = UUID("7d0d1ee9-46fe-4a56-a115-69df3f6860c1") +CLIENT_UUID_BYTES = str(CLIENT_UUID).upper().encode("utf-8") +CLIENT2_UUID_BYTES = b"7d0d1ee9-46fe-4a56-a115-69df3f6860c2" +WRITER = ("1.2.3.4", 5) +ASYNC_TIMEOUT = 1.0 + + +async def _run_scheduled_jobs(rounds: int = 8) -> None: + """Let jobs scheduled by the driver and their tasks run.""" + for _ in range(rounds): + await asyncio.sleep(0) + + +def _ed25519_keypair() -> tuple[ed25519.Ed25519PrivateKey, bytes]: + """A client identity key pair and its raw public key bytes.""" + private_key = ed25519.Ed25519PrivateKey.generate() + public_key = private_key.public_key().public_bytes( + encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw + ) + return private_key, public_key + + +async def _pair_verify(driver: AccessoryDriver, handler: Any) -> None: + """Complete pair verify on ``handler`` as CLIENT_UUID.""" + client_private_key, client_public_key_bytes = _ed25519_keypair() + driver.pair(CLIENT_UUID_BYTES, client_public_key_bytes, HAP_PERMISSIONS.ADMIN) + + handler.is_encrypted = False + response = hap_handler.HAPResponse() + handler.response = response + handler.request_body = tlv.encode( + hap_handler.HAP_TLV_TAGS.SEQUENCE_NUM, + hap_handler.HAP_TLV_STATES.M1, + hap_handler.HAP_TLV_TAGS.PUBLIC_KEY, + client_public_key_bytes, + ) + handler.handle_pair_verify() + + assert handler.enc_context is not None + server_public_key: bytes = handler.enc_context["public_key"].public_bytes( + encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw + ) + material = client_public_key_bytes + CLIENT_UUID_BYTES + server_public_key + unencrypted_data = tlv.encode( + hap_handler.HAP_TLV_TAGS.USERNAME, + CLIENT_UUID_BYTES, + hap_handler.HAP_TLV_TAGS.PROOF, + client_private_key.sign(material), + ) + cipher = ChaCha20Poly1305(handler.enc_context["pre_session_key"]) + + response = hap_handler.HAPResponse() + handler.response = response + handler.request_body = tlv.encode( + hap_handler.HAP_TLV_TAGS.SEQUENCE_NUM, + hap_handler.HAP_TLV_STATES.M3, + hap_handler.HAP_TLV_TAGS.ENCRYPTED_DATA, + cipher.encrypt( + hap_handler.HAPServerHandler.PVERIFY_2_NONCE, + bytes(unencrypted_data), + b"", + ), + ) + handler.handle_pair_verify() + + +async def test_default_hooks_are_async_noops(driver: AccessoryDriver) -> None: + """The base hooks are coroutine functions that do nothing.""" + acc = Accessory(driver, "Test Accessory", aid=STANDALONE_AID) + driver.add_accessory(acc) + + assert inspect.iscoroutinefunction(acc.client_connected) + assert inspect.iscoroutinefunction(acc.client_verified) + assert await acc.client_connected(WRITER) is None + assert await acc.client_verified(WRITER, CLIENT_UUID) is None + + +async def test_client_connected_of_a_failing_hook_is_isolated( + driver: AccessoryDriver, caplog: pytest.LogCaptureFixture +) -> None: + """A raising hook is logged and never reaches the connection.""" + acc = Accessory(driver, "Test Accessory", aid=STANDALONE_AID) + calls: list[Any] = [] + + async def _hook(client_addr: Any) -> None: + calls.append(client_addr) + raise RuntimeError("boom") + + acc.client_connected = _hook + driver.add_accessory(acc) + driver.loop = asyncio.get_running_loop() + + driver.client_connected(WRITER) + await _run_scheduled_jobs() + + assert calls == [WRITER] + assert "failed to run client_connected" in caplog.text + assert "boom" in caplog.text + + +async def test_client_verified_of_a_failing_hook_is_isolated( + driver: AccessoryDriver, caplog: pytest.LogCaptureFixture +) -> None: + """A raising verified hook is logged and never reaches the response.""" + acc = Accessory(driver, "Test Accessory", aid=STANDALONE_AID) + + async def _hook(client_addr: Any, client_uuid: Any) -> None: + raise RuntimeError("boom") + + acc.client_verified = _hook + driver.add_accessory(acc) + driver.loop = asyncio.get_running_loop() + + driver.client_verified(WRITER, CLIENT_UUID) + await _run_scheduled_jobs() + + assert "failed to run client_verified" in caplog.text + + +async def test_bridge_tells_every_accessory(driver: AccessoryDriver) -> None: + """A bridge forwards both hooks to each bridged accessory.""" + bridge = Bridge(driver, "Test Bridge") + first = Accessory(driver, "First") + second = Accessory(driver, "Second") + bridge.add_accessory(first) + bridge.add_accessory(second) + driver.add_accessory(bridge) + driver.loop = asyncio.get_running_loop() + + with ( + patch.object(first, "client_connected", AsyncMock()) as first_connected, + patch.object(second, "client_connected", AsyncMock()) as second_connected, + patch.object(first, "client_verified", AsyncMock()) as first_verified, + patch.object(second, "client_verified", AsyncMock()) as second_verified, + ): + driver.client_connected(WRITER) + driver.client_verified(WRITER, CLIENT_UUID) + await _run_scheduled_jobs() + + first_connected.assert_awaited_once_with(WRITER) + second_connected.assert_awaited_once_with(WRITER) + first_verified.assert_awaited_once_with(WRITER, CLIENT_UUID) + second_verified.assert_awaited_once_with(WRITER, CLIENT_UUID) + + +async def test_bridge_isolates_a_failing_accessory(driver: AccessoryDriver) -> None: + """One bridged accessory's raising hook does not stop the others.""" + bridge = Bridge(driver, "Test Bridge") + first = Accessory(driver, "First") + second = Accessory(driver, "Second") + bridge.add_accessory(first) + bridge.add_accessory(second) + driver.add_accessory(bridge) + driver.loop = asyncio.get_running_loop() + + with ( + patch.object( + first, "client_connected", AsyncMock(side_effect=RuntimeError("boom")) + ), + patch.object(second, "client_connected", AsyncMock()) as second_connected, + ): + driver.client_connected(WRITER) + await _run_scheduled_jobs() + + second_connected.assert_awaited_once_with(WRITER) + + +async def test_connection_made_tells_the_accessory(driver: AccessoryDriver) -> None: + """An accepted connection runs the accessory's client_connected.""" + driver.add_accessory(Accessory(driver, "Test Accessory")) + driver.loop = asyncio.get_running_loop() + + with ( + patch.object(driver.accessory, "client_connected", AsyncMock()) as connected, + patch.object(driver.accessory, "client_verified", AsyncMock()) as verified, + ): + transport = MagicMock() + transport.get_extra_info.return_value = WRITER + proto = HAPServerProtocol(asyncio.get_running_loop(), {}, driver) + proto.connection_made(transport) + await _run_scheduled_jobs() + + connected.assert_awaited_once_with(WRITER) + verified.assert_not_awaited() + + +async def test_pair_verify_tells_the_accessory(driver: AccessoryDriver) -> None: + """A finished pair verify runs the accessory's client_verified.""" + driver.add_accessory(Accessory(driver, "Test Accessory")) + driver.loop = asyncio.get_running_loop() + handler = hap_handler.HAPServerHandler(driver, WRITER) + + with patch.object(driver.accessory, "client_verified", AsyncMock()) as verified: + await _pair_verify(driver, handler) + await _run_scheduled_jobs() + + verified.assert_awaited_once_with(WRITER, CLIENT_UUID) + + +async def test_pair_verify_failure_tells_the_accessory_nothing( + driver: AccessoryDriver, +) -> None: + """A pair verify that fails authentication runs no hook.""" + driver.add_accessory(Accessory(driver, "Test Accessory")) + driver.loop = asyncio.get_running_loop() + handler = hap_handler.HAPServerHandler(driver, WRITER) + + with patch.object(driver.accessory, "client_verified", AsyncMock()) as verified: + # An unknown client cannot finish pair verify: the accessory + # stays paired, but CLIENT2 never paired with it. + client_private_key, client_public_key_bytes = _ed25519_keypair() + driver.pair(CLIENT_UUID_BYTES, client_public_key_bytes, HAP_PERMISSIONS.ADMIN) + handler.is_encrypted = False + response = hap_handler.HAPResponse() + handler.response = response + handler.request_body = tlv.encode( + hap_handler.HAP_TLV_TAGS.SEQUENCE_NUM, + hap_handler.HAP_TLV_STATES.M1, + hap_handler.HAP_TLV_TAGS.PUBLIC_KEY, + client_public_key_bytes, + ) + handler.handle_pair_verify() + assert handler.enc_context is not None + cipher = ChaCha20Poly1305(handler.enc_context["pre_session_key"]) + response = hap_handler.HAPResponse() + handler.response = response + handler.request_body = tlv.encode( + hap_handler.HAP_TLV_TAGS.SEQUENCE_NUM, + hap_handler.HAP_TLV_STATES.M3, + hap_handler.HAP_TLV_TAGS.ENCRYPTED_DATA, + cipher.encrypt( + hap_handler.HAPServerHandler.PVERIFY_2_NONCE, + bytes( + tlv.encode(hap_handler.HAP_TLV_TAGS.USERNAME, CLIENT2_UUID_BYTES) + ), + b"", + ), + ) + handler.handle_pair_verify() + await _run_scheduled_jobs() + + verified.assert_not_awaited() + assert handler.client_uuid is None diff --git a/tests/test_media_multi_tier_e2e.py b/tests/test_media_multi_tier_e2e.py index b4da7451..bb3e7cf8 100644 --- a/tests/test_media_multi_tier_e2e.py +++ b/tests/test_media_multi_tier_e2e.py @@ -21,11 +21,13 @@ from pyhap.camera import Camera from pyhap.camera_multi_tier import MultiTierController from pyhap.camera_stream import StreamError +from pyhap.context import CharWriteContext from pyhap.media.multi_tier_delegate import MultiTierMediaDelegate from pyhap.media.pool import SourcePool from pyhap.media.webrtc_delegate import WebRTCMediaDelegate from pyhap.media.worker import MediaWorker from pyhap.util import base64_to_bytes, to_base64_str +from tests.conftest import connection_of from .media_hap import ( SyntheticPull, @@ -119,6 +121,23 @@ def _controller(camera: Camera) -> MultiTierController: return camera.multi_tier_controllers[SENSOR] +async def _write(camera: Camera, name: str, payload: bytes) -> str: + """Write a control characteristic like the connection at CLIENT.""" + controller = _controller(camera) + char = controller.service.get_characteristic(name) + context = CharWriteContext( + client_addr=CLIENT, + client_uuid=None, + connection=connection_of(CLIENT), + deadline=asyncio.get_running_loop().time() + controller.hook_timeout, + characteristic=char, + is_admin=True, + ) + delegate = char.delegate + assert delegate is not None + return await delegate.on_set(to_base64_str(payload), context) # ty: ignore[unsound-return] + + async def setup(camera: Camera, peer: SrtpController) -> hksv3.SetupEndpointsResponse: """Write Setup Endpoints towards the loopback controller.""" suite = hksv3.SRTPCryptoSuite.AES_CM_128_HMAC_SHA1_80 @@ -128,9 +147,7 @@ async def setup(camera: Camera, peer: SrtpController) -> hksv3.SetupEndpointsRes hksv3.SRTPParameters(suite, VIDEO_KEY[:16], VIDEO_KEY[16:]), hksv3.SRTPParameters(suite, AUDIO_KEY[:16], AUDIO_KEY[16:]), ) - answer_value = await _controller(camera)._set_setup_endpoints( - to_base64_str(request.encode()), CLIENT - ) + answer_value = await _write(camera, "SetupEndpoints", request.encode()) return hksv3.SetupEndpointsResponse.decode(base64_to_bytes(answer_value)) @@ -142,9 +159,7 @@ async def control(camera: Camera, command: int, tier: int | None = None) -> int: data += hksv3.encode_item(4, CONTROLLER_VIDEO_SSRC.to_bytes(4, "little")) data += hksv3.encode_item(5, (1).to_bytes(4, "little")) data += hksv3.encode_item(6, (0x5678).to_bytes(4, "little")) - answer_value = await _controller(camera)._set_streaming_control( - to_base64_str(data), CLIENT - ) + answer_value = await _write(camera, "RTPStreamingControl", data) fields = dict(hksv3.decode_items(base64_to_bytes(answer_value))) return fields[2][0] diff --git a/tests/test_service.py b/tests/test_service.py index 1b3b44e2..5806d65a 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -2,6 +2,7 @@ from unittest.mock import Mock, call, patch from uuid import uuid1 +import warnings import pytest @@ -11,8 +12,10 @@ PROP_FORMAT, PROP_PERMISSIONS, Characteristic, + _LegacyCallbackDelegateWrapper, ) -from pyhap.service import Service +from pyhap.delegates import CharacteristicDelegate, ServiceDelegate +from pyhap.service import Service, _LegacySetterDelegateWrapper CHAR_PROPS = { PROP_FORMAT: HAP_FORMAT_INT, @@ -85,7 +88,13 @@ def test_configure_char() -> None: service.configure_char("Char 1") mock_override_prop.assert_not_called() mock_set_value.assert_not_called() - assert service.get_characteristic("Char 1").setter_callback is None + assert isinstance( + service.get_characteristic("Char 1").delegate, + _LegacyCallbackDelegateWrapper, + ) + delegate = service.get_characteristic("Char 1").delegate + assert isinstance(delegate, _LegacyCallbackDelegateWrapper) + assert delegate.setter_callback is None with patch(pyhap_char + ".override_properties") as mock_override_prop: new_properties = {"Format": "string"} @@ -246,3 +255,107 @@ def test_from_dict() -> None: mock_char_loader.get_char.assert_has_calls( [call("Char 1"), call("Char 2")], any_order=True ) + + +class _AsyncGate(ServiceDelegate): + """A service delegate overriding the grouped gate.""" + + +class _AsyncCharDelegate(CharacteristicDelegate): + """A characteristic delegate.""" + + +def test_service_delegate_assignment() -> None: + """An assigned delegate is the service's delegate.""" + service = Service(uuid1()) + delegate = _AsyncGate() + + service.delegate = delegate + + assert service.delegate is delegate + + service.delegate = None + + assert isinstance(service.delegate, _LegacySetterDelegateWrapper) + assert service.delegate.setter is None + + +def test_configure_char_wires_delegate() -> None: + """configure_char wires a delegate instance or class onto the char.""" + service = Service(uuid1()) + service.add_characteristic(*get_chars()) + delegate = _AsyncCharDelegate() + + configured = service.configure_char("Char 1", delegate=delegate) + + assert configured.delegate is delegate + + +def test_service_delegate_conflicts_with_legacy_setter() -> None: + """Either a service delegate or the legacy setter, never both.""" + service = Service(uuid1()) + + service.setter_callback = lambda values: None # noqa: E731 + with pytest.raises(ValueError, match="has a legacy setter_callback"): + service.delegate = _AsyncGate() + + service.setter_callback = None + service.delegate = _AsyncGate() + + with pytest.raises(ValueError, match="has a delegate"): + service.setter_callback = lambda values: None # noqa: E731 + + service.delegate = None + service.setter_callback = lambda values: None # noqa: E731 + + assert service.setter_callback is not None + + +def test_configure_char_with_both_conflicts() -> None: + """configure_char rejects a delegate next to a legacy callback.""" + service = Service(uuid1()) + service.add_characteristic(*get_chars()) + + with pytest.raises(ValueError, match="has a legacy callback"): + service.configure_char( + "Char 1", + setter_callback=lambda value: None, + delegate=_AsyncCharDelegate(), + ) + + +def test_legacy_setter_warns_deprecated() -> None: + """Assigning a legacy grouped setter announces its deprecation.""" + service = Service(uuid1()) + + with pytest.deprecated_call(match="legacy setter_callback is deprecated"): + service.setter_callback = lambda values: None # noqa: E731 + + +def test_configure_char_legacy_callbacks_warn_deprecated() -> None: + """The legacy configure_char parameters announce their deprecation.""" + service = Service(uuid1()) + service.add_characteristic(*get_chars()) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + service.configure_char("Char 1", setter_callback=lambda value: None) + service.configure_char("Char 2", getter_callback=lambda: 1) + (setter_warning, getter_warning) = caught + assert "legacy setter_callback is deprecated" in str(setter_warning.message) + assert setter_warning.filename == __file__ + assert "legacy getter_callback is deprecated" in str(getter_warning.message) + assert getter_warning.filename == __file__ + + +def test_configure_char_without_delegate() -> None: + """configure_char without a delegate leaves the char without one.""" + service = Service(uuid1()) + service.add_characteristic(*get_chars()) + + configured = service.configure_char("Char 1", value=5) + + assert isinstance(configured.delegate, _LegacyCallbackDelegateWrapper) + assert configured.delegate.getter_callback is None + assert configured.delegate.setter_callback is None + assert configured.value == 5 diff --git a/tests/test_timed_write.py b/tests/test_timed_write.py index 929c919a..289b2d7c 100644 --- a/tests/test_timed_write.py +++ b/tests/test_timed_write.py @@ -1,5 +1,6 @@ """Tests for timed writes (prepare, then write with the pid).""" +import asyncio from collections.abc import Iterator import logging from typing import Any, NamedTuple @@ -21,6 +22,7 @@ HAP_SERVER_STATUS, ) from pyhap.service import Service +from tests.conftest import run_scheduled_jobs CLIENT = ("1.2.3.4", 5000) NOW = 1000.0 @@ -85,18 +87,20 @@ def _write(aid: int, iid: int, pid: int) -> dict[str, Any]: } -def test_prepared_write_is_applied( +async def test_prepared_write_is_applied( driver: AccessoryDriver, door: WritableChar, ) -> None: """Test a write with a prepared pid inside its TTL is applied.""" + driver.loop = asyncio.get_running_loop() with patch("pyhap.accessory_driver.time.monotonic", return_value=NOW) as now: driver.prepare({HAP_REPR_TTL: 2500, HAP_REPR_PID: 7}, CLIENT) now.return_value = NOW + 2.5 assert driver.set_characteristics(_write(door.aid, door.iid, 7), CLIENT) is None + await run_scheduled_jobs() door.setter.assert_called_once_with(1) - assert CLIENT in driver.topics[get_topic(door.aid, door.iid)] + assert driver._connection_of(CLIENT) in driver.topics[get_topic(door.aid, door.iid)] @pytest.mark.parametrize( @@ -131,16 +135,18 @@ def test_unprepared_write_is_ignored( assert get_topic(door.aid, door.iid) not in driver.topics -def test_prepared_write_is_kept_until_its_ttl_ends( +async def test_prepared_write_is_kept_until_its_ttl_ends( driver: AccessoryDriver, door: WritableChar, ) -> None: """Test a later prepare at the last moment of a TTL keeps that write.""" + driver.loop = asyncio.get_running_loop() with patch("pyhap.accessory_driver.time.monotonic", return_value=NOW) as now: driver.prepare({HAP_REPR_TTL: 2500, HAP_REPR_PID: 7}, CLIENT) now.return_value = NOW + 2.5 driver.prepare({HAP_REPR_TTL: 2500, HAP_REPR_PID: 8}, CLIENT) assert driver.set_characteristics(_write(door.aid, door.iid, 7), CLIENT) is None + await run_scheduled_jobs() door.setter.assert_called_once_with(1) @@ -201,13 +207,15 @@ def test_prepare_refuses_non_integers( assert driver.prepared_writes.get(CLIENT, {}) == {} -def test_prepared_pid_is_used_once( +async def test_prepared_pid_is_used_once( driver: AccessoryDriver, door: WritableChar, ) -> None: """Test a prepared pid cannot be replayed.""" + driver.loop = asyncio.get_running_loop() driver.prepare({HAP_REPR_TTL: 2500, HAP_REPR_PID: 7}, CLIENT) assert driver.set_characteristics(_write(door.aid, door.iid, 7), CLIENT) is None + await run_scheduled_jobs() response = driver.set_characteristics(_write(door.aid, door.iid, 7), CLIENT) @@ -215,6 +223,7 @@ def test_prepared_pid_is_used_once( assert response[HAP_REPR_CHARS][0][HAP_REPR_STATUS] == ( HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST ) + await run_scheduled_jobs() door.setter.assert_called_once_with(1) @@ -269,7 +278,7 @@ def _highest_level(records: list[logging.LogRecord]) -> int: "lenient_plain_write_without_tw", ], ) -def test_timed_write_permission( +async def test_timed_write_permission( driver: AccessoryDriver, chars: dict[str, WritableChar], caplog: pytest.LogCaptureFixture, @@ -282,6 +291,7 @@ def test_timed_write_permission( logged: int, ) -> None: """Test a plain write to a timed write characteristic is refused or logged.""" + driver.loop = asyncio.get_running_loop() caplog.set_level(logging.DEBUG, logger="pyhap.accessory_driver") char = chars[name] driver.enforce_timed_writes = enforce @@ -294,6 +304,7 @@ def test_timed_write_permission( } response = driver.set_characteristics(query, CLIENT) + await run_scheduled_jobs() assert _statuses(response) == statuses assert char.setter.call_count == calls