Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The nVent RAYCHEM SENZ integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 from aiosenz import SENZAPI, Thermostat
9 from httpx import RequestError
10 
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import Platform
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import ConfigEntryNotReady
15 from homeassistant.helpers import (
16  config_entry_oauth2_flow,
17  config_validation as cv,
18  httpx_client,
19 )
20 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
21 
22 from .api import SENZConfigEntryAuth
23 from .const import DOMAIN
24 
25 UPDATE_INTERVAL = timedelta(seconds=30)
26 
27 _LOGGER = logging.getLogger(__name__)
28 
29 CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
30 
31 PLATFORMS = [Platform.CLIMATE]
32 
33 type SENZDataUpdateCoordinator = DataUpdateCoordinator[dict[str, Thermostat]]
34 
35 
36 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
37  """Set up SENZ from a config entry."""
38  implementation = (
39  await config_entry_oauth2_flow.async_get_config_entry_implementation(
40  hass, entry
41  )
42  )
43  session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
44  auth = SENZConfigEntryAuth(httpx_client.get_async_client(hass), session)
45  senz_api = SENZAPI(auth)
46 
47  async def update_thermostats() -> dict[str, Thermostat]:
48  """Fetch SENZ thermostats data."""
49  try:
50  thermostats = await senz_api.get_thermostats()
51  except RequestError as err:
52  raise UpdateFailed from err
53  return {thermostat.serial_number: thermostat for thermostat in thermostats}
54 
55  try:
56  account = await senz_api.get_account()
57  except RequestError as err:
58  raise ConfigEntryNotReady from err
59 
60  coordinator: SENZDataUpdateCoordinator = DataUpdateCoordinator(
61  hass,
62  _LOGGER,
63  config_entry=entry,
64  name=account.username,
65  update_interval=UPDATE_INTERVAL,
66  update_method=update_thermostats,
67  )
68 
69  await coordinator.async_config_entry_first_refresh()
70 
71  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
72 
73  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
74 
75  return True
76 
77 
78 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
79  """Unload a config entry."""
80  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
81  hass.data[DOMAIN].pop(entry.entry_id)
82 
83  return unload_ok
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:78
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:36