diff --git a/AGENTS.md b/AGENTS.md index 9c94ced..b6ae8db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ Project-intrinsic knowledge that should travel with the code: build, test, relea - `__anext__` treats `ClientResponseError` with status 401/403 as terminal: sets `active = False` and raises `TeslemetryStreamAuthenticationError`. Every other `aiohttp.ClientError` keeps backoff-and-reconnect. - `connect()`'s `sock_read=30` bounds a connection that stops producing bytes (no data, no SSE keepalive) - a read timeout raises `aiohttp.ClientError`, which the existing client-error handler in `__anext__` already logs and reconnects. There is no separate silence mechanism. - `listen()` tracks whether it has ever seen a successful connect (via a scoped internal connection listener). If it returns or raises before that - including cancellation - it logs one WARNING line before propagating; nothing before a first connect is swallowed. -- `async_add_listener(..., internal=True)` marks a bookkeeping-only listener (the vehicle config-sync listener is the only user). Its `schedule_refresh` gate is unconditionally false, which is what makes construction-time registration safe outside a running event loop. Both the "first listener starts the task" and "last listener removed auto-closes" checks count only public listeners, so an internal listener can neither pin the connection open nor block a later public listener's zero-to-one restart. **Any stream stand-in (test doubles included) must implement `async_add_listener(callback, filters, internal=False)` and `async_add_connection_listener(callback)`.** +- `async_add_listener(..., internal=True)` marks a bookkeeping-only listener (the vehicle config-sync and alert-tracker listeners). Its `schedule_refresh` gate is unconditionally false, which is what makes construction-time registration safe outside a running event loop. Both the "first listener starts the task" and "last listener removed auto-closes" checks count only public listeners, so an internal listener can neither pin the connection open nor block a later public listener's zero-to-one restart. **Any stream stand-in (test doubles included) must implement `async_add_listener(callback, filters, internal=False)` and `async_add_connection_listener(callback)`.** - `topics=` is an optional exact SSE wire-event allowlist sent as the connection's `topics` query param. `SseTopic` is the closed server-recognized set; `SSE_VEHICLE_TOPICS`/`SSE_ENERGY_TOPICS`/`SSE_ALL_TOPICS` are client-side presets, flat per-product-kind lists deliberately not split by whether a topic has a connect-time snapshot (server behavior, not something this library encodes). Omitting it (`None`) is legacy-all forever. An explicitly empty iterable raises `ValueError` at construction - "no topics" must not mean "all topics", mirroring the server's 400. A bare `str`/`SseTopic` is accepted as a single topic, not iterated character-by-character; `topics: str | Iterable[str] | None` exists precisely because a lone string also satisfies `Iterable[str]`. - `ingest()` (and `TeslemetryStreamVehicle.ingest()`, same call with the VIN filled in) is the entry point for an observation not read off the SSE connection - a Bluetooth broadcast, today. It builds the native wire event (`vin`/`data`/`createdAt`) plus an open-ended `metadata` dict (`Metadata.SOURCE`/`Metadata.RAW`) and hands it to the same `_dispatch` `listen()` uses, so existing `listen_*` callbacks receive both sources with no translation and no second subscription. Dispatch is arrival-ordered and the stream holds no per-field value: **nothing is deduplicated, reordered, or dropped, and there is deliberately no source ranking or precedence** - which report to believe is the consumer's decision, made on `metadata`. Ingesting neither requires nor opens a connection. Neither library depends on the other: the BLE-side shim shaping a broadcast into this format lives in `tesla-fleet-api` and the consumer wires the two. diff --git a/README.md b/README.md index b548dc4..10351be 100644 --- a/README.md +++ b/README.md @@ -339,6 +339,12 @@ Listen for vehicle alert events. The callback receives a list of dictionaries co ### `listen_Errors(callback: Callable[[list[dict]], None]) -> Callable[[],None]` Listen for vehicle error events. The callback receives a list of dictionaries containing error information. +### `alerts -> list[dict]` +The alerts in the vehicle's latest alerts batch, newest first. An alert without `endedAt` is active. The vehicle sends its window of recent alerts (up to 100, reaching back days) and drops old ones off it, active ones included, so this is what the vehicle currently reports, not a lifetime history. + +### `listen_AlertChanges(callback: Callable[[str, dict], None]) -> Callable[[],None]` +Listen for alerts starting and ending. The callback receives `"started"` or `"ended"` and the alert. Each alerts event carries the vehicle's recent alerts, ended ones included, and is resent unchanged, including as the snapshot on every reconnect, so only an alert not seen before that comes ahead of every alert already seen (batches are newest first; position is used rather than `startedAt`, which the vehicle's clock can skew) is a start, and only a known active alert that now has `endedAt` is an end. The first batch only seeds `alerts`. An alert that started and ended between two batches calls back with both. The lifecycle rules are based on [purcell-lab/teslemetry-alerts](https://github.com/purcell-lab/teslemetry-alerts). + ### `listen_ChargerPower(callback: Callable[[float | None], None]) -> Callable[[],None]` Listen for charger power whether the vehicle is AC or DC charging. Combines `ACChargingPower` and `DCChargingPower` (DC preferred), gated by `DetailedChargeState`: the value drops to `0` when charging ends, since neither source is reliably reset then, and a lone zero while charging is held until both sources have reported. Enables all three fields; the returned function removes all three listeners. diff --git a/teslemetry_stream/vehicle.py b/teslemetry_stream/vehicle.py index eee88ec..a8647f4 100644 --- a/teslemetry_stream/vehicle.py +++ b/teslemetry_stream/vehicle.py @@ -6,7 +6,7 @@ import logging from collections.abc import Callable from datetime import datetime, timezone -from typing import TYPE_CHECKING, Any, TypeVar, cast +from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast import aiohttp @@ -68,6 +68,8 @@ _T = TypeVar("_T") +AlertChange = Literal["started", "ended"] + class TeslemetryStreamVehicle: """Handle streaming field updates.""" @@ -117,6 +119,18 @@ def __init__(self, stream: TeslemetryStream, vin: str): # landing in that window awaits a fresh fetch instead of trusting # the pre-disconnect record. self.stream.async_add_connection_listener(self._on_connection_event) + # Alerts seen, keyed by (name, startedAt), newest first. + self._alerts: dict[tuple[str, str], dict[str, Any]] = {} + # The transitions found in the alerts event being dispatched, read by + # each listen_AlertChanges listener, which dispatch runs after this + # internal one. + self._alert_event: dict[str, Any] | None = None + self._alert_changes: list[tuple[AlertChange, dict[str, Any]]] = [] + self.stream.async_add_listener( + self._on_alerts_event, + {Key.VIN: self.vin, Key.ALERTS: None}, + internal=True, + ) @property def config(self) -> dict[str, Any]: @@ -453,6 +467,78 @@ def listen_Errors( lambda x: callback(x[Key.ERRORS]), {Key.VIN: self.vin, Key.ERRORS: None} ) + @property + def alerts(self) -> list[dict[str, Any]]: + """The alerts in the vehicle's latest alerts batch, newest first. + + An alert without ``endedAt`` is active. + """ + return [dict(alert) for alert in self._alerts.values()] + + def _on_alerts_event(self, event: dict[str, Any]) -> None: + """Take an alerts batch as `alerts` and record its transitions. + + Each batch is the vehicle's window of recent alerts, newest first and + ended ones included, and is resent unchanged (on every reconnect + too), so only an alert not seen before or newly ended is a + transition. Newness comes from batch position, not ``startedAt``, + which the vehicle's clock can skew. The first batch only seeds: + without anything seen yet, nothing in it can be told apart from + history. + """ + alerts = event.get(Key.ALERTS) + if not isinstance(alerts, list): + LOGGER.warning("Ignoring malformed alerts event for %s: %r", self.vin, alerts) + return + + seeding = self._alert_event is None + # Unseen alerts behind one already seen are older history, not starts. + first_known = next( + (i for i, alert in enumerate(alerts) if _alert_key(alert) in self._alerts), + len(alerts), + ) + batch: dict[tuple[str, str], dict[str, Any]] = {} + changes: list[tuple[AlertChange, dict[str, Any]]] = [] + # Oldest first, so transitions are reported in the order they happened. + for index in reversed(range(len(alerts))): + alert = alerts[index] + key = _alert_key(alert) + known = self._alerts.get(key) + if known is None: + known = dict(alert) + if not seeding and index < first_known: + changes.append(("started", known)) + if "endedAt" in known: + changes.append(("ended", known)) + elif "endedAt" not in known and "endedAt" in alert: + known = dict(alert) + changes.append(("ended", known)) + # A copy of an ended alert without endedAt is stale and never + # revives it. + batch[key] = known + + self._alerts = dict(reversed(batch.items())) + self._alert_event = event + self._alert_changes = changes + + def listen_AlertChanges( + self, callback: Callable[[AlertChange, dict[str, Any]], None] + ) -> Callable[[], None]: + """Call back with ("started" | "ended", alert) for each alert transition. + + The first alerts batch after the vehicle is created seeds `alerts` + without calling back; a later batch, including the snapshot replayed + on reconnect, calls back only for alerts that started or ended since. + An alert that both started and ended between batches calls back twice. + """ + + def handle(event: dict[str, Any]) -> None: + if event is self._alert_event: + for change, alert in self._alert_changes: + callback(change, dict(alert)) + + return self.stream.async_add_listener(handle, {Key.VIN: self.vin, Key.ALERTS: None}) + # Add listeners for each signal def listen_ACChargingEnergyIn( self, callback: Callable[[float | None], None] @@ -3365,6 +3451,11 @@ def typer(event: dict[str, Any]) -> None: return typer +def _alert_key(alert: dict[str, Any]) -> tuple[str, str]: + """Identify an alert across batches.""" + return (alert["name"], alert["startedAt"]) + + def merge(source: dict[Any, Any], destination: dict[Any, Any]) -> dict[Any, Any]: for key, value in source.items(): if isinstance(value, dict): diff --git a/tests/test_alert_changes.py b/tests/test_alert_changes.py new file mode 100644 index 0000000..9a72283 --- /dev/null +++ b/tests/test_alert_changes.py @@ -0,0 +1,340 @@ +"""Tests for the per-vehicle alert tracker (`alerts`, `listen_AlertChanges`). + +Each alerts event carries the vehicle's window of recent alerts, newest first, +ended ones included, and the same window is resent unchanged - including as +the snapshot replayed with ``isCache`` on every (re)connect. What is asserted: + +- the first batch seeds `alerts` without calling back; +- a later batch calls back "started" for an alert not seen before and "ended" + for a known active alert that now carries ``endedAt``, and nothing for a + resent batch; +- a reconnect's replayed snapshot produces no duplicates, but reports what + started or ended while disconnected; +- a stale copy of an ended alert (no ``endedAt``) never revives it; +- `alerts` is the latest batch, so an alert the vehicle drops off its window + leaves it, ended or not; +- an unseen alert behind one already seen is kept as history, not + reported as a start, and newness follows batch position even when the + vehicle's clock has skewed ``startedAt``. +""" +from __future__ import annotations + +import asyncio +import json +from typing import Any, Callable + +from teslemetry_stream.stream import TeslemetryStream + +VIN = "TESTVIN0000000001" + + +def alert(name: str, started: str, ended: str | None = None) -> dict[str, Any]: + value: dict[str, Any] = { + "name": name, + "audiences": ["Customer"], + "startedAt": f"2026-11-06T{started}.000Z", + } + if ended: + value["endedAt"] = f"2026-11-06T{ended}.000Z" + return value + + +def batch(*alerts: dict[str, Any], cache: bool = False) -> dict[str, Any]: + event: dict[str, Any] = { + "vin": VIN, + "createdAt": "2026-11-06T12:00:00.000Z", + "alerts": list(alerts), + } + if cache: + event["isCache"] = True + return event + + +DOOR = alert("UI_a002_DoorOpen", "10:00:00", "10:00:05") +CABLE = alert("VCFRONT_a186_noDriveChgCableCon", "09:00:00") +CABLE_ENDED = alert("VCFRONT_a186_noDriveChgCableCon", "09:00:00", "11:00:00") +KEY = alert("VCSEC_a260_prsntPhoneKeyDisconnected", "11:30:00") +USB = alert("UI_a112_badUSBDevice", "11:40:00", "11:40:01") +# Seen on the wire: after a clock correction an alert can carry a startedAt +# later than its own endedAt, and later than an alert the vehicle sends after it. +WASHER = alert("VCFRONT_a361_washerFluidLowMomentary", "11:50:00", "11:48:00") +DASHCAM = alert("UI_a266_DashcamRecentBufferDurationReduced", "11:49:00") + + +class FakeEventContent: + """Async-iterable response body yielding canned SSE lines, then ending + (so the stream reconnects) or blocking forever.""" + + def __init__(self, lines: list[bytes], end: bool) -> None: + self._lines = list(lines) + self._end = end + self._blocker: asyncio.Future[None] = asyncio.get_running_loop().create_future() + + def __aiter__(self) -> FakeEventContent: + return self + + async def __anext__(self) -> bytes: + if self._lines: + return self._lines.pop(0) + if self._end: + raise StopAsyncIteration + await self._blocker + raise AssertionError("unreachable - blocker only resolves via cancellation") + + +class FakeResponse: + def __init__(self, content: Any) -> None: + self.url = "https://fake.teslemetry.com/sse" + self.status = 200 + self.content = content + self.closed = False + + def close(self) -> None: + self.closed = True + + +class FakeSession: + """Serves one canned list of events per connection; all but the last end.""" + + def __init__(self, connections: list[list[dict[str, Any]]]) -> None: + self.connections = connections + self.calls = 0 + + async def get(self, url: str, **kwargs: Any) -> FakeResponse: + events = self.connections[min(self.calls, len(self.connections) - 1)] + self.calls += 1 + lines = [f"data: {json.dumps(event)}\n".encode() for event in events] + return FakeResponse(FakeEventContent(lines, end=self.calls < len(self.connections))) + + +def make_stream(session: Any = None, manual: bool = True) -> TeslemetryStream: + return TeslemetryStream( + session=session, + access_token="test-token", + server="api.teslemetry.com", + manual=manual, + ) + + +def track(stream: TeslemetryStream) -> tuple[Any, list[tuple[str, str]]]: + vehicle = stream.get_vehicle(VIN) + changes: list[tuple[str, str]] = [] + vehicle.listen_AlertChanges(lambda change, a: changes.append((change, a["name"]))) + return vehicle, changes + + +async def wait_for(predicate: Callable[[], bool], timeout: float = 2.0) -> bool: + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while loop.time() < deadline: + if predicate(): + return True + await asyncio.sleep(0) + return predicate() + + +def check(label: str, ok: bool, detail: str = "") -> bool: + print(f"{label:<72} {'PASS' if ok else 'FAIL'}{' ' + detail if detail else ''}") + return ok + + +def test_first_batch_seeds_silently(results: list[bool]) -> None: + stream = make_stream() + vehicle, changes = track(stream) + stream._dispatch(batch(DOOR, CABLE, cache=True)) + results.append(check("first batch calls back nothing", changes == [], f"got {changes}")) + results.append( + check( + "first batch seeds alerts newest first", + vehicle.alerts == [DOOR, CABLE], + f"got {vehicle.alerts}", + ) + ) + + +def test_live_transitions(results: list[bool]) -> None: + stream = make_stream() + vehicle, changes = track(stream) + stream._dispatch(batch(DOOR, CABLE, cache=True)) + + stream._dispatch(batch(KEY, DOOR, CABLE)) + results.append( + check("a new alert is started", changes == [("started", KEY["name"])], f"got {changes}") + ) + + changes.clear() + stream._dispatch(batch(KEY, DOOR, CABLE)) + results.append(check("a resent batch calls back nothing", changes == [], f"got {changes}")) + + stream._dispatch(batch(KEY, DOOR, CABLE_ENDED)) + results.append( + check( + "a known active alert with endedAt is ended", + changes == [("ended", CABLE["name"])], + f"got {changes}", + ) + ) + results.append( + check( + "the ended alert keeps its endedAt in alerts", + vehicle.alerts == [KEY, DOOR, CABLE_ENDED], + f"got {vehicle.alerts}", + ) + ) + + changes.clear() + stream._dispatch(batch(USB, KEY, DOOR, CABLE_ENDED)) + results.append( + check( + "an alert started and ended between batches is both", + changes == [("started", USB["name"]), ("ended", USB["name"])], + f"got {changes}", + ) + ) + + +def test_stale_ended_alert_never_revives(results: list[bool]) -> None: + stream = make_stream() + vehicle, changes = track(stream) + stream._dispatch(batch(DOOR, CABLE, cache=True)) + stream._dispatch(batch(DOOR, CABLE_ENDED)) + changes.clear() + + # e.g. a replayed snapshot older than what was already seen live + stream._dispatch(batch(DOOR, CABLE, cache=True)) + results.append(check("a stale copy calls back nothing", changes == [], f"got {changes}")) + results.append( + check( + "a stale copy leaves the alert ended", + vehicle.alerts == [DOOR, CABLE_ENDED], + f"got {vehicle.alerts}", + ) + ) + + +def test_unseen_history_is_not_a_start(results: list[bool]) -> None: + stream = make_stream() + vehicle, changes = track(stream) + stream._dispatch(batch(KEY, cache=True)) + stream._dispatch(batch(KEY, DOOR, CABLE)) + results.append( + check( + "unseen alerts behind a seen one call back nothing", changes == [], f"got {changes}" + ) + ) + results.append( + check( + "unseen older alerts are kept", + vehicle.alerts == [KEY, DOOR, CABLE], + f"got {vehicle.alerts}", + ) + ) + + +def test_skewed_clock(results: list[bool]) -> None: + stream = make_stream() + vehicle, changes = track(stream) + stream._dispatch(batch(WASHER, KEY, cache=True)) + stream._dispatch(batch(DASHCAM, WASHER, KEY)) + results.append( + check( + "an alert ahead of a seen one starts despite an earlier startedAt", + changes == [("started", DASHCAM["name"])], + f"got {changes}", + ) + ) + results.append( + check( + "alerts keeps the vehicle's order", + vehicle.alerts == [DASHCAM, WASHER, KEY], + f"got {vehicle.alerts}", + ) + ) + + +def test_alerts_follow_the_latest_batch(results: list[bool]) -> None: + """The vehicle drops old alerts off its window, active ones included, with + no endedAt; `alerts` follows it rather than holding them active forever.""" + stream = make_stream() + vehicle, changes = track(stream) + stream._dispatch(batch(KEY, DOOR, CABLE, cache=True)) + stream._dispatch(batch(KEY, DOOR)) + results.append( + check("an alert dropped off the window calls back nothing", changes == [], f"got {changes}") + ) + results.append( + check( + "an alert dropped off the window leaves alerts", + vehicle.alerts == [KEY, DOOR], + f"got {vehicle.alerts}", + ) + ) + + +def test_callers_get_copies(results: list[bool]) -> None: + stream = make_stream() + vehicle = stream.get_vehicle(VIN) + received: list[dict[str, Any]] = [] + vehicle.listen_AlertChanges(lambda change, a: received.append(a)) + stream._dispatch(batch(DOOR, cache=True)) + stream._dispatch(batch(KEY, DOOR)) + received[0]["endedAt"] = "mutated" + vehicle.alerts[0]["endedAt"] = "mutated" + results.append( + check( + "callers get copies, not the tracked alerts", + vehicle.alerts == [KEY, DOOR], + f"got {vehicle.alerts}", + ) + ) + + +async def test_reconnect_replay(results: list[bool]) -> None: + """Through the real SSE reader: the first connection's snapshot seeds and + a live batch starts KEY; the stream then ends and reconnects, and the new + connection's snapshot is the latest batch plus what changed meanwhile.""" + session = FakeSession( + [ + [batch(DOOR, CABLE, cache=True), batch(KEY, DOOR, CABLE)], + [batch(USB, KEY, DOOR, CABLE_ENDED, cache=True)], + ] + ) + stream = make_stream(session, manual=False) + _, changes = track(stream) + await wait_for(lambda: session.calls == 2 and len(changes) >= 4) + await asyncio.sleep(0) + stream.close() + + results.append(check("the stream reconnected", session.calls == 2, f"calls {session.calls}")) + results.append( + check( + "the replayed snapshot reports only what changed", + changes + == [ + ("started", KEY["name"]), + ("ended", CABLE["name"]), + ("started", USB["name"]), + ("ended", USB["name"]), + ], + f"got {changes}", + ) + ) + + +async def main() -> None: + results: list[bool] = [] + test_first_batch_seeds_silently(results) + test_live_transitions(results) + test_stale_ended_alert_never_revives(results) + test_unseen_history_is_not_a_start(results) + test_skewed_clock(results) + test_alerts_follow_the_latest_batch(results) + test_callers_get_copies(results) + await test_reconnect_replay(results) + print(f"\n{sum(results)}/{len(results)} passed") + if not all(results): + raise SystemExit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tests/test_config_listener_lifecycle.py b/tests/test_config_listener_lifecycle.py index b2debe7..09019e4 100644 --- a/tests/test_config_listener_lifecycle.py +++ b/tests/test_config_listener_lifecycle.py @@ -130,6 +130,15 @@ async def patch_config(config: dict[str, Any]) -> dict[str, Any]: return vehicle, sent +def config_listeners(stream: TeslemetryStream) -> int: + """How many registered listeners filter on config events.""" + return sum(1 for _, filters, _ in stream._listeners.values() if filters and "config" in filters) + + +def public_listeners(stream: TeslemetryStream) -> int: + return sum(1 for _, _, is_internal in stream._listeners.values() if not is_internal) + + def test_sync_construction_without_a_loop() -> bool: """Must run before any event loop exists - constructing a stream+vehicle synchronously (the library's documented pre-async-context usage) must not @@ -148,8 +157,8 @@ def test_sync_construction_without_a_loop() -> bool: ok = ( check( "the config listener is registered by the time construction returns", - len(stream._listeners) == 1, - f"listeners {len(stream._listeners)}", + config_listeners(stream) == 1, + f"config listeners {config_listeners(stream)}", ) and ok ) @@ -170,8 +179,8 @@ async def test_registration_happens_at_construction(results: list[bool]) -> None results.append( check( "the internal config listener is registered by construction, before any call", - len(stream._listeners) == 1, - f"listeners {len(stream._listeners)}", + config_listeners(stream) == 1, + f"config listeners {config_listeners(stream)}", ) ) results.append( @@ -199,9 +208,9 @@ async def test_auto_close_after_last_public_listener_removed(results: list[bool] results.append( check( - "two listeners are registered: one internal, one public", - len(stream._listeners) == 2, - f"listeners {len(stream._listeners)}", + "the config listener and one public listener are registered", + config_listeners(stream) == 1 and public_listeners(stream) == 1, + f"config {config_listeners(stream)}, public {public_listeners(stream)}", ) ) @@ -217,8 +226,8 @@ async def test_auto_close_after_last_public_listener_removed(results: list[bool] results.append( check( "the internal listener remains registered after auto-close", - len(stream._listeners) == 1, - f"listeners {len(stream._listeners)}", + config_listeners(stream) == 1 and public_listeners(stream) == 0, + f"config {config_listeners(stream)}, public {public_listeners(stream)}", ) )