11"""The generic_thermostat component."""
22
33from homeassistant .config_entries import ConfigEntry
4- from homeassistant .core import HomeAssistant
4+ from homeassistant .core import Event , HomeAssistant
5+ from homeassistant .helpers import entity_registry as er
56from homeassistant .helpers .device import (
7+ async_entity_id_to_device_id ,
68 async_remove_stale_devices_links_keep_entity_device ,
79)
10+ from homeassistant .helpers .event import async_track_entity_registry_updated_event
11+ from homeassistant .helpers .helper_integration import async_handle_source_entity_changes
812
9- from .const import CONF_HEATER , PLATFORMS
13+ from .const import CONF_HEATER , CONF_SENSOR , PLATFORMS
1014
1115
1216async def async_setup_entry (hass : HomeAssistant , entry : ConfigEntry ) -> bool :
@@ -17,6 +21,55 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
1721 entry .entry_id ,
1822 entry .options [CONF_HEATER ],
1923 )
24+
25+ def set_humidifier_entity_id_or_uuid (source_entity_id : str ) -> None :
26+ hass .config_entries .async_update_entry (
27+ entry ,
28+ options = {** entry .options , CONF_HEATER : source_entity_id },
29+ )
30+
31+ async def source_entity_removed () -> None :
32+ # The source entity has been removed, we need to clean the device links.
33+ async_remove_stale_devices_links_keep_entity_device (hass , entry .entry_id , None )
34+
35+ entry .async_on_unload (
36+ # We use async_handle_source_entity_changes to track changes to the heater, but
37+ # not the temperature sensor because the generic_hygrostat adds itself to the
38+ # heater's device.
39+ async_handle_source_entity_changes (
40+ hass ,
41+ helper_config_entry_id = entry .entry_id ,
42+ set_source_entity_id_or_uuid = set_humidifier_entity_id_or_uuid ,
43+ source_device_id = async_entity_id_to_device_id (
44+ hass , entry .options [CONF_HEATER ]
45+ ),
46+ source_entity_id_or_uuid = entry .options [CONF_HEATER ],
47+ source_entity_removed = source_entity_removed ,
48+ )
49+ )
50+
51+ async def async_sensor_updated (
52+ event : Event [er .EventEntityRegistryUpdatedData ],
53+ ) -> None :
54+ """Handle entity registry update."""
55+ data = event .data
56+ if data ["action" ] != "update" :
57+ return
58+ if "entity_id" not in data ["changes" ]:
59+ return
60+
61+ # Entity_id changed, update the config entry
62+ hass .config_entries .async_update_entry (
63+ entry ,
64+ options = {** entry .options , CONF_SENSOR : data ["entity_id" ]},
65+ )
66+
67+ entry .async_on_unload (
68+ async_track_entity_registry_updated_event (
69+ hass , entry .options [CONF_SENSOR ], async_sensor_updated
70+ )
71+ )
72+
2073 await hass .config_entries .async_forward_entry_setups (entry , PLATFORMS )
2174 entry .async_on_unload (entry .add_update_listener (config_entry_update_listener ))
2275 return True
0 commit comments