Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Define a config flow manager for AirVisual Pro."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from dataclasses import dataclass, field
7 from typing import Any
8 
9 from pyairvisual.node import (
10  InvalidAuthenticationError,
11  NodeConnectionError,
12  NodeProError,
13  NodeSamba,
14 )
15 import voluptuous as vol
16 
17 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
18 from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD
19 
20 from .const import DOMAIN, LOGGER
21 
22 STEP_REAUTH_SCHEMA = vol.Schema(
23  {
24  vol.Required(CONF_PASSWORD): str,
25  }
26 )
27 
28 STEP_USER_SCHEMA = vol.Schema(
29  {
30  vol.Required(CONF_IP_ADDRESS): str,
31  vol.Required(CONF_PASSWORD): str,
32  }
33 )
34 
35 
36 @dataclass
38  """Define a validation result."""
39 
40  serial_number: str | None = None
41  errors: dict[str, Any] = field(default_factory=dict)
42 
43 
45  ip_address: str, password: str
46 ) -> ValidationResult:
47  """Validate an IP address/password combo."""
48  node = NodeSamba(ip_address, password)
49  errors = {}
50 
51  try:
52  await node.async_connect()
53  measurements = await node.async_get_latest_measurements()
54  except InvalidAuthenticationError as err:
55  LOGGER.error("Invalid password for Pro at IP address %s: %s", ip_address, err)
56  errors["base"] = "invalid_auth"
57  except NodeConnectionError as err:
58  LOGGER.error("Cannot connect to Pro at IP address %s: %s", ip_address, err)
59  errors["base"] = "cannot_connect"
60  except NodeProError as err:
61  LOGGER.error("Unknown Pro error while connecting to %s: %s", ip_address, err)
62  errors["base"] = "unknown"
63  except Exception as err: # noqa: BLE001
64  LOGGER.exception("Unknown error while connecting to %s: %s", ip_address, err)
65  errors["base"] = "unknown"
66  else:
67  return ValidationResult(serial_number=measurements["serial_number"])
68  finally:
69  await node.async_disconnect()
70 
71  return ValidationResult(errors=errors)
72 
73 
74 class AirVisualProFlowHandler(ConfigFlow, domain=DOMAIN):
75  """Handle an AirVisual Pro config flow."""
76 
77  VERSION = 1
78 
79  _reauth_entry_data: Mapping[str, Any]
80 
81  async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
82  """Import a config entry from `airvisual` integration (see #83882)."""
83  return await self.async_step_userasync_step_userasync_step_user(import_data)
84 
85  async def async_step_reauth(
86  self, entry_data: Mapping[str, Any]
87  ) -> ConfigFlowResult:
88  """Handle configuration by re-auth."""
89  self._reauth_entry_data_reauth_entry_data = entry_data
90  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
91 
93  self, user_input: dict[str, Any] | None = None
94  ) -> ConfigFlowResult:
95  """Handle the re-auth step."""
96  if user_input is None:
97  return self.async_show_formasync_show_formasync_show_form(
98  step_id="reauth_confirm", data_schema=STEP_REAUTH_SCHEMA
99  )
100 
101  validation_result = await async_validate_credentials(
102  self._reauth_entry_data_reauth_entry_data[CONF_IP_ADDRESS], user_input[CONF_PASSWORD]
103  )
104 
105  if validation_result.errors:
106  return self.async_show_formasync_show_formasync_show_form(
107  step_id="reauth_confirm",
108  data_schema=STEP_REAUTH_SCHEMA,
109  errors=validation_result.errors,
110  )
111 
112  return self.async_update_reload_and_abortasync_update_reload_and_abort(
113  self._get_reauth_entry_get_reauth_entry(), data_updates=user_input
114  )
115 
116  async def async_step_user(
117  self, user_input: dict[str, str] | None = None
118  ) -> ConfigFlowResult:
119  """Handle the initial step."""
120  if not user_input:
121  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=STEP_USER_SCHEMA)
122 
123  ip_address = user_input[CONF_IP_ADDRESS]
124 
125  validation_result = await async_validate_credentials(
126  ip_address, user_input[CONF_PASSWORD]
127  )
128 
129  if validation_result.errors:
130  return self.async_show_formasync_show_formasync_show_form(
131  step_id="user",
132  data_schema=STEP_USER_SCHEMA,
133  errors=validation_result.errors,
134  )
135 
136  await self.async_set_unique_idasync_set_unique_id(validation_result.serial_number)
137  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
138 
139  return self.async_create_entryasync_create_entryasync_create_entry(title=ip_address, data=user_input)
ConfigFlowResult async_step_import(self, dict[str, Any] import_data)
Definition: config_flow.py:81
ConfigFlowResult async_step_user(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:118
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:87
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:94
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_step_user(self, dict[str, Any]|None user_input=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)
ValidationResult async_validate_credentials(str ip_address, str password)
Definition: config_flow.py:46