Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Official Home Assistant custom integration (`smart_frame_engine`) for **Smart Fr
- `custom_components/smart_frame_engine/image.py` — Live preview entity of currently rendered frame image
- `custom_components/smart_frame_engine/manifest.json` — HA integration metadata (strict `hassfest` key sorting)
- `custom_components/smart_frame_engine/sensor.py` — Active source/mode, media title, engine version, ambient context
- `custom_components/smart_frame_engine/services.py` — Service handlers (capability-gated, `ServiceValidationError`), registered once from `async_setup`
- `custom_components/smart_frame_engine/services.yaml` — Service definitions & UI selectors
- `custom_components/smart_frame_engine/strings.json` — Base UI & error strings (must stay identical to `translations/en.json`)
- `custom_components/smart_frame_engine/switch.py` — Family Mode toggle
Expand Down
44 changes: 42 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ Custom [Home Assistant](https://www.home-assistant.io/) integration for
[Smart Frame Engine](https://github.com/ant1fr/Smart-Frame-Engine), installable through
[HACS](https://hacs.xyz/) or manually.

> **Status:** work in progress. The foundation (discovery, setup, authentication, compatibility
> checks) is being built first; entities and services follow in later milestones.
> **Status:** work in progress. Discovery, setup, authentication, compatibility checks, entities
> and services are in place; blueprints follow in a later milestone.

## Requirements

Expand All @@ -25,6 +25,46 @@ Custom [Home Assistant](https://www.home-assistant.io/) integration for
Copy `custom_components/smart_frame_engine` into the `custom_components` folder of your Home
Assistant configuration directory and restart Home Assistant.

## What you get

Everything is grouped under one device per engine. Entities that depend on an optional engine
feature (a *capability*) only appear when your engine supports it, and show up after an engine
update without any manual step.

| Platform | Entities |
| --- | --- |
| Image | **Current image**: live preview of what the frame displays |
| Sensor | Engine version, image source, refresh mode, media title (with the image metadata as attributes), ambient context summary, last delivery, frame last seen, frame battery, Wi-Fi signal (disabled by default) |
| Binary sensor | Engine connected, frame online, frame charging, image pending delivery, temporary image, quiet hours |
| Switch | **Family Mode** (needs the `family_mode` capability) |
| Button | **Refresh image** (`force_refresh`), **Wake up frame** (`frame_wakeup`) |

The *media title* sensor exposes the image's provider details (which may include people or places)
as an attribute that is shown in the UI but never stored in the history, and diagnostics redact it.

## Services

If you have several engines, pass `config_entry_id` to choose one; it is optional otherwise.

- `smart_frame_engine.set_ambient_context` (needs `ambient_context`): `family_mode`, `presence`,
`weather`, `season`, `boost_tags`, `boost_people` and `ttl_minutes` (1 to 10080). Fields you
leave out keep their value; an empty text or list clears that field.
- `smart_frame_engine.clear_ambient_context` (needs `ambient_context`): optional `field` to clear
only one field.
- `smart_frame_engine.send_title_card` (needs `title_card`): `title`, `subtitle`, `caption`,
`accent`, `ephemeral`, `ttl_minutes`, `hold_minutes`, `push_to_fraimic`.

```yaml
action: smart_frame_engine.set_ambient_context
data:
weather: rainy
presence: [Alice, Bob]
ttl_minutes: 120
```

A service called on an engine that lacks the capability fails with a clear message instead of
sending a request.

## License

[MIT](LICENSE)
22 changes: 19 additions & 3 deletions custom_components/smart_frame_engine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,34 @@

from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import ConfigType

from .api import SmartFrameClient
from .const import CONF_PATH, DEFAULT_PATH
from .const import CONF_PATH, DEFAULT_PATH, DOMAIN
from .coordinator import (
SmartFrameConfigEntry,
SmartFrameCoordinator,
async_delete_compatibility_issue,
)
from .services import async_setup_services

# Entity platforms arrive in a later milestone; the coordinator and device already work.
PLATFORMS: list[Platform] = []
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)

PLATFORMS: list[Platform] = [
Platform.BINARY_SENSOR,
Platform.BUTTON,
Platform.IMAGE,
Platform.SENSOR,
Platform.SWITCH,
]


async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Register the services once; they resolve the target engine when called."""
async_setup_services(hass)
return True


async def async_setup_entry(hass: HomeAssistant, entry: SmartFrameConfigEntry) -> bool:
Expand Down
88 changes: 82 additions & 6 deletions custom_components/smart_frame_engine/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import asyncio
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from datetime import datetime
from datetime import UTC, datetime
import enum
import json
from typing import Any, Final, Literal, TypeIs
Expand Down Expand Up @@ -128,9 +128,11 @@ def _dt(value: Any) -> datetime | None:
if not isinstance(value, str):
return None
try:
return datetime.fromisoformat(value)
parsed = datetime.fromisoformat(value)
except ValueError:
return None
# The contract says "date-time"; treat a missing offset as UTC so every value is aware.
return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)


def _str_tuple(value: Any) -> tuple[str, ...]:
Expand Down Expand Up @@ -229,8 +231,16 @@ class CurrentImage:
ephemeral: bool = False
pushed: bool = True
content_key: str | None = None
sha256: str | None = None
processed_at: datetime | None = None
expires_at: datetime | None = None
# Provider metadata (date, location, people...): free-form per the contract.
details: Mapping[str, Any] = field(default_factory=dict)

@property
def identity(self) -> tuple[str | None, datetime | None]:
"""What changes when the displayed image changes (content hash + render time)."""
return (self.sha256, self.processed_at)

@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> CurrentImage:
Expand All @@ -242,8 +252,10 @@ def from_dict(cls, data: Mapping[str, Any]) -> CurrentImage:
ephemeral=_bool(data.get("ephemeral")),
pushed=_bool(data.get("pushed"), True),
content_key=_str(data.get("content_key")),
sha256=_str(data.get("sha256")),
processed_at=_dt(data.get("processed_at")),
expires_at=_dt(data.get("expires_at")),
details=dict(_mapping(data.get("details"))),
)


Expand Down Expand Up @@ -273,6 +285,38 @@ def from_dict(cls, data: Mapping[str, Any]) -> EphemeralState:
)


@dataclass(frozen=True, slots=True)
class FrameTelemetry:
"""Last known frame state (``FrameTelemetry``); updated whenever the frame is contacted."""

online: bool | None = None # None = the frame was never contacted
last_seen: datetime | None = None
last_checked: datetime | None = None
last_error: str | None = None
battery_percent: float | None = None
charging: bool | None = None
firmware_version: str | None = None
rssi: int | None = None

@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> FrameTelemetry:
"""Parse ``FrameTelemetry`` (and its nested ``FrameInfo``) tolerantly."""
info = _mapping(data.get("info"))
online = data.get("online")
charging = info.get("charging")
rssi = info.get("rssi")
return cls(
online=online if isinstance(online, bool) else None,
last_seen=_dt(data.get("last_seen")),
last_checked=_dt(data.get("last_checked")),
last_error=_str(data.get("last_error")),
battery_percent=_float(info.get("battery_percent")),
charging=charging if isinstance(charging, bool) else None,
firmware_version=_str(info.get("firmware_version")),
rssi=rssi if _is_int(rssi) else None,
)


@dataclass(frozen=True, slots=True)
class FrameState:
"""Configured frame characteristics (``FrameStatus``)."""
Expand All @@ -282,7 +326,7 @@ class FrameState:
panel_label: str | None = None
orientation: str | None = None
power_mode: str | None = None
telemetry: Mapping[str, Any] = field(default_factory=dict)
telemetry: FrameTelemetry = field(default_factory=FrameTelemetry)

@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> FrameState:
Expand All @@ -293,7 +337,28 @@ def from_dict(cls, data: Mapping[str, Any]) -> FrameState:
panel_label=_str(data.get("panel_label")),
orientation=_str(data.get("orientation")),
power_mode=_str(data.get("power_mode")),
telemetry=dict(_mapping(data.get("telemetry"))),
telemetry=FrameTelemetry.from_dict(_mapping(data.get("telemetry"))),
)


@dataclass(frozen=True, slots=True)
class LastDelivery:
"""The most recent successful upload to the frame (``LastDelivery``)."""

delivered_at: datetime | None = None
reason: str | None = None # submit | force | wakeup | worker
duration_s: float | None = None
size_bytes: int | None = None

@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> LastDelivery:
"""Parse ``LastDelivery`` tolerantly."""
size = data.get("bytes")
return cls(
delivered_at=_dt(data.get("delivered_at")),
reason=_str(data.get("reason")),
duration_s=_float(data.get("duration_s")),
size_bytes=size if _is_int(size) else None,
)


Expand All @@ -302,14 +367,15 @@ class DeliveryState:
"""Upload queue state (``DeliveryStatus``)."""

pending: bool = False
last_delivered_at: datetime | None = None
last_delivery: LastDelivery | None = None

@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> DeliveryState:
"""Parse ``DeliveryStatus`` tolerantly."""
last = data.get("last_delivery")
return cls(
pending=_bool(data.get("pending")),
last_delivered_at=_dt(_mapping(data.get("last_delivery")).get("delivered_at")),
last_delivery=LastDelivery.from_dict(last) if isinstance(last, Mapping) else None,
)


Expand Down Expand Up @@ -393,12 +459,16 @@ class SchedulerState:
hold_until: datetime | None = None
last_run_status: str | None = None
last_run_reason: str | None = None
# Which rule a refresh would replay: kind (immich, tmdb...) and source (pinned|smart_mix|last).
active_rule_kind: str | None = None
active_rule_source: str | None = None
ambient: AmbientState = field(default_factory=AmbientState)

@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> SchedulerState:
"""Parse ``SchedulerSnapshot`` tolerantly."""
last_run = _mapping(data.get("last_run"))
rule = _mapping(data.get("active_rule"))
return cls(
enabled=_bool(data.get("enabled")),
running=_bool(data.get("running")),
Expand All @@ -409,6 +479,8 @@ def from_dict(cls, data: Mapping[str, Any]) -> SchedulerState:
hold_until=_dt(data.get("hold_until")),
last_run_status=_str(last_run.get("status")),
last_run_reason=_str(last_run.get("reason")),
active_rule_kind=_str(rule.get("kind")),
active_rule_source=_str(rule.get("source")),
ambient=AmbientState.from_dict(_mapping(data.get("ambient"))),
)

Expand All @@ -427,6 +499,9 @@ class EngineStatus:
scheduler: SchedulerState
immich_configured: bool
tmdb_configured: bool
# Contract v1.2 (display only): the version spelled like the git/Docker tag, e.g.
# ``1.0.0-rc.3``. ``None`` on engines older than 1.0.0rc3.
release: str | None = None

@classmethod
def from_dict(cls, data: Any) -> EngineStatus:
Expand All @@ -446,6 +521,7 @@ def from_dict(cls, data: Any) -> EngineStatus:
scheduler=SchedulerState.from_dict(_mapping(data.get("scheduler"))),
immich_configured=_bool(services.get("immich")),
tmdb_configured=_bool(services.get("tmdb")),
release=_str(data.get("release")) or None,
)


Expand Down
Loading
Loading