Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for TP-Link Omada integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 import re
8 from types import MappingProxyType
9 from typing import Any, NamedTuple
10 from urllib.parse import urlsplit
11 
12 from aiohttp import CookieJar
13 from tplink_omada_client import OmadaClient, OmadaSite
14 from tplink_omada_client.exceptions import (
15  ConnectionFailed,
16  LoginFailed,
17  OmadaClientException,
18  UnsupportedControllerVersion,
19 )
20 import voluptuous as vol
21 
22 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
23 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL
24 from homeassistant.core import HomeAssistant
25 from homeassistant.helpers import selector
27  async_create_clientsession,
28  async_get_clientsession,
29 )
30 
31 from .const import DOMAIN
32 
33 _LOGGER = logging.getLogger(__name__)
34 
35 CONF_SITE = "site"
36 
37 STEP_USER_DATA_SCHEMA = vol.Schema(
38  {
39  vol.Required(CONF_HOST): str,
40  vol.Required(CONF_VERIFY_SSL, default=True): bool,
41  vol.Required(CONF_USERNAME): str,
42  vol.Required(CONF_PASSWORD): str,
43  }
44 )
45 
46 
48  hass: HomeAssistant, data: MappingProxyType[str, Any]
49 ) -> OmadaClient:
50  """Create a TP-Link Omada client API for the given config entry."""
51 
52  host: str = data[CONF_HOST]
53  verify_ssl = bool(data[CONF_VERIFY_SSL])
54 
55  if not host.lower().startswith(("http://", "https://")):
56  host = "https://" + host
57  host_parts = urlsplit(host)
58  if (
59  host_parts.hostname
60  and re.fullmatch(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", host_parts.hostname)
61  is not None
62  ):
63  # TP-Link API uses cookies for login session, so an unsafe cookie jar is required for IP addresses
64  websession = async_create_clientsession(
65  hass, cookie_jar=CookieJar(unsafe=True), verify_ssl=verify_ssl
66  )
67  else:
68  websession = async_get_clientsession(hass, verify_ssl=verify_ssl)
69 
70  username = data[CONF_USERNAME]
71  password = data[CONF_PASSWORD]
72 
73  return OmadaClient(host, username, password, websession=websession)
74 
75 
76 class HubInfo(NamedTuple):
77  """Discovered controller information."""
78 
79  controller_id: str
80  name: str
81  sites: list[OmadaSite]
82 
83 
84 async def _validate_input(hass: HomeAssistant, data: dict[str, Any]) -> HubInfo:
85  """Validate the user input allows us to connect."""
86 
87  client = await create_omada_client(hass, MappingProxyType(data))
88  controller_id = await client.login()
89  name = await client.get_controller_name()
90  sites = await client.get_sites()
91 
92  return HubInfo(controller_id, name, sites)
93 
94 
95 class TpLinkOmadaConfigFlow(ConfigFlow, domain=DOMAIN):
96  """Handle a config flow for TP-Link Omada."""
97 
98  VERSION = 1
99 
100  def __init__(self) -> None:
101  """Create the config flow for a new integration."""
102  self._omada_opts_omada_opts: dict[str, Any] = {}
103  self._sites_sites: list[OmadaSite] = []
104  self._controller_name_controller_name = ""
105 
106  async def async_step_user(
107  self, user_input: dict[str, Any] | None = None
108  ) -> ConfigFlowResult:
109  """Handle the initial step."""
110 
111  errors: dict[str, str] = {}
112  info = None
113  if user_input is not None:
114  info = await self._test_login_test_login(user_input, errors)
115 
116  if info is None or user_input is None:
117  return self.async_show_formasync_show_formasync_show_form(
118  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
119  )
120 
121  await self.async_set_unique_idasync_set_unique_id(info.controller_id)
122  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
123 
124  self._omada_opts_omada_opts.update(user_input)
125  self._sites_sites = info.sites
126  self._controller_name_controller_name = info.name
127  if len(self._sites_sites) > 1:
128  return await self.async_step_siteasync_step_site()
129  return await self.async_step_siteasync_step_site({CONF_SITE: self._sites_sites[0].id})
130 
131  async def async_step_site(
132  self, user_input: dict[str, Any] | None = None
133  ) -> ConfigFlowResult:
134  """Handle step to select site to manage."""
135 
136  if user_input is None:
137  schema = vol.Schema(
138  {
139  vol.Required(CONF_SITE, "site"): selector.SelectSelector(
140  selector.SelectSelectorConfig(
141  options=[
142  selector.SelectOptionDict(value=s.id, label=s.name)
143  for s in self._sites_sites
144  ],
145  multiple=False,
146  mode=selector.SelectSelectorMode.DROPDOWN,
147  )
148  )
149  }
150  )
151 
152  return self.async_show_formasync_show_formasync_show_form(step_id="site", data_schema=schema)
153 
154  self._omada_opts_omada_opts.update(user_input)
155  site_name = next(
156  site for site in self._sites_sites if site.id == user_input["site"]
157  ).name
158  display_name = f"{self._controller_name} ({site_name})"
159 
160  return self.async_create_entryasync_create_entryasync_create_entry(title=display_name, data=self._omada_opts_omada_opts)
161 
162  async def async_step_reauth(
163  self, entry_data: Mapping[str, Any]
164  ) -> ConfigFlowResult:
165  """Perform reauth upon an API authentication error."""
166  self._omada_opts_omada_opts = dict(entry_data)
167  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
168 
170  self, user_input: dict[str, Any] | None = None
171  ) -> ConfigFlowResult:
172  """Dialog that informs the user that reauth is required."""
173 
174  errors: dict[str, str] = {}
175 
176  if user_input is not None:
177  self._omada_opts_omada_opts.update(user_input)
178  info = await self._test_login_test_login(self._omada_opts_omada_opts, errors)
179 
180  if info is not None:
181  # Auth successful - update the config entry with the new credentials
182  return self.async_update_reload_and_abortasync_update_reload_and_abort(
183  self._get_reauth_entry_get_reauth_entry(), data=self._omada_opts_omada_opts
184  )
185 
186  return self.async_show_formasync_show_formasync_show_form(
187  step_id="reauth_confirm",
188  data_schema=vol.Schema(
189  {
190  vol.Required(CONF_USERNAME): str,
191  vol.Required(CONF_PASSWORD): str,
192  }
193  ),
194  errors=errors,
195  )
196 
197  async def _test_login(
198  self, data: dict[str, Any], errors: dict[str, str]
199  ) -> HubInfo | None:
200  try:
201  info = await _validate_input(self.hass, data)
202  if len(info.sites) > 0:
203  return info
204  errors["base"] = "no_sites_found"
205 
206  except ConnectionFailed:
207  errors["base"] = "cannot_connect"
208  except LoginFailed:
209  errors["base"] = "invalid_auth"
210  except UnsupportedControllerVersion:
211  errors["base"] = "unsupported_controller"
212  except OmadaClientException as ex:
213  _LOGGER.error("Unexpected API error: %s", ex)
214  errors["base"] = "unknown"
215  except Exception:
216  _LOGGER.exception("Unexpected exception")
217  errors["base"] = "unknown"
218  return None
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigEntry|None async_set_unique_id(self, str|None unique_id=None, *bool raise_on_progress=True)
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_update_reload_and_abort(self, ConfigEntry entry, *str|None|UndefinedType unique_id=UNDEFINED, str|UndefinedType title=UNDEFINED, Mapping[str, Any]|UndefinedType data=UNDEFINED, Mapping[str, Any]|UndefinedType data_updates=UNDEFINED, Mapping[str, Any]|UndefinedType options=UNDEFINED, str|UndefinedType reason=UNDEFINED, bool reload_even_if_entry_is_unchanged=True)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
aiohttp.ClientSession async_create_clientsession()
Definition: coordinator.py:51
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)