Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Implement a iotty Light Switch Device."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from iottycloud.device import Device
9 from iottycloud.lightswitch import LightSwitch
10 from iottycloud.verbs import LS_DEVICE_TYPE_UID
11 
12 from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
13 from homeassistant.core import HomeAssistant, callback
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from . import IottyConfigEntry
17 from .api import IottyProxy
18 from .coordinator import IottyDataUpdateCoordinator
19 from .entity import IottyEntity
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 
25  hass: HomeAssistant,
26  config_entry: IottyConfigEntry,
27  async_add_entities: AddEntitiesCallback,
28 ) -> None:
29  """Activate the iotty LightSwitch component."""
30  _LOGGER.debug("Setup SWITCH entry id is %s", config_entry.entry_id)
31 
32  coordinator = config_entry.runtime_data.coordinator
33  entities = [
35  coordinator=coordinator, iotty_cloud=coordinator.iotty, iotty_device=d
36  )
37  for d in coordinator.data.devices
38  if d.device_type == LS_DEVICE_TYPE_UID
39  if (isinstance(d, LightSwitch))
40  ]
41  _LOGGER.debug("Found %d LightSwitches", len(entities))
42 
43  async_add_entities(entities)
44 
45  known_devices: set = config_entry.runtime_data.known_devices
46  for known_device in coordinator.data.devices:
47  if known_device.device_type == LS_DEVICE_TYPE_UID:
48  known_devices.add(known_device)
49 
50  @callback
51  def async_update_data() -> None:
52  """Handle updated data from the API endpoint."""
53  if not coordinator.last_update_success:
54  return
55 
56  devices = coordinator.data.devices
57  entities = []
58  known_devices: set = config_entry.runtime_data.known_devices
59 
60  # Add entities for devices which we've not yet seen
61  for device in devices:
62  if (
63  any(d.device_id == device.device_id for d in known_devices)
64  or device.device_type != LS_DEVICE_TYPE_UID
65  ):
66  continue
67 
68  iotty_entity = IottyLightSwitch(
69  coordinator=coordinator,
70  iotty_cloud=coordinator.iotty,
71  iotty_device=LightSwitch(
72  device.device_id,
73  device.serial_number,
74  device.device_type,
75  device.device_name,
76  ),
77  )
78 
79  entities.extend([iotty_entity])
80  known_devices.add(device)
81 
82  async_add_entities(entities)
83 
84  # Add a subscriber to the coordinator to discover new devices
85  coordinator.async_add_listener(async_update_data)
86 
87 
89  """Haas entity class for iotty LightSwitch."""
90 
91  _attr_device_class = SwitchDeviceClass.SWITCH
92  _iotty_device: LightSwitch
93 
94  def __init__(
95  self,
96  coordinator: IottyDataUpdateCoordinator,
97  iotty_cloud: IottyProxy,
98  iotty_device: LightSwitch,
99  ) -> None:
100  """Initialize the LightSwitch device."""
101  super().__init__(coordinator, iotty_cloud, iotty_device)
102 
103  @property
104  def is_on(self) -> bool:
105  """Return true if the LightSwitch is on."""
106  _LOGGER.debug(
107  "Retrieve device status for %s ? %s",
108  self._iotty_device_iotty_device.device_id,
109  self._iotty_device_iotty_device.is_on,
110  )
111  return self._iotty_device_iotty_device.is_on
112 
113  async def async_turn_on(self, **kwargs: Any) -> None:
114  """Turn the LightSwitch on."""
115  _LOGGER.debug("[%s] Turning on", self._iotty_device_iotty_device.device_id)
116  await self._iotty_cloud_iotty_cloud.command(
117  self._iotty_device_iotty_device.device_id, self._iotty_device_iotty_device.cmd_turn_on()
118  )
119  await self.coordinator.async_request_refresh()
120 
121  async def async_turn_off(self, **kwargs: Any) -> None:
122  """Turn the LightSwitch off."""
123  _LOGGER.debug("[%s] Turning off", self._iotty_device_iotty_device.device_id)
124  await self._iotty_cloud_iotty_cloud.command(
125  self._iotty_device_iotty_device.device_id, self._iotty_device_iotty_device.cmd_turn_off()
126  )
127  await self.coordinator.async_request_refresh()
128 
129  @callback
130  def _handle_coordinator_update(self) -> None:
131  """Handle updated data from the coordinator."""
132 
133  device: Device = next(
134  device
135  for device in self.coordinator.data.devices
136  if device.device_id == self._iotty_device_iotty_device.device_id
137  )
138  if isinstance(device, LightSwitch):
139  self._iotty_device_iotty_device.is_on = device.is_on
140  self.async_write_ha_stateasync_write_ha_state()
None __init__(self, IottyDataUpdateCoordinator coordinator, IottyProxy iotty_cloud, LightSwitch iotty_device)
Definition: switch.py:99
None async_setup_entry(HomeAssistant hass, IottyConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:28