Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for hydrological data from the Fed. Office for the Environment."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 from swisshydrodata import SwissHydroData
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA,
13  SensorEntity,
14 )
15 from homeassistant.const import CONF_MONITORED_CONDITIONS
16 from homeassistant.core import HomeAssistant
18 from homeassistant.helpers.entity_platform import AddEntitiesCallback
19 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
20 from homeassistant.util import Throttle
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 ATTR_MAX_24H = "max-24h"
25 ATTR_MEAN_24H = "mean-24h"
26 ATTR_MIN_24H = "min-24h"
27 ATTR_STATION = "station"
28 ATTR_STATION_UPDATE = "station_update"
29 ATTR_WATER_BODY = "water_body"
30 ATTR_WATER_BODY_TYPE = "water_body_type"
31 
32 CONF_STATION = "station"
33 
34 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
35 
36 SENSOR_DISCHARGE = "discharge"
37 SENSOR_LEVEL = "level"
38 SENSOR_TEMPERATURE = "temperature"
39 
40 CONDITIONS = {
41  SENSOR_DISCHARGE: "mdi:waves",
42  SENSOR_LEVEL: "mdi:zodiac-aquarius",
43  SENSOR_TEMPERATURE: "mdi:oil-temperature",
44 }
45 
46 CONDITION_DETAILS = [
47  ATTR_MAX_24H,
48  ATTR_MEAN_24H,
49  ATTR_MIN_24H,
50 ]
51 
52 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
53  {
54  vol.Required(CONF_STATION): vol.Coerce(int),
55  vol.Optional(CONF_MONITORED_CONDITIONS, default=[SENSOR_TEMPERATURE]): vol.All(
56  cv.ensure_list, [vol.In(CONDITIONS)]
57  ),
58  }
59 )
60 
61 
63  hass: HomeAssistant,
64  config: ConfigType,
65  add_entities: AddEntitiesCallback,
66  discovery_info: DiscoveryInfoType | None = None,
67 ) -> None:
68  """Set up the Swiss hydrological sensor."""
69  station = config[CONF_STATION]
70  monitored_conditions = config[CONF_MONITORED_CONDITIONS]
71 
72  hydro_data = HydrologicalData(station)
73  hydro_data.update()
74 
75  if hydro_data.data is None:
76  _LOGGER.error("The station doesn't exists: %s", station)
77  return
78 
80  (
81  SwissHydrologicalDataSensor(hydro_data, station, condition)
82  for condition in monitored_conditions
83  ),
84  True,
85  )
86 
87 
89  """Implementation of a Swiss hydrological sensor."""
90 
91  _attr_attribution = (
92  "Data provided by the Swiss Federal Office for the Environment FOEN"
93  )
94 
95  def __init__(self, hydro_data, station, condition):
96  """Initialize the Swiss hydrological sensor."""
97  self.hydro_datahydro_data = hydro_data
98  self._condition_condition = condition
99  self._data_data = self._state_state = self._unit_of_measurement_unit_of_measurement = None
100  self._icon_icon = CONDITIONS[condition]
101  self._station_station = station
102 
103  @property
104  def name(self):
105  """Return the name of the sensor."""
106  return f"{self._data['water-body-name']} {self._condition}"
107 
108  @property
109  def unique_id(self) -> str:
110  """Return a unique, friendly identifier for this entity."""
111  return f"{self._station}_{self._condition}"
112 
113  @property
115  """Return the unit of measurement of this entity, if any."""
116  if self._state_state is not None:
117  return self.hydro_datahydro_data.data["parameters"][self._condition_condition]["unit"]
118  return None
119 
120  @property
121  def native_value(self):
122  """Return the state of the sensor."""
123  if isinstance(self._state_state, (int, float)):
124  return round(self._state_state, 2)
125  return None
126 
127  @property
129  """Return the device state attributes."""
130  attrs = {}
131 
132  if not self._data_data:
133  return attrs
134 
135  attrs[ATTR_WATER_BODY_TYPE] = self._data_data["water-body-type"]
136  attrs[ATTR_STATION] = self._data_data["name"]
137  attrs[ATTR_STATION_UPDATE] = self._data_data["parameters"][self._condition_condition][
138  "datetime"
139  ]
140 
141  for entry in CONDITION_DETAILS:
142  attrs[entry.replace("-", "_")] = self._data_data["parameters"][self._condition_condition][
143  entry
144  ]
145 
146  return attrs
147 
148  @property
149  def icon(self):
150  """Icon to use in the frontend."""
151  return self._icon_icon
152 
153  def update(self) -> None:
154  """Get the latest data and update the state."""
155  self.hydro_datahydro_data.update()
156  self._data_data = self.hydro_datahydro_data.data
157 
158  if self._data_data is None:
159  self._state_state = None
160  else:
161  self._state_state = self._data_data["parameters"][self._condition_condition]["value"]
162 
163 
165  """The Class for handling the data retrieval."""
166 
167  def __init__(self, station):
168  """Initialize the data object."""
169  self.stationstation = station
170  self.datadata = None
171 
172  @Throttle(MIN_TIME_BETWEEN_UPDATES)
173  def update(self):
174  """Get the latest data."""
175 
176  shd = SwissHydroData()
177  self.datadata = shd.get_station(self.stationstation)
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:67