Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Tomorrow.io integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from pytomorrowio.exceptions import (
10  CantConnectException,
11  InvalidAPIKeyException,
12  RateLimitedException,
13 )
14 from pytomorrowio.pytomorrowio import TomorrowioV4
15 import voluptuous as vol
16 
17 from homeassistant.components.zone import async_active_zone
18 from homeassistant.config_entries import (
19  ConfigEntry,
20  ConfigFlow,
21  ConfigFlowResult,
22  OptionsFlow,
23 )
24 from homeassistant.const import (
25  CONF_API_KEY,
26  CONF_FRIENDLY_NAME,
27  CONF_LATITUDE,
28  CONF_LOCATION,
29  CONF_LONGITUDE,
30  CONF_NAME,
31 )
32 from homeassistant.core import HomeAssistant, callback
33 from homeassistant.helpers.aiohttp_client import async_get_clientsession
34 from homeassistant.helpers.selector import LocationSelector, LocationSelectorConfig
35 
36 from .const import (
37  CONF_TIMESTEP,
38  DEFAULT_NAME,
39  DEFAULT_TIMESTEP,
40  DOMAIN,
41  TMRW_ATTR_TEMPERATURE,
42 )
43 
44 _LOGGER = logging.getLogger(__name__)
45 
46 
48  hass: HomeAssistant,
49  source: str | None,
50  input_dict: dict[str, Any] | None = None,
51 ) -> vol.Schema:
52  """Return schema defaults for init step based on user input/config dict.
53 
54  Retain info already provided for future form views by setting them as
55  defaults in schema.
56  """
57  if input_dict is None:
58  input_dict = {}
59 
60  api_key_schema = {
61  vol.Required(CONF_API_KEY, default=input_dict.get(CONF_API_KEY)): str,
62  }
63 
64  default_location = input_dict.get(
65  CONF_LOCATION,
66  {
67  CONF_LATITUDE: hass.config.latitude,
68  CONF_LONGITUDE: hass.config.longitude,
69  },
70  )
71  return vol.Schema(
72  {
73  **api_key_schema,
74  vol.Required(
75  CONF_LOCATION,
76  default=default_location,
77  ): LocationSelector(LocationSelectorConfig(radius=False)),
78  },
79  )
80 
81 
82 def _get_unique_id(hass: HomeAssistant, input_dict: dict[str, Any]):
83  """Return unique ID from config data."""
84  return (
85  f"{input_dict[CONF_API_KEY]}"
86  f"_{input_dict[CONF_LOCATION][CONF_LATITUDE]}"
87  f"_{input_dict[CONF_LOCATION][CONF_LONGITUDE]}"
88  )
89 
90 
92  """Handle Tomorrow.io options."""
93 
94  async def async_step_init(
95  self, user_input: dict[str, Any] | None = None
96  ) -> ConfigFlowResult:
97  """Manage the Tomorrow.io options."""
98  if user_input is not None:
99  return self.async_create_entryasync_create_entry(title="", data=user_input)
100 
101  options_schema = {
102  vol.Required(
103  CONF_TIMESTEP,
104  default=self.config_entryconfig_entryconfig_entry.options[CONF_TIMESTEP],
105  ): vol.In([1, 5, 15, 30, 60]),
106  }
107 
108  return self.async_show_formasync_show_form(
109  step_id="init", data_schema=vol.Schema(options_schema)
110  )
111 
112 
113 class TomorrowioConfigFlow(ConfigFlow, domain=DOMAIN):
114  """Handle a config flow for Tomorrow.io Weather API."""
115 
116  VERSION = 1
117 
118  @staticmethod
119  @callback
121  config_entry: ConfigEntry,
122  ) -> TomorrowioOptionsConfigFlow:
123  """Get the options flow for this handler."""
125 
126  async def async_step_user(
127  self, user_input: dict[str, Any] | None = None
128  ) -> ConfigFlowResult:
129  """Handle the initial step."""
130  errors = {}
131  if user_input is not None:
132  await self.async_set_unique_idasync_set_unique_id(
133  unique_id=_get_unique_id(self.hass, user_input)
134  )
135  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
136 
137  location = user_input[CONF_LOCATION]
138  latitude = location[CONF_LATITUDE]
139  longitude = location[CONF_LONGITUDE]
140  if CONF_NAME not in user_input:
141  user_input[CONF_NAME] = DEFAULT_NAME
142  # Append zone name if it exists and we are using the default name
143  if zone_state := async_active_zone(self.hass, latitude, longitude):
144  zone_name = zone_state.attributes[CONF_FRIENDLY_NAME]
145  user_input[CONF_NAME] += f" - {zone_name}"
146  try:
147  await TomorrowioV4(
148  user_input[CONF_API_KEY],
149  str(latitude),
150  str(longitude),
151  session=async_get_clientsession(self.hass),
152  ).realtime([TMRW_ATTR_TEMPERATURE])
153  except CantConnectException:
154  errors["base"] = "cannot_connect"
155  except InvalidAPIKeyException:
156  errors[CONF_API_KEY] = "invalid_api_key"
157  except RateLimitedException:
158  errors[CONF_API_KEY] = "rate_limited"
159  except Exception:
160  _LOGGER.exception("Unexpected exception")
161  errors["base"] = "unknown"
162 
163  if not errors:
164  options: Mapping[str, Any] = {CONF_TIMESTEP: DEFAULT_TIMESTEP}
165  return self.async_create_entryasync_create_entryasync_create_entry(
166  title=user_input[CONF_NAME],
167  data=user_input,
168  options=options,
169  )
170 
171  return self.async_show_formasync_show_formasync_show_form(
172  step_id="user",
173  data_schema=_get_config_schema(self.hass, self.sourcesourcesource, user_input),
174  errors=errors,
175  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:128
TomorrowioOptionsConfigFlow async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:122
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:96
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)
None config_entry(self, ConfigEntry value)
str
_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)
def _get_unique_id(HomeAssistant hass, dict[str, Any] input_dict)
Definition: config_flow.py:82
vol.Schema _get_config_schema(HomeAssistant hass, str|None source, dict[str, Any]|None input_dict=None)
Definition: config_flow.py:51
State|None async_active_zone(HomeAssistant hass, float latitude, float longitude, int radius=0)
Definition: __init__.py:115
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)