|
17 | 17 | entity_registry as er, |
18 | 18 | ) |
19 | 19 | from homeassistant.helpers.device import ( |
| 20 | + async_entity_id_to_device_id, |
20 | 21 | async_remove_stale_devices_links_keep_entity_device, |
21 | 22 | ) |
22 | 23 | from homeassistant.helpers.dispatcher import async_dispatcher_send |
| 24 | +from homeassistant.helpers.helper_integration import async_handle_source_entity_changes |
23 | 25 | from homeassistant.helpers.typing import ConfigType |
24 | 26 |
|
25 | 27 | from .const import ( |
@@ -217,6 +219,29 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: |
217 | 219 | ) |
218 | 220 | return False |
219 | 221 |
|
| 222 | + def set_source_entity_id_or_uuid(source_entity_id: str) -> None: |
| 223 | + hass.config_entries.async_update_entry( |
| 224 | + entry, |
| 225 | + options={**entry.options, CONF_SOURCE_SENSOR: source_entity_id}, |
| 226 | + ) |
| 227 | + |
| 228 | + async def source_entity_removed() -> None: |
| 229 | + # The source entity has been removed, we need to clean the device links. |
| 230 | + async_remove_stale_devices_links_keep_entity_device(hass, entry.entry_id, None) |
| 231 | + |
| 232 | + entry.async_on_unload( |
| 233 | + async_handle_source_entity_changes( |
| 234 | + hass, |
| 235 | + helper_config_entry_id=entry.entry_id, |
| 236 | + set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, |
| 237 | + source_device_id=async_entity_id_to_device_id( |
| 238 | + hass, entry.options[CONF_SOURCE_SENSOR] |
| 239 | + ), |
| 240 | + source_entity_id_or_uuid=entry.options[CONF_SOURCE_SENSOR], |
| 241 | + source_entity_removed=source_entity_removed, |
| 242 | + ) |
| 243 | + ) |
| 244 | + |
220 | 245 | if not entry.options.get(CONF_TARIFFS): |
221 | 246 | # Only a single meter sensor is required |
222 | 247 | hass.data[DATA_UTILITY][entry.entry_id][CONF_TARIFF_ENTITY] = None |
|
0 commit comments