Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Fully Kiosk Browser integration."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 import json
7 from typing import Any
8 
9 from aiohttp.client_exceptions import ClientConnectorError
10 from fullykiosk import FullyKiosk
11 from fullykiosk.exceptions import FullyKioskError
12 import voluptuous as vol
13 
14 from homeassistant.components.dhcp import DhcpServiceInfo
15 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
16 from homeassistant.const import (
17  CONF_HOST,
18  CONF_MAC,
19  CONF_PASSWORD,
20  CONF_SSL,
21  CONF_VERIFY_SSL,
22 )
23 from homeassistant.helpers.aiohttp_client import async_get_clientsession
24 from homeassistant.helpers.device_registry import format_mac
25 from homeassistant.helpers.service_info.mqtt import MqttServiceInfo
26 
27 from .const import DEFAULT_PORT, DOMAIN, LOGGER
28 
29 
30 class FullyKioskConfigFlow(ConfigFlow, domain=DOMAIN):
31  """Handle a config flow for Fully Kiosk Browser."""
32 
33  VERSION = 1
34 
35  host: str
36 
37  def __init__(self) -> None:
38  """Initialize the config flow."""
39  self._discovered_device_info_discovered_device_info: dict[str, Any] = {}
40 
41  async def _create_entry(
42  self,
43  host: str,
44  user_input: dict[str, Any],
45  errors: dict[str, str],
46  description_placeholders: dict[str, str] | Any = None,
47  ) -> ConfigFlowResult | None:
48  fully = FullyKiosk(
49  async_get_clientsession(self.hass),
50  host,
51  DEFAULT_PORT,
52  user_input[CONF_PASSWORD],
53  use_ssl=user_input[CONF_SSL],
54  verify_ssl=user_input[CONF_VERIFY_SSL],
55  )
56 
57  try:
58  async with asyncio.timeout(15):
59  device_info = await fully.getDeviceInfo()
60  except (
61  ClientConnectorError,
62  FullyKioskError,
63  TimeoutError,
64  ) as error:
65  LOGGER.debug(error.args, exc_info=True)
66  errors["base"] = "cannot_connect"
67  description_placeholders["error_detail"] = str(error.args)
68  return None
69  except Exception as error: # noqa: BLE001
70  LOGGER.exception("Unexpected exception: %s", error)
71  errors["base"] = "unknown"
72  description_placeholders["error_detail"] = str(error.args)
73  return None
74 
75  await self.async_set_unique_idasync_set_unique_id(device_info["deviceID"], raise_on_progress=False)
76  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates=user_input)
77  return self.async_create_entryasync_create_entryasync_create_entry(
78  title=device_info["deviceName"],
79  data={
80  CONF_HOST: host,
81  CONF_PASSWORD: user_input[CONF_PASSWORD],
82  CONF_MAC: format_mac(device_info["Mac"]),
83  CONF_SSL: user_input[CONF_SSL],
84  CONF_VERIFY_SSL: user_input[CONF_VERIFY_SSL],
85  },
86  )
87 
88  async def async_step_user(
89  self, user_input: dict[str, Any] | None = None
90  ) -> ConfigFlowResult:
91  """Handle the initial step."""
92  errors: dict[str, str] = {}
93  placeholders: dict[str, str] = {}
94  if user_input is not None:
95  result = await self._create_entry_create_entry(
96  user_input[CONF_HOST], user_input, errors, placeholders
97  )
98  if result:
99  return result
100 
101  return self.async_show_formasync_show_formasync_show_form(
102  step_id="user",
103  data_schema=vol.Schema(
104  {
105  vol.Required(CONF_HOST): str,
106  vol.Required(CONF_PASSWORD): str,
107  vol.Optional(CONF_SSL, default=False): bool,
108  vol.Optional(CONF_VERIFY_SSL, default=False): bool,
109  }
110  ),
111  description_placeholders=placeholders,
112  errors=errors,
113  )
114 
115  async def async_step_dhcp(
116  self, discovery_info: DhcpServiceInfo
117  ) -> ConfigFlowResult:
118  """Handle dhcp discovery."""
119  mac = format_mac(discovery_info.macaddress)
120 
121  for entry in self._async_current_entries_async_current_entries():
122  if entry.data[CONF_MAC] == mac:
123  self.hass.config_entries.async_update_entry(
124  entry,
125  data=entry.data | {CONF_HOST: discovery_info.ip},
126  )
127  self.hass.async_create_task(
128  self.hass.config_entries.async_reload(entry.entry_id)
129  )
130  return self.async_abortasync_abortasync_abort(reason="already_configured")
131 
132  return self.async_abortasync_abortasync_abort(reason="unknown")
133 
135  self, user_input: dict[str, Any] | None = None
136  ) -> ConfigFlowResult:
137  """Confirm discovery."""
138  errors: dict[str, str] = {}
139  if user_input is not None:
140  result = await self._create_entry_create_entry(self.hosthost, user_input, errors)
141  if result:
142  return result
143 
144  placeholders = {
145  "name": self._discovered_device_info_discovered_device_info["deviceName"],
146  CONF_HOST: self.hosthost,
147  }
148  self.context["title_placeholders"] = placeholders
149  return self.async_show_formasync_show_formasync_show_form(
150  step_id="discovery_confirm",
151  data_schema=vol.Schema(
152  {
153  vol.Required(CONF_PASSWORD): str,
154  vol.Optional(CONF_SSL, default=False): bool,
155  vol.Optional(CONF_VERIFY_SSL, default=False): bool,
156  }
157  ),
158  description_placeholders=placeholders,
159  errors=errors,
160  )
161 
162  async def async_step_mqtt(
163  self, discovery_info: MqttServiceInfo
164  ) -> ConfigFlowResult:
165  """Handle a flow initialized by MQTT discovery."""
166  device_info: dict[str, Any] = json.loads(discovery_info.payload)
167  device_id: str = device_info["deviceId"]
168  await self.async_set_unique_idasync_set_unique_id(device_id)
169  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
170 
171  self.hosthost = device_info["hostname4"]
172  self._discovered_device_info_discovered_device_info = device_info
173  return await self.async_step_discovery_confirmasync_step_discovery_confirm()
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:90
ConfigFlowResult|None _create_entry(self, str host, dict[str, Any] user_input, dict[str, str] errors, dict[str, str]|Any description_placeholders=None)
Definition: config_flow.py:47
ConfigFlowResult async_step_mqtt(self, MqttServiceInfo discovery_info)
Definition: config_flow.py:164
ConfigFlowResult async_step_discovery_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:136
ConfigFlowResult async_step_dhcp(self, DhcpServiceInfo discovery_info)
Definition: config_flow.py:117
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)
list[ConfigEntry] _async_current_entries(self, bool|None include_ignore=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)
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)
_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)