Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """Support for HLK-SW16 relay switches."""
2 
3 import logging
4 
5 from homeassistant.core import callback
6 from homeassistant.helpers.dispatcher import async_dispatcher_connect
7 from homeassistant.helpers.entity import Entity
8 
9 _LOGGER = logging.getLogger(__name__)
10 
11 
13  """Representation of a HLK-SW16 device.
14 
15  Contains the common logic for HLK-SW16 entities.
16  """
17 
18  _attr_should_poll = False
19 
20  def __init__(self, device_port, entry_id, client):
21  """Initialize the device."""
22  # HLK-SW16 specific attributes for every component type
23  self._entry_id_entry_id = entry_id
24  self._device_port_device_port = device_port
25  self._is_on_is_on = None
26  self._client_client = client
27  self._attr_name_attr_name = device_port
28  self._attr_unique_id_attr_unique_id = f"{self._entry_id}_{self._device_port}"
29 
30  @callback
31  def handle_event_callback(self, event):
32  """Propagate changes through ha."""
33  _LOGGER.debug("Relay %s new state callback: %r", self.unique_idunique_id, event)
34  self._is_on_is_on = event
35  self.async_write_ha_stateasync_write_ha_state()
36 
37  @property
38  def available(self):
39  """Return True if entity is available."""
40  return bool(self._client_client.is_connected)
41 
42  @callback
43  def _availability_callback(self, availability):
44  """Update availability state."""
45  self.async_write_ha_stateasync_write_ha_state()
46 
47  async def async_added_to_hass(self):
48  """Register update callback."""
49  self._client_client.register_status_callback(
50  self.handle_event_callbackhandle_event_callback, self._device_port_device_port
51  )
52  self._is_on_is_on = await self._client_client.status(self._device_port_device_port)
53  self.async_on_removeasync_on_remove(
55  self.hasshass,
56  f"hlk_sw16_device_available_{self._entry_id}",
57  self._availability_callback_availability_callback,
58  )
59  )
def _availability_callback(self, availability)
Definition: entity.py:43
def __init__(self, device_port, entry_id, client)
Definition: entity.py:20
None async_on_remove(self, CALLBACK_TYPE func)
Definition: entity.py:1331
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103