Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Coordinator for Roku."""
2 
3 from __future__ import annotations
4 
5 from datetime import datetime, timedelta
6 import logging
7 
8 from rokuecp import Roku, RokuError
9 from rokuecp.models import Device
10 
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers.aiohttp_client import async_get_clientsession
13 from homeassistant.helpers.debounce import Debouncer
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
15 from homeassistant.util.dt import utcnow
16 
17 from .const import DOMAIN
18 
19 REQUEST_REFRESH_DELAY = 0.35
20 
21 SCAN_INTERVAL = timedelta(seconds=10)
22 _LOGGER = logging.getLogger(__name__)
23 
24 
26  """Class to manage fetching Roku data."""
27 
28  last_full_update: datetime | None
29  roku: Roku
30 
31  def __init__(
32  self, hass: HomeAssistant, *, host: str, device_id: str, play_media_app_id: str
33  ) -> None:
34  """Initialize global Roku data updater."""
35  self.device_iddevice_id = device_id
36  self.rokuroku = Roku(host=host, session=async_get_clientsession(hass))
37  self.play_media_app_idplay_media_app_id = play_media_app_id
38 
39  self.full_update_intervalfull_update_interval = timedelta(minutes=15)
40  self.last_full_updatelast_full_update = None
41 
42  super().__init__(
43  hass,
44  _LOGGER,
45  name=DOMAIN,
46  update_interval=SCAN_INTERVAL,
47  # We don't want an immediate refresh since the device
48  # takes a moment to reflect the state change
49  request_refresh_debouncer=Debouncer(
50  hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False
51  ),
52  )
53 
54  async def _async_update_data(self) -> Device:
55  """Fetch data from Roku."""
56  full_update = self.last_full_updatelast_full_update is None or utcnow() >= (
57  self.last_full_updatelast_full_update + self.full_update_intervalfull_update_interval
58  )
59 
60  try:
61  data = await self.rokuroku.update(full_update=full_update)
62  except RokuError as error:
63  raise UpdateFailed(f"Invalid response from API: {error}") from error
64 
65  if full_update:
66  self.last_full_updatelast_full_update = utcnow()
67 
68  return data
None __init__(self, HomeAssistant hass, *str host, str device_id, str play_media_app_id)
Definition: coordinator.py:33
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)