Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the sma integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import pysma
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
12 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_SSL, CONF_VERIFY_SSL
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.aiohttp_client import async_get_clientsession
16 
17 from .const import CONF_GROUP, DOMAIN, GROUPS
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 
22 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
23  """Validate the user input allows us to connect."""
24  session = async_get_clientsession(hass, verify_ssl=data[CONF_VERIFY_SSL])
25 
26  protocol = "https" if data[CONF_SSL] else "http"
27  url = f"{protocol}://{data[CONF_HOST]}"
28 
29  sma = pysma.SMA(session, url, data[CONF_PASSWORD], group=data[CONF_GROUP])
30 
31  # new_session raises SmaAuthenticationException on failure
32  await sma.new_session()
33  device_info = await sma.device_info()
34  await sma.close_session()
35 
36  return device_info
37 
38 
39 class SmaConfigFlow(ConfigFlow, domain=DOMAIN):
40  """Handle a config flow for SMA."""
41 
42  VERSION = 1
43  MINOR_VERSION = 2
44 
45  def __init__(self) -> None:
46  """Initialize."""
47  self._data: dict[str, Any] = {
48  CONF_HOST: vol.UNDEFINED,
49  CONF_SSL: False,
50  CONF_VERIFY_SSL: True,
51  CONF_GROUP: GROUPS[0],
52  CONF_PASSWORD: vol.UNDEFINED,
53  }
54 
55  async def async_step_user(
56  self, user_input: dict[str, Any] | None = None
57  ) -> ConfigFlowResult:
58  """First step in config flow."""
59  errors = {}
60  if user_input is not None:
61  self._data[CONF_HOST] = user_input[CONF_HOST]
62  self._data[CONF_SSL] = user_input[CONF_SSL]
63  self._data[CONF_VERIFY_SSL] = user_input[CONF_VERIFY_SSL]
64  self._data[CONF_GROUP] = user_input[CONF_GROUP]
65  self._data[CONF_PASSWORD] = user_input[CONF_PASSWORD]
66 
67  try:
68  device_info = await validate_input(self.hass, user_input)
69  except pysma.exceptions.SmaConnectionException:
70  errors["base"] = "cannot_connect"
71  except pysma.exceptions.SmaAuthenticationException:
72  errors["base"] = "invalid_auth"
73  except pysma.exceptions.SmaReadException:
74  errors["base"] = "cannot_retrieve_device_info"
75  except Exception:
76  _LOGGER.exception("Unexpected exception")
77  errors["base"] = "unknown"
78 
79  if not errors:
80  await self.async_set_unique_idasync_set_unique_id(str(device_info["serial"]))
81  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates=self._data)
82  return self.async_create_entryasync_create_entryasync_create_entry(
83  title=self._data[CONF_HOST], data=self._data
84  )
85 
86  return self.async_show_formasync_show_formasync_show_form(
87  step_id="user",
88  data_schema=vol.Schema(
89  {
90  vol.Required(CONF_HOST, default=self._data[CONF_HOST]): cv.string,
91  vol.Optional(CONF_SSL, default=self._data[CONF_SSL]): cv.boolean,
92  vol.Optional(
93  CONF_VERIFY_SSL, default=self._data[CONF_VERIFY_SSL]
94  ): cv.boolean,
95  vol.Optional(CONF_GROUP, default=self._data[CONF_GROUP]): vol.In(
96  GROUPS
97  ),
98  vol.Required(CONF_PASSWORD): cv.string,
99  }
100  ),
101  errors=errors,
102  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:57
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)
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)
dict[str, Any] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:22
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)