Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support the UPB PIM."""
2 
3 import logging
4 
5 import upb_lib
6 
7 from homeassistant.config_entries import ConfigEntry
8 from homeassistant.const import ATTR_COMMAND, CONF_FILE_PATH, CONF_HOST, Platform
9 from homeassistant.core import HomeAssistant
10 
11 from .const import (
12  ATTR_ADDRESS,
13  ATTR_BRIGHTNESS_PCT,
14  ATTR_RATE,
15  DOMAIN,
16  EVENT_UPB_SCENE_CHANGED,
17 )
18 
19 _LOGGER = logging.getLogger(__name__)
20 PLATFORMS = [Platform.LIGHT, Platform.SCENE]
21 
22 
23 async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
24  """Set up a new config_entry for UPB PIM."""
25 
26  url = config_entry.data[CONF_HOST]
27  file = config_entry.data[CONF_FILE_PATH]
28 
29  upb = upb_lib.UpbPim({"url": url, "UPStartExportFile": file})
30  await upb.async_connect()
31  hass.data.setdefault(DOMAIN, {})
32  hass.data[DOMAIN][config_entry.entry_id] = {"upb": upb}
33 
34  await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
35 
36  def _element_changed(element, changeset):
37  if (change := changeset.get("last_change")) is None:
38  return
39  if change.get("command") is None:
40  return
41 
42  hass.bus.async_fire(
43  EVENT_UPB_SCENE_CHANGED,
44  {
45  ATTR_COMMAND: change["command"],
46  ATTR_ADDRESS: element.addr.index,
47  ATTR_BRIGHTNESS_PCT: change.get("level", -1),
48  ATTR_RATE: change.get("rate", -1),
49  },
50  )
51 
52  for link in upb.links:
53  element = upb.links[link]
54  element.add_callback(_element_changed)
55 
56  return True
57 
58 
59 async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
60  """Unload the config_entry."""
61  unload_ok = await hass.config_entries.async_unload_platforms(
62  config_entry, PLATFORMS
63  )
64  if unload_ok:
65  upb = hass.data[DOMAIN][config_entry.entry_id]["upb"]
66  upb.disconnect()
67  hass.data[DOMAIN].pop(config_entry.entry_id)
68  return unload_ok
69 
70 
71 async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
72  """Migrate entry."""
73 
74  _LOGGER.debug("Migrating from version %s", entry.version)
75 
76  if entry.version == 1:
77  # 1 -> 2: Unique ID from integer to string
78  if entry.minor_version == 1:
79  minor_version = 2
80  hass.config_entries.async_update_entry(
81  entry, unique_id=str(entry.unique_id), minor_version=minor_version
82  )
83 
84  _LOGGER.debug("Migration successful")
85 
86  return True
bool async_migrate_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:71
bool async_unload_entry(HomeAssistant hass, ConfigEntry config_entry)
Definition: __init__.py:59
bool async_setup_entry(HomeAssistant hass, ConfigEntry config_entry)
Definition: __init__.py:23