Drop departed connections in Swiss public transport between updates (#192576)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Stefan Agner
2026-11-17 21:23:36 +01:00
committed by GitHub
co-authored by Claude Fable 5.2
parent 2fdf7b57d3
commit 72d0a450d9
3 changed files with 234 additions and 7 deletions
@@ -11,16 +11,28 @@ from opendata_transport.exceptions import (
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.helpers.event import async_track_point_in_time
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import dt as dt_util
from homeassistant.util.json import JsonValueType
from .const import CONNECTIONS_COUNT, DEFAULT_UPDATE_TIME, DOMAIN
from .const import (
CONF_TIME_FIXED,
CONF_TIME_STATION,
CONNECTIONS_COUNT,
DEFAULT_TIME_STATION,
DEFAULT_UPDATE_TIME,
DOMAIN,
)
from .helper import offset_opendata
_LOGGER = logging.getLogger(__name__)
# Spare connections which replace departed ones until the next update
CONNECTIONS_SPARE = 2
DEPARTED_GRACE = timedelta(seconds=30)
type SwissPublicTransportConfigEntry = ConfigEntry[
SwissPublicTransportDataUpdateCoordinator
]
@@ -49,6 +61,13 @@ def calculate_duration_in_seconds(duration_text: str) -> int | None:
return duration.seconds if duration else None
def _departed_at(connection: DataConnection) -> datetime | None:
"""Return when a connection counts as departed."""
if (departure := connection["departure"]) is None:
return None
return departure + timedelta(minutes=connection["delay"] or 0) + DEPARTED_GRACE
class SwissPublicTransportDataUpdateCoordinator(
DataUpdateCoordinator[list[DataConnection]]
):
@@ -73,6 +92,13 @@ class SwissPublicTransportDataUpdateCoordinator(
)
self._opendata = opendata
self._time_offset = time_offset
# A fixed time or an arrival time returns connections which already left
self._drop_departed = (
CONF_TIME_FIXED not in config_entry.data
and config_entry.data.get(CONF_TIME_STATION, DEFAULT_TIME_STATION)
== "departure"
)
self._unsub_departed: CALLBACK_TYPE | None = None
def remaining_time(self, departure) -> timedelta | None:
"""Calculate the remaining time for the departure."""
@@ -84,7 +110,61 @@ class SwissPublicTransportDataUpdateCoordinator(
@override
async def _async_update_data(self) -> list[DataConnection]:
return await self.fetch_connections(limit=CONNECTIONS_COUNT)
if not self._drop_departed:
return await self.fetch_connections(limit=CONNECTIONS_COUNT)
connections = self._async_remaining(
await self.fetch_connections(limit=CONNECTIONS_COUNT + CONNECTIONS_SPARE)
)
self._async_schedule_departed(connections)
return connections
@override
async def async_shutdown(self) -> None:
self._async_cancel_departed()
await super().async_shutdown()
@callback
def _async_remaining(
self, connections: list[DataConnection]
) -> list[DataConnection]:
"""Return the connections which have not departed yet."""
now = dt_util.utcnow()
return [
connection
for connection in connections
if (departed := _departed_at(connection)) is None or departed > now
]
@callback
def _async_cancel_departed(self) -> None:
"""Cancel the removal of the next departing connection."""
if self._unsub_departed:
self._unsub_departed()
self._unsub_departed = None
@callback
def _async_schedule_departed(self, connections: list[DataConnection]) -> None:
"""Schedule the removal of the next departing connection."""
self._async_cancel_departed()
departures = [
departed
for connection in connections
if (departed := _departed_at(connection)) is not None
]
if not departures:
return
# A delayed connection can leave after the ones following it
self._unsub_departed = async_track_point_in_time(
self.hass, self._async_handle_departed, min(departures)
)
@callback
def _async_handle_departed(self, now: datetime) -> None:
"""Remove the departed connections, the next ones move up."""
self._unsub_departed = None
self.data = self._async_remaining(self.data)
self.async_update_listeners()
self._async_schedule_departed(self.data)
async def fetch_connections(self, limit: int) -> list[DataConnection]:
"""Fetch connections using the opendata api."""
@@ -2,7 +2,7 @@
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime, timedelta
from datetime import datetime
import logging
from typing import TYPE_CHECKING, override
@@ -29,8 +29,6 @@ PARALLEL_UPDATES = 0
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=90)
@dataclass(kw_only=True, frozen=True)
class SwissPublicTransportSensorEntityDescription(SensorEntityDescription):
@@ -131,6 +129,9 @@ class SwissPublicTransportSensor(
@override
def native_value(self) -> StateType | datetime:
"""Return the state of the sensor."""
connections = self.coordinator.data
if len(connections) <= self.entity_description.index:
return None
return self.entity_description.value_fn(
self.coordinator.data[self.entity_description.index]
connections[self.entity_description.index]
)
@@ -17,6 +17,10 @@ from syrupy.assertion import SnapshotAssertion
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.swiss_public_transport.const import (
CONF_DESTINATION,
CONF_START,
CONF_TIME_FIXED,
CONF_TIME_STATION,
DEFAULT_UPDATE_TIME,
DOMAIN,
)
@@ -26,10 +30,12 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from .conftest import DESTINATION, START
from tests.test_config_entries import FrozenDateTimeFactory
@pytest.mark.freeze_time("2024-01-06T17:00:00+00:00")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
@@ -60,6 +66,7 @@ async def test_fetching_data(
raise_error: Exception,
) -> None:
"""Test fetching data."""
freezer.move_to("2024-01-06T17:00:00+00:00")
await setup_integration(hass, swiss_public_transport_config_entry)
assert swiss_public_transport_config_entry.state is ConfigEntryState.LOADED
@@ -144,3 +151,142 @@ async def test_fetching_data_setup_exception(
await setup_integration(hass, swiss_public_transport_config_entry)
assert swiss_public_transport_config_entry.state is state
@pytest.mark.parametrize(
("config_data", "departure", "departure_2", "platform"),
[
pytest.param({}, "2024-01-06T17:04:00+00:00", "unknown", "1", id="now"),
pytest.param(
{CONF_TIME_FIXED: "18:03:00"},
"2024-01-06T17:03:00+00:00",
"2024-01-06T17:05:00+00:00",
"0",
id="fixed_time",
),
pytest.param(
{CONF_TIME_STATION: "arrival"},
"2024-01-06T17:03:00+00:00",
"2024-01-06T17:05:00+00:00",
"0",
id="arrival",
),
],
)
async def test_departed_connection(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_opendata_client: AsyncMock,
config_data: dict[str, str],
departure: str,
departure_2: str,
platform: str,
) -> None:
"""Test a departed connection is only dropped when tracking next departures."""
freezer.move_to("2024-01-06T17:02:45+00:00")
config_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_START: START, CONF_DESTINATION: DESTINATION, **config_data},
title=f"{START} {DESTINATION}",
)
await setup_integration(hass, config_entry)
assert (
hass.states.get("sensor.zurich_bern_departure").state
== "2024-01-06T17:03:00+00:00"
)
assert (
hass.states.get("sensor.zurich_bern_departure_2").state
== "2024-01-06T17:05:00+00:00"
)
assert hass.states.get("sensor.zurich_bern_platform").state == "0"
call_count = mock_opendata_client.async_get_data.call_count
# Pass the grace period after the first departure, before the next update
freezer.tick(46)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_opendata_client.async_get_data.call_count == call_count
assert hass.states.get("sensor.zurich_bern_departure").state == departure
assert hass.states.get("sensor.zurich_bern_departure_2").state == departure_2
assert hass.states.get("sensor.zurich_bern_platform").state == platform
@pytest.mark.freeze_time("2024-01-06T17:03:45+00:00")
async def test_departed_connection_dropped_on_update(
hass: HomeAssistant,
mock_opendata_client: AsyncMock,
swiss_public_transport_config_entry: MockConfigEntry,
) -> None:
"""Test a connection which already departed is dropped from an update."""
await setup_integration(hass, swiss_public_transport_config_entry)
assert (
hass.states.get("sensor.zurich_bern_departure").state
== "2024-01-06T17:04:00+00:00"
)
@pytest.mark.freeze_time("2024-01-06T17:03:15+00:00")
async def test_departed_connection_after_delayed_one(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_opendata_client: AsyncMock,
swiss_public_transport_config_entry: MockConfigEntry,
) -> None:
"""Test a connection is dropped while a delayed earlier one is kept."""
mock_opendata_client.connections[0]["delay"] = 5
await setup_integration(hass, swiss_public_transport_config_entry)
assert (
hass.states.get("sensor.zurich_bern_departure_1").state
== "2024-01-06T17:04:00+00:00"
)
call_count = mock_opendata_client.async_get_data.call_count
# Pass the grace period of the second connection, the first leaves at 17:08
freezer.tick(76)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_opendata_client.async_get_data.call_count == call_count
assert (
hass.states.get("sensor.zurich_bern_departure").state
== "2024-01-06T17:03:00+00:00"
)
assert (
hass.states.get("sensor.zurich_bern_departure_1").state
== "2024-01-06T17:05:00+00:00"
)
@pytest.mark.freeze_time("2024-01-06T17:02:45+00:00")
async def test_departed_connection_replaced_by_spare(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_opendata_client: AsyncMock,
swiss_public_transport_config_entry: MockConfigEntry,
) -> None:
"""Test a spare connection moves up without another request."""
mock_opendata_client.connections = (
await async_load_json_array_fixture(hass, "connections.json", DOMAIN)
)[0:5]
await setup_integration(hass, swiss_public_transport_config_entry)
assert mock_opendata_client.limit == 5
assert (
hass.states.get("sensor.zurich_bern_departure_2").state
== "2024-01-06T17:05:00+00:00"
)
call_count = mock_opendata_client.async_get_data.call_count
freezer.tick(46)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_opendata_client.async_get_data.call_count == call_count
assert (
hass.states.get("sensor.zurich_bern_departure_2").state
== "2024-01-06T17:06:00+00:00"
)