diff --git a/CLAUDE.md b/CLAUDE.md index 46dbf05..a2ef627 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,6 +25,7 @@ Official Home Assistant custom integration (`smart_frame_engine`) for **Smart Fr - `custom_components/smart_frame_engine/image.py` — Live preview entity of currently rendered frame image - `custom_components/smart_frame_engine/manifest.json` — HA integration metadata (strict `hassfest` key sorting) - `custom_components/smart_frame_engine/sensor.py` — Active source/mode, media title, engine version, ambient context +- `custom_components/smart_frame_engine/services.py` — Service handlers (capability-gated, `ServiceValidationError`), registered once from `async_setup` - `custom_components/smart_frame_engine/services.yaml` — Service definitions & UI selectors - `custom_components/smart_frame_engine/strings.json` — Base UI & error strings (must stay identical to `translations/en.json`) - `custom_components/smart_frame_engine/switch.py` — Family Mode toggle diff --git a/README.md b/README.md index a12c625..e276839 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ Custom [Home Assistant](https://www.home-assistant.io/) integration for [Smart Frame Engine](https://github.com/ant1fr/Smart-Frame-Engine), installable through [HACS](https://hacs.xyz/) or manually. -> **Status:** work in progress. The foundation (discovery, setup, authentication, compatibility -> checks) is being built first; entities and services follow in later milestones. +> **Status:** work in progress. Discovery, setup, authentication, compatibility checks, entities +> and services are in place; blueprints follow in a later milestone. ## Requirements @@ -25,6 +25,46 @@ Custom [Home Assistant](https://www.home-assistant.io/) integration for Copy `custom_components/smart_frame_engine` into the `custom_components` folder of your Home Assistant configuration directory and restart Home Assistant. +## What you get + +Everything is grouped under one device per engine. Entities that depend on an optional engine +feature (a *capability*) only appear when your engine supports it, and show up after an engine +update without any manual step. + +| Platform | Entities | +| --- | --- | +| Image | **Current image**: live preview of what the frame displays | +| Sensor | Engine version, image source, refresh mode, media title (with the image metadata as attributes), ambient context summary, last delivery, frame last seen, frame battery, Wi-Fi signal (disabled by default) | +| Binary sensor | Engine connected, frame online, frame charging, image pending delivery, temporary image, quiet hours | +| Switch | **Family Mode** (needs the `family_mode` capability) | +| Button | **Refresh image** (`force_refresh`), **Wake up frame** (`frame_wakeup`) | + +The *media title* sensor exposes the image's provider details (which may include people or places) +as an attribute that is shown in the UI but never stored in the history, and diagnostics redact it. + +## Services + +If you have several engines, pass `config_entry_id` to choose one; it is optional otherwise. + +- `smart_frame_engine.set_ambient_context` (needs `ambient_context`): `family_mode`, `presence`, + `weather`, `season`, `boost_tags`, `boost_people` and `ttl_minutes` (1 to 10080). Fields you + leave out keep their value; an empty text or list clears that field. +- `smart_frame_engine.clear_ambient_context` (needs `ambient_context`): optional `field` to clear + only one field. +- `smart_frame_engine.send_title_card` (needs `title_card`): `title`, `subtitle`, `caption`, + `accent`, `ephemeral`, `ttl_minutes`, `hold_minutes`, `push_to_fraimic`. + +```yaml +action: smart_frame_engine.set_ambient_context +data: + weather: rainy + presence: [Alice, Bob] + ttl_minutes: 120 +``` + +A service called on an engine that lacks the capability fails with a clear message instead of +sending a request. + ## License [MIT](LICENSE) diff --git a/custom_components/smart_frame_engine/__init__.py b/custom_components/smart_frame_engine/__init__.py index f14034a..aded24e 100644 --- a/custom_components/smart_frame_engine/__init__.py +++ b/custom_components/smart_frame_engine/__init__.py @@ -4,18 +4,34 @@ from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT, Platform from homeassistant.core import HomeAssistant +from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.typing import ConfigType from .api import SmartFrameClient -from .const import CONF_PATH, DEFAULT_PATH +from .const import CONF_PATH, DEFAULT_PATH, DOMAIN from .coordinator import ( SmartFrameConfigEntry, SmartFrameCoordinator, async_delete_compatibility_issue, ) +from .services import async_setup_services -# Entity platforms arrive in a later milestone; the coordinator and device already work. -PLATFORMS: list[Platform] = [] +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) + +PLATFORMS: list[Platform] = [ + Platform.BINARY_SENSOR, + Platform.BUTTON, + Platform.IMAGE, + Platform.SENSOR, + Platform.SWITCH, +] + + +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Register the services once; they resolve the target engine when called.""" + async_setup_services(hass) + return True async def async_setup_entry(hass: HomeAssistant, entry: SmartFrameConfigEntry) -> bool: diff --git a/custom_components/smart_frame_engine/api.py b/custom_components/smart_frame_engine/api.py index 3a676c5..4cd48c0 100644 --- a/custom_components/smart_frame_engine/api.py +++ b/custom_components/smart_frame_engine/api.py @@ -13,7 +13,7 @@ import asyncio from collections.abc import Mapping, Sequence from dataclasses import dataclass, field -from datetime import datetime +from datetime import UTC, datetime import enum import json from typing import Any, Final, Literal, TypeIs @@ -128,9 +128,11 @@ def _dt(value: Any) -> datetime | None: if not isinstance(value, str): return None try: - return datetime.fromisoformat(value) + parsed = datetime.fromisoformat(value) except ValueError: return None + # The contract says "date-time"; treat a missing offset as UTC so every value is aware. + return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC) def _str_tuple(value: Any) -> tuple[str, ...]: @@ -229,8 +231,16 @@ class CurrentImage: ephemeral: bool = False pushed: bool = True content_key: str | None = None + sha256: str | None = None processed_at: datetime | None = None expires_at: datetime | None = None + # Provider metadata (date, location, people...): free-form per the contract. + details: Mapping[str, Any] = field(default_factory=dict) + + @property + def identity(self) -> tuple[str | None, datetime | None]: + """What changes when the displayed image changes (content hash + render time).""" + return (self.sha256, self.processed_at) @classmethod def from_dict(cls, data: Mapping[str, Any]) -> CurrentImage: @@ -242,8 +252,10 @@ def from_dict(cls, data: Mapping[str, Any]) -> CurrentImage: ephemeral=_bool(data.get("ephemeral")), pushed=_bool(data.get("pushed"), True), content_key=_str(data.get("content_key")), + sha256=_str(data.get("sha256")), processed_at=_dt(data.get("processed_at")), expires_at=_dt(data.get("expires_at")), + details=dict(_mapping(data.get("details"))), ) @@ -273,6 +285,38 @@ def from_dict(cls, data: Mapping[str, Any]) -> EphemeralState: ) +@dataclass(frozen=True, slots=True) +class FrameTelemetry: + """Last known frame state (``FrameTelemetry``); updated whenever the frame is contacted.""" + + online: bool | None = None # None = the frame was never contacted + last_seen: datetime | None = None + last_checked: datetime | None = None + last_error: str | None = None + battery_percent: float | None = None + charging: bool | None = None + firmware_version: str | None = None + rssi: int | None = None + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> FrameTelemetry: + """Parse ``FrameTelemetry`` (and its nested ``FrameInfo``) tolerantly.""" + info = _mapping(data.get("info")) + online = data.get("online") + charging = info.get("charging") + rssi = info.get("rssi") + return cls( + online=online if isinstance(online, bool) else None, + last_seen=_dt(data.get("last_seen")), + last_checked=_dt(data.get("last_checked")), + last_error=_str(data.get("last_error")), + battery_percent=_float(info.get("battery_percent")), + charging=charging if isinstance(charging, bool) else None, + firmware_version=_str(info.get("firmware_version")), + rssi=rssi if _is_int(rssi) else None, + ) + + @dataclass(frozen=True, slots=True) class FrameState: """Configured frame characteristics (``FrameStatus``).""" @@ -282,7 +326,7 @@ class FrameState: panel_label: str | None = None orientation: str | None = None power_mode: str | None = None - telemetry: Mapping[str, Any] = field(default_factory=dict) + telemetry: FrameTelemetry = field(default_factory=FrameTelemetry) @classmethod def from_dict(cls, data: Mapping[str, Any]) -> FrameState: @@ -293,7 +337,28 @@ def from_dict(cls, data: Mapping[str, Any]) -> FrameState: panel_label=_str(data.get("panel_label")), orientation=_str(data.get("orientation")), power_mode=_str(data.get("power_mode")), - telemetry=dict(_mapping(data.get("telemetry"))), + telemetry=FrameTelemetry.from_dict(_mapping(data.get("telemetry"))), + ) + + +@dataclass(frozen=True, slots=True) +class LastDelivery: + """The most recent successful upload to the frame (``LastDelivery``).""" + + delivered_at: datetime | None = None + reason: str | None = None # submit | force | wakeup | worker + duration_s: float | None = None + size_bytes: int | None = None + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> LastDelivery: + """Parse ``LastDelivery`` tolerantly.""" + size = data.get("bytes") + return cls( + delivered_at=_dt(data.get("delivered_at")), + reason=_str(data.get("reason")), + duration_s=_float(data.get("duration_s")), + size_bytes=size if _is_int(size) else None, ) @@ -302,14 +367,15 @@ class DeliveryState: """Upload queue state (``DeliveryStatus``).""" pending: bool = False - last_delivered_at: datetime | None = None + last_delivery: LastDelivery | None = None @classmethod def from_dict(cls, data: Mapping[str, Any]) -> DeliveryState: """Parse ``DeliveryStatus`` tolerantly.""" + last = data.get("last_delivery") return cls( pending=_bool(data.get("pending")), - last_delivered_at=_dt(_mapping(data.get("last_delivery")).get("delivered_at")), + last_delivery=LastDelivery.from_dict(last) if isinstance(last, Mapping) else None, ) @@ -393,12 +459,16 @@ class SchedulerState: hold_until: datetime | None = None last_run_status: str | None = None last_run_reason: str | None = None + # Which rule a refresh would replay: kind (immich, tmdb...) and source (pinned|smart_mix|last). + active_rule_kind: str | None = None + active_rule_source: str | None = None ambient: AmbientState = field(default_factory=AmbientState) @classmethod def from_dict(cls, data: Mapping[str, Any]) -> SchedulerState: """Parse ``SchedulerSnapshot`` tolerantly.""" last_run = _mapping(data.get("last_run")) + rule = _mapping(data.get("active_rule")) return cls( enabled=_bool(data.get("enabled")), running=_bool(data.get("running")), @@ -409,6 +479,8 @@ def from_dict(cls, data: Mapping[str, Any]) -> SchedulerState: hold_until=_dt(data.get("hold_until")), last_run_status=_str(last_run.get("status")), last_run_reason=_str(last_run.get("reason")), + active_rule_kind=_str(rule.get("kind")), + active_rule_source=_str(rule.get("source")), ambient=AmbientState.from_dict(_mapping(data.get("ambient"))), ) @@ -427,6 +499,9 @@ class EngineStatus: scheduler: SchedulerState immich_configured: bool tmdb_configured: bool + # Contract v1.2 (display only): the version spelled like the git/Docker tag, e.g. + # ``1.0.0-rc.3``. ``None`` on engines older than 1.0.0rc3. + release: str | None = None @classmethod def from_dict(cls, data: Any) -> EngineStatus: @@ -446,6 +521,7 @@ def from_dict(cls, data: Any) -> EngineStatus: scheduler=SchedulerState.from_dict(_mapping(data.get("scheduler"))), immich_configured=_bool(services.get("immich")), tmdb_configured=_bool(services.get("tmdb")), + release=_str(data.get("release")) or None, ) diff --git a/custom_components/smart_frame_engine/binary_sensor.py b/custom_components/smart_frame_engine/binary_sensor.py new file mode 100644 index 0000000..fd7bef3 --- /dev/null +++ b/custom_components/smart_frame_engine/binary_sensor.py @@ -0,0 +1,127 @@ +"""Binary sensors: engine/frame connectivity and delivery state.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +# Imported from the package: before HA 2026.2 the class has no ``.const`` module, and later +# versions only re-export it (hence the type-checker ignore). +from homeassistant.components.binary_sensor import ( # type: ignore[attr-defined] + BinarySensorDeviceClass, + BinarySensorEntity, + BinarySensorEntityDescription, +) +from homeassistant.const import EntityCategory +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from .coordinator import SmartFrameConfigEntry, SmartFrameCoordinator +from .entity import SmartFrameEntity + +PARALLEL_UPDATES = 0 + + +@dataclass(frozen=True, kw_only=True) +class SmartFrameBinarySensorDescription(BinarySensorEntityDescription): + """Describe a binary sensor backed by the coordinator.""" + + value_fn: Callable[[SmartFrameCoordinator], bool | None] + attrs_fn: Callable[[SmartFrameCoordinator], dict[str, Any]] | None = None + # The engine connectivity sensor must keep reporting while the engine is unreachable. + always_available: bool = False + + +def _frame_configured(coordinator: SmartFrameCoordinator) -> bool: + return coordinator.data.status.frame.configured + + +BINARY_SENSORS: tuple[SmartFrameBinarySensorDescription, ...] = ( + SmartFrameBinarySensorDescription( + key="engine_connected", + translation_key="engine_connected", + device_class=BinarySensorDeviceClass.CONNECTIVITY, + entity_category=EntityCategory.DIAGNOSTIC, + always_available=True, + value_fn=lambda c: c.last_update_success, + ), + SmartFrameBinarySensorDescription( + key="frame_online", + translation_key="frame_online", + device_class=BinarySensorDeviceClass.CONNECTIVITY, + entity_category=EntityCategory.DIAGNOSTIC, + # ``telemetry.online`` is null until the frame was contacted once. + value_fn=lambda c: c.data.status.frame.telemetry.online if _frame_configured(c) else None, + attrs_fn=lambda c: {"last_error": c.data.status.frame.telemetry.last_error}, + ), + SmartFrameBinarySensorDescription( + key="frame_charging", + translation_key="frame_charging", + device_class=BinarySensorDeviceClass.BATTERY_CHARGING, + entity_category=EntityCategory.DIAGNOSTIC, + value_fn=lambda c: c.data.status.frame.telemetry.charging, + ), + SmartFrameBinarySensorDescription( + key="delivery_pending", + translation_key="delivery_pending", + entity_category=EntityCategory.DIAGNOSTIC, + value_fn=lambda c: c.data.status.delivery.pending, + ), + SmartFrameBinarySensorDescription( + key="ephemeral_active", + translation_key="ephemeral_active", + value_fn=lambda c: c.data.status.ephemeral.active, + attrs_fn=lambda c: { + "expires_at": c.data.status.ephemeral.expires_at, + "title": c.data.status.ephemeral.title, + "source": c.data.status.ephemeral.source, + }, + ), + SmartFrameBinarySensorDescription( + key="quiet_hours", + translation_key="quiet_hours", + value_fn=lambda c: c.data.status.scheduler.in_quiet_hours, + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SmartFrameConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the binary sensors of one engine.""" + coordinator = entry.runtime_data + async_add_entities(SmartFrameBinarySensor(coordinator, d) for d in BINARY_SENSORS) + + +class SmartFrameBinarySensor(SmartFrameEntity, BinarySensorEntity): + """A binary state read from the coordinator snapshot.""" + + entity_description: SmartFrameBinarySensorDescription + + def __init__( + self, + coordinator: SmartFrameCoordinator, + description: SmartFrameBinarySensorDescription, + ) -> None: + """Initialise the binary sensor.""" + super().__init__(coordinator, description) + + @property + def available(self) -> bool: + """Engine connectivity stays available (it reports the outage itself).""" + return self.entity_description.always_available or super().available + + @property + def is_on(self) -> bool | None: + """Return the state.""" + return self.entity_description.value_fn(self.coordinator) + + @property + def extra_state_attributes(self) -> dict[str, Any] | None: + """Return grounded extra attributes, if the description defines any.""" + if self.entity_description.attrs_fn is None or not self.coordinator.last_update_success: + return None + return self.entity_description.attrs_fn(self.coordinator) diff --git a/custom_components/smart_frame_engine/button.py b/custom_components/smart_frame_engine/button.py new file mode 100644 index 0000000..a9d0684 --- /dev/null +++ b/custom_components/smart_frame_engine/button.py @@ -0,0 +1,69 @@ +"""Buttons: force a refresh, wake the frame.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import Any + +from homeassistant.components.button import ButtonEntity, ButtonEntityDescription +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from .api import SmartFrameClient +from .const import CAPABILITY_FORCE_REFRESH, CAPABILITY_FRAME_WAKEUP +from .coordinator import SmartFrameConfigEntry +from .entity import SmartFrameEntity + +PARALLEL_UPDATES = 1 + + +@dataclass(frozen=True, kw_only=True) +class SmartFrameButtonDescription(ButtonEntityDescription): + """Describe a button that calls one engine endpoint.""" + + capability: str + press_fn: Callable[[SmartFrameClient], Awaitable[Any]] + + +BUTTONS: tuple[SmartFrameButtonDescription, ...] = ( + SmartFrameButtonDescription( + key="force_refresh", + translation_key="force_refresh", + capability=CAPABILITY_FORCE_REFRESH, + press_fn=lambda client: client.async_refresh(), + ), + SmartFrameButtonDescription( + key="wake_frame", + translation_key="wake_frame", + capability=CAPABILITY_FRAME_WAKEUP, + # Non-blocking: the engine answers 202 and uploads in the background. + press_fn=lambda client: client.async_wakeup(), + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SmartFrameConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the buttons the engine supports.""" + coordinator = entry.runtime_data + async_add_entities( + SmartFrameButton(coordinator, description) + for description in BUTTONS + if description.capability in coordinator.capabilities + ) + + +class SmartFrameButton(SmartFrameEntity, ButtonEntity): + """A button that triggers an action on the engine.""" + + entity_description: SmartFrameButtonDescription + + async def async_press(self) -> None: + """Call the endpoint, then refresh so the new state shows up.""" + coordinator = self.coordinator + await coordinator.async_action(self.entity_description.press_fn(coordinator.client)) + await coordinator.async_request_refresh() diff --git a/custom_components/smart_frame_engine/const.py b/custom_components/smart_frame_engine/const.py index 20dea4a..8fae0f6 100644 --- a/custom_components/smart_frame_engine/const.py +++ b/custom_components/smart_frame_engine/const.py @@ -40,7 +40,7 @@ TXT_AUTH: Final = "auth" TXT_INSTANCE_ID: Final = "instance_id" -# Capability flags advertised in ``GET /api/health`` (contract v1.0, 18 flags). +# Capability flags advertised in ``GET /api/health`` (contract v1.2, 19 flags). CAPABILITY_ACTIVITY_LOG: Final = "activity_log" CAPABILITY_AMBIENT_CONTEXT: Final = "ambient_context" CAPABILITY_DISPLAY_IMMICH: Final = "display_immich" @@ -57,6 +57,7 @@ CAPABILITY_RANDOM_DISCOVERY: Final = "random_discovery" CAPABILITY_SMART_MIX: Final = "smart_mix" CAPABILITY_SMART_MIX_CONTEXT: Final = "smart_mix_context" +CAPABILITY_SMART_MIX_KINDS: Final = "smart_mix_kinds" CAPABILITY_TITLE_CARD: Final = "title_card" CAPABILITY_UPLOAD_IMAGE: Final = "upload_image" @@ -78,6 +79,7 @@ CAPABILITY_RANDOM_DISCOVERY, CAPABILITY_SMART_MIX, CAPABILITY_SMART_MIX_CONTEXT, + CAPABILITY_SMART_MIX_KINDS, CAPABILITY_TITLE_CARD, CAPABILITY_UPLOAD_IMAGE, } diff --git a/custom_components/smart_frame_engine/coordinator.py b/custom_components/smart_frame_engine/coordinator.py index cb23074..11d6ba6 100644 --- a/custom_components/smart_frame_engine/coordinator.py +++ b/custom_components/smart_frame_engine/coordinator.py @@ -9,28 +9,36 @@ from __future__ import annotations from collections.abc import Awaitable -from dataclasses import dataclass +from dataclasses import dataclass, replace from datetime import timedelta import logging from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback -from homeassistant.exceptions import ConfigEntryAuthFailed +from homeassistant.exceptions import ( + ConfigEntryAuthFailed, + HomeAssistantError, + ServiceValidationError, +) from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .api import ( AmbientView, + ConfigView, EngineStatus, HealthInfo, + SmartFrameApiError, SmartFrameAuthError, SmartFrameClient, SmartFrameError, + SmartFrameValidationError, UpdateTarget, ) from .const import ( CAPABILITY_AMBIENT_CONTEXT, + CAPABILITY_FAMILY_MODE, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL, DOMAIN, @@ -55,6 +63,13 @@ class SmartFrameData: status: EngineStatus # ``None`` when the engine does not advertise the ``ambient_context`` capability. ambient: AmbientView | None + # ``None`` when the engine does not advertise the ``family_mode`` capability. + config: ConfigView | None = None + + @property + def engine_version(self) -> str: + """The version to show: the tag spelling (contract v1.2) when known, else PEP 440.""" + return self.status.release or self.health.version SmartFrameConfigEntry = ConfigEntry["SmartFrameCoordinator"] @@ -109,7 +124,7 @@ def device_info(self) -> DeviceInfo: name=(health.instance_name if health else None) or self.config_entry.title, manufacturer=MANUFACTURER, model=MODEL, - sw_version=health.version if health else None, + sw_version=self.data.engine_version if self.data else None, configuration_url=self.client.base_url, ) @@ -139,9 +154,63 @@ async def _async_update_data(self) -> SmartFrameData: if CAPABILITY_AMBIENT_CONTEXT in health.capabilities: # Also proves the key is still valid in ``key`` mode, where ``/api/status`` is public. ambient = await self._async_call(self.client.async_get_context()) + config: ConfigView | None = None + if CAPABILITY_FAMILY_MODE in health.capabilities: + # ``config.family.enabled`` is the persistent Family Mode setting. + config = await self._async_call(self.client.async_get_config()) + + self._async_track_capabilities(health.capabilities) + return SmartFrameData(health=health, status=status, ambient=ambient, config=config) + + def _async_track_capabilities(self, capabilities: frozenset[str]) -> None: + """Cache the capabilities and reload the entry when the engine's set changes. + + Platforms and services gate on ``capabilities`` at setup, so an engine that was + upgraded (or downgraded) needs a reload for its entities to follow. + """ + previous, self.capabilities = self.capabilities, capabilities + if previous and previous != capabilities: + _LOGGER.info("Engine capabilities changed; reloading %s", self.config_entry.title) + self.hass.config_entries.async_schedule_reload(self.config_entry.entry_id) + + async def async_action[T](self, awaitable: Awaitable[T]) -> T: + """Run a client call made on behalf of the user (entity action or service). + + Failures surface as ``HomeAssistantError`` with a translated message; a rejected key + also starts the reauthentication flow. + """ + try: + return await awaitable + except SmartFrameAuthError as err: + self.config_entry.async_start_reauth(self.hass) + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="invalid_auth" + ) from err + except SmartFrameValidationError as err: + # HTTP 422: the engine rejected what the user asked for. + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="request_rejected", + translation_placeholders={"error": err.detail or "HTTP 422"}, + ) from err + except SmartFrameApiError as err: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="action_failed", + translation_placeholders={"error": err.detail or f"HTTP {err.status}"}, + ) from err + except SmartFrameError as err: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="action_failed", + translation_placeholders={"error": str(err)}, + ) from err - self.capabilities = health.capabilities - return SmartFrameData(health=health, status=status, ambient=ambient) + @callback + def async_apply_config(self, config: ConfigView) -> None: + """Publish a fresh ``ConfigView`` (a ``PUT /api/config`` reply) to the entities.""" + if self.data is not None: + self.async_set_updated_data(replace(self.data, config=config)) def _async_check_instance(self, health: HealthInfo) -> None: """Refuse to poll a different engine that took over this address.""" diff --git a/custom_components/smart_frame_engine/diagnostics.py b/custom_components/smart_frame_engine/diagnostics.py index 1eed058..15a3060 100644 --- a/custom_components/smart_frame_engine/diagnostics.py +++ b/custom_components/smart_frame_engine/diagnostics.py @@ -12,7 +12,17 @@ from .coordinator import SmartFrameConfigEntry # The engine never returns secrets, but anything key-like is redacted defensively. -TO_REDACT = {CONF_API_KEY, "api_key", "password", "token", "X-API-Key"} +TO_REDACT = { + CONF_API_KEY, + "api_key", + "password", + "token", + "X-API-Key", + # Personal data: provider metadata (people, places) and the ambient people lists. + "details", + "presence", + "boost_people", +} async def async_get_config_entry_diagnostics( @@ -39,6 +49,7 @@ async def async_get_config_entry_diagnostics( ), }, "capabilities": sorted(coordinator.capabilities), + "family_enabled": data.config.family_enabled if data and data.config else None, "health": data.health.as_dict() if data else None, "status": asdict(data.status) if data else None, "ambient": asdict(data.ambient) if data and data.ambient else None, diff --git a/custom_components/smart_frame_engine/image.py b/custom_components/smart_frame_engine/image.py new file mode 100644 index 0000000..4a443dc --- /dev/null +++ b/custom_components/smart_frame_engine/image.py @@ -0,0 +1,87 @@ +"""Live preview of the image currently rendered for the frame.""" + +from __future__ import annotations + +from datetime import datetime +import logging + +from homeassistant.components.image import ImageEntity, ImageEntityDescription +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +import homeassistant.util.dt as dt_util + +from .api import SmartFrameError +from .coordinator import SmartFrameConfigEntry, SmartFrameCoordinator +from .entity import SmartFrameEntity + +_LOGGER = logging.getLogger(__name__) + +PARALLEL_UPDATES = 0 + +CURRENT_IMAGE = ImageEntityDescription(key="current_image", translation_key="current_image") + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SmartFrameConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the preview image of one engine.""" + async_add_entities([SmartFrameImage(hass, entry.runtime_data)]) + + +class SmartFrameImage(SmartFrameEntity, ImageEntity): + """The current frame image, fetched lazily and cached until the image changes. + + ``GET /api/current.jpg`` is the image being displayed; before the first image exists it + answers 404 and the most recent render (``GET /api/preview.jpg``) is used instead. + """ + + _attr_content_type = "image/jpeg" + + def __init__(self, hass: HomeAssistant, coordinator: SmartFrameCoordinator) -> None: + """Initialise the image entity.""" + SmartFrameEntity.__init__(self, coordinator, CURRENT_IMAGE) + ImageEntity.__init__(self, hass) + self._identity: tuple[str | None, datetime | None] | None = None + self._cached: bytes | None = None + self._async_track_image() + + @callback + def _async_track_image(self) -> None: + """Invalidate the cache and bump ``image_last_updated`` when the image changed.""" + image = self.coordinator.data.status.current_image + identity = image.identity if image else None + if identity == self._identity: + return + self._identity = identity + self._cached = None + if image is None: + self._attr_image_last_updated = None + else: + self._attr_image_last_updated = image.processed_at or dt_util.utcnow() + self.async_update_token() + + @callback + def _handle_coordinator_update(self) -> None: + """Track the displayed image on every poll.""" + self._async_track_image() + super()._handle_coordinator_update() + + async def async_image(self) -> bytes | None: + """Return the JPEG, from the cache when the displayed image has not changed.""" + if self._cached is not None: + return self._cached + identity = self._identity + client = self.coordinator.client + try: + content = await client.async_get_current_image() + if content is None: + content = await client.async_get_preview_image() + except SmartFrameError as err: + _LOGGER.warning("Cannot fetch the frame image: %s", err) + return None + # Do not cache a download that raced with a newer image. + if content is not None and identity == self._identity: + self._cached = content + return content diff --git a/custom_components/smart_frame_engine/sensor.py b/custom_components/smart_frame_engine/sensor.py new file mode 100644 index 0000000..2f2ee68 --- /dev/null +++ b/custom_components/smart_frame_engine/sensor.py @@ -0,0 +1,239 @@ +"""Sensors: engine version, what is displayed, ambient context, delivery and frame state.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +from homeassistant.components.sensor import ( + SensorDeviceClass, + SensorEntity, + SensorEntityDescription, + SensorStateClass, +) +from homeassistant.const import ( + PERCENTAGE, + SIGNAL_STRENGTH_DECIBELS_MILLIWATT, + EntityCategory, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from .api import AmbientState +from .const import CAPABILITY_AMBIENT_CONTEXT +from .coordinator import SmartFrameConfigEntry, SmartFrameData +from .entity import SmartFrameEntity + +PARALLEL_UPDATES = 0 + +# ``scheduler.active_rule.source`` values enumerated by the contract. +REFRESH_RULE_SOURCES = ["pinned", "smart_mix", "last"] +MAX_STATE_LENGTH = 255 + +_AMBIENT_FIELDS = ( + "family_mode", + "presence", + "weather", + "season", + "boost_tags", + "boost_people", +) + + +@dataclass(frozen=True, kw_only=True) +class SmartFrameSensorDescription(SensorEntityDescription): + """Describe a sensor backed by the coordinator snapshot.""" + + value_fn: Callable[[SmartFrameData], str | int | float | datetime | None] + attrs_fn: Callable[[SmartFrameData], dict[str, Any]] | None = None + # Only created when the engine advertises this capability flag. + capability: str | None = None + + +def _ambient_fields(ambient: AmbientState) -> dict[str, Any]: + """Flatten the active ambient fields: ```` and ``_expires_at``.""" + attrs: dict[str, Any] = {} + for name in _AMBIENT_FIELDS: + timed = getattr(ambient, name) + if timed is None: + continue + attrs[name] = timed.value if hasattr(timed, "value") else list(timed.values) + attrs[f"{name}_expires_at"] = timed.expires_at + return attrs + + +def _ambient_count(data: SmartFrameData) -> int | None: + if data.ambient is None: + return None + return sum(getattr(data.ambient.context, name) is not None for name in _AMBIENT_FIELDS) + + +def _ambient_attrs(data: SmartFrameData) -> dict[str, Any]: + if data.ambient is None: + return {} + return { + **_ambient_fields(data.ambient.context), + "family_active": data.ambient.family_active, + "smart_mix_enabled": data.ambient.smart_mix_enabled, + "extra_candidates": list(data.ambient.extra_candidates), + } + + +def _image_attrs(data: SmartFrameData) -> dict[str, Any]: + image = data.status.current_image + if image is None: + return {} + return { + "source": image.source, + "template": image.template, + "ephemeral": image.ephemeral, + "pushed": image.pushed, + "processed_at": image.processed_at, + "expires_at": image.expires_at, + # Provider metadata (date, location, people...): free-form, shown but not recorded. + "details": dict(image.details), + } + + +def _source(data: SmartFrameData) -> str | None: + image = data.status.current_image + return image.source if image else None + + +def _title(data: SmartFrameData) -> str | None: + image = data.status.current_image + if image is None or not image.title: + return None + return image.title[:MAX_STATE_LENGTH] + + +def _refresh_rule(data: SmartFrameData) -> str | None: + source = data.status.scheduler.active_rule_source + # The contract only ever adds enum values; an unknown one must not break the state. + return source if source in REFRESH_RULE_SOURCES else None + + +def _last_delivery_at(data: SmartFrameData) -> datetime | None: + last = data.status.delivery.last_delivery + return last.delivered_at if last else None + + +def _last_delivery_attrs(data: SmartFrameData) -> dict[str, Any]: + last = data.status.delivery.last_delivery + if last is None: + return {} + return { + "reason": last.reason, + "duration_s": last.duration_s, + "bytes": last.size_bytes, + } + + +SENSORS: tuple[SmartFrameSensorDescription, ...] = ( + SmartFrameSensorDescription( + key="engine_version", + translation_key="engine_version", + entity_category=EntityCategory.DIAGNOSTIC, + value_fn=lambda d: d.engine_version, + ), + SmartFrameSensorDescription( + key="active_source", + translation_key="active_source", + value_fn=_source, + attrs_fn=lambda d: ( + {"template": d.status.current_image.template} if d.status.current_image else {} + ), + ), + SmartFrameSensorDescription( + key="refresh_rule", + translation_key="refresh_rule", + device_class=SensorDeviceClass.ENUM, + options=REFRESH_RULE_SOURCES, + value_fn=_refresh_rule, + attrs_fn=lambda d: {"kind": d.status.scheduler.active_rule_kind}, + ), + SmartFrameSensorDescription( + key="media_title", + translation_key="media_title", + value_fn=_title, + attrs_fn=_image_attrs, + ), + SmartFrameSensorDescription( + key="ambient_context", + translation_key="ambient_context", + capability=CAPABILITY_AMBIENT_CONTEXT, + state_class=SensorStateClass.MEASUREMENT, + value_fn=_ambient_count, + attrs_fn=_ambient_attrs, + ), + SmartFrameSensorDescription( + key="last_delivery", + translation_key="last_delivery", + device_class=SensorDeviceClass.TIMESTAMP, + entity_category=EntityCategory.DIAGNOSTIC, + value_fn=_last_delivery_at, + attrs_fn=_last_delivery_attrs, + ), + SmartFrameSensorDescription( + key="frame_last_seen", + translation_key="frame_last_seen", + device_class=SensorDeviceClass.TIMESTAMP, + entity_category=EntityCategory.DIAGNOSTIC, + value_fn=lambda d: d.status.frame.telemetry.last_seen, + ), + SmartFrameSensorDescription( + key="frame_battery", + translation_key="frame_battery", + device_class=SensorDeviceClass.BATTERY, + native_unit_of_measurement=PERCENTAGE, + state_class=SensorStateClass.MEASUREMENT, + entity_category=EntityCategory.DIAGNOSTIC, + value_fn=lambda d: d.status.frame.telemetry.battery_percent, + ), + SmartFrameSensorDescription( + key="frame_wifi_signal", + translation_key="frame_wifi_signal", + device_class=SensorDeviceClass.SIGNAL_STRENGTH, + native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, + state_class=SensorStateClass.MEASUREMENT, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + value_fn=lambda d: d.status.frame.telemetry.rssi, + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SmartFrameConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the sensors of one engine, skipping those the engine cannot back.""" + coordinator = entry.runtime_data + async_add_entities( + SmartFrameSensor(coordinator, description) + for description in SENSORS + if description.capability is None or description.capability in coordinator.capabilities + ) + + +class SmartFrameSensor(SmartFrameEntity, SensorEntity): + """A value read from the coordinator snapshot.""" + + entity_description: SmartFrameSensorDescription + # The provider details can hold people and places: visible in the UI, never recorded. + _unrecorded_attributes = frozenset({"details"}) + + @property + def native_value(self) -> str | int | float | datetime | None: + """Return the value.""" + return self.entity_description.value_fn(self.coordinator.data) + + @property + def extra_state_attributes(self) -> dict[str, Any] | None: + """Return grounded extra attributes, if the description defines any.""" + if self.entity_description.attrs_fn is None: + return None + return self.entity_description.attrs_fn(self.coordinator.data) diff --git a/custom_components/smart_frame_engine/services.py b/custom_components/smart_frame_engine/services.py new file mode 100644 index 0000000..b6f5d31 --- /dev/null +++ b/custom_components/smart_frame_engine/services.py @@ -0,0 +1,184 @@ +"""Home Assistant services: ambient context and title cards. + +Each service checks the engine's capability flag first and raises a translated +``ServiceValidationError`` when the connected engine does not support it (contract: +"A missing flag means this engine is older: hide or disable that feature"). +""" + +from __future__ import annotations + +from typing import Any, Final + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant, ServiceCall, callback +from homeassistant.exceptions import ServiceValidationError +from homeassistant.helpers import config_validation as cv +import voluptuous as vol + +from .api import AmbientField +from .const import CAPABILITY_AMBIENT_CONTEXT, CAPABILITY_TITLE_CARD, DOMAIN +from .coordinator import SmartFrameConfigEntry + +SERVICE_SET_AMBIENT_CONTEXT: Final = "set_ambient_context" +SERVICE_CLEAR_AMBIENT_CONTEXT: Final = "clear_ambient_context" +SERVICE_SEND_TITLE_CARD: Final = "send_title_card" + +ATTR_CONFIG_ENTRY_ID: Final = "config_entry_id" +ATTR_FIELD: Final = "field" + +AMBIENT_FIELDS: Final = ( + "family_mode", + "presence", + "weather", + "season", + "boost_tags", + "boost_people", +) +SEASONS: Final = ["spring", "summer", "autumn", "winter"] +ACCENTS: Final = ["red", "yellow", "blue", "green", "white"] + +# Limits from openapi.json (AmbientRequest, TitleCardRequest). +MAX_LIST_ITEMS: Final = 20 +MAX_TEXT: Final = 80 +MAX_CARD_TEXT: Final = 200 +MIN_MINUTES: Final = 1 +MAX_MINUTES: Final = 10080 + +_minutes = vol.All(vol.Coerce(int), vol.Range(min=MIN_MINUTES, max=MAX_MINUTES)) +_names = vol.All(cv.ensure_list, [cv.string], vol.Length(max=MAX_LIST_ITEMS)) + + +def _schema(fields: dict[Any, Any]) -> Any: + """Build a service schema (typed ``Any``: HA 2026.10 types schemas as ``probatio``).""" + return vol.Schema({vol.Optional(ATTR_CONFIG_ENTRY_ID): cv.string, **fields}) + + +SET_AMBIENT_CONTEXT_SCHEMA = _schema( + { + vol.Optional("family_mode"): cv.boolean, + vol.Optional("presence"): _names, + vol.Optional("weather"): vol.All(cv.string, vol.Length(max=MAX_TEXT)), + vol.Optional("season"): vol.In(SEASONS), + vol.Optional("boost_tags"): _names, + vol.Optional("boost_people"): _names, + vol.Optional("ttl_minutes"): _minutes, + } +) +CLEAR_AMBIENT_CONTEXT_SCHEMA = _schema({vol.Optional(ATTR_FIELD): vol.In(AMBIENT_FIELDS)}) +SEND_TITLE_CARD_SCHEMA = _schema( + { + vol.Required("title"): vol.All(cv.string, vol.Length(min=1, max=MAX_CARD_TEXT)), + vol.Optional("subtitle"): vol.All(cv.string, vol.Length(max=MAX_CARD_TEXT)), + vol.Optional("caption"): vol.All(cv.string, vol.Length(max=MAX_CARD_TEXT)), + vol.Optional("accent"): vol.In(ACCENTS), + vol.Optional("ephemeral"): cv.boolean, + vol.Optional("ttl_minutes"): _minutes, + vol.Optional("hold_minutes"): _minutes, + vol.Optional("push_to_fraimic"): cv.boolean, + } +) + + +@callback +def _async_resolve_entries( + hass: HomeAssistant, call: ServiceCall, capability: str +) -> list[SmartFrameConfigEntry]: + """Return the loaded engine this call targets, after checking its capability. + + ``config_entry_id`` may be omitted when exactly one engine is set up. + """ + entries = hass.config_entries.async_entries(DOMAIN) + if (entry_id := call.data.get(ATTR_CONFIG_ENTRY_ID)) is not None: + entries = [entry for entry in entries if entry.entry_id == entry_id] + if not entries: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="entry_not_found", + translation_placeholders={"entry_id": str(entry_id)}, + ) + elif len(entries) > 1: + raise ServiceValidationError( + translation_domain=DOMAIN, translation_key="config_entry_required" + ) + + loaded = [entry for entry in entries if entry.state is ConfigEntryState.LOADED] + if not loaded: + raise ServiceValidationError(translation_domain=DOMAIN, translation_key="no_engine_loaded") + + for entry in loaded: + if capability not in entry.runtime_data.capabilities: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="capability_not_supported", + translation_placeholders={"capability": capability, "name": entry.title}, + ) + return loaded + + +async def _async_set_ambient_context(call: ServiceCall) -> None: + """``POST /api/context``.""" + fields = {name: call.data[name] for name in AMBIENT_FIELDS if name in call.data} + entries = _async_resolve_entries(call.hass, call, CAPABILITY_AMBIENT_CONTEXT) + if not fields: + raise ServiceValidationError(translation_domain=DOMAIN, translation_key="no_context_fields") + for entry in entries: + coordinator = entry.runtime_data + await coordinator.async_action( + coordinator.client.async_set_context(ttl_minutes=call.data.get("ttl_minutes"), **fields) + ) + await coordinator.async_request_refresh() + + +async def _async_clear_ambient_context(call: ServiceCall) -> None: + """``DELETE /api/context`` (optionally ``?field=``).""" + field: AmbientField | None = call.data.get(ATTR_FIELD) + for entry in _async_resolve_entries(call.hass, call, CAPABILITY_AMBIENT_CONTEXT): + coordinator = entry.runtime_data + await coordinator.async_action(coordinator.client.async_clear_context(field)) + await coordinator.async_request_refresh() + + +async def _async_send_title_card(call: ServiceCall) -> None: + """``POST /api/display/title-card``.""" + options = { + name: call.data[name] + for name in ( + "subtitle", + "caption", + "accent", + "ephemeral", + "ttl_minutes", + "hold_minutes", + "push_to_fraimic", + ) + if name in call.data + } + for entry in _async_resolve_entries(call.hass, call, CAPABILITY_TITLE_CARD): + coordinator = entry.runtime_data + await coordinator.async_action( + coordinator.client.async_title_card(call.data["title"], **options) + ) + await coordinator.async_request_refresh() + + +@callback +def async_setup_services(hass: HomeAssistant) -> None: + """Register the integration's services (once, from ``async_setup``).""" + hass.services.async_register( + DOMAIN, + SERVICE_SET_AMBIENT_CONTEXT, + _async_set_ambient_context, + schema=SET_AMBIENT_CONTEXT_SCHEMA, + ) + hass.services.async_register( + DOMAIN, + SERVICE_CLEAR_AMBIENT_CONTEXT, + _async_clear_ambient_context, + schema=CLEAR_AMBIENT_CONTEXT_SCHEMA, + ) + hass.services.async_register( + DOMAIN, + SERVICE_SEND_TITLE_CARD, + _async_send_title_card, + schema=SEND_TITLE_CARD_SCHEMA, + ) diff --git a/custom_components/smart_frame_engine/services.yaml b/custom_components/smart_frame_engine/services.yaml new file mode 100644 index 0000000..3cb6268 --- /dev/null +++ b/custom_components/smart_frame_engine/services.yaml @@ -0,0 +1,131 @@ +set_ambient_context: + fields: + config_entry_id: + required: false + selector: + config_entry: + integration: smart_frame_engine + family_mode: + required: false + selector: + boolean: + presence: + required: false + example: '["Alice", "Bob"]' + selector: + text: + multiple: true + weather: + required: false + example: rainy + selector: + text: + season: + required: false + selector: + select: + options: + - spring + - summer + - autumn + - winter + translation_key: season + boost_tags: + required: false + example: '["beach", "birthday"]' + selector: + text: + multiple: true + boost_people: + required: false + example: '["Alice"]' + selector: + text: + multiple: true + ttl_minutes: + required: false + selector: + number: + min: 1 + max: 10080 + mode: box + unit_of_measurement: min + +clear_ambient_context: + fields: + config_entry_id: + required: false + selector: + config_entry: + integration: smart_frame_engine + field: + required: false + selector: + select: + options: + - presence + - family_mode + - weather + - season + - boost_tags + - boost_people + translation_key: ambient_field + +send_title_card: + fields: + config_entry_id: + required: false + selector: + config_entry: + integration: smart_frame_engine + title: + required: true + example: Dinner is ready + selector: + text: + subtitle: + required: false + selector: + text: + caption: + required: false + selector: + text: + accent: + required: false + selector: + select: + options: + - red + - yellow + - blue + - green + - white + translation_key: accent + ephemeral: + required: false + default: true + selector: + boolean: + ttl_minutes: + required: false + default: 60 + selector: + number: + min: 1 + max: 10080 + mode: box + unit_of_measurement: min + hold_minutes: + required: false + selector: + number: + min: 1 + max: 10080 + mode: box + unit_of_measurement: min + push_to_fraimic: + required: false + default: true + selector: + boolean: diff --git a/custom_components/smart_frame_engine/strings.json b/custom_components/smart_frame_engine/strings.json index 6d0afe4..35ef4d9 100644 --- a/custom_components/smart_frame_engine/strings.json +++ b/custom_components/smart_frame_engine/strings.json @@ -74,6 +74,205 @@ } } }, + "entity": { + "binary_sensor": { + "engine_connected": { + "name": "Engine connected" + }, + "frame_online": { + "name": "Frame online" + }, + "frame_charging": { + "name": "Frame charging" + }, + "delivery_pending": { + "name": "Image pending delivery" + }, + "ephemeral_active": { + "name": "Temporary image" + }, + "quiet_hours": { + "name": "Quiet hours" + } + }, + "button": { + "force_refresh": { + "name": "Refresh image" + }, + "wake_frame": { + "name": "Wake up frame" + } + }, + "image": { + "current_image": { + "name": "Current image" + } + }, + "sensor": { + "engine_version": { + "name": "Engine version" + }, + "active_source": { + "name": "Image source" + }, + "refresh_rule": { + "name": "Refresh mode", + "state": { + "pinned": "Pinned rule", + "smart_mix": "Smart Mix", + "last": "Last request" + } + }, + "media_title": { + "name": "Media title" + }, + "ambient_context": { + "name": "Ambient context" + }, + "last_delivery": { + "name": "Last delivery" + }, + "frame_last_seen": { + "name": "Frame last seen" + }, + "frame_battery": { + "name": "Frame battery" + }, + "frame_wifi_signal": { + "name": "Frame Wi-Fi signal" + } + }, + "switch": { + "family_mode": { + "name": "Family Mode" + } + } + }, + "services": { + "set_ambient_context": { + "name": "Set ambient context", + "description": "Tells the engine about the current situation (weather, who is home, season, boosts). Each field expires on its own. Fields you leave out keep their value; an empty text or list clears that field.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "family_mode": { + "name": "Family Mode", + "description": "Temporarily forces Family Mode on or off." + }, + "presence": { + "name": "People at home", + "description": "Immich people at home; their photos are favoured (up to 20)." + }, + "weather": { + "name": "Weather", + "description": "A weather keyword known to the engine, for example rainy (up to 80 characters)." + }, + "season": { + "name": "Season", + "description": "Replaces the calendar season." + }, + "boost_tags": { + "name": "Boost tags", + "description": "Search phrases to favour, for example beach or birthday (up to 20)." + }, + "boost_people": { + "name": "Boost people", + "description": "Immich people to favour (up to 20)." + }, + "ttl_minutes": { + "name": "Lifetime", + "description": "How long the fields set by this call last, in minutes (1 to 10080). The engine's default applies when left empty." + } + } + }, + "clear_ambient_context": { + "name": "Clear ambient context", + "description": "Clears the ambient context, or only one field of it.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "field": { + "name": "Field", + "description": "Clear only this field. Leave empty to clear everything." + } + } + }, + "send_title_card": { + "name": "Send title card", + "description": "Shows a text card (title, subtitle, caption) on the frame.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "title": { + "name": "Title", + "description": "Large centered text (1 to 200 characters)." + }, + "subtitle": { + "name": "Subtitle", + "description": "Smaller text below the title (up to 200 characters)." + }, + "caption": { + "name": "Caption", + "description": "Small text at the bottom (up to 200 characters)." + }, + "accent": { + "name": "Accent color", + "description": "Color of the rule under the title." + }, + "ephemeral": { + "name": "Temporary", + "description": "When on, the previous image comes back afterwards." + }, + "ttl_minutes": { + "name": "Duration", + "description": "Temporary cards only: minutes before the previous image returns (1 to 10080). The engine's default (60) applies when left empty." + }, + "hold_minutes": { + "name": "Protect from refresh", + "description": "Minutes during which scheduled refreshes will not replace the card (1 to 10080)." + }, + "push_to_fraimic": { + "name": "Send to frame", + "description": "Turn off to only render a preview without sending it to the frame." + } + } + } + }, + "selector": { + "season": { + "options": { + "spring": "Spring", + "summer": "Summer", + "autumn": "Autumn", + "winter": "Winter" + } + }, + "ambient_field": { + "options": { + "presence": "People at home", + "family_mode": "Family Mode", + "weather": "Weather", + "season": "Season", + "boost_tags": "Boost tags", + "boost_people": "Boost people" + } + }, + "accent": { + "options": { + "red": "Red", + "yellow": "Yellow", + "blue": "Blue", + "green": "Green", + "white": "White" + } + } + }, "issues": { "integration_outdated": { "title": "Smart Frame Engine integration needs an update", @@ -99,6 +298,27 @@ }, "instance_mismatch": { "message": "The device at the configured address is not {name}. It is a different Smart Frame Engine." + }, + "action_failed": { + "message": "The Smart Frame Engine could not do that: {error}" + }, + "request_rejected": { + "message": "The Smart Frame Engine rejected the request: {error}" + }, + "capability_not_supported": { + "message": "The Smart Frame Engine {name} does not support this feature ({capability}). Update the engine to use it." + }, + "no_context_fields": { + "message": "Give at least one ambient context field to set (family mode, presence, weather, season, boost tags or boost people)." + }, + "config_entry_required": { + "message": "Several Smart Frame Engines are set up. Choose which one to use." + }, + "entry_not_found": { + "message": "No Smart Frame Engine with the ID {entry_id} was found." + }, + "no_engine_loaded": { + "message": "The Smart Frame Engine is not loaded. Check that it is reachable and try again." } } } diff --git a/custom_components/smart_frame_engine/switch.py b/custom_components/smart_frame_engine/switch.py new file mode 100644 index 0000000..76e1f83 --- /dev/null +++ b/custom_components/smart_frame_engine/switch.py @@ -0,0 +1,66 @@ +"""Family Mode switch.""" + +from __future__ import annotations + +from typing import Any + +from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from .const import CAPABILITY_FAMILY_MODE +from .coordinator import SmartFrameConfigEntry, SmartFrameCoordinator +from .entity import SmartFrameEntity + +PARALLEL_UPDATES = 1 + +FAMILY_MODE = SwitchEntityDescription(key="family_mode", translation_key="family_mode") + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SmartFrameConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the Family Mode switch when the engine supports it.""" + coordinator = entry.runtime_data + if CAPABILITY_FAMILY_MODE in coordinator.capabilities: + async_add_entities([SmartFrameFamilyModeSwitch(coordinator)]) + + +class SmartFrameFamilyModeSwitch(SmartFrameEntity, SwitchEntity): + """The persistent Family Mode setting (``config.family.enabled``). + + A temporary override made through the ambient context is reported in the + ``active_now`` attribute (``AmbientView.family_active``: "applies right now"). + """ + + def __init__(self, coordinator: SmartFrameCoordinator) -> None: + """Initialise the switch.""" + super().__init__(coordinator, FAMILY_MODE) + + @property + def is_on(self) -> bool | None: + """Return the stored Family Mode setting.""" + config = self.coordinator.data.config + return config.family_enabled if config else None + + @property + def extra_state_attributes(self) -> dict[str, Any] | None: + """Report whether Family Mode applies right now (a temporary override may differ).""" + ambient = self.coordinator.data.ambient + return {"active_now": ambient.family_active} if ambient else None + + async def _async_set(self, enabled: bool) -> None: + coordinator = self.coordinator + config = await coordinator.async_action(coordinator.client.async_set_family_mode(enabled)) + coordinator.async_apply_config(config) + await coordinator.async_request_refresh() + + async def async_turn_on(self, **kwargs: Any) -> None: + """Enable Family Mode.""" + await self._async_set(True) + + async def async_turn_off(self, **kwargs: Any) -> None: + """Disable Family Mode.""" + await self._async_set(False) diff --git a/custom_components/smart_frame_engine/translations/en.json b/custom_components/smart_frame_engine/translations/en.json index 6d0afe4..35ef4d9 100644 --- a/custom_components/smart_frame_engine/translations/en.json +++ b/custom_components/smart_frame_engine/translations/en.json @@ -74,6 +74,205 @@ } } }, + "entity": { + "binary_sensor": { + "engine_connected": { + "name": "Engine connected" + }, + "frame_online": { + "name": "Frame online" + }, + "frame_charging": { + "name": "Frame charging" + }, + "delivery_pending": { + "name": "Image pending delivery" + }, + "ephemeral_active": { + "name": "Temporary image" + }, + "quiet_hours": { + "name": "Quiet hours" + } + }, + "button": { + "force_refresh": { + "name": "Refresh image" + }, + "wake_frame": { + "name": "Wake up frame" + } + }, + "image": { + "current_image": { + "name": "Current image" + } + }, + "sensor": { + "engine_version": { + "name": "Engine version" + }, + "active_source": { + "name": "Image source" + }, + "refresh_rule": { + "name": "Refresh mode", + "state": { + "pinned": "Pinned rule", + "smart_mix": "Smart Mix", + "last": "Last request" + } + }, + "media_title": { + "name": "Media title" + }, + "ambient_context": { + "name": "Ambient context" + }, + "last_delivery": { + "name": "Last delivery" + }, + "frame_last_seen": { + "name": "Frame last seen" + }, + "frame_battery": { + "name": "Frame battery" + }, + "frame_wifi_signal": { + "name": "Frame Wi-Fi signal" + } + }, + "switch": { + "family_mode": { + "name": "Family Mode" + } + } + }, + "services": { + "set_ambient_context": { + "name": "Set ambient context", + "description": "Tells the engine about the current situation (weather, who is home, season, boosts). Each field expires on its own. Fields you leave out keep their value; an empty text or list clears that field.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "family_mode": { + "name": "Family Mode", + "description": "Temporarily forces Family Mode on or off." + }, + "presence": { + "name": "People at home", + "description": "Immich people at home; their photos are favoured (up to 20)." + }, + "weather": { + "name": "Weather", + "description": "A weather keyword known to the engine, for example rainy (up to 80 characters)." + }, + "season": { + "name": "Season", + "description": "Replaces the calendar season." + }, + "boost_tags": { + "name": "Boost tags", + "description": "Search phrases to favour, for example beach or birthday (up to 20)." + }, + "boost_people": { + "name": "Boost people", + "description": "Immich people to favour (up to 20)." + }, + "ttl_minutes": { + "name": "Lifetime", + "description": "How long the fields set by this call last, in minutes (1 to 10080). The engine's default applies when left empty." + } + } + }, + "clear_ambient_context": { + "name": "Clear ambient context", + "description": "Clears the ambient context, or only one field of it.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "field": { + "name": "Field", + "description": "Clear only this field. Leave empty to clear everything." + } + } + }, + "send_title_card": { + "name": "Send title card", + "description": "Shows a text card (title, subtitle, caption) on the frame.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "title": { + "name": "Title", + "description": "Large centered text (1 to 200 characters)." + }, + "subtitle": { + "name": "Subtitle", + "description": "Smaller text below the title (up to 200 characters)." + }, + "caption": { + "name": "Caption", + "description": "Small text at the bottom (up to 200 characters)." + }, + "accent": { + "name": "Accent color", + "description": "Color of the rule under the title." + }, + "ephemeral": { + "name": "Temporary", + "description": "When on, the previous image comes back afterwards." + }, + "ttl_minutes": { + "name": "Duration", + "description": "Temporary cards only: minutes before the previous image returns (1 to 10080). The engine's default (60) applies when left empty." + }, + "hold_minutes": { + "name": "Protect from refresh", + "description": "Minutes during which scheduled refreshes will not replace the card (1 to 10080)." + }, + "push_to_fraimic": { + "name": "Send to frame", + "description": "Turn off to only render a preview without sending it to the frame." + } + } + } + }, + "selector": { + "season": { + "options": { + "spring": "Spring", + "summer": "Summer", + "autumn": "Autumn", + "winter": "Winter" + } + }, + "ambient_field": { + "options": { + "presence": "People at home", + "family_mode": "Family Mode", + "weather": "Weather", + "season": "Season", + "boost_tags": "Boost tags", + "boost_people": "Boost people" + } + }, + "accent": { + "options": { + "red": "Red", + "yellow": "Yellow", + "blue": "Blue", + "green": "Green", + "white": "White" + } + } + }, "issues": { "integration_outdated": { "title": "Smart Frame Engine integration needs an update", @@ -99,6 +298,27 @@ }, "instance_mismatch": { "message": "The device at the configured address is not {name}. It is a different Smart Frame Engine." + }, + "action_failed": { + "message": "The Smart Frame Engine could not do that: {error}" + }, + "request_rejected": { + "message": "The Smart Frame Engine rejected the request: {error}" + }, + "capability_not_supported": { + "message": "The Smart Frame Engine {name} does not support this feature ({capability}). Update the engine to use it." + }, + "no_context_fields": { + "message": "Give at least one ambient context field to set (family mode, presence, weather, season, boost tags or boost people)." + }, + "config_entry_required": { + "message": "Several Smart Frame Engines are set up. Choose which one to use." + }, + "entry_not_found": { + "message": "No Smart Frame Engine with the ID {entry_id} was found." + }, + "no_engine_loaded": { + "message": "The Smart Frame Engine is not loaded. Check that it is reachable and try again." } } } diff --git a/custom_components/smart_frame_engine/translations/fr.json b/custom_components/smart_frame_engine/translations/fr.json index 276eb62..80a5ca2 100644 --- a/custom_components/smart_frame_engine/translations/fr.json +++ b/custom_components/smart_frame_engine/translations/fr.json @@ -74,6 +74,205 @@ } } }, + "entity": { + "binary_sensor": { + "engine_connected": { + "name": "Moteur connecté" + }, + "frame_online": { + "name": "Cadre en ligne" + }, + "frame_charging": { + "name": "Cadre en charge" + }, + "delivery_pending": { + "name": "Image en attente d'envoi" + }, + "ephemeral_active": { + "name": "Image temporaire" + }, + "quiet_hours": { + "name": "Heures calmes" + } + }, + "button": { + "force_refresh": { + "name": "Rafraîchir l'image" + }, + "wake_frame": { + "name": "Réveiller le cadre" + } + }, + "image": { + "current_image": { + "name": "Image actuelle" + } + }, + "sensor": { + "engine_version": { + "name": "Version du moteur" + }, + "active_source": { + "name": "Source de l'image" + }, + "refresh_rule": { + "name": "Mode de rafraîchissement", + "state": { + "pinned": "Règle fixée", + "smart_mix": "Smart Mix", + "last": "Dernière demande" + } + }, + "media_title": { + "name": "Titre du média" + }, + "ambient_context": { + "name": "Contexte ambiant" + }, + "last_delivery": { + "name": "Dernier envoi" + }, + "frame_last_seen": { + "name": "Cadre vu pour la dernière fois" + }, + "frame_battery": { + "name": "Batterie du cadre" + }, + "frame_wifi_signal": { + "name": "Signal Wi-Fi du cadre" + } + }, + "switch": { + "family_mode": { + "name": "Mode Famille" + } + } + }, + "services": { + "set_ambient_context": { + "name": "Définir le contexte ambiant", + "description": "Informe le moteur de la situation actuelle (météo, qui est à la maison, saison, mises en avant). Chaque champ expire de lui-même. Les champs omis conservent leur valeur ; un texte ou une liste vide efface le champ.", + "fields": { + "config_entry_id": { + "name": "Moteur", + "description": "Le Smart Frame Engine à utiliser. Facultatif si un seul est configuré." + }, + "family_mode": { + "name": "Mode Famille", + "description": "Force temporairement le mode Famille activé ou désactivé." + }, + "presence": { + "name": "Personnes à la maison", + "description": "Personnes Immich présentes à la maison ; leurs photos sont favorisées (20 maximum)." + }, + "weather": { + "name": "Météo", + "description": "Un mot-clé météo connu du moteur, par exemple rainy (80 caractères maximum)." + }, + "season": { + "name": "Saison", + "description": "Remplace la saison du calendrier." + }, + "boost_tags": { + "name": "Mots-clés à favoriser", + "description": "Expressions de recherche à favoriser, par exemple beach ou birthday (20 maximum)." + }, + "boost_people": { + "name": "Personnes à favoriser", + "description": "Personnes Immich à favoriser (20 maximum)." + }, + "ttl_minutes": { + "name": "Durée de vie", + "description": "Durée des champs définis par cet appel, en minutes (1 à 10080). La valeur par défaut du moteur s'applique si le champ est vide." + } + } + }, + "clear_ambient_context": { + "name": "Effacer le contexte ambiant", + "description": "Efface le contexte ambiant, ou seulement l'un de ses champs.", + "fields": { + "config_entry_id": { + "name": "Moteur", + "description": "Le Smart Frame Engine à utiliser. Facultatif si un seul est configuré." + }, + "field": { + "name": "Champ", + "description": "Efface uniquement ce champ. Laissez vide pour tout effacer." + } + } + }, + "send_title_card": { + "name": "Envoyer une carte de titre", + "description": "Affiche une carte de texte (titre, sous-titre, légende) sur le cadre.", + "fields": { + "config_entry_id": { + "name": "Moteur", + "description": "Le Smart Frame Engine à utiliser. Facultatif si un seul est configuré." + }, + "title": { + "name": "Titre", + "description": "Grand texte centré (de 1 à 200 caractères)." + }, + "subtitle": { + "name": "Sous-titre", + "description": "Texte plus petit sous le titre (200 caractères maximum)." + }, + "caption": { + "name": "Légende", + "description": "Petit texte en bas (200 caractères maximum)." + }, + "accent": { + "name": "Couleur d'accent", + "description": "Couleur du filet sous le titre." + }, + "ephemeral": { + "name": "Temporaire", + "description": "Si activé, l'image précédente revient ensuite." + }, + "ttl_minutes": { + "name": "Durée", + "description": "Cartes temporaires uniquement : minutes avant le retour de l'image précédente (1 à 10080). La valeur par défaut du moteur (60) s'applique si le champ est vide." + }, + "hold_minutes": { + "name": "Protéger du rafraîchissement", + "description": "Minutes pendant lesquelles les rafraîchissements planifiés ne remplaceront pas la carte (1 à 10080)." + }, + "push_to_fraimic": { + "name": "Envoyer au cadre", + "description": "Désactivez pour seulement générer un aperçu sans l'envoyer au cadre." + } + } + } + }, + "selector": { + "season": { + "options": { + "spring": "Printemps", + "summer": "Été", + "autumn": "Automne", + "winter": "Hiver" + } + }, + "ambient_field": { + "options": { + "presence": "Personnes à la maison", + "family_mode": "Mode Famille", + "weather": "Météo", + "season": "Saison", + "boost_tags": "Mots-clés à favoriser", + "boost_people": "Personnes à favoriser" + } + }, + "accent": { + "options": { + "red": "Rouge", + "yellow": "Jaune", + "blue": "Bleu", + "green": "Vert", + "white": "Blanc" + } + } + }, "issues": { "integration_outdated": { "title": "L'intégration Smart Frame Engine doit être mise à jour", @@ -99,6 +298,27 @@ }, "instance_mismatch": { "message": "L'appareil à l'adresse configurée n'est pas {name}. Il s'agit d'un autre Smart Frame Engine." + }, + "action_failed": { + "message": "Le Smart Frame Engine n'a pas pu effectuer l'action : {error}" + }, + "request_rejected": { + "message": "Le Smart Frame Engine a rejeté la requête : {error}" + }, + "capability_not_supported": { + "message": "Le Smart Frame Engine {name} ne prend pas en charge cette fonctionnalité ({capability}). Mettez à jour le moteur pour l'utiliser." + }, + "no_context_fields": { + "message": "Indiquez au moins un champ de contexte ambiant à définir (mode Famille, présence, météo, saison, mots-clés ou personnes à favoriser)." + }, + "config_entry_required": { + "message": "Plusieurs Smart Frame Engine sont configurés. Choisissez celui à utiliser." + }, + "entry_not_found": { + "message": "Aucun Smart Frame Engine avec l'identifiant {entry_id} n'a été trouvé." + }, + "no_engine_loaded": { + "message": "Le Smart Frame Engine n'est pas chargé. Vérifiez qu'il est joignable puis réessayez." } } } diff --git a/tests/common.py b/tests/common.py index 76a5c94..792e4ee 100644 --- a/tests/common.py +++ b/tests/common.py @@ -6,6 +6,8 @@ from typing import Any from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from pytest_homeassistant_custom_component.common import MockConfigEntry from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker @@ -33,7 +35,7 @@ def health_payload( capabilities: set[str] | frozenset[str] | None = None, instance_id: str | None = INSTANCE_ID, instance_name: str | None = INSTANCE_NAME, - version: str = "1.0.0rc2", + version: str = "1.0.0rc3", ) -> dict[str, Any]: """Return a ``GET /api/health`` body; ``instance_id=None`` mimics an rc.1 engine.""" payload: dict[str, Any] = { @@ -54,7 +56,8 @@ def health_payload( def status_payload() -> dict[str, Any]: """Return a ``GET /api/status`` body.""" return { - "version": "1.0.0rc2", + "version": "1.0.0rc3", + "release": "1.0.0-rc.3", "uptime_s": 1234.5, "auth_enabled": False, "auth_mode": "open", @@ -85,7 +88,20 @@ def status_payload() -> dict[str, Any]: "panel": "133", "panel_label": "13.3 inch", "power_mode": "deepsleep", - "telemetry": {"battery": 80}, + "telemetry": { + "online": True, + "last_seen": "2026-11-19T09:59:00Z", + "last_checked": "2026-11-19T10:00:00Z", + "last_error": None, + "info": { + "battery_percent": 80, + "charging": False, + "firmware_version": "1.2.3", + "ip": "192.168.1.60", + "rssi": -61, + "raw": {}, + }, + }, }, "delivery": { "pending": False, @@ -98,6 +114,7 @@ def status_payload() -> dict[str, Any]: }, }, "scheduler": { + "active_rule": {"kind": "immich", "source": "smart_mix"}, "enabled": True, "running": False, "in_quiet_hours": False, @@ -152,14 +169,48 @@ def mock_engine( aioclient_mock: AiohttpClientMocker, *, base: str = BASE, + status: dict[str, Any] | None = None, + config: dict[str, Any] | None = None, + context: dict[str, Any] | None = None, **health_kwargs: Any, ) -> None: """Register the endpoints polled by the coordinator for a healthy engine.""" health = health_payload(**health_kwargs) aioclient_mock.get(f"{base}/api/health", json=health) - aioclient_mock.get(f"{base}/api/status", json=status_payload()) - aioclient_mock.get(f"{base}/api/context", json=context_payload()) - aioclient_mock.get(f"{base}/api/config", json=config_payload()) + aioclient_mock.get(f"{base}/api/status", json=status or status_payload()) + aioclient_mock.get(f"{base}/api/context", json=context or context_payload()) + aioclient_mock.get(f"{base}/api/config", json=config or config_payload()) + + +async def setup_engine( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + *, + api_key: str | None = None, + entry: MockConfigEntry | None = None, + **mock_kwargs: Any, +) -> MockConfigEntry: + """Mock a healthy engine and set its config entry up.""" + mock_engine(aioclient_mock, **mock_kwargs) + entry = entry or make_entry(api_key=api_key) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + return entry + + +def entity_id(hass: HomeAssistant, platform: str, key: str, instance_id: str = INSTANCE_ID) -> str: + """Return the entity id registered for ``key`` (fails the test when it does not exist).""" + found = er.async_get(hass).async_get_entity_id(platform, DOMAIN, f"{instance_id}_{key}") + assert found is not None, f"no {platform} entity with key {key}" + return found + + +def has_entity(hass: HomeAssistant, platform: str, key: str) -> bool: + """Whether an entity with ``key`` is registered.""" + return ( + er.async_get(hass).async_get_entity_id(platform, DOMAIN, f"{INSTANCE_ID}_{key}") is not None + ) def make_entry( @@ -186,7 +237,7 @@ def zeroconf_info( ) -> ZeroconfServiceInfo: """Return a discovery record of ``_smartframe._tcp.local.``.""" properties: dict[str, str | None] = { - "version": "1.0.0rc2", + "version": "1.0.0rc3", "api_version": api_version, "min_api_version": min_api_version, "path": path, diff --git a/tests/test_api.py b/tests/test_api.py index 9676779..7e57ca7 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -50,9 +50,9 @@ def _last_call(mock: AiohttpClientMocker) -> tuple[str, Any, Any, Any]: def test_supported_version_and_capability_flags() -> None: - """The client speaks contract 1 and knows all 18 flags of API_CONTRACT.md.""" + """The client speaks contract 1 and knows all 19 flags of API_CONTRACT.md.""" assert SUPPORTED_API_VERSION == 1 - assert len(ALL_CAPABILITIES) == 18 + assert len(ALL_CAPABILITIES) == 19 assert { "activity_log", "ambient_context", @@ -70,6 +70,7 @@ def test_supported_version_and_capability_flags() -> None: "random_discovery", "smart_mix", "smart_mix_context", + "smart_mix_kinds", "title_card", "upload_image", } == ALL_CAPABILITIES @@ -115,7 +116,7 @@ async def test_health_parsing(hass: HomeAssistant, aioclient_mock: AiohttpClient health = await _client(hass).async_get_health() - assert health.version == "1.0.0rc2" + assert health.version == "1.0.0rc3" assert health.api_version == 1 assert health.min_api_version == 1 assert health.auth == "key" @@ -129,7 +130,7 @@ async def test_health_parsing(hass: HomeAssistant, aioclient_mock: AiohttpClient async def test_health_without_instance_id( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: - """An engine older than 1.0.0rc2 simply has no instance id.""" + """An engine older than 1.0.0rc3 simply has no instance id.""" aioclient_mock.get( f"{BASE}/api/health", json=health_payload(instance_id=None, instance_name=None) ) @@ -292,7 +293,8 @@ async def test_status_parsing(hass: HomeAssistant, aioclient_mock: AiohttpClient aioclient_mock.get(f"{BASE}/api/status", json=status_payload()) status = await _client(hass).async_get_status() - assert status.version == "1.0.0rc2" + assert status.version == "1.0.0rc3" + assert status.release == "1.0.0-rc.3" assert status.uptime_s == 1234.5 assert status.current_image is not None assert status.current_image.source == "immich" @@ -301,9 +303,19 @@ async def test_status_parsing(hass: HomeAssistant, aioclient_mock: AiohttpClient assert status.ephemeral.active is False assert status.frame.configured is True assert status.frame.power_mode == "deepsleep" - assert status.frame.telemetry == {"battery": 80} + assert status.frame.telemetry.online is True + assert status.frame.telemetry.battery_percent == 80 + assert status.frame.telemetry.charging is False + assert status.frame.telemetry.rssi == -61 + assert status.frame.telemetry.firmware_version == "1.2.3" + assert status.frame.telemetry.last_seen is not None + assert status.scheduler.active_rule_kind == "immich" + assert status.scheduler.active_rule_source == "smart_mix" assert status.delivery.pending is False - assert status.delivery.last_delivered_at is not None + assert status.delivery.last_delivery is not None + assert status.delivery.last_delivery.delivered_at is not None + assert status.delivery.last_delivery.reason == "submit" + assert status.delivery.last_delivery.size_bytes == 1 assert status.scheduler.enabled is True assert status.scheduler.last_run_status == "ok" assert status.scheduler.ambient.weather is not None diff --git a/tests/test_binary_sensor.py b/tests/test_binary_sensor.py new file mode 100644 index 0000000..e4b4419 --- /dev/null +++ b/tests/test_binary_sensor.py @@ -0,0 +1,127 @@ +"""Tests for the binary sensor platform.""" + +from __future__ import annotations + +from typing import Any + +from homeassistant.const import ( + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, + STATE_UNKNOWN, + EntityCategory, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er +import pytest +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.coordinator import SmartFrameCoordinator + +from .common import BASE, entity_id, mock_engine, setup_engine, status_payload + + +def _state(hass: HomeAssistant, key: str) -> Any: + state = hass.states.get(entity_id(hass, "binary_sensor", key)) + assert state is not None + return state + + +async def test_states_and_metadata( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Every binary sensor reports the value documented in /api/status.""" + await setup_engine(hass, aioclient_mock) + + assert _state(hass, "engine_connected").state == STATE_ON + assert _state(hass, "engine_connected").attributes["device_class"] == "connectivity" + assert _state(hass, "frame_online").state == STATE_ON + assert _state(hass, "frame_online").attributes["device_class"] == "connectivity" + assert _state(hass, "frame_online").attributes["last_error"] is None + assert _state(hass, "frame_charging").state == STATE_OFF + assert _state(hass, "frame_charging").attributes["device_class"] == "battery_charging" + assert _state(hass, "delivery_pending").state == STATE_OFF + assert _state(hass, "ephemeral_active").state == STATE_OFF + assert _state(hass, "quiet_hours").state == STATE_OFF + + registry = er.async_get(hass) + for key in ("engine_connected", "frame_online", "frame_charging", "delivery_pending"): + entry = registry.async_get(entity_id(hass, "binary_sensor", key)) + assert entry is not None + assert entry.entity_category is EntityCategory.DIAGNOSTIC + + +async def test_active_states(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """Pending delivery, temporary image, quiet hours and an offline frame are reflected.""" + status = status_payload() + status["delivery"]["pending"] = True + status["ephemeral"] = { + "active": True, + "pending": False, + "has_base": True, + "expires_at": "2026-11-19T12:00:00Z", + "source": "tmdb", + "title": "Dune", + } + status["scheduler"]["in_quiet_hours"] = True + status["frame"]["telemetry"]["online"] = False + status["frame"]["telemetry"]["last_error"] = "timeout" + status["frame"]["telemetry"]["info"]["charging"] = True + await setup_engine(hass, aioclient_mock, status=status) + + assert _state(hass, "delivery_pending").state == STATE_ON + assert _state(hass, "quiet_hours").state == STATE_ON + assert _state(hass, "frame_online").state == STATE_OFF + assert _state(hass, "frame_online").attributes["last_error"] == "timeout" + assert _state(hass, "frame_charging").state == STATE_ON + ephemeral = _state(hass, "ephemeral_active") + assert ephemeral.state == STATE_ON + assert ephemeral.attributes["title"] == "Dune" + assert ephemeral.attributes["source"] == "tmdb" + + +async def test_frame_never_contacted_is_unknown( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """telemetry.online is null until the frame was contacted: unknown, not off.""" + status = status_payload() + status["frame"]["telemetry"] = {"online": None, "info": None} + await setup_engine(hass, aioclient_mock, status=status) + + assert _state(hass, "frame_online").state == STATE_UNKNOWN + assert _state(hass, "frame_charging").state == STATE_UNKNOWN + + +async def test_frame_not_configured_is_unknown( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Without a configured frame there is nothing to be online.""" + status = status_payload() + status["frame"]["configured"] = False + await setup_engine(hass, aioclient_mock, status=status) + assert _state(hass, "frame_online").state == STATE_UNKNOWN + + +@pytest.mark.parametrize("exc", [TimeoutError, ConnectionError]) +async def test_engine_connectivity_reports_the_outage( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, exc: type[Exception] +) -> None: + """When polling fails the connectivity sensor goes off; the others become unavailable.""" + entry = await setup_engine(hass, aioclient_mock) + coordinator: SmartFrameCoordinator = entry.runtime_data + + aioclient_mock.clear_requests() + aioclient_mock.get(f"{BASE}/api/health", exc=exc) + await coordinator.async_refresh() + await hass.async_block_till_done() + + assert _state(hass, "engine_connected").state == STATE_OFF + assert _state(hass, "frame_online").state == STATE_UNAVAILABLE + assert _state(hass, "quiet_hours").state == STATE_UNAVAILABLE + + aioclient_mock.clear_requests() + mock_engine(aioclient_mock) + await coordinator.async_refresh() + await hass.async_block_till_done() + assert _state(hass, "engine_connected").state == STATE_ON + assert _state(hass, "frame_online").state == STATE_ON diff --git a/tests/test_button.py b/tests/test_button.py new file mode 100644 index 0000000..544b79b --- /dev/null +++ b/tests/test_button.py @@ -0,0 +1,139 @@ +"""Tests for the button platform.""" + +from __future__ import annotations + +from homeassistant.config_entries import SOURCE_REAUTH +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +import pytest +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.const import ( + CAPABILITY_FORCE_REFRESH, + CAPABILITY_FRAME_WAKEUP, + DOMAIN, +) + +from .common import ( + API_KEY, + BASE, + display_payload, + entity_id, + has_entity, + setup_engine, +) + +REFRESH_REPLY = { + "display": display_payload(), + "reason": "manual", + "rule_kind": "immich", + "rule_source": "smart_mix", +} + + +async def _press(hass: HomeAssistant, key: str) -> None: + await hass.services.async_call( + "button", "press", {"entity_id": entity_id(hass, "button", key)}, blocking=True + ) + + +def _count(aioclient_mock: AiohttpClientMocker, path: str) -> int: + return sum(call[1].path == path for call in aioclient_mock.mock_calls) + + +@pytest.mark.parametrize( + ("capabilities", "refresh", "wake"), + [ + ({CAPABILITY_FORCE_REFRESH, CAPABILITY_FRAME_WAKEUP}, True, True), + ({CAPABILITY_FORCE_REFRESH}, True, False), + ({CAPABILITY_FRAME_WAKEUP}, False, True), + (set(), False, False), + ], +) +async def test_capability_gating( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + capabilities: set[str], + refresh: bool, + wake: bool, +) -> None: + """Each button exists only when the engine advertises its capability.""" + await setup_engine(hass, aioclient_mock, capabilities=capabilities) + assert has_entity(hass, "button", "force_refresh") is refresh + assert has_entity(hass, "button", "wake_frame") is wake + + +async def test_force_refresh(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """Pressing calls POST /api/refresh and then refreshes the coordinator.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.post(f"{BASE}/api/refresh", json=REFRESH_REPLY) + before = _count(aioclient_mock, "/api/status") + + await _press(hass, "force_refresh") + + method, url, _, headers = [c for c in aioclient_mock.mock_calls if c[0] == "POST"][-1] + assert (method, url.path) == ("POST", "/api/refresh") + assert headers["X-API-Key"] == API_KEY + assert _count(aioclient_mock, "/api/status") == before + 1 + + +async def test_wake_frame_is_non_blocking( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Wake up: POST /api/fraimic/wakeup without ?wait (the engine answers 202).""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post( + f"{BASE}/api/fraimic/wakeup", status=202, json={"accepted": True, "pending": True} + ) + before = _count(aioclient_mock, "/api/status") + + await _press(hass, "wake_frame") + + _, url, _, _ = [c for c in aioclient_mock.mock_calls if c[0] == "POST"][-1] + assert url.path == "/api/fraimic/wakeup" + assert dict(url.query) == {} + assert _count(aioclient_mock, "/api/status") == before + 1 + + +@pytest.mark.parametrize( + ("key", "path"), + [("force_refresh", "/api/refresh"), ("wake_frame", "/api/fraimic/wakeup")], +) +@pytest.mark.parametrize("status", [404, 409, 502, 504]) +async def test_engine_errors_surface( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + key: str, + path: str, + status: int, +) -> None: + """404/409/502/504 (no source, upstream down...) reach the user with the engine's message.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}{path}", status=status, json={"detail": "Immich is not set up"}) + with pytest.raises(HomeAssistantError, match="Immich is not set up"): + await _press(hass, key) + + +async def test_no_refresh_after_a_failed_press( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A failed action does not trigger a coordinator refresh.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}/api/refresh", status=409, json={"detail": "nope"}) + before = _count(aioclient_mock, "/api/status") + with pytest.raises(HomeAssistantError): + await _press(hass, "force_refresh") + assert _count(aioclient_mock, "/api/status") == before + + +async def test_rejected_key_starts_reauth( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A 401 on a press starts reauthentication.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.post(f"{BASE}/api/refresh", status=401, json={"detail": "no"}) + with pytest.raises(HomeAssistantError): + await _press(hass, "force_refresh") + await hass.async_block_till_done() + flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) + assert [flow["context"]["source"] for flow in flows] == [SOURCE_REAUTH] diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index 31352b0..05e1314 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -14,7 +14,14 @@ from custom_components.smart_frame_engine.const import ALL_CAPABILITIES -from .common import API_KEY, INSTANCE_ID, make_entry, mock_engine +from .common import ( + API_KEY, + INSTANCE_ID, + context_payload, + make_entry, + mock_engine, + status_payload, +) async def test_diagnostics_redacts_the_api_key( @@ -39,6 +46,34 @@ async def test_diagnostics_redacts_the_api_key( assert diagnostics["health"]["auth"] == "key" assert diagnostics["health"]["api_version"] == 1 assert diagnostics["health"]["instance_id"] == INSTANCE_ID - assert diagnostics["status"]["version"] == "1.0.0rc2" + assert diagnostics["status"]["version"] == "1.0.0rc3" assert diagnostics["ambient"]["family_active"] is True assert diagnostics["coordinator"]["last_update_success"] is True + + +async def test_diagnostics_redacts_personal_data( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + aioclient_mock: AiohttpClientMocker, +) -> None: + """People and places (image details, presence, boost lists) never reach a shared report.""" + status = status_payload() + status["current_image"]["details"] = {"people": ["Alice"], "location": "Lyon"} + context = context_payload() + context["context"]["boost_people"] = {"values": ["Carol"], "expires_at": "2026-11-19T12:00:00Z"} + mock_engine(aioclient_mock, status=status, context=context) + entry = make_entry() + entry.add_to_hass(hass) + assert await async_setup_component(hass, "diagnostics", {}) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + diagnostics = await get_diagnostics_for_config_entry(hass, hass_client, entry) + + assert diagnostics["status"]["current_image"]["details"] == "**REDACTED**" + assert diagnostics["ambient"]["context"]["presence"] == "**REDACTED**" + assert diagnostics["ambient"]["context"]["boost_people"] == "**REDACTED**" + dumped = json.dumps(diagnostics) + for personal in ("Alice", "Bob", "Carol", "Lyon"): + assert personal not in dumped + assert diagnostics["family_enabled"] is False diff --git a/tests/test_entity.py b/tests/test_entity.py index c0b7a6f..94bfa76 100644 --- a/tests/test_entity.py +++ b/tests/test_entity.py @@ -32,6 +32,6 @@ async def test_entity_shares_the_engine_device( assert info["identifiers"] == {(DOMAIN, INSTANCE_ID)} assert info["name"] == INSTANCE_NAME assert info["manufacturer"] == "Smart Frame Engine" - assert info["sw_version"] == "1.0.0rc2" + assert info["sw_version"] == "1.0.0-rc.3" assert info["configuration_url"] == "http://192.168.1.50:8080/" assert entity.available is True diff --git a/tests/test_image.py b/tests/test_image.py new file mode 100644 index 0000000..4da5a31 --- /dev/null +++ b/tests/test_image.py @@ -0,0 +1,198 @@ +"""Tests for the live preview image entity.""" + +from __future__ import annotations + +from typing import Any + +import aiohttp +from homeassistant.components.image import async_get_image +from homeassistant.const import STATE_UNKNOWN +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +import pytest +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.coordinator import SmartFrameCoordinator + +from .common import API_KEY, BASE, entity_id, mock_engine, setup_engine, status_payload + +JPEG = b"\xff\xd8\xff\xe0current" +PREVIEW = b"\xff\xd8\xff\xe0preview" + + +def _count(aioclient_mock: AiohttpClientMocker, path: str) -> int: + return sum(call[1].path == path for call in aioclient_mock.mock_calls) + + +def _status_with(**image: Any) -> dict[str, Any]: + status = status_payload() + status["current_image"].update(image) + return status + + +async def _refresh( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + coordinator: SmartFrameCoordinator, + status: dict[str, Any], +) -> None: + aioclient_mock.clear_requests() + mock_engine(aioclient_mock, status=status) + aioclient_mock.get(f"{BASE}/api/current.jpg", content=JPEG) + await coordinator.async_refresh() + await hass.async_block_till_done() + + +async def test_state_is_the_render_time( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The image entity's state is image_last_updated, taken from processed_at.""" + await setup_engine(hass, aioclient_mock) + state = hass.states.get(entity_id(hass, "image", "current_image")) + assert state is not None + assert state.state == "2026-11-19T10:00:00+00:00" + assert "access_token" in state.attributes + + +async def test_fetches_current_jpg_and_caches_it( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """One download serves any number of reads while the image does not change.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.get(f"{BASE}/api/current.jpg", content=JPEG) + entity = entity_id(hass, "image", "current_image") + + first = await async_get_image(hass, entity) + second = await async_get_image(hass, entity) + + assert first.content == second.content == JPEG + assert first.content_type == "image/jpeg" + assert _count(aioclient_mock, "/api/current.jpg") == 1 + assert _count(aioclient_mock, "/api/preview.jpg") == 0 + + +async def test_polling_the_same_image_keeps_the_cache( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Coordinator updates that do not change the image do not invalidate the cache.""" + entry = await setup_engine(hass, aioclient_mock) + aioclient_mock.get(f"{BASE}/api/current.jpg", content=JPEG) + entity = entity_id(hass, "image", "current_image") + await async_get_image(hass, entity) + + await _refresh(hass, aioclient_mock, entry.runtime_data, status_payload()) + await async_get_image(hass, entity) + + assert _count(aioclient_mock, "/api/current.jpg") == 0 + + +@pytest.mark.parametrize( + "change", + [{"sha256": "f" * 64}, {"processed_at": "2026-11-19T11:30:00Z"}], + ids=["new content hash", "new render time"], +) +async def test_new_image_invalidates_the_cache( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + change: dict[str, str], +) -> None: + """A new image (hash or render time) bumps image_last_updated and is downloaded again.""" + entry = await setup_engine(hass, aioclient_mock) + aioclient_mock.get(f"{BASE}/api/current.jpg", content=JPEG) + entity = entity_id(hass, "image", "current_image") + await async_get_image(hass, entity) + token_before = hass.states.get(entity).attributes["access_token"] # type: ignore[union-attr] + + await _refresh(hass, aioclient_mock, entry.runtime_data, _status_with(**change)) + + state = hass.states.get(entity) + assert state is not None + expected = change.get("processed_at", "2026-11-19T10:00:00Z").replace("Z", "+00:00") + assert state.state == expected + assert state.attributes["access_token"] != token_before + await async_get_image(hass, entity) + assert _count(aioclient_mock, "/api/current.jpg") == 1 + + +async def test_falls_back_to_the_preview_on_404( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """current.jpg answers 404 before an image is displayed: use preview.jpg.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.get(f"{BASE}/api/current.jpg", status=404, json={"detail": "none"}) + aioclient_mock.get(f"{BASE}/api/preview.jpg", content=PREVIEW) + entity = entity_id(hass, "image", "current_image") + + image = await async_get_image(hass, entity) + again = await async_get_image(hass, entity) + + assert image.content == again.content == PREVIEW + # The fallback result is cached too, so the 404 is not retried on every read. + assert _count(aioclient_mock, "/api/current.jpg") == 1 + assert _count(aioclient_mock, "/api/preview.jpg") == 1 + + +async def test_no_image_at_all(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """Both endpoints 404: nothing to show, and nothing is cached.""" + status = status_payload() + status["current_image"] = None + await setup_engine(hass, aioclient_mock, status=status) + aioclient_mock.get(f"{BASE}/api/current.jpg", status=404, json={"detail": "none"}) + aioclient_mock.get(f"{BASE}/api/preview.jpg", status=404, json={"detail": "none"}) + entity = entity_id(hass, "image", "current_image") + + assert hass.states.get(entity).state == STATE_UNKNOWN # type: ignore[union-attr] + with pytest.raises(HomeAssistantError): + await async_get_image(hass, entity) + with pytest.raises(HomeAssistantError): + await async_get_image(hass, entity) + assert _count(aioclient_mock, "/api/current.jpg") == 2 + + +@pytest.mark.parametrize("failure", [{"exc": TimeoutError}, {"status": 500, "text": "boom"}]) +async def test_download_errors_are_not_cached( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, failure: dict[str, Any] +) -> None: + """A failing download yields no image and is retried on the next read.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.get(f"{BASE}/api/current.jpg", **failure) + entity = entity_id(hass, "image", "current_image") + with pytest.raises(HomeAssistantError): + await async_get_image(hass, entity) + + aioclient_mock.clear_requests() + aioclient_mock.get(f"{BASE}/api/current.jpg", content=JPEG) + assert (await async_get_image(hass, entity)).content == JPEG + + +async def test_sends_the_api_key(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """With PUBLIC_IMAGE_ENDPOINTS=false the image needs the key.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.get(f"{BASE}/api/current.jpg", content=JPEG) + await async_get_image(hass, entity_id(hass, "image", "current_image")) + call = [c for c in aioclient_mock.mock_calls if c[1].path == "/api/current.jpg"][-1] + assert call[3]["X-API-Key"] == API_KEY + + +async def test_no_image_before_the_first_render_then_first_image( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Going from 'no image yet' to a first image sets image_last_updated.""" + status = status_payload() + status["current_image"] = None + entry = await setup_engine(hass, aioclient_mock, status=status) + entity = entity_id(hass, "image", "current_image") + assert hass.states.get(entity).state == STATE_UNKNOWN # type: ignore[union-attr] + + await _refresh(hass, aioclient_mock, entry.runtime_data, status_payload()) + assert hass.states.get(entity).state == "2026-11-19T10:00:00+00:00" # type: ignore[union-attr] + + +async def test_connection_error_class_is_handled( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Transport errors (not only timeouts) are swallowed into 'no image'.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.get(f"{BASE}/api/current.jpg", exc=aiohttp.ClientConnectionError("x")) + with pytest.raises(HomeAssistantError): + await async_get_image(hass, entity_id(hass, "image", "current_image")) diff --git a/tests/test_init.py b/tests/test_init.py index 5cde5b6..0d26f7a 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from datetime import timedelta import aiohttp @@ -19,6 +20,7 @@ from custom_components.smart_frame_engine.const import ( ALL_CAPABILITIES, + CAPABILITY_FORCE_REFRESH, CAPABILITY_TITLE_CARD, CONF_SCAN_INTERVAL, DOMAIN, @@ -41,6 +43,20 @@ def _issue(hass: HomeAssistant, entry_id: str) -> ir.IssueEntry | None: return ir.async_get(hass).async_get_issue(DOMAIN, f"incompatible_api_{entry_id}") +async def _wait_for_state( + hass: HomeAssistant, entry: MockConfigEntry, state: ConfigEntryState +) -> None: + """Wait (bounded) for a setup that starts from a timer. + + The first load of a platform's dependencies (for instance ``http``) happens off the event + loop, so ``async_block_till_done`` alone can return while the setup is still running. + """ + async with asyncio.timeout(10): + while entry.state is not state: + await hass.async_block_till_done() + await asyncio.sleep(0.01) + + async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) @@ -60,7 +76,7 @@ async def test_setup_and_unload(hass: HomeAssistant, aioclient_mock: AiohttpClie coordinator: SmartFrameCoordinator = entry.runtime_data assert coordinator.capabilities == ALL_CAPABILITIES assert coordinator.data.health.instance_id == INSTANCE_ID - assert coordinator.data.status.version == "1.0.0rc2" + assert coordinator.data.status.version == "1.0.0rc3" assert coordinator.data.ambient is not None assert coordinator.data.ambient.family_active is True assert _issue(hass, entry.entry_id) is None @@ -221,7 +237,7 @@ async def test_incompatible_engine_creates_repair_issue( assert issue.is_fixable is False assert issue.translation_placeholders == { "name": entry.title, - "server_version": "1.0.0rc2", + "server_version": "1.0.0rc3", "api_version": str(api_version), "min_api_version": str(min_api_version), "supported_version": "1", @@ -267,9 +283,8 @@ async def test_issue_cleared_when_setup_retry_succeeds( aioclient_mock.clear_requests() mock_engine(aioclient_mock) async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5)) - await hass.async_block_till_done() + await _wait_for_state(hass, entry, ConfigEntryState.LOADED) - assert entry.state is ConfigEntryState.LOADED assert _issue(hass, entry.entry_id) is None @@ -285,3 +300,41 @@ async def test_removing_entry_deletes_issue( await hass.config_entries.async_remove(entry.entry_id) await hass.async_block_till_done() assert _issue(hass, entry.entry_id) is None + + +# -- Capability changes ---------------------------------------------------------------- + + +async def test_capability_change_reloads_the_entry( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """An engine that gains or loses a capability gets its entities rebuilt.""" + mock_engine(aioclient_mock) + entry = make_entry() + await _setup(hass, entry) + first: SmartFrameCoordinator = entry.runtime_data + assert CAPABILITY_FORCE_REFRESH in first.capabilities + + aioclient_mock.clear_requests() + mock_engine(aioclient_mock, capabilities=ALL_CAPABILITIES - {CAPABILITY_FORCE_REFRESH}) + await first.async_refresh() + await hass.async_block_till_done() + + assert entry.state is ConfigEntryState.LOADED + assert entry.runtime_data is not first + assert CAPABILITY_FORCE_REFRESH not in entry.runtime_data.capabilities + + +async def test_unchanged_capabilities_do_not_reload( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Normal polling never reloads the entry.""" + mock_engine(aioclient_mock) + entry = make_entry() + await _setup(hass, entry) + first: SmartFrameCoordinator = entry.runtime_data + + await first.async_refresh() + await hass.async_block_till_done() + + assert entry.runtime_data is first diff --git a/tests/test_metadata.py b/tests/test_metadata.py index 9d63f4d..b004166 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -8,6 +8,14 @@ from typing import Any import pytest +import yaml + +from custom_components.smart_frame_engine import services +from custom_components.smart_frame_engine.binary_sensor import BINARY_SENSORS +from custom_components.smart_frame_engine.button import BUTTONS +from custom_components.smart_frame_engine.image import CURRENT_IMAGE +from custom_components.smart_frame_engine.sensor import REFRESH_RULE_SOURCES, SENSORS +from custom_components.smart_frame_engine.switch import FAMILY_MODE ROOT = Path(__file__).parent.parent INTEGRATION = ROOT / "custom_components" / "smart_frame_engine" @@ -80,3 +88,81 @@ def test_repair_issues_are_translated(issue: str) -> None: data = _load(INTEGRATION / "translations" / f"{lang}.json") assert data["issues"][issue]["title"] assert data["issues"][issue]["description"] + + +# -- Services, entities and exceptions are fully translated ---------------------------- + + +def _english() -> dict[str, Any]: + return _load(INTEGRATION / "translations" / "en.json") + + +def test_services_yaml_matches_schemas_and_translations() -> None: + """Every service/field in services.yaml has a schema key and an English name+description.""" + definitions = yaml.safe_load((INTEGRATION / "services.yaml").read_text(encoding="utf-8")) + schemas = { + services.SERVICE_SET_AMBIENT_CONTEXT: services.SET_AMBIENT_CONTEXT_SCHEMA, + services.SERVICE_CLEAR_AMBIENT_CONTEXT: services.CLEAR_AMBIENT_CONTEXT_SCHEMA, + services.SERVICE_SEND_TITLE_CARD: services.SEND_TITLE_CARD_SCHEMA, + } + translated = _english()["services"] + + assert set(definitions) == set(schemas) == set(translated) + for name, definition in definitions.items(): + fields = set(definition["fields"]) + assert fields == {str(key) for key in schemas[name].schema}, name + assert fields == set(translated[name]["fields"]), name + assert translated[name]["name"] + assert translated[name]["description"] + for field, text in translated[name]["fields"].items(): + assert text["name"], (name, field) + assert text["description"], (name, field) + + +def test_select_selectors_are_translated() -> None: + """Each translation_key used by a select selector lists exactly its options.""" + definitions = yaml.safe_load((INTEGRATION / "services.yaml").read_text(encoding="utf-8")) + selectors = _english()["selector"] + seen = 0 + for definition in definitions.values(): + for field in definition["fields"].values(): + select = field["selector"].get("select") + if select: + seen += 1 + assert set(select["options"]) == set( + selectors[select["translation_key"]]["options"] + ) + assert seen == 3 + + +def test_every_entity_has_a_translated_name() -> None: + """Entity names come from translations: every translation_key must exist.""" + entities = _english()["entity"] + expected = { + "binary_sensor": BINARY_SENSORS, + "button": BUTTONS, + "image": (CURRENT_IMAGE,), + "sensor": SENSORS, + "switch": (FAMILY_MODE,), + } + assert set(entities) == set(expected) + for platform, descriptions in expected.items(): + keys = {d.translation_key for d in descriptions} + assert keys == {d.key for d in descriptions}, platform + assert keys == set(entities[platform]), platform + assert set(entities["sensor"]["refresh_rule"]["state"]) == set(REFRESH_RULE_SOURCES) + + +def test_every_translation_key_used_in_code_exists() -> None: + """Exceptions and issues raised with a translation_key must be translated.""" + english = _english() + known = set(english["exceptions"]) | set(english["issues"]) + used: set[str] = set() + for path in INTEGRATION.glob("*.py"): + text = path.read_text(encoding="utf-8") + used |= set(re.findall(r'translation_key="(\w+)"', text)) + used |= set(re.findall(r'translation_key=\(\s*"(\w+)"', text)) + # Keys chosen at runtime in coordinator.py (``"a" if x else "b"``) are listed explicitly. + used |= {"incompatible_server", "incompatible_integration"} + entity_keys = {k for platform in english["entity"].values() for k in platform} + assert used - entity_keys <= known, sorted(used - entity_keys - known) diff --git a/tests/test_sensor.py b/tests/test_sensor.py new file mode 100644 index 0000000..b259ed0 --- /dev/null +++ b/tests/test_sensor.py @@ -0,0 +1,204 @@ +"""Tests for the sensor platform.""" + +from __future__ import annotations + +from typing import Any + +from homeassistant.const import STATE_UNKNOWN, EntityCategory +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.const import ( + CAPABILITY_AMBIENT_CONTEXT, + CAPABILITY_TITLE_CARD, +) +from custom_components.smart_frame_engine.sensor import SmartFrameSensor + +from .common import entity_id, has_entity, setup_engine, status_payload + + +def _state(hass: HomeAssistant, key: str) -> Any: + state = hass.states.get(entity_id(hass, "sensor", key)) + assert state is not None + return state + + +async def test_values(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """Each sensor reports the documented field.""" + await setup_engine(hass, aioclient_mock) + + assert _state(hass, "engine_version").state == "1.0.0-rc.3" + assert _state(hass, "active_source").state == "immich" + assert _state(hass, "media_title").state == "Summer 2024" + assert _state(hass, "refresh_rule").state == "smart_mix" + assert _state(hass, "last_delivery").state == "2026-11-19T10:00:05+00:00" + assert _state(hass, "frame_last_seen").state == "2026-11-19T09:59:00+00:00" + assert _state(hass, "frame_battery").state == "80.0" + assert _state(hass, "frame_battery").attributes["device_class"] == "battery" + assert _state(hass, "frame_battery").attributes["unit_of_measurement"] == "%" + + +async def test_engine_version_falls_back_before_rc3( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Engines older than 1.0.0rc3 send no ``release``: show the PEP 440 version instead.""" + status = status_payload() + del status["release"] + entry = await setup_engine(hass, aioclient_mock, status=status) + + assert entry.runtime_data.data.status.release is None + assert _state(hass, "engine_version").state == "1.0.0rc3" + + +async def test_refresh_rule_is_an_enum( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The rule source enum of the contract is exposed with options and the rule kind.""" + await setup_engine(hass, aioclient_mock) + state = _state(hass, "refresh_rule") + assert state.attributes["device_class"] == "enum" + assert state.attributes["options"] == ["pinned", "smart_mix", "last"] + assert state.attributes["kind"] == "immich" + + +async def test_unknown_rule_source_does_not_break_the_state( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Contract: enum values may be added; an unknown one becomes unknown, not an error.""" + status = status_payload() + status["scheduler"]["active_rule"] = {"kind": "immich", "source": "from_the_future"} + await setup_engine(hass, aioclient_mock, status=status) + assert _state(hass, "refresh_rule").state == STATE_UNKNOWN + + +async def test_media_title_attributes( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The title sensor carries the image metadata that /api/status documents.""" + status = status_payload() + status["current_image"].update( + { + "title": "Dune", + "source": "tmdb", + "template": "poster", + "ephemeral": True, + "expires_at": "2026-11-19T12:00:00Z", + "details": {"year": 2021, "people": ["Alice"]}, + } + ) + await setup_engine(hass, aioclient_mock, status=status) + + state = _state(hass, "media_title") + assert state.state == "Dune" + assert state.attributes["source"] == "tmdb" + assert state.attributes["template"] == "poster" + assert state.attributes["ephemeral"] is True + assert state.attributes["pushed"] is True + assert state.attributes["processed_at"].isoformat() == "2026-11-19T10:00:00+00:00" + assert state.attributes["expires_at"].isoformat() == "2026-11-19T12:00:00+00:00" + assert state.attributes["details"] == {"year": 2021, "people": ["Alice"]} + assert _state(hass, "active_source").attributes["template"] == "poster" + + +def test_provider_details_are_not_recorded() -> None: + """People and places in the provider metadata stay out of the recorder database.""" + assert "details" in SmartFrameSensor._unrecorded_attributes + + +async def test_long_titles_fit_the_state_limit( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """HA states are limited to 255 characters.""" + status = status_payload() + status["current_image"]["title"] = "x" * 400 + await setup_engine(hass, aioclient_mock, status=status) + assert _state(hass, "media_title").state == "x" * 255 + + +async def test_before_the_first_image( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """current_image is null before the first image: unknown, no attributes.""" + status = status_payload() + status["current_image"] = None + await setup_engine(hass, aioclient_mock, status=status) + for key in ("media_title", "active_source"): + assert _state(hass, key).state == STATE_UNKNOWN + assert "processed_at" not in _state(hass, "media_title").attributes + + +async def test_ambient_context_summary( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The ambient sensor counts the active fields and lists them with their expiry.""" + await setup_engine(hass, aioclient_mock) + + state = _state(hass, "ambient_context") + assert state.state == "2" + assert state.attributes["family_mode"] is True + assert state.attributes["family_mode_expires_at"].isoformat() == "2026-11-19T12:00:00+00:00" + assert state.attributes["presence"] == ["Alice", "Bob"] + assert state.attributes["presence_expires_at"].isoformat() == "2026-11-19T12:00:00+00:00" + assert state.attributes["family_active"] is True + assert state.attributes["smart_mix_enabled"] is True + assert state.attributes["extra_candidates"] == ["rainy"] + assert "weather" not in state.attributes + + +async def test_ambient_context_empty( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """No active field means a count of zero.""" + await setup_engine( + hass, + aioclient_mock, + context={ + "context": {}, + "extra_candidates": [], + "family_active": False, + "smart_mix_enabled": False, + }, + ) + assert _state(hass, "ambient_context").state == "0" + + +async def test_ambient_sensor_needs_the_capability( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Capability gating: no ambient_context flag, no ambient sensor (and no polling of it).""" + await setup_engine(hass, aioclient_mock, capabilities={CAPABILITY_TITLE_CARD}) + assert not has_entity(hass, "sensor", "ambient_context") + assert has_entity(hass, "sensor", "engine_version") + + await hass.config_entries.async_reload(hass.config_entries.async_entries()[0].entry_id) + await hass.async_block_till_done() + assert CAPABILITY_AMBIENT_CONTEXT not in { + c[1].path.removeprefix("/api/") for c in aioclient_mock.mock_calls + } + + +async def test_diagnostic_entities_and_defaults( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Diagnostic sensors are categorised; the noisy Wi-Fi signal is disabled by default.""" + await setup_engine(hass, aioclient_mock) + registry = er.async_get(hass) + + for key in ("engine_version", "last_delivery", "frame_last_seen", "frame_battery"): + entry = registry.async_get(entity_id(hass, "sensor", key)) + assert entry is not None + assert entry.entity_category is EntityCategory.DIAGNOSTIC + + wifi = registry.async_get(entity_id(hass, "sensor", "frame_wifi_signal")) + assert wifi is not None + assert wifi.disabled_by is er.RegistryEntryDisabler.INTEGRATION + assert hass.states.get(wifi.entity_id) is None + + +async def test_no_delivery_yet(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """A fresh engine has no last delivery.""" + status = status_payload() + status["delivery"] = {"pending": False, "last_delivery": None} + await setup_engine(hass, aioclient_mock, status=status) + assert _state(hass, "last_delivery").state == STATE_UNKNOWN diff --git a/tests/test_services.py b/tests/test_services.py new file mode 100644 index 0000000..298290f --- /dev/null +++ b/tests/test_services.py @@ -0,0 +1,407 @@ +"""Tests for the Home Assistant services.""" + +from __future__ import annotations + +from typing import Any + +from homeassistant.config_entries import SOURCE_REAUTH +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.setup import async_setup_component +import pytest +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker +import voluptuous as vol + +from custom_components.smart_frame_engine.const import ( + CAPABILITY_AMBIENT_CONTEXT, + CAPABILITY_TITLE_CARD, + DOMAIN, +) + +from .common import ( + API_KEY, + BASE, + OTHER_INSTANCE_ID, + context_payload, + display_payload, + make_entry, + setup_engine, +) + +OTHER_BASE = "http://192.168.1.51:8080" + + +def _calls(aioclient_mock: AiohttpClientMocker, method: str) -> list[tuple[Any, ...]]: + return [c for c in aioclient_mock.mock_calls if c[0] == method] + + +async def _call(hass: HomeAssistant, service: str, data: dict[str, Any] | None = None) -> None: + await hass.services.async_call(DOMAIN, service, data or {}, blocking=True) + + +async def test_services_are_registered_without_any_entry(hass: HomeAssistant) -> None: + """Services are registered when the integration loads (from async_setup).""" + assert await async_setup_component(hass, DOMAIN, {}) + for name in ("set_ambient_context", "clear_ambient_context", "send_title_card"): + assert hass.services.has_service(DOMAIN, name) + + +# -- set_ambient_context --------------------------------------------------------------- + + +async def test_set_ambient_context_with_every_field( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """All documented fields and ttl_minutes go to POST /api/context.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.post(f"{BASE}/api/context", json=context_payload()) + before = len([c for c in aioclient_mock.mock_calls if c[1].path == "/api/status"]) + + await _call( + hass, + "set_ambient_context", + { + "family_mode": True, + "presence": ["Alice", "Bob"], + "weather": "rainy", + "season": "winter", + "boost_tags": ["beach"], + "boost_people": ["Alice"], + "ttl_minutes": 90, + }, + ) + + _, url, body, headers = _calls(aioclient_mock, "POST")[-1] + assert url.path == "/api/context" + assert body == { + "family_mode": True, + "presence": ["Alice", "Bob"], + "weather": "rainy", + "season": "winter", + "boost_tags": ["beach"], + "boost_people": ["Alice"], + "ttl_minutes": 90, + } + assert headers["X-API-Key"] == API_KEY + assert len([c for c in aioclient_mock.mock_calls if c[1].path == "/api/status"]) == before + 1 + + +async def test_set_ambient_context_single_field_and_clearing_values( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Only given fields are sent; an empty list or text is passed on (the engine clears it).""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}/api/context", json=context_payload()) + + await _call(hass, "set_ambient_context", {"weather": "sunny"}) + assert _calls(aioclient_mock, "POST")[-1][2] == {"weather": "sunny"} + + await _call(hass, "set_ambient_context", {"presence": [], "weather": ""}) + assert _calls(aioclient_mock, "POST")[-1][2] == {"presence": [], "weather": ""} + + +async def test_set_ambient_context_needs_a_field( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """ttl_minutes alone is not a request.""" + await setup_engine(hass, aioclient_mock) + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "set_ambient_context", {"ttl_minutes": 30}) + assert err.value.translation_domain == DOMAIN + assert err.value.translation_key == "no_context_fields" + assert not _calls(aioclient_mock, "POST") + + +@pytest.mark.parametrize( + "data", + [ + {"ttl_minutes": 0, "weather": "rainy"}, + {"ttl_minutes": 10081, "weather": "rainy"}, + {"season": "monsoon"}, + {"weather": "x" * 81}, + {"presence": [str(i) for i in range(21)]}, + {"boost_tags": [str(i) for i in range(21)]}, + {"is_locked": True, "weather": "rainy"}, + ], + ids=["ttl 0", "ttl too big", "season", "weather length", "presence 21", "tags 21", "is_locked"], +) +async def test_set_ambient_context_schema_limits( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, data: dict[str, Any] +) -> None: + """Limits from openapi.json are enforced before anything is sent; no invented fields.""" + await setup_engine(hass, aioclient_mock) + with pytest.raises(vol.Invalid): + await _call(hass, "set_ambient_context", data) + assert not _calls(aioclient_mock, "POST") + + +async def test_ambient_services_boundaries_are_accepted( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The documented bounds themselves (1 and 10080 minutes, 20 items, 80 chars) are valid.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}/api/context", json=context_payload()) + for ttl in (1, 10080): + await _call(hass, "set_ambient_context", {"weather": "w" * 80, "ttl_minutes": ttl}) + await _call(hass, "set_ambient_context", {"boost_tags": [str(i) for i in range(20)]}) + assert len(_calls(aioclient_mock, "POST")) == 3 + + +# -- clear_ambient_context ------------------------------------------------------------- + + +async def test_clear_ambient_context( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """DELETE /api/context, with or without ?field=.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.delete(f"{BASE}/api/context", json=context_payload()) + + await _call(hass, "clear_ambient_context") + method, url, _, _ = _calls(aioclient_mock, "DELETE")[-1] + assert (method, url.path, dict(url.query)) == ("DELETE", "/api/context", {}) + + await _call(hass, "clear_ambient_context", {"field": "boost_people"}) + assert dict(_calls(aioclient_mock, "DELETE")[-1][1].query) == {"field": "boost_people"} + + +async def test_clear_ambient_context_rejects_unknown_field( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Only the six documented fields may be cleared.""" + await setup_engine(hass, aioclient_mock) + with pytest.raises(vol.Invalid): + await _call(hass, "clear_ambient_context", {"field": "is_locked"}) + + +# -- send_title_card ------------------------------------------------------------------- + + +async def test_send_title_card_minimal( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Only the title is required; the engine's defaults apply for the rest.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}/api/display/title-card", json=display_payload()) + await _call(hass, "send_title_card", {"title": "Hello"}) + assert _calls(aioclient_mock, "POST")[-1][2] == {"title": "Hello"} + + +async def test_send_title_card_with_every_parameter( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """All documented parameters are forwarded.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.post(f"{BASE}/api/display/title-card", json=display_payload()) + await _call( + hass, + "send_title_card", + { + "title": "Dinner", + "subtitle": "is ready", + "caption": "7 pm", + "accent": "green", + "ephemeral": False, + "ttl_minutes": 15, + "hold_minutes": 30, + "push_to_fraimic": False, + }, + ) + _, url, body, headers = _calls(aioclient_mock, "POST")[-1] + assert url.path == "/api/display/title-card" + assert body == { + "title": "Dinner", + "subtitle": "is ready", + "caption": "7 pm", + "accent": "green", + "ephemeral": False, + "ttl_minutes": 15, + "hold_minutes": 30, + "push_to_fraimic": False, + } + assert headers["X-API-Key"] == API_KEY + + +@pytest.mark.parametrize( + "data", + [ + {}, + {"title": ""}, + {"title": "x" * 201}, + {"title": "ok", "subtitle": "x" * 201}, + {"title": "ok", "caption": "x" * 201}, + {"title": "ok", "accent": "purple"}, + {"title": "ok", "ttl_minutes": 0}, + {"title": "ok", "hold_minutes": 10081}, + ], + ids=["no title", "empty", "title 201", "subtitle 201", "caption 201", "accent", "ttl", "hold"], +) +async def test_send_title_card_schema_limits( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, data: dict[str, Any] +) -> None: + """Limits of TitleCardRequest are enforced before any request.""" + await setup_engine(hass, aioclient_mock) + with pytest.raises(vol.Invalid): + await _call(hass, "send_title_card", data) + assert not _calls(aioclient_mock, "POST") + + +async def test_send_title_card_accepts_the_bounds( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """200-character texts and the 1..10080 minute range are valid.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}/api/display/title-card", json=display_payload()) + await _call( + hass, + "send_title_card", + {"title": "t" * 200, "subtitle": "s" * 200, "ttl_minutes": 10080, "hold_minutes": 1}, + ) + assert len(_calls(aioclient_mock, "POST")) == 1 + + +# -- Capability gating ----------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("service", "data", "missing", "available"), + [ + ( + "set_ambient_context", + {"weather": "rainy"}, + CAPABILITY_AMBIENT_CONTEXT, + {CAPABILITY_TITLE_CARD}, + ), + ("clear_ambient_context", {}, CAPABILITY_AMBIENT_CONTEXT, {CAPABILITY_TITLE_CARD}), + ("send_title_card", {"title": "Hi"}, CAPABILITY_TITLE_CARD, {CAPABILITY_AMBIENT_CONTEXT}), + ], +) +async def test_unsupported_capability_raises_before_any_request( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + service: str, + data: dict[str, Any], + missing: str, + available: set[str], +) -> None: + """An engine without the capability gets a translated ServiceValidationError.""" + entry = await setup_engine(hass, aioclient_mock, capabilities=available) + with pytest.raises(ServiceValidationError) as err: + await _call(hass, service, data) + + assert err.value.translation_domain == DOMAIN + assert err.value.translation_key == "capability_not_supported" + assert err.value.translation_placeholders == {"capability": missing, "name": entry.title} + assert not [c for c in aioclient_mock.mock_calls if c[0] in ("POST", "DELETE")] + + +# -- Targeting ------------------------------------------------------------------------- + + +async def test_unknown_config_entry( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A config_entry_id that does not exist is reported.""" + await setup_engine(hass, aioclient_mock) + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "send_title_card", {"title": "Hi", "config_entry_id": "nope"}) + assert err.value.translation_key == "entry_not_found" + assert err.value.translation_placeholders == {"entry_id": "nope"} + + +async def test_no_engine_loaded(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """With the engine unreachable (entry not loaded) the service says so.""" + aioclient_mock.get(f"{BASE}/api/health", exc=TimeoutError) + entry = make_entry() + entry.add_to_hass(hass) + assert await async_setup_component(hass, DOMAIN, {}) + await hass.async_block_till_done() + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "send_title_card", {"title": "Hi"}) + assert err.value.translation_key == "no_engine_loaded" + + +async def test_several_engines_need_an_explicit_target( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """With two engines the call must say which; with config_entry_id only that one is used.""" + first = await setup_engine(hass, aioclient_mock) + second = await setup_engine( + hass, + aioclient_mock, + base=OTHER_BASE, + instance_id=OTHER_INSTANCE_ID, + entry=make_entry(unique_id=OTHER_INSTANCE_ID, host="192.168.1.51"), + ) + aioclient_mock.post(f"{BASE}/api/display/title-card", json=display_payload()) + aioclient_mock.post(f"{OTHER_BASE}/api/display/title-card", json=display_payload()) + + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "send_title_card", {"title": "Hi"}) + assert err.value.translation_key == "config_entry_required" + assert not _calls(aioclient_mock, "POST") + + await _call(hass, "send_title_card", {"title": "Hi", "config_entry_id": second.entry_id}) + posts = _calls(aioclient_mock, "POST") + assert [str(c[1].host) for c in posts] == ["192.168.1.51"] + assert first.entry_id != second.entry_id + + +async def test_every_target_is_checked_before_any_is_called( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The capability check is part of resolving the target: nothing is sent on failure.""" + await setup_engine(hass, aioclient_mock, capabilities={CAPABILITY_AMBIENT_CONTEXT}) + aioclient_mock.post(f"{BASE}/api/display/title-card", json=display_payload()) + with pytest.raises(ServiceValidationError): + await _call(hass, "send_title_card", {"title": "Hi"}) + assert not _calls(aioclient_mock, "POST") + + +# -- Engine errors --------------------------------------------------------------------- + + +async def test_engine_422_is_a_validation_error( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A request the engine rejects is reported as invalid input, with its message.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post( + f"{BASE}/api/display/title-card", status=422, json={"detail": "title: too short"} + ) + with pytest.raises(ServiceValidationError, match="title: too short") as err: + await _call(hass, "send_title_card", {"title": "Hi"}) + assert err.value.translation_key == "request_rejected" + + +@pytest.mark.parametrize("status", [409, 500, 502]) +async def test_engine_failures_are_home_assistant_errors( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, status: int +) -> None: + """Other engine errors surface as HomeAssistantError (not as bad input).""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.delete(f"{BASE}/api/context", status=status, json={"detail": "engine broke"}) + with pytest.raises(HomeAssistantError, match="engine broke") as err: + await _call(hass, "clear_ambient_context") + assert not isinstance(err.value, ServiceValidationError) + + +async def test_unreachable_engine(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """Network failures are reported.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}/api/display/title-card", exc=TimeoutError) + with pytest.raises(HomeAssistantError): + await _call(hass, "send_title_card", {"title": "Hi"}) + + +async def test_rejected_key_starts_reauth( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A 401 from a service starts reauthentication.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.post(f"{BASE}/api/context", status=401, json={"detail": "no"}) + with pytest.raises(HomeAssistantError): + await _call(hass, "set_ambient_context", {"weather": "rainy"}) + await hass.async_block_till_done() + flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) + assert [flow["context"]["source"] for flow in flows] == [SOURCE_REAUTH] diff --git a/tests/test_switch.py b/tests/test_switch.py new file mode 100644 index 0000000..a13181f --- /dev/null +++ b/tests/test_switch.py @@ -0,0 +1,172 @@ +"""Tests for the Family Mode switch.""" + +from __future__ import annotations + +from homeassistant.config_entries import SOURCE_REAUTH +from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +import pytest +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.const import ( + CAPABILITY_FAMILY_MODE, + CAPABILITY_TITLE_CARD, + DOMAIN, +) + +from .common import ( + API_KEY, + BASE, + config_payload, + context_payload, + entity_id, + has_entity, + mock_engine, + setup_engine, +) + + +async def _call(hass: HomeAssistant, service: str) -> None: + await hass.services.async_call( + "switch", service, {"entity_id": entity_id(hass, "switch", "family_mode")}, blocking=True + ) + + +def _puts(aioclient_mock: AiohttpClientMocker) -> list[tuple]: # type: ignore[type-arg] + return [call for call in aioclient_mock.mock_calls if call[0] == "PUT"] + + +async def test_state_follows_config_family_enabled( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The switch reads config.family.enabled, not the temporary ambient override.""" + await setup_engine(hass, aioclient_mock, config=config_payload(family_enabled=True)) + state = hass.states.get(entity_id(hass, "switch", "family_mode")) + assert state is not None + assert state.state == STATE_ON + # AmbientView.family_active ("applies right now") is exposed separately. + assert state.attributes["active_now"] is True + + +async def test_off_state_and_override_attribute( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The stored setting can be off while a temporary override applies.""" + await setup_engine(hass, aioclient_mock, config=config_payload(family_enabled=False)) + state = hass.states.get(entity_id(hass, "switch", "family_mode")) + assert state is not None + assert state.state == STATE_OFF + assert state.attributes["active_now"] is True # context_payload() says it applies now + + +async def test_turn_on_and_off(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """Toggling sends PUT /api/config {"family": {"enabled": ...}} then refreshes.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + switch = entity_id(hass, "switch", "family_mode") + assert hass.states.get(switch).state == STATE_OFF # type: ignore[union-attr] + + # The engine now reports Family Mode on (the first matching mock wins, so start afresh). + aioclient_mock.clear_requests() + mock_engine(aioclient_mock, auth="key", config=config_payload(family_enabled=True)) + aioclient_mock.put(f"{BASE}/api/config", json=config_payload(family_enabled=True)) + await _call(hass, "turn_on") + + method, url, body, headers = _puts(aioclient_mock)[-1] + assert (method, url.path, body) == ("PUT", "/api/config", {"family": {"enabled": True}}) + assert headers["X-API-Key"] == API_KEY + assert hass.states.get(switch).state == STATE_ON # type: ignore[union-attr] + + aioclient_mock.clear_requests() + mock_engine(aioclient_mock, auth="key") + aioclient_mock.put(f"{BASE}/api/config", json=config_payload(family_enabled=False)) + await _call(hass, "turn_off") + assert _puts(aioclient_mock)[-1][2] == {"family": {"enabled": False}} + assert hass.states.get(switch).state == STATE_OFF # type: ignore[union-attr] + + +async def test_state_is_updated_before_the_next_poll( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The PUT reply is applied at once; the follow-up refresh then confirms it.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.clear_requests() + mock_engine(aioclient_mock, config=config_payload(family_enabled=True)) + aioclient_mock.put(f"{BASE}/api/config", json=config_payload(family_enabled=True)) + status_calls = sum(c[1].path == "/api/status" for c in aioclient_mock.mock_calls) + + await _call(hass, "turn_on") + + assert sum(c[1].path == "/api/status" for c in aioclient_mock.mock_calls) == status_calls + 1 + + +async def test_needs_the_family_mode_capability( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Engines without family_mode get no switch, and /api/config is not polled.""" + await setup_engine(hass, aioclient_mock, capabilities={CAPABILITY_TITLE_CARD}) + assert not has_entity(hass, "switch", "family_mode") + assert all(c[1].path != "/api/config" for c in aioclient_mock.mock_calls) + + +async def test_config_is_polled_with_the_capability( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """With family_mode the coordinator fetches /api/config.""" + entry = await setup_engine( + hass, aioclient_mock, capabilities={CAPABILITY_FAMILY_MODE}, context=context_payload() + ) + assert any(c[1].path == "/api/config" for c in aioclient_mock.mock_calls) + assert entry.runtime_data.data.config.family_enabled is False + # Without ambient_context the attribute is simply absent. + state = hass.states.get(entity_id(hass, "switch", "family_mode")) + assert state is not None + assert "active_now" not in state.attributes + + +@pytest.mark.parametrize("status", [409, 422, 500]) +async def test_engine_errors_surface( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, status: int +) -> None: + """Engine errors become Home Assistant errors that carry the engine's message.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.put(f"{BASE}/api/config", status=status, json={"detail": "bad family"}) + with pytest.raises(HomeAssistantError, match="bad family"): + await _call(hass, "turn_on") + + +async def test_unreachable_engine_raises( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A network error while toggling is reported to the user.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.put(f"{BASE}/api/config", exc=TimeoutError) + with pytest.raises(HomeAssistantError): + await _call(hass, "turn_on") + + +async def test_rejected_key_starts_reauth( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A 401 while acting asks the user to re-enter the key.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.put(f"{BASE}/api/config", status=401, json={"detail": "no"}) + with pytest.raises(HomeAssistantError): + await _call(hass, "turn_on") + await hass.async_block_till_done() + flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) + assert [flow["context"]["source"] for flow in flows] == [SOURCE_REAUTH] + + +async def test_unavailable_when_the_engine_is_down( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The switch becomes unavailable while polling fails.""" + entry = await setup_engine(hass, aioclient_mock) + aioclient_mock.clear_requests() + aioclient_mock.get(f"{BASE}/api/health", exc=TimeoutError) + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + state = hass.states.get(entity_id(hass, "switch", "family_mode")) + assert state is not None + assert state.state == STATE_UNAVAILABLE