Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Provides the DataUpdateCoordinator."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 
7 from automower_ble.mower import Mower
8 from bleak import BleakError
9 from bleak_retry_connector import close_stale_connections_by_address
10 
11 from homeassistant.components import bluetooth
12 from homeassistant.core import HomeAssistant
13 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
14 
15 from .const import DOMAIN, LOGGER
16 
17 SCAN_INTERVAL = timedelta(seconds=60)
18 
19 
21  """Class to manage fetching data."""
22 
23  def __init__(
24  self,
25  hass: HomeAssistant,
26  mower: Mower,
27  address: str,
28  channel_id: str,
29  model: str,
30  ) -> None:
31  """Initialize global data updater."""
32  super().__init__(
33  hass=hass,
34  logger=LOGGER,
35  name=DOMAIN,
36  update_interval=SCAN_INTERVAL,
37  )
38  self.addressaddress = address
39  self.channel_idchannel_id = channel_id
40  self.modelmodel = model
41  self.mowermower = mower
42 
43  async def async_shutdown(self) -> None:
44  """Shutdown coordinator and any connection."""
45  LOGGER.debug("Shutdown")
46  await super().async_shutdown()
47  if self.mowermower.is_connected():
48  await self.mowermower.disconnect()
49 
50  async def _async_find_device(self):
51  LOGGER.debug("Trying to reconnect")
52  await close_stale_connections_by_address(self.addressaddress)
53 
54  device = bluetooth.async_ble_device_from_address(
55  self.hasshass, self.addressaddress, connectable=True
56  )
57 
58  try:
59  if not await self.mowermower.connect(device):
60  raise UpdateFailed("Failed to connect")
61  except BleakError as err:
62  raise UpdateFailed("Failed to connect") from err
63 
64  async def _async_update_data(self) -> dict[str, bytes]:
65  """Poll the device."""
66  LOGGER.debug("Polling device")
67 
68  data: dict[str, bytes] = {}
69 
70  try:
71  if not self.mowermower.is_connected():
72  await self._async_find_device_async_find_device()
73  except BleakError as err:
74  raise UpdateFailed("Failed to connect") from err
75 
76  try:
77  data["battery_level"] = await self.mowermower.battery_level()
78  LOGGER.debug("battery_level" + str(data["battery_level"]))
79  if data["battery_level"] is None:
80  await self._async_find_device_async_find_device()
81  raise UpdateFailed("Error getting data from device")
82 
83  data["activity"] = await self.mowermower.mower_activity()
84  LOGGER.debug("activity:" + str(data["activity"]))
85  if data["activity"] is None:
86  await self._async_find_device_async_find_device()
87  raise UpdateFailed("Error getting data from device")
88 
89  data["state"] = await self.mowermower.mower_state()
90  LOGGER.debug("state:" + str(data["state"]))
91  if data["state"] is None:
92  await self._async_find_device_async_find_device()
93  raise UpdateFailed("Error getting data from device")
94 
95  except BleakError as err:
96  LOGGER.error("Error getting data from device")
97  await self._async_find_device_async_find_device()
98  raise UpdateFailed("Error getting data from device") from err
99 
100  return data
None __init__(self, HomeAssistant hass, Mower mower, str address, str channel_id, str model)
Definition: coordinator.py:30