Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for OVO Energy."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from datetime import timedelta
7 import logging
8 
9 import aiohttp
10 from ovoenergy import OVOEnergy
11 from ovoenergy.models import OVODailyUsage
12 
13 from homeassistant.config_entries import ConfigEntry
14 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform
15 from homeassistant.core import HomeAssistant
16 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
19 from homeassistant.util import dt as dt_util
20 
21 from .const import CONF_ACCOUNT, DATA_CLIENT, DATA_COORDINATOR, DOMAIN
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 PLATFORMS = [Platform.SENSOR]
26 
27 
28 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
29  """Set up OVO Energy from a config entry."""
30 
31  client = OVOEnergy(
32  client_session=async_get_clientsession(hass),
33  )
34 
35  if (custom_account := entry.data.get(CONF_ACCOUNT)) is not None:
36  client.custom_account_id = custom_account
37 
38  try:
39  if not await client.authenticate(
40  entry.data[CONF_USERNAME],
41  entry.data[CONF_PASSWORD],
42  ):
43  raise ConfigEntryAuthFailed
44 
45  await client.bootstrap_accounts()
46  except aiohttp.ClientError as exception:
47  _LOGGER.warning(exception)
48  raise ConfigEntryNotReady from exception
49 
50  async def async_update_data() -> OVODailyUsage:
51  """Fetch data from OVO Energy."""
52  if (custom_account := entry.data.get(CONF_ACCOUNT)) is not None:
53  client.custom_account_id = custom_account
54 
55  async with asyncio.timeout(10):
56  try:
57  authenticated = await client.authenticate(
58  entry.data[CONF_USERNAME],
59  entry.data[CONF_PASSWORD],
60  )
61  except aiohttp.ClientError as exception:
62  raise UpdateFailed(exception) from exception
63  if not authenticated:
64  raise ConfigEntryAuthFailed("Not authenticated with OVO Energy")
65  return await client.get_daily_usage(dt_util.utcnow().strftime("%Y-%m"))
66 
67  coordinator = DataUpdateCoordinator[OVODailyUsage](
68  hass,
69  _LOGGER,
70  config_entry=entry,
71  # Name of the data. For logging purposes.
72  name="sensor",
73  update_method=async_update_data,
74  # Polling interval. Will only be polled if there are subscribers.
75  update_interval=timedelta(seconds=3600),
76  )
77 
78  hass.data.setdefault(DOMAIN, {})
79  hass.data[DOMAIN][entry.entry_id] = {
80  DATA_CLIENT: client,
81  DATA_COORDINATOR: coordinator,
82  }
83 
84  # Fetch initial data so we have data when entities subscribe
85  await coordinator.async_config_entry_first_refresh()
86 
87  # Setup components
88  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
89 
90  return True
91 
92 
93 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
94  """Unload OVO Energy config entry."""
95  # Unload sensors
96  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
97 
98  del hass.data[DOMAIN][entry.entry_id]
99 
100  return unload_ok
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:93
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:28
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)