Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for National Weather Service (NWS) integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import aiohttp
9 from pynws import SimpleNWS
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE
14 from homeassistant.core import HomeAssistant
15 from homeassistant.exceptions import HomeAssistantError
16 from homeassistant.helpers import config_validation as cv
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 
19 from . import base_unique_id
20 from .const import CONF_STATION, DOMAIN
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 
25 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, str]:
26  """Validate the user input allows us to connect.
27 
28  Data has the keys from DATA_SCHEMA with values provided by the user.
29  """
30  latitude = data[CONF_LATITUDE]
31  longitude = data[CONF_LONGITUDE]
32  api_key = data[CONF_API_KEY]
33  station = data.get(CONF_STATION)
34 
35  client_session = async_get_clientsession(hass)
36  ha_api_key = f"{api_key} homeassistant"
37  nws = SimpleNWS(latitude, longitude, ha_api_key, client_session)
38 
39  try:
40  await nws.set_station(station)
41  except aiohttp.ClientError as err:
42  _LOGGER.error("Could not connect: %s", err)
43  raise CannotConnect from err
44 
45  return {"title": nws.station}
46 
47 
48 class NWSConfigFlow(ConfigFlow, domain=DOMAIN):
49  """Handle a config flow for National Weather Service (NWS)."""
50 
51  VERSION = 1
52 
53  async def async_step_user(
54  self, user_input: dict[str, Any] | None = None
55  ) -> ConfigFlowResult:
56  """Handle the initial step."""
57  errors: dict[str, str] = {}
58  if user_input is not None:
59  await self.async_set_unique_idasync_set_unique_id(
60  base_unique_id(user_input[CONF_LATITUDE], user_input[CONF_LONGITUDE])
61  )
62  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
63  try:
64  info = await validate_input(self.hass, user_input)
65  user_input[CONF_STATION] = info["title"]
66  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
67  except CannotConnect:
68  errors["base"] = "cannot_connect"
69  except Exception:
70  _LOGGER.exception("Unexpected exception")
71  errors["base"] = "unknown"
72 
73  data_schema = vol.Schema(
74  {
75  vol.Required(CONF_API_KEY): str,
76  vol.Required(
77  CONF_LATITUDE, default=self.hass.config.latitude
78  ): cv.latitude,
79  vol.Required(
80  CONF_LONGITUDE, default=self.hass.config.longitude
81  ): cv.longitude,
82  vol.Optional(CONF_STATION): str,
83  }
84  )
85 
86  return self.async_show_formasync_show_formasync_show_form(
87  step_id="user", data_schema=data_schema, errors=errors
88  )
89 
90 
92  """Error to indicate we cannot connect."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:55
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)
_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)
dict[str, str] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:25
str base_unique_id(float latitude, float longitude)
Definition: __init__.py:40
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)