Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """Base class Harmony entities."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from datetime import datetime
7 import logging
8 
9 from homeassistant.core import callback
10 from homeassistant.helpers.entity import Entity
11 from homeassistant.helpers.event import async_call_later
12 
13 from .data import HarmonyData
14 
15 _LOGGER = logging.getLogger(__name__)
16 
17 TIME_MARK_DISCONNECTED = 10
18 
19 
21  """Base entity for Harmony with connection state handling."""
22 
23  _attr_has_entity_name = True
24 
25  def __init__(self, data: HarmonyData) -> None:
26  """Initialize the Harmony base entity."""
27  super().__init__()
28  self._unsub_mark_disconnected_unsub_mark_disconnected: Callable[[], None] | None = None
29  self._data_data = data
30  self._attr_should_poll_attr_should_poll = False
31 
32  @property
33  def available(self) -> bool:
34  """Return True if we're connected to the Hub, otherwise False."""
35  return self._data_data.available
36 
37  async def async_got_connected(self, _: str | None = None) -> None:
38  """Notification that we're connected to the HUB."""
39  _LOGGER.debug("%s: connected to the HUB", self._data_data.name)
40  self.async_write_ha_stateasync_write_ha_state()
41 
42  self._async_clear_disconnection_delay_async_clear_disconnection_delay()
43 
44  async def async_got_disconnected(self, _: str | None = None) -> None:
45  """Notification that we're disconnected from the HUB."""
46  _LOGGER.debug("%s: disconnected from the HUB", self._data_data.name)
47  # We're going to wait for 10 seconds before announcing we're
48  # unavailable, this to allow a reconnection to happen.
49  self._unsub_mark_disconnected_unsub_mark_disconnected = async_call_later(
50  self.hasshass,
51  TIME_MARK_DISCONNECTED,
52  self._async_mark_disconnected_if_unavailable_async_mark_disconnected_if_unavailable,
53  )
54 
55  @callback
57  if self._unsub_mark_disconnected_unsub_mark_disconnected:
58  self._unsub_mark_disconnected_unsub_mark_disconnected()
59  self._unsub_mark_disconnected_unsub_mark_disconnected = None
60 
61  @callback
62  def _async_mark_disconnected_if_unavailable(self, _: datetime) -> None:
63  self._unsub_mark_disconnected_unsub_mark_disconnected = None
64  if not self.availableavailableavailable:
65  # Still disconnected. Let the state engine know.
66  self.async_write_ha_stateasync_write_ha_state()
None async_got_connected(self, str|None _=None)
Definition: entity.py:37
None _async_mark_disconnected_if_unavailable(self, datetime _)
Definition: entity.py:62
None async_got_disconnected(self, str|None _=None)
Definition: entity.py:44
CALLBACK_TYPE async_call_later(HomeAssistant hass, float|timedelta delay, HassJob[[datetime], Coroutine[Any, Any, None]|None]|Callable[[datetime], Coroutine[Any, Any, None]|None] action)
Definition: event.py:1597