Move ukraine_alarm coordinator to separate module (#126549)

pull/126552/head
epenet 2024-09-23 15:58:02 +02:00 committed by GitHub
parent 380019dd56
commit 02ab2c1433
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 52 additions and 44 deletions

View File

@ -2,25 +2,13 @@
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
import aiohttp
from aiohttp import ClientSession
from uasiren.client import Client
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_REGION
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import ALERT_TYPES, DOMAIN, PLATFORMS
_LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = timedelta(seconds=10)
from .const import DOMAIN, PLATFORMS
from .coordinator import UkraineAlarmDataUpdateCoordinator
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
@ -45,32 +33,3 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
class UkraineAlarmDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): # pylint: disable=hass-enforce-class-module
"""Class to manage fetching Ukraine Alarm API."""
def __init__(
self,
hass: HomeAssistant,
session: ClientSession,
region_id: str,
) -> None:
"""Initialize."""
self.region_id = region_id
self.uasiren = Client(session)
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL)
async def _async_update_data(self) -> dict[str, Any]:
"""Update data via library."""
try:
res = await self.uasiren.get_alerts(self.region_id)
except aiohttp.ClientError as error:
raise UpdateFailed(f"Error fetching alerts from API: {error}") from error
current = {alert_type: False for alert_type in ALERT_TYPES}
for alert in res[0]["activeAlerts"]:
current[alert["type"]] = True
return current

View File

@ -14,7 +14,6 @@ from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import UkraineAlarmDataUpdateCoordinator
from .const import (
ALERT_TYPE_AIR,
ALERT_TYPE_ARTILLERY,
@ -26,6 +25,7 @@ from .const import (
DOMAIN,
MANUFACTURER,
)
from .coordinator import UkraineAlarmDataUpdateCoordinator
BINARY_SENSOR_TYPES: tuple[BinarySensorEntityDescription, ...] = (
BinarySensorEntityDescription(

View File

@ -0,0 +1,49 @@
"""The ukraine_alarm component."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
import aiohttp
from aiohttp import ClientSession
from uasiren.client import Client
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import ALERT_TYPES, DOMAIN
_LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = timedelta(seconds=10)
class UkraineAlarmDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Class to manage fetching Ukraine Alarm API."""
def __init__(
self,
hass: HomeAssistant,
session: ClientSession,
region_id: str,
) -> None:
"""Initialize."""
self.region_id = region_id
self.uasiren = Client(session)
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL)
async def _async_update_data(self) -> dict[str, Any]:
"""Update data via library."""
try:
res = await self.uasiren.get_alerts(self.region_id)
except aiohttp.ClientError as error:
raise UpdateFailed(f"Error fetching alerts from API: {error}") from error
current = {alert_type: False for alert_type in ALERT_TYPES}
for alert in res[0]["activeAlerts"]:
current[alert["type"]] = True
return current