Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Code to handle a Livisi switches."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from homeassistant.components.switch import SwitchEntity
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.core import HomeAssistant, callback
10 from homeassistant.exceptions import HomeAssistantError
11 from homeassistant.helpers.dispatcher import async_dispatcher_connect
12 from homeassistant.helpers.entity_platform import AddEntitiesCallback
13 
14 from .const import DOMAIN, LIVISI_STATE_CHANGE, LOGGER, SWITCH_DEVICE_TYPES
15 from .coordinator import LivisiDataUpdateCoordinator
16 from .entity import LivisiEntity
17 
18 
20  hass: HomeAssistant,
21  config_entry: ConfigEntry,
22  async_add_entities: AddEntitiesCallback,
23 ) -> None:
24  """Set up switch device."""
25  coordinator: LivisiDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
26 
27  @callback
28  def handle_coordinator_update() -> None:
29  """Add switch."""
30  shc_devices: list[dict[str, Any]] = coordinator.data
31  entities: list[SwitchEntity] = []
32  for device in shc_devices:
33  if (
34  device["type"] in SWITCH_DEVICE_TYPES
35  and device["id"] not in coordinator.devices
36  ):
37  livisi_switch: SwitchEntity = LivisiSwitch(
38  config_entry, coordinator, device
39  )
40  LOGGER.debug("Include device type: %s", device["type"])
41  coordinator.devices.add(device["id"])
42  entities.append(livisi_switch)
43  async_add_entities(entities)
44 
45  config_entry.async_on_unload(
46  coordinator.async_add_listener(handle_coordinator_update)
47  )
48 
49 
51  """Represents the Livisi Switch."""
52 
53  def __init__(
54  self,
55  config_entry: ConfigEntry,
56  coordinator: LivisiDataUpdateCoordinator,
57  device: dict[str, Any],
58  ) -> None:
59  """Initialize the Livisi switch."""
60  super().__init__(config_entry, coordinator, device)
61  self._capability_id_capability_id = self.capabilities["SwitchActuator"]
62 
63  async def async_turn_on(self, **kwargs: Any) -> None:
64  """Turn the entity on."""
65  response = await self.aio_livisiaio_livisi.async_pss_set_state(
66  self._capability_id_capability_id, is_on=True
67  )
68  if response is None:
69  self._attr_available_attr_available_attr_available = False
70  raise HomeAssistantError(f"Failed to turn on {self._attr_name}")
71 
72  async def async_turn_off(self, **kwargs: Any) -> None:
73  """Turn the entity off."""
74  response = await self.aio_livisiaio_livisi.async_pss_set_state(
75  self._capability_id_capability_id, is_on=False
76  )
77  if response is None:
78  self._attr_available_attr_available_attr_available = False
79  raise HomeAssistantError(f"Failed to turn off {self._attr_name}")
80 
81  async def async_added_to_hass(self) -> None:
82  """Register callbacks."""
83  await super().async_added_to_hass()
84 
85  response = await self.coordinator.async_get_device_state(
86  self._capability_id_capability_id, "onState"
87  )
88  if response is None:
89  self._attr_is_on_attr_is_on = False
90  self._attr_available_attr_available_attr_available = False
91  else:
92  self._attr_is_on_attr_is_on = response
93  self.async_on_removeasync_on_remove(
95  self.hasshasshasshass,
96  f"{LIVISI_STATE_CHANGE}_{self._capability_id}",
97  self.update_statesupdate_states,
98  )
99  )
100 
101  @callback
102  def update_states(self, state: bool) -> None:
103  """Update the state of the switch device."""
104  self._attr_is_on_attr_is_on = state
105  self.async_write_ha_stateasync_write_ha_state()
Any|None async_get_device_state(self, str capability, str key)
Definition: coordinator.py:94
None __init__(self, ConfigEntry config_entry, LivisiDataUpdateCoordinator coordinator, dict[str, Any] device)
Definition: switch.py:58
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:23
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103