From 89f39c30053a1ca4619e812eb840c6dc8745cfe9 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Fri, 13 Nov 2026 13:29:46 +0100 Subject: [PATCH 01/14] Add HapStatusError to answer a HAP request with a status A callback that fails answers -70402 (service communication failure), whatever went wrong: a busy device, a refused request and a broken one look the same to the controller. This is the error protocol of the callback interface refactor (refactor.md); issue #75 asked for it. HapStatusError carries a HAP status the controller receives for the characteristic, e.g. RESOURCE_BUSY for a lock whose motor is moving. The status set is curated: privileges, permissions and timeouts belong to the accessory driver and cannot be raised, a reserved or unknown status fails at construction with a ValueError. --- docs/source/api/errors.rst | 23 ++++++++++++ pyhap/errors.py | 74 ++++++++++++++++++++++++++++++++++++++ tests/test_errors.py | 59 ++++++++++++++++++++++++++++++ 3 files changed, 156 insertions(+) create mode 100644 docs/source/api/errors.rst create mode 100644 pyhap/errors.py create mode 100644 tests/test_errors.py diff --git a/docs/source/api/errors.rst b/docs/source/api/errors.rst new file mode 100644 index 00000000..398caf45 --- /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/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/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 From b17272dc284b3ec0101b77598d9d6981313cab0f Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Fri, 13 Nov 2026 14:01:25 +0100 Subject: [PATCH 02/14] Add the delegate, context and connection APIs of the callback interface The API side of the callback interface refactor, ahead of the write and read pipelines that dispatch it: - CharacteristicDelegate and ServiceDelegate: the noop-base interfaces replacing the legacy setter/getter attributes over time. Every method is a coroutine function by design - the driver awaits every call, there is no sync/async detection on this path - and a delegate instance may serve many characteristics: the context carries which one a call is about. - Context, ReadContext and WriteContext: frozen dataclasses carrying what a callback knows about the request - the client's address and identity, the connection handle and the deadline - so new input data arrives as new context fields instead of new callback signatures. - HAPConnectionHandle: the stable identity of a controller connection, equal only for the same connection, never for a later one reusing its address. Camera session ownership adopts it first; the driver's remaining per-client state migrates in a second phase, documented in the class docstring. The driver does not dispatch these yet; they are pure API with unit tests and autodoc pages. HapStatusError from the previous commit rides along as the error protocol of the same interface. --- docs/source/api/connection.rst | 22 +++++++ docs/source/api/context.rst | 20 ++++++ docs/source/api/delegates.rst | 28 +++++++++ docs/source/api/errors.rst | 4 +- pyhap/connection.py | 76 +++++++++++++++++++++++ pyhap/context.py | 61 +++++++++++++++++++ pyhap/delegates.py | 103 +++++++++++++++++++++++++++++++ tests/test_connection.py | 49 +++++++++++++++ tests/test_context.py | 108 +++++++++++++++++++++++++++++++++ tests/test_delegates.py | 104 +++++++++++++++++++++++++++++++ 10 files changed, 573 insertions(+), 2 deletions(-) create mode 100644 docs/source/api/connection.rst create mode 100644 docs/source/api/context.rst create mode 100644 docs/source/api/delegates.rst create mode 100644 pyhap/connection.py create mode 100644 pyhap/context.py create mode 100644 pyhap/delegates.py create mode 100644 tests/test_connection.py create mode 100644 tests/test_context.py create mode 100644 tests/test_delegates.py diff --git a/docs/source/api/connection.rst b/docs/source/api/connection.rst new file mode 100644 index 00000000..7761e5fc --- /dev/null +++ b/docs/source/api/connection.rst @@ -0,0 +1,22 @@ +.. _api-connection: + +========== +Connection +========== + +The identity of a controller connection. + +.. currentmodule:: pyhap.connection + +.. autoclass:: HAPConnectionHandle + :members: + +Why not just the client address +=============================== + +The ``(address, port)`` of a connection is unique only while it lives - a +later connection may reuse the address of a closed one. A handle compares +equal only for the same connection, so anything a callback keeps per +connection, a write response, a camera session, cannot leak to a +connection that reused the address. See the class docstring for the +phased migration of the driver's per-client state to the handle. diff --git a/docs/source/api/context.rst b/docs/source/api/context.rst new file mode 100644 index 00000000..2fca846f --- /dev/null +++ b/docs/source/api/context.rst @@ -0,0 +1,20 @@ +.. _api-context: + +======== +Contexts +======== + +The contexts passed to delegate and lifecycle calls. New input data +arrives as new fields of these classes; a callback's signature never +changes. + +.. currentmodule:: pyhap.context + +.. autoclass:: CharContext + :members: + +.. autoclass:: CharReadContext + :members: + +.. autoclass:: CharWriteContext + :members: diff --git a/docs/source/api/delegates.rst b/docs/source/api/delegates.rst new file mode 100644 index 00000000..31f4bf54 --- /dev/null +++ b/docs/source/api/delegates.rst @@ -0,0 +1,28 @@ +.. _api-delegates: + +========= +Delegates +========= + +The delegate interfaces of the callback interface: an object a +characteristic or service is wired up with, receiving a +:class:`~pyhap.context.CharContext` per call. Registration is when the driver +records what a delegate overrides; the read and write paths never +introspect it again. + +.. currentmodule:: pyhap.delegates + +.. autoclass:: CharacteristicDelegate + :members: + +.. autoclass:: ServiceDelegate + :members: + +Async by design +=============== + +Every delegate method is a coroutine function. The driver awaits every +call and enforces the context's deadline - there is no sync/async +detection. An overridden method that is not a coroutine function fails +registration with a :class:`TypeError`, so a wrong method is caught at +its source. diff --git a/docs/source/api/errors.rst b/docs/source/api/errors.rst index 398caf45..d19ce2a4 100644 --- a/docs/source/api/errors.rst +++ b/docs/source/api/errors.rst @@ -1,8 +1,8 @@ .. _api-errors: -===== +======= Errors -===== +======= Errors raised by accessory callbacks to answer a HAP request with a status. diff --git a/pyhap/connection.py b/pyhap/connection.py new file mode 100644 index 00000000..fbc9dc0b --- /dev/null +++ b/pyhap/connection.py @@ -0,0 +1,76 @@ +"""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-client state is keyed by the client address today, + with guards at the connection boundaries (e.g. a write response that + arrives after its connection closed is dropped). The refactor moves + it to the handle in two phases that do not change this class: + + 1. Handles appear in contexts, and camera session ownership uses + them; the address-keyed state keeps its guards. + 2. Event subscriptions, prepared writes, write responses and pending + writes are re-keyed by the handle, and the guards are removed. + """ + + __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..a7a2914b --- /dev/null +++ b/pyhap/context.py @@ -0,0 +1,61 @@ +"""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 + + +@dataclass(frozen=True) +class CharContext: + """What a characteristic callback 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. + """ + + client_addr: tuple[str, int] | None + client_uuid: UUID | None + connection: HAPConnectionHandle + deadline: float + + +@dataclass(frozen=True) +class CharReadContext(CharContext): + """The context of a read, e.g. of ``on_get``. + + :ivar characteristic: The characteristic being read. + """ + + characteristic: Characteristic + + +@dataclass(frozen=True) +class CharWriteContext(CharContext): + """The context of a write, e.g. of ``on_set``. + + :ivar characteristic: The characteristic being written, or ``None`` + for a grouped call that carries several, e.g. a service's or an + accessory's ``on_set``. + :ivar is_admin: Whether the writing controller has admin privileges. + """ + + characteristic: Characteristic | None + is_admin: bool diff --git a/pyhap/delegates.py b/pyhap/delegates.py new file mode 100644 index 00000000..41c5b9ee --- /dev/null +++ b/pyhap/delegates.py @@ -0,0 +1,103 @@ +"""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.CharContext`) that carries what a +callback needs to know about the request - and grows new fields instead of +new callback signatures. + +Registration, on e.g. ``char.delegate = ...``, is when everything about a +delegate is decided once: the driver records which methods are overridden +and rejects an overridden method that is not a coroutine function. The +read and write paths never introspect a delegate again. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +from .context import CharReadContext, CharWriteContext + +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 method means the characteristic has no hook for it; + an overridden one 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. + + An unoverridden ``on_get`` reads the characteristic's stored + value. An 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. + """ + + async def on_set(self, value: Any, context: CharWriteContext) -> Any: + """Apply a controller's write of ``value``. + + Runs after the write passed its gate hooks, under the context's + 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. + """ + + 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. Failures are logged and isolated; + the subscription itself always registers. + """ + + 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. + Failures are logged and isolated. + """ + + +class ServiceDelegate: + """Delegate of a whole service. + + The service's ``on_set`` is the gate 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 whole + request before anything is applied: values are restored, subscribers + are told nothing, and per-characteristic ``on_set`` calls do not run. + """ + + async def on_set( + self, values: Mapping[Characteristic, Any], context: CharWriteContext + ) -> 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/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..5992d6b8 --- /dev/null +++ b/tests/test_context.py @@ -0,0 +1,108 @@ +"""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 CharContext, CharReadContext, CharWriteContext + + +def _char() -> Characteristic: + return Characteristic( + "Value", + uuid1(), + { + PROP_FORMAT: HAP_FORMAT_INT, + PROP_PERMISSIONS: [HAP_PERMISSION_READ, HAP_PERMISSION_WRITE], + }, + ) + + +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 = CharContext( + 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_groups_and_admin() -> None: + """A grouped write carries no characteristic, and the admin flag.""" + context = CharWriteContext( + client_addr=("1.2.3.4", 5), + client_uuid=None, + connection=_handle(), + deadline=1.0, + characteristic=None, + is_admin=False, + ) + + assert context.characteristic is None + assert context.is_admin is False + + +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=True, + ) + + assert context.characteristic is characteristic + assert context.is_admin is True + + +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_delegates.py b/tests/test_delegates.py new file mode 100644 index 00000000..3dc1c66d --- /dev/null +++ b/tests/test_delegates.py @@ -0,0 +1,104 @@ +"""Tests for the delegate base classes.""" + +import asyncio +from collections.abc import Awaitable, Mapping +import inspect +from typing import Any +from uuid import uuid1 + +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 +from pyhap.delegates import CharacteristicDelegate, ServiceDelegate + + +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=None, + 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_answer_none() -> None: + """An unoverridden delegate does nothing and answers None.""" + delegate = CharacteristicDelegate() + + assert await _run(delegate.on_get(_read_context())) is None + 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({}, _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_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: CharWriteContext + ) -> None: + await done.wait() + + done.set() + assert await _run(Setter().on_set({}, _write_context())) is None From eb991bcd204ce95dba0f8d31eaef844f2d3f5473 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Fri, 13 Nov 2026 13:44:55 +0100 Subject: [PATCH 03/14] Answer a setter's HapStatusError with its status A setter that raises HapStatusError now answers the controller with its status instead of the generic -70402, at every callback level: a characteristic's setter answers for itself, a service or accessory setter for all of its characteristics in the request. A coroutine setter that raises it answers the same way once it is done, so a refusal is reported whether the callback is sync or async, and other characteristics of the request keep their own results. Closes #75 for characteristic, service and accessory level setters. --- docs/source/advanced/async.rst | 19 ++++ pyhap/accessory_driver.py | 43 +++++++++ tests/test_accessory_driver.py | 168 +++++++++++++++++++++++++++++++++ 3 files changed, 230 insertions(+) diff --git a/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index d9abaf9a..a6c4b0b8 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -112,6 +112,25 @@ 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. +**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``. + 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 the HTTP response. A write response, and the read back value of a diff --git a/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index 790b8da9..98794fcb 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -76,6 +76,7 @@ from pyhap.state import State from .const import HAP_SERVER_STATUS +from .errors import HapStatusError from .util import callback logger = logging.getLogger(__name__) @@ -124,6 +125,16 @@ def _wrap_char_setter( response = char.client_update_value( value, client_addr, notify=notify, defer_notify=True ) + except HapStatusError as e: + # The setter answers the controller with its own HAP status. + logger.debug( + "%s: Characteristic %s answered status %s for value %s", + client_addr, + char.display_name, + e.status, + value, + ) + return e.status, None except Exception: logger.exception( "%s: Error while setting characteristic %s to %s", @@ -153,6 +164,17 @@ def _wrap_acc_setter(acc: Any, updates_by_service: Any, client_addr: Any) -> Any _close_unsupported_coroutine( acc.setter_callback(updates_by_service), acc.display_name ) + except HapStatusError as e: + # The callback answers the controller with its own HAP status, + # applied to every characteristic of the accessory in the request. + logger.debug( + "%s: The %s accessory answered status %s for %s", + client_addr, + acc.display_name, + e.status, + updates_by_service, + ) + return e.status except Exception: logger.exception( "%s: Error while setting characteristics to %s for the %s accessory", @@ -174,6 +196,17 @@ def _wrap_service_setter(service: Any, chars: Any, client_addr: Any) -> Any: _close_unsupported_coroutine( service.setter_callback(service_chars), service.display_name ) + except HapStatusError as e: + # The callback answers the controller with its own HAP status, + # applied to every characteristic of the service in the request. + logger.debug( + "%s: The %s service answered status %s for %s", + client_addr, + service.display_name, + e.status, + service_chars, + ) + return e.status except Exception: logger.exception( "%s: Error while setting characteristics to %s for the %s service", @@ -1551,6 +1584,16 @@ async def _async_finish_set_characteristics( write = tasks[task] try: outcome = task.result() + except HapStatusError as e: + # The setter answers the controller with its own HAP status. + logger.debug( + "%s: Characteristic %s answered status %s", + client_addr, + write.char.display_name, + e.status, + ) + write.result[HAP_REPR_STATUS] = e.status + continue except (Exception, asyncio.CancelledError): logger.exception( "%s: Error while setting characteristic %s", diff --git a/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index 7ecd4312..4cad5947 100644 --- a/tests/test_accessory_driver.py +++ b/tests/test_accessory_driver.py @@ -47,6 +47,7 @@ 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.service import Service @@ -845,6 +846,173 @@ 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 = driver.set_characteristics( + { + 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] + ) + + 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, + } + ] + } + + +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 = driver.set_characteristics( + { + 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] + ) + + 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, + }, + ] + } + + +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 = driver.set_characteristics( + { + 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] + ) + + 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"), [ From 417dbbe0d008a623a42830dc7e4dd9c2793d6bf3 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Fri, 13 Nov 2026 13:48:26 +0100 Subject: [PATCH 04/14] Answer a getter's failure with its status, isolated per characteristic A getter that raises HapStatusError answers a read of its characteristic with that status instead of -70402, like a setter does. A failing getter no longer fails the whole /accessories response: its characteristic is listed without its value, and the rest of the accessory database is served as usual. Until now a raising getter failed the entire request, so one broken accessory could break pairing for every accessory behind the bridge. Add accessories/busy_lock.py as an example of the error protocol: a lock that refuses commands with RESOURCE_BUSY while its bolt is moving, and an offline sensor whose reads answer with a status instead of a value. --- accessories/busy_lock.py | 108 +++++++++++++++++++++++++++++++++ docs/source/advanced/async.rst | 7 +++ docs/source/intro/examples.rst | 5 ++ pyhap/accessory_driver.py | 9 +++ pyhap/characteristic.py | 10 ++- tests/test_accessory_driver.py | 50 +++++++++++++++ 6 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 accessories/busy_lock.py 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/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index a6c4b0b8..e5c1fc29 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -131,6 +131,13 @@ 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 the HTTP response. A write response, and the read back value of a diff --git a/docs/source/intro/examples.rst b/docs/source/intro/examples.rst index 28c11d2e..7deb6ea8 100644 --- a/docs/source/intro/examples.rst +++ b/docs/source/intro/examples.rst @@ -43,6 +43,11 @@ 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`). 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/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index 98794fcb..0dcfb203 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -1176,6 +1176,15 @@ def get_characteristics( else char.get_value() ) rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS + except HapStatusError as e: + # The getter answers the controller with its own HAP status. + logger.debug( + "%s: Characteristic %s answered status %s", + self.accessory.display_name, + (aid, iid), + e.status, + ) + rep[HAP_REPR_STATUS] = e.status except CharacteristicError: logger.error( "%s: Error getting value for characteristic %s.", diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index d72313dd..6c88e631 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -571,7 +571,15 @@ 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() + try: + hap_rep[HAP_REPR_VALUE] = self.get_value() + except Exception: + # One failing getter must not fail the whole accessories + # response: the characteristic is listed without a value. + logger.exception( + "%s: Error getting the value; answering without it", + self._display_name, + ) if not include_value: self._to_hap_cache = hap_rep diff --git a/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index 4cad5947..c78e14d8 100644 --- a/tests/test_accessory_driver.py +++ b/tests/test_accessory_driver.py @@ -225,6 +225,56 @@ 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) + + +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 = driver.get_characteristics([f"{acc.aid}.{iid}"]) + + assert result == { + HAP_REPR_CHARS: [ + { + HAP_REPR_AID: acc.aid, + HAP_REPR_IID: iid, + HAP_REPR_STATUS: HAP_SERVER_STATUS.OUT_OF_RESOURCE, + } + ] + } + + +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,) = driver.get_accessories()[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"), [ From 143cb4756cbc215e988e361810b88bfdca52af4d Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Fri, 13 Nov 2026 16:01:45 +0100 Subject: [PATCH 05/14] Add the delegate attribute and wire it in configure_char A characteristic and a service get a delegate attribute, and Service.configure_char accepts one alongside the legacy callbacks. A delegate is a CharacteristicDelegate or ServiceDelegate instance stored as a plain attribute with a type; the instance is made by the caller, configure_char does not instantiate classes. Using something else, or a delegate method that is not a coroutine function, is a misuse that fails at runtime when the driver dispatches it - there is no validation at the assignment. A delegate takes over the reads of its characteristics: the base on_get has no default answer and raises NotImplementedError, so the dispatch calls it unconditionally and an override returning None is a real answer, a null value. on_set, on_subscribe and on_unsubscribe do nothing by default. Either a delegate or the legacy callbacks, never both: a conflict would be silent at dispatch - one of the two would run and the other become dead code - so assigning one to a characteristic or service that has the other raises ValueError, in both directions. Unlike the delegate's quality, a conflict cannot fail loudly later. None or del clears one side, and the other can then be assigned. The legacy setter_callback/getter_callback attributes otherwise work as they always did; a DeprecationWarning on their assignment ships with the release that dispatches delegates, when a delegate is a working alternative. The driver does not call delegates yet - that is the gate pipeline change. This stores them so the pipelines can dispatch them. --- docs/source/api/delegates.rst | 52 +++++++++++++++++--- pyhap/characteristic.py | 86 +++++++++++++++++++++++++++++++++- pyhap/delegates.py | 32 ++++++------- pyhap/service.py | 72 +++++++++++++++++++++++++++- tests/test_accessory_driver.py | 10 ++-- tests/test_admin_only.py | 5 +- tests/test_characteristic.py | 69 +++++++++++++++++++++++++++ tests/test_delegates.py | 24 ++++++++-- tests/test_service.py | 78 ++++++++++++++++++++++++++++++ 9 files changed, 393 insertions(+), 35 deletions(-) diff --git a/docs/source/api/delegates.rst b/docs/source/api/delegates.rst index 31f4bf54..f23ecfd5 100644 --- a/docs/source/api/delegates.rst +++ b/docs/source/api/delegates.rst @@ -6,9 +6,7 @@ Delegates The delegate interfaces of the callback interface: an object a characteristic or service is wired up with, receiving a -:class:`~pyhap.context.CharContext` per call. Registration is when the driver -records what a delegate overrides; the read and write paths never -introspect it again. +:class:`~pyhap.context.CharContext` per call. .. currentmodule:: pyhap.delegates @@ -23,6 +21,48 @@ Async by design Every delegate method is a coroutine function. The driver awaits every call and enforces the context's deadline - there is no sync/async -detection. An overridden method that is not a coroutine function fails -registration with a :class:`TypeError`, so a wrong method is caught at -its source. +detection. A method that is not a coroutine function is a misuse that +fails at runtime when the driver dispatches it, not a validated error. + +Wiring a delegate +================= + +Assign an instance to the ``delegate`` of a characteristic or a +service, or pass it through :meth:`Service.configure_char +`: + +.. 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: a delegate is a +plain attribute with a type, and using something else than a +:class:`CharacteristicDelegate` or a method that is not a coroutine +function fails at runtime when the driver dispatches it. ``None`` or +``del`` removes 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. + +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.** The driver stores delegates from this release on; +the write and read pipelines dispatch them in the following releases of +the callback interface refactor. Until then, a delegate is wired but +not yet called. The legacy +:attr:`~pyhap.characteristic.Characteristic.setter_callback` / +:attr:`~pyhap.characteristic.Characteristic.getter_callback` attributes +keep working unchanged for code that uses them alone, and are +deprecated once the delegates are dispatched. diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index 6c88e631..9234fc10 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -21,6 +21,7 @@ HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) +from .delegates import CharacteristicDelegate from .util import hap_type_to_uuid, uuid_to_hap_type if TYPE_CHECKING: @@ -184,8 +185,9 @@ class Characteristic: "_properties", "type_id", "_value", - "getter_callback", - "setter_callback", + "_getter_callback", + "_setter_callback", + "_delegate", "service", "_uuid_str", "_loader_display_name", @@ -243,6 +245,10 @@ def __init__( # 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 + # The delegate of the reads, writes and subscriptions of this + # characteristic, see ``CharacteristicDelegate``. Either a delegate + # or the legacy callbacks, never both. + self.delegate: CharacteristicDelegate | 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 @@ -269,6 +275,82 @@ def display_name(self, value: str) -> None: self._display_name = value self._clear_cache() + @property + def delegate(self) -> CharacteristicDelegate | None: + """The characteristic's delegate, or ``None`` without one. + + A characteristic has either a delegate or the legacy callbacks, + never both: assigning a delegate to a characteristic that has one + raises ``ValueError``, and the reverse. A 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`` removes it.""" + if delegate is not None and ( + self._setter_callback is not None or self._getter_callback is not None + ): + raise ValueError( + f"{self._display_name} has a legacy callback, remove it before" + " assigning a delegate" + ) + self._delegate = delegate + + @delegate.deleter + def delegate(self) -> None: + """Remove the delegate.""" + self._delegate = None + + @property + def getter_callback(self) -> Callable[[], Any] | None: + """The legacy getter, called with nothing on every read of the value.""" + return self._getter_callback + + @getter_callback.setter + def getter_callback(self, callback: Callable[[], Any] | None) -> None: + """Assign the legacy getter; ``None`` removes it.""" + if callback is not None and self._delegate is not None: + raise ValueError( + f"{self._display_name} has a delegate, remove it before" + " assigning a legacy callback" + ) + self._getter_callback = callback + + @getter_callback.deleter + def getter_callback(self) -> None: + """Remove the legacy getter.""" + self._getter_callback = None + + @property + def setter_callback(self) -> Callable[..., Any] | None: + """The legacy setter, called with the value on a controller's write. + + 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. May also be a coroutine function; a + controller's write is answered once it is done. + """ + return self._setter_callback + + @setter_callback.setter + def setter_callback(self, callback: Callable[..., Any] | None) -> None: + """Assign the legacy setter; ``None`` removes it.""" + if callback is not None and self._delegate is not None: + raise ValueError( + f"{self._display_name} has a delegate, remove it before" + " assigning a legacy callback" + ) + self._setter_callback = callback + + @setter_callback.deleter + def setter_callback(self) -> None: + """Remove the legacy setter.""" + self._setter_callback = None + @property def value(self) -> Any: """Return the value of the characteristic.""" diff --git a/pyhap/delegates.py b/pyhap/delegates.py index 41c5b9ee..9a413610 100644 --- a/pyhap/delegates.py +++ b/pyhap/delegates.py @@ -4,14 +4,9 @@ :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.CharContext`) that carries what a -callback needs to know about the request - and grows new fields instead of -new callback signatures. - -Registration, on e.g. ``char.delegate = ...``, is when everything about a -delegate is decided once: the driver records which methods are overridden -and rejects an overridden method that is not a coroutine function. The -read and write paths never introspect a delegate again. +a delegate receives a context (:class:`~pyhap.context.CharContext`) that +carries what a callback needs to know about the request - and grows new +fields instead of new callback signatures. """ from __future__ import annotations @@ -39,21 +34,26 @@ class CharacteristicDelegate: blocks the loop and the request; keep such work in a task or an executor and await it. - An unoverridden method means the characteristic has no hook for it; - an overridden one 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 + 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. - An unoverridden ``on_get`` reads the characteristic's stored - value. An 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. + 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. """ + raise NotImplementedError("on_get is not implemented") async def on_set(self, value: Any, context: CharWriteContext) -> Any: """Apply a controller's write of ``value``. diff --git a/pyhap/service.py b/pyhap/service.py index d4171ef7..6561fdd6 100644 --- a/pyhap/service.py +++ b/pyhap/service.py @@ -13,6 +13,7 @@ ) from .characteristic import Characteristic +from .delegates import CharacteristicDelegate, ServiceDelegate from .util import hap_type_to_uuid, uuid_to_hap_type if TYPE_CHECKING: @@ -34,7 +35,8 @@ class Service: "type_id", "linked_services", "is_primary_service", - "setter_callback", + "_setter_callback", + "_delegate", "unique_id", "_uuid_str", ) @@ -53,9 +55,62 @@ def __init__( 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``. Either a delegate or the legacy setter, + # never both. + self.delegate: ServiceDelegate | None = None self.unique_id = unique_id self._uuid_str = uuid_to_hap_type(type_id) + @property + def delegate(self) -> ServiceDelegate | None: + """The service's delegate, or ``None`` without one. + + A service has either a delegate or the legacy ``setter_callback``, + never both: assigning a delegate to a service that has one raises + ``ValueError``, and the reverse. + """ + return self._delegate + + @delegate.setter + def delegate(self, delegate: ServiceDelegate | None) -> None: + """Assign the delegate; ``None`` removes it.""" + if delegate is not None and self._setter_callback is not None: + raise ValueError( + f"{self.display_name} has a legacy setter_callback, remove it" + " before assigning a delegate" + ) + self._delegate = delegate + + @delegate.deleter + def delegate(self) -> None: + """Remove the delegate.""" + self._delegate = None + + @property + def setter_callback(self) -> Callable[[Any], None] | None: + """The legacy setter, called with the request's values by name. + + Called with a ``{display_name: value}`` dict after the + per-characteristic setters of a write. + """ + return self._setter_callback + + @setter_callback.setter + def setter_callback(self, callback: Callable[[Any], None] | None) -> None: + """Assign the legacy setter; ``None`` removes it.""" + if callback is not None and self._delegate is not None: + raise ValueError( + f"{self.display_name} has a delegate, remove it before" + " assigning a legacy setter_callback" + ) + self._setter_callback = callback + + @setter_callback.deleter + def setter_callback(self) -> None: + """Remove the legacy setter.""" + self._setter_callback = None + def __repr__(self) -> str: """Return the representation of the service.""" chars_dict = {c.display_name: c.value for c in self.characteristics} @@ -108,8 +163,19 @@ 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) @@ -119,6 +185,8 @@ def configure_char( char.setter_callback = setter_callback if getter_callback: char.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/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index c78e14d8..60771b93 100644 --- a/tests/test_accessory_driver.py +++ b/tests/test_accessory_driver.py @@ -707,7 +707,8 @@ 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}) @@ -721,7 +722,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 @@ -744,10 +745,11 @@ def test_write_response_not_returned( ) -> 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) + setter.assert_called_once_with(0) assert char.value == 0 diff --git a/tests/test_admin_only.py b/tests/test_admin_only.py index f63f2832..7e7f896c 100644 --- a/tests/test_admin_only.py +++ b/tests/test_admin_only.py @@ -295,7 +295,8 @@ 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() + service_setter = MagicMock() + service.setter_callback = service_setter driver.accessory.setter_callback = MagicMock() query = { HAP_REPR_CHARS: [ @@ -307,7 +308,7 @@ 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() + service_setter.assert_not_called() driver.accessory.setter_callback.assert_not_called() diff --git a/tests/test_characteristic.py b/tests/test_characteristic.py index ba10d027..7f632d64 100644 --- a/tests/test_characteristic.py +++ b/tests/test_characteristic.py @@ -18,6 +18,7 @@ HAP_PERMISSION_READ, Characteristic, ) +from pyhap.delegates import CharacteristicDelegate PROPERTIES: dict[str, Any] = { "Format": HAP_FORMAT_INT, @@ -584,3 +585,71 @@ def test_getter_callback() -> None: "perms": ["pr"], "type": "A1", } + + +class _AsyncGetter(CharacteristicDelegate): + """A delegate overriding on_get.""" + + +def test_delegate_assignment() -> None: + """An assigned delegate instance is the characteristic's delegate.""" + char = get_char(PROPERTIES) + delegate = _AsyncGetter() + + char.delegate = delegate + + assert char.delegate is delegate + assert char.getter_callback is None + assert char.setter_callback is None + + char.delegate = None + + assert char.delegate is None + + +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 with None or del 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 + + del char.getter_callback + char.delegate = _AsyncGetter() + + assert char.delegate is not None + + del char.delegate + char.setter_callback = lambda value: None # noqa: E731 + + assert char.setter_callback is not None diff --git a/tests/test_delegates.py b/tests/test_delegates.py index 3dc1c66d..4c78cfef 100644 --- a/tests/test_delegates.py +++ b/tests/test_delegates.py @@ -6,6 +6,8 @@ from typing import Any from uuid import uuid1 +import pytest + from pyhap.characteristic import ( HAP_FORMAT_INT, HAP_PERMISSION_READ, @@ -67,11 +69,17 @@ def test_noop_defaults_are_coroutine_functions() -> None: assert inspect.iscoroutinefunction(getattr(delegate, method)), method -async def test_noop_defaults_answer_none() -> None: - """An unoverridden delegate does nothing and answers None.""" +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() - assert await _run(delegate.on_get(_read_context())) is None + 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 @@ -90,6 +98,16 @@ async def on_get(self, context: CharReadContext) -> object: 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() diff --git a/tests/test_service.py b/tests/test_service.py index 1b3b44e2..d4e28d73 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -12,6 +12,7 @@ PROP_PERMISSIONS, Characteristic, ) +from pyhap.delegates import CharacteristicDelegate, ServiceDelegate from pyhap.service import Service CHAR_PROPS = { @@ -246,3 +247,80 @@ 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 service.delegate 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_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 configured.delegate is None + assert configured.value == 5 From 4304358e0c2bc893508712e50e6f9ebbb7fc377c Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 16 Nov 2026 10:52:25 +0100 Subject: [PATCH 06/14] Give grouped writes their own ServiceWriteContext --- docs/source/api/context.rst | 5 ++++- docs/source/api/delegates.rst | 2 +- pyhap/context.py | 29 +++++++++++++++++++--------- pyhap/delegates.py | 10 +++++++--- tests/test_context.py | 36 +++++++++++++++++++++++------------ tests/test_delegates.py | 22 ++++++++++++++++----- 6 files changed, 73 insertions(+), 31 deletions(-) diff --git a/docs/source/api/context.rst b/docs/source/api/context.rst index 2fca846f..91571a8b 100644 --- a/docs/source/api/context.rst +++ b/docs/source/api/context.rst @@ -10,7 +10,7 @@ changes. .. currentmodule:: pyhap.context -.. autoclass:: CharContext +.. autoclass:: Context :members: .. autoclass:: CharReadContext @@ -18,3 +18,6 @@ changes. .. autoclass:: CharWriteContext :members: + +.. autoclass:: ServiceWriteContext + :members: diff --git a/docs/source/api/delegates.rst b/docs/source/api/delegates.rst index f23ecfd5..f2a3e434 100644 --- a/docs/source/api/delegates.rst +++ b/docs/source/api/delegates.rst @@ -6,7 +6,7 @@ Delegates The delegate interfaces of the callback interface: an object a characteristic or service is wired up with, receiving a -:class:`~pyhap.context.CharContext` per call. +:class:`~pyhap.context.Context` per call. .. currentmodule:: pyhap.delegates diff --git a/pyhap/context.py b/pyhap/context.py index a7a2914b..ca9fea7e 100644 --- a/pyhap/context.py +++ b/pyhap/context.py @@ -10,11 +10,12 @@ if TYPE_CHECKING: from .characteristic import Characteristic + from .service import Service @dataclass(frozen=True) -class CharContext: - """What a characteristic callback knows about the controller it serves. +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 @@ -38,7 +39,7 @@ class CharContext: @dataclass(frozen=True) -class CharReadContext(CharContext): +class CharReadContext(Context): """The context of a read, e.g. of ``on_get``. :ivar characteristic: The characteristic being read. @@ -48,14 +49,24 @@ class CharReadContext(CharContext): @dataclass(frozen=True) -class CharWriteContext(CharContext): - """The context of a write, e.g. of ``on_set``. +class CharWriteContext(Context): + """The context of a write of one characteristic, e.g. of ``on_set``. - :ivar characteristic: The characteristic being written, or ``None`` - for a grouped call that carries several, e.g. a service's or an - accessory's ``on_set``. + :ivar characteristic: The characteristic being written. :ivar is_admin: Whether the writing controller has admin privileges. """ - characteristic: Characteristic | None + characteristic: Characteristic + is_admin: bool + + +@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 diff --git a/pyhap/delegates.py b/pyhap/delegates.py index 9a413610..486b4a2f 100644 --- a/pyhap/delegates.py +++ b/pyhap/delegates.py @@ -4,7 +4,7 @@ :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.CharContext`) that +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. """ @@ -14,7 +14,7 @@ from collections.abc import Mapping from typing import TYPE_CHECKING, Any -from .context import CharReadContext, CharWriteContext +from .context import CharReadContext, CharWriteContext, ServiceWriteContext if TYPE_CHECKING: from .characteristic import Characteristic @@ -91,10 +91,14 @@ class ServiceDelegate: Raise :class:`~pyhap.errors.HapStatusError` to refuse the whole request before anything is applied: values are restored, subscribers are told nothing, and per-characteristic ``on_set`` calls do not run. + + 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: CharWriteContext + self, values: Mapping[Characteristic, Any], context: ServiceWriteContext ) -> None: """Veto or accept a grouped write before it is applied. diff --git a/tests/test_context.py b/tests/test_context.py index 5992d6b8..a33ae57e 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -14,7 +14,13 @@ ) from pyhap.connection import HAPConnectionHandle from pyhap.const import HAP_PERMISSION_WRITE -from pyhap.context import CharContext, CharReadContext, CharWriteContext +from pyhap.context import ( + CharReadContext, + CharWriteContext, + Context, + ServiceWriteContext, +) +from pyhap.service import Service def _char() -> Characteristic: @@ -28,6 +34,10 @@ def _char() -> Characteristic: ) +def _service() -> Service: + return Service(uuid1(), "Test Service") + + def _handle() -> HAPConnectionHandle: return HAPConnectionHandle(("1.2.3.4", 5), 3) @@ -35,7 +45,7 @@ def _handle() -> HAPConnectionHandle: def test_context_fields() -> None: """The context carries what a callback knows about the controller.""" client_uuid = uuid4() - context = CharContext( + context = Context( client_addr=("1.2.3.4", 5), client_uuid=client_uuid, connection=_handle(), @@ -62,35 +72,37 @@ def test_contexts_are_frozen() -> None: context.deadline = 2.0 # ty: ignore[invalid-assignment] -def test_write_context_groups_and_admin() -> None: - """A grouped write carries no characteristic, and the admin flag.""" +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=None, + characteristic=characteristic, is_admin=False, ) - assert context.characteristic is None + assert context.characteristic is characteristic assert context.is_admin is False -def test_write_context_of_one_characteristic() -> None: - """A per-characteristic write carries its characteristic.""" - characteristic = _char() - context = CharWriteContext( +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, - characteristic=characteristic, + service=service, is_admin=True, ) - assert context.characteristic is characteristic + assert context.service is service assert context.is_admin is True + assert not hasattr(context, "characteristic") def test_read_context_carries_the_characteristic() -> None: diff --git a/tests/test_delegates.py b/tests/test_delegates.py index 4c78cfef..bd86c4ee 100644 --- a/tests/test_delegates.py +++ b/tests/test_delegates.py @@ -17,8 +17,9 @@ ) from pyhap.connection import HAPConnectionHandle from pyhap.const import HAP_PERMISSION_WRITE -from pyhap.context import CharReadContext, CharWriteContext +from pyhap.context import CharReadContext, CharWriteContext, ServiceWriteContext from pyhap.delegates import CharacteristicDelegate, ServiceDelegate +from pyhap.service import Service def _char() -> Characteristic: @@ -48,7 +49,18 @@ def _write_context() -> CharWriteContext: client_uuid=None, connection=HAPConnectionHandle(("1.2.3.4", 5), 3), deadline=1.0, - characteristic=None, + 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, ) @@ -84,7 +96,7 @@ async def test_noop_defaults_do_nothing_but_on_get_raises() -> 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({}, _write_context())) is None + assert await _run(service.on_set({}, _service_write_context())) is None async def test_overrides_answer_values() -> None: @@ -114,9 +126,9 @@ async def test_an_override_may_await_inside() -> None: class Setter(ServiceDelegate): async def on_set( - self, values: Mapping[Characteristic, Any], context: CharWriteContext + self, values: Mapping[Characteristic, Any], context: ServiceWriteContext ) -> None: await done.wait() done.set() - assert await _run(Setter().on_set({}, _write_context())) is None + assert await _run(Setter().on_set({}, _service_write_context())) is None From 3de5a6863d1bfef556401f670059a2b0072b9d7e Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 16 Nov 2026 10:58:39 +0100 Subject: [PATCH 07/14] Document why contexts carry the object, not the id --- docs/source/api/context.rst | 13 +++++++++++++ pyhap/context.py | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/docs/source/api/context.rst b/docs/source/api/context.rst index 91571a8b..3aa89e73 100644 --- a/docs/source/api/context.rst +++ b/docs/source/api/context.rst @@ -8,6 +8,19 @@ The contexts passed to delegate and lifecycle calls. New input data arrives as new fields of these classes; a callback's signature never changes. +Why objects, not ids +==================== + +The contexts identify their target by the object itself, never by an +iid. Iids are the wire protocol's identity - assigned by the driver at +publish time and meaningless outside a running driver - and a delegate +is wired at construction time, before iids even exist. The object +serves as the identity for dispatch (``is`` checks, the keys of a +grouped ``on_set``'s ``values``) and carries what a callback needs: +the display name, the stored value, the properties, the owning +service. Translating to and from the wire format is the driver's job, +not a delegate's. + .. currentmodule:: pyhap.context .. autoclass:: Context diff --git a/pyhap/context.py b/pyhap/context.py index ca9fea7e..760b34a3 100644 --- a/pyhap/context.py +++ b/pyhap/context.py @@ -30,6 +30,15 @@ class Context: :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 From 8dd93062fb88b1f67121d63e95f9b2c933a76430 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 16 Nov 2026 15:23:28 +0100 Subject: [PATCH 08/14] Dispatch delegate writes: gates first, then on_set under the deadline --- docs/source/advanced/async.rst | 37 ++ docs/source/api/delegates.rst | 19 +- docs/source/intro/overview.rst | 8 + pyhap/accessory_driver.py | 654 ++++++++++++++++++++++++++++---- pyhap/characteristic.py | 17 + pyhap/delegates.py | 10 +- pyhap/hap_handler.py | 14 +- pyhap/hap_protocol.py | 10 +- tests/test_delegate_dispatch.py | 561 +++++++++++++++++++++++++++ 9 files changed, 1235 insertions(+), 95 deletions(-) create mode 100644 tests/test_delegate_dispatch.py diff --git a/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index e5c1fc29..db940c40 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -146,6 +146,43 @@ 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 +================ + +The new-style interface of the write path is the delegate, see +:ref:`api-delegates`. A write that touches a characteristic with a +delegate, or a service with one, leaves the legacy path above and runs +the delegate pipeline instead: + +1. Validation, privileges and timed-write checks — the same ones as + before. +2. The values are stored, but subscribers are not told yet. +3. The gate: the ``on_set`` of each written service's + :class:`~pyhap.delegates.ServiceDelegate` runs, concurrently, with + every written value of its service. A + :class:`pyhap.errors.HapStatusError` refuses the writes of that + service — their values are restored, nobody is notified, their + per-characteristic ``on_set`` calls do not run, and the raised + status is answered. A timeout (``-70408``) or any other failure + (``-70402``) refuses the same way. +4. The per-characteristic ``on_set`` calls of the surviving writes run + concurrently, in request order, under the same deadline. +5. Subscribers learn the values of the writes that succeeded; a write + that raised, failed or missed its deadline restores the previous + value and notifies nobody, answering its status. + +The deadline in the context is one per request — the driver answers a +request it cannot finish in time with ``-70408`` per characteristic. A +direct ``set_characteristics`` call has no controller waiting on a +timeout: it stores the values, answers at once and runs the dispatch +as a job without a deadline. + +A request may mix both interfaces: characteristics without delegates +keep the legacy dispatch above, byte for byte. A service with a +delegate, however, is gated as a whole — the legacy callback chars of +that service are applied after its gate too, so the gate sees every +value and can refuse the group. + Provided utilities ================== diff --git a/docs/source/api/delegates.rst b/docs/source/api/delegates.rst index f2a3e434..4f9f6f96 100644 --- a/docs/source/api/delegates.rst +++ b/docs/source/api/delegates.rst @@ -58,11 +58,20 @@ 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.** The driver stores delegates from this release on; -the write and read pipelines dispatch them in the following releases of -the callback interface refactor. Until then, a delegate is wired but -not yet called. The legacy +**Rollout state.** The driver dispatches the writes of delegates from +this release on: a write to a characteristic with a delegate, or to a +service with one, runs its gates and its ``on_set`` calls as described +above, and answers with the per-characteristic statuses. Reads still +use the legacy path - the async read pipeline and the +``on_subscribe`` / ``on_unsubscribe`` hooks follow in the next +releases of the callback interface refactor. The legacy :attr:`~pyhap.characteristic.Characteristic.setter_callback` / :attr:`~pyhap.characteristic.Characteristic.getter_callback` attributes keep working unchanged for code that uses them alone, and are -deprecated once the delegates are dispatched. +deprecated once the read pipeline dispatches delegates too. + +A request may mix both interfaces. A characteristic with a legacy +callback keeps its legacy dispatch, byte for byte, unless its service +has a delegate: the writes of a gated service - delegate or legacy +callback - all pass its gate first, so the gate can refuse them as a +group. diff --git a/docs/source/intro/overview.rst b/docs/source/intro/overview.rst index 7041fe1d..56ae2166 100644 --- a/docs/source/intro/overview.rst +++ b/docs/source/intro/overview.rst @@ -127,6 +127,14 @@ 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 served by a delegate (see :ref:`api-delegates`) runs the +delegate pipeline instead: the values are stored without notifying +anyone, the written services' gates run first and may refuse their +writes as a group, 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 value change to subscribers ----------------------------- diff --git a/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index 0dcfb203..171a879a 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -26,6 +26,7 @@ import inspect import ipaddress import logging +import math import os import re import sys @@ -49,6 +50,7 @@ CharacteristicWrite, HAPValue, ) +from pyhap.connection import HAPConnectionHandle from pyhap.const import ( HAP_PERMISSION_NOTIFY, HAP_PERMISSION_READ, @@ -67,6 +69,8 @@ HAP_REPR_WRITE_RESPONSE, STANDALONE_AID, ) +from pyhap.context import CharWriteContext, Context, ServiceWriteContext +from pyhap.delegates import CharacteristicDelegate from pyhap.encoder import AccessoryEncoder from pyhap.hap_server import HAPServer from pyhap.hsrp import Server as SrpServer @@ -244,6 +248,68 @@ def __init__(self) -> None: self.alive = True +class _DelegateWrite(NamedTuple): + """A characteristic write the delegate stage applies. + + ``delegate`` is the characteristic's delegate, or ``None`` for a + legacy callback characteristic of a gated service, which the stage + applies after the gate like the legacy path applies it. + """ + + char: Characteristic + value: Any # The validated value ``on_set`` receives, the raw one otherwise. + previous_value: Any + result: dict[str, Any] # The result entry to complete. + write_response: bool + private_write: bool + service: Service + delegate: CharacteristicDelegate | None + + +class _DelegateWork: + """The writes of a request that its delegate stage gates and applies. + + A service with a delegate is gated as a whole: every value the + request writes to it goes to its gate first, and the writes of the + service - delegate or legacy callback - are applied only after the + gate accepted. + """ + + __slots__ = ("gates", "is_admin", "writes") + + def __init__(self, is_admin: bool) -> None: + self.gates: dict[Service, dict[Characteristic, Any]] = {} + self.writes: list[_DelegateWrite] = [] + self.is_admin = is_admin + + def __bool__(self) -> bool: + """Whether the request has anything for the delegate stage.""" + return bool(self.gates or self.writes) + + +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: """Retrieve the outcome of a setter that ran on after it was cancelled.""" if not task.cancelled() and (err := task.exception()) is not None: @@ -488,6 +554,8 @@ def __init__( self._pending_connection_writes: dict[ tuple[str, int], set[_ConnectionWrites] ] = {} + # 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.""" @@ -1249,6 +1317,7 @@ 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. @@ -1284,12 +1353,23 @@ 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. """ - results, pending = self._apply_characteristic_writes( + results, pending, work = self._apply_characteristic_writes( chars_query, client_addr, client_uuid ) for write in pending: self.add_job(self._finish_pending_write(write, client_addr)) + if work: + self.add_job( + self._dispatch_delegates( + work, + self._request_context(client_addr, client_uuid, connection, None), + ) + ) return _set_characteristics_response(results) async def _finish_pending_write( @@ -1316,6 +1396,7 @@ def _set_characteristics_for_controller( timeout: float, *, client_uuid: UUID | None = None, + connection: HAPConnectionHandle | None = None, ) -> dict[str, Any] | None | Awaitable[dict[str, Any] | None]: """Apply a controller's write, waiting for coroutine setters. @@ -1327,13 +1408,23 @@ def _set_characteristics_for_controller( 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( + results, pending, work = self._apply_characteristic_writes( chars_query, client_addr, client_uuid ) + if work: + writes = _ConnectionWrites() + self._pending_connection_writes.setdefault(client_addr, set()).add(writes) + return self._set_characteristics_with_delegates( + results, + pending, + work, + self._request_context(client_addr, client_uuid, connection, timeout), + writes, + ) if pending: writes = _ConnectionWrites() self._pending_connection_writes.setdefault(client_addr, set()).add(writes) - return self._async_finish_set_characteristics( + return self._finish_set_characteristics( results, pending, client_addr, timeout, writes ) return _set_characteristics_response(results) @@ -1343,12 +1434,15 @@ def _apply_characteristic_writes( chars_query: dict[str, Any], client_addr: tuple[str, int], client_uuid: UUID | None, - ) -> tuple[dict[int, dict[int, dict[str, Any]]], list[_PendingWrite]]: + ) -> tuple[ + dict[int, dict[int, dict[str, Any]]], list[_PendingWrite], _DelegateWork + ]: """Run the setters of a write and collect the per-characteristic results.""" pending: list[_PendingWrite] = [] + work = _DelegateWork(self.state.is_admin(client_uuid)) try: - return self._run_characteristic_writes( - chars_query, client_addr, client_uuid, pending + results, pending = self._run_characteristic_writes( + chars_query, client_addr, client_uuid, pending, work ) except BaseException: # A malformed later entry must not leave a setter coroutine @@ -1356,6 +1450,7 @@ def _apply_characteristic_writes( for write in pending: write.coro.close() raise + return results, pending, work def _run_characteristic_writes( self, @@ -1363,6 +1458,7 @@ def _run_characteristic_writes( client_addr: tuple[str, int], client_uuid: UUID | None, pending: list[_PendingWrite], + delegate_work: _DelegateWork, ) -> tuple[dict[int, dict[int, dict[str, Any]]], list[_PendingWrite]]: queries: list[CharacteristicWrite] = chars_query[HAP_REPR_CHARS] @@ -1398,7 +1494,7 @@ def _run_characteristic_writes( HAP_REPR_STATUS: HAP_SERVER_STATUS.NOTIFICATION_NOT_SUPPORTED } - is_admin = self.state.is_admin(client_uuid) + is_admin = delegate_work.is_admin for query in queries: aid = query[HAP_REPR_AID] iid = query[HAP_REPR_IID] @@ -1479,6 +1575,29 @@ def _run_characteristic_writes( and HAP_PERMISSION_READ in char.properties[PROP_PERMISSIONS] ) previous_value = char.value + service = char.service + assert service is not None # noqa: S101 + + if char.delegate is not None or service.delegate is not None: + # The write goes to the delegate stage: gated by its + # service's delegate, applied by its own on_set, or both. + # A legacy callback char of a gated service is applied + # there too, after the gate, so the gate sees every value + # of the request and can refuse them all. + result = self._collect_delegate_write( + delegate_work, + client_addr, + char, + service, + value, + previous_value, + write_response, + private_write, + ) + results[aid][iid] = result + char_to_iid[char] = iid + updates_by_accessories_services[acc][service][char] = value + continue set_result = HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST set_result_value = None @@ -1491,23 +1610,12 @@ def _run_characteristic_writes( # 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. + # back the former one unless the setter set a value of its own, + # see _settle_private_write. 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 + set_result_value = _settle_private_write( + char, previous_value, value, set_result_value + ) result: dict[str, Any] = {HAP_REPR_STATUS: set_result} if inspect.iscoroutine(set_result_value): @@ -1528,8 +1636,6 @@ def _run_characteristic_writes( 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 # Proccess accessory and service level setter callbacks @@ -1558,7 +1664,17 @@ def _run_characteristic_writes( return results, pending - async def _async_finish_set_characteristics( + def _discard_connection_writes( + self, client_addr: tuple[str, int], writes: _ConnectionWrites + ) -> None: + """Drop a finished batch from the pending writes of the connection.""" + 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] + + async def _finish_set_characteristics( self, results: dict[int, dict[int, dict[str, Any]]], pending: list[_PendingWrite], @@ -1567,74 +1683,444 @@ async def _async_finish_set_characteristics( writes: _ConnectionWrites, ) -> dict[str, Any] | None: """Wait for the coroutine setters, then build the response.""" + deadline = time.monotonic() + timeout + try: + return await self._wait_pending( + results, pending, client_addr, deadline, writes + ) + finally: + self._discard_connection_writes(client_addr, writes) + + async def _wait_pending( + self, + results: dict[int, dict[int, dict[str, Any]]], + pending: list[_PendingWrite], + client_addr: tuple[str, int], + deadline: float, + writes: _ConnectionWrites, + ) -> dict[str, Any] | None: + """Wait for the coroutine setters, then build the response.""" + if not pending: + return _set_characteristics_response(results) tasks = {asyncio.ensure_future(write.coro): write for write in pending} try: + done, not_done = await asyncio.wait( + tasks, timeout=self._remaining(deadline) + ) + except asyncio.CancelledError: + for task, write in tasks.items(): + if task.done(): + self._finish_done_write(task, write, client_addr) + continue + 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 HapStatusError as e: + # The setter answers the controller with its own HAP status. + logger.debug( + "%s: Characteristic %s answered status %s", + client_addr, + write.char.display_name, + e.status, + ) + write.result[HAP_REPR_STATUS] = e.status + continue + except (Exception, asyncio.CancelledError): + logger.exception( + "%s: Error while setting characteristic %s", + client_addr, + write.char.display_name, + ) + write.result[HAP_REPR_STATUS] = ( + HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + continue + write.char.client_update_finished( + write.previous_value, client_addr, notify=write.notify + ) + 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) + + async def _set_characteristics_with_delegates( + self, + results: dict[int, dict[int, dict[str, Any]]], + pending: list[_PendingWrite], + work: _DelegateWork, + context: Context, + writes: _ConnectionWrites, + ) -> dict[str, Any] | None: + """Gate and apply the delegate writes, then wait for the rest.""" + client_addr = context.client_addr + # A controller's write always has an address: it keys the write + # responses and the pending writes of its connection. + assert client_addr is not None # noqa: S101 + try: + await self._dispatch_delegates(work, context, writes) + return await self._wait_pending( + results, pending, client_addr, context.deadline, writes + ) + finally: + self._discard_connection_writes(client_addr, writes) + + def _next_connection_generation(self) -> int: + """The identity number of the next connection, see HAPConnectionHandle.""" + self._connection_generation += 1 + return self._connection_generation + + def _request_context( + self, + client_addr: tuple[str, int], + client_uuid: UUID | None, + connection: HAPConnectionHandle | None, + 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. A call without a + connection gets a handle that belongs to no connection. + """ + if connection is None: + connection = HAPConnectionHandle(None, self._next_connection_generation()) + deadline = float("inf") if timeout is None else time.monotonic() + timeout + return Context( + client_addr=client_addr, + client_uuid=client_uuid, + connection=connection, + deadline=deadline, + ) + + @staticmethod + def _remaining(deadline: float) -> float | None: + """Seconds left of the deadline, ``None`` without one.""" + if math.isinf(deadline): + return None + return max(0.0, deadline - time.monotonic()) + + async def _dispatch_delegates( + self, + work: _DelegateWork, + context: Context, + writes: _ConnectionWrites | None = None, + ) -> None: + """Gate the writes of services with a delegate, then apply the rest. + + The gates 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 + gate 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 writes is None: + writes = _ConnectionWrites() + if work.gates: + await self._run_gates(work, context) + if work.writes: + await self._run_char_writes(work, context, writes) + + async def _run_gates(self, work: _DelegateWork, context: Context) -> None: + """Run the gates of the request's services, refusing what they refuse.""" + client_addr = context.client_addr + tasks: dict[asyncio.Future[Any], Service] = {} + for service, values in work.gates.items(): + delegate = service.delegate + assert delegate is not None # noqa: S101 + gate_context = ServiceWriteContext( + client_addr=context.client_addr, + client_uuid=context.client_uuid, + connection=context.connection, + deadline=context.deadline, + service=service, + is_admin=work.is_admin, + ) 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 - task.cancel() - task.add_done_callback(_retrieve_late_result) - raise - for task in not_done: + tasks[asyncio.ensure_future(delegate.on_set(values, gate_context))] = ( + service + ) + except TypeError: + logger.exception( + "%s: on_set of the %s service is not a coroutine function", + client_addr, + service.display_name, + ) + self._veto_writes( + work, service, HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + if not tasks: + return + try: + done, not_done = await asyncio.wait( + tasks, timeout=self._remaining(context.deadline) + ) + except asyncio.CancelledError: + for task in tasks: task.cancel() task.add_done_callback(_retrieve_late_result) - write = tasks[task] - logger.warning( - "%s: Timed out setting characteristic %s", + raise + for task in not_done: + task.cancel() + task.add_done_callback(_retrieve_late_result) + service = tasks[task] + logger.warning( + "%s: Timed out gating the writes of the %s service", + client_addr, + service.display_name, + ) + self._veto_writes(work, service, HAP_SERVER_STATUS.OPERATION_TIMED_OUT) + for task in done: + service = tasks[task] + try: + task.result() + except HapStatusError as e: + # The gate answers the controller with its own HAP status. + logger.debug( + "%s: The %s service refused its writes with status %s", + client_addr, + service.display_name, + e.status, + ) + self._veto_writes(work, service, e.status) + except Exception: + logger.exception( + "%s: Error gating the writes of the %s service", + client_addr, + service.display_name, + ) + self._veto_writes( + work, service, HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + + async def _run_char_writes( + self, + work: _DelegateWork, + context: Context, + writes: _ConnectionWrites, + ) -> None: + """Apply the writes the gates left standing, in request order.""" + client_addr = context.client_addr + tasks: dict[asyncio.Future[Any], _DelegateWrite] = {} + for write in work.writes: + if write.value is None: + # A null write applies nothing and runs no callback, like + # in the legacy path. + continue + if write.delegate is None: + coro: Any = self._apply_legacy_in_stage(write, context) + else: + char_context = CharWriteContext( + client_addr=context.client_addr, + client_uuid=context.client_uuid, + connection=context.connection, + deadline=context.deadline, + characteristic=write.char, + is_admin=work.is_admin, + ) + coro = write.delegate.on_set(write.value, char_context) + try: + tasks[asyncio.ensure_future(coro)] = write + except TypeError: + logger.exception( + "%s: on_set of %s is not a coroutine function", 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 HapStatusError as e: - # The setter answers the controller with its own HAP status. - logger.debug( - "%s: Characteristic %s answered status %s", - client_addr, - write.char.display_name, - e.status, - ) - write.result[HAP_REPR_STATUS] = e.status - continue - except (Exception, asyncio.CancelledError): - logger.exception( - "%s: Error while setting characteristic %s", - client_addr, - write.char.display_name, - ) - write.result[HAP_REPR_STATUS] = ( - HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE - ) + write.result[HAP_REPR_STATUS] = ( + HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + self._restore_write_value(write) + if not tasks: + return + try: + done, not_done = await asyncio.wait( + tasks, timeout=self._remaining(context.deadline) + ) + except asyncio.CancelledError: + for task, write in tasks.items(): + if task.done(): + self._finish_task_write(task, write, context, writes) continue - write.char.client_update_finished( - write.previous_value, client_addr, notify=write.notify + 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 + self._restore_write_value(write) + for task in done: + self._finish_task_write(task, tasks[task], context, writes) + + async def _apply_legacy_in_stage( + self, write: _DelegateWrite, context: Context + ) -> Any: + """Apply a legacy callback write of a gated service, after its gate. + + Mirrors the legacy path: the value is stored and the callback run + inline, a coroutine it returns is awaited, and subscribers are + told once it is done. + """ + client_addr = context.client_addr + response = write.char.client_update_value( + write.value, client_addr, notify=not write.private_write, defer_notify=True + ) + if inspect.iscoroutine(response): + outcome = await response + write.char.client_update_finished( + write.previous_value, client_addr, notify=not write.private_write + ) + return outcome + return response + + def _finish_task_write( + self, + task: asyncio.Future[Any], + write: _DelegateWrite, + context: Context, + writes: _ConnectionWrites, + ) -> None: + """Settle one applied write: status, response, subscribers.""" + client_addr = context.client_addr + try: + outcome = task.result() + except HapStatusError as e: + # The delegate answers the controller with its own HAP status. + logger.debug( + "%s: Characteristic %s answered status %s", + client_addr, + write.char.display_name, + e.status, + ) + write.result[HAP_REPR_STATUS] = e.status + self._restore_write_value(write) + return + except (Exception, asyncio.CancelledError): + logger.exception( + "%s: Error while setting characteristic %s", + client_addr, + write.char.display_name, + ) + write.result[HAP_REPR_STATUS] = ( + HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + self._restore_write_value(write) + return + # Complete the applied write: read back bookkeeping, response, notify. + response = outcome + if write.private_write: + response = _settle_private_write( + write.char, write.previous_value, write.value, response + ) + if response is not None and writes.alive: + self._keep_response( + write.result, write.char, response, write.write_response, client_addr + ) + if write.delegate is not None: + write.char.client_update_finished( + write.previous_value, client_addr, notify=not write.private_write + ) + + @staticmethod + def _restore_write_value(write: _DelegateWrite) -> None: + """Put back what a refused write of a delegate changed.""" + if write.delegate is not None and write.char.value != write.previous_value: + write.char.value = write.previous_value + + def _veto_writes(self, work: _DelegateWork, service: Service, status: int) -> None: + """Refuse every write of ``service``: restore, tell nobody, answer status.""" + kept: list[_DelegateWrite] = [] + for write in work.writes: + if write.service is not service: + kept.append(write) + continue + write.result[HAP_REPR_STATUS] = status + self._restore_write_value(write) + work.writes = kept + + def _collect_delegate_write( + self, + work: _DelegateWork, + client_addr: tuple[str, int], + char: Characteristic, + service: Service, + value: Any, + previous_value: Any, + write_response: bool, + private_write: bool, + ) -> dict[str, Any]: + """Collect a write for the delegate stage, return its result entry. + + A service with a delegate is gated as a whole, so the value goes + to its gate whatever the characteristic itself uses. A char with + a delegate stores the value now and its ``on_set`` applies it + once the gates accepted; a legacy callback char of a gated + service is applied after them, like the value writes of the + legacy path. + """ + if service.delegate is not None: + work.gates.setdefault(service, {})[char] = value + delegate = char.delegate + result: dict[str, Any] = {HAP_REPR_STATUS: HAP_SERVER_STATUS.SUCCESS} + if delegate is not None and value is not None: + try: + previous_value = char._store_client_value(value) + except Exception: + logger.exception( + "%s: Error while setting characteristic %s to %s", + client_addr, + char.display_name, + value, ) - 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] + result[HAP_REPR_STATUS] = ( + HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + return result + value = char.value + work.writes.append( + _DelegateWrite( + char, + value, + previous_value, + result, + write_response, + private_write, + service, + delegate, + ) + ) + return result @staticmethod def _finish_done_write( diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index 9234fc10..6a4a5835 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -561,6 +561,23 @@ def client_update_value( ) return response + def _store_client_value(self, value: Any) -> Any: + """Store a controller's write without running any callback. + + The new-style write path of the driver: validate and store the + value like :meth:`client_update_value` does, tell no subscriber + and call no callback - the driver runs the characteristic's + ``on_set`` and notifies 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, diff --git a/pyhap/delegates.py b/pyhap/delegates.py index 486b4a2f..1cb60df5 100644 --- a/pyhap/delegates.py +++ b/pyhap/delegates.py @@ -63,6 +63,8 @@ async def on_set(self, value: Any, context: CharWriteContext) -> Any: 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: @@ -88,9 +90,11 @@ class ServiceDelegate: 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 whole - request before anything is applied: values are restored, subscribers - are told nothing, and per-characteristic ``on_set`` calls do not run. + 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 diff --git a/pyhap/hap_handler.py b/pyhap/hap_handler.py index 736f0227..79cc4b3a 100644 --- a/pyhap/hap_handler.py +++ b/pyhap/hap_handler.py @@ -20,6 +20,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 +146,22 @@ 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 + self.connection = connection or HAPConnectionHandle( + cast("tuple[str, int] | None", client_address), + self.accessory_handler._next_connection_generation(), + ) self.is_encrypted = False self.client_uuid: uuid.UUID | None = None @@ -708,13 +717,14 @@ 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) + self._set_characteristics_body(self.response, result) ) return self._fill_set_characteristics_response(self.response, result) @@ -732,7 +742,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.""" diff --git a/pyhap/hap_protocol.py b/pyhap/hap_protocol.py index 75da13a1..f9f0a735 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 @@ -127,7 +128,14 @@ def connection_made(self, transport: asyncio.BaseTransport) -> None: 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, see ``HAPConnectionHandle``. + self.connection_handle = HAPConnectionHandle( + peername, self.accessory_driver._next_connection_generation() + ) + self.handler = HAPServerHandler( + self.accessory_driver, peername, self.connection_handle + ) def derive_key(self, salt: bytes, info: bytes) -> bytes | None: """Derive a key from this connection's pair-verify session key. diff --git a/tests/test_delegate_dispatch.py b/tests/test_delegate_dispatch.py new file mode 100644 index 00000000..fb6788e0 --- /dev/null +++ b/tests/test_delegate_dispatch.py @@ -0,0 +1,561 @@ +"""Tests for the delegate write dispatch of the driver.""" + +import asyncio +from collections.abc import Mapping +import inspect +from typing import Any +from unittest.mock import MagicMock, patch +from uuid import UUID, uuid1, uuid4 + +from pyhap.accessory import STANDALONE_AID, Accessory +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_AID, + HAP_REPR_CHARS, + HAP_REPR_IID, + HAP_REPR_STATUS, + HAP_REPR_VALUE, + HAP_REPR_WRITE_RESPONSE, + HAP_SERVER_STATUS, +) +from pyhap.context import CharWriteContext, ServiceWriteContext +from pyhap.delegates import CharacteristicDelegate, ServiceDelegate +from pyhap.errors import HapStatusError +from pyhap.service import Service + +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 _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, +) -> 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 + 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}") + + +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 _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(WRITER) + # 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_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_runs_no_on_set(driver: AccessoryDriver) -> None: + """A null write applies nothing 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 result is None + 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_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(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(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_callback = MagicMock() + char.delegate = _CharDelegate() + + await _write_chars(driver, acc, [(char, 7)]) + + acc.setter_callback.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) + + write = asyncio.ensure_future( + _write_chars(driver, acc, [(char, 5)], write_response=True) + ) + await asyncio.sleep(0) + driver.connection_lost(WRITER) + await asyncio.sleep(0) + release.set() + + assert await write is None + assert driver._write_responses == {} + + +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.client_addr is None + assert context.deadline == float("inf") + notify.assert_called_once_with(WRITER) From 067b07afb79aa99c8ca0fdb8802823d3fa5b5d28 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 16 Nov 2026 15:44:45 +0100 Subject: [PATCH 09/14] Migrate the camera stack to delegates and connection handles Every characteristic pyhap's own camera code answers - the classic RTP stream management, the HDS transport setup, the recording and HKSV 17.99 settings, the multi-tier and WebRTC control points - now runs its handler through a CharacteristicDelegate, so no internal setter_callback wiring is left. A camera delegate serves them all from a per-characteristic handler registry, answers reads with the stored value, and its handlers receive the write context: set_data_stream_transport derives the HDS keys from the writing connection it carries. The (value, sender_client_addr) setter opt-in is deleted with the magic parameter-name detection that implemented it: a legacy setter is always called with the value alone, and what a callback needs to know about a request comes through the delegate interface instead. Stream sessions own their connection by its HAPConnectionHandle, not its address: a later connection that reuses a closed one's address can no longer control or crowd out its sessions, closing the address-reuse bug class for multi-tier and WebRTC. A closed connection still ends its sessions by address, the conservative guard of the address-keyed phase. The controllers run their hooks under the request's write deadline from the context; the self-computed one is gone. --- docs/source/advanced/async.rst | 16 +++- docs/source/api/delegates.rst | 16 ++-- docs/source/intro/tutorial.rst | 9 ++- docs/source/media/camera.rst | 8 +- pyhap/camera.py | 116 +++++++++++++++++++++------- pyhap/camera_multi_tier.py | 76 +++++++++++++----- pyhap/camera_stream.py | 49 +++++++----- pyhap/camera_webrtc.py | 86 ++++++++++++++------- pyhap/characteristic.py | 63 +++------------ tests/conftest.py | 55 ++++++++++++- tests/media_fakes.py | 3 +- tests/media_hap.py | 5 +- tests/test_accessory_driver.py | 12 --- tests/test_camera.py | 56 +++++++------- tests/test_camera_capabilities.py | 48 ++++++------ tests/test_camera_multi_tier.py | 28 +++++-- tests/test_camera_operating_mode.py | 41 +++++----- tests/test_camera_stream.py | 89 +++++++++++++++------ tests/test_camera_webrtc.py | 60 +++++++++----- tests/test_camera_webrtc_hap.py | 5 +- tests/test_hksv_gating.py | 19 +++-- tests/test_hksv_recording.py | 66 ++++++++++++---- tests/test_hksv_state.py | 27 +++---- tests/test_media_multi_tier_e2e.py | 27 +++++-- 24 files changed, 643 insertions(+), 337 deletions(-) diff --git a/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index db940c40..04a67faf 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -107,10 +107,10 @@ 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. **Answering a HAP status.** A callback that fails does not have to answer the generic ``-70402`` (service communication failure): raise @@ -183,6 +183,14 @@ delegate, however, is gated as a whole — the legacy callback chars of that service are applied after its gate too, so the gate sees every value and can refuse the group. +The camera stack itself writes through delegates: every characteristic +pyhap's own camera code answers — the stream management services' control +points, the HDS transport setup, the recording and HKSV 17.99 settings — +runs its handler through the interface above. Its multi-tier and WebRTC +sessions belong to the connection that set them up, by +:class:`~pyhap.connection.HAPConnectionHandle`, so a later connection that +reuses a closed one's address cannot control them. + Provided utilities ================== diff --git a/docs/source/api/delegates.rst b/docs/source/api/delegates.rst index 4f9f6f96..eed3cd26 100644 --- a/docs/source/api/delegates.rst +++ b/docs/source/api/delegates.rst @@ -61,14 +61,18 @@ one per characteristic. **Rollout state.** The driver dispatches the writes of delegates from this release on: a write to a characteristic with a delegate, or to a service with one, runs its gates and its ``on_set`` calls as described -above, and answers with the per-characteristic statuses. Reads still -use the legacy path - the async read pipeline and the -``on_subscribe`` / ``on_unsubscribe`` hooks follow in the next -releases of the callback interface refactor. The legacy +above, and answers with the per-characteristic statuses. pyhap's own +camera stack writes through delegates - every characteristic its camera +code answers is served by one, and its stream sessions belong to the +connection that set them up, by +:class:`~pyhap.connection.HAPConnectionHandle`. Reads still use the +legacy path - the async read pipeline and the ``on_subscribe`` / +``on_unsubscribe`` hooks follow in the next releases of the callback +interface refactor. The legacy :attr:`~pyhap.characteristic.Characteristic.setter_callback` / :attr:`~pyhap.characteristic.Characteristic.getter_callback` attributes -keep working unchanged for code that uses them alone, and are -deprecated once the read pipeline dispatches delegates too. +keep working unchanged for code that uses them alone, and are deprecated +once the read pipeline dispatches delegates too. A request may mix both interfaces. A characteristic with a legacy callback keeps its legacy dispatch, byte for byte, unless its service diff --git a/docs/source/intro/tutorial.rst b/docs/source/intro/tutorial.rst index 88b92c34..10ef59f8 100644 --- a/docs/source/intro/tutorial.rst +++ b/docs/source/intro/tutorial.rst @@ -177,10 +177,11 @@ 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`. 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/camera.py b/pyhap/camera.py index 28eb218d..9838663c 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 @@ -44,6 +45,8 @@ from pyhap.camera_webrtc import WebRTCConfig, WebRTCController from pyhap.characteristic import Characteristic 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 +282,42 @@ ) +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 written, and each has its handler + in ``handlers``. A 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]] = {} + + 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 + + async def on_get(self, context: CharReadContext) -> Any: + # Reads answer the stored value, like the camera always has. + return context.characteristic.value + + 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 +686,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: @@ -787,15 +827,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 @@ -965,7 +1004,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) @@ -1006,9 +1048,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 +1105,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 +1145,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 +1184,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 +1221,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.client_addr), request.controller_key_salt, ) if listener is None or accessory_salt is None: @@ -1282,8 +1329,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: @@ -1458,6 +1509,16 @@ 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 _persist_hksv3_char( self, char: Characteristic, key: str, handler: Callable[[Any], None] ) -> None: @@ -1468,7 +1529,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..fb66bae4 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.client_addr, 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..63e8457d 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 @@ -460,7 +465,13 @@ 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 driver reports a + closed connection by address, and while a later connection may reuse + it, a live one has its own sessions under its own handle - ending by + address is the conservative guard of the address-keyed phase. + """ 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 6a4a5835..5ad4c143 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -31,22 +31,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 @@ -196,8 +180,6 @@ class Characteristic: "_to_hap_cache_with_value", "_to_hap_cache", "_always_null", - "_setter_addr_cache", - "_setter_addr_cache_for", "read_back_response", ) @@ -239,20 +221,16 @@ def __init__( 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. + # The legacy setter is called with the written value. 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 # The delegate of the reads, writes and subscriptions of this # characteristic, see ``CharacteristicDelegate``. Either a delegate # or the legacy callbacks, never both. self.delegate: CharacteristicDelegate | 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 self.service: Service | None = None self.unique_id = unique_id self._uuid_str = uuid_to_hap_type(type_id) @@ -328,11 +306,12 @@ def getter_callback(self) -> None: def setter_callback(self) -> Callable[..., Any] | None: """The legacy setter, called with the value on a controller's write. - 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. May also be a coroutine function; a - controller's write is answered once it is done. + 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`. """ return self._setter_callback @@ -551,10 +530,7 @@ def client_update_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) + response = self.setter_callback(value) if not (defer_notify and inspect.iscoroutine(response)): self.client_update_finished( previous_value, sender_client_addr, notify=notify @@ -595,21 +571,6 @@ def client_update_finished( if self._always_null: self.value = None - def _setter_wants_addr(self) -> bool: - """Whether the current setter opts into the sender's client address. - - 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. - """ - 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 - def notify(self, sender_client_addr: tuple[str, int] | None = None) -> None: """Notify clients about a value change. Sends the value. diff --git a/tests/conftest.py b/tests/conftest.py index 65793154..2e209894 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -17,8 +17,59 @@ 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. + + A delegate-wired characteristic goes through its delegate: the value + is stored, ``on_set`` runs under the write deadline and the + subscribers are told once it succeeded - what the driver's write + stage does. A handler that raises restores the previous value, like + the driver does. A characteristic without a delegate runs its legacy + ``setter_callback``, like ``client_update_value``. + """ + if char.delegate is None: + return char.client_update_value(value, client_addr) + 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_value(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 + @pytest.fixture(scope="session") def mock_driver() -> Iterator["MockDriver"]: @@ -189,7 +240,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..05901638 100644 --- a/tests/media_hap.py +++ b/tests/media_hap.py @@ -14,6 +14,7 @@ from pyhap.camera import Camera from pyhap.util import base64_to_bytes, to_base64_str +from .conftest import connection_of from .media_peer import KEY, KEYFRAME, TRAIL, Controller, Source, video_count from .webrtc_helpers import SFrameKey @@ -87,7 +88,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=connection_of(CLIENT) + ) assert inspect.isawaitable(pending) result = await pending assert result is not None diff --git a/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index 60771b93..b79240e3 100644 --- a/tests/test_accessory_driver.py +++ b/tests/test_accessory_driver.py @@ -829,11 +829,6 @@ async def _async_return_one(value: int) -> int: return 1 -async def _async_return_one_with_addr(value: int, sender_client_addr: Any) -> int: - await asyncio.sleep(0) - return 1 - - async def _async_return_none(value: int) -> None: await asyncio.sleep(0) @@ -854,13 +849,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"], diff --git a/tests/test_camera.py b/tests/test_camera.py index 4ac62d27..f7e18775 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 @@ -15,6 +16,7 @@ from pyhap import camera, tlv from pyhap.camera_talkback import TalkbackReceiverProtocol +from tests.conftest import client_write # A Setup Endpoints request of a controller at 192.168.1.114. _SETUP_ENDPOINTS_REQUEST = ( @@ -82,7 +84,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 +96,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 +113,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 +182,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 +193,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 +247,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 +260,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 +292,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 +335,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 +367,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 +526,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 +553,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 +561,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 +598,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 +606,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 +621,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 +633,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 +729,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 +747,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..a6a364cc 100644 --- a/tests/test_camera_operating_mode.py +++ b/tests/test_camera_operating_mode.py @@ -14,6 +14,7 @@ from pyhap.accessory_driver import AccessoryDriver from pyhap.camera import SETUP_STATUS, SETUP_TYPES, STREAMING_STATUS, Camera from pyhap.characteristic import PROP_PERMISSIONS +from tests.conftest import client_write CAMERA_AID = 2 GLOBAL = "CameraGlobalOperatingMode" @@ -143,7 +144,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 +170,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 +216,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 +230,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 +244,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 +265,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 +303,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 +336,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 +348,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 +427,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 +439,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..4fcf0b21 100644 --- a/tests/test_camera_webrtc_hap.py +++ b/tests/test_camera_webrtc_hap.py @@ -12,6 +12,7 @@ from pyhap.accessory_driver import AccessoryDriver from pyhap.camera import Camera from pyhap.util import base64_to_bytes, to_base64_str +from tests.conftest import connection_of WEBRTC = "CameraWebRTCStreamManagement" MULTI_TIER = "CameraMultiTierRTPStreamManagement" @@ -55,7 +56,9 @@ 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) + result = driver._set_characteristics_for_controller( + query, CLIENT, timeout, connection=connection_of(CLIENT) + ) assert inspect.isawaitable(result) body = await result # Without r a write that succeeds has no body. 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..aa80f4d2 100644 --- a/tests/test_hksv_recording.py +++ b/tests/test_hksv_recording.py @@ -6,7 +6,9 @@ test_hds_recording.py. """ +import inspect import os +import time from typing import Any from unittest.mock import MagicMock, patch @@ -16,9 +18,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 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 +275,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 +297,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,7 +322,7 @@ def _hap_connection( return connection -def _write_setup( +async def _write_setup( camera: Any, client: tuple[str, int], controller_key_salt: bytes ) -> dict[bytes, Any]: """Write SetupDataStreamTransport through the HAP write-response path.""" @@ -304,7 +330,8 @@ def _write_setup( "SetupDataStreamTransport" ) request = tlv.encode(hds.SETUP_TYPES["CONTROLLER_KEY_SALT"], controller_key_salt) - response = camera.driver.set_characteristics( + connection = camera.driver.http_server.connections.get(client) + response = camera.driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -316,16 +343,22 @@ def _write_setup( ] }, client, + RESPONSE_TIMEOUT, + connection=connection.connection_handle if connection else None, ) - 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: @@ -333,7 +366,7 @@ async def test_setup_data_stream_transport_write_response_plumbing( 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) + objs = await _write_setup(camera, client, 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 @@ -354,7 +387,7 @@ async def test_setup_data_stream_transport_unencrypted_connection_errors( try: client = ("10.0.0.9", 5000) _hap_connection(camera, client) - objs = _write_setup(camera, client, os.urandom(32)) + objs = await _write_setup(camera, client, 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,7 +459,7 @@ 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) @@ -445,7 +477,7 @@ def test_sensor_follows_camera_active_set_without_write( assert status_active.get_value() 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 +488,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..8a3cd269 100644 --- a/tests/test_hksv_state.py +++ b/tests/test_hksv_state.py @@ -18,6 +18,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 +96,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 +120,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 +133,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 +148,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 +159,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) @@ -234,7 +235,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 +246,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 +276,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 +291,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 +447,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_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] From 0162a9a5efd21c9c93cb7d6f519cd63e073f44de Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 16 Nov 2026 16:10:46 +0100 Subject: [PATCH 10/14] Add the connection lifecycle hooks and dispatch subscription hooks Accessory gains two overridable connection hooks, client_connected and client_verified, the async counterparts of client_disconnected: the first runs when a controller's TCP connection is accepted, the second when it finishes pair verify, with the controller's UUID. A bridge forwards both to each bridged accessory, isolating one accessory's failure like client_disconnected does. The driver schedules them as isolated jobs: a hook never delays the connection or the pair verify response, and its exception is logged, never raised. Delegates hear about event subscriptions: a controller's ev write runs on_subscribe of the characteristic's delegate, on_unsubscribe when it unsubscribes, and on_unsubscribe again when its connection closes while subscribed - with a CharReadContext whose connection and client_uuid are the closed connection's. The hooks run on the transition only, isolated from the request: they are scheduled without a deadline, so a write or a connection close never waits for one, and a failing hook is logged without touching the subscription, which has already registered by then. driver.connection_lost takes the closed connection's identity as optional arguments, so the close path can build a hook's context; address-keyed cleanup is unchanged, and direct callers keep working with None. --- docs/source/advanced/async.rst | 43 ++++++ docs/source/api/delegates.rst | 16 +- pyhap/accessory.py | 60 +++++++- pyhap/accessory_driver.py | 180 ++++++++++++++++++++-- pyhap/delegates.py | 15 +- pyhap/hap_handler.py | 3 + pyhap/hap_protocol.py | 8 +- tests/test_delegate_dispatch.py | 169 +++++++++++++++++++- tests/test_lifecycle.py | 262 ++++++++++++++++++++++++++++++++ 9 files changed, 732 insertions(+), 24 deletions(-) create mode 100644 tests/test_lifecycle.py diff --git a/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index 04a67faf..17eca83d 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 ======================== @@ -191,6 +202,38 @@ sessions belong to the connection that set them up, by :class:`~pyhap.connection.HAPConnectionHandle`, so a later connection that reuses a closed one's address cannot control them. +Delegate subscriptions +====================== + +A controller enables events for a characteristic by writing it with +``ev``, and a delegate hears about that: the +``on_subscribe``/``on_unsubscribe`` of the characteristic's +:class:`~pyhap.delegates.CharacteristicDelegate` run with a +:class:`~pyhap.context.CharReadContext` — the same context as a read, +without a deadline. + +The hooks are isolated from what caused them: they run as background +jobs, so the write request (or the connection close) never waits for +one, and a failing hook is logged without affecting the subscription — +the subscription itself has already registered. They run on the change +only: subscribing a controller that is already subscribed, or +unsubscribing one that is not, runs nothing. + +``on_unsubscribe`` also runs when a subscribed controller's connection +closes, with the connection's identity and its UUID when the driver +knows them. Use the pair to run work only while someone listens — e.g. +poll a battery-powered sensor between ``on_subscribe`` and +``on_unsubscribe``: + +.. code-block:: python + + class SensorDelegate(CharacteristicDelegate): + async def on_subscribe(self, context): + self.task = asyncio.create_task(self._poll()) + + async def on_unsubscribe(self, context): + self.task.cancel() + Provided utilities ================== diff --git a/docs/source/api/delegates.rst b/docs/source/api/delegates.rst index eed3cd26..42ac710d 100644 --- a/docs/source/api/delegates.rst +++ b/docs/source/api/delegates.rst @@ -61,14 +61,16 @@ one per characteristic. **Rollout state.** The driver dispatches the writes of delegates from this release on: a write to a characteristic with a delegate, or to a service with one, runs its gates and its ``on_set`` calls as described -above, and answers with the per-characteristic statuses. pyhap's own -camera stack writes through delegates - every characteristic its camera -code answers is served by one, and its stream sessions belong to the -connection that set them up, by +above, and answers with the per-characteristic statuses. The subscription +hooks dispatch too: ``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. +pyhap's own camera stack writes through delegates - every characteristic +its camera code answers is served by one, and its stream sessions belong +to the connection that set them up, by :class:`~pyhap.connection.HAPConnectionHandle`. Reads still use the -legacy path - the async read pipeline and the ``on_subscribe`` / -``on_unsubscribe`` hooks follow in the next releases of the callback -interface refactor. The legacy +legacy path - the async read pipeline is the last piece of the callback +interface refactor that follows. The legacy :attr:`~pyhap.characteristic.Characteristic.setter_callback` / :attr:`~pyhap.characteristic.Characteristic.getter_callback` attributes keep working unchanged for code that uses them alone, and are deprecated diff --git a/pyhap/accessory.py b/pyhap/accessory.py index 78538e20..e23fd396 100644 --- a/pyhap/accessory.py +++ b/pyhap/accessory.py @@ -337,7 +337,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: @@ -473,6 +509,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 171a879a..a28d37db 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -20,7 +20,7 @@ import asyncio import base64 from collections import defaultdict -from collections.abc import Awaitable, Coroutine +from collections.abc import Awaitable, Callable, Coroutine from concurrent.futures import ThreadPoolExecutor import hashlib import inspect @@ -69,7 +69,12 @@ HAP_REPR_WRITE_RESPONSE, STANDALONE_AID, ) -from pyhap.context import CharWriteContext, Context, ServiceWriteContext +from pyhap.context import ( + CharReadContext, + CharWriteContext, + Context, + ServiceWriteContext, +) from pyhap.delegates import CharacteristicDelegate from pyhap.encoder import AccessoryEncoder from pyhap.hap_server import HAPServer @@ -805,13 +810,93 @@ 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, when the + caller knows it. It reaches the ``on_unsubscribe`` calls of the + subscribed characteristics' delegates. + :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 """ client_topics = [] for topic, subscribed_clients in self.topics.items(): @@ -820,8 +905,13 @@ def connection_lost(self, client: Any) -> None: # self.topics during iteration client_topics.append(topic) + accessory = self.accessory for topic in client_topics: self.async_subscribe_client_topic(client, topic, subscribe=False) + if accessory is not None: + self._dispatch_close_unsubscribe( + topic, accessory, client, client_uuid, connection + ) 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 @@ -832,7 +922,6 @@ def connection_lost(self, client: Any) -> None: 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 if accessory is None: return try: @@ -842,6 +931,22 @@ 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, + ) -> 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 and char.delegate is not None: + self._dispatch_subscription( + char.delegate, char, False, client_addr, client_uuid, connection + ) + def publish( self, data: dict[str, Any], @@ -1359,7 +1464,7 @@ def set_characteristics( call without one. """ results, pending, work = self._apply_characteristic_writes( - chars_query, client_addr, client_uuid + chars_query, client_addr, client_uuid, connection ) for write in pending: self.add_job(self._finish_pending_write(write, client_addr)) @@ -1409,7 +1514,7 @@ def _set_characteristics_for_controller( closed does not get it kept: it would never be read. """ results, pending, work = self._apply_characteristic_writes( - chars_query, client_addr, client_uuid + chars_query, client_addr, client_uuid, connection ) if work: writes = _ConnectionWrites() @@ -1434,6 +1539,7 @@ def _apply_characteristic_writes( chars_query: dict[str, Any], client_addr: tuple[str, int], client_uuid: UUID | None, + connection: HAPConnectionHandle | None, ) -> tuple[ dict[int, dict[int, dict[str, Any]]], list[_PendingWrite], _DelegateWork ]: @@ -1442,7 +1548,7 @@ def _apply_characteristic_writes( work = _DelegateWork(self.state.is_admin(client_uuid)) try: results, pending = self._run_characteristic_writes( - chars_query, client_addr, client_uuid, pending, work + chars_query, client_addr, client_uuid, connection, pending, work ) except BaseException: # A malformed later entry must not leave a setter coroutine @@ -1457,6 +1563,7 @@ def _run_characteristic_writes( chars_query: dict[str, Any], client_addr: tuple[str, int], client_uuid: UUID | None, + connection: HAPConnectionHandle | None, pending: list[_PendingWrite], delegate_work: _DelegateWork, ) -> tuple[dict[int, dict[int, dict[str, Any]]], list[_PendingWrite]]: @@ -1475,7 +1582,7 @@ def _run_characteristic_writes( } 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]] @@ -2265,13 +2372,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 | None, ) -> 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() @@ -2291,7 +2405,53 @@ def _notify( continue char_topic = get_topic(aid, iid) + was_subscribed = client_addr 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) + if char is not None and char.delegate is not None and ev != was_subscribed: + self._dispatch_subscription( + char.delegate, char, ev, client_addr, client_uuid, connection + ) return not_notifiable + + def _dispatch_subscription( + self, + delegate: CharacteristicDelegate, + characteristic: Characteristic, + subscribe: bool, + client_addr: tuple[str, int] | None, + client_uuid: UUID | None, + connection: HAPConnectionHandle | None, + ) -> None: + """Run a delegate'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 = CharReadContext( + client_addr=client_addr, + client_uuid=client_uuid, + connection=connection + or HAPConnectionHandle(client_addr, self._next_connection_generation()), + deadline=float("inf"), + characteristic=characteristic, + ) + if subscribe: + self.add_job( + self._run_isolated_hook, + delegate.on_subscribe, + (context,), + "on_subscribe", + client_addr, + ) + else: + self.add_job( + self._run_isolated_hook, + delegate.on_unsubscribe, + (context,), + "on_unsubscribe", + client_addr, + ) diff --git a/pyhap/delegates.py b/pyhap/delegates.py index 1cb60df5..c340f112 100644 --- a/pyhap/delegates.py +++ b/pyhap/delegates.py @@ -71,15 +71,22 @@ 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. Failures are logged and isolated; - the subscription itself always registers. + 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. - Failures are logged and isolated. + 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. """ diff --git a/pyhap/hap_handler.py b/pyhap/hap_handler.py index 79cc4b3a..b9ad9dd5 100644 --- a/pyhap/hap_handler.py +++ b/pyhap/hap_handler.py @@ -660,6 +660,9 @@ 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.""" diff --git a/pyhap/hap_protocol.py b/pyhap/hap_protocol.py index f9f0a735..2787cad1 100644 --- a/pyhap/hap_protocol.py +++ b/pyhap/hap_protocol.py @@ -64,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 @@ -104,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: @@ -136,6 +141,7 @@ def connection_made(self, transport: asyncio.BaseTransport) -> None: 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. diff --git a/tests/test_delegate_dispatch.py b/tests/test_delegate_dispatch.py index fb6788e0..30c786d0 100644 --- a/tests/test_delegate_dispatch.py +++ b/tests/test_delegate_dispatch.py @@ -7,6 +7,8 @@ from unittest.mock import MagicMock, patch from uuid import UUID, uuid1, uuid4 +import pytest + from pyhap.accessory import STANDALONE_AID, Accessory from pyhap.accessory_driver import AccessoryDriver from pyhap.characteristic import ( @@ -29,7 +31,7 @@ HAP_REPR_WRITE_RESPONSE, HAP_SERVER_STATUS, ) -from pyhap.context import CharWriteContext, ServiceWriteContext +from pyhap.context import CharReadContext, CharWriteContext, ServiceWriteContext from pyhap.delegates import CharacteristicDelegate, ServiceDelegate from pyhap.errors import HapStatusError from pyhap.service import Service @@ -71,6 +73,12 @@ def _add_service_with_chars( 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, @@ -80,6 +88,7 @@ async def _write_chars( 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 = [] @@ -92,6 +101,8 @@ async def _write_chars( 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}, @@ -139,6 +150,25 @@ async def on_set(self, value: Any, context: CharWriteContext) -> Any: 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.""" @@ -520,6 +550,143 @@ async def test_write_response_dropped_when_closed_before_on_set_done( 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 == float("inf") + assert driver.topics == {char_topic: {WRITER}} + + +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: {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: 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 From 338ac19f8ce23d122ea0eaa6e9b33fb4df901f38 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 16 Nov 2026 16:25:23 +0100 Subject: [PATCH 11/14] Dispatch delegate reads: async getters for characteristics and accessories GET /characteristics and GET /accessories await the on_get of every delegate-backed characteristic of the request, concurrently under the same deadline as a write: a read that misses it answers -70408, a failing one answers its HapStatusError status or -70402, and in the accessories list a failing read lists its characteristic without a value, like a failing getter does. The answer is validated and stored like a legacy getter's; subscribers are not told. Requests without delegates execute exactly today's code: legacy getters run inline, byte for byte. A write response still wins over on_get for the connection that wrote. Direct calls cannot await, so they answer the stored values and run the delegate reads as a job without a deadline, like a direct write runs its setters. The to_HAP value cache skips delegate-backed characteristics, as it skips getter-backed ones. --- docs/source/advanced/async.rst | 32 +++ docs/source/api/delegates.rst | 16 +- docs/source/intro/overview.rst | 11 ++ pyhap/accessory_driver.py | 341 +++++++++++++++++++++++++++++++- pyhap/characteristic.py | 17 +- pyhap/delegates.py | 7 +- pyhap/hap_handler.py | 68 +++++-- tests/test_characteristic.py | 23 +++ tests/test_delegate_dispatch.py | 333 ++++++++++++++++++++++++++++++- tests/test_hap_handler.py | 83 ++++++++ 10 files changed, 895 insertions(+), 36 deletions(-) diff --git a/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index 17eca83d..27e2e3d5 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -202,6 +202,38 @@ sessions belong to the connection that set them up, by :class:`~pyhap.connection.HAPConnectionHandle`, so a later connection that reuses a closed one's address cannot control them. +Delegate reads +================ + +Reads await delegates the same way writes do — this is the point of the +getter and the setter having the same async-ness. ``GET +/characteristics`` and ``GET /accessories`` await the ``on_get`` of every +delegate-backed characteristic of the request, concurrently, under the +same deadline as a write: + +* a read that misses the deadline answers ``-70408`` for its + characteristic; cancelling the response — e.g. because the connection + closed — cancels the reads, like it cancels writes; +* a failing read answers its status: a raised + :class:`pyhap.errors.HapStatusError` answers its code, anything else + ``-70402``. The accessories list carries no per-characteristic status, + so there a failing read lists its characteristic without a value, + like a failing getter does; +* the answer is validated like any value, then stored on the + characteristic — like a legacy getter's answer. Subscribers are not + told: a read is not a change. + +A write response still wins over ``on_get``: the connection that wrote a +``read_back_response`` characteristic reads back what it wrote, and the +other connections read ``on_get``'s answer. + +Direct calls cannot await: ``driver.get_characteristics(...)`` and +``driver.get_accessories()`` answer the stored values at once and run the +delegate reads as a job without a deadline, like a direct write runs its +setters. The HAP representation cache skips delegate-backed +characteristics, as it skips getter-backed ones, since a read may answer +something else than the stored value. + Delegate subscriptions ====================== diff --git a/docs/source/api/delegates.rst b/docs/source/api/delegates.rst index 42ac710d..47989f76 100644 --- a/docs/source/api/delegates.rst +++ b/docs/source/api/delegates.rst @@ -65,16 +65,16 @@ above, and answers with the per-characteristic statuses. The subscription hooks dispatch too: ``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. -pyhap's own camera stack writes through delegates - every characteristic -its camera code answers is served by one, and its stream sessions belong -to the connection that set them up, by -:class:`~pyhap.connection.HAPConnectionHandle`. Reads still use the -legacy path - the async read pipeline is the last piece of the callback -interface refactor that follows. The legacy +Reads dispatch as well: the ``on_get`` of a delegate-backed characteristic +answers ``GET /characteristics`` and ``GET /accessories`` under the read +deadline, like a write's callbacks. pyhap's own camera stack uses delegates +for everything its camera code answers - its reads, writes, its stream +sessions belong to the connection that set them up, by +:class:`~pyhap.connection.HAPConnectionHandle`. The legacy :attr:`~pyhap.characteristic.Characteristic.setter_callback` / :attr:`~pyhap.characteristic.Characteristic.getter_callback` attributes -keep working unchanged for code that uses them alone, and are deprecated -once the read pipeline dispatches delegates too. +keep working unchanged for code that uses them alone; their deprecation +is announced separately when it happens. A request may mix both interfaces. A characteristic with a legacy callback keeps its legacy dispatch, byte for byte, unless its service diff --git a/docs/source/intro/overview.rst b/docs/source/intro/overview.rst index 56ae2166..c3d26afd 100644 --- a/docs/source/intro/overview.rst +++ b/docs/source/intro/overview.rst @@ -135,6 +135,17 @@ 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 two interfaces: a getter callback runs +inline and answers at once, while the ``on_get`` of a delegate-backed +characteristic is awaited — concurrently with the rest of the request, +under a deadline — 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/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index a28d37db..ea9cf338 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -63,6 +63,7 @@ HAP_REPR_CHARS, HAP_REPR_IID, HAP_REPR_PID, + HAP_REPR_SERVICES, HAP_REPR_STATUS, HAP_REPR_TTL, HAP_REPR_VALUE, @@ -253,6 +254,26 @@ def __init__(self) -> None: self.alive = True +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. + """ + + rep: dict[str, Any] + char: Characteristic + delegate: CharacteristicDelegate + + +def _ignore_read_answer(read: _DelegateRead, value: Any, status: int | None) -> None: + """Drop the rep answer of a background read of a direct call. + + 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. + """ + + class _DelegateWrite(NamedTuple): """A characteristic write the delegate stage applies. @@ -1266,6 +1287,11 @@ def get_accessories(self, include_value: bool = True) -> dict[str, Any]: } :rtype: dict + + A direct call answers the stored values of delegate-backed + characteristics and runs their reads as a job without a deadline, + like a direct write runs its setters; a controller's request + awaits them through their ``on_get`` instead. """ assert self.accessory is not None # noqa: S101 hap_rep = self.accessory.to_HAP(include_value=include_value) @@ -1273,9 +1299,94 @@ def get_accessories(self, include_value: bool = True) -> dict[str, Any]: hap_rep = [ hap_rep, ] + 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, + reads, + self._request_context(None, None, 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, + ) -> dict[str, Any] | Awaitable[dict[str, Any]]: + """Answer a controller's accessories request, awaiting delegate reads. + + Returns an awaitable of the response when a readable characteristic + is delegate-backed: its ``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. + """ + assert self.accessory is not None # noqa: S101 + hap_rep = self.accessory.to_HAP() + if not isinstance(hap_rep, list): + hap_rep = [ + hap_rep, + ] + reads = self._collect_accessory_reads(hap_rep) + if reads: + return self._read_accessories_response( + hap_rep, + reads, + self._request_context(client_addr, client_uuid, connection, timeout), + ) + return {HAP_REPR_ACCS: hap_rep} + + async def _read_accessories_response( + self, + hap_rep: list[dict[str, Any]], + reads: list[_DelegateRead], + context: Context, + ) -> dict[str, Any]: + """Answer the delegate reads of an accessories request.""" + await self._read_delegate_values(reads, context, 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 char.delegate is None: + continue + 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, char.delegate)) + return reads + def get_characteristics( self, char_ids: Any, client_addr: tuple[str, int] | None = None ) -> dict[str, Any]: @@ -1301,12 +1412,78 @@ def get_characteristics( } :rtype: dict + + A characteristic with a delegate answers its stored value here: + ``on_get`` is async, so a direct call answers at once and runs the + reads as a job without a deadline, like a direct write runs its + setters. A controller's read goes through + ``_get_characteristics_for_controller`` instead and awaits them. + """ + chars, reads = self._collect_characteristic_reads(char_ids, client_addr) + if reads: + self.add_job( + self._read_delegate_values, + reads, + self._request_context(client_addr, None, None, 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, + ) -> dict[str, Any] | Awaitable[dict[str, Any]]: + """Read characteristics for a controller, awaiting the delegate reads. + + Returns an awaitable of the response when a read characteristic is + delegate-backed: its ``on_get`` runs under the deadline and a read + not done by it answers ``-70408``. Cancelling the awaitable, e.g. + because the connection closed, cancels the reads. Reads of legacy + characteristics run inline as before; a mixed request answers its + legacy parts in the same pass and its delegate parts once they + are done. + """ + chars, reads = self._collect_characteristic_reads(char_ids, client_addr) + if reads: + return self._read_characteristics_response( + chars, + reads, + self._request_context(client_addr, client_uuid, connection, timeout), + ) + return {HAP_REPR_CHARS: chars} + + async def _read_characteristics_response( + self, + chars: list[dict[str, Any]], + reads: list[_DelegateRead], + context: Context, + ) -> dict[str, Any]: + """Answer the delegate reads of a characteristics request.""" + await self._read_delegate_values(reads, context, self._answer_char_read) + return {HAP_REPR_CHARS: chars} + + def _collect_characteristic_reads( + self, char_ids: Any, client_addr: tuple[str, int] | None + ) -> tuple[list[dict[str, Any]], list[_DelegateRead]]: + """Answer a read per requested characteristic, collecting delegate reads. + + Legacy getters run inline, exactly as before. A characteristic with + a delegate answers its stored value optimistically and its read is + collected for the caller to run: a controller's request awaits it + through ``on_get``, a direct call runs it as a background job. """ assert self.accessory is not None # noqa: S101 write_responses = ( self._write_responses.get(client_addr, {}) if client_addr else {} ) chars = [] + reads: list[_DelegateRead] = [] for aid_iid in char_ids: aid, iid = (int(i) for i in aid_iid.split(".")) rep = { @@ -1343,12 +1520,19 @@ 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 + elif char.delegate is not None: + # Optimistic, the caller runs the read. + rep[HAP_REPR_VALUE] = char.value + rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS + reads.append(_DelegateRead(rep, char, char.delegate)) + else: + rep[HAP_REPR_VALUE] = char.get_value() + rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS except HapStatusError as e: # The getter answers the controller with its own HAP status. logger.debug( @@ -1372,8 +1556,7 @@ 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 @@ -1901,7 +2084,7 @@ def _next_connection_generation(self) -> int: def _request_context( self, - client_addr: tuple[str, int], + client_addr: tuple[str, int] | None, client_uuid: UUID | None, connection: HAPConnectionHandle | None, timeout: float | None, @@ -1910,7 +2093,9 @@ def _request_context( A direct call has no controller waiting on a timeout, so a ``timeout`` of ``None`` means no deadline. A call without a - connection gets a handle that belongs to no connection. + connection gets a handle that belongs to no connection; its + address is ``None`` when it has no controller at all, e.g. a + direct read. """ if connection is None: connection = HAPConnectionHandle(None, self._next_connection_generation()) @@ -1929,6 +2114,142 @@ def _remaining(deadline: float) -> float | None: return None return max(0.0, deadline - time.monotonic()) + async def _read_delegate_values( + self, + reads: list[_DelegateRead], + context: Context, + 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. + """ + tasks: dict[asyncio.Future[Any], _DelegateRead] = {} + for read in reads: + char_context = CharReadContext( + client_addr=context.client_addr, + client_uuid=context.client_uuid, + connection=context.connection, + deadline=context.deadline, + characteristic=read.char, + ) + try: + tasks[asyncio.ensure_future(read.delegate.on_get(char_context))] = read + except TypeError: + logger.exception( + "%s: on_get of %s is not a coroutine function", + context.client_addr, + read.char.display_name, + ) + self._finish_read( + read, + answer, + HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE, + ) + if not tasks: + return + try: + done, not_done = await asyncio.wait( + tasks, timeout=self._remaining(context.deadline) + ) + except asyncio.CancelledError: + for task in tasks: + task.cancel() + task.add_done_callback(_retrieve_late_result) + raise + for task in not_done: + task.cancel() + task.add_done_callback(_retrieve_late_result) + 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] + try: + value = task.result() + except HapStatusError as e: + # 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, + e.status, + ) + self._finish_read(read, answer, e.status) + except Exception: + logger.exception( + "%s: Error getting value for characteristic %s", + context.client_addr, + read.char.display_name, + ) + self._finish_read( + read, answer, HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + ) + else: + self._finish_read(read, answer, None, 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, + ) + value = None + status = HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + answer(read, value, status) + + @staticmethod + 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: + """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, work: _DelegateWork, diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index 5ad4c143..b5b805cc 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -372,6 +372,11 @@ 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: @@ -593,7 +598,11 @@ 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.getter_callback is None + and self.delegate is None + ): return self._to_hap_cache_with_value elif self._to_hap_cache is not None: return self._to_hap_cache @@ -643,8 +652,10 @@ def to_HAP(self, include_value: bool = True) -> dict[str, Any]: 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.getter_callback is None and self.delegate is None: + # Only cache if nothing answers reads dynamically: a getter + # callback or a delegate's on_get may answer something else + # than the stored value. self._to_hap_cache_with_value = hap_rep return hap_rep diff --git a/pyhap/delegates.py b/pyhap/delegates.py index c340f112..549677fb 100644 --- a/pyhap/delegates.py +++ b/pyhap/delegates.py @@ -51,7 +51,12 @@ async def on_get(self, context: CharReadContext) -> Any: 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. + 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") diff --git a/pyhap/hap_handler.py b/pyhap/hap_handler.py index b9ad9dd5..d7481019 100644 --- a/pyhap/hap_handler.py +++ b/pyhap/hap_handler.py @@ -669,10 +669,27 @@ def handle_accessories(self) -> None: 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)) + if inspect.isawaitable(result): + # A delegate read is still running, answer once it is 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)) + return + assert self.response is not None # noqa: S101 + self.end_response(to_hap_json(result)) + + async def _accessories_body(self, result: Awaitable[dict[str, Any]]) -> bytes: + """Wait for the pending delegate 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.""" @@ -682,23 +699,50 @@ 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, ) - chars = response[HAP_REPR_CHARS] + assert self.response is not None # noqa: S101 + if inspect.isawaitable(result): + # A delegate read is still running, answer once it is done. The + # driver times out slow getters itself. + self.response.task = asyncio.ensure_future( + self._get_characteristics_body(self.response, result) + ) + return + self._fill_get_characteristics_response(self.response, result) + + 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.""" diff --git a/tests/test_characteristic.py b/tests/test_characteristic.py index 7f632d64..70137750 100644 --- a/tests/test_characteristic.py +++ b/tests/test_characteristic.py @@ -607,6 +607,29 @@ def test_delegate_assignment() -> None: assert char.delegate is None +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) diff --git a/tests/test_delegate_dispatch.py b/tests/test_delegate_dispatch.py index 30c786d0..c31874d3 100644 --- a/tests/test_delegate_dispatch.py +++ b/tests/test_delegate_dispatch.py @@ -1,15 +1,16 @@ -"""Tests for the delegate write dispatch of the driver.""" +"""Tests for the delegate dispatch of the driver.""" import asyncio from collections.abc import Mapping import inspect +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 +from pyhap.accessory import STANDALONE_AID, Accessory, Bridge from pyhap.accessory_driver import AccessoryDriver from pyhap.characteristic import ( HAP_FORMAT_INT, @@ -23,9 +24,11 @@ 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, @@ -35,6 +38,7 @@ 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) @@ -131,6 +135,58 @@ def _status_of( 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.""" @@ -150,6 +206,25 @@ async def on_set(self, value: Any, context: CharWriteContext) -> Any: 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.""" @@ -726,3 +801,257 @@ def _record(*_: Any) -> None: assert context.connection.client_addr is None assert context.deadline == float("inf") notify.assert_called_once_with(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_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 == float("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_hap_handler.py b/tests/test_hap_handler.py index 02e8161f..bd9aea14 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") @@ -1329,3 +1331,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 From a79d7766f2748633ba05bf9904555990bfa8a20c Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 16 Nov 2026 17:43:19 +0100 Subject: [PATCH 12/14] Deprecate the legacy setter and getter callbacks Assigning setter_callback/getter_callback on a characteristic, setter_callback on a service or an accessory, or passing them to configure_char, warns DeprecationWarning that names the assigning line; the callbacks keep working byte for byte. pyhap's own camera code no longer trips it: the last two legacy getter wirings (StreamingStatus, StatusActive) moved to _CameraDelegate read handlers, so the camera is fully delegate-based. The repo's own pytest config silences the expected warnings of its legacy-semantics tests; dedicated tests assert the warning itself. Also fills the CHANGELOG's Unreleased section with the callback interface stack: delegates, contexts, HapStatusError, async getters, lifecycle hooks, connection handles, camera internals, the deprecation and the sender_client_addr removal. --- CHANGELOG.md | 64 +++++++++++++++++++++++++++------ docs/source/advanced/async.rst | 10 ++++++ docs/source/api/delegates.rst | 5 +-- docs/source/intro/tutorial.rst | 4 ++- pyhap/accessory.py | 26 +++++++++++++- pyhap/camera.py | 51 +++++++++++++++++++++----- pyhap/characteristic.py | 52 +++++++++++++++++++-------- pyhap/service.py | 18 ++++++++-- pyproject.toml | 4 +++ tests/test_accessory.py | 23 ++++++++++++ tests/test_admin_only.py | 5 +-- tests/test_camera.py | 22 ++++++++++++ tests/test_characteristic.py | 25 +++++++++++++ tests/test_delegate_dispatch.py | 5 +-- tests/test_hksv_recording.py | 29 +++++++++++---- tests/test_service.py | 25 +++++++++++++ 16 files changed, 316 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0d3e09d..4c6aab78 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,30 @@ 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 gates + the grouped writes of its service: it may refuse them by raising + `HapStatusError`, which restores the previous values and notifies nobody. +- `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 a + delegate's `on_get` under the request deadline, 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. ### Changed @@ -85,6 +98,35 @@ 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. +- 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. +- A failing getter answers its own status per characteristic instead of + failing the whole `/accessories` response. + +### 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, byte for byte; 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 + +- 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/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index 27e2e3d5..34d77dcc 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -123,6 +123,16 @@ 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, byte for +byte, 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 diff --git a/docs/source/api/delegates.rst b/docs/source/api/delegates.rst index 47989f76..ff643c1a 100644 --- a/docs/source/api/delegates.rst +++ b/docs/source/api/delegates.rst @@ -73,8 +73,9 @@ sessions belong to the connection that set them up, by :class:`~pyhap.connection.HAPConnectionHandle`. The legacy :attr:`~pyhap.characteristic.Characteristic.setter_callback` / :attr:`~pyhap.characteristic.Characteristic.getter_callback` attributes -keep working unchanged for code that uses them alone; their deprecation -is announced separately when it happens. +keep working unchanged for code that uses them alone; assigning one warns +``DeprecationWarning`` from this release on (see +:doc:`/advanced/async`). A request may mix both interfaces. A characteristic with a legacy callback keeps its legacy dispatch, byte for byte, unless its service diff --git a/docs/source/intro/tutorial.rst b/docs/source/intro/tutorial.rst index 10ef59f8..ffdfbb38 100644 --- a/docs/source/intro/tutorial.rst +++ b/docs/source/intro/tutorial.rst @@ -181,7 +181,9 @@ 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`. +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/pyhap/accessory.py b/pyhap/accessory.py index e23fd396..eb1706b7 100644 --- a/pyhap/accessory.py +++ b/pyhap/accessory.py @@ -5,6 +5,7 @@ import logging from typing import TYPE_CHECKING, Any from uuid import UUID +import warnings from . import SUPPORT_QR_CODE, util from .characteristic import Characteristic @@ -66,7 +67,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 +78,29 @@ 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 a ``{display_name: value}`` dict of every write of every + service after the per-characteristic setters. Deprecated: a + :class:`~pyhap.delegates.ServiceDelegate` gates the grouped writes of + its service instead, and can refuse them. + """ + 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 + @property def available(self) -> bool: """Accessory is available. diff --git a/pyhap/camera.py b/pyhap/camera.py index 9838663c..ad0e8b72 100644 --- a/pyhap/camera.py +++ b/pyhap/camera.py @@ -286,14 +286,16 @@ 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 written, and each has its handler - in ``handlers``. A handler runs as part of ``on_set`` and returns the - write response of a write-response characteristic; the driver restores + 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] @@ -306,9 +308,26 @@ def wire( 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: - # Reads answer the stored value, like the camera always has. - return context.characteristic.value + 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] @@ -811,9 +830,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", @@ -1024,7 +1043,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) @@ -1519,6 +1542,16 @@ def _wire( """ 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: diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index b5b805cc..6f0a68e4 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -9,6 +9,7 @@ import logging from typing import TYPE_CHECKING, Any, TypedDict from uuid import UUID +import warnings from .const import ( HAP_PERMISSION_READ, @@ -220,13 +221,13 @@ 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 + self._getter_callback: Callable[[], Any] | None = None # The legacy setter is called with the written value. 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 + self._setter_callback: Callable[..., Any] | None = None # The delegate of the reads, writes and subscriptions of this # characteristic, see ``CharacteristicDelegate``. Either a delegate # or the legacy callbacks, never both. @@ -284,18 +285,17 @@ def delegate(self) -> None: @property def getter_callback(self) -> Callable[[], Any] | None: - """The legacy getter, called with nothing on every read of the value.""" + """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. + """ return self._getter_callback @getter_callback.setter def getter_callback(self, callback: Callable[[], Any] | None) -> None: """Assign the legacy getter; ``None`` removes it.""" - if callback is not None and self._delegate is not None: - raise ValueError( - f"{self._display_name} has a delegate, remove it before" - " assigning a legacy callback" - ) - self._getter_callback = callback + self._assign_legacy_callback("getter_callback", callback, warn_stacklevel=3) @getter_callback.deleter def getter_callback(self) -> None: @@ -318,18 +318,40 @@ def setter_callback(self) -> Callable[..., Any] | None: @setter_callback.setter def setter_callback(self, callback: Callable[..., Any] | None) -> None: """Assign the legacy setter; ``None`` removes it.""" - if callback is not None and self._delegate is not None: - raise ValueError( - f"{self._display_name} has a delegate, remove it before" - " assigning a legacy callback" - ) - self._setter_callback = callback + self._assign_legacy_callback("setter_callback", callback, warn_stacklevel=3) @setter_callback.deleter def setter_callback(self) -> None: """Remove the legacy setter.""" self._setter_callback = None + def _assign_legacy_callback( + self, name: str, callback: Callable[..., Any] | None, *, warn_stacklevel: int + ) -> None: + """Store a legacy callback, announcing its deprecation. + + The delegate conflict is checked first. Both the property setters + above and :meth:`~pyhap.service.Service.configure_char` call this + with ``warn_stacklevel=3``, so the warning names the user code + that assigns the callback. + """ + if callback is not None and self._delegate is not None: + raise ValueError( + f"{self._display_name} has a delegate, remove it before" + " assigning a legacy callback" + ) + if callback is not None: + warnings.warn( + f"The legacy {name} is deprecated, use a CharacteristicDelegate" + " instead", + DeprecationWarning, + stacklevel=warn_stacklevel, + ) + if name == "getter_callback": + self._getter_callback = callback + else: + self._setter_callback = callback + @property def value(self) -> Any: """Return the value of the characteristic.""" diff --git a/pyhap/service.py b/pyhap/service.py index 6561fdd6..0b892075 100644 --- a/pyhap/service.py +++ b/pyhap/service.py @@ -3,6 +3,7 @@ from collections.abc import Callable from typing import TYPE_CHECKING, Any from uuid import UUID +import warnings from pyhap.const import ( HAP_REPR_CHARS, @@ -54,7 +55,7 @@ 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 + self._setter_callback: Callable[[Any], None] | None = None # The delegate of the grouped writes of this service, see # ``ServiceDelegate``. Either a delegate or the legacy setter, # never both. @@ -104,6 +105,13 @@ def setter_callback(self, callback: Callable[[Any], None] | None) -> None: f"{self.display_name} has a delegate, remove it before" " assigning a legacy setter_callback" ) + if callback is not None: + warnings.warn( + "The legacy setter_callback is deprecated, use a ServiceDelegate" + " instead", + DeprecationWarning, + stacklevel=2, + ) self._setter_callback = callback @setter_callback.deleter @@ -182,9 +190,13 @@ def configure_char( if value: char.set_value(value, should_notify=False) if setter_callback: - char.setter_callback = setter_callback + char._assign_legacy_callback( + "setter_callback", setter_callback, warn_stacklevel=3 + ) if getter_callback: - char.getter_callback = getter_callback + char._assign_legacy_callback( + "getter_callback", getter_callback, warn_stacklevel=3 + ) if delegate is not None: char.delegate = delegate return char 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/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_admin_only.py b/tests/test_admin_only.py index 7e7f896c..e1cf4f77 100644 --- a/tests/test_admin_only.py +++ b/tests/test_admin_only.py @@ -297,7 +297,8 @@ def test_admin_only_null_write_reaches_no_setter( assert service is not None service_setter = MagicMock() service.setter_callback = service_setter - driver.accessory.setter_callback = MagicMock() + 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} @@ -309,7 +310,7 @@ def test_admin_only_null_write_reaches_no_setter( assert response == _response(char, REFUSED) char.setter.assert_not_called() service_setter.assert_not_called() - driver.accessory.setter_callback.assert_not_called() + acc_setter.assert_not_called() def _write_through_handler( diff --git a/tests/test_camera.py b/tests/test_camera.py index f7e18775..34bb0aa4 100644 --- a/tests/test_camera.py +++ b/tests/test_camera.py @@ -10,6 +10,7 @@ from typing import Any, cast from unittest.mock import AsyncMock, Mock, PropertyMock, patch from uuid import UUID +import warnings import pylibsrtp import pytest @@ -61,6 +62,27 @@ } +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): + assert char.getter_callback is None + 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") diff --git a/tests/test_characteristic.py b/tests/test_characteristic.py index 70137750..9ce9fc23 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 @@ -676,3 +677,27 @@ def test_removing_one_side_allows_the_other() -> 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 + del char.getter_callback diff --git a/tests/test_delegate_dispatch.py b/tests/test_delegate_dispatch.py index c31874d3..1b6f1175 100644 --- a/tests/test_delegate_dispatch.py +++ b/tests/test_delegate_dispatch.py @@ -572,12 +572,13 @@ async def test_gate_veto_only_its_service(driver: AccessoryDriver) -> None: 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_callback = MagicMock() + acc_setter = MagicMock() + acc.setter_callback = acc_setter char.delegate = _CharDelegate() await _write_chars(driver, acc, [(char, 7)]) - acc.setter_callback.assert_called_once_with({service: {char: 7}}) + acc_setter.assert_called_once_with({service: {char: 7}}) async def test_on_set_is_admin(driver: AccessoryDriver) -> None: diff --git a/tests/test_hksv_recording.py b/tests/test_hksv_recording.py index aa80f4d2..8a58f475 100644 --- a/tests/test_hksv_recording.py +++ b/tests/test_hksv_recording.py @@ -26,7 +26,7 @@ HAP_REPR_VALUE, RESPONSE_TIMEOUT, ) -from pyhap.context import CharWriteContext +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 @@ -464,17 +464,34 @@ async def test_camera_off_in_home_app_marks_sensor_inactive( 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=float("inf"), + characteristic=status_active, + ) + assert status_active.delegate is not None + assert await status_active.delegate.on_get(context) is False async def test_sensor_event_after_restored_camera_off(recording_camera: Any) -> None: diff --git a/tests/test_service.py b/tests/test_service.py index d4e28d73..9a537e99 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 @@ -315,6 +316,30 @@ def test_configure_char_with_both_conflicts() -> None: ) +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()) From bca09e1a62ccc2d0ab2c7565e8cb72f4fcc60784 Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Mon, 16 Nov 2026 22:14:27 +0100 Subject: [PATCH 13/14] Key the driver's per-connection state by the connection handle The driver keeps everything per controller by its connection now, not by its address: event subscriptions (topics), prepared timed writes, write responses and the server's connections are keyed by HAPConnectionHandle. The address of a connection is unique only while it lives, so keying by it needed guards at every boundary - a write response that arrived after its connection closed had to be dropped, or a later connection reusing the address could read it, and closing a connection had to check it still owned its address key. Keyed by the handle, nothing of a closed connection reaches a later one at all. The guards are gone with the address keys: _ConnectionWrites and pending_connection_writes are deleted, and a write response is kept only of a still-open connection (AccessoryDriver._is_open), so a late answer is dropped at the store instead of tracked and marked dead. The deferred write-response cleanup in connection_lost and the identity check in HAPServerProtocol.close() are gone too. A direct call without a connection - driver.set_characteristics, get_characteristics, prepare - acts as a virtual connection of its client address (AccessoryDriver._connection_of), so its prepared timed writes, stored write responses and read-backs pair up across calls, like a controller's requests pair up over its one connection. A handler without its protocol's connection does the same. The notify chain carries the connection, not the address: the writer is skipped by its handle, so a controller that reuses another connection's address is not skipped another's events nor sent its own. derive_session_key takes the connection instead of its address; _local_address and the camera's stream address lookup follow. --- CHANGELOG.md | 18 ++ docs/source/advanced/async.rst | 22 ++ docs/source/api/connection.rst | 11 +- pyhap/accessory.py | 13 +- pyhap/accessory_driver.py | 380 ++++++++++++++++---------------- pyhap/camera.py | 11 +- pyhap/camera_multi_tier.py | 2 +- pyhap/camera_stream.py | 10 +- pyhap/characteristic.py | 37 ++-- pyhap/connection.py | 16 +- pyhap/hap_handler.py | 11 +- pyhap/hap_protocol.py | 19 +- pyhap/hap_server.py | 15 +- tests/media_hap.py | 3 +- tests/test_accessory_driver.py | 172 ++++++++++----- tests/test_admin_only.py | 4 +- tests/test_camera_webrtc_hap.py | 5 +- tests/test_delegate_dispatch.py | 24 +- tests/test_hap_protocol.py | 56 +++-- tests/test_hap_server.py | 52 +++-- tests/test_hksv_recording.py | 15 +- tests/test_timed_write.py | 2 +- 22 files changed, 524 insertions(+), 374 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c6aab78..9e1d66a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,6 +103,15 @@ Sections author-facing camera methods keep their signatures. - A failing getter answers its own status per characteristic instead of failing the whole `/accessories` response. +- 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 @@ -123,6 +132,15 @@ Sections ### Breaking Changes +- 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 diff --git a/docs/source/advanced/async.rst b/docs/source/advanced/async.rst index 34d77dcc..8c9d22af 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -276,6 +276,28 @@ poll a battery-powered sensor between ``on_subscribe`` and async def on_unsubscribe(self, context): self.task.cancel() +Connections, not addresses +========================== + +Everything the driver keeps per controller is keyed by the connection, +not by its address: event subscriptions, prepared timed writes, write +responses and the server's connections, all by +:class:`~pyhap.connection.HAPConnectionHandle`. The address of a +connection is unique only while it lives, so keying by it needed guards +at every boundary - a response that arrived after its connection closed +had to be dropped, or a later connection reusing the address could have +read it. Keyed by the handle, nothing of a closed connection reaches a +later one at all: it cannot read its write responses or control its +camera sessions, and an answer that arrives only after its connection +closed is dropped instead of kept, because the store keeps a response +only of a connection it may still answer. + +A direct call without a connection - ``driver.set_characteristics`` and +friends - acts as a virtual connection of its client address, so its +prepared timed writes, its stored write responses and its read-backs +pair up across calls, like the requests of a controller pair up over its +one connection. + Provided utilities ================== diff --git a/docs/source/api/connection.rst b/docs/source/api/connection.rst index 7761e5fc..983c031b 100644 --- a/docs/source/api/connection.rst +++ b/docs/source/api/connection.rst @@ -18,5 +18,12 @@ The ``(address, port)`` of a connection is unique only while it lives - a later connection may reuse the address of a closed one. A handle compares equal only for the same connection, so anything a callback keeps per connection, a write response, a camera session, cannot leak to a -connection that reused the address. See the class docstring for the -phased migration of the driver's per-client state to the handle. +connection that reused the address. + +The driver keys its per-connection state by the handle too: event +subscriptions, prepared writes, write responses and the server's +connections. 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 (``driver.set_characteristics`` +and friends) acts as a virtual connection of its client address, so its +writes, prepared timed writes and read-backs pair up across calls. diff --git a/pyhap/accessory.py b/pyhap/accessory.py index eb1706b7..443db944 100644 --- a/pyhap/accessory.py +++ b/pyhap/accessory.py @@ -9,6 +9,7 @@ from . import SUPPORT_QR_CODE, util from .characteristic import Characteristic +from .connection import HAPConnectionHandle from .const import ( CATEGORY_BRIDGE, CATEGORY_OTHER, @@ -413,15 +414,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 @@ -431,7 +434,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): diff --git a/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index ea9cf338..333764bd 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -127,19 +127,19 @@ def _stored_value(char: Characteristic, value: HAPValue) -> HAPValue: def _wrap_char_setter( - char: Any, value: Any, client_addr: Any, notify: bool = True + char: Any, value: Any, connection: HAPConnectionHandle, 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 + value, connection, notify=notify, defer_notify=True ) except HapStatusError as e: # The setter answers the controller with its own HAP status. logger.debug( "%s: Characteristic %s answered status %s for value %s", - client_addr, + connection.client_addr, char.display_name, e.status, value, @@ -148,7 +148,7 @@ def _wrap_char_setter( except Exception: logger.exception( "%s: Error while setting characteristic %s to %s", - client_addr, + connection.client_addr, char.display_name, value, ) @@ -239,21 +239,6 @@ class _PendingWrite(NamedTuple): notify: bool # Whether subscribers learn the value once the setter is done. -class _ConnectionWrites: - """The pending writes of one controller connection. - - ``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. - """ - - __slots__ = ("alive",) - - def __init__(self) -> None: - self.alive = True - - class _DelegateRead(NamedTuple): """A delegate-backed read of one characteristic. @@ -544,7 +529,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() @@ -571,15 +558,14 @@ 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 @@ -799,14 +785,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 @@ -909,9 +896,10 @@ def connection_lost( :param client: A client (address, port) tuple that should be unsubscribed. :type client: tuple - :param connection: The identity of the closed connection, when the - caller knows it. It reaches the ``on_unsubscribe`` calls of the - subscribed characteristics' delegates. + :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, @@ -919,30 +907,23 @@ def connection_lost( 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) accessory = self.accessory for topic in client_topics: - self.async_subscribe_client_topic(client, topic, subscribe=False) + 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(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) + self.prepared_writes.pop(connection, None) + self._write_responses.pop(connection, None) if accessory is None: return try: @@ -958,7 +939,7 @@ def _dispatch_close_unsubscribe( accessory: Accessory, client_addr: Any, client_uuid: UUID | None, - connection: HAPConnectionHandle | 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(".")) @@ -971,13 +952,14 @@ def _dispatch_close_unsubscribe( 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. The publishing occurs only if the current client is subscribed to the topic for - the aid and iid contained in the data. + the aid and iid contained in the data. The connection ``connection`` is not + sent its own write back. :param data: The data to publish. It must at least contain the keys "aid" and "iid". @@ -988,18 +970,18 @@ def publish( 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. @@ -1012,33 +994,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. @@ -1309,7 +1291,7 @@ def get_accessories(self, include_value: bool = True) -> dict[str, Any]: self.add_job( self._read_delegate_values, reads, - self._request_context(None, None, None, None), + self._request_context(None, None, self._connection_of(None), None), _ignore_read_answer, ) logger.debug("Get accessories response: %s", hap_rep) @@ -1331,6 +1313,7 @@ def _get_accessories_for_controller( characteristic without a value, like a failing getter does. """ assert self.accessory is not None # noqa: S101 + connection = connection or self._connection_of(client_addr) hap_rep = self.accessory.to_HAP() if not isinstance(hap_rep, list): hap_rep = [ @@ -1419,12 +1402,13 @@ def get_characteristics( setters. A controller's read goes through ``_get_characteristics_for_controller`` instead and awaits them. """ - chars, reads = self._collect_characteristic_reads(char_ids, client_addr) + connection = self._connection_of(client_addr) + chars, reads = self._collect_characteristic_reads(char_ids, connection) if reads: self.add_job( self._read_delegate_values, reads, - self._request_context(client_addr, None, None, None), + self._request_context(client_addr, None, connection, None), _ignore_read_answer, ) logger.debug("Get chars response: %s", chars) @@ -1449,7 +1433,8 @@ def _get_characteristics_for_controller( legacy parts in the same pass and its delegate parts once they are done. """ - chars, reads = self._collect_characteristic_reads(char_ids, client_addr) + connection = connection or self._connection_of(client_addr) + chars, reads = self._collect_characteristic_reads(char_ids, connection) if reads: return self._read_characteristics_response( chars, @@ -1469,7 +1454,7 @@ async def _read_characteristics_response( return {HAP_REPR_CHARS: chars} def _collect_characteristic_reads( - self, char_ids: Any, client_addr: tuple[str, int] | None + self, char_ids: Any, connection: HAPConnectionHandle ) -> tuple[list[dict[str, Any]], list[_DelegateRead]]: """Answer a read per requested characteristic, collecting delegate reads. @@ -1479,9 +1464,7 @@ def _collect_characteristic_reads( through ``on_get``, a direct call runs it as a background job. """ assert self.accessory is not None # noqa: S101 - write_responses = ( - self._write_responses.get(client_addr, {}) if client_addr else {} - ) + write_responses = self._write_responses.get(connection, {}) chars = [] reads: list[_DelegateRead] = [] for aid_iid in char_ids: @@ -1559,24 +1542,24 @@ def _collect_characteristic_reads( 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. @@ -1584,10 +1567,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 @@ -1644,13 +1625,15 @@ def set_characteristics( :param connection: The connection the write came over, see :class:`~pyhap.connection.HAPConnectionHandle`. ``None`` for a - call without one. + call without one: it acts as the virtual connection of + ``client_addr``, see :meth:`_connection_of`. """ + connection = connection or self._connection_of(client_addr) results, pending, work = self._apply_characteristic_writes( chars_query, client_addr, client_uuid, connection ) for write in pending: - self.add_job(self._finish_pending_write(write, client_addr)) + self.add_job(self._finish_pending_write(write, connection)) if work: self.add_job( self._dispatch_delegates( @@ -1661,7 +1644,7 @@ def set_characteristics( return _set_characteristics_response(results) async def _finish_pending_write( - self, write: _PendingWrite, client_addr: tuple[str, int] + self, write: _PendingWrite, connection: HAPConnectionHandle ) -> None: """Run a coroutine setter of a direct call, then tell subscribers.""" try: @@ -1669,12 +1652,12 @@ async def _finish_pending_write( except Exception: logger.exception( "%s: Error while setting characteristic %s", - client_addr, + connection.client_addr, write.char.display_name, ) return write.char.client_update_finished( - write.previous_value, client_addr, notify=write.notify + write.previous_value, connection, notify=write.notify ) def _set_characteristics_for_controller( @@ -1694,26 +1677,23 @@ def _set_characteristics_for_controller( 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. + closed does not get it kept: the store drops it, see + :meth:`_store_write_response`. """ + connection = connection or self._connection_of(client_addr) results, pending, work = self._apply_characteristic_writes( chars_query, client_addr, client_uuid, connection ) if work: - writes = _ConnectionWrites() - self._pending_connection_writes.setdefault(client_addr, set()).add(writes) return self._set_characteristics_with_delegates( results, pending, work, self._request_context(client_addr, client_uuid, connection, timeout), - writes, ) if pending: - writes = _ConnectionWrites() - self._pending_connection_writes.setdefault(client_addr, set()).add(writes) return self._finish_set_characteristics( - results, pending, client_addr, timeout, writes + results, pending, connection, timeout ) return _set_characteristics_response(results) @@ -1722,7 +1702,7 @@ def _apply_characteristic_writes( chars_query: dict[str, Any], client_addr: tuple[str, int], client_uuid: UUID | None, - connection: HAPConnectionHandle | None, + connection: HAPConnectionHandle, ) -> tuple[ dict[int, dict[int, dict[str, Any]]], list[_PendingWrite], _DelegateWork ]: @@ -1746,7 +1726,7 @@ def _run_characteristic_writes( chars_query: dict[str, Any], client_addr: tuple[str, int], client_uuid: UUID | None, - connection: HAPConnectionHandle | None, + connection: HAPConnectionHandle, pending: list[_PendingWrite], delegate_work: _DelegateWork, ) -> tuple[dict[int, dict[int, dict[str, Any]]], list[_PendingWrite]]: @@ -1754,7 +1734,7 @@ def _run_characteristic_writes( 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. @@ -1858,7 +1838,7 @@ def _run_characteristic_writes( # 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) + self._write_responses.get(connection, {}).pop(char, None) private_write = ( (write_response or char.read_back_response) and value is not None @@ -1894,7 +1874,7 @@ def _run_characteristic_writes( if value is not None: set_result, set_result_value = _wrap_char_setter( - char, value, client_addr, notify=not private_write + char, value, connection, 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 @@ -1921,7 +1901,7 @@ def _run_characteristic_writes( ) elif set_result_value is not None: self._keep_response( - result, char, set_result_value, write_response, client_addr + result, char, set_result_value, write_response, connection ) results[aid][iid] = result @@ -1954,40 +1934,23 @@ def _run_characteristic_writes( return results, pending - def _discard_connection_writes( - self, client_addr: tuple[str, int], writes: _ConnectionWrites - ) -> None: - """Drop a finished batch from the pending writes of the connection.""" - 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] - async def _finish_set_characteristics( self, results: dict[int, dict[int, dict[str, Any]]], pending: list[_PendingWrite], - client_addr: tuple[str, int], + connection: HAPConnectionHandle, timeout: float, - writes: _ConnectionWrites, ) -> dict[str, Any] | None: """Wait for the coroutine setters, then build the response.""" deadline = time.monotonic() + timeout - try: - return await self._wait_pending( - results, pending, client_addr, deadline, writes - ) - finally: - self._discard_connection_writes(client_addr, writes) + return await self._wait_pending(results, pending, connection, deadline) async def _wait_pending( self, results: dict[int, dict[int, dict[str, Any]]], pending: list[_PendingWrite], - client_addr: tuple[str, int], + connection: HAPConnectionHandle, deadline: float, - writes: _ConnectionWrites, ) -> dict[str, Any] | None: """Wait for the coroutine setters, then build the response.""" if not pending: @@ -2000,7 +1963,7 @@ async def _wait_pending( except asyncio.CancelledError: for task, write in tasks.items(): if task.done(): - self._finish_done_write(task, write, client_addr) + self._finish_done_write(task, write, connection) continue task.cancel() task.add_done_callback(_retrieve_late_result) @@ -2011,7 +1974,7 @@ async def _wait_pending( write = tasks[task] logger.warning( "%s: Timed out setting characteristic %s", - client_addr, + connection.client_addr, write.char.display_name, ) write.result[HAP_REPR_STATUS] = HAP_SERVER_STATUS.OPERATION_TIMED_OUT @@ -2023,7 +1986,7 @@ async def _wait_pending( # The setter answers the controller with its own HAP status. logger.debug( "%s: Characteristic %s answered status %s", - client_addr, + connection.client_addr, write.char.display_name, e.status, ) @@ -2032,7 +1995,7 @@ async def _wait_pending( except (Exception, asyncio.CancelledError): logger.exception( "%s: Error while setting characteristic %s", - client_addr, + connection.client_addr, write.char.display_name, ) write.result[HAP_REPR_STATUS] = ( @@ -2040,19 +2003,19 @@ async def _wait_pending( ) continue write.char.client_update_finished( - write.previous_value, client_addr, notify=write.notify + write.previous_value, connection, notify=write.notify ) - if outcome is not None and writes.alive: + if outcome is not None: # 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. + # dropped by the store, so it cannot wait for one that + # reuses the address: 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, + connection, ) return _set_characteristics_response(results) @@ -2062,43 +2025,65 @@ async def _set_characteristics_with_delegates( pending: list[_PendingWrite], work: _DelegateWork, context: Context, - writes: _ConnectionWrites, ) -> dict[str, Any] | None: """Gate and apply the delegate writes, then wait for the rest.""" - client_addr = context.client_addr - # A controller's write always has an address: it keys the write - # responses and the pending writes of its connection. - assert client_addr is not None # noqa: S101 - try: - await self._dispatch_delegates(work, context, writes) - return await self._wait_pending( - results, pending, client_addr, context.deadline, writes - ) - finally: - self._discard_connection_writes(client_addr, writes) + await self._dispatch_delegates(work, context) + return await self._wait_pending( + results, pending, context.connection, context.deadline + ) 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 + + def _is_open(self, connection: HAPConnectionHandle) -> bool: + """Whether ``connection`` is a connection the server may still answer. + + 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 + ) + def _request_context( self, client_addr: tuple[str, int] | None, client_uuid: UUID | None, - connection: HAPConnectionHandle | 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. A call without a - connection gets a handle that belongs to no connection; its - address is ``None`` when it has no controller at all, e.g. a - direct read. + ``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`. """ - if connection is None: - connection = HAPConnectionHandle(None, self._next_connection_generation()) deadline = float("inf") if timeout is None else time.monotonic() + timeout return Context( client_addr=client_addr, @@ -2254,7 +2239,6 @@ async def _dispatch_delegates( self, work: _DelegateWork, context: Context, - writes: _ConnectionWrites | None = None, ) -> None: """Gate the writes of services with a delegate, then apply the rest. @@ -2266,12 +2250,10 @@ async def _dispatch_delegates( concurrently, each under the context's deadline; one that fails or misses it restores the previous value and notifies nobody. """ - if writes is None: - writes = _ConnectionWrites() if work.gates: await self._run_gates(work, context) if work.writes: - await self._run_char_writes(work, context, writes) + await self._run_char_writes(work, context) async def _run_gates(self, work: _DelegateWork, context: Context) -> None: """Run the gates of the request's services, refusing what they refuse.""" @@ -2349,7 +2331,6 @@ async def _run_char_writes( self, work: _DelegateWork, context: Context, - writes: _ConnectionWrites, ) -> None: """Apply the writes the gates left standing, in request order.""" client_addr = context.client_addr @@ -2392,7 +2373,7 @@ async def _run_char_writes( except asyncio.CancelledError: for task, write in tasks.items(): if task.done(): - self._finish_task_write(task, write, context, writes) + self._finish_task_write(task, write, context) continue task.cancel() task.add_done_callback(_retrieve_late_result) @@ -2409,7 +2390,7 @@ async def _run_char_writes( 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, writes) + self._finish_task_write(task, tasks[task], context) async def _apply_legacy_in_stage( self, write: _DelegateWrite, context: Context @@ -2420,14 +2401,18 @@ async def _apply_legacy_in_stage( inline, a coroutine it returns is awaited, and subscribers are told once it is done. """ - client_addr = context.client_addr response = write.char.client_update_value( - write.value, client_addr, notify=not write.private_write, defer_notify=True + write.value, + context.connection, + notify=not write.private_write, + defer_notify=True, ) if inspect.iscoroutine(response): outcome = await response write.char.client_update_finished( - write.previous_value, client_addr, notify=not write.private_write + write.previous_value, + context.connection, + notify=not write.private_write, ) return outcome return response @@ -2437,7 +2422,6 @@ def _finish_task_write( task: asyncio.Future[Any], write: _DelegateWrite, context: Context, - writes: _ConnectionWrites, ) -> None: """Settle one applied write: status, response, subscribers.""" client_addr = context.client_addr @@ -2471,13 +2455,20 @@ def _finish_task_write( response = _settle_private_write( write.char, write.previous_value, write.value, response ) - if response is not None and writes.alive: + 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, client_addr + write.result, + write.char, + response, + write.write_response, + context.connection, ) if write.delegate is not None: write.char.client_update_finished( - write.previous_value, client_addr, notify=not write.private_write + write.previous_value, context.connection, notify=not write.private_write ) @staticmethod @@ -2552,7 +2543,7 @@ def _collect_delegate_write( @staticmethod def _finish_done_write( - task: asyncio.Future[Any], write: _PendingWrite, client_addr: tuple[str, int] + task: asyncio.Future[Any], write: _PendingWrite, connection: HAPConnectionHandle ) -> None: """Tell subscribers about a setter done before the write was cancelled.""" if task.cancelled(): @@ -2560,13 +2551,13 @@ def _finish_done_write( if (err := task.exception()) is not None: logger.error( "%s: Error while setting characteristic %s", - client_addr, + connection.client_addr, write.char.display_name, exc_info=err, ) return write.char.client_update_finished( - write.previous_value, client_addr, notify=write.notify + write.previous_value, connection, notify=write.notify ) def _keep_response( @@ -2575,32 +2566,32 @@ def _keep_response( 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. @@ -2609,12 +2600,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: @@ -2627,14 +2618,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. @@ -2648,7 +2643,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) @@ -2657,7 +2662,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. @@ -2668,7 +2673,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} @@ -2697,7 +2702,7 @@ def _notify( queries: list[CharacteristicWrite], client_addr: tuple[str, int], client_uuid: UUID | None, - connection: HAPConnectionHandle | None, + connection: HAPConnectionHandle, ) -> set[tuple[int, int]]: """Notify the driver that the client has subscribed or unsubscribed. @@ -2726,10 +2731,10 @@ def _notify( continue char_topic = get_topic(aid, iid) - was_subscribed = client_addr in self.topics.get(char_topic, ()) + 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 char.delegate is not None and ev != was_subscribed: self._dispatch_subscription( char.delegate, char, ev, client_addr, client_uuid, connection @@ -2743,7 +2748,7 @@ def _dispatch_subscription( subscribe: bool, client_addr: tuple[str, int] | None, client_uuid: UUID | None, - connection: HAPConnectionHandle | None, + connection: HAPConnectionHandle, ) -> None: """Run a delegate's ``on_subscribe`` or ``on_unsubscribe``, isolated. @@ -2755,8 +2760,7 @@ def _dispatch_subscription( context = CharReadContext( client_addr=client_addr, client_uuid=client_uuid, - connection=connection - or HAPConnectionHandle(client_addr, self._next_connection_generation()), + connection=connection, deadline=float("inf"), characteristic=characteristic, ) diff --git a/pyhap/camera.py b/pyhap/camera.py index ad0e8b72..ed177534 100644 --- a/pyhap/camera.py +++ b/pyhap/camera.py @@ -44,6 +44,7 @@ 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 @@ -945,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: @@ -1264,7 +1265,7 @@ def set_data_stream_transport(self, value: str, context: CharWriteContext) -> st accessory_salt = None if listener is not None: accessory_salt = listener.register_session_transport( - functools.partial(self.driver.derive_session_key, context.client_addr), + functools.partial(self.driver.derive_session_key, context.connection), request.controller_key_salt, ) if listener is None or accessory_salt is None: @@ -1470,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 diff --git a/pyhap/camera_multi_tier.py b/pyhap/camera_multi_tier.py index fb66bae4..badb8f17 100644 --- a/pyhap/camera_multi_tier.py +++ b/pyhap/camera_multi_tier.py @@ -400,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( - connection.client_addr, endpoint.is_ipv6 + connection, endpoint.is_ipv6 ) if accessory_address is None: logger.warning( diff --git a/pyhap/camera_stream.py b/pyhap/camera_stream.py index 63e8457d..52853136 100644 --- a/pyhap/camera_stream.py +++ b/pyhap/camera_stream.py @@ -467,10 +467,12 @@ def _end_sessions(self, reason: str) -> None: def client_disconnected(self, client_addr: tuple[str, int]) -> None: """End the sessions of a connection that closed. - The address still names the sessions here: the driver reports a - closed connection by address, and while a later connection may reuse - it, a live one has its own sessions under its own handle - ending by - address is the conservative guard of the address-keyed phase. + 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: diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index 6f0a68e4..aeae0ae3 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -11,6 +11,7 @@ from uuid import UUID import warnings +from .connection import HAPConnectionHandle from .const import ( HAP_PERMISSION_READ, HAP_REPR_DESC, @@ -526,7 +527,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, @@ -534,12 +535,14 @@ 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. ``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: @@ -551,7 +554,7 @@ def client_update_value( self._display_name, value, original_value, - sender_client_addr, + connection, ) previous_value = self._value self.value = value @@ -559,9 +562,7 @@ def client_update_value( if self.setter_callback: response = self.setter_callback(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_value(self, value: Any) -> Any: @@ -584,23 +585,27 @@ def _store_client_value(self, value: Any) -> Any: 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. Tells subscribers about the new value if it differs from - ``previous_value``, see :meth:`client_update_value`. + ``previous_value``, 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 notify(self, sender_client_addr: tuple[str, int] | None = None) -> None: + 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 """ @@ -609,7 +614,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. diff --git a/pyhap/connection.py b/pyhap/connection.py index fbc9dc0b..4cf1e848 100644 --- a/pyhap/connection.py +++ b/pyhap/connection.py @@ -17,15 +17,13 @@ class HAPConnectionHandle: session, cannot leak to a connection that reused the address of a closed one. - The driver's per-client state is keyed by the client address today, - with guards at the connection boundaries (e.g. a write response that - arrives after its connection closed is dropped). The refactor moves - it to the handle in two phases that do not change this class: - - 1. Handles appear in contexts, and camera session ownership uses - them; the address-keyed state keeps its guards. - 2. Event subscriptions, prepared writes, write responses and pending - writes are re-keyed by the handle, and the guards are removed. + 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") diff --git a/pyhap/hap_handler.py b/pyhap/hap_handler.py index d7481019..ee4d40b6 100644 --- a/pyhap/hap_handler.py +++ b/pyhap/hap_handler.py @@ -158,9 +158,10 @@ def __init__( self.state: State = self.accessory_handler.state self.enc_context: dict[str, Any] | None = None self.client_address = client_address - self.connection = connection or HAPConnectionHandle( - cast("tuple[str, int] | None", client_address), - self.accessory_handler._next_connection_generation(), + # 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 @@ -810,7 +811,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 2787cad1..a3a7d409 100644 --- a/pyhap/hap_protocol.py +++ b/pyhap/hap_protocol.py @@ -55,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 @@ -132,12 +132,13 @@ 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 # The stable identity of this connection, passed to the delegate - # calls made for its requests, see ``HAPConnectionHandle``. + # 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 ) @@ -176,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 @@ -337,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/tests/media_hap.py b/tests/media_hap.py index 05901638..2912e3a8 100644 --- a/tests/media_hap.py +++ b/tests/media_hap.py @@ -14,7 +14,6 @@ from pyhap.camera import Camera from pyhap.util import base64_to_bytes, to_base64_str -from .conftest import connection_of from .media_peer import KEY, KEYFRAME, TRAIL, Controller, Source, video_count from .webrtc_helpers import SFrameKey @@ -89,7 +88,7 @@ async def write(camera: Camera, name: str, value: Any) -> bytes: ] } pending = camera.driver._set_characteristics_for_controller( - query, CLIENT, 9.0, connection=connection_of(CLIENT) + query, CLIENT, 9.0, connection=camera.driver._connection_of(CLIENT) ) assert inspect.isawaitable(pending) result = await pending diff --git a/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index b79240e3..9bcfa26d 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 @@ -31,6 +31,7 @@ PROP_PERMISSIONS, Characteristic, ) +from pyhap.connection import HAPConnectionHandle from pyhap.const import ( HAP_PERMISSION_NOTIFY, HAP_PERMISSION_WRITE, @@ -313,7 +314,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 @@ -404,7 +405,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"]) @@ -525,7 +526,7 @@ 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: @@ -803,7 +804,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( @@ -819,11 +827,30 @@ async def _controller_write( }, WRITER, ASYNC_TIMEOUT, + connection=connection, ) assert inspect.isawaitable(result) return await result +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(value: int) -> int: await asyncio.sleep(0) return 1 @@ -1084,6 +1111,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: @@ -1093,7 +1121,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) @@ -1102,7 +1134,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) @@ -1114,11 +1146,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: @@ -1128,19 +1162,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 @@ -1150,6 +1188,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: @@ -1158,12 +1197,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 @@ -1505,14 +1545,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) @@ -1524,7 +1564,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: @@ -1562,12 +1605,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( @@ -1591,7 +1635,7 @@ def _record(*_: Any) -> 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( @@ -1622,14 +1666,14 @@ async def test_public_write_logs_a_failing_async_setter( @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") @@ -1664,7 +1708,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() @@ -1915,10 +1962,6 @@ async def test_write_response_dropped_on_disconnect(driver: AccessoryDriver) -> _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 @@ -2040,7 +2083,7 @@ def test_stale_write_response_dropped(driver: AccessoryDriver, second: Any) -> N def test_write_response_without_client_not_kept(driver: AccessoryDriver) -> None: - """A write response without a known connection is sent but not kept.""" + """A direct write without a client is sent and read back without one.""" acc, char, _ = _add_write_response_char(driver, False) request = { HAP_REPR_CHARS: [ @@ -2058,7 +2101,9 @@ def test_write_response_without_client_not_kept(driver: AccessoryDriver) -> None assert response is not None assert response[HAP_REPR_CHARS][0][HAP_REPR_VALUE] == 7 - assert driver._write_responses == {} + # 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"]) @@ -2757,7 +2802,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 @@ -2771,14 +2818,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 == {} @@ -3125,20 +3172,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: @@ -3146,6 +3198,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: @@ -3179,11 +3234,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 ) @@ -3192,7 +3248,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 @@ -3313,14 +3369,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: @@ -3338,10 +3395,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 e1cf4f77..b58f6e59 100644 --- a/tests/test_admin_only.py +++ b/tests/test_admin_only.py @@ -260,7 +260,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() diff --git a/tests/test_camera_webrtc_hap.py b/tests/test_camera_webrtc_hap.py index 4fcf0b21..9946d487 100644 --- a/tests/test_camera_webrtc_hap.py +++ b/tests/test_camera_webrtc_hap.py @@ -12,7 +12,6 @@ from pyhap.accessory_driver import AccessoryDriver from pyhap.camera import Camera from pyhap.util import base64_to_bytes, to_base64_str -from tests.conftest import connection_of WEBRTC = "CameraWebRTCStreamManagement" MULTI_TIER = "CameraMultiTierRTPStreamManagement" @@ -56,8 +55,10 @@ async def _write( aid, iid = _char_id(camera, name, service_name) char = {"aid": aid, "iid": iid, "value": value, "r": response} query = {"characteristics": [char]} + # 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=connection_of(CLIENT) + query, CLIENT, timeout, connection=driver._connection_of(CLIENT) ) assert inspect.isawaitable(result) body = await result diff --git a/tests/test_delegate_dispatch.py b/tests/test_delegate_dispatch.py index 1b6f1175..a07b7455 100644 --- a/tests/test_delegate_dispatch.py +++ b/tests/test_delegate_dispatch.py @@ -296,7 +296,7 @@ async def test_on_set_receives_value_and_context(driver: AccessoryDriver) -> Non assert context.is_admin is False assert context.deadline > 0 assert char.value == 7 - notify.assert_called_once_with(WRITER) + notify.assert_called_once_with(handle) # Every write succeeded without a value to answer: no response body. assert result is None @@ -494,7 +494,7 @@ async def on_set( assert result is None assert order == ["gate", "on_set"] assert char.value == 7 - notify.assert_called_once_with(WRITER) + notify.assert_called_once_with(driver._connection_of(WRITER)) async def test_gate_covers_legacy_chars_of_its_service(driver: AccessoryDriver) -> None: @@ -566,7 +566,7 @@ async def test_gate_veto_only_its_service(driver: AccessoryDriver) -> None: setter.assert_called_once_with(2) assert plain_char.value == 2 assert gated_char.value == 0 - notify.assert_called_once_with(WRITER) + notify.assert_called_once_with(driver._connection_of(WRITER)) async def test_accessory_setter_sees_delegate_writes(driver: AccessoryDriver) -> None: @@ -613,16 +613,20 @@ async def test_write_response_dropped_when_closed_before_on_set_done( ) release = asyncio.Event() char.delegate = _CharDelegate(answer=7, release=release) + handle = HAPConnectionHandle(WRITER, 1) write = asyncio.ensure_future( - _write_chars(driver, acc, [(char, 5)], write_response=True) + _write_chars(driver, acc, [(char, 5)], connection=handle, write_response=True) ) await asyncio.sleep(0) - driver.connection_lost(WRITER) + driver.connection_lost(WRITER, connection=handle) await asyncio.sleep(0) release.set() - assert await write is None + # 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 == {} @@ -653,7 +657,7 @@ async def test_on_subscribe_receives_a_full_context(driver: AccessoryDriver) -> assert context.client_uuid == client_uuid assert context.connection is handle assert context.deadline == float("inf") - assert driver.topics == {char_topic: {WRITER}} + assert driver.topics == {char_topic: {handle}} async def test_on_unsubscribe_receives_the_context(driver: AccessoryDriver) -> None: @@ -708,7 +712,7 @@ async def test_on_subscribe_failure_is_isolated( await _run_scheduled_jobs() assert result is None - assert driver.topics == {char_topic: {WRITER}} + assert driver.topics == {char_topic: {driver._connection_of(WRITER)}} assert "failed to run on_subscribe" in caplog.text @@ -799,9 +803,9 @@ def _record(*_: Any) -> None: ((value, context),) = delegate.calls assert value == 7 assert context.client_addr == WRITER - assert context.connection.client_addr is None + assert context.connection is driver._connection_of(WRITER) assert context.deadline == float("inf") - notify.assert_called_once_with(WRITER) + notify.assert_called_once_with(driver._connection_of(WRITER)) async def test_on_get_receives_a_full_context(driver: AccessoryDriver) -> None: diff --git a/tests/test_hap_protocol.py b/tests/test_hap_protocol.py index 22953be8..617ed1cd 100644 --- a/tests/test_hap_protocol.py +++ b/tests/test_hap_protocol.py @@ -13,6 +13,7 @@ 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 @@ -86,39 +87,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 @@ -461,7 +466,7 @@ 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") @@ -750,7 +755,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 +857,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 +978,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 @@ -1099,11 +1113,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 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_recording.py b/tests/test_hksv_recording.py index 8a58f475..850b00f4 100644 --- a/tests/test_hksv_recording.py +++ b/tests/test_hksv_recording.py @@ -323,14 +323,13 @@ def _hap_connection( async def _write_setup( - camera: Any, client: tuple[str, int], controller_key_salt: bytes + 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) - connection = camera.driver.http_server.connections.get(client) response = camera.driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ @@ -342,9 +341,9 @@ async def _write_setup( } ] }, - client, + connection.peername, RESPONSE_TIMEOUT, - connection=connection.connection_handle if connection else None, + connection=connection.connection_handle, ) assert inspect.isawaitable(response) result = await response @@ -365,8 +364,8 @@ async def test_setup_data_stream_transport_write_response_plumbing( 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 = await _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 @@ -386,8 +385,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 = await _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 ) diff --git a/tests/test_timed_write.py b/tests/test_timed_write.py index 929c919a..1694127e 100644 --- a/tests/test_timed_write.py +++ b/tests/test_timed_write.py @@ -96,7 +96,7 @@ def test_prepared_write_is_applied( assert driver.set_characteristics(_write(door.aid, door.iid, 7), CLIENT) is None 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( From 7dc933a5100834cdae3d17f5aaa63982c337e30f Mon Sep 17 00:00:00 2001 From: Ivan Kalchev Date: Fri, 20 Nov 2026 10:20:30 +0100 Subject: [PATCH 14/14] Run the legacy callbacks inside one delegate dispatch pipeline - delegate is never None: the default delegate wraps the legacy callbacks (a plain noop without them), so a single dispatch path serves both interfaces; assigning a legacy callback to a delegate-wired object raises ValueError, and so does reading the legacy attributes of one - the driver dispatches through Characteristic.dispatch_get / dispatch_set / subscription_hook and Service.dispatch_set, which build the leaf context via the new Context.of classmethods instead of calling delegate methods directly - per-request state bundled into _WriteRequest / _ReadRequest; the triplicated wait/cancel/timeout code collapsed into _await_calls + _outcome_of, and a delegate method raising at call time answers -70402 per characteristic instead of escaping the request - the mDNS advertisement moves to pyhap/mdns.py (plus its API page) - accessories/delegate_lightbulb.py demonstrates the delegate interface end to end; docs and CHANGELOG updated Checks: 1795 passed, 3 skipped; ruff clean; ty at the 2 pre-existing config warnings; docs build clean with -W. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 47 +- accessories/delegate_lightbulb.py | 114 ++ docs/source/advanced/async.rst | 62 +- docs/source/api/delegates.rst | 71 +- docs/source/api/mdns.rst | 12 + docs/source/intro/examples.rst | 7 + docs/source/intro/overview.rst | 26 +- pyhap/accessory.py | 39 +- pyhap/accessory_driver.py | 1794 ++++++++++++--------------- pyhap/camera_stream.py | 12 +- pyhap/characteristic.py | 319 +++-- pyhap/context.py | 56 + pyhap/delegates.py | 5 +- pyhap/hap_handler.py | 40 +- pyhap/mdns.py | 117 ++ pyhap/service.py | 165 ++- tests/conftest.py | 21 +- tests/test_accessory_driver.py | 322 +++-- tests/test_admin_only.py | 33 +- tests/test_camera.py | 5 +- tests/test_camera_operating_mode.py | 7 +- tests/test_characteristic.py | 35 +- tests/test_delegate_dispatch.py | 81 +- tests/test_hap_handler.py | 40 +- tests/test_hap_protocol.py | 34 +- tests/test_hksv_recording.py | 3 +- tests/test_hksv_state.py | 3 +- tests/test_service.py | 18 +- tests/test_timed_write.py | 19 +- 29 files changed, 2047 insertions(+), 1460 deletions(-) create mode 100644 accessories/delegate_lightbulb.py create mode 100644 docs/source/api/mdns.rst create mode 100644 pyhap/mdns.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e1d66a5..ed5e817b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,16 +66,21 @@ Sections 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 gates - the grouped writes of its service: it may refuse them by raising - `HapStatusError`, which restores the previous values and notifies nobody. + 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 a - delegate's `on_get` under the request deadline, so a getter may do IO. A - getter that fails or misses the deadline answers per characteristic +- 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 @@ -86,6 +91,8 @@ Sections 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 @@ -98,11 +105,21 @@ 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. -- A failing getter answers its own status per characteristic instead of - failing the whole `/accessories` response. - 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 @@ -118,7 +135,7 @@ Sections - 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, byte for byte; move new code to the delegates. + working, wrapped into the delegate calls; move new code to the delegates. ### Fixed @@ -132,6 +149,18 @@ Sections ### 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`, 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 8c9d22af..cfdd1056 100644 --- a/docs/source/advanced/async.rst +++ b/docs/source/advanced/async.rst @@ -123,8 +123,11 @@ 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, byte for -byte, but assigning one — a characteristic's +**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 @@ -170,18 +173,29 @@ answers only after the connection already closed. Delegate writes ================ -The new-style interface of the write path is the delegate, see -:ref:`api-delegates`. A write that touches a characteristic with a -delegate, or a service with one, leaves the legacy path above and runs -the delegate pipeline instead: +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. -2. The values are stored, but subscribers are not told yet. -3. The gate: the ``on_set`` of each written service's + 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 + >H: EVENT for the other subscribers of aid.iid H-->>C: EVENT aid.iid = value -A write served by a delegate (see :ref:`api-delegates`) runs the -delegate pipeline instead: the values are stored without notifying -anyone, the written services' gates run first and may refuse their -writes as a group, 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 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 two interfaces: a getter callback runs -inline and answers at once, while the ``on_get`` of a delegate-backed -characteristic is awaited — concurrently with the rest of the request, -under a deadline — 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 +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/pyhap/accessory.py b/pyhap/accessory.py index 443db944..dcd7e396 100644 --- a/pyhap/accessory.py +++ b/pyhap/accessory.py @@ -1,6 +1,7 @@ """Module for the Accessory classes.""" from collections.abc import Callable, Iterable +import inspect import itertools import logging from typing import TYPE_CHECKING, Any @@ -37,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. @@ -83,10 +96,11 @@ def __repr__(self) -> str: def setter_callback(self) -> Callable[[Any], None] | None: """The legacy grouped setter, called with the request's values by name. - Called with a ``{display_name: value}`` dict of every write of every - service after the per-characteristic setters. Deprecated: a - :class:`~pyhap.delegates.ServiceDelegate` gates the grouped writes of - its service instead, and can refuse them. + 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 @@ -102,6 +116,23 @@ def setter_callback(self, callback: Callable[[Any], None] | None) -> None: ) 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. diff --git a/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index 333764bd..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,17 +66,14 @@ """ import asyncio -import base64 from collections import defaultdict -from collections.abc import Awaitable, Callable, 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 @@ -57,7 +102,6 @@ HAP_PERMISSION_TIMED_WRITE, HAP_PERMISSION_WRITE, HAP_PERMISSION_WRITE_RESPONSE, - HAP_PROTOCOL_SHORT_VERSION, HAP_REPR_ACCS, HAP_REPR_AID, HAP_REPR_CHARS, @@ -70,17 +114,12 @@ HAP_REPR_WRITE_RESPONSE, STANDALONE_AID, ) -from pyhap.context import ( - CharReadContext, - CharWriteContext, - Context, - ServiceWriteContext, -) -from pyhap.delegates import CharacteristicDelegate +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 @@ -94,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 @@ -126,119 +161,6 @@ def _stored_value(char: Characteristic, value: HAPValue) -> HAPValue: return stored -def _wrap_char_setter( - char: Any, value: Any, connection: HAPConnectionHandle, 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, connection, notify=notify, defer_notify=True - ) - except HapStatusError as e: - # The setter answers the controller with its own HAP status. - logger.debug( - "%s: Characteristic %s answered status %s for value %s", - connection.client_addr, - char.display_name, - e.status, - value, - ) - return e.status, None - except Exception: - logger.exception( - "%s: Error while setting characteristic %s to %s", - connection.client_addr, - char.display_name, - value, - ) - return HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE, None - return HAP_SERVER_STATUS.SUCCESS, response - - -def _close_unsupported_coroutine(result: Any, name: str) -> None: - """Close a coroutine an accessory or service 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 - ) - - -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 HapStatusError as e: - # The callback answers the controller with its own HAP status, - # applied to every characteristic of the accessory in the request. - logger.debug( - "%s: The %s accessory answered status %s for %s", - client_addr, - acc.display_name, - e.status, - updates_by_service, - ) - return e.status - 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 - - -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 HapStatusError as e: - # The callback answers the controller with its own HAP status, - # applied to every characteristic of the service in the request. - logger.debug( - "%s: The %s service answered status %s for %s", - client_addr, - service.display_name, - e.status, - service_chars, - ) - return e.status - 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 - - -class _PendingWrite(NamedTuple): - """A characteristic write whose setter returned a coroutine.""" - - 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. - - class _DelegateRead(NamedTuple): """A delegate-backed read of one characteristic. @@ -248,7 +170,6 @@ class _DelegateRead(NamedTuple): rep: dict[str, Any] char: Characteristic - delegate: CharacteristicDelegate def _ignore_read_answer(read: _DelegateRead, value: Any, status: int | None) -> None: @@ -260,42 +181,57 @@ def _ignore_read_answer(read: _DelegateRead, value: Any, status: int | None) -> class _DelegateWrite(NamedTuple): - """A characteristic write the delegate stage applies. + """A characteristic write the delegates of a request apply. - ``delegate`` is the characteristic's delegate, or ``None`` for a - legacy callback characteristic of a gated service, which the stage - applies after the gate like the legacy path applies it. + ``value`` is the validated value ``on_set`` receives, already + stored: a write the pre-checks or ``on_set`` refuse is restored. """ char: Characteristic - value: Any # The validated value ``on_set`` receives, the raw one otherwise. + value: Any previous_value: Any result: dict[str, Any] # The result entry to complete. write_response: bool private_write: bool service: Service - delegate: CharacteristicDelegate | None -class _DelegateWork: - """The writes of a request that its delegate stage gates and applies. +class _ReadRequest(NamedTuple): + """One read request's collected delegate reads and its base context.""" + + reads: list[_DelegateRead] + context: Context + - A service with a delegate is gated as a whole: every value the - request writes to it goes to its gate first, and the writes of the - service - delegate or legacy callback - are applied only after the - gate accepted. +class _WriteRequest: + """One write request's collected delegate work. + + 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__ = ("gates", "is_admin", "writes") + __slots__ = ("context", "is_admin", "pre_checks", "writes") - def __init__(self, is_admin: bool) -> None: - self.gates: dict[Service, dict[Characteristic, Any]] = {} - self.writes: list[_DelegateWrite] = [] + 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 anything for the delegate stage.""" - return bool(self.gates or self.writes) + """Whether the request has any write for the delegates to apply.""" + return bool(self.pre_checks or self.writes) + + +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( @@ -347,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__( @@ -468,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 @@ -626,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() @@ -701,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 @@ -746,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): @@ -768,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 @@ -944,9 +871,9 @@ def _dispatch_close_unsubscribe( """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 and char.delegate is not None: + if char is not None: self._dispatch_subscription( - char.delegate, char, False, client_addr, client_uuid, connection + char, False, client_addr, client_uuid, connection ) def publish( @@ -955,15 +882,25 @@ def publish( 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 connection ``connection`` is not - sent its own write back. + 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: @@ -984,9 +921,12 @@ def async_send_event( 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(): @@ -1034,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") @@ -1076,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 @@ -1110,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. """ @@ -1225,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) @@ -1233,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: @@ -1254,33 +1229,32 @@ 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 of delegate-backed - characteristics and runs their reads as a job without a deadline, - like a direct write runs its setters; a controller's request - awaits them through their ``on_get`` instead. + 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 @@ -1290,8 +1264,12 @@ def get_accessories(self, include_value: bool = True) -> dict[str, Any]: if reads: self.add_job( self._read_delegate_values, - reads, - self._request_context(None, None, self._connection_of(None), None), + _ReadRequest( + reads, + self._build_request_context( + None, None, self._connection_of(None), None + ), + ), _ignore_read_answer, ) logger.debug("Get accessories response: %s", hap_rep) @@ -1304,38 +1282,34 @@ def _get_accessories_for_controller( *, client_uuid: UUID | None = None, connection: HAPConnectionHandle | None = None, - ) -> dict[str, Any] | Awaitable[dict[str, Any]]: - """Answer a controller's accessories request, awaiting delegate reads. + ) -> Awaitable[dict[str, Any]]: + """Answer a controller's accessories request, awaiting the reads. - Returns an awaitable of the response when a readable characteristic - is delegate-backed: its ``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. + 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. """ - assert self.accessory is not None # noqa: S101 connection = connection or self._connection_of(client_addr) - hap_rep = self.accessory.to_HAP() - if not isinstance(hap_rep, list): - hap_rep = [ - hap_rep, - ] + hap_rep = self._hap_reps() reads = self._collect_accessory_reads(hap_rep) - if reads: - return self._read_accessories_response( - hap_rep, + return self._read_accessories_response( + hap_rep, + _ReadRequest( reads, - self._request_context(client_addr, client_uuid, connection, timeout), - ) - return {HAP_REPR_ACCS: hap_rep} + self._build_request_context( + client_addr, client_uuid, connection, timeout + ), + ), + ) async def _read_accessories_response( self, hap_rep: list[dict[str, Any]], - reads: list[_DelegateRead], - context: Context, + request: _ReadRequest, ) -> dict[str, Any]: """Answer the delegate reads of an accessories request.""" - await self._read_delegate_values(reads, context, self._answer_accessory_read) + await self._read_delegate_values(request, self._answer_accessory_read) return {HAP_REPR_ACCS: hap_rep} def _collect_accessory_reads( @@ -1359,15 +1333,13 @@ def _collect_accessory_reads( for acc in accessories: for service in acc.services: for char in service.characteristics: - if char.delegate is None: - continue 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, char.delegate)) + reads.append(_DelegateRead(rep, char)) return reads def get_characteristics( @@ -1396,10 +1368,10 @@ def get_characteristics( :rtype: dict - A characteristic with a delegate answers its stored value here: - ``on_get`` is async, so a direct call answers at once and runs the + 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 controller's read goes through + 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. """ connection = self._connection_of(client_addr) @@ -1407,8 +1379,10 @@ def get_characteristics( if reads: self.add_job( self._read_delegate_values, - reads, - self._request_context(client_addr, None, connection, None), + _ReadRequest( + reads, + self._build_request_context(client_addr, None, connection, None), + ), _ignore_read_answer, ) logger.debug("Get chars response: %s", chars) @@ -1422,46 +1396,49 @@ def _get_characteristics_for_controller( *, client_uuid: UUID | None = None, connection: HAPConnectionHandle | None = None, - ) -> dict[str, Any] | Awaitable[dict[str, Any]]: - """Read characteristics for a controller, awaiting the delegate reads. - - Returns an awaitable of the response when a read characteristic is - delegate-backed: its ``on_get`` runs under the deadline and a read - not done by it answers ``-70408``. Cancelling the awaitable, e.g. - because the connection closed, cancels the reads. Reads of legacy - characteristics run inline as before; a mixed request answers its - legacy parts in the same pass and its delegate parts once they - are done. + ) -> 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) - if reads: - return self._read_characteristics_response( - chars, + return self._read_characteristics_response( + chars, + _ReadRequest( reads, - self._request_context(client_addr, client_uuid, connection, timeout), - ) - return {HAP_REPR_CHARS: chars} + self._build_request_context( + client_addr, client_uuid, connection, timeout + ), + ), + ) async def _read_characteristics_response( self, chars: list[dict[str, Any]], - reads: list[_DelegateRead], - context: Context, + request: _ReadRequest, ) -> dict[str, Any]: """Answer the delegate reads of a characteristics request.""" - await self._read_delegate_values(reads, context, self._answer_char_read) + 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 delegate reads. - - Legacy getters run inline, exactly as before. A characteristic with - a delegate answers its stored value optimistically and its read is - collected for the caller to run: a controller's request awaits it - through ``on_get``, a direct call runs it as a background job. + """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, {}) @@ -1477,22 +1454,21 @@ def _collect_characteristic_reads( 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 @@ -1508,23 +1484,12 @@ def _collect_characteristic_reads( # response back; it wins over any read callback. rep[HAP_REPR_VALUE] = write_responses[char] rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS - elif char.delegate is not None: - # Optimistic, the caller runs the read. - rep[HAP_REPR_VALUE] = char.value - rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS - reads.append(_DelegateRead(rep, char, char.delegate)) else: - rep[HAP_REPR_VALUE] = char.get_value() + # 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 - except HapStatusError as e: - # The getter answers the controller with its own HAP status. - logger.debug( - "%s: Characteristic %s answered status %s", - self.accessory.display_name, - (aid, iid), - e.status, - ) - rep[HAP_REPR_STATUS] = e.status + reads.append(_DelegateRead(rep, char)) except CharacteristicError: logger.error( "%s: Error getting value for characteristic %s.", @@ -1593,14 +1558,12 @@ def set_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: @@ -1629,37 +1592,13 @@ def set_characteristics( ``client_addr``, see :meth:`_connection_of`. """ connection = connection or self._connection_of(client_addr) - results, pending, work = self._apply_characteristic_writes( - chars_query, client_addr, client_uuid, connection + 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, connection)) - if work: - self.add_job( - self._dispatch_delegates( - work, - self._request_context(client_addr, client_uuid, connection, None), - ) - ) + if request: + self.add_job(self._dispatch_delegates(request)) return _set_characteristics_response(results) - async def _finish_pending_write( - self, write: _PendingWrite, connection: HAPConnectionHandle - ) -> 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", - connection.client_addr, - write.char.display_name, - ) - return - write.char.client_update_finished( - write.previous_value, connection, notify=write.notify - ) - def _set_characteristics_for_controller( self, chars_query: dict[str, Any], @@ -1668,34 +1607,25 @@ def _set_characteristics_for_controller( *, client_uuid: UUID | None = None, connection: HAPConnectionHandle | 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: the store drops it, see + ) -> 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, pending, work = self._apply_characteristic_writes( - chars_query, client_addr, client_uuid, connection + results, request = self._apply_characteristic_writes( + chars_query, client_addr, client_uuid, connection, timeout ) - if work: - return self._set_characteristics_with_delegates( - results, - pending, - work, - self._request_context(client_addr, client_uuid, connection, timeout), - ) - if pending: - return self._finish_set_characteristics( - results, pending, connection, timeout - ) - return _set_characteristics_response(results) + return self._apply_delegate_writes(results, request) def _apply_characteristic_writes( self, @@ -1703,23 +1633,22 @@ def _apply_characteristic_writes( client_addr: tuple[str, int], client_uuid: UUID | None, connection: HAPConnectionHandle, - ) -> tuple[ - dict[int, dict[int, dict[str, Any]]], list[_PendingWrite], _DelegateWork - ]: - """Run the setters of a write and collect the per-characteristic results.""" - pending: list[_PendingWrite] = [] - work = _DelegateWork(self.state.is_admin(client_uuid)) - try: - results, pending = self._run_characteristic_writes( - chars_query, client_addr, client_uuid, connection, pending, work - ) - except BaseException: - # A malformed later entry must not leave a setter coroutine - # un-awaited. - for write in pending: - write.coro.close() - raise - return results, pending, work + 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, @@ -1727,9 +1656,20 @@ def _run_characteristic_writes( client_addr: tuple[str, int], client_uuid: UUID | None, connection: HAPConnectionHandle, - pending: list[_PendingWrite], - delegate_work: _DelegateWork, - ) -> tuple[dict[int, dict[int, dict[str, Any]]], list[_PendingWrite]]: + 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 @@ -1743,294 +1683,172 @@ 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, 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 = delegate_work.is_admin 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) - - 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 - - # 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 - - 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 - - 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, - ) - - # 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] + self._store_write_query( + results, + request, + query, + not_notifiable, + timed_write, + connection, + client_addr, ) - previous_value = char.value - service = char.service - assert service is not None # noqa: S101 - - if char.delegate is not None or service.delegate is not None: - # The write goes to the delegate stage: gated by its - # service's delegate, applied by its own on_set, or both. - # A legacy callback char of a gated service is applied - # there too, after the gate, so the gate sees every value - # of the request and can refuse them all. - result = self._collect_delegate_write( - delegate_work, - client_addr, - char, - service, - value, - previous_value, - write_response, - private_write, - ) - results[aid][iid] = result - char_to_iid[char] = iid - updates_by_accessories_services[acc][service][char] = value - continue - set_result = HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST - set_result_value = None - - if value is not None: - set_result, set_result_value = _wrap_char_setter( - char, value, connection, 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, - # see _settle_private_write. - if private_write: - set_result_value = _settle_private_write( - char, previous_value, value, set_result_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, connection - ) + return results - results[aid][iid] = result - char_to_iid[char] = iid - updates_by_accessories_services[acc][service][char] = value + def _bridged_accessory(self, aid: int) -> Accessory | None: + """The bridged accessory ``aid`` addresses, None when there is none. - # 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] + 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 - # 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 _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) - # 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 + 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 - if not set_result: - continue + 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 - for char in chars: - aid_results[char_to_iid[char]][HAP_REPR_STATUS] = set_result + # 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 - return results, pending + results[aid][iid] = self._collect_delegate_write( + request, + client_addr, + char, + service, + value, + previous_value, + write_response, + private_write, + ) - async def _finish_set_characteristics( + def _write_permission_status( self, - results: dict[int, dict[int, dict[str, Any]]], - pending: list[_PendingWrite], - connection: HAPConnectionHandle, - timeout: float, - ) -> dict[str, Any] | None: - """Wait for the coroutine setters, then build the response.""" - deadline = time.monotonic() + timeout - return await self._wait_pending(results, pending, connection, deadline) + 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. - async def _wait_pending( - self, - results: dict[int, dict[int, dict[str, Any]]], - pending: list[_PendingWrite], - connection: HAPConnectionHandle, - deadline: float, - ) -> dict[str, Any] | None: - """Wait for the coroutine setters, then build the response.""" - if not pending: - return _set_characteristics_response(results) - tasks = {asyncio.ensure_future(write.coro): write for write in pending} - try: - done, not_done = await asyncio.wait( - tasks, timeout=self._remaining(deadline) - ) - except asyncio.CancelledError: - for task, write in tasks.items(): - if task.done(): - self._finish_done_write(task, write, connection) - continue - 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", - connection.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 HapStatusError as e: - # The setter answers the controller with its own HAP status. - logger.debug( - "%s: Characteristic %s answered status %s", - connection.client_addr, - write.char.display_name, - e.status, - ) - write.result[HAP_REPR_STATUS] = e.status - continue - except (Exception, asyncio.CancelledError): - logger.exception( - "%s: Error while setting characteristic %s", - connection.client_addr, - write.char.display_name, - ) - write.result[HAP_REPR_STATUS] = ( - HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE - ) - continue - write.char.client_update_finished( - write.previous_value, connection, notify=write.notify + 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, ) - if outcome is not None: - # A response of a connection that closed meanwhile is - # dropped by the store, so it cannot wait for one that - # reuses the address: the response of a request is - # answered once, to the writing connection. - self._keep_response( - write.result, - write.char, - outcome, - write.write_response, - connection, - ) - return _set_characteristics_response(results) + return None - async def _set_characteristics_with_delegates( + async def _apply_delegate_writes( self, results: dict[int, dict[int, dict[str, Any]]], - pending: list[_PendingWrite], - work: _DelegateWork, - context: Context, + request: _WriteRequest, ) -> dict[str, Any] | None: - """Gate and apply the delegate writes, then wait for the rest.""" - await self._dispatch_delegates(work, context) - return await self._wait_pending( - results, pending, context.connection, context.deadline - ) + """Apply the writes of a request through their delegates, build its response. + + 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) def _next_connection_generation(self) -> int: """The identity number of the next connection, see HAPConnectionHandle.""" @@ -2069,7 +1887,7 @@ def _is_open(self, connection: HAPConnectionHandle) -> bool: or connection in self.http_server.connections ) - def _request_context( + def _build_request_context( self, client_addr: tuple[str, int] | None, client_uuid: UUID | None, @@ -2084,7 +1902,7 @@ def _request_context( connection, a direct call the virtual handle of its address, see :meth:`_connection_of`. """ - deadline = float("inf") if timeout is None else time.monotonic() + timeout + deadline = math.inf if timeout is None else time.monotonic() + timeout return Context( client_addr=client_addr, client_uuid=client_uuid, @@ -2094,15 +1912,62 @@ def _request_context( @staticmethod def _remaining(deadline: float) -> float | None: - """Seconds left of the deadline, ``None`` without one.""" + """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 _await_calls( + self, + 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: + 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) + 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, - reads: list[_DelegateRead], - context: Context, + request: _ReadRequest, answer: Callable[[_DelegateRead, Any, int | None], None], ) -> None: """Run the delegate reads of a request concurrently, answering each. @@ -2113,42 +1978,14 @@ async def _read_delegate_values( 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 reads: - char_context = CharReadContext( - client_addr=context.client_addr, - client_uuid=context.client_uuid, - connection=context.connection, - deadline=context.deadline, - characteristic=read.char, - ) - try: - tasks[asyncio.ensure_future(read.delegate.on_get(char_context))] = read - except TypeError: - logger.exception( - "%s: on_get of %s is not a coroutine function", - context.client_addr, - read.char.display_name, - ) - self._finish_read( - read, - answer, - HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE, - ) + for read in request.reads: + tasks[asyncio.ensure_future(read.char.dispatch_get(context))] = read if not tasks: return - try: - done, not_done = await asyncio.wait( - tasks, timeout=self._remaining(context.deadline) - ) - except asyncio.CancelledError: - for task in tasks: - task.cancel() - task.add_done_callback(_retrieve_late_result) - raise + done, not_done = await self._await_calls(tasks, context.deadline) for task in not_done: - task.cancel() - task.add_done_callback(_retrieve_late_result) read = tasks[task] logger.warning( "%s: Timed out getting characteristic %s", @@ -2158,28 +1995,26 @@ async def _read_delegate_values( self._finish_read(read, answer, HAP_SERVER_STATUS.OPERATION_TIMED_OUT) for task in done: read = tasks[task] - try: - value = task.result() - except HapStatusError as e: - # 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, - e.status, - ) - self._finish_read(read, answer, e.status) - except Exception: - logger.exception( - "%s: Error getting value for characteristic %s", - context.client_addr, - read.char.display_name, - ) - self._finish_read( - read, answer, HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE - ) + 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, + ) + else: + logger.error( + "%s: Error getting value for characteristic %s", + context.client_addr, + read.char.display_name, + exc_info=outcome.error, + ) + self._finish_read(read, answer, outcome.status) else: - self._finish_read(read, answer, None, value) + self._finish_read(read, answer, None, outcome.value) @staticmethod def _finish_read( @@ -2235,152 +2070,117 @@ def _answer_accessory_read( else: read.rep.pop(HAP_REPR_VALUE, None) - async def _dispatch_delegates( - self, - work: _DelegateWork, - context: Context, - ) -> None: - """Gate the writes of services with a delegate, then apply the rest. - - The gates 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 - gate 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 work.gates: - await self._run_gates(work, context) - if work.writes: - await self._run_char_writes(work, context) - - async def _run_gates(self, work: _DelegateWork, context: Context) -> None: - """Run the gates of the request's services, refusing what they refuse.""" + 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 - tasks: dict[asyncio.Future[Any], Service] = {} - for service, values in work.gates.items(): - delegate = service.delegate - assert delegate is not None # noqa: S101 - gate_context = ServiceWriteContext( - client_addr=context.client_addr, - client_uuid=context.client_uuid, - connection=context.connection, - deadline=context.deadline, - service=service, - is_admin=work.is_admin, - ) - try: - tasks[asyncio.ensure_future(delegate.on_set(values, gate_context))] = ( - service - ) - except TypeError: - logger.exception( - "%s: on_set of the %s service is not a coroutine function", - client_addr, - service.display_name, - ) - self._veto_writes( - work, service, HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + # 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 - try: - done, not_done = await asyncio.wait( - tasks, timeout=self._remaining(context.deadline) - ) - except asyncio.CancelledError: - for task in tasks: - task.cancel() - task.add_done_callback(_retrieve_late_result) - raise + done, not_done = await self._await_calls(tasks, context.deadline) for task in not_done: - task.cancel() - task.add_done_callback(_retrieve_late_result) - service = tasks[task] + services = tasks[task] logger.warning( - "%s: Timed out gating the writes of the %s service", + "%s: Timed out checking the writes of %s", client_addr, - service.display_name, + ", ".join(service.display_name or "" for service in services), ) - self._veto_writes(work, service, HAP_SERVER_STATUS.OPERATION_TIMED_OUT) + self._veto_writes(request, services, HAP_SERVER_STATUS.OPERATION_TIMED_OUT) for task in done: - service = tasks[task] - try: - task.result() - except HapStatusError as e: - # The gate answers the controller with its own HAP status. - logger.debug( - "%s: The %s service refused its writes with status %s", - client_addr, - service.display_name, - e.status, - ) - self._veto_writes(work, service, e.status) - except Exception: - logger.exception( - "%s: Error gating the writes of the %s service", - client_addr, - service.display_name, - ) - self._veto_writes( - work, service, HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE - ) + 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, - work: _DelegateWork, - context: Context, - ) -> None: - """Apply the writes the gates left standing, in request order.""" + 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 work.writes: - if write.value is None: - # A null write applies nothing and runs no callback, like - # in the legacy path. - continue - if write.delegate is None: - coro: Any = self._apply_legacy_in_stage(write, context) - else: - char_context = CharWriteContext( - client_addr=context.client_addr, - client_uuid=context.client_uuid, - connection=context.connection, - deadline=context.deadline, - characteristic=write.char, - is_admin=work.is_admin, - ) - coro = write.delegate.on_set(write.value, char_context) - try: - tasks[asyncio.ensure_future(coro)] = write - except TypeError: - logger.exception( - "%s: on_set of %s is not a coroutine function", - client_addr, - write.char.display_name, - ) - write.result[HAP_REPR_STATUS] = ( - HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE + for write in request.writes: + tasks[ + asyncio.ensure_future( + write.char.dispatch_set( + write.value, context, is_admin=request.is_admin + ) ) - self._restore_write_value(write) + ] = write if not tasks: return - try: - done, not_done = await asyncio.wait( - tasks, timeout=self._remaining(context.deadline) - ) - except asyncio.CancelledError: - for task, write in tasks.items(): - if task.done(): - self._finish_task_write(task, write, context) - continue - task.cancel() - task.add_done_callback(_retrieve_late_result) - raise + 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: - task.cancel() - task.add_done_callback(_retrieve_late_result) write = tasks[task] logger.warning( "%s: Timed out setting characteristic %s", @@ -2392,65 +2192,45 @@ async def _run_char_writes( for task in done: self._finish_task_write(task, tasks[task], context) - async def _apply_legacy_in_stage( - self, write: _DelegateWrite, context: Context - ) -> Any: - """Apply a legacy callback write of a gated service, after its gate. - - Mirrors the legacy path: the value is stored and the callback run - inline, a coroutine it returns is awaited, and subscribers are - told once it is done. - """ - response = write.char.client_update_value( - write.value, - context.connection, - notify=not write.private_write, - defer_notify=True, - ) - if inspect.iscoroutine(response): - outcome = await response - write.char.client_update_finished( - write.previous_value, - context.connection, - notify=not write.private_write, - ) - return outcome - return response - def _finish_task_write( self, task: asyncio.Future[Any], write: _DelegateWrite, context: Context, ) -> None: - """Settle one applied write: status, response, subscribers.""" + """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 - try: - outcome = task.result() - except HapStatusError as e: - # The delegate answers the controller with its own HAP status. - logger.debug( - "%s: Characteristic %s answered status %s", - client_addr, - write.char.display_name, - e.status, - ) - write.result[HAP_REPR_STATUS] = e.status - self._restore_write_value(write) - return - except (Exception, asyncio.CancelledError): - logger.exception( - "%s: Error while setting characteristic %s", - client_addr, - write.char.display_name, - ) - write.result[HAP_REPR_STATUS] = ( - HAP_SERVER_STATUS.SERVICE_COMMUNICATION_FAILURE - ) + 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 + response = outcome.value if write.private_write: response = _settle_private_write( write.char, write.previous_value, write.value, response @@ -2466,31 +2246,35 @@ def _finish_task_write( write.write_response, context.connection, ) - if write.delegate is not None: - write.char.client_update_finished( - write.previous_value, context.connection, notify=not write.private_write - ) + write.char.client_update_finished( + write.previous_value, context.connection, notify=not write.private_write + ) @staticmethod def _restore_write_value(write: _DelegateWrite) -> None: - """Put back what a refused write of a delegate changed.""" - if write.delegate is not None and write.char.value != write.previous_value: + """Put back what a refused write changed.""" + if write.char.value != write.previous_value: write.char.value = write.previous_value - def _veto_writes(self, work: _DelegateWork, service: Service, status: int) -> None: - """Refuse every write of ``service``: restore, tell nobody, answer status.""" + 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 work.writes: - if write.service is not service: + 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) - work.writes = kept + request.writes = kept def _collect_delegate_write( self, - work: _DelegateWork, + request: _WriteRequest, client_addr: tuple[str, int], char: Characteristic, service: Service, @@ -2499,35 +2283,40 @@ def _collect_delegate_write( write_response: bool, private_write: bool, ) -> dict[str, Any]: - """Collect a write for the delegate stage, return its result entry. - - A service with a delegate is gated as a whole, so the value goes - to its gate whatever the characteristic itself uses. A char with - a delegate stores the value now and its ``on_set`` applies it - once the gates accepted; a legacy callback char of a gated - service is applied after them, like the value writes of the - legacy path. - """ - if service.delegate is not None: - work.gates.setdefault(service, {})[char] = value - delegate = char.delegate + """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 delegate is not None and value is not None: - try: - previous_value = char._store_client_value(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 - work.writes.append( + 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, @@ -2536,30 +2325,10 @@ def _collect_delegate_write( write_response, private_write, service, - delegate, ) ) return result - @staticmethod - def _finish_done_write( - task: asyncio.Future[Any], write: _PendingWrite, connection: HAPConnectionHandle - ) -> None: - """Tell subscribers about a setter done before the write was cancelled.""" - if task.cancelled(): - return - if (err := task.exception()) is not None: - logger.error( - "%s: Error while setting characteristic %s", - connection.client_addr, - write.char.display_name, - exc_info=err, - ) - return - write.char.client_update_finished( - write.previous_value, connection, notify=write.notify - ) - def _keep_response( self, result: dict[str, Any], @@ -2735,48 +2504,35 @@ def _notify( action = "Subscribed" if ev else "Unsubscribed" logger.debug("%s client %s to topic %s", action, client_addr, char_topic) self.async_subscribe_client_topic(connection, char_topic, ev) - if char is not None and char.delegate is not None and ev != was_subscribed: + if char is not None and ev != was_subscribed: self._dispatch_subscription( - char.delegate, char, ev, client_addr, client_uuid, connection + char, ev, client_addr, client_uuid, connection ) return not_notifiable def _dispatch_subscription( self, - delegate: CharacteristicDelegate, characteristic: Characteristic, subscribe: bool, client_addr: tuple[str, int] | None, client_uuid: UUID | None, connection: HAPConnectionHandle, ) -> None: - """Run a delegate's ``on_subscribe`` or ``on_unsubscribe``, isolated. + """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 = CharReadContext( - client_addr=client_addr, - client_uuid=client_uuid, - connection=connection, - deadline=float("inf"), - characteristic=characteristic, + 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, ) - if subscribe: - self.add_job( - self._run_isolated_hook, - delegate.on_subscribe, - (context,), - "on_subscribe", - client_addr, - ) - else: - self.add_job( - self._run_isolated_hook, - delegate.on_unsubscribe, - (context,), - "on_unsubscribe", - client_addr, - ) diff --git a/pyhap/camera_stream.py b/pyhap/camera_stream.py index 52853136..1f1c5aec 100644 --- a/pyhap/camera_stream.py +++ b/pyhap/camera_stream.py @@ -275,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. @@ -287,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) diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index aeae0ae3..2ff68928 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -4,7 +4,7 @@ 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 @@ -23,7 +23,8 @@ HAP_REPR_VALID_VALUES, HAP_REPR_VALUE, ) -from .delegates import CharacteristicDelegate +from .context import Context +from .delegates import CharacteristicDelegate, CharReadContext, CharWriteContext from .util import hap_type_to_uuid, uuid_to_hap_type if TYPE_CHECKING: @@ -149,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. @@ -171,8 +213,6 @@ class Characteristic: "_properties", "type_id", "_value", - "_getter_callback", - "_setter_callback", "_delegate", "service", "_uuid_str", @@ -222,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 - # The legacy setter is called with the written value. 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 # The delegate of the reads, writes and subscriptions of this - # characteristic, see ``CharacteristicDelegate``. Either a delegate - # or the legacy callbacks, never both. - self.delegate: CharacteristicDelegate | None = None + # 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) @@ -256,33 +293,45 @@ def display_name(self, value: str) -> None: self._clear_cache() @property - def delegate(self) -> CharacteristicDelegate | None: - """The characteristic's delegate, or ``None`` without one. + def delegate(self) -> CharacteristicDelegate: + """The characteristic's delegate, never ``None``. - A characteristic has either a delegate or the legacy callbacks, - never both: assigning a delegate to a characteristic that has one - raises ``ValueError``, and the reverse. A delegate takes over the - reads of the characteristic, see + 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`` removes it.""" - if delegate is not None and ( - self._setter_callback is not None or self._getter_callback is not 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 = delegate + self._delegate = ( + _LegacyCallbackDelegateWrapper(characteristic=self) + if delegate is None + else delegate + ) - @delegate.deleter - def delegate(self) -> None: - """Remove the delegate.""" - self._delegate = None + @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: @@ -291,17 +340,22 @@ def getter_callback(self) -> Callable[[], Any] | None: Deprecated: a delegate's :meth:`~pyhap.delegates.CharacteristicDelegate.on_get` answers the reads instead. """ - return self._getter_callback + 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.""" - self._assign_legacy_callback("getter_callback", callback, warn_stacklevel=3) + """Assign the legacy getter. ``None`` removes it. - @getter_callback.deleter - def getter_callback(self) -> None: - """Remove the legacy getter.""" - self._getter_callback = None + 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: @@ -314,44 +368,57 @@ def setter_callback(self) -> Callable[..., Any] | None: request comes through a delegate instead, see :class:`~pyhap.delegates.CharacteristicDelegate`. """ - return self._setter_callback + 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.""" - self._assign_legacy_callback("setter_callback", callback, warn_stacklevel=3) + """Assign the legacy setter; ``None`` removes it. - @setter_callback.deleter - def setter_callback(self) -> None: - """Remove the legacy setter.""" - self._setter_callback = None + 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 + self, + name: str, + callback: Callable[..., Any] | None, + *, + warn_stacklevel: int = 3, ) -> None: - """Store a legacy callback, announcing its deprecation. + """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``. - The delegate conflict is checked first. Both the property setters - above and :meth:`~pyhap.service.Service.configure_char` call this - with ``warn_stacklevel=3``, so the warning names the user code - that assigns the callback. + 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 and self._delegate is not None: - raise ValueError( - f"{self._display_name} has a delegate, remove it before" - " assigning a legacy callback" - ) if callback is not None: warnings.warn( f"The legacy {name} is deprecated, use a CharacteristicDelegate" - " instead", + " instead.", DeprecationWarning, stacklevel=warn_stacklevel, ) - if name == "getter_callback": - self._getter_callback = callback - else: - self._setter_callback = callback + 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: @@ -402,8 +469,9 @@ def get_value(self) -> Any: :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: @@ -535,7 +603,11 @@ 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. ``connection`` is the identity of the connection the write + 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 @@ -559,20 +631,27 @@ def client_update_value( previous_value = self._value self.value = value response = None - if self.setter_callback: - 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, connection, notify=notify) return response - def _store_client_value(self, value: Any) -> Any: - """Store a controller's write without running any callback. - - The new-style write path of the driver: validate and store the - value like :meth:`client_update_value` does, tell no subscriber - and call no callback - the driver runs the characteristic's - ``on_set`` and notifies once it succeeded, or restores this value - if the write is refused. Returns the value's previous state. + 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) @@ -589,10 +668,11 @@ def client_update_finished( *, 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 connection + 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: @@ -600,6 +680,62 @@ def client_update_finished( if self._always_null: self.value = None + async def dispatch_get(self, context: Context) -> Any: + """Answer a read of this characteristic through its delegate. + + 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. + """ + return await self.delegate.on_get( + CharReadContext.of(context, characteristic=self) + ) + + 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. @@ -625,11 +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 self.getter_callback is None - and self.delegate is None - ): + 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 @@ -667,25 +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: - try: - hap_rep[HAP_REPR_VALUE] = self.get_value() - except Exception: - # One failing getter must not fail the whole accessories - # response: the characteristic is listed without a value. - logger.exception( - "%s: Error getting the value; answering without it", - self._display_name, - ) + # 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 self.getter_callback is None and self.delegate is None: - # Only cache if nothing answers reads dynamically: a getter - # callback or a delegate's on_get may answer something else + 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/context.py b/pyhap/context.py index 760b34a3..debb4dbc 100644 --- a/pyhap/context.py +++ b/pyhap/context.py @@ -56,6 +56,22 @@ class CharReadContext(Context): 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): @@ -68,6 +84,26 @@ class CharWriteContext(Context): 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): @@ -79,3 +115,23 @@ class ServiceWriteContext(Context): 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 index 549677fb..23584f47 100644 --- a/pyhap/delegates.py +++ b/pyhap/delegates.py @@ -63,7 +63,7 @@ async def on_get(self, context: CharReadContext) -> Any: async def on_set(self, value: Any, context: CharWriteContext) -> Any: """Apply a controller's write of ``value``. - Runs after the write passed its gate hooks, under the context's + 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; @@ -98,7 +98,8 @@ async def on_unsubscribe(self, context: CharReadContext) -> None: class ServiceDelegate: """Delegate of a whole service. - The service's ``on_set`` is the gate of its grouped writes: a request + 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. diff --git a/pyhap/hap_handler.py b/pyhap/hap_handler.py index ee4d40b6..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 @@ -678,17 +677,13 @@ def handle_accessories(self) -> None: ) self.send_response(HTTPStatus.OK) self.send_header("Content-Type", self.JSON_RESPONSE_TYPE) - if inspect.isawaitable(result): - # A delegate read is still running, answer once it is 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)) - return + # 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.end_response(to_hap_json(result)) + 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 delegate reads, then answer the accessories.""" + """Wait for the pending reads, then answer the accessories.""" body: bytes = to_hap_json(await result) return body @@ -708,14 +703,11 @@ def handle_get_characteristics(self) -> None: connection=self.connection, ) assert self.response is not None # noqa: S101 - if inspect.isawaitable(result): - # A delegate read is still running, answer once it is done. The - # driver times out slow getters itself. - self.response.task = asyncio.ensure_future( - self._get_characteristics_body(self.response, result) - ) - return - self._fill_get_characteristics_response(self.response, result) + # 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) + ) def _fill_get_characteristics_response( self, response: HAPResponse, result: dict[str, Any] @@ -768,14 +760,12 @@ def handle_set_characteristics(self) -> None: 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._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 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 0b892075..43628fc7 100644 --- a/pyhap/service.py +++ b/pyhap/service.py @@ -1,6 +1,8 @@ """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 @@ -14,6 +16,7 @@ ) 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 @@ -21,6 +24,43 @@ 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. @@ -36,7 +76,6 @@ class Service: "type_id", "linked_services", "is_primary_service", - "_setter_callback", "_delegate", "unique_id", "_uuid_str", @@ -55,56 +94,77 @@ 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``. Either a delegate or the legacy setter, - # never both. - self.delegate: ServiceDelegate | None = None + # ``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 | None: - """The service's delegate, or ``None`` without one. - - A service has either a delegate or the legacy ``setter_callback``, - never both: assigning a delegate to a service that has one raises - ``ValueError``, and the reverse. + 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`` removes it.""" - if delegate is not None and self._setter_callback is not 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 = delegate + self._delegate = ( + _LegacySetterDelegateWrapper(service=self) if delegate is None else delegate + ) - @delegate.deleter - def delegate(self) -> None: - """Remove the delegate.""" - self._delegate = None + @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[[Any], None] | None: + 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 after the - per-characteristic setters of a write. + 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. """ - return self._setter_callback + 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[[Any], None] | None) -> None: - """Assign the legacy setter; ``None`` removes it.""" - if callback is not None and self._delegate is not None: - raise ValueError( - f"{self.display_name} has a delegate, remove it before" - " assigning a legacy setter_callback" - ) + 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" @@ -112,12 +172,35 @@ def setter_callback(self, callback: Callable[[Any], None] | None) -> None: DeprecationWarning, stacklevel=2, ) - self._setter_callback = callback + 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 - @setter_callback.deleter - def setter_callback(self) -> None: - """Remove the legacy setter.""" - self._setter_callback = None + 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.""" @@ -189,14 +272,10 @@ def configure_char( char.override_properties(properties, valid_values) if value: char.set_value(value, should_notify=False) - if setter_callback: - char._assign_legacy_callback( - "setter_callback", setter_callback, warn_stacklevel=3 - ) - if getter_callback: - char._assign_legacy_callback( - "getter_callback", getter_callback, warn_stacklevel=3 - ) + 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 diff --git a/tests/conftest.py b/tests/conftest.py index 2e209894..3425e0cc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -44,15 +44,12 @@ async def client_write( ) -> Any: """Write a characteristic like a controller's request. - A delegate-wired characteristic goes through its delegate: the value - is stored, ``on_set`` runs under the write deadline and the - subscribers are told once it succeeded - what the driver's write - stage does. A handler that raises restores the previous value, like - the driver does. A characteristic without a delegate runs its legacy - ``setter_callback``, like ``client_update_value``. + 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. """ - if char.delegate is None: - return char.client_update_value(value, client_addr) context = CharWriteContext( client_addr=client_addr, client_uuid=None, @@ -61,7 +58,7 @@ async def client_write( characteristic=char, is_admin=True, ) - previous = char._store_client_value(value) + previous = char._store_client_update(value) try: response = await char.delegate.on_set(value, context) except Exception: @@ -71,6 +68,12 @@ async def client_write( 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"]: yield MockDriver() diff --git a/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index 9bcfa26d..76c5a98e 100644 --- a/tests/test_accessory_driver.py +++ b/tests/test_accessory_driver.py @@ -22,7 +22,6 @@ MAX_PREPARED_WRITES_PER_CLIENT, PAIRING_LOCKOUT_SECONDS, AccessoryDriver, - AccessoryMDNSServiceInfo, ) from pyhap.characteristic import ( HAP_FORMAT_INT, @@ -51,8 +50,10 @@ 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, @@ -102,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.""" @@ -122,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, @@ -141,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() @@ -207,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], @@ -218,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}] @@ -230,7 +235,7 @@ def _raise_out_of_resource() -> NoReturn: raise HapStatusError(HAP_SERVER_STATUS.OUT_OF_RESOURCE) -def test_get_characteristics_hap_status_answers_request( +async def test_get_characteristics_hap_status_answers_request( driver: AccessoryDriver, ) -> None: """A getter's HapStatusError answers with its status, not -70402.""" @@ -238,7 +243,9 @@ def test_get_characteristics_hap_status_answers_request( char.getter_callback = _raise_out_of_resource 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: [ @@ -251,7 +258,7 @@ def test_get_characteristics_hap_status_answers_request( } -def test_get_accessories_isolates_a_failing_getter( +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.""" @@ -265,7 +272,9 @@ def test_get_accessories_isolates_a_failing_getter( acc.add_service(service) driver.add_accessory(acc) - (acc_rep,) = driver.get_accessories()[HAP_REPR_ACCS] + (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] } @@ -286,14 +295,17 @@ def test_get_accessories_isolates_a_failing_getter( (["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 @@ -445,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: [ @@ -492,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) @@ -506,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.""" @@ -514,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: [ @@ -529,7 +544,7 @@ def test_write_with_subscribe_without_write_permission( 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") @@ -545,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}, @@ -553,6 +568,7 @@ def test_refused_write_does_not_block_others(driver: AccessoryDriver) -> None: ] }, ("1.2.3.4", 5), + ASYNC_TIMEOUT, ) assert result == { @@ -666,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: [ { @@ -682,6 +712,7 @@ def _write( ] }, WRITER, + ASYNC_TIMEOUT, ) @@ -695,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], @@ -711,7 +742,7 @@ def test_write_response_returned_when_requested( 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: [ @@ -741,7 +772,7 @@ 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.""" @@ -749,7 +780,7 @@ def test_write_response_not_returned( setter = MagicMock(return_value=1) char.setter_callback = setter - assert _write(driver, acc, char, **query) is None + assert await _write(driver, acc, char, **query) is None setter.assert_called_once_with(0) assert char.value == 0 @@ -761,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} ) @@ -777,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.""" @@ -785,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: [ @@ -930,7 +961,7 @@ async def test_sync_setter_hap_status_answers_request( acc, char, _ = _add_bridged_or_standalone(driver, ["pr", "pw"], bridged) char.setter_callback = _raise_resource_busy - result = driver.set_characteristics( + result = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -941,6 +972,7 @@ async def test_sync_setter_hap_status_answers_request( ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert result == { @@ -977,7 +1009,7 @@ async def test_async_setter_hap_status_answers_request( } -def test_service_setter_hap_status_answers_all_its_chars( +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.""" @@ -992,7 +1024,7 @@ def test_service_setter_hap_status_answers_all_its_chars( driver.add_accessory(acc) refused.setter_callback = _raise_resource_busy - response = driver.set_characteristics( + response = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -1008,6 +1040,7 @@ def test_service_setter_hap_status_answers_all_its_chars( ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert response == { @@ -1026,7 +1059,7 @@ def test_service_setter_hap_status_answers_all_its_chars( } -def test_accessory_setter_hap_status_answers_all_its_chars( +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.""" @@ -1046,7 +1079,7 @@ def test_accessory_setter_hap_status_answers_all_its_chars( driver.add_accessory(bridge) acc.setter_callback = _raise_resource_busy - response = driver.set_characteristics( + response = await driver._set_characteristics_for_controller( { HAP_REPR_CHARS: [ { @@ -1062,6 +1095,7 @@ def test_accessory_setter_hap_status_answers_all_its_chars( ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert response == { @@ -1304,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: [ { @@ -1361,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, @@ -1491,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: [ { @@ -1513,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( @@ -1524,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) @@ -1631,7 +1684,7 @@ 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] @@ -1652,15 +1705,18 @@ 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() @@ -1772,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) @@ -1846,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 @@ -1864,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, ) @@ -1909,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 = { @@ -1936,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 @@ -1959,18 +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) == 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 @@ -1983,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.""" @@ -1991,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) @@ -2007,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 @@ -2020,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``.""" @@ -2031,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, @@ -2050,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 @@ -2070,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 direct write without a client is sent and read back without one.""" +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: [ @@ -2097,10 +2171,9 @@ 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 + # 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 @@ -2114,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) @@ -2163,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: [ { @@ -2189,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": [ @@ -2209,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": [ @@ -2227,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) @@ -2267,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: [ { @@ -2293,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}) @@ -2322,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) @@ -2361,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: [ { @@ -2387,6 +2468,7 @@ def fail_callback(*_: Any) -> NoReturn: ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert response == { @@ -2443,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) @@ -2487,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: [ { @@ -2518,6 +2600,7 @@ def test_accessory_level_callbacks(driver: AccessoryDriver) -> None: ] }, "mock_addr", # ty: ignore[invalid-argument-type] + ASYNC_TIMEOUT, ) assert response is None @@ -2532,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) @@ -2576,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: [ { @@ -2607,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( @@ -3271,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 @@ -3286,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) @@ -3296,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 @@ -3310,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.""" @@ -3321,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 @@ -3349,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 diff --git a/tests/test_admin_only.py b/tests/test_admin_only.py index b58f6e59..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) == { @@ -315,7 +328,7 @@ def test_admin_only_null_write_reaches_no_setter( 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``.""" @@ -325,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 34bb0aa4..60056531 100644 --- a/tests/test_camera.py +++ b/tests/test_camera.py @@ -17,6 +17,7 @@ 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. @@ -72,7 +73,9 @@ def test_camera_wiring_is_delegate_based(mock_driver: Any) -> None: streaming_status = _char_of(acc, "CameraRTPStreamManagement", "StreamingStatus") status_active = _char_of(acc, "MotionSensor", "StatusActive") for char in (streaming_status, status_active): - assert char.getter_callback is None + # 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 diff --git a/tests/test_camera_operating_mode.py b/tests/test_camera_operating_mode.py index a6a364cc..a40c0c8e 100644 --- a/tests/test_camera_operating_mode.py +++ b/tests/test_camera_operating_mode.py @@ -13,7 +13,7 @@ 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 @@ -122,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 diff --git a/tests/test_characteristic.py b/tests/test_characteristic.py index 9ce9fc23..c6a7e371 100644 --- a/tests/test_characteristic.py +++ b/tests/test_characteristic.py @@ -350,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] @@ -567,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", @@ -575,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", @@ -592,22 +596,6 @@ class _AsyncGetter(CharacteristicDelegate): """A delegate overriding on_get.""" -def test_delegate_assignment() -> None: - """An assigned delegate instance is the characteristic's delegate.""" - char = get_char(PROPERTIES) - delegate = _AsyncGetter() - - char.delegate = delegate - - assert char.delegate is delegate - assert char.getter_callback is None - assert char.setter_callback is None - - char.delegate = None - - assert char.delegate is None - - def test_to_HAP_cache_skips_delegate() -> None: """A delegate-backed characteristic is not served from the value cache. @@ -654,7 +642,7 @@ def test_delegate_conflicts_with_legacy_callbacks() -> None: def test_removing_one_side_allows_the_other() -> None: - """Clearing with None or del frees the characteristic for the other.""" + """Clearing one side with ``None`` frees the characteristic for the other.""" char = get_char(PROPERTIES) char.setter_callback = lambda value: None # noqa: E731 @@ -668,12 +656,12 @@ def test_removing_one_side_allows_the_other() -> None: assert char.getter_callback is not None - del char.getter_callback + char.getter_callback = None char.delegate = _AsyncGetter() assert char.delegate is not None - del char.delegate + char.delegate = None char.setter_callback = lambda value: None # noqa: E731 assert char.setter_callback is not None @@ -700,4 +688,3 @@ def test_legacy_callbacks_warn_deprecated() -> None: with warnings.catch_warnings(): warnings.simplefilter("error") char.setter_callback = None - del char.getter_callback diff --git a/tests/test_delegate_dispatch.py b/tests/test_delegate_dispatch.py index a07b7455..a0e4332a 100644 --- a/tests/test_delegate_dispatch.py +++ b/tests/test_delegate_dispatch.py @@ -3,6 +3,7 @@ import asyncio from collections.abc import Mapping import inspect +import math import time from typing import Any from unittest.mock import MagicMock, patch @@ -374,6 +375,28 @@ async def test_on_set_failure_answers_70402(driver: AccessoryDriver) -> None: 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) @@ -404,15 +427,17 @@ async def test_invalid_value_answers_70402_without_on_set( assert char.value == 0 -async def test_null_write_runs_no_on_set(driver: AccessoryDriver) -> None: - """A null write applies nothing and runs no on_set, like the legacy path.""" +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 result is None + assert _status_of(result, acc, char) == HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST assert delegate.calls == [] assert char.value == 0 @@ -473,6 +498,31 @@ async def test_gate_failure_answers_70402(driver: AccessoryDriver) -> None: 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) @@ -656,7 +706,7 @@ async def test_on_subscribe_receives_a_full_context(driver: AccessoryDriver) -> assert context.client_addr == WRITER assert context.client_uuid == client_uuid assert context.connection is handle - assert context.deadline == float("inf") + assert context.deadline == math.inf assert driver.topics == {char_topic: {handle}} @@ -804,7 +854,7 @@ def _record(*_: Any) -> None: assert value == 7 assert context.client_addr == WRITER assert context.connection is driver._connection_of(WRITER) - assert context.deadline == float("inf") + assert context.deadline == math.inf notify.assert_called_once_with(driver._connection_of(WRITER)) @@ -888,6 +938,25 @@ def on_get(self, context: CharReadContext) -> Any: 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) @@ -983,7 +1052,7 @@ async def test_direct_get_characteristics_answers_stored_and_schedules( assert context.characteristic is char assert context.client_addr is None assert context.connection.client_addr is None - assert context.deadline == float("inf") + assert context.deadline == math.inf async def test_on_get_answers_an_accessories_request(driver: AccessoryDriver) -> None: diff --git a/tests/test_hap_handler.py b/tests/test_hap_handler.py index bd9aea14..7e1c57ae 100644 --- a/tests/test_hap_handler.py +++ b/tests/test_hap_handler.py @@ -699,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.""" @@ -716,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.""" @@ -740,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.""" @@ -772,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.""" @@ -810,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"" @@ -837,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.""" @@ -864,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.""" @@ -896,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 @@ -920,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.""" @@ -942,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 @@ -991,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 @@ -1008,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()) @@ -1020,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()) @@ -1035,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.""" @@ -1059,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) @@ -1068,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 diff --git a/tests/test_hap_protocol.py b/tests/test_hap_protocol.py index 617ed1cd..602fc74b 100644 --- a/tests/test_hap_protocol.py +++ b/tests/test_hap_protocol.py @@ -18,6 +18,7 @@ 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): @@ -353,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")) @@ -372,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) @@ -401,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]) @@ -420,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) @@ -446,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 ( @@ -473,10 +481,11 @@ def test_crypto_failure_closes_connection(driver: AccessoryDriver) -> None: 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")) @@ -493,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]) @@ -1021,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 @@ -1332,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 = {} @@ -1360,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" @@ -1367,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_hksv_recording.py b/tests/test_hksv_recording.py index 850b00f4..219a391b 100644 --- a/tests/test_hksv_recording.py +++ b/tests/test_hksv_recording.py @@ -7,6 +7,7 @@ """ import inspect +import math import os import time from typing import Any @@ -486,7 +487,7 @@ async def test_sensor_follows_camera_active_set_without_write( client_addr=None, client_uuid=None, connection=HAPConnectionHandle(None, 1), - deadline=float("inf"), + deadline=math.inf, characteristic=status_active, ) assert status_active.delegate is not None diff --git a/tests/test_hksv_state.py b/tests/test_hksv_state.py index 8a3cd269..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 @@ -188,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: diff --git a/tests/test_service.py b/tests/test_service.py index 9a537e99..5806d65a 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -12,9 +12,10 @@ PROP_FORMAT, PROP_PERMISSIONS, Characteristic, + _LegacyCallbackDelegateWrapper, ) from pyhap.delegates import CharacteristicDelegate, ServiceDelegate -from pyhap.service import Service +from pyhap.service import Service, _LegacySetterDelegateWrapper CHAR_PROPS = { PROP_FORMAT: HAP_FORMAT_INT, @@ -87,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"} @@ -269,7 +276,8 @@ def test_service_delegate_assignment() -> None: service.delegate = None - assert service.delegate is None + assert isinstance(service.delegate, _LegacySetterDelegateWrapper) + assert service.delegate.setter is None def test_configure_char_wires_delegate() -> None: @@ -347,5 +355,7 @@ def test_configure_char_without_delegate() -> None: configured = service.configure_char("Char 1", value=5) - assert configured.delegate is None + 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 1694127e..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,15 +87,17 @@ 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 driver._connection_of(CLIENT) in driver.topics[get_topic(door.aid, door.iid)] @@ -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