Compare commits

...

1 Commits

Author SHA1 Message Date
Paul Bottein cbb6789031 Add time platform to Yoto 2026-06-12 16:54:27 +02:00
11 changed files with 378 additions and 23 deletions
+1 -1
View File
@@ -19,7 +19,7 @@ from homeassistant.helpers.config_entry_oauth2_flow import (
from .const import DOMAIN
from .coordinator import YotoConfigEntry, YotoDataUpdateCoordinator
PLATFORMS: list[Platform] = [Platform.MEDIA_PLAYER]
PLATFORMS: list[Platform] = [Platform.MEDIA_PLAYER, Platform.TIME]
async def async_setup_entry(hass: HomeAssistant, entry: YotoConfigEntry) -> bool:
+31 -1
View File
@@ -1,7 +1,10 @@
"""Base entity for the Yoto integration."""
from yoto_api import YotoPlayer
from typing import Any
from yoto_api import YotoError, YotoPlayer
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
@@ -44,3 +47,30 @@ class YotoEntity(CoordinatorEntity[YotoDataUpdateCoordinator]):
def available(self) -> bool:
"""Return if the entity is available."""
return super().available and self._player_id in self.coordinator.data
class YotoPlayerEntity(YotoEntity):
"""Base class for entities reflecting live player state over MQTT."""
@property
def available(self) -> bool:
"""Return if the entity is available."""
return super().available and bool(self.player.is_online)
class YotoConfigEntity(YotoEntity):
"""Base class for entities that write player settings over REST."""
async def _async_set_config(self, **fields: Any) -> None:
"""Write player config fields and refresh the local copy."""
client = self.coordinator.client
try:
await client.set_player_config(self._player_id, **fields)
await client.update_player_info(self._player_id)
except YotoError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="config_update_failed",
translation_placeholders={"error": str(err)},
) from err
self.coordinator.async_set_updated_data(client.players)
+12
View File
@@ -0,0 +1,12 @@
{
"entity": {
"time": {
"day_mode_start": {
"default": "mdi:weather-sunny"
},
"night_mode_start": {
"default": "mdi:weather-night"
}
}
}
}
@@ -22,7 +22,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN
from .coordinator import YotoConfigEntry, YotoDataUpdateCoordinator
from .entity import YotoEntity
from .entity import YotoPlayerEntity
URI_SCHEME = "yoto"
URI_CARD = "card"
@@ -53,7 +53,7 @@ async def async_setup_entry(
)
class YotoMediaPlayer(YotoEntity, MediaPlayerEntity):
class YotoMediaPlayer(YotoPlayerEntity, MediaPlayerEntity):
"""Representation of a Yoto Player."""
_attr_name = None
@@ -82,11 +82,6 @@ class YotoMediaPlayer(YotoEntity, MediaPlayerEntity):
super().__init__(coordinator, player)
self._attr_unique_id = player.id
@property
def available(self) -> bool:
"""Return whether the player is reachable through the Yoto cloud."""
return super().available and bool(self.player.is_online)
@property
def state(self) -> MediaPlayerState:
"""Return the playback state."""
@@ -57,20 +57,14 @@ rules:
docs-troubleshooting: todo
docs-use-cases: todo
dynamic-devices: todo
entity-category:
status: exempt
comment: Only the media_player entity ships in this PR; no diagnostic entities yet.
entity-category: done
entity-device-class: done
entity-disabled-by-default:
status: exempt
comment: Only the media_player entity ships in this PR; no entities are disabled by default.
entity-translations:
status: exempt
comment: The media_player uses the device name; no translatable strings yet.
comment: No noisy or less popular entities; nothing is disabled by default.
entity-translations: done
exception-translations: done
icon-translations:
status: exempt
comment: No custom icon translations are needed yet.
icon-translations: done
reconfiguration-flow:
status: exempt
comment: Authorization is the only configuration; reauth covers re-linking the account.
@@ -36,6 +36,16 @@
}
}
},
"entity": {
"time": {
"day_mode_start": {
"name": "Day mode start"
},
"night_mode_start": {
"name": "Night mode start"
}
}
},
"exceptions": {
"authentication_failed": {
"message": "Yoto credentials are no longer valid. Please reauthenticate your account."
@@ -46,6 +56,9 @@
"command_failed": {
"message": "Yoto command failed: {error}"
},
"config_update_failed": {
"message": "Failed to update Yoto player settings: {error}"
},
"invalid_media_id": {
"message": "Not a Yoto media identifier: {media_id}"
},
+86
View File
@@ -0,0 +1,86 @@
"""Time platform for the Yoto integration."""
from collections.abc import Callable
from dataclasses import dataclass
from datetime import time
from yoto_api import PlayerConfig, YotoPlayer
from homeassistant.components.time import TimeEntity, TimeEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import YotoConfigEntry, YotoDataUpdateCoordinator
from .entity import YotoConfigEntity
PARALLEL_UPDATES = 1
@dataclass(frozen=True, kw_only=True)
class YotoTimeEntityDescription(TimeEntityDescription):
"""Describes a Yoto time entity.
``config_field`` is the ``set_player_config`` kwarg written on change.
"""
value_fn: Callable[[PlayerConfig], time | None]
config_field: str
TIME_ENTITIES: tuple[YotoTimeEntityDescription, ...] = (
YotoTimeEntityDescription(
key="day_mode_start",
translation_key="day_mode_start",
entity_category=EntityCategory.CONFIG,
value_fn=lambda config: config.day_time,
config_field="day_time",
),
YotoTimeEntityDescription(
key="night_mode_start",
translation_key="night_mode_start",
entity_category=EntityCategory.CONFIG,
value_fn=lambda config: config.night_time,
config_field="night_time",
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: YotoConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Yoto time platform."""
coordinator = entry.runtime_data
async_add_entities(
YotoTime(coordinator, player, description)
for player in coordinator.client.players.values()
for description in TIME_ENTITIES
)
class YotoTime(YotoConfigEntity, TimeEntity):
"""Representation of a Yoto player config time."""
entity_description: YotoTimeEntityDescription
def __init__(
self,
coordinator: YotoDataUpdateCoordinator,
player: YotoPlayer,
description: YotoTimeEntityDescription,
) -> None:
"""Initialize the time entity."""
super().__init__(coordinator, player)
self.entity_description = description
self._attr_unique_id = f"{player.id}_{description.key}"
@property
def native_value(self) -> time | None:
"""Return the configured time."""
return self.entity_description.value_fn(self.player.info.config)
async def async_set_value(self, value: time) -> None:
"""Update the configured time."""
await self._async_set_config(**{self.entity_description.config_field: value})
+6 -1
View File
@@ -1,7 +1,7 @@
"""Fixtures for the Yoto integration tests."""
from collections.abc import Generator
from datetime import UTC, datetime
from datetime import UTC, datetime, time as dt_time
import time
from unittest.mock import AsyncMock, MagicMock, patch
@@ -14,6 +14,7 @@ from yoto_api import (
Group,
PlaybackEvent,
PlaybackStatus,
PlayerConfig,
PlayerInfo,
Track,
YotoPlayer,
@@ -87,6 +88,10 @@ def _build_player() -> YotoPlayer:
player.info = PlayerInfo(
firmware_version="v2.17.5",
mac="aa:bb:cc:dd:ee:ff",
config=PlayerConfig(
day_time=dt_time(7, 0),
night_time=dt_time(19, 0),
),
)
player.last_event = PlaybackEvent(
player_id=PLAYER_ID,
@@ -0,0 +1,101 @@
# serializer version: 1
# name: test_all_entities[time.nursery_yoto_day_mode_start-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'time',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'time.nursery_yoto_day_mode_start',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Day mode start',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Day mode start',
'platform': 'yoto',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'day_mode_start',
'unique_id': 'player-test_day_mode_start',
'unit_of_measurement': None,
})
# ---
# name: test_all_entities[time.nursery_yoto_day_mode_start-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Nursery Yoto Day mode start',
}),
'context': <ANY>,
'entity_id': 'time.nursery_yoto_day_mode_start',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '07:00:00',
})
# ---
# name: test_all_entities[time.nursery_yoto_night_mode_start-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'time',
'entity_category': <EntityCategory.CONFIG: 'config'>,
'entity_id': 'time.nursery_yoto_night_mode_start',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Night mode start',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Night mode start',
'platform': 'yoto',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'night_mode_start',
'unique_id': 'player-test_night_mode_start',
'unit_of_measurement': None,
})
# ---
# name: test_all_entities[time.nursery_yoto_night_mode_start-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'Nursery Yoto Night mode start',
}),
'context': <ANY>,
'entity_id': 'time.nursery_yoto_night_mode_start',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '19:00:00',
})
# ---
+4 -3
View File
@@ -1,7 +1,7 @@
"""Tests for the Yoto media player platform."""
from typing import Any
from unittest.mock import MagicMock
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
@@ -22,7 +22,7 @@ from homeassistant.components.media_player import (
SERVICE_VOLUME_SET,
MediaPlayerState,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import entity_registry as er
@@ -68,7 +68,8 @@ async def test_entity_state(
) -> None:
"""Snapshot the media player entity state."""
freezer.move_to("2026-05-08T12:00:00+00:00")
await setup_integration(hass, mock_config_entry)
with patch("homeassistant.components.yoto.PLATFORMS", [Platform.MEDIA_PLAYER]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
+118
View File
@@ -0,0 +1,118 @@
"""Tests for the Yoto time platform."""
from datetime import time
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from yoto_api import YotoError
from homeassistant.components.time import (
ATTR_TIME,
DOMAIN as TIME_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from .conftest import PLAYER_ID
from tests.common import MockConfigEntry, snapshot_platform
pytestmark = pytest.mark.usefixtures("setup_credentials")
async def _setup(hass: HomeAssistant, mock_config_entry: MockConfigEntry) -> None:
"""Set up the integration with only the time platform."""
with patch("homeassistant.components.yoto.PLATFORMS", [Platform.TIME]):
await setup_integration(hass, mock_config_entry)
@pytest.mark.usefixtures("mock_yoto_client")
async def test_all_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot every Yoto time entity."""
await _setup(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_available_when_offline(
hass: HomeAssistant,
mock_yoto_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Config is written over REST, so entities stay available when offline."""
player = next(iter(mock_yoto_client.players.values()))
player.is_online = False
await _setup(hass, mock_config_entry)
state = hass.states.get("time.nursery_yoto_day_mode_start")
assert state is not None
assert state.state != STATE_UNAVAILABLE
@pytest.mark.parametrize(
("entity_id", "expected_fields"),
[
pytest.param(
"time.nursery_yoto_day_mode_start",
{"day_time": time(8, 30)},
id="day-mode-start",
),
pytest.param(
"time.nursery_yoto_night_mode_start",
{"night_time": time(8, 30)},
id="night-mode-start",
),
],
)
async def test_set_value(
hass: HomeAssistant,
mock_yoto_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
expected_fields: dict[str, time],
) -> None:
"""Setting a time writes the matching player config field."""
await _setup(hass, mock_config_entry)
await hass.services.async_call(
TIME_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_TIME: time(8, 30)},
blocking=True,
)
mock_yoto_client.set_player_config.assert_awaited_once_with(
PLAYER_ID, **expected_fields
)
mock_yoto_client.update_player_info.assert_awaited_once_with(PLAYER_ID)
async def test_set_value_failure(
hass: HomeAssistant,
mock_yoto_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""A failed config write raises a Home Assistant error."""
await _setup(hass, mock_config_entry)
mock_yoto_client.set_player_config.side_effect = YotoError("MQTT timeout")
with pytest.raises(
HomeAssistantError, match="Failed to update Yoto player settings"
):
await hass.services.async_call(
TIME_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: "time.nursery_yoto_day_mode_start", ATTR_TIME: time(7, 0)},
blocking=True,
)