Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Kaleidescape integration."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 import logging
7 from typing import TYPE_CHECKING
8 
9 from kaleidescape import Device as KaleidescapeDevice, KaleidescapeError
10 
11 from homeassistant.const import CONF_HOST, EVENT_HOMEASSISTANT_STOP, Platform
12 from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
13 
14 from .const import DOMAIN
15 
16 if TYPE_CHECKING:
17  from homeassistant.config_entries import ConfigEntry
18  from homeassistant.core import Event, HomeAssistant
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 PLATFORMS = [Platform.MEDIA_PLAYER, Platform.REMOTE, Platform.SENSOR]
23 
24 
25 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
26  """Set up Kaleidescape from a config entry."""
27  device = KaleidescapeDevice(
28  entry.data[CONF_HOST], timeout=5, reconnect=True, reconnect_delay=5
29  )
30 
31  try:
32  await device.connect()
33  except (KaleidescapeError, ConnectionError) as err:
34  await device.disconnect()
35  raise ConfigEntryNotReady(
36  f"Unable to connect to {entry.data[CONF_HOST]}: {err}"
37  ) from err
38 
39  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = device
40 
41  async def disconnect(event: Event) -> None:
42  await device.disconnect()
43 
44  entry.async_on_unload(
45  hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, disconnect)
46  )
47 
48  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
49 
50  return True
51 
52 
53 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
54  """Unload config entry."""
55  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
56  await hass.data[DOMAIN][entry.entry_id].disconnect()
57  hass.data[DOMAIN].pop(entry.entry_id)
58  return unload_ok
59 
60 
61 @dataclass
63  """Metadata for a Kaleidescape device."""
64 
65  host: str
66  serial: str
67  name: str
68  model: str
69  server_only: bool
70 
71 
73  """Error for unsupported device types."""
74 
75 
76 async def validate_host(host: str) -> KaleidescapeDeviceInfo:
77  """Validate device host."""
78  device = KaleidescapeDevice(host)
79 
80  try:
81  await device.connect()
82  except (KaleidescapeError, ConnectionError):
83  await device.disconnect()
84  raise
85 
86  info = KaleidescapeDeviceInfo(
87  host=device.host,
88  serial=device.system.serial_number,
89  name=device.system.friendly_name,
90  model=device.system.type,
91  server_only=device.is_server_only,
92  )
93 
94  await device.disconnect()
95 
96  return info
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:25
KaleidescapeDeviceInfo validate_host(str host)
Definition: __init__.py:76
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:53