From c64d9cefbed1acf93b229684f852bfe44913bbf8 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Wed, 26 Jul 2023 23:40:54 -0700 Subject: [PATCH] Delete AdaptiveLighting instances that have been removed from YAML (#669) * Do not re-add already added configs * Use async_remove --- .../adaptive_lighting/config_flow.py | 5 ++++- custom_components/adaptive_lighting/switch.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/custom_components/adaptive_lighting/config_flow.py b/custom_components/adaptive_lighting/config_flow.py index 170c8503..3dd89fd4 100644 --- a/custom_components/adaptive_lighting/config_flow.py +++ b/custom_components/adaptive_lighting/config_flow.py @@ -40,10 +40,13 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): ) async def async_step_import(self, user_input=None): - """Handle configuration by yaml file.""" + """Handle configuration by YAML file.""" await self.async_set_unique_id(user_input[CONF_NAME]) for entry in self._async_current_entries(): if entry.unique_id == self.unique_id: + # Keep a list of switches that are configured via YAML + data = self.hass.data.setdefault(DOMAIN, {}) + data.setdefault("__yaml__", []).append(self.unique_id) self.hass.config_entries.async_update_entry(entry, data=user_input) self._abort_if_unique_id_configured() return self.async_create_entry(title=user_input[CONF_NAME], data=user_input) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 6bba8afe..72b53635 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -42,6 +42,7 @@ from homeassistant.components.light import ( from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.switch import SwitchEntity +from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import ( ATTR_AREA_ID, ATTR_DOMAIN, @@ -444,6 +445,22 @@ async def async_setup_entry( # noqa: PLR0915 assert hass is not None data = hass.data[DOMAIN] assert config_entry.entry_id in data + _LOGGER.debug( + "Setting up AdaptiveLighting with data: %s and config_entry %s", + data, + config_entry, + ) + if ( # Skip deleted YAML config entries + config_entry.source == SOURCE_IMPORT + and config_entry.unique_id not in data.get("__yaml__", []) + ): + _LOGGER.warning( + "Deleting AdaptiveLighting switch '%s' because YAML" + " defined switch has been removed from YAML configuration", + config_entry.unique_id, + ) + await hass.config_entries.async_remove(config_entry.entry_id) + return manager = data.setdefault( ATTR_ADAPTIVE_LIGHTING_MANAGER, AdaptiveLightingManager(hass, config_entry),