Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Support for iCloud sensors."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.const import PERCENTAGE
10 from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
11 from homeassistant.helpers.device_registry import DeviceInfo
12 from homeassistant.helpers.dispatcher import async_dispatcher_connect
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
14 from homeassistant.helpers.icon import icon_for_battery_level
15 
16 from .account import IcloudAccount, IcloudDevice
17 from .const import DOMAIN
18 
19 
21  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
22 ) -> None:
23  """Set up device tracker for iCloud component."""
24  account: IcloudAccount = hass.data[DOMAIN][entry.unique_id]
25  tracked = set[str]()
26 
27  @callback
28  def update_account():
29  """Update the values of the account."""
30  add_entities(account, async_add_entities, tracked)
31 
32  account.listeners.append(
33  async_dispatcher_connect(hass, account.signal_device_new, update_account)
34  )
35 
36  update_account()
37 
38 
39 @callback
40 def add_entities(account, async_add_entities, tracked):
41  """Add new tracker entities from the account."""
42  new_tracked = []
43 
44  for dev_id, device in account.devices.items():
45  if dev_id in tracked or device.battery_level is None:
46  continue
47 
48  new_tracked.append(IcloudDeviceBatterySensor(account, device))
49  tracked.add(dev_id)
50 
51  async_add_entities(new_tracked, True)
52 
53 
55  """Representation of a iCloud device battery sensor."""
56 
57  _attr_device_class = SensorDeviceClass.BATTERY
58  _attr_native_unit_of_measurement = PERCENTAGE
59  _attr_should_poll = False
60  _attr_has_entity_name = True
61 
62  def __init__(self, account: IcloudAccount, device: IcloudDevice) -> None:
63  """Initialize the battery sensor."""
64  self._account_account = account
65  self._device_device = device
66  self._unsub_dispatcher_unsub_dispatcher: CALLBACK_TYPE | None = None
67  self._attr_unique_id_attr_unique_id = f"{device.unique_id}_battery"
68  self._attr_device_info_attr_device_info = DeviceInfo(
69  configuration_url="https://icloud.com/",
70  identifiers={(DOMAIN, device.unique_id)},
71  manufacturer="Apple",
72  model=device.device_model,
73  name=device.name,
74  )
75 
76  @property
77  def native_value(self) -> int | None:
78  """Battery state percentage."""
79  return self._device_device.battery_level
80 
81  @property
82  def icon(self) -> str:
83  """Battery state icon handling."""
85  battery_level=self._device_device.battery_level,
86  charging=self._device_device.battery_status == "Charging",
87  )
88 
89  @property
90  def extra_state_attributes(self) -> dict[str, Any]:
91  """Return default attributes for the iCloud device entity."""
92  return self._device_device.extra_state_attributes
93 
94  async def async_added_to_hass(self) -> None:
95  """Register state update callback."""
97  self.hasshass, self._account_account.signal_device_update, self.async_write_ha_stateasync_write_ha_state
98  )
99 
100  async def async_will_remove_from_hass(self) -> None:
101  """Clean up after entity before removal."""
102  if self._unsub_dispatcher_unsub_dispatcher:
103  self._unsub_dispatcher_unsub_dispatcher()
None __init__(self, IcloudAccount account, IcloudDevice device)
Definition: sensor.py:62
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:22
def add_entities(account, async_add_entities, tracked)
Definition: sensor.py:40
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103
str icon_for_battery_level(int|None battery_level=None, bool charging=False)
Definition: icon.py:169