Home Assistant Unofficial Reference 2024.12.1
api.py
Go to the documentation of this file.
1 """Provide an object to communicate with UniFi Network application."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 import ssl
7 from types import MappingProxyType
8 from typing import Any, Literal
9 
10 from aiohttp import CookieJar
11 import aiounifi
12 from aiounifi.models.configuration import Configuration
13 
14 from homeassistant.const import (
15  CONF_HOST,
16  CONF_PASSWORD,
17  CONF_PORT,
18  CONF_USERNAME,
19  CONF_VERIFY_SSL,
20 )
21 from homeassistant.core import HomeAssistant
22 from homeassistant.helpers import aiohttp_client
23 
24 from ..const import CONF_SITE_ID, LOGGER
25 from ..errors import AuthenticationRequired, CannotConnect
26 
27 
28 async def get_unifi_api(
29  hass: HomeAssistant,
30  config: MappingProxyType[str, Any],
31 ) -> aiounifi.Controller:
32  """Create a aiounifi object and verify authentication."""
33  ssl_context: ssl.SSLContext | Literal[False] = False
34 
35  if verify_ssl := config.get(CONF_VERIFY_SSL):
36  session = aiohttp_client.async_get_clientsession(hass)
37  if isinstance(verify_ssl, str):
38  ssl_context = ssl.create_default_context(cafile=verify_ssl)
39  else:
40  session = aiohttp_client.async_create_clientsession(
41  hass, verify_ssl=False, cookie_jar=CookieJar(unsafe=True)
42  )
43 
44  api = aiounifi.Controller(
45  Configuration(
46  session,
47  host=config[CONF_HOST],
48  username=config[CONF_USERNAME],
49  password=config[CONF_PASSWORD],
50  port=config[CONF_PORT],
51  site=config[CONF_SITE_ID],
52  ssl_context=ssl_context,
53  )
54  )
55 
56  try:
57  async with asyncio.timeout(10):
58  await api.login()
59 
60  except aiounifi.Unauthorized as err:
61  LOGGER.warning(
62  "Connected to UniFi Network at %s but not registered: %s",
63  config[CONF_HOST],
64  err,
65  )
66  raise AuthenticationRequired from err
67 
68  except (
69  TimeoutError,
70  aiounifi.BadGateway,
71  aiounifi.Forbidden,
72  aiounifi.ServiceUnavailable,
73  aiounifi.RequestError,
74  aiounifi.ResponseError,
75  ) as err:
76  LOGGER.error(
77  "Error connecting to the UniFi Network at %s: %s", config[CONF_HOST], err
78  )
79  raise CannotConnect from err
80 
81  except aiounifi.LoginRequired as err:
82  LOGGER.warning(
83  "Connected to UniFi Network at %s but login required: %s",
84  config[CONF_HOST],
85  err,
86  )
87  raise AuthenticationRequired from err
88 
89  except aiounifi.AiounifiException as err:
90  LOGGER.exception("Unknown UniFi Network communication error occurred: %s", err)
91  raise AuthenticationRequired from err
92 
93  return api
aiounifi.Controller get_unifi_api(HomeAssistant hass, MappingProxyType[str, Any] config)
Definition: api.py:31