Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Adds config flow for Airly."""
2 
3 from __future__ import annotations
4 
5 from asyncio import timeout
6 from http import HTTPStatus
7 from typing import Any
8 
9 from aiohttp import ClientSession
10 from airly import Airly
11 from airly.exceptions import AirlyError
12 import voluptuous as vol
13 
14 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
15 from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
16 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 
19 from .const import CONF_USE_NEAREST, DOMAIN, NO_AIRLY_SENSORS
20 
21 
22 class AirlyFlowHandler(ConfigFlow, domain=DOMAIN):
23  """Config flow for Airly."""
24 
25  VERSION = 1
26 
27  async def async_step_user(
28  self, user_input: dict[str, Any] | None = None
29  ) -> ConfigFlowResult:
30  """Handle a flow initialized by the user."""
31  errors = {}
32  use_nearest = False
33 
34  websession = async_get_clientsession(self.hass)
35 
36  if user_input is not None:
37  await self.async_set_unique_idasync_set_unique_id(
38  f"{user_input[CONF_LATITUDE]}-{user_input[CONF_LONGITUDE]}"
39  )
40  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
41  try:
42  location_point_valid = await test_location(
43  websession,
44  user_input["api_key"],
45  user_input["latitude"],
46  user_input["longitude"],
47  )
48  if not location_point_valid:
49  location_nearest_valid = await test_location(
50  websession,
51  user_input["api_key"],
52  user_input["latitude"],
53  user_input["longitude"],
54  use_nearest=True,
55  )
56  except AirlyError as err:
57  if err.status_code == HTTPStatus.UNAUTHORIZED:
58  errors["base"] = "invalid_api_key"
59  if err.status_code == HTTPStatus.NOT_FOUND:
60  errors["base"] = "wrong_location"
61  else:
62  if not location_point_valid:
63  if not location_nearest_valid:
64  return self.async_abortasync_abortasync_abort(reason="wrong_location")
65  use_nearest = True
66  return self.async_create_entryasync_create_entryasync_create_entry(
67  title=user_input[CONF_NAME],
68  data={**user_input, CONF_USE_NEAREST: use_nearest},
69  )
70 
71  return self.async_show_formasync_show_formasync_show_form(
72  step_id="user",
73  data_schema=vol.Schema(
74  {
75  vol.Required(CONF_API_KEY): str,
76  vol.Optional(
77  CONF_LATITUDE, default=self.hass.config.latitude
78  ): cv.latitude,
79  vol.Optional(
80  CONF_LONGITUDE, default=self.hass.config.longitude
81  ): cv.longitude,
82  vol.Optional(
83  CONF_NAME, default=self.hass.config.location_name
84  ): str,
85  }
86  ),
87  errors=errors,
88  )
89 
90 
91 async def test_location(
92  client: ClientSession,
93  api_key: str,
94  latitude: float,
95  longitude: float,
96  use_nearest: bool = False,
97 ) -> bool:
98  """Return true if location is valid."""
99  airly = Airly(api_key, client)
100  if use_nearest:
101  measurements = airly.create_measurements_session_nearest(
102  latitude=latitude, longitude=longitude, max_distance_km=5
103  )
104  else:
105  measurements = airly.create_measurements_session_point(
106  latitude=latitude, longitude=longitude
107  )
108  async with timeout(10):
109  await measurements.update()
110 
111  current = measurements.current
112 
113  if current["indexes"][0]["description"] == NO_AIRLY_SENSORS:
114  return False
115  return True
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:29
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_abort(self, *str reason, Mapping[str, str]|None description_placeholders=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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
bool test_location(ClientSession client, str api_key, float latitude, float longitude, bool use_nearest=False)
Definition: config_flow.py:97
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)