Skip to content
Merged
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
43 changes: 39 additions & 4 deletions custom_components/tronbytassistant/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@

from homeassistant.components.light import ATTR_BRIGHTNESS, ColorMode, LightEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.helpers.entity import EntityCategory

Expand Down Expand Up @@ -99,7 +100,7 @@ async def async_setup_entry(
async_add_entities(entities)


class TronbytLight(CoordinatorEntity, LightEntity):
class TronbytLight(CoordinatorEntity, LightEntity, RestoreEntity):
"""Brightness style light bound to a Tronbyt device attribute."""

_attr_supported_color_modes = {ColorMode.BRIGHTNESS}
Expand All @@ -119,6 +120,40 @@ def __init__(
self._attr_icon = description.icon
self._attr_translation_key = description.translation_key
self._attr_entity_category = description.entity_category
self._last_brightness: int | None = None

async def async_added_to_hass(self) -> None:
await super().async_added_to_hass()
last_state = await self.async_get_last_state()
if last_state:
stored = last_state.attributes.get("last_brightness")
if stored is None:
stored = last_state.attributes.get(ATTR_BRIGHTNESS)
if stored is not None:
try:
self._last_brightness = int(stored)
except (TypeError, ValueError):
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
_LOGGER.debug(
"Ignoring invalid restored brightness for %s: %r",
self.entity_id,
stored,
)
current = self.brightness
if current:
self._last_brightness = current

@callback
def _handle_coordinator_update(self) -> None:
current = self.brightness
if current:
self._last_brightness = current
super()._handle_coordinator_update()

@property
def extra_state_attributes(self) -> dict[str, Any]:
if self._last_brightness is not None:
return {"last_brightness": self._last_brightness}
return {}

def _device(self) -> Optional[dict[str, Any]]:
for device in self.coordinator.data or []:
Expand Down Expand Up @@ -157,8 +192,8 @@ async def async_turn_on(self, **kwargs: Any) -> None:
brightness = int(kwargs[ATTR_BRIGHTNESS])
else:
brightness = self.brightness
if brightness is None:
brightness = self._description.default_on
if not brightness:
brightness = self._last_brightness or self._description.default_on

brightness = max(BRIGHTNESS_MIN, min(BRIGHTNESS_MAX, brightness))
api_value = int(round((brightness / BRIGHTNESS_MAX) * BRIGHTNESS_API_MAX))
Expand Down
38 changes: 38 additions & 0 deletions tests/test_entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,44 @@ async def test_light_brightness_and_controls(coordinator: TronbytCoordinator):
coordinator.async_patch_device.assert_awaited_once_with("dev1", {"brightness": 0})


@pytest.mark.asyncio
async def test_light_restores_last_brightness_after_off(
coordinator: TronbytCoordinator,
):
"""turn_on with no args should restore the last non-zero brightness."""
entity = light_mod.TronbytLight(
coordinator, "dev1", light_mod.LIGHT_DESCRIPTIONS[0]
)
coordinator.async_patch_device = AsyncMock()
entity.async_write_ha_state = lambda: None

entity._handle_coordinator_update()
assert entity._last_brightness == 204 # 80% in 0-255

coordinator.data[0]["brightness"] = 0
entity._handle_coordinator_update()
assert entity.is_on is False
assert entity._last_brightness == 204

await entity.async_turn_on()
coordinator.async_patch_device.assert_awaited_once_with("dev1", {"brightness": 80})


@pytest.mark.asyncio
async def test_light_falls_back_to_default_when_no_history(
coordinator: TronbytCoordinator,
):
"""With no cached brightness and device at 0, fall back to default_on."""
coordinator.data[0]["brightness"] = 0
entity = light_mod.TronbytLight(
coordinator, "dev1", light_mod.LIGHT_DESCRIPTIONS[0]
)
coordinator.async_patch_device = AsyncMock()

await entity.async_turn_on()
coordinator.async_patch_device.assert_awaited_once_with("dev1", {"brightness": 100})


@pytest.mark.asyncio
async def test_night_mode_brightness_defaults(coordinator: TronbytCoordinator):
"""Night mode light should use the default on value if brightness unavailable."""
Expand Down
Loading