Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Subaru integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import datetime
6 import logging
7 from typing import TYPE_CHECKING, Any
8 
9 from subarulink import (
10  Controller as SubaruAPI,
11  InvalidCredentials,
12  InvalidPIN,
13  SubaruException,
14 )
15 from subarulink.const import COUNTRY_CAN, COUNTRY_USA
16 import voluptuous as vol
17 
18 from homeassistant.config_entries import (
19  ConfigEntry,
20  ConfigFlow,
21  ConfigFlowResult,
22  OptionsFlow,
23 )
24 from homeassistant.const import (
25  CONF_COUNTRY,
26  CONF_DEVICE_ID,
27  CONF_PASSWORD,
28  CONF_PIN,
29  CONF_USERNAME,
30 )
31 from homeassistant.core import callback
32 from homeassistant.helpers import aiohttp_client, config_validation as cv
33 
34 from .const import CONF_UPDATE_ENABLED, DOMAIN
35 
36 _LOGGER = logging.getLogger(__name__)
37 CONF_CONTACT_METHOD = "contact_method"
38 CONF_VALIDATION_CODE = "validation_code"
39 PIN_SCHEMA = vol.Schema({vol.Required(CONF_PIN): str})
40 
41 
42 class SubaruConfigFlow(ConfigFlow, domain=DOMAIN):
43  """Handle a config flow for Subaru."""
44 
45  VERSION = 1
46 
47  def __init__(self) -> None:
48  """Initialize config flow."""
49  self.config_data: dict[str, Any] = {CONF_PIN: None}
50  self.controllercontroller: SubaruAPI | None = None
51 
52  async def async_step_user(
53  self, user_input: dict[str, Any] | None = None
54  ) -> ConfigFlowResult:
55  """Handle the start of the config flow."""
56  error = None
57 
58  if user_input:
59  self._async_abort_entries_match_async_abort_entries_match({CONF_USERNAME: user_input[CONF_USERNAME]})
60 
61  try:
62  await self.validate_login_credsvalidate_login_creds(user_input)
63  except InvalidCredentials:
64  error = {"base": "invalid_auth"}
65  except SubaruException as ex:
66  _LOGGER.error("Unable to communicate with Subaru API: %s", ex.message)
67  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
68  else:
69  if TYPE_CHECKING:
70  assert self.controllercontroller
71  if not self.controllercontroller.device_registered:
72  _LOGGER.debug("2FA validation is required")
73  return await self.async_step_two_factorasync_step_two_factor()
74  if self.controllercontroller.is_pin_required():
75  return await self.async_step_pinasync_step_pin()
76  return self.async_create_entryasync_create_entryasync_create_entry(
77  title=user_input[CONF_USERNAME], data=self.config_data
78  )
79 
80  return self.async_show_formasync_show_formasync_show_form(
81  step_id="user",
82  data_schema=vol.Schema(
83  {
84  vol.Required(
85  CONF_USERNAME,
86  default=user_input.get(CONF_USERNAME) if user_input else "",
87  ): str,
88  vol.Required(
89  CONF_PASSWORD,
90  default=user_input.get(CONF_PASSWORD) if user_input else "",
91  ): str,
92  vol.Required(
93  CONF_COUNTRY,
94  default=user_input.get(CONF_COUNTRY)
95  if user_input
96  else COUNTRY_USA,
97  ): vol.In([COUNTRY_CAN, COUNTRY_USA]),
98  }
99  ),
100  errors=error,
101  )
102 
103  @staticmethod
104  @callback
106  config_entry: ConfigEntry,
107  ) -> OptionsFlowHandler:
108  """Get the options flow for this handler."""
109  return OptionsFlowHandler()
110 
111  async def validate_login_creds(self, data):
112  """Validate the user input allows us to connect.
113 
114  data: contains values provided by the user.
115  """
116  websession = aiohttp_client.async_get_clientsession(self.hass)
117  now = datetime.now()
118  if not data.get(CONF_DEVICE_ID):
119  data[CONF_DEVICE_ID] = int(now.timestamp())
120  date = now.strftime("%Y-%m-%d")
121  device_name = "Home Assistant: Added " + date
122 
123  self.controllercontroller = SubaruAPI(
124  websession,
125  username=data[CONF_USERNAME],
126  password=data[CONF_PASSWORD],
127  device_id=data[CONF_DEVICE_ID],
128  pin=None,
129  device_name=device_name,
130  country=data[CONF_COUNTRY],
131  )
132  _LOGGER.debug("Setting up first time connection to Subaru API")
133  if await self.controllercontroller.connect():
134  _LOGGER.debug("Successfully authenticated with Subaru API")
135  self.config_data.update(data)
136 
138  self, user_input: dict[str, Any] | None = None
139  ) -> ConfigFlowResult:
140  """Select contact method and request 2FA code from Subaru."""
141  error = None
142  if TYPE_CHECKING:
143  assert self.controllercontroller
144  if user_input:
145  # self.controller.contact_methods is a dict:
146  # {"phone":"555-555-5555", "userName":"my@email.com"}
147  selected_method = next(
148  k
149  for k, v in self.controllercontroller.contact_methods.items()
150  if v == user_input[CONF_CONTACT_METHOD]
151  )
152  if await self.controllercontroller.request_auth_code(selected_method):
153  return await self.async_step_two_factor_validateasync_step_two_factor_validate()
154  return self.async_abortasync_abortasync_abort(reason="two_factor_request_failed")
155 
156  data_schema = vol.Schema(
157  {
158  vol.Required(CONF_CONTACT_METHOD): vol.In(
159  list(self.controllercontroller.contact_methods.values())
160  )
161  }
162  )
163  return self.async_show_formasync_show_formasync_show_form(
164  step_id="two_factor", data_schema=data_schema, errors=error
165  )
166 
168  self, user_input: dict[str, Any] | None = None
169  ) -> ConfigFlowResult:
170  """Validate received 2FA code with Subaru."""
171  error = None
172  if TYPE_CHECKING:
173  assert self.controllercontroller
174  if user_input:
175  try:
176  vol.Match(r"^[0-9]{6}$")(user_input[CONF_VALIDATION_CODE])
177  if await self.controllercontroller.submit_auth_code(
178  user_input[CONF_VALIDATION_CODE]
179  ):
180  if self.controllercontroller.is_pin_required():
181  return await self.async_step_pinasync_step_pin()
182  return self.async_create_entryasync_create_entryasync_create_entry(
183  title=self.config_data[CONF_USERNAME], data=self.config_data
184  )
185  error = {"base": "incorrect_validation_code"}
186  except vol.Invalid:
187  error = {"base": "bad_validation_code_format"}
188 
189  data_schema = vol.Schema({vol.Required(CONF_VALIDATION_CODE): str})
190  return self.async_show_formasync_show_formasync_show_form(
191  step_id="two_factor_validate", data_schema=data_schema, errors=error
192  )
193 
194  async def async_step_pin(
195  self, user_input: dict[str, Any] | None = None
196  ) -> ConfigFlowResult:
197  """Handle second part of config flow, if required."""
198  error = None
199  if TYPE_CHECKING:
200  assert self.controllercontroller
201  if user_input and self.controllercontroller.update_saved_pin(user_input[CONF_PIN]):
202  try:
203  vol.Match(r"[0-9]{4}")(user_input[CONF_PIN])
204  await self.controllercontroller.test_pin()
205  except vol.Invalid:
206  error = {"base": "bad_pin_format"}
207  except InvalidPIN:
208  error = {"base": "incorrect_pin"}
209  else:
210  _LOGGER.debug("PIN successfully tested")
211  self.config_data.update(user_input)
212  return self.async_create_entryasync_create_entryasync_create_entry(
213  title=self.config_data[CONF_USERNAME], data=self.config_data
214  )
215  return self.async_show_formasync_show_formasync_show_form(step_id="pin", data_schema=PIN_SCHEMA, errors=error)
216 
217 
219  """Handle a option flow for Subaru."""
220 
221  async def async_step_init(
222  self, user_input: dict[str, Any] | None = None
223  ) -> ConfigFlowResult:
224  """Handle options flow."""
225  if user_input is not None:
226  return self.async_create_entryasync_create_entry(title="", data=user_input)
227 
228  data_schema = vol.Schema(
229  {
230  vol.Required(
231  CONF_UPDATE_ENABLED,
232  default=self.config_entryconfig_entryconfig_entry.options.get(CONF_UPDATE_ENABLED, False),
233  ): cv.boolean,
234  }
235  )
236  return self.async_show_formasync_show_form(step_id="init", data_schema=data_schema)
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:223
ConfigFlowResult async_step_two_factor(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:139
ConfigFlowResult async_step_pin(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:196
ConfigFlowResult async_step_two_factor_validate(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:169
OptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:107
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:54
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_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
IssData update(pyiss.ISS iss)
Definition: __init__.py:33