Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for iotawatt integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from iotawattpy.iotawatt import Iotawatt
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
12 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import HomeAssistantError
15 from homeassistant.helpers import httpx_client
16 
17 from .const import CONNECTION_ERRORS, DOMAIN
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 
22 async def validate_input(hass: HomeAssistant, data: dict[str, str]) -> dict[str, str]:
23  """Validate the user input allows us to connect."""
24  iotawatt = Iotawatt(
25  "",
26  data[CONF_HOST],
27  httpx_client.get_async_client(hass),
28  data.get(CONF_USERNAME),
29  data.get(CONF_PASSWORD),
30  )
31  try:
32  is_connected = await iotawatt.connect()
33  except CONNECTION_ERRORS:
34  return {"base": "cannot_connect"}
35  except Exception:
36  _LOGGER.exception("Unexpected exception")
37  return {"base": "unknown"}
38 
39  if not is_connected:
40  return {"base": "invalid_auth"}
41 
42  return {}
43 
44 
45 class IOTaWattConfigFlow(ConfigFlow, domain=DOMAIN):
46  """Handle a config flow for iotawatt."""
47 
48  VERSION = 1
49 
50  def __init__(self) -> None:
51  """Initialize."""
52  self._data: dict[str, Any] = {}
53 
54  async def async_step_user(
55  self, user_input: dict[str, Any] | None = None
56  ) -> ConfigFlowResult:
57  """Handle the initial step."""
58  if user_input is None:
59  user_input = {}
60 
61  schema = vol.Schema(
62  {
63  vol.Required(CONF_HOST, default=user_input.get(CONF_HOST, "")): str,
64  }
65  )
66  if not user_input:
67  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=schema)
68 
69  if not (errors := await validate_input(self.hass, user_input)):
70  return self.async_create_entryasync_create_entryasync_create_entry(title=user_input[CONF_HOST], data=user_input)
71 
72  if errors == {"base": "invalid_auth"}:
73  self._data.update(user_input)
74  return await self.async_step_authasync_step_auth()
75 
76  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=schema, errors=errors)
77 
78  async def async_step_auth(
79  self, user_input: dict[str, Any] | None = None
80  ) -> ConfigFlowResult:
81  """Authenticate user if authentication is enabled on the IoTaWatt device."""
82  if user_input is None:
83  user_input = {}
84 
85  data_schema = vol.Schema(
86  {
87  vol.Required(
88  CONF_USERNAME, default=user_input.get(CONF_USERNAME, "")
89  ): str,
90  vol.Required(
91  CONF_PASSWORD, default=user_input.get(CONF_PASSWORD, "")
92  ): str,
93  }
94  )
95  if not user_input:
96  return self.async_show_formasync_show_formasync_show_form(step_id="auth", data_schema=data_schema)
97 
98  data = {**self._data, **user_input}
99 
100  if errors := await validate_input(self.hass, data):
101  return self.async_show_formasync_show_formasync_show_form(
102  step_id="auth", data_schema=data_schema, errors=errors
103  )
104 
105  return self.async_create_entryasync_create_entryasync_create_entry(title=data[CONF_HOST], data=data)
106 
107 
109  """Error to indicate we cannot connect."""
110 
111 
112 class InvalidAuth(HomeAssistantError):
113  """Error to indicate there is invalid auth."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:56
ConfigFlowResult async_step_auth(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:80
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, str] data)
Definition: config_flow.py:22
IssData update(pyiss.ISS iss)
Definition: __init__.py:33