Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Tankerkoenig."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from aiotankerkoenig import (
9  GasType,
10  Sort,
11  Station,
12  Tankerkoenig,
13  TankerkoenigInvalidKeyError,
14 )
15 import voluptuous as vol
16 
17 from homeassistant.config_entries import (
18  ConfigEntry,
19  ConfigFlow,
20  ConfigFlowResult,
21  OptionsFlow,
22 )
23 from homeassistant.const import (
24  CONF_API_KEY,
25  CONF_LATITUDE,
26  CONF_LOCATION,
27  CONF_LONGITUDE,
28  CONF_NAME,
29  CONF_RADIUS,
30  CONF_SHOW_ON_MAP,
31  UnitOfLength,
32 )
33 from homeassistant.core import callback
34 from homeassistant.helpers.aiohttp_client import async_get_clientsession
37  LocationSelector,
38  NumberSelector,
39  NumberSelectorConfig,
40 )
41 
42 from .const import CONF_FUEL_TYPES, CONF_STATIONS, DEFAULT_RADIUS, DOMAIN, FUEL_TYPES
43 
44 
46  tankerkoenig: Tankerkoenig, data: Mapping[str, Any]
47 ) -> list[Station]:
48  """Fetch nearby stations."""
49  return await tankerkoenig.nearby_stations(
50  coordinates=(
51  data[CONF_LOCATION][CONF_LATITUDE],
52  data[CONF_LOCATION][CONF_LONGITUDE],
53  ),
54  radius=data[CONF_RADIUS],
55  gas_type=GasType.ALL,
56  sort=Sort.DISTANCE,
57  )
58 
59 
60 class FlowHandler(ConfigFlow, domain=DOMAIN):
61  """Handle a config flow."""
62 
63  VERSION = 1
64 
65  def __init__(self) -> None:
66  """Init the FlowHandler."""
67  super().__init__()
68  self._data_data: dict[str, Any] = {}
69  self._stations: dict[str, str] = {}
70 
71  @staticmethod
72  @callback
74  config_entry: ConfigEntry,
75  ) -> OptionsFlowHandler:
76  """Get the options flow for this handler."""
77  return OptionsFlowHandler()
78 
79  async def async_step_user(
80  self, user_input: dict[str, Any] | None = None
81  ) -> ConfigFlowResult:
82  """Handle a flow initialized by the user."""
83  if not user_input:
84  return self._show_form_user_show_form_user()
85 
86  await self.async_set_unique_idasync_set_unique_id(
87  f"{user_input[CONF_LOCATION][CONF_LATITUDE]}_{user_input[CONF_LOCATION][CONF_LONGITUDE]}"
88  )
89  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
90 
91  tankerkoenig = Tankerkoenig(
92  api_key=user_input[CONF_API_KEY],
93  session=async_get_clientsession(self.hass),
94  )
95  try:
96  stations = await async_get_nearby_stations(tankerkoenig, user_input)
97  except TankerkoenigInvalidKeyError:
98  return self._show_form_user_show_form_user(
99  user_input, errors={CONF_API_KEY: "invalid_auth"}
100  )
101 
102  # no stations found
103  if len(stations) == 0:
104  return self._show_form_user_show_form_user(user_input, errors={CONF_RADIUS: "no_stations"})
105 
106  for station in stations:
107  self._stations[station.id] = (
108  f"{station.brand} {station.street} {station.house_number} -"
109  f" ({station.distance}km)"
110  )
111 
112  self._data_data = user_input
113 
114  return await self.async_step_select_stationasync_step_select_station()
115 
117  self, user_input: dict[str, Any] | None = None
118  ) -> ConfigFlowResult:
119  """Handle the step select_station of a flow initialized by the user."""
120  if not user_input:
121  return self.async_show_formasync_show_formasync_show_form(
122  step_id="select_station",
123  description_placeholders={"stations_count": str(len(self._stations))},
124  data_schema=vol.Schema(
125  {vol.Required(CONF_STATIONS): cv.multi_select(self._stations)}
126  ),
127  )
128 
129  return self._create_entry_create_entry(
130  data={**self._data_data, **user_input},
131  options={CONF_SHOW_ON_MAP: True},
132  )
133 
134  async def async_step_reauth(
135  self, entry_data: Mapping[str, Any]
136  ) -> ConfigFlowResult:
137  """Perform reauth upon an API authentication error."""
138  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
139 
141  self, user_input: dict[str, Any] | None = None
142  ) -> ConfigFlowResult:
143  """Perform reauth confirm upon an API authentication error."""
144  if not user_input:
145  return self._show_form_reauth_show_form_reauth()
146 
147  reauth_entry = self._get_reauth_entry_get_reauth_entry()
148  user_input = {**reauth_entry.data, **user_input}
149 
150  tankerkoenig = Tankerkoenig(
151  api_key=user_input[CONF_API_KEY],
152  session=async_get_clientsession(self.hass),
153  )
154  try:
155  await async_get_nearby_stations(tankerkoenig, user_input)
156  except TankerkoenigInvalidKeyError:
157  return self._show_form_reauth_show_form_reauth(user_input, {CONF_API_KEY: "invalid_auth"})
158 
159  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=user_input)
160 
162  self,
163  user_input: dict[str, Any] | None = None,
164  errors: dict[str, Any] | None = None,
165  ) -> ConfigFlowResult:
166  if user_input is None:
167  user_input = {}
168  return self.async_show_formasync_show_formasync_show_form(
169  step_id="user",
170  data_schema=vol.Schema(
171  {
172  vol.Required(
173  CONF_NAME, default=user_input.get(CONF_NAME, "")
174  ): cv.string,
175  vol.Required(
176  CONF_API_KEY, default=user_input.get(CONF_API_KEY, "")
177  ): cv.string,
178  vol.Required(
179  CONF_FUEL_TYPES,
180  default=user_input.get(CONF_FUEL_TYPES, list(FUEL_TYPES)),
181  ): cv.multi_select(FUEL_TYPES),
182  vol.Required(
183  CONF_LOCATION,
184  default=user_input.get(
185  CONF_LOCATION,
186  {
187  "latitude": self.hass.config.latitude,
188  "longitude": self.hass.config.longitude,
189  },
190  ),
191  ): LocationSelector(),
192  vol.Required(
193  CONF_RADIUS, default=user_input.get(CONF_RADIUS, DEFAULT_RADIUS)
194  ): NumberSelector(
196  min=1.0,
197  max=25,
198  step=0.1,
199  unit_of_measurement=UnitOfLength.KILOMETERS,
200  ),
201  ),
202  }
203  ),
204  errors=errors,
205  )
206 
208  self,
209  user_input: dict[str, Any] | None = None,
210  errors: dict[str, Any] | None = None,
211  ) -> ConfigFlowResult:
212  if user_input is None:
213  user_input = {}
214  return self.async_show_formasync_show_formasync_show_form(
215  step_id="reauth_confirm",
216  data_schema=vol.Schema(
217  {
218  vol.Required(
219  CONF_API_KEY, default=user_input.get(CONF_API_KEY, "")
220  ): cv.string,
221  }
222  ),
223  errors=errors,
224  )
225 
227  self, data: dict[str, Any], options: dict[str, Any]
228  ) -> ConfigFlowResult:
229  return self.async_create_entryasync_create_entryasync_create_entry(
230  title=data[CONF_NAME],
231  data=data,
232  options=options,
233  )
234 
235 
237  """Handle an options flow."""
238 
239  def __init__(self) -> None:
240  """Initialize options flow."""
241  self._stations: dict[str, str] = {}
242 
243  async def async_step_init(
244  self, user_input: dict[str, Any] | None = None
245  ) -> ConfigFlowResult:
246  """Handle options flow."""
247  if user_input is not None:
248  self.hass.config_entries.async_update_entry(
249  self.config_entryconfig_entryconfig_entry,
250  data={
251  **self.config_entryconfig_entryconfig_entry.data,
252  CONF_STATIONS: user_input.pop(CONF_STATIONS),
253  },
254  )
255  return self.async_create_entryasync_create_entry(title="", data=user_input)
256 
257  tankerkoenig = Tankerkoenig(
258  api_key=self.config_entryconfig_entryconfig_entry.data[CONF_API_KEY],
259  session=async_get_clientsession(self.hass),
260  )
261  try:
262  stations = await async_get_nearby_stations(
263  tankerkoenig, self.config_entryconfig_entryconfig_entry.data
264  )
265  except TankerkoenigInvalidKeyError:
266  return self.async_show_formasync_show_form(step_id="init", errors={"base": "invalid_auth"})
267 
268  if stations:
269  for station in stations:
270  self._stations[station.id] = (
271  f"{station.brand} {station.street} {station.house_number} -"
272  f" ({station.distance}km)"
273  )
274 
275  # add possible extra selected stations from import
276  for selected_station in self.config_entryconfig_entryconfig_entry.data[CONF_STATIONS]:
277  if selected_station not in self._stations:
278  self._stations[selected_station] = f"id: {selected_station}"
279 
280  return self.async_show_formasync_show_form(
281  step_id="init",
282  data_schema=vol.Schema(
283  {
284  vol.Required(
285  CONF_SHOW_ON_MAP,
286  default=self.config_entryconfig_entryconfig_entry.options[CONF_SHOW_ON_MAP],
287  ): bool,
288  vol.Required(
289  CONF_STATIONS, default=self.config_entryconfig_entryconfig_entry.data[CONF_STATIONS]
290  ): cv.multi_select(self._stations),
291  }
292  ),
293  )
ConfigFlowResult async_step_select_station(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:118
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:81
OptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:75
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:142
ConfigFlowResult _create_entry(self, dict[str, Any] data, dict[str, Any] options)
Definition: config_flow.py:228
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:136
ConfigFlowResult _show_form_user(self, dict[str, Any]|None user_input=None, dict[str, Any]|None errors=None)
Definition: config_flow.py:165
ConfigFlowResult _show_form_reauth(self, dict[str, Any]|None user_input=None, dict[str, Any]|None errors=None)
Definition: config_flow.py:211
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:245
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_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)
list[Station] async_get_nearby_stations(Tankerkoenig tankerkoenig, Mapping[str, Any] data)
Definition: config_flow.py:47
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)