Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The zamg component."""
2 
3 from __future__ import annotations
4 
5 from homeassistant.config_entries import ConfigEntry
6 from homeassistant.const import Platform
7 from homeassistant.core import HomeAssistant, callback
8 from homeassistant.helpers import entity_registry as er
9 
10 from .const import CONF_STATION_ID, DOMAIN, LOGGER
11 from .coordinator import ZamgDataUpdateCoordinator
12 
13 PLATFORMS = (Platform.SENSOR, Platform.WEATHER)
14 
15 
16 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
17  """Set up Zamg from config entry."""
18  await _async_migrate_entries(hass, entry)
19 
20  coordinator = ZamgDataUpdateCoordinator(hass, entry=entry)
21  station_id = entry.data[CONF_STATION_ID]
22  coordinator.zamg.set_default_station(station_id)
23  await coordinator.async_config_entry_first_refresh()
24 
25  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
26 
27  # Set up all platforms for this device/entry.
28  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
29 
30  return True
31 
32 
33 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
34  """Unload ZAMG config entry."""
35  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
36  hass.data[DOMAIN].pop(entry.entry_id)
37  return unload_ok
38 
39 
41  hass: HomeAssistant, config_entry: ConfigEntry
42 ) -> bool:
43  """Migrate old entry."""
44  entity_registry = er.async_get(hass)
45 
46  @callback
47  def update_unique_id(entry: er.RegistryEntry) -> dict[str, str] | None:
48  """Convert the unique_id from 'name_stationid' to 'station_id'.
49 
50  Example: 'WIEN/HOHE WARTE_11035' --> '11035'.
51  """
52  if (
53  entry.domain == Platform.WEATHER
54  and entry.unique_id != config_entry.data[CONF_STATION_ID]
55  ):
56  new_unique_id = config_entry.data[CONF_STATION_ID]
57  LOGGER.debug(
58  "Migrating entity '%s' unique_id from '%s' to '%s'",
59  entry.entity_id,
60  entry.unique_id,
61  new_unique_id,
62  )
63  if existing_entity_id := entity_registry.async_get_entity_id(
64  entry.domain, entry.platform, new_unique_id
65  ):
66  LOGGER.debug(
67  "Cannot migrate to unique_id '%s', already exists for '%s'",
68  new_unique_id,
69  existing_entity_id,
70  )
71  return None
72  return {
73  "new_unique_id": new_unique_id,
74  }
75  return None
76 
77  await er.async_migrate_entries(hass, config_entry.entry_id, update_unique_id)
78 
79  return True
dict[str, str]|None update_unique_id(er.RegistryEntry entity_entry, str unique_id)
Definition: __init__.py:168
bool _async_migrate_entries(HomeAssistant hass, ConfigEntry config_entry)
Definition: __init__.py:42
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:16
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:33