Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Govee light local."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from contextlib import suppress
7 import logging
8 
9 from govee_local_api import GoveeController
10 
11 from homeassistant.components import network
12 from homeassistant.core import HomeAssistant
13 from homeassistant.helpers import config_entry_flow
14 
15 from .const import (
16  CONF_LISTENING_PORT_DEFAULT,
17  CONF_MULTICAST_ADDRESS_DEFAULT,
18  CONF_TARGET_PORT_DEFAULT,
19  DISCOVERY_TIMEOUT,
20  DOMAIN,
21 )
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 
26 async def _async_has_devices(hass: HomeAssistant) -> bool:
27  """Return if there are devices that can be discovered."""
28 
29  adapter = await network.async_get_source_ip(hass, network.PUBLIC_TARGET_IP)
30 
31  controller: GoveeController = GoveeController(
32  loop=hass.loop,
33  logger=_LOGGER,
34  listening_address=adapter,
35  broadcast_address=CONF_MULTICAST_ADDRESS_DEFAULT,
36  broadcast_port=CONF_TARGET_PORT_DEFAULT,
37  listening_port=CONF_LISTENING_PORT_DEFAULT,
38  discovery_enabled=True,
39  discovery_interval=1,
40  update_enabled=False,
41  )
42 
43  try:
44  await controller.start()
45  except OSError as ex:
46  _LOGGER.error("Start failed, errno: %d", ex.errno)
47  return False
48 
49  try:
50  async with asyncio.timeout(delay=DISCOVERY_TIMEOUT):
51  while not controller.devices:
52  await asyncio.sleep(delay=1)
53  except TimeoutError:
54  _LOGGER.debug("No devices found")
55 
56  devices_count = len(controller.devices)
57  cleanup_complete: asyncio.Event = controller.cleanup()
58  with suppress(TimeoutError):
59  await asyncio.wait_for(cleanup_complete.wait(), 1)
60 
61  return devices_count > 0
62 
63 
64 config_entry_flow.register_discovery_flow(
65  DOMAIN, "Govee light local", _async_has_devices
66 )