Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Sensor platform to display the current fuel prices at a NSW fuel station."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import voluptuous as vol
8 
10  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
11  SensorEntity,
12 )
13 from homeassistant.const import CURRENCY_CENT, UnitOfVolume
14 from homeassistant.core import HomeAssistant
16 from homeassistant.helpers.entity_platform import AddEntitiesCallback
17 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
19  CoordinatorEntity,
20  DataUpdateCoordinator,
21 )
22 
23 from . import DATA_NSW_FUEL_STATION, StationPriceData
24 
25 _LOGGER = logging.getLogger(__name__)
26 
27 ATTR_STATION_ID = "station_id"
28 ATTR_STATION_NAME = "station_name"
29 
30 CONF_STATION_ID = "station_id"
31 CONF_FUEL_TYPES = "fuel_types"
32 CONF_ALLOWED_FUEL_TYPES = [
33  "E10",
34  "U91",
35  "E85",
36  "P95",
37  "P98",
38  "DL",
39  "PDL",
40  "B20",
41  "LPG",
42  "CNG",
43  "EV",
44 ]
45 CONF_DEFAULT_FUEL_TYPES = ["E10", "U91"]
46 
47 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
48  {
49  vol.Required(CONF_STATION_ID): cv.positive_int,
50  vol.Optional(CONF_FUEL_TYPES, default=CONF_DEFAULT_FUEL_TYPES): vol.All(
51  cv.ensure_list, [vol.In(CONF_ALLOWED_FUEL_TYPES)]
52  ),
53  }
54 )
55 
56 
58  hass: HomeAssistant,
59  config: ConfigType,
60  add_entities: AddEntitiesCallback,
61  discovery_info: DiscoveryInfoType | None = None,
62 ) -> None:
63  """Set up the NSW Fuel Station sensor."""
64 
65  station_id = config[CONF_STATION_ID]
66  fuel_types = config[CONF_FUEL_TYPES]
67 
68  coordinator = hass.data[DATA_NSW_FUEL_STATION]
69 
70  if coordinator.data is None:
71  _LOGGER.error("Initial fuel station price data not available")
72  return
73 
74  entities = []
75  for fuel_type in fuel_types:
76  if coordinator.data.prices.get((station_id, fuel_type)) is None:
77  _LOGGER.error(
78  "Fuel station price data not available for station %d and fuel type %s",
79  station_id,
80  fuel_type,
81  )
82  continue
83 
84  entities.append(StationPriceSensor(coordinator, station_id, fuel_type))
85 
86  add_entities(entities)
87 
88 
90  CoordinatorEntity[DataUpdateCoordinator[StationPriceData]], SensorEntity
91 ):
92  """Implementation of a sensor that reports the fuel price for a station."""
93 
94  _attr_attribution = "Data provided by NSW Government FuelCheck"
95 
96  def __init__(
97  self,
98  coordinator: DataUpdateCoordinator[StationPriceData],
99  station_id: int,
100  fuel_type: str,
101  ) -> None:
102  """Initialize the sensor."""
103  super().__init__(coordinator)
104 
105  self._station_id_station_id = station_id
106  self._fuel_type_fuel_type = fuel_type
107 
108  @property
109  def name(self) -> str:
110  """Return the name of the sensor."""
111  station_name = self._get_station_name_get_station_name()
112  return f"{station_name} {self._fuel_type}"
113 
114  @property
115  def native_value(self) -> float | None:
116  """Return the state of the sensor."""
117  if self.coordinator.data is None:
118  return None
119 
120  prices = self.coordinator.data.prices
121  return prices.get((self._station_id_station_id, self._fuel_type_fuel_type))
122 
123  @property
124  def extra_state_attributes(self) -> dict[str, int | str]:
125  """Return the state attributes of the device."""
126  return {
127  ATTR_STATION_ID: self._station_id_station_id,
128  ATTR_STATION_NAME: self._get_station_name_get_station_name(),
129  }
130 
131  @property
132  def native_unit_of_measurement(self) -> str:
133  """Return the units of measurement."""
134  return f"{CURRENCY_CENT}/{UnitOfVolume.LITERS}"
135 
136  def _get_station_name(self):
137  default_name = f"station {self._station_id}"
138  if self.coordinator.data is None:
139  return default_name
140 
141  station = self.coordinator.data.stations.get(self._station_id_station_id)
142  if station is None:
143  return default_name
144 
145  return station.name
146 
147  @property
148  def unique_id(self) -> str | None:
149  """Return a unique ID."""
150  return f"{self._station_id}_{self._fuel_type}"
None __init__(self, DataUpdateCoordinator[StationPriceData] coordinator, int station_id, str fuel_type)
Definition: sensor.py:101
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:62