hass-core/homeassistant/components/laundrify/coordinator.py
xLarry abf9aab18f
Add laundrify integration (#65090)
* First version of laundrify integration

* Code cleanup

* Code cleanup after review #2

* Move coordinator to its own file

* Save devices as dict and implement available prop as fn

* Validate token on init, abort if already configured

* Some more cleanup after review

* Add strict type hints

* Minor changes after code review

* Remove OptionsFlow (use default poll interval instead)

* Fix CODEOWNERS to pass hassfest job

* Fix formatting to pass prettier job

* Fix mypy typing error

* Update internal device property after fetching data

* Call parental update handler and remove obsolete code

* Add coordinator tests and fix some config flow tests

* Refactor tests

* Refactor fixtures

* Device unavailable if polling fails
2022-05-21 15:18:01 -04:00

46 lines
1.8 KiB
Python

"""Custom DataUpdateCoordinator for the laundrify integration."""
from datetime import timedelta
import logging
import async_timeout
from laundrify_aio import LaundrifyAPI
from laundrify_aio.exceptions import ApiConnectionException, UnauthorizedException
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN, REQUEST_TIMEOUT
from .model import LaundrifyDevice
_LOGGER = logging.getLogger(__name__)
class LaundrifyUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching laundrify API data."""
def __init__(
self, hass: HomeAssistant, laundrify_api: LaundrifyAPI, poll_interval: int
) -> None:
"""Initialize laundrify coordinator."""
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
update_interval=timedelta(seconds=poll_interval),
)
self.laundrify_api = laundrify_api
async def _async_update_data(self) -> dict[str, LaundrifyDevice]:
"""Fetch data from laundrify API."""
try:
# Note: asyncio.TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator.
async with async_timeout.timeout(REQUEST_TIMEOUT):
return {m["_id"]: m for m in await self.laundrify_api.get_machines()}
except UnauthorizedException as err:
# Raising ConfigEntryAuthFailed will cancel future updates
# and start a config flow with SOURCE_REAUTH (async_step_reauth)
raise ConfigEntryAuthFailed from err
except ApiConnectionException as err:
raise UpdateFailed(f"Error communicating with API: {err}") from err