Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Rain Bird."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from collections.abc import Mapping
7 import logging
8 from typing import Any
9 
10 from pyrainbird.async_client import AsyncRainbirdClient, AsyncRainbirdController
11 from pyrainbird.data import WifiParams
12 from pyrainbird.exceptions import RainbirdApiException, RainbirdAuthException
13 import voluptuous as vol
14 
15 from homeassistant.config_entries import (
16  ConfigEntry,
17  ConfigFlow,
18  ConfigFlowResult,
19  OptionsFlow,
20 )
21 from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PASSWORD
22 from homeassistant.core import callback
23 from homeassistant.helpers import config_validation as cv, selector
24 from homeassistant.helpers.device_registry import format_mac
25 
26 from .const import (
27  ATTR_DURATION,
28  CONF_SERIAL_NUMBER,
29  DEFAULT_TRIGGER_TIME_MINUTES,
30  DOMAIN,
31  TIMEOUT_SECONDS,
32 )
33 from .coordinator import async_create_clientsession
34 
35 _LOGGER = logging.getLogger(__name__)
36 
37 
38 DATA_SCHEMA = vol.Schema(
39  {
40  vol.Required(CONF_HOST): selector.TextSelector(),
41  vol.Required(CONF_PASSWORD): selector.TextSelector(
42  selector.TextSelectorConfig(type=selector.TextSelectorType.PASSWORD)
43  ),
44  }
45 )
46 REAUTH_SCHEMA = vol.Schema(
47  {
48  vol.Required(CONF_PASSWORD): selector.TextSelector(
49  selector.TextSelectorConfig(type=selector.TextSelectorType.PASSWORD)
50  ),
51  }
52 )
53 
54 
55 class ConfigFlowError(Exception):
56  """Error raised during a config flow."""
57 
58  def __init__(self, message: str, error_code: str) -> None:
59  """Initialize ConfigFlowError."""
60  super().__init__(message)
61  self.error_codeerror_code = error_code
62 
63 
64 class RainbirdConfigFlowHandler(ConfigFlow, domain=DOMAIN):
65  """Handle a config flow for Rain Bird."""
66 
67  host: str
68 
69  @staticmethod
70  @callback
72  config_entry: ConfigEntry,
73  ) -> RainBirdOptionsFlowHandler:
74  """Define the config flow to handle options."""
76 
77  async def async_step_reauth(
78  self, entry_data: Mapping[str, Any]
79  ) -> ConfigFlowResult:
80  """Perform reauthentication upon an API authentication error."""
81  self.hosthost = entry_data[CONF_HOST]
82  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
83 
85  self, user_input: dict[str, Any] | None = None
86  ) -> ConfigFlowResult:
87  """Confirm reauthentication dialog."""
88  errors: dict[str, str] = {}
89  if user_input:
90  try:
91  await self._test_connection_test_connection(self.hosthost, user_input[CONF_PASSWORD])
92  except ConfigFlowError as err:
93  _LOGGER.error("Error during config flow: %s", err)
94  errors["base"] = err.error_code
95  else:
96  return self.async_update_reload_and_abortasync_update_reload_and_abort(
97  self._get_reauth_entry_get_reauth_entry(),
98  data_updates={CONF_PASSWORD: user_input[CONF_PASSWORD]},
99  )
100  return self.async_show_formasync_show_formasync_show_form(
101  step_id="reauth_confirm",
102  data_schema=REAUTH_SCHEMA,
103  errors=errors,
104  )
105 
106  async def async_step_user(
107  self, user_input: dict[str, Any] | None = None
108  ) -> ConfigFlowResult:
109  """Configure the Rain Bird device."""
110  error_code: str | None = None
111  if user_input:
112  try:
113  serial_number, wifi_params = await self._test_connection_test_connection(
114  user_input[CONF_HOST], user_input[CONF_PASSWORD]
115  )
116  except ConfigFlowError as err:
117  _LOGGER.error("Error during config flow: %s", err)
118  error_code = err.error_code
119  else:
120  return await self.async_finishasync_finish(
121  data={
122  CONF_HOST: user_input[CONF_HOST],
123  CONF_PASSWORD: user_input[CONF_PASSWORD],
124  CONF_SERIAL_NUMBER: serial_number,
125  CONF_MAC: wifi_params.mac_address,
126  },
127  options={ATTR_DURATION: DEFAULT_TRIGGER_TIME_MINUTES},
128  )
129 
130  return self.async_show_formasync_show_formasync_show_form(
131  step_id="user",
132  data_schema=DATA_SCHEMA,
133  errors={"base": error_code} if error_code else None,
134  )
135 
136  async def _test_connection(
137  self, host: str, password: str
138  ) -> tuple[str, WifiParams]:
139  """Test the connection and return the device identifiers.
140 
141  Raises a ConfigFlowError on failure.
142  """
143  clientsession = async_create_clientsession()
144  controller = AsyncRainbirdController(
145  AsyncRainbirdClient(
146  clientsession,
147  host,
148  password,
149  )
150  )
151  try:
152  async with asyncio.timeout(TIMEOUT_SECONDS):
153  return await asyncio.gather(
154  controller.get_serial_number(),
155  controller.get_wifi_params(),
156  )
157  except TimeoutError as err:
158  raise ConfigFlowError(
159  f"Timeout connecting to Rain Bird controller: {err!s}",
160  "timeout_connect",
161  ) from err
162  except RainbirdAuthException as err:
163  raise ConfigFlowError(
164  f"Authentication error connecting from Rain Bird controller: {err!s}",
165  "invalid_auth",
166  ) from err
167  except RainbirdApiException as err:
168  raise ConfigFlowError(
169  f"Error connecting to Rain Bird controller: {err!s}",
170  "cannot_connect",
171  ) from err
172  finally:
173  await clientsession.close()
174 
175  async def async_finish(
176  self,
177  data: dict[str, Any],
178  options: dict[str, Any],
179  ) -> ConfigFlowResult:
180  """Create the config entry."""
181  # The integration has historically used a serial number, but not all devices
182  # historically had a valid one. Now the mac address is used as a unique id
183  # and serial is still persisted in config entry data in case it is needed
184  # in the future.
185  # Either way, also prevent configuring the same host twice.
186  await self.async_set_unique_idasync_set_unique_id(format_mac(data[CONF_MAC]))
187  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
188  updates={
189  CONF_HOST: data[CONF_HOST],
190  CONF_PASSWORD: data[CONF_PASSWORD],
191  }
192  )
193  self._async_abort_entries_match_async_abort_entries_match(
194  {
195  CONF_HOST: data[CONF_HOST],
196  CONF_PASSWORD: data[CONF_PASSWORD],
197  }
198  )
199  return self.async_create_entryasync_create_entryasync_create_entry(
200  title=data[CONF_HOST],
201  data=data,
202  options=options,
203  )
204 
205 
207  """Handle a RainBird options flow."""
208 
209  async def async_step_init(
210  self, user_input: dict[str, Any] | None = None
211  ) -> ConfigFlowResult:
212  """Manage the options."""
213  if user_input is not None:
214  return self.async_create_entryasync_create_entry(data=user_input)
215 
216  return self.async_show_formasync_show_form(
217  step_id="init",
218  data_schema=vol.Schema(
219  {
220  vol.Optional(
221  ATTR_DURATION,
222  default=self.config_entryconfig_entryconfig_entry.options[ATTR_DURATION],
223  ): cv.positive_int,
224  }
225  ),
226  )
None __init__(self, str message, str error_code)
Definition: config_flow.py:58
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:211
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:86
ConfigFlowResult async_finish(self, dict[str, Any] data, dict[str, Any] options)
Definition: config_flow.py:179
RainBirdOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:73
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:108
tuple[str, WifiParams] _test_connection(self, str host, str password)
Definition: config_flow.py:138
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:79
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)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
_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)
aiohttp.ClientSession async_create_clientsession()
Definition: coordinator.py:51