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