Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow to configure SMHI component."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from smhi.smhi_lib import Smhi, SmhiForecastException
8 import voluptuous as vol
9 
10 from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN
11 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
12 from homeassistant.const import CONF_LATITUDE, CONF_LOCATION, CONF_LONGITUDE, CONF_NAME
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers import (
15  aiohttp_client,
16  device_registry as dr,
17  entity_registry as er,
18 )
19 from homeassistant.helpers.selector import LocationSelector
20 
21 from .const import DEFAULT_NAME, DOMAIN, HOME_LOCATION_NAME
22 
23 
25  hass: HomeAssistant, longitude: float, latitude: float
26 ) -> bool:
27  """Return true if location is ok."""
28  session = aiohttp_client.async_get_clientsession(hass)
29  smhi_api = Smhi(longitude, latitude, session=session)
30  try:
31  await smhi_api.async_get_forecast()
32  except SmhiForecastException:
33  return False
34 
35  return True
36 
37 
38 class SmhiFlowHandler(ConfigFlow, domain=DOMAIN):
39  """Config flow for SMHI component."""
40 
41  VERSION = 2
42 
43  async def async_step_user(
44  self, user_input: dict[str, Any] | None = None
45  ) -> ConfigFlowResult:
46  """Handle a flow initialized by the user."""
47 
48  errors: dict[str, str] = {}
49 
50  if user_input is not None:
51  lat: float = user_input[CONF_LOCATION][CONF_LATITUDE]
52  lon: float = user_input[CONF_LOCATION][CONF_LONGITUDE]
53  if await async_check_location(self.hass, lon, lat):
54  name = f"{DEFAULT_NAME} {round(lat, 6)} {round(lon, 6)}"
55  if (
56  lat == self.hass.config.latitude
57  and lon == self.hass.config.longitude
58  ):
59  name = HOME_LOCATION_NAME
60 
61  user_input[CONF_NAME] = (
62  HOME_LOCATION_NAME if name == HOME_LOCATION_NAME else DEFAULT_NAME
63  )
64 
65  await self.async_set_unique_idasync_set_unique_id(f"{lat}-{lon}")
66  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
67  return self.async_create_entryasync_create_entryasync_create_entry(title=name, data=user_input)
68 
69  errors["base"] = "wrong_location"
70 
71  home_location = {
72  CONF_LATITUDE: self.hass.config.latitude,
73  CONF_LONGITUDE: self.hass.config.longitude,
74  }
75  return self.async_show_formasync_show_formasync_show_form(
76  step_id="user",
77  data_schema=vol.Schema(
78  {vol.Required(CONF_LOCATION, default=home_location): LocationSelector()}
79  ),
80  errors=errors,
81  )
82 
84  self, user_input: dict[str, Any] | None = None
85  ) -> ConfigFlowResult:
86  """Handle a reconfiguration flow initialized by the user."""
87  errors: dict[str, str] = {}
88  reconfigure_entry = self._get_reconfigure_entry_get_reconfigure_entry()
89 
90  if user_input is not None:
91  lat: float = user_input[CONF_LOCATION][CONF_LATITUDE]
92  lon: float = user_input[CONF_LOCATION][CONF_LONGITUDE]
93  if await async_check_location(self.hass, lon, lat):
94  unique_id = f"{lat}-{lon}"
95  await self.async_set_unique_idasync_set_unique_id(unique_id)
96  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
97 
98  old_lat = reconfigure_entry.data[CONF_LOCATION][CONF_LATITUDE]
99  old_lon = reconfigure_entry.data[CONF_LOCATION][CONF_LONGITUDE]
100 
101  entity_reg = er.async_get(self.hass)
102  if entity := entity_reg.async_get_entity_id(
103  WEATHER_DOMAIN, DOMAIN, f"{old_lat}, {old_lon}"
104  ):
105  entity_reg.async_update_entity(
106  entity, new_unique_id=f"{lat}, {lon}"
107  )
108 
109  device_reg = dr.async_get(self.hass)
110  if device := device_reg.async_get_device(
111  identifiers={(DOMAIN, f"{old_lat}, {old_lon}")}
112  ):
113  device_reg.async_update_device(
114  device.id, new_identifiers={(DOMAIN, f"{lat}, {lon}")}
115  )
116 
117  return self.async_update_reload_and_abortasync_update_reload_and_abort(
118  reconfigure_entry,
119  unique_id=unique_id,
120  data_updates=user_input,
121  )
122  errors["base"] = "wrong_location"
123 
124  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
125  vol.Schema({vol.Required(CONF_LOCATION): LocationSelector()}),
126  reconfigure_entry.data,
127  )
128  return self.async_show_formasync_show_formasync_show_form(
129  step_id="reconfigure", data_schema=schema, errors=errors
130  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:45
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:85
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)
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)
bool async_check_location(HomeAssistant hass, float longitude, float latitude)
Definition: config_flow.py:26