Compare commits

..

3 Commits

Author SHA1 Message Date
Paul Bottein ce0bc2f18f Make battery sensor diagnostic 2026-06-13 21:44:10 +02:00
Paul Bottein ca6e45d8d8 Remove extended status 2026-06-13 21:44:10 +02:00
Paul Bottein 4c3ff8d7c1 Add sensors to Yoto
Add the sensor platform: battery, card slot and day mode, plus power
source, SSID and Wi-Fi RSSI as diagnostics (RSSI disabled by default).

Move the online check to the base entity so all entities (including the
media player) report unavailable when the player is offline.
2026-06-13 21:43:28 +02:00
9 changed files with 381 additions and 7 deletions
+5 -1
View File
@@ -19,7 +19,11 @@ from homeassistant.helpers.config_entry_oauth2_flow import (
from .const import DOMAIN
from .coordinator import YotoConfigEntry, YotoDataUpdateCoordinator
PLATFORMS: list[Platform] = [Platform.MEDIA_PLAYER, Platform.TIME]
PLATFORMS: list[Platform] = [
Platform.MEDIA_PLAYER,
Platform.SENSOR,
Platform.TIME,
]
async def async_setup_entry(hass: HomeAssistant, entry: YotoConfigEntry) -> bool:
@@ -148,8 +148,6 @@ class YotoDataUpdateCoordinator(DataUpdateCoordinator[dict[str, YotoPlayer]]):
"""Ask each player to push a fresh status snapshot over MQTT."""
if not self.client.is_mqtt_connected:
return
# Fire-and-forget: the data/status response lands via the on_update
# callback later, which already triggers async_set_updated_data.
for device_id in list(self.client.players):
await self.client.request_player_status(device_id)
+18
View File
@@ -1,5 +1,23 @@
{
"entity": {
"sensor": {
"card_insertion_state": {
"default": "mdi:card-bulleted-outline",
"state": {
"none": "mdi:card-bulleted-off-outline",
"physical": "mdi:card-bulleted",
"remote": "mdi:cast-audio",
"streaming": "mdi:radio-tower"
}
},
"day_mode": {
"default": "mdi:theme-light-dark",
"state": {
"day": "mdi:weather-sunny",
"night": "mdi:weather-night"
}
}
},
"time": {
"day_mode_start": {
"default": "mdi:weather-sunny"
+103
View File
@@ -0,0 +1,103 @@
"""Sensor platform for the Yoto integration."""
from collections.abc import Callable
from dataclasses import dataclass
from yoto_api import CardInsertionState, DayMode, YotoPlayer
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import PERCENTAGE, EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .coordinator import YotoConfigEntry, YotoDataUpdateCoordinator
from .entity import YotoPlayerEntity
PARALLEL_UPDATES = 0
def _enum_state(value: CardInsertionState | None) -> str | None:
"""Return an enum member as a lowercase string, or None if unset."""
return value.name.lower() if value is not None else None
def _day_mode_state(value: DayMode | None) -> str | None:
"""Return day/night, treating the firmware's UNKNOWN as unset."""
if value is None or value is DayMode.UNKNOWN:
return None
return value.name.lower()
@dataclass(frozen=True, kw_only=True)
class YotoSensorEntityDescription(SensorEntityDescription):
"""Describes a Yoto sensor entity."""
value_fn: Callable[[YotoPlayer], StateType]
SENSORS: tuple[YotoSensorEntityDescription, ...] = (
YotoSensorEntityDescription(
key="battery_level",
device_class=SensorDeviceClass.BATTERY,
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda player: player.status.battery_level_percentage,
),
YotoSensorEntityDescription(
key="card_insertion_state",
translation_key="card_insertion_state",
device_class=SensorDeviceClass.ENUM,
options=[state.name.lower() for state in CardInsertionState],
value_fn=lambda player: _enum_state(player.status.card_insertion_state),
),
YotoSensorEntityDescription(
key="day_mode",
translation_key="day_mode",
device_class=SensorDeviceClass.ENUM,
options=["day", "night"],
value_fn=lambda player: _day_mode_state(player.status.day_mode),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: YotoConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Yoto sensor platform."""
coordinator = entry.runtime_data
async_add_entities(
YotoSensor(coordinator, player, description)
for player in coordinator.client.players.values()
for description in SENSORS
)
class YotoSensor(YotoPlayerEntity, SensorEntity):
"""Representation of a Yoto player sensor."""
entity_description: YotoSensorEntityDescription
def __init__(
self,
coordinator: YotoDataUpdateCoordinator,
player: YotoPlayer,
description: YotoSensorEntityDescription,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator, player)
self.entity_description = description
self._attr_unique_id = f"{player.id}_{description.key}"
@property
def native_value(self) -> StateType:
"""Return the sensor value."""
return self.entity_description.value_fn(self.player)
@@ -37,6 +37,24 @@
}
},
"entity": {
"sensor": {
"card_insertion_state": {
"name": "Card slot",
"state": {
"none": "Empty",
"physical": "Physical card",
"remote": "Remote",
"streaming": "Streaming"
}
},
"day_mode": {
"name": "Day mode",
"state": {
"day": "Day",
"night": "Night"
}
}
},
"time": {
"day_mode_start": {
"name": "Day mode start"
-4
View File
@@ -214,10 +214,6 @@ class ZHAEntity(LogMixin, RestoreEntity, Entity):
def log(self, level: int, msg: str, *args, **kwargs):
"""Log a message."""
if not _LOGGER.isEnabledFor(level):
# Avoid building the prefixed message and args tuple for disabled
# levels; this runs for every entity event via _handle_entity_events.
return
msg = f"%s: {msg}"
args = (self.entity_id, *args)
_LOGGER.log(level, msg, *args, **kwargs)
+8
View File
@@ -9,13 +9,16 @@ import jwt
import pytest
from yoto_api import (
Card,
CardInsertionState,
Chapter,
DayMode,
Device,
Group,
PlaybackEvent,
PlaybackStatus,
PlayerConfig,
PlayerInfo,
PlayerStatus,
Track,
YotoPlayer,
)
@@ -93,6 +96,11 @@ def _build_player() -> YotoPlayer:
night_time=dt_time(19, 0),
),
)
player.status = PlayerStatus(
battery_level_percentage=75,
card_insertion_state=CardInsertionState.PHYSICAL,
day_mode=DayMode.DAY,
)
player.last_event = PlaybackEvent(
player_id=PLAYER_ID,
playback_status=PlaybackStatus.PLAYING,
@@ -0,0 +1,180 @@
# serializer version: 1
# name: test_all_entities[sensor.nursery_yoto_battery-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.nursery_yoto_battery',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Battery',
'options': dict({
}),
'original_device_class': <SensorDeviceClass.BATTERY: 'battery'>,
'original_icon': None,
'original_name': 'Battery',
'platform': 'yoto',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': 'player-test_battery_level',
'unit_of_measurement': '%',
})
# ---
# name: test_all_entities[sensor.nursery_yoto_battery-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'battery',
'friendly_name': 'Nursery Yoto Battery',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': '%',
}),
'context': <ANY>,
'entity_id': 'sensor.nursery_yoto_battery',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '75',
})
# ---
# name: test_all_entities[sensor.nursery_yoto_card_slot-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
'options': list([
'none',
'physical',
'remote',
'streaming',
]),
}),
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.nursery_yoto_card_slot',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Card slot',
'options': dict({
}),
'original_device_class': <SensorDeviceClass.ENUM: 'enum'>,
'original_icon': None,
'original_name': 'Card slot',
'platform': 'yoto',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'card_insertion_state',
'unique_id': 'player-test_card_insertion_state',
'unit_of_measurement': None,
})
# ---
# name: test_all_entities[sensor.nursery_yoto_card_slot-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'enum',
'friendly_name': 'Nursery Yoto Card slot',
'options': list([
'none',
'physical',
'remote',
'streaming',
]),
}),
'context': <ANY>,
'entity_id': 'sensor.nursery_yoto_card_slot',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'physical',
})
# ---
# name: test_all_entities[sensor.nursery_yoto_day_mode-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
'options': list([
'day',
'night',
]),
}),
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.nursery_yoto_day_mode',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Day mode',
'options': dict({
}),
'original_device_class': <SensorDeviceClass.ENUM: 'enum'>,
'original_icon': None,
'original_name': 'Day mode',
'platform': 'yoto',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'day_mode',
'unique_id': 'player-test_day_mode',
'unit_of_measurement': None,
})
# ---
# name: test_all_entities[sensor.nursery_yoto_day_mode-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'enum',
'friendly_name': 'Nursery Yoto Day mode',
'options': list([
'day',
'night',
]),
}),
'context': <ANY>,
'entity_id': 'sensor.nursery_yoto_day_mode',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'day',
})
# ---
+49
View File
@@ -0,0 +1,49 @@
"""Tests for the Yoto sensor platform."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import 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, snapshot_platform
pytestmark = pytest.mark.usefixtures("setup_credentials")
ENTITY_ID = "sensor.nursery_yoto_battery"
@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 sensor entity."""
with patch("homeassistant.components.yoto.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_sensor_unavailable_when_offline(
hass: HomeAssistant,
mock_yoto_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Sensors are unavailable while the player is offline."""
player = next(iter(mock_yoto_client.players.values()))
player.is_online = False
with patch("homeassistant.components.yoto.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == STATE_UNAVAILABLE