Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Meater Temperature Probe integration."""
2 
3 import asyncio
4 from datetime import timedelta
5 import logging
6 
7 from meater import (
8  AuthenticationError,
9  MeaterApi,
10  ServiceUnavailableError,
11  TooManyRequestsError,
12 )
13 from meater.MeaterApi import MeaterProbe
14 
15 from homeassistant.config_entries import ConfigEntry
16 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform
17 from homeassistant.core import HomeAssistant
18 from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
19 from homeassistant.helpers.aiohttp_client import async_get_clientsession
20 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
21 
22 from .const import DOMAIN
23 
24 PLATFORMS = [Platform.SENSOR]
25 
26 _LOGGER = logging.getLogger(__name__)
27 
28 
29 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
30  """Set up Meater Temperature Probe from a config entry."""
31  # Store an API object to access
32  session = async_get_clientsession(hass)
33  meater_api = MeaterApi(session)
34 
35  # Add the credentials
36  try:
37  _LOGGER.debug("Authenticating with the Meater API")
38  await meater_api.authenticate(
39  entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD]
40  )
41  except (ServiceUnavailableError, TooManyRequestsError) as err:
42  raise ConfigEntryNotReady from err
43  except AuthenticationError as err:
45  f"Unable to authenticate with the Meater API: {err}"
46  ) from err
47 
48  async def async_update_data() -> dict[str, MeaterProbe]:
49  """Fetch data from API endpoint."""
50  try:
51  # Note: TimeoutError and aiohttp.ClientError are already
52  # handled by the data update coordinator.
53  async with asyncio.timeout(10):
54  devices: list[MeaterProbe] = await meater_api.get_all_devices()
55  except AuthenticationError as err:
56  raise ConfigEntryAuthFailed("The API call wasn't authenticated") from err
57  except TooManyRequestsError as err:
58  raise UpdateFailed(
59  "Too many requests have been made to the API, rate limiting is in place"
60  ) from err
61 
62  return {device.id: device for device in devices}
63 
64  coordinator = DataUpdateCoordinator(
65  hass,
66  _LOGGER,
67  config_entry=entry,
68  # Name of the data. For logging purposes.
69  name="meater_api",
70  update_method=async_update_data,
71  # Polling interval. Will only be polled if there are subscribers.
72  update_interval=timedelta(seconds=30),
73  )
74  await coordinator.async_config_entry_first_refresh()
75 
76  hass.data.setdefault(DOMAIN, {})
77  hass.data[DOMAIN].setdefault("known_probes", set())
78 
79  hass.data[DOMAIN][entry.entry_id] = {
80  "api": meater_api,
81  "coordinator": coordinator,
82  }
83 
84  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
85  return True
86 
87 
88 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
89  """Unload a config entry."""
90  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
91  hass.data[DOMAIN].pop(entry.entry_id)
92 
93  return unload_ok
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:88
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:29
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)