Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Enphase Envoy integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import TYPE_CHECKING, Any
8 
9 from awesomeversion import AwesomeVersion
10 from pyenphase import AUTH_TOKEN_MIN_VERSION, Envoy, EnvoyError
11 import voluptuous as vol
12 
13 from homeassistant.components import zeroconf
14 from homeassistant.config_entries import (
15  SOURCE_REAUTH,
16  ConfigEntry,
17  ConfigFlow,
18  ConfigFlowResult,
19  OptionsFlow,
20 )
21 from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
22 from homeassistant.core import HomeAssistant, callback
23 from homeassistant.helpers.httpx_client import get_async_client
24 from homeassistant.helpers.typing import VolDictType
25 
26 from .const import (
27  DOMAIN,
28  INVALID_AUTH_ERRORS,
29  OPTION_DIAGNOSTICS_INCLUDE_FIXTURES,
30  OPTION_DIAGNOSTICS_INCLUDE_FIXTURES_DEFAULT_VALUE,
31  OPTION_DISABLE_KEEP_ALIVE,
32  OPTION_DISABLE_KEEP_ALIVE_DEFAULT_VALUE,
33 )
34 
35 _LOGGER = logging.getLogger(__name__)
36 
37 ENVOY = "Envoy"
38 
39 CONF_SERIAL = "serial"
40 
41 INSTALLER_AUTH_USERNAME = "installer"
42 
43 
44 async def validate_input(
45  hass: HomeAssistant, host: str, username: str, password: str
46 ) -> Envoy:
47  """Validate the user input allows us to connect."""
48  envoy = Envoy(host, get_async_client(hass, verify_ssl=False))
49  await envoy.setup()
50  await envoy.authenticate(username=username, password=password)
51  return envoy
52 
53 
54 class EnphaseConfigFlow(ConfigFlow, domain=DOMAIN):
55  """Handle a config flow for Enphase Envoy."""
56 
57  VERSION = 1
58 
59  _reauth_entry: ConfigEntry
60 
61  def __init__(self) -> None:
62  """Initialize an envoy flow."""
63  self.ip_addressip_address: str | None = None
64  self.usernameusername = None
65  self.protoversprotovers: str | None = None
66 
67  @staticmethod
68  @callback
70  config_entry: ConfigEntry,
71  ) -> EnvoyOptionsFlowHandler:
72  """Options flow handler for Enphase_Envoy."""
74 
75  @callback
76  def _async_generate_schema(self) -> vol.Schema:
77  """Generate schema."""
78  schema: VolDictType = {}
79 
80  if self.ip_addressip_address:
81  schema[vol.Required(CONF_HOST, default=self.ip_addressip_address)] = vol.In(
82  [self.ip_addressip_address]
83  )
84  elif self.sourcesourcesourcesource != SOURCE_REAUTH:
85  schema[vol.Required(CONF_HOST)] = str
86 
87  default_username = ""
88  if (
89  not self.usernameusername
90  and self.protoversprotovers
91  and AwesomeVersion(self.protoversprotovers) < AUTH_TOKEN_MIN_VERSION
92  ):
93  default_username = INSTALLER_AUTH_USERNAME
94 
95  schema[
96  vol.Optional(CONF_USERNAME, default=self.usernameusername or default_username)
97  ] = str
98  schema[vol.Optional(CONF_PASSWORD, default="")] = str
99 
100  return vol.Schema(schema)
101 
102  @callback
103  def _async_current_hosts(self) -> set[str]:
104  """Return a set of hosts."""
105  return {
106  entry.data[CONF_HOST]
107  for entry in self._async_current_entries_async_current_entries(include_ignore=False)
108  if CONF_HOST in entry.data
109  }
110 
112  self, discovery_info: zeroconf.ZeroconfServiceInfo
113  ) -> ConfigFlowResult:
114  """Handle a flow initialized by zeroconf discovery."""
115  if _LOGGER.isEnabledFor(logging.DEBUG):
116  current_hosts = self._async_current_hosts_async_current_hosts()
117  _LOGGER.debug(
118  "Zeroconf ip %s processing %s, current hosts: %s",
119  discovery_info.ip_address.version,
120  discovery_info.host,
121  current_hosts,
122  )
123  if discovery_info.ip_address.version != 4:
124  return self.async_abortasync_abortasync_abort(reason="not_ipv4_address")
125  serial = discovery_info.properties["serialnum"]
126  self.protoversprotovers = discovery_info.properties.get("protovers")
127  await self.async_set_unique_idasync_set_unique_id(serial)
128  self.ip_addressip_address = discovery_info.host
129  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_HOST: self.ip_addressip_address})
130  _LOGGER.debug(
131  "Zeroconf ip %s, fw %s, no existing entry with serial %s",
132  self.ip_addressip_address,
133  self.protoversprotovers,
134  serial,
135  )
136  for entry in self._async_current_entries_async_current_entries(include_ignore=False):
137  if (
138  entry.unique_id is None
139  and CONF_HOST in entry.data
140  and entry.data[CONF_HOST] == self.ip_addressip_address
141  ):
142  _LOGGER.debug(
143  "Zeroconf update envoy with this ip and blank serial in unique_id",
144  )
145  title = f"{ENVOY} {serial}" if entry.title == ENVOY else ENVOY
146  return self.async_update_reload_and_abortasync_update_reload_and_abort(
147  entry, title=title, unique_id=serial, reason="already_configured"
148  )
149 
150  _LOGGER.debug("Zeroconf ip %s to step user", self.ip_addressip_address)
151  return await self.async_step_userasync_step_userasync_step_user()
152 
153  async def async_step_reauth(
154  self, entry_data: Mapping[str, Any]
155  ) -> ConfigFlowResult:
156  """Handle configuration by re-auth."""
157  self._reauth_entry_reauth_entry = self._get_reauth_entry_get_reauth_entry()
158  if unique_id := self._reauth_entry_reauth_entry.unique_id:
159  await self.async_set_unique_idasync_set_unique_id(unique_id, raise_on_progress=False)
160  return await self.async_step_userasync_step_userasync_step_user()
161 
162  def _async_envoy_name(self) -> str:
163  """Return the name of the envoy."""
164  return f"{ENVOY} {self.unique_id}" if self.unique_idunique_id else ENVOY
165 
166  async def async_step_user(
167  self, user_input: dict[str, Any] | None = None
168  ) -> ConfigFlowResult:
169  """Handle the initial step."""
170  errors: dict[str, str] = {}
171  description_placeholders: dict[str, str] = {}
172 
173  if self.sourcesourcesourcesource == SOURCE_REAUTH:
174  host = self._reauth_entry_reauth_entry.data[CONF_HOST]
175  else:
176  host = (user_input or {}).get(CONF_HOST) or self.ip_addressip_address or ""
177 
178  if user_input is not None:
179  try:
180  envoy = await validate_input(
181  self.hass,
182  host,
183  user_input[CONF_USERNAME],
184  user_input[CONF_PASSWORD],
185  )
186  except INVALID_AUTH_ERRORS as e:
187  errors["base"] = "invalid_auth"
188  description_placeholders = {"reason": str(e)}
189  except EnvoyError as e:
190  errors["base"] = "cannot_connect"
191  description_placeholders = {"reason": str(e)}
192  except Exception:
193  _LOGGER.exception("Unexpected exception")
194  errors["base"] = "unknown"
195  else:
196  name = self._async_envoy_name_async_envoy_name()
197 
198  if self.sourcesourcesourcesource == SOURCE_REAUTH:
199  return self.async_update_reload_and_abortasync_update_reload_and_abort(
200  self._reauth_entry_reauth_entry,
201  data=self._reauth_entry_reauth_entry.data | user_input,
202  )
203 
204  if not self.unique_idunique_id:
205  await self.async_set_unique_idasync_set_unique_id(envoy.serial_number)
206  name = self._async_envoy_name_async_envoy_name()
207 
208  if self.unique_idunique_id:
209  # If envoy exists in configuration update fields and exit
210  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
211  {
212  CONF_HOST: host,
213  CONF_USERNAME: user_input[CONF_USERNAME],
214  CONF_PASSWORD: user_input[CONF_PASSWORD],
215  },
216  error="reauth_successful",
217  )
218 
219  # CONF_NAME is still set for legacy backwards compatibility
220  return self.async_create_entryasync_create_entryasync_create_entry(
221  title=name, data={CONF_HOST: host, CONF_NAME: name} | user_input
222  )
223 
224  if self.unique_idunique_id:
225  self.context["title_placeholders"] = {
226  CONF_SERIAL: self.unique_idunique_id,
227  CONF_HOST: host,
228  }
229 
230  return self.async_show_formasync_show_formasync_show_form(
231  step_id="user",
232  data_schema=self._async_generate_schema_async_generate_schema(),
233  description_placeholders=description_placeholders,
234  errors=errors,
235  )
236 
238  self, user_input: dict[str, Any] | None = None
239  ) -> ConfigFlowResult:
240  """Add reconfigure step to allow to manually reconfigure a config entry."""
241  reconfigure_entry = self._get_reconfigure_entry_get_reconfigure_entry()
242  errors: dict[str, str] = {}
243  description_placeholders: dict[str, str] = {}
244 
245  if user_input is not None:
246  host: str = user_input[CONF_HOST]
247  username: str = user_input[CONF_USERNAME]
248  password: str = user_input[CONF_PASSWORD]
249  try:
250  envoy = await validate_input(
251  self.hass,
252  host,
253  username,
254  password,
255  )
256  except INVALID_AUTH_ERRORS as e:
257  errors["base"] = "invalid_auth"
258  description_placeholders = {"reason": str(e)}
259  except EnvoyError as e:
260  errors["base"] = "cannot_connect"
261  description_placeholders = {"reason": str(e)}
262  except Exception: # pylint: disable=broad-except
263  _LOGGER.exception("Unexpected exception")
264  errors["base"] = "unknown"
265  else:
266  await self.async_set_unique_idasync_set_unique_id(envoy.serial_number)
267  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch()
268  return self.async_update_reload_and_abortasync_update_reload_and_abort(
269  reconfigure_entry,
270  data_updates={
271  CONF_HOST: host,
272  CONF_USERNAME: username,
273  CONF_PASSWORD: password,
274  },
275  )
276 
277  self.context["title_placeholders"] = {
278  CONF_SERIAL: reconfigure_entry.unique_id or "-",
279  CONF_HOST: reconfigure_entry.data[CONF_HOST],
280  }
281 
282  suggested_values: Mapping[str, Any] = user_input or reconfigure_entry.data
283  return self.async_show_formasync_show_formasync_show_form(
284  step_id="reconfigure",
285  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
286  self._async_generate_schema_async_generate_schema(), suggested_values
287  ),
288  description_placeholders=description_placeholders,
289  errors=errors,
290  )
291 
292 
294  """Envoy config flow options handler."""
295 
296  async def async_step_init(
297  self, user_input: dict[str, Any] | None = None
298  ) -> ConfigFlowResult:
299  """Manage the options."""
300  if user_input is not None:
301  return self.async_create_entryasync_create_entry(title="", data=user_input)
302 
303  if TYPE_CHECKING:
304  assert self.config_entryconfig_entryconfig_entry.unique_id is not None
305 
306  return self.async_show_formasync_show_form(
307  step_id="init",
308  data_schema=vol.Schema(
309  {
310  vol.Required(
311  OPTION_DIAGNOSTICS_INCLUDE_FIXTURES,
312  default=self.config_entryconfig_entryconfig_entry.options.get(
313  OPTION_DIAGNOSTICS_INCLUDE_FIXTURES,
314  OPTION_DIAGNOSTICS_INCLUDE_FIXTURES_DEFAULT_VALUE,
315  ),
316  ): bool,
317  vol.Required(
318  OPTION_DISABLE_KEEP_ALIVE,
319  default=self.config_entryconfig_entryconfig_entry.options.get(
320  OPTION_DISABLE_KEEP_ALIVE,
321  OPTION_DISABLE_KEEP_ALIVE_DEFAULT_VALUE,
322  ),
323  ): bool,
324  }
325  ),
326  description_placeholders={
327  CONF_SERIAL: self.config_entryconfig_entryconfig_entry.unique_id,
328  CONF_HOST: self.config_entryconfig_entryconfig_entry.data[CONF_HOST],
329  },
330  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:168
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:239
EnvoyOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:71
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:155
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:113
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:298
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)
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)
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
vol.Schema add_suggested_values_to_schema(self, vol.Schema data_schema, Mapping[str, Any]|None suggested_values)
_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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
Envoy validate_input(HomeAssistant hass, str host, str username, str password)
Definition: config_flow.py:46
httpx.AsyncClient get_async_client(HomeAssistant hass, bool verify_ssl=True)
Definition: httpx_client.py:41