diff --git a/homeassistant/helpers/device_registry.py b/homeassistant/helpers/device_registry.py index 990f34d78466..27429a8f4b6c 100644 --- a/homeassistant/helpers/device_registry.py +++ b/homeassistant/helpers/device_registry.py @@ -372,7 +372,10 @@ class DeviceInfoError(HomeAssistantError): """Raised when device info is invalid.""" def __init__( - self, domain: str, device_info: Mapping[str, Any], message: str + self, + domain: str, + device_info: ChildDeviceInfo | Mapping[str, Any], + message: str, ) -> None: """Initialize error.""" super().__init__( @@ -2824,6 +2827,24 @@ class DeviceRegistry(BaseRegistry[dict[str, list[dict[str, Any]]]]): self._live_device_ids.setdefault(device.config_entry_id, set()).add(device.id) return device + @callback + def _resolve_device_info_name( + self, config_entry: ConfigEntry, device_info: ChildDeviceInfo + ) -> str | UndefinedType | None: + """Return the name of a device info, translated if it has a translation key.""" + if isinstance(translation_key := device_info.translation_key, str) and ( + translation_key + ): + translation_placeholders = device_info.translation_placeholders + return self._resolve_translated_name( + config_entry, + translation_key, + None + if translation_placeholders is UNDEFINED + else translation_placeholders, + ) + return device_info.name + @callback def _resolve_translated_name( self, @@ -2859,6 +2880,34 @@ class DeviceRegistry(BaseRegistry[dict[str, list[dict[str, Any]]]]): ) -> ChildDeviceEntry: """Get child device. Create if it doesn't exist. + If identifiers match those of an existing device, that device is converted to + a child device, preserving its id. + """ + return self.async_get_or_create_child_device( + config_entry_id=config_entry_id, + config_subentry_id=config_subentry_id, + disabled_by=disabled_by, + device_info=ChildDeviceInfo( + identifiers=identifiers, + name=name, + parent_device_id=parent_device_id, + suggested_area=suggested_area, + translation_key=translation_key, + translation_placeholders=translation_placeholders, + ), + ) + + @callback + def async_get_or_create_child_device( + self, + *, + config_entry_id: str, + config_subentry_id: str | UndefinedType | None = UNDEFINED, + disabled_by: DeviceEntryDisabler | UndefinedType | None = UNDEFINED, + device_info: ChildDeviceInfo, + ) -> ChildDeviceEntry: + """Get child device. Create if it doesn't exist. + If identifiers match those of an existing device, that device is converted to a child device, preserving its id. """ @@ -2877,25 +2926,11 @@ class DeviceRegistry(BaseRegistry[dict[str, list[dict[str, Any]]]]): f"Config entry {config_entry_id} has no subentry {config_subentry_id}" ) - if translation_key: - name = self._resolve_translated_name( - config_entry, translation_key, translation_placeholders - ) - - # Reconstruct a child device info dict from the arguments, used for error - # reporting and conversion of an existing device to a child device. - device_info: dict[str, Any] = { - key: val - for key, val in ( - ("identifiers", identifiers), - ("name", name), - ("parent_device_id", parent_device_id), - ("suggested_area", suggested_area), - ) - if val is not UNDEFINED - } - domain = config_entry.domain + name = self._resolve_device_info_name(config_entry, device_info) + identifiers = device_info.identifiers + parent_device_id = device_info.parent_device_id + suggested_area = device_info.suggested_area if not identifiers: raise DeviceInfoError( @@ -3069,7 +3104,7 @@ class DeviceRegistry(BaseRegistry[dict[str, list[dict[str, Any]]]]): device: DeviceEntry, parent: DeviceEntry, config_entry: ConfigEntry, - device_info: Mapping[str, Any], + device_info: ChildDeviceInfo, ) -> None: """Validate converting a device to a child device. @@ -4100,7 +4135,7 @@ class DeviceRegistry(BaseRegistry[dict[str, list[dict[str, Any]]]]): self, matched_device: DeviceEntry | None, config_entry: ConfigEntry, - device_info: Mapping[str, Any], + device_info: ChildDeviceInfo | Mapping[str, Any], identifiers: set[tuple[str, str]], connections: set[tuple[str, str]], ) -> None: diff --git a/homeassistant/helpers/entity_platform.py b/homeassistant/helpers/entity_platform.py index c10eacd503d8..0df50fbcaac8 100644 --- a/homeassistant/helpers/entity_platform.py +++ b/homeassistant/helpers/entity_platform.py @@ -845,11 +845,16 @@ class EntityPlatform: A device info with fields gets or creates the device, otherwise the device entry set on the entity is used. """ - device_info = entity.device_info + if (device_info := entity.device_info) is None: + return entity.device_entry + if isinstance(device_info, dr.ChildDeviceInfo): + return dr.async_get(self.hass).async_get_or_create_child_device( + config_entry_id=config_entry_id, + config_subentry_id=config_subentry_id, + device_info=device_info, + ) device_info_fields: dict[str, Any] - if device_info is None: - device_info_fields = {} - elif isinstance(device_info, dr.DeviceInfo | dr.ChildDeviceInfo): + if isinstance(device_info, dr.DeviceInfo): device_info_fields = device_info.as_dict() else: # An integration can still describe its device with a plain diff --git a/tests/helpers/test_device_registry.py b/tests/helpers/test_device_registry.py index ef705b128c92..dcaaa4bf2056 100644 --- a/tests/helpers/test_device_registry.py +++ b/tests/helpers/test_device_registry.py @@ -13444,3 +13444,45 @@ async def test_clear_config_subentry_removes_orphaned_child_device( # The child in the cleared subentry is removed, the one in the other subentry kept assert device_registry.async_get(child_1.id, include_main_devices=False) is None assert device_registry.async_get(child_2.id, include_main_devices=False) is not None + + +async def test_get_or_create_child_device( + device_registry: dr.DeviceRegistry, + mock_config_entry_with_subentries: MockConfigEntry, +) -> None: + """Test getting or creating a child device from a child device info.""" + config_entry_id = mock_config_entry_with_subentries.entry_id + parent = device_registry.async_get_or_create( + config_entry_id=config_entry_id, + config_subentry_id="mock-subentry-id-1-1", + identifiers={("test", "strip")}, + name="Power strip", + ) + + child_device = device_registry.async_get_or_create_child_device( + config_entry_id=config_entry_id, + config_subentry_id="mock-subentry-id-1-1", + disabled_by=dr.DeviceEntryDisabler.INTEGRATION, + device_info=dr.ChildDeviceInfo( + identifiers={("test", "strip_outlet_1")}, + parent_device_id=parent.id, + name="Outlet 1", + ), + ) + assert isinstance(child_device, dr.ChildDeviceEntry) + assert child_device.config_subentry_id == "mock-subentry-id-1-1" + assert child_device.disabled_by is dr.DeviceEntryDisabler.INTEGRATION + assert child_device.identifiers == {("test", "strip_outlet_1")} + assert child_device.name == "Outlet 1" + assert child_device.parent_device_id == parent.id + + # Fields left unset in the child device info keep their value + same_child_device = device_registry.async_get_or_create_child_device( + config_entry_id=config_entry_id, + config_subentry_id="mock-subentry-id-1-1", + device_info=dr.ChildDeviceInfo( + identifiers={("test", "strip_outlet_1")}, parent_device_id=parent.id + ), + ) + assert same_child_device.id == child_device.id + assert same_child_device.name == "Outlet 1"