Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for BMW ConnectedDrive integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from bimmer_connected.api.authentication import MyBMWAuthentication
9 from bimmer_connected.api.regions import get_region_from_name
10 from bimmer_connected.models import (
11  MyBMWAPIError,
12  MyBMWAuthError,
13  MyBMWCaptchaMissingError,
14 )
15 from httpx import RequestError
16 import voluptuous as vol
17 
18 from homeassistant.config_entries import (
19  SOURCE_REAUTH,
20  SOURCE_RECONFIGURE,
21  ConfigEntry,
22  ConfigFlow,
23  ConfigFlowResult,
24  OptionsFlow,
25 )
26 from homeassistant.const import CONF_PASSWORD, CONF_REGION, CONF_SOURCE, CONF_USERNAME
27 from homeassistant.core import HomeAssistant, callback
28 from homeassistant.exceptions import HomeAssistantError
29 from homeassistant.helpers.selector import SelectSelector, SelectSelectorConfig
30 from homeassistant.util.ssl import get_default_context
31 
32 from . import DOMAIN
33 from .const import (
34  CONF_ALLOWED_REGIONS,
35  CONF_CAPTCHA_REGIONS,
36  CONF_CAPTCHA_TOKEN,
37  CONF_CAPTCHA_URL,
38  CONF_GCID,
39  CONF_READ_ONLY,
40  CONF_REFRESH_TOKEN,
41 )
42 
43 DATA_SCHEMA = vol.Schema(
44  {
45  vol.Required(CONF_USERNAME): str,
46  vol.Required(CONF_PASSWORD): str,
47  vol.Required(CONF_REGION): SelectSelector(
49  options=CONF_ALLOWED_REGIONS,
50  translation_key="regions",
51  )
52  ),
53  },
54  extra=vol.REMOVE_EXTRA,
55 )
56 CAPTCHA_SCHEMA = vol.Schema(
57  {
58  vol.Required(CONF_CAPTCHA_TOKEN): str,
59  },
60  extra=vol.REMOVE_EXTRA,
61 )
62 
63 
64 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, str]:
65  """Validate the user input allows us to connect.
66 
67  Data has the keys from DATA_SCHEMA with values provided by the user.
68  """
69  auth = MyBMWAuthentication(
70  data[CONF_USERNAME],
71  data[CONF_PASSWORD],
72  get_region_from_name(data[CONF_REGION]),
73  hcaptcha_token=data.get(CONF_CAPTCHA_TOKEN),
74  verify=get_default_context(),
75  )
76 
77  try:
78  await auth.login()
79  except MyBMWCaptchaMissingError as ex:
80  raise MissingCaptcha from ex
81  except MyBMWAuthError as ex:
82  raise InvalidAuth from ex
83  except (MyBMWAPIError, RequestError) as ex:
84  raise CannotConnect from ex
85 
86  # Return info that you want to store in the config entry.
87  retval = {"title": f"{data[CONF_USERNAME]}{data.get(CONF_SOURCE, '')}"}
88  if auth.refresh_token:
89  retval[CONF_REFRESH_TOKEN] = auth.refresh_token
90  if auth.gcid:
91  retval[CONF_GCID] = auth.gcid
92  return retval
93 
94 
95 class BMWConfigFlow(ConfigFlow, domain=DOMAIN):
96  """Handle a config flow for MyBMW."""
97 
98  VERSION = 1
99 
100  data: dict[str, Any] = {}
101 
102  _existing_entry_data: Mapping[str, Any] | None = None
103 
104  async def async_step_user(
105  self, user_input: dict[str, Any] | None = None
106  ) -> ConfigFlowResult:
107  """Handle the initial step."""
108  errors: dict[str, str] = self.data.pop("errors", {})
109 
110  if user_input is not None and not errors:
111  unique_id = f"{user_input[CONF_REGION]}-{user_input[CONF_USERNAME]}"
112  await self.async_set_unique_idasync_set_unique_id(unique_id)
113 
114  if self.sourcesourcesourcesource in {SOURCE_REAUTH, SOURCE_RECONFIGURE}:
115  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch(reason="account_mismatch")
116  else:
117  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
118 
119  # Store user input for later use
120  self.data.update(user_input)
121 
122  # North America and Rest of World require captcha token
123  if (
124  self.data.get(CONF_REGION) in CONF_CAPTCHA_REGIONS
125  and CONF_CAPTCHA_TOKEN not in self.data
126  ):
127  return await self.async_step_captcha()
128 
129  info = None
130  try:
131  info = await validate_input(self.hass, self.data)
132  except MissingCaptcha:
133  errors["base"] = "missing_captcha"
134  except CannotConnect:
135  errors["base"] = "cannot_connect"
136  except InvalidAuth:
137  errors["base"] = "invalid_auth"
138  finally:
139  self.data.pop(CONF_CAPTCHA_TOKEN, None)
140 
141  if info:
142  entry_data = {
143  **self.data,
144  CONF_REFRESH_TOKEN: info.get(CONF_REFRESH_TOKEN),
145  CONF_GCID: info.get(CONF_GCID),
146  }
147 
148  if self.sourcesourcesourcesource == SOURCE_REAUTH:
149  return self.async_update_reload_and_abortasync_update_reload_and_abort(
150  self._get_reauth_entry_get_reauth_entry(), data=entry_data
151  )
152  if self.sourcesourcesourcesource == SOURCE_RECONFIGURE:
153  return self.async_update_reload_and_abortasync_update_reload_and_abort(
154  self._get_reconfigure_entry_get_reconfigure_entry(),
155  data=entry_data,
156  )
157  return self.async_create_entryasync_create_entryasync_create_entry(
158  title=info["title"],
159  data=entry_data,
160  )
161 
162  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
163  DATA_SCHEMA,
164  self._existing_entry_data_existing_entry_data or self.data,
165  )
166 
167  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=schema, errors=errors)
168 
169  async def async_step_reauth(
170  self, entry_data: Mapping[str, Any]
171  ) -> ConfigFlowResult:
172  """Handle configuration by re-auth."""
173  self._existing_entry_data_existing_entry_data = entry_data
174  return await self.async_step_userasync_step_userasync_step_user()
175 
176  async def async_step_reconfigure(
177  self, user_input: dict[str, Any] | None = None
178  ) -> ConfigFlowResult:
179  """Handle a reconfiguration flow initialized by the user."""
180  self._existing_entry_data_existing_entry_data = self._get_reconfigure_entry_get_reconfigure_entry().data
181  return await self.async_step_userasync_step_userasync_step_user()
182 
183  async def async_step_captcha(
184  self, user_input: dict[str, Any] | None = None
185  ) -> ConfigFlowResult:
186  """Show captcha form."""
187  if user_input and user_input.get(CONF_CAPTCHA_TOKEN):
188  self.data[CONF_CAPTCHA_TOKEN] = user_input[CONF_CAPTCHA_TOKEN].strip()
189  return await self.async_step_userasync_step_userasync_step_user(self.data)
190 
191  return self.async_show_formasync_show_formasync_show_form(
192  step_id="captcha",
193  data_schema=CAPTCHA_SCHEMA,
194  description_placeholders={
195  "captcha_url": CONF_CAPTCHA_URL.format(region=self.data[CONF_REGION])
196  },
197  )
198 
199  @staticmethod
200  @callback
202  config_entry: ConfigEntry,
203  ) -> BMWOptionsFlow:
204  """Return a MyBMW option flow."""
205  return BMWOptionsFlow()
206 
207 
209  """Handle a option flow for MyBMW."""
210 
211  async def async_step_init(
212  self, user_input: dict[str, Any] | None = None
213  ) -> ConfigFlowResult:
214  """Manage the options."""
215  return await self.async_step_account_options()
216 
217  async def async_step_account_options(
218  self, user_input: dict[str, Any] | None = None
219  ) -> ConfigFlowResult:
220  """Handle the initial step."""
221  if user_input is not None:
222  # Manually update & reload the config entry after options change.
223  # Required as each successful login will store the latest refresh_token
224  # using async_update_entry, which would otherwise trigger a full reload
225  # if the options would be refreshed using a listener.
226  changed = self.hass.config_entries.async_update_entry(
227  self.config_entryconfig_entryconfig_entry,
228  options=user_input,
229  )
230  if changed:
231  await self.hass.config_entries.async_reload(self.config_entryconfig_entryconfig_entry.entry_id)
232  return self.async_create_entryasync_create_entry(title="", data=user_input)
233  return self.async_show_formasync_show_form(
234  step_id="account_options",
235  data_schema=vol.Schema(
236  {
237  vol.Optional(
238  CONF_READ_ONLY,
239  default=self.config_entryconfig_entryconfig_entry.options.get(CONF_READ_ONLY, False),
240  ): bool,
241  }
242  ),
243  )
244 
245 
247  """Error to indicate we cannot connect."""
248 
249 
250 class InvalidAuth(HomeAssistantError):
251  """Error to indicate there is invalid auth."""
252 
253 
255  """Error to indicate the captcha token is missing."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:106
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:213
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)
OptionsFlow async_get_options_flow(ConfigEntry config_entry)
None config_entry(self, ConfigEntry value)
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)
dict[str, str] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:64
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
ssl.SSLContext get_default_context()
Definition: ssl.py:118