diff --git a/homeassistant/components/hue_ble/const.py b/homeassistant/components/hue_ble/const.py index 25edceb0683e..4f03a685984c 100644 --- a/homeassistant/components/hue_ble/const.py +++ b/homeassistant/components/hue_ble/const.py @@ -3,3 +3,4 @@ DOMAIN = "hue_ble" URL_PAIRING_MODE = "https://www.home-assistant.io/integrations/hue_ble#initial-setup" URL_FACTORY_RESET = "https://www.philips-hue.com/en-gb/support/article/how-to-factory-reset-philips-hue-lights/000004" +EFFECT_SPEED = 117 diff --git a/homeassistant/components/hue_ble/light.py b/homeassistant/components/hue_ble/light.py index c1577b1d756a..8b23e51d7765 100644 --- a/homeassistant/components/hue_ble/light.py +++ b/homeassistant/components/hue_ble/light.py @@ -3,21 +3,27 @@ import logging from typing import TYPE_CHECKING, Any, override -from HueBLE import HueBleLight +from HueBLE import EffectType, HueBleLight from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP_KELVIN, + ATTR_EFFECT, ATTR_XY_COLOR, + EFFECT_OFF, ColorMode, LightEntity, + LightEntityFeature, filter_supported_color_modes, ) from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers.device_registry import CONNECTION_BLUETOOTH, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import color as color_util +from .const import EFFECT_SPEED + _LOGGER = logging.getLogger(__name__) @@ -50,11 +56,36 @@ def get_available_color_modes(api: HueBleLight) -> set[ColorMode]: return filter_supported_color_modes(color_modes) +def _get_effect_name(effect: EffectType | None) -> str | None: + """Return the effect name str or None from EffectType enum.""" + + if effect is None or effect is EffectType.NONE: + return EFFECT_OFF + + return effect.name.lower() + + +def _get_effect_type(effect_name: str | None) -> EffectType | None: + """Return the effect type from the effect name.""" + try: + if effect_name is None: + return None + + if effect_name == EFFECT_OFF: + return EffectType.NONE + + return EffectType[effect_name.upper()] + + except KeyError as e: + raise ServiceValidationError("Unknown effect") from e + + class HueBLELight(LightEntity): """Representation of a light.""" _attr_has_entity_name = True _attr_name = None + _attr_translation_key = "hue_ble_light" def __init__(self, light: HueBleLight) -> None: """Initialize the light object. Does not connect.""" @@ -77,6 +108,11 @@ class HueBLELight(LightEntity): sw_version=light.firmware, ) self._attr_supported_color_modes = get_available_color_modes(self._api) + if self._api.supports_effects and ( + self._api.supports_colour_temp or self._api.supports_colour_xy + ): + self._attr_supported_features = LightEntityFeature.EFFECT + self._attr_effect_list = [str(_get_effect_name(e)) for e in EffectType] self._update_updatable_attributes() @override @@ -91,6 +127,46 @@ class HueBLELight(LightEntity): self._api.remove_callback(self._state_change_callback) + async def _async_set_effect( + self, + **kwargs: Any, + ) -> None: + """Set a light state using the effect API.""" + + brightness = ( + max(1, min(254, kwargs[ATTR_BRIGHTNESS])) + if kwargs.get(ATTR_BRIGHTNESS) + else self._api.brightness + ) + + colour = None + if ATTR_COLOR_TEMP_KELVIN in kwargs: + colour = color_util.color_temperature_kelvin_to_mired( + kwargs[ATTR_COLOR_TEMP_KELVIN] + ) + elif ATTR_XY_COLOR in kwargs: + colour = kwargs[ATTR_XY_COLOR] + else: + colour = ( + self._api.colour_temp + if self._api.colour_temp_mode + else self._api.colour_xy + ) + + effect = None + if ATTR_EFFECT in kwargs: + effect = _get_effect_type(kwargs[ATTR_EFFECT]) + elif self._api.effect: + effect = self._api.effect[0] + + await self._api.set_effect( + power=True, + brightness=brightness, + colour=colour, + effect=effect, + effect_speed=EFFECT_SPEED if effect else None, + ) + def _update_updatable_attributes(self) -> None: """Update this entities updatable attrs from the lights state.""" self._attr_available = self._api.available @@ -102,6 +178,9 @@ class HueBLELight(LightEntity): else None ) self._attr_xy_color = self._api.colour_xy + self._attr_effect = ( + _get_effect_name(self._api.effect[0]) if self._api.effect else None + ) def _state_change_callback(self) -> None: """Run when light informs of state update. Updates local properties.""" @@ -117,7 +196,16 @@ class HueBLELight(LightEntity): async def async_turn_on(self, **kwargs: Any) -> None: """Set properties then turn the light on.""" - _LOGGER.debug("Turning light %s on with args %s", self.name, kwargs) + if self._api.supports_effects: + _LOGGER.debug( + "Turning light %s on with args %s using effects API", self.name, kwargs + ) + await self._async_set_effect(**kwargs) + return + + _LOGGER.debug( + "Turning light %s on with args %s using legacy API", self.name, kwargs + ) if ATTR_BRIGHTNESS in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] diff --git a/homeassistant/components/hue_ble/strings.json b/homeassistant/components/hue_ble/strings.json index 7349f8956a79..b09747bc2961 100644 --- a/homeassistant/components/hue_ble/strings.json +++ b/homeassistant/components/hue_ble/strings.json @@ -28,6 +28,30 @@ } } }, + "entity": { + "light": { + "hue_ble_light": { + "state_attributes": { + "effect": { + "state": { + "candle": "Candle", + "cosmos": "Cosmos", + "enchant": "Enchant", + "fireplace": "Fireplace", + "glisten": "Glisten", + "opal": "Opal", + "prism": "Prism", + "sparkle": "Sparkle", + "sunbeam": "Sunbeam", + "sunrise": "Sunrise", + "sunset": "Sunset", + "underwater": "Underwater" + } + } + } + } + } + }, "exceptions": { "device_not_found": { "message": "The light {name} ({mac}) was not found: {reason}" diff --git a/tests/components/hue_ble/conftest.py b/tests/components/hue_ble/conftest.py index 7354c5e904fa..a067d47c87df 100644 --- a/tests/components/hue_ble/conftest.py +++ b/tests/components/hue_ble/conftest.py @@ -1,6 +1,6 @@ """Common fixtures for the Hue BLE tests.""" -from collections.abc import Generator +from collections.abc import Callable, Generator from unittest.mock import AsyncMock, patch import pytest @@ -8,6 +8,7 @@ from pytest_homeassistant.common import MockConfigEntry from pytest_homeassistant.components.bluetooth import generate_ble_device from homeassistant.components.hue_ble.const import DOMAIN +from homeassistant.components.hue_ble.light import EffectType from . import TEST_DEVICE_MAC, TEST_DEVICE_NAME @@ -74,9 +75,72 @@ def mock_light() -> Generator[AsyncMock]: client.supports_colour_temp = True client.supports_brightness = True client.supports_on_off = True + client.supports_effects = False client.available = True client.power_state = True client.brightness = 100 client.colour_temp = 250 - client.colour_xy = (0.5, 0.5) + client.colour_xy = (0.0, 0.0) + client.colour_temp_mode = True + client.effect = None + client._state_changed_callbacks = [] + + def add_callback_on_state_changed(function: Callable[[], None]): + client._state_changed_callbacks.append(function) + + def remove_callback(function: Callable[[], None]) -> None: + client._state_changed_callbacks.remove(function) + + def run_callbacks() -> None: + [function() for function in client._state_changed_callbacks] + + async def mock_set_power(on: bool): + client.power_state = on + run_callbacks() + + async def mock_set_brightness(brightness: int): + client.brightness = brightness + run_callbacks() + + async def mock_set_colour_temp(colour_temp: int): + client.colour_temp = colour_temp + client.colour_temp_mode = True + run_callbacks() + + async def mock_set_colour_xy(x: float, y: float): + client.colour_xy = (x, y) + client.colour_temp_mode = False + run_callbacks() + + async def mock_set_effect( + power: bool | None = None, + brightness: int | None = None, + colour: int | tuple[float, float] | None = None, + effect: EffectType | None = None, + effect_speed: int | None = None, + transition: int | None = None, + ): + client.power_state = power or client.power_state + client.brightness = brightness or client.brightness + client.colour_temp = colour if type(colour) is int else client.colour_temp + client.colour_xy = colour if type(colour) is tuple else client.colour_xy + client.effect = ( + effect + if effect is not None + else (client.effect[0] if client.effect else None), + effect_speed + if effect_speed is not None + else (client.effect[1] if client.effect else None), + ) + client.colour_temp_mode = type(colour) is int + run_callbacks() + + client.add_callback_on_state_changed = add_callback_on_state_changed + client.remove_callback = remove_callback + client.set_power = AsyncMock(side_effect=mock_set_power) + client.set_brightness = AsyncMock(side_effect=mock_set_brightness) + client.set_colour_temp = AsyncMock(side_effect=mock_set_colour_temp) + client.set_colour_xy = AsyncMock(side_effect=mock_set_colour_xy) + client.set_effect = AsyncMock(side_effect=mock_set_effect) + yield client diff --git a/tests/components/hue_ble/snapshots/test_light.ambr b/tests/components/hue_ble/snapshots/test_light.ambr index 9c51829d917b..3d27cc2bc3ad 100644 --- a/tests/components/hue_ble/snapshots/test_light.ambr +++ b/tests/components/hue_ble/snapshots/test_light.ambr @@ -38,7 +38,7 @@ 'previous_unique_id': None, 'suggested_object_id': None, 'supported_features': 0, - 'translation_key': None, + 'translation_key': 'hue_ble_light', 'unique_id': 'AA:BB:CC:DD:EE:FF', 'unit_of_measurement': None, }) diff --git a/tests/components/hue_ble/test_light.py b/tests/components/hue_ble/test_light.py index ad6b797b4842..91e133d9bfc8 100644 --- a/tests/components/hue_ble/test_light.py +++ b/tests/components/hue_ble/test_light.py @@ -2,13 +2,30 @@ from unittest.mock import AsyncMock +from HueBLE import EffectType +import pytest from pytest_homeassistant.common import MockConfigEntry, snapshot_platform from syrupy.assertion import SnapshotAssertion +from homeassistant.components.hue_ble.const import EFFECT_SPEED +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, + ATTR_COLOR_MODE, + ATTR_COLOR_TEMP_KELVIN, + ATTR_EFFECT, + ATTR_XY_COLOR, + DOMAIN as LIGHT_DOMAIN, + EFFECT_OFF, + ColorMode, +) from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import entity_registry as er +from . import TEST_DEVICE_NAME + async def test_light( hass: HomeAssistant, @@ -25,3 +42,306 @@ async def test_light( assert mock_config_entry.state is ConfigEntryState.LOADED await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "supports_effects_api", + [pytest.param(False, id="legacy_api"), pytest.param(True, id="effects_api")], +) +async def test_light_control_basic( + hass: HomeAssistant, + mock_light: AsyncMock, + mock_config_entry: MockConfigEntry, + supports_effects_api: bool, +) -> None: + """Test on/off and brightness control.""" + mock_light.supports_effects = supports_effects_api + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.LOADED + + entity_id = f"light.{TEST_DEVICE_NAME.lower().replace(' ', '_')}" + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_BRIGHTNESS] == 100 + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_off", + {ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "off" + assert not mock_light.power_state + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 50}, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_BRIGHTNESS] == 50 + assert mock_light.power_state + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 200}, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_BRIGHTNESS] == 200 + assert mock_light.power_state + + +async def test_light_control_color_temp( + hass: HomeAssistant, + mock_light: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test color temperature control.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.LOADED + + entity_id = f"light.{TEST_DEVICE_NAME.lower().replace(' ', '_')}" + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_COLOR_TEMP_KELVIN] == 4000 + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert mock_light.colour_temp == 250 + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + {ATTR_ENTITY_ID: entity_id, ATTR_COLOR_TEMP_KELVIN: 3000}, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_COLOR_TEMP_KELVIN] == 3003 + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert mock_light.colour_temp == 333 + + +async def test_light_control_color_xy( + hass: HomeAssistant, + mock_light: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test color (xy) control.""" + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.LOADED + + entity_id = f"light.{TEST_DEVICE_NAME.lower().replace(' ', '_')}" + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_XY_COLOR] == (0.42, 0.365) + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert mock_light.colour_xy == (0.0, 0.0) + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + {ATTR_ENTITY_ID: entity_id, ATTR_XY_COLOR: (0.1, 0.1)}, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_XY_COLOR] == (0.1, 0.1) + assert attributes[ATTR_COLOR_MODE] == ColorMode.XY + assert mock_light.colour_xy == (0.1, 0.1) + + +async def test_light_control_effect_xy( + hass: HomeAssistant, + mock_light: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test color effect control.""" + + mock_light.supports_effects = True + mock_light.effect = EffectType.NONE, EFFECT_SPEED + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.LOADED + + entity_id = f"light.{TEST_DEVICE_NAME.lower().replace(' ', '_')}" + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_EFFECT] == EFFECT_OFF + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + { + ATTR_ENTITY_ID: entity_id, + ATTR_EFFECT: EffectType.CANDLE.name.lower(), + ATTR_XY_COLOR: (0.3, 0.3), + }, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_EFFECT] == EffectType.CANDLE.name.lower() + assert attributes[ATTR_XY_COLOR] == (0.3, 0.3) + assert attributes[ATTR_COLOR_MODE] == ColorMode.XY + assert mock_light.effect == (EffectType.CANDLE, EFFECT_SPEED) + assert not mock_light.colour_temp_mode + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + { + ATTR_ENTITY_ID: entity_id, + ATTR_XY_COLOR: (0.5, 0.5), + }, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_EFFECT] == EffectType.CANDLE.name.lower() + assert attributes[ATTR_XY_COLOR] == (0.5, 0.5) + assert attributes[ATTR_COLOR_MODE] == ColorMode.XY + assert mock_light.effect == (EffectType.CANDLE, EFFECT_SPEED) + assert not mock_light.colour_temp_mode + + +async def test_light_control_effect_temp( + hass: HomeAssistant, + mock_light: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test temperature effect control.""" + + mock_light.supports_effects = True + mock_light.effect = EffectType.NONE, EFFECT_SPEED + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.LOADED + + entity_id = f"light.{TEST_DEVICE_NAME.lower().replace(' ', '_')}" + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_EFFECT] == EFFECT_OFF + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + {ATTR_ENTITY_ID: entity_id, ATTR_EFFECT: EffectType.COSMOS.name.lower()}, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_EFFECT] == EffectType.COSMOS.name.lower() + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert mock_light.effect == (EffectType.COSMOS, EFFECT_SPEED) + assert mock_light.colour_temp_mode + + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + { + ATTR_ENTITY_ID: entity_id, + ATTR_EFFECT: EffectType.CANDLE.name.lower(), + ATTR_XY_COLOR: (0.3, 0.3), + }, + blocking=True, + ) + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + {ATTR_ENTITY_ID: entity_id, ATTR_COLOR_TEMP_KELVIN: 4000}, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_EFFECT] == EffectType.CANDLE.name.lower() + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert attributes[ATTR_COLOR_TEMP_KELVIN] == 4000 + assert mock_light.effect == (EffectType.CANDLE, EFFECT_SPEED) + assert mock_light.colour_temp_mode + + +async def test_light_bad_effect( + hass: HomeAssistant, + mock_light: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test trying to set an invalid effect.""" + + mock_light.supports_effects = True + mock_light.effect = EffectType.NONE, EFFECT_SPEED + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.LOADED + + entity_id = f"light.{TEST_DEVICE_NAME.lower().replace(' ', '_')}" + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_EFFECT] == EFFECT_OFF + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + + with pytest.raises(ServiceValidationError): + await hass.services.async_call( + LIGHT_DOMAIN, + "turn_on", + { + ATTR_ENTITY_ID: entity_id, + ATTR_EFFECT: "invalid_effect_name", + ATTR_XY_COLOR: (0.3, 0.3), + }, + blocking=True, + ) + + state = hass.states.get(entity_id) + assert state.state == "on" + attributes = state.attributes + assert attributes[ATTR_EFFECT] == EFFECT_OFF + assert attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP