Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for QNAP QSW."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from aioqsw.exceptions import LoginError, QswError
9 from aioqsw.localapi import ConnectionOptions, QnapQswApi
10 import voluptuous as vol
11 
12 from homeassistant.components import dhcp
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_PASSWORD, CONF_URL, CONF_USERNAME
15 from homeassistant.data_entry_flow import AbortFlow
16 from homeassistant.helpers import aiohttp_client
17 from homeassistant.helpers.device_registry import format_mac
18 
19 from .const import DOMAIN
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 
24 class QNapQSWConfigFlow(ConfigFlow, domain=DOMAIN):
25  """Handle config flow for a QNAP QSW device."""
26 
27  _discovered_mac: str | None = None
28  _discovered_url: str | None = None
29 
30  async def async_step_user(
31  self, user_input: dict[str, Any] | None = None
32  ) -> ConfigFlowResult:
33  """Handle the initial step."""
34  errors = {}
35 
36  if user_input is not None:
37  url = user_input[CONF_URL]
38  username = user_input[CONF_USERNAME]
39  password = user_input[CONF_PASSWORD]
40 
41  qsw = QnapQswApi(
42  aiohttp_client.async_get_clientsession(self.hass),
43  ConnectionOptions(url, username, password),
44  )
45 
46  try:
47  system_board = await qsw.validate()
48  except LoginError:
49  errors[CONF_PASSWORD] = "invalid_auth"
50  except QswError:
51  errors[CONF_URL] = "cannot_connect"
52  else:
53  mac = system_board.get_mac()
54  if mac is None:
55  raise AbortFlow("invalid_id")
56 
57  await self.async_set_unique_idasync_set_unique_id(format_mac(mac), raise_on_progress=False)
58  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
59 
60  title = f"QNAP {system_board.get_product()} {mac}"
61  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=user_input)
62 
63  return self.async_show_formasync_show_formasync_show_form(
64  step_id="user",
65  data_schema=vol.Schema(
66  {
67  vol.Required(CONF_URL): str,
68  vol.Required(CONF_USERNAME): str,
69  vol.Required(CONF_PASSWORD): str,
70  }
71  ),
72  errors=errors,
73  )
74 
75  async def async_step_dhcp(
76  self, discovery_info: dhcp.DhcpServiceInfo
77  ) -> ConfigFlowResult:
78  """Handle DHCP discovery."""
79  self._discovered_url_discovered_url = f"http://{discovery_info.ip}"
80  self._discovered_mac_discovered_mac = discovery_info.macaddress
81 
82  _LOGGER.debug("DHCP discovery detected QSW: %s", self._discovered_mac_discovered_mac)
83 
84  await self.async_set_unique_idasync_set_unique_id(format_mac(self._discovered_mac_discovered_mac))
85  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
86  updates={
87  CONF_URL: self._discovered_url_discovered_url,
88  }
89  )
90 
91  options = ConnectionOptions(self._discovered_url_discovered_url, "", "")
92  qsw = QnapQswApi(aiohttp_client.async_get_clientsession(self.hass), options)
93 
94  try:
95  await qsw.get_live()
96  except QswError as err:
97  raise AbortFlow("cannot_connect") from err
98 
99  return await self.async_step_discovered_connection()
100 
101  async def async_step_discovered_connection(
102  self, user_input: dict[str, Any] | None = None
103  ) -> ConfigFlowResult:
104  """Confirm discovery."""
105  errors = {}
106  assert self._discovered_url_discovered_url is not None
107 
108  if user_input is not None:
109  username = user_input[CONF_USERNAME]
110  password = user_input[CONF_PASSWORD]
111 
112  qsw = QnapQswApi(
113  aiohttp_client.async_get_clientsession(self.hass),
114  ConnectionOptions(self._discovered_url_discovered_url, username, password),
115  )
116 
117  try:
118  system_board = await qsw.validate()
119  except LoginError:
120  errors[CONF_PASSWORD] = "invalid_auth"
121  except QswError:
122  errors["base"] = "cannot_connect"
123  else:
124  title = f"QNAP {system_board.get_product()} {self._discovered_mac}"
125  user_input[CONF_URL] = self._discovered_url_discovered_url
126  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=user_input)
127 
128  return self.async_show_formasync_show_formasync_show_form(
129  step_id="discovered_connection",
130  data_schema=vol.Schema(
131  {
132  vol.Required(CONF_USERNAME): str,
133  vol.Required(CONF_PASSWORD): str,
134  }
135  ),
136  errors=errors,
137  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:32
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigFlowResult async_step_dhcp(self, DhcpServiceInfo discovery_info)
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_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)