Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """The lookin integration config_flow."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import aiohttp
9 from aiolookin import Device, LookInHttpProtocol, NoUsableService
10 import voluptuous as vol
11 
12 from homeassistant.components import zeroconf
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_HOST
15 from homeassistant.helpers.aiohttp_client import async_get_clientsession
16 
17 from .const import DOMAIN
18 
19 LOGGER = logging.getLogger(__name__)
20 
21 
22 class LookinFlowHandler(ConfigFlow, domain=DOMAIN):
23  """Handle a config flow for lookin."""
24 
25  def __init__(self) -> None:
26  """Init the lookin flow."""
27  self._host_host: str | None = None
28  self._name_name: str | None = None
29 
31  self, discovery_info: zeroconf.ZeroconfServiceInfo
32  ) -> ConfigFlowResult:
33  """Start a discovery flow from zeroconf."""
34  uid: str = discovery_info.hostname.removesuffix(".local.")
35  host: str = discovery_info.host
36  await self.async_set_unique_idasync_set_unique_id(uid.upper())
37  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates={CONF_HOST: host})
38 
39  try:
40  device: Device = await self._validate_device_validate_device(host=host)
41  except (aiohttp.ClientError, NoUsableService):
42  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
43  except Exception:
44  LOGGER.exception("Unexpected exception")
45  return self.async_abortasync_abortasync_abort(reason="unknown")
46 
47  self._name_name = device.name
48  self._host_host = host
49  self._set_confirm_only_set_confirm_only()
50  self.context["title_placeholders"] = {
51  "name": self._name_name or "LOOKin",
52  "host": host,
53  }
54  return await self.async_step_discovery_confirmasync_step_discovery_confirm()
55 
56  async def async_step_user(
57  self, user_input: dict[str, Any] | None = None
58  ) -> ConfigFlowResult:
59  """User initiated discover flow."""
60  errors: dict[str, str] = {}
61 
62  if user_input is not None:
63  host = user_input[CONF_HOST]
64  try:
65  device = await self._validate_device_validate_device(host=host)
66  except (aiohttp.ClientError, NoUsableService):
67  errors[CONF_HOST] = "cannot_connect"
68  except Exception:
69  LOGGER.exception("Unexpected exception")
70  errors["base"] = "unknown"
71  else:
72  device_id = device.id.upper()
73  await self.async_set_unique_idasync_set_unique_id(device_id, raise_on_progress=False)
74  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates={CONF_HOST: host})
75  return self.async_create_entryasync_create_entryasync_create_entry(
76  title=device.name or host,
77  data={CONF_HOST: host},
78  )
79 
80  return self.async_show_formasync_show_formasync_show_form(
81  step_id="user",
82  data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
83  errors=errors,
84  )
85 
86  async def _validate_device(self, host: str) -> Device:
87  """Validate we can connect to the device."""
88  session = async_get_clientsession(self.hass)
89  lookin_protocol = LookInHttpProtocol(f"http://{host}", session)
90  return await lookin_protocol.get_info()
91 
93  self, user_input: dict[str, Any] | None = None
94  ) -> ConfigFlowResult:
95  """Confirm the discover flow."""
96  assert self._host_host is not None
97  if user_input is None:
98  return self.async_show_formasync_show_formasync_show_form(
99  step_id="discovery_confirm",
100  description_placeholders={
101  "name": self._name_name or "LOOKin",
102  "host": self._host_host,
103  },
104  )
105 
106  return self.async_create_entryasync_create_entryasync_create_entry(
107  title=self._name_name or self._host_host,
108  data={CONF_HOST: self._host_host},
109  )
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:32
ConfigFlowResult async_step_discovery_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:94
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:58
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)
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)
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)