Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The VLC media player Telnet integration."""
2 
3 from dataclasses import dataclass
4 
5 from aiovlc.client import Client
6 from aiovlc.exceptions import AuthError, ConnectError
7 
9  SCAN_INTERVAL as MEDIAPLAYER_SCAN_INTERVAL,
10 )
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, Platform
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import ConfigEntryAuthFailed
15 
16 from .const import LOGGER
17 
18 PLATFORMS = [Platform.MEDIA_PLAYER]
19 
20 type VlcConfigEntry = ConfigEntry[VlcData]
21 
22 
23 @dataclass
24 class VlcData:
25  """Runtime data definition."""
26 
27  vlc: Client
28  available: bool
29 
30 
31 async def async_setup_entry(hass: HomeAssistant, entry: VlcConfigEntry) -> bool:
32  """Set up VLC media player Telnet from a config entry."""
33  config = entry.data
34 
35  host = config[CONF_HOST]
36  port = config[CONF_PORT]
37  password = config[CONF_PASSWORD]
38 
39  vlc = Client(
40  password=password,
41  host=host,
42  port=port,
43  timeout=int(MEDIAPLAYER_SCAN_INTERVAL.total_seconds() - 1),
44  )
45 
46  available = True
47 
48  try:
49  await vlc.connect()
50  except ConnectError as err:
51  LOGGER.warning("Failed to connect to VLC: %s. Trying again", err)
52  available = False
53 
54  async def _disconnect_vlc() -> None:
55  """Disconnect from VLC."""
56  LOGGER.debug("Disconnecting from VLC")
57  try:
58  await vlc.disconnect()
59  except ConnectError as err:
60  LOGGER.warning("Connection error: %s", err)
61 
62  if available:
63  try:
64  await vlc.login()
65  except AuthError as err:
66  await _disconnect_vlc()
67  raise ConfigEntryAuthFailed from err
68 
69  entry.runtime_data = VlcData(vlc, available)
70 
71  entry.async_on_unload(_disconnect_vlc)
72 
73  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
74 
75  return True
76 
77 
78 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
79  """Unload a config entry."""
80  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
bool async_setup_entry(HomeAssistant hass, VlcConfigEntry entry)
Definition: __init__.py:31
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:78