Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """Utils for Sensibo integration."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 
7 from pysensibo import SensiboClient
8 from pysensibo.exceptions import AuthenticationError
9 
10 from homeassistant.core import HomeAssistant
11 from homeassistant.helpers.aiohttp_client import async_get_clientsession
12 
13 from .const import LOGGER, SENSIBO_ERRORS, TIMEOUT
14 
15 
16 async def async_validate_api(hass: HomeAssistant, api_key: str) -> str:
17  """Validate the api and return username."""
18  client = SensiboClient(
19  api_key,
20  session=async_get_clientsession(hass),
21  timeout=TIMEOUT,
22  )
23 
24  try:
25  async with asyncio.timeout(TIMEOUT):
26  device_query = await client.async_get_devices()
27  user_query = await client.async_get_me()
28  except AuthenticationError as err:
29  LOGGER.error("Could not authenticate on Sensibo servers %s", err)
30  raise AuthenticationError from err
31  except SENSIBO_ERRORS as err:
32  LOGGER.error("Failed to get information from Sensibo servers %s", err)
33  raise ConnectionError from err
34 
35  devices = device_query["result"]
36  user: str = user_query["result"].get("username")
37  if not devices:
38  LOGGER.error("Could not retrieve any devices from Sensibo servers")
39  raise NoDevicesError
40  if not user:
41  LOGGER.error("Could not retrieve username from Sensibo servers")
42  raise NoUsernameError
43  return user
44 
45 
46 class NoDevicesError(Exception):
47  """No devices from Sensibo api."""
48 
49 
50 class NoUsernameError(Exception):
51  """No username from Sensibo api."""
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
str async_validate_api(HomeAssistant hass, str api_key)
Definition: util.py:16
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)