Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """Base class for ThinQ entities."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable, Coroutine
6 import logging
7 from typing import Any
8 
9 from thinqconnect import ThinQAPIException
10 from thinqconnect.devices.const import Location
11 from thinqconnect.integration import PropertyState
12 
13 from homeassistant.const import UnitOfTemperature
14 from homeassistant.core import callback
15 from homeassistant.exceptions import ServiceValidationError
16 from homeassistant.helpers import device_registry as dr
17 from homeassistant.helpers.entity import EntityDescription
18 from homeassistant.helpers.update_coordinator import CoordinatorEntity
19 
20 from .const import COMPANY, DOMAIN
21 from .coordinator import DeviceDataUpdateCoordinator
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 EMPTY_STATE = PropertyState()
26 
27 UNIT_CONVERSION_MAP: dict[str, str] = {
28  "F": UnitOfTemperature.FAHRENHEIT,
29  "C": UnitOfTemperature.CELSIUS,
30 }
31 
32 
33 class ThinQEntity(CoordinatorEntity[DeviceDataUpdateCoordinator]):
34  """The base implementation of all lg thinq entities."""
35 
36  _attr_has_entity_name = True
37 
38  def __init__(
39  self,
40  coordinator: DeviceDataUpdateCoordinator,
41  entity_description: EntityDescription,
42  property_id: str,
43  ) -> None:
44  """Initialize an entity."""
45  super().__init__(coordinator)
46 
47  self.entity_descriptionentity_description = entity_description
48  self.property_idproperty_id = property_id
49  self.locationlocation = self.coordinator.api.get_location_for_idx(self.property_idproperty_id)
50 
51  self._attr_device_info_attr_device_info = dr.DeviceInfo(
52  identifiers={(DOMAIN, coordinator.unique_id)},
53  manufacturer=COMPANY,
54  model=f"{coordinator.api.device.model_name} ({self.coordinator.api.device.device_type})",
55  name=coordinator.device_name,
56  )
57  self._attr_unique_id_attr_unique_id = f"{coordinator.unique_id}_{self.property_id}"
58  if self.locationlocation is not None and self.locationlocation not in (
59  Location.MAIN,
60  Location.OVEN,
61  coordinator.sub_id,
62  ):
63  self._attr_translation_placeholders_attr_translation_placeholders = {"location": self.locationlocation}
64  self._attr_translation_key_attr_translation_key = (
65  f"{entity_description.translation_key}_for_location"
66  )
67 
68  @property
69  def data(self) -> PropertyState:
70  """Return the state data of entity."""
71  return self.coordinator.data.get(self.property_idproperty_id, EMPTY_STATE)
72 
73  def _get_unit_of_measurement(self, unit: str | None) -> str | None:
74  """Convert thinq unit string to HA unit string."""
75  if unit is None:
76  return None
77 
78  return UNIT_CONVERSION_MAP.get(unit)
79 
80  def _update_status(self) -> None:
81  """Update status itself.
82 
83  All inherited classes can update their own status in here.
84  """
85 
86  @callback
87  def _handle_coordinator_update(self) -> None:
88  """Handle updated data from the coordinator."""
89  self._update_status_update_status()
90  self.async_write_ha_state()
91 
92  async def async_added_to_hass(self) -> None:
93  """Call when entity is added to hass."""
94  await super().async_added_to_hass()
95  self._handle_coordinator_update_handle_coordinator_update()
96 
97  async def async_call_api(
98  self,
99  target: Coroutine[Any, Any, Any],
100  on_fail_method: Callable[[], None] | None = None,
101  ) -> None:
102  """Call the given api and handle exception."""
103  try:
104  await target
105  except ThinQAPIException as exc:
106  if on_fail_method:
107  on_fail_method()
109  exc.message, translation_domain=DOMAIN, translation_key=exc.code
110  ) from exc
111  except ValueError as exc:
112  if on_fail_method:
113  on_fail_method()
114  raise ServiceValidationError(exc) from exc
None async_call_api(self, Coroutine[Any, Any, Any] target, Callable[[], None]|None on_fail_method=None)
Definition: entity.py:101
None __init__(self, DeviceDataUpdateCoordinator coordinator, EntityDescription entity_description, str property_id)
Definition: entity.py:43
str|None _get_unit_of_measurement(self, str|None unit)
Definition: entity.py:73