diff --git a/custom_components/localtuya/__init__.py b/custom_components/localtuya/__init__.py index 2f3349f..64d7e57 100644 --- a/custom_components/localtuya/__init__.py +++ b/custom_components/localtuya/__init__.py @@ -1,4 +1,5 @@ """The LocalTuya integration integration.""" +import asyncio import logging import voluptuous as vol @@ -25,6 +26,8 @@ _LOGGER = logging.getLogger(__name__) DEFAULT_ID = "1" DEFAULT_PROTOCOL_VERSION = 3.3 +UNSUB_LISTENER = "unsub_listener" + BASE_PLATFORM_SCHEMA = { vol.Optional(CONF_ICON): cv.icon, # Deprecated: not used vol.Required(CONF_HOST): cv.string, @@ -77,13 +80,19 @@ def import_from_yaml(hass, config, platform): async def async_setup(hass: HomeAssistant, config: dict): """Set up the LocalTuya integration component.""" + hass.data.setdefault(DOMAIN, {}) return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up LocalTuya integration from a config entry.""" + unsub_listener = entry.add_update_listener(update_listener) + + hass.data[DOMAIN][entry.entry_id] = { + UNSUB_LISTENER: unsub_listener, + } + for platform in set(entity[CONF_PLATFORM] for entity in entry.data[CONF_ENTITIES]): - # print("ASE*** [{}] [{}]".format(entry.data["entities"][0][CONF_PLATFORM], platform)) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform) ) @@ -92,10 +101,29 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" - # Nothing is stored and no persistent connections exist, so nothing to do + unload_ok = all( + await asyncio.gather( + *[ + hass.config_entries.async_forward_entry_unload(entry, component) + for component in set( + entity[CONF_PLATFORM] for entity in entry.data[CONF_ENTITIES] + ) + ] + ) + ) + + hass.data[DOMAIN][entry.entry_id][UNSUB_LISTENER]() + if unload_ok: + hass.data[DOMAIN].pop(entry.entry_id) + return True +async def update_listener(hass, config_entry): + """Update listener.""" + await hass.config_entries.async_reload(config_entry.entry_id) + + def get_entity_config(config_entry, dps_id): """Return entity config for a given DPS id.""" for entity in config_entry.data[CONF_ENTITIES]: