mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Add segment lights for Hue gradient lights (#190905)
This commit is contained in:
@@ -109,6 +109,9 @@
|
||||
}
|
||||
},
|
||||
"light": {
|
||||
"gradient_segment": {
|
||||
"name": "Segment {segment}"
|
||||
},
|
||||
"hue_light": {
|
||||
"state_attributes": {
|
||||
"effect": {
|
||||
|
||||
@@ -18,6 +18,11 @@ def normalize_hue_brightness(brightness: float | None) -> float | None:
|
||||
return brightness
|
||||
|
||||
|
||||
def hue_brightness_to_ha(brightness: float) -> int:
|
||||
"""Convert a Hue brightness (0-100) to a Home Assistant brightness (0-255)."""
|
||||
return round((brightness / 100) * 255)
|
||||
|
||||
|
||||
def normalize_hue_transition(transition: float | None) -> float | None:
|
||||
"""Return rounded transition values."""
|
||||
if transition is not None:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Support for Hue lights."""
|
||||
|
||||
from functools import partial
|
||||
import asyncio
|
||||
from typing import Any, override
|
||||
|
||||
from aiohue import HueBridgeV2
|
||||
@@ -26,11 +26,13 @@ from homeassistant.components.light import (
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.helpers.group import IntegrationSpecificGroup
|
||||
from homeassistant.util import color as color_util
|
||||
|
||||
from ..bridge import HueBridge, HueConfigEntry
|
||||
from .entity import HueBaseEntity
|
||||
from .helpers import (
|
||||
hue_brightness_to_ha,
|
||||
normalize_hue_brightness,
|
||||
normalize_hue_colortemp,
|
||||
normalize_hue_transition,
|
||||
@@ -39,6 +41,23 @@ from .helpers import (
|
||||
FALLBACK_MIN_MIREDS = 153 # hue default for most lights
|
||||
FALLBACK_MAX_MIREDS = 500 # hue default for most lights
|
||||
FALLBACK_KELVIN = 5800 # halfway
|
||||
GRADIENT_COALESCE_DELAY = 0.1 # seconds to collect concurrent segment writes
|
||||
|
||||
|
||||
def gradient_segment_unique_id(resource: Light, number: int) -> str:
|
||||
"""Return the unique id of a gradient segment entity."""
|
||||
return f"{resource.id}_segment_{number}"
|
||||
|
||||
|
||||
def gradient_point_color(resource: Light, index: int) -> tuple[float, float]:
|
||||
"""Return the color of a gradient point.
|
||||
|
||||
Falls back to the color of the whole light, which is what the bridge
|
||||
reports while no gradient is active.
|
||||
"""
|
||||
points = resource.gradient.points
|
||||
xy = points[index].color.xy if index < len(points) else resource.color.xy
|
||||
return (xy.x, xy.y)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
@@ -50,15 +69,27 @@ async def async_setup_entry(
|
||||
bridge = config_entry.runtime_data
|
||||
api: HueBridgeV2 = bridge.api
|
||||
controller: LightsController = api.lights
|
||||
make_light_entity = partial(HueLight, bridge, controller)
|
||||
|
||||
def make_light_entities(resource: Light) -> list[HueBaseEntity]:
|
||||
"""Create the light entity plus a segment entity per gradient point."""
|
||||
entities: list[HueBaseEntity] = [HueLight(bridge, controller, resource)]
|
||||
if resource.gradient is not None:
|
||||
writer = HueGradientWriter(bridge, controller, resource)
|
||||
entities.extend(
|
||||
HueGradientSegmentLight(bridge, controller, resource, writer, number)
|
||||
for number in range(1, resource.gradient.points_capable + 1)
|
||||
)
|
||||
return entities
|
||||
|
||||
@callback
|
||||
def async_add_light(event_type: EventType, resource: Light) -> None:
|
||||
"""Add Hue Light."""
|
||||
async_add_entities([make_light_entity(resource)])
|
||||
async_add_entities(make_light_entities(resource))
|
||||
|
||||
# add all current items in controller
|
||||
async_add_entities(make_light_entity(light) for light in controller)
|
||||
async_add_entities(
|
||||
entity for light in controller for entity in make_light_entities(light)
|
||||
)
|
||||
# register listener for new lights
|
||||
config_entry.async_on_unload(
|
||||
controller.subscribe(async_add_light, event_filter=EventType.RESOURCE_ADDED)
|
||||
@@ -116,14 +147,21 @@ class HueLight(HueBaseEntity, LightEntity):
|
||||
if len(self._attr_effect_list) > 0:
|
||||
self._attr_effect_list.insert(0, EFFECT_OFF)
|
||||
self._attr_supported_features |= LightEntityFeature.EFFECT
|
||||
if (gradient := resource.gradient) is not None:
|
||||
self.group = IntegrationSpecificGroup(
|
||||
self,
|
||||
[
|
||||
gradient_segment_unique_id(resource, number)
|
||||
for number in range(1, gradient.points_capable + 1)
|
||||
],
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def brightness(self) -> int | None:
|
||||
"""Return the brightness of this light between 0..255."""
|
||||
if dimming := self.resource.dimming:
|
||||
# Hue uses a range of [0, 100] to control brightness.
|
||||
return round((dimming.brightness / 100) * 255)
|
||||
return hue_brightness_to_ha(dimming.brightness)
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -323,3 +361,182 @@ class HueLight(HueBaseEntity, LightEntity):
|
||||
id=self.resource.id,
|
||||
short=flash == FLASH_SHORT,
|
||||
)
|
||||
|
||||
|
||||
# pylint: disable-next=home-assistant-enforce-class-module
|
||||
class HueGradientSegmentLight(HueBaseEntity, LightEntity):
|
||||
"""One color point of a Hue gradient light.
|
||||
|
||||
On/off and brightness apply to the whole light, as the Hue API has no
|
||||
per-point control for them. Segments are hidden by default.
|
||||
"""
|
||||
|
||||
entity_description = LightEntityDescription(
|
||||
key="hue_gradient_segment",
|
||||
translation_key="gradient_segment",
|
||||
has_entity_name=True,
|
||||
)
|
||||
_attr_color_mode = ColorMode.XY
|
||||
_attr_supported_color_modes = {ColorMode.XY}
|
||||
_attr_supported_features = LightEntityFeature.TRANSITION
|
||||
# area and device targets skip hidden entities, so whole-room commands
|
||||
# reach only the main light instead of fanning out to every segment
|
||||
_attr_entity_registry_visible_default = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
bridge: HueBridge,
|
||||
controller: LightsController,
|
||||
resource: Light,
|
||||
writer: HueGradientWriter,
|
||||
number: int,
|
||||
) -> None:
|
||||
"""Initialize the segment light."""
|
||||
super().__init__(bridge, controller, resource)
|
||||
self.resource = resource
|
||||
self._writer = writer
|
||||
self._index = number - 1
|
||||
self._attr_unique_id = gradient_segment_unique_id(resource, number)
|
||||
self._attr_translation_placeholders = {"segment": str(number)}
|
||||
|
||||
@property
|
||||
@override
|
||||
def is_on(self) -> bool:
|
||||
"""Return true if the light is on."""
|
||||
return self.resource.on.on
|
||||
|
||||
@property
|
||||
@override
|
||||
def brightness(self) -> int | None:
|
||||
"""Return the brightness of the light between 0..255."""
|
||||
if dimming := self.resource.dimming:
|
||||
return hue_brightness_to_ha(dimming.brightness)
|
||||
return None
|
||||
|
||||
@property
|
||||
@override
|
||||
def xy_color(self) -> tuple[float, float]:
|
||||
"""Return the xy color of this segment."""
|
||||
return gradient_point_color(self.resource, self._index)
|
||||
|
||||
@override
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn the light on, setting the color of this segment when given."""
|
||||
point = None
|
||||
if (xy_color := kwargs.get(ATTR_XY_COLOR)) is not None:
|
||||
point = (self._index, xy_color)
|
||||
await self._writer.async_set_state(
|
||||
on=True,
|
||||
brightness=normalize_hue_brightness(kwargs.get(ATTR_BRIGHTNESS)),
|
||||
transition=normalize_hue_transition(kwargs.get(ATTR_TRANSITION)),
|
||||
point=point,
|
||||
)
|
||||
|
||||
@override
|
||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
||||
"""Turn the light off."""
|
||||
await self._writer.async_set_state(
|
||||
on=False,
|
||||
brightness=None,
|
||||
transition=normalize_hue_transition(kwargs.get(ATTR_TRANSITION)),
|
||||
)
|
||||
|
||||
@callback
|
||||
@override
|
||||
def on_update(self) -> None:
|
||||
"""Handle a state update of the light reported by the bridge."""
|
||||
self._writer.resource_updated()
|
||||
|
||||
|
||||
class HueGradientWriter:
|
||||
"""Write the state of the segments of a gradient light to the bridge.
|
||||
|
||||
The segments share one light resource, so writes to several segments at
|
||||
the same time are merged into a single request. Colors are sent as the
|
||||
full list of gradient points.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, bridge: HueBridge, controller: LightsController, resource: Light
|
||||
) -> None:
|
||||
"""Initialize the writer."""
|
||||
self._bridge = bridge
|
||||
self._controller = controller
|
||||
self._resource = resource
|
||||
self._pending_on: bool | None = None
|
||||
self._pending_points: dict[int, tuple[float, float]] = {}
|
||||
self._pending_brightness: float | None = None
|
||||
self._pending_transition: float | None = None
|
||||
self._written_points: list[tuple[float, float]] | None = None
|
||||
self._flush_task: asyncio.Task[None] | None = None
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def async_set_state(
|
||||
self,
|
||||
on: bool,
|
||||
brightness: float | None,
|
||||
transition: float | None,
|
||||
point: tuple[int, tuple[float, float]] | None = None,
|
||||
) -> None:
|
||||
"""Set the light state, optionally with the color of one gradient point.
|
||||
|
||||
The write is sent together with writes of other segments made at the
|
||||
same time.
|
||||
"""
|
||||
self._pending_on = on
|
||||
if point is not None:
|
||||
index, xy_color = point
|
||||
self._pending_points[index] = xy_color
|
||||
if brightness is not None:
|
||||
self._pending_brightness = brightness
|
||||
if transition is not None:
|
||||
self._pending_transition = transition
|
||||
if self._flush_task is None:
|
||||
self._flush_task = self._bridge.hass.async_create_task(self._async_flush())
|
||||
# shielded so a cancelled caller does not drop the writes of the others
|
||||
await asyncio.shield(self._flush_task)
|
||||
|
||||
@callback
|
||||
def resource_updated(self) -> None:
|
||||
"""Handle a state update of the light reported by the bridge."""
|
||||
self._written_points = None
|
||||
|
||||
async def _async_flush(self) -> None:
|
||||
"""Send the pending state to the bridge after the coalescing window."""
|
||||
await asyncio.sleep(GRADIENT_COALESCE_DELAY)
|
||||
# requests go out one at a time so each builds on the result of the last
|
||||
async with self._lock:
|
||||
# take the pending state before the request so writes arriving while
|
||||
# it is in flight start a new flush instead of getting lost
|
||||
on, self._pending_on = self._pending_on, None
|
||||
points, self._pending_points = self._pending_points, {}
|
||||
brightness, self._pending_brightness = self._pending_brightness, None
|
||||
transition, self._pending_transition = self._pending_transition, None
|
||||
self._flush_task = None
|
||||
gradient_points = None
|
||||
gradient_mode = None
|
||||
if points:
|
||||
gradient = self._resource.gradient
|
||||
# the resource only reflects a write once the bridge reports it
|
||||
# back, so until then the last written points are the baseline
|
||||
if (baseline := self._written_points) is None:
|
||||
baseline = [
|
||||
gradient_point_color(self._resource, index)
|
||||
for index in range(gradient.points_capable)
|
||||
]
|
||||
gradient_points = [
|
||||
points.get(index, color) for index, color in enumerate(baseline)
|
||||
]
|
||||
# the bridge resets the mode to interpolated when it is omitted
|
||||
gradient_mode = gradient.mode
|
||||
await self._bridge.async_request_call(
|
||||
self._controller.set_state,
|
||||
id=self._resource.id,
|
||||
on=on,
|
||||
brightness=brightness,
|
||||
transition_time=transition,
|
||||
gradient_points=gradient_points,
|
||||
gradient_mode=gradient_mode,
|
||||
)
|
||||
if gradient_points is not None:
|
||||
self._written_points = gradient_points
|
||||
|
||||
@@ -63,6 +63,20 @@ FAKE_LIGHT = {
|
||||
"type": "light",
|
||||
}
|
||||
|
||||
FAKE_GRADIENT_LIGHT = {
|
||||
**FAKE_LIGHT,
|
||||
"color": {"gamut_type": "C", "xy": {"x": 0.3127, "y": 0.329}},
|
||||
"dimming": {"brightness": 50.0, "min_dim_level": 0.2},
|
||||
"on": {"on": True},
|
||||
"gradient": {
|
||||
"points": [
|
||||
{"color": {"xy": {"x": 0.1, "y": 0.2}}},
|
||||
{"color": {"xy": {"x": 0.3, "y": 0.4}}},
|
||||
],
|
||||
"points_capable": 3,
|
||||
},
|
||||
}
|
||||
|
||||
FAKE_ZIGBEE_CONNECTIVITY = {
|
||||
"id": "fake_zigbee_connectivity_id_1",
|
||||
"id_v1": "/lights/29",
|
||||
|
||||
@@ -1,23 +1,56 @@
|
||||
"""Philips Hue lights platform tests for V2 bridge/api."""
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.hue.v2.light import GRADIENT_COALESCE_DELAY
|
||||
from homeassistant.components.light import ColorMode
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.util import color as color_util
|
||||
from homeassistant.util.json import JsonArrayType
|
||||
|
||||
from .conftest import setup_platform
|
||||
from .const import FAKE_DEVICE, FAKE_LIGHT, FAKE_ZIGBEE_CONNECTIVITY
|
||||
from .const import (
|
||||
FAKE_DEVICE,
|
||||
FAKE_GRADIENT_LIGHT,
|
||||
FAKE_LIGHT,
|
||||
FAKE_ZIGBEE_CONNECTIVITY,
|
||||
)
|
||||
|
||||
GRADIENT_LIGHT_ID = "8015b17f-8336-415b-966a-b364bd082397"
|
||||
GRADIENT_LIGHT_ENTITY_ID = "light.hue_light_with_color_and_color_temperature_gradient"
|
||||
GRADIENT_SEGMENT_ENTITY_IDS = [
|
||||
f"{GRADIENT_LIGHT_ENTITY_ID}_segment_{number}" for number in range(1, 6)
|
||||
]
|
||||
# the gradient points of the gradient light in the test data
|
||||
GRADIENT_POINTS = [
|
||||
(0.5022, 0.4466),
|
||||
(0.4806, 0.4484),
|
||||
(0.5022, 0.4466),
|
||||
(0.5614, 0.4058),
|
||||
(0.5022, 0.4466),
|
||||
]
|
||||
|
||||
|
||||
def gradient_json(points: list[tuple[float, float]]) -> dict[str, Any]:
|
||||
"""Return the gradient part of a light PUT request for the given points."""
|
||||
return {
|
||||
"points": [{"color": {"xy": {"x": x, "y": y}}} for x, y in points],
|
||||
"mode": "interpolated_palette",
|
||||
}
|
||||
|
||||
|
||||
async def test_lights(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_bridge_v2: Mock,
|
||||
v2_resources_test_data: JsonArrayType,
|
||||
) -> None:
|
||||
"""Test if all v2 lights get created with correct features."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
@@ -25,8 +58,8 @@ async def test_lights(
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
# there shouldn't have been any requests at this point
|
||||
assert len(mock_bridge_v2.mock_requests) == 0
|
||||
# 8 entities should be created from test data
|
||||
assert len(hass.states.async_all()) == 8
|
||||
# 13 entities should be created from test data
|
||||
assert len(hass.states.async_all()) == 13
|
||||
|
||||
# test light which supports color and color temperature
|
||||
light_1 = hass.states.get("light.hue_light_with_color_and_color_temperature_1")
|
||||
@@ -83,6 +116,42 @@ async def test_lights(
|
||||
assert light_4.attributes["mode"] == "normal"
|
||||
assert light_4.attributes["supported_color_modes"] == [ColorMode.ONOFF]
|
||||
|
||||
# test gradient light, which groups a segment light per gradient point
|
||||
light_5 = hass.states.get(GRADIENT_LIGHT_ENTITY_ID)
|
||||
assert light_5 is not None
|
||||
assert light_5.attributes["group_entities"] == GRADIENT_SEGMENT_ENTITY_IDS
|
||||
segment_1 = hass.states.get(GRADIENT_SEGMENT_ENTITY_IDS[0])
|
||||
assert segment_1 is not None
|
||||
assert (
|
||||
segment_1.attributes["friendly_name"]
|
||||
== "Hue light with color and color temperature gradient Segment 1"
|
||||
)
|
||||
assert segment_1.state == "on"
|
||||
assert segment_1.attributes["brightness"] == light_5.attributes["brightness"]
|
||||
assert segment_1.attributes["supported_color_modes"] == [ColorMode.XY]
|
||||
assert segment_1.attributes["color_mode"] == ColorMode.XY
|
||||
assert segment_1.attributes["xy_color"] == GRADIENT_POINTS[0]
|
||||
segment_5 = hass.states.get(GRADIENT_SEGMENT_ENTITY_IDS[4])
|
||||
assert segment_5 is not None
|
||||
assert (
|
||||
segment_5.attributes["friendly_name"]
|
||||
== "Hue light with color and color temperature gradient Segment 5"
|
||||
)
|
||||
assert segment_5.attributes["xy_color"] == GRADIENT_POINTS[4]
|
||||
assert (
|
||||
entity_registry.async_get(GRADIENT_SEGMENT_ENTITY_IDS[0]).unique_id
|
||||
== f"{GRADIENT_LIGHT_ID}_segment_1"
|
||||
)
|
||||
assert (
|
||||
entity_registry.async_get(GRADIENT_SEGMENT_ENTITY_IDS[4]).unique_id
|
||||
== f"{GRADIENT_LIGHT_ID}_segment_5"
|
||||
)
|
||||
assert entity_registry.async_get(GRADIENT_LIGHT_ENTITY_ID).hidden_by is None
|
||||
assert (
|
||||
entity_registry.async_get(GRADIENT_SEGMENT_ENTITY_IDS[0]).hidden_by
|
||||
== er.RegistryEntryHider.INTEGRATION
|
||||
)
|
||||
|
||||
|
||||
async def test_light_turn_on_service(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
@@ -451,6 +520,367 @@ async def test_light_turn_off_service(
|
||||
assert mock_bridge_v2.mock_requests[4]["json"]["identify"]["action"] == "identify"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_data", "expected_json"),
|
||||
[
|
||||
pytest.param({}, {}, id="color_only"),
|
||||
pytest.param(
|
||||
{"brightness": 51, "transition": 0.25},
|
||||
{"dimming": {"brightness": 20.0}, "dynamics": {"duration": 200}},
|
||||
id="color_brightness_transition",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_gradient_segment_turn_on_color(
|
||||
hass: HomeAssistant,
|
||||
mock_bridge_v2: Mock,
|
||||
v2_resources_test_data: JsonArrayType,
|
||||
service_data: dict[str, Any],
|
||||
expected_json: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test setting the color of one segment sends the full gradient."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{
|
||||
"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[2],
|
||||
"xy_color": (0.123, 0.456),
|
||||
**service_data,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
# a single PUT request should have been sent to the light with all points
|
||||
expected_points = list(GRADIENT_POINTS)
|
||||
expected_points[2] = (0.123, 0.456)
|
||||
assert len(mock_bridge_v2.mock_requests) == 1
|
||||
assert mock_bridge_v2.mock_requests[0]["method"] == "put"
|
||||
assert (
|
||||
mock_bridge_v2.mock_requests[0]["path"]
|
||||
== f"clip/v2/resource/light/{GRADIENT_LIGHT_ID}"
|
||||
)
|
||||
assert mock_bridge_v2.mock_requests[0]["json"] == {
|
||||
"on": {"on": True},
|
||||
"gradient": gradient_json(expected_points),
|
||||
**expected_json,
|
||||
}
|
||||
|
||||
|
||||
async def test_gradient_segments_turn_on_coalesced(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
) -> None:
|
||||
"""Test concurrent color writes to several segments result in one request."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
colors = {0: (0.1, 0.2), 1: (0.3, 0.4), 4: (0.5, 0.6)}
|
||||
await asyncio.gather(
|
||||
*(
|
||||
hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[index], "xy_color": xy},
|
||||
blocking=True,
|
||||
)
|
||||
for index, xy in colors.items()
|
||||
)
|
||||
)
|
||||
|
||||
expected_points = [
|
||||
colors.get(index, point) for index, point in enumerate(GRADIENT_POINTS)
|
||||
]
|
||||
assert len(mock_bridge_v2.mock_requests) == 1
|
||||
assert mock_bridge_v2.mock_requests[0]["json"] == {
|
||||
"on": {"on": True},
|
||||
"gradient": gradient_json(expected_points),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service", "service_data", "expected_json"),
|
||||
[
|
||||
pytest.param(
|
||||
"turn_on",
|
||||
{"brightness": 51},
|
||||
{"on": {"on": True}, "dimming": {"brightness": 20.0}},
|
||||
id="turn_on_brightness",
|
||||
),
|
||||
pytest.param(
|
||||
"turn_off",
|
||||
{"transition": 0.25},
|
||||
{"on": {"on": False}, "dynamics": {"duration": 200}},
|
||||
id="turn_off_transition",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_gradient_segment_passthrough(
|
||||
hass: HomeAssistant,
|
||||
mock_bridge_v2: Mock,
|
||||
v2_resources_test_data: JsonArrayType,
|
||||
service: str,
|
||||
service_data: dict[str, Any],
|
||||
expected_json: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test on/off and brightness of a segment are sent to the whole light."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
service,
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[1], **service_data},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
assert len(mock_bridge_v2.mock_requests) == 1
|
||||
assert (
|
||||
mock_bridge_v2.mock_requests[0]["path"]
|
||||
== f"clip/v2/resource/light/{GRADIENT_LIGHT_ID}"
|
||||
)
|
||||
assert mock_bridge_v2.mock_requests[0]["json"] == expected_json
|
||||
|
||||
|
||||
async def test_gradient_segment_color_fallback(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
) -> None:
|
||||
"""Test segments use the color of the light while no gradient is active."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
mock_bridge_v2.api.emit_event(
|
||||
"update",
|
||||
{"id": GRADIENT_LIGHT_ID, "type": "light", "gradient": {"points": []}},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
light_color = hass.states.get(GRADIENT_LIGHT_ENTITY_ID).attributes["xy_color"]
|
||||
for entity_id in GRADIENT_SEGMENT_ENTITY_IDS:
|
||||
assert hass.states.get(entity_id).attributes["xy_color"] == light_color
|
||||
|
||||
# a segment write fills the other points with the color of the light
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[1], "xy_color": (0.123, 0.456)},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
expected_points = [light_color] * 5
|
||||
expected_points[1] = (0.123, 0.456)
|
||||
assert len(mock_bridge_v2.mock_requests) == 1
|
||||
assert mock_bridge_v2.mock_requests[0]["json"] == {
|
||||
"on": {"on": True},
|
||||
"gradient": gradient_json(expected_points),
|
||||
}
|
||||
|
||||
|
||||
async def test_gradient_segments_sequential_writes(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
) -> None:
|
||||
"""Test a write keeps the points of a previous write the bridge has not echoed."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
for index, xy_color in ((0, (0.1, 0.2)), (1, (0.3, 0.4))):
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[index], "xy_color": xy_color},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
# the second request carries both new colors
|
||||
expected_points = list(GRADIENT_POINTS)
|
||||
expected_points[0] = (0.1, 0.2)
|
||||
expected_points[1] = (0.3, 0.4)
|
||||
assert len(mock_bridge_v2.mock_requests) == 2
|
||||
assert mock_bridge_v2.mock_requests[1]["json"]["gradient"] == gradient_json(
|
||||
expected_points
|
||||
)
|
||||
|
||||
# once the bridge reports its points those are the baseline again
|
||||
reported_points = [(0.5, 0.5), (0.6, 0.6), (0.7, 0.7), (0.8, 0.8), (0.9, 0.9)]
|
||||
mock_bridge_v2.api.emit_event(
|
||||
"update",
|
||||
{
|
||||
"id": GRADIENT_LIGHT_ID,
|
||||
"type": "light",
|
||||
"gradient": {
|
||||
"points": [
|
||||
{"color": {"xy": {"x": x, "y": y}}} for x, y in reported_points
|
||||
]
|
||||
},
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[2], "xy_color": (0.123, 0.456)},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
expected_points = list(reported_points)
|
||||
expected_points[2] = (0.123, 0.456)
|
||||
assert len(mock_bridge_v2.mock_requests) == 3
|
||||
assert mock_bridge_v2.mock_requests[2]["json"]["gradient"] == gradient_json(
|
||||
expected_points
|
||||
)
|
||||
|
||||
|
||||
async def test_gradient_segments_write_in_flight(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
) -> None:
|
||||
"""Test a write made while another one is in flight builds on that write."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
request_started = asyncio.Event()
|
||||
release_request = asyncio.Event()
|
||||
original_request_call = mock_bridge_v2.async_request_call
|
||||
|
||||
async def held_request_call(task: Any, *args: Any, **kwargs: Any) -> None:
|
||||
if not request_started.is_set():
|
||||
request_started.set()
|
||||
await release_request.wait()
|
||||
await original_request_call(task, *args, **kwargs)
|
||||
|
||||
with patch.object(
|
||||
mock_bridge_v2, "async_request_call", side_effect=held_request_call
|
||||
):
|
||||
first = hass.async_create_task(
|
||||
hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[0], "xy_color": (0.1, 0.2)},
|
||||
blocking=True,
|
||||
)
|
||||
)
|
||||
await request_started.wait()
|
||||
second = hass.async_create_task(
|
||||
hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[1], "xy_color": (0.3, 0.4)},
|
||||
blocking=True,
|
||||
)
|
||||
)
|
||||
# let the second write pass its coalescing window while the first is held
|
||||
await asyncio.sleep(GRADIENT_COALESCE_DELAY * 3)
|
||||
release_request.set()
|
||||
await asyncio.gather(first, second)
|
||||
|
||||
# the second request carries the colors of both writes
|
||||
expected_points = list(GRADIENT_POINTS)
|
||||
expected_points[0] = (0.1, 0.2)
|
||||
expected_points[1] = (0.3, 0.4)
|
||||
assert len(mock_bridge_v2.mock_requests) == 2
|
||||
assert mock_bridge_v2.mock_requests[1]["json"]["gradient"] == gradient_json(
|
||||
expected_points
|
||||
)
|
||||
|
||||
|
||||
async def test_gradient_segments_write_failure(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
) -> None:
|
||||
"""Test a failed request reaches all merged callers and leaves no stale state."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
with patch.object(
|
||||
mock_bridge_v2, "async_request_call", side_effect=HomeAssistantError
|
||||
):
|
||||
results = await asyncio.gather(
|
||||
*(
|
||||
hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[index], "xy_color": xy},
|
||||
blocking=True,
|
||||
)
|
||||
for index, xy in ((0, (0.1, 0.2)), (1, (0.3, 0.4)))
|
||||
),
|
||||
return_exceptions=True,
|
||||
)
|
||||
assert len(results) == 2
|
||||
for result in results:
|
||||
assert isinstance(result, HomeAssistantError)
|
||||
|
||||
# the failed colors are dropped, the next write starts from the light state
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{"entity_id": GRADIENT_SEGMENT_ENTITY_IDS[2], "xy_color": (0.123, 0.456)},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
expected_points = list(GRADIENT_POINTS)
|
||||
expected_points[2] = (0.123, 0.456)
|
||||
assert len(mock_bridge_v2.mock_requests) == 1
|
||||
assert mock_bridge_v2.mock_requests[0]["json"] == {
|
||||
"on": {"on": True},
|
||||
"gradient": gradient_json(expected_points),
|
||||
}
|
||||
|
||||
|
||||
async def test_gradient_segments_turn_off_coalesced(
|
||||
hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType
|
||||
) -> None:
|
||||
"""Test turning off several segments at once results in one request."""
|
||||
await mock_bridge_v2.api.load_test_data(v2_resources_test_data)
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
await asyncio.gather(
|
||||
*(
|
||||
hass.services.async_call(
|
||||
"light", "turn_off", {"entity_id": entity_id}, blocking=True
|
||||
)
|
||||
for entity_id in GRADIENT_SEGMENT_ENTITY_IDS[:3]
|
||||
)
|
||||
)
|
||||
|
||||
assert len(mock_bridge_v2.mock_requests) == 1
|
||||
assert mock_bridge_v2.mock_requests[0]["json"] == {"on": {"on": False}}
|
||||
|
||||
|
||||
async def test_gradient_light_added(hass: HomeAssistant, mock_bridge_v2: Mock) -> None:
|
||||
"""Test a gradient light added to the bridge gets its segment lights."""
|
||||
await mock_bridge_v2.api.load_test_data([FAKE_DEVICE, FAKE_ZIGBEE_CONNECTIVITY])
|
||||
|
||||
await setup_platform(hass, mock_bridge_v2, Platform.LIGHT)
|
||||
|
||||
mock_bridge_v2.api.emit_event("add", FAKE_GRADIENT_LIGHT)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
segment_entity_ids = [
|
||||
f"light.hue_mocked_device_segment_{number}" for number in range(1, 4)
|
||||
]
|
||||
test_entity = hass.states.get("light.hue_mocked_device")
|
||||
assert test_entity is not None
|
||||
assert test_entity.attributes["group_entities"] == segment_entity_ids
|
||||
segment_1 = hass.states.get(segment_entity_ids[0])
|
||||
assert segment_1 is not None
|
||||
assert segment_1.attributes["friendly_name"] == "Hue mocked device Segment 1"
|
||||
assert segment_1.state == "on"
|
||||
assert segment_1.attributes["brightness"] == 128
|
||||
assert segment_1.attributes["xy_color"] == (0.1, 0.2)
|
||||
# the light reports fewer points than it is capable of, the rest shows its color
|
||||
segment_3 = hass.states.get(segment_entity_ids[2])
|
||||
assert segment_3 is not None
|
||||
assert segment_3.attributes["xy_color"] == (0.3127, 0.329)
|
||||
|
||||
|
||||
async def test_light_added(hass: HomeAssistant, mock_bridge_v2: Mock) -> None:
|
||||
"""Test new light added to bridge."""
|
||||
await mock_bridge_v2.api.load_test_data([FAKE_DEVICE, FAKE_ZIGBEE_CONNECTIVITY])
|
||||
|
||||
Reference in New Issue
Block a user