Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for the OSO Energy devices and services."""
2 
3 from typing import Any
4 
5 from aiohttp.web_exceptions import HTTPException
6 from apyosoenergyapi import OSOEnergy
7 from apyosoenergyapi.helper.osoenergy_exceptions import OSOEnergyReauthRequired
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_API_KEY, Platform
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
13 from homeassistant.helpers import aiohttp_client
14 
15 from .const import DOMAIN
16 
17 PLATFORMS = [
18  Platform.BINARY_SENSOR,
19  Platform.SENSOR,
20  Platform.WATER_HEATER,
21 ]
22 PLATFORM_LOOKUP = {
23  Platform.BINARY_SENSOR: "binary_sensor",
24  Platform.SENSOR: "sensor",
25  Platform.WATER_HEATER: "water_heater",
26 }
27 
28 
29 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
30  """Set up OSO Energy from a config entry."""
31  subscription_key = entry.data[CONF_API_KEY]
32  websession = aiohttp_client.async_get_clientsession(hass)
33  osoenergy = OSOEnergy(subscription_key, websession)
34 
35  osoenergy_config = dict(entry.data)
36 
37  hass.data.setdefault(DOMAIN, {})
38 
39  try:
40  devices: Any = await osoenergy.session.start_session(osoenergy_config)
41  except HTTPException as error:
42  raise ConfigEntryNotReady from error
43  except OSOEnergyReauthRequired as err:
44  raise ConfigEntryAuthFailed from err
45 
46  hass.data[DOMAIN][entry.entry_id] = osoenergy
47 
48  platforms = set()
49  for ha_type, oso_type in PLATFORM_LOOKUP.items():
50  device_list = devices.get(oso_type, [])
51  if device_list:
52  platforms.add(ha_type)
53  if platforms:
54  await hass.config_entries.async_forward_entry_setups(entry, platforms)
55  return True
56 
57 
58 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
59  """Unload a config entry."""
60  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
61  if unload_ok:
62  hass.data[DOMAIN].pop(entry.entry_id)
63 
64  return unload_ok
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:58
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:29