Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """Support for YoLink Device."""
2 
3 from __future__ import annotations
4 
5 from abc import abstractmethod
6 
7 from yolink.client_request import ClientRequest
8 from yolink.exception import YoLinkAuthFailError, YoLinkClientError
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.core import callback
12 from homeassistant.exceptions import HomeAssistantError
13 from homeassistant.helpers.device_registry import DeviceInfo
14 from homeassistant.helpers.update_coordinator import CoordinatorEntity
15 
16 from .const import DOMAIN, MANUFACTURER
17 from .coordinator import YoLinkCoordinator
18 
19 
20 class YoLinkEntity(CoordinatorEntity[YoLinkCoordinator]):
21  """YoLink Device Basic Entity."""
22 
23  _attr_has_entity_name = True
24 
25  def __init__(
26  self,
27  config_entry: ConfigEntry,
28  coordinator: YoLinkCoordinator,
29  ) -> None:
30  """Init YoLink Entity."""
31  super().__init__(coordinator)
32  self.config_entryconfig_entryconfig_entry = config_entry
33 
34  @property
35  def device_id(self) -> str:
36  """Return the device id of the YoLink device."""
37  return self.coordinator.device.device_id
38 
39  async def async_added_to_hass(self) -> None:
40  """Update state."""
41  await super().async_added_to_hass()
42  return self._handle_coordinator_update_handle_coordinator_update()
43 
44  @callback
45  def _handle_coordinator_update(self) -> None:
46  """Update state."""
47  data = self.coordinator.data
48  if data is not None:
49  self.update_entity_stateupdate_entity_state(data)
50 
51  @property
52  def device_info(self) -> DeviceInfo:
53  """Return the device info for HA."""
54  return DeviceInfo(
55  identifiers={(DOMAIN, self.coordinator.device.device_id)},
56  manufacturer=MANUFACTURER,
57  model=self.coordinator.device.device_type,
58  model_id=self.coordinator.device.device_model_name,
59  name=self.coordinator.device.device_name,
60  )
61 
62  @callback
63  @abstractmethod
64  def update_entity_state(self, state: dict) -> None:
65  """Parse and update entity state, should be overridden."""
66 
67  async def call_device(self, request: ClientRequest) -> None:
68  """Call device api."""
69  try:
70  # call_device will check result, fail by raise YoLinkClientError
71  await self.coordinator.device.call_device(request)
72  except YoLinkAuthFailError as yl_auth_err:
73  self.config_entryconfig_entryconfig_entry.async_start_reauth(self.hasshass)
74  raise HomeAssistantError(yl_auth_err) from yl_auth_err
75  except YoLinkClientError as yl_client_err:
76  raise HomeAssistantError(yl_client_err) from yl_client_err