Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The chacon_dio integration."""
2 
3 from dataclasses import dataclass
4 import logging
5 from typing import Any
6 
7 from dio_chacon_wifi_api import DIOChaconAPIClient
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import (
11  CONF_PASSWORD,
12  CONF_USERNAME,
13  EVENT_HOMEASSISTANT_STOP,
14  Platform,
15 )
16 from homeassistant.core import Event, HomeAssistant
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 PLATFORMS: list[Platform] = [Platform.COVER, Platform.SWITCH]
21 
22 
23 @dataclass
25  """Chacon Dio data class."""
26 
27  client: DIOChaconAPIClient
28  list_devices: list[dict[str, Any]]
29 
30 
31 type ChaconDioConfigEntry = ConfigEntry[ChaconDioData]
32 
33 
34 async def async_setup_entry(hass: HomeAssistant, entry: ChaconDioConfigEntry) -> bool:
35  """Set up chacon_dio from a config entry."""
36 
37  config = entry.data
38 
39  username = config[CONF_USERNAME]
40  password = config[CONF_PASSWORD]
41  dio_chacon_id = entry.unique_id
42 
43  _LOGGER.debug("Initializing Chacon Dio client %s, %s", username, dio_chacon_id)
44  client = DIOChaconAPIClient(
45  username,
46  password,
47  dio_chacon_id,
48  )
49 
50  found_devices = await client.search_all_devices(with_state=True)
51  list_devices = list(found_devices.values())
52  _LOGGER.debug("List of devices %s", list_devices)
53 
54  entry.runtime_data = ChaconDioData(
55  client=client,
56  list_devices=list_devices,
57  )
58 
59  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
60 
61  # Disconnect the permanent websocket connection of home assistant on shutdown
62  async def _async_disconnect_websocket(_: Event) -> None:
63  await client.disconnect()
64 
65  entry.async_on_unload(
66  hass.bus.async_listen_once(
67  EVENT_HOMEASSISTANT_STOP, _async_disconnect_websocket
68  )
69  )
70 
71  return True
72 
73 
74 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
75  """Unload a config entry."""
76 
77  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
78  await entry.runtime_data.client.disconnect()
79 
80  return unload_ok
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:74
bool async_setup_entry(HomeAssistant hass, ChaconDioConfigEntry entry)
Definition: __init__.py:34