Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for HLK-SW16 relay switches."""
2 
3 import logging
4 
5 from hlk_sw16 import create_hlk_sw16_connection
6 import voluptuous as vol
7 
8 from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
9 from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_SWITCHES, Platform
10 from homeassistant.core import HomeAssistant, callback
12 from homeassistant.helpers.dispatcher import async_dispatcher_send
13 from homeassistant.helpers.typing import ConfigType
14 
15 from .const import (
16  CONNECTION_TIMEOUT,
17  DEFAULT_KEEP_ALIVE_INTERVAL,
18  DEFAULT_PORT,
19  DEFAULT_RECONNECT_INTERVAL,
20  DOMAIN,
21 )
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 PLATFORMS = [Platform.SWITCH]
26 
27 DATA_DEVICE_REGISTER = "hlk_sw16_device_register"
28 DATA_DEVICE_LISTENER = "hlk_sw16_device_listener"
29 
30 SWITCH_SCHEMA = vol.Schema({vol.Optional(CONF_NAME): cv.string})
31 
32 RELAY_ID = vol.All(
33  vol.Any(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"), vol.Coerce(str)
34 )
35 
36 CONFIG_SCHEMA = vol.Schema(
37  {
38  DOMAIN: vol.Schema(
39  {
40  cv.string: vol.Schema(
41  {
42  vol.Required(CONF_HOST): cv.string,
43  vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
44  vol.Required(CONF_SWITCHES): vol.Schema(
45  {RELAY_ID: SWITCH_SCHEMA}
46  ),
47  }
48  )
49  }
50  )
51  },
52  extra=vol.ALLOW_EXTRA,
53 )
54 
55 
56 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
57  """Component setup, do nothing."""
58  if DOMAIN not in config:
59  return True
60 
61  for device_id in config[DOMAIN]:
62  conf = config[DOMAIN][device_id]
63  hass.async_create_task(
64  hass.config_entries.flow.async_init(
65  DOMAIN,
66  context={"source": SOURCE_IMPORT},
67  data={CONF_HOST: conf[CONF_HOST], CONF_PORT: conf[CONF_PORT]},
68  )
69  )
70  return True
71 
72 
73 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
74  """Set up the HLK-SW16 switch."""
75  hass.data.setdefault(DOMAIN, {})
76  host = entry.data[CONF_HOST]
77  port = entry.data[CONF_PORT]
78  address = f"{host}:{port}"
79 
80  hass.data[DOMAIN][entry.entry_id] = {}
81 
82  @callback
83  def disconnected():
84  """Schedule reconnect after connection has been lost."""
85  _LOGGER.warning("HLK-SW16 %s disconnected", address)
87  hass, f"hlk_sw16_device_available_{entry.entry_id}", False
88  )
89 
90  @callback
91  def reconnected():
92  """Schedule reconnect after connection has been lost."""
93  _LOGGER.warning("HLK-SW16 %s connected", address)
94  async_dispatcher_send(hass, f"hlk_sw16_device_available_{entry.entry_id}", True)
95 
96  _LOGGER.debug("Initiating HLK-SW16 connection to %s", address)
97 
98  client = await create_hlk_sw16_connection(
99  host=host,
100  port=port,
101  disconnect_callback=disconnected,
102  reconnect_callback=reconnected,
103  loop=hass.loop,
104  timeout=CONNECTION_TIMEOUT,
105  reconnect_interval=DEFAULT_RECONNECT_INTERVAL,
106  keep_alive_interval=DEFAULT_KEEP_ALIVE_INTERVAL,
107  )
108 
109  hass.data[DOMAIN][entry.entry_id][DATA_DEVICE_REGISTER] = client
110 
111  # Load entities
112  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
113 
114  _LOGGER.debug("Connected to HLK-SW16 device: %s", address)
115 
116  return True
117 
118 
119 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
120  """Unload a config entry."""
121  client = hass.data[DOMAIN][entry.entry_id].pop(DATA_DEVICE_REGISTER)
122  client.stop()
123  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
124  if unload_ok:
125  if hass.data[DOMAIN][entry.entry_id]:
126  hass.data[DOMAIN].pop(entry.entry_id)
127  if not hass.data[DOMAIN]:
128  hass.data.pop(DOMAIN)
129  return unload_ok
bool async_setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:56
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:73
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:119
None async_dispatcher_send(HomeAssistant hass, str signal, *Any args)
Definition: dispatcher.py:193