Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for pvpc_hourly_pricing."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from aiopvpc import DEFAULT_POWER_KW, PVPCData
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import (
12  SOURCE_REAUTH,
13  ConfigEntry,
14  ConfigFlow,
15  ConfigFlowResult,
16  OptionsFlow,
17 )
18 from homeassistant.const import CONF_API_TOKEN, CONF_NAME
19 from homeassistant.core import callback
20 from homeassistant.helpers.aiohttp_client import async_get_clientsession
21 from homeassistant.util import dt as dt_util
22 
23 from .const import (
24  ATTR_POWER,
25  ATTR_POWER_P3,
26  ATTR_TARIFF,
27  CONF_USE_API_TOKEN,
28  DEFAULT_NAME,
29  DEFAULT_TARIFF,
30  DOMAIN,
31  VALID_POWER,
32  VALID_TARIFF,
33 )
34 
35 _MAIL_TO_LINK = (
36  "[consultasios@ree.es]"
37  "(mailto:consultasios@ree.es?subject=Personal%20token%20request)"
38 )
39 
40 
41 class TariffSelectorConfigFlow(ConfigFlow, domain=DOMAIN):
42  """Handle config flow for `pvpc_hourly_pricing`."""
43 
44  VERSION = 1
45  _name: str | None = None
46  _tariff: str | None = None
47  _power: float | None = None
48  _power_p3: float | None = None
49  _use_api_token: bool = False
50  _api_token: str | None = None
51  _api: PVPCData | None = None
52 
53  @staticmethod
54  @callback
56  config_entry: ConfigEntry,
57  ) -> PVPCOptionsFlowHandler:
58  """Get the options flow for this handler."""
59  return PVPCOptionsFlowHandler()
60 
61  async def async_step_user(
62  self, user_input: dict[str, Any] | None = None
63  ) -> ConfigFlowResult:
64  """Handle the initial step."""
65  if user_input is not None:
66  await self.async_set_unique_idasync_set_unique_id(user_input[ATTR_TARIFF])
67  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
68  if not user_input[CONF_USE_API_TOKEN]:
69  return self.async_create_entryasync_create_entryasync_create_entry(
70  title=user_input[CONF_NAME],
71  data={
72  CONF_NAME: user_input[CONF_NAME],
73  ATTR_TARIFF: user_input[ATTR_TARIFF],
74  ATTR_POWER: user_input[ATTR_POWER],
75  ATTR_POWER_P3: user_input[ATTR_POWER_P3],
76  CONF_API_TOKEN: None,
77  },
78  )
79 
80  self._name_name = user_input[CONF_NAME]
81  self._tariff_tariff = user_input[ATTR_TARIFF]
82  self._power_power = user_input[ATTR_POWER]
83  self._power_p3_power_p3 = user_input[ATTR_POWER_P3]
84  self._use_api_token_use_api_token = user_input[CONF_USE_API_TOKEN]
85  return await self.async_step_api_tokenasync_step_api_token()
86 
87  data_schema = vol.Schema(
88  {
89  vol.Required(CONF_NAME, default=DEFAULT_NAME): str,
90  vol.Required(ATTR_TARIFF, default=DEFAULT_TARIFF): VALID_TARIFF,
91  vol.Required(ATTR_POWER, default=DEFAULT_POWER_KW): VALID_POWER,
92  vol.Required(ATTR_POWER_P3, default=DEFAULT_POWER_KW): VALID_POWER,
93  vol.Required(CONF_USE_API_TOKEN, default=False): bool,
94  }
95  )
96  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=data_schema)
97 
99  self, user_input: dict[str, Any] | None = None
100  ) -> ConfigFlowResult:
101  """Handle optional step to define API token for extra sensors."""
102  if user_input is not None:
103  self._api_token_api_token = user_input[CONF_API_TOKEN]
104  return await self._async_verify_async_verify(
105  "api_token",
106  data_schema=vol.Schema(
107  {vol.Required(CONF_API_TOKEN, default=self._api_token_api_token): str}
108  ),
109  )
110  return self.async_show_formasync_show_formasync_show_form(
111  step_id="api_token",
112  data_schema=vol.Schema(
113  {vol.Required(CONF_API_TOKEN, default=self._api_token_api_token): str}
114  ),
115  description_placeholders={"mail_to_link": _MAIL_TO_LINK},
116  )
117 
118  async def _async_verify(
119  self, step_id: str, data_schema: vol.Schema
120  ) -> ConfigFlowResult:
121  """Attempt to verify the provided configuration."""
122  errors: dict[str, str] = {}
123  auth_ok = True
124  if self._use_api_token_use_api_token:
125  if not self._api_api:
126  self._api_api = PVPCData(session=async_get_clientsession(self.hass))
127  auth_ok = await self._api_api.check_api_token(dt_util.utcnow(), self._api_token_api_token)
128  if not auth_ok:
129  errors["base"] = "invalid_auth"
130  return self.async_show_formasync_show_formasync_show_form(
131  step_id=step_id,
132  data_schema=data_schema,
133  errors=errors,
134  description_placeholders={"mail_to_link": _MAIL_TO_LINK},
135  )
136 
137  data = {
138  CONF_NAME: self._name_name,
139  ATTR_TARIFF: self._tariff_tariff,
140  ATTR_POWER: self._power_power,
141  ATTR_POWER_P3: self._power_p3_power_p3,
142  CONF_API_TOKEN: self._api_token_api_token if self._use_api_token_use_api_token else None,
143  }
144  if self.sourcesourcesourcesource == SOURCE_REAUTH:
145  return self.async_update_reload_and_abortasync_update_reload_and_abort(
146  self._get_reauth_entry_get_reauth_entry(), data=data
147  )
148 
149  assert self._name_name is not None
150  return self.async_create_entryasync_create_entryasync_create_entry(title=self._name_name, data=data)
151 
152  async def async_step_reauth(
153  self, entry_data: Mapping[str, Any]
154  ) -> ConfigFlowResult:
155  """Handle re-authentication with ESIOS Token."""
156  self._api_token_api_token = entry_data.get(CONF_API_TOKEN)
157  self._use_api_token_use_api_token = self._api_token_api_token is not None
158  self._name_name = entry_data[CONF_NAME]
159  self._tariff_tariff = entry_data[ATTR_TARIFF]
160  self._power_power = entry_data[ATTR_POWER]
161  self._power_p3_power_p3 = entry_data[ATTR_POWER_P3]
162  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
163 
165  self, user_input: dict[str, Any] | None = None
166  ) -> ConfigFlowResult:
167  """Confirm reauth dialog."""
168  data_schema = vol.Schema(
169  {
170  vol.Required(CONF_USE_API_TOKEN, default=self._use_api_token_use_api_token): bool,
171  vol.Optional(CONF_API_TOKEN, default=self._api_token_api_token): str,
172  }
173  )
174  if user_input:
175  self._api_token_api_token = user_input[CONF_API_TOKEN]
176  self._use_api_token_use_api_token = user_input[CONF_USE_API_TOKEN]
177  return await self._async_verify_async_verify("reauth_confirm", data_schema)
178  return self.async_show_formasync_show_formasync_show_form(step_id="reauth_confirm", data_schema=data_schema)
179 
180 
182  """Handle PVPC options."""
183 
184  _power: float | None = None
185  _power_p3: float | None = None
186 
188  self, user_input: dict[str, Any] | None = None
189  ) -> ConfigFlowResult:
190  """Handle optional step to define API token for extra sensors."""
191  if user_input is not None and user_input.get(CONF_API_TOKEN):
192  return self.async_create_entryasync_create_entry(
193  title="",
194  data={
195  ATTR_POWER: self._power_power,
196  ATTR_POWER_P3: self._power_p3_power_p3,
197  CONF_API_TOKEN: user_input[CONF_API_TOKEN],
198  },
199  )
200 
201  # Fill options with entry data
202  api_token = self.config_entryconfig_entryconfig_entry.options.get(
203  CONF_API_TOKEN, self.config_entryconfig_entryconfig_entry.data.get(CONF_API_TOKEN)
204  )
205  return self.async_show_formasync_show_form(
206  step_id="api_token",
207  data_schema=vol.Schema(
208  {vol.Required(CONF_API_TOKEN, default=api_token): str}
209  ),
210  description_placeholders={"mail_to_link": _MAIL_TO_LINK},
211  )
212 
213  async def async_step_init(
214  self, user_input: dict[str, Any] | None = None
215  ) -> ConfigFlowResult:
216  """Manage the options."""
217  if user_input is not None:
218  if user_input[CONF_USE_API_TOKEN]:
219  self._power_power = user_input[ATTR_POWER]
220  self._power_p3_power_p3 = user_input[ATTR_POWER_P3]
221  return await self.async_step_api_tokenasync_step_api_token(user_input)
222  return self.async_create_entryasync_create_entry(
223  title="",
224  data={
225  ATTR_POWER: user_input[ATTR_POWER],
226  ATTR_POWER_P3: user_input[ATTR_POWER_P3],
227  CONF_API_TOKEN: None,
228  },
229  )
230 
231  # Fill options with entry data
232  options = self.config_entryconfig_entryconfig_entry.options
233  data = self.config_entryconfig_entryconfig_entry.data
234  power = options.get(ATTR_POWER, data[ATTR_POWER])
235  power_valley = options.get(ATTR_POWER_P3, data[ATTR_POWER_P3])
236  api_token = options.get(CONF_API_TOKEN, data.get(CONF_API_TOKEN))
237  use_api_token = api_token is not None
238  schema = vol.Schema(
239  {
240  vol.Required(ATTR_POWER, default=power): VALID_POWER,
241  vol.Required(ATTR_POWER_P3, default=power_valley): VALID_POWER,
242  vol.Required(CONF_USE_API_TOKEN, default=use_api_token): bool,
243  }
244  )
245  return self.async_show_formasync_show_form(step_id="init", data_schema=schema)
ConfigFlowResult async_step_api_token(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:189
PVPCOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:57
ConfigFlowResult _async_verify(self, str step_id, vol.Schema data_schema)
Definition: config_flow.py:120
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:166
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:63
ConfigFlowResult async_step_api_token(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:100
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:154
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)
None config_entry(self, ConfigEntry value)
_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)
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)