Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow to configure the Meteo-France integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from meteofrance_api.client import MeteoFranceClient
9 from meteofrance_api.model import Place
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import SOURCE_IMPORT, ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
14 from homeassistant.core import callback
15 
16 from .const import CONF_CITY, DOMAIN
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
21 class MeteoFranceFlowHandler(ConfigFlow, domain=DOMAIN):
22  """Handle a Meteo-France config flow."""
23 
24  VERSION = 1
25 
26  def __init__(self) -> None:
27  """Init MeteoFranceFlowHandler."""
28  self.placesplaces: list[Place] = []
29 
30  @callback
32  self,
33  user_input: dict[str, Any] | None = None,
34  errors: dict[str, str] | None = None,
35  ) -> ConfigFlowResult:
36  """Show the setup form to the user."""
37 
38  if user_input is None:
39  user_input = {}
40 
41  return self.async_show_formasync_show_formasync_show_form(
42  step_id="user",
43  data_schema=vol.Schema(
44  {vol.Required(CONF_CITY, default=user_input.get(CONF_CITY, "")): str}
45  ),
46  errors=errors or {},
47  )
48 
49  async def async_step_user(
50  self, user_input: dict[str, Any] | None = None
51  ) -> ConfigFlowResult:
52  """Handle a flow initiated by the user."""
53  errors: dict[str, str] = {}
54 
55  if user_input is None:
56  return self._show_setup_form_show_setup_form(user_input, errors)
57 
58  city = user_input[CONF_CITY] # Might be a city name or a postal code
59  latitude = user_input.get(CONF_LATITUDE)
60  longitude = user_input.get(CONF_LONGITUDE)
61 
62  if not latitude:
63  client = MeteoFranceClient()
64  self.placesplaces = await self.hass.async_add_executor_job(
65  client.search_places, city
66  )
67  _LOGGER.debug("Places search result: %s", self.placesplaces)
68  if not self.placesplaces:
69  errors[CONF_CITY] = "empty"
70  return self._show_setup_form_show_setup_form(user_input, errors)
71 
72  return await self.async_step_citiesasync_step_cities()
73 
74  # Check if already configured
75  await self.async_set_unique_idasync_set_unique_id(f"{latitude}, {longitude}")
76  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
77 
78  return self.async_create_entryasync_create_entryasync_create_entry(
79  title=city,
80  data={CONF_LATITUDE: latitude, CONF_LONGITUDE: longitude},
81  )
82 
83  async def async_step_cities(
84  self, user_input: dict[str, Any] | None = None
85  ) -> ConfigFlowResult:
86  """Step where the user choose the city from the API search results."""
87  if not user_input:
88  if len(self.placesplaces) > 1 and self.sourcesourcesource != SOURCE_IMPORT:
89  places_for_form: dict[str, str] = {}
90  for place in self.placesplaces:
91  places_for_form[_build_place_key(place)] = f"{place}"
92 
93  return self.async_show_formasync_show_formasync_show_form(
94  step_id="cities",
95  data_schema=vol.Schema(
96  {
97  vol.Required(CONF_CITY): vol.All(
98  vol.Coerce(str), vol.In(places_for_form)
99  )
100  }
101  ),
102  )
103  user_input = {CONF_CITY: _build_place_key(self.placesplaces[0])}
104 
105  city_infos = user_input[CONF_CITY].split(";")
106  return await self.async_step_userasync_step_userasync_step_user(
107  {
108  CONF_CITY: city_infos[0],
109  CONF_LATITUDE: city_infos[1],
110  CONF_LONGITUDE: city_infos[2],
111  }
112  )
113 
114 
115 def _build_place_key(place: Place) -> str:
116  return f"{place};{place.latitude};{place.longitude}"
ConfigFlowResult async_step_cities(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:85
ConfigFlowResult _show_setup_form(self, dict[str, Any]|None user_input=None, dict[str, str]|None errors=None)
Definition: config_flow.py:35
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:51
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_step_user(self, dict[str, Any]|None user_input=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)
_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)