Home Assistant Unofficial Reference 2024.12.1
entity.py
Go to the documentation of this file.
1 """Support for SwitchBee entity."""
2 
3 import logging
4 from typing import cast
5 
6 from switchbee import SWITCHBEE_BRAND
7 from switchbee.device import DeviceType, SwitchBeeBaseDevice
8 
9 from homeassistant.helpers.device_registry import DeviceInfo
10 from homeassistant.helpers.update_coordinator import CoordinatorEntity
11 
12 from .const import DOMAIN
13 from .coordinator import SwitchBeeCoordinator
14 
15 _LOGGER = logging.getLogger(__name__)
16 
17 
18 class SwitchBeeEntity[_DeviceTypeT: SwitchBeeBaseDevice](
19  CoordinatorEntity[SwitchBeeCoordinator]
20 ):
21  """Representation of a Switchbee entity."""
22 
23  _attr_has_entity_name = True
24 
25  def __init__(
26  self,
27  device: _DeviceTypeT,
28  coordinator: SwitchBeeCoordinator,
29  ) -> None:
30  """Initialize the Switchbee entity."""
31  super().__init__(coordinator)
32  self._device = device
33  self._attr_name = device.name
34  self._attr_unique_id = f"{coordinator.unique_id}-{device.id}"
35 
36 
37 class SwitchBeeDeviceEntity[_DeviceTypeT: SwitchBeeBaseDevice](
38  SwitchBeeEntity[_DeviceTypeT]
39 ):
40  """Representation of a Switchbee device entity."""
41 
42  def __init__(
43  self,
44  device: _DeviceTypeT,
45  coordinator: SwitchBeeCoordinator,
46  ) -> None:
47  """Initialize the Switchbee device."""
48  super().__init__(device, coordinator)
49  self._is_online: bool = True
50  identifier = (
51  device.id if device.type == DeviceType.Thermostat else device.unit_id
52  )
53  self._attr_device_info = DeviceInfo(
54  name=device.zone,
55  identifiers={
56  (
57  DOMAIN,
58  f"{identifier}-{coordinator.unique_id}",
59  )
60  },
61  manufacturer=SWITCHBEE_BRAND,
62  model=coordinator.api.module_display(device.unit_id),
63  suggested_area=device.zone,
64  via_device=(
65  DOMAIN,
66  f"{coordinator.api.name} ({coordinator.api.unique_id})",
67  ),
68  )
69 
70  @property
71  def available(self) -> bool:
72  """Return True if entity is available."""
73  return self._is_online and super().available
74 
75  def _check_if_became_offline(self) -> None:
76  """Check if the device was online (now offline), log message and mark it as Unavailable."""
77 
78  if self._is_online:
79  _LOGGER.warning(
80  (
81  "%s device is not responding, check the status in the SwitchBee"
82  " mobile app"
83  ),
84  self.name,
85  )
86  self._is_online = False
87 
88  def _check_if_became_online(self) -> None:
89  """Check if the device was offline (now online) and bring it back."""
90  if not self._is_online:
91  _LOGGER.warning(
92  "%s device is now responding",
93  self.name,
94  )
95  self._is_online = True
96 
97  def _get_coordinator_device(self) -> _DeviceTypeT:
98  return cast(_DeviceTypeT, self.coordinator.data[self._device.id])
_DeviceTypeT _get_coordinator_device(self)
Definition: entity.py:97
None __init__(self, _DeviceTypeT device, SwitchBeeCoordinator coordinator)
Definition: entity.py:29