Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Network UPS Tools (NUT) integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from aionut import NUTError, NUTLoginError
10 import voluptuous as vol
11 
12 from homeassistant.components import zeroconf
13 from homeassistant.config_entries import (
14  ConfigEntry,
15  ConfigFlow,
16  ConfigFlowResult,
17  OptionsFlow,
18 )
19 from homeassistant.const import (
20  CONF_ALIAS,
21  CONF_BASE,
22  CONF_HOST,
23  CONF_PASSWORD,
24  CONF_PORT,
25  CONF_SCAN_INTERVAL,
26  CONF_USERNAME,
27 )
28 from homeassistant.core import HomeAssistant, callback
29 from homeassistant.data_entry_flow import AbortFlow
30 
31 from . import PyNUTData
32 from .const import DEFAULT_HOST, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN
33 
34 _LOGGER = logging.getLogger(__name__)
35 
36 AUTH_SCHEMA = {vol.Optional(CONF_USERNAME): str, vol.Optional(CONF_PASSWORD): str}
37 
38 
39 def _base_schema(nut_config: dict[str, Any]) -> vol.Schema:
40  """Generate base schema."""
41  base_schema = {
42  vol.Optional(CONF_HOST, default=nut_config.get(CONF_HOST) or DEFAULT_HOST): str,
43  vol.Optional(CONF_PORT, default=nut_config.get(CONF_PORT) or DEFAULT_PORT): int,
44  }
45  base_schema.update(AUTH_SCHEMA)
46  return vol.Schema(base_schema)
47 
48 
49 def _ups_schema(ups_list: dict[str, str]) -> vol.Schema:
50  """UPS selection schema."""
51  return vol.Schema({vol.Required(CONF_ALIAS): vol.In(ups_list)})
52 
53 
54 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
55  """Validate the user input allows us to connect.
56 
57  Data has the keys from _base_schema with values provided by the user.
58  """
59 
60  host = data[CONF_HOST]
61  port = data[CONF_PORT]
62  alias = data.get(CONF_ALIAS)
63  username = data.get(CONF_USERNAME)
64  password = data.get(CONF_PASSWORD)
65 
66  nut_data = PyNUTData(host, port, alias, username, password, persistent=False)
67  status = await nut_data.async_update()
68 
69  if not alias and not nut_data.ups_list:
70  raise AbortFlow("no_ups_found")
71 
72  return {"ups_list": nut_data.ups_list, "available_resources": status}
73 
74 
75 def _format_host_port_alias(user_input: Mapping[str, Any]) -> str:
76  """Format a host, port, and alias so it can be used for comparison or display."""
77  host = user_input[CONF_HOST]
78  port = user_input[CONF_PORT]
79  alias = user_input.get(CONF_ALIAS)
80  if alias:
81  return f"{alias}@{host}:{port}"
82  return f"{host}:{port}"
83 
84 
85 class NutConfigFlow(ConfigFlow, domain=DOMAIN):
86  """Handle a config flow for Network UPS Tools (NUT)."""
87 
88  VERSION = 1
89 
90  def __init__(self) -> None:
91  """Initialize the nut config flow."""
92  self.nut_confignut_config: dict[str, Any] = {}
93  self.ups_listups_list: dict[str, str] | None = None
94  self.title: str | None = None
95  self.reauth_entryreauth_entry: ConfigEntry | None = None
96 
98  self, discovery_info: zeroconf.ZeroconfServiceInfo
99  ) -> ConfigFlowResult:
100  """Prepare configuration for a discovered nut device."""
101  await self._async_handle_discovery_without_unique_id_async_handle_discovery_without_unique_id()
102  self.nut_confignut_config = {
103  CONF_HOST: discovery_info.host or DEFAULT_HOST,
104  CONF_PORT: discovery_info.port or DEFAULT_PORT,
105  }
106  self.context["title_placeholders"] = self.nut_confignut_config.copy()
107  return await self.async_step_userasync_step_userasync_step_user()
108 
109  async def async_step_user(
110  self, user_input: dict[str, Any] | None = None
111  ) -> ConfigFlowResult:
112  """Handle the user input."""
113  errors: dict[str, str] = {}
114  placeholders: dict[str, str] = {}
115  nut_config = self.nut_confignut_config
116  if user_input is not None:
117  nut_config.update(user_input)
118 
119  info, errors, placeholders = await self._async_validate_or_error_async_validate_or_error(nut_config)
120 
121  if not errors:
122  if len(info["ups_list"]) > 1:
123  self.ups_listups_list = info["ups_list"]
124  return await self.async_step_upsasync_step_ups()
125 
126  if self._host_port_alias_already_configured_host_port_alias_already_configured(nut_config):
127  return self.async_abortasync_abortasync_abort(reason="already_configured")
128  title = _format_host_port_alias(nut_config)
129  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=nut_config)
130 
131  return self.async_show_formasync_show_formasync_show_form(
132  step_id="user",
133  data_schema=_base_schema(nut_config),
134  errors=errors,
135  description_placeholders=placeholders,
136  )
137 
138  async def async_step_ups(
139  self, user_input: dict[str, Any] | None = None
140  ) -> ConfigFlowResult:
141  """Handle the picking the ups."""
142  errors: dict[str, str] = {}
143  placeholders: dict[str, str] = {}
144  nut_config = self.nut_confignut_config
145 
146  if user_input is not None:
147  self.nut_confignut_config.update(user_input)
148  if self._host_port_alias_already_configured_host_port_alias_already_configured(nut_config):
149  return self.async_abortasync_abortasync_abort(reason="already_configured")
150  _, errors, placeholders = await self._async_validate_or_error_async_validate_or_error(nut_config)
151  if not errors:
152  title = _format_host_port_alias(nut_config)
153  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=nut_config)
154 
155  return self.async_show_formasync_show_formasync_show_form(
156  step_id="ups",
157  data_schema=_ups_schema(self.ups_listups_list or {}),
158  errors=errors,
159  description_placeholders=placeholders,
160  )
161 
162  def _host_port_alias_already_configured(self, user_input: dict[str, Any]) -> bool:
163  """See if we already have a nut entry matching user input configured."""
164  existing_host_port_aliases = {
165  _format_host_port_alias(entry.data)
166  for entry in self._async_current_entries_async_current_entries()
167  if CONF_HOST in entry.data
168  }
169  return _format_host_port_alias(user_input) in existing_host_port_aliases
170 
172  self, config: dict[str, Any]
173  ) -> tuple[dict[str, Any], dict[str, str], dict[str, str]]:
174  errors: dict[str, str] = {}
175  info: dict[str, Any] = {}
176  description_placeholders: dict[str, str] = {}
177  try:
178  info = await validate_input(self.hass, config)
179  except NUTLoginError:
180  errors[CONF_PASSWORD] = "invalid_auth"
181  except NUTError as ex:
182  errors[CONF_BASE] = "cannot_connect"
183  description_placeholders["error"] = str(ex)
184  except AbortFlow:
185  raise
186  except Exception:
187  _LOGGER.exception("Unexpected exception")
188  errors[CONF_BASE] = "unknown"
189  return info, errors, description_placeholders
190 
191  async def async_step_reauth(
192  self, entry_data: Mapping[str, Any]
193  ) -> ConfigFlowResult:
194  """Handle reauth."""
195  entry_id = self.context["entry_id"]
196  self.reauth_entryreauth_entry = self.hass.config_entries.async_get_entry(entry_id)
197  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
198 
200  self, user_input: dict[str, Any] | None = None
201  ) -> ConfigFlowResult:
202  """Handle reauth input."""
203  errors: dict[str, str] = {}
204  existing_entry = self.reauth_entryreauth_entry
205  assert existing_entry
206  existing_data = existing_entry.data
207  description_placeholders: dict[str, str] = {
208  CONF_HOST: existing_data[CONF_HOST],
209  CONF_PORT: existing_data[CONF_PORT],
210  }
211  if user_input is not None:
212  new_config = {
213  **existing_data,
214  # Username/password are optional and some servers
215  # use ip based authentication and will fail if
216  # username/password are provided
217  CONF_USERNAME: user_input.get(CONF_USERNAME),
218  CONF_PASSWORD: user_input.get(CONF_PASSWORD),
219  }
220  _, errors, placeholders = await self._async_validate_or_error_async_validate_or_error(new_config)
221  if not errors:
222  return self.async_update_reload_and_abortasync_update_reload_and_abort(
223  existing_entry, data=new_config
224  )
225  description_placeholders.update(placeholders)
226 
227  return self.async_show_formasync_show_formasync_show_form(
228  description_placeholders=description_placeholders,
229  step_id="reauth_confirm",
230  data_schema=vol.Schema(AUTH_SCHEMA),
231  errors=errors,
232  )
233 
234  @staticmethod
235  @callback
236  def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow:
237  """Get the options flow for this handler."""
238  return OptionsFlowHandler()
239 
240 
242  """Handle a option flow for nut."""
243 
244  async def async_step_init(
245  self, user_input: dict[str, Any] | None = None
246  ) -> ConfigFlowResult:
247  """Handle options flow."""
248  if user_input is not None:
249  return self.async_create_entryasync_create_entry(title="", data=user_input)
250 
251  scan_interval = self.config_entryconfig_entryconfig_entry.options.get(
252  CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
253  )
254 
255  base_schema = {
256  vol.Optional(CONF_SCAN_INTERVAL, default=scan_interval): vol.All(
257  vol.Coerce(int), vol.Clamp(min=10, max=300)
258  )
259  }
260 
261  return self.async_show_formasync_show_form(step_id="init", data_schema=vol.Schema(base_schema))
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:201
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:193
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:99
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:111
bool _host_port_alias_already_configured(self, dict[str, Any] user_input)
Definition: config_flow.py:162
OptionsFlow async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:236
tuple[dict[str, Any], dict[str, str], dict[str, str]] _async_validate_or_error(self, dict[str, Any] config)
Definition: config_flow.py:173
ConfigFlowResult async_step_ups(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:140
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:246
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)
list[ConfigEntry] _async_current_entries(self, bool|None include_ignore=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_step_user(self, dict[str, Any]|None user_input=None)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=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)
None config_entry(self, ConfigEntry value)
str
_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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
dict[str, Any] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:54
vol.Schema _ups_schema(dict[str, str] ups_list)
Definition: config_flow.py:49
vol.Schema _base_schema(dict[str, Any] nut_config)
Definition: config_flow.py:39
str _format_host_port_alias(Mapping[str, Any] user_input)
Definition: config_flow.py:75