Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The nsw_fuel_station component."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 import datetime
7 import logging
8 
9 from nsw_fuel import FuelCheckClient, FuelCheckError, Station
10 
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers import config_validation as cv
13 from homeassistant.helpers.typing import ConfigType
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
15 
16 from .const import DATA_NSW_FUEL_STATION
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 DOMAIN = "nsw_fuel_station"
21 SCAN_INTERVAL = datetime.timedelta(hours=1)
22 
23 CONFIG_SCHEMA = cv.platform_only_config_schema(DOMAIN)
24 
25 
26 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
27  """Set up the NSW Fuel Station platform."""
28  client = FuelCheckClient()
29 
30  async def async_update_data():
31  return await hass.async_add_executor_job(fetch_station_price_data, client)
32 
33  coordinator = DataUpdateCoordinator(
34  hass,
35  _LOGGER,
36  config_entry=None,
37  name="sensor",
38  update_interval=SCAN_INTERVAL,
39  update_method=async_update_data,
40  )
41  hass.data[DATA_NSW_FUEL_STATION] = coordinator
42 
43  await coordinator.async_refresh()
44 
45  return True
46 
47 
48 @dataclass
50  """Data structure for O(1) price and name lookups."""
51 
52  stations: dict[int, Station]
53  prices: dict[tuple[int, str], float]
54 
55 
56 def fetch_station_price_data(client: FuelCheckClient) -> StationPriceData | None:
57  """Fetch fuel price and station data."""
58  try:
59  raw_price_data = client.get_fuel_prices()
60  # Restructure prices and station details to be indexed by station code
61  # for O(1) lookup
62  return StationPriceData(
63  stations={s.code: s for s in raw_price_data.stations},
64  prices={
65  (p.station_code, p.fuel_type): p.price for p in raw_price_data.prices
66  },
67  )
68 
69  except FuelCheckError as exc:
70  raise UpdateFailed(
71  f"Failed to fetch NSW Fuel station price data: {exc}"
72  ) from exc
StationPriceData|None fetch_station_price_data(FuelCheckClient client)
Definition: __init__.py:56
bool async_setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:26