Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Met Office integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import datapoint
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
12 from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import HomeAssistantError
15 from homeassistant.helpers import config_validation as cv
16 
17 from .const import DOMAIN
18 from .helpers import fetch_site
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
23 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, str]:
24  """Validate that the user input allows us to connect to DataPoint.
25 
26  Data has the keys from DATA_SCHEMA with values provided by the user.
27  """
28  latitude = data[CONF_LATITUDE]
29  longitude = data[CONF_LONGITUDE]
30  api_key = data[CONF_API_KEY]
31 
32  connection = datapoint.connection(api_key=api_key)
33 
34  site = await hass.async_add_executor_job(
35  fetch_site, connection, latitude, longitude
36  )
37 
38  if site is None:
39  raise CannotConnect
40 
41  return {"site_name": site.name}
42 
43 
44 class MetOfficeConfigFlow(ConfigFlow, domain=DOMAIN):
45  """Handle a config flow for Met Office weather integration."""
46 
47  VERSION = 1
48 
49  async def async_step_user(
50  self, user_input: dict[str, Any] | None = None
51  ) -> ConfigFlowResult:
52  """Handle the initial step."""
53  errors = {}
54  if user_input is not None:
55  await self.async_set_unique_idasync_set_unique_id(
56  f"{user_input[CONF_LATITUDE]}_{user_input[CONF_LONGITUDE]}"
57  )
58  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
59 
60  try:
61  info = await validate_input(self.hass, user_input)
62  except CannotConnect:
63  errors["base"] = "cannot_connect"
64  except Exception:
65  _LOGGER.exception("Unexpected exception")
66  errors["base"] = "unknown"
67  else:
68  user_input[CONF_NAME] = info["site_name"]
69  return self.async_create_entryasync_create_entryasync_create_entry(
70  title=user_input[CONF_NAME], data=user_input
71  )
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  },
83  )
84 
85  return self.async_show_formasync_show_formasync_show_form(
86  step_id="user", data_schema=data_schema, errors=errors
87  )
88 
89 
91  """Error to indicate we cannot connect."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:51
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:23