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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/source/api/adaptive_lighting.rst
Original file line number Diff line number Diff line change
@@ -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:
370 changes: 370 additions & 0 deletions pyhap/adaptive_lighting.py
Original file line number Diff line number Diff line change
@@ -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.
"""
configuration_raw = first_tlv_value(tlv.decode_ordered(update), TAG_CFG_IID)
if configuration_raw is None:
return None
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:
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("<Q", start_time)[0] + EPOCH_MILLIS_2001

curve_entries = tlv.decode_ordered(curve_raw)
curve: list[CurveEntry] = []
for tag, raw in curve_entries:
if tag != TAG_CURVE_ENTRY:
continue
entry = tlv.decode_ordered(raw)
factor = first_tlv_value(entry, TAG_ENTRY_ADJUSTMENT_FACTOR)
value_raw = first_tlv_value(entry, TAG_ENTRY_VALUE)
if not factor or not value_raw or len(factor) != 4 or len(value_raw) != 4:
_LOGGER.warning("Adaptive lighting curve entry is incomplete")
continue
temperature = struct.unpack("<f", value_raw)[0]
adjustment_factor = struct.unpack("<f", factor)[0]
if not math.isfinite(temperature) or not math.isfinite(adjustment_factor):
raise ValueError("adaptive lighting curve entry is not finite")
offset_raw = first_tlv_value(entry, TAG_ENTRY_TRANSITION_OFFSET)
duration_raw = first_tlv_value(entry, TAG_ENTRY_DURATION)
# On the wire the duration of an entry is the hold time of the
# *previous* curve point, matching the reference implementation.
if curve and duration_raw:
curve[-1].duration = decode_variable_uint(duration_raw)
curve.append(
CurveEntry(
temperature=temperature,
brightness_adjustment_factor=adjustment_factor,
transition_time=(decode_variable_uint(offset_raw) if offset_raw else 0),
duration=0,
)
)
if len(curve) < 2:
return None

min_multiplier, max_multiplier = 10, 100
if multiplier_raw := first_tlv_value(configuration, TAG_CURVE_MULTIPLIER_RANGE):
multiplier = tlv.decode_ordered(multiplier_raw)
if (raw_min := first_tlv_value(multiplier, TAG_RANGE_MIN)) is not None:
min_multiplier = decode_variable_uint(raw_min)
if (raw_max := first_tlv_value(multiplier, TAG_RANGE_MAX)) is not None:
max_multiplier = decode_variable_uint(raw_max)

update_interval_raw = first_tlv_value(configuration, TAG_CFG_UPDATE_INTERVAL)
notify_threshold_raw = first_tlv_value(configuration, TAG_CFG_NOTIFY_THRESHOLD)

now = int(time.time() * 1000) if now_millis is None else now_millis
return ActiveTransition(
transition_id=transition_id,
parameters=parameters_raw,
start_millis=start_millis,
time_millis_offset=now - start_millis,
curve=curve,
update_interval=(
max(MIN_UPDATE_INTERVAL, decode_variable_uint(update_interval_raw))
if update_interval_raw
else 60000
),
notify_threshold=(
decode_variable_uint(notify_threshold_raw)
if notify_threshold_raw
else 600000
),
min_multiplier=min_multiplier,
max_multiplier=max_multiplier,
)


def interpolate_point(
transition: ActiveTransition, now_millis: int
) -> 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]
Loading