From 29c852f96cd13a783e664a103cd389ed37151c38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pierre=20St=C3=A5hl?= Date: Mon, 28 Sep 2020 09:27:40 +0200 Subject: [PATCH] Add support for reloading from YAML --- custom_components/localtuya/__init__.py | 40 ++++++++++++++++++++++- custom_components/localtuya/services.yaml | 2 ++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 custom_components/localtuya/services.yaml diff --git a/custom_components/localtuya/__init__.py b/custom_components/localtuya/__init__.py index 2feffb4..306b468 100644 --- a/custom_components/localtuya/__init__.py +++ b/custom_components/localtuya/__init__.py @@ -53,14 +53,16 @@ import logging from datetime import timedelta, datetime from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback from homeassistant.const import ( CONF_DEVICE_ID, CONF_PLATFORM, CONF_ENTITIES, + SERVICE_RELOAD, ) from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.dispatcher import async_dispatcher_send +from homeassistant.helpers.reload import async_integration_yaml_config from .const import DOMAIN, TUYA_DEVICE from .config_flow import config_schema @@ -76,10 +78,46 @@ POLL_INTERVAL = 30 CONFIG_SCHEMA = config_schema() +@callback +def _async_update_config_entry_if_from_yaml(hass, entries_by_id, conf): + """Update a config entry with the latest yaml.""" + device_id = conf[CONF_DEVICE_ID] + + if device_id in entries_by_id and entries_by_id[device_id].source == SOURCE_IMPORT: + entry = entries_by_id[device_id] + hass.config_entries.async_update_entry(entry, data=conf.copy()) + + async def async_setup(hass: HomeAssistant, config: dict): """Set up the LocalTuya integration component.""" hass.data.setdefault(DOMAIN, {}) + async def _handle_reload(service): + """Handle reload service call.""" + config = await async_integration_yaml_config(hass, DOMAIN) + + if not config or DOMAIN not in config: + return + + current_entries = hass.config_entries.async_entries(DOMAIN) + entries_by_id = {entry.data[CONF_DEVICE_ID]: entry for entry in current_entries} + + for conf in config[DOMAIN]: + _async_update_config_entry_if_from_yaml(hass, entries_by_id, conf) + + reload_tasks = [ + hass.config_entries.async_reload(entry.entry_id) + for entry in current_entries + ] + + await asyncio.gather(*reload_tasks) + + hass.helpers.service.async_register_admin_service( + DOMAIN, + SERVICE_RELOAD, + _handle_reload, + ) + for host_config in config.get(DOMAIN, []): hass.async_create_task( hass.config_entries.flow.async_init( diff --git a/custom_components/localtuya/services.yaml b/custom_components/localtuya/services.yaml new file mode 100644 index 0000000..9aff7d7 --- /dev/null +++ b/custom_components/localtuya/services.yaml @@ -0,0 +1,2 @@ +reload: + description: Reload localtuya and re-process yaml configuration.