Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """The Apple TV integration."""
2 
3 from __future__ import annotations
4 
5 from pyatv.interface import AppleTV as AppleTVInterface
6 
7 from homeassistant.core import callback
8 from homeassistant.helpers.device_registry import DeviceInfo
9 from homeassistant.helpers.dispatcher import async_dispatcher_connect
10 from homeassistant.helpers.entity import Entity
11 
12 from . import AppleTVManager
13 from .const import DOMAIN, SIGNAL_CONNECTED, SIGNAL_DISCONNECTED
14 
15 
17  """Device that sends commands to an Apple TV."""
18 
19  _attr_should_poll = False
20  _attr_has_entity_name = True
21  _attr_name = None
22  atv: AppleTVInterface | None = None
23 
24  def __init__(self, name: str, identifier: str, manager: AppleTVManager) -> None:
25  """Initialize device."""
26  self.managermanager = manager
27  self._attr_unique_id_attr_unique_id = identifier
28  self._attr_device_info_attr_device_info = DeviceInfo(
29  identifiers={(DOMAIN, identifier)},
30  name=name,
31  )
32 
33  async def async_added_to_hass(self) -> None:
34  """Handle when an entity is about to be added to Home Assistant."""
35 
36  @callback
37  def _async_connected(atv: AppleTVInterface) -> None:
38  """Handle that a connection was made to a device."""
39  self.atvatv = atv
40  self.async_device_connectedasync_device_connected(atv)
41  self.async_write_ha_stateasync_write_ha_state()
42 
43  @callback
44  def _async_disconnected() -> None:
45  """Handle that a connection to a device was lost."""
46  self.async_device_disconnectedasync_device_disconnected()
47  self.atvatv = None
48  self.async_write_ha_stateasync_write_ha_state()
49 
50  if self.managermanager.atv:
51  # ATV is already connected
52  _async_connected(self.managermanager.atv)
53 
54  self.async_on_removeasync_on_remove(
56  self.hasshass, f"{SIGNAL_CONNECTED}_{self.unique_id}", _async_connected
57  )
58  )
59  self.async_on_removeasync_on_remove(
61  self.hasshass,
62  f"{SIGNAL_DISCONNECTED}_{self.unique_id}",
63  _async_disconnected,
64  )
65  )
66 
67  def async_device_connected(self, atv: AppleTVInterface) -> None:
68  """Handle when connection is made to device."""
69 
70  def async_device_disconnected(self) -> None:
71  """Handle when connection was lost to device."""
None async_device_connected(self, AppleTVInterface atv)
Definition: entity.py:67
None __init__(self, str name, str identifier, AppleTVManager manager)
Definition: entity.py:24
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