Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Switch platform for FireServiceRota integration."""
2 
3 import logging
4 from typing import Any
5 
6 from homeassistant.components.switch import SwitchEntity
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 
12 from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN as FIRESERVICEROTA_DOMAIN
13 
14 _LOGGER = logging.getLogger(__name__)
15 
16 
18  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
19 ) -> None:
20  """Set up FireServiceRota switch based on a config entry."""
21  client = hass.data[FIRESERVICEROTA_DOMAIN][entry.entry_id][DATA_CLIENT]
22 
23  coordinator = hass.data[FIRESERVICEROTA_DOMAIN][entry.entry_id][DATA_COORDINATOR]
24 
25  async_add_entities([ResponseSwitch(coordinator, client, entry)])
26 
27 
29  """Representation of an FireServiceRota switch."""
30 
31  _attr_should_poll = False
32  _attr_has_entity_name = True
33  _attr_translation_key = "incident_response"
34 
35  def __init__(self, coordinator, client, entry):
36  """Initialize."""
37  self._coordinator_coordinator = coordinator
38  self._client_client = client
39  self._attr_unique_id_attr_unique_id = f"{entry.unique_id}_Response"
40  self._entry_id_entry_id = entry.entry_id
41 
42  self._state_state = None
43  self._state_attributes_state_attributes = {}
44  self._state_icon_state_icon = None
45 
46  @property
47  def icon(self) -> str:
48  """Return the icon to use in the frontend."""
49  if self._state_icon_state_icon == "acknowledged":
50  return "mdi:run-fast"
51  if self._state_icon_state_icon == "rejected":
52  return "mdi:account-off-outline"
53 
54  return "mdi:forum"
55 
56  @property
57  def is_on(self) -> bool:
58  """Get the assumed state of the switch."""
59  return self._state_state
60 
61  @property
62  def available(self) -> bool:
63  """Return if switch is available."""
64  return self._client_client.on_duty
65 
66  @property
67  def extra_state_attributes(self) -> dict[str, Any]:
68  """Return available attributes for switch."""
69  attr: dict[str, Any] = {}
70  if not self._state_attributes_state_attributes:
71  return attr
72 
73  data = self._state_attributes_state_attributes
74  return {
75  key: data[key]
76  for key in (
77  "user_name",
78  "assigned_skill_ids",
79  "responded_at",
80  "start_time",
81  "status",
82  "reported_status",
83  "arrived_at_station",
84  "available_at_incident_creation",
85  "active_duty_function_ids",
86  )
87  if key in data
88  }
89 
90  async def async_turn_on(self, **kwargs: Any) -> None:
91  """Send Acknowledge response status."""
92  await self.async_set_responseasync_set_response(True)
93 
94  async def async_turn_off(self, **kwargs: Any) -> None:
95  """Send Reject response status."""
96  await self.async_set_responseasync_set_response(False)
97 
98  async def async_set_response(self, value) -> None:
99  """Send response status."""
100  if not self._client_client.on_duty:
101  _LOGGER.debug(
102  "Cannot send incident response when not on duty",
103  )
104  return
105 
106  await self._client_client.async_set_response(value)
107  self.client_updateclient_update()
108 
109  async def async_added_to_hass(self) -> None:
110  """Register update callback."""
111  self.async_on_removeasync_on_remove(
113  self.hasshass,
114  f"{FIRESERVICEROTA_DOMAIN}_{self._entry_id}_update",
115  self.client_updateclient_update,
116  )
117  )
118  self.async_on_removeasync_on_remove(
119  self._coordinator_coordinator.async_add_listener(self.async_write_ha_stateasync_write_ha_state)
120  )
121 
122  @callback
123  def client_update(self) -> None:
124  """Handle updated incident data from the client."""
125  self.async_schedule_update_ha_stateasync_schedule_update_ha_state(True)
126 
127  async def async_update(self) -> None:
128  """Update FireServiceRota response data."""
129  data = await self._client_client.async_response_update()
130 
131  if not data or "status" not in data:
132  return
133 
134  self._state_state = data["status"] == "acknowledged"
135  self._state_attributes_state_attributes = data
136  self._state_icon_state_icon = data["status"]
137 
138  _LOGGER.debug("Set state of entity 'Response Switch' to '%s'", self._state_state)
def __init__(self, coordinator, client, entry)
Definition: switch.py:35
None async_schedule_update_ha_state(self, bool force_refresh=False)
Definition: entity.py:1265
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: switch.py:19
None async_add_listener(HomeAssistant hass, Callable[[], None] listener)
Definition: __init__.py:82
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103