2021-02-24 08:34:27 +00:00
|
|
|
"""The ClimaCell integration."""
|
2021-03-17 22:43:55 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2021-02-24 08:34:27 +00:00
|
|
|
import asyncio
|
|
|
|
from datetime import timedelta
|
|
|
|
import logging
|
|
|
|
from math import ceil
|
2021-03-17 22:43:55 +00:00
|
|
|
from typing import Any
|
2021-02-24 08:34:27 +00:00
|
|
|
|
2021-04-05 17:39:39 +00:00
|
|
|
from pyclimacell import ClimaCellV3, ClimaCellV4
|
|
|
|
from pyclimacell.const import CURRENT, DAILY, FORECASTS, HOURLY, NOWCAST
|
|
|
|
from pyclimacell.exceptions import (
|
2021-02-24 08:34:27 +00:00
|
|
|
CantConnectException,
|
|
|
|
InvalidAPIKeyException,
|
|
|
|
RateLimitedException,
|
|
|
|
UnknownException,
|
|
|
|
)
|
|
|
|
|
2021-04-15 20:31:59 +00:00
|
|
|
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
|
2021-02-24 08:34:27 +00:00
|
|
|
from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN
|
|
|
|
from homeassistant.config_entries import ConfigEntry
|
2021-04-05 17:39:39 +00:00
|
|
|
from homeassistant.const import (
|
|
|
|
CONF_API_KEY,
|
|
|
|
CONF_API_VERSION,
|
|
|
|
CONF_LATITUDE,
|
|
|
|
CONF_LONGITUDE,
|
|
|
|
CONF_NAME,
|
|
|
|
)
|
2021-02-24 08:34:27 +00:00
|
|
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
2021-03-29 23:23:44 +00:00
|
|
|
from homeassistant.helpers.typing import HomeAssistantType
|
2021-02-24 08:34:27 +00:00
|
|
|
from homeassistant.helpers.update_coordinator import (
|
|
|
|
CoordinatorEntity,
|
|
|
|
DataUpdateCoordinator,
|
|
|
|
UpdateFailed,
|
|
|
|
)
|
|
|
|
|
|
|
|
from .const import (
|
2021-04-15 20:31:59 +00:00
|
|
|
ATTR_FIELD,
|
2021-02-24 08:34:27 +00:00
|
|
|
ATTRIBUTION,
|
2021-04-11 09:59:42 +00:00
|
|
|
CC_ATTR_CLOUD_COVER,
|
2021-04-05 17:39:39 +00:00
|
|
|
CC_ATTR_CONDITION,
|
|
|
|
CC_ATTR_HUMIDITY,
|
|
|
|
CC_ATTR_OZONE,
|
|
|
|
CC_ATTR_PRECIPITATION,
|
|
|
|
CC_ATTR_PRECIPITATION_PROBABILITY,
|
2021-04-11 09:59:42 +00:00
|
|
|
CC_ATTR_PRECIPITATION_TYPE,
|
2021-04-05 17:39:39 +00:00
|
|
|
CC_ATTR_PRESSURE,
|
|
|
|
CC_ATTR_TEMPERATURE,
|
|
|
|
CC_ATTR_TEMPERATURE_HIGH,
|
|
|
|
CC_ATTR_TEMPERATURE_LOW,
|
|
|
|
CC_ATTR_VISIBILITY,
|
|
|
|
CC_ATTR_WIND_DIRECTION,
|
2021-04-11 09:59:42 +00:00
|
|
|
CC_ATTR_WIND_GUST,
|
2021-04-05 17:39:39 +00:00
|
|
|
CC_ATTR_WIND_SPEED,
|
2021-04-15 20:31:59 +00:00
|
|
|
CC_SENSOR_TYPES,
|
2021-04-11 09:59:42 +00:00
|
|
|
CC_V3_ATTR_CLOUD_COVER,
|
2021-04-05 17:39:39 +00:00
|
|
|
CC_V3_ATTR_CONDITION,
|
|
|
|
CC_V3_ATTR_HUMIDITY,
|
|
|
|
CC_V3_ATTR_OZONE,
|
|
|
|
CC_V3_ATTR_PRECIPITATION,
|
|
|
|
CC_V3_ATTR_PRECIPITATION_DAILY,
|
|
|
|
CC_V3_ATTR_PRECIPITATION_PROBABILITY,
|
2021-04-11 09:59:42 +00:00
|
|
|
CC_V3_ATTR_PRECIPITATION_TYPE,
|
2021-04-05 17:39:39 +00:00
|
|
|
CC_V3_ATTR_PRESSURE,
|
|
|
|
CC_V3_ATTR_TEMPERATURE,
|
|
|
|
CC_V3_ATTR_VISIBILITY,
|
|
|
|
CC_V3_ATTR_WIND_DIRECTION,
|
2021-04-11 09:59:42 +00:00
|
|
|
CC_V3_ATTR_WIND_GUST,
|
2021-04-05 17:39:39 +00:00
|
|
|
CC_V3_ATTR_WIND_SPEED,
|
2021-04-15 20:31:59 +00:00
|
|
|
CC_V3_SENSOR_TYPES,
|
2021-02-24 08:34:27 +00:00
|
|
|
CONF_TIMESTEP,
|
|
|
|
DEFAULT_TIMESTEP,
|
|
|
|
DOMAIN,
|
|
|
|
MAX_REQUESTS_PER_DAY,
|
|
|
|
)
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2021-04-15 20:31:59 +00:00
|
|
|
PLATFORMS = [SENSOR_DOMAIN, WEATHER_DOMAIN]
|
2021-02-24 08:34:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _set_update_interval(
|
|
|
|
hass: HomeAssistantType, current_entry: ConfigEntry
|
|
|
|
) -> timedelta:
|
|
|
|
"""Recalculate update_interval based on existing ClimaCell instances and update them."""
|
2021-04-05 17:39:39 +00:00
|
|
|
api_calls = 4 if current_entry.data[CONF_API_VERSION] == 3 else 2
|
2021-02-24 08:34:27 +00:00
|
|
|
# We check how many ClimaCell configured instances are using the same API key and
|
|
|
|
# calculate interval to not exceed allowed numbers of requests. Divide 90% of
|
|
|
|
# MAX_REQUESTS_PER_DAY by 4 because every update requires four API calls and we want
|
|
|
|
# a buffer in the number of API calls left at the end of the day.
|
|
|
|
other_instance_entry_ids = [
|
|
|
|
entry.entry_id
|
|
|
|
for entry in hass.config_entries.async_entries(DOMAIN)
|
|
|
|
if entry.entry_id != current_entry.entry_id
|
|
|
|
and entry.data[CONF_API_KEY] == current_entry.data[CONF_API_KEY]
|
|
|
|
]
|
|
|
|
|
|
|
|
interval = timedelta(
|
|
|
|
minutes=(
|
|
|
|
ceil(
|
2021-04-05 17:39:39 +00:00
|
|
|
(24 * 60 * (len(other_instance_entry_ids) + 1) * api_calls)
|
2021-02-24 08:34:27 +00:00
|
|
|
/ (MAX_REQUESTS_PER_DAY * 0.9)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
for entry_id in other_instance_entry_ids:
|
|
|
|
if entry_id in hass.data[DOMAIN]:
|
|
|
|
hass.data[DOMAIN][entry_id].update_interval = interval
|
|
|
|
|
|
|
|
return interval
|
|
|
|
|
|
|
|
|
|
|
|
async def async_setup_entry(hass: HomeAssistantType, config_entry: ConfigEntry) -> bool:
|
|
|
|
"""Set up ClimaCell API from a config entry."""
|
|
|
|
hass.data.setdefault(DOMAIN, {})
|
|
|
|
|
2021-04-05 17:39:39 +00:00
|
|
|
params = {}
|
2021-02-24 08:34:27 +00:00
|
|
|
# If config entry options not set up, set them up
|
|
|
|
if not config_entry.options:
|
2021-04-05 17:39:39 +00:00
|
|
|
params["options"] = {
|
|
|
|
CONF_TIMESTEP: DEFAULT_TIMESTEP,
|
|
|
|
}
|
|
|
|
else:
|
|
|
|
# Use valid timestep if it's invalid
|
|
|
|
timestep = config_entry.options[CONF_TIMESTEP]
|
|
|
|
if timestep not in (1, 5, 15, 30):
|
|
|
|
if timestep <= 2:
|
|
|
|
timestep = 1
|
|
|
|
elif timestep <= 7:
|
|
|
|
timestep = 5
|
|
|
|
elif timestep <= 20:
|
|
|
|
timestep = 15
|
|
|
|
else:
|
|
|
|
timestep = 30
|
|
|
|
new_options = config_entry.options.copy()
|
|
|
|
new_options[CONF_TIMESTEP] = timestep
|
|
|
|
params["options"] = new_options
|
|
|
|
# Add API version if not found
|
|
|
|
if CONF_API_VERSION not in config_entry.data:
|
|
|
|
new_data = config_entry.data.copy()
|
|
|
|
new_data[CONF_API_VERSION] = 3
|
|
|
|
params["data"] = new_data
|
|
|
|
|
|
|
|
if params:
|
|
|
|
hass.config_entries.async_update_entry(config_entry, **params)
|
|
|
|
|
|
|
|
api_class = ClimaCellV3 if config_entry.data[CONF_API_VERSION] == 3 else ClimaCellV4
|
|
|
|
api = api_class(
|
|
|
|
config_entry.data[CONF_API_KEY],
|
|
|
|
config_entry.data.get(CONF_LATITUDE, hass.config.latitude),
|
|
|
|
config_entry.data.get(CONF_LONGITUDE, hass.config.longitude),
|
|
|
|
session=async_get_clientsession(hass),
|
|
|
|
)
|
2021-02-24 08:34:27 +00:00
|
|
|
|
|
|
|
coordinator = ClimaCellDataUpdateCoordinator(
|
|
|
|
hass,
|
|
|
|
config_entry,
|
2021-04-05 17:39:39 +00:00
|
|
|
api,
|
2021-02-24 08:34:27 +00:00
|
|
|
_set_update_interval(hass, config_entry),
|
|
|
|
)
|
|
|
|
|
2021-03-29 22:51:39 +00:00
|
|
|
await coordinator.async_config_entry_first_refresh()
|
2021-02-24 08:34:27 +00:00
|
|
|
|
|
|
|
hass.data[DOMAIN][config_entry.entry_id] = coordinator
|
|
|
|
|
2021-03-02 20:43:59 +00:00
|
|
|
for platform in PLATFORMS:
|
2021-02-24 08:34:27 +00:00
|
|
|
hass.async_create_task(
|
2021-03-02 20:43:59 +00:00
|
|
|
hass.config_entries.async_forward_entry_setup(config_entry, platform)
|
2021-02-24 08:34:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
async def async_unload_entry(
|
|
|
|
hass: HomeAssistantType, config_entry: ConfigEntry
|
|
|
|
) -> bool:
|
|
|
|
"""Unload a config entry."""
|
|
|
|
unload_ok = all(
|
|
|
|
await asyncio.gather(
|
|
|
|
*[
|
2021-03-02 20:43:59 +00:00
|
|
|
hass.config_entries.async_forward_entry_unload(config_entry, platform)
|
|
|
|
for platform in PLATFORMS
|
2021-02-24 08:34:27 +00:00
|
|
|
]
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
hass.data[DOMAIN].pop(config_entry.entry_id)
|
|
|
|
if not hass.data[DOMAIN]:
|
|
|
|
hass.data.pop(DOMAIN)
|
|
|
|
|
|
|
|
return unload_ok
|
|
|
|
|
|
|
|
|
|
|
|
class ClimaCellDataUpdateCoordinator(DataUpdateCoordinator):
|
|
|
|
"""Define an object to hold ClimaCell data."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
hass: HomeAssistantType,
|
|
|
|
config_entry: ConfigEntry,
|
2021-04-05 17:39:39 +00:00
|
|
|
api: ClimaCellV3 | ClimaCellV4,
|
2021-02-24 08:34:27 +00:00
|
|
|
update_interval: timedelta,
|
|
|
|
) -> None:
|
|
|
|
"""Initialize."""
|
|
|
|
|
|
|
|
self._config_entry = config_entry
|
2021-04-05 17:39:39 +00:00
|
|
|
self._api_version = config_entry.data[CONF_API_VERSION]
|
2021-02-24 08:34:27 +00:00
|
|
|
self._api = api
|
|
|
|
self.name = config_entry.data[CONF_NAME]
|
|
|
|
self.data = {CURRENT: {}, FORECASTS: {}}
|
|
|
|
|
|
|
|
super().__init__(
|
|
|
|
hass,
|
|
|
|
_LOGGER,
|
|
|
|
name=config_entry.data[CONF_NAME],
|
|
|
|
update_interval=update_interval,
|
|
|
|
)
|
|
|
|
|
2021-03-17 22:43:55 +00:00
|
|
|
async def _async_update_data(self) -> dict[str, Any]:
|
2021-02-24 08:34:27 +00:00
|
|
|
"""Update data via library."""
|
|
|
|
data = {FORECASTS: {}}
|
|
|
|
try:
|
2021-04-05 17:39:39 +00:00
|
|
|
if self._api_version == 3:
|
|
|
|
data[CURRENT] = await self._api.realtime(
|
|
|
|
[
|
|
|
|
CC_V3_ATTR_TEMPERATURE,
|
|
|
|
CC_V3_ATTR_HUMIDITY,
|
|
|
|
CC_V3_ATTR_PRESSURE,
|
|
|
|
CC_V3_ATTR_WIND_SPEED,
|
|
|
|
CC_V3_ATTR_WIND_DIRECTION,
|
|
|
|
CC_V3_ATTR_CONDITION,
|
|
|
|
CC_V3_ATTR_VISIBILITY,
|
|
|
|
CC_V3_ATTR_OZONE,
|
2021-04-11 09:59:42 +00:00
|
|
|
CC_V3_ATTR_WIND_GUST,
|
|
|
|
CC_V3_ATTR_CLOUD_COVER,
|
|
|
|
CC_V3_ATTR_PRECIPITATION_TYPE,
|
2021-04-15 20:31:59 +00:00
|
|
|
*[
|
|
|
|
sensor_type[ATTR_FIELD]
|
|
|
|
for sensor_type in CC_V3_SENSOR_TYPES
|
|
|
|
],
|
2021-04-05 17:39:39 +00:00
|
|
|
]
|
|
|
|
)
|
|
|
|
data[FORECASTS][HOURLY] = await self._api.forecast_hourly(
|
|
|
|
[
|
|
|
|
CC_V3_ATTR_TEMPERATURE,
|
|
|
|
CC_V3_ATTR_WIND_SPEED,
|
|
|
|
CC_V3_ATTR_WIND_DIRECTION,
|
|
|
|
CC_V3_ATTR_CONDITION,
|
|
|
|
CC_V3_ATTR_PRECIPITATION,
|
|
|
|
CC_V3_ATTR_PRECIPITATION_PROBABILITY,
|
|
|
|
],
|
|
|
|
None,
|
|
|
|
timedelta(hours=24),
|
|
|
|
)
|
|
|
|
|
|
|
|
data[FORECASTS][DAILY] = await self._api.forecast_daily(
|
|
|
|
[
|
|
|
|
CC_V3_ATTR_TEMPERATURE,
|
|
|
|
CC_V3_ATTR_WIND_SPEED,
|
|
|
|
CC_V3_ATTR_WIND_DIRECTION,
|
|
|
|
CC_V3_ATTR_CONDITION,
|
|
|
|
CC_V3_ATTR_PRECIPITATION_DAILY,
|
|
|
|
CC_V3_ATTR_PRECIPITATION_PROBABILITY,
|
|
|
|
],
|
|
|
|
None,
|
|
|
|
timedelta(days=14),
|
|
|
|
)
|
|
|
|
|
|
|
|
data[FORECASTS][NOWCAST] = await self._api.forecast_nowcast(
|
|
|
|
[
|
|
|
|
CC_V3_ATTR_TEMPERATURE,
|
|
|
|
CC_V3_ATTR_WIND_SPEED,
|
|
|
|
CC_V3_ATTR_WIND_DIRECTION,
|
|
|
|
CC_V3_ATTR_CONDITION,
|
|
|
|
CC_V3_ATTR_PRECIPITATION,
|
|
|
|
],
|
|
|
|
None,
|
|
|
|
timedelta(
|
|
|
|
minutes=min(300, self._config_entry.options[CONF_TIMESTEP] * 30)
|
|
|
|
),
|
|
|
|
self._config_entry.options[CONF_TIMESTEP],
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
return await self._api.realtime_and_all_forecasts(
|
|
|
|
[
|
|
|
|
CC_ATTR_TEMPERATURE,
|
|
|
|
CC_ATTR_HUMIDITY,
|
|
|
|
CC_ATTR_PRESSURE,
|
|
|
|
CC_ATTR_WIND_SPEED,
|
|
|
|
CC_ATTR_WIND_DIRECTION,
|
|
|
|
CC_ATTR_CONDITION,
|
|
|
|
CC_ATTR_VISIBILITY,
|
|
|
|
CC_ATTR_OZONE,
|
2021-04-11 09:59:42 +00:00
|
|
|
CC_ATTR_WIND_GUST,
|
|
|
|
CC_ATTR_CLOUD_COVER,
|
|
|
|
CC_ATTR_PRECIPITATION_TYPE,
|
2021-04-15 20:31:59 +00:00
|
|
|
*[sensor_type[ATTR_FIELD] for sensor_type in CC_SENSOR_TYPES],
|
2021-04-05 17:39:39 +00:00
|
|
|
],
|
|
|
|
[
|
|
|
|
CC_ATTR_TEMPERATURE_LOW,
|
|
|
|
CC_ATTR_TEMPERATURE_HIGH,
|
|
|
|
CC_ATTR_WIND_SPEED,
|
|
|
|
CC_ATTR_WIND_DIRECTION,
|
|
|
|
CC_ATTR_CONDITION,
|
|
|
|
CC_ATTR_PRECIPITATION,
|
|
|
|
CC_ATTR_PRECIPITATION_PROBABILITY,
|
|
|
|
],
|
|
|
|
)
|
2021-02-24 08:34:27 +00:00
|
|
|
except (
|
|
|
|
CantConnectException,
|
|
|
|
InvalidAPIKeyException,
|
|
|
|
RateLimitedException,
|
|
|
|
UnknownException,
|
|
|
|
) as error:
|
|
|
|
raise UpdateFailed from error
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
|
class ClimaCellEntity(CoordinatorEntity):
|
|
|
|
"""Base ClimaCell Entity."""
|
|
|
|
|
|
|
|
def __init__(
|
2021-04-05 17:39:39 +00:00
|
|
|
self,
|
|
|
|
config_entry: ConfigEntry,
|
|
|
|
coordinator: ClimaCellDataUpdateCoordinator,
|
|
|
|
api_version: int,
|
2021-02-24 08:34:27 +00:00
|
|
|
) -> None:
|
|
|
|
"""Initialize ClimaCell Entity."""
|
|
|
|
super().__init__(coordinator)
|
2021-04-05 17:39:39 +00:00
|
|
|
self.api_version = api_version
|
2021-02-24 08:34:27 +00:00
|
|
|
self._config_entry = config_entry
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _get_cc_value(
|
2021-03-17 22:43:55 +00:00
|
|
|
weather_dict: dict[str, Any], key: str
|
|
|
|
) -> int | float | str | None:
|
2021-04-15 20:31:59 +00:00
|
|
|
"""
|
|
|
|
Return property from weather_dict.
|
|
|
|
|
|
|
|
Used for V3 API.
|
|
|
|
"""
|
2021-02-24 08:34:27 +00:00
|
|
|
items = weather_dict.get(key, {})
|
|
|
|
# Handle cases where value returned is a list.
|
|
|
|
# Optimistically find the best value to return.
|
|
|
|
if isinstance(items, list):
|
|
|
|
if len(items) == 1:
|
|
|
|
return items[0].get("value")
|
|
|
|
return next(
|
|
|
|
(item.get("value") for item in items if "max" in item),
|
|
|
|
next(
|
|
|
|
(item.get("value") for item in items if "min" in item),
|
|
|
|
items[0].get("value", None),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
return items.get("value")
|
|
|
|
|
2021-04-15 20:31:59 +00:00
|
|
|
def _get_current_property(self, property_name: str) -> int | str | float | None:
|
|
|
|
"""
|
|
|
|
Get property from current conditions.
|
2021-04-05 17:39:39 +00:00
|
|
|
|
2021-04-15 20:31:59 +00:00
|
|
|
Used for V4 API.
|
|
|
|
"""
|
|
|
|
return self.coordinator.data.get(CURRENT, {}).get(property_name)
|
2021-02-24 08:34:27 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def attribution(self):
|
|
|
|
"""Return the attribution."""
|
|
|
|
return ATTRIBUTION
|
|
|
|
|
|
|
|
@property
|
2021-03-17 22:43:55 +00:00
|
|
|
def device_info(self) -> dict[str, Any]:
|
2021-02-24 08:34:27 +00:00
|
|
|
"""Return device registry information."""
|
|
|
|
return {
|
|
|
|
"identifiers": {(DOMAIN, self._config_entry.data[CONF_API_KEY])},
|
2021-03-03 00:55:10 +00:00
|
|
|
"name": "ClimaCell",
|
2021-02-24 08:34:27 +00:00
|
|
|
"manufacturer": "ClimaCell",
|
2021-04-15 20:31:59 +00:00
|
|
|
"sw_version": f"v{self.api_version}",
|
2021-02-24 08:34:27 +00:00
|
|
|
"entry_type": "service",
|
|
|
|
}
|