Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Anthem A/V Receivers integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import anthemav
8 from anthemav.device_error import DeviceError
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP, Platform
12 from homeassistant.core import Event, HomeAssistant, callback
13 from homeassistant.exceptions import ConfigEntryNotReady
14 from homeassistant.helpers.dispatcher import async_dispatcher_send
15 
16 from .const import ANTHEMAV_UPDATE_SIGNAL, DEVICE_TIMEOUT_SECONDS
17 
18 type AnthemavConfigEntry = ConfigEntry[anthemav.Connection]
19 
20 PLATFORMS = [Platform.MEDIA_PLAYER]
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 
25 async def async_setup_entry(hass: HomeAssistant, entry: AnthemavConfigEntry) -> bool:
26  """Set up Anthem A/V Receivers from a config entry."""
27 
28  @callback
29  def async_anthemav_update_callback(message: str) -> None:
30  """Receive notification from transport that new data exists."""
31  _LOGGER.debug("Received update callback from AVR: %s", message)
32  async_dispatcher_send(hass, f"{ANTHEMAV_UPDATE_SIGNAL}_{entry.entry_id}")
33 
34  try:
35  avr = await anthemav.Connection.create(
36  host=entry.data[CONF_HOST],
37  port=entry.data[CONF_PORT],
38  update_callback=async_anthemav_update_callback,
39  )
40 
41  # Wait for the zones to be initialised based on the model
42  await avr.protocol.wait_for_device_initialised(DEVICE_TIMEOUT_SECONDS)
43  except (OSError, DeviceError) as err:
44  raise ConfigEntryNotReady from err
45 
46  entry.runtime_data = avr
47 
48  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
49 
50  @callback
51  def close_avr(event: Event) -> None:
52  avr.close()
53 
54  entry.async_on_unload(
55  hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, close_avr)
56  )
57 
58  return True
59 
60 
61 async def async_unload_entry(hass: HomeAssistant, entry: AnthemavConfigEntry) -> bool:
62  """Unload a config entry."""
63  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
64 
65  avr = entry.runtime_data
66  _LOGGER.debug("Close avr connection")
67  avr.close()
68 
69  return unload_ok
bool async_unload_entry(HomeAssistant hass, AnthemavConfigEntry entry)
Definition: __init__.py:61
bool async_setup_entry(HomeAssistant hass, AnthemavConfigEntry entry)
Definition: __init__.py:25
None async_dispatcher_send(HomeAssistant hass, str signal, *Any args)
Definition: dispatcher.py:193