Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Coordinator for Glances integration."""
2 
3 from datetime import datetime, timedelta
4 import logging
5 from typing import Any
6 
7 from glances_api import Glances, exceptions
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_HOST
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import ConfigEntryAuthFailed
13 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
14 from homeassistant.util.dt import parse_duration, utcnow
15 
16 from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
22  """Get the latest data from Glances api."""
23 
24  config_entry: ConfigEntry
25 
26  def __init__(self, hass: HomeAssistant, entry: ConfigEntry, api: Glances) -> None:
27  """Initialize the Glances data."""
28  self.hasshasshass = hass
29  self.config_entryconfig_entryconfig_entry = entry
30  self.host: str = entry.data[CONF_HOST]
31  self.apiapi = api
32  super().__init__(
33  hass,
34  _LOGGER,
35  name=f"{DOMAIN} - {self.host}",
36  update_interval=DEFAULT_SCAN_INTERVAL,
37  )
38 
39  async def _async_update_data(self) -> dict[str, Any]:
40  """Get the latest data from the Glances REST API."""
41  try:
42  data = await self.apiapi.get_ha_sensor_data()
43  except exceptions.GlancesApiAuthorizationError as err:
44  raise ConfigEntryAuthFailed from err
45  except exceptions.GlancesApiError as err:
46  raise UpdateFailed from err
47  # Update computed values
48  uptime: datetime | None = None
49  up_duration: timedelta | None = None
50  if "uptime" in data and (up_duration := parse_duration(data["uptime"])):
51  uptime = self.datadata["computed"]["uptime"] if self.datadata else None
52  # Update uptime if previous value is None or previous uptime is bigger than
53  # new uptime (i.e. server restarted)
54  if uptime is None or self.datadata["computed"]["uptime_duration"] > up_duration:
55  uptime = utcnow() - up_duration
56  data["computed"] = {"uptime_duration": up_duration, "uptime": uptime}
57  return data or {}
None __init__(self, HomeAssistant hass, ConfigEntry entry, Glances api)
Definition: coordinator.py:26
dt.timedelta|None parse_duration(str value)
Definition: dt.py:265