Home Assistant Unofficial Reference 2024.12.1
parent_device.py
Go to the documentation of this file.
1 """The WiLight Device integration."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 import logging
7 
8 import pywilight
9 from pywilight.wilight_device import PyWiLightDevice
10 import requests
11 
12 from homeassistant.config_entries import ConfigEntry
13 from homeassistant.const import CONF_HOST, EVENT_HOMEASSISTANT_STOP
14 from homeassistant.core import HomeAssistant, callback
15 from homeassistant.helpers.dispatcher import async_dispatcher_send
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
21  """Manages a single WiLight Parent Device."""
22 
23  def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
24  """Initialize the system."""
25  self._host: str = config_entry.data[CONF_HOST]
26  self._hass_hass = hass
27  self._api_api: PyWiLightDevice | None = None
28 
29  @property
30  def host(self) -> str:
31  """Return the host of this parent."""
32  return self._host
33 
34  @property
35  def api(self) -> PyWiLightDevice | None:
36  """Return the api of this parent."""
37  return self._api_api
38 
39  async def async_setup(self) -> bool:
40  """Set up a WiLight Parent Device based on host parameter."""
41  host = self._host
42  hass = self._hass_hass
43 
44  api_device = await hass.async_add_executor_job(create_api_device, host)
45 
46  if api_device is None:
47  return False
48 
49  @callback
50  def disconnected() -> None:
51  # Schedule reconnect after connection has been lost.
52  _LOGGER.warning("WiLight %s disconnected", api_device.device_id)
54  hass, f"wilight_device_available_{api_device.device_id}", False
55  )
56 
57  @callback
58  def reconnected() -> None:
59  # Schedule reconnect after connection has been lost.
60  _LOGGER.warning("WiLight %s reconnect", api_device.device_id)
62  hass, f"wilight_device_available_{api_device.device_id}", True
63  )
64 
65  async def connect(api_device: PyWiLightDevice) -> None:
66  # Set up connection and hook it into HA for reconnect/shutdown.
67  _LOGGER.debug("Initiating connection to %s", api_device.device_id)
68 
69  client = await api_device.config_client(
70  disconnect_callback=disconnected,
71  reconnect_callback=reconnected,
72  loop=asyncio.get_running_loop(),
73  logger=_LOGGER,
74  )
75 
76  # handle shutdown of WiLight asyncio transport
77  hass.bus.async_listen_once(
78  EVENT_HOMEASSISTANT_STOP, lambda x: client.stop()
79  )
80 
81  _LOGGER.debug("Connected to WiLight device: %s", api_device.device_id)
82 
83  await connect(api_device)
84 
85  self._api_api = api_device
86 
87  return True
88 
89  async def async_reset(self) -> None:
90  """Reset api."""
91 
92  # If the initialization was not wrong.
93  if self._api_api is not None:
94  self._api_api.client.stop()
95 
96 
97 def create_api_device(host: str) -> PyWiLightDevice:
98  """Create an API Device."""
99  try:
100  return pywilight.device_from_host(host)
101  except (
102  requests.exceptions.ConnectionError,
103  requests.exceptions.Timeout,
104  ) as err:
105  _LOGGER.error("Unable to access WiLight at %s (%s)", host, err)
106  return None
None __init__(self, HomeAssistant hass, ConfigEntry config_entry)
None async_dispatcher_send(HomeAssistant hass, str signal, *Any args)
Definition: dispatcher.py:193