Add automatic keep-alive for IKEA Trådfri (#41778)

* 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 <paulus@home-assistant.io>

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
Thomas Barnekov 2020-10-16 11:21:36 +02:00 committed by GitHub
parent d16c04a8e0
commit 8be3f2f2a5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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(