From 8be3f2f2a55b92c4718283e437097f8c03711ebc Mon Sep 17 00:00:00 2001 From: Thomas Barnekov <37448419+tbarnekov@users.noreply.github.com> Date: Fri, 16 Oct 2020 11:21:36 +0200 Subject: [PATCH] =?UTF-8?q?Add=20automatic=20keep-alive=20for=20IKEA=20Tr?= =?UTF-8?q?=C3=A5dfri=20(#41778)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added automatic keep-alive for IKEA Trådfri * Don't shut down factory on keep-alive error * Avoid keep-alive after shutdown Co-authored-by: Paulus Schoutsen Co-authored-by: Paulus Schoutsen --- homeassistant/components/tradfri/__init__.py | 26 +++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) 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(