Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Adds config flow for Trafikverket Weather integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from pytrafikverket.exceptions import (
9  InvalidAuthentication,
10  MultipleWeatherStationsFound,
11  NoWeatherStationFound,
12 )
13 from pytrafikverket.trafikverket_weather import TrafikverketWeather
14 import voluptuous as vol
15 
16 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
17 from homeassistant.const import CONF_API_KEY
18 from homeassistant.helpers.aiohttp_client import async_get_clientsession
21  TextSelector,
22  TextSelectorConfig,
23  TextSelectorType,
24 )
25 
26 from .const import CONF_STATION, DOMAIN
27 
28 
29 class TVWeatherConfigFlow(ConfigFlow, domain=DOMAIN):
30  """Handle a config flow for Trafikverket Weatherstation integration."""
31 
32  VERSION = 1
33 
34  async def validate_input(self, sensor_api: str, station: str) -> None:
35  """Validate input from user input."""
36  web_session = async_get_clientsession(self.hass)
37  weather_api = TrafikverketWeather(web_session, sensor_api)
38  await weather_api.async_get_weather(station)
39 
40  async def async_step_user(
41  self, user_input: dict[str, str] | None = None
42  ) -> ConfigFlowResult:
43  """Handle the initial step."""
44  errors = {}
45 
46  if user_input is not None:
47  name = user_input[CONF_STATION]
48  api_key = user_input[CONF_API_KEY]
49  station = user_input[CONF_STATION]
50 
51  try:
52  await self.validate_inputvalidate_input(api_key, station)
53  except InvalidAuthentication:
54  errors["base"] = "invalid_auth"
55  except NoWeatherStationFound:
56  errors["base"] = "invalid_station"
57  except MultipleWeatherStationsFound:
58  errors["base"] = "more_stations"
59  except Exception: # noqa: BLE001
60  errors["base"] = "cannot_connect"
61  else:
62  return self.async_create_entryasync_create_entryasync_create_entry(
63  title=name,
64  data={
65  CONF_API_KEY: api_key,
66  CONF_STATION: station,
67  },
68  )
69 
70  return self.async_show_formasync_show_formasync_show_form(
71  step_id="user",
72  data_schema=vol.Schema(
73  {
74  vol.Required(CONF_API_KEY): cv.string,
75  vol.Required(CONF_STATION): cv.string,
76  }
77  ),
78  errors=errors,
79  )
80 
81  async def async_step_reauth(
82  self, entry_data: Mapping[str, Any]
83  ) -> ConfigFlowResult:
84  """Handle re-authentication with Trafikverket."""
85  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
86 
88  self, user_input: dict[str, Any] | None = None
89  ) -> ConfigFlowResult:
90  """Confirm re-authentication with Trafikverket."""
91  errors: dict[str, str] = {}
92  reauth_entry = self._get_reauth_entry_get_reauth_entry()
93 
94  if user_input:
95  api_key = user_input[CONF_API_KEY]
96 
97  try:
98  await self.validate_inputvalidate_input(api_key, reauth_entry.data[CONF_STATION])
99  except InvalidAuthentication:
100  errors["base"] = "invalid_auth"
101  except NoWeatherStationFound:
102  errors["base"] = "invalid_station"
103  except MultipleWeatherStationsFound:
104  errors["base"] = "more_stations"
105  except Exception: # noqa: BLE001
106  errors["base"] = "cannot_connect"
107  else:
108  return self.async_update_reload_and_abortasync_update_reload_and_abort(
109  reauth_entry, data_updates={CONF_API_KEY: api_key}
110  )
111 
112  return self.async_show_formasync_show_formasync_show_form(
113  step_id="reauth_confirm",
114  data_schema=vol.Schema({vol.Required(CONF_API_KEY): cv.string}),
115  errors=errors,
116  )
117 
119  self, user_input: dict[str, Any] | None = None
120  ) -> ConfigFlowResult:
121  """Handle re-configuration with Trafikverket."""
122  errors: dict[str, str] = {}
123 
124  if user_input:
125  try:
126  await self.validate_inputvalidate_input(
127  user_input[CONF_API_KEY], user_input[CONF_STATION]
128  )
129  except InvalidAuthentication:
130  errors["base"] = "invalid_auth"
131  except NoWeatherStationFound:
132  errors["base"] = "invalid_station"
133  except MultipleWeatherStationsFound:
134  errors["base"] = "more_stations"
135  except Exception: # noqa: BLE001
136  errors["base"] = "cannot_connect"
137  else:
138  return self.async_update_reload_and_abortasync_update_reload_and_abort(
139  self._get_reconfigure_entry_get_reconfigure_entry(),
140  title=user_input[CONF_STATION],
141  data=user_input,
142  )
143 
144  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
145  vol.Schema(
146  {
147  vol.Required(CONF_API_KEY): TextSelector(
148  TextSelectorConfig(type=TextSelectorType.PASSWORD)
149  ),
150  vol.Required(CONF_STATION): TextSelector(),
151  }
152  ),
153  {**self._get_reconfigure_entry_get_reconfigure_entry().data, **(user_input or {})},
154  )
155 
156  return self.async_show_formasync_show_formasync_show_form(
157  step_id="reconfigure",
158  data_schema=schema,
159  errors=errors,
160  )
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:120
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:83
ConfigFlowResult async_step_user(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:42
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:89
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)
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)