Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Define a config flow manager for AirVisual."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from collections.abc import Mapping
7 from typing import Any
8 
9 from pyairvisual.cloud_api import (
10  CloudAPI,
11  InvalidKeyError,
12  KeyExpiredError,
13  NotFoundError,
14  UnauthorizedError,
15 )
16 from pyairvisual.errors import AirVisualError
17 import voluptuous as vol
18 
19 from homeassistant.config_entries import (
20  SOURCE_REAUTH,
21  ConfigEntry,
22  ConfigFlow,
23  ConfigFlowResult,
24 )
25 from homeassistant.const import (
26  CONF_API_KEY,
27  CONF_COUNTRY,
28  CONF_LATITUDE,
29  CONF_LONGITUDE,
30  CONF_SHOW_ON_MAP,
31  CONF_STATE,
32 )
33 from homeassistant.core import callback
34 from homeassistant.helpers import aiohttp_client, config_validation as cv
36  SchemaFlowFormStep,
37  SchemaOptionsFlowHandler,
38 )
39 
40 from . import async_get_geography_id
41 from .const import (
42  CONF_CITY,
43  CONF_INTEGRATION_TYPE,
44  DOMAIN,
45  INTEGRATION_TYPE_GEOGRAPHY_COORDS,
46  INTEGRATION_TYPE_GEOGRAPHY_NAME,
47  LOGGER,
48 )
49 
50 API_KEY_DATA_SCHEMA = vol.Schema({vol.Required(CONF_API_KEY): cv.string})
51 GEOGRAPHY_NAME_SCHEMA = API_KEY_DATA_SCHEMA.extend(
52  {
53  vol.Required(CONF_CITY): cv.string,
54  vol.Required(CONF_STATE): cv.string,
55  vol.Required(CONF_COUNTRY): cv.string,
56  }
57 )
58 PICK_INTEGRATION_TYPE_SCHEMA = vol.Schema(
59  {
60  vol.Required("type"): vol.In(
61  [
62  INTEGRATION_TYPE_GEOGRAPHY_COORDS,
63  INTEGRATION_TYPE_GEOGRAPHY_NAME,
64  ]
65  )
66  }
67 )
68 
69 OPTIONS_SCHEMA = vol.Schema(
70  {vol.Required(CONF_SHOW_ON_MAP): bool},
71 )
72 OPTIONS_FLOW = {
73  "init": SchemaFlowFormStep(OPTIONS_SCHEMA),
74 }
75 
76 
77 class AirVisualFlowHandler(ConfigFlow, domain=DOMAIN):
78  """Handle an AirVisual config flow."""
79 
80  VERSION = 3
81 
82  def __init__(self) -> None:
83  """Initialize the config flow."""
84  self._entry_data_for_reauth_entry_data_for_reauth: Mapping[str, Any] = {}
85  self._geo_id_geo_id: str | None = None
86 
87  @property
88  def geography_coords_schema(self) -> vol.Schema:
89  """Return the data schema for the cloud API."""
90  return API_KEY_DATA_SCHEMA.extend(
91  {
92  vol.Required(
93  CONF_LATITUDE, default=self.hass.config.latitude
94  ): cv.latitude,
95  vol.Required(
96  CONF_LONGITUDE, default=self.hass.config.longitude
97  ): cv.longitude,
98  }
99  )
100 
102  self, user_input: dict[str, str], integration_type: str
103  ) -> ConfigFlowResult:
104  """Validate a Cloud API key."""
105  errors = {}
106  websession = aiohttp_client.async_get_clientsession(self.hass)
107  cloud_api = CloudAPI(user_input[CONF_API_KEY], session=websession)
108 
109  # If this is the first (and only the first) time we've seen this API key, check
110  # that it's valid:
111  valid_keys = self.hass.data.setdefault("airvisual_checked_api_keys", set())
112  valid_keys_lock = self.hass.data.setdefault(
113  "airvisual_checked_api_keys_lock", asyncio.Lock()
114  )
115 
116  async with valid_keys_lock:
117  if user_input[CONF_API_KEY] not in valid_keys:
118  if integration_type == INTEGRATION_TYPE_GEOGRAPHY_COORDS:
119  coro = cloud_api.air_quality.nearest_city()
120  error_schema = self.geography_coords_schemageography_coords_schema
121  error_step = "geography_by_coords"
122  else:
123  coro = cloud_api.air_quality.city(
124  user_input[CONF_CITY],
125  user_input[CONF_STATE],
126  user_input[CONF_COUNTRY],
127  )
128  error_schema = GEOGRAPHY_NAME_SCHEMA
129  error_step = "geography_by_name"
130 
131  try:
132  await coro
133  except (InvalidKeyError, KeyExpiredError, UnauthorizedError):
134  errors[CONF_API_KEY] = "invalid_api_key"
135  except NotFoundError:
136  errors[CONF_CITY] = "location_not_found"
137  except AirVisualError as err:
138  LOGGER.error(err)
139  errors["base"] = "unknown"
140 
141  if errors:
142  return self.async_show_formasync_show_formasync_show_form(
143  step_id=error_step, data_schema=error_schema, errors=errors
144  )
145 
146  valid_keys.add(user_input[CONF_API_KEY])
147 
148  if self.sourcesourcesourcesource == SOURCE_REAUTH:
149  return self.async_update_reload_and_abortasync_update_reload_and_abort(
150  self._get_reauth_entry_get_reauth_entry(),
151  data_updates={CONF_API_KEY: user_input[CONF_API_KEY]},
152  )
153 
154  return self.async_create_entryasync_create_entryasync_create_entry(
155  title=f"Cloud API ({self._geo_id})",
156  data={**user_input, CONF_INTEGRATION_TYPE: integration_type},
157  )
158 
160  self, user_input: dict[str, str], integration_type: str
161  ) -> ConfigFlowResult:
162  """Handle the initialization of the integration via the cloud API."""
163  self._geo_id_geo_id = async_get_geography_id(user_input)
164  await self._async_set_unique_id_async_set_unique_id(self._geo_id_geo_id)
165  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
166  return await self._async_finish_geography_async_finish_geography(user_input, integration_type)
167 
168  async def _async_set_unique_id(self, unique_id: str) -> None:
169  """Set the unique ID of the config flow and abort if it already exists."""
170  await self.async_set_unique_idasync_set_unique_id(unique_id)
171  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
172 
173  @staticmethod
174  @callback
175  def async_get_options_flow(config_entry: ConfigEntry) -> SchemaOptionsFlowHandler:
176  """Define the config flow to handle options."""
177  return SchemaOptionsFlowHandler(config_entry, OPTIONS_FLOW)
178 
179  async def async_step_import(self, import_data: dict[str, str]) -> ConfigFlowResult:
180  """Handle import of config entry version 1 data."""
181  import_source = import_data.pop("import_source")
182  if import_source == "geography_by_coords":
183  return await self.async_step_geography_by_coordsasync_step_geography_by_coords(import_data)
184  return await self.async_step_geography_by_nameasync_step_geography_by_name(import_data)
185 
187  self, user_input: dict[str, str] | None = None
188  ) -> ConfigFlowResult:
189  """Handle the initialization of the cloud API based on latitude/longitude."""
190  if not user_input:
191  return self.async_show_formasync_show_formasync_show_form(
192  step_id="geography_by_coords", data_schema=self.geography_coords_schemageography_coords_schema
193  )
194 
195  return await self._async_init_geography_async_init_geography(
196  user_input, INTEGRATION_TYPE_GEOGRAPHY_COORDS
197  )
198 
200  self, user_input: dict[str, str] | None = None
201  ) -> ConfigFlowResult:
202  """Handle the initialization of the cloud API based on city/state/country."""
203  if not user_input:
204  return self.async_show_formasync_show_formasync_show_form(
205  step_id="geography_by_name", data_schema=GEOGRAPHY_NAME_SCHEMA
206  )
207 
208  return await self._async_init_geography_async_init_geography(
209  user_input, INTEGRATION_TYPE_GEOGRAPHY_NAME
210  )
211 
212  async def async_step_reauth(
213  self, entry_data: Mapping[str, Any]
214  ) -> ConfigFlowResult:
215  """Handle configuration by re-auth."""
216  self._entry_data_for_reauth_entry_data_for_reauth = entry_data
217  self._geo_id_geo_id = async_get_geography_id(entry_data)
218  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
219 
221  self, user_input: dict[str, str] | None = None
222  ) -> ConfigFlowResult:
223  """Handle re-auth completion."""
224  if not user_input:
225  return self.async_show_formasync_show_formasync_show_form(
226  step_id="reauth_confirm", data_schema=API_KEY_DATA_SCHEMA
227  )
228 
229  conf = {**self._entry_data_for_reauth_entry_data_for_reauth, CONF_API_KEY: user_input[CONF_API_KEY]}
230 
231  return await self._async_finish_geography_async_finish_geography(
232  conf, self._entry_data_for_reauth_entry_data_for_reauth[CONF_INTEGRATION_TYPE]
233  )
234 
235  async def async_step_user(
236  self, user_input: dict[str, str] | None = None
237  ) -> ConfigFlowResult:
238  """Handle the start of the config flow."""
239  if not user_input:
240  return self.async_show_formasync_show_formasync_show_form(
241  step_id="user", data_schema=PICK_INTEGRATION_TYPE_SCHEMA
242  )
243 
244  if user_input["type"] == INTEGRATION_TYPE_GEOGRAPHY_COORDS:
245  return await self.async_step_geography_by_coordsasync_step_geography_by_coords()
246  return await self.async_step_geography_by_nameasync_step_geography_by_name()
ConfigFlowResult async_step_import(self, dict[str, str] import_data)
Definition: config_flow.py:179
ConfigFlowResult async_step_user(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:237
SchemaOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:175
ConfigFlowResult _async_finish_geography(self, dict[str, str] user_input, str integration_type)
Definition: config_flow.py:103
ConfigFlowResult async_step_reauth_confirm(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:222
ConfigFlowResult async_step_geography_by_name(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:201
ConfigFlowResult async_step_geography_by_coords(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:188
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:214
ConfigFlowResult _async_init_geography(self, dict[str, str] user_input, str integration_type)
Definition: config_flow.py:161
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)
_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)
str async_get_geography_id(Mapping[str, Any] geography_dict)
Definition: __init__.py:98