Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for HERE Travel Time integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from here_routing import (
10  HERERoutingApi,
11  HERERoutingError,
12  HERERoutingUnauthorizedError,
13  Place,
14  TransportMode,
15 )
16 from here_transit import HERETransitError
17 import voluptuous as vol
18 
19 from homeassistant.config_entries import (
20  SOURCE_RECONFIGURE,
21  ConfigEntry,
22  ConfigFlow,
23  ConfigFlowResult,
24  OptionsFlow,
25 )
26 from homeassistant.const import (
27  CONF_API_KEY,
28  CONF_LATITUDE,
29  CONF_LONGITUDE,
30  CONF_MODE,
31  CONF_NAME,
32 )
33 from homeassistant.core import callback
36  EntitySelector,
37  LocationSelector,
38  TimeSelector,
39 )
40 
41 from .const import (
42  CONF_ARRIVAL_TIME,
43  CONF_DEPARTURE_TIME,
44  CONF_DESTINATION,
45  CONF_DESTINATION_ENTITY_ID,
46  CONF_DESTINATION_LATITUDE,
47  CONF_DESTINATION_LONGITUDE,
48  CONF_ORIGIN,
49  CONF_ORIGIN_ENTITY_ID,
50  CONF_ORIGIN_LATITUDE,
51  CONF_ORIGIN_LONGITUDE,
52  CONF_ROUTE_MODE,
53  DEFAULT_NAME,
54  DOMAIN,
55  ROUTE_MODE_FASTEST,
56  ROUTE_MODES,
57  TRAVEL_MODE_CAR,
58  TRAVEL_MODE_PUBLIC,
59  TRAVEL_MODES,
60 )
61 
62 _LOGGER = logging.getLogger(__name__)
63 
64 DEFAULT_OPTIONS = {
65  CONF_ROUTE_MODE: ROUTE_MODE_FASTEST,
66  CONF_ARRIVAL_TIME: None,
67  CONF_DEPARTURE_TIME: None,
68 }
69 
70 
71 async def async_validate_api_key(api_key: str) -> None:
72  """Validate the user input allows us to connect."""
73  known_working_origin = Place(latitude=38.9, longitude=-77.04833)
74  known_working_destination = Place(latitude=39.0, longitude=-77.1)
75 
76  await HERERoutingApi(api_key).route(
77  origin=known_working_origin,
78  destination=known_working_destination,
79  transport_mode=TransportMode.CAR,
80  )
81 
82 
83 def get_user_step_schema(data: Mapping[str, Any]) -> vol.Schema:
84  """Get a populated schema or default."""
85  travel_mode = data.get(CONF_MODE, TRAVEL_MODE_CAR)
86  if travel_mode == "publicTransportTimeTable":
87  travel_mode = TRAVEL_MODE_PUBLIC
88  return vol.Schema(
89  {
90  vol.Optional(
91  CONF_NAME, default=data.get(CONF_NAME, DEFAULT_NAME)
92  ): cv.string,
93  vol.Required(CONF_API_KEY, default=data.get(CONF_API_KEY)): cv.string,
94  vol.Optional(
95  CONF_MODE, default=data.get(CONF_MODE, TRAVEL_MODE_CAR)
96  ): vol.In(TRAVEL_MODES),
97  }
98  )
99 
100 
101 class HERETravelTimeConfigFlow(ConfigFlow, domain=DOMAIN):
102  """Handle a config flow for HERE Travel Time."""
103 
104  VERSION = 1
105 
106  def __init__(self) -> None:
107  """Init Config Flow."""
108  self._config: dict[str, Any] = {}
109 
110  @staticmethod
111  @callback
113  config_entry: ConfigEntry,
114  ) -> HERETravelTimeOptionsFlow:
115  """Get the options flow."""
117 
118  async def async_step_user(
119  self, user_input: dict[str, Any] | None = None
120  ) -> ConfigFlowResult:
121  """Handle the initial step."""
122  errors = {}
123  user_input = user_input or {}
124  if user_input:
125  try:
126  await async_validate_api_key(user_input[CONF_API_KEY])
127  except HERERoutingUnauthorizedError:
128  errors["base"] = "invalid_auth"
129  except (HERERoutingError, HERETransitError):
130  _LOGGER.exception("Unexpected exception")
131  errors["base"] = "unknown"
132  if not errors:
133  self._config[CONF_NAME] = user_input[CONF_NAME]
134  self._config[CONF_API_KEY] = user_input[CONF_API_KEY]
135  self._config[CONF_MODE] = user_input[CONF_MODE]
136  return await self.async_step_origin_menuasync_step_origin_menu()
137  return self.async_show_formasync_show_formasync_show_form(
138  step_id="user", data_schema=get_user_step_schema(user_input), errors=errors
139  )
140 
142  self, user_input: dict[str, Any] | None = None
143  ) -> ConfigFlowResult:
144  """Handle reconfiguration."""
145  return self.async_show_formasync_show_formasync_show_form(
146  step_id="user",
147  data_schema=get_user_step_schema(self._get_reconfigure_entry_get_reconfigure_entry().data),
148  )
149 
150  async def async_step_origin_menu(self, _: None = None) -> ConfigFlowResult:
151  """Show the origin menu."""
152  return self.async_show_menuasync_show_menu(
153  step_id="origin_menu",
154  menu_options=["origin_coordinates", "origin_entity"],
155  )
156 
158  self, user_input: dict[str, Any] | None = None
159  ) -> ConfigFlowResult:
160  """Configure origin by using gps coordinates."""
161  if user_input is not None:
162  self._config[CONF_ORIGIN_LATITUDE] = user_input[CONF_ORIGIN][CONF_LATITUDE]
163  self._config[CONF_ORIGIN_LONGITUDE] = user_input[CONF_ORIGIN][
164  CONF_LONGITUDE
165  ]
166  # Remove possible previous configuration using an entity_id
167  self._config.pop(CONF_ORIGIN_ENTITY_ID, None)
168  return await self.async_step_destination_menuasync_step_destination_menu()
169  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
170  vol.Schema(
171  {
172  vol.Required(
173  CONF_ORIGIN,
174  ): LocationSelector()
175  }
176  ),
177  {
178  CONF_ORIGIN: {
179  CONF_LATITUDE: self._config.get(CONF_ORIGIN_LATITUDE)
180  or self.hass.config.latitude,
181  CONF_LONGITUDE: self._config.get(CONF_ORIGIN_LONGITUDE)
182  or self.hass.config.longitude,
183  }
184  },
185  )
186  return self.async_show_formasync_show_formasync_show_form(step_id="origin_coordinates", data_schema=schema)
187 
189  self, user_input: dict[str, Any] | None = None
190  ) -> ConfigFlowResult:
191  """Configure origin by using an entity."""
192  if user_input is not None:
193  self._config[CONF_ORIGIN_ENTITY_ID] = user_input[CONF_ORIGIN_ENTITY_ID]
194  # Remove possible previous configuration using coordinates
195  self._config.pop(CONF_ORIGIN_LATITUDE, None)
196  self._config.pop(CONF_ORIGIN_LONGITUDE, None)
197  return await self.async_step_destination_menuasync_step_destination_menu()
198  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
199  vol.Schema(
200  {
201  vol.Required(
202  CONF_ORIGIN_ENTITY_ID,
203  ): EntitySelector()
204  }
205  ),
206  {CONF_ORIGIN_ENTITY_ID: self._config.get(CONF_ORIGIN_ENTITY_ID)},
207  )
208  return self.async_show_formasync_show_formasync_show_form(step_id="origin_entity", data_schema=schema)
209 
210  async def async_step_destination_menu(self, _: None = None) -> ConfigFlowResult:
211  """Show the destination menu."""
212  return self.async_show_menuasync_show_menu(
213  step_id="destination_menu",
214  menu_options=["destination_coordinates", "destination_entity"],
215  )
216 
218  self,
219  user_input: dict[str, Any] | None = None,
220  ) -> ConfigFlowResult:
221  """Configure destination by using gps coordinates."""
222  if user_input is not None:
223  self._config[CONF_DESTINATION_LATITUDE] = user_input[CONF_DESTINATION][
224  CONF_LATITUDE
225  ]
226  self._config[CONF_DESTINATION_LONGITUDE] = user_input[CONF_DESTINATION][
227  CONF_LONGITUDE
228  ]
229  # Remove possible previous configuration using an entity_id
230  self._config.pop(CONF_DESTINATION_ENTITY_ID, None)
231  if self.sourcesourcesourcesource == SOURCE_RECONFIGURE:
232  return self.async_update_reload_and_abortasync_update_reload_and_abort(
233  self._get_reconfigure_entry_get_reconfigure_entry(),
234  title=self._config[CONF_NAME],
235  data=self._config,
236  )
237  return self.async_create_entryasync_create_entryasync_create_entry(
238  title=self._config[CONF_NAME],
239  data=self._config,
240  options=DEFAULT_OPTIONS,
241  )
242  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
243  vol.Schema(
244  {
245  vol.Required(
246  CONF_DESTINATION,
247  ): LocationSelector()
248  }
249  ),
250  {
251  CONF_DESTINATION: {
252  CONF_LATITUDE: self._config.get(CONF_DESTINATION_LATITUDE)
253  or self.hass.config.latitude,
254  CONF_LONGITUDE: self._config.get(CONF_DESTINATION_LONGITUDE)
255  or self.hass.config.longitude,
256  },
257  },
258  )
259  return self.async_show_formasync_show_formasync_show_form(
260  step_id="destination_coordinates", data_schema=schema
261  )
262 
264  self,
265  user_input: dict[str, Any] | None = None,
266  ) -> ConfigFlowResult:
267  """Configure destination by using an entity."""
268  if user_input is not None:
269  self._config[CONF_DESTINATION_ENTITY_ID] = user_input[
270  CONF_DESTINATION_ENTITY_ID
271  ]
272  # Remove possible previous configuration using coordinates
273  self._config.pop(CONF_DESTINATION_LATITUDE, None)
274  self._config.pop(CONF_DESTINATION_LONGITUDE, None)
275  if self.sourcesourcesourcesource == SOURCE_RECONFIGURE:
276  return self.async_update_reload_and_abortasync_update_reload_and_abort(
277  self._get_reconfigure_entry_get_reconfigure_entry(), data=self._config
278  )
279  return self.async_create_entryasync_create_entryasync_create_entry(
280  title=self._config[CONF_NAME],
281  data=self._config,
282  options=DEFAULT_OPTIONS,
283  )
284  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
285  vol.Schema(
286  {
287  vol.Required(
288  CONF_DESTINATION_ENTITY_ID,
289  ): EntitySelector()
290  }
291  ),
292  {CONF_DESTINATION_ENTITY_ID: self._config.get(CONF_DESTINATION_ENTITY_ID)},
293  )
294  return self.async_show_formasync_show_formasync_show_form(step_id="destination_entity", data_schema=schema)
295 
296 
298  """Handle HERE Travel Time options."""
299 
300  def __init__(self) -> None:
301  """Initialize HERE Travel Time options flow."""
302  self._config_config: dict[str, Any] = {}
303 
304  async def async_step_init(
305  self, user_input: dict[str, Any] | None = None
306  ) -> ConfigFlowResult:
307  """Manage the HERE Travel Time options."""
308  if user_input is not None:
309  self._config_config = user_input
310  return await self.async_step_time_menuasync_step_time_menu()
311 
312  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
313  vol.Schema(
314  {
315  vol.Optional(
316  CONF_ROUTE_MODE,
317  default=self.config_entryconfig_entryconfig_entry.options.get(
318  CONF_ROUTE_MODE, DEFAULT_OPTIONS[CONF_ROUTE_MODE]
319  ),
320  ): vol.In(ROUTE_MODES),
321  }
322  ),
323  {
324  CONF_ROUTE_MODE: self.config_entryconfig_entryconfig_entry.options.get(
325  CONF_ROUTE_MODE, DEFAULT_OPTIONS[CONF_ROUTE_MODE]
326  ),
327  },
328  )
329 
330  return self.async_show_formasync_show_form(step_id="init", data_schema=schema)
331 
332  async def async_step_time_menu(self, _: None = None) -> ConfigFlowResult:
333  """Show the time menu."""
334  return self.async_show_menuasync_show_menu(
335  step_id="time_menu",
336  menu_options=["departure_time", "arrival_time", "no_time"],
337  )
338 
340  self, user_input: dict[str, Any] | None = None
341  ) -> ConfigFlowResult:
342  """Create Options Entry."""
343  return self.async_create_entryasync_create_entry(title="", data=self._config_config)
344 
346  self, user_input: dict[str, Any] | None = None
347  ) -> ConfigFlowResult:
348  """Configure arrival time."""
349  if user_input is not None:
350  self._config_config[CONF_ARRIVAL_TIME] = user_input[CONF_ARRIVAL_TIME]
351  return self.async_create_entryasync_create_entry(title="", data=self._config_config)
352 
353  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
354  vol.Schema(
355  {vol.Required(CONF_ARRIVAL_TIME, default="00:00:00"): TimeSelector()}
356  ),
357  {CONF_ARRIVAL_TIME: "00:00:00"},
358  )
359 
360  return self.async_show_formasync_show_form(step_id="arrival_time", data_schema=schema)
361 
363  self, user_input: dict[str, Any] | None = None
364  ) -> ConfigFlowResult:
365  """Configure departure time."""
366  if user_input is not None:
367  self._config_config[CONF_DEPARTURE_TIME] = user_input[CONF_DEPARTURE_TIME]
368  return self.async_create_entryasync_create_entry(title="", data=self._config_config)
369 
370  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
371  vol.Schema(
372  {vol.Required(CONF_DEPARTURE_TIME, default="00:00:00"): TimeSelector()}
373  ),
374  {CONF_DEPARTURE_TIME: "00:00:00"},
375  )
376 
377  return self.async_show_formasync_show_form(step_id="departure_time", data_schema=schema)
ConfigFlowResult async_step_destination_coordinates(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:220
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:120
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:143
HERETravelTimeOptionsFlow async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:114
ConfigFlowResult async_step_origin_coordinates(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:159
ConfigFlowResult async_step_origin_entity(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:190
ConfigFlowResult async_step_destination_entity(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:266
ConfigFlowResult async_step_departure_time(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:364
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:306
ConfigFlowResult async_step_arrival_time(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:347
ConfigFlowResult async_step_no_time(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:341
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_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)
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_show_menu(self, *str|None step_id=None, Container[str] menu_options, Mapping[str, str]|None description_placeholders=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)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
vol.Schema get_user_step_schema(Mapping[str, Any] data)
Definition: config_flow.py:83