Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the Reolink camera component."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from reolink_aio.api import ALLOWED_SPECIAL_CHARS
10 from reolink_aio.exceptions import (
11  ApiError,
12  CredentialsInvalidError,
13  LoginFirmwareError,
14  ReolinkError,
15 )
16 import voluptuous as vol
17 
18 from homeassistant.components import dhcp
19 from homeassistant.config_entries import (
20  SOURCE_REAUTH,
21  SOURCE_RECONFIGURE,
22  ConfigFlow,
23  ConfigFlowResult,
24  OptionsFlow,
25 )
26 from homeassistant.const import (
27  CONF_HOST,
28  CONF_PASSWORD,
29  CONF_PORT,
30  CONF_PROTOCOL,
31  CONF_USERNAME,
32 )
33 from homeassistant.core import callback
34 from homeassistant.data_entry_flow import AbortFlow
35 from homeassistant.helpers import config_validation as cv, selector
36 from homeassistant.helpers.device_registry import format_mac
37 
38 from .const import CONF_USE_HTTPS, DOMAIN
39 from .exceptions import (
40  PasswordIncompatible,
41  ReolinkException,
42  ReolinkWebhookException,
43  UserNotAdmin,
44 )
45 from .host import ReolinkHost
46 from .util import ReolinkConfigEntry, is_connected
47 
48 _LOGGER = logging.getLogger(__name__)
49 
50 DEFAULT_PROTOCOL = "rtsp"
51 DEFAULT_OPTIONS = {CONF_PROTOCOL: DEFAULT_PROTOCOL}
52 
53 
55  """Handle Reolink options."""
56 
57  async def async_step_init(
58  self, user_input: dict[str, Any] | None = None
59  ) -> ConfigFlowResult:
60  """Manage the Reolink options."""
61  if user_input is not None:
62  return self.async_create_entryasync_create_entry(data=user_input)
63 
64  return self.async_show_formasync_show_form(
65  step_id="init",
66  data_schema=vol.Schema(
67  {
68  vol.Required(
69  CONF_PROTOCOL,
70  default=self.config_entryconfig_entryconfig_entry.options[CONF_PROTOCOL],
71  ): selector.SelectSelector(
72  selector.SelectSelectorConfig(
73  options=[
74  selector.SelectOptionDict(
75  value="rtsp",
76  label="RTSP",
77  ),
78  selector.SelectOptionDict(
79  value="rtmp",
80  label="RTMP",
81  ),
82  selector.SelectOptionDict(
83  value="flv",
84  label="FLV",
85  ),
86  ],
87  ),
88  ),
89  }
90  ),
91  )
92 
93 
94 class ReolinkFlowHandler(ConfigFlow, domain=DOMAIN):
95  """Handle a config flow for Reolink device."""
96 
97  VERSION = 1
98 
99  def __init__(self) -> None:
100  """Initialize."""
101  self._host_host: str | None = None
102  self._username_username: str = "admin"
103  self._password_password: str | None = None
104 
105  @staticmethod
106  @callback
108  config_entry: ReolinkConfigEntry,
109  ) -> ReolinkOptionsFlowHandler:
110  """Options callback for Reolink."""
112 
113  async def async_step_reauth(
114  self, entry_data: Mapping[str, Any]
115  ) -> ConfigFlowResult:
116  """Perform reauth upon an authentication error or no admin privileges."""
117  self._host_host = entry_data[CONF_HOST]
118  self._username_username = entry_data[CONF_USERNAME]
119  self._password_password = entry_data[CONF_PASSWORD]
120  placeholders = {
121  **self.context["title_placeholders"],
122  "ip_address": entry_data[CONF_HOST],
123  "hostname": self.context["title_placeholders"]["name"],
124  }
125  self.context["title_placeholders"] = placeholders
126  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
127 
129  self, user_input: dict[str, Any] | None = None
130  ) -> ConfigFlowResult:
131  """Dialog that informs the user that reauth is required."""
132  if user_input is not None:
133  return await self.async_step_userasync_step_userasync_step_user()
134  placeholders = {"name": self.context["title_placeholders"]["name"]}
135  return self.async_show_formasync_show_formasync_show_form(
136  step_id="reauth_confirm", description_placeholders=placeholders
137  )
138 
140  self, user_input: dict[str, Any] | None = None
141  ) -> ConfigFlowResult:
142  """Perform a reconfiguration."""
143  entry_data = self._get_reconfigure_entry_get_reconfigure_entry().data
144  self._host_host = entry_data[CONF_HOST]
145  self._username_username = entry_data[CONF_USERNAME]
146  self._password_password = entry_data[CONF_PASSWORD]
147  return await self.async_step_userasync_step_userasync_step_user()
148 
149  async def async_step_dhcp(
150  self, discovery_info: dhcp.DhcpServiceInfo
151  ) -> ConfigFlowResult:
152  """Handle discovery via dhcp."""
153  mac_address = format_mac(discovery_info.macaddress)
154  existing_entry = await self.async_set_unique_idasync_set_unique_id(mac_address)
155  if (
156  existing_entry
157  and CONF_PASSWORD in existing_entry.data
158  and existing_entry.data[CONF_HOST] != discovery_info.ip
159  ):
160  if is_connected(self.hass, existing_entry):
161  _LOGGER.debug(
162  "Reolink DHCP reported new IP '%s', "
163  "but connection to camera seems to be okay, so sticking to IP '%s'",
164  discovery_info.ip,
165  existing_entry.data[CONF_HOST],
166  )
167  raise AbortFlow("already_configured")
168 
169  # check if the camera is reachable at the new IP
170  new_config = dict(existing_entry.data)
171  new_config[CONF_HOST] = discovery_info.ip
172  host = ReolinkHost(self.hass, new_config, existing_entry.options)
173  try:
174  await host.api.get_state("GetLocalLink")
175  await host.api.logout()
176  except ReolinkError as err:
177  _LOGGER.debug(
178  "Reolink DHCP reported new IP '%s', "
179  "but got error '%s' trying to connect, so sticking to IP '%s'",
180  discovery_info.ip,
181  err,
182  existing_entry.data[CONF_HOST],
183  )
184  raise AbortFlow("already_configured") from err
185  if format_mac(host.api.mac_address) != mac_address:
186  _LOGGER.debug(
187  "Reolink mac address '%s' at new IP '%s' from DHCP, "
188  "does not match mac '%s' of config entry, so sticking to IP '%s'",
189  format_mac(host.api.mac_address),
190  discovery_info.ip,
191  mac_address,
192  existing_entry.data[CONF_HOST],
193  )
194  raise AbortFlow("already_configured")
195 
196  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates={CONF_HOST: discovery_info.ip})
197 
198  self.context["title_placeholders"] = {
199  "ip_address": discovery_info.ip,
200  "hostname": discovery_info.hostname,
201  }
202 
203  self._host_host = discovery_info.ip
204  return await self.async_step_userasync_step_userasync_step_user()
205 
206  async def async_step_user(
207  self, user_input: dict[str, Any] | None = None
208  ) -> ConfigFlowResult:
209  """Handle the initial step."""
210  errors = {}
211  placeholders = {
212  "error": "",
213  "troubleshooting_link": "https://www.home-assistant.io/integrations/reolink/#troubleshooting",
214  }
215 
216  if user_input is not None:
217  if CONF_HOST not in user_input:
218  user_input[CONF_HOST] = self._host_host
219 
220  # remember input in case of a error
221  self._username_username = user_input[CONF_USERNAME]
222  self._password_password = user_input[CONF_PASSWORD]
223  self._host_host = user_input[CONF_HOST]
224 
225  host = ReolinkHost(self.hass, user_input, DEFAULT_OPTIONS)
226  try:
227  await host.async_init()
228  except UserNotAdmin:
229  errors[CONF_USERNAME] = "not_admin"
230  placeholders["username"] = host.api.username
231  placeholders["userlevel"] = host.api.user_level
232  except PasswordIncompatible:
233  errors[CONF_PASSWORD] = "password_incompatible"
234  placeholders["special_chars"] = ALLOWED_SPECIAL_CHARS
235  except CredentialsInvalidError:
236  errors[CONF_PASSWORD] = "invalid_auth"
237  except LoginFirmwareError:
238  errors["base"] = "update_needed"
239  placeholders["current_firmware"] = host.api.sw_version
240  placeholders["needed_firmware"] = (
241  host.api.sw_version_required.version_string
242  )
243  placeholders["download_center_url"] = (
244  "https://reolink.com/download-center"
245  )
246  except ApiError as err:
247  placeholders["error"] = str(err)
248  errors[CONF_HOST] = "api_error"
249  except ReolinkWebhookException as err:
250  placeholders["error"] = str(err)
251  placeholders["more_info"] = (
252  "https://www.home-assistant.io/more-info/no-url-available/#configuring-the-instance-url"
253  )
254  errors["base"] = "webhook_exception"
255  except (ReolinkError, ReolinkException) as err:
256  placeholders["error"] = str(err)
257  errors[CONF_HOST] = "cannot_connect"
258  except Exception as err:
259  _LOGGER.exception("Unexpected exception")
260  placeholders["error"] = str(err)
261  errors[CONF_HOST] = "unknown"
262  finally:
263  await host.stop()
264 
265  if not errors:
266  user_input[CONF_PORT] = host.api.port
267  user_input[CONF_USE_HTTPS] = host.api.use_https
268 
269  mac_address = format_mac(host.api.mac_address)
270  await self.async_set_unique_idasync_set_unique_id(mac_address, raise_on_progress=False)
271  if self.sourcesourcesourcesource == SOURCE_REAUTH:
272  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch()
273  return self.async_update_reload_and_abortasync_update_reload_and_abort(
274  entry=self._get_reauth_entry_get_reauth_entry(), data=user_input
275  )
276  if self.sourcesourcesourcesource == SOURCE_RECONFIGURE:
277  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch()
278  return self.async_update_reload_and_abortasync_update_reload_and_abort(
279  entry=self._get_reconfigure_entry_get_reconfigure_entry(), data=user_input
280  )
281  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates=user_input)
282 
283  return self.async_create_entryasync_create_entryasync_create_entry(
284  title=str(host.api.nvr_name),
285  data=user_input,
286  options=DEFAULT_OPTIONS,
287  )
288 
289  data_schema = vol.Schema(
290  {
291  vol.Required(CONF_USERNAME, default=self._username_username): str,
292  vol.Required(CONF_PASSWORD, default=self._password_password): str,
293  }
294  )
295  if self._host_host is None or self.sourcesourcesourcesource == SOURCE_RECONFIGURE or errors:
296  data_schema = data_schema.extend(
297  {
298  vol.Required(CONF_HOST, default=self._host_host): str,
299  }
300  )
301  if errors:
302  data_schema = data_schema.extend(
303  {
304  vol.Optional(CONF_PORT): cv.positive_int,
305  vol.Required(CONF_USE_HTTPS, default=False): bool,
306  }
307  )
308 
309  return self.async_show_formasync_show_formasync_show_form(
310  step_id="user",
311  data_schema=data_schema,
312  errors=errors,
313  description_placeholders=placeholders,
314  )
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)
None _abort_if_unique_id_mismatch(self, *str reason="unique_id_mismatch", 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)
str|None source(self)