Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Electric Kiwi integration."""
2 
3 from __future__ import annotations
4 
5 import aiohttp
6 from electrickiwi_api import ElectricKiwiApi
7 from electrickiwi_api.exceptions import ApiException
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import Platform
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
13 from homeassistant.helpers import aiohttp_client, config_entry_oauth2_flow
14 
15 from . import api
16 from .const import ACCOUNT_COORDINATOR, DOMAIN, HOP_COORDINATOR
17 from .coordinator import (
18  ElectricKiwiAccountDataCoordinator,
19  ElectricKiwiHOPDataCoordinator,
20 )
21 
22 PLATFORMS: list[Platform] = [Platform.SELECT, Platform.SENSOR]
23 
24 
25 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
26  """Set up Electric Kiwi from a config entry."""
27  implementation = (
28  await config_entry_oauth2_flow.async_get_config_entry_implementation(
29  hass, entry
30  )
31  )
32 
33  session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
34 
35  try:
36  await session.async_ensure_token_valid()
37  except aiohttp.ClientResponseError as err:
38  if 400 <= err.status < 500:
39  raise ConfigEntryAuthFailed(err) from err
40  raise ConfigEntryNotReady from err
41  except aiohttp.ClientError as err:
42  raise ConfigEntryNotReady from err
43 
44  ek_api = ElectricKiwiApi(
45  api.AsyncConfigEntryAuth(aiohttp_client.async_get_clientsession(hass), session)
46  )
47  hop_coordinator = ElectricKiwiHOPDataCoordinator(hass, ek_api)
48  account_coordinator = ElectricKiwiAccountDataCoordinator(hass, ek_api)
49 
50  try:
51  await ek_api.set_active_session()
52  await hop_coordinator.async_config_entry_first_refresh()
53  await account_coordinator.async_config_entry_first_refresh()
54  except ApiException as err:
55  raise ConfigEntryNotReady from err
56 
57  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
58  HOP_COORDINATOR: hop_coordinator,
59  ACCOUNT_COORDINATOR: account_coordinator,
60  }
61 
62  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
63 
64  return True
65 
66 
67 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
68  """Unload a config entry."""
69  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
70  hass.data[DOMAIN].pop(entry.entry_id)
71 
72  return unload_ok
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:25
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:67