Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Sensor platform for FireServiceRota integration."""
2 
3 import logging
4 from typing import Any
5 
6 from homeassistant.components.sensor import SensorEntity
7 from homeassistant.config_entries import ConfigEntry
8 from homeassistant.core import HomeAssistant, callback
9 from homeassistant.helpers.dispatcher import async_dispatcher_connect
10 from homeassistant.helpers.entity_platform import AddEntitiesCallback
11 from homeassistant.helpers.restore_state import RestoreEntity
12 
13 from .const import DATA_CLIENT, DOMAIN as FIRESERVICEROTA_DOMAIN
14 
15 _LOGGER = logging.getLogger(__name__)
16 
17 
19  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
20 ) -> None:
21  """Set up FireServiceRota sensor based on a config entry."""
22  client = hass.data[FIRESERVICEROTA_DOMAIN][entry.entry_id][DATA_CLIENT]
23 
25 
26 
27 # pylint: disable-next=hass-invalid-inheritance # needs fixing
29  """Representation of FireServiceRota incidents sensor."""
30 
31  _attr_should_poll = False
32  _attr_has_entity_name = True
33  _attr_translation_key = "incidents"
34 
35  def __init__(self, client):
36  """Initialize."""
37  self._client_client = client
38  self._entry_id_entry_id = self._client_client.entry_id
39  self._attr_unique_id_attr_unique_id = f"{self._client.unique_id}_Incidents"
40  self._state_state = None
41  self._state_attributes_state_attributes = {}
42 
43  @property
44  def icon(self) -> str:
45  """Return the icon to use in the frontend."""
46  if (
47  "prio" in self._state_attributes_state_attributes
48  and self._state_attributes_state_attributes["prio"][0] == "a"
49  ):
50  return "mdi:ambulance"
51 
52  return "mdi:fire-truck"
53 
54  @property
55  def native_value(self) -> str:
56  """Return the state of the sensor."""
57  return self._state_state
58 
59  @property
60  def extra_state_attributes(self) -> dict[str, Any]:
61  """Return available attributes for sensor."""
62  attr: dict[str, Any] = {}
63 
64  if not (data := self._state_attributes_state_attributes):
65  return attr
66 
67  for value in (
68  "id",
69  "trigger",
70  "created_at",
71  "message_to_speech_url",
72  "prio",
73  "type",
74  "responder_mode",
75  "can_respond_until",
76  "task_ids",
77  ):
78  if data.get(value):
79  attr[value] = data[value]
80 
81  if "address" not in data:
82  continue
83 
84  for address_value in (
85  "latitude",
86  "longitude",
87  "address_type",
88  "formatted_address",
89  ):
90  if address_value in data["address"]:
91  attr[address_value] = data["address"][address_value]
92 
93  return attr
94 
95  async def async_added_to_hass(self) -> None:
96  """Run when about to be added to hass."""
97  await super().async_added_to_hass()
98 
99  if state := await self.async_get_last_stateasync_get_last_state():
100  self._state_state = state.state
101  self._state_attributes_state_attributes = state.attributes
102  if "id" in self._state_attributes_state_attributes:
103  self._client_client.incident_id = self._state_attributes_state_attributes["id"]
104  _LOGGER.debug("Restored entity 'Incidents' to: %s", self._state_state)
105 
106  self.async_on_removeasync_on_remove(
108  self.hasshass,
109  f"{FIRESERVICEROTA_DOMAIN}_{self._entry_id}_update",
110  self.client_updateclient_update,
111  )
112  )
113 
114  @callback
115  def client_update(self) -> None:
116  """Handle updated data from the data client."""
117  data = self._client_client.websocket.incident_data
118  if not data or "body" not in data:
119  return
120 
121  self._state_state = data["body"]
122  self._state_attributes_state_attributes = data
123  if "id" in self._state_attributes_state_attributes:
124  self._client_client.incident_id = self._state_attributes_state_attributes["id"]
125  self.async_write_ha_stateasync_write_ha_state()
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:20
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103