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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 100 additions & 11 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -63,16 +62,37 @@ Sections
awaitables zeroconf returns (the
[#580](https://github.com/ikalchev/HAP-python/pull/580) bug class).
`tests/test_asyncio_guards.py` guards the `filterwarnings` config itself.

### Fixed

- Drop the write response of a coroutine setter that answers only after its
connection closed. The per-connection response was kept under the closed
connection's address forever, where a later connection reusing the address
could read it, e.g. a Setup Endpoints answer with its session's SRTP keys.
- Cancel tasks still pending on the loop before `AccessoryDriver.start`
closes it, so e.g. a `run_at_interval` wrapper is not destroyed pending at
shutdown ("Task was destroyed but it is pending!").
- Characteristic and service delegates (`pyhap.delegates`) with request
contexts (`pyhap.context`): the reads, writes and event subscriptions of a
characteristic dispatch to a delegate — every call an awaited coroutine
function under a request deadline, with a frozen context carrying the
controller's connection, identity and privileges. A service delegate is
the pre-check of the grouped writes of its service: it may refuse them by
raising `HapStatusError`, which restores the previous values and notifies
nobody. `delegate` is never `None`: without an assigned one the default
delegate — the wrapper of the legacy callbacks without any — answers,
and reading the legacy callbacks of a delegate-wired object raises
`ValueError`.
- `HapStatusError` (`pyhap.errors`): a callback answers a curated HAP status
code by raising it, so a busy or refusing accessory no longer fails with
the generic `-70402`. A legacy callback may raise it too.
[#75](https://github.com/ikalchev/HAP-python/issues/75)
- Async getters: `GET /characteristics` and `GET /accessories` await the
`on_get` of every readable characteristic under the request deadline — a
legacy getter wrapped into the delegate — so a getter may do IO. A getter
that fails or misses the deadline answers per characteristic
(`-70402` / `-70408`).
- Connection lifecycle hooks on `Accessory`: `client_connected` and
`client_verified`, async and isolated like the existing
`client_disconnected`.
- A stable per-connection identity (`HAPConnectionHandle`,
`pyhap.connection`), which camera streaming sessions are keyed by: a new
connection reusing a closed one's address can no longer control its
sessions.
- `accessories/busy_lock.py`, an example accessory that refuses a lock with
`RESOURCE_BUSY` instead of answering a silent failure.
- `accessories/delegate_lightbulb.py`, an example accessory built on
delegates, contexts and `HapStatusError`.

### Changed

Expand All @@ -85,6 +105,75 @@ Sections
`pyhap.hap_handler`). `pyhap.camera` now imports the multi-tier and WebRTC
stream services at the top, which makes the cycle gone instead of hidden in
a deferred import.
- A failing getter answers its own status per characteristic instead of
failing the whole `/accessories` response.
- One dispatch pipeline for every write and read: the legacy callbacks run
wrapped inside the delegate calls, so a characteristic without a delegate
and one with one take the same path — the values are stored, the written
services' pre-checks run first (a legacy grouped setter of a service or an
accessory among them), then each written characteristic's `on_set`, and
a refused or failed write is restored and notifies nobody. An explicit
`null` write answers `-70410`, like before, without reaching a callback.
- A camera delegate hook gets at most `hook_timeout` seconds, or as long as
the request has left: whichever ends first, the answer still fits in the
request.
- The camera stack (stream management, recording, operating mode, multi-tier
and WebRTC) dispatches through delegates and contexts internally; the
author-facing camera methods keep their signatures.
- The driver's per-controller state is keyed by the connection, not by its
address: event subscriptions, prepared timed writes, write responses and
the server's connections, all by `HAPConnectionHandle`. Nothing of a
closed connection reaches a later one that reuses its address, and a
write response that arrives only after its connection closed is dropped
instead of kept. A direct call (`driver.set_characteristics` and
friends) without a connection acts as a virtual connection of its
client address, so its prepared writes and read-backs pair up across
calls as before.

### Deprecated

- The legacy callbacks: assigning `setter_callback` or `getter_callback` on
a characteristic, `setter_callback` on a service or an accessory, or
passing them to `configure_char`, warns `DeprecationWarning`. They keep
working, wrapped into the delegate calls; move new code to the delegates.

### Fixed

- Drop the write response of a coroutine setter that answers only after its
connection closed. The per-connection response was kept under the closed
connection's address forever, where a later connection reusing the address
could read it, e.g. a Setup Endpoints answer with its session's SRTP keys.
- Cancel tasks still pending on the loop before `AccessoryDriver.start`
closes it, so e.g. a `run_at_interval` wrapper is not destroyed pending at
shutdown ("Task was destroyed but it is pending!").

### Breaking Changes

- Direct calls answer at once, optimistically: `driver.set_characteristics`
answers a plain success and runs the setters as a job, and
`driver.get_characteristics` / `driver.get_accessories` answer the stored
values and run the reads as a job — a write response or a getter's fresh
value is no longer part of the synchronous answer. The HAP representation
(`to_HAP`) answers the stored value; a fresh answer comes from the read
path.
- A legacy grouped setter — `Service.setter_callback` or
`Accessory.setter_callback` — runs *before* the per-characteristic
setters, as the pre-check of its service or accessory, and its
`HapStatusError` now refuses the writes (restores the values, notifies
nobody) instead of answering a status after they were applied.
- The notify chain takes the writing connection, not its address: the
third parameter of `Accessory.publish` and `Camera.publish` and the
second of `Characteristic.client_update_value`,
`Characteristic.client_update_finished` and `Characteristic.notify`
is a `HAPConnectionHandle` (or `None`), so a controller is not sent its
own write back even while another connection reuses its address.
`AccessoryDriver.derive_session_key` takes the connection instead of its
address (`AccessoryDriver.prepare` and the other direct-call entry points
keep their signatures, taking an optional `connection`).
- A legacy setter is always called with the value alone: the
`(value, sender_client_addr)` two-argument form, detected by parameter
name, is gone. What a callback needs to know about the writer arrives
through a delegate's context instead.

## [5.2.0] - 2026-11-07

Expand Down
108 changes: 108 additions & 0 deletions accessories/busy_lock.py
Original file line number Diff line number Diff line change
@@ -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()
114 changes: 114 additions & 0 deletions accessories/delegate_lightbulb.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading