Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Tesla Wall Connector integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from tesla_wall_connector import WallConnector
9 from tesla_wall_connector.exceptions import WallConnectorError
10 import voluptuous as vol
11 
12 from homeassistant.components import dhcp
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_HOST
15 from homeassistant.core import HomeAssistant
16 from homeassistant.helpers.aiohttp_client import async_get_clientsession
17 
18 from .const import DOMAIN, WALLCONNECTOR_DEVICE_NAME, WALLCONNECTOR_SERIAL_NUMBER
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
23 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
24  """Validate the user input allows us to connect.
25 
26  Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
27  """
28  wall_connector = WallConnector(
29  host=data[CONF_HOST], session=async_get_clientsession(hass)
30  )
31 
32  version = await wall_connector.async_get_version()
33 
34  return {
35  "title": WALLCONNECTOR_DEVICE_NAME,
36  WALLCONNECTOR_SERIAL_NUMBER: version.serial_number,
37  }
38 
39 
41  """Handle a config flow for Tesla Wall Connector."""
42 
43  VERSION = 1
44 
45  def __init__(self) -> None:
46  """Initialize config flow."""
47  super().__init__()
48  self.ip_addressip_address: str | None = None
49 
50  async def async_step_dhcp(
51  self, discovery_info: dhcp.DhcpServiceInfo
52  ) -> ConfigFlowResult:
53  """Handle dhcp discovery."""
54  self.ip_addressip_address = discovery_info.ip
55  _LOGGER.debug("Discovered Tesla Wall Connector at [%s]", self.ip_addressip_address)
56 
57  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: self.ip_addressip_address})
58 
59  try:
60  wall_connector = WallConnector(
61  host=self.ip_addressip_address, session=async_get_clientsession(self.hass)
62  )
63  version = await wall_connector.async_get_version()
64  except WallConnectorError as ex:
65  _LOGGER.debug(
66  "Could not read serial number from Tesla WallConnector at [%s]: [%s]",
67  self.ip_addressip_address,
68  ex,
69  )
70  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
71 
72  serial_number: str = version.serial_number
73 
74  await self.async_set_unique_idasync_set_unique_id(serial_number)
75  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates={CONF_HOST: self.ip_addressip_address})
76 
77  _LOGGER.debug(
78  "No entry found for wall connector with IP %s. Serial nr: %s",
79  self.ip_addressip_address,
80  serial_number,
81  )
82 
83  self.context["title_placeholders"] = {
84  CONF_HOST: self.ip_addressip_address,
85  WALLCONNECTOR_SERIAL_NUMBER: serial_number,
86  }
87  return await self.async_step_userasync_step_userasync_step_user()
88 
89  async def async_step_user(
90  self, user_input: dict[str, Any] | None = None
91  ) -> ConfigFlowResult:
92  """Handle the initial step."""
93  data_schema = vol.Schema(
94  {vol.Required(CONF_HOST, default=self.ip_addressip_address): str}
95  )
96  if user_input is None:
97  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=data_schema)
98  errors = {}
99 
100  try:
101  info = await validate_input(self.hass, user_input)
102  except WallConnectorError:
103  errors["base"] = "cannot_connect"
104  except Exception:
105  _LOGGER.exception("Unexpected exception")
106  errors["base"] = "unknown"
107 
108  if not errors:
109  await self.async_set_unique_idasync_set_unique_id(
110  unique_id=info[WALLCONNECTOR_SERIAL_NUMBER], raise_on_progress=True
111  )
112  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
113  updates=user_input, reload_on_update=True
114  )
115 
116  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
117 
118  return self.async_show_formasync_show_formasync_show_form(
119  step_id="user", data_schema=data_schema, errors=errors
120  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:91
ConfigFlowResult async_step_dhcp(self, dhcp.DhcpServiceInfo discovery_info)
Definition: config_flow.py:52
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_step_user(self, dict[str, Any]|None user_input=None)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
dict[str, Any] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:23
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)