From 6365742afe7608929e588249835a38e185a0cbbe Mon Sep 17 00:00:00 2001 From: ant1fr Date: Fri, 20 Nov 2026 09:48:30 +0100 Subject: [PATCH 1/2] feat: add album cover and movie/series poster services show_now_playing (now_playing) and show_media_poster (display_tmdb) call POST /api/display/now-playing and /api/display/tmdb. A media_player entity can fill the fields; values given in the call win. The player's picture is sent as the cover (music: tried first, then the engine's lookup) or as the TMDB fallback, made absolute with the internal URL when relative. Co-Authored-By: Claude Sonnet 5.5 --- custom_components/smart_frame_engine/api.py | 79 ++ .../smart_frame_engine/services.py | 247 +++++- .../smart_frame_engine/services.yaml | 179 +++++ .../smart_frame_engine/strings.json | 150 ++++ .../smart_frame_engine/translations/en.json | 150 ++++ .../smart_frame_engine/translations/fr.json | 150 ++++ tests/test_api.py | 115 +++ tests/test_media_services.py | 760 ++++++++++++++++++ tests/test_metadata.py | 4 +- 9 files changed, 1830 insertions(+), 4 deletions(-) create mode 100644 tests/test_media_services.py diff --git a/custom_components/smart_frame_engine/api.py b/custom_components/smart_frame_engine/api.py index 4cd48c0..1b59d0b 100644 --- a/custom_components/smart_frame_engine/api.py +++ b/custom_components/smart_frame_engine/api.py @@ -669,6 +669,8 @@ def from_dict(cls, data: Any) -> WakeupResult: AmbientField = Literal["presence", "family_mode", "weather", "season", "boost_tags", "boost_people"] Season = Literal["spring", "summer", "autumn", "winter"] Accent = Literal["red", "yellow", "blue", "green", "white"] +MusicStyle = Literal["sleeve", "vinyl"] +TmdbMediaType = Literal["movie", "tv", "multi"] class _Unset(enum.Enum): @@ -947,6 +949,83 @@ async def async_title_card( _, data = await self._json("POST", "/api/display/title-card", json_body=body) return DisplayResult.from_dict(data) + async def async_now_playing( + self, + artist: str, + *, + album: str | None = None, + title: str | None = None, + artwork_url: str | None = None, + duration_seconds: float | None = None, + position_seconds: float | None = None, + enrich_artwork: bool | None = None, + ephemeral: bool | None = None, + hold_minutes: int | None = None, + push_to_fraimic: bool | None = None, + show_title: bool | None = None, + style: MusicStyle | None = None, + ttl_seconds: int | None = None, + ) -> DisplayResult: + """``POST /api/display/now-playing``: show the cover of the track that is playing. + + The cover given in ``artwork_url`` is tried first; without a usable one the engine + looks a cover up itself (``enrich_artwork``, on by default). Omitted options keep + the engine's defaults. Sending the album that is already shown only moves its expiry. + """ + body: dict[str, Any] = {"artist": artist} + optional: dict[str, Any] = { + "album": album, + "title": title, + "artwork_url": artwork_url, + "duration_seconds": duration_seconds, + "position_seconds": position_seconds, + "enrich_artwork": enrich_artwork, + "ephemeral": ephemeral, + "hold_minutes": hold_minutes, + "push_to_fraimic": push_to_fraimic, + "show_title": show_title, + "style": style, + "ttl_seconds": ttl_seconds, + } + body.update({key: value for key, value in optional.items() if value is not None}) + _, data = await self._json("POST", "/api/display/now-playing", json_body=body) + return DisplayResult.from_dict(data) + + async def async_display_tmdb( + self, + query: str, + *, + media_type: TmdbMediaType | None = None, + season: int | None = None, + year: int | None = None, + language: str | None = None, + fallback_url: str | None = None, + ephemeral: bool | None = None, + ttl_minutes: int | None = None, + hold_minutes: int | None = None, + push_to_fraimic: bool | None = None, + ) -> DisplayResult: + """``POST /api/display/tmdb``: show the poster of a movie or series. + + ``fallback_url`` is only used when TMDB has no match or fails. Omitted options keep + the engine's defaults. + """ + body: dict[str, Any] = {"query": query} + optional: dict[str, Any] = { + "media_type": media_type, + "season": season, + "year": year, + "language": language, + "fallback_url": fallback_url, + "ephemeral": ephemeral, + "ttl_minutes": ttl_minutes, + "hold_minutes": hold_minutes, + "push_to_fraimic": push_to_fraimic, + } + body.update({key: value for key, value in optional.items() if value is not None}) + _, data = await self._json("POST", "/api/display/tmdb", json_body=body) + return DisplayResult.from_dict(data) + async def async_wakeup(self, *, wait: bool = False) -> WakeupResult: """``POST /api/fraimic/wakeup``: tell a deep-sleep engine the frame woke up.""" _, data = await self._json( diff --git a/custom_components/smart_frame_engine/services.py b/custom_components/smart_frame_engine/services.py index b6f5d31..6df1390 100644 --- a/custom_components/smart_frame_engine/services.py +++ b/custom_components/smart_frame_engine/services.py @@ -1,4 +1,4 @@ -"""Home Assistant services: ambient context and title cards. +"""Home Assistant services: ambient context, title cards, album covers and posters. Each service checks the engine's capability flag first and raises a translated ``ServiceValidationError`` when the connected engine does not support it (contract: @@ -7,24 +7,40 @@ from __future__ import annotations +from datetime import datetime +import logging from typing import Any, Final from homeassistant.config_entries import ConfigEntryState -from homeassistant.core import HomeAssistant, ServiceCall, callback +from homeassistant.core import HomeAssistant, ServiceCall, State, callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.network import NoURLAvailableError, get_url +from homeassistant.util import dt as dt_util import voluptuous as vol from .api import AmbientField -from .const import CAPABILITY_AMBIENT_CONTEXT, CAPABILITY_TITLE_CARD, DOMAIN +from .const import ( + CAPABILITY_AMBIENT_CONTEXT, + CAPABILITY_DISPLAY_TMDB, + CAPABILITY_NOW_PLAYING, + CAPABILITY_TITLE_CARD, + DOMAIN, +) from .coordinator import SmartFrameConfigEntry +_LOGGER = logging.getLogger(__name__) + SERVICE_SET_AMBIENT_CONTEXT: Final = "set_ambient_context" SERVICE_CLEAR_AMBIENT_CONTEXT: Final = "clear_ambient_context" SERVICE_SEND_TITLE_CARD: Final = "send_title_card" +SERVICE_SHOW_NOW_PLAYING: Final = "show_now_playing" +SERVICE_SHOW_MEDIA_POSTER: Final = "show_media_poster" ATTR_CONFIG_ENTRY_ID: Final = "config_entry_id" ATTR_FIELD: Final = "field" +ATTR_MEDIA_PLAYER: Final = "media_player" +ATTR_USE_PICTURE: Final = "use_media_player_picture" AMBIENT_FIELDS: Final = ( "family_mode", @@ -36,6 +52,8 @@ ) SEASONS: Final = ["spring", "summer", "autumn", "winter"] ACCENTS: Final = ["red", "yellow", "blue", "green", "white"] +MUSIC_STYLES: Final = ["sleeve", "vinyl"] +TMDB_MEDIA_TYPES: Final = ["movie", "tv", "multi"] # Limits from openapi.json (AmbientRequest, TitleCardRequest). MAX_LIST_ITEMS: Final = 20 @@ -43,9 +61,21 @@ MAX_CARD_TEXT: Final = 200 MIN_MINUTES: Final = 1 MAX_MINUTES: Final = 10080 +# Limits from openapi.json (NowPlayingRequest, TmdbDisplayRequest). +MAX_MUSIC_TEXT: Final = 300 +MAX_URL: Final = 4096 +MAX_TRACK_SECONDS: Final = 86400 +MIN_TTL_SECONDS: Final = 10 +MAX_TMDB_QUERY: Final = 200 +MAX_TMDB_TTL_MINUTES: Final = 1440 +MAX_SEASON: Final = 100 +MIN_YEAR: Final = 1870 +MAX_YEAR: Final = 2200 _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)) +_track_seconds = vol.All(vol.Coerce(float), vol.Range(min=0, max=MAX_TRACK_SECONDS)) +_url = vol.All(cv.string, vol.Length(max=MAX_URL)) def _schema(fields: dict[Any, Any]) -> Any: @@ -77,6 +107,45 @@ def _schema(fields: dict[Any, Any]) -> Any: vol.Optional("push_to_fraimic"): cv.boolean, } ) +SHOW_NOW_PLAYING_SCHEMA = _schema( + { + vol.Optional(ATTR_MEDIA_PLAYER): cv.entity_domain("media_player"), + vol.Optional(ATTR_USE_PICTURE): cv.boolean, + vol.Optional("artist"): vol.All(cv.string, vol.Length(min=1, max=MAX_MUSIC_TEXT)), + vol.Optional("album"): vol.All(cv.string, vol.Length(max=MAX_MUSIC_TEXT)), + vol.Optional("title"): vol.All(cv.string, vol.Length(max=MAX_MUSIC_TEXT)), + vol.Optional("artwork_url"): _url, + vol.Optional("duration_seconds"): _track_seconds, + vol.Optional("position_seconds"): _track_seconds, + vol.Optional("enrich_artwork"): cv.boolean, + vol.Optional("ephemeral"): cv.boolean, + vol.Optional("hold_minutes"): _minutes, + vol.Optional("push_to_fraimic"): cv.boolean, + vol.Optional("show_title"): cv.boolean, + vol.Optional("style"): vol.In(MUSIC_STYLES), + vol.Optional("ttl_seconds"): vol.All( + vol.Coerce(int), vol.Range(min=MIN_TTL_SECONDS, max=MAX_TRACK_SECONDS) + ), + } +) +SHOW_MEDIA_POSTER_SCHEMA = _schema( + { + vol.Optional(ATTR_MEDIA_PLAYER): cv.entity_domain("media_player"), + vol.Optional(ATTR_USE_PICTURE): cv.boolean, + vol.Optional("query"): vol.All(cv.string, vol.Length(min=1, max=MAX_TMDB_QUERY)), + vol.Optional("media_type"): vol.In(TMDB_MEDIA_TYPES), + vol.Optional("season"): vol.All(vol.Coerce(int), vol.Range(min=0, max=MAX_SEASON)), + vol.Optional("year"): vol.All(vol.Coerce(int), vol.Range(min=MIN_YEAR, max=MAX_YEAR)), + vol.Optional("language"): cv.string, + vol.Optional("fallback_url"): _url, + vol.Optional("ephemeral"): cv.boolean, + vol.Optional("ttl_minutes"): vol.All( + vol.Coerce(int), vol.Range(min=MIN_MINUTES, max=MAX_TMDB_TTL_MINUTES) + ), + vol.Optional("hold_minutes"): _minutes, + vol.Optional("push_to_fraimic"): cv.boolean, + } +) @callback @@ -161,6 +230,166 @@ async def _async_send_title_card(call: ServiceCall) -> None: await coordinator.async_request_refresh() +# -- media_player helpers --------------------------------------------------------------- + + +def _text(value: Any, limit: int) -> str | None: + """A trimmed, length-capped string attribute, or ``None`` when empty or not text.""" + if not isinstance(value, str): + return None + value = value.strip() + return value[:limit] or None + + +def _number(value: Any, maximum: float) -> float | None: + """A non-negative number within ``maximum`` (booleans are not numbers), else ``None``.""" + if isinstance(value, bool) or not isinstance(value, int | float): + return None + return float(value) if 0 <= value <= maximum else None + + +def _player(hass: HomeAssistant, entity_id: str) -> State: + """The state of the ``media_player`` entity a call refers to.""" + if (state := hass.states.get(entity_id)) is None: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="media_player_not_found", + translation_placeholders={"entity_id": entity_id}, + ) + return state + + +def _picture_url(hass: HomeAssistant, state: State) -> str | None: + """The player's picture as an absolute URL the engine can fetch, when there is one. + + ``entity_picture`` is usually a path relative to Home Assistant + (``/api/media_player_proxy/...``). It is made absolute with the internal URL; when none + is configured the picture is left out (and the engine looks the artwork up itself). + """ + picture = _text(state.attributes.get("entity_picture"), MAX_URL + 1) + if picture is None: + return None + if picture.startswith(("http://", "https://")): + url = picture + elif picture.startswith("/"): + try: + url = f"{get_url(hass, allow_external=False, allow_cloud=False)}{picture}" + except NoURLAvailableError: + _LOGGER.debug("No internal URL to make the picture of %s absolute", state.entity_id) + return None + else: + return None + return url if len(url) <= MAX_URL else None + + +def _live_position(state: State) -> float | None: + """Playback position now: the reported one plus the time elapsed while playing.""" + position = _number(state.attributes.get("media_position"), MAX_TRACK_SECONDS) + if position is None: + return None + updated_at = state.attributes.get("media_position_updated_at") + if state.state == "playing" and isinstance(updated_at, datetime): + position += max((dt_util.utcnow() - updated_at).total_seconds(), 0.0) + duration = _number(state.attributes.get("media_duration"), MAX_TRACK_SECONDS) + return round(min(position, duration if duration is not None else MAX_TRACK_SECONDS), 1) + + +def _passthrough(call: ServiceCall, names: tuple[str, ...]) -> dict[str, Any]: + """The optional fields of a call that go to the engine unchanged.""" + return {name: call.data[name] for name in names if name in call.data} + + +def _async_player_of(call: ServiceCall) -> State | None: + """The ``media_player`` the call names, if any.""" + if ATTR_MEDIA_PLAYER not in call.data: + return None + return _player(call.hass, call.data[ATTR_MEDIA_PLAYER]) + + +async def _async_show_now_playing(call: ServiceCall) -> None: + """``POST /api/display/now-playing``.""" + entries = _async_resolve_entries(call.hass, call, CAPABILITY_NOW_PLAYING) + state = _async_player_of(call) + + # Values given in the call win; the media_player only fills what is missing. + values: dict[str, Any] = {} + if state is not None: + attrs = state.attributes + values = { + "artist": _text(attrs.get("media_artist"), MAX_MUSIC_TEXT), + "album": _text(attrs.get("media_album_name"), MAX_MUSIC_TEXT), + "title": _text(attrs.get("media_title"), MAX_MUSIC_TEXT), + "duration_seconds": _number(attrs.get("media_duration"), MAX_TRACK_SECONDS), + "position_seconds": _live_position(state), + } + if call.data.get(ATTR_USE_PICTURE, True): + values["artwork_url"] = _picture_url(call.hass, state) + values.update( + _passthrough( + call, + ("artist", "album", "title", "artwork_url", "duration_seconds", "position_seconds"), + ) + ) + + if not values.get("artist"): + raise ServiceValidationError(translation_domain=DOMAIN, translation_key="missing_artist") + artist = values.pop("artist") + options = values | _passthrough( + call, + ( + "enrich_artwork", + "ephemeral", + "hold_minutes", + "push_to_fraimic", + "show_title", + "style", + "ttl_seconds", + ), + ) + for entry in entries: + coordinator = entry.runtime_data + await coordinator.async_action(coordinator.client.async_now_playing(artist, **options)) + await coordinator.async_request_refresh() + + +# ``media_content_type`` values of Home Assistant's ``MediaType`` that name a TMDB media type. +_TMDB_TYPE_BY_CONTENT_TYPE: Final = {"movie": "movie", "tvshow": "tv", "episode": "tv"} + + +async def _async_show_media_poster(call: ServiceCall) -> None: + """``POST /api/display/tmdb``.""" + entries = _async_resolve_entries(call.hass, call, CAPABILITY_DISPLAY_TMDB) + state = _async_player_of(call) + + values: dict[str, Any] = {} + if state is not None: + attrs = state.attributes + media_type = _TMDB_TYPE_BY_CONTENT_TYPE.get(str(attrs.get("media_content_type"))) + values = { + "query": _text(attrs.get("media_series_title"), MAX_TMDB_QUERY) + or _text(attrs.get("media_title"), MAX_TMDB_QUERY), + "media_type": media_type, + } + season = _number(attrs.get("media_season"), MAX_SEASON) + if media_type == "tv" and season is not None: + values["season"] = int(season) + if call.data.get(ATTR_USE_PICTURE, True): + values["fallback_url"] = _picture_url(call.hass, state) + values.update(_passthrough(call, ("query", "media_type", "season", "fallback_url"))) + + if not values.get("query"): + raise ServiceValidationError(translation_domain=DOMAIN, translation_key="missing_query") + query = values.pop("query") + options = values | _passthrough( + call, + ("year", "language", "ephemeral", "ttl_minutes", "hold_minutes", "push_to_fraimic"), + ) + for entry in entries: + coordinator = entry.runtime_data + await coordinator.async_action(coordinator.client.async_display_tmdb(query, **options)) + await coordinator.async_request_refresh() + + @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the integration's services (once, from ``async_setup``).""" @@ -182,3 +411,15 @@ def async_setup_services(hass: HomeAssistant) -> None: _async_send_title_card, schema=SEND_TITLE_CARD_SCHEMA, ) + hass.services.async_register( + DOMAIN, + SERVICE_SHOW_NOW_PLAYING, + _async_show_now_playing, + schema=SHOW_NOW_PLAYING_SCHEMA, + ) + hass.services.async_register( + DOMAIN, + SERVICE_SHOW_MEDIA_POSTER, + _async_show_media_poster, + schema=SHOW_MEDIA_POSTER_SCHEMA, + ) diff --git a/custom_components/smart_frame_engine/services.yaml b/custom_components/smart_frame_engine/services.yaml index 3cb6268..11b2909 100644 --- a/custom_components/smart_frame_engine/services.yaml +++ b/custom_components/smart_frame_engine/services.yaml @@ -129,3 +129,182 @@ send_title_card: default: true selector: boolean: + +show_now_playing: + fields: + config_entry_id: + required: false + selector: + config_entry: + integration: smart_frame_engine + media_player: + required: false + selector: + entity: + filter: + domain: media_player + use_media_player_picture: + required: false + default: true + selector: + boolean: + artist: + required: false + example: Daft Punk + selector: + text: + album: + required: false + example: Discovery + selector: + text: + title: + required: false + example: One More Time + selector: + text: + artwork_url: + required: false + selector: + text: + duration_seconds: + required: false + selector: + number: + min: 0 + max: 86400 + mode: box + unit_of_measurement: s + position_seconds: + required: false + selector: + number: + min: 0 + max: 86400 + mode: box + unit_of_measurement: s + enrich_artwork: + required: false + default: true + selector: + boolean: + ephemeral: + required: false + default: true + selector: + boolean: + 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: + show_title: + required: false + selector: + boolean: + style: + required: false + selector: + select: + options: + - sleeve + - vinyl + translation_key: music_style + ttl_seconds: + required: false + selector: + number: + min: 10 + max: 86400 + mode: box + unit_of_measurement: s + +show_media_poster: + fields: + config_entry_id: + required: false + selector: + config_entry: + integration: smart_frame_engine + media_player: + required: false + selector: + entity: + filter: + domain: media_player + use_media_player_picture: + required: false + default: true + selector: + boolean: + query: + required: false + example: Blade Runner + selector: + text: + media_type: + required: false + selector: + select: + options: + - movie + - tv + - multi + translation_key: media_type + season: + required: false + selector: + number: + min: 0 + max: 100 + mode: box + year: + required: false + selector: + number: + min: 1870 + max: 2200 + mode: box + language: + required: false + example: fr-CA + selector: + text: + fallback_url: + required: false + selector: + text: + ephemeral: + required: false + default: true + selector: + boolean: + ttl_minutes: + required: false + selector: + number: + min: 1 + max: 1440 + 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 35ef4d9..249f2ab 100644 --- a/custom_components/smart_frame_engine/strings.json +++ b/custom_components/smart_frame_engine/strings.json @@ -242,9 +242,150 @@ "description": "Turn off to only render a preview without sending it to the frame." } } + }, + "show_now_playing": { + "name": "Show album cover", + "description": "Shows the cover of the track that is playing, with the artist and album. Pick a media player to fill the fields from it; values you set yourself win. The cover sent by Home Assistant is tried first; without a usable one the engine looks a cover up itself.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "media_player": { + "name": "Media player", + "description": "Fills the artist, album, title, position and cover from this player." + }, + "use_media_player_picture": { + "name": "Send the player's cover", + "description": "Send the cover of the media player to the engine (on by default). Turn off to let the engine look the cover up itself." + }, + "artist": { + "name": "Artist", + "description": "Artist of the track (1 to 300 characters)." + }, + "album": { + "name": "Album", + "description": "Album of the track (up to 300 characters)." + }, + "title": { + "name": "Track title", + "description": "Title of the track (up to 300 characters)." + }, + "artwork_url": { + "name": "Cover URL", + "description": "Address of the cover. It must be reachable by the engine." + }, + "duration_seconds": { + "name": "Track length", + "description": "Length of the track, in seconds." + }, + "position_seconds": { + "name": "Position", + "description": "Playback position, in seconds." + }, + "enrich_artwork": { + "name": "Look up a cover", + "description": "When no usable cover is given, let the engine look one up (on by default)." + }, + "ephemeral": { + "name": "Temporary", + "description": "When on, the previous image comes back afterwards." + }, + "hold_minutes": { + "name": "Protect from refresh", + "description": "Minutes during which scheduled refreshes will not replace the cover (1 to 10080)." + }, + "push_to_fraimic": { + "name": "Send to frame", + "description": "Turn off to only render a preview without sending it to the frame." + }, + "show_title": { + "name": "Print the track title", + "description": "Print the track title on the cover. Without it, the frame is only refreshed when the album changes." + }, + "style": { + "name": "Style", + "description": "Show the cover as a sleeve or as a vinyl record." + }, + "ttl_seconds": { + "name": "Duration", + "description": "Seconds before the previous image returns (10 to 86400). Overrides the duration worked out from the track length." + } + } + }, + "show_media_poster": { + "name": "Show movie or series poster", + "description": "Finds a movie or series on TMDB and shows its poster. Pick a media player to fill the fields from it; values you set yourself win. The player's picture is only used when TMDB has no match.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "media_player": { + "name": "Media player", + "description": "Fills the title, type, season and fallback picture from this player." + }, + "use_media_player_picture": { + "name": "Use the player's picture as fallback", + "description": "Send the picture of the media player, shown when TMDB finds no poster (on by default)." + }, + "query": { + "name": "Title", + "description": "Title of the movie or series (1 to 200 characters)." + }, + "media_type": { + "name": "Type", + "description": "Look for a movie, a series, or both." + }, + "season": { + "name": "Season", + "description": "Series only: prefer the poster of this season." + }, + "year": { + "name": "Year", + "description": "Release year, to tell apart titles with the same name." + }, + "language": { + "name": "Language", + "description": "Language of the poster, for example fr or fr-CA. The engine's language applies when left empty." + }, + "fallback_url": { + "name": "Fallback picture URL", + "description": "Picture shown when TMDB has no match. It must be reachable by the engine." + }, + "ephemeral": { + "name": "Temporary", + "description": "When on, the previous image comes back afterwards." + }, + "ttl_minutes": { + "name": "Duration", + "description": "Temporary posters only: minutes before the previous image returns (1 to 1440). The engine's default applies when left empty." + }, + "hold_minutes": { + "name": "Protect from refresh", + "description": "Minutes during which scheduled refreshes will not replace the poster (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": { + "music_style": { + "options": { + "sleeve": "Sleeve", + "vinyl": "Vinyl record" + } + }, + "media_type": { + "options": { + "movie": "Movie", + "tv": "Series", + "multi": "Movie or series" + } + }, "season": { "options": { "spring": "Spring", @@ -319,6 +460,15 @@ }, "no_engine_loaded": { "message": "The Smart Frame Engine is not loaded. Check that it is reachable and try again." + }, + "missing_artist": { + "message": "No artist to show. Give an artist, or a media player that reports one." + }, + "missing_query": { + "message": "No title to look up. Give a title, or a media player that reports one." + }, + "media_player_not_found": { + "message": "The media player {entity_id} was not found." } } } diff --git a/custom_components/smart_frame_engine/translations/en.json b/custom_components/smart_frame_engine/translations/en.json index 35ef4d9..249f2ab 100644 --- a/custom_components/smart_frame_engine/translations/en.json +++ b/custom_components/smart_frame_engine/translations/en.json @@ -242,9 +242,150 @@ "description": "Turn off to only render a preview without sending it to the frame." } } + }, + "show_now_playing": { + "name": "Show album cover", + "description": "Shows the cover of the track that is playing, with the artist and album. Pick a media player to fill the fields from it; values you set yourself win. The cover sent by Home Assistant is tried first; without a usable one the engine looks a cover up itself.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "media_player": { + "name": "Media player", + "description": "Fills the artist, album, title, position and cover from this player." + }, + "use_media_player_picture": { + "name": "Send the player's cover", + "description": "Send the cover of the media player to the engine (on by default). Turn off to let the engine look the cover up itself." + }, + "artist": { + "name": "Artist", + "description": "Artist of the track (1 to 300 characters)." + }, + "album": { + "name": "Album", + "description": "Album of the track (up to 300 characters)." + }, + "title": { + "name": "Track title", + "description": "Title of the track (up to 300 characters)." + }, + "artwork_url": { + "name": "Cover URL", + "description": "Address of the cover. It must be reachable by the engine." + }, + "duration_seconds": { + "name": "Track length", + "description": "Length of the track, in seconds." + }, + "position_seconds": { + "name": "Position", + "description": "Playback position, in seconds." + }, + "enrich_artwork": { + "name": "Look up a cover", + "description": "When no usable cover is given, let the engine look one up (on by default)." + }, + "ephemeral": { + "name": "Temporary", + "description": "When on, the previous image comes back afterwards." + }, + "hold_minutes": { + "name": "Protect from refresh", + "description": "Minutes during which scheduled refreshes will not replace the cover (1 to 10080)." + }, + "push_to_fraimic": { + "name": "Send to frame", + "description": "Turn off to only render a preview without sending it to the frame." + }, + "show_title": { + "name": "Print the track title", + "description": "Print the track title on the cover. Without it, the frame is only refreshed when the album changes." + }, + "style": { + "name": "Style", + "description": "Show the cover as a sleeve or as a vinyl record." + }, + "ttl_seconds": { + "name": "Duration", + "description": "Seconds before the previous image returns (10 to 86400). Overrides the duration worked out from the track length." + } + } + }, + "show_media_poster": { + "name": "Show movie or series poster", + "description": "Finds a movie or series on TMDB and shows its poster. Pick a media player to fill the fields from it; values you set yourself win. The player's picture is only used when TMDB has no match.", + "fields": { + "config_entry_id": { + "name": "Engine", + "description": "The Smart Frame Engine to use. Optional when only one is set up." + }, + "media_player": { + "name": "Media player", + "description": "Fills the title, type, season and fallback picture from this player." + }, + "use_media_player_picture": { + "name": "Use the player's picture as fallback", + "description": "Send the picture of the media player, shown when TMDB finds no poster (on by default)." + }, + "query": { + "name": "Title", + "description": "Title of the movie or series (1 to 200 characters)." + }, + "media_type": { + "name": "Type", + "description": "Look for a movie, a series, or both." + }, + "season": { + "name": "Season", + "description": "Series only: prefer the poster of this season." + }, + "year": { + "name": "Year", + "description": "Release year, to tell apart titles with the same name." + }, + "language": { + "name": "Language", + "description": "Language of the poster, for example fr or fr-CA. The engine's language applies when left empty." + }, + "fallback_url": { + "name": "Fallback picture URL", + "description": "Picture shown when TMDB has no match. It must be reachable by the engine." + }, + "ephemeral": { + "name": "Temporary", + "description": "When on, the previous image comes back afterwards." + }, + "ttl_minutes": { + "name": "Duration", + "description": "Temporary posters only: minutes before the previous image returns (1 to 1440). The engine's default applies when left empty." + }, + "hold_minutes": { + "name": "Protect from refresh", + "description": "Minutes during which scheduled refreshes will not replace the poster (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": { + "music_style": { + "options": { + "sleeve": "Sleeve", + "vinyl": "Vinyl record" + } + }, + "media_type": { + "options": { + "movie": "Movie", + "tv": "Series", + "multi": "Movie or series" + } + }, "season": { "options": { "spring": "Spring", @@ -319,6 +460,15 @@ }, "no_engine_loaded": { "message": "The Smart Frame Engine is not loaded. Check that it is reachable and try again." + }, + "missing_artist": { + "message": "No artist to show. Give an artist, or a media player that reports one." + }, + "missing_query": { + "message": "No title to look up. Give a title, or a media player that reports one." + }, + "media_player_not_found": { + "message": "The media player {entity_id} was not found." } } } diff --git a/custom_components/smart_frame_engine/translations/fr.json b/custom_components/smart_frame_engine/translations/fr.json index 80a5ca2..6946163 100644 --- a/custom_components/smart_frame_engine/translations/fr.json +++ b/custom_components/smart_frame_engine/translations/fr.json @@ -242,9 +242,150 @@ "description": "Désactivez pour seulement générer un aperçu sans l'envoyer au cadre." } } + }, + "show_now_playing": { + "name": "Afficher la pochette d'album", + "description": "Affiche la pochette du morceau en cours de lecture, avec l'artiste et l'album. Choisissez un lecteur multimédia pour remplir les champs à partir de lui ; les valeurs que vous indiquez priment. La pochette envoyée par Home Assistant est essayée en premier ; sans pochette utilisable, le moteur en cherche une lui-même.", + "fields": { + "config_entry_id": { + "name": "Moteur", + "description": "Le Smart Frame Engine à utiliser. Facultatif si un seul est configuré." + }, + "media_player": { + "name": "Lecteur multimédia", + "description": "Remplit l'artiste, l'album, le titre, la position et la pochette à partir de ce lecteur." + }, + "use_media_player_picture": { + "name": "Envoyer la pochette du lecteur", + "description": "Envoie au moteur la pochette du lecteur multimédia (activé par défaut). Désactivez pour laisser le moteur chercher la pochette lui-même." + }, + "artist": { + "name": "Artiste", + "description": "Artiste du morceau (de 1 à 300 caractères)." + }, + "album": { + "name": "Album", + "description": "Album du morceau (300 caractères maximum)." + }, + "title": { + "name": "Titre du morceau", + "description": "Titre du morceau (300 caractères maximum)." + }, + "artwork_url": { + "name": "URL de la pochette", + "description": "Adresse de la pochette. Elle doit être accessible par le moteur." + }, + "duration_seconds": { + "name": "Durée du morceau", + "description": "Durée du morceau, en secondes." + }, + "position_seconds": { + "name": "Position", + "description": "Position de lecture, en secondes." + }, + "enrich_artwork": { + "name": "Chercher une pochette", + "description": "Si aucune pochette utilisable n'est fournie, laisse le moteur en chercher une (activé par défaut)." + }, + "ephemeral": { + "name": "Temporaire", + "description": "Si activé, l'image précédente revient ensuite." + }, + "hold_minutes": { + "name": "Protéger du rafraîchissement", + "description": "Minutes pendant lesquelles les rafraîchissements planifiés ne remplaceront pas la pochette (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." + }, + "show_title": { + "name": "Afficher le titre du morceau", + "description": "Affiche le titre du morceau sur la pochette. Sans lui, le cadre n'est rafraîchi que lorsque l'album change." + }, + "style": { + "name": "Style", + "description": "Affiche la pochette comme une pochette ou un vinyle." + }, + "ttl_seconds": { + "name": "Durée", + "description": "Secondes avant le retour de l'image précédente (10 à 86400). Remplace la durée calculée à partir de la longueur du morceau." + } + } + }, + "show_media_poster": { + "name": "Afficher l'affiche d'un film ou d'une série", + "description": "Trouve un film ou une série sur TMDB et affiche son affiche. Choisissez un lecteur multimédia pour remplir les champs à partir de lui ; les valeurs que vous indiquez priment. L'image du lecteur n'est utilisée que si TMDB ne trouve rien.", + "fields": { + "config_entry_id": { + "name": "Moteur", + "description": "Le Smart Frame Engine à utiliser. Facultatif si un seul est configuré." + }, + "media_player": { + "name": "Lecteur multimédia", + "description": "Remplit le titre, le type, la saison et l'image de secours à partir de ce lecteur." + }, + "use_media_player_picture": { + "name": "Image du lecteur en secours", + "description": "Envoie l'image du lecteur multimédia, affichée si TMDB ne trouve pas d'affiche (activé par défaut)." + }, + "query": { + "name": "Titre", + "description": "Titre du film ou de la série (de 1 à 200 caractères)." + }, + "media_type": { + "name": "Type", + "description": "Cherche un film, une série, ou les deux." + }, + "season": { + "name": "Saison", + "description": "Séries uniquement : privilégie l'affiche de cette saison." + }, + "year": { + "name": "Année", + "description": "Année de sortie, pour départager des titres portant le même nom." + }, + "language": { + "name": "Langue", + "description": "Langue de l'affiche, par exemple fr ou fr-CA. La langue du moteur s'applique si le champ est vide." + }, + "fallback_url": { + "name": "URL de l'image de secours", + "description": "Image affichée si TMDB ne trouve rien. Elle doit être accessible par le moteur." + }, + "ephemeral": { + "name": "Temporaire", + "description": "Si activé, l'image précédente revient ensuite." + }, + "ttl_minutes": { + "name": "Durée", + "description": "Affiches temporaires uniquement : minutes avant le retour de l'image précédente (1 à 1440). La valeur par défaut du moteur 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 l'affiche (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": { + "music_style": { + "options": { + "sleeve": "Pochette", + "vinyl": "Disque vinyle" + } + }, + "media_type": { + "options": { + "movie": "Film", + "tv": "Série", + "multi": "Film ou série" + } + }, "season": { "options": { "spring": "Printemps", @@ -319,6 +460,15 @@ }, "no_engine_loaded": { "message": "Le Smart Frame Engine n'est pas chargé. Vérifiez qu'il est joignable puis réessayez." + }, + "missing_artist": { + "message": "Aucun artiste à afficher. Indiquez un artiste, ou un lecteur multimédia qui en fournit un." + }, + "missing_query": { + "message": "Aucun titre à rechercher. Indiquez un titre, ou un lecteur multimédia qui en fournit un." + }, + "media_player_not_found": { + "message": "Le lecteur multimédia {entity_id} est introuvable." } } } diff --git a/tests/test_api.py b/tests/test_api.py index 7e57ca7..d7376bc 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -470,6 +470,121 @@ async def test_title_card_minimal_and_full( assert _last_call(aioclient_mock)[2] == {"title": "Hello", "ttl_minutes": 5} +async def test_now_playing_body(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """POST /api/display/now-playing sends only the documented fields that were given.""" + aioclient_mock.post(f"{BASE}/api/display/now-playing", json=display_payload()) + client = _client(hass, API_KEY) + + await client.async_now_playing("Daft Punk") + call = _last_call(aioclient_mock) + assert (call[0], call[1].path, call[2]) == ( + "POST", + "/api/display/now-playing", + {"artist": "Daft Punk"}, + ) + assert call[3]["X-API-Key"] == API_KEY + + result = await client.async_now_playing( + "Daft Punk", + album="Discovery", + title="One More Time", + artwork_url="http://ha/cover.jpg", + duration_seconds=320.0, + position_seconds=0.0, + enrich_artwork=False, + ephemeral=False, + hold_minutes=30, + push_to_fraimic=False, + show_title=False, + style="vinyl", + ttl_seconds=120, + ) + assert _last_call(aioclient_mock)[2] == { + "artist": "Daft Punk", + "album": "Discovery", + "title": "One More Time", + "artwork_url": "http://ha/cover.jpg", + "duration_seconds": 320.0, + "position_seconds": 0.0, + "enrich_artwork": False, + "ephemeral": False, + "hold_minutes": 30, + "push_to_fraimic": False, + "show_title": False, + "style": "vinyl", + "ttl_seconds": 120, + } + assert result.image.source == "immich" + + +async def test_now_playing_deduplicated_result( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Sending the album that is already shown answers deduplicated: true.""" + aioclient_mock.post( + f"{BASE}/api/display/now-playing", json=display_payload() | {"deduplicated": True} + ) + assert (await _client(hass).async_now_playing("Air")).deduplicated is True + + +async def test_display_tmdb_body(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """POST /api/display/tmdb sends only the documented fields that were given.""" + aioclient_mock.post(f"{BASE}/api/display/tmdb", json=display_payload()) + client = _client(hass, API_KEY) + + await client.async_display_tmdb("Blade Runner") + call = _last_call(aioclient_mock) + assert (call[0], call[1].path, call[2]) == ( + "POST", + "/api/display/tmdb", + {"query": "Blade Runner"}, + ) + assert call[3]["X-API-Key"] == API_KEY + + await client.async_display_tmdb( + "Severance", + media_type="tv", + season=0, + year=2022, + language="fr-CA", + fallback_url="http://ha/poster.jpg", + ephemeral=False, + ttl_minutes=90, + hold_minutes=15, + push_to_fraimic=False, + ) + assert _last_call(aioclient_mock)[2] == { + "query": "Severance", + "media_type": "tv", + "season": 0, + "year": 2022, + "language": "fr-CA", + "fallback_url": "http://ha/poster.jpg", + "ephemeral": False, + "ttl_minutes": 90, + "hold_minutes": 15, + "push_to_fraimic": False, + } + + +@pytest.mark.parametrize("status", [404, 409, 502, 504]) +async def test_display_tmdb_errors( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, status: int +) -> None: + """The documented TMDB error statuses carry the engine's message.""" + aioclient_mock.post(f"{BASE}/api/display/tmdb", status=status, json={"detail": "nope"}) + with pytest.raises(SmartFrameApiError) as err: + await _client(hass).async_display_tmdb("x") + assert (err.value.status, err.value.detail) == (status, "nope") + + +async def test_now_playing_422(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """A rejected cover request is a validation error.""" + aioclient_mock.post(f"{BASE}/api/display/now-playing", status=422, json={"detail": "bad"}) + with pytest.raises(SmartFrameValidationError): + await _client(hass).async_now_playing("Air") + + async def test_wakeup_non_blocking_returns_202( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: diff --git a/tests/test_media_services.py b/tests/test_media_services.py new file mode 100644 index 0000000..c027349 --- /dev/null +++ b/tests/test_media_services.py @@ -0,0 +1,760 @@ +"""Tests for the album cover and movie/series poster services.""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any +from unittest.mock import patch + +from freezegun.api import FrozenDateTimeFactory +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers.network import NoURLAvailableError +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_DISPLAY_TMDB, + CAPABILITY_NOW_PLAYING, + CAPABILITY_TITLE_CARD, + DOMAIN, +) + +from .common import API_KEY, BASE, OTHER_INSTANCE_ID, display_payload, make_entry, setup_engine + +OTHER_BASE = "http://192.168.1.51:8080" +PLAYER = "media_player.living_room" +INTERNAL_URL = "http://homeassistant.local:8123" +NOW_PLAYING = f"{BASE}/api/display/now-playing" +TMDB = f"{BASE}/api/display/tmdb" + + +def _posts(aioclient_mock: AiohttpClientMocker, path: str) -> list[dict[str, Any]]: + return [c[2] for c in aioclient_mock.mock_calls if c[0] == "POST" and c[1].path == path] + + +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 _internal_url(hass: HomeAssistant) -> None: + await hass.config.async_update(internal_url=INTERNAL_URL) + + +def _music(**attributes: Any) -> dict[str, Any]: + return { + "media_artist": "Daft Punk", + "media_album_name": "Discovery", + "media_title": "One More Time", + "media_duration": 320, + "media_position": 20, + "entity_picture": "/api/media_player_proxy/media_player.living_room?token=abc", + } | attributes + + +def _video(**attributes: Any) -> dict[str, Any]: + return { + "media_content_type": "movie", + "media_title": "Blade Runner", + "entity_picture": "/api/media_player_proxy/media_player.tv?token=abc", + } | attributes + + +@pytest.fixture +async def music_engine(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """An engine that shows covers, and an internal URL for the pictures.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.post(NOW_PLAYING, json=display_payload()) + aioclient_mock.post(TMDB, json=display_payload()) + await _internal_url(hass) + + +async def test_media_services_are_registered(hass: HomeAssistant) -> None: + """Both services exist as soon as the integration is loaded.""" + assert await async_setup_component(hass, DOMAIN, {}) + assert hass.services.has_service(DOMAIN, "show_now_playing") + assert hass.services.has_service(DOMAIN, "show_media_poster") + + +# -- show_now_playing ------------------------------------------------------------------ + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_from_a_media_player( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Artist, album, title, duration, position and the picture come from the player.""" + hass.states.async_set(PLAYER, "paused", _music()) + await _call(hass, "show_now_playing", {"media_player": PLAYER}) + + (body,) = _posts(aioclient_mock, "/api/display/now-playing") + assert body == { + "artist": "Daft Punk", + "album": "Discovery", + "title": "One More Time", + "duration_seconds": 320.0, + "position_seconds": 20.0, + # The relative picture is made absolute with the internal URL. + "artwork_url": f"{INTERNAL_URL}/api/media_player_proxy/media_player.living_room?token=abc", + } + call = [c for c in aioclient_mock.mock_calls if c[1].path == "/api/display/now-playing"][-1] + assert call[3]["X-API-Key"] == API_KEY + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_position_advances_while_playing( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + freezer: FrozenDateTimeFactory, +) -> None: + """A playing track's reported position is topped up with the time since it was reported.""" + freezer.move_to(datetime(2026, 11, 20, 12, 0, 30, tzinfo=UTC)) + updated = datetime(2026, 11, 20, 12, 0, 0, tzinfo=UTC) + hass.states.async_set(PLAYER, "playing", _music(media_position_updated_at=updated)) + + await _call(hass, "show_now_playing", {"media_player": PLAYER}) + + assert _posts(aioclient_mock, "/api/display/now-playing")[-1]["position_seconds"] == 50.0 + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_position_is_not_advanced_when_paused_or_past_the_end( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + freezer: FrozenDateTimeFactory, +) -> None: + """Paused players keep their position; a stale one never exceeds the track length.""" + freezer.move_to(datetime(2026, 11, 20, 12, 0, 30, tzinfo=UTC)) + updated = datetime(2026, 11, 20, 12, 0, 0, tzinfo=UTC) + hass.states.async_set(PLAYER, "paused", _music(media_position_updated_at=updated)) + await _call(hass, "show_now_playing", {"media_player": PLAYER}) + assert _posts(aioclient_mock, "/api/display/now-playing")[-1]["position_seconds"] == 20.0 + + hass.states.async_set( + PLAYER, "playing", _music(media_position=319, media_position_updated_at=updated) + ) + await _call(hass, "show_now_playing", {"media_player": PLAYER}) + assert _posts(aioclient_mock, "/api/display/now-playing")[-1]["position_seconds"] == 320.0 + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_explicit_values_win( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """What the call sets is sent as is; the player only fills the gaps.""" + hass.states.async_set(PLAYER, "playing", _music()) + await _call( + hass, + "show_now_playing", + { + "media_player": PLAYER, + "artist": "Justice", + "album": "Cross", + "title": "D.A.N.C.E.", + "artwork_url": "http://cdn.example/cover.jpg", + "duration_seconds": 200, + "position_seconds": 5, + }, + ) + body = _posts(aioclient_mock, "/api/display/now-playing")[-1] + assert body == { + "artist": "Justice", + "album": "Cross", + "title": "D.A.N.C.E.", + "artwork_url": "http://cdn.example/cover.jpg", + "duration_seconds": 200.0, + "position_seconds": 5.0, + } + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_without_a_media_player_sends_only_what_is_given( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The contract's own fields work on their own, with every option forwarded.""" + await _call( + hass, + "show_now_playing", + { + "artist": "Air", + "enrich_artwork": False, + "ephemeral": False, + "hold_minutes": 30, + "push_to_fraimic": False, + "show_title": True, + "style": "vinyl", + "ttl_seconds": 600, + }, + ) + assert _posts(aioclient_mock, "/api/display/now-playing")[-1] == { + "artist": "Air", + "enrich_artwork": False, + "ephemeral": False, + "hold_minutes": 30, + "push_to_fraimic": False, + "show_title": True, + "style": "vinyl", + "ttl_seconds": 600, + } + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_artist_only( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Only the artist is required.""" + await _call(hass, "show_now_playing", {"artist": "Air"}) + assert _posts(aioclient_mock, "/api/display/now-playing")[-1] == {"artist": "Air"} + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_can_leave_the_cover_to_the_engine( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """use_media_player_picture: false sends no cover, so the engine's lookup applies.""" + hass.states.async_set(PLAYER, "playing", _music()) + await _call( + hass, "show_now_playing", {"media_player": PLAYER, "use_media_player_picture": False} + ) + body = _posts(aioclient_mock, "/api/display/now-playing")[-1] + assert "artwork_url" not in body + assert body["artist"] == "Daft Punk" + + +@pytest.mark.parametrize( + ("picture", "expected"), + [ + ("https://cdn.example/a.jpg", "https://cdn.example/a.jpg"), + ("/local/cover.jpg", f"{INTERNAL_URL}/local/cover.jpg"), + ("data:image/png;base64,AAAA", None), + ("cover.jpg", None), + ("/" + "x" * 4096, None), + ("", None), + (None, None), + ], + ids=["absolute", "relative", "data uri", "no scheme", "too long", "empty", "missing"], +) +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_picture_handling( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + picture: str | None, + expected: str | None, +) -> None: + """Only a picture the engine can fetch is sent; the rest is left out, never an error.""" + hass.states.async_set(PLAYER, "playing", _music(entity_picture=picture)) + await _call(hass, "show_now_playing", {"media_player": PLAYER}) + body = _posts(aioclient_mock, "/api/display/now-playing")[-1] + assert body.get("artwork_url") == expected + + +async def test_now_playing_without_an_internal_url_sends_no_cover( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A relative picture cannot be made absolute without an internal URL: the engine looks.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(NOW_PLAYING, json=display_payload()) + hass.states.async_set(PLAYER, "playing", _music()) + with patch( + "custom_components.smart_frame_engine.services.get_url", side_effect=NoURLAvailableError + ): + await _call(hass, "show_now_playing", {"media_player": PLAYER}) + body = _posts(aioclient_mock, "/api/display/now-playing")[-1] + assert "artwork_url" not in body + assert body["artist"] == "Daft Punk" + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_ignores_unusable_attributes( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Blank text and out-of-range or non-numeric numbers are left out, long text is cut.""" + hass.states.async_set( + PLAYER, + "playing", + _music( + media_artist=" " + "a" * 400, + media_album_name=" ", + media_title=None, + media_duration=True, + media_position=-5, + entity_picture=None, + ), + ) + await _call(hass, "show_now_playing", {"media_player": PLAYER}) + assert _posts(aioclient_mock, "/api/display/now-playing")[-1] == {"artist": "a" * 300} + + +@pytest.mark.parametrize( + "attributes", [{}, {"media_artist": ""}, {"media_artist": None}, {"media_artist": 12}] +) +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_needs_an_artist( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, attributes: dict[str, Any] +) -> None: + """No artist (from the call or the player) means nothing is sent.""" + hass.states.async_set(PLAYER, "playing", attributes) + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "show_now_playing", {"media_player": PLAYER}) + assert err.value.translation_domain == DOMAIN + assert err.value.translation_key == "missing_artist" + assert not _posts(aioclient_mock, "/api/display/now-playing") + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_without_artist_or_player( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Neither an artist nor a player is the same error.""" + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "show_now_playing", {"album": "Discovery"}) + assert err.value.translation_key == "missing_artist" + + +@pytest.mark.parametrize("service", ["show_now_playing", "show_media_poster"]) +@pytest.mark.usefixtures("music_engine") +async def test_unknown_media_player( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, service: str +) -> None: + """A media player that does not exist is reported with its id.""" + with pytest.raises(ServiceValidationError) as err: + await _call(hass, service, {"media_player": "media_player.ghost"}) + assert err.value.translation_key == "media_player_not_found" + assert err.value.translation_placeholders == {"entity_id": "media_player.ghost"} + assert not [c for c in aioclient_mock.mock_calls if c[0] == "POST"] + + +@pytest.mark.parametrize( + ("service", "data"), + [ + ("show_now_playing", {"media_player": "light.kitchen"}), + ("show_media_poster", {"media_player": "light.kitchen"}), + ], +) +@pytest.mark.usefixtures("music_engine") +async def test_media_player_must_be_a_media_player( + hass: HomeAssistant, service: str, data: dict[str, Any] +) -> None: + """Other domains are refused by the schema.""" + with pytest.raises(vol.Invalid): + await _call(hass, service, data) + + +@pytest.mark.parametrize( + "data", + [ + {"artist": ""}, + {"artist": "x" * 301}, + {"artist": "a", "album": "x" * 301}, + {"artist": "a", "title": "x" * 301}, + {"artist": "a", "artwork_url": "x" * 4097}, + {"artist": "a", "duration_seconds": -1}, + {"artist": "a", "duration_seconds": 86401}, + {"artist": "a", "position_seconds": 86401}, + {"artist": "a", "hold_minutes": 0}, + {"artist": "a", "style": "cassette"}, + {"artist": "a", "ttl_seconds": 9}, + {"artist": "a", "ttl_seconds": 86401}, + {"artist": "a", "is_locked": True}, + ], + ids=[ + "empty artist", + "artist 301", + "album 301", + "title 301", + "url 4097", + "duration -1", + "duration big", + "position big", + "hold 0", + "style", + "ttl 9", + "ttl big", + "unknown field", + ], +) +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_schema_limits( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, data: dict[str, Any] +) -> None: + """The limits of NowPlayingRequest are enforced before any request; no invented fields.""" + with pytest.raises(vol.Invalid): + await _call(hass, "show_now_playing", data) + assert not _posts(aioclient_mock, "/api/display/now-playing") + + +@pytest.mark.usefixtures("music_engine") +async def test_now_playing_accepts_the_bounds( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The inclusive limits are valid.""" + await _call( + hass, + "show_now_playing", + { + "artist": "a" * 300, + "album": "b" * 300, + "title": "c" * 300, + "artwork_url": "u" * 4096, + "duration_seconds": 86400, + "position_seconds": 0, + "ttl_seconds": 10, + "hold_minutes": 10080, + }, + ) + assert len(_posts(aioclient_mock, "/api/display/now-playing")) == 1 + + +# -- show_media_poster ----------------------------------------------------------------- + + +@pytest.mark.usefixtures("music_engine") +async def test_poster_for_a_movie_player( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A movie: its title, type movie, and the picture as the TMDB fallback.""" + hass.states.async_set("media_player.tv", "playing", _video()) + await _call(hass, "show_media_poster", {"media_player": "media_player.tv"}) + assert _posts(aioclient_mock, "/api/display/tmdb")[-1] == { + "query": "Blade Runner", + "media_type": "movie", + "fallback_url": f"{INTERNAL_URL}/api/media_player_proxy/media_player.tv?token=abc", + } + + +@pytest.mark.usefixtures("music_engine") +async def test_poster_for_an_episode_uses_the_series( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """An episode: the series title (not the episode's), type tv, and its season.""" + hass.states.async_set( + "media_player.tv", + "playing", + _video( + media_content_type="episode", + media_title="Pilot", + media_series_title="Severance", + media_season=2, + ), + ) + await _call(hass, "show_media_poster", {"media_player": "media_player.tv"}) + body = _posts(aioclient_mock, "/api/display/tmdb")[-1] + assert (body["query"], body["media_type"], body["season"]) == ("Severance", "tv", 2) + + +@pytest.mark.parametrize( + ("content_type", "media_type"), + [("movie", "movie"), ("tvshow", "tv"), ("episode", "tv"), ("video", None), (None, None)], +) +@pytest.mark.usefixtures("music_engine") +async def test_poster_media_type_mapping( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + content_type: str | None, + media_type: str | None, +) -> None: + """Only the documented content types name a TMDB type; otherwise the engine searches both.""" + hass.states.async_set( + "media_player.tv", "playing", _video(media_content_type=content_type, media_season=3) + ) + await _call(hass, "show_media_poster", {"media_player": "media_player.tv"}) + body = _posts(aioclient_mock, "/api/display/tmdb")[-1] + assert body.get("media_type") == media_type + # A season only makes sense for a series. + assert ("season" in body) is (media_type == "tv") + + +@pytest.mark.usefixtures("music_engine") +async def test_poster_explicit_values_win( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The call's own values replace the ones read from the player.""" + hass.states.async_set( + "media_player.tv", + "playing", + _video(media_content_type="episode", media_series_title="Severance", media_season=2), + ) + await _call( + hass, + "show_media_poster", + { + "media_player": "media_player.tv", + "query": "Dark", + "media_type": "multi", + "season": 1, + "fallback_url": "http://cdn.example/p.jpg", + }, + ) + body = _posts(aioclient_mock, "/api/display/tmdb")[-1] + assert body == { + "query": "Dark", + "media_type": "multi", + "season": 1, + "fallback_url": "http://cdn.example/p.jpg", + } + + +@pytest.mark.usefixtures("music_engine") +async def test_poster_without_a_media_player_forwards_every_option( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The contract's own fields work on their own.""" + await _call( + hass, + "show_media_poster", + { + "query": "Dune", + "media_type": "movie", + "season": 0, + "year": 2021, + "language": "fr-CA", + "fallback_url": "http://cdn.example/p.jpg", + "ephemeral": False, + "ttl_minutes": 1440, + "hold_minutes": 10080, + "push_to_fraimic": False, + }, + ) + assert _posts(aioclient_mock, "/api/display/tmdb")[-1] == { + "query": "Dune", + "media_type": "movie", + "season": 0, + "year": 2021, + "language": "fr-CA", + "fallback_url": "http://cdn.example/p.jpg", + "ephemeral": False, + "ttl_minutes": 1440, + "hold_minutes": 10080, + "push_to_fraimic": False, + } + + +@pytest.mark.usefixtures("music_engine") +async def test_poster_picture_fallback_can_be_turned_off( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """use_media_player_picture: false sends no fallback picture.""" + hass.states.async_set("media_player.tv", "playing", _video()) + await _call( + hass, + "show_media_poster", + {"media_player": "media_player.tv", "use_media_player_picture": False}, + ) + assert "fallback_url" not in _posts(aioclient_mock, "/api/display/tmdb")[-1] + + +@pytest.mark.parametrize( + "attributes", + [{}, {"media_title": ""}, {"media_title": None}, {"media_series_title": " "}], +) +@pytest.mark.usefixtures("music_engine") +async def test_poster_needs_a_title( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, attributes: dict[str, Any] +) -> None: + """No title (from the call or the player) means nothing is sent.""" + hass.states.async_set("media_player.tv", "playing", attributes) + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "show_media_poster", {"media_player": "media_player.tv"}) + assert err.value.translation_key == "missing_query" + assert not _posts(aioclient_mock, "/api/display/tmdb") + + +@pytest.mark.parametrize( + "data", + [ + {"query": ""}, + {"query": "x" * 201}, + {"query": "a", "media_type": "anime"}, + {"query": "a", "season": 101}, + {"query": "a", "season": -1}, + {"query": "a", "year": 1869}, + {"query": "a", "year": 2201}, + {"query": "a", "ttl_minutes": 0}, + {"query": "a", "ttl_minutes": 1441}, + {"query": "a", "hold_minutes": 10081}, + {"query": "a", "fallback_url": "x" * 4097}, + {"query": "a", "accent": "red"}, + ], + ids=[ + "empty query", + "query 201", + "media type", + "season 101", + "season -1", + "year 1869", + "year 2201", + "ttl 0", + "ttl 1441 (max is 1440, not 10080)", + "hold 10081", + "url 4097", + "unknown field", + ], +) +@pytest.mark.usefixtures("music_engine") +async def test_poster_schema_limits( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, data: dict[str, Any] +) -> None: + """The limits of TmdbDisplayRequest are enforced before any request.""" + with pytest.raises(vol.Invalid): + await _call(hass, "show_media_poster", data) + assert not _posts(aioclient_mock, "/api/display/tmdb") + + +@pytest.mark.usefixtures("music_engine") +async def test_poster_accepts_the_bounds( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The inclusive limits are valid.""" + await _call( + hass, + "show_media_poster", + {"query": "q" * 200, "season": 100, "year": 1870, "ttl_minutes": 1, "hold_minutes": 1}, + ) + await _call(hass, "show_media_poster", {"query": "q", "season": 0, "year": 2200}) + assert len(_posts(aioclient_mock, "/api/display/tmdb")) == 2 + + +# -- Capability gating, targeting and errors ------------------------------------------- + + +@pytest.mark.parametrize( + ("service", "data", "missing"), + [ + ("show_now_playing", {"artist": "Air"}, CAPABILITY_NOW_PLAYING), + ("show_media_poster", {"query": "Dune"}, CAPABILITY_DISPLAY_TMDB), + ], +) +async def test_unsupported_capability_raises_before_any_request( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + service: str, + data: dict[str, Any], + missing: str, +) -> None: + """An engine without the capability gets a translated ServiceValidationError.""" + entry = await setup_engine(hass, aioclient_mock, capabilities={CAPABILITY_TITLE_CARD}) + 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] == "POST"] + + +async def test_each_service_needs_its_own_capability( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """now_playing does not unlock the poster service, and display_tmdb not the cover one.""" + await setup_engine(hass, aioclient_mock, capabilities={CAPABILITY_NOW_PLAYING}) + aioclient_mock.post(NOW_PLAYING, json=display_payload()) + await _call(hass, "show_now_playing", {"artist": "Air"}) + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "show_media_poster", {"query": "Dune"}) + assert err.value.translation_placeholders is not None + assert err.value.translation_placeholders["capability"] == CAPABILITY_DISPLAY_TMDB + + +async def test_several_engines_need_an_explicit_target( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """With two engines the call says which one; only that one is used.""" + 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(NOW_PLAYING, json=display_payload()) + aioclient_mock.post(f"{OTHER_BASE}/api/display/now-playing", json=display_payload()) + + with pytest.raises(ServiceValidationError) as err: + await _call(hass, "show_now_playing", {"artist": "Air"}) + assert err.value.translation_key == "config_entry_required" + + await _call(hass, "show_now_playing", {"artist": "Air", "config_entry_id": second.entry_id}) + posts = [c for c in aioclient_mock.mock_calls if c[0] == "POST"] + assert [str(c[1].host) for c in posts] == ["192.168.1.51"] + + +@pytest.mark.parametrize( + ("service", "data", "path"), + [ + ("show_now_playing", {"artist": "Air"}, "/api/display/now-playing"), + ("show_media_poster", {"query": "Dune"}, "/api/display/tmdb"), + ], +) +async def test_engine_422_is_a_validation_error( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + service: str, + data: dict[str, Any], + path: str, +) -> None: + """A request the engine rejects (e.g. an unknown person) is invalid input, with its message.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}{path}", status=422, json={"detail": "bad request"}) + with pytest.raises(ServiceValidationError, match="bad request") as err: + await _call(hass, service, data) + assert err.value.translation_key == "request_rejected" + + +@pytest.mark.parametrize( + ("service", "data", "path", "status"), + [ + ("show_now_playing", {"artist": "Air"}, "/api/display/now-playing", 502), + ("show_media_poster", {"query": "Dune"}, "/api/display/tmdb", 404), + ("show_media_poster", {"query": "Dune"}, "/api/display/tmdb", 409), + ("show_media_poster", {"query": "Dune"}, "/api/display/tmdb", 502), + ("show_media_poster", {"query": "Dune"}, "/api/display/tmdb", 504), + ], +) +async def test_engine_failures_are_home_assistant_errors( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + service: str, + data: dict[str, Any], + path: str, + status: int, +) -> None: + """404 (no poster), 409 (TMDB not configured), 502 and 504 carry the engine's message.""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(f"{BASE}{path}", status=status, json={"detail": "engine said no"}) + with pytest.raises(HomeAssistantError, match="engine said no") as err: + await _call(hass, service, data) + 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(NOW_PLAYING, exc=TimeoutError) + with pytest.raises(HomeAssistantError): + await _call(hass, "show_now_playing", {"artist": "Air"}) + + +async def test_rejected_key_starts_reauth( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A 401 starts reauthentication.""" + await setup_engine(hass, aioclient_mock, api_key=API_KEY, auth="key") + aioclient_mock.post(TMDB, status=401, json={"detail": "no"}) + with pytest.raises(HomeAssistantError): + await _call(hass, "show_media_poster", {"query": "Dune"}) + await hass.async_block_till_done() + flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) + assert [flow["context"]["source"] for flow in flows] == ["reauth"] + + +async def test_services_refresh_the_engine_state( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """After showing something the coordinator is refreshed (the image entity follows).""" + await setup_engine(hass, aioclient_mock) + aioclient_mock.post(NOW_PLAYING, json=display_payload()) + before = sum(c[1].path == "/api/status" for c in aioclient_mock.mock_calls) + await _call(hass, "show_now_playing", {"artist": "Air"}) + assert sum(c[1].path == "/api/status" for c in aioclient_mock.mock_calls) == before + 1 diff --git a/tests/test_metadata.py b/tests/test_metadata.py index b004166..f040907 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -104,6 +104,8 @@ def test_services_yaml_matches_schemas_and_translations() -> None: 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, + services.SERVICE_SHOW_NOW_PLAYING: services.SHOW_NOW_PLAYING_SCHEMA, + services.SERVICE_SHOW_MEDIA_POSTER: services.SHOW_MEDIA_POSTER_SCHEMA, } translated = _english()["services"] @@ -132,7 +134,7 @@ def test_select_selectors_are_translated() -> None: assert set(select["options"]) == set( selectors[select["translation_key"]]["options"] ) - assert seen == 3 + assert seen == 5 def test_every_entity_has_a_translated_name() -> None: From dea1e53859e7f5e5f850a09b4123995f4ad13833 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Fri, 20 Nov 2026 09:57:38 +0100 Subject: [PATCH 2/2] feat: add automation blueprints for weather, presence, title cards, music and TV Five blueprints under blueprints/automation/smart_frame_engine that call the integration's services. Tests load them with Home Assistant's blueprint models and run them as real automations against the real service schemas. README documents the import links and where each picture comes from. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 4 +- README.md | 50 +- .../smart_frame_engine/ambient_presence.yaml | 82 ++ .../smart_frame_engine/ambient_weather.yaml | 77 ++ .../smart_frame_engine/now_playing_cover.yaml | 143 +++ .../smart_frame_engine/title_card.yaml | 123 +++ .../smart_frame_engine/tv_poster.yaml | 118 +++ tests/test_blueprints.py | 854 ++++++++++++++++++ 8 files changed, 1447 insertions(+), 4 deletions(-) create mode 100644 blueprints/automation/smart_frame_engine/ambient_presence.yaml create mode 100644 blueprints/automation/smart_frame_engine/ambient_weather.yaml create mode 100644 blueprints/automation/smart_frame_engine/now_playing_cover.yaml create mode 100644 blueprints/automation/smart_frame_engine/title_card.yaml create mode 100644 blueprints/automation/smart_frame_engine/tv_poster.yaml create mode 100644 tests/test_blueprints.py diff --git a/CLAUDE.md b/CLAUDE.md index a2ef627..b7d94a9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,12 +25,12 @@ 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.py` — Service handlers (ambient context, title card, album cover, poster; capability-gated, `ServiceValidationError`), registered once from `async_setup`. Album covers: the player's picture is tried first, then the engine's own lookup; TMDB posters: the player's picture is only the fallback - `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 - `custom_components/smart_frame_engine/translations/en.json` & `fr.json` — Complete English & French translations -- `blueprints/automation/smart_frame_engine/` — Ready-to-use YAML blueprints (weather/presence context, title cards) +- `blueprints/automation/smart_frame_engine/` — Ready-to-use YAML blueprints (weather/presence context, title cards, album covers, movie/series posters). They only call this integration's services, are validated by `tests/test_blueprints.py` (loaded with HA's blueprint models and run as real automations), and are **not installed by HACS** (users import them by URL; keep the README import links in step) - `tests/` — `pytest` + `pytest-homeassistant-custom-component` - `hacs.json` — HACS metadata - `pyproject.toml` — `ruff`, `mypy`, `pytest` configuration diff --git a/README.md b/README.md index e276839..17fad96 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,9 @@ 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. Discovery, setup, authentication, compatibility checks, entities -> and services are in place; blueprints follow in a later milestone. +> **Status:** work in progress. Discovery, setup, authentication, compatibility checks, entities, +> services and blueprints are in place. It has been tested against the engine's API contract +> (v1.2), not yet against a real engine. ## Requirements @@ -62,9 +63,54 @@ data: ttl_minutes: 120 ``` +- `smart_frame_engine.show_now_playing` (needs `now_playing`): shows the album cover of the music + playing. Pass a `media_player` and the artist, album, title, position and cover are read from it; + anything you set yourself wins. Other fields: `artist`, `album`, `title`, `artwork_url`, + `duration_seconds`, `position_seconds`, `style` (`sleeve` or `vinyl`), `show_title`, + `enrich_artwork`, `ephemeral`, `ttl_seconds`, `hold_minutes`, `push_to_fraimic`. +- `smart_frame_engine.show_media_poster` (needs `display_tmdb`): finds a movie or series on TMDB + and shows its poster. Pass a `media_player` and the title, type (movie or series) and season are + read from it. Other fields: `query`, `media_type`, `season`, `year`, `language`, `fallback_url`, + `ephemeral`, `ttl_minutes` (1 to 1440), `hold_minutes`, `push_to_fraimic`. + +```yaml +action: smart_frame_engine.show_now_playing +data: + media_player: media_player.kitchen +``` + A service called on an engine that lacks the capability fails with a clear message instead of sending a request. +### Where the picture comes from + +- **Album covers:** the cover of the media player is sent to the engine and **tried first**. If it + is missing or unusable, the engine looks one up itself (Deezer, then MusicBrainz / Cover Art + Archive). Set `use_media_player_picture: false` to always let the engine look it up. +- **Movie and series posters:** the engine looks the title up on TMDB, and the picture of the media + player is only the **fallback**, used when TMDB has no match. +- The picture of a media player is a Home Assistant address, so the engine must be able to reach + Home Assistant's **internal URL** (Settings > System > Network). Without an internal URL no + picture is sent, and the engine's own lookup applies. + +## Blueprints + +Ready-to-use automations are in [`blueprints/automation/smart_frame_engine`](blueprints/automation/smart_frame_engine). +HACS does not install blueprints: import each one with its button (Settings > Automations > +Blueprints), or copy the files into `config/blueprints/automation/smart_frame_engine/`. + +| Blueprint | What it does | Import | +| --- | --- | --- | +| `ambient_weather.yaml` | Tells the engine about the weather of a weather entity | [![Import](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fant1fr%2FSmart-Frame-Engine-HA%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fsmart_frame_engine%2Fambient_weather.yaml) | +| `ambient_presence.yaml` | Tells the engine which people are home | [![Import](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fant1fr%2FSmart-Frame-Engine-HA%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fsmart_frame_engine%2Fambient_presence.yaml) | +| `title_card.yaml` | Shows a text card when your trigger fires | [![Import](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fant1fr%2FSmart-Frame-Engine-HA%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fsmart_frame_engine%2Ftitle_card.yaml) | +| `now_playing_cover.yaml` | Shows the album cover of the music playing | [![Import](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fant1fr%2FSmart-Frame-Engine-HA%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fsmart_frame_engine%2Fnow_playing_cover.yaml) | +| `tv_poster.yaml` | Shows the poster of the movie or series playing | [![Import](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fant1fr%2FSmart-Frame-Engine-HA%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fsmart_frame_engine%2Ftv_poster.yaml) | + +The weather and presence blueprints re-send their value every 30 minutes, and each value expires +on its own after its lifetime, so the engine forgets it if Home Assistant stops updating it. Every +blueprint has an optional engine input, only needed when you have several engines. + ## License [MIT](LICENSE) diff --git a/blueprints/automation/smart_frame_engine/ambient_presence.yaml b/blueprints/automation/smart_frame_engine/ambient_presence.yaml new file mode 100644 index 0000000..d271bed --- /dev/null +++ b/blueprints/automation/smart_frame_engine/ambient_presence.yaml @@ -0,0 +1,82 @@ +blueprint: + name: Smart Frame Engine - Tell the frame who is home + description: >- + Keeps the list of people who are home in the ambient context of Smart Frame Engine, so the + engine can favour their photos. + + + The people are sent by name (their `person` entity's name), so the names must match the + people known to Immich. When nobody is home the list is emptied, which clears it in the + engine. It is updated when someone arrives or leaves, when Home Assistant starts, and every + 30 minutes. Each update expires on its own after the lifetime below. + domain: automation + source_url: https://github.com/ant1fr/Smart-Frame-Engine-HA/blob/main/blueprints/automation/smart_frame_engine/ambient_presence.yaml + author: ant1fr + homeassistant: + min_version: 2026.1.0 + input: + persons: + name: People + description: The people to follow (up to 20 can be at home at the same time). + selector: + entity: + multiple: true + filter: + domain: person + ttl_minutes: + name: Lifetime + description: >- + How long the engine keeps the list without an update, in minutes. It is renewed every 30 + minutes, so keep this above 30. + default: 180 + selector: + number: + min: 1 + max: 10080 + mode: box + unit_of_measurement: min + engine: + name: Smart Frame Engine + description: Only needed when you have several engines. Leave empty otherwise. + default: "" + selector: + config_entry: + integration: smart_frame_engine + +mode: restart +max_exceeded: silent + +variables: + persons: !input persons + ttl_minutes: !input ttl_minutes + engine: !input engine + # The engine takes at most 20 names of at most 80 characters. + home_names: >- + {% set ns = namespace(names=[]) %} + {% for person in persons if is_state(person, 'home') %} + {% set ns.names = ns.names + [(state_attr(person, 'friendly_name') or person)[:80]] %} + {% endfor %} + {{ ns.names[:20] }} + +triggers: + - trigger: state + entity_id: !input persons + # Only the state (home, away...): other attributes change for unrelated reasons. + to: null + id: changed + - trigger: homeassistant + event: start + id: started + - trigger: time_pattern + minutes: "/30" + id: renew + +actions: + - alias: Tell the engine who is home + action: smart_frame_engine.set_ambient_context + data: >- + {{ dict({ + 'config_entry_id': engine, + 'presence': home_names, + 'ttl_minutes': ttl_minutes, + }.items() | rejectattr('1', 'in', ['', none]) | list) }} diff --git a/blueprints/automation/smart_frame_engine/ambient_weather.yaml b/blueprints/automation/smart_frame_engine/ambient_weather.yaml new file mode 100644 index 0000000..703bffb --- /dev/null +++ b/blueprints/automation/smart_frame_engine/ambient_weather.yaml @@ -0,0 +1,77 @@ +blueprint: + name: Smart Frame Engine - Tell the frame about the weather + description: >- + Keeps the weather of a weather entity in the ambient context of Smart Frame Engine, so the + engine can favour fitting pictures. + + + The weather is sent when it changes, when Home Assistant starts, and every 30 minutes. Each + value expires on its own after the lifetime below, so the engine forgets it if Home Assistant + stops updating it. The weather entity's condition is sent as is (for example `rainy`, + `sunny` or `clear-night`). + domain: automation + source_url: https://github.com/ant1fr/Smart-Frame-Engine-HA/blob/main/blueprints/automation/smart_frame_engine/ambient_weather.yaml + author: ant1fr + homeassistant: + min_version: 2026.1.0 + input: + weather_entity: + name: Weather entity + selector: + entity: + filter: + domain: weather + ttl_minutes: + name: Lifetime + description: >- + How long the engine keeps the weather without an update, in minutes. It is renewed every + 30 minutes, so keep this above 30. + default: 180 + selector: + number: + min: 1 + max: 10080 + mode: box + unit_of_measurement: min + engine: + name: Smart Frame Engine + description: Only needed when you have several engines. Leave empty otherwise. + default: "" + selector: + config_entry: + integration: smart_frame_engine + +mode: restart +max_exceeded: silent + +variables: + weather_entity: !input weather_entity + ttl_minutes: !input ttl_minutes + engine: !input engine + +triggers: + - trigger: state + entity_id: !input weather_entity + # Only the condition: temperature and other attributes change all the time. + to: null + id: changed + - trigger: homeassistant + event: start + id: started + - trigger: time_pattern + minutes: "/30" + id: renew + +conditions: + - condition: template + value_template: "{{ states(weather_entity) not in ['unknown', 'unavailable'] }}" + +actions: + - alias: Tell the engine about the weather + action: smart_frame_engine.set_ambient_context + data: >- + {{ dict({ + 'config_entry_id': engine, + 'weather': states(weather_entity), + 'ttl_minutes': ttl_minutes, + }.items() | rejectattr('1', 'in', ['', none]) | list) }} diff --git a/blueprints/automation/smart_frame_engine/now_playing_cover.yaml b/blueprints/automation/smart_frame_engine/now_playing_cover.yaml new file mode 100644 index 0000000..38d6081 --- /dev/null +++ b/blueprints/automation/smart_frame_engine/now_playing_cover.yaml @@ -0,0 +1,143 @@ +blueprint: + name: Smart Frame Engine - Show the album cover of the music playing + description: >- + Shows the cover of the track that a media player is playing, with the artist and album, and + puts the previous image back when the track should be over. + + + The cover of the media player is sent to the engine and tried first. If it is missing or + unusable, the engine looks one up itself (Deezer, then MusicBrainz / Cover Art Archive). + Turn off "Send the player's cover" to always let the engine look it up. The picture of a + media player is a Home Assistant address, so the engine must be able to reach Home + Assistant's internal URL (Settings > System > Network). + + + Sending the same album again only extends its time on the frame, so it is safe that this + runs on every track change. + domain: automation + source_url: https://github.com/ant1fr/Smart-Frame-Engine-HA/blob/main/blueprints/automation/smart_frame_engine/now_playing_cover.yaml + author: ant1fr + homeassistant: + min_version: 2026.1.0 + input: + media_player: + name: Media player + description: The player whose music is shown. + selector: + entity: + filter: + domain: media_player + send_artwork: + name: Send the player's cover + description: >- + On: the player's cover is tried first, and the engine's lookup is the safety net. Off: + the engine always looks the cover up itself. + default: true + selector: + boolean: + style: + name: Style + default: "" + selector: + select: + options: + - label: Engine default + value: "" + - label: Sleeve + value: sleeve + - label: Vinyl record + value: vinyl + show_title: + name: Print the track title + description: >- + Without the title, every track of the same album shares one picture, so the frame is + only refreshed when the album changes. + default: "" + selector: + select: + options: + - label: Engine default + value: "" + - label: "Yes" + value: "yes" + - label: "No" + value: "no" + hold_minutes: + name: Protect from refresh + description: >- + Minutes during which scheduled refreshes will not replace the cover. 0 means the + engine's default. + default: 0 + selector: + number: + min: 0 + max: 10080 + mode: box + unit_of_measurement: min + ttl_seconds: + name: Duration + description: >- + Seconds before the previous image returns. 0 means it is worked out from the length of + the track. + default: 0 + selector: + number: + min: 0 + max: 86400 + mode: box + unit_of_measurement: s + engine: + name: Smart Frame Engine + description: Only needed when you have several engines. Leave empty otherwise. + default: "" + selector: + config_entry: + integration: smart_frame_engine + +# The latest track wins. +mode: restart +max_exceeded: silent + +variables: + media_player: !input media_player + send_artwork: !input send_artwork + style: !input style + show_title: !input show_title + hold_minutes: !input hold_minutes + ttl_seconds: !input ttl_seconds + engine: !input engine + +triggers: + - trigger: state + entity_id: !input media_player + to: playing + id: started + # Changes while playing. Position updates are not listened to: they come every few seconds. + - trigger: state + entity_id: !input media_player + attribute: media_title + id: title + +conditions: + - condition: template + value_template: "{{ is_state(media_player, 'playing') }}" + # Starting playback with a new title fires both triggers: count it once, as 'started'. + - condition: template + value_template: "{{ trigger.id == 'started' or trigger.from_state.state == 'playing' }}" + # Radio streams and some sources report no artist: there is nothing to show then. + - condition: template + value_template: "{{ (state_attr(media_player, 'media_artist') or '') | string | trim != '' }}" + +actions: + - alias: Show the cover + action: smart_frame_engine.show_now_playing + data: >- + {{ dict({ + 'config_entry_id': engine, + 'media_player': media_player, + 'use_media_player_picture': send_artwork, + 'style': style, + 'show_title': ((show_title == 'yes') if show_title else none), + 'hold_minutes': hold_minutes or none, + 'ttl_seconds': ttl_seconds or none, + }.items() | rejectattr('1', 'in', ['', none]) | list) }} diff --git a/blueprints/automation/smart_frame_engine/title_card.yaml b/blueprints/automation/smart_frame_engine/title_card.yaml new file mode 100644 index 0000000..22e412b --- /dev/null +++ b/blueprints/automation/smart_frame_engine/title_card.yaml @@ -0,0 +1,123 @@ +blueprint: + name: Smart Frame Engine - Show a title card + description: >- + Shows a text card (a title with an optional subtitle and caption) on the frame whenever your + trigger fires, for example "Dinner is ready" or "The front door is open". + + + The title, subtitle and caption accept templates, for example + `{{ trigger.to_state.name }} is open`. Temporary cards give way to the previous image after + the duration below. + domain: automation + source_url: https://github.com/ant1fr/Smart-Frame-Engine-HA/blob/main/blueprints/automation/smart_frame_engine/title_card.yaml + author: ant1fr + homeassistant: + min_version: 2026.1.0 + input: + trigger: + name: Trigger + description: What shows the card. + selector: + trigger: + title: + name: Title + description: Large centered text (up to 200 characters). Templates are allowed. + selector: + text: + subtitle: + name: Subtitle + description: Smaller text below the title (up to 200 characters). Templates are allowed. + default: "" + selector: + text: + caption: + name: Caption + description: Small text at the bottom (up to 200 characters). Templates are allowed. + default: "" + selector: + text: + accent: + name: Accent color + description: Color of the rule under the title. + default: red + selector: + select: + options: + - label: Red + value: red + - label: Yellow + value: yellow + - label: Blue + value: blue + - label: Green + value: green + - label: White + value: white + ephemeral: + name: Temporary + description: When on, the previous image comes back after the duration below. + default: true + selector: + boolean: + ttl_minutes: + name: Duration + description: Temporary cards only. Minutes before the previous image returns. + default: 60 + selector: + number: + min: 1 + max: 10080 + mode: box + unit_of_measurement: min + hold_minutes: + name: Protect from refresh + description: >- + Minutes during which scheduled refreshes will not replace the card. 0 means the engine's + default. + default: 0 + selector: + number: + min: 0 + max: 10080 + mode: box + unit_of_measurement: min + engine: + name: Smart Frame Engine + description: Only needed when you have several engines. Leave empty otherwise. + default: "" + selector: + config_entry: + integration: smart_frame_engine + +mode: queued +max: 5 +max_exceeded: silent + +variables: + title: !input title + subtitle: !input subtitle + caption: !input caption + accent: !input accent + ephemeral: !input ephemeral + ttl_minutes: !input ttl_minutes + hold_minutes: !input hold_minutes + engine: !input engine + +triggers: !input trigger + +actions: + - alias: Show the card + action: smart_frame_engine.send_title_card + # Empty inputs are left out so the engine's defaults apply. The engine takes at most 200 + # characters per text. + data: >- + {{ dict({ + 'config_entry_id': engine, + 'title': (title | string)[:200], + 'subtitle': (subtitle | string)[:200], + 'caption': (caption | string)[:200], + 'accent': accent, + 'ephemeral': ephemeral, + 'ttl_minutes': (ttl_minutes if ephemeral and ttl_minutes else none), + 'hold_minutes': hold_minutes or none, + }.items() | rejectattr('1', 'in', ['', none]) | list) }} diff --git a/blueprints/automation/smart_frame_engine/tv_poster.yaml b/blueprints/automation/smart_frame_engine/tv_poster.yaml new file mode 100644 index 0000000..cca01d0 --- /dev/null +++ b/blueprints/automation/smart_frame_engine/tv_poster.yaml @@ -0,0 +1,118 @@ +blueprint: + name: Smart Frame Engine - Show the poster of the movie or series playing + description: >- + Shows the poster of the movie or series that a media player (TV, Plex, Jellyfin, Kodi...) is + playing, and puts the previous image back after the duration below. + + + The engine finds the poster on TMDB. The picture of the media player is only used when TMDB + has no match (turn off "Use the player's picture as fallback" to never send it). It is a Home + Assistant address, so the engine must be able to reach Home Assistant's internal URL + (Settings > System > Network). For an episode, the poster of the series is shown, for the + season being played when the player reports it. Only movies, series and episodes are shown: + other kinds of video are ignored. + domain: automation + source_url: https://github.com/ant1fr/Smart-Frame-Engine-HA/blob/main/blueprints/automation/smart_frame_engine/tv_poster.yaml + author: ant1fr + homeassistant: + min_version: 2026.1.0 + input: + media_player: + name: Media player + description: The player whose movie or series is shown. + selector: + entity: + filter: + domain: media_player + use_media_player_picture: + name: Use the player's picture as fallback + description: Sent to the engine and shown only when TMDB finds no poster. + default: true + selector: + boolean: + language: + name: Poster language + description: >- + For example fr or fr-CA. Leave empty to use the language set in the engine. + default: "" + selector: + text: + ttl_minutes: + name: Duration + description: >- + Minutes before the previous image returns (up to 1440). 0 means the engine's default. + default: 0 + selector: + number: + min: 0 + max: 1440 + mode: box + unit_of_measurement: min + hold_minutes: + name: Protect from refresh + description: >- + Minutes during which scheduled refreshes will not replace the poster. 0 means the + engine's default. + default: 0 + selector: + number: + min: 0 + max: 10080 + mode: box + unit_of_measurement: min + engine: + name: Smart Frame Engine + description: Only needed when you have several engines. Leave empty otherwise. + default: "" + selector: + config_entry: + integration: smart_frame_engine + +# The latest title wins. +mode: restart +max_exceeded: silent + +variables: + media_player: !input media_player + use_media_player_picture: !input use_media_player_picture + language: !input language + ttl_minutes: !input ttl_minutes + hold_minutes: !input hold_minutes + engine: !input engine + +triggers: + - trigger: state + entity_id: !input media_player + to: playing + id: started + - trigger: state + entity_id: !input media_player + attribute: media_title + id: title + +conditions: + - condition: template + value_template: "{{ is_state(media_player, 'playing') }}" + # Starting playback with a new title fires both triggers: count it once, as 'started'. + - condition: template + value_template: "{{ trigger.id == 'started' or trigger.from_state.state == 'playing' }}" + - condition: template + value_template: >- + {{ state_attr(media_player, 'media_content_type') in ['movie', 'tvshow', 'episode'] }} + - condition: template + value_template: >- + {{ (state_attr(media_player, 'media_series_title') or state_attr(media_player, 'media_title') + or '') | string | trim != '' }} + +actions: + - alias: Show the poster + action: smart_frame_engine.show_media_poster + data: >- + {{ dict({ + 'config_entry_id': engine, + 'media_player': media_player, + 'use_media_player_picture': use_media_player_picture, + 'language': language | trim, + 'ttl_minutes': ttl_minutes or none, + 'hold_minutes': hold_minutes or none, + }.items() | rejectattr('1', 'in', ['', none]) | list) }} diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py new file mode 100644 index 0000000..c7e1766 --- /dev/null +++ b/tests/test_blueprints.py @@ -0,0 +1,854 @@ +"""Tests for the automation blueprints. + +The blueprints are loaded with Home Assistant's own blueprint models, then run as real +automations whose ``smart_frame_engine`` services are replaced by recorders that validate the +call with the integration's real service schemas. +""" + +from __future__ import annotations + +from collections.abc import AsyncGenerator +from datetime import UTC, datetime +import json +from pathlib import Path +import re +import shutil +from typing import Any +from urllib.parse import quote + +from freezegun.api import FrozenDateTimeFactory +from homeassistant.components import automation +from homeassistant.components.blueprint import models +from homeassistant.components.blueprint.schemas import BLUEPRINT_SCHEMA +from homeassistant.const import EVENT_HOMEASSISTANT_STARTED +from homeassistant.core import HomeAssistant, ServiceCall +from homeassistant.setup import async_setup_component +from homeassistant.util.yaml import load_yaml +import pytest +from pytest_homeassistant_custom_component.common import async_fire_time_changed +import yaml + +from custom_components.smart_frame_engine import services +from custom_components.smart_frame_engine.const import DOMAIN + +ROOT = Path(__file__).resolve().parents[1] +BLUEPRINTS = ROOT / "blueprints" / "automation" / "smart_frame_engine" +BLUEPRINT_FILES = sorted(BLUEPRINTS.glob("*.yaml")) +SOURCE_URL = "https://github.com/ant1fr/Smart-Frame-Engine-HA/blob/main/blueprints/automation/smart_frame_engine/" + +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, + services.SERVICE_SHOW_NOW_PLAYING: services.SHOW_NOW_PLAYING_SCHEMA, + services.SERVICE_SHOW_MEDIA_POSTER: services.SHOW_MEDIA_POSTER_SCHEMA, +} + + +# -- Static checks --------------------------------------------------------------------- + + +def test_there_are_five_blueprints() -> None: + """Weather, presence, title card, music and TV.""" + assert [path.name for path in BLUEPRINT_FILES] == [ + "ambient_presence.yaml", + "ambient_weather.yaml", + "now_playing_cover.yaml", + "title_card.yaml", + "tv_poster.yaml", + ] + + +@pytest.mark.parametrize("path", BLUEPRINT_FILES, ids=lambda p: p.stem) +def test_blueprint_is_valid_and_documented(path: Path) -> None: + """Home Assistant accepts it, and it carries what an importable blueprint needs.""" + blueprint = models.Blueprint( + load_yaml(str(path)), expected_domain="automation", schema=BLUEPRINT_SCHEMA + ) + meta = blueprint.metadata + + assert meta["name"].startswith("Smart Frame Engine - ") + assert meta["description"] + assert meta["domain"] == "automation" + assert meta["source_url"] == f"{SOURCE_URL}{path.name}" + hacs = json.loads((ROOT / "hacs.json").read_text(encoding="utf-8")) + assert meta["homeassistant"]["min_version"] == hacs["homeassistant"] + assert blueprint.validate() is None + for name, definition in blueprint.inputs.items(): + assert definition["name"], name + assert definition["selector"], name + + +@pytest.mark.parametrize("path", BLUEPRINT_FILES, ids=lambda p: p.stem) +def test_blueprint_only_uses_existing_services_and_fields(path: Path) -> None: + """Every service and every field sent exists in services.yaml and in the real schema.""" + definitions = yaml.safe_load( + (ROOT / "custom_components" / "smart_frame_engine" / "services.yaml").read_text( + encoding="utf-8" + ) + ) + data = load_yaml(str(path)) + calls = [ + step for step in data["actions"] if str(step.get("action", "")).startswith(f"{DOMAIN}.") + ] + assert calls, "the blueprint calls no smart_frame_engine service" + for step in calls: + service = step["action"].split(".", 1)[1] + assert service in definitions + sent = set(re.findall(r"'(\w+)':", step["data"])) + assert sent + assert sent <= {str(key) for key in SCHEMAS[service].schema}, (service, sent) + assert sent <= set(definitions[service]["fields"]), (service, sent) + + +def test_readme_lists_every_blueprint() -> None: + """Each blueprint has its import link in the README.""" + readme = (ROOT / "README.md").read_text(encoding="utf-8") + for path in BLUEPRINT_FILES: + link = "blueprint_url=" + quote(f"{SOURCE_URL}{path.name}", safe="") + assert link in readme, path.name + + +# -- Running the blueprints ------------------------------------------------------------ + + +@pytest.fixture +async def calls( + hass: HomeAssistant, tmp_path: Path +) -> AsyncGenerator[list[tuple[str, dict[str, Any]]]]: + """Install the blueprints, and record every ``smart_frame_engine`` service call.""" + shutil.copytree(BLUEPRINTS, tmp_path / "blueprints" / "automation" / "smart_frame_engine") + hass.config.config_dir = str(tmp_path) + + recorded: list[tuple[str, dict[str, Any]]] = [] + + def _recorder(name: str) -> Any: + async def _record(call: ServiceCall) -> None: + recorded.append((name, dict(call.data))) + + return _record + + for name, schema in SCHEMAS.items(): + hass.services.async_register(DOMAIN, name, _recorder(name), schema=schema) + yield recorded + + # Stop the automations: their time triggers would otherwise outlive the test. + for entity_id in hass.states.async_entity_ids(automation.DOMAIN): + await hass.services.async_call( + automation.DOMAIN, "turn_off", {"entity_id": entity_id}, blocking=True + ) + + +async def _setup(hass: HomeAssistant, blueprint: str, inputs: dict[str, Any]) -> None: + assert await async_setup_component( + hass, + "automation", + { + "automation": { + "alias": f"test {blueprint}", + "use_blueprint": { + "path": f"smart_frame_engine/{blueprint}.yaml", + "input": inputs, + }, + } + }, + ) + await hass.async_block_till_done() + assert hass.states.async_entity_ids(automation.DOMAIN), "the automation was not created" + + +async def _set( + hass: HomeAssistant, entity_id: str, state: str, attributes: dict[str, Any] | None = None +) -> None: + hass.states.async_set(entity_id, state, attributes or {}) + await hass.async_block_till_done() + + +# -- Weather --------------------------------------------------------------------------- + +WEATHER = "weather.home" + + +async def test_weather_follows_the_entity( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """A new condition is sent with the default lifetime and no engine.""" + await _set(hass, WEATHER, "sunny", {"temperature": 20}) + await _setup(hass, "ambient_weather", {"weather_entity": WEATHER}) + + await _set(hass, WEATHER, "rainy", {"temperature": 20}) + + assert calls == [("set_ambient_context", {"weather": "rainy", "ttl_minutes": 180})] + + +async def test_weather_ignores_attribute_changes( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Temperature and the like change all the time: only the condition counts.""" + await _set(hass, WEATHER, "sunny", {"temperature": 20}) + await _setup(hass, "ambient_weather", {"weather_entity": WEATHER}) + + await _set(hass, WEATHER, "sunny", {"temperature": 21}) + + assert calls == [] + + +@pytest.mark.parametrize("state", ["unknown", "unavailable"]) +async def test_weather_ignores_unusable_states( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]], state: str +) -> None: + """The engine is never told that the weather is 'unavailable'.""" + await _set(hass, WEATHER, "sunny") + await _setup(hass, "ambient_weather", {"weather_entity": WEATHER}) + + await _set(hass, WEATHER, state) + + assert calls == [] + + +async def test_weather_inputs(hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]]) -> None: + """The engine and the lifetime are forwarded.""" + await _set(hass, WEATHER, "sunny") + await _setup( + hass, + "ambient_weather", + {"weather_entity": WEATHER, "ttl_minutes": 90, "engine": "abc123"}, + ) + + await _set(hass, WEATHER, "snowy") + + assert calls == [ + ( + "set_ambient_context", + {"config_entry_id": "abc123", "weather": "snowy", "ttl_minutes": 90}, + ) + ] + + +async def test_weather_is_sent_at_startup( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """When Home Assistant starts, the current weather is sent.""" + await _set(hass, WEATHER, "cloudy") + await _setup(hass, "ambient_weather", {"weather_entity": WEATHER}) + + hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) + await hass.async_block_till_done() + + assert calls == [("set_ambient_context", {"weather": "cloudy", "ttl_minutes": 180})] + + +async def test_weather_is_renewed_every_half_hour( + hass: HomeAssistant, + calls: list[tuple[str, dict[str, Any]]], + freezer: FrozenDateTimeFactory, +) -> None: + """The value is re-sent so it does not expire while the weather stays the same.""" + freezer.move_to(datetime(2026, 11, 20, 12, 5, 0, tzinfo=UTC)) + await _set(hass, WEATHER, "cloudy") + await _setup(hass, "ambient_weather", {"weather_entity": WEATHER}) + + async_fire_time_changed(hass, datetime(2026, 11, 20, 12, 15, 0, tzinfo=UTC)) + await hass.async_block_till_done() + assert calls == [] + + async_fire_time_changed(hass, datetime(2026, 11, 20, 12, 30, 1, tzinfo=UTC)) + await hass.async_block_till_done() + assert calls == [("set_ambient_context", {"weather": "cloudy", "ttl_minutes": 180})] + + +# -- Presence -------------------------------------------------------------------------- + + +def _persons(hass: HomeAssistant, **states: str) -> list[str]: + """Create person entities named after their key; returns their entity ids.""" + entity_ids = [] + for name, state in states.items(): + entity_id = f"person.{name}" + hass.states.async_set(entity_id, state, {"friendly_name": name.capitalize()}) + entity_ids.append(entity_id) + return entity_ids + + +async def test_presence_lists_the_people_at_home( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Names of the people at home, in the order they were chosen.""" + people = _persons(hass, alice="home", bob="not_home", carol="home") + await _setup(hass, "ambient_presence", {"persons": people}) + + await _set(hass, "person.bob", "home", {"friendly_name": "Bob"}) + + assert calls == [ + ("set_ambient_context", {"presence": ["Alice", "Bob", "Carol"], "ttl_minutes": 180}) + ] + + +async def test_presence_is_emptied_when_everyone_leaves( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """An empty list is sent (the engine clears the field).""" + people = _persons(hass, alice="home") + await _setup(hass, "ambient_presence", {"persons": people}) + + await _set(hass, "person.alice", "not_home", {"friendly_name": "Alice"}) + + assert calls == [("set_ambient_context", {"presence": [], "ttl_minutes": 180})] + + +async def test_presence_follows_a_single_person( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """One person arriving gives a one-element list; other zones count as away.""" + people = _persons(hass, alice="work") + await _setup(hass, "ambient_presence", {"persons": people}) + + await _set(hass, "person.alice", "home", {"friendly_name": "Alice"}) + + assert calls == [("set_ambient_context", {"presence": ["Alice"], "ttl_minutes": 180})] + + +async def test_presence_respects_the_engine_limits( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """At most 20 names, each cut to 80 characters (the schema would refuse more).""" + people = [] + for index in range(25): + entity_id = f"person.p{index:02}" + name = ("x" * 90) if index == 0 else f"Person {index}" + hass.states.async_set(entity_id, "home", {"friendly_name": name}) + people.append(entity_id) + await _setup(hass, "ambient_presence", {"persons": people}) + + hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) + await hass.async_block_till_done() + + ((_, data),) = calls + assert len(data["presence"]) == 20 + assert data["presence"][0] == "x" * 80 + assert data["presence"][1] == "Person 1" + + +async def test_presence_forwards_the_engine_and_lifetime( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """The engine and the lifetime are forwarded.""" + people = _persons(hass, alice="home") + await _setup( + hass, + "ambient_presence", + {"persons": people, "engine": "abc123", "ttl_minutes": 600}, + ) + + hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) + await hass.async_block_till_done() + + assert calls == [ + ( + "set_ambient_context", + {"config_entry_id": "abc123", "presence": ["Alice"], "ttl_minutes": 600}, + ) + ] + + +async def test_presence_ignores_attribute_changes( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Person entities update their coordinates constantly: that is not an arrival.""" + people = _persons(hass, alice="home") + await _setup(hass, "ambient_presence", {"persons": people}) + + await _set(hass, "person.alice", "home", {"friendly_name": "Alice", "latitude": 1.5}) + + assert calls == [] + + +async def test_presence_is_renewed_every_half_hour( + hass: HomeAssistant, + calls: list[tuple[str, dict[str, Any]]], + freezer: FrozenDateTimeFactory, +) -> None: + """The list is re-sent so it does not expire while nothing changes.""" + freezer.move_to(datetime(2026, 11, 20, 12, 5, 0, tzinfo=UTC)) + people = _persons(hass, alice="home") + await _setup(hass, "ambient_presence", {"persons": people}) + + async_fire_time_changed(hass, datetime(2026, 11, 20, 12, 15, 0, tzinfo=UTC)) + await hass.async_block_till_done() + assert calls == [] + + async_fire_time_changed(hass, datetime(2026, 11, 20, 12, 30, 1, tzinfo=UTC)) + await hass.async_block_till_done() + assert calls == [("set_ambient_context", {"presence": ["Alice"], "ttl_minutes": 180})] + + +# -- Title card ------------------------------------------------------------------------ + +DOOR = "input_boolean.front_door" +DOOR_TRIGGER = [{"trigger": "state", "entity_id": DOOR, "to": "on"}] + + +async def _open_door(hass: HomeAssistant) -> None: + await _set(hass, DOOR, "off", {"friendly_name": "Front door"}) + await _set(hass, DOOR, "on", {"friendly_name": "Front door"}) + + +async def test_title_card_with_the_defaults( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Only the title is required; empty texts are left out.""" + await _set(hass, DOOR, "off") + await _setup(hass, "title_card", {"trigger": DOOR_TRIGGER, "title": "Welcome"}) + + await _set(hass, DOOR, "on") + + assert calls == [ + ( + "send_title_card", + {"title": "Welcome", "accent": "red", "ephemeral": True, "ttl_minutes": 60}, + ) + ] + + +async def test_title_card_templates_use_the_trigger( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Title, subtitle and caption are rendered with the trigger's data.""" + await _set(hass, DOOR, "off", {"friendly_name": "Front door"}) + await _setup( + hass, + "title_card", + { + "trigger": DOOR_TRIGGER, + "title": "{{ trigger.to_state.name }} is open", + "subtitle": "since {{ trigger.to_state.state }}", + "caption": "check it", + }, + ) + + await _set(hass, DOOR, "on", {"friendly_name": "Front door"}) + + ((name, data),) = calls + assert name == "send_title_card" + assert data["title"] == "Front door is open" + assert data["subtitle"] == "since on" + assert data["caption"] == "check it" + + +async def test_title_card_every_input( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """All inputs reach the service.""" + await _set(hass, DOOR, "off") + await _setup( + hass, + "title_card", + { + "trigger": DOOR_TRIGGER, + "title": "Dinner", + "subtitle": "is ready", + "caption": "7 pm", + "accent": "green", + "ephemeral": True, + "ttl_minutes": 15, + "hold_minutes": 30, + "engine": "abc123", + }, + ) + + await _set(hass, DOOR, "on") + + assert calls == [ + ( + "send_title_card", + { + "config_entry_id": "abc123", + "title": "Dinner", + "subtitle": "is ready", + "caption": "7 pm", + "accent": "green", + "ephemeral": True, + "ttl_minutes": 15, + "hold_minutes": 30, + }, + ) + ] + + +async def test_title_card_that_is_not_temporary_sends_no_duration( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """The duration only applies to temporary cards.""" + await _set(hass, DOOR, "off") + await _setup( + hass, + "title_card", + {"trigger": DOOR_TRIGGER, "title": "Sticky", "ephemeral": False, "ttl_minutes": 15}, + ) + + await _set(hass, DOOR, "on") + + assert calls == [("send_title_card", {"title": "Sticky", "accent": "red", "ephemeral": False})] + + +async def test_title_card_texts_are_cut_to_the_engine_limit( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """A long templated text is cut to 200 characters instead of failing.""" + await _set(hass, DOOR, "off") + await _setup( + hass, + "title_card", + { + "trigger": DOOR_TRIGGER, + "title": "t" * 250, + "subtitle": "s" * 250, + "caption": "c" * 250, + }, + ) + + await _set(hass, DOOR, "on") + + ((_, data),) = calls + assert (len(data["title"]), len(data["subtitle"]), len(data["caption"])) == (200, 200, 200) + + +async def test_title_card_accepts_any_trigger( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """The trigger input is whatever the user picks, here an event.""" + await _setup( + hass, + "title_card", + {"trigger": [{"trigger": "event", "event_type": "doorbell"}], "title": "Ding dong"}, + ) + + hass.bus.async_fire("doorbell") + await hass.async_block_till_done() + + assert [name for name, _ in calls] == ["send_title_card"] + + +# -- Music ----------------------------------------------------------------------------- + +SPEAKER = "media_player.kitchen" +SONG = { + "media_artist": "Daft Punk", + "media_album_name": "Discovery", + "media_title": "One More Time", + "media_duration": 320, + "media_position": 0, +} +SHOW_COVER = ("show_now_playing", {"media_player": SPEAKER, "use_media_player_picture": True}) + + +async def test_music_shows_the_cover_when_playback_starts( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """The player is passed on: the service reads the track from it.""" + await _set(hass, SPEAKER, "idle") + await _setup(hass, "now_playing_cover", {"media_player": SPEAKER}) + + await _set(hass, SPEAKER, "playing", SONG) + + assert calls[-1] == SHOW_COVER + + +async def test_music_follows_track_changes( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """A new title while playing shows the new track.""" + await _set(hass, SPEAKER, "playing", SONG) + await _setup(hass, "now_playing_cover", {"media_player": SPEAKER}) + + await _set(hass, SPEAKER, "playing", SONG | {"media_title": "Aerodynamic"}) + + assert calls == [SHOW_COVER] + + +async def test_music_ignores_position_updates( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """The position changes every few seconds: that must not call the engine.""" + await _set(hass, SPEAKER, "playing", SONG) + await _setup(hass, "now_playing_cover", {"media_player": SPEAKER}) + + for position in (5, 10, 15): + await _set(hass, SPEAKER, "playing", SONG | {"media_position": position}) + + assert calls == [] + + +@pytest.mark.parametrize("state", ["paused", "idle", "off", "unavailable"]) +async def test_music_only_shows_while_playing( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]], state: str +) -> None: + """A title change on a player that is not playing shows nothing.""" + await _set(hass, SPEAKER, state, SONG) + await _setup(hass, "now_playing_cover", {"media_player": SPEAKER}) + + await _set(hass, SPEAKER, state, SONG | {"media_title": "Aerodynamic"}) + + assert calls == [] + + +@pytest.mark.parametrize("artist", [None, "", " "]) +async def test_music_needs_an_artist( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]], artist: str | None +) -> None: + """A stream that reports no artist is skipped (the service would refuse it).""" + await _set(hass, SPEAKER, "idle") + await _setup(hass, "now_playing_cover", {"media_player": SPEAKER}) + + await _set(hass, SPEAKER, "playing", SONG | {"media_artist": artist}) + + assert calls == [] + + +async def test_music_can_leave_the_cover_to_the_engine( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """With 'send the player's cover' off, the engine looks the cover up itself.""" + await _set(hass, SPEAKER, "idle") + await _setup(hass, "now_playing_cover", {"media_player": SPEAKER, "send_artwork": False}) + + await _set(hass, SPEAKER, "playing", SONG) + + assert calls[-1] == ( + "show_now_playing", + {"media_player": SPEAKER, "use_media_player_picture": False}, + ) + + +@pytest.mark.parametrize(("show_title", "expected"), [("", None), ("yes", True), ("no", False)]) +async def test_music_show_title_choice( + hass: HomeAssistant, + calls: list[tuple[str, dict[str, Any]]], + show_title: str, + expected: bool | None, +) -> None: + """Engine default, yes and no; 'no' is sent as false, not dropped.""" + await _set(hass, SPEAKER, "idle") + await _setup(hass, "now_playing_cover", {"media_player": SPEAKER, "show_title": show_title}) + + await _set(hass, SPEAKER, "playing", SONG) + + data = calls[-1][1] + if expected is None: + assert "show_title" not in data + else: + assert data["show_title"] is expected + + +async def test_music_every_input( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Style, protection, duration and engine are forwarded.""" + await _set(hass, SPEAKER, "idle") + await _setup( + hass, + "now_playing_cover", + { + "media_player": SPEAKER, + "style": "vinyl", + "show_title": "yes", + "hold_minutes": 20, + "ttl_seconds": 240, + "engine": "abc123", + }, + ) + + await _set(hass, SPEAKER, "playing", SONG) + + assert calls[-1] == ( + "show_now_playing", + { + "config_entry_id": "abc123", + "media_player": SPEAKER, + "use_media_player_picture": True, + "style": "vinyl", + "show_title": True, + "hold_minutes": 20, + "ttl_seconds": 240, + }, + ) + + +# -- TV -------------------------------------------------------------------------------- + +TV = "media_player.living_room_tv" +MOVIE = {"media_content_type": "movie", "media_title": "Blade Runner"} +SHOW_POSTER = ("show_media_poster", {"media_player": TV, "use_media_player_picture": True}) + + +async def test_tv_shows_the_poster_of_a_movie( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """The player is passed on: the service reads the title from it.""" + await _set(hass, TV, "idle") + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set(hass, TV, "playing", MOVIE) + + assert calls[-1] == SHOW_POSTER + + +@pytest.mark.parametrize("content_type", ["movie", "tvshow", "episode"]) +async def test_tv_accepts_movies_series_and_episodes( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]], content_type: str +) -> None: + """These three content types are shown.""" + await _set(hass, TV, "idle") + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set(hass, TV, "playing", {"media_content_type": content_type, "media_title": "X"}) + + assert calls[-1] == SHOW_POSTER + + +@pytest.mark.parametrize("content_type", ["music", "video", "channel", "app", None]) +async def test_tv_ignores_other_content( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]], content_type: str | None +) -> None: + """Music, channels, apps and untyped video are not looked up on TMDB.""" + await _set(hass, TV, "idle") + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set(hass, TV, "playing", {"media_content_type": content_type, "media_title": "X"}) + + assert calls == [] + + +async def test_tv_follows_title_changes( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """The next episode or film shows its poster.""" + await _set(hass, TV, "playing", MOVIE) + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set(hass, TV, "playing", MOVIE | {"media_title": "Dune"}) + + assert calls == [SHOW_POSTER] + + +async def test_tv_ignores_position_updates( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Playback progress does not call the engine.""" + await _set(hass, TV, "playing", MOVIE) + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set(hass, TV, "playing", MOVIE | {"media_position": 30}) + + assert calls == [] + + +@pytest.mark.parametrize("state", ["paused", "idle", "off"]) +async def test_tv_only_shows_while_playing( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]], state: str +) -> None: + """A title change while not playing shows nothing.""" + await _set(hass, TV, state, MOVIE) + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set(hass, TV, state, MOVIE | {"media_title": "Dune"}) + + assert calls == [] + + +async def test_tv_needs_a_title( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """A player that reports no title has nothing to look up.""" + await _set(hass, TV, "idle") + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set(hass, TV, "playing", {"media_content_type": "movie", "media_title": " "}) + + assert calls == [] + + +async def test_tv_series_title_is_enough( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """An episode without its own title still has its series.""" + await _set(hass, TV, "idle") + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set( + hass, + TV, + "playing", + {"media_content_type": "episode", "media_series_title": "Severance"}, + ) + + assert calls[-1] == SHOW_POSTER + + +async def test_tv_can_skip_the_fallback_picture( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """The player's picture is not sent when the fallback is turned off.""" + await _set(hass, TV, "idle") + await _setup(hass, "tv_poster", {"media_player": TV, "use_media_player_picture": False}) + + await _set(hass, TV, "playing", MOVIE) + + assert calls[-1] == ( + "show_media_poster", + {"media_player": TV, "use_media_player_picture": False}, + ) + + +async def test_tv_every_input(hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]]) -> None: + """Language (trimmed), duration, protection and engine are forwarded.""" + await _set(hass, TV, "idle") + await _setup( + hass, + "tv_poster", + { + "media_player": TV, + "language": " fr-CA ", + "ttl_minutes": 120, + "hold_minutes": 10, + "engine": "abc123", + }, + ) + + await _set(hass, TV, "playing", MOVIE) + + assert calls[-1] == ( + "show_media_poster", + { + "config_entry_id": "abc123", + "media_player": TV, + "use_media_player_picture": True, + "language": "fr-CA", + "ttl_minutes": 120, + "hold_minutes": 10, + }, + ) + + +async def test_music_a_new_track_that_also_starts_playback_is_not_sent_twice( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Starting playback with a new title fires both triggers; the second run replaces the first.""" + await _set(hass, SPEAKER, "idle", SONG) + await _setup(hass, "now_playing_cover", {"media_player": SPEAKER}) + + await _set(hass, SPEAKER, "playing", SONG | {"media_title": "Aerodynamic"}) + + assert calls == [SHOW_COVER] + + +async def test_tv_a_new_title_that_also_starts_playback_is_not_sent_twice( + hass: HomeAssistant, calls: list[tuple[str, dict[str, Any]]] +) -> None: + """Starting playback with a new title fires both triggers; it is counted once.""" + await _set(hass, TV, "idle", MOVIE) + await _setup(hass, "tv_poster", {"media_player": TV}) + + await _set(hass, TV, "playing", MOVIE | {"media_title": "Dune"}) + + assert calls == [SHOW_POSTER]