diff --git a/homeassistant/components/tradfri/__init__.py b/homeassistant/components/tradfri/__init__.py index 002231e4e20..3a89852a55e 100644 --- a/homeassistant/components/tradfri/__init__.py +++ b/homeassistant/components/tradfri/__init__.py @@ -1,14 +1,19 @@ """Support for IKEA Tradfri.""" import asyncio +from datetime import timedelta +import logging from pytradfri import Gateway, RequestError from pytradfri.api.aiocoap_api import APIFactory import voluptuous as vol from homeassistant import config_entries +from homeassistant.config_entries import ConfigEntry from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.exceptions import ConfigEntryNotReady import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.event import async_track_time_interval +from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.util.json import load_json from . import config_flow # noqa: F401 @@ -31,6 +36,8 @@ from .const import ( PLATFORMS, ) +_LOGGER = logging.getLogger(__name__) + FACTORY = "tradfri_factory" LISTENERS = "tradfri_listeners" @@ -49,7 +56,7 @@ CONFIG_SCHEMA = vol.Schema( ) -async def async_setup(hass, config): +async def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up the Tradfri component.""" conf = config.get(DOMAIN) @@ -94,7 +101,7 @@ async def async_setup(hass, config): return True -async def async_setup_entry(hass, entry): +async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups tradfri_data = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {} @@ -147,10 +154,23 @@ async def async_setup_entry(hass, entry): hass.config_entries.async_forward_entry_setup(entry, component) ) + async def async_keep_alive(now): + if hass.is_stopping: + return + + try: + await api(gateway.get_gateway_info()) + except RequestError: + _LOGGER.error("Keep-alive failed") + + listeners.append( + async_track_time_interval(hass, async_keep_alive, timedelta(seconds=60)) + ) + return True -async def async_unload_entry(hass, entry): +async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry): """Unload a config entry.""" unload_ok = all( await asyncio.gather(