From 616ed3f7bb46eb25cd89cf92c484e0524c205b30 Mon Sep 17 00:00:00 2001 From: Martin Andersson Date: Mon, 9 Nov 2026 15:39:57 +0100 Subject: [PATCH] Add dynamic devices to A Better Routeplanner (#191478) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/abrp/__init__.py | 108 +++++++------ homeassistant/components/abrp/config_flow.py | 3 +- homeassistant/components/abrp/coordinator.py | 44 +++++- homeassistant/components/abrp/diagnostics.py | 2 +- homeassistant/components/abrp/sensor.py | 3 +- tests/components/abrp/test_init.py | 152 +++++++++++++------ 6 files changed, 205 insertions(+), 107 deletions(-) diff --git a/homeassistant/components/abrp/__init__.py b/homeassistant/components/abrp/__init__.py index da096268f180..49917551e3ab 100644 --- a/homeassistant/components/abrp/__init__.py +++ b/homeassistant/components/abrp/__init__.py @@ -5,18 +5,19 @@ import logging from aioabrp import AbrpClient, TelemetryStream from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform -from homeassistant.core import Event, HomeAssistant +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import config_entry_oauth2_flow, device_registry as dr from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.typing import Undefined from .auth import AbrpAuth from .const import ABRP_APP_KEY, DOMAIN from .coordinator import ( AbrpConfigEntry, AbrpData, + AbrpGarageCoordinator, AbrpTelemetryCoordinator, - async_fetch_garage, ) _LOGGER = logging.getLogger(__name__) @@ -46,58 +47,73 @@ async def async_setup_entry(hass: HomeAssistant, entry: AbrpConfigEntry) -> None auth = AbrpAuth(session) client = AbrpClient(websession, ABRP_APP_KEY, auth) - vehicles = await async_fetch_garage(client) - - device_registry = dr.async_get(hass) - for raw, display in vehicles: - scope = f"{entry.unique_id}_{raw.vehicle_id}" - if display is None: - _LOGGER.info( - "No display metadata for vehicle %d (typecode %s); the device " - "shows the raw typecode until the entry is reloaded", - raw.vehicle_id, - raw.vehicle_model, - ) - device_registry.async_get_or_create( - config_entry_id=entry.entry_id, - identifiers={(DOMAIN, scope)}, - manufacturer=display.manufacturer if display is not None else None, - model=display.model_name if display is not None else raw.vehicle_model, - name=raw.name or raw.vehicle_model, - configuration_url=( - f"https://abetterrouteplanner.com/?vehicle_id={raw.vehicle_id}" - ), - ) + garage_coordinator = AbrpGarageCoordinator(hass, entry, client) + await garage_coordinator.async_config_entry_first_refresh() telemetry_coordinator = AbrpTelemetryCoordinator(hass, entry) + stream = TelemetryStream( + websession, + ABRP_APP_KEY, + auth, + [], + on_update=telemetry_coordinator.on_update, + on_connection_change=telemetry_coordinator.on_connection_change, + name=entry.title, + ) - # Deduplicated: the stream sends one comma-joined id list, which the v2 - # endpoint rejects as a whole if it is malformed. - vehicle_ids = list(dict.fromkeys(raw.vehicle_id for raw, _ in vehicles)) + device_registry = dr.async_get(hass) + known: set[int] = set() - if vehicle_ids: - stream = TelemetryStream( - websession, - ABRP_APP_KEY, - auth, - vehicle_ids, - on_update=telemetry_coordinator.on_update, - on_connection_change=telemetry_coordinator.on_connection_change, - name=entry.title, - ) - await stream.start() - entry.async_on_unload(stream.stop) + @callback + def _async_add_new_vehicles() -> None: + """Create a device per garage vehicle, then subscribe the stream to new ones.""" + for raw, display in garage_coordinator.data: + scope = f"{entry.unique_id}_{raw.vehicle_id}" + manufacturer: str | Undefined | None = Undefined + model: str | Undefined | None = Undefined + if display is not None: + manufacturer, model = display.manufacturer, display.model_name + elif raw.vehicle_id not in known: + # A known vehicle keeps what an earlier poll resolved. + model = raw.vehicle_model + _LOGGER.info( + "No display metadata for vehicle %d (typecode %s); the device " + "shows the raw typecode until a later garage check resolves it", + raw.vehicle_id, + raw.vehicle_model, + ) + device_registry.async_get_or_create( + config_entry_id=entry.entry_id, + identifiers={(DOMAIN, scope)}, + manufacturer=manufacturer, + model=model, + name=raw.name or raw.vehicle_model, + configuration_url=( + f"https://abetterrouteplanner.com/?vehicle_id={raw.vehicle_id}" + ), + ) + # Add-only: vehicles that leave the garage stay until the entry reloads. + known.update(raw.vehicle_id for raw, _ in garage_coordinator.data) + stream.set_vehicle_ids(known) - # Entries are not unloaded on shutdown, so stop the stream there too. - async def _async_stop_stream(_: Event) -> None: - await stream.stop() + _async_add_new_vehicles() + await stream.start() + entry.async_on_unload(stream.stop) - entry.async_on_unload( - hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop_stream) - ) + # Entries are not unloaded on shutdown, so stop the stream there too. + async def _async_stop_stream(_: Event) -> None: + await stream.stop() + + entry.async_on_unload( + hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop_stream) + ) entry.runtime_data = AbrpData( - vehicles=vehicles, telemetry_coordinator=telemetry_coordinator + garage_coordinator=garage_coordinator, + telemetry_coordinator=telemetry_coordinator, + ) + entry.async_on_unload( + garage_coordinator.async_add_listener(_async_add_new_vehicles) ) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) diff --git a/homeassistant/components/abrp/config_flow.py b/homeassistant/components/abrp/config_flow.py index 4449765f4917..3fda7ffaf241 100644 --- a/homeassistant/components/abrp/config_flow.py +++ b/homeassistant/components/abrp/config_flow.py @@ -74,8 +74,7 @@ class AbrpFlowHandler( binding the entry to an unverified account. A token without a refresh_token aborts as well: the entry could not outlive the access token, and the stream would retry it forever. On a new entry an empty - garage aborts too: the garage is only re-read at setup, so such an entry - would load green and stay empty until a manual reload. + garage aborts too, so a new entry always starts with a vehicle to show. """ try: identity = parse_unverified_identity(data["token"].get("id_token")) diff --git a/homeassistant/components/abrp/coordinator.py b/homeassistant/components/abrp/coordinator.py index f5be615c8774..edba3d5268df 100644 --- a/homeassistant/components/abrp/coordinator.py +++ b/homeassistant/components/abrp/coordinator.py @@ -1,8 +1,10 @@ -"""Telemetry coordinator for the A Better Routeplanner integration.""" +"""Coordinators for the A Better Routeplanner integration.""" import asyncio from dataclasses import dataclass +from datetime import timedelta import logging +from typing import override from aioabrp import ( AbrpApiError, @@ -17,19 +19,21 @@ from aioabrp import ( from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback -from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady -from homeassistant.helpers.update_coordinator import DataUpdateCoordinator +from homeassistant.exceptions import ConfigEntryAuthFailed +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN _LOGGER = logging.getLogger(__name__) +GARAGE_SCAN_INTERVAL = timedelta(hours=1) + @dataclass(frozen=True, slots=True) class AbrpData: """Runtime data stored on the config entry.""" - vehicles: list[tuple[AbrpVehicle, VehicleModelDisplay | None]] + garage_coordinator: AbrpGarageCoordinator telemetry_coordinator: AbrpTelemetryCoordinator @@ -39,7 +43,7 @@ type AbrpConfigEntry = ConfigEntry[AbrpData] async def async_fetch_garage( client: AbrpClient, ) -> list[tuple[AbrpVehicle, VehicleModelDisplay | None]]: - """Fetch the garage once at setup, pairing each vehicle with its display.""" + """Fetch the garage, pairing each vehicle with its display.""" try: raw_vehicles = await client.async_get_vehicles() except AbrpAuthError as err: @@ -48,7 +52,7 @@ async def async_fetch_garage( translation_key="abrp_session_invalid", ) from err except AbrpApiError as err: - raise ConfigEntryNotReady( + raise UpdateFailed( translation_domain=DOMAIN, translation_key="abrp_update_failed", ) from err @@ -95,6 +99,34 @@ async def async_fetch_garage( return paired +class AbrpGarageCoordinator( + DataUpdateCoordinator[list[tuple[AbrpVehicle, VehicleModelDisplay | None]]] +): + """Polls the garage so vehicles added in ABRP appear without a reload.""" + + config_entry: AbrpConfigEntry + + def __init__( + self, hass: HomeAssistant, entry: AbrpConfigEntry, client: AbrpClient + ) -> None: + """Initialize the garage coordinator.""" + super().__init__( + hass, + _LOGGER, + config_entry=entry, + name=f"{DOMAIN} garage", + update_interval=GARAGE_SCAN_INTERVAL, + ) + self.client = client + + @override + async def _async_update_data( + self, + ) -> list[tuple[AbrpVehicle, VehicleModelDisplay | None]]: + """Fetch the garage.""" + return await async_fetch_garage(self.client) + + class AbrpTelemetryCoordinator(DataUpdateCoordinator[dict[int, Telemetry]]): """Thin push-mode coordinator for the v2 telemetry stream.""" diff --git a/homeassistant/components/abrp/diagnostics.py b/homeassistant/components/abrp/diagnostics.py index f5b4efbfba21..e6b34a09a7f4 100644 --- a/homeassistant/components/abrp/diagnostics.py +++ b/homeassistant/components/abrp/diagnostics.py @@ -29,7 +29,7 @@ async def async_get_config_entry_diagnostics( coordinator = entry.runtime_data.telemetry_coordinator event = coordinator.last_connection_event vehicles: list[dict[str, Any]] = [] - for raw, display in entry.runtime_data.vehicles: + for raw, display in entry.runtime_data.garage_coordinator.data: metrics: dict[str, dict[str, Any]] = {} if (telemetry := coordinator.data.get(raw.vehicle_id)) is not None: for metric, metric_value in telemetry.items(): diff --git a/homeassistant/components/abrp/sensor.py b/homeassistant/components/abrp/sensor.py index 7562667e1a9e..5d287af95234 100644 --- a/homeassistant/components/abrp/sensor.py +++ b/homeassistant/components/abrp/sensor.py @@ -207,7 +207,6 @@ async def async_setup_entry( ) -> None: """Create telemetry sensors for every vehicle in the ABRP garage.""" runtime = entry.runtime_data - vehicles = runtime.vehicles telemetry_coordinator = runtime.telemetry_coordinator added: set[tuple[int, Metric]] = set() @@ -216,7 +215,7 @@ async def async_setup_entry( def _add_new_sensors() -> None: """Create a sensor per ``(vehicle, metric)`` pair that now carries a value.""" entities: list[SensorEntity] = [] - for raw, _ in vehicles: + for raw, _ in runtime.garage_coordinator.data: vehicle_id = raw.vehicle_id tlm = telemetry_coordinator.data.get(vehicle_id) if tlm is None: diff --git a/tests/components/abrp/test_init.py b/tests/components/abrp/test_init.py index 5b83fb9ebe5c..d9d70d9b856b 100644 --- a/tests/components/abrp/test_init.py +++ b/tests/components/abrp/test_init.py @@ -1,5 +1,6 @@ """Tests for the A Better Routeplanner integration setup.""" +from dataclasses import replace from http import HTTPStatus import logging import time @@ -13,16 +14,18 @@ from aioabrp import ( ConnectionState, ) from aiohttp import ClientError +from freezegun.api import FrozenDateTimeFactory import pytest -from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed from pytest_homeassistant.test_util.aiohttp import AiohttpClientMocker from homeassistant.components.abrp.const import ABRP_APP_KEY, DOMAIN, OAUTH2_TOKEN +from homeassistant.components.abrp.coordinator import GARAGE_SCAN_INTERVAL from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import HomeAssistant from homeassistant.exceptions import OAuth2TokenRequestTransientError -from homeassistant.helpers import device_registry as dr, entity_registry as er +from homeassistant.helpers import device_registry as dr from homeassistant.helpers.config_entry_oauth2_flow import ( ImplementationUnavailableError, ) @@ -33,6 +36,7 @@ from .conftest import ( MOCK_VEHICLE_ID_2, MOCK_VEHICLE_MODEL, MOCK_VEHICLE_MODEL_2, + MOCK_VEHICLE_NAME_2, build_vehicle_model_display, fire_connection, stream_auth, @@ -283,6 +287,37 @@ async def test_garage_fetch_failure( ) +@pytest.mark.parametrize( + ("side_effect", "expected_reauth"), + [ + pytest.param(AbrpAuthError("HTTP 401"), True, id="auth_error"), + pytest.param(AbrpApiError("HTTP 503"), False, id="api_error"), + ], +) +@pytest.mark.usefixtures("mock_telemetry_stream") +async def test_garage_poll_failure( + hass: HomeAssistant, + config_entry_with_vehicles: MockConfigEntry, + mock_abrp_client: AsyncMock, + freezer: FrozenDateTimeFactory, + side_effect: Exception, + expected_reauth: bool, +) -> None: + """A poll-time auth error starts reauth; an API error waits for the next poll.""" + await setup_integration(hass, config_entry_with_vehicles) + + mock_abrp_client.side_effect = side_effect + freezer.tick(GARAGE_SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert config_entry_with_vehicles.state is ConfigEntryState.LOADED + assert ( + any(config_entry_with_vehicles.async_get_active_flows(hass, {SOURCE_REAUTH})) + is expected_reauth + ) + + @pytest.mark.parametrize( ("display_error", "warns"), [ @@ -333,6 +368,34 @@ async def test_display_failure_degrades_only_that_vehicle( ) +@pytest.mark.usefixtures("mock_telemetry_stream") +async def test_display_failure_on_poll_keeps_device_metadata( + hass: HomeAssistant, + config_entry_with_vehicles: MockConfigEntry, + mock_abrp_client: AsyncMock, + device_registry: dr.DeviceRegistry, + freezer: FrozenDateTimeFactory, +) -> None: + """A failed display lookup on a poll keeps the make and model already shown.""" + display = build_vehicle_model_display(manufacturer="Rivian", model="R2") + mock_abrp_client.display_responses[MOCK_VEHICLE_MODEL] = display + await setup_integration(hass, config_entry_with_vehicles) + + mock_abrp_client.display_responses[MOCK_VEHICLE_MODEL] = AbrpApiError("HTTP 503") + freezer.tick(GARAGE_SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + device = device_registry.async_get_device_by_identifier( + (DOMAIN, f"{config_entry_with_vehicles.unique_id}_{MOCK_VEHICLE_ID}"), + config_entry_with_vehicles.entry_id, + ) + assert (device.manufacturer, device.model) == ( + display.manufacturer, + display.model_name, + ) + + @pytest.mark.usefixtures("mock_abrp_client") async def test_connection_logged_once_per_transition( hass: HomeAssistant, @@ -378,33 +441,17 @@ async def test_stream_spawned_for_every_garage_vehicle( ANY, ABRP_APP_KEY, ANY, - [MOCK_VEHICLE_ID, MOCK_VEHICLE_ID_2], + [], on_update=ANY, on_connection_change=ANY, name=config_entry_with_vehicles.title, ) + mock_telemetry_stream.return_value.set_vehicle_ids.assert_called_once_with( + {MOCK_VEHICLE_ID, MOCK_VEHICLE_ID_2} + ) mock_telemetry_stream.return_value.start.assert_awaited_once() -async def test_no_stream_when_garage_is_empty( - hass: HomeAssistant, - config_entry: MockConfigEntry, - mock_abrp_client: AsyncMock, - mock_telemetry_stream: MagicMock, - device_registry: dr.DeviceRegistry, - entity_registry: er.EntityRegistry, -) -> None: - """An empty garage loads the entry with no stream, devices or entities.""" - mock_abrp_client.return_value = [] - - await setup_integration(hass, config_entry) - - assert config_entry.state is ConfigEntryState.LOADED - mock_telemetry_stream.assert_not_called() - assert not dr.async_entries_for_config_entry(device_registry, config_entry.entry_id) - assert not er.async_entries_for_config_entry(entity_registry, config_entry.entry_id) - - @pytest.mark.usefixtures("mock_abrp_client") async def test_shutdown_stops_stream( hass: HomeAssistant, @@ -420,43 +467,48 @@ async def test_shutdown_stops_stream( mock_telemetry_stream.return_value.stop.assert_awaited_once() -async def test_vehicle_added_to_garage_appears_after_reload( +@pytest.mark.parametrize( + "initial_indexes", + [ + pytest.param([0], id="vehicle_added"), + pytest.param([], id="added_to_empty_garage"), + ], +) +async def test_vehicle_added_to_garage_appears_without_reload( hass: HomeAssistant, config_entry_with_vehicles: MockConfigEntry, mock_abrp_client: AsyncMock, mock_abrp_vehicles: list[AbrpVehicle], device_registry: dr.DeviceRegistry, mock_telemetry_stream: MagicMock, + freezer: FrozenDateTimeFactory, + caplog: pytest.LogCaptureFixture, + initial_indexes: list[int], ) -> None: - """A vehicle added to the ABRP garage becomes a device on the next reload.""" - mock_abrp_client.return_value = mock_abrp_vehicles[:1] + """A vehicle added to the ABRP garage becomes a device on the next poll. + + The first vehicle also comes back renamed, which the poll carries over. + """ + mock_abrp_client.return_value = [mock_abrp_vehicles[i] for i in initial_indexes] await setup_integration(hass, config_entry_with_vehicles) + mock_telemetry_stream.return_value.set_vehicle_ids.reset_mock() + polled = [replace(mock_abrp_vehicles[0], name="Weekend car"), mock_abrp_vehicles[1]] + mock_abrp_client.return_value = polled + freezer.tick(GARAGE_SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + scope = config_entry_with_vehicles.unique_id - identifier = (DOMAIN, f"{scope}_{MOCK_VEHICLE_ID_2}") - assert ( + assert [ device_registry.async_get_device_by_identifier( - identifier, config_entry_with_vehicles.entry_id - ) - is None - ) - - mock_abrp_client.return_value = mock_abrp_vehicles - await hass.config_entries.async_reload(config_entry_with_vehicles.entry_id) - await hass.async_block_till_done() - - assert ( - device_registry.async_get_device_by_identifier( - identifier, config_entry_with_vehicles.entry_id - ) - is not None - ) - mock_telemetry_stream.assert_called_with( - ANY, - ANY, - ANY, - [MOCK_VEHICLE_ID, MOCK_VEHICLE_ID_2], - on_update=ANY, - on_connection_change=ANY, - name=ANY, + (DOMAIN, f"{scope}_{raw.vehicle_id}"), config_entry_with_vehicles.entry_id + ).name + for raw in polled + ] == ["Weekend car", MOCK_VEHICLE_NAME_2] + # Not reloaded: the one stream is resubscribed in place. + mock_telemetry_stream.assert_called_once() + mock_telemetry_stream.return_value.set_vehicle_ids.assert_called_once_with( + {MOCK_VEHICLE_ID, MOCK_VEHICLE_ID_2} ) + assert caplog.text.count(f"No display metadata for vehicle {MOCK_VEHICLE_ID}") == 1