Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Arcam component."""
2 
3 import asyncio
4 from asyncio import timeout
5 import logging
6 from typing import Any
7 
8 from arcam.fmj import ConnectionFailed
9 from arcam.fmj.client import Client
10 
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import CONF_HOST, CONF_PORT, Platform
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.dispatcher import async_dispatcher_send
15 
16 from .const import (
17  DEFAULT_SCAN_INTERVAL,
18  SIGNAL_CLIENT_DATA,
19  SIGNAL_CLIENT_STARTED,
20  SIGNAL_CLIENT_STOPPED,
21 )
22 
23 type ArcamFmjConfigEntry = ConfigEntry[Client]
24 
25 _LOGGER = logging.getLogger(__name__)
26 
27 
28 PLATFORMS = [Platform.MEDIA_PLAYER]
29 
30 
31 async def async_setup_entry(hass: HomeAssistant, entry: ArcamFmjConfigEntry) -> bool:
32  """Set up config entry."""
33  entry.runtime_data = Client(entry.data[CONF_HOST], entry.data[CONF_PORT])
34 
35  entry.async_create_background_task(
36  hass, _run_client(hass, entry.runtime_data, DEFAULT_SCAN_INTERVAL), "arcam_fmj"
37  )
38 
39  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
40  return True
41 
42 
43 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
44  """Cleanup before removing config entry."""
45  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
46 
47 
48 async def _run_client(hass: HomeAssistant, client: Client, interval: float) -> None:
49  def _listen(_: Any) -> None:
50  async_dispatcher_send(hass, SIGNAL_CLIENT_DATA, client.host)
51 
52  while True:
53  try:
54  async with timeout(interval):
55  await client.start()
56 
57  _LOGGER.debug("Client connected %s", client.host)
58  async_dispatcher_send(hass, SIGNAL_CLIENT_STARTED, client.host)
59 
60  try:
61  with client.listen(_listen):
62  await client.process()
63  finally:
64  await client.stop()
65 
66  _LOGGER.debug("Client disconnected %s", client.host)
67  async_dispatcher_send(hass, SIGNAL_CLIENT_STOPPED, client.host)
68 
69  except ConnectionFailed:
70  await asyncio.sleep(interval)
71  except TimeoutError:
72  continue
73  except Exception:
74  _LOGGER.exception("Unexpected exception, aborting arcam client")
75  return
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:43
None _run_client(HomeAssistant hass, Client client, float interval)
Definition: __init__.py:48
bool async_setup_entry(HomeAssistant hass, ArcamFmjConfigEntry entry)
Definition: __init__.py:31
None async_dispatcher_send(HomeAssistant hass, str signal, *Any args)
Definition: dispatcher.py:193