Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Aprilaire integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 from pyaprilaire.const import Attribute
8 
9 from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP, Platform
10 from homeassistant.core import Event, HomeAssistant
11 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
12 from homeassistant.helpers.device_registry import format_mac
13 
14 from .coordinator import AprilaireConfigEntry, AprilaireCoordinator
15 
16 PLATFORMS: list[Platform] = [
17  Platform.CLIMATE,
18  Platform.HUMIDIFIER,
19  Platform.SELECT,
20  Platform.SENSOR,
21 ]
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 
26 async def async_setup_entry(hass: HomeAssistant, entry: AprilaireConfigEntry) -> bool:
27  """Set up a config entry for Aprilaire."""
28 
29  host = entry.data[CONF_HOST]
30  port = entry.data[CONF_PORT]
31 
32  coordinator = AprilaireCoordinator(hass, entry.unique_id, host, port)
33  await coordinator.start_listen()
34 
35  async def ready_callback(ready: bool) -> None:
36  if ready:
37  mac_address = format_mac(coordinator.data[Attribute.MAC_ADDRESS])
38 
39  if mac_address != entry.unique_id:
40  raise ConfigEntryAuthFailed("Invalid MAC address")
41 
42  entry.runtime_data = coordinator
43  entry.async_on_unload(coordinator.stop_listen)
44 
45  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
46 
47  async def _async_close(_: Event) -> None:
48  coordinator.stop_listen()
49 
50  entry.async_on_unload(
51  hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_close)
52  )
53  else:
54  _LOGGER.error("Failed to wait for ready")
55 
56  coordinator.stop_listen()
57 
58  raise ConfigEntryNotReady
59 
60  await coordinator.wait_for_ready(ready_callback)
61 
62  return True
63 
64 
65 async def async_unload_entry(hass: HomeAssistant, entry: AprilaireConfigEntry) -> bool:
66  """Unload a config entry."""
67  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
bool async_unload_entry(HomeAssistant hass, AprilaireConfigEntry entry)
Definition: __init__.py:65
bool async_setup_entry(HomeAssistant hass, AprilaireConfigEntry entry)
Definition: __init__.py:26