From 8f8752d86b68d45f933eb6628fc3eff8a991eb07 Mon Sep 17 00:00:00 2001 From: emiliano Date: Fri, 13 Nov 2026 23:10:44 +0100 Subject: [PATCH 1/2] feat: Add support for Alexa Media Player timers - Introduced new configuration option for Alexa sensors in the integration. - Updated the controller to handle timers from Alexa Media Player's next_timer sensors. - Implemented a new source entity to parse and manage Alexa timers. - Enhanced configuration flow to include Alexa timer selection. - Added Italian translations for new features and updated existing strings. - Created tests to validate the functionality of Alexa timer integration. --- custom_components/second_hand/__init__.py | 4 +- custom_components/second_hand/config_flow.py | 11 +- custom_components/second_hand/const.py | 1 + custom_components/second_hand/controller.py | 20 +- .../second_hand/sources_entities.py | 209 +++++++++++++++++ custom_components/second_hand/strings.json | 14 +- .../second_hand/translations/en.json | 14 +- .../second_hand/translations/it.json | 96 ++++++++ docs/DEVELOPING.md | 3 + fixtures/alexa-next-timer-two-active.yaml | 183 +++++++++++++++ tests/test_alexa.py | 219 ++++++++++++++++++ 11 files changed, 757 insertions(+), 17 deletions(-) create mode 100644 custom_components/second_hand/sources_entities.py create mode 100644 custom_components/second_hand/translations/it.json create mode 100644 fixtures/alexa-next-timer-two-active.yaml create mode 100644 tests/test_alexa.py diff --git a/custom_components/second_hand/__init__.py b/custom_components/second_hand/__init__.py index 81b774e..b06c3da 100644 --- a/custom_components/second_hand/__init__.py +++ b/custom_components/second_hand/__init__.py @@ -7,7 +7,7 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady -from .const import CONF_ADAPTER, CONF_ADDRESS, CONF_ASSIST_DEVICES, CONF_HELPERS +from .const import CONF_ADAPTER, CONF_ADDRESS, CONF_ALEXA_SENSORS, CONF_ASSIST_DEVICES, CONF_HELPERS from .controller import ClockController PLATFORMS = [Platform.BINARY_SENSOR, Platform.BUTTON, Platform.SENSOR] @@ -20,6 +20,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: EchoWallClockConfigEntry hass, list(entry.options.get(CONF_ASSIST_DEVICES, [])), list(entry.options.get(CONF_HELPERS, [])), + alexa_sensors=list(entry.options.get(CONF_ALEXA_SENSORS, [])), ) stop_call_ins = None if address := entry.data.get(CONF_ADDRESS): @@ -87,4 +88,5 @@ async def _options_updated(hass: HomeAssistant, entry: EchoWallClockConfigEntry) entry.runtime_data.update_sources( list(entry.options.get(CONF_ASSIST_DEVICES, [])), list(entry.options.get(CONF_HELPERS, [])), + list(entry.options.get(CONF_ALEXA_SENSORS, [])), ) diff --git a/custom_components/second_hand/config_flow.py b/custom_components/second_hand/config_flow.py index c4eb523..f2da820 100644 --- a/custom_components/second_hand/config_flow.py +++ b/custom_components/second_hand/config_flow.py @@ -26,6 +26,7 @@ from .const import ( CONF_ADAPTER, CONF_ADDRESS, + CONF_ALEXA_SENSORS, CONF_ASSIST_DEVICES, CONF_HELPERS, ALLOW_TIMERS_ONLY, @@ -39,6 +40,7 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Echo Wall Clock" +ALEXA_MEDIA_DOMAIN = "alexa_media" # Alexa Media Player (HACS) def _timer_schema(hass: HomeAssistant, current: dict[str, Any]) -> vol.Schema: @@ -57,12 +59,19 @@ def _timer_schema(hass: HomeAssistant, current: dict[str, Any]) -> vol.Schema: vol.Optional(CONF_HELPERS, default=current.get(CONF_HELPERS, [])): EntitySelector( EntitySelectorConfig(domain="timer", multiple=True) ), + vol.Optional(CONF_ALEXA_SENSORS, default=current.get(CONF_ALEXA_SENSORS, [])): EntitySelector( + EntitySelectorConfig( + integration=ALEXA_MEDIA_DOMAIN, domain="sensor", device_class="timestamp", multiple=True + ) + ), } ) def _picked_something(user_input: dict[str, Any]) -> bool: - return bool(user_input.get(CONF_ASSIST_DEVICES) or user_input.get(CONF_HELPERS)) + return bool( + user_input.get(CONF_ASSIST_DEVICES) or user_input.get(CONF_HELPERS) or user_input.get(CONF_ALEXA_SENSORS) + ) async def _bluetooth_adapters() -> dict[str, str] | None: diff --git a/custom_components/second_hand/const.py b/custom_components/second_hand/const.py index 5e07ef9..d3e8935 100644 --- a/custom_components/second_hand/const.py +++ b/custom_components/second_hand/const.py @@ -6,6 +6,7 @@ CONF_ADAPTER = "adapter" CONF_ASSIST_DEVICES = "assist_devices" CONF_HELPERS = "helpers" +CONF_ALEXA_SENSORS = "alexa_sensors" # fork: Alexa Media Player next_timer sensors CONF_TIMERS_ONLY = "timers_only" ALLOW_TIMERS_ONLY = False diff --git a/custom_components/second_hand/controller.py b/custom_components/second_hand/controller.py index dab3532..8542eec 100644 --- a/custom_components/second_hand/controller.py +++ b/custom_components/second_hand/controller.py @@ -15,6 +15,7 @@ from .const import DOMAIN, ISSUE_ASSIST_UNSUPPORTED, POLL_SECONDS from .reconcile import ClockTimer, Command, Reconciler from .sources import AssistTimers, HelperTimers +from .sources_entities import EntityTimers, parse_alexa _LOGGER = logging.getLogger(__name__) @@ -42,11 +43,14 @@ def __init__( assist_devices: list[str], helpers: list[str], link: ClockLink | None = None, + *, + alexa_sensors: list[str] | None = None, ) -> None: self.hass = hass self._reconciler = Reconciler(dt_util.get_default_time_zone()) self._assist = AssistTimers(hass, assist_devices, self._changed, self._finished) self._helpers = HelperTimers(hass, helpers, self._changed, self._finished) + self._alexa = EntityTimers(hass, alexa_sensors or [], parse_alexa, self._changed, self._finished) self._link = link self._listeners: list[Callable[[], None]] = [] self._unsubs: list[CALLBACK_TYPE] = [] @@ -83,12 +87,16 @@ async def async_start(self) -> None: self._link.start(self._link_up, self._link_down) @callback - def update_sources(self, assist_devices: list[str], helpers: list[str]) -> None: + def update_sources( + self, assist_devices: list[str], helpers: list[str], alexa_sensors: list[str] | None = None + ) -> None: """Change which timers are shown without touching the link to the clock.""" self._assist.stop() self._helpers.stop() + self._alexa.stop() self._assist = AssistTimers(self.hass, assist_devices, self._changed, self._finished) self._helpers = HelperTimers(self.hass, helpers, self._changed, self._finished) + self._alexa = EntityTimers(self.hass, alexa_sensors or [], parse_alexa, self._changed, self._finished) self._start_sources() self._refresh(dt_util.utcnow()) @@ -106,10 +114,12 @@ def _start_sources(self) -> None: translation_key=ISSUE_ASSIST_UNSUPPORTED, ) self._helpers.start() + self._alexa.start() async def async_stop(self) -> None: self._assist.stop() self._helpers.stop() + self._alexa.stop() while self._unsubs: self._unsubs.pop()() self._cancel_tick() @@ -150,9 +160,13 @@ def _finished(self, key: str) -> None: def _poll(self, now: datetime) -> None: self._refresh(dt_util.utcnow()) + @callback + def _snapshot(self, now: datetime) -> dict[str, ClockTimer]: + return {**self._assist.snapshot(now), **self._helpers.snapshot(now), **self._alexa.snapshot(now)} + @callback def _refresh(self, now: datetime) -> None: - timers = {**self._assist.snapshot(now), **self._helpers.snapshot(now)} + timers = self._snapshot(now) changed = _visible(timers) != _visible(self.timers) self.timers = timers self._send(self._reconciler.update(now, timers)) @@ -164,7 +178,7 @@ def _refresh(self, now: datetime) -> None: @callback def _link_up(self) -> None: now = dt_util.utcnow() - self.timers = {**self._assist.snapshot(now), **self._helpers.snapshot(now)} + self.timers = self._snapshot(now) self._send(self._reconciler.on_connected(now, self.timers)) self._notify() diff --git a/custom_components/second_hand/sources_entities.py b/custom_components/second_hand/sources_entities.py new file mode 100644 index 0000000..6fd0de0 --- /dev/null +++ b/custom_components/second_hand/sources_entities.py @@ -0,0 +1,209 @@ +"""Timers read from other integrations' sensors: Alexa Media Player (`sensor._next_timer`). + +Fork addition. These integrations have no timer events, only sensors whose attributes list the timers, refreshed +by push or polling. So this source re-reads the picked sensors whenever they change, and works out on its own +when a timer finishes: an alarm at each timer's end time, plus a check for timers that drop off the sensor right +at their end (whichever comes first, once per timer). + +Parsing is pure and tolerant: anything it doesn't understand is skipped and logged at debug level, so a format +change in the other integration hides timers instead of breaking the clock. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping +from datetime import UTC, datetime, timedelta +import json +import logging +from typing import Any + +from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback +from homeassistant.helpers.event import async_track_point_in_utc_time, async_track_state_change_event +from homeassistant.util import dt as dt_util + +from .reconcile import SAME_END, ClockTimer + +_LOGGER = logging.getLogger(__name__) + +ALEXA_PREFIX = "alexa:" + +FINISH_WINDOW = timedelta(seconds=3) +"""A timer that drops off its sensor this close to its end time finished (it wasn't cancelled).""" + +_FORGET_FINISHED = timedelta(minutes=5) + +OnChange = Callable[[], None] +OnFinished = Callable[[str], None] +Parser = Callable[[Mapping[str, Any]], list[ClockTimer]] + + +# ---------------------------------------------------------------- Alexa Media Player + + +def parse_alexa(attrs: Mapping[str, Any]) -> list[ClockTimer]: + """Timers in the attributes of an Alexa Media Player `next_timer` sensor. + + Uses `sorted_active` (falling back to `sorted_all`): a list of notification dicts (older versions: JSON + strings, or `[id, dict]` pairs). Running timers have status ON and an absolute `triggerTime` in epoch ms; + without one, `process_timestamp + remainingTime`. Paused timers have status PAUSED. Alarms and reminders + (the `next_alarm` / `next_reminder` sensors) are skipped by `type`. + """ + items = _json_list(attrs.get("sorted_active")) + if items is None: + items = _json_list(attrs.get("sorted_all")) or [] + processed = _parse_time(attrs.get("process_timestamp")) + out: list[ClockTimer] = [] + for raw in items: + item = raw[1] if isinstance(raw, (list, tuple)) and len(raw) == 2 else raw + if not isinstance(item, Mapping): + _LOGGER.debug("Skipping an Alexa entry this version does not understand: %r", raw) + continue + if str(item.get("type", "")).lower() != "timer" or not item.get("id"): + continue + key = ALEXA_PREFIX + str(item["id"]) + name = str(item.get("timerLabel") or item.get("label") or "") + status = str(item.get("status", "")).upper() + if status == "PAUSED": + out.append(ClockTimer(key, None, name)) + continue + if status != "ON": + continue + ends_at = _epoch_ms(item.get("triggerTime")) + if ends_at is None and processed is not None and _is_number(item.get("remainingTime")): + ends_at = processed + timedelta(milliseconds=item["remainingTime"]) + if ends_at is None: + _LOGGER.debug("Skipping an Alexa timer without an end time: %r", item) + continue + out.append(ClockTimer(key, ends_at, name)) + return out + + +def _json_list(value: Any) -> list[Any] | None: + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + return None + return list(value) if isinstance(value, (list, tuple)) else None + + +def _is_number(value: Any) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def _epoch_ms(value: Any) -> datetime | None: + if not _is_number(value) or value <= 0: + return None + try: + return datetime.fromtimestamp(value / 1000, UTC) + except (OverflowError, OSError, ValueError): + return None + + +def _parse_time(value: Any) -> datetime | None: + if isinstance(value, datetime): + return value if value.tzinfo else None + if isinstance(value, str) and (parsed := dt_util.parse_datetime(value)) and parsed.tzinfo: + return parsed + return None + + +# ---------------------------------------------------------------- the source + + +class EntityTimers: + """Timers from the attributes of the sensors the user picked, read with `parser`.""" + + def __init__( + self, + hass: HomeAssistant, + entity_ids: Iterable[str], + parser: Parser, + on_change: OnChange, + on_finished: OnFinished, + ) -> None: + self._hass = hass + self._entities = list(entity_ids) + self._parser = parser + self._on_change = on_change + self._on_finished = on_finished + self._unsubs: list[CALLBACK_TYPE] = [] + self._ends: dict[str, datetime] = {} # running timers at the last read: key -> end time + self._alarms: dict[str, tuple[datetime, CALLBACK_TYPE]] = {} + self._finished: dict[str, datetime] = {} # key -> end time already reported, so it pulses once + + def start(self) -> bool: + if not self._entities: + return True + self._unsubs.append(async_track_state_change_event(self._hass, self._entities, self._state_changed)) + self._sync(dt_util.utcnow(), report=False) # timers already running at start get their alarms + return True + + def stop(self) -> None: + while self._unsubs: + self._unsubs.pop()() + for _, unsub in self._alarms.values(): + unsub() + self._alarms.clear() + + def snapshot(self, now: datetime) -> dict[str, ClockTimer]: + out: dict[str, ClockTimer] = {} + for entity_id in self._entities: + state = self._hass.states.get(entity_id) + if state is None: + continue + try: + timers = self._parser(state.attributes) + except Exception: # noqa: BLE001 (a format we don't know must not break the clock) + _LOGGER.debug("Couldn't read timers from %s", entity_id, exc_info=True) + continue + for timer in timers: + out.setdefault(timer.key, timer) + return out + + @callback + def _state_changed(self, event: Event) -> None: + self._sync(dt_util.utcnow(), report=True) + self._on_change() + + @callback + def _sync(self, now: datetime, report: bool) -> None: + """Re-read the sensors: report timers that dropped off at their end, and move the end-time alarms.""" + timers = self.snapshot(now) + running = {key: t.ends_at for key, t in timers.items() if t.ends_at is not None} + if report: + for key, ends_at in self._ends.items(): + if key not in timers and abs(ends_at - now) <= FINISH_WINDOW: + self._finish(key, ends_at) + self._ends = running + for key in [k for k in self._alarms if k not in running]: + self._alarms.pop(key)[1]() + for key, ends_at in running.items(): + alarm = self._alarms.get(key) + if alarm is not None and abs(alarm[0] - ends_at) < SAME_END: + continue + if alarm is not None: + alarm[1]() + del self._alarms[key] + if ends_at > now: + self._alarms[key] = (ends_at, async_track_point_in_utc_time(self._hass, self._alarm(key), ends_at)) + for key in [k for k, at in self._finished.items() if at < now - _FORGET_FINISHED]: + del self._finished[key] + + def _alarm(self, key: str) -> Callable[[datetime], None]: + @callback + def fire(_: datetime) -> None: + if (alarm := self._alarms.pop(key, None)) is None: + return + self._finish(key, alarm[0]) + self._on_change() + + return fire + + @callback + def _finish(self, key: str, ends_at: datetime) -> None: + done = self._finished.get(key) + if done is not None and abs(done - ends_at) < SAME_END: + return + self._finished[key] = ends_at + self._on_finished(key) diff --git a/custom_components/second_hand/strings.json b/custom_components/second_hand/strings.json index c91f64e..9e932d5 100644 --- a/custom_components/second_hand/strings.json +++ b/custom_components/second_hand/strings.json @@ -32,15 +32,16 @@ }, "timers": { "title": "Which timers should this clock show?", - "description": "Select the voice assistants and timer helpers you want to show on this clock.", + "description": "Select the voice assistants, timer helpers and Alexa devices you want to show on this clock. For Alexa, pick the \"Next timer\" sensors of Alexa Media Player.", "data": { "assist_devices": "Voice assistants", - "helpers": "Timer helpers" + "helpers": "Timer helpers", + "alexa_sensors": "Alexa timers (Alexa Media Player)" } } }, "error": { - "nothing_picked": "Pick at least one voice assistant or timer helper.", + "nothing_picked": "Pick at least one voice assistant, timer helper or Alexa timer sensor.", "not_found": "No clock in pairing mode was found. Check that its light pulses orange and that it's within range of this Home Assistant's Bluetooth adapter, then try again.", "pair_failed": "Pairing didn't work. Put the clock back in pairing mode, move it closer to the adapter, and try again." }, @@ -57,15 +58,16 @@ "step": { "init": { "title": "Which timers should this clock show?", - "description": "Select the voice assistants and timer helpers you want to show on this clock.", + "description": "Select the voice assistants, timer helpers and Alexa devices you want to show on this clock. For Alexa, pick the \"Next timer\" sensors of Alexa Media Player.", "data": { "assist_devices": "Voice assistants", - "helpers": "Timer helpers" + "helpers": "Timer helpers", + "alexa_sensors": "Alexa timers (Alexa Media Player)" } } }, "error": { - "nothing_picked": "Pick at least one voice assistant or timer helper." + "nothing_picked": "Pick at least one voice assistant, timer helper or Alexa timer sensor." } }, "entity": { diff --git a/custom_components/second_hand/translations/en.json b/custom_components/second_hand/translations/en.json index c91f64e..9e932d5 100644 --- a/custom_components/second_hand/translations/en.json +++ b/custom_components/second_hand/translations/en.json @@ -32,15 +32,16 @@ }, "timers": { "title": "Which timers should this clock show?", - "description": "Select the voice assistants and timer helpers you want to show on this clock.", + "description": "Select the voice assistants, timer helpers and Alexa devices you want to show on this clock. For Alexa, pick the \"Next timer\" sensors of Alexa Media Player.", "data": { "assist_devices": "Voice assistants", - "helpers": "Timer helpers" + "helpers": "Timer helpers", + "alexa_sensors": "Alexa timers (Alexa Media Player)" } } }, "error": { - "nothing_picked": "Pick at least one voice assistant or timer helper.", + "nothing_picked": "Pick at least one voice assistant, timer helper or Alexa timer sensor.", "not_found": "No clock in pairing mode was found. Check that its light pulses orange and that it's within range of this Home Assistant's Bluetooth adapter, then try again.", "pair_failed": "Pairing didn't work. Put the clock back in pairing mode, move it closer to the adapter, and try again." }, @@ -57,15 +58,16 @@ "step": { "init": { "title": "Which timers should this clock show?", - "description": "Select the voice assistants and timer helpers you want to show on this clock.", + "description": "Select the voice assistants, timer helpers and Alexa devices you want to show on this clock. For Alexa, pick the \"Next timer\" sensors of Alexa Media Player.", "data": { "assist_devices": "Voice assistants", - "helpers": "Timer helpers" + "helpers": "Timer helpers", + "alexa_sensors": "Alexa timers (Alexa Media Player)" } } }, "error": { - "nothing_picked": "Pick at least one voice assistant or timer helper." + "nothing_picked": "Pick at least one voice assistant, timer helper or Alexa timer sensor." } }, "entity": { diff --git a/custom_components/second_hand/translations/it.json b/custom_components/second_hand/translations/it.json new file mode 100644 index 0000000..8671a18 --- /dev/null +++ b/custom_components/second_hand/translations/it.json @@ -0,0 +1,96 @@ +{ + "config": { + "step": { + "user": { + "title": "Aggiungi un Echo Wall Clock", + "data": { + "name": "Nome" + } + }, + "no_bluetooth": { + "title": "Bluetooth non disponibile", + "description": "Home Assistant non raggiunge un adattatore Bluetooth Classic, e l'orologio ne ha bisogno. Puoi comunque aggiungere Second Hand per il sensore Timer, ma nulla verrà inviato a un orologio." + }, + "pair_mode": { + "title": "Metti l'orologio in modalità di associazione", + "description": "Tieni premuto il pulsante blu di associazione sul retro dell'orologio (fino a 10 secondi) finché la luce sul davanti non pulsa in arancione. Poi seleziona Invia.", + "data": { + "adapter": "Adattatore Bluetooth", + "timers_only": "Salta l'associazione (solo timer)" + } + }, + "choose": { + "title": "Quale orologio?", + "data": { + "address": "Orologio" + }, + "description": "Più di un orologio è in modalità di associazione. Scegline uno, oppure annulla, lascia in associazione un solo orologio e riprova." + }, + "confirm": { + "title": "Associare questo orologio?", + "description": "Trovato {name} ({address}).\n\nUn orologio funziona con un solo dispositivo alla volta: associarlo qui lo scollega da ciò a cui era associato, per esempio un Echo. Seleziona Invia per associarlo." + }, + "timers": { + "title": "Quali timer deve mostrare questo orologio?", + "description": "Seleziona gli assistenti vocali, gli helper timer e i dispositivi Alexa da mostrare su questo orologio. Per Alexa, scegli i sensori \"Prossimo timer\" di Alexa Media Player.", + "data": { + "assist_devices": "Assistenti vocali", + "helpers": "Helper timer", + "alexa_sensors": "Timer Alexa (Alexa Media Player)" + } + } + }, + "error": { + "nothing_picked": "Scegli almeno un assistente vocale, un helper timer o un sensore timer Alexa.", + "not_found": "Nessun orologio in modalità di associazione trovato. Controlla che la luce pulsi in arancione e che sia nel raggio dell'adattatore Bluetooth di Home Assistant, poi riprova.", + "pair_failed": "L'associazione non è riuscita. Rimetti l'orologio in modalità di associazione, avvicinalo all'adattatore e riprova." + }, + "progress": { + "search": "Ricerca di un orologio in modalità di associazione (fino a 30 secondi)…", + "pair": "Associazione con l'orologio in corso. Può richiedere qualche minuto…" + }, + "abort": { + "already_configured": "Questo orologio è già configurato in questo Home Assistant.", + "no_bluetooth": "Home Assistant non raggiunge un adattatore Bluetooth Classic, e l'orologio ne ha bisogno. In un container, controlla la rete host e il mount di /run/dbus dell'host." + } + }, + "options": { + "step": { + "init": { + "title": "Quali timer deve mostrare questo orologio?", + "description": "Seleziona gli assistenti vocali, gli helper timer e i dispositivi Alexa da mostrare su questo orologio. Per Alexa, scegli i sensori \"Prossimo timer\" di Alexa Media Player.", + "data": { + "assist_devices": "Assistenti vocali", + "helpers": "Helper timer", + "alexa_sensors": "Timer Alexa (Alexa Media Player)" + } + } + }, + "error": { + "nothing_picked": "Scegli almeno un assistente vocale, un helper timer o un sensore timer Alexa." + } + }, + "entity": { + "sensor": { + "timers": { + "name": "Timer" + } + }, + "binary_sensor": { + "connected": { + "name": "Connesso" + } + }, + "button": { + "sync_time": { + "name": "Sincronizza ora" + } + } + }, + "issues": { + "assist_timers_unsupported": { + "title": "I timer vocali non compaiono sull'orologio", + "description": "Un aggiornamento di Home Assistant ha cambiato il funzionamento dei timer vocali, quindi Second Hand non riesce a leggerli. I timer degli helper continuano a comparire. Cerca un aggiornamento di Second Hand o apri una issue." + } + } +} diff --git a/docs/DEVELOPING.md b/docs/DEVELOPING.md index a832495..50702bd 100644 --- a/docs/DEVELOPING.md +++ b/docs/DEVELOPING.md @@ -11,6 +11,9 @@ VIRTUAL_ENV=.venv uv pip install pytest-homeassistant-custom-component - `reconcile.py`: desired timers in, clock commands out. Pure; no Home Assistant. - `sources.py`: Assist (voice satellite) timers and timer helpers. All use of HA's internal TimerManager is in this file. +- `sources_entities.py` (fork): timers read from other integrations' sensors (Alexa Media Player + `next_timer`). Pure parser plus a source that detects the end of a timer on its own; real attributes in + `fixtures/alexa-next-timer-two-active.yaml`. - `controller.py`: one clock, wiring sources, reconciler and the link. - `link.py`: connect, Discover handshake, hold the link, retry with backoff. Transport-agnostic. - `bluez.py`: BlueZ over D-Bus (pairing agent, search, call-in listener) and the RFCOMM socket. Linux only. diff --git a/fixtures/alexa-next-timer-two-active.yaml b/fixtures/alexa-next-timer-two-active.yaml new file mode 100644 index 0000000..7976fe8 --- /dev/null +++ b/fixtures/alexa-next-timer-two-active.yaml @@ -0,0 +1,183 @@ +# Attributes of sensor.echo_time_prossimo_timer (Alexa Media Player), two running timers (15 and 20 minutes), +# copied from Developer tools > States on 2026-11-13 at 22:51 (+01:00). sorted_active was identical to +# sorted_all; the YAML anchor keeps the file short without changing the data. +recurrence: Never Repeat +process_timestamp: '2026-11-13T22:51:22.712927+01:00' +prior_value: '2026-11-13T23:06:21+01:00' +total_active: 2 +total_all: 2 +status: 'ON' +dismissed: null +timer: null +device_class: timestamp +icon: mdi:timer-outline +friendly_name: Echo time Prossimo timer +brief: + active: + - id: A1P493D1054TAW-G095590263470531-4ed6dbdc-5a3c-4ca6-89e4-caae2feed9c7_TIMER + label: null + status: 'ON' + type: Timer + version: '3' + remainingTime: 884000 + lastUpdatedDate: 1794606667125 + - id: A1P493D1054TAW-G095590263470531-55ae7a73-0965-475e-9e49-2442d9dea25c_TIMER + label: null + status: 'ON' + type: Timer + version: '3' + remainingTime: 1184000 + lastUpdatedDate: 1794606667540 + all: + - id: A1P493D1054TAW-G095590263470531-4ed6dbdc-5a3c-4ca6-89e4-caae2feed9c7_TIMER + label: null + status: 'ON' + type: Timer + version: '3' + remainingTime: 884000 + lastUpdatedDate: 1794606667125 + - id: A1P493D1054TAW-G095590263470531-55ae7a73-0965-475e-9e49-2442d9dea25c_TIMER + label: null + status: 'ON' + type: Timer + version: '3' + remainingTime: 1184000 + lastUpdatedDate: 1794606667540 +sorted_all: &timers + - alarmLabel: null + alarmTime: 0 + assigner: null + automationId: null + createdDate: 1794606666828 + deferredAtTime: null + deliveryMetadata: null + deliveryType: null + deviceName: null + deviceSerialNumber: G095590263470531 + deviceType: A1P493D1054TAW + extensibleAttribute: null + followUpMetadata: null + geoLocationTriggerData: null + id: A1P493D1054TAW-G095590263470531-4ed6dbdc-5a3c-4ca6-89e4-caae2feed9c7_TIMER + instanceState: null + lastOccurrenceTimeInMilli: 0 + lastTriggerTimeInUtc: null + lastUpdatedDate: 1794606667125 + loopCount: null + mrmGroupContext: null + musicAlarmId: null + musicEntity: null + notificationIndex: 4ed6dbdc-5a3c-4ca6-89e4-caae2feed9c7_TIMER + originalDate: null + originalDurationInMillis: 900000 + originalTime: null + personProfile: null + primaryDeviceState: null + provider: null + rRuleData: null + recurrenceEligibility: false + recurringPattern: null + remainingTime: 884000 + reminderAppLabel: null + reminderLabel: null + reminderSubLabel: null + showDeregisteredWarning: null + skillInfo: + asin: null + iconUrl: null + id: AlexaTimeMachineService + name: null + stage: null + status: null + sleepTrackingAlarmProperties: null + snoozedToTime: null + sound: + displayName: Simple Timer + dynamicTone: false + folder: null + id: system_alerts_melodic_02 + isChildDirected: false + numAssets: 0 + pricing: null + providerId: ECHO + sampleUrl: https://s3.amazonaws.com/deeappservice.prod.notificationtones/system_alerts_melodic_02.mp3 + sampleVideoUrl: null + skillUrl: null + status: 'ON' + targetPersonProfiles: null + taskMetadata: null + timeZoneId: null + timerLabel: null + tmwNotificationProperties: null + triggerTime: 1794607566809 + type: Timer + version: '3' + - alarmLabel: null + alarmTime: 0 + assigner: null + automationId: null + createdDate: 1794606667231 + deferredAtTime: null + deliveryMetadata: null + deliveryType: null + deviceName: null + deviceSerialNumber: G095590263470531 + deviceType: A1P493D1054TAW + extensibleAttribute: null + followUpMetadata: null + geoLocationTriggerData: null + id: A1P493D1054TAW-G095590263470531-55ae7a73-0965-475e-9e49-2442d9dea25c_TIMER + instanceState: null + lastOccurrenceTimeInMilli: 0 + lastTriggerTimeInUtc: null + lastUpdatedDate: 1794606667540 + loopCount: null + mrmGroupContext: null + musicAlarmId: null + musicEntity: null + notificationIndex: 55ae7a73-0965-475e-9e49-2442d9dea25c_TIMER + originalDate: null + originalDurationInMillis: 1200000 + originalTime: null + personProfile: null + primaryDeviceState: null + provider: null + rRuleData: null + recurrenceEligibility: false + recurringPattern: null + remainingTime: 1184000 + reminderAppLabel: null + reminderLabel: null + reminderSubLabel: null + showDeregisteredWarning: null + skillInfo: + asin: null + iconUrl: null + id: AlexaTimeMachineService + name: null + stage: null + status: null + sleepTrackingAlarmProperties: null + snoozedToTime: null + sound: + displayName: Simple Timer + dynamicTone: false + folder: null + id: system_alerts_melodic_02 + isChildDirected: false + numAssets: 0 + pricing: null + providerId: ECHO + sampleUrl: https://s3.amazonaws.com/deeappservice.prod.notificationtones/system_alerts_melodic_02.mp3 + sampleVideoUrl: null + skillUrl: null + status: 'ON' + targetPersonProfiles: null + taskMetadata: null + timeZoneId: null + timerLabel: null + tmwNotificationProperties: null + triggerTime: 1794607867212 + type: Timer + version: '3' +sorted_active: *timers diff --git a/tests/test_alexa.py b/tests/test_alexa.py new file mode 100644 index 0000000..e237815 --- /dev/null +++ b/tests/test_alexa.py @@ -0,0 +1,219 @@ +"""Fork: timers from Alexa Media Player's next_timer sensors.""" + +from __future__ import annotations + +import asyncio +from datetime import UTC, datetime, timedelta +import json +from pathlib import Path +from typing import Any + +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType +from homeassistant.util import dt as dt_util +from pytest_homeassistant_custom_component.common import MockConfigEntry +import yaml + +from custom_components.second_hand import protocol +from custom_components.second_hand.const import CONF_ALEXA_SENSORS, CONF_ASSIST_DEVICES, CONF_HELPERS, DOMAIN +from custom_components.second_hand.controller import ClockController +from custom_components.second_hand.sources_entities import parse_alexa + +from .test_integration import FakeLink, _settle + +FIXTURE = Path(__file__).parent.parent / "fixtures" / "alexa-next-timer-two-active.yaml" +ECHO = "sensor.echo_kitchen_next_timer" +ID1 = "A1P493D1054TAW-G095590263470531-4ed6dbdc-5a3c-4ca6-89e4-caae2feed9c7_TIMER" +ID2 = "A1P493D1054TAW-G095590263470531-55ae7a73-0965-475e-9e49-2442d9dea25c_TIMER" + + +def _item(timer_id: str, ends_at: datetime | None, status: str = "ON", label: str | None = None) -> dict[str, Any]: + """One notification like Alexa Media Player lists it (the fields we read, plus a few we don't).""" + return { + "id": timer_id, + "type": "Timer", + "status": status, + "timerLabel": label, + "label": None, + "remainingTime": 600000, + "originalDurationInMillis": 900000, + "triggerTime": int(ends_at.timestamp() * 1000) if ends_at else 0, + "deviceSerialNumber": "G095590263470531", + } + + +def _attrs(*items: dict[str, Any]) -> dict[str, Any]: + return { + "process_timestamp": dt_util.now().isoformat(), + "total_active": len(items), + "sorted_active": list(items), + "sorted_all": list(items), + "device_class": "timestamp", + "friendly_name": "Echo Kitchen Next timer", + } + + +def _set(hass: HomeAssistant, *items: dict[str, Any]) -> None: + ends = [datetime.fromtimestamp(i["triggerTime"] / 1000, UTC) for i in items if i["triggerTime"]] + state = min(ends).isoformat() if ends else "unavailable" + hass.states.async_set(ECHO, state, _attrs(*items)) + + +# ---------------------------------------------------------------- parser + + +def test_parse_real_sensor() -> None: + attrs = yaml.safe_load(FIXTURE.read_text(encoding="utf-8")) + timers = {t.key: t for t in parse_alexa(attrs)} + assert set(timers) == {f"alexa:{ID1}", f"alexa:{ID2}"} + # triggerTime is epoch milliseconds: created 22:51:06.828 + 15 min. + assert timers[f"alexa:{ID1}"].ends_at == datetime(2026, 11, 13, 22, 6, 6, 809000, tzinfo=UTC) + assert timers[f"alexa:{ID2}"].ends_at == datetime(2026, 11, 13, 22, 11, 7, 212000, tzinfo=UTC) + assert all(t.name == "" and not t.paused for t in timers.values()) + + +def test_parse_older_formats_and_fallbacks() -> None: + ends = datetime(2026, 11, 13, 22, 0, tzinfo=UTC) + item = _item("a", ends, label="pasta") + # JSON strings of [id, dict] pairs, as older Alexa Media Player versions wrote them. + (timer,) = parse_alexa({"sorted_active": json.dumps([["a", item]])}) + assert timer.key == "alexa:a" and timer.ends_at == ends and timer.name == "pasta" + # No triggerTime: process_timestamp + remainingTime. + no_trigger = {**item, "triggerTime": None, "remainingTime": 60000} + (timer,) = parse_alexa({"sorted_active": [no_trigger], "process_timestamp": "2026-11-13T22:00:00+00:00"}) + assert timer.ends_at == ends + timedelta(minutes=1) + # Only sorted_all: finished (OFF) timers in it are skipped. + (timer,) = parse_alexa({"sorted_all": [item, _item("b", ends, status="OFF")]}) + assert timer.key == "alexa:a" + + +def test_parse_paused_and_skips_what_it_does_not_understand() -> None: + ends = datetime(2026, 11, 13, 22, 0, tzinfo=UTC) + alarm = {**_item("alarm", ends), "type": "Alarm"} + timers = parse_alexa( + {"sorted_active": [_item("p", None, status="PAUSED"), alarm, 42, "x", {"type": "Timer"}, _item("ok", ends)]} + ) + assert [(t.key, t.paused) for t in timers] == [("alexa:p", True), ("alexa:ok", False)] + assert parse_alexa({}) == [] + assert parse_alexa({"sorted_active": "not json"}) == [] + assert parse_alexa({"sorted_active": [_item("bad", None, status="ON")]}) == [] + + +# ---------------------------------------------------------------- with the controller + + +async def test_alexa_timer_lifecycle(hass: HomeAssistant) -> None: + link = FakeLink() + controller = ClockController(hass, [], [], link, alexa_sensors=[ECHO]) + await controller.async_start() + link.up() + assert link.labels() == ["timeinfo", "ClearIndicator"] + + ends1 = dt_util.utcnow() + timedelta(minutes=15) + ends2 = dt_util.utcnow() + timedelta(minutes=20) + _set(hass, _item(ID1, ends1), _item(ID2, ends2, label="pasta")) + await _settle(hass) + assert link.labels()[2:] == ["SetAlert", "SetAlert"] + assert controller.timers[f"alexa:{ID2}"].name == "pasta" + + # Polling the same timers again (the sensor's process_timestamp moves) sends nothing. + _set(hass, _item(ID1, ends1), _item(ID2, ends2, label="pasta")) + await _settle(hass) + assert len(link.sent) == 4 + + # Pause deletes it; resume (later end) shows it again with the same token. + _set(hass, _item(ID1, None, status="PAUSED"), _item(ID2, ends2)) + await _settle(hass) + assert link.labels()[4:] == ["DeleteAlert"] + assert controller.timers[f"alexa:{ID1}"].paused + _set(hass, _item(ID1, ends1 + timedelta(minutes=1)), _item(ID2, ends2)) + await _settle(hass) + assert link.labels()[5:] == ["SetAlert"] + token = protocol.alert_token(f"alexa:{ID1}").encode() + assert token in link.sent[4] and token in link.sent[5] + + # Cancel (drops off the sensor long before its end): DeleteAlert, no pulse. + _set(hass, _item(ID2, ends2)) + await _settle(hass) + assert link.labels()[6:] == ["DeleteAlert"] + hass.states.async_set(ECHO, "unavailable", {"sorted_active": [], "sorted_all": []}) + await _settle(hass) + assert link.labels()[7:] == ["DeleteAlert"] + assert controller.timers == {} + await controller.async_stop() + + +async def test_alexa_timer_finishing_pulses_once(hass: HomeAssistant) -> None: + """The alarm at the end time pulses, and the sensor dropping the timer afterwards doesn't pulse again.""" + ends = dt_util.utcnow() + timedelta(seconds=1) + _set(hass, _item(ID1, ends)) # already running when Home Assistant starts + link = FakeLink() + controller = ClockController(hass, [], [], link, alexa_sensors=[ECHO]) + await controller.async_start() + link.up() + assert link.labels() == ["timeinfo", "ClearIndicator", "SetAlert"] + await asyncio.sleep(2.3) # the timer ends, then the pulse is due 1 s later + await _settle(hass) + assert link.labels()[3:] == ["timers=active"] + _set(hass) # Alexa Media Player catches up + await _settle(hass) + await asyncio.sleep(1.2) + await _settle(hass) + assert link.labels()[3:] == ["timers=active"] + await controller.async_stop() + + +async def test_alexa_timer_dropping_off_at_its_end_pulses(hass: HomeAssistant) -> None: + """The sensor drops the timer right before its end: finished, not cancelled; the alarm doesn't pulse again.""" + link = FakeLink() + controller = ClockController(hass, [], [], link, alexa_sensors=[ECHO]) + await controller.async_start() + link.up() + _set(hass, _item(ID1, dt_util.utcnow() + timedelta(seconds=2.5))) + await _settle(hass) + await asyncio.sleep(1) + _set(hass) + await _settle(hass) + await asyncio.sleep(2.8) # past the pulse and past the old alarm time + await _settle(hass) + assert link.labels()[2:] == ["SetAlert", "timers=active"] + await controller.async_stop() + + +async def test_changing_to_alexa_keeps_the_link(hass: HomeAssistant) -> None: + ends = dt_util.utcnow() + timedelta(minutes=3) + hass.states.async_set("timer.tea", "active", {"finishes_at": ends.isoformat()}) + _set(hass, _item(ID1, ends + timedelta(minutes=1))) + link = FakeLink() + controller = ClockController(hass, [], ["timer.tea"], link) + await controller.async_start() + link.up() + assert link.labels()[2:] == ["SetAlert"] + controller.update_sources([], ["timer.tea"], [ECHO]) + await _settle(hass) + assert controller.connected + assert set(controller.timers) == {"helper:timer.tea", f"alexa:{ID1}"} + assert link.labels()[3:] == ["SetAlert"] + controller.update_sources([], ["timer.tea"], []) + await _settle(hass) + assert link.labels()[4:] == ["DeleteAlert"] + await controller.async_stop() + + +async def test_options_with_alexa_only(hass: HomeAssistant) -> None: + entry = MockConfigEntry(domain=DOMAIN, title="Kitchen clock", options={CONF_HELPERS: ["timer.tea"]}) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + _set(hass, _item(ID1, dt_util.utcnow() + timedelta(minutes=5))) + + result = await hass.config_entries.options.async_init(entry.entry_id) + result = await hass.config_entries.options.async_configure( + result["flow_id"], {CONF_ASSIST_DEVICES: [], CONF_HELPERS: [], CONF_ALEXA_SENSORS: [ECHO]} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + await hass.async_block_till_done() + state = hass.states.get("sensor.kitchen_clock_timers") + assert state.state == "1" + assert state.attributes["timers"][0]["id"] == f"alexa:{ID1}" + assert await hass.config_entries.async_unload(entry.entry_id) From 71fb6c734fafe1623634149b3af8aa85b3280640 Mon Sep 17 00:00:00 2001 From: emiliano Date: Fri, 13 Nov 2026 23:11:29 +0100 Subject: [PATCH 2/2] version change --- custom_components/second_hand/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/second_hand/manifest.json b/custom_components/second_hand/manifest.json index 9e27872..ae26437 100644 --- a/custom_components/second_hand/manifest.json +++ b/custom_components/second_hand/manifest.json @@ -13,5 +13,5 @@ "requirements": [ "dbus-fast>=2.21.0" ], - "version": "0.9.1" + "version": "0.10" }