Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Coordinate data for powerview devices."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from datetime import timedelta
7 import logging
8 
9 from aiopvapi.helpers.aiorequest import PvApiMaintenance
10 from aiopvapi.hub import Hub
11 from aiopvapi.shades import Shades
12 
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
15 
16 from .const import HUB_EXCEPTIONS
17 from .shade_data import PowerviewShadeData
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 
23  """DataUpdateCoordinator to gather data from a powerview hub."""
24 
25  def __init__(self, hass: HomeAssistant, shades: Shades, hub: Hub) -> None:
26  """Initialize DataUpdateCoordinator to gather data for specific Powerview Hub."""
27  self.shadesshades = shades
28  self.hubhub = hub
29  # The hub tends to crash if there are multiple radio operations at the same time
30  # but it seems to handle all other requests that do not use RF without issue
31  # so we have a lock to prevent multiple radio operations at the same time
32  self.radio_operation_lockradio_operation_lock = asyncio.Lock()
33  super().__init__(
34  hass,
35  _LOGGER,
36  name=f"powerview hub {hub.hub_address}",
37  update_interval=timedelta(seconds=60),
38  )
39 
40  async def _async_update_data(self) -> PowerviewShadeData:
41  """Fetch data from shade endpoint."""
42 
43  try:
44  shade_entries = await self.shadesshades.get_shades()
45  except PvApiMaintenance as error:
46  # hub is undergoing maintenance, pause polling
47  raise UpdateFailed(error) from error
48  except HUB_EXCEPTIONS as error:
49  raise UpdateFailed(
50  f"Powerview Hub {self.hub.hub_address} did not return any data: {error}"
51  ) from error
52 
53  if not shade_entries:
54  raise UpdateFailed("No new shade data was returned")
55 
56  # only update if shade_entries is valid
57  self.datadata.store_group_data(shade_entries)
58 
59  return self.datadata