From 45a86bb15bf8a19748f17526a339f33704b8142b Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:33:16 -0300 Subject: [PATCH 1/9] Add Adaptive Lighting transition codec and interpolator First step towards a reusable AdaptiveLightingController (issue #495): decode the TransitionControl TLV8 schedule the Home app writes, expose the parsed curve and interpolate the current colour temperature and brightness factor at any moment, and serialise the state so a consumer can persist it. No controller or HomeKit service wiring yet. - pyhap.tlv.decode_ordered: TLV8 decode preserving record order, duplicates and empty records (used as list delimiters), rejoining 255-byte chunks - pyhap.adaptive_lighting: variable-width uint codec, TLV helpers, CurveEntry/ActiveTransition model, parse_transition_control / parse_transition_update with injectable clock, interpolate / interpolate_point with hold-duration and brightness-factor interpolation, ActiveTransition.to_dict/from_dict - tests cover the real Home app payload, curve end, hold windows, brightness factor smoothness, malformed writes and state roundtrip Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- docs/source/api/adaptive_lighting.rst | 11 + pyhap/adaptive_lighting.py | 370 +++++++++++++++++++++ pyhap/tlv.py | 38 +++ tests/test_adaptive_lighting.py | 441 ++++++++++++++++++++++++++ 4 files changed, 860 insertions(+) create mode 100644 docs/source/api/adaptive_lighting.rst create mode 100644 pyhap/adaptive_lighting.py create mode 100644 tests/test_adaptive_lighting.py diff --git a/docs/source/api/adaptive_lighting.rst b/docs/source/api/adaptive_lighting.rst new file mode 100644 index 00000000..e0336fd4 --- /dev/null +++ b/docs/source/api/adaptive_lighting.rst @@ -0,0 +1,11 @@ +.. _api-adaptive-lighting: + +================== +Adaptive Lighting +================== + +Codec and interpolator for HomeKit Adaptive Lighting transition schedules. + +.. automodule:: pyhap.adaptive_lighting + :members: + :undoc-members: diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py new file mode 100644 index 00000000..8b9a2d1b --- /dev/null +++ b/pyhap/adaptive_lighting.py @@ -0,0 +1,370 @@ +"""Codec and interpolator for HomeKit Adaptive Lighting schedules. + +Apple's Adaptive Lighting pushes a ``TransitionControl`` characteristic +whose value is a base64 TLV8 schedule: a list of curve points covering +about 24 hours, each carrying a colour temperature in mireds, a +brightness adjustment factor and the timing until the next point. This +module decodes that schedule and evaluates it at a given moment. + +The wire format is not documented by Apple; the implementation follows +the reference behaviour of HAP-NodeJS: +https://github.com/homebridge/HAP-NodeJS/blob/latest/src/lib/controller/AdaptiveLightingController.ts + +This is protocol code only: scheduling evaluations, writing values to +accessories and persisting state are left to the consumer. +""" + +import base64 +from dataclasses import dataclass +import logging +import math +import struct +import time +from typing import Any + +from pyhap import tlv + +_LOGGER = logging.getLogger(__name__) + +CHAR_ACTIVE_TRANSITION_COUNT = "ActiveTransitionCount" +CHAR_TRANSITION_CONTROL = "TransitionControl" +CHAR_SUPPORTED_TRANSITION_CONFIGURATION = "SupportedTransitionConfiguration" + +ADAPTIVE_LIGHTING_CHARS = ( + CHAR_ACTIVE_TRANSITION_COUNT, + CHAR_TRANSITION_CONTROL, + CHAR_SUPPORTED_TRANSITION_CONFIGURATION, +) + +EMPTY_TLV_TYPE = 0x00 + +# SupportedCharacteristicValueTransitionConfigurations +TAG_SUPPORTED_TRANSITION_CONFIGURATION = 0x01 +TAG_CHARACTERISTIC_IID = 0x01 +TAG_TRANSITION_TYPE = 0x02 +TRANSITION_TYPE_BRIGHTNESS = 0x01 +TRANSITION_TYPE_COLOR_TEMPERATURE = 0x02 + +# TransitionControl +TAG_READ_CURRENT_TRANSITION = 0x01 +TAG_UPDATE_TRANSITION = 0x02 + +# ValueTransitionConfiguration +TAG_CFG_IID = 0x01 +TAG_CFG_PARAMETERS = 0x02 +TAG_CFG_UNKNOWN_3 = 0x03 +TAG_CFG_CURVE = 0x05 +TAG_CFG_UPDATE_INTERVAL = 0x06 +TAG_CFG_NOTIFY_THRESHOLD = 0x08 + +# ValueTransitionParameters +TAG_PARAM_TRANSITION_ID = 0x01 +TAG_PARAM_START_TIME = 0x02 + +# TransitionCurveConfiguration +TAG_CURVE_ENTRY = 0x01 +TAG_CURVE_ADJUSTMENT_IID = 0x02 +TAG_CURVE_MULTIPLIER_RANGE = 0x03 +TAG_RANGE_MIN = 0x01 +TAG_RANGE_MAX = 0x02 + +# TransitionEntry +TAG_ENTRY_ADJUSTMENT_FACTOR = 0x01 +TAG_ENTRY_VALUE = 0x02 +TAG_ENTRY_TRANSITION_OFFSET = 0x03 +TAG_ENTRY_DURATION = 0x04 + +# HAP timestamps count from 2001-01-01, the Unix epoch counts from 1970-01-01. +EPOCH_MILLIS_2001 = 978307200000 + +# An update interval of zero would reschedule the timer immediately forever. +MIN_UPDATE_INTERVAL = 1000 + + +def encode_variable_uint(value: int) -> bytes: + """Encode an unsigned int in the smallest little-endian width HAP accepts.""" + if value < 0: + raise ValueError("value must not be negative") + if value <= 0xFF: + return value.to_bytes(1, "little") + if value <= 0xFFFF: + return value.to_bytes(2, "little") + if value <= 0xFFFFFFFF: + return value.to_bytes(4, "little") + raise ValueError("value does not fit in 32 bits") + + +def decode_variable_uint(value: bytes) -> int: + """Decode a variable width little-endian unsigned int.""" + return int.from_bytes(value, "little") + + +def encode_tlv(*args: int | bytes) -> bytes: + """Encode tag/value pairs, splitting values longer than 255 bytes. + + Tags are given as ints and values as bytes, alternating. The result is + the raw TLV8 record sequence; see :func:`pyhap.tlv.decode_ordered` for + the matching decoder. + """ + return tlv.encode(*[bytes((arg,)) if isinstance(arg, int) else arg for arg in args]) + + +def encode_tlv_list(tag: int, entries: list[bytes]) -> bytes: + """Encode repeated entries under one tag, separated by the empty-TLV delimiter.""" + if not entries: + return encode_tlv(tag, b"") + parts: list[bytes] = [] + for position, entry in enumerate(entries): + if position: + parts.append(encode_tlv(EMPTY_TLV_TYPE, b"")) + parts.append(encode_tlv(tag, entry)) + return b"".join(parts) + + +def first_tlv_value(entries: list[tuple[int, bytes]], tag: int) -> bytes | None: + """Return the first value for a tag, or None.""" + return next((value for entry_tag, value in entries if entry_tag == tag), None) + + +def supported_transition_configuration( + brightness_iid: int, color_temperature_iid: int +) -> str: + """Build the base64 value advertising which characteristics support transitions.""" + return base64.b64encode( + encode_tlv_list( + TAG_SUPPORTED_TRANSITION_CONFIGURATION, + [ + encode_tlv( + TAG_CHARACTERISTIC_IID, + encode_variable_uint(brightness_iid), + TAG_TRANSITION_TYPE, + bytes((TRANSITION_TYPE_BRIGHTNESS,)), + ), + encode_tlv( + TAG_CHARACTERISTIC_IID, + encode_variable_uint(color_temperature_iid), + TAG_TRANSITION_TYPE, + bytes((TRANSITION_TYPE_COLOR_TEMPERATURE,)), + ), + ], + ) + ).decode() + + +@dataclass(slots=True) +class CurveEntry: + """One point of the 24 hour schedule Apple sends.""" + + temperature: float # mireds + brightness_adjustment_factor: float + transition_time: int # milliseconds since the previous entry + duration: int # milliseconds this value is held before interpolating + + +@dataclass(slots=True) +class ActiveTransition: + """The schedule currently driving a light.""" + + transition_id: bytes + parameters: bytes + start_millis: int # unix millis, in the controller's clock + time_millis_offset: int # our clock minus the controller's clock + curve: list[CurveEntry] + update_interval: int + notify_threshold: int + min_multiplier: int + max_multiplier: int + + def to_dict(self) -> dict[str, Any]: + """Serialise the transition so it survives a restart.""" + return { + "transition_id": self.transition_id.hex(), + "parameters": self.parameters.hex(), + "start_millis": self.start_millis, + "time_millis_offset": self.time_millis_offset, + "update_interval": self.update_interval, + "notify_threshold": self.notify_threshold, + "min_multiplier": self.min_multiplier, + "max_multiplier": self.max_multiplier, + "curve": [ + [ + entry.temperature, + entry.brightness_adjustment_factor, + entry.transition_time, + entry.duration, + ] + for entry in self.curve + ], + } + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> "ActiveTransition": + """Rebuild a stored transition.""" + return cls( + transition_id=bytes.fromhex(data["transition_id"]), + parameters=bytes.fromhex(data["parameters"]), + start_millis=data["start_millis"], + time_millis_offset=data["time_millis_offset"], + curve=[CurveEntry(*entry) for entry in data["curve"]], + update_interval=data["update_interval"], + notify_threshold=data["notify_threshold"], + min_multiplier=data["min_multiplier"], + max_multiplier=data["max_multiplier"], + ) + + +def parse_transition_control( + value: str, *, now_millis: int | None = None +) -> ActiveTransition | None: + """Parse an UpdateValueTransitionConfiguration write from the Home app. + + :param value: The base64 value written to the TransitionControl characteristic. + :param now_millis: The current time in unix millis; defaults to the wall clock. + Pass an explicit value to make parsing deterministic. + """ + update = first_tlv_value( + tlv.decode_ordered(base64.b64decode(value)), TAG_UPDATE_TRANSITION + ) + if not update: + return None + return parse_transition_update(update, now_millis=now_millis) + + +def parse_transition_update( + update: bytes, *, now_millis: int | None = None +) -> ActiveTransition | None: + """Parse the VALUE_TRANSITION_CONFIGURATION payload of an update write. + + :param update: The TLV8 payload carried under the update tag. + :param now_millis: The current time in unix millis; defaults to the wall clock. + """ + outer = tlv.decode_ordered(update) + if not outer: + return None + configuration = tlv.decode_ordered(outer[0][1]) + parameters_raw = first_tlv_value(configuration, TAG_CFG_PARAMETERS) + curve_raw = first_tlv_value(configuration, TAG_CFG_CURVE) + if not parameters_raw or not curve_raw: + return None + + parameters = tlv.decode_ordered(parameters_raw) + start_time = first_tlv_value(parameters, TAG_PARAM_START_TIME) + transition_id = first_tlv_value(parameters, TAG_PARAM_TRANSITION_ID) + if not start_time or not transition_id or len(start_time) != 8: + return None + start_millis = struct.unpack(" tuple[float, float] | None: + """Return (mired, brightness adjustment factor) for this moment. + + Both values are interpolated between the two surrounding curve points, so + the factor does not jump when the curve moves on to the next point. None is + returned past the end of the curve. + """ + offset = now_millis - transition.time_millis_offset - transition.start_millis + if offset < 0: + return None + + lower_bound_time_offset = 0 + for index in range(len(transition.curve) - 1): + lower = transition.curve[index] + upper = transition.curve[index + 1] + lower_bound_time_offset += lower.transition_time + if offset >= lower_bound_time_offset: + if ( + offset + <= lower_bound_time_offset + lower.duration + upper.transition_time + ): + transition_offset = offset - lower_bound_time_offset + if lower.duration and transition_offset <= lower.duration: + return lower.temperature, lower.brightness_adjustment_factor + if not upper.transition_time: + return upper.temperature, upper.brightness_adjustment_factor + percentage = ( + transition_offset - lower.duration + ) / upper.transition_time + return ( + lower.temperature + + (upper.temperature - lower.temperature) * percentage, + lower.brightness_adjustment_factor + + ( + upper.brightness_adjustment_factor + - lower.brightness_adjustment_factor + ) + * percentage, + ) + lower_bound_time_offset += lower.duration + return None + + +def interpolate(transition: ActiveTransition, now_millis: int) -> float | None: + """Return the mired value for this moment, or None past the end of the curve.""" + point = interpolate_point(transition, now_millis) + return None if point is None else point[0] diff --git a/pyhap/tlv.py b/pyhap/tlv.py index 076716f9..0c3fbd84 100644 --- a/pyhap/tlv.py +++ b/pyhap/tlv.py @@ -106,3 +106,41 @@ def decode(data: bytes | str, from_base64: bool = False) -> dict[bytes, Any]: if chunked: return {tag: b"".join(chunks) for tag, chunks in objects.items()} return objects + + +def decode_ordered(data: bytes) -> list[tuple[int, bytes]]: + """Decode TLV8 preserving record order, duplicates and empty records. + + Unlike :func:`decode`, which collapses records into a ``dict``, this + returns every record as ``(tag, value)`` with the tag as an ``int``. + Records with a zero length are kept: protocols such as Adaptive Lighting + use a ``0x00`` record as a delimiter between repeated entries. Values + longer than 255 bytes are split into chunks by :func:`encode`; chunks + of the same tag are joined back together here. + + :param data: The TLV-encoded bytes to decode. + :type data: ``bytes`` + + :return: The records in wire order. + :rtype: ``list`` of ``(int, bytes)`` tuples + """ + entries: list[tuple[int, bytes]] = [] + current = 0 + while current + 1 < len(data): + tag = data[current] + length = data[current + 1] + end = current + 2 + length + if end > len(data): + raise ValueError(f"TLV value truncated at offset {current}") + value = data[current + 2 : end] + current = end + if ( + entries + and entries[-1][0] == tag + and entries[-1][1] + and len(entries[-1][1]) % 255 == 0 + ): + entries[-1] = (tag, entries[-1][1] + value) + else: + entries.append((tag, value)) + return entries diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py new file mode 100644 index 00000000..9b3a562c --- /dev/null +++ b/tests/test_adaptive_lighting.py @@ -0,0 +1,441 @@ +"""Tests for pyhap.adaptive_lighting.""" + +import base64 +import json +import math +import struct +from typing import Any + +import pytest + +from pyhap import adaptive_lighting, tlv +from pyhap.adaptive_lighting import ( + TAG_CFG_CURVE, + TAG_CFG_IID, + TAG_CFG_PARAMETERS, + TAG_CFG_UNKNOWN_3, + TAG_CFG_UPDATE_INTERVAL, + TAG_CURVE_ENTRY, + TAG_ENTRY_ADJUSTMENT_FACTOR, + TAG_ENTRY_DURATION, + TAG_ENTRY_TRANSITION_OFFSET, + TAG_ENTRY_VALUE, + TAG_PARAM_START_TIME, + TAG_PARAM_TRANSITION_ID, + TAG_UPDATE_TRANSITION, + ActiveTransition, + decode_variable_uint, + encode_tlv, + encode_tlv_list, + encode_variable_uint, + first_tlv_value, + interpolate, + interpolate_point, + parse_transition_control, + parse_transition_update, + supported_transition_configuration, +) + +# A real schedule written by the Home app to a colour temperature light. The +# curve covers 24 hours in 42 points and asks for an update every 60 seconds. +TRANSITION_CONTROL_WRITE = ( + "Av8B/wEBDQImARDE8z2pY8lMD4uJbDajPu+eAgiCLNrVvAAAAAMI7Ig7PwjVT4kDAQEF/wEP" + "AQQXbEG/AgQcx/1DAwEAAAABEgEEMzMzvwIEAID9QwMEwLAHAAAAARIBBGzBFr8CBMdx+0MD" + "BEB3GwAAAAESAQT1SR+/AgRyHP1DAwRAdxsAAAABGAEEbMEWvwIEx/H5QwMEQHcbAAQEgMuk" + "AAAAARIBBLZgC78CBOS49UMDBEB3GwAAAAESAQTv7u6+AgRVVe9DAwRAdxsAAAABEgEEchzH" + "vgIEx3HoQwMEQHcbAAAAARIBBJqZmb4CBACA4UMDBEB3GwAAAAESAQQC/83MAf9MvgIEAADa" + "QwMEQHcbAAAAARIBBM3MzL0CBAAA00MDBEB3GwAAAAESAQSJiAi9AgQF/6sqzEMDBEB3GwAA" + "AAESAQRhCza9AgTkOMZDAwRAdxsAAAABEgEE9UkfvgIEHMfAQwMEQHcbAAAAARIBBGELtr4C" + "BBzHu0MDBEB3GwAAAAESAQTkOA6/AgQcR7dDAwRAdxsAAAABEgEE6ZM+vwIE5LizQwMEQHcb" + "AAAAARIBBFuwhb8CBOQ4sUMDBEB3GwAAAAESAQQ5jqO/AgSO469DAwRAdxsAAAABEgEEjuO4" + "vwIE5DivQwMEQHcbAAAAARIBBKVPur8CBBxHrgL/QwMEQAH/dxsAAAABEgEEpU+6vwIEHMet" + "QwMEQHcbAAAAARIBBLy7u78CBFXVrUMDBEB3GwAAAAEF/xIBBKVPur8CBBzHrUMDBEB3GwAA" + "AAEYAQS8u7u/AgRV1a1DAwRAdxsABASA7jYAAAABEgEEpU+6vwIEHMetQwMEQHcbAAAAARIB" + "BHd3t78CBKsqrkMDBEB3GwAAAAESAQQGW7C/AgSO465DAwRAdxsAAAABEgEEZmamvwIEAICw" + "QwMEQHcbAAAAARIBBJqZmb8CBAAAskMDBEB3GwAAAAESAQTNzIy/AgQAALVDAwRAdxsAAAAB" + "EgEE0id9vwIEx3G4QwMEAv9AdxsAAAAB9wESAQSUPmm/AgQ5jr1DAwRAdxsAAAABEgEEMzMz" + "vwIEAADEQwMEQHcbAAAAARIBBFuwBb8FtwIEchzMQwMEQHcbAAAAARIBBAZbML8CBMfx10MD" + "BEB3GwAAAAESAQRyHEe/AgSOY+NDAwRAdxsAAAABEgEEsAVbvwIEHMfuQwMEQHcbAAAAARIB" + "BLAFW78CBBxH+EMDBEB3GwAAAAESAQTv7m6/AgSrqv5DAwRAdxsAAAABEgEE3t1dvwIEVVX+" + "QwMEQHcbAAAAARIBBBdsQb8CBBzH/UMDBIDGEwACAQoDDAEECgAAAAIEZAAAAAYCYOoIBMAn" + "CQA=" +) + +# A fixed parse time keeps every interpolation test deterministic: the curve +# position is measured from the moment the schedule was parsed. +NOW_MILLIS = 1_800_000_000_000 + + +def test_encode_variable_uint() -> None: + """Values are encoded in the smallest little-endian width.""" + assert encode_variable_uint(2) == b"\x02" + assert encode_variable_uint(300) == b"\x2c\x01" + assert encode_variable_uint(70000) == b"\x70\x11\x01\x00" + assert decode_variable_uint(b"\x70\x11\x01\x00") == 70000 + + +def test_encode_variable_uint_rejects_impossible_values() -> None: + """HAP has no encoding for a negative or larger than 32 bit value.""" + with pytest.raises(ValueError, match="negative"): + encode_variable_uint(-1) + with pytest.raises(ValueError, match="32 bits"): + encode_variable_uint(2**32) + + +def test_encode_tlv_splits_long_values() -> None: + """A value longer than 255 bytes is split across repeated entries.""" + assert encode_tlv(0x01, b"\x02") == b"\x01\x01\x02" + assert ( + encode_tlv(0x09, b"\xaa" * 256) == b"\x09\xff" + b"\xaa" * 255 + b"\x09\x01\xaa" + ) + assert encode_tlv(0x01, b"") == b"\x01\x00" + + +def test_encode_tlv_rejects_bad_arguments() -> None: + """Tags and values are encoded in pairs of int and bytes.""" + with pytest.raises(ValueError, match="Even number"): + encode_tlv(0x01) + bad_value: Any = "not bytes" + with pytest.raises(TypeError): + encode_tlv(0x01, bad_value) + + +def test_encode_tlv_list_uses_the_empty_delimiter() -> None: + """Repeated entries are separated by a zero length TLV, as HAP expects.""" + assert ( + encode_tlv_list(0x01, [b"\xaa", b"\xbb"]) == b"\x01\x01\xaa\x00\x00\x01\x01\xbb" + ) + assert encode_tlv_list(0x01, []) == b"\x01\x00" + + +def test_decode_ordered_preserves_order_duplicates_and_delimiters() -> None: + """The ordered decoder keeps every record, including empty delimiters.""" + assert tlv.decode_ordered(b"\x02\x01\xaa\x01\x01\xbb\x00\x00") == [ + (2, b"\xaa"), + (1, b"\xbb"), + (0, b""), + ] + + +def test_decode_ordered_rejoins_split_values() -> None: + """Decoding is the inverse of encoding for values of any length.""" + value = bytes(range(256)) * 2 + encoded = encode_tlv(0x07, value) + assert tlv.decode_ordered(encoded) == [(7, value)] + + +def test_decode_ordered_rejects_a_truncated_value() -> None: + """A declared length past the buffer end is an error, not a short read.""" + with pytest.raises(ValueError, match="truncated"): + tlv.decode_ordered(b"\x01\x05\x00") + + +def test_supported_transition_configuration() -> None: + """Brightness and colour temperature are advertised with their iids.""" + encoded = base64.b64decode(supported_transition_configuration(2, 4)) + assert encoded == bytes.fromhex("010601010202010100000106010104020102") + + +def test_parse_real_transition_control_write() -> None: + """A schedule from the Home app is parsed into a usable curve.""" + transition = parse_transition_control( + TRANSITION_CONTROL_WRITE, now_millis=NOW_MILLIS + ) + + assert transition is not None + assert len(transition.curve) == 42 + assert transition.update_interval == 60000 + assert transition.notify_threshold == 600000 + assert (transition.min_multiplier, transition.max_multiplier) == (10, 100) + assert len(transition.transition_id) == 16 + + +def test_interpolate_covers_a_full_day() -> None: + """The schedule walks a full day of colour temperatures. + + The Home app may send points slightly outside the advertised range of the + characteristic (it sent 509 mireds for a light advertising 500), which is + why the consumer clamps the interpolated value before writing it. + """ + transition = parse_transition_control( + TRANSITION_CONTROL_WRITE, now_millis=NOW_MILLIS + ) + assert transition is not None + + values = [] + for minutes in range(0, 24 * 60, 37): + value = interpolate(transition, NOW_MILLIS + minutes * 60000) + assert value is not None + assert 100 <= value <= 600 + values.append(value) + + assert max(values) - min(values) > 100 + assert interpolate(transition, NOW_MILLIS + 25 * 3600 * 1000) is None + + +def test_interpolate_returns_none_past_the_end() -> None: + """The schedule only covers 24 hours; afterwards there is nothing to apply.""" + transition = parse_transition_control( + TRANSITION_CONTROL_WRITE, now_millis=NOW_MILLIS + ) + assert transition is not None + assert interpolate(transition, NOW_MILLIS + 48 * 3600 * 1000) is None + assert interpolate_point(transition, NOW_MILLIS + 48 * 3600 * 1000) is None + + +def test_interpolate_point_interpolates_the_brightness_factor() -> None: + """The factor moves smoothly between points, like the temperature. + + A factor that stepped at each point would shift the colour by up to + factor * brightness mireds in a single update. + """ + transition = parse_transition_control( + TRANSITION_CONTROL_WRITE, now_millis=NOW_MILLIS + ) + assert transition is not None + + previous: tuple[float, float] | None = None + for minutes in range(24 * 60): + point = interpolate_point(transition, NOW_MILLIS + minutes * 60000) + assert point is not None + temperature, factor = point + if previous is not None: + shift = abs( + (temperature + factor * transition.max_multiplier) + - (previous[0] + previous[1] * transition.max_multiplier) + ) + assert shift < 10 + previous = point + assert interpolate(transition, NOW_MILLIS + minutes * 60000) == temperature + assert previous is not None + + +def test_transition_survives_serialization() -> None: + """A stored schedule is restored unchanged after a restart.""" + transition = parse_transition_control( + TRANSITION_CONTROL_WRITE, now_millis=NOW_MILLIS + ) + assert transition is not None + restored = ActiveTransition.from_dict(transition.to_dict()) + assert restored == transition + # The dict form is plain JSON so any backend can persist it. + stored = json.loads(json.dumps(transition.to_dict())) + assert ActiveTransition.from_dict(stored) == transition + + +def test_parse_rejects_an_empty_write() -> None: + """Clearing the characteristic does not produce a transition.""" + assert parse_transition_control(base64.b64encode(b"").decode()) is None + + +def _control_write(configuration: bytes) -> str: + """Wrap a configuration the way the Home app writes it.""" + return base64.b64encode( + encode_tlv(TAG_UPDATE_TRANSITION, encode_tlv(TAG_CFG_IID, configuration)) + ).decode() + + +def _curve_write( + entries: list[bytes], extra_config: list[int | bytes] | None = None +) -> str: + """Build a minimal update write around the given curve entries.""" + config: list[int | bytes] = [ + TAG_CFG_PARAMETERS, + encode_tlv( + TAG_PARAM_TRANSITION_ID, + b"\x00" * 16, + TAG_PARAM_START_TIME, + (1_700_000_000_000).to_bytes(8, "little"), + ), + TAG_CFG_UNKNOWN_3, + b"\x01", + TAG_CFG_CURVE, + encode_tlv_list(TAG_CURVE_ENTRY, entries), + ] + if extra_config: + config += extra_config + return _control_write(encode_tlv(*config)) + + +def _curve_point( + temperature: float, + factor: float, + offset: int = 0, + duration: int | None = None, +) -> bytes: + """Build one curve entry for _curve_write.""" + args: list[int | bytes] = [ + TAG_ENTRY_ADJUSTMENT_FACTOR, + struct.pack(" None: + """A wire entry's duration holds the previous point, like HAP-NodeJS.""" + write = _curve_write( + [ + _curve_point(300.0, -10.0, 0, None), + _curve_point(400.0, -20.0, 60_000, 30_000), + ] + ) + + transition = parse_transition_control(write, now_millis=NOW_MILLIS) + assert transition is not None + assert transition.curve[0].duration == 30_000 + assert transition.curve[1].duration == 0 + + # Inside the hold window the first point still applies exactly; without + # the shift the value would already be interpolating towards the second. + assert interpolate_point(transition, NOW_MILLIS + 15_000) == (300.0, -10.0) + assert interpolate_point(transition, NOW_MILLIS + 45_000) == (325.0, -12.5) + assert interpolate_point(transition, NOW_MILLIS + 60_000) == (350.0, -15.0) + + +def test_a_zero_update_interval_is_clamped() -> None: + """A zero interval would busy-loop the timer, so it is raised to the minimum.""" + write = _curve_write( + [_curve_point(300.0, -10.0), _curve_point(400.0, -20.0, 60_000)], + [TAG_CFG_UPDATE_INTERVAL, encode_variable_uint(0)], + ) + + transition = parse_transition_control(write, now_millis=NOW_MILLIS) + assert transition is not None + assert transition.update_interval == 1000 + + +def test_a_non_finite_curve_value_is_rejected() -> None: + """NaN or infinite curve values would poison every interpolation.""" + write = _curve_write( + [ + _curve_point(math.nan, -10.0), + _curve_point(400.0, -20.0, 60_000), + ] + ) + + with pytest.raises(ValueError, match="not finite"): + parse_transition_control(write, now_millis=NOW_MILLIS) + + +def test_parse_rejects_incomplete_schedules() -> None: + """A write that is not a complete schedule produces no transition.""" + curve = encode_tlv( + TAG_CURVE_ENTRY, + encode_tlv( + TAG_ENTRY_ADJUSTMENT_FACTOR, + b"\x00\x00\x00\x00", + TAG_ENTRY_VALUE, + b"\x00\x00\x7a\x43", + ), + ) + parameters = encode_tlv( + TAG_PARAM_TRANSITION_ID, + b"\x01" * 16, + TAG_PARAM_START_TIME, + b"\x00" * 8, + ) + + # A read request carries no update at all. + assert ( + parse_transition_control( + base64.b64encode(encode_tlv(0x01, b"\x00")).decode(), + now_millis=NOW_MILLIS, + ) + is None + ) + # An update without the parameters and the curve. + assert ( + parse_transition_control( + _control_write(encode_tlv(TAG_CFG_IID, b"\x0b")), + now_millis=NOW_MILLIS, + ) + is None + ) + # Parameters without the start time. + assert ( + parse_transition_control( + _control_write( + encode_tlv( + TAG_CFG_PARAMETERS, + encode_tlv(TAG_PARAM_TRANSITION_ID, b"\x01" * 16), + TAG_CFG_CURVE, + curve, + ) + ), + now_millis=NOW_MILLIS, + ) + is None + ) + # A curve needs two points to interpolate between. + assert ( + parse_transition_control( + _control_write( + encode_tlv(TAG_CFG_PARAMETERS, parameters, TAG_CFG_CURVE, curve) + ), + now_millis=NOW_MILLIS, + ) + is None + ) + + +def test_an_incomplete_curve_entry_is_skipped() -> None: + """A point that carries no value is dropped, the rest of the curve stands.""" + point = encode_tlv( + TAG_ENTRY_ADJUSTMENT_FACTOR, + b"\x00\x00\x00\x00", + TAG_ENTRY_VALUE, + b"\x00\x00\x7a\x43", + ) + schedule = _control_write( + encode_tlv( + TAG_CFG_PARAMETERS, + encode_tlv( + TAG_PARAM_TRANSITION_ID, + b"\x01" * 16, + TAG_PARAM_START_TIME, + b"\x00" * 8, + ), + TAG_CFG_CURVE, + encode_tlv_list( + TAG_CURVE_ENTRY, + [ + point, + encode_tlv(TAG_ENTRY_ADJUSTMENT_FACTOR, b"\x00\x00\x00\x00"), + point, + ], + ), + ) + ) + + transition = parse_transition_control(schedule, now_millis=NOW_MILLIS) + + assert transition is not None + assert len(transition.curve) == 2 + + +def test_parse_transition_update_handles_garbage() -> None: + """A truncated update payload returns None instead of raising.""" + assert parse_transition_update(b"\x05", now_millis=NOW_MILLIS) is None + assert parse_transition_update(b"", now_millis=NOW_MILLIS) is None + + +def test_first_tlv_value() -> None: + """The first matching record wins; missing tags give None.""" + entries = [(1, b"\xaa"), (2, b"\xbb"), (1, b"\xcc")] + assert first_tlv_value(entries, 1) == b"\xaa" + assert first_tlv_value(entries, 3) is None + + +def test_module_constants() -> None: + """The characteristic names match the HAP specification.""" + assert adaptive_lighting.ADAPTIVE_LIGHTING_CHARS == ( + "ActiveTransitionCount", + "TransitionControl", + "SupportedTransitionConfiguration", + ) From caaefb5b6b260845b5bbf798434cc98abcc7405e Mon Sep 17 00:00:00 2001 From: Adriano Valumin Date: Tue, 1 Dec 2026 18:50:14 -0300 Subject: [PATCH 2/9] Check the update record tag and document the TLV join heuristic parse_transition_update now looks up the configuration record by its TAG_CFG_IID tag instead of assuming it is the first record, so updates carrying extra records still parse. decode_ordered documents that rejoining same-tag chunks is a heuristic bounded by the 255-byte length rule and its inherent ambiguity. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- pyhap/adaptive_lighting.py | 6 ++--- pyhap/tlv.py | 9 ++++++++ tests/test_adaptive_lighting.py | 40 +++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py index 8b9a2d1b..0fdd16ef 100644 --- a/pyhap/adaptive_lighting.py +++ b/pyhap/adaptive_lighting.py @@ -238,10 +238,10 @@ def parse_transition_update( :param update: The TLV8 payload carried under the update tag. :param now_millis: The current time in unix millis; defaults to the wall clock. """ - outer = tlv.decode_ordered(update) - if not outer: + configuration_raw = first_tlv_value(tlv.decode_ordered(update), TAG_CFG_IID) + if configuration_raw is None: return None - configuration = tlv.decode_ordered(outer[0][1]) + configuration = tlv.decode_ordered(configuration_raw) parameters_raw = first_tlv_value(configuration, TAG_CFG_PARAMETERS) curve_raw = first_tlv_value(configuration, TAG_CFG_CURVE) if not parameters_raw or not curve_raw: diff --git a/pyhap/tlv.py b/pyhap/tlv.py index 0c3fbd84..7b53530a 100644 --- a/pyhap/tlv.py +++ b/pyhap/tlv.py @@ -118,6 +118,15 @@ def decode_ordered(data: bytes) -> list[tuple[int, bytes]]: longer than 255 bytes are split into chunks by :func:`encode`; chunks of the same tag are joined back together here. + The join is a heuristic, not a protocol feature: TLV8 has no + continuation marker, so a record is treated as the next chunk of the + previous one only when both share a tag, the previous value is + non-empty and its length is a multiple of 255. Two legitimate + consecutive records that happen to share a tag, the first with a + value length that is a multiple of 255, are merged into one — the + ambiguity is inherent to the format and callers must not rely on + same-tag adjacency surviving a decode/encode round trip. + :param data: The TLV-encoded bytes to decode. :type data: ``bytes`` diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py index 9b3a562c..8b70b86d 100644 --- a/tests/test_adaptive_lighting.py +++ b/tests/test_adaptive_lighting.py @@ -130,6 +130,22 @@ def test_decode_ordered_rejects_a_truncated_value() -> None: tlv.decode_ordered(b"\x01\x05\x00") +def test_decode_ordered_chunk_join_boundary() -> None: + """A same-tag record after a 255-byte value is always merged. + + TLV8 carries no continuation marker, so the decoder cannot tell a + chunk boundary from two real records: the previous value's length + being a multiple of 255 is the only signal. One byte shorter and the + records stay separate. + """ + value = bytes(range(256))[:255] + data = bytes([7, 255]) + value + bytes([7, 1, 0xAB]) + assert tlv.decode_ordered(data) == [(7, value + b"\xab")] + + data = bytes([7, 254]) + value[:-1] + bytes([7, 1, 0xAB]) + assert tlv.decode_ordered(data) == [(7, value[:-1]), (7, b"\xab")] + + def test_supported_transition_configuration() -> None: """Brightness and colour temperature are advertised with their iids.""" encoded = base64.b64decode(supported_transition_configuration(2, 4)) @@ -150,6 +166,30 @@ def test_parse_real_transition_control_write() -> None: assert len(transition.transition_id) == 16 +def test_parse_transition_update_skips_unexpected_records() -> None: + """Records ahead of the configuration one are ignored, not parsed.""" + configuration = encode_tlv( + TAG_CFG_PARAMETERS, + encode_tlv( + TAG_PARAM_TRANSITION_ID, + b"\x00" * 16, + TAG_PARAM_START_TIME, + (1_700_000_000_000).to_bytes(8, "little"), + ), + TAG_CFG_CURVE, + encode_tlv_list( + TAG_CURVE_ENTRY, + [_curve_point(300.0, 0.0), _curve_point(400.0, 0.0, 60_000)], + ), + ) + update = encode_tlv(0x7F, b"\x01\x02\xaa\xbb", TAG_CFG_IID, configuration) + + transition = parse_transition_update(update, now_millis=NOW_MILLIS) + + assert transition is not None + assert len(transition.curve) == 2 + + def test_interpolate_covers_a_full_day() -> None: """The schedule walks a full day of colour temperatures. From 263b060a0193c45b5a08777837193dfb3e28783c Mon Sep 17 00:00:00 2001 From: Adriano Valumin Date: Tue, 1 Dec 2026 17:40:37 -0300 Subject: [PATCH 3/9] Add AdaptiveLightingController service wiring Wires a Lightbulb service to the Adaptive Lighting protocol: obtains or creates the ActiveTransitionCount, TransitionControl and SupportedTransitionConfiguration characteristics, advertises the supported transition configuration with the real iids, decodes the schedules the Home app writes (arming, renewing and disabling via the configuration marker), answers read-current-transition requests with the stored schedule and reports elapsed time through an injectable clock. The active transition is kept on the controller for a follow-up that will evaluate and apply it; no timers, persistence or accessory writes are included yet. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- docs/source/api/adaptive_lighting.rst | 3 +- pyhap/adaptive_lighting.py | 270 +++++++++++++++++++++++++- tests/test_adaptive_lighting.py | 197 +++++++++++++++++++ 3 files changed, 467 insertions(+), 3 deletions(-) diff --git a/docs/source/api/adaptive_lighting.rst b/docs/source/api/adaptive_lighting.rst index e0336fd4..17516240 100644 --- a/docs/source/api/adaptive_lighting.rst +++ b/docs/source/api/adaptive_lighting.rst @@ -4,7 +4,8 @@ Adaptive Lighting ================== -Codec and interpolator for HomeKit Adaptive Lighting transition schedules. +Codec, interpolator and service wiring for HomeKit Adaptive Lighting +transition schedules. .. automodule:: pyhap.adaptive_lighting :members: diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py index 0fdd16ef..6ab57574 100644 --- a/pyhap/adaptive_lighting.py +++ b/pyhap/adaptive_lighting.py @@ -10,11 +10,14 @@ the reference behaviour of HAP-NodeJS: https://github.com/homebridge/HAP-NodeJS/blob/latest/src/lib/controller/AdaptiveLightingController.ts -This is protocol code only: scheduling evaluations, writing values to -accessories and persisting state are left to the consumer. +This is protocol code only: evaluating the schedule at a moment and +wiring it to the Lightbulb service is provided by +:class:`AdaptiveLightingController`; scheduling evaluations, writing +values to accessories and persisting state are left to the consumer. """ import base64 +from collections.abc import Callable from dataclasses import dataclass import logging import math @@ -23,6 +26,8 @@ from typing import Any from pyhap import tlv +from pyhap.characteristic import Characteristic +from pyhap.service import Service _LOGGER = logging.getLogger(__name__) @@ -74,6 +79,12 @@ TAG_ENTRY_TRANSITION_OFFSET = 0x03 TAG_ENTRY_DURATION = 0x04 +# ValueTransitionConfigurationResponse +TAG_RESPONSE_STATUS = 0x01 +TAG_STATUS_IID = 0x01 +TAG_STATUS_PARAMETERS = 0x02 +TAG_STATUS_TIME_SINCE_START = 0x03 + # HAP timestamps count from 2001-01-01, the Unix epoch counts from 1970-01-01. EPOCH_MILLIS_2001 = 978307200000 @@ -368,3 +379,258 @@ def interpolate(transition: ActiveTransition, now_millis: int) -> float | None: """Return the mired value for this moment, or None past the end of the curve.""" point = interpolate_point(transition, now_millis) return None if point is None else point[0] + + +class AdaptiveLightingController: + """Wire a Lightbulb service to the Adaptive Lighting protocol. + + Obtains (or creates) the ``ActiveTransitionCount``, + ``TransitionControl`` and ``SupportedTransitionConfiguration`` + characteristics on the service, decodes the schedules the Home app + writes to ``TransitionControl`` and keeps the active transition on + :attr:`transition` for the consumer to evaluate and apply. + + Scheduling evaluations, writing values to the accessory and + persisting the transition are intentionally left out; a follow-up + will add them on top of this wiring. + """ + + def __init__( + self, + service: Service, + *, + clock: Callable[[], int] | None = None, + ) -> None: + """Attach the adaptive lighting characteristics to ``service``. + + :param service: A Lightbulb ``Service`` already added to an + ``Accessory``; ``Brightness`` and ``ColorTemperature`` must be + present as their iids are advertised in the configuration. + :param clock: Callable returning the current unix time in millis; + defaults to the wall clock. Pass one to make the controller + deterministic in tests. + """ + self.service = service + self._now = clock or (lambda: int(time.time() * 1000)) + self.transition: ActiveTransition | None = None + + self.char_brightness = self._required_characteristic("Brightness") + self.char_color_temp = self._required_characteristic("ColorTemperature") + self.char_active_count = self._get_or_create_characteristic( + CHAR_ACTIVE_TRANSITION_COUNT + ) + self.char_control = self._get_or_create_characteristic(CHAR_TRANSITION_CONTROL) + self.char_supported = self._get_or_create_characteristic( + CHAR_SUPPORTED_TRANSITION_CONFIGURATION + ) + + self.char_supported.set_value( + supported_transition_configuration( + self._iid(self.char_brightness), self._iid(self.char_color_temp) + ), + should_notify=False, + ) + self.char_active_count.set_value(0, should_notify=False) + self.char_control.setter_callback = self._handle_transition_control_write + self.char_control.getter_callback = self._build_control_response + self.char_control.set_value("", should_notify=False) + + def _required_characteristic(self, name: str) -> Characteristic: + """Return a characteristic the adaptive lighting protocol needs.""" + try: + return self.service.get_characteristic(name) + except ValueError: + raise ValueError( + f"{name} is required for adaptive lighting; add it to the " + "Lightbulb service before creating the controller" + ) from None + + def _get_or_create_characteristic(self, name: str) -> Characteristic: + """Return the characteristic, creating it from the loader if absent.""" + try: + return self.service.get_characteristic(name) + except ValueError: + pass + accessory = self.service.broker + if accessory is None: + raise ValueError( + f"{name} is missing and the service is not attached to an accessory" + ) + char: Characteristic = accessory.driver.loader.get_char(name) + self.service.add_characteristic(char) + char.broker = accessory + accessory.iid_manager.assign(char) + return char + + def _iid(self, char: Characteristic) -> int: + """Return the iid the accessory assigned to a characteristic.""" + accessory = self.service.broker + assert accessory is not None # noqa: S101 - constructor requires it + iid = accessory.iid_manager.get_iid(char) + assert iid is not None # noqa: S101 + return iid + + def _handle_transition_control_write(self, value: str) -> str | None: + """Start, renew or stop the schedule the Home app just wrote. + + Returns the base64 TLV8 acknowledgement the controller expects back. + """ + if not value: + self.disable("TransitionControl was cleared") + return None + + try: + request = tlv.decode_ordered(base64.b64decode(value)) + except ValueError: + _LOGGER.exception("Could not decode the transition request") + return None + + responses: list[bytes] = [] + for tag, raw in request: + if tag == TAG_READ_CURRENT_TRANSITION: + if response := self._build_read_response(raw): + responses.append(encode_tlv(TAG_READ_CURRENT_TRANSITION, response)) + elif ( + tag == TAG_UPDATE_TRANSITION + and (response := self._handle_update_write(raw)) is not None + ): + responses.append(response) + + # client_update_value stored the raw request as the characteristic + # value; put the status of the running transition back. + self.char_control.value = self._build_control_response() + if not responses: + return None + return base64.b64encode(b"".join(responses)).decode() + + def _handle_update_write(self, update: bytes) -> bytes | None: + """Arm, renew or disable the schedule carried by an update write.""" + try: + outer = tlv.decode_ordered(update) + configuration = tlv.decode_ordered(outer[0][1]) if outer else [] + except (IndexError, ValueError): + _LOGGER.exception("Malformed transition update") + return None + + unknown_3 = first_tlv_value(configuration, TAG_CFG_UNKNOWN_3) + if not unknown_3 or unknown_3[0] == 0: + # Like the reference implementation, an update without the + # always-one marker is how the Home app disables adaptive + # lighting. + self.disable("Home app sent no transition configuration") + return encode_tlv(TAG_UPDATE_TRANSITION, b"") + + try: + transition = parse_transition_update(update, now_millis=self._now()) + except (IndexError, ValueError, struct.error): + _LOGGER.exception("Could not parse the transition schedule") + return None + + if transition is None: + _LOGGER.warning( + "Transition schedule is incomplete, keeping the current one" + ) + return None + + self._arm(transition) + return encode_tlv(TAG_UPDATE_TRANSITION, self._status_tlv()) + + def _build_read_response(self, read_request: bytes) -> bytes | None: + """Rebuild the stored schedule for a read-current-transition request.""" + transition = self.transition + if transition is None: + return None + + read_entries = tlv.decode_ordered(read_request) + if not read_entries: + return None + if ( + requested_iid := first_tlv_value(read_entries, TAG_CHARACTERISTIC_IID) + ) is not None and decode_variable_uint(requested_iid) != self._iid( + self.char_color_temp + ): + _LOGGER.warning("Read request for an unknown characteristic iid") + return None + + curve_entries = [] + previous_duration = 0 + for entry in transition.curve: + curve_entries.append( + encode_tlv( + TAG_ENTRY_ADJUSTMENT_FACTOR, + struct.pack(" None: + """Mark a schedule as the active transition.""" + self.transition = transition + self.char_active_count.set_value(1, should_notify=False) + self.char_control.value = self._build_control_response() + _LOGGER.debug( + "Adaptive lighting armed with %d curve points", + len(transition.curve), + ) + + def _status_tlv(self) -> bytes: + """The ValueTransitionConfigurationResponse TLV of the running transition.""" + if not (transition := self.transition): + return b"" + elapsed = self._now() - transition.time_millis_offset - transition.start_millis + return encode_tlv( + TAG_RESPONSE_STATUS, + encode_tlv( + TAG_STATUS_IID, + encode_variable_uint(self._iid(self.char_color_temp)), + TAG_STATUS_PARAMETERS, + transition.parameters, + TAG_STATUS_TIME_SINCE_START, + encode_variable_uint(max(0, elapsed)), + ), + ) + + def _build_control_response(self) -> str: + """Answer a control read with the status of the running transition.""" + return base64.b64encode(self._status_tlv()).decode() + + def disable(self, reason: str) -> None: + """Drop the active transition, as Apple expects on disable writes.""" + if self.transition is None: + return + _LOGGER.debug("Adaptive lighting disabled (%s)", reason) + self.transition = None + self.char_active_count.set_value(0, should_notify=False) + self.char_control.value = "" diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py index 8b70b86d..95110080 100644 --- a/tests/test_adaptive_lighting.py +++ b/tests/test_adaptive_lighting.py @@ -9,12 +9,14 @@ import pytest from pyhap import adaptive_lighting, tlv +from pyhap.accessory import Accessory from pyhap.adaptive_lighting import ( TAG_CFG_CURVE, TAG_CFG_IID, TAG_CFG_PARAMETERS, TAG_CFG_UNKNOWN_3, TAG_CFG_UPDATE_INTERVAL, + TAG_CHARACTERISTIC_IID, TAG_CURVE_ENTRY, TAG_ENTRY_ADJUSTMENT_FACTOR, TAG_ENTRY_DURATION, @@ -22,8 +24,13 @@ TAG_ENTRY_VALUE, TAG_PARAM_START_TIME, TAG_PARAM_TRANSITION_ID, + TAG_READ_CURRENT_TRANSITION, + TAG_RESPONSE_STATUS, + TAG_STATUS_IID, + TAG_STATUS_TIME_SINCE_START, TAG_UPDATE_TRANSITION, ActiveTransition, + AdaptiveLightingController, decode_variable_uint, encode_tlv, encode_tlv_list, @@ -479,3 +486,193 @@ def test_module_constants() -> None: "TransitionControl", "SupportedTransitionConfiguration", ) + + +# --- AdaptiveLightingController --------------------------------------------- + + +def _controller( + mock_driver: Any, + clock: Any = None, + extra_chars: list[str] | None = None, +) -> tuple[Accessory, AdaptiveLightingController]: + """Build a lightbulb accessory and its adaptive lighting controller.""" + acc = Accessory(mock_driver, "Test Light", aid=1) + service = acc.add_preload_service( + "Lightbulb", ["Brightness", "ColorTemperature", *(extra_chars or [])] + ) + return acc, AdaptiveLightingController(service, clock=clock or (lambda: NOW_MILLIS)) + + +def _iid(controller: AdaptiveLightingController, char: Any) -> int: + """Return the iid the accessory assigned to a characteristic.""" + accessory = controller.service.broker + assert accessory is not None # noqa: S101 + iid = accessory.iid_manager.get_iid(char) + assert iid is not None # noqa: S101 + return iid + + +def _status_response(value: str) -> dict[int, bytes]: + """Decode a base64 TransitionControl read response into its status tags.""" + outer = tlv.decode_ordered(base64.b64decode(value)) + status_tlv = first_tlv_value(outer, TAG_RESPONSE_STATUS) + assert status_tlv is not None + status = tlv.decode_ordered(status_tlv) + return dict(status) + + +def test_controller_creates_the_adaptive_characteristics(mock_driver: Any) -> None: + """The three characteristics are created when the service lacks them.""" + _, controller = _controller(mock_driver) + for name in adaptive_lighting.ADAPTIVE_LIGHTING_CHARS: + assert controller.service.get_characteristic(name) is not None + assert controller.char_supported.value == supported_transition_configuration( + _iid(controller, controller.char_brightness), + _iid(controller, controller.char_color_temp), + ) + assert controller.char_active_count.value == 0 + assert controller.char_control.value == "" + + +def test_controller_reuses_existing_characteristics(mock_driver: Any) -> None: + """Characteristics the service already has are wired, not duplicated.""" + _, controller = _controller( + mock_driver, extra_chars=list(adaptive_lighting.ADAPTIVE_LIGHTING_CHARS) + ) + names = [char.display_name for char in controller.service.characteristics] + for name in adaptive_lighting.ADAPTIVE_LIGHTING_CHARS: + assert names.count(name) == 1 + + +def test_controller_requires_colour_temperature(mock_driver: Any) -> None: + """The configuration advertises iids that must already exist.""" + acc = Accessory(mock_driver, "Bare Light", aid=1) + service = acc.add_preload_service("Lightbulb") + with pytest.raises(ValueError, match="required for adaptive lighting"): + AdaptiveLightingController(service) + + +def test_controller_arms_a_transition_on_update_write(mock_driver: Any) -> None: + """A real Home app write arms the transition and returns an ack.""" + _, controller = _controller(mock_driver) + response = controller.char_control.client_update_value(TRANSITION_CONTROL_WRITE) + + assert controller.transition is not None + assert controller.transition.curve + assert controller.char_active_count.value == 1 + assert response is not None + + outer = tlv.decode_ordered(base64.b64decode(response)) + assert [tag for tag, _ in outer] == [TAG_UPDATE_TRANSITION] + status = _status_response(base64.b64encode(outer[0][1]).decode()) + assert first_tlv_value( + [(TAG_STATUS_IID, status[TAG_STATUS_IID])], TAG_STATUS_IID + ) == encode_variable_uint(_iid(controller, controller.char_color_temp)) + assert decode_variable_uint(status[TAG_STATUS_TIME_SINCE_START]) == 0 + + +def test_controller_counts_elapsed_time_with_the_injected_clock( + mock_driver: Any, +) -> None: + """Reads report the time since the schedule started, not a frozen value.""" + now = [NOW_MILLIS] + _, controller = _controller(mock_driver, clock=lambda: now[0]) + controller.char_control.client_update_value(TRANSITION_CONTROL_WRITE) + + now[0] += 5000 + status = _status_response(controller.char_control.get_value()) + assert decode_variable_uint(status[TAG_STATUS_TIME_SINCE_START]) == 5000 + + +def test_controller_answers_a_read_current_transition_request( + mock_driver: Any, +) -> None: + """A read request rebuilds the stored schedule for the Home app.""" + _, controller = _controller(mock_driver) + controller.char_control.client_update_value(TRANSITION_CONTROL_WRITE) + + color_temp_iid = _iid(controller, controller.char_color_temp) + request = base64.b64encode( + encode_tlv( + TAG_READ_CURRENT_TRANSITION, + encode_tlv(TAG_CHARACTERISTIC_IID, encode_variable_uint(color_temp_iid)), + ) + ).decode() + response = controller.char_control.client_update_value(request) + + assert response is not None + outer = tlv.decode_ordered(base64.b64decode(response)) + assert [tag for tag, _ in outer] == [TAG_READ_CURRENT_TRANSITION] + rebuilt = tlv.decode_ordered(outer[0][1]) + assert first_tlv_value(rebuilt, TAG_CFG_PARAMETERS) is not None + assert first_tlv_value(rebuilt, TAG_CFG_CURVE) is not None + assert first_tlv_value(rebuilt, TAG_CFG_UPDATE_INTERVAL) is not None + + +def test_controller_ignores_a_read_for_another_iid(mock_driver: Any) -> None: + """A read request for an unknown characteristic gets no response.""" + _, controller = _controller(mock_driver) + controller.char_control.client_update_value(TRANSITION_CONTROL_WRITE) + + request = base64.b64encode( + encode_tlv( + TAG_READ_CURRENT_TRANSITION, + encode_tlv(TAG_CHARACTERISTIC_IID, encode_variable_uint(4000)), + ) + ).decode() + assert controller.char_control.client_update_value(request) is None + + +def test_controller_disables_when_the_marker_is_missing(mock_driver: Any) -> None: + """An update without the always-one marker disables adaptive lighting.""" + _, controller = _controller(mock_driver) + controller.char_control.client_update_value(TRANSITION_CONTROL_WRITE) + assert controller.transition is not None + + start = 1_700_000_000_000 + config = encode_tlv( + TAG_CFG_PARAMETERS, + encode_tlv( + TAG_PARAM_TRANSITION_ID, + b"\x00" * 16, + TAG_PARAM_START_TIME, + start.to_bytes(8, "little"), + ), + TAG_CFG_CURVE, + encode_tlv_list( + TAG_CURVE_ENTRY, + [ + _curve_point(300.0, 1.0), + _curve_point(400.0, 1.0, duration=60), + ], + ), + ) + write = base64.b64encode( + encode_tlv(TAG_UPDATE_TRANSITION, encode_tlv(TAG_CFG_IID, config)) + ).decode() + response = controller.char_control.client_update_value(write) + + assert controller.transition is None + assert controller.char_active_count.value == 0 + assert response == base64.b64encode(encode_tlv(TAG_UPDATE_TRANSITION, b"")).decode() + + +def test_controller_disables_on_an_empty_write(mock_driver: Any) -> None: + """Clearing the characteristic stops the transition.""" + _, controller = _controller(mock_driver) + controller.char_control.client_update_value(TRANSITION_CONTROL_WRITE) + + assert controller.char_control.client_update_value("") is None + assert controller.transition is None + assert controller.char_active_count.value == 0 + assert controller.char_control.get_value() == "" + + +def test_controller_survives_a_malformed_write(mock_driver: Any) -> None: + """Garbage in the characteristic does not kill the controller.""" + _, controller = _controller(mock_driver) + controller.char_control.client_update_value(TRANSITION_CONTROL_WRITE) + + assert controller.char_control.client_update_value("not base64!!") is None + assert controller.transition is not None From 8b1fd1dee5ded96eb32bdfbb6f441c845c6e2386 Mon Sep 17 00:00:00 2001 From: Adriano Valumin Date: Tue, 1 Dec 2026 17:54:17 -0300 Subject: [PATCH 4/9] Add the adaptive lighting update loop Evaluate the armed curve on the consumer's event loop: the controller applies the interpolated colour temperature, shifted by the brightness adjustment factor and clamped to the characteristic range, through an on_apply_temperature callback once per update interval, deduplicating unchanged mireds. Disabling, reaching the end of the curve or stop() cancel the timer, and a client write to ColorTemperature disarms the schedule while still reaching the consumer's own setter. Persistence remains with the consumer. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- pyhap/adaptive_lighting.py | 160 +++++++++++++++++-- tests/test_adaptive_lighting.py | 268 +++++++++++++++++++++++++++++++- 2 files changed, 418 insertions(+), 10 deletions(-) diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py index 6ab57574..11b88563 100644 --- a/pyhap/adaptive_lighting.py +++ b/pyhap/adaptive_lighting.py @@ -19,11 +19,12 @@ import base64 from collections.abc import Callable from dataclasses import dataclass +import inspect import logging import math import struct import time -from typing import Any +from typing import Any, Protocol from pyhap import tlv from pyhap.characteristic import Characteristic @@ -92,6 +93,20 @@ MIN_UPDATE_INTERVAL = 1000 +class _UpdateTimer(Protocol): + """The part of an ``asyncio`` timer handle the controller uses.""" + + def cancel(self) -> None: ... + + +class _UpdateLoop(Protocol): + """The part of an event loop the controller uses to schedule updates.""" + + def call_later( + self, delay: float, callback: Callable[..., Any], *args: Any + ) -> _UpdateTimer: ... + + def encode_variable_uint(value: int) -> bytes: """Encode an unsigned int in the smallest little-endian width HAP accepts.""" if value < 0: @@ -382,17 +397,26 @@ def interpolate(transition: ActiveTransition, now_millis: int) -> float | None: class AdaptiveLightingController: - """Wire a Lightbulb service to the Adaptive Lighting protocol. + """Drive a Lightbulb service from the schedule the Home app sends. Obtains (or creates) the ``ActiveTransitionCount``, ``TransitionControl`` and ``SupportedTransitionConfiguration`` characteristics on the service, decodes the schedules the Home app writes to ``TransitionControl`` and keeps the active transition on - :attr:`transition` for the consumer to evaluate and apply. - - Scheduling evaluations, writing values to the accessory and - persisting the transition are intentionally left out; a follow-up - will add them on top of this wiring. + :attr:`transition`. + + While a transition is armed the controller evaluates the curve every + ``update_interval`` on the given event loop and reports the resulting + colour temperature, in mireds, through ``on_apply_temperature``. The + consumer is responsible for writing the value to the accessory and + for notifying subscribers; persisting the transition across restarts + is also left to the consumer. + + Create the controller after the service characteristics are + configured: the ``ColorTemperature`` setter callback is wrapped so a + colour temperature written by a paired controller disarms adaptive + lighting, like Apple expects. Local ``set_value`` calls do not run + setter callbacks, so the controller's own applies never disarm it. """ def __init__( @@ -400,6 +424,8 @@ def __init__( service: Service, *, clock: Callable[[], int] | None = None, + loop: _UpdateLoop | None = None, + on_apply_temperature: Callable[[int], None] | None = None, ) -> None: """Attach the adaptive lighting characteristics to ``service``. @@ -409,10 +435,22 @@ def __init__( :param clock: Callable returning the current unix time in millis; defaults to the wall clock. Pass one to make the controller deterministic in tests. + :param loop: Event loop used to schedule the periodic curve + evaluation. Without it the transition is still decoded and + reported but never applied. + :param on_apply_temperature: Called with the mireds value the + curve asks for, once when the schedule arms and then on every + update interval until it is disabled or ends. """ self.service = service self._now = clock or (lambda: int(time.time() * 1000)) + self._loop = loop + self._on_apply_temperature = on_apply_temperature self.transition: ActiveTransition | None = None + self.applying = False + self._stopped = False + self._last_applied: int | None = None + self._update_timer: _UpdateTimer | None = None self.char_brightness = self._required_characteristic("Brightness") self.char_color_temp = self._required_characteristic("ColorTemperature") @@ -434,6 +472,32 @@ def __init__( self.char_control.setter_callback = self._handle_transition_control_write self.char_control.getter_callback = self._build_control_response self.char_control.set_value("", should_notify=False) + self._wrap_color_temp_setter() + + def _wrap_color_temp_setter(self) -> None: + """Disarm adaptive lighting when the client writes the colour itself. + + The wrapper forwards the write to the setter the consumer had + configured, preserving a ``sender_client_addr`` parameter when the + original setter declares one. + """ + previous = self.char_color_temp.setter_callback + try: + parameters = inspect.signature(previous).parameters if previous else {} + except (TypeError, ValueError): + parameters = {} + wants_addr = "sender_client_addr" in parameters + + def setter(value: Any, sender_client_addr: Any = None) -> Any: + if not self.applying: + self.disable("manual colour change") + if previous is None: + return None + if wants_addr: + return previous(value, sender_client_addr) + return previous(value) + + self.char_color_temp.setter_callback = setter def _required_characteristic(self, name: str) -> Characteristic: """Return a characteristic the adaptive lighting protocol needs.""" @@ -596,14 +660,81 @@ def _build_read_response(self, read_request: bytes) -> bytes | None: ) def _arm(self, transition: ActiveTransition) -> None: - """Mark a schedule as the active transition.""" + """Start applying a schedule, whether it just arrived or was renewed.""" + self._stopped = False self.transition = transition self.char_active_count.set_value(1, should_notify=False) self.char_control.value = self._build_control_response() _LOGGER.debug( - "Adaptive lighting armed with %d curve points", + "Adaptive lighting armed with %d curve points, updating every %dms", len(transition.curve), + transition.update_interval, + ) + + self._cancel_update_timer() + if self._loop is None: + return + self._update() + self._schedule_next_update() + + def _schedule_next_update(self) -> None: + """Arm the timer for the next curve evaluation, if still running.""" + if ( + self._loop is None + or self._stopped + or self.transition is None + or self._update_timer is not None + ): + return + interval = max(self.transition.update_interval, MIN_UPDATE_INTERVAL) / 1000 + self._update_timer = self._loop.call_later(interval, self._tick) + + def _cancel_update_timer(self) -> None: + """Cancel a pending curve evaluation, if any.""" + if self._update_timer is not None: + self._update_timer.cancel() + self._update_timer = None + + def _tick(self) -> None: + """Evaluate the curve and reschedule while the transition runs.""" + self._update_timer = None + self._update() + self._schedule_next_update() + + def _update(self) -> None: + """Apply the point of the curve that belongs to this moment.""" + if self._stopped or (transition := self.transition) is None: + return + + point = interpolate_point(transition, self._now()) + if point is None: + self.disable("reached the end of the curve") + return + temperature, adjustment_factor = point + + # Apple sends a factor that shifts the colour with the brightness level. + brightness = self.char_brightness.value or transition.max_multiplier + multiplier = min( + transition.max_multiplier, max(transition.min_multiplier, brightness) ) + temperature += adjustment_factor * multiplier + + mireds = round(temperature) + properties = self.char_color_temp.properties + mireds = min( + properties.get("maxValue", 500), + max(properties.get("minValue", 140), mireds), + ) + + if self._on_apply_temperature is None or self._last_applied == mireds: + return + self._last_applied = mireds + _LOGGER.debug("Adaptive lighting applying %d mireds", mireds) + self.applying = True + try: + self._on_apply_temperature(mireds) + finally: + self.applying = False def _status_tlv(self) -> bytes: """The ValueTransitionConfigurationResponse TLV of the running transition.""" @@ -632,5 +763,16 @@ def disable(self, reason: str) -> None: return _LOGGER.debug("Adaptive lighting disabled (%s)", reason) self.transition = None + self._last_applied = None + self.stop() self.char_active_count.set_value(0, should_notify=False) self.char_control.value = "" + + def stop(self) -> None: + """Cancel the update timer but keep the transition for status reads. + + Called when the accessory is torn down. A later schedule write arms + the controller again. + """ + self._stopped = True + self._cancel_update_timer() diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py index 95110080..92a7ab93 100644 --- a/tests/test_adaptive_lighting.py +++ b/tests/test_adaptive_lighting.py @@ -495,13 +495,20 @@ def _controller( mock_driver: Any, clock: Any = None, extra_chars: list[str] | None = None, + loop: Any = None, + on_apply_temperature: Any = None, ) -> tuple[Accessory, AdaptiveLightingController]: """Build a lightbulb accessory and its adaptive lighting controller.""" acc = Accessory(mock_driver, "Test Light", aid=1) service = acc.add_preload_service( "Lightbulb", ["Brightness", "ColorTemperature", *(extra_chars or [])] ) - return acc, AdaptiveLightingController(service, clock=clock or (lambda: NOW_MILLIS)) + return acc, AdaptiveLightingController( + service, + clock=clock or (lambda: NOW_MILLIS), + loop=loop, + on_apply_temperature=on_apply_temperature, + ) def _iid(controller: AdaptiveLightingController, char: Any) -> int: @@ -676,3 +683,262 @@ def test_controller_survives_a_malformed_write(mock_driver: Any) -> None: assert controller.char_control.client_update_value("not base64!!") is None assert controller.transition is not None + + +# --- AdaptiveLightingController update loop ---------------------------------- + + +class _FakeTimer: + """Minimal stand-in for an asyncio timer handle.""" + + def __init__(self, callback: Any) -> None: + self.callback = callback + self.delay: float | None = None + self._cancelled = False + + def cancel(self) -> None: + self._cancelled = True + + def cancelled(self) -> bool: + return self._cancelled + + +class _FakeLoop: + """Captures call_later timers so tests fire ticks manually.""" + + def __init__(self) -> None: + self.pending: list[_FakeTimer] = [] + + def call_later(self, delay: float, callback: Any, *args: Any) -> _FakeTimer: + timer = _FakeTimer(lambda: callback(*args)) + timer.delay = delay + self.pending.append(timer) + return timer + + def run_next(self) -> None: + """Fire the oldest pending timer.""" + timer = self.pending.pop(0) + assert not timer.cancelled() # noqa: S101 + timer.callback() + + +def _looped_controller( + mock_driver: Any, + applied: list[int], + now: list[int], +) -> tuple[_FakeLoop, AdaptiveLightingController]: + """Build a controller with a fake loop and a recording apply callback.""" + loop = _FakeLoop() + _, controller = _controller( + mock_driver, + clock=lambda: now[0], + loop=loop, + on_apply_temperature=applied.append, + ) + return loop, controller + + +def _ramp_write() -> str: + """A two point curve ramping 300 to 400 mireds over 60 seconds.""" + return _curve_write( + [ + _curve_point(300.0, 0.0), + _curve_point(400.0, 0.0, 60_000), + ], + [TAG_CFG_UPDATE_INTERVAL, encode_variable_uint(1000)], + ) + + +def test_controller_applies_the_curve_once_on_arm(mock_driver: Any) -> None: + """Arming evaluates the curve immediately and schedules the next tick.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + + controller.char_control.client_update_value(_ramp_write()) + + assert applied == [300] + timer = controller._update_timer + assert isinstance(timer, _FakeTimer) # noqa: S101 + assert timer.delay == 1.0 + assert len(loop.pending) == 1 + + +def test_controller_ticks_apply_new_points_and_reschedule(mock_driver: Any) -> None: + """Each tick evaluates the curve at the current time and re-arms.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + controller.char_control.client_update_value(_ramp_write()) + + now[0] += 30_000 + loop.run_next() + + assert applied == [300, 350] + assert controller._update_timer is not None + assert len(loop.pending) == 1 + + +def test_controller_does_not_reapply_the_same_point(mock_driver: Any) -> None: + """A tick that lands on the same mireds does not write again.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + controller.char_control.client_update_value(_ramp_write()) + + loop.run_next() + loop.run_next() + + assert applied == [300] + + +def test_controller_disables_at_the_end_of_the_curve(mock_driver: Any) -> None: + """Running past the last curve point disables adaptive lighting.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + controller.char_control.client_update_value(_ramp_write()) + + now[0] += 60_001 + loop.run_next() + + assert controller.transition is None + assert controller.char_active_count.value == 0 + assert controller._update_timer is None + assert len(loop.pending) == 0 + + +def test_controller_disable_cancels_the_timer(mock_driver: Any) -> None: + """Disabling stops the schedule instead of leaving a dangling timer.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + controller.char_control.client_update_value(_ramp_write()) + assert controller._update_timer is not None + + controller.char_control.client_update_value("") + + assert controller.transition is None + assert controller._update_timer is None + assert loop.pending[0].cancelled() + + +def test_controller_stop_cancels_the_timer_but_keeps_the_transition( + mock_driver: Any, +) -> None: + """Tearing down pauses updates without dropping the reported status.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + controller.char_control.client_update_value(_ramp_write()) + + controller.stop() + + assert controller.transition is not None + assert controller._update_timer is None + assert controller.char_control.get_value() != "" + + now[0] += 30_000 + assert applied == [300] + + +def test_controller_clamps_mireds_to_the_characteristic_range( + mock_driver: Any, +) -> None: + """Values outside 140-500 are clamped to the characteristic range.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + controller.char_control.client_update_value( + _curve_write( + [ + _curve_point(600.0, 0.0), + _curve_point(600.0, 0.0, 60_000), + ] + ) + ) + assert applied == [500] + + controller.disable("test") + applied.clear() + controller.char_control.client_update_value( + _curve_write( + [ + _curve_point(100.0, 0.0), + _curve_point(100.0, 0.0, 60_000), + ] + ) + ) + assert applied == [140] + + +def test_controller_applies_the_brightness_adjustment_factor( + mock_driver: Any, +) -> None: + """The curve factor shifts the temperature by the current brightness.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + controller.char_brightness.set_value(50, should_notify=False) + + controller.char_control.client_update_value( + _curve_write( + [ + _curve_point(300.0, 1.0), + _curve_point(300.0, 1.0, 60_000), + ] + ) + ) + + # multiplier = clamp(50, 10, 100) = 50 -> 300 + 1.0 * 50 = 350 + assert applied == [350] + + +def test_controller_client_colour_write_disarms_and_forwards( + mock_driver: Any, +) -> None: + """A client write to ColorTemperature disables and reaches the old setter.""" + acc = Accessory(mock_driver, "Test Light", aid=1) + service = acc.add_preload_service("Lightbulb", ["Brightness", "ColorTemperature"]) + received: list[int] = [] + service.configure_char("ColorTemperature", setter_callback=received.append) + now = [NOW_MILLIS] + loop = _FakeLoop() + applied: list[int] = [] + controller = AdaptiveLightingController( + service, clock=lambda: now[0], loop=loop, on_apply_temperature=applied.append + ) + controller.char_control.client_update_value(_ramp_write()) + assert controller.transition is not None + + controller.char_color_temp.client_update_value(400) + + assert controller.transition is None + assert controller.char_active_count.value == 0 + assert controller._update_timer is None + assert received == [400] + + +def test_controller_own_apply_does_not_disarm(mock_driver: Any) -> None: + """The controller's own colour writes keep the schedule running.""" + acc = Accessory(mock_driver, "Test Light", aid=1) + service = acc.add_preload_service("Lightbulb", ["Brightness", "ColorTemperature"]) + received: list[int] = [] + service.configure_char("ColorTemperature", setter_callback=received.append) + now = [NOW_MILLIS] + applied: list[int] = [] + + def apply(mireds: int) -> None: + applied.append(mireds) + controller.char_color_temp.set_value(mireds, should_notify=False) + + controller = AdaptiveLightingController( + service, + clock=lambda: now[0], + loop=_FakeLoop(), + on_apply_temperature=apply, + ) + controller.char_control.client_update_value(_ramp_write()) + + assert controller.transition is not None + assert received == [] From d4d3e3cb1efc58bb0ed7baf5251a6e9ad45b6909 Mon Sep 17 00:00:00 2001 From: Adriano Valumin Date: Tue, 1 Dec 2026 18:04:12 -0300 Subject: [PATCH 5/9] Persist adaptive lighting transitions and refresh the example The controller now saves the active transition into the accessory state on arm and clears it on disable, and restore() re-arms a still valid schedule after a restart, discarding expired or unreadable payloads. The adaptive_lightbulb example is rewritten on top of AdaptiveLightingController instead of the stale external tlv8 package, and the docs cover the new persistence hook. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- accessories/adaptive_lightbulb.py | 110 ++++++++++++------------------ docs/source/advanced/state.rst | 14 ++++ docs/source/intro/examples.rst | 9 ++- pyhap/adaptive_lighting.py | 66 +++++++++++++++++- tests/conftest.py | 8 +++ tests/test_adaptive_lighting.py | 98 ++++++++++++++++++++++++++ 6 files changed, 234 insertions(+), 71 deletions(-) diff --git a/accessories/adaptive_lightbulb.py b/accessories/adaptive_lightbulb.py index 3fd4aee0..9c1f0cd3 100644 --- a/accessories/adaptive_lightbulb.py +++ b/accessories/adaptive_lightbulb.py @@ -1,93 +1,71 @@ -"""This virtual lightbulb implements the bare minimum needed for HomeKit - controller to recognize it as having AdaptiveLightning +"""This virtual lightbulb implements Adaptive Lighting. + +It drives the Lightbulb service with ``AdaptiveLightingController``: the +Home app sends the 24 hour colour curve and the controller applies it. """ + import logging import signal -import random -import tlv8 -import base64 +from typing import Any from pyhap.accessory import Accessory from pyhap.accessory_driver import AccessoryDriver -from pyhap.const import (CATEGORY_LIGHTBULB, - HAP_REPR_IID) -from pyhap.loader import get_loader - -# Define tlv8 Keys and Values -SUPPORTED_TRANSITION_CONFIGURATION = 1 -CHARACTERISTIC_IID = 1 -TRANSITION_TYPE = 2 - -BRIGHTNESS = 1 -COLOR_TEMPERATURE = 2 +from pyhap.adaptive_lighting import AdaptiveLightingController +from pyhap.const import CATEGORY_LIGHTBULB logging.basicConfig(level=logging.DEBUG, format="[%(module)s] %(message)s") -def bytes_to_base64_string(value: bytes) -> str: - return base64.b64encode(value).decode('ASCII') class LightBulb(Accessory): - """Fake lightbulb, logs what the client sets.""" + """Fake adaptive lightbulb, logs what the client sets.""" category = CATEGORY_LIGHTBULB - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - serv_light = self.add_preload_service('Lightbulb', [ - # The names here refer to the Characteristic name defined - # in characteristic.json - "Brightness", - "ColorTemperature", - "ActiveTransitionCount", - "TransitionControl", - "SupportedTransitionConfiguration"]) - - self.char_on = serv_light.configure_char( - 'On', setter_callback=self.set_on) + serv_light = self.add_preload_service( + "Lightbulb", ["On", "Brightness", "ColorTemperature"] + ) + + self.char_on = serv_light.configure_char("On", setter_callback=self.set_on) self.char_br = serv_light.configure_char( - 'Brightness', setter_callback=self.set_brightness) + "Brightness", setter_callback=self.set_brightness + ) self.char_ct = serv_light.configure_char( - 'ColorTemperature', setter_callback=self.set_ct, value=140) - - # Via this structure we advertise to the controller that we are - # capable of autonomous transitions between states on brightness - # and color temperature. - supported_transitions = [tlv8.Entry(SUPPORTED_TRANSITION_CONFIGURATION, [ - tlv8.Entry(CHARACTERISTIC_IID, self.char_br.to_HAP()[HAP_REPR_IID]), - tlv8.Entry(TRANSITION_TYPE, BRIGHTNESS), - tlv8.Entry(CHARACTERISTIC_IID, self.char_ct.to_HAP()[HAP_REPR_IID]), - tlv8.Entry(TRANSITION_TYPE, COLOR_TEMPERATURE) - ])] - - bytes_data = tlv8.encode(supported_transitions) - b64str = bytes_to_base64_string(bytes_data) - - self.char_atc = serv_light.configure_char( - 'ActiveTransitionCount', setter_callback=self.set_atc) - self.char_tc = serv_light.configure_char( - 'TransitionControl', setter_callback=self.set_tc) - self.char_stc = serv_light.configure_char( - 'SupportedTransitionConfiguration', - value=b64str) - - def set_on(self, value): + "ColorTemperature", setter_callback=self.set_ct, value=140 + ) + + # Wire the adaptive lighting characteristics and the update loop. + # The controller wraps the ColorTemperature setter, so a manual + # colour change from the Home app disarms the schedule. + self.adaptive_lighting = AdaptiveLightingController( + serv_light, + loop=self.driver.loop, + on_apply_temperature=self._apply_temperature, + ) + + def _apply_temperature(self, mireds: int) -> None: + """Write the colour temperature the curve asks for.""" + logging.info("Adaptive lighting applies %d mireds", mireds) + self.char_ct.set_value(mireds) + self.char_ct.notify() + + def set_on(self, value: Any) -> None: logging.info("Write On State: %s", value) - def set_ct(self, value): + def set_ct(self, value: Any) -> None: logging.info("Bulb color temp: %s", value) - def set_atc(self, value): - logging.info("Write to ActiveTransactionCount: %s", value) + def set_brightness(self, value: Any) -> None: + logging.info("Bulb brightness: %s", value) - def set_tc(self, value): - logging.info("Write to TransitionControl: %s", value) + def restore_accessory_state(self) -> None: + """Resume the adaptive lighting schedule saved before a restart.""" + self.adaptive_lighting.restore() - def set_brightness(self, value): - logging.info("Bulb brightness: %s", value) -driver = AccessoryDriver(port=51826, persist_file='adaptive_lightbulb.state') -driver.add_accessory(accessory=LightBulb(driver, 'Lightbulb')) +driver = AccessoryDriver(port=51826, persist_file="adaptive_lightbulb.state") +driver.add_accessory(accessory=LightBulb(driver, "Lightbulb")) signal.signal(signal.SIGTERM, driver.signal_handler) driver.start() - diff --git a/docs/source/advanced/state.rst b/docs/source/advanced/state.rst index 0ba59d8c..4ff34275 100644 --- a/docs/source/advanced/state.rst +++ b/docs/source/advanced/state.rst @@ -119,6 +119,20 @@ selection, unless its supported recording configuration changed. The 17.99 values a controller writes, like the global operating mode and the motion zones, are kept as well. A new home resets all of it. +What an adaptive lighting controller keeps +========================================== + +The :class:`~pyhap.adaptive_lighting.AdaptiveLightingController` stores the +active transition schedule under its AID in the ``adaptive_lighting`` key +every time the Home app arms or disables it, through the usual +``driver.accessory_state``/``async_persist`` pair. On restart the consumer +calls :meth:`AdaptiveLightingController.restore +` — typically +from ``Accessory.restore_accessory_state`` — which re-arms the schedule and +its update loop, unless the curve already ended or the stored value is +unreadable, in which case it is discarded. See +:ref:`api-adaptive-lighting` and the ``adaptive_lightbulb.py`` example. + A new home must not inherit the old one ======================================= diff --git a/docs/source/intro/examples.rst b/docs/source/intro/examples.rst index 28c11d2e..bb1e43eb 100644 --- a/docs/source/intro/examples.rst +++ b/docs/source/intro/examples.rst @@ -23,9 +23,12 @@ device. setter callbacks driving the state. * - ``TemperatureSensor.py`` - A sensor reporting a value periodically from ``run``. - * - ``MotionSensor.py``, ``adaptive_lightbulb.py`` - - A sensor that triggers characteristics on motion; a light that - changes its value from a background ``run`` task. + * - ``MotionSensor.py`` + - A sensor that triggers characteristics on motion. + * - ``adaptive_lightbulb.py`` + - A light driven by ``AdaptiveLightingController``: the Home app's + colour curve is decoded, interpolated every update interval and + applied, surviving restarts through the accessory state. * - ``TV.py``, ``FakeFan.py``, ``DisplaySwitch.py`` - TVs, fans and switches: services with several linked characteristics. * - ``AudioReceiver.py`` diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py index 11b88563..918acf15 100644 --- a/pyhap/adaptive_lighting.py +++ b/pyhap/adaptive_lighting.py @@ -24,12 +24,15 @@ import math import struct import time -from typing import Any, Protocol +from typing import TYPE_CHECKING, Any, Protocol from pyhap import tlv from pyhap.characteristic import Characteristic from pyhap.service import Service +if TYPE_CHECKING: + from pyhap.accessory import Accessory + _LOGGER = logging.getLogger(__name__) CHAR_ACTIVE_TRANSITION_COUNT = "ActiveTransitionCount" @@ -92,6 +95,9 @@ # An update interval of zero would reschedule the timer immediately forever. MIN_UPDATE_INTERVAL = 1000 +# Key of the saved transition inside ``driver.accessory_state(aid)``. +STATE_KEY = "adaptive_lighting" + class _UpdateTimer(Protocol): """The part of an ``asyncio`` timer handle the controller uses.""" @@ -659,7 +665,7 @@ def _build_read_response(self, read_request: bytes) -> bytes | None: encode_variable_uint(transition.notify_threshold), ) - def _arm(self, transition: ActiveTransition) -> None: + def _arm(self, transition: ActiveTransition, *, persist: bool = True) -> None: """Start applying a schedule, whether it just arrived or was renewed.""" self._stopped = False self.transition = transition @@ -670,6 +676,8 @@ def _arm(self, transition: ActiveTransition) -> None: len(transition.curve), transition.update_interval, ) + if persist: + self._persist_transition() self._cancel_update_timer() if self._loop is None: @@ -764,6 +772,7 @@ def disable(self, reason: str) -> None: _LOGGER.debug("Adaptive lighting disabled (%s)", reason) self.transition = None self._last_applied = None + self._persist_transition() self.stop() self.char_active_count.set_value(0, should_notify=False) self.char_control.value = "" @@ -776,3 +785,56 @@ def stop(self) -> None: """ self._stopped = True self._cancel_update_timer() + + def _persist_transition(self) -> None: + """Save the active transition, or clear it, in the accessory state.""" + accessory = self.service.broker + if accessory is None or accessory.aid is None: + return + state = accessory.driver.accessory_state(accessory.aid) + if self.transition is None: + state.pop(STATE_KEY, None) + else: + state[STATE_KEY] = self.transition.to_dict() + accessory.driver.async_persist() + + def restore(self) -> None: + """Re-arm the transition persisted before the last restart. + + The consumer calls this once the accessory state is loaded, e.g. + from ``Accessory.restore_accessory_state``. A schedule whose curve + already ended is discarded instead of restored. + """ + accessory = self.service.broker + if accessory is None or accessory.aid is None: + return + if self._stopped or self.transition is not None: + return + stored = accessory.driver.accessory_state(accessory.aid).get(STATE_KEY) + if stored is None: + return + + try: + transition = ActiveTransition.from_dict(stored) + except (KeyError, TypeError, ValueError): + _LOGGER.warning("Stored adaptive lighting transition is unreadable") + self._clear_stored_transition(accessory) + return + + if interpolate(transition, self._now()) is None: + # The schedule only covers about 24 hours; the Home app sends a + # new one. + _LOGGER.debug("Stored adaptive lighting transition expired") + self._clear_stored_transition(accessory) + return + + _LOGGER.debug("Restoring adaptive lighting after restart") + self._arm(transition, persist=False) + + def _clear_stored_transition(self, accessory: "Accessory") -> None: + """Drop an unusable stored transition from the accessory state.""" + if accessory.aid is None: + return + state = accessory.driver.accessory_state(accessory.aid) + if state.pop(STATE_KEY, None) is not None: + accessory.driver.async_persist() diff --git a/tests/conftest.py b/tests/conftest.py index 65793154..1610a6af 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -106,6 +106,14 @@ class MockDriver: def __init__(self) -> None: self.loader = Loader() self.loop = None + self.accessory_states: dict[int, dict[str, Any]] = {} + self.persist_calls = 0 + + def accessory_state(self, aid: int) -> dict[str, Any]: + return self.accessory_states.setdefault(aid, {}) + + def async_persist(self) -> None: + self.persist_calls += 1 def publish( self, data: Any, client_addr: Any = None, immediate: bool = False diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py index 92a7ab93..2a7323c7 100644 --- a/tests/test_adaptive_lighting.py +++ b/tests/test_adaptive_lighting.py @@ -942,3 +942,101 @@ def apply(mireds: int) -> None: assert controller.transition is not None assert received == [] + + +# --- AdaptiveLightingController persistence ----------------------------------- + + +def test_controller_persists_the_transition_on_arm(mock_driver: Any) -> None: + """Arming writes the transition dict into the accessory state.""" + mock_driver.accessory_states.clear() + persist_before = mock_driver.persist_calls + _, controller = _controller(mock_driver) + + controller.char_control.client_update_value(_ramp_write()) + + stored = mock_driver.accessory_states[1][adaptive_lighting.STATE_KEY] + assert stored["update_interval"] == 1000 + assert stored["curve"] + assert mock_driver.persist_calls > persist_before + + +def test_controller_clears_the_stored_transition_on_disable( + mock_driver: Any, +) -> None: + """Disabling removes the saved transition so a restart stays off.""" + mock_driver.accessory_states.clear() + _, controller = _controller(mock_driver) + controller.char_control.client_update_value(_ramp_write()) + assert adaptive_lighting.STATE_KEY in mock_driver.accessory_states[1] + + controller.char_control.client_update_value("") + + assert adaptive_lighting.STATE_KEY not in mock_driver.accessory_states[1] + + +def test_controller_restore_rearms_a_still_valid_transition( + mock_driver: Any, +) -> None: + """A restart restores the schedule and resumes applying it.""" + mock_driver.accessory_states.clear() + now = [NOW_MILLIS] + _, first = _controller(mock_driver, clock=lambda: now[0]) + first.char_control.client_update_value(_ramp_write()) + + applied: list[int] = [] + loop = _FakeLoop() + _, second = _controller( + mock_driver, + clock=lambda: now[0], + loop=loop, + on_apply_temperature=applied.append, + ) + second.restore() + + assert second.transition is not None + assert applied == [300] + assert second._update_timer is not None + + +def test_controller_restore_discards_an_expired_transition( + mock_driver: Any, +) -> None: + """A curve that already ended is dropped instead of restored.""" + mock_driver.accessory_states.clear() + now = [NOW_MILLIS] + _, first = _controller(mock_driver, clock=lambda: now[0]) + first.char_control.client_update_value(_ramp_write()) + + now[0] += 120_000 + _, second = _controller(mock_driver, clock=lambda: now[0]) + second.restore() + + assert second.transition is None + assert adaptive_lighting.STATE_KEY not in mock_driver.accessory_states[1] + + +def test_controller_restore_discards_an_unreadable_transition( + mock_driver: Any, +) -> None: + """A corrupt stored value is cleared without breaking the accessory.""" + mock_driver.accessory_states.clear() + mock_driver.accessory_states[1] = {adaptive_lighting.STATE_KEY: {"bogus": 1}} + _, controller = _controller(mock_driver) + + controller.restore() + + assert controller.transition is None + assert adaptive_lighting.STATE_KEY not in mock_driver.accessory_states[1] + + +def test_controller_restore_does_nothing_without_a_stored_transition( + mock_driver: Any, +) -> None: + """A fresh accessory has nothing to restore.""" + mock_driver.accessory_states.clear() + _, controller = _controller(mock_driver) + + controller.restore() + + assert controller.transition is None From 22b19c0dca221a17ceccb80e820a6f3325418ce0 Mon Sep 17 00:00:00 2001 From: Adriano Valumin Date: Tue, 1 Dec 2026 18:28:40 -0300 Subject: [PATCH 6/9] Harden the adaptive lighting controller against bad writes Reject malformed or incomplete transition schedules by raising from the setter so the driver fails the write instead of acknowledging it, keep the running transition untouched and skip undecodable read requests instead of failing the whole write. Replace the iid asserts with ValueError and clamp the update interval to the asyncio timer limit. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- pyhap/adaptive_lighting.py | 53 ++++++++++++++++++------- tests/test_adaptive_lighting.py | 69 +++++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 15 deletions(-) diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py index 918acf15..61e0156e 100644 --- a/pyhap/adaptive_lighting.py +++ b/pyhap/adaptive_lighting.py @@ -98,6 +98,9 @@ # Key of the saved transition inside ``driver.accessory_state(aid)``. STATE_KEY = "adaptive_lighting" +# asyncio timers overflow past this delay; the curve never asks for more. +MAX_UPDATE_INTERVAL_MS = (2**31) - 1 + class _UpdateTimer(Protocol): """The part of an ``asyncio`` timer handle the controller uses.""" @@ -535,9 +538,17 @@ def _get_or_create_characteristic(self, name: str) -> Characteristic: def _iid(self, char: Characteristic) -> int: """Return the iid the accessory assigned to a characteristic.""" accessory = self.service.broker - assert accessory is not None # noqa: S101 - constructor requires it + if accessory is None: + raise ValueError( + f"{char.display_name} has no iid: the service is not " + "attached to an accessory" + ) iid = accessory.iid_manager.get_iid(char) - assert iid is not None # noqa: S101 + if iid is None: + raise ValueError( + f"{char.display_name} has no iid: add it to the service " + "before the accessory assigns iids" + ) return iid def _handle_transition_control_write(self, value: str) -> str | None: @@ -574,13 +585,19 @@ def _handle_transition_control_write(self, value: str) -> str | None: return base64.b64encode(b"".join(responses)).decode() def _handle_update_write(self, update: bytes) -> bytes | None: - """Arm, renew or disable the schedule carried by an update write.""" + """Arm, renew or disable the schedule carried by an update write. + + Raises ``ValueError`` when the payload is not a valid schedule, so + the driver fails the write instead of acknowledging it; the + running transition is left untouched. Like HAP-NodeJS, which + answers INVALID_VALUE_IN_REQUEST, pyhap reports a setter exception + as a failed write. + """ try: outer = tlv.decode_ordered(update) configuration = tlv.decode_ordered(outer[0][1]) if outer else [] - except (IndexError, ValueError): - _LOGGER.exception("Malformed transition update") - return None + except (IndexError, ValueError) as err: + raise ValueError("malformed transition update") from err unknown_3 = first_tlv_value(configuration, TAG_CFG_UNKNOWN_3) if not unknown_3 or unknown_3[0] == 0: @@ -592,15 +609,11 @@ def _handle_update_write(self, update: bytes) -> bytes | None: try: transition = parse_transition_update(update, now_millis=self._now()) - except (IndexError, ValueError, struct.error): - _LOGGER.exception("Could not parse the transition schedule") - return None + except (IndexError, ValueError, struct.error) as err: + raise ValueError("could not parse the transition schedule") from err if transition is None: - _LOGGER.warning( - "Transition schedule is incomplete, keeping the current one" - ) - return None + raise ValueError("incomplete transition schedule") self._arm(transition) return encode_tlv(TAG_UPDATE_TRANSITION, self._status_tlv()) @@ -611,7 +624,11 @@ def _build_read_response(self, read_request: bytes) -> bytes | None: if transition is None: return None - read_entries = tlv.decode_ordered(read_request) + try: + read_entries = tlv.decode_ordered(read_request) + except ValueError: + _LOGGER.exception("Malformed read-current-transition request") + return None if not read_entries: return None if ( @@ -694,7 +711,13 @@ def _schedule_next_update(self) -> None: or self._update_timer is not None ): return - interval = max(self.transition.update_interval, MIN_UPDATE_INTERVAL) / 1000 + interval = ( + min( + max(self.transition.update_interval, MIN_UPDATE_INTERVAL), + MAX_UPDATE_INTERVAL_MS, + ) + / 1000 + ) self._update_timer = self._loop.call_later(interval, self._tick) def _cancel_update_timer(self) -> None: diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py index 2a7323c7..cdd603b8 100644 --- a/tests/test_adaptive_lighting.py +++ b/tests/test_adaptive_lighting.py @@ -5,6 +5,7 @@ import math import struct from typing import Any +from uuid import uuid4 import pytest @@ -42,6 +43,8 @@ parse_transition_update, supported_transition_configuration, ) +from pyhap.loader import get_loader +from pyhap.service import Service # A real schedule written by the Home app to a colour temperature light. The # curve covers 24 hours in 42 points and asks for an update every 60 seconds. @@ -1040,3 +1043,69 @@ def test_controller_restore_does_nothing_without_a_stored_transition( controller.restore() assert controller.transition is None + + +# --- AdaptiveLightingController review fixes (B1) ------------------------------ + + +def test_controller_rejects_a_schedule_with_too_few_points( + mock_driver: Any, +) -> None: + """A curve under two points fails the write and keeps the old schedule.""" + _, controller = _controller(mock_driver) + controller.char_control.client_update_value(_ramp_write()) + armed = controller.transition + assert armed is not None + + short = _curve_write([_curve_point(300.0, 0.0)]) + with pytest.raises(ValueError, match="incomplete"): + controller.char_control.client_update_value(short) + + assert controller.transition is armed + assert controller.char_active_count.value == 1 + + +def test_controller_ignores_an_undecodable_read_request(mock_driver: Any) -> None: + """A malformed read request is skipped without failing the whole write.""" + _, controller = _controller(mock_driver) + controller.char_control.client_update_value(_ramp_write()) + + request = base64.b64encode( + encode_tlv(TAG_READ_CURRENT_TRANSITION, b"\xff\x01") + ).decode() + assert controller.char_control.client_update_value(request) is None + assert controller.transition is not None + + +def test_iid_requires_an_attached_accessory() -> None: + """Advertising iids is impossible while the service has no accessory.""" + service = Service(uuid4(), "Lightbulb") + loader = get_loader() + for name in ( + "On", + "Brightness", + "ColorTemperature", + *adaptive_lighting.ADAPTIVE_LIGHTING_CHARS, + ): + service.add_characteristic(loader.get_char(name)) + + with pytest.raises(ValueError, match="not attached"): + AdaptiveLightingController(service) + + +def test_update_interval_is_clamped_to_the_timer_limit(mock_driver: Any) -> None: + """An absurd update interval cannot overflow the asyncio timer.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + + controller.char_control.client_update_value( + _curve_write( + [_curve_point(300.0, 0.0), _curve_point(400.0, 0.0, 60_000)], + [TAG_CFG_UPDATE_INTERVAL, encode_variable_uint(0xFFFFFFFF)], + ) + ) + + timer = controller._update_timer + assert isinstance(timer, _FakeTimer) # noqa: S101 + assert timer.delay == (2**31 - 1) / 1000 From d22cbe453bbb22022875fed27027b50760ba8245 Mon Sep 17 00:00:00 2001 From: Adriano Valumin Date: Tue, 1 Dec 2026 18:37:06 -0300 Subject: [PATCH 7/9] Notify adaptive lighting count changes and document notify pacing ActiveTransitionCount now notifies subscribers on arm (1) and disable (0), matching HAP-NodeJS. The notify_threshold stays consumer-owned: the controller reports every applied point and the consumer paces the characteristic notifications, as shown by the updated example which also notifies exactly once per applied point. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- accessories/adaptive_lightbulb.py | 31 +++++++++++++++----- docs/source/intro/examples.rst | 5 +++- pyhap/adaptive_lighting.py | 17 +++++++++-- tests/test_adaptive_lighting.py | 48 +++++++++++++++++++++++++++++++ 4 files changed, 90 insertions(+), 11 deletions(-) diff --git a/accessories/adaptive_lightbulb.py b/accessories/adaptive_lightbulb.py index 9c1f0cd3..47e833c6 100644 --- a/accessories/adaptive_lightbulb.py +++ b/accessories/adaptive_lightbulb.py @@ -6,6 +6,7 @@ import logging import signal +import time from typing import Any from pyhap.accessory import Accessory @@ -23,6 +24,7 @@ class LightBulb(Accessory): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self._last_notification = 0 serv_light = self.add_preload_service( "Lightbulb", ["On", "Brightness", "ColorTemperature"] @@ -46,10 +48,20 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: ) def _apply_temperature(self, mireds: int) -> None: - """Write the colour temperature the curve asks for.""" + """Write the colour temperature the curve asks for. + + The characteristic is updated on every interval, but subscribers + are only notified at the ``notify_threshold`` pace the Home app + asked for in the schedule. + """ logging.info("Adaptive lighting applies %d mireds", mireds) - self.char_ct.set_value(mireds) - self.char_ct.notify() + self.char_ct.set_value(mireds, should_notify=False) + transition = self.adaptive_lighting.transition + threshold = transition.notify_threshold if transition else 0 + now = int(time.time() * 1000) + if now - self._last_notification >= threshold: + self._last_notification = now + self.char_ct.notify() def set_on(self, value: Any) -> None: logging.info("Write On State: %s", value) @@ -65,7 +77,12 @@ def restore_accessory_state(self) -> None: self.adaptive_lighting.restore() -driver = AccessoryDriver(port=51826, persist_file="adaptive_lightbulb.state") -driver.add_accessory(accessory=LightBulb(driver, "Lightbulb")) -signal.signal(signal.SIGTERM, driver.signal_handler) -driver.start() +def main() -> None: + driver = AccessoryDriver(port=51826, persist_file="adaptive_lightbulb.state") + driver.add_accessory(accessory=LightBulb(driver, "Lightbulb")) + signal.signal(signal.SIGTERM, driver.signal_handler) + driver.start() + + +if __name__ == "__main__": + main() diff --git a/docs/source/intro/examples.rst b/docs/source/intro/examples.rst index bb1e43eb..be3db3f5 100644 --- a/docs/source/intro/examples.rst +++ b/docs/source/intro/examples.rst @@ -28,7 +28,10 @@ device. * - ``adaptive_lightbulb.py`` - A light driven by ``AdaptiveLightingController``: the Home app's colour curve is decoded, interpolated every update interval and - applied, surviving restarts through the accessory state. + applied, surviving restarts through the accessory state. The + example also shows the consumer side of the protocol: it updates + the characteristic every interval but paces event notifications + to subscribers at the schedule's ``notify_threshold``. * - ``TV.py``, ``FakeFan.py``, ``DisplaySwitch.py`` - TVs, fans and switches: services with several linked characteristics. * - ``AudioReceiver.py`` diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py index 61e0156e..592760d2 100644 --- a/pyhap/adaptive_lighting.py +++ b/pyhap/adaptive_lighting.py @@ -421,6 +421,13 @@ class AdaptiveLightingController: for notifying subscribers; persisting the transition across restarts is also left to the consumer. + ``ActiveTransitionCount`` notifies subscribers when a schedule arms + (1) and when it is disabled (0). The curve's ``notify_threshold`` is + the minimum interval, in milliseconds, at which the Home app wants + event notifications about the colour. The controller reports every + applied point and leaves the notification pacing to the consumer, + which owns the characteristic writes and their notifications. + Create the controller after the service characteristics are configured: the ``ColorTemperature`` setter callback is wrapped so a colour temperature written by a paired controller disarms adaptive @@ -449,7 +456,11 @@ def __init__( reported but never applied. :param on_apply_temperature: Called with the mireds value the curve asks for, once when the schedule arms and then on every - update interval until it is disabled or ends. + update interval until it is disabled or ends. It fires on + every interval regardless of the transition's + ``notify_threshold``: that threshold paces event + notifications to HomeKit subscribers, which the consumer + sends itself when it writes the characteristic. """ self.service = service self._now = clock or (lambda: int(time.time() * 1000)) @@ -686,7 +697,7 @@ def _arm(self, transition: ActiveTransition, *, persist: bool = True) -> None: """Start applying a schedule, whether it just arrived or was renewed.""" self._stopped = False self.transition = transition - self.char_active_count.set_value(1, should_notify=False) + self.char_active_count.set_value(1) self.char_control.value = self._build_control_response() _LOGGER.debug( "Adaptive lighting armed with %d curve points, updating every %dms", @@ -797,7 +808,7 @@ def disable(self, reason: str) -> None: self._last_applied = None self._persist_transition() self.stop() - self.char_active_count.set_value(0, should_notify=False) + self.char_active_count.set_value(0) self.char_control.value = "" def stop(self) -> None: diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py index cdd603b8..41300d37 100644 --- a/tests/test_adaptive_lighting.py +++ b/tests/test_adaptive_lighting.py @@ -1,10 +1,13 @@ """Tests for pyhap.adaptive_lighting.""" import base64 +import importlib.util import json import math +import pathlib import struct from typing import Any +from unittest.mock import patch from uuid import uuid4 import pytest @@ -43,6 +46,7 @@ parse_transition_update, supported_transition_configuration, ) +from pyhap.const import HAP_REPR_IID, HAP_REPR_VALUE from pyhap.loader import get_loader from pyhap.service import Service @@ -1109,3 +1113,47 @@ def test_update_interval_is_clamped_to_the_timer_limit(mock_driver: Any) -> None timer = controller._update_timer assert isinstance(timer, _FakeTimer) # noqa: S101 assert timer.delay == (2**31 - 1) / 1000 + + +# --- AdaptiveLightingController notifications (B2) ----------------------------- + + +def test_controller_notifies_active_transition_count(mock_driver: Any) -> None: + """Arming and disabling push ActiveTransitionCount events.""" + _, controller = _controller(mock_driver) + count_iid = _iid(controller, controller.char_active_count) + + with patch.object(mock_driver, "publish") as publish: + controller.char_control.client_update_value(_ramp_write()) + # Re-arming while the count is already 1 does not re-notify. + controller.char_control.client_update_value(_ramp_write()) + controller.disable("test") + + events = [ + call.args[0] + for call in publish.call_args_list + if call.args[0].get(HAP_REPR_IID) == count_iid + ] + assert [event[HAP_REPR_VALUE] for event in events] == [1, 0] + + +def test_example_applies_temperature_with_one_notification( + mock_driver: Any, +) -> None: + """The example notifies subscribers once per applied point.""" + example = ( + pathlib.Path(__file__).parents[1] / "accessories" / "adaptive_lightbulb.py" + ) + spec = importlib.util.spec_from_file_location("adaptive_lightbulb_example", example) + assert spec is not None and spec.loader is not None # noqa: S101 + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + bulb = module.LightBulb(mock_driver, "Lightbulb") + with patch.object(mock_driver, "publish") as publish: + bulb._apply_temperature(300) + + assert bulb.char_ct.value == 300 + events = [call.args[0] for call in publish.call_args_list] + assert len(events) == 1 + assert events[0][HAP_REPR_VALUE] == 300 From cbb1b525fedb3dbe4be21a3ba83c1b249ee13aeb Mon Sep 17 00:00:00 2001 From: Adriano Valumin Date: Tue, 1 Dec 2026 18:42:50 -0300 Subject: [PATCH 8/9] Fix zero brightness handling and document loop contract A brightness of 0 is a real value and now clamps to min_multiplier instead of falling back to max_multiplier. The class docstring and state docs spell out the driver-loop contract: setter callbacks, restore() and async_persist all run on driver.loop, which must be the loop passed to the controller, and restore() stays a no-op after stop(). Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- docs/source/advanced/state.rst | 7 ++++ pyhap/adaptive_lighting.py | 21 +++++++--- tests/test_adaptive_lighting.py | 70 ++++++++++++++++++++++++++++++++- 3 files changed, 91 insertions(+), 7 deletions(-) diff --git a/docs/source/advanced/state.rst b/docs/source/advanced/state.rst index 4ff34275..0db37840 100644 --- a/docs/source/advanced/state.rst +++ b/docs/source/advanced/state.rst @@ -133,6 +133,13 @@ its update loop, unless the curve already ended or the stored value is unreadable, in which case it is discarded. See :ref:`api-adaptive-lighting` and the ``adaptive_lightbulb.py`` example. +The controller is not thread-safe: its characteristic callbacks and its +update timer run on the driver's event loop, so pass ``driver.loop`` as +its ``loop`` and call ``restore()`` from accessory code that already +runs there — ``loop.call_later`` and ``driver.async_persist`` must not +be reached from another thread. Once :meth:`~pyhap.adaptive_lighting.AdaptiveLightingController.stop` +has run at teardown, ``restore()`` stays a no-op. + A new home must not inherit the old one ======================================= diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py index 592760d2..9230d080 100644 --- a/pyhap/adaptive_lighting.py +++ b/pyhap/adaptive_lighting.py @@ -428,6 +428,13 @@ class AdaptiveLightingController: applied point and leaves the notification pacing to the consumer, which owns the characteristic writes and their notifications. + Everything the controller does runs on the driver's event loop: + characteristic setter callbacks are invoked there, so ``loop`` must + be ``driver.loop`` and :meth:`restore` — which also reaches + ``driver.async_persist`` — must be called from accessory code that + already runs on that loop. ``loop.call_later`` is not thread-safe, + so the controller cannot be armed or ticked from another thread. + Create the controller after the service characteristics are configured: the ``ColorTemperature`` setter callback is wrapped so a colour temperature written by a paired controller disarms adaptive @@ -452,8 +459,8 @@ def __init__( defaults to the wall clock. Pass one to make the controller deterministic in tests. :param loop: Event loop used to schedule the periodic curve - evaluation. Without it the transition is still decoded and - reported but never applied. + evaluation; pass ``driver.loop``. Without it the transition + is still decoded and reported but never applied. :param on_apply_temperature: Called with the mireds value the curve asks for, once when the schedule arms and then on every update interval until it is disabled or ends. It fires on @@ -755,7 +762,9 @@ def _update(self) -> None: temperature, adjustment_factor = point # Apple sends a factor that shifts the colour with the brightness level. - brightness = self.char_brightness.value or transition.max_multiplier + brightness = self.char_brightness.value + if brightness is None: + brightness = transition.max_multiplier multiplier = min( transition.max_multiplier, max(transition.min_multiplier, brightness) ) @@ -836,8 +845,10 @@ def restore(self) -> None: """Re-arm the transition persisted before the last restart. The consumer calls this once the accessory state is loaded, e.g. - from ``Accessory.restore_accessory_state``. A schedule whose curve - already ended is discarded instead of restored. + from ``Accessory.restore_accessory_state``, on the driver's event + loop. A schedule whose curve already ended is discarded instead + of restored. After :meth:`stop` — accessory teardown — the + controller stays disarmed and this is a no-op. """ accessory = self.service.broker if accessory is None or accessory.aid is None: diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py index 41300d37..6f9f0a60 100644 --- a/tests/test_adaptive_lighting.py +++ b/tests/test_adaptive_lighting.py @@ -290,7 +290,9 @@ def _control_write(configuration: bytes) -> str: def _curve_write( - entries: list[bytes], extra_config: list[int | bytes] | None = None + entries: list[bytes], + extra_config: list[int | bytes] | None = None, + start_time: int = 1_700_000_000_000, ) -> str: """Build a minimal update write around the given curve entries.""" config: list[int | bytes] = [ @@ -299,7 +301,7 @@ def _curve_write( TAG_PARAM_TRANSITION_ID, b"\x00" * 16, TAG_PARAM_START_TIME, - (1_700_000_000_000).to_bytes(8, "little"), + start_time.to_bytes(8, "little"), ), TAG_CFG_UNKNOWN_3, b"\x01", @@ -1157,3 +1159,67 @@ def test_example_applies_temperature_with_one_notification( events = [call.args[0] for call in publish.call_args_list] assert len(events) == 1 assert events[0][HAP_REPR_VALUE] == 300 + + +# --- AdaptiveLightingController review fixes (B3) ----------------------------- + + +def test_controller_treats_zero_brightness_as_a_real_value( + mock_driver: Any, +) -> None: + """Brightness 0 clamps to min_multiplier instead of reading as missing.""" + now = [NOW_MILLIS] + applied: list[int] = [] + _, controller = _looped_controller(mock_driver, applied, now) + controller.char_brightness.set_value(0, should_notify=False) + + controller.char_control.client_update_value( + _curve_write( + [_curve_point(300.0, -10.0), _curve_point(400.0, -10.0, 60_000)], + [TAG_CFG_UPDATE_INTERVAL, encode_variable_uint(1000)], + ) + ) + + # multiplier = min_multiplier (10): 300 + (-10 * 10) = 200 mireds. + # Treating 0 as absent would use max_multiplier (100) and clamp to 140. + assert applied == [200] + + +def test_future_start_time_does_not_disarm_the_transition( + mock_driver: Any, +) -> None: + """Interpolation is relative to the parse time, not to start_time. + + ``parse_transition_update`` stores ``time_millis_offset = now - + start_millis`` and ``interpolate_point`` evaluates ``now - offset - + start_millis``, so the start time cancels out: a schedule whose start + lies in the future still applies from the moment it was written. + """ + now = [NOW_MILLIS] + applied: list[int] = [] + _, controller = _looped_controller(mock_driver, applied, now) + + controller.char_control.client_update_value( + _curve_write( + [_curve_point(300.0, 0.0), _curve_point(400.0, 0.0, 60_000)], + start_time=(NOW_MILLIS + 3_600_000 - adaptive_lighting.EPOCH_MILLIS_2001), + ) + ) + + assert controller.transition is not None + assert applied == [300] + + +def test_controller_restore_is_a_noop_after_stop(mock_driver: Any) -> None: + """After teardown the controller stays disarmed and keeps the state.""" + mock_driver.accessory_states.clear() + now = [NOW_MILLIS] + _, first = _controller(mock_driver, clock=lambda: now[0]) + first.char_control.client_update_value(_ramp_write()) + + _, second = _controller(mock_driver, clock=lambda: now[0]) + second.stop() + second.restore() + + assert second.transition is None + assert adaptive_lighting.STATE_KEY in mock_driver.accessory_states[1] From f623852cd3a0427bf530628d2a7aaa0f1a609db8 Mon Sep 17 00:00:00 2001 From: Adriano Valumin Date: Tue, 1 Dec 2026 19:47:05 -0300 Subject: [PATCH 9/9] Add update_now and discard_applied to the lighting controller Consumers can re-evaluate the curve on demand when the light state changed outside the schedule, and force the next evaluation to rewrite the colour by discarding the deduplicated value. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- pyhap/adaptive_lighting.py | 22 +++++++++++++++++ tests/test_adaptive_lighting.py | 43 +++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/pyhap/adaptive_lighting.py b/pyhap/adaptive_lighting.py index 9230d080..6f544f85 100644 --- a/pyhap/adaptive_lighting.py +++ b/pyhap/adaptive_lighting.py @@ -829,6 +829,28 @@ def stop(self) -> None: self._stopped = True self._cancel_update_timer() + def update_now(self) -> None: + """Re-evaluate the curve and apply the current point immediately. + + Runs the same logic as a scheduled tick — interpolation at the + current time, the brightness adjustment, the characteristic + range clamp and the applied-value deduplication — without waiting + for the next ``update_interval``. Call it when the consumer knows + the light's state changed outside the curve, e.g. it was switched + on. Does nothing while stopped or without an active transition. + """ + self._update() + + def discard_applied(self) -> None: + """Forget the last applied mireds value. + + The next evaluation applies the curve point again even when it + computes the same mireds, rewriting the colour temperature on the + accessory. Useful when the consumer knows the physical state + drifted, e.g. the bulb was power-cycled. + """ + self._last_applied = None + def _persist_transition(self) -> None: """Save the active transition, or clear it, in the accessory state.""" accessory = self.service.broker diff --git a/tests/test_adaptive_lighting.py b/tests/test_adaptive_lighting.py index 6f9f0a60..c5e67f9e 100644 --- a/tests/test_adaptive_lighting.py +++ b/tests/test_adaptive_lighting.py @@ -1223,3 +1223,46 @@ def test_controller_restore_is_a_noop_after_stop(mock_driver: Any) -> None: assert second.transition is None assert adaptive_lighting.STATE_KEY in mock_driver.accessory_states[1] + + +# --- AdaptiveLightingController consumer hooks (P0) ----------------------------- + + +def test_controller_update_now_applies_the_current_point( + mock_driver: Any, +) -> None: + """update_now evaluates the curve immediately, outside the tick schedule.""" + now = [NOW_MILLIS] + applied: list[int] = [] + _, controller = _looped_controller(mock_driver, applied, now) + controller.char_control.client_update_value(_ramp_write()) + assert applied == [300] + + now[0] += 30_000 + controller.update_now() + assert applied == [300, 350] + + # A repeated call at the same instant is deduplicated. + controller.update_now() + assert applied == [300, 350] + + # A stopped controller ignores it entirely. + controller.stop() + now[0] += 30_000 + controller.update_now() + assert applied == [300, 350] + + +def test_controller_discard_applied_forces_a_rewrite(mock_driver: Any) -> None: + """discard_applied makes the next evaluation rewrite the same mireds.""" + now = [NOW_MILLIS] + applied: list[int] = [] + loop, controller = _looped_controller(mock_driver, applied, now) + controller.char_control.client_update_value(_ramp_write()) + + loop.run_next() + assert applied == [300] + + controller.discard_applied() + loop.run_next() + assert applied == [300, 300]