Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The madvr-envy integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 from madvr.madvr import Madvr
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP, Platform
11 from homeassistant.core import Event, HomeAssistant
12 
13 from .coordinator import MadVRCoordinator
14 
15 PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR, Platform.REMOTE, Platform.SENSOR]
16 
17 
18 type MadVRConfigEntry = ConfigEntry[MadVRCoordinator]
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
23 async def async_handle_unload(coordinator: MadVRCoordinator) -> None:
24  """Handle unload."""
25  _LOGGER.debug("Integration unloading")
26  coordinator.client.stop()
27  await coordinator.client.async_cancel_tasks()
28  _LOGGER.debug("Integration closing connection")
29  await coordinator.client.close_connection()
30  _LOGGER.debug("Unloaded")
31 
32 
33 async def async_setup_entry(hass: HomeAssistant, entry: MadVRConfigEntry) -> bool:
34  """Set up the integration from a config entry."""
35  assert entry.unique_id
36  madVRClient = Madvr(
37  host=entry.data[CONF_HOST],
38  logger=_LOGGER,
39  port=entry.data[CONF_PORT],
40  mac=entry.unique_id,
41  connect_timeout=10,
42  loop=hass.loop,
43  )
44  coordinator = MadVRCoordinator(hass, madVRClient)
45 
46  entry.runtime_data = coordinator
47 
48  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
49 
50  async def handle_unload(event: Event) -> None:
51  """Handle unload."""
52  await async_handle_unload(coordinator=coordinator)
53 
54  # listen for core stop event
55  hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, handle_unload)
56 
57  # handle loading operations
58  await coordinator.handle_coordinator_load()
59  return True
60 
61 
62 async def async_unload_entry(hass: HomeAssistant, entry: MadVRConfigEntry) -> bool:
63  """Unload a config entry."""
64  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
65  if unload_ok:
66  coordinator: MadVRCoordinator = entry.runtime_data
67  await async_handle_unload(coordinator=coordinator)
68 
69  return unload_ok
bool async_setup_entry(HomeAssistant hass, MadVRConfigEntry entry)
Definition: __init__.py:33
None async_handle_unload(MadVRCoordinator coordinator)
Definition: __init__.py:23
bool async_unload_entry(HomeAssistant hass, MadVRConfigEntry entry)
Definition: __init__.py:62