Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The russound_rio component."""
2 
3 import asyncio
4 import logging
5 
6 from aiorussound import RussoundClient, RussoundTcpConnectionHandler
7 from aiorussound.models import CallbackType
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_HOST, CONF_PORT, Platform
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import ConfigEntryNotReady
13 
14 from .const import CONNECT_TIMEOUT, DOMAIN, RUSSOUND_RIO_EXCEPTIONS
15 
16 PLATFORMS = [Platform.MEDIA_PLAYER]
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 type RussoundConfigEntry = ConfigEntry[RussoundClient]
21 
22 
23 async def async_setup_entry(hass: HomeAssistant, entry: RussoundConfigEntry) -> bool:
24  """Set up a config entry."""
25 
26  host = entry.data[CONF_HOST]
27  port = entry.data[CONF_PORT]
28  client = RussoundClient(RussoundTcpConnectionHandler(host, port))
29 
30  async def _connection_update_callback(
31  _client: RussoundClient, _callback_type: CallbackType
32  ) -> None:
33  """Call when the device is notified of changes."""
34  if _callback_type == CallbackType.CONNECTION:
35  if _client.is_connected():
36  _LOGGER.warning("Reconnected to device at %s", entry.data[CONF_HOST])
37  else:
38  _LOGGER.warning("Disconnected from device at %s", entry.data[CONF_HOST])
39 
40  await client.register_state_update_callbacks(_connection_update_callback)
41 
42  try:
43  async with asyncio.timeout(CONNECT_TIMEOUT):
44  await client.connect()
45  except RUSSOUND_RIO_EXCEPTIONS as err:
46  raise ConfigEntryNotReady(
47  translation_domain=DOMAIN,
48  translation_key="entry_cannot_connect",
49  translation_placeholders={
50  "host": host,
51  "port": port,
52  },
53  ) from err
54  entry.runtime_data = client
55 
56  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
57 
58  return True
59 
60 
61 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
62  """Unload a config entry."""
63  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
64  await entry.runtime_data.disconnect()
65 
66  return unload_ok
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:61
bool async_setup_entry(HomeAssistant hass, RussoundConfigEntry entry)
Definition: __init__.py:23