Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add twinkly select mode #134041

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion homeassistant/components/twinkly/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from .const import DOMAIN
from .coordinator import TwinklyCoordinator

PLATFORMS = [Platform.LIGHT]
PLATFORMS = [Platform.LIGHT, Platform.SELECT]

_LOGGER = logging.getLogger(__name__)

Expand Down
4 changes: 4 additions & 0 deletions homeassistant/components/twinkly/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class TwinklyData:
is_on: bool
movies: dict[int, str]
current_movie: int | None
current_mode: str | None


class TwinklyCoordinator(DataUpdateCoordinator[TwinklyData]):
Expand Down Expand Up @@ -66,6 +67,8 @@ async def _async_update_data(self) -> TwinklyData:
device_info = await self.client.get_details()
brightness = await self.client.get_brightness()
is_on = await self.client.is_on()
mode_data = await self.client.get_mode()
current_mode = mode_data.get("mode")
if self.supports_effects:
movies = (await self.client.get_saved_movies())["movies"]
except (TimeoutError, ClientError) as exception:
Expand All @@ -87,6 +90,7 @@ async def _async_update_data(self) -> TwinklyData:
is_on,
{movie["id"]: movie["name"] for movie in movies},
current_movie.get("id"),
current_mode,
)

def _async_update_device_info(self, name: str) -> None:
Expand Down
63 changes: 63 additions & 0 deletions homeassistant/components/twinkly/select.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""The Twinkly select component."""

from __future__ import annotations

import logging

from ttls.client import TWINKLY_MODES

from homeassistant.components.select import SelectEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import TwinklyConfigEntry, TwinklyCoordinator
from .const import DEV_MODEL, DEV_NAME, DOMAIN

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
hass: HomeAssistant,
config_entry: TwinklyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Setups a mode select from a config entry."""
entity = TwinklyModeSelect(config_entry.runtime_data)
async_add_entities([entity], update_before_add=True)


class TwinklyModeSelect(CoordinatorEntity[TwinklyCoordinator], SelectEntity):
"""Twinkly Mode Selection."""

_attr_has_entity_name = True
_attr_name = "Mode"
_attr_options = TWINKLY_MODES

def __init__(self, coordinator: TwinklyCoordinator) -> None:
"""Initialize TwinklyModeSelect."""
super().__init__(coordinator)
device_info = coordinator.data.device_info
mac = device_info["mac"]

self._attr_unique_id = f"{mac}_mode"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, mac)},
connections={(CONNECTION_NETWORK_MAC, mac)},
manufacturer="LEDWORKS",
model=device_info[DEV_MODEL],
name=device_info[DEV_NAME],
sw_version=coordinator.software_version,
)
self.client = coordinator.client

@property
def current_option(self) -> str | None:
"""Return current mode."""
return self.coordinator.data.current_mode

async def async_select_option(self, option: str) -> None:
"""Change the selected option."""
await self.client.set_mode(option)
await self.coordinator.async_refresh()
1 change: 1 addition & 0 deletions tests/components/twinkly/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def mock_twinkly_client() -> Generator[AsyncMock]:
client.get_current_movie.return_value = load_json_object_fixture(
"get_current_movie.json", DOMAIN
)
client.get_mode.return_value = load_json_object_fixture("get_mode.json", DOMAIN)
client.is_on.return_value = True
client.get_brightness.return_value = {"mode": "enabled", "value": 10}
client.host = "192.168.0.123"
Expand Down
3 changes: 3 additions & 0 deletions tests/components/twinkly/fixtures/get_mode.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"mode": "color"
}
66 changes: 66 additions & 0 deletions tests/components/twinkly/snapshots/test_select.ambr
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# serializer version: 1
# name: test_select_entities[select.tree_1_mode-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'options': list([
'color',
'demo',
'effect',
'movie',
'off',
'playlist',
'rt',
]),
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'select',
'entity_category': None,
'entity_id': 'select.tree_1_mode',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Mode',
'platform': 'twinkly',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': '00:2d:13:3b:aa:bb_mode',
'unit_of_measurement': None,
})
# ---
# name: test_select_entities[select.tree_1_mode-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Tree 1 Mode',
'options': list([
'color',
'demo',
'effect',
'movie',
'off',
'playlist',
'rt',
]),
}),
'context': <ANY>,
'entity_id': 'select.tree_1_mode',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'color',
})
# ---
77 changes: 77 additions & 0 deletions tests/components/twinkly/test_select.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""Tests for the Twinkly select component."""

from __future__ import annotations

from datetime import timedelta
from unittest.mock import AsyncMock, patch

from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy import SnapshotAssertion

from homeassistant.components.select import DOMAIN as SELECT_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, ATTR_OPTION, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er

from . import setup_integration

from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform


@pytest.mark.usefixtures("mock_twinkly_client")
async def test_select_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the created select entities."""
with patch("homeassistant.components.twinkly.PLATFORMS", [Platform.SELECT]):
await setup_integration(hass, mock_config_entry)

await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)


async def test_select_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_twinkly_client: AsyncMock,
) -> None:
"""Test selecting a mode."""
await setup_integration(hass, mock_config_entry)

state = hass.states.get("select.tree_1_mode")
assert state is not None
assert state.state == "color"

await hass.services.async_call(
SELECT_DOMAIN,
"select_option",
{
ATTR_ENTITY_ID: "select.tree_1_mode",
ATTR_OPTION: "movie",
},
blocking=True,
)

mock_twinkly_client.set_mode.assert_called_once_with("movie")
mock_twinkly_client.interview.assert_not_called()


async def test_mode_unavailable(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_twinkly_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test handling of unavailable mode data."""
await setup_integration(hass, mock_config_entry)

mock_twinkly_client.get_mode.side_effect = Exception
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done()

state = hass.states.get("select.tree_1_mode")
assert state.state == STATE_UNAVAILABLE