Skip to content
129 changes: 62 additions & 67 deletions accessories/adaptive_lightbulb.py
Original file line number Diff line number Diff line change
@@ -1,93 +1,88 @@
"""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
import time
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)
self._last_notification = 0

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.

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, 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)

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 restore_accessory_state(self) -> None:
"""Resume the adaptive lighting schedule saved before a restart."""
self.adaptive_lighting.restore()

def set_tc(self, value):
logging.info("Write to TransitionControl: %s", value)

def set_brightness(self, value):
logging.info("Bulb brightness: %s", value)
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()

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()
21 changes: 21 additions & 0 deletions docs/source/advanced/state.rst
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,27 @@ 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
<pyhap.adaptive_lighting.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.

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
=======================================

Expand Down
12 changes: 12 additions & 0 deletions docs/source/api/adaptive_lighting.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.. _api-adaptive-lighting:

==================
Adaptive Lighting
==================

Codec, interpolator and service wiring for HomeKit Adaptive Lighting
transition schedules.

.. automodule:: pyhap.adaptive_lighting
:members:
:undoc-members:
12 changes: 9 additions & 3 deletions docs/source/intro/examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,15 @@ 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. 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``
Expand Down
Loading