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/2] 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/2] 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.