Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Radio Thermostat integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 from urllib.error import URLError
8 
9 from radiotherm.validate import RadiothermTstatError
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.exceptions import HomeAssistantError
17 
18 from .const import DOMAIN
19 from .data import RadioThermInitData, async_get_init_data
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 
25  """Error to indicate we cannot connect."""
26 
27 
28 async def validate_connection(hass: HomeAssistant, host: str) -> RadioThermInitData:
29  """Validate the connection."""
30  try:
31  return await async_get_init_data(hass, host)
32  except (TimeoutError, RadiothermTstatError, URLError, OSError) as ex:
33  raise CannotConnect(f"Failed to connect to {host}: {ex}") from ex
34 
35 
36 class RadioThermConfigFlow(ConfigFlow, domain=DOMAIN):
37  """Handle a config flow for Radio Thermostat."""
38 
39  VERSION = 1
40 
41  def __init__(self) -> None:
42  """Initialize ConfigFlow."""
43  self.discovered_ipdiscovered_ip: str | None = None
44  self.discovered_init_datadiscovered_init_data: RadioThermInitData | None = None
45 
46  async def async_step_dhcp(
47  self, discovery_info: dhcp.DhcpServiceInfo
48  ) -> ConfigFlowResult:
49  """Discover via DHCP."""
50  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: discovery_info.ip})
51  try:
52  init_data = await validate_connection(self.hass, discovery_info.ip)
53  except CannotConnect:
54  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
55  await self.async_set_unique_idasync_set_unique_id(init_data.mac)
56  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
57  updates={CONF_HOST: discovery_info.ip}, reload_on_update=False
58  )
59  self.discovered_init_datadiscovered_init_data = init_data
60  self.discovered_ipdiscovered_ip = discovery_info.ip
61  return await self.async_step_confirmasync_step_confirm()
62 
63  async def async_step_confirm(
64  self, user_input: dict[str, Any] | None = None
65  ) -> ConfigFlowResult:
66  """Attempt to confirm."""
67  ip_address = self.discovered_ipdiscovered_ip
68  init_data = self.discovered_init_datadiscovered_init_data
69  assert ip_address is not None
70  assert init_data is not None
71  if user_input is not None:
72  return self.async_create_entryasync_create_entryasync_create_entry(
73  title=init_data.name,
74  data={CONF_HOST: ip_address},
75  )
76 
77  self._set_confirm_only_set_confirm_only()
78  placeholders = {
79  "name": init_data.name,
80  "host": ip_address,
81  "model": init_data.model or "Unknown",
82  }
83  self.context["title_placeholders"] = placeholders
84  return self.async_show_formasync_show_formasync_show_form(
85  step_id="confirm",
86  description_placeholders=placeholders,
87  )
88 
89  async def async_step_user(
90  self, user_input: dict[str, Any] | None = None
91  ) -> ConfigFlowResult:
92  """Handle the initial step."""
93  errors = {}
94  if user_input is not None:
95  try:
96  init_data = await validate_connection(self.hass, user_input[CONF_HOST])
97  except CannotConnect:
98  errors[CONF_HOST] = "cannot_connect"
99  except Exception:
100  _LOGGER.exception("Unexpected exception")
101  errors["base"] = "unknown"
102  else:
103  await self.async_set_unique_idasync_set_unique_id(init_data.mac, raise_on_progress=False)
104  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
105  updates={CONF_HOST: user_input[CONF_HOST]},
106  reload_on_update=False,
107  )
108  return self.async_create_entryasync_create_entryasync_create_entry(
109  title=init_data.name,
110  data=user_input,
111  )
112 
113  return self.async_show_formasync_show_formasync_show_form(
114  step_id="user",
115  data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
116  errors=errors,
117  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:91
ConfigFlowResult async_step_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:65
ConfigFlowResult async_step_dhcp(self, dhcp.DhcpServiceInfo discovery_info)
Definition: config_flow.py:48
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_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)
RadioThermInitData validate_connection(HomeAssistant hass, str host)
Definition: config_flow.py:28
RadioThermInitData async_get_init_data(HomeAssistant hass, str host)
Definition: data.py:50