diff --git a/homeassistant/helpers/area_registry.py b/homeassistant/helpers/area_registry.py index 3cb978f964f9..1ffecd4286d5 100644 --- a/homeassistant/helpers/area_registry.py +++ b/homeassistant/helpers/area_registry.py @@ -8,7 +8,7 @@ from datetime import datetime from typing import TYPE_CHECKING, Any, Literal, TypedDict, override from homeassistant.const import EntityStateAttribute -from homeassistant.core import HomeAssistant, callback, verify_event_loop_thread +from homeassistant.core import Event, HomeAssistant, callback, verify_event_loop_thread from homeassistant.util.dt import utc_from_timestamp, utcnow from homeassistant.util.event_type import EventType from homeassistant.util.hass_dict import HassKey @@ -390,6 +390,7 @@ class AreaRegistry(BaseRegistry[AreasRegistryStoreData]): name: str | UndefinedType = UNDEFINED, picture: str | UndefinedType | None = UNDEFINED, temperature_entity_id: str | UndefinedType | None = UNDEFINED, + validate: bool = True, ) -> AreaEntry: """Update name of area.""" old = self.areas[area_id] @@ -408,10 +409,18 @@ class AreaRegistry(BaseRegistry[AreasRegistryStoreData]): if value is not UNDEFINED and value != getattr(old, attr_name) } - if "humidity_entity_id" in new_values and humidity_entity_id is not None: + if ( + validate + and "humidity_entity_id" in new_values + and humidity_entity_id is not None + ): _validate_humidity_entity(self.hass, new_values["humidity_entity_id"]) - if "temperature_entity_id" in new_values and temperature_entity_id is not None: + if ( + validate + and "temperature_entity_id" in new_values + and temperature_entity_id is not None + ): _validate_temperature_entity(self.hass, new_values["temperature_entity_id"]) if name is not UNDEFINED and name != old.name: @@ -502,6 +511,7 @@ class AreaRegistry(BaseRegistry[AreasRegistryStoreData]): def _async_setup_cleanup(self) -> None: """Set up the area registry cleanup.""" from . import ( # Circular dependencies # noqa: PLC0415 + entity_registry as er, floor_registry as fr, label_registry as lr, ) @@ -542,6 +552,48 @@ class AreaRegistry(BaseRegistry[AreasRegistryStoreData]): listener=_handle_label_registry_update, ) + @callback + def _entity_renamed_filter( + event_data: er.EventEntityRegistryUpdatedData, + ) -> bool: + """Filter entity registry events for renamed entities.""" + return event_data["action"] == "update" and "old_entity_id" in event_data + + @callback + def _handle_entity_registry_update( + event: Event[er.EventEntityRegistryUpdatedData], + ) -> None: + """Update areas referencing an entity that was renamed.""" + if TYPE_CHECKING: + assert event.data["action"] == "update" + old_entity_id = event.data["old_entity_id"] + new_entity_id = event.data["entity_id"] + + for area in list(self.areas.values()): + humidity_match = area.humidity_entity_id == old_entity_id + temperature_match = area.temperature_entity_id == old_entity_id + if not humidity_match and not temperature_match: + continue + # The renamed entity's state may not exist yet under its new id + self._async_update( + area.id, + humidity_entity_id=new_entity_id if humidity_match else UNDEFINED, + temperature_entity_id=( + new_entity_id if temperature_match else UNDEFINED + ), + validate=False, + ) + self.hass.bus.async_fire_internal( + EVENT_AREA_REGISTRY_UPDATED, + EventAreaRegistryUpdatedData(action="update", area_id=area.id), + ) + + self.hass.bus.async_listen( + event_type=er.EVENT_ENTITY_REGISTRY_UPDATED, + event_filter=_entity_renamed_filter, + listener=_handle_entity_registry_update, + ) + @callback @singleton(DATA_REGISTRY) diff --git a/tests/helpers/test_area_registry.py b/tests/helpers/test_area_registry.py index e8c39110aeb5..40faab5bcd21 100644 --- a/tests/helpers/test_area_registry.py +++ b/tests/helpers/test_area_registry.py @@ -18,6 +18,7 @@ from homeassistant.const import ( from homeassistant.core import HomeAssistant from homeassistant.helpers import ( area_registry as ar, + entity_registry as er, floor_registry as fr, label_registry as lr, ) @@ -725,6 +726,67 @@ async def test_removing_labels( assert not area_registry.async_get_area(bedroom.id).labels +@pytest.mark.parametrize( + ("attribute", "device_class"), + [ + pytest.param( + "temperature_entity_id", SensorDeviceClass.TEMPERATURE, id="temperature" + ), + pytest.param("humidity_entity_id", SensorDeviceClass.HUMIDITY, id="humidity"), + ], +) +async def test_entity_renamed( + hass: HomeAssistant, + area_registry: ar.AreaRegistry, + entity_registry: er.EntityRegistry, + attribute: str, + device_class: SensorDeviceClass, +) -> None: + """Test area sensor references follow entity_id renames.""" + entry = entity_registry.async_get_or_create("sensor", "test", "1234") + hass.states.async_set(entry.entity_id, "20", {ATTR_DEVICE_CLASS: device_class}) + kitchen = area_registry.async_create("Kitchen", **{attribute: entry.entity_id}) + bedroom = area_registry.async_create("Bedroom") + update_events = async_capture_events(hass, ar.EVENT_AREA_REGISTRY_UPDATED) + + entity_registry.async_update_entity(entry.entity_id, new_entity_id="sensor.renamed") + await hass.async_block_till_done() + + assert getattr(area_registry.async_get_area(kitchen.id), attribute) == ( + "sensor.renamed" + ) + assert getattr(area_registry.async_get_area(bedroom.id), attribute) is None + assert [event.data for event in update_events] == [ + {"action": "update", "area_id": kitchen.id} + ] + + +async def test_entity_removed_or_unrelated_entity_renamed( + hass: HomeAssistant, + area_registry: ar.AreaRegistry, + entity_registry: er.EntityRegistry, +) -> None: + """Test area sensor references are kept on removal and unrelated renames.""" + referenced = entity_registry.async_get_or_create("sensor", "test", "1") + unrelated = entity_registry.async_get_or_create("sensor", "test", "2") + hass.states.async_set( + referenced.entity_id, + "20", + {ATTR_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE}, + ) + kitchen = area_registry.async_create( + "Kitchen", temperature_entity_id=referenced.entity_id + ) + update_events = async_capture_events(hass, ar.EVENT_AREA_REGISTRY_UPDATED) + + entity_registry.async_update_entity(unrelated.entity_id, new_entity_id="sensor.new") + entity_registry.async_remove(referenced.entity_id) + await hass.async_block_till_done() + + assert area_registry.async_get_area(kitchen.id) == kitchen + assert not update_events + + @pytest.mark.usefixtures("hass") async def test_entries_for_label( area_registry: ar.AreaRegistry, label_registry: lr.LabelRegistry