Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The kodi component."""
2 
3 import logging
4 
5 from pykodi import CannotConnectError, InvalidAuthError, Kodi, get_kodi_connection
6 
7 from homeassistant.config_entries import ConfigEntry
8 from homeassistant.const import (
9  CONF_HOST,
10  CONF_PASSWORD,
11  CONF_PORT,
12  CONF_SSL,
13  CONF_USERNAME,
14  EVENT_HOMEASSISTANT_STOP,
15  Platform,
16 )
17 from homeassistant.core import HomeAssistant
18 from homeassistant.helpers.aiohttp_client import async_get_clientsession
19 
20 from .const import (
21  CONF_WS_PORT,
22  DATA_CONNECTION,
23  DATA_KODI,
24  DATA_REMOVE_LISTENER,
25  DOMAIN,
26 )
27 
28 _LOGGER = logging.getLogger(__name__)
29 PLATFORMS = [Platform.MEDIA_PLAYER]
30 
31 
32 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
33  """Set up Kodi from a config entry."""
34  conn = get_kodi_connection(
35  entry.data[CONF_HOST],
36  entry.data[CONF_PORT],
37  entry.data[CONF_WS_PORT],
38  entry.data[CONF_USERNAME],
39  entry.data[CONF_PASSWORD],
40  entry.data[CONF_SSL],
41  session=async_get_clientsession(hass),
42  )
43 
44  kodi = Kodi(conn)
45 
46  try:
47  await conn.connect()
48  except CannotConnectError:
49  pass
50  except InvalidAuthError as error:
51  _LOGGER.error(
52  "Login to %s failed: [%s]",
53  entry.data[CONF_HOST],
54  error,
55  )
56  return False
57 
58  async def _close(event):
59  await conn.close()
60 
61  remove_stop_listener = hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close)
62 
63  hass.data.setdefault(DOMAIN, {})
64  hass.data[DOMAIN][entry.entry_id] = {
65  DATA_CONNECTION: conn,
66  DATA_KODI: kodi,
67  DATA_REMOVE_LISTENER: remove_stop_listener,
68  }
69 
70  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
71 
72  return True
73 
74 
75 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
76  """Unload a config entry."""
77  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
78  if unload_ok:
79  data = hass.data[DOMAIN].pop(entry.entry_id)
80  await data[DATA_CONNECTION].close()
81  data[DATA_REMOVE_LISTENER]()
82 
83  return unload_ok
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:75
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:32
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)