Home Assistant Unofficial Reference 2024.12.1
migration.py
Go to the documentation of this file.
1 """Migrate lifx devices to their own config entry."""
2 
3 from __future__ import annotations
4 
5 from homeassistant.config_entries import ConfigEntry
6 from homeassistant.core import HomeAssistant, callback
7 from homeassistant.helpers import device_registry as dr, entity_registry as er
8 
9 from .const import _LOGGER, DOMAIN
10 from .discovery import async_init_discovery_flow
11 
12 
13 @callback
15  hass: HomeAssistant,
16  discovered_hosts_by_serial: dict[str, str],
17  existing_serials: set[str],
18  legacy_entry: ConfigEntry,
19 ) -> int:
20  """Migrate the legacy config entries to have an entry per device."""
21  _LOGGER.debug(
22  "Migrating legacy entries: discovered_hosts_by_serial=%s, existing_serials=%s",
23  discovered_hosts_by_serial,
24  existing_serials,
25  )
26 
27  device_registry = dr.async_get(hass)
28  for dev_entry in dr.async_entries_for_config_entry(
29  device_registry, legacy_entry.entry_id
30  ):
31  for domain, serial in dev_entry.identifiers:
32  if (
33  domain == DOMAIN
34  and serial not in existing_serials
35  and (host := discovered_hosts_by_serial.get(serial))
36  ):
37  async_init_discovery_flow(hass, host, serial)
38 
39  remaining_devices = dr.async_entries_for_config_entry(
40  dr.async_get(hass), legacy_entry.entry_id
41  )
42  _LOGGER.debug("The following devices remain: %s", remaining_devices)
43  return len(remaining_devices)
44 
45 
46 @callback
48  hass: HomeAssistant, legacy_entry_id: str, new_entry: ConfigEntry
49 ) -> None:
50  """Move entities and devices to the new config entry."""
51  migrated_devices = []
52  device_registry = dr.async_get(hass)
53  for dev_entry in dr.async_entries_for_config_entry(
54  device_registry, legacy_entry_id
55  ):
56  for domain, value in dev_entry.identifiers:
57  if domain == DOMAIN and value == new_entry.unique_id:
58  _LOGGER.debug(
59  "Migrating device with %s to %s",
60  dev_entry.identifiers,
61  new_entry.unique_id,
62  )
63  migrated_devices.append(dev_entry.id)
64  device_registry.async_update_device(
65  dev_entry.id,
66  add_config_entry_id=new_entry.entry_id,
67  remove_config_entry_id=legacy_entry_id,
68  )
69 
70  entity_registry = er.async_get(hass)
71  for reg_entity in er.async_entries_for_config_entry(
72  entity_registry, legacy_entry_id
73  ):
74  if reg_entity.device_id in migrated_devices:
75  entity_registry.async_update_entity(
76  reg_entity.entity_id, config_entry_id=new_entry.entry_id
77  )
None async_init_discovery_flow(HomeAssistant hass, str host, str serial)
Definition: discovery.py:41
None async_migrate_entities_devices(HomeAssistant hass, str legacy_entry_id, ConfigEntry new_entry)
Definition: migration.py:49
int async_migrate_legacy_entries(HomeAssistant hass, dict[str, str] discovered_hosts_by_serial, set[str] existing_serials, ConfigEntry legacy_entry)
Definition: migration.py:19