Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the Ambient Weather Network integration."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from aioambient import OpenAPI
8 import voluptuous as vol
9 
10 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
11 from homeassistant.const import (
12  CONF_LATITUDE,
13  CONF_LOCATION,
14  CONF_LONGITUDE,
15  CONF_MAC,
16  CONF_RADIUS,
17  UnitOfLength,
18 )
20  LocationSelector,
21  LocationSelectorConfig,
22  SelectOptionDict,
23  SelectSelector,
24  SelectSelectorConfig,
25 )
26 from homeassistant.util.unit_conversion import DistanceConverter
27 
28 from .const import API_STATION_INDOOR, API_STATION_INFO, API_STATION_MAC_ADDRESS, DOMAIN
29 from .helper import get_station_name
30 
31 CONF_USER = "user"
32 CONF_STATION = "station"
33 
34 # One mile
35 CONF_RADIUS_DEFAULT = 1609.34
36 
37 
38 class AmbientNetworkConfigFlow(ConfigFlow, domain=DOMAIN):
39  """Handle the config flow for the Ambient Weather Network integration."""
40 
41  VERSION = 1
42 
43  def __init__(self) -> None:
44  """Construct the config flow."""
45 
46  self._longitude_longitude = 0.0
47  self._latitude_latitude = 0.0
48  self._radius_radius = 0.0
49  self._stations_stations: dict[str, dict[str, Any]] = {}
50 
51  async def async_step_user(
52  self,
53  user_input: dict[str, Any] | None = None,
54  ) -> ConfigFlowResult:
55  """Handle the initial step to select the location."""
56 
57  errors: dict[str, str] | None = None
58  if user_input:
59  self._latitude_latitude = user_input[CONF_LOCATION][CONF_LATITUDE]
60  self._longitude_longitude = user_input[CONF_LOCATION][CONF_LONGITUDE]
61  self._radius_radius = user_input[CONF_LOCATION][CONF_RADIUS]
62 
63  client: OpenAPI = OpenAPI()
64  self._stations_stations = {
65  x[API_STATION_MAC_ADDRESS]: x
66  for x in await client.get_devices_by_location(
67  self._latitude_latitude,
68  self._longitude_longitude,
69  radius=DistanceConverter.convert(
70  self._radius_radius,
71  UnitOfLength.METERS,
72  UnitOfLength.MILES,
73  ),
74  )
75  }
76 
77  # Filter out indoor stations
78  self._stations_stations = dict(
79  filter(
80  lambda item: not item[1]
81  .get(API_STATION_INFO, {})
82  .get(API_STATION_INDOOR, False),
83  self._stations_stations.items(),
84  )
85  )
86 
87  if self._stations_stations:
88  return await self.async_step_stationasync_step_station()
89 
90  errors = {"base": "no_stations_found"}
91 
92  schema: vol.Schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
93  vol.Schema(
94  {
95  vol.Required(
96  CONF_LOCATION,
98  }
99  ),
100  {
101  CONF_LOCATION: {
102  CONF_LATITUDE: self.hass.config.latitude,
103  CONF_LONGITUDE: self.hass.config.longitude,
104  CONF_RADIUS: CONF_RADIUS_DEFAULT,
105  }
106  if not errors
107  else {
108  CONF_LATITUDE: self._latitude_latitude,
109  CONF_LONGITUDE: self._longitude_longitude,
110  CONF_RADIUS: self._radius_radius,
111  }
112  },
113  )
114 
115  return self.async_show_formasync_show_formasync_show_form(
116  step_id=CONF_USER, data_schema=schema, errors=errors if errors else {}
117  )
118 
120  self, user_input: dict[str, Any] | None = None
121  ) -> ConfigFlowResult:
122  """Handle the second step to select the station."""
123 
124  if user_input:
125  mac_address = user_input[CONF_STATION]
126  await self.async_set_unique_idasync_set_unique_id(mac_address)
127  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
128  return self.async_create_entryasync_create_entryasync_create_entry(
129  title=get_station_name(self._stations_stations[mac_address]),
130  data={CONF_MAC: mac_address},
131  )
132 
133  options: list[SelectOptionDict] = [
135  label=get_station_name(station),
136  value=mac_address,
137  )
138  for mac_address, station in self._stations_stations.items()
139  ]
140 
141  schema: vol.Schema = vol.Schema(
142  {
143  vol.Required(CONF_STATION): SelectSelector(
144  SelectSelectorConfig(options=options, multiple=False, sort=True),
145  )
146  }
147  )
148 
149  return self.async_show_formasync_show_formasync_show_form(
150  step_id=CONF_STATION,
151  data_schema=schema,
152  )
ConfigFlowResult async_step_station(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:121
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:54
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_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)
str get_station_name(dict[str, Any] station)
Definition: helper.py:17
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88