From e65936ad412e3f507ec782caec877c9524663685 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Thu, 19 Nov 2026 14:23:13 +0100 Subject: [PATCH 1/3] chore: add tooling, CI and HACS metadata - pyproject.toml: ruff, mypy (strict) and pytest (asyncio_mode=auto) for Python 3.13.2+ (HA 2026.1 minimum); CI and tests run on Python 3.14 - CI: hassfest, HACS (category integration), ruff check/format, mypy, pytest - hacs.json targeting Home Assistant 2026.1.0 - .gitattributes forces LF so strings.json and en.json stay byte-identical - CLAUDE.md: correct the Python target, document instance_id as unique_id and that pytest needs Linux/macOS/WSL (HA's test plugin imports fcntl) Co-Authored-By: Claude Sonnet 5.5 --- .gitattributes | 3 +++ .github/workflows/ci.yml | 55 ++++++++++++++++++++++++++++++++++++++++ CLAUDE.md | 7 ++--- hacs.json | 5 ++++ pyproject.toml | 48 +++++++++++++++++++++++++++++++++++ requirements_test.txt | 3 +++ 6 files changed, 118 insertions(+), 3 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/workflows/ci.yml create mode 100644 hacs.json create mode 100644 pyproject.toml create mode 100644 requirements_test.txt diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..46526f6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +* text=auto eol=lf +*.png binary +*.jpg binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..30dcf15 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,55 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + schedule: + - cron: "0 5 * * *" + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + hassfest: + name: Hassfest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: home-assistant/actions/hassfest@master + + hacs: + name: HACS + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: hacs/action@22.5.0 + with: + category: integration + # The brand assets are only required for the HACS default repository list. + ignore: brands + + quality: + name: Ruff, mypy, pytest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: requirements_test.txt + - name: Install dependencies + run: pip install -r requirements_test.txt + - name: Ruff lint + run: ruff check . + - name: Ruff format + run: ruff format --check . + - name: mypy + run: mypy custom_components + - name: pytest + run: pytest diff --git a/CLAUDE.md b/CLAUDE.md index 8583a37..46dbf05 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,10 +3,10 @@ ## Project Overview Official Home Assistant custom integration (`smart_frame_engine`) for **Smart Frame Engine** (`[https://github.com/ant1fr/Smart-Frame-Engine](https://github.com/ant1fr/Smart-Frame-Engine)`), installable via HACS (Home Assistant Community Store) and manual installation. -- **Target Home Assistant Core:** 2026.x+ (Python 3.12+) +- **Target Home Assistant Core:** 2026.1.0+ (Python 3.13.2+; CI and local tests run on Python 3.14, which latest HA and `pytest-homeassistant-custom-component` require) - **Integration Domain:** `smart_frame_engine` - **IoT Class:** `local_polling` (with Zeroconf mDNS discovery on `_smartframe._tcp.local.`) -- **Supported Server Contract:** `SUPPORTED_API_VERSION = 1` +- **Supported Server Contract:** `SUPPORTED_API_VERSION = 1` (contract v1.1: the engine's `instance_id` from `GET /api/health` / Zeroconf TXT is the config entry `unique_id` and the `DeviceInfo` identifier) - **Upstream API Contract (Single Source of Truth):** - Human-readable contract: `[https://github.com/ant1fr/Smart-Frame-Engine/blob/main/docs/API_CONTRACT.md](https://github.com/ant1fr/Smart-Frame-Engine/blob/main/docs/API_CONTRACT.md)` - Machine-readable OpenAPI schema: `[https://github.com/ant1fr/Smart-Frame-Engine/blob/main/docs/openapi.json](https://github.com/ant1fr/Smart-Frame-Engine/blob/main/docs/openapi.json)` @@ -33,6 +33,7 @@ Official Home Assistant custom integration (`smart_frame_engine`) for **Smart Fr - `tests/` — `pytest` + `pytest-homeassistant-custom-component` - `hacs.json` — HACS metadata - `pyproject.toml` — `ruff`, `mypy`, `pytest` configuration +- `requirements_test.txt` — test/lint dependencies (`pytest-homeassistant-custom-component`, `ruff`, `mypy`) ## Development, Quality & GitHub Rules (CRITICAL) @@ -66,4 +67,4 @@ Official Home Assistant custom integration (`smart_frame_engine`) for **Smart Fr - `ruff check .` - `ruff format --check .` - `mypy custom_components` -- `pytest` \ No newline at end of file +- `pytest` — HA's test plugin imports `fcntl`, so run it on Linux/macOS/WSL (not native Windows); `ruff` and `mypy` run anywhere diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..f791faa --- /dev/null +++ b/hacs.json @@ -0,0 +1,5 @@ +{ + "name": "Smart Frame Engine", + "render_readme": true, + "homeassistant": "2026.1.0" +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e314e9a --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,48 @@ +[project] +name = "smart-frame-engine-ha" +version = "1.0.0" +description = "Home Assistant custom integration for Smart Frame Engine" +readme = "README.md" +license = { text = "MIT" } +requires-python = ">=3.13.2" + +[tool.ruff] +target-version = "py313" +line-length = 100 +extend-exclude = [".venv"] + +[tool.ruff.lint] +select = [ + "ASYNC", + "B", + "C4", + "E", + "F", + "I", + "PT", + "RUF", + "SIM", + "UP", + "W", +] + +[tool.ruff.lint.isort] +known-first-party = ["custom_components"] +force-sort-within-sections = true +combine-as-imports = true + +[tool.mypy] +python_version = "3.13" +strict = true +warn_unreachable = true +files = ["custom_components"] + +[[tool.mypy.overrides]] +module = ["custom_components.*"] +disallow_any_generics = true + +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] +pythonpath = ["."] +addopts = "-ra" diff --git a/requirements_test.txt b/requirements_test.txt new file mode 100644 index 0000000..d97db33 --- /dev/null +++ b/requirements_test.txt @@ -0,0 +1,3 @@ +pytest-homeassistant-custom-component +ruff +mypy From e4f8a5456229424a9cdd318854431c599ce136a5 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Thu, 19 Nov 2026 14:23:13 +0100 Subject: [PATCH 2/3] feat: add API client, config flow, coordinator and diagnostics Foundation of the smart_frame_engine integration, grounded in the Smart Frame Engine API contract v1.1 (instance_id / instance_name). - api.py: typed async client on HA's shared session; health handshake, status, config + Family Mode, ambient context (TTL, clear by field), force refresh, title card, wake-up, push and current/preview images - const.py: SUPPORTED_API_VERSION and all 18 capability flags - config_flow.py: Zeroconf (open vs key/password), manual setup, reauth, options flow (polling interval); instance_id is the unique_id so DHCP address changes update the existing entry - coordinator.py: health + status (+ ambient) polling, compatibility check on every refresh with a persistent Repair issue that clears itself, capability cache, shared DeviceInfo - entity.py, __init__.py, diagnostics.py (api_key redacted) - strings.json / translations en + fr Co-Authored-By: Claude Sonnet 5.5 --- .../smart_frame_engine/__init__.py | 46 + custom_components/smart_frame_engine/api.py | 917 ++++++++++++++++++ .../smart_frame_engine/config_flow.py | 346 +++++++ custom_components/smart_frame_engine/const.py | 94 ++ .../smart_frame_engine/coordinator.py | 199 ++++ .../smart_frame_engine/diagnostics.py | 47 + .../smart_frame_engine/entity.py | 26 + .../smart_frame_engine/manifest.json | 16 + .../smart_frame_engine/strings.json | 104 ++ .../smart_frame_engine/translations/en.json | 104 ++ .../smart_frame_engine/translations/fr.json | 104 ++ 11 files changed, 2003 insertions(+) create mode 100644 custom_components/smart_frame_engine/__init__.py create mode 100644 custom_components/smart_frame_engine/api.py create mode 100644 custom_components/smart_frame_engine/config_flow.py create mode 100644 custom_components/smart_frame_engine/const.py create mode 100644 custom_components/smart_frame_engine/coordinator.py create mode 100644 custom_components/smart_frame_engine/diagnostics.py create mode 100644 custom_components/smart_frame_engine/entity.py create mode 100644 custom_components/smart_frame_engine/manifest.json create mode 100644 custom_components/smart_frame_engine/strings.json create mode 100644 custom_components/smart_frame_engine/translations/en.json create mode 100644 custom_components/smart_frame_engine/translations/fr.json diff --git a/custom_components/smart_frame_engine/__init__.py b/custom_components/smart_frame_engine/__init__.py new file mode 100644 index 0000000..f14034a --- /dev/null +++ b/custom_components/smart_frame_engine/__init__.py @@ -0,0 +1,46 @@ +"""The Smart Frame Engine integration.""" + +from __future__ import annotations + +from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT, Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers.aiohttp_client import async_get_clientsession + +from .api import SmartFrameClient +from .const import CONF_PATH, DEFAULT_PATH +from .coordinator import ( + SmartFrameConfigEntry, + SmartFrameCoordinator, + async_delete_compatibility_issue, +) + +# Entity platforms arrive in a later milestone; the coordinator and device already work. +PLATFORMS: list[Platform] = [] + + +async def async_setup_entry(hass: HomeAssistant, entry: SmartFrameConfigEntry) -> bool: + """Set up one engine from a config entry.""" + client = SmartFrameClient( + async_get_clientsession(hass), + entry.data[CONF_HOST], + entry.data[CONF_PORT], + entry.data.get(CONF_PATH, DEFAULT_PATH), + entry.data.get(CONF_API_KEY), + ) + coordinator = SmartFrameCoordinator(hass, entry, client) + # Raises ConfigEntryNotReady (unreachable / incompatible) or ConfigEntryAuthFailed (401). + await coordinator.async_config_entry_first_refresh() + entry.runtime_data = coordinator + + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: SmartFrameConfigEntry) -> bool: + """Unload a config entry.""" + return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + + +async def async_remove_entry(hass: HomeAssistant, entry: SmartFrameConfigEntry) -> None: + """Drop the compatibility Repair issue together with the entry.""" + async_delete_compatibility_issue(hass, entry.entry_id) diff --git a/custom_components/smart_frame_engine/api.py b/custom_components/smart_frame_engine/api.py new file mode 100644 index 0000000..3a676c5 --- /dev/null +++ b/custom_components/smart_frame_engine/api.py @@ -0,0 +1,917 @@ +"""Async client and typed models for the Smart Frame Engine HTTP API. + +Every path, method, parameter and field here is taken from ``docs/API_CONTRACT.md`` and +``docs/openapi.json`` of https://github.com/ant1fr/Smart-Frame-Engine (contract v1.1). +Unknown response fields and unknown capability flags are ignored on purpose (contract +section 1, "Graceful degradation"). + +The client never creates its own session: Home Assistant's shared one is injected. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from datetime import datetime +import enum +import json +from typing import Any, Final, Literal, TypeIs + +import aiohttp +from yarl import URL + +from .const import ( + AUTH_OPEN, + DEFAULT_PATH, + REQUEST_TIMEOUT, + SUPPORTED_API_VERSION, +) + +# -------------------------------------------------------------------------------------- +# Exceptions +# -------------------------------------------------------------------------------------- + + +class SmartFrameError(Exception): + """Base class for every error raised by this client.""" + + +class SmartFrameConnectionError(SmartFrameError): + """The engine could not be reached, timed out, or did not answer like an engine.""" + + +class SmartFrameAuthError(SmartFrameError): + """HTTP 401: credentials are missing or wrong.""" + + +class SmartFrameApiError(SmartFrameError): + """The engine answered with an error status (other than 401).""" + + def __init__(self, status: int, detail: str) -> None: + """Store the HTTP status and the engine's ``detail`` message.""" + super().__init__(f"HTTP {status}: {detail}") + self.status = status + self.detail = detail + + +class SmartFrameValidationError(SmartFrameApiError): + """HTTP 422: the engine rejected the request payload.""" + + +UpdateTarget = Literal["integration", "server"] + + +class SmartFrameIncompatibleError(SmartFrameError): + """The engine speaks a contract version this integration cannot use.""" + + def __init__(self, api_version: int, min_api_version: int, update_target: UpdateTarget) -> None: + """Store both sides of the mismatch and which one must be updated.""" + super().__init__( + f"Engine speaks contract {min_api_version}..{api_version}, " + f"integration needs {SUPPORTED_API_VERSION} (update the {update_target})" + ) + self.api_version = api_version + self.min_api_version = min_api_version + self.update_target: UpdateTarget = update_target + + +# -------------------------------------------------------------------------------------- +# Compatibility handshake +# -------------------------------------------------------------------------------------- + + +def compatibility_target( + api_version: int, min_api_version: int, supported: int = SUPPORTED_API_VERSION +) -> UpdateTarget | None: + """Return which side must be updated, or ``None`` when the versions are compatible. + + Contract rule: compatible iff ``min_api_version <= supported <= api_version``. + ``supported > api_version`` means the engine is older than this integration. + ``supported < min_api_version`` means this integration is older than the engine. + """ + if supported > api_version: + return "server" + if supported < min_api_version: + return "integration" + return None + + +# -------------------------------------------------------------------------------------- +# Tolerant JSON helpers +# -------------------------------------------------------------------------------------- + + +def _mapping(value: Any) -> Mapping[str, Any]: + return value if isinstance(value, Mapping) else {} + + +def _str(value: Any) -> str | None: + return value if isinstance(value, str) else None + + +def _bool(value: Any, default: bool = False) -> bool: + return value if isinstance(value, bool) else default + + +def _is_int(value: Any) -> TypeIs[int]: + return isinstance(value, int) and not isinstance(value, bool) + + +def _float(value: Any) -> float | None: + if isinstance(value, bool) or not isinstance(value, int | float): + return None + return float(value) + + +def _dt(value: Any) -> datetime | None: + if not isinstance(value, str): + return None + try: + return datetime.fromisoformat(value) + except ValueError: + return None + + +def _str_tuple(value: Any) -> tuple[str, ...]: + if not isinstance(value, list): + return () + return tuple(item for item in value if isinstance(item, str)) + + +# -------------------------------------------------------------------------------------- +# Models +# -------------------------------------------------------------------------------------- + + +@dataclass(frozen=True, slots=True) +class HealthInfo: + """``GET /api/health``: liveness and compatibility handshake (always public).""" + + version: str + api_version: int + min_api_version: int + auth: str + capabilities: frozenset[str] + # Contract v1.1. ``None`` on engines older than 1.0.0rc2. + instance_id: str | None = None + instance_name: str | None = None + + @classmethod + def from_dict(cls, data: Any) -> HealthInfo: + """Parse a health payload, rejecting anything that is not an engine.""" + if not isinstance(data, Mapping): + raise SmartFrameConnectionError("Unexpected health response (not an object)") + version = data.get("version") + api_version = data.get("api_version") + min_api_version = data.get("min_api_version") + auth = data.get("auth") + capabilities = data.get("capabilities") + if not ( + isinstance(version, str) + and _is_int(api_version) + and _is_int(min_api_version) + and isinstance(auth, str) + and isinstance(capabilities, list) + ): + raise SmartFrameConnectionError("Unexpected health response (missing fields)") + return cls( + version=version, + api_version=api_version, + min_api_version=min_api_version, + auth=auth, + capabilities=frozenset(c for c in capabilities if isinstance(c, str)), + instance_id=_str(data.get("instance_id")) or None, + instance_name=_str(data.get("instance_name")) or None, + ) + + @property + def requires_key(self) -> bool: + """Whether some endpoints need credentials (any mode other than ``open``).""" + return self.auth != AUTH_OPEN + + @property + def update_target(self) -> UpdateTarget | None: + """Which side must be updated, or ``None`` when compatible.""" + return compatibility_target(self.api_version, self.min_api_version) + + @property + def is_compatible(self) -> bool: + """Whether this engine speaks a contract version this integration supports.""" + return self.update_target is None + + def ensure_compatible(self) -> None: + """Raise ``SmartFrameIncompatibleError`` when the engine cannot be used.""" + target = self.update_target + if target is not None: + raise SmartFrameIncompatibleError(self.api_version, self.min_api_version, target) + + def as_dict(self) -> dict[str, Any]: + """Return a JSON-serialisable view (used by diagnostics).""" + return { + "version": self.version, + "api_version": self.api_version, + "min_api_version": self.min_api_version, + "auth": self.auth, + "capabilities": sorted(self.capabilities), + "instance_id": self.instance_id, + "instance_name": self.instance_name, + } + + +@dataclass(frozen=True, slots=True) +class CurrentImage: + """Metadata of a rendered image (``CurrentImageMeta``).""" + + source: str | None = None + title: str | None = None + template: str | None = None + ephemeral: bool = False + pushed: bool = True + content_key: str | None = None + processed_at: datetime | None = None + expires_at: datetime | None = None + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> CurrentImage: + """Parse ``CurrentImageMeta`` tolerantly.""" + return cls( + source=_str(data.get("source")), + title=_str(data.get("title")), + template=_str(data.get("template")), + ephemeral=_bool(data.get("ephemeral")), + pushed=_bool(data.get("pushed"), True), + content_key=_str(data.get("content_key")), + processed_at=_dt(data.get("processed_at")), + expires_at=_dt(data.get("expires_at")), + ) + + +@dataclass(frozen=True, slots=True) +class EphemeralState: + """The temporary image (now playing, poster, title card) shown or queued.""" + + active: bool = False + pending: bool = False + has_base: bool = False + expires_at: datetime | None = None + source: str | None = None + template: str | None = None + title: str | None = None + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> EphemeralState: + """Parse ``EphemeralView`` tolerantly.""" + return cls( + active=_bool(data.get("active")), + pending=_bool(data.get("pending")), + has_base=_bool(data.get("has_base")), + expires_at=_dt(data.get("expires_at")), + source=_str(data.get("source")), + template=_str(data.get("template")), + title=_str(data.get("title")), + ) + + +@dataclass(frozen=True, slots=True) +class FrameState: + """Configured frame characteristics (``FrameStatus``).""" + + configured: bool = False + panel: str | None = None + panel_label: str | None = None + orientation: str | None = None + power_mode: str | None = None + telemetry: Mapping[str, Any] = field(default_factory=dict) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> FrameState: + """Parse ``FrameStatus`` tolerantly.""" + return cls( + configured=_bool(data.get("configured")), + panel=_str(data.get("panel")), + panel_label=_str(data.get("panel_label")), + orientation=_str(data.get("orientation")), + power_mode=_str(data.get("power_mode")), + telemetry=dict(_mapping(data.get("telemetry"))), + ) + + +@dataclass(frozen=True, slots=True) +class DeliveryState: + """Upload queue state (``DeliveryStatus``).""" + + pending: bool = False + last_delivered_at: datetime | None = None + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> DeliveryState: + """Parse ``DeliveryStatus`` tolerantly.""" + return cls( + pending=_bool(data.get("pending")), + last_delivered_at=_dt(_mapping(data.get("last_delivery")).get("delivered_at")), + ) + + +@dataclass(frozen=True, slots=True) +class TimedFlag: + """A boolean with an expiry.""" + + value: bool + expires_at: datetime | None + + +@dataclass(frozen=True, slots=True) +class TimedText: + """One word or phrase with an expiry.""" + + value: str + expires_at: datetime | None + + +@dataclass(frozen=True, slots=True) +class TimedList: + """A list of names or phrases with an expiry.""" + + values: tuple[str, ...] + expires_at: datetime | None + + +@dataclass(frozen=True, slots=True) +class AmbientState: + """The live ambient fields (``None`` = not set).""" + + family_mode: TimedFlag | None = None + presence: TimedList | None = None + weather: TimedText | None = None + season: TimedText | None = None + boost_tags: TimedList | None = None + boost_people: TimedList | None = None + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> AmbientState: + """Parse ``AmbientState`` tolerantly.""" + + def flag(key: str) -> TimedFlag | None: + raw = data.get(key) + if not isinstance(raw, Mapping) or not isinstance(raw.get("value"), bool): + return None + return TimedFlag(raw["value"], _dt(raw.get("expires_at"))) + + def text(key: str) -> TimedText | None: + raw = data.get(key) + if not isinstance(raw, Mapping) or not isinstance(raw.get("value"), str): + return None + return TimedText(raw["value"], _dt(raw.get("expires_at"))) + + def items(key: str) -> TimedList | None: + raw = data.get(key) + if not isinstance(raw, Mapping) or not isinstance(raw.get("values"), list): + return None + return TimedList(_str_tuple(raw["values"]), _dt(raw.get("expires_at"))) + + return cls( + family_mode=flag("family_mode"), + presence=items("presence"), + weather=text("weather"), + season=text("season"), + boost_tags=items("boost_tags"), + boost_people=items("boost_people"), + ) + + +@dataclass(frozen=True, slots=True) +class SchedulerState: + """Autonomous refresh state (``SchedulerSnapshot``).""" + + enabled: bool = False + running: bool = False + in_quiet_hours: bool = False + interval_hours: float | None = None + next_run_at: datetime | None = None + last_display_at: datetime | None = None + hold_until: datetime | None = None + last_run_status: str | None = None + last_run_reason: str | None = None + ambient: AmbientState = field(default_factory=AmbientState) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> SchedulerState: + """Parse ``SchedulerSnapshot`` tolerantly.""" + last_run = _mapping(data.get("last_run")) + return cls( + enabled=_bool(data.get("enabled")), + running=_bool(data.get("running")), + in_quiet_hours=_bool(data.get("in_quiet_hours")), + interval_hours=_float(data.get("interval_hours")), + next_run_at=_dt(data.get("next_run_at")), + last_display_at=_dt(data.get("last_display_at")), + hold_until=_dt(data.get("hold_until")), + last_run_status=_str(last_run.get("status")), + last_run_reason=_str(last_run.get("reason")), + ambient=AmbientState.from_dict(_mapping(data.get("ambient"))), + ) + + +@dataclass(frozen=True, slots=True) +class EngineStatus: + """``GET /api/status``: overall system status.""" + + version: str + uptime_s: float + auth_mode: str + current_image: CurrentImage | None + ephemeral: EphemeralState + frame: FrameState + delivery: DeliveryState + scheduler: SchedulerState + immich_configured: bool + tmdb_configured: bool + + @classmethod + def from_dict(cls, data: Any) -> EngineStatus: + """Parse ``StatusResponse``, rejecting anything that is not an object.""" + if not isinstance(data, Mapping): + raise SmartFrameConnectionError("Unexpected status response (not an object)") + image = data.get("current_image") + services = _mapping(data.get("services")) + return cls( + version=_str(data.get("version")) or "", + uptime_s=_float(data.get("uptime_s")) or 0.0, + auth_mode=_str(data.get("auth_mode")) or "", + current_image=CurrentImage.from_dict(image) if isinstance(image, Mapping) else None, + ephemeral=EphemeralState.from_dict(_mapping(data.get("ephemeral"))), + frame=FrameState.from_dict(_mapping(data.get("frame"))), + delivery=DeliveryState.from_dict(_mapping(data.get("delivery"))), + scheduler=SchedulerState.from_dict(_mapping(data.get("scheduler"))), + immich_configured=_bool(services.get("immich")), + tmdb_configured=_bool(services.get("tmdb")), + ) + + +@dataclass(frozen=True, slots=True) +class AmbientView: + """``GET /api/context``: the live ambient context and what it currently does.""" + + context: AmbientState + family_active: bool = False + smart_mix_enabled: bool = False + extra_candidates: tuple[str, ...] = () + + @classmethod + def from_dict(cls, data: Any) -> AmbientView: + """Parse ``AmbientView`` tolerantly.""" + if not isinstance(data, Mapping): + raise SmartFrameConnectionError("Unexpected context response (not an object)") + return cls( + context=AmbientState.from_dict(_mapping(data.get("context"))), + family_active=_bool(data.get("family_active")), + smart_mix_enabled=_bool(data.get("smart_mix_enabled")), + extra_candidates=_str_tuple(data.get("extra_candidates")), + ) + + +@dataclass(frozen=True, slots=True) +class ConfigView: + """``GET``/``PUT /api/config``: effective configuration (secrets are masked).""" + + config: Mapping[str, Any] + sources: Mapping[str, Any] = field(default_factory=dict) + + @classmethod + def from_dict(cls, data: Any) -> ConfigView: + """Parse ``ConfigView`` tolerantly.""" + if not isinstance(data, Mapping): + raise SmartFrameConnectionError("Unexpected config response (not an object)") + return cls( + config=dict(_mapping(data.get("config"))), + sources=dict(_mapping(data.get("sources"))), + ) + + @property + def family_enabled(self) -> bool | None: + """The persistent Family Mode setting (``config.family.enabled``), if present.""" + enabled = _mapping(self.config.get("family")).get("enabled") + return enabled if isinstance(enabled, bool) else None + + +@dataclass(frozen=True, slots=True) +class DeliveryOutcome: + """Result of a submit, push or flush (``DeliveryOutcome``).""" + + status: str + reason: str | None = None + error: str | None = None + duration_s: float | None = None + sha256: str | None = None + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> DeliveryOutcome: + """Parse ``DeliveryOutcome`` tolerantly.""" + return cls( + status=_str(data.get("status")) or "", + reason=_str(data.get("reason")), + error=_str(data.get("error")), + duration_s=_float(data.get("duration_s")), + sha256=_str(data.get("sha256")), + ) + + +@dataclass(frozen=True, slots=True) +class DisplayResult: + """Result of displaying an image (``DisplayResult``).""" + + image: CurrentImage + delivery: DeliveryOutcome | None = None + deduplicated: bool = False + + @classmethod + def from_dict(cls, data: Any) -> DisplayResult: + """Parse ``DisplayResult`` tolerantly.""" + if not isinstance(data, Mapping): + raise SmartFrameConnectionError("Unexpected display response (not an object)") + delivery = data.get("delivery") + return cls( + image=CurrentImage.from_dict(_mapping(data.get("image"))), + delivery=DeliveryOutcome.from_dict(delivery) if isinstance(delivery, Mapping) else None, + deduplicated=_bool(data.get("deduplicated")), + ) + + +@dataclass(frozen=True, slots=True) +class RefreshResult: + """Outcome of a manual refresh (``RefreshResult``).""" + + display: DisplayResult + rule_kind: str | None = None + rule_source: str | None = None + entry_label: str | None = None + + @classmethod + def from_dict(cls, data: Any) -> RefreshResult: + """Parse ``RefreshResult`` tolerantly.""" + if not isinstance(data, Mapping): + raise SmartFrameConnectionError("Unexpected refresh response (not an object)") + return cls( + display=DisplayResult.from_dict(_mapping(data.get("display"))), + rule_kind=_str(data.get("rule_kind")), + rule_source=_str(data.get("rule_source")), + entry_label=_str(data.get("entry_label")), + ) + + +@dataclass(frozen=True, slots=True) +class WakeupResult: + """Result of ``POST /api/fraimic/wakeup``. + + A non-blocking wake-up answers ``WakeupAccepted`` (``accepted`` + ``pending``); with + ``wait=true`` it answers a ``DeliveryOutcome``. + """ + + accepted: bool + pending: bool | None = None + outcome: DeliveryOutcome | None = None + + @classmethod + def from_dict(cls, data: Any) -> WakeupResult: + """Parse either wake-up response shape.""" + if not isinstance(data, Mapping): + raise SmartFrameConnectionError("Unexpected wake-up response (not an object)") + if "accepted" in data: + pending = data.get("pending") + return cls( + accepted=_bool(data.get("accepted"), True), + pending=pending if isinstance(pending, bool) else None, + ) + return cls(accepted=True, outcome=DeliveryOutcome.from_dict(data)) + + +# -------------------------------------------------------------------------------------- +# Request helpers +# -------------------------------------------------------------------------------------- + +AmbientField = Literal["presence", "family_mode", "weather", "season", "boost_tags", "boost_people"] +Season = Literal["spring", "summer", "autumn", "winter"] +Accent = Literal["red", "yellow", "blue", "green", "white"] + + +class _Unset(enum.Enum): + UNSET = enum.auto() + + +UNSET: Final = _Unset.UNSET +"""Marker for "argument not given" where ``None`` is itself a meaningful value.""" + + +@dataclass(frozen=True, slots=True) +class WithTtl[T]: + """An ambient value with its own lifetime, overriding the request-wide ``ttl_minutes``.""" + + value: T + ttl_minutes: int + + +def _encode_ambient(value: Any) -> Any: + """Encode one ambient field as a bare value or ``{value|values, ttl_minutes}``.""" + if isinstance(value, WithTtl): + inner = value.value + key = "values" if isinstance(inner, Sequence) and not isinstance(inner, str) else "value" + return {key: list(inner) if key == "values" else inner, "ttl_minutes": value.ttl_minutes} + if isinstance(value, Sequence) and not isinstance(value, str): + return list(value) + return value + + +def _error_detail(body: bytes) -> str: + """Extract a readable message from an error body (never echoes submitted values).""" + text = body.decode("utf-8", errors="replace") + try: + payload = json.loads(text) + except ValueError: + return text.strip()[:200] + detail = payload.get("detail") if isinstance(payload, Mapping) else None + if isinstance(detail, str): + return detail + if isinstance(detail, list): + parts: list[str] = [] + for item in detail: + if isinstance(item, Mapping): + loc = ".".join(str(p) for p in item.get("loc", []) if p != "body") + msg = str(item.get("msg", "")).strip() + parts.append(f"{loc}: {msg}" if loc else msg) + return "; ".join(p for p in parts if p)[:500] + return text.strip()[:200] + + +@dataclass(frozen=True, slots=True) +class _Response: + status: int + body: bytes + + +# -------------------------------------------------------------------------------------- +# Client +# -------------------------------------------------------------------------------------- + + +class SmartFrameClient: + """Async client for one Smart Frame Engine.""" + + def __init__( + self, + session: aiohttp.ClientSession, + host: str, + port: int, + path: str = DEFAULT_PATH, + api_key: str | None = None, + ) -> None: + """Create a client bound to Home Assistant's shared ``session``.""" + self._session = session + self._host = host + self._port = port + stripped = path.strip("/") + self._base_path = f"/{stripped}" if stripped else "" + self._api_key = api_key or None + + @property + def host(self) -> str: + """Engine host (name or IP).""" + return self._host + + @property + def port(self) -> int: + """Engine port.""" + return self._port + + @property + def base_url(self) -> str: + """Root URL of the engine, including its ``ROOT_PATH`` (used for the device link).""" + return str( + URL.build(scheme="http", host=self._host, port=self._port, path=self._base_path or "/") + ) + + def _url(self, endpoint: str) -> URL: + return URL.build( + scheme="http", host=self._host, port=self._port, path=f"{self._base_path}{endpoint}" + ) + + async def _request( + self, + method: str, + endpoint: str, + *, + json_body: Mapping[str, Any] | None = None, + params: Mapping[str, str] | None = None, + ok_statuses: tuple[int, ...] = (200,), + ) -> _Response: + """Send one request and map failures onto the client's exceptions.""" + headers: dict[str, str] = {} + if self._api_key: + headers["X-API-Key"] = self._api_key + try: + async with ( + asyncio.timeout(REQUEST_TIMEOUT), + self._session.request( + method, + self._url(endpoint), + json=json_body, + params=params, + headers=headers, + ) as response, + ): + response_body = await response.read() + status = response.status + except TimeoutError as err: + raise SmartFrameConnectionError(f"Timed out talking to {self._host}") from err + except aiohttp.ClientError as err: + raise SmartFrameConnectionError(f"Cannot reach {self._host}: {err}") from err + + if status == 401: + raise SmartFrameAuthError("Missing or invalid API key") + if status in ok_statuses: + return _Response(status, response_body) + detail = _error_detail(response_body) + if status == 422: + raise SmartFrameValidationError(status, detail) + raise SmartFrameApiError(status, detail) + + async def _json( + self, + method: str, + endpoint: str, + *, + json_body: Mapping[str, Any] | None = None, + params: Mapping[str, str] | None = None, + ok_statuses: tuple[int, ...] = (200,), + ) -> tuple[int, Any]: + response = await self._request( + method, endpoint, json_body=json_body, params=params, ok_statuses=ok_statuses + ) + try: + return response.status, json.loads(response.body) + except ValueError as err: + raise SmartFrameConnectionError(f"Invalid JSON from {endpoint}") from err + + # -- Health, status, configuration --------------------------------------------------- + + async def async_get_health(self) -> HealthInfo: + """``GET /api/health`` (public in every auth mode).""" + _, data = await self._json("GET", "/api/health") + return HealthInfo.from_dict(data) + + async def async_validate_key(self) -> None: + """Check that the configured credentials are accepted. + + ``GET /api/status`` is public in ``key`` mode and so cannot prove a key is valid; + ``GET /api/config`` needs the key in both ``key`` and ``password`` modes (and is + public in ``open`` mode, where there is nothing to validate). + + Raises ``SmartFrameAuthError`` on HTTP 401. + """ + await self._request("GET", "/api/config") + + async def async_get_status(self) -> EngineStatus: + """``GET /api/status``.""" + _, data = await self._json("GET", "/api/status") + return EngineStatus.from_dict(data) + + async def async_get_config(self) -> ConfigView: + """``GET /api/config`` (needs the key in ``key`` and ``password`` modes).""" + _, data = await self._json("GET", "/api/config") + return ConfigView.from_dict(data) + + async def async_set_family_mode(self, enabled: bool) -> ConfigView: + """Persistently toggle Family Mode: ``PUT /api/config`` with ``{"family": {"enabled"}}``.""" + _, data = await self._json("PUT", "/api/config", json_body={"family": {"enabled": enabled}}) + return ConfigView.from_dict(data) + + # -- Ambient context ----------------------------------------------------------------- + + async def async_get_context(self) -> AmbientView: + """``GET /api/context``.""" + _, data = await self._json("GET", "/api/context") + return AmbientView.from_dict(data) + + async def async_set_context( + self, + *, + presence: Sequence[str] | WithTtl[Sequence[str]] | None = None, + family_mode: bool | WithTtl[bool] | None = None, + weather: str | WithTtl[str] | None = None, + season: Season | WithTtl[Season] | None = None, + boost_tags: Sequence[str] | WithTtl[Sequence[str]] | None = None, + boost_people: Sequence[str] | WithTtl[Sequence[str]] | None = None, + ttl_minutes: int | None = None, + ) -> AmbientView: + """``POST /api/context``: set ambient fields; each one expires on its own. + + Fields left as ``None`` keep their current value. Pass ``WithTtl`` for a per-field + lifetime, or ``ttl_minutes`` for the default lifetime of every field of this call + (1..10080 minutes; the engine validates the range). + """ + fields: dict[str, Any] = { + "presence": presence, + "family_mode": family_mode, + "weather": weather, + "season": season, + "boost_tags": boost_tags, + "boost_people": boost_people, + } + body = {key: _encode_ambient(value) for key, value in fields.items() if value is not None} + if not body: + raise ValueError("At least one ambient context field must be given") + if ttl_minutes is not None: + body["ttl_minutes"] = ttl_minutes + _, data = await self._json("POST", "/api/context", json_body=body) + return AmbientView.from_dict(data) + + async def async_clear_context(self, field_name: AmbientField | None = None) -> AmbientView: + """``DELETE /api/context``: clear one field, or everything when ``None``.""" + params = {"field": field_name} if field_name else None + _, data = await self._json("DELETE", "/api/context", params=params) + return AmbientView.from_dict(data) + + # -- Display triggers ---------------------------------------------------------------- + + async def async_refresh(self) -> RefreshResult: + """``POST /api/refresh``: re-run the active source rule now.""" + _, data = await self._json("POST", "/api/refresh") + return RefreshResult.from_dict(data) + + async def async_title_card( + self, + title: str, + *, + subtitle: str | None = None, + caption: str | None = None, + accent: Accent | None = None, + ephemeral: bool | None = None, + ttl_minutes: int | _Unset | None = UNSET, + hold_minutes: int | None = None, + push_to_fraimic: bool | None = None, + ) -> DisplayResult: + """``POST /api/display/title-card``: show a typographic card. + + Omitted options keep the engine's defaults. ``ttl_minutes=None`` is sent as ``null`` + (the card stays until cancelled or replaced), which differs from leaving it unset + (the engine's 60-minute default). + """ + body: dict[str, Any] = {"title": title} + optional: dict[str, Any] = { + "subtitle": subtitle, + "caption": caption, + "accent": accent, + "ephemeral": ephemeral, + "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}) + if ttl_minutes is not UNSET: + body["ttl_minutes"] = ttl_minutes + _, data = await self._json("POST", "/api/display/title-card", 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( + "POST", + "/api/fraimic/wakeup", + params={"wait": "true"} if wait else None, + ok_statuses=(200, 202), + ) + return WakeupResult.from_dict(data) + + async def async_push(self, *, from_preview: bool = False) -> DeliveryOutcome: + """``POST /api/fraimic/push``: send the current (or preview) image to the frame. + + HTTP 202 (frame unreachable, image stays queued) is a normal outcome, reported as + ``status == "queued"``. + """ + _, data = await self._json( + "POST", + "/api/fraimic/push", + params={"from_preview": "true"} if from_preview else None, + ok_statuses=(200, 202), + ) + if not isinstance(data, Mapping): + raise SmartFrameConnectionError("Unexpected push response (not an object)") + return DeliveryOutcome.from_dict(data) + + # -- Images -------------------------------------------------------------------------- + + async def _image(self, endpoint: str) -> bytes | None: + try: + response = await self._request("GET", endpoint) + except SmartFrameApiError as err: + if err.status == 404: + return None + raise + return response.body + + async def async_get_current_image(self) -> bytes | None: + """``GET /api/current.jpg``: the image currently rendered; ``None`` before the first.""" + return await self._image("/api/current.jpg") + + async def async_get_preview_image(self) -> bytes | None: + """``GET /api/preview.jpg``: the most recent render, pushed or not.""" + return await self._image("/api/preview.jpg") diff --git a/custom_components/smart_frame_engine/config_flow.py b/custom_components/smart_frame_engine/config_flow.py new file mode 100644 index 0000000..ca9330b --- /dev/null +++ b/custom_components/smart_frame_engine/config_flow.py @@ -0,0 +1,346 @@ +"""Config flow for Smart Frame Engine. + +Discovery (Zeroconf) and manual setup both start from ``GET /api/health``, which is public +in every auth mode: it tells us whether the engine is compatible, which auth mode it uses +and its stable ``instance_id`` (the config entry's unique ID). +""" + +from __future__ import annotations + +from collections.abc import Mapping +import logging +from typing import Any + +from homeassistant.config_entries import ( + ConfigEntry, + ConfigFlow, + ConfigFlowResult, + OptionsFlowWithReload, +) +from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT +from homeassistant.core import callback +from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.selector import ( + NumberSelector, + NumberSelectorConfig, + NumberSelectorMode, + TextSelector, + TextSelectorConfig, + TextSelectorType, +) +from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo +import voluptuous as vol + +from .api import ( + HealthInfo, + SmartFrameAuthError, + SmartFrameClient, + SmartFrameError, + compatibility_target, +) +from .const import ( + CONF_PATH, + CONF_SCAN_INTERVAL, + DEFAULT_PATH, + DEFAULT_PORT, + DEFAULT_SCAN_INTERVAL, + DOMAIN, + MAX_SCAN_INTERVAL, + MIN_SCAN_INTERVAL, + TXT_API_VERSION, + TXT_INSTANCE_ID, + TXT_MIN_API_VERSION, + TXT_PATH, +) + +_LOGGER = logging.getLogger(__name__) + + +def _form_schema(fields: dict[Any, Any]) -> Any: + """Build a form schema. + + Home Assistant 2026.10 moved to ``probatio`` and types ``data_schema`` accordingly, but it + still serves ``import voluptuous`` through a runtime shim, which is what keeps this + integration working on every 2026.x release (the minimum in ``hacs.json`` is 2026.1.0). + Returning ``Any`` here avoids a type-only mismatch between the two libraries. + """ + return vol.Schema(fields) + + +_API_KEY_SCHEMA = _form_schema( + { + vol.Required(CONF_API_KEY): TextSelector( + TextSelectorConfig(type=TextSelectorType.PASSWORD, autocomplete="off") + ) + } +) + + +def _abort_reason_for(health: HealthInfo) -> str | None: + """Return the abort reason that makes this engine unusable, or ``None``.""" + target = health.update_target + if target == "server": + return "server_outdated" + if target == "integration": + return "integration_outdated" + if health.instance_id is None: + # Engines older than 1.0.0rc2 have no stable ID to key the config entry on. + return "instance_id_missing" + return None + + +class SmartFrameConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle a config flow for Smart Frame Engine.""" + + VERSION = 1 + + def __init__(self) -> None: + """Initialise the flow state.""" + self._host = "" + self._port = DEFAULT_PORT + self._path = DEFAULT_PATH + self._health: HealthInfo | None = None + + @staticmethod + @callback + def async_get_options_flow(config_entry: ConfigEntry) -> SmartFrameOptionsFlow: + """Return the options flow.""" + return SmartFrameOptionsFlow() + + # -- Helpers ------------------------------------------------------------------------- + + def _client( + self, host: str, port: int, path: str, api_key: str | None = None + ) -> SmartFrameClient: + return SmartFrameClient(async_get_clientsession(self.hass), host, port, path, api_key) + + async def _async_validate_key(self, api_key: str) -> str | None: + """Return a form error key if ``api_key`` is not accepted, else ``None``.""" + client = self._client(self._host, self._port, self._path, api_key) + try: + await client.async_validate_key() + except SmartFrameAuthError: + return "invalid_auth" + except SmartFrameError: + return "cannot_connect" + except Exception: + _LOGGER.exception("Unexpected error while validating the API key") + return "unknown" + return None + + def _async_create_entry(self, api_key: str | None = None) -> ConfigFlowResult: + health = self._health + assert health is not None + data: dict[str, Any] = { + CONF_HOST: self._host, + CONF_PORT: self._port, + CONF_PATH: self._path, + } + if api_key: + data[CONF_API_KEY] = api_key + return self.async_create_entry( + title=health.instance_name or health.instance_id or self._host, data=data + ) + + async def _async_register_engine(self, health: HealthInfo) -> None: + """Make ``health.instance_id`` the flow's unique ID, updating a known entry's address.""" + await self.async_set_unique_id(health.instance_id) + self._abort_if_unique_id_configured( + updates={CONF_HOST: self._host, CONF_PORT: self._port, CONF_PATH: self._path} + ) + + # -- Manual setup -------------------------------------------------------------------- + + async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: + """Ask for host and port, then probe ``GET /api/health``.""" + errors: dict[str, str] = {} + if user_input is not None: + self._host = user_input[CONF_HOST].strip() + self._port = int(user_input[CONF_PORT]) + self._path = DEFAULT_PATH + try: + health = await self._client(self._host, self._port, self._path).async_get_health() + except SmartFrameError: + errors["base"] = "cannot_connect" + except Exception: + _LOGGER.exception("Unexpected error while probing the engine") + errors["base"] = "unknown" + else: + if reason := _abort_reason_for(health): + return self.async_abort(reason=reason) + self._health = health + await self._async_register_engine(health) + if health.requires_key: + return await self.async_step_auth() + return self._async_create_entry() + + schema = _form_schema( + { + vol.Required(CONF_HOST, default=self._host): str, + vol.Required(CONF_PORT, default=self._port): vol.All( + vol.Coerce(int), vol.Range(min=1, max=65535) + ), + } + ) + return self.async_show_form(step_id="user", data_schema=schema, errors=errors) + + async def async_step_auth(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: + """Ask for the API key (only reached when the engine's ``auth`` is not ``open``).""" + errors: dict[str, str] = {} + if user_input is not None: + api_key = user_input[CONF_API_KEY].strip() + if (error := await self._async_validate_key(api_key)) is None: + return self._async_create_entry(api_key) + errors["base"] = error + return self.async_show_form(step_id="auth", data_schema=_API_KEY_SCHEMA, errors=errors) + + # -- Zeroconf discovery -------------------------------------------------------------- + + async def async_step_zeroconf(self, discovery_info: ZeroconfServiceInfo) -> ConfigFlowResult: + """Handle a ``_smartframe._tcp.local.`` record.""" + props = discovery_info.properties + self._host = discovery_info.host + self._port = discovery_info.port or DEFAULT_PORT + self._path = props.get(TXT_PATH) or DEFAULT_PATH + + # The TXT record alone is enough to reject an incompatible engine. + try: + api_version = int(props[TXT_API_VERSION] or "") + min_api_version = int(props[TXT_MIN_API_VERSION] or "") + except (KeyError, ValueError): + pass + else: + if (target := compatibility_target(api_version, min_api_version)) is not None: + return self.async_abort(reason=f"{target}_outdated") + + # Known engine: update its address without any network call. + txt_instance_id = props.get(TXT_INSTANCE_ID) + if txt_instance_id: + await self.async_set_unique_id(txt_instance_id) + self._abort_if_unique_id_configured( + updates={CONF_HOST: self._host, CONF_PORT: self._port, CONF_PATH: self._path} + ) + + try: + health = await self._client(self._host, self._port, self._path).async_get_health() + except SmartFrameError: + return self.async_abort(reason="cannot_connect") + + if reason := _abort_reason_for(health): + return self.async_abort(reason=reason) + if txt_instance_id and health.instance_id != txt_instance_id: + return self.async_abort(reason="wrong_instance") + + self._health = health + await self._async_register_engine(health) + self.context["title_placeholders"] = {"name": health.instance_name or self._host} + return await self.async_step_zeroconf_confirm() + + async def async_step_zeroconf_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm a discovered engine; ask for the API key only when one is required.""" + health = self._health + assert health is not None + placeholders = { + "name": health.instance_name or self._host, + "host": self._host, + "port": str(self._port), + } + errors: dict[str, str] = {} + + if not health.requires_key: + if user_input is not None: + return self._async_create_entry() + self._set_confirm_only() + return self.async_show_form( + step_id="zeroconf_confirm", description_placeholders=placeholders + ) + + if user_input is not None: + api_key = user_input[CONF_API_KEY].strip() + if (error := await self._async_validate_key(api_key)) is None: + return self._async_create_entry(api_key) + errors["base"] = error + return self.async_show_form( + step_id="zeroconf_confirm", + data_schema=_API_KEY_SCHEMA, + description_placeholders=placeholders, + errors=errors, + ) + + # -- Reauthentication ---------------------------------------------------------------- + + async def async_step_reauth(self, entry_data: Mapping[str, Any]) -> ConfigFlowResult: + """Start reauthentication after the engine answered 401.""" + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Ask for a new API key.""" + entry = self._get_reauth_entry() + errors: dict[str, str] = {} + + if user_input is not None: + api_key = user_input[CONF_API_KEY].strip() + client = self._client( + entry.data[CONF_HOST], + entry.data[CONF_PORT], + entry.data.get(CONF_PATH, DEFAULT_PATH), + api_key, + ) + try: + health = await client.async_get_health() + await client.async_validate_key() + except SmartFrameAuthError: + errors["base"] = "invalid_auth" + except SmartFrameError: + errors["base"] = "cannot_connect" + except Exception: + _LOGGER.exception("Unexpected error during reauthentication") + errors["base"] = "unknown" + else: + if health.update_target == "server": + return self.async_abort(reason="server_outdated") + if health.update_target == "integration": + return self.async_abort(reason="integration_outdated") + if health.instance_id and health.instance_id != entry.unique_id: + return self.async_abort(reason="wrong_instance") + return self.async_update_reload_and_abort( + entry, data_updates={CONF_API_KEY: api_key} + ) + + return self.async_show_form( + step_id="reauth_confirm", + data_schema=_API_KEY_SCHEMA, + description_placeholders={"name": entry.title}, + errors=errors, + ) + + +class SmartFrameOptionsFlow(OptionsFlowWithReload): + """Options: the polling interval (the entry reloads automatically on change).""" + + async def async_step_init(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: + """Manage the polling interval.""" + if user_input is not None: + return self.async_create_entry( + data={CONF_SCAN_INTERVAL: int(user_input[CONF_SCAN_INTERVAL])} + ) + + current = self.config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) + schema = _form_schema( + { + vol.Required(CONF_SCAN_INTERVAL, default=current): NumberSelector( + NumberSelectorConfig( + min=MIN_SCAN_INTERVAL, + max=MAX_SCAN_INTERVAL, + step=1, + unit_of_measurement="s", + mode=NumberSelectorMode.BOX, + ) + ) + } + ) + return self.async_show_form(step_id="init", data_schema=schema) diff --git a/custom_components/smart_frame_engine/const.py b/custom_components/smart_frame_engine/const.py new file mode 100644 index 0000000..20dea4a --- /dev/null +++ b/custom_components/smart_frame_engine/const.py @@ -0,0 +1,94 @@ +"""Constants for the Smart Frame Engine integration. + +Everything contract-related (auth modes, capability flags, API version) mirrors +``docs/API_CONTRACT.md`` of https://github.com/ant1fr/Smart-Frame-Engine. +""" + +from __future__ import annotations + +from typing import Final + +DOMAIN: Final = "smart_frame_engine" +MANUFACTURER: Final = "Smart Frame Engine" +MODEL: Final = "Smart Frame Engine" + +# Contract version this integration speaks. The engine is compatible when +# ``min_api_version <= SUPPORTED_API_VERSION <= api_version``. +SUPPORTED_API_VERSION: Final = 1 + +# Config entry keys (``host``, ``port`` and ``api_key`` come from homeassistant.const). +CONF_PATH: Final = "path" +CONF_SCAN_INTERVAL: Final = "scan_interval" + +DEFAULT_PORT: Final = 8080 +DEFAULT_PATH: Final = "/" +DEFAULT_SCAN_INTERVAL: Final = 30 # seconds +MIN_SCAN_INTERVAL: Final = 10 +MAX_SCAN_INTERVAL: Final = 3600 +REQUEST_TIMEOUT: Final = 10 # seconds + +# Authentication modes reported by ``GET /api/health`` and the Zeroconf ``auth`` TXT key. +AUTH_OPEN: Final = "open" +AUTH_KEY: Final = "key" +AUTH_PASSWORD: Final = "password" + +# Zeroconf TXT keys (all values are strings). +TXT_VERSION: Final = "version" +TXT_API_VERSION: Final = "api_version" +TXT_MIN_API_VERSION: Final = "min_api_version" +TXT_PATH: Final = "path" +TXT_AUTH: Final = "auth" +TXT_INSTANCE_ID: Final = "instance_id" + +# Capability flags advertised in ``GET /api/health`` (contract v1.0, 18 flags). +CAPABILITY_ACTIVITY_LOG: Final = "activity_log" +CAPABILITY_AMBIENT_CONTEXT: Final = "ambient_context" +CAPABILITY_DISPLAY_IMMICH: Final = "display_immich" +CAPABILITY_DISPLAY_SMART_SEARCH: Final = "display_smart_search" +CAPABILITY_DISPLAY_TMDB: Final = "display_tmdb" +CAPABILITY_EPHEMERAL_IMAGES: Final = "ephemeral_images" +CAPABILITY_FAMILY_MODE: Final = "family_mode" +CAPABILITY_FORCE_REFRESH: Final = "force_refresh" +CAPABILITY_FRAME_PUSH: Final = "frame_push" +CAPABILITY_FRAME_WAKEUP: Final = "frame_wakeup" +CAPABILITY_NOW_PLAYING: Final = "now_playing" +CAPABILITY_NOW_PLAYING_DEDUP: Final = "now_playing_dedup" +CAPABILITY_PLAYGROUND: Final = "playground" +CAPABILITY_RANDOM_DISCOVERY: Final = "random_discovery" +CAPABILITY_SMART_MIX: Final = "smart_mix" +CAPABILITY_SMART_MIX_CONTEXT: Final = "smart_mix_context" +CAPABILITY_TITLE_CARD: Final = "title_card" +CAPABILITY_UPLOAD_IMAGE: Final = "upload_image" + +ALL_CAPABILITIES: Final[frozenset[str]] = frozenset( + { + CAPABILITY_ACTIVITY_LOG, + CAPABILITY_AMBIENT_CONTEXT, + CAPABILITY_DISPLAY_IMMICH, + CAPABILITY_DISPLAY_SMART_SEARCH, + CAPABILITY_DISPLAY_TMDB, + CAPABILITY_EPHEMERAL_IMAGES, + CAPABILITY_FAMILY_MODE, + CAPABILITY_FORCE_REFRESH, + CAPABILITY_FRAME_PUSH, + CAPABILITY_FRAME_WAKEUP, + CAPABILITY_NOW_PLAYING, + CAPABILITY_NOW_PLAYING_DEDUP, + CAPABILITY_PLAYGROUND, + CAPABILITY_RANDOM_DISCOVERY, + CAPABILITY_SMART_MIX, + CAPABILITY_SMART_MIX_CONTEXT, + CAPABILITY_TITLE_CARD, + CAPABILITY_UPLOAD_IMAGE, + } +) + +# Repair issues. +ISSUE_INCOMPATIBLE_PREFIX: Final = "incompatible_api" +# Translation keys of the two Repair issues (which side needs an update). +ISSUE_INTEGRATION_OUTDATED: Final = "integration_outdated" +ISSUE_SERVER_OUTDATED: Final = "server_outdated" + +# Where to read about updating. +ENGINE_RELEASES_URL: Final = "https://github.com/ant1fr/Smart-Frame-Engine/releases" +INTEGRATION_RELEASES_URL: Final = "https://github.com/ant1fr/Smart-Frame-Engine-HA/releases" diff --git a/custom_components/smart_frame_engine/coordinator.py b/custom_components/smart_frame_engine/coordinator.py new file mode 100644 index 0000000..cb23074 --- /dev/null +++ b/custom_components/smart_frame_engine/coordinator.py @@ -0,0 +1,199 @@ +"""DataUpdateCoordinator for Smart Frame Engine. + +Every refresh re-validates the compatibility handshake (``GET /api/health``) so an engine +that is updated, downgraded or replaced is noticed within one polling interval. An +incompatible engine raises a persistent Repair issue that is removed automatically as soon +as the versions are compatible again. +""" + +from __future__ import annotations + +from collections.abc import Awaitable +from dataclasses import dataclass +from datetime import timedelta +import logging + +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant, callback +from homeassistant.exceptions import ConfigEntryAuthFailed +from homeassistant.helpers import issue_registry as ir +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed + +from .api import ( + AmbientView, + EngineStatus, + HealthInfo, + SmartFrameAuthError, + SmartFrameClient, + SmartFrameError, + UpdateTarget, +) +from .const import ( + CAPABILITY_AMBIENT_CONTEXT, + CONF_SCAN_INTERVAL, + DEFAULT_SCAN_INTERVAL, + DOMAIN, + ENGINE_RELEASES_URL, + INTEGRATION_RELEASES_URL, + ISSUE_INCOMPATIBLE_PREFIX, + ISSUE_INTEGRATION_OUTDATED, + ISSUE_SERVER_OUTDATED, + MANUFACTURER, + MODEL, + SUPPORTED_API_VERSION, +) + +_LOGGER = logging.getLogger(__name__) + + +@dataclass(frozen=True, slots=True) +class SmartFrameData: + """One coherent snapshot of the engine.""" + + health: HealthInfo + status: EngineStatus + # ``None`` when the engine does not advertise the ``ambient_context`` capability. + ambient: AmbientView | None + + +SmartFrameConfigEntry = ConfigEntry["SmartFrameCoordinator"] + + +def _issue_id(entry_id: str) -> str: + return f"{ISSUE_INCOMPATIBLE_PREFIX}_{entry_id}" + + +@callback +def async_delete_compatibility_issue(hass: HomeAssistant, entry_id: str) -> None: + """Remove the incompatibility Repair issue of a config entry (no-op when absent).""" + ir.async_delete_issue(hass, DOMAIN, _issue_id(entry_id)) + + +class SmartFrameCoordinator(DataUpdateCoordinator[SmartFrameData]): + """Poll health, status and ambient context of one engine.""" + + config_entry: SmartFrameConfigEntry + + def __init__( + self, + hass: HomeAssistant, + entry: SmartFrameConfigEntry, + client: SmartFrameClient, + ) -> None: + """Initialise the coordinator; the polling interval comes from the entry options.""" + interval = int(entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)) + super().__init__( + hass, + _LOGGER, + name=f"{DOMAIN} {entry.title}", + config_entry=entry, + update_interval=timedelta(seconds=interval), + ) + self.client = client + # Capability flags of the connected engine; entity platforms and services read this + # to adapt (contract: check ``capabilities``, never ``version``). + self.capabilities: frozenset[str] = frozenset() + + @property + def instance_id(self) -> str: + """Stable engine identity: the config entry's unique ID (the engine's ``instance_id``).""" + return self.config_entry.unique_id or self.config_entry.entry_id + + @property + def device_info(self) -> DeviceInfo: + """Shared ``DeviceInfo`` for every entity of this engine.""" + health = self.data.health if self.data is not None else None + return DeviceInfo( + identifiers={(DOMAIN, self.instance_id)}, + name=(health.instance_name if health else None) or self.config_entry.title, + manufacturer=MANUFACTURER, + model=MODEL, + sw_version=health.version if health else None, + configuration_url=self.client.base_url, + ) + + async def _async_call[T](self, awaitable: Awaitable[T]) -> T: + """Await a client call and translate its errors for the coordinator.""" + try: + return await awaitable + except SmartFrameAuthError as err: + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, translation_key="invalid_auth" + ) from err + except SmartFrameError as err: + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="update_failed", + translation_placeholders={"error": str(err)}, + ) from err + + async def _async_update_data(self) -> SmartFrameData: + """Fetch health (and re-check compatibility), then status and ambient context.""" + health = await self._async_call(self.client.async_get_health()) + self._async_check_instance(health) + self._async_check_compatibility(health) + + status = await self._async_call(self.client.async_get_status()) + ambient: AmbientView | None = None + if CAPABILITY_AMBIENT_CONTEXT in health.capabilities: + # Also proves the key is still valid in ``key`` mode, where ``/api/status`` is public. + ambient = await self._async_call(self.client.async_get_context()) + + self.capabilities = health.capabilities + return SmartFrameData(health=health, status=status, ambient=ambient) + + def _async_check_instance(self, health: HealthInfo) -> None: + """Refuse to poll a different engine that took over this address.""" + expected = self.config_entry.unique_id + if health.instance_id and expected and health.instance_id != expected: + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="instance_mismatch", + translation_placeholders={"name": self.config_entry.title}, + ) + + def _async_check_compatibility(self, health: HealthInfo) -> None: + """Create/delete the Repair issue and fail the refresh when incompatible.""" + target = health.update_target + if target is None: + async_delete_compatibility_issue(self.hass, self.config_entry.entry_id) + return + + self._async_create_compatibility_issue(health, target) + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key=( + "incompatible_server" if target == "server" else "incompatible_integration" + ), + translation_placeholders={ + "api_version": str(health.api_version), + "min_api_version": str(health.min_api_version), + "supported_version": str(SUPPORTED_API_VERSION), + }, + ) + + def _async_create_compatibility_issue(self, health: HealthInfo, target: UpdateTarget) -> None: + """Create a persistent Repair issue saying which side needs updating.""" + outdated_integration = target == "integration" + ir.async_create_issue( + self.hass, + DOMAIN, + _issue_id(self.config_entry.entry_id), + is_fixable=False, + is_persistent=True, + severity=ir.IssueSeverity.ERROR, + learn_more_url=INTEGRATION_RELEASES_URL + if outdated_integration + else ENGINE_RELEASES_URL, + translation_key=( + ISSUE_INTEGRATION_OUTDATED if outdated_integration else ISSUE_SERVER_OUTDATED + ), + translation_placeholders={ + "name": self.config_entry.title, + "server_version": health.version, + "api_version": str(health.api_version), + "min_api_version": str(health.min_api_version), + "supported_version": str(SUPPORTED_API_VERSION), + }, + ) diff --git a/custom_components/smart_frame_engine/diagnostics.py b/custom_components/smart_frame_engine/diagnostics.py new file mode 100644 index 0000000..1eed058 --- /dev/null +++ b/custom_components/smart_frame_engine/diagnostics.py @@ -0,0 +1,47 @@ +"""Diagnostics for Smart Frame Engine (secrets redacted).""" + +from __future__ import annotations + +from dataclasses import asdict +from typing import Any + +from homeassistant.components.diagnostics import async_redact_data +from homeassistant.const import CONF_API_KEY +from homeassistant.core import HomeAssistant + +from .coordinator import SmartFrameConfigEntry + +# The engine never returns secrets, but anything key-like is redacted defensively. +TO_REDACT = {CONF_API_KEY, "api_key", "password", "token", "X-API-Key"} + + +async def async_get_config_entry_diagnostics( + hass: HomeAssistant, entry: SmartFrameConfigEntry +) -> dict[str, Any]: + """Return redacted diagnostics for a config entry.""" + coordinator = entry.runtime_data + data = coordinator.data + + return async_redact_data( + { + "entry": { + "unique_id": entry.unique_id, + "title": entry.title, + "data": dict(entry.data), + "options": dict(entry.options), + }, + "coordinator": { + "last_update_success": coordinator.last_update_success, + "update_interval_seconds": ( + coordinator.update_interval.total_seconds() + if coordinator.update_interval + else None + ), + }, + "capabilities": sorted(coordinator.capabilities), + "health": data.health.as_dict() if data else None, + "status": asdict(data.status) if data else None, + "ambient": asdict(data.ambient) if data and data.ambient else None, + }, + TO_REDACT, + ) diff --git a/custom_components/smart_frame_engine/entity.py b/custom_components/smart_frame_engine/entity.py new file mode 100644 index 0000000..e2dc9ca --- /dev/null +++ b/custom_components/smart_frame_engine/entity.py @@ -0,0 +1,26 @@ +"""Base entity for Smart Frame Engine.""" + +from __future__ import annotations + +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity import EntityDescription +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from .coordinator import SmartFrameCoordinator + + +class SmartFrameEntity(CoordinatorEntity[SmartFrameCoordinator]): + """Entity attached to the single device that represents one engine.""" + + _attr_has_entity_name = True + + def __init__(self, coordinator: SmartFrameCoordinator, description: EntityDescription) -> None: + """Bind the entity to the engine's shared device.""" + super().__init__(coordinator) + self.entity_description = description + self._attr_unique_id = f"{coordinator.instance_id}_{description.key}" + + @property + def device_info(self) -> DeviceInfo: + """Return the shared device (``sw_version`` from ``/api/health``, config URL).""" + return self.coordinator.device_info diff --git a/custom_components/smart_frame_engine/manifest.json b/custom_components/smart_frame_engine/manifest.json new file mode 100644 index 0000000..e6afcd7 --- /dev/null +++ b/custom_components/smart_frame_engine/manifest.json @@ -0,0 +1,16 @@ +{ + "domain": "smart_frame_engine", + "name": "Smart Frame Engine", + "codeowners": ["@ant1fr"], + "config_flow": true, + "documentation": "https://github.com/ant1fr/Smart-Frame-Engine-HA", + "iot_class": "local_polling", + "issue_tracker": "https://github.com/ant1fr/Smart-Frame-Engine-HA/issues", + "requirements": [], + "version": "1.0.0", + "zeroconf": [ + { + "type": "_smartframe._tcp.local." + } + ] +} diff --git a/custom_components/smart_frame_engine/strings.json b/custom_components/smart_frame_engine/strings.json new file mode 100644 index 0000000..6d0afe4 --- /dev/null +++ b/custom_components/smart_frame_engine/strings.json @@ -0,0 +1,104 @@ +{ + "config": { + "flow_title": "{name}", + "step": { + "user": { + "title": "Connect to Smart Frame Engine", + "description": "Enter the address of your Smart Frame Engine. The API port is 8080 unless you changed it.", + "data": { + "host": "Host", + "port": "Port" + }, + "data_description": { + "host": "Hostname or IP address of the machine running Smart Frame Engine.", + "port": "Port of the Smart Frame Engine web server." + } + }, + "auth": { + "title": "Authentication required", + "description": "This Smart Frame Engine requires an API key. You can find it in the engine's web interface.", + "data": { + "api_key": "API key" + }, + "data_description": { + "api_key": "API key of the engine, sent as the X-API-Key header." + } + }, + "zeroconf_confirm": { + "title": "Add {name}?", + "description": "Smart Frame Engine **{name}** was found at {host}:{port}. Do you want to add it to Home Assistant? If the engine requires an API key, enter it below.", + "data": { + "api_key": "API key" + }, + "data_description": { + "api_key": "API key of the engine. Leave empty only if the engine does not require authentication." + } + }, + "reauth_confirm": { + "title": "Re-authenticate {name}", + "description": "The API key for **{name}** was rejected. Enter the current API key.", + "data": { + "api_key": "API key" + }, + "data_description": { + "api_key": "The current API key of the engine." + } + } + }, + "error": { + "cannot_connect": "Failed to connect", + "invalid_auth": "Invalid authentication", + "unknown": "Unexpected error" + }, + "abort": { + "already_configured": "Device is already configured", + "already_in_progress": "Configuration flow is already in progress", + "cannot_connect": "Failed to connect", + "reauth_successful": "Re-authentication was successful", + "integration_outdated": "This Smart Frame Engine is newer than this integration supports. Update the Smart Frame Engine integration (HACS) and try again.", + "server_outdated": "This Smart Frame Engine is too old for this integration. Update the engine and try again.", + "instance_id_missing": "This Smart Frame Engine does not report an instance ID. Update the engine to version 1.0.0-rc.2 or later and try again.", + "wrong_instance": "The device at this address is a different Smart Frame Engine than the one configured." + } + }, + "options": { + "step": { + "init": { + "title": "Smart Frame Engine options", + "data": { + "scan_interval": "Polling interval (seconds)" + }, + "data_description": { + "scan_interval": "How often Home Assistant asks the engine for its status (10 to 3600 seconds)." + } + } + } + }, + "issues": { + "integration_outdated": { + "title": "Smart Frame Engine integration needs an update", + "description": "The engine **{name}** (version {server_version}) speaks API versions {min_api_version} to {api_version}, but this integration only supports version {supported_version}. The engine is newer than the integration.\n\nUpdate the Smart Frame Engine integration in HACS and restart Home Assistant. This issue disappears on its own once the versions are compatible." + }, + "server_outdated": { + "title": "Smart Frame Engine needs an update", + "description": "The engine **{name}** (version {server_version}) speaks API versions {min_api_version} to {api_version}, but this integration needs version {supported_version}. The engine is older than the integration.\n\nUpdate Smart Frame Engine. This issue disappears on its own once the versions are compatible." + } + }, + "exceptions": { + "invalid_auth": { + "message": "The Smart Frame Engine rejected the API key." + }, + "update_failed": { + "message": "Error communicating with the Smart Frame Engine: {error}" + }, + "incompatible_server": { + "message": "The Smart Frame Engine is too old: it speaks API versions {min_api_version} to {api_version} but this integration needs version {supported_version}. Update the engine." + }, + "incompatible_integration": { + "message": "The Smart Frame Engine is newer than this integration: it speaks API versions {min_api_version} to {api_version} but this integration only supports version {supported_version}. Update the integration." + }, + "instance_mismatch": { + "message": "The device at the configured address is not {name}. It is a different Smart Frame Engine." + } + } +} diff --git a/custom_components/smart_frame_engine/translations/en.json b/custom_components/smart_frame_engine/translations/en.json new file mode 100644 index 0000000..6d0afe4 --- /dev/null +++ b/custom_components/smart_frame_engine/translations/en.json @@ -0,0 +1,104 @@ +{ + "config": { + "flow_title": "{name}", + "step": { + "user": { + "title": "Connect to Smart Frame Engine", + "description": "Enter the address of your Smart Frame Engine. The API port is 8080 unless you changed it.", + "data": { + "host": "Host", + "port": "Port" + }, + "data_description": { + "host": "Hostname or IP address of the machine running Smart Frame Engine.", + "port": "Port of the Smart Frame Engine web server." + } + }, + "auth": { + "title": "Authentication required", + "description": "This Smart Frame Engine requires an API key. You can find it in the engine's web interface.", + "data": { + "api_key": "API key" + }, + "data_description": { + "api_key": "API key of the engine, sent as the X-API-Key header." + } + }, + "zeroconf_confirm": { + "title": "Add {name}?", + "description": "Smart Frame Engine **{name}** was found at {host}:{port}. Do you want to add it to Home Assistant? If the engine requires an API key, enter it below.", + "data": { + "api_key": "API key" + }, + "data_description": { + "api_key": "API key of the engine. Leave empty only if the engine does not require authentication." + } + }, + "reauth_confirm": { + "title": "Re-authenticate {name}", + "description": "The API key for **{name}** was rejected. Enter the current API key.", + "data": { + "api_key": "API key" + }, + "data_description": { + "api_key": "The current API key of the engine." + } + } + }, + "error": { + "cannot_connect": "Failed to connect", + "invalid_auth": "Invalid authentication", + "unknown": "Unexpected error" + }, + "abort": { + "already_configured": "Device is already configured", + "already_in_progress": "Configuration flow is already in progress", + "cannot_connect": "Failed to connect", + "reauth_successful": "Re-authentication was successful", + "integration_outdated": "This Smart Frame Engine is newer than this integration supports. Update the Smart Frame Engine integration (HACS) and try again.", + "server_outdated": "This Smart Frame Engine is too old for this integration. Update the engine and try again.", + "instance_id_missing": "This Smart Frame Engine does not report an instance ID. Update the engine to version 1.0.0-rc.2 or later and try again.", + "wrong_instance": "The device at this address is a different Smart Frame Engine than the one configured." + } + }, + "options": { + "step": { + "init": { + "title": "Smart Frame Engine options", + "data": { + "scan_interval": "Polling interval (seconds)" + }, + "data_description": { + "scan_interval": "How often Home Assistant asks the engine for its status (10 to 3600 seconds)." + } + } + } + }, + "issues": { + "integration_outdated": { + "title": "Smart Frame Engine integration needs an update", + "description": "The engine **{name}** (version {server_version}) speaks API versions {min_api_version} to {api_version}, but this integration only supports version {supported_version}. The engine is newer than the integration.\n\nUpdate the Smart Frame Engine integration in HACS and restart Home Assistant. This issue disappears on its own once the versions are compatible." + }, + "server_outdated": { + "title": "Smart Frame Engine needs an update", + "description": "The engine **{name}** (version {server_version}) speaks API versions {min_api_version} to {api_version}, but this integration needs version {supported_version}. The engine is older than the integration.\n\nUpdate Smart Frame Engine. This issue disappears on its own once the versions are compatible." + } + }, + "exceptions": { + "invalid_auth": { + "message": "The Smart Frame Engine rejected the API key." + }, + "update_failed": { + "message": "Error communicating with the Smart Frame Engine: {error}" + }, + "incompatible_server": { + "message": "The Smart Frame Engine is too old: it speaks API versions {min_api_version} to {api_version} but this integration needs version {supported_version}. Update the engine." + }, + "incompatible_integration": { + "message": "The Smart Frame Engine is newer than this integration: it speaks API versions {min_api_version} to {api_version} but this integration only supports version {supported_version}. Update the integration." + }, + "instance_mismatch": { + "message": "The device at the configured address is not {name}. It is a different Smart Frame Engine." + } + } +} diff --git a/custom_components/smart_frame_engine/translations/fr.json b/custom_components/smart_frame_engine/translations/fr.json new file mode 100644 index 0000000..276eb62 --- /dev/null +++ b/custom_components/smart_frame_engine/translations/fr.json @@ -0,0 +1,104 @@ +{ + "config": { + "flow_title": "{name}", + "step": { + "user": { + "title": "Se connecter à Smart Frame Engine", + "description": "Saisissez l'adresse de votre Smart Frame Engine. Le port de l'API est 8080, sauf si vous l'avez modifié.", + "data": { + "host": "Hôte", + "port": "Port" + }, + "data_description": { + "host": "Nom d'hôte ou adresse IP de la machine qui exécute Smart Frame Engine.", + "port": "Port du serveur web de Smart Frame Engine." + } + }, + "auth": { + "title": "Authentification requise", + "description": "Ce Smart Frame Engine requiert une clé API. Vous la trouverez dans l'interface web du moteur.", + "data": { + "api_key": "Clé API" + }, + "data_description": { + "api_key": "Clé API du moteur, envoyée dans l'en-tête X-API-Key." + } + }, + "zeroconf_confirm": { + "title": "Ajouter {name} ?", + "description": "Smart Frame Engine **{name}** a été trouvé à l'adresse {host}:{port}. Voulez-vous l'ajouter à Home Assistant ? Si le moteur requiert une clé API, saisissez-la ci-dessous.", + "data": { + "api_key": "Clé API" + }, + "data_description": { + "api_key": "Clé API du moteur. Ne la laissez vide que si le moteur ne requiert pas d'authentification." + } + }, + "reauth_confirm": { + "title": "Se réauthentifier sur {name}", + "description": "La clé API de **{name}** a été refusée. Saisissez la clé API actuelle.", + "data": { + "api_key": "Clé API" + }, + "data_description": { + "api_key": "La clé API actuelle du moteur." + } + } + }, + "error": { + "cannot_connect": "Échec de la connexion", + "invalid_auth": "Authentification invalide", + "unknown": "Erreur inattendue" + }, + "abort": { + "already_configured": "L'appareil est déjà configuré", + "already_in_progress": "La configuration est déjà en cours", + "cannot_connect": "Échec de la connexion", + "reauth_successful": "La réauthentification a réussi", + "integration_outdated": "Ce Smart Frame Engine est plus récent que ce que cette intégration prend en charge. Mettez à jour l'intégration Smart Frame Engine (HACS) puis réessayez.", + "server_outdated": "Ce Smart Frame Engine est trop ancien pour cette intégration. Mettez à jour le moteur puis réessayez.", + "instance_id_missing": "Ce Smart Frame Engine ne fournit pas d'identifiant d'instance. Mettez à jour le moteur vers la version 1.0.0-rc.2 ou ultérieure puis réessayez.", + "wrong_instance": "L'appareil à cette adresse est un autre Smart Frame Engine que celui qui est configuré." + } + }, + "options": { + "step": { + "init": { + "title": "Options de Smart Frame Engine", + "data": { + "scan_interval": "Intervalle d'interrogation (secondes)" + }, + "data_description": { + "scan_interval": "Fréquence à laquelle Home Assistant interroge le moteur pour connaître son état (de 10 à 3600 secondes)." + } + } + } + }, + "issues": { + "integration_outdated": { + "title": "L'intégration Smart Frame Engine doit être mise à jour", + "description": "Le moteur **{name}** (version {server_version}) utilise les versions d'API {min_api_version} à {api_version}, mais cette intégration ne prend en charge que la version {supported_version}. Le moteur est plus récent que l'intégration.\n\nMettez à jour l'intégration Smart Frame Engine dans HACS puis redémarrez Home Assistant. Ce problème disparaît de lui-même dès que les versions sont compatibles." + }, + "server_outdated": { + "title": "Smart Frame Engine doit être mis à jour", + "description": "Le moteur **{name}** (version {server_version}) utilise les versions d'API {min_api_version} à {api_version}, mais cette intégration requiert la version {supported_version}. Le moteur est plus ancien que l'intégration.\n\nMettez à jour Smart Frame Engine. Ce problème disparaît de lui-même dès que les versions sont compatibles." + } + }, + "exceptions": { + "invalid_auth": { + "message": "Le Smart Frame Engine a refusé la clé API." + }, + "update_failed": { + "message": "Erreur de communication avec le Smart Frame Engine : {error}" + }, + "incompatible_server": { + "message": "Le Smart Frame Engine est trop ancien : il utilise les versions d'API {min_api_version} à {api_version} mais cette intégration requiert la version {supported_version}. Mettez à jour le moteur." + }, + "incompatible_integration": { + "message": "Le Smart Frame Engine est plus récent que cette intégration : il utilise les versions d'API {min_api_version} à {api_version} mais cette intégration ne prend en charge que la version {supported_version}. Mettez à jour l'intégration." + }, + "instance_mismatch": { + "message": "L'appareil à l'adresse configurée n'est pas {name}. Il s'agit d'un autre Smart Frame Engine." + } + } +} From e62adae44adbe48aa5f8a484afe320ab1063327a Mon Sep 17 00:00:00 2001 From: ant1fr Date: Thu, 19 Nov 2026 14:23:14 +0100 Subject: [PATCH 3/3] test: cover the API client, flows, coordinator and diagnostics 100 tests: api (all auth modes, 401, 422, timeouts, compatibility matrix), config flow (Zeroconf open/key, manual, duplicate address update, incompatible api_version, reauth, options), coordinator (capability cache, Repair issue creation and auto-resolution, reauth on 401, instance mismatch), diagnostics redaction, entity device info, manifest ordering and en/fr translation parity. Co-Authored-By: Claude Sonnet 5.5 --- tests/__init__.py | 1 + tests/common.py | 205 +++++++++++++++ tests/conftest.py | 20 ++ tests/test_api.py | 516 ++++++++++++++++++++++++++++++++++++++ tests/test_config_flow.py | 456 +++++++++++++++++++++++++++++++++ tests/test_diagnostics.py | 44 ++++ tests/test_entity.py | 37 +++ tests/test_init.py | 287 +++++++++++++++++++++ tests/test_metadata.py | 82 ++++++ 9 files changed, 1648 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/common.py create mode 100644 tests/conftest.py create mode 100644 tests/test_api.py create mode 100644 tests/test_config_flow.py create mode 100644 tests/test_diagnostics.py create mode 100644 tests/test_entity.py create mode 100644 tests/test_init.py create mode 100644 tests/test_metadata.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..6020740 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the Smart Frame Engine integration.""" diff --git a/tests/common.py b/tests/common.py new file mode 100644 index 0000000..76a5c94 --- /dev/null +++ b/tests/common.py @@ -0,0 +1,205 @@ +"""Payloads and helpers shared by the tests (shapes follow openapi.json, contract v1.1).""" + +from __future__ import annotations + +from ipaddress import ip_address +from typing import Any + +from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT +from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo +from pytest_homeassistant_custom_component.common import MockConfigEntry +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.const import ( + ALL_CAPABILITIES, + CONF_PATH, + DOMAIN, +) + +HOST = "192.168.1.50" +PORT = 8080 +BASE = f"http://{HOST}:{PORT}" +API_KEY = "test-secret-key-0123456789" +INSTANCE_ID = "3f2b8c1e-5d0a-4c7e-9b61-0a1d2e3f4a5b" +OTHER_INSTANCE_ID = "9a8b7c6d-1111-4222-8333-444455556666" +INSTANCE_NAME = "Smart Frame Engine 3f2b8c" + + +def health_payload( + *, + auth: str = "open", + api_version: int = 1, + min_api_version: int = 1, + capabilities: set[str] | frozenset[str] | None = None, + instance_id: str | None = INSTANCE_ID, + instance_name: str | None = INSTANCE_NAME, + version: str = "1.0.0rc2", +) -> dict[str, Any]: + """Return a ``GET /api/health`` body; ``instance_id=None`` mimics an rc.1 engine.""" + payload: dict[str, Any] = { + "status": "ok", + "version": version, + "api_version": api_version, + "min_api_version": min_api_version, + "auth": auth, + "capabilities": sorted(ALL_CAPABILITIES if capabilities is None else capabilities), + } + if instance_id is not None: + payload["instance_id"] = instance_id + if instance_name is not None: + payload["instance_name"] = instance_name + return payload + + +def status_payload() -> dict[str, Any]: + """Return a ``GET /api/status`` body.""" + return { + "version": "1.0.0rc2", + "uptime_s": 1234.5, + "auth_enabled": False, + "auth_mode": "open", + "public_image_endpoints": True, + "current_image": { + "source": "immich", + "title": "Summer 2024", + "template": None, + "ephemeral": False, + "pushed": True, + "content_key": "immich:abc", + "processed_at": "2026-11-19T10:00:00Z", + "expires_at": None, + "bin_size": 1000, + "dither": "auto", + "fit": "smart_crop", + "frame_size": [1200, 1600], + "orientation": "portrait", + "panel": "133", + "rotation": 0, + "sha256": "0" * 64, + }, + "ephemeral": {"active": False, "pending": False, "has_base": False}, + "frame": { + "configured": True, + "frame_size": [1200, 1600], + "orientation": "portrait", + "panel": "133", + "panel_label": "13.3 inch", + "power_mode": "deepsleep", + "telemetry": {"battery": 80}, + }, + "delivery": { + "pending": False, + "last_delivery": { + "bytes": 1, + "delivered_at": "2026-11-19T10:00:05Z", + "duration_s": 1.2, + "reason": "submit", + "sha256": "0" * 64, + }, + }, + "scheduler": { + "enabled": True, + "running": False, + "in_quiet_hours": False, + "interval_hours": 6.0, + "next_run_at": "2026-11-19T16:00:00+01:00", + "last_display_at": "2026-11-19T10:00:00Z", + "hold_until": None, + "last_run": {"at": "2026-11-19T10:00:00Z", "reason": "scheduled", "status": "ok"}, + "ambient": {"weather": {"value": "rainy", "expires_at": "2026-11-19T12:00:00Z"}}, + }, + "services": {"immich": True, "tmdb": False}, + } + + +def context_payload() -> dict[str, Any]: + """Return a ``GET /api/context`` body.""" + return { + "context": { + "family_mode": {"value": True, "expires_at": "2026-11-19T12:00:00Z"}, + "presence": {"values": ["Alice", "Bob"], "expires_at": "2026-11-19T12:00:00Z"}, + }, + "extra_candidates": ["rainy"], + "family_active": True, + "smart_mix_enabled": True, + } + + +def config_payload(*, family_enabled: bool = False) -> dict[str, Any]: + """Return a ``GET``/``PUT /api/config`` body.""" + return { + "config": {"family": {"enabled": family_enabled, "members": []}}, + "frame_size": [1200, 1600], + "sources": {"family.enabled": "default"}, + } + + +def delivery_payload(status: str = "delivered", reason: str = "force") -> dict[str, Any]: + """Return a ``DeliveryOutcome`` body.""" + return {"status": status, "reason": reason, "error": None, "duration_s": 1.5, "sha256": "ab"} + + +def display_payload() -> dict[str, Any]: + """Return a ``DisplayResult`` body.""" + return { + "image": status_payload()["current_image"], + "delivery": delivery_payload("delivered", "submit"), + "deduplicated": False, + } + + +def mock_engine( + aioclient_mock: AiohttpClientMocker, + *, + base: str = BASE, + **health_kwargs: Any, +) -> None: + """Register the endpoints polled by the coordinator for a healthy engine.""" + health = health_payload(**health_kwargs) + aioclient_mock.get(f"{base}/api/health", json=health) + aioclient_mock.get(f"{base}/api/status", json=status_payload()) + aioclient_mock.get(f"{base}/api/context", json=context_payload()) + aioclient_mock.get(f"{base}/api/config", json=config_payload()) + + +def make_entry( + *, api_key: str | None = None, unique_id: str | None = INSTANCE_ID, host: str = HOST +) -> MockConfigEntry: + """Return a config entry for the test engine.""" + data: dict[str, Any] = {CONF_HOST: host, CONF_PORT: PORT, CONF_PATH: "/"} + if api_key: + data[CONF_API_KEY] = api_key + return MockConfigEntry( + domain=DOMAIN, unique_id=unique_id, title=INSTANCE_NAME, data=data, version=1 + ) + + +def zeroconf_info( + *, + host: str = HOST, + port: int = PORT, + instance_id: str | None = INSTANCE_ID, + auth: str = "open", + api_version: str = "1", + min_api_version: str = "1", + path: str = "/", +) -> ZeroconfServiceInfo: + """Return a discovery record of ``_smartframe._tcp.local.``.""" + properties: dict[str, str | None] = { + "version": "1.0.0rc2", + "api_version": api_version, + "min_api_version": min_api_version, + "path": path, + "auth": auth, + } + if instance_id is not None: + properties["instance_id"] = instance_id + return ZeroconfServiceInfo( + ip_address=ip_address(host), + ip_addresses=[ip_address(host)], + hostname="engine.local.", + name=f"{INSTANCE_NAME}._smartframe._tcp.local.", + port=port, + properties=properties, + type="_smartframe._tcp.local.", + ) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..6dfa8bd --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,20 @@ +"""Shared fixtures.""" + +from __future__ import annotations + +from collections.abc import Generator +from unittest.mock import AsyncMock, patch + +import pytest + + +@pytest.fixture(autouse=True) +def auto_enable_custom_integrations(enable_custom_integrations: None) -> None: + """Let Home Assistant load ``custom_components/`` in every test.""" + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Stop config-flow tests from actually setting the entry up.""" + with patch("custom_components.smart_frame_engine.async_setup_entry", return_value=True) as mock: + yield mock diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..9676779 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,516 @@ +"""Tests for the API client (api.py).""" + +from __future__ import annotations + +from typing import Any + +import aiohttp +from homeassistant.core import HomeAssistant +from homeassistant.helpers.aiohttp_client import async_get_clientsession +import pytest +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.api import ( + HealthInfo, + SmartFrameApiError, + SmartFrameAuthError, + SmartFrameClient, + SmartFrameConnectionError, + SmartFrameIncompatibleError, + SmartFrameValidationError, + WithTtl, + compatibility_target, +) +from custom_components.smart_frame_engine.const import ALL_CAPABILITIES, SUPPORTED_API_VERSION + +from .common import ( + API_KEY, + BASE, + HOST, + PORT, + config_payload, + context_payload, + delivery_payload, + display_payload, + health_payload, + status_payload, +) + + +def _client(hass: HomeAssistant, api_key: str | None = None, path: str = "/") -> SmartFrameClient: + return SmartFrameClient(async_get_clientsession(hass), HOST, PORT, path, api_key) + + +def _last_call(mock: AiohttpClientMocker) -> tuple[str, Any, Any, Any]: + method, url, data, headers = mock.mock_calls[-1] + return method, url, data, headers + + +# -- Constants ------------------------------------------------------------------------- + + +def test_supported_version_and_capability_flags() -> None: + """The client speaks contract 1 and knows all 18 flags of API_CONTRACT.md.""" + assert SUPPORTED_API_VERSION == 1 + assert len(ALL_CAPABILITIES) == 18 + assert { + "activity_log", + "ambient_context", + "display_immich", + "display_smart_search", + "display_tmdb", + "ephemeral_images", + "family_mode", + "force_refresh", + "frame_push", + "frame_wakeup", + "now_playing", + "now_playing_dedup", + "playground", + "random_discovery", + "smart_mix", + "smart_mix_context", + "title_card", + "upload_image", + } == ALL_CAPABILITIES + + +# -- Compatibility handshake ----------------------------------------------------------- + + +@pytest.mark.parametrize( + ("api_version", "min_api_version", "expected"), + [ + (1, 1, None), # exactly our version + (2, 1, None), # newer engine still serving contract 1 + (5, 1, None), + (0, 0, "server"), # engine older than the integration + (2, 2, "integration"), # engine dropped contract 1 + (3, 2, "integration"), + ], +) +def test_compatibility_rule(api_version: int, min_api_version: int, expected: str | None) -> None: + """Compatible iff min_api_version <= 1 <= api_version; the target says who updates.""" + assert compatibility_target(api_version, min_api_version) == expected + health = HealthInfo.from_dict( + health_payload(api_version=api_version, min_api_version=min_api_version) + ) + assert health.is_compatible is (expected is None) + if expected is None: + health.ensure_compatible() + else: + with pytest.raises(SmartFrameIncompatibleError) as err: + health.ensure_compatible() + assert err.value.update_target == expected + + +# -- Health ---------------------------------------------------------------------------- + + +async def test_health_parsing(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """Health is parsed; unknown fields and unknown capability flags are tolerated.""" + payload = health_payload(auth="key", capabilities={"title_card", "flag_from_the_future"}) + payload["brand_new_field"] = {"anything": True} + aioclient_mock.get(f"{BASE}/api/health", json=payload) + + health = await _client(hass).async_get_health() + + assert health.version == "1.0.0rc2" + assert health.api_version == 1 + assert health.min_api_version == 1 + assert health.auth == "key" + assert health.requires_key is True + assert health.capabilities == {"title_card", "flag_from_the_future"} + assert health.instance_id == "3f2b8c1e-5d0a-4c7e-9b61-0a1d2e3f4a5b" + assert health.instance_name == "Smart Frame Engine 3f2b8c" + assert health.as_dict()["capabilities"] == ["flag_from_the_future", "title_card"] + + +async def test_health_without_instance_id( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """An engine older than 1.0.0rc2 simply has no instance id.""" + aioclient_mock.get( + f"{BASE}/api/health", json=health_payload(instance_id=None, instance_name=None) + ) + health = await _client(hass).async_get_health() + assert health.instance_id is None + assert health.instance_name is None + + +@pytest.mark.parametrize("body", [["not", "an", "object"], {"status": "ok"}, {"version": 1}]) +async def test_health_rejects_non_engines( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, body: Any +) -> None: + """Anything that does not look like an engine is a connection error.""" + aioclient_mock.get(f"{BASE}/api/health", json=body) + with pytest.raises(SmartFrameConnectionError): + await _client(hass).async_get_health() + + +async def test_health_invalid_json( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A web server answering HTML is not an engine.""" + aioclient_mock.get(f"{BASE}/api/health", text="hello") + with pytest.raises(SmartFrameConnectionError): + await _client(hass).async_get_health() + + +# -- Auth modes ------------------------------------------------------------------------ + + +@pytest.mark.parametrize("auth", ["open", "key", "password"]) +async def test_health_needs_no_credentials_in_any_mode( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, auth: str +) -> None: + """GET /api/health works without a key whatever the auth mode.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth=auth)) + health = await _client(hass).async_get_health() + assert health.auth == auth + assert health.requires_key is (auth != "open") + assert "X-API-Key" not in _last_call(aioclient_mock)[3] + + +async def test_key_is_sent_as_x_api_key_header( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The key goes in the X-API-Key header (never in the URL).""" + aioclient_mock.get(f"{BASE}/api/status", json=status_payload()) + await _client(hass, API_KEY).async_get_status() + _, url, _, headers = _last_call(aioclient_mock) + assert headers["X-API-Key"] == API_KEY + assert API_KEY not in str(url) + + +async def test_no_header_in_open_mode( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Without a configured key, no credential header is sent.""" + aioclient_mock.get(f"{BASE}/api/status", json=status_payload()) + await _client(hass).async_get_status() + assert "X-API-Key" not in _last_call(aioclient_mock)[3] + + +async def test_validate_key_uses_key_gated_endpoint( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """/api/status is public in key mode, so key validation hits /api/config.""" + aioclient_mock.get(f"{BASE}/api/config", json=config_payload()) + await _client(hass, API_KEY).async_validate_key() + method, url, _, headers = _last_call(aioclient_mock) + assert (method, url.path) == ("GET", "/api/config") + assert headers["X-API-Key"] == API_KEY + + +@pytest.mark.parametrize("method_name", ["async_get_status", "async_validate_key", "async_refresh"]) +async def test_401_is_an_auth_error( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, method_name: str +) -> None: + """HTTP 401 becomes SmartFrameAuthError.""" + body = {"detail": "Missing or invalid API key or session"} + for path in ("/api/status", "/api/config"): + aioclient_mock.get(f"{BASE}{path}", status=401, json=body) + aioclient_mock.post(f"{BASE}/api/refresh", status=401, json=body) + with pytest.raises(SmartFrameAuthError): + await getattr(_client(hass, "wrong"), method_name)() + + +# -- Errors ---------------------------------------------------------------------------- + + +async def test_422_string_detail(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """422 with a plain-text detail.""" + aioclient_mock.post(f"{BASE}/api/display/title-card", status=422, json={"detail": "text"}) + with pytest.raises(SmartFrameValidationError) as err: + await _client(hass).async_title_card("x") + assert err.value.status == 422 + assert err.value.detail == "text" + + +async def test_422_list_detail(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """422 with FastAPI-style validation errors is flattened into readable text.""" + aioclient_mock.post( + f"{BASE}/api/context", + status=422, + json={ + "detail": [ + {"loc": ["body", "ttl_minutes"], "msg": "less than or equal to 10080", "type": "x"} + ] + }, + ) + with pytest.raises(SmartFrameValidationError) as err: + await _client(hass).async_set_context(weather="rainy", ttl_minutes=99999) + assert err.value.detail == "ttl_minutes: less than or equal to 10080" + + +@pytest.mark.parametrize("status", [404, 409, 500, 502, 504]) +async def test_other_error_statuses( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, status: int +) -> None: + """Other error statuses carry the engine's detail.""" + aioclient_mock.post(f"{BASE}/api/refresh", status=status, json={"detail": "nope"}) + with pytest.raises(SmartFrameApiError) as err: + await _client(hass).async_refresh() + assert not isinstance(err.value, SmartFrameValidationError) + assert (err.value.status, err.value.detail) == (status, "nope") + + +@pytest.mark.parametrize("exc", [TimeoutError, aiohttp.ClientConnectionError("boom")]) +async def test_network_failures( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, exc: Any +) -> None: + """Timeouts and transport errors become SmartFrameConnectionError.""" + aioclient_mock.get(f"{BASE}/api/health", exc=exc) + with pytest.raises(SmartFrameConnectionError): + await _client(hass).async_get_health() + + +# -- URL building ---------------------------------------------------------------------- + + +async def test_ipv6_host_and_root_path( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """IPv6 hosts are bracketed and ROOT_PATH prefixes every endpoint.""" + client = SmartFrameClient(async_get_clientsession(hass), "2001:db8::1", 8080, "/frame/") + aioclient_mock.get("http://[2001:db8::1]:8080/frame/api/health", json=health_payload()) + await client.async_get_health() + assert client.base_url == "http://[2001:db8::1]:8080/frame" + + +async def test_base_url_at_root(hass: HomeAssistant) -> None: + """The default path is the server root.""" + assert _client(hass).base_url == f"{BASE}/" + + +# -- Status / config / family mode ----------------------------------------------------- + + +async def test_status_parsing(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """GET /api/status is parsed into typed models.""" + aioclient_mock.get(f"{BASE}/api/status", json=status_payload()) + status = await _client(hass).async_get_status() + + assert status.version == "1.0.0rc2" + assert status.uptime_s == 1234.5 + assert status.current_image is not None + assert status.current_image.source == "immich" + assert status.current_image.title == "Summer 2024" + assert status.current_image.processed_at is not None + assert status.ephemeral.active is False + assert status.frame.configured is True + assert status.frame.power_mode == "deepsleep" + assert status.frame.telemetry == {"battery": 80} + assert status.delivery.pending is False + assert status.delivery.last_delivered_at is not None + assert status.scheduler.enabled is True + assert status.scheduler.last_run_status == "ok" + assert status.scheduler.ambient.weather is not None + assert status.scheduler.ambient.weather.value == "rainy" + assert status.immich_configured is True + assert status.tmdb_configured is False + + +async def test_status_before_first_image( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """current_image is null before the first image.""" + payload = status_payload() + payload["current_image"] = None + aioclient_mock.get(f"{BASE}/api/status", json=payload) + assert (await _client(hass).async_get_status()).current_image is None + + +async def test_config_and_family_mode( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Family Mode is read from config.family.enabled and set with PUT /api/config.""" + aioclient_mock.get(f"{BASE}/api/config", json=config_payload(family_enabled=False)) + client = _client(hass, API_KEY) + assert (await client.async_get_config()).family_enabled is False + + aioclient_mock.put(f"{BASE}/api/config", json=config_payload(family_enabled=True)) + result = await client.async_set_family_mode(True) + + method, url, data, _ = _last_call(aioclient_mock) + assert (method, url.path) == ("PUT", "/api/config") + assert data == {"family": {"enabled": True}} + assert result.family_enabled is True + + +# -- Ambient context ------------------------------------------------------------------- + + +async def test_get_context(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """GET /api/context is parsed.""" + aioclient_mock.get(f"{BASE}/api/context", json=context_payload()) + view = await _client(hass, API_KEY).async_get_context() + assert view.family_active is True + assert view.smart_mix_enabled is True + assert view.extra_candidates == ("rainy",) + assert view.context.family_mode is not None + assert view.context.family_mode.value is True + assert view.context.presence is not None + assert view.context.presence.values == ("Alice", "Bob") + assert view.context.weather is None + + +async def test_set_context_with_ttls( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Bare values, per-field TTL objects and the request-wide ttl_minutes.""" + aioclient_mock.post(f"{BASE}/api/context", json=context_payload()) + await _client(hass, API_KEY).async_set_context( + presence=["Alice"], + family_mode=WithTtl(True, 30), + weather="rainy", + boost_tags=WithTtl(["beach", "birthday"], 120), + ttl_minutes=60, + ) + _, url, data, _ = _last_call(aioclient_mock) + assert url.path == "/api/context" + assert data == { + "presence": ["Alice"], + "family_mode": {"value": True, "ttl_minutes": 30}, + "weather": "rainy", + "boost_tags": {"values": ["beach", "birthday"], "ttl_minutes": 120}, + "ttl_minutes": 60, + } + assert "is_locked" not in data + + +async def test_set_context_requires_a_field(hass: HomeAssistant) -> None: + """An empty update is a programming error, not a request.""" + with pytest.raises(ValueError, match="At least one"): + await _client(hass, API_KEY).async_set_context() + + +async def test_clear_context(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """DELETE /api/context clears everything, or one field with ?field=.""" + aioclient_mock.delete(f"{BASE}/api/context", json=context_payload()) + client = _client(hass, API_KEY) + + await client.async_clear_context() + method, url, _, _ = _last_call(aioclient_mock) + assert (method, url.path, dict(url.query)) == ("DELETE", "/api/context", {}) + + await client.async_clear_context("weather") + assert dict(_last_call(aioclient_mock)[1].query) == {"field": "weather"} + + +# -- Display triggers ------------------------------------------------------------------ + + +async def test_refresh(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """POST /api/refresh returns the replayed rule and the display result.""" + aioclient_mock.post( + f"{BASE}/api/refresh", + json={ + "display": display_payload(), + "reason": "manual", + "rule_kind": "immich", + "rule_source": "smart_mix", + "entry_label": "Beach", + }, + ) + result = await _client(hass, API_KEY).async_refresh() + assert result.rule_source == "smart_mix" + assert result.entry_label == "Beach" + assert result.display.delivery is not None + assert result.display.delivery.status == "delivered" + assert result.display.image.title == "Summer 2024" + + +async def test_title_card_minimal_and_full( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Only provided options are sent; ttl_minutes=None means 'until cancelled' (null).""" + aioclient_mock.post(f"{BASE}/api/display/title-card", json=display_payload()) + client = _client(hass, API_KEY) + + await client.async_title_card("Hello") + assert _last_call(aioclient_mock)[2] == {"title": "Hello"} + + result = await client.async_title_card( + "Hello", + subtitle="sub", + caption="cap", + accent="blue", + ephemeral=False, + ttl_minutes=None, + hold_minutes=15, + push_to_fraimic=False, + ) + assert _last_call(aioclient_mock)[2] == { + "title": "Hello", + "subtitle": "sub", + "caption": "cap", + "accent": "blue", + "ephemeral": False, + "ttl_minutes": None, + "hold_minutes": 15, + "push_to_fraimic": False, + } + assert result.deduplicated is False + + await client.async_title_card("Hello", ttl_minutes=5) + assert _last_call(aioclient_mock)[2] == {"title": "Hello", "ttl_minutes": 5} + + +async def test_wakeup_non_blocking_returns_202( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """POST /api/fraimic/wakeup answers 202 WakeupAccepted without wait.""" + aioclient_mock.post( + f"{BASE}/api/fraimic/wakeup", status=202, json={"accepted": True, "pending": True} + ) + result = await _client(hass, API_KEY).async_wakeup() + assert (result.accepted, result.pending, result.outcome) == (True, True, None) + assert dict(_last_call(aioclient_mock)[1].query) == {} + + +async def test_wakeup_wait_returns_outcome( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """With wait=true the delivery outcome comes back (200).""" + aioclient_mock.post(f"{BASE}/api/fraimic/wakeup", json=delivery_payload("delivered", "wakeup")) + result = await _client(hass, API_KEY).async_wakeup(wait=True) + assert dict(_last_call(aioclient_mock)[1].query) == {"wait": "true"} + assert result.outcome is not None + assert result.outcome.status == "delivered" + assert result.outcome.reason == "wakeup" + + +@pytest.mark.parametrize(("http_status", "outcome"), [(200, "delivered"), (202, "queued")]) +async def test_push( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, http_status: int, outcome: str +) -> None: + """200 = delivered, 202 = frame unreachable and still queued; both are normal.""" + aioclient_mock.post( + f"{BASE}/api/fraimic/push", status=http_status, json=delivery_payload(outcome) + ) + result = await _client(hass, API_KEY).async_push(from_preview=True) + assert result.status == outcome + assert dict(_last_call(aioclient_mock)[1].query) == {"from_preview": "true"} + + +# -- Images ---------------------------------------------------------------------------- + + +async def test_images(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """current.jpg and preview.jpg return raw bytes; 404 means no image yet.""" + aioclient_mock.get(f"{BASE}/api/current.jpg", content=b"\xff\xd8current") + aioclient_mock.get(f"{BASE}/api/preview.jpg", status=404, json={"detail": "none"}) + client = _client(hass) + assert await client.async_get_current_image() == b"\xff\xd8current" + assert await client.async_get_preview_image() is None + + +async def test_image_server_error_is_raised( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Only 404 is swallowed for images.""" + aioclient_mock.get(f"{BASE}/api/current.jpg", status=500, text="boom") + with pytest.raises(SmartFrameApiError): + await _client(hass).async_get_current_image() diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py new file mode 100644 index 0000000..52b6b7c --- /dev/null +++ b/tests/test_config_flow.py @@ -0,0 +1,456 @@ +"""Tests for the config flow: manual setup, Zeroconf, reauth and options.""" + +from __future__ import annotations + +from typing import Any +from unittest.mock import AsyncMock, patch + +import aiohttp +from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF +from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType +import pytest +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.const import ( + CONF_PATH, + CONF_SCAN_INTERVAL, + DOMAIN, +) + +from .common import ( + API_KEY, + BASE, + HOST, + INSTANCE_ID, + INSTANCE_NAME, + OTHER_INSTANCE_ID, + PORT, + config_payload, + health_payload, + make_entry, + zeroconf_info, +) + +pytestmark = pytest.mark.usefixtures("mock_setup_entry") + + +async def _manual(hass: HomeAssistant) -> dict[str, Any]: + """Open the manual flow and submit host and port.""" + result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_USER}) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + return await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_HOST: HOST, CONF_PORT: PORT} + ) + + +async def _zeroconf(hass: HomeAssistant, **kwargs: Any) -> dict[str, Any]: + return await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_ZEROCONF}, data=zeroconf_info(**kwargs) + ) + + +# -- Manual setup ---------------------------------------------------------------------- + + +async def test_user_flow_open( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock +) -> None: + """Open auth mode: host/port -> entry, no key asked, unique id is the instance id.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth="open")) + + result = await _manual(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == INSTANCE_NAME + assert result["data"] == {CONF_HOST: HOST, CONF_PORT: PORT, CONF_PATH: "/"} + assert result["result"].unique_id == INSTANCE_ID + assert len(mock_setup_entry.mock_calls) == 1 + + +@pytest.mark.parametrize("auth", ["key", "password"]) +async def test_user_flow_key( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, auth: str +) -> None: + """key/password modes: ask for the key, reject a wrong one, accept the right one.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth=auth)) + aioclient_mock.get(f"{BASE}/api/config", status=401, json={"detail": "Missing"}) + + result = await _manual(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "auth" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: "wrong"} + ) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "invalid_auth"} + + aioclient_mock.clear_requests() + aioclient_mock.get(f"{BASE}/api/config", json=config_payload()) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: f" {API_KEY} "} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"][CONF_API_KEY] == API_KEY + assert aioclient_mock.mock_calls[-1][3]["X-API-Key"] == API_KEY + + +async def test_auth_step_cannot_connect( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A network failure while validating the key is reported as cannot_connect.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth="key")) + aioclient_mock.get(f"{BASE}/api/config", exc=aiohttp.ClientError("down")) + + result = await _manual(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["errors"] == {"base": "cannot_connect"} + + +async def test_user_flow_cannot_connect_then_recovers( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """An unreachable host shows an error and the form can be resubmitted.""" + aioclient_mock.get(f"{BASE}/api/health", exc=TimeoutError) + result = await _manual(hass) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "cannot_connect"} + + aioclient_mock.clear_requests() + aioclient_mock.get(f"{BASE}/api/health", json=health_payload()) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_HOST: HOST, CONF_PORT: PORT} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_user_flow_unexpected_error(hass: HomeAssistant) -> None: + """Anything unexpected is shown as 'unknown' instead of crashing the flow.""" + with patch( + "custom_components.smart_frame_engine.config_flow.SmartFrameClient.async_get_health", + side_effect=RuntimeError("bug"), + ): + result = await _manual(hass) + assert result["errors"] == {"base": "unknown"} + + +@pytest.mark.parametrize( + ("api_version", "min_api_version", "reason"), + [(0, 0, "server_outdated"), (2, 2, "integration_outdated")], +) +async def test_user_flow_incompatible( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + api_version: int, + min_api_version: int, + reason: str, +) -> None: + """An incompatible engine aborts and says which side to update.""" + aioclient_mock.get( + f"{BASE}/api/health", + json=health_payload(api_version=api_version, min_api_version=min_api_version), + ) + result = await _manual(hass) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason + + +async def test_user_flow_engine_without_instance_id( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """An engine older than 1.0.0rc2 cannot be keyed: abort with a clear reason.""" + aioclient_mock.get( + f"{BASE}/api/health", json=health_payload(instance_id=None, instance_name=None) + ) + result = await _manual(hass) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "instance_id_missing" + + +async def test_user_flow_duplicate_updates_address( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The same engine reached at a new address is not added twice; its host is updated.""" + entry = make_entry(host="192.168.1.99") + entry.add_to_hass(hass) + aioclient_mock.get(f"{BASE}/api/health", json=health_payload()) + + result = await _manual(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert entry.data[CONF_HOST] == HOST + assert len(hass.config_entries.async_entries(DOMAIN)) == 1 + + +# -- Zeroconf -------------------------------------------------------------------------- + + +async def test_zeroconf_open( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock +) -> None: + """auth=open: a plain confirmation, no key requested.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth="open")) + + result = await _zeroconf(hass, auth="open") + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "zeroconf_confirm" + assert result["data_schema"] is None + assert result["description_placeholders"] == { + "name": INSTANCE_NAME, + "host": HOST, + "port": str(PORT), + } + + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == INSTANCE_NAME + assert result["data"] == {CONF_HOST: HOST, CONF_PORT: PORT, CONF_PATH: "/"} + assert result["result"].unique_id == INSTANCE_ID + assert len(mock_setup_entry.mock_calls) == 1 + + +async def test_zeroconf_key_asks_for_api_key( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """auth=key: the confirmation step asks for, and validates, the API key.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth="key")) + aioclient_mock.get(f"{BASE}/api/config", status=401, json={"detail": "x"}) + + result = await _zeroconf(hass, auth="key") + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "zeroconf_confirm" + assert CONF_API_KEY in result["data_schema"].schema + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: "wrong"} + ) + assert result["errors"] == {"base": "invalid_auth"} + + aioclient_mock.clear_requests() + aioclient_mock.get(f"{BASE}/api/config", json=config_payload()) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"][CONF_API_KEY] == API_KEY + + +async def test_zeroconf_uses_path_from_txt( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """ROOT_PATH advertised in TXT is used for requests and stored.""" + aioclient_mock.get(f"{BASE}/frame/api/health", json=health_payload()) + + result = await _zeroconf(hass, path="/frame") + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"][CONF_PATH] == "/frame" + + +async def test_zeroconf_known_engine_updates_address_without_network( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A DHCP address change of a known engine is applied from the TXT record alone.""" + entry = make_entry(host="192.168.1.99") + entry.add_to_hass(hass) + + result = await _zeroconf(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert entry.data[CONF_HOST] == HOST + assert aioclient_mock.call_count == 0 + + +@pytest.mark.parametrize( + ("api_version", "min_api_version", "reason"), + [("0", "0", "server_outdated"), ("2", "2", "integration_outdated")], +) +async def test_zeroconf_incompatible_txt( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + api_version: str, + min_api_version: str, + reason: str, +) -> None: + """The TXT record alone is enough to reject an incompatible engine.""" + result = await _zeroconf(hass, api_version=api_version, min_api_version=min_api_version) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason + assert aioclient_mock.call_count == 0 + + +async def test_zeroconf_incompatible_health( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """GET /api/health is authoritative when TXT looked compatible.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(api_version=0, min_api_version=0)) + result = await _zeroconf(hass) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "server_outdated" + + +async def test_zeroconf_cannot_connect( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A discovered engine that does not answer aborts.""" + aioclient_mock.get(f"{BASE}/api/health", exc=aiohttp.ClientError("down")) + result = await _zeroconf(hass) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "cannot_connect" + + +async def test_zeroconf_instance_id_mismatch( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """If the engine at that address is not the one that advertised, do not trust it.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(instance_id=OTHER_INSTANCE_ID)) + result = await _zeroconf(hass) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "wrong_instance" + + +async def test_zeroconf_without_txt_instance_id_uses_health( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A record without instance_id still works when /api/health provides one.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload()) + result = await _zeroconf(hass, instance_id=None) + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == INSTANCE_ID + + +async def test_zeroconf_engine_without_any_instance_id( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """rc.1 engines (no instance id anywhere) are rejected with a clear reason.""" + aioclient_mock.get( + f"{BASE}/api/health", json=health_payload(instance_id=None, instance_name=None) + ) + result = await _zeroconf(hass, instance_id=None) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "instance_id_missing" + + +# -- Reauth ---------------------------------------------------------------------------- + + +async def test_reauth_success(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """A new valid key replaces the old one.""" + entry = make_entry(api_key="old-key") + entry.add_to_hass(hass) + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth="key")) + aioclient_mock.get(f"{BASE}/api/config", status=401, json={"detail": "x"}) + + result = await entry.start_reauth_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + assert result["description_placeholders"] == {"name": INSTANCE_NAME} + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: "still-wrong"} + ) + assert result["errors"] == {"base": "invalid_auth"} + + aioclient_mock.clear_requests() + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth="key")) + aioclient_mock.get(f"{BASE}/api/config", json=config_payload()) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert entry.data[CONF_API_KEY] == API_KEY + + +async def test_reauth_cannot_connect( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Network failures during reauth keep the form open.""" + entry = make_entry(api_key="old-key") + entry.add_to_hass(hass) + aioclient_mock.get(f"{BASE}/api/health", exc=TimeoutError) + + result = await entry.start_reauth_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["errors"] == {"base": "cannot_connect"} + + +async def test_reauth_wrong_instance( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Never store a key for a different engine that took over the address.""" + entry = make_entry(api_key="old-key") + entry.add_to_hass(hass) + aioclient_mock.get( + f"{BASE}/api/health", json=health_payload(auth="key", instance_id=OTHER_INSTANCE_ID) + ) + aioclient_mock.get(f"{BASE}/api/config", json=config_payload()) + + result = await entry.start_reauth_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "wrong_instance" + assert entry.data[CONF_API_KEY] == "old-key" + + +@pytest.mark.parametrize( + ("api_version", "min_api_version", "reason"), + [(0, 0, "server_outdated"), (2, 2, "integration_outdated")], +) +async def test_reauth_incompatible( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + api_version: int, + min_api_version: int, + reason: str, +) -> None: + """An engine that became incompatible aborts reauth with the right reason.""" + entry = make_entry(api_key="old-key") + entry.add_to_hass(hass) + aioclient_mock.get( + f"{BASE}/api/health", + json=health_payload(auth="key", api_version=api_version, min_api_version=min_api_version), + ) + aioclient_mock.get(f"{BASE}/api/config", json=config_payload()) + + result = await entry.start_reauth_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: API_KEY} + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason + + +# -- Options --------------------------------------------------------------------------- + + +async def test_options_flow_scan_interval(hass: HomeAssistant) -> None: + """The polling interval is configurable and defaults to 30 seconds.""" + entry = make_entry() + entry.add_to_hass(hass) + + result = await hass.config_entries.options.async_init(entry.entry_id) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "init" + assert next(iter(result["data_schema"].schema)).default() == 30 + + result = await hass.config_entries.options.async_configure( + result["flow_id"], {CONF_SCAN_INTERVAL: 45} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert entry.options == {CONF_SCAN_INTERVAL: 45} diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py new file mode 100644 index 0000000..31352b0 --- /dev/null +++ b/tests/test_diagnostics.py @@ -0,0 +1,44 @@ +"""Tests for diagnostics (secrets must never leak).""" + +from __future__ import annotations + +import json + +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component +from pytest_homeassistant_custom_component.components.diagnostics import ( + get_diagnostics_for_config_entry, +) +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker +from pytest_homeassistant_custom_component.typing import ClientSessionGenerator + +from custom_components.smart_frame_engine.const import ALL_CAPABILITIES + +from .common import API_KEY, INSTANCE_ID, make_entry, mock_engine + + +async def test_diagnostics_redacts_the_api_key( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + aioclient_mock: AiohttpClientMocker, +) -> None: + """Coordinator data, health and capabilities are exported; the API key is redacted.""" + mock_engine(aioclient_mock, auth="key") + entry = make_entry(api_key=API_KEY) + entry.add_to_hass(hass) + assert await async_setup_component(hass, "diagnostics", {}) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + diagnostics = await get_diagnostics_for_config_entry(hass, hass_client, entry) + + assert diagnostics["entry"]["data"]["api_key"] == "**REDACTED**" + assert API_KEY not in json.dumps(diagnostics) + assert diagnostics["entry"]["unique_id"] == INSTANCE_ID + assert diagnostics["capabilities"] == sorted(ALL_CAPABILITIES) + assert diagnostics["health"]["auth"] == "key" + assert diagnostics["health"]["api_version"] == 1 + assert diagnostics["health"]["instance_id"] == INSTANCE_ID + assert diagnostics["status"]["version"] == "1.0.0rc2" + assert diagnostics["ambient"]["family_active"] is True + assert diagnostics["coordinator"]["last_update_success"] is True diff --git a/tests/test_entity.py b/tests/test_entity.py new file mode 100644 index 0000000..c0b7a6f --- /dev/null +++ b/tests/test_entity.py @@ -0,0 +1,37 @@ +"""Tests for the base entity and the shared device.""" + +from __future__ import annotations + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity import EntityDescription +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.const import DOMAIN +from custom_components.smart_frame_engine.coordinator import SmartFrameCoordinator +from custom_components.smart_frame_engine.entity import SmartFrameEntity + +from .common import INSTANCE_ID, INSTANCE_NAME, make_entry, mock_engine + + +async def test_entity_shares_the_engine_device( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Entities attach to one device keyed on instance_id, with sw_version and a config URL.""" + mock_engine(aioclient_mock) + entry = make_entry() + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + coordinator: SmartFrameCoordinator = entry.runtime_data + + entity = SmartFrameEntity(coordinator, EntityDescription(key="status")) + + assert entity.unique_id == f"{INSTANCE_ID}_status" + assert entity.has_entity_name is True + info = entity.device_info + assert info["identifiers"] == {(DOMAIN, INSTANCE_ID)} + assert info["name"] == INSTANCE_NAME + assert info["manufacturer"] == "Smart Frame Engine" + assert info["sw_version"] == "1.0.0rc2" + assert info["configuration_url"] == "http://192.168.1.50:8080/" + assert entity.available is True diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..5cde5b6 --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,287 @@ +"""Tests for setup, the coordinator, the compatibility guardrail and Repair issues.""" + +from __future__ import annotations + +from datetime import timedelta + +import aiohttp +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant +from homeassistant.helpers import issue_registry as ir +from homeassistant.helpers.update_coordinator import UpdateFailed +from homeassistant.util import dt as dt_util +import pytest +from pytest_homeassistant_custom_component.common import ( + MockConfigEntry, + async_fire_time_changed, +) +from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker + +from custom_components.smart_frame_engine.const import ( + ALL_CAPABILITIES, + CAPABILITY_TITLE_CARD, + CONF_SCAN_INTERVAL, + DOMAIN, +) +from custom_components.smart_frame_engine.coordinator import SmartFrameCoordinator + +from .common import ( + API_KEY, + BASE, + INSTANCE_ID, + OTHER_INSTANCE_ID, + health_payload, + make_entry, + mock_engine, + status_payload, +) + + +def _issue(hass: HomeAssistant, entry_id: str) -> ir.IssueEntry | None: + return ir.async_get(hass).async_get_issue(DOMAIN, f"incompatible_api_{entry_id}") + + +async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + +# -- Happy path ------------------------------------------------------------------------ + + +async def test_setup_and_unload(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """A compatible engine loads; capabilities and data are cached; unload works.""" + mock_engine(aioclient_mock) + entry = make_entry() + await _setup(hass, entry) + + assert entry.state is ConfigEntryState.LOADED + coordinator: SmartFrameCoordinator = entry.runtime_data + assert coordinator.capabilities == ALL_CAPABILITIES + assert coordinator.data.health.instance_id == INSTANCE_ID + assert coordinator.data.status.version == "1.0.0rc2" + assert coordinator.data.ambient is not None + assert coordinator.data.ambient.family_active is True + assert _issue(hass, entry.entry_id) is None + + assert await hass.config_entries.async_unload(entry.entry_id) + assert entry.state is ConfigEntryState.NOT_LOADED + + +async def test_capabilities_adapt_to_the_engine( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Only advertised capabilities are cached; ambient context is skipped without its flag.""" + mock_engine(aioclient_mock, capabilities={CAPABILITY_TITLE_CARD}) + entry = make_entry() + await _setup(hass, entry) + + coordinator: SmartFrameCoordinator = entry.runtime_data + assert coordinator.capabilities == {CAPABILITY_TITLE_CARD} + assert coordinator.data.ambient is None + assert all(call[1].path != "/api/context" for call in aioclient_mock.mock_calls) + + +async def test_key_is_sent_when_configured( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Polling carries the configured API key.""" + mock_engine(aioclient_mock, auth="key") + await _setup(hass, make_entry(api_key=API_KEY)) + keyed = [c for c in aioclient_mock.mock_calls if c[1].path == "/api/context"] + assert keyed + assert all(c[3]["X-API-Key"] == API_KEY for c in keyed) + + +@pytest.mark.parametrize(("options", "seconds"), [({}, 30), ({CONF_SCAN_INTERVAL: 120}, 120)]) +async def test_scan_interval_option( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + options: dict[str, int], + seconds: int, +) -> None: + """The polling interval defaults to 30 s and follows the option.""" + mock_engine(aioclient_mock) + entry = make_entry() + entry.add_to_hass(hass) + hass.config_entries.async_update_entry(entry, options=options) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert entry.runtime_data.update_interval == timedelta(seconds=seconds) + + +# -- Failures -------------------------------------------------------------------------- + + +async def test_unreachable_engine_retries_setup( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A connection error during setup means 'not ready yet', not a broken entry.""" + aioclient_mock.get(f"{BASE}/api/health", exc=aiohttp.ClientError("down")) + entry = make_entry() + await _setup(hass, entry) + assert entry.state is ConfigEntryState.SETUP_RETRY + + +async def test_timeout_retries_setup( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """A timeout is handled like any other connection error.""" + aioclient_mock.get(f"{BASE}/api/health", exc=TimeoutError) + entry = make_entry() + await _setup(hass, entry) + assert entry.state is ConfigEntryState.SETUP_RETRY + + +async def test_401_starts_reauth(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: + """In key mode /api/status is public; the key-gated context call detects a bad key.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth="key")) + aioclient_mock.get(f"{BASE}/api/status", json=status_payload()) + aioclient_mock.get(f"{BASE}/api/context", status=401, json={"detail": "Missing"}) + entry = make_entry(api_key="revoked") + await _setup(hass, entry) + + assert entry.state is ConfigEntryState.SETUP_ERROR + flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) + assert [flow["context"]["source"] for flow in flows] == ["reauth"] + + +async def test_status_401_starts_reauth( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """In password mode /api/status itself needs the key.""" + aioclient_mock.get(f"{BASE}/api/health", json=health_payload(auth="password")) + aioclient_mock.get(f"{BASE}/api/status", status=401, json={"detail": "Missing"}) + entry = make_entry(api_key="revoked") + await _setup(hass, entry) + + assert entry.state is ConfigEntryState.SETUP_ERROR + assert hass.config_entries.flow.async_progress_by_handler(DOMAIN) + + +async def test_later_failure_marks_update_failed_and_recovers( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """After setup, a failed poll fails the update (entities unavailable) and then recovers.""" + mock_engine(aioclient_mock) + entry = make_entry() + await _setup(hass, entry) + coordinator: SmartFrameCoordinator = entry.runtime_data + + aioclient_mock.clear_requests() + aioclient_mock.get(f"{BASE}/api/health", exc=TimeoutError) + await coordinator.async_refresh() + assert coordinator.last_update_success is False + assert isinstance(coordinator.last_exception, UpdateFailed) + assert entry.state is ConfigEntryState.LOADED + + aioclient_mock.clear_requests() + mock_engine(aioclient_mock) + await coordinator.async_refresh() + assert coordinator.last_update_success is True + + +async def test_different_engine_at_same_address_is_refused( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """If another engine takes over the address, do not poll it as ours.""" + mock_engine(aioclient_mock, instance_id=OTHER_INSTANCE_ID) + entry = make_entry() + await _setup(hass, entry) + assert entry.state is ConfigEntryState.SETUP_RETRY + assert _issue(hass, entry.entry_id) is None + + +# -- Compatibility guardrail + Repair issues ------------------------------------------- + + +@pytest.mark.parametrize( + ("api_version", "min_api_version", "translation_key"), + [(0, 0, "server_outdated"), (2, 2, "integration_outdated")], +) +async def test_incompatible_engine_creates_repair_issue( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + api_version: int, + min_api_version: int, + translation_key: str, +) -> None: + """Incompatibility blocks setup and raises a persistent, non-fixable Repair issue.""" + mock_engine(aioclient_mock, api_version=api_version, min_api_version=min_api_version) + entry = make_entry() + await _setup(hass, entry) + + assert entry.state is ConfigEntryState.SETUP_RETRY + issue = _issue(hass, entry.entry_id) + assert issue is not None + assert issue.translation_key == translation_key + assert issue.severity is ir.IssueSeverity.ERROR + assert issue.is_persistent is True + assert issue.is_fixable is False + assert issue.translation_placeholders == { + "name": entry.title, + "server_version": "1.0.0rc2", + "api_version": str(api_version), + "min_api_version": str(min_api_version), + "supported_version": "1", + } + + +async def test_repair_issue_is_resolved_automatically( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """The issue disappears on its own once the engine is compatible again.""" + mock_engine(aioclient_mock) + entry = make_entry() + await _setup(hass, entry) + coordinator: SmartFrameCoordinator = entry.runtime_data + assert _issue(hass, entry.entry_id) is None + + # The engine is upgraded to a contract that dropped version 1. + aioclient_mock.clear_requests() + mock_engine(aioclient_mock, api_version=2, min_api_version=2) + await coordinator.async_refresh() + assert coordinator.last_update_success is False + issue = _issue(hass, entry.entry_id) + assert issue is not None + assert issue.translation_key == "integration_outdated" + + # The integration is updated (here: the engine serves contract 1 again). + aioclient_mock.clear_requests() + mock_engine(aioclient_mock, api_version=2, min_api_version=1) + await coordinator.async_refresh() + assert coordinator.last_update_success is True + assert _issue(hass, entry.entry_id) is None + + +async def test_issue_cleared_when_setup_retry_succeeds( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """An entry stuck in SETUP_RETRY by an old engine loads once the engine is updated.""" + mock_engine(aioclient_mock, api_version=0, min_api_version=0) + entry = make_entry() + await _setup(hass, entry) + assert _issue(hass, entry.entry_id) is not None + + aioclient_mock.clear_requests() + mock_engine(aioclient_mock) + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5)) + await hass.async_block_till_done() + + assert entry.state is ConfigEntryState.LOADED + assert _issue(hass, entry.entry_id) is None + + +async def test_removing_entry_deletes_issue( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Deleting the entry removes its Repair issue.""" + mock_engine(aioclient_mock, api_version=0, min_api_version=0) + entry = make_entry() + await _setup(hass, entry) + assert _issue(hass, entry.entry_id) is not None + + await hass.config_entries.async_remove(entry.entry_id) + await hass.async_block_till_done() + assert _issue(hass, entry.entry_id) is None diff --git a/tests/test_metadata.py b/tests/test_metadata.py new file mode 100644 index 0000000..9d63f4d --- /dev/null +++ b/tests/test_metadata.py @@ -0,0 +1,82 @@ +"""File-level checks that hassfest/HACS would otherwise only catch in CI.""" + +from __future__ import annotations + +import json +from pathlib import Path +import re +from typing import Any + +import pytest + +ROOT = Path(__file__).parent.parent +INTEGRATION = ROOT / "custom_components" / "smart_frame_engine" +PLACEHOLDER = re.compile(r"\{(\w+)\}") + + +def _load(path: Path) -> dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) # type: ignore[no-any-return] + + +def _leaves(node: Any, prefix: str = "") -> dict[str, str]: + if isinstance(node, dict): + out: dict[str, str] = {} + for key, value in node.items(): + out.update(_leaves(value, f"{prefix}.{key}" if prefix else key)) + return out + return {prefix: node} + + +def test_manifest_key_order_and_values() -> None: + """hassfest: domain, name, then every other key sorted alphabetically.""" + manifest = _load(INTEGRATION / "manifest.json") + keys = list(manifest) + assert keys[:2] == ["domain", "name"] + assert keys[2:] == sorted(keys[2:]) + assert manifest["domain"] == "smart_frame_engine" + assert manifest["iot_class"] == "local_polling" + assert manifest["config_flow"] is True + assert manifest["codeowners"] == ["@ant1fr"] + assert manifest["version"] == "1.0.0" + assert manifest["zeroconf"] == [{"type": "_smartframe._tcp.local."}] + + +def test_hacs_json() -> None: + """HACS metadata.""" + assert _load(ROOT / "hacs.json") == { + "name": "Smart Frame Engine", + "render_readme": True, + "homeassistant": "2026.1.0", + } + + +def test_strings_and_english_translation_are_byte_identical() -> None: + """strings.json and translations/en.json must not drift.""" + assert (INTEGRATION / "strings.json").read_bytes() == ( + INTEGRATION / "translations" / "en.json" + ).read_bytes() + + +def test_no_unresolved_translation_references() -> None: + """Custom integrations do not get ``[%key:...%]`` resolved: they would show literally.""" + assert "[%key:" not in (INTEGRATION / "translations" / "en.json").read_text(encoding="utf-8") + + +def test_french_translation_covers_everything() -> None: + """fr.json has exactly the keys of en.json and the same placeholders in every string.""" + english = _leaves(_load(INTEGRATION / "translations" / "en.json")) + french = _leaves(_load(INTEGRATION / "translations" / "fr.json")) + + assert set(french) == set(english) + for key, text in english.items(): + assert french[key].strip(), key + assert set(PLACEHOLDER.findall(french[key])) == set(PLACEHOLDER.findall(text)), key + + +@pytest.mark.parametrize("issue", ["integration_outdated", "server_outdated"]) +def test_repair_issues_are_translated(issue: str) -> None: + """Both Repair issues have a title and a description in both languages.""" + for lang in ("en", "fr"): + data = _load(INTEGRATION / "translations" / f"{lang}.json") + assert data["issues"][issue]["title"] + assert data["issues"][issue]["description"]