Skip to content

Commit 13b717e

Browse files
thecodefrenck
andauthored
Fix shelly remove orphaned entities (home-assistant#154182)
Co-authored-by: Franck Nijhof <[email protected]>
1 parent 5fcfd3a commit 13b717e

File tree

2 files changed

+18
-19
lines changed

2 files changed

+18
-19
lines changed

homeassistant/components/shelly/utils.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -692,27 +692,25 @@ def async_remove_orphaned_entities(
692692
"""Remove orphaned entities."""
693693
orphaned_entities = []
694694
entity_reg = er.async_get(hass)
695-
device_reg = dr.async_get(hass)
696695

697-
if not (
698-
devices := device_reg.devices.get_devices_for_config_entry_id(config_entry_id)
699-
):
700-
return
696+
entities = er.async_entries_for_config_entry(entity_reg, config_entry_id)
697+
for entity in entities:
698+
if not entity.entity_id.startswith(platform):
699+
continue
700+
if key_suffix is not None and key_suffix not in entity.unique_id:
701+
continue
702+
# we are looking for the component ID, e.g. boolean:201, em1data:1
703+
if not (match := COMPONENT_ID_PATTERN.search(entity.unique_id)):
704+
continue
701705

702-
for device in devices:
703-
entities = er.async_entries_for_device(entity_reg, device.id, True)
704-
for entity in entities:
705-
if not entity.entity_id.startswith(platform):
706-
continue
707-
if key_suffix is not None and key_suffix not in entity.unique_id:
708-
continue
709-
# we are looking for the component ID, e.g. boolean:201, em1data:1
710-
if not (match := COMPONENT_ID_PATTERN.search(entity.unique_id)):
711-
continue
712-
713-
key = match.group()
714-
if key not in keys:
715-
orphaned_entities.append(entity.unique_id.split("-", 1)[1])
706+
key = match.group()
707+
if key not in keys:
708+
LOGGER.debug(
709+
"Found orphaned Shelly entity: %s, unique id: %s",
710+
entity.entity_id,
711+
entity.unique_id,
712+
)
713+
orphaned_entities.append(entity.unique_id.split("-", 1)[1])
716714

717715
if orphaned_entities:
718716
async_remove_shelly_rpc_entities(hass, platform, mac, orphaned_entities)

tests/components/shelly/test_sensor.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1088,6 +1088,7 @@ async def test_rpc_device_virtual_text_sensor(
10881088
("text", "text_generic", None),
10891089
],
10901090
)
1091+
@pytest.mark.usefixtures("disable_async_remove_shelly_rpc_entities")
10911092
async def test_migrate_unique_id_virtual_components_roles(
10921093
hass: HomeAssistant,
10931094
mock_rpc_device: Mock,

0 commit comments

Comments
 (0)