Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Monoprice 6-Zone Amplifier integration."""
2 
3 import logging
4 
5 from pymonoprice import get_monoprice
6 from serial import SerialException
7 
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.const import CONF_PORT, Platform
10 from homeassistant.core import HomeAssistant
11 from homeassistant.exceptions import ConfigEntryNotReady
12 
13 from .const import (
14  CONF_NOT_FIRST_RUN,
15  DOMAIN,
16  FIRST_RUN,
17  MONOPRICE_OBJECT,
18  UNDO_UPDATE_LISTENER,
19 )
20 
21 PLATFORMS = [Platform.MEDIA_PLAYER]
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 
26 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
27  """Set up Monoprice 6-Zone Amplifier from a config entry."""
28  port = entry.data[CONF_PORT]
29 
30  try:
31  monoprice = await hass.async_add_executor_job(get_monoprice, port)
32  except SerialException as err:
33  _LOGGER.error("Error connecting to Monoprice controller at %s", port)
34  raise ConfigEntryNotReady from err
35 
36  # double negative to handle absence of value
37  first_run = not bool(entry.data.get(CONF_NOT_FIRST_RUN))
38 
39  if first_run:
40  hass.config_entries.async_update_entry(
41  entry, data={**entry.data, CONF_NOT_FIRST_RUN: True}
42  )
43 
44  undo_listener = entry.add_update_listener(_update_listener)
45 
46  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
47  MONOPRICE_OBJECT: monoprice,
48  UNDO_UPDATE_LISTENER: undo_listener,
49  FIRST_RUN: first_run,
50  }
51 
52  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
53 
54  return True
55 
56 
57 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
58  """Unload a config entry."""
59  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
60  if not unload_ok:
61  return False
62 
63  hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENER]()
64 
65  def _cleanup(monoprice) -> None:
66  """Destroy the Monoprice object.
67 
68  Destroying the Monoprice closes the serial connection, do it in an executor so the garbage
69  collection does not block.
70  """
71  del monoprice
72 
73  monoprice = hass.data[DOMAIN][entry.entry_id][MONOPRICE_OBJECT]
74  hass.data[DOMAIN].pop(entry.entry_id)
75 
76  await hass.async_add_executor_job(_cleanup, monoprice)
77 
78  return True
79 
80 
81 async def _update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
82  """Handle options update."""
83  await hass.config_entries.async_reload(entry.entry_id)
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:57
None _update_listener(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:81
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:26