Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Read Your Meter Pro integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 from pyrympro import CannotConnectError, RymPro, UnauthorizedError
8 
9 from homeassistant.config_entries import ConfigEntry
10 from homeassistant.const import CONF_EMAIL, CONF_PASSWORD, CONF_TOKEN, Platform
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
13 from homeassistant.helpers.aiohttp_client import async_get_clientsession
14 
15 from .const import DOMAIN
16 from .coordinator import RymProDataUpdateCoordinator
17 
18 PLATFORMS: list[Platform] = [Platform.SENSOR]
19 _LOGGER = logging.getLogger(__name__)
20 
21 
22 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
23  """Set up Read Your Meter Pro from a config entry."""
24  data = entry.data
25  rympro = RymPro(async_get_clientsession(hass))
26  rympro.set_token(data[CONF_TOKEN])
27  try:
28  await rympro.account_info()
29  except CannotConnectError as error:
30  raise ConfigEntryNotReady from error
31  except UnauthorizedError:
32  try:
33  token = await rympro.login(data[CONF_EMAIL], data[CONF_PASSWORD], "ha")
34  except UnauthorizedError as error:
35  raise ConfigEntryAuthFailed from error
36  hass.config_entries.async_update_entry(
37  entry,
38  data={**data, CONF_TOKEN: token},
39  )
40 
41  coordinator = RymProDataUpdateCoordinator(hass, rympro)
42  await coordinator.async_config_entry_first_refresh()
43 
44  hass.data.setdefault(DOMAIN, {})
45  hass.data[DOMAIN][entry.entry_id] = coordinator
46 
47  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
48 
49  return True
50 
51 
52 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
53  """Unload a config entry."""
54  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
55  hass.data[DOMAIN].pop(entry.entry_id)
56 
57  return unload_ok
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:22
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:52
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)