|
| 1 | +"""Coordinator for the Uptime Kuma integration.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from datetime import timedelta |
| 6 | +import logging |
| 7 | + |
| 8 | +from pythonkuma import ( |
| 9 | + UptimeKuma, |
| 10 | + UptimeKumaAuthenticationException, |
| 11 | + UptimeKumaException, |
| 12 | + UptimeKumaMonitor, |
| 13 | + UptimeKumaVersion, |
| 14 | +) |
| 15 | + |
| 16 | +from homeassistant.config_entries import ConfigEntry |
| 17 | +from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL |
| 18 | +from homeassistant.core import HomeAssistant, callback |
| 19 | +from homeassistant.exceptions import ConfigEntryError |
| 20 | +from homeassistant.helpers import entity_registry as er |
| 21 | +from homeassistant.helpers.aiohttp_client import async_get_clientsession |
| 22 | +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed |
| 23 | + |
| 24 | +from .const import DOMAIN |
| 25 | + |
| 26 | +_LOGGER = logging.getLogger(__name__) |
| 27 | + |
| 28 | +type UptimeKumaConfigEntry = ConfigEntry[UptimeKumaDataUpdateCoordinator] |
| 29 | + |
| 30 | + |
| 31 | +class UptimeKumaDataUpdateCoordinator( |
| 32 | + DataUpdateCoordinator[dict[str | int, UptimeKumaMonitor]] |
| 33 | +): |
| 34 | + """Update coordinator for Uptime Kuma.""" |
| 35 | + |
| 36 | + config_entry: UptimeKumaConfigEntry |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, hass: HomeAssistant, config_entry: UptimeKumaConfigEntry |
| 40 | + ) -> None: |
| 41 | + """Initialize the coordinator.""" |
| 42 | + |
| 43 | + super().__init__( |
| 44 | + hass, |
| 45 | + _LOGGER, |
| 46 | + config_entry=config_entry, |
| 47 | + name=DOMAIN, |
| 48 | + update_interval=timedelta(seconds=30), |
| 49 | + ) |
| 50 | + session = async_get_clientsession(hass, config_entry.data[CONF_VERIFY_SSL]) |
| 51 | + self.api = UptimeKuma( |
| 52 | + session, config_entry.data[CONF_URL], config_entry.data[CONF_API_KEY] |
| 53 | + ) |
| 54 | + self.version: UptimeKumaVersion | None = None |
| 55 | + |
| 56 | + async def _async_update_data(self) -> dict[str | int, UptimeKumaMonitor]: |
| 57 | + """Fetch the latest data from Uptime Kuma.""" |
| 58 | + |
| 59 | + try: |
| 60 | + metrics = await self.api.metrics() |
| 61 | + except UptimeKumaAuthenticationException as e: |
| 62 | + raise ConfigEntryError( |
| 63 | + translation_domain=DOMAIN, |
| 64 | + translation_key="auth_failed_exception", |
| 65 | + ) from e |
| 66 | + except UptimeKumaException as e: |
| 67 | + raise UpdateFailed( |
| 68 | + translation_domain=DOMAIN, |
| 69 | + translation_key="request_failed_exception", |
| 70 | + ) from e |
| 71 | + else: |
| 72 | + async_migrate_entities_unique_ids(self.hass, self, metrics) |
| 73 | + self.version = self.api.version |
| 74 | + |
| 75 | + return metrics |
| 76 | + |
| 77 | + |
| 78 | +@callback |
| 79 | +def async_migrate_entities_unique_ids( |
| 80 | + hass: HomeAssistant, |
| 81 | + coordinator: UptimeKumaDataUpdateCoordinator, |
| 82 | + metrics: dict[str | int, UptimeKumaMonitor], |
| 83 | +) -> None: |
| 84 | + """Migrate unique_ids in the entity registry after updating Uptime Kuma.""" |
| 85 | + |
| 86 | + if ( |
| 87 | + coordinator.version is coordinator.api.version |
| 88 | + or int(coordinator.api.version.major) < 2 |
| 89 | + ): |
| 90 | + return |
| 91 | + |
| 92 | + entity_registry = er.async_get(hass) |
| 93 | + registry_entries = er.async_entries_for_config_entry( |
| 94 | + entity_registry, coordinator.config_entry.entry_id |
| 95 | + ) |
| 96 | + |
| 97 | + for registry_entry in registry_entries: |
| 98 | + name = registry_entry.unique_id.removeprefix( |
| 99 | + f"{registry_entry.config_entry_id}_" |
| 100 | + ).removesuffix(f"_{registry_entry.translation_key}") |
| 101 | + if monitor := next( |
| 102 | + (m for m in metrics.values() if m.monitor_name == name), None |
| 103 | + ): |
| 104 | + entity_registry.async_update_entity( |
| 105 | + registry_entry.entity_id, |
| 106 | + new_unique_id=f"{registry_entry.config_entry_id}_{monitor.monitor_id!s}_{registry_entry.translation_key}", |
| 107 | + ) |
0 commit comments