2021-02-05 11:41:36 +00:00
|
|
|
"""The Airly integration."""
|
2021-05-07 14:47:52 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2019-10-16 10:06:52 +00:00
|
|
|
from datetime import timedelta
|
2019-10-31 16:29:27 +00:00
|
|
|
import logging
|
2020-03-25 18:13:28 +00:00
|
|
|
from math import ceil
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2021-05-07 14:47:52 +00:00
|
|
|
from aiohttp import ClientSession
|
2019-10-16 10:06:52 +00:00
|
|
|
from aiohttp.client_exceptions import ClientConnectorError
|
|
|
|
from airly import Airly
|
|
|
|
from airly.exceptions import AirlyError
|
2019-10-31 16:29:27 +00:00
|
|
|
import async_timeout
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2021-05-07 14:47:52 +00:00
|
|
|
from homeassistant.config_entries import ConfigEntry
|
2019-10-16 10:06:52 +00:00
|
|
|
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE
|
2021-05-07 14:47:52 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
2019-10-16 10:06:52 +00:00
|
|
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
2021-05-07 14:47:52 +00:00
|
|
|
from homeassistant.helpers.device_registry import async_get_registry
|
2020-03-25 18:13:28 +00:00
|
|
|
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
2021-04-27 21:34:53 +00:00
|
|
|
from homeassistant.util import dt as dt_util
|
2019-10-16 10:06:52 +00:00
|
|
|
|
|
|
|
from .const import (
|
|
|
|
ATTR_API_ADVICE,
|
|
|
|
ATTR_API_CAQI,
|
|
|
|
ATTR_API_CAQI_DESCRIPTION,
|
|
|
|
ATTR_API_CAQI_LEVEL,
|
2021-01-04 22:14:45 +00:00
|
|
|
CONF_USE_NEAREST,
|
2019-10-16 10:06:52 +00:00
|
|
|
DOMAIN,
|
2021-04-27 21:34:53 +00:00
|
|
|
MAX_UPDATE_INTERVAL,
|
|
|
|
MIN_UPDATE_INTERVAL,
|
2019-10-16 10:06:52 +00:00
|
|
|
NO_AIRLY_SENSORS,
|
|
|
|
)
|
|
|
|
|
2020-03-25 18:13:28 +00:00
|
|
|
PLATFORMS = ["air_quality", "sensor"]
|
|
|
|
|
2019-10-16 10:06:52 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2020-03-25 18:13:28 +00:00
|
|
|
|
2021-05-07 14:47:52 +00:00
|
|
|
def set_update_interval(instances_count: int, requests_remaining: int) -> timedelta:
|
2021-04-27 21:34:53 +00:00
|
|
|
"""
|
|
|
|
Return data update interval.
|
2020-03-25 18:13:28 +00:00
|
|
|
|
2021-04-27 21:34:53 +00:00
|
|
|
The number of requests is reset at midnight UTC so we calculate the update
|
|
|
|
interval based on number of minutes until midnight, the number of Airly instances
|
|
|
|
and the number of remaining requests.
|
|
|
|
"""
|
|
|
|
now = dt_util.utcnow()
|
|
|
|
midnight = dt_util.find_next_time_expression_time(
|
|
|
|
now, seconds=[0], minutes=[0], hours=[0]
|
|
|
|
)
|
|
|
|
minutes_to_midnight = (midnight - now).total_seconds() / 60
|
|
|
|
interval = timedelta(
|
|
|
|
minutes=min(
|
|
|
|
max(
|
2021-05-07 14:47:52 +00:00
|
|
|
ceil(minutes_to_midnight / requests_remaining * instances_count),
|
2021-04-27 21:34:53 +00:00
|
|
|
MIN_UPDATE_INTERVAL,
|
|
|
|
),
|
|
|
|
MAX_UPDATE_INTERVAL,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
_LOGGER.debug("Data will be update every %s", interval)
|
2020-03-25 18:13:28 +00:00
|
|
|
|
|
|
|
return interval
|
2019-10-04 11:58:29 +00:00
|
|
|
|
|
|
|
|
2021-05-07 14:47:52 +00:00
|
|
|
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
2019-10-04 11:58:29 +00:00
|
|
|
"""Set up Airly as config entry."""
|
2021-05-07 14:47:52 +00:00
|
|
|
api_key = entry.data[CONF_API_KEY]
|
|
|
|
latitude = entry.data[CONF_LATITUDE]
|
|
|
|
longitude = entry.data[CONF_LONGITUDE]
|
|
|
|
use_nearest = entry.data.get(CONF_USE_NEAREST, False)
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2020-01-13 12:28:07 +00:00
|
|
|
# For backwards compat, set unique ID
|
2021-05-07 14:47:52 +00:00
|
|
|
if entry.unique_id is None:
|
2020-01-13 12:28:07 +00:00
|
|
|
hass.config_entries.async_update_entry(
|
2021-05-07 14:47:52 +00:00
|
|
|
entry, unique_id=f"{latitude}-{longitude}"
|
2020-01-13 12:28:07 +00:00
|
|
|
)
|
|
|
|
|
2021-05-07 14:47:52 +00:00
|
|
|
# identifiers in device_info should use Tuple[str, str, str] type, but latitude and
|
|
|
|
# longitude are float, so we convert old device entries to use correct types
|
|
|
|
device_registry = await async_get_registry(hass)
|
|
|
|
old_ids = (DOMAIN, latitude, longitude)
|
|
|
|
device_entry = device_registry.async_get_device({old_ids})
|
|
|
|
if device_entry and entry.entry_id in device_entry.config_entries:
|
|
|
|
new_ids = (DOMAIN, str(latitude), str(longitude))
|
|
|
|
device_registry.async_update_device(device_entry.id, new_identifiers={new_ids})
|
|
|
|
|
2019-10-16 10:06:52 +00:00
|
|
|
websession = async_get_clientsession(hass)
|
2021-04-27 21:34:53 +00:00
|
|
|
|
|
|
|
update_interval = timedelta(minutes=MIN_UPDATE_INTERVAL)
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2020-03-25 18:13:28 +00:00
|
|
|
coordinator = AirlyDataUpdateCoordinator(
|
2021-01-04 22:14:45 +00:00
|
|
|
hass, websession, api_key, latitude, longitude, update_interval, use_nearest
|
2020-03-25 18:13:28 +00:00
|
|
|
)
|
2021-03-29 22:51:39 +00:00
|
|
|
await coordinator.async_config_entry_first_refresh()
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2020-03-25 18:13:28 +00:00
|
|
|
hass.data.setdefault(DOMAIN, {})
|
2021-05-07 14:47:52 +00:00
|
|
|
hass.data[DOMAIN][entry.entry_id] = coordinator
|
2020-03-25 18:13:28 +00:00
|
|
|
|
2021-05-07 14:47:52 +00:00
|
|
|
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2019-10-04 11:58:29 +00:00
|
|
|
return True
|
|
|
|
|
|
|
|
|
2021-05-07 14:47:52 +00:00
|
|
|
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
2019-10-04 11:58:29 +00:00
|
|
|
"""Unload a config entry."""
|
2021-05-07 14:47:52 +00:00
|
|
|
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
2021-04-26 17:46:55 +00:00
|
|
|
|
2020-03-25 18:13:28 +00:00
|
|
|
if unload_ok:
|
2021-05-07 14:47:52 +00:00
|
|
|
hass.data[DOMAIN].pop(entry.entry_id)
|
2020-03-25 18:13:28 +00:00
|
|
|
|
|
|
|
return unload_ok
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2020-03-25 18:13:28 +00:00
|
|
|
|
|
|
|
class AirlyDataUpdateCoordinator(DataUpdateCoordinator):
|
2019-10-16 10:06:52 +00:00
|
|
|
"""Define an object to hold Airly data."""
|
|
|
|
|
2021-01-04 22:14:45 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
2021-05-07 14:47:52 +00:00
|
|
|
hass: HomeAssistant,
|
|
|
|
session: ClientSession,
|
|
|
|
api_key: str,
|
|
|
|
latitude: float,
|
|
|
|
longitude: float,
|
|
|
|
update_interval: timedelta,
|
|
|
|
use_nearest: bool,
|
2021-01-04 22:14:45 +00:00
|
|
|
):
|
2019-10-16 10:06:52 +00:00
|
|
|
"""Initialize."""
|
|
|
|
self.latitude = latitude
|
|
|
|
self.longitude = longitude
|
|
|
|
self.airly = Airly(api_key, session)
|
2021-01-04 22:14:45 +00:00
|
|
|
self.use_nearest = use_nearest
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2020-03-25 18:13:28 +00:00
|
|
|
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)
|
2019-10-16 10:06:52 +00:00
|
|
|
|
2021-05-07 14:47:52 +00:00
|
|
|
async def _async_update_data(self) -> dict[str, str | float | int]:
|
2020-03-25 18:13:28 +00:00
|
|
|
"""Update data via library."""
|
2021-05-07 14:47:52 +00:00
|
|
|
data: dict[str, str | float | int] = {}
|
2021-01-04 22:14:45 +00:00
|
|
|
if self.use_nearest:
|
|
|
|
measurements = self.airly.create_measurements_session_nearest(
|
|
|
|
self.latitude, self.longitude, max_distance_km=5
|
|
|
|
)
|
|
|
|
else:
|
2020-03-25 18:13:28 +00:00
|
|
|
measurements = self.airly.create_measurements_session_point(
|
|
|
|
self.latitude, self.longitude
|
|
|
|
)
|
2021-01-04 22:14:45 +00:00
|
|
|
with async_timeout.timeout(20):
|
2020-03-25 18:13:28 +00:00
|
|
|
try:
|
2019-10-16 10:06:52 +00:00
|
|
|
await measurements.update()
|
2020-03-25 18:13:28 +00:00
|
|
|
except (AirlyError, ClientConnectorError) as error:
|
2020-08-28 11:50:32 +00:00
|
|
|
raise UpdateFailed(error) from error
|
2020-03-25 18:13:28 +00:00
|
|
|
|
2021-02-28 11:53:13 +00:00
|
|
|
_LOGGER.debug(
|
|
|
|
"Requests remaining: %s/%s",
|
|
|
|
self.airly.requests_remaining,
|
|
|
|
self.airly.requests_per_day,
|
|
|
|
)
|
|
|
|
|
2021-04-27 21:34:53 +00:00
|
|
|
# Airly API sometimes returns None for requests remaining so we update
|
|
|
|
# update_interval only if we have valid value.
|
|
|
|
if self.airly.requests_remaining:
|
|
|
|
self.update_interval = set_update_interval(
|
|
|
|
len(self.hass.config_entries.async_entries(DOMAIN)),
|
|
|
|
self.airly.requests_remaining,
|
|
|
|
)
|
|
|
|
|
2020-03-25 18:13:28 +00:00
|
|
|
values = measurements.current["values"]
|
|
|
|
index = measurements.current["indexes"][0]
|
|
|
|
standards = measurements.current["standards"]
|
|
|
|
|
|
|
|
if index["description"] == NO_AIRLY_SENSORS:
|
|
|
|
raise UpdateFailed("Can't retrieve data: no Airly sensors in this area")
|
|
|
|
for value in values:
|
|
|
|
data[value["name"]] = value["value"]
|
|
|
|
for standard in standards:
|
|
|
|
data[f"{standard['pollutant']}_LIMIT"] = standard["limit"]
|
|
|
|
data[f"{standard['pollutant']}_PERCENT"] = standard["percent"]
|
|
|
|
data[ATTR_API_CAQI] = index["value"]
|
|
|
|
data[ATTR_API_CAQI_LEVEL] = index["level"].lower().replace("_", " ")
|
|
|
|
data[ATTR_API_CAQI_DESCRIPTION] = index["description"]
|
|
|
|
data[ATTR_API_ADVICE] = index["advice"]
|
|
|
|
return data
|