Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Component for the Somfy MyLink device supporting the Synergy API."""
2 
3 import logging
4 
5 from somfy_mylink_synergy import SomfyMyLinkSynergy
6 
7 from homeassistant.config_entries import ConfigEntry
8 from homeassistant.const import CONF_HOST, CONF_PORT
9 from homeassistant.core import HomeAssistant
10 from homeassistant.exceptions import ConfigEntryNotReady
11 
12 from .const import CONF_SYSTEM_ID, DATA_SOMFY_MYLINK, DOMAIN, MYLINK_STATUS, PLATFORMS
13 
14 UNDO_UPDATE_LISTENER = "undo_update_listener"
15 
16 _LOGGER = logging.getLogger(__name__)
17 
18 
19 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
20  """Set up Somfy MyLink from a config entry."""
21  hass.data.setdefault(DOMAIN, {})
22 
23  config = entry.data
24  somfy_mylink = SomfyMyLinkSynergy(
25  config[CONF_SYSTEM_ID], config[CONF_HOST], config[CONF_PORT]
26  )
27 
28  try:
29  mylink_status = await somfy_mylink.status_info()
30  except TimeoutError as ex:
31  raise ConfigEntryNotReady(
32  "Unable to connect to the Somfy MyLink device, please check your settings"
33  ) from ex
34 
35  if not mylink_status or "error" in mylink_status:
36  _LOGGER.error(
37  "Somfy Mylink failed to setup because of an error: %s",
38  mylink_status.get("error", {}).get(
39  "message", "Empty response from mylink device"
40  ),
41  )
42  return False
43 
44  if "result" not in mylink_status:
45  raise ConfigEntryNotReady("The Somfy MyLink device returned an empty result")
46 
47  undo_listener = entry.add_update_listener(_async_update_listener)
48 
49  hass.data[DOMAIN][entry.entry_id] = {
50  DATA_SOMFY_MYLINK: somfy_mylink,
51  MYLINK_STATUS: mylink_status,
52  UNDO_UPDATE_LISTENER: undo_listener,
53  }
54 
55  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
56 
57  return True
58 
59 
60 async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
61  """Handle options update."""
62  await hass.config_entries.async_reload(entry.entry_id)
63 
64 
65 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
66  """Unload a config entry."""
67  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
68 
69  hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENER]()
70 
71  if unload_ok:
72  hass.data[DOMAIN].pop(entry.entry_id)
73 
74  return unload_ok
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88