Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Nanoleaf integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 import os
8 from typing import Any, Final, cast
9 
10 from aionanoleaf import InvalidToken, Nanoleaf, Unauthorized, Unavailable
11 import voluptuous as vol
12 
13 from homeassistant.components import ssdp, zeroconf
14 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
15 from homeassistant.const import CONF_HOST, CONF_TOKEN
16 from homeassistant.helpers.aiohttp_client import async_get_clientsession
17 from homeassistant.helpers.json import save_json
18 from homeassistant.util.json import JsonObjectType, JsonValueType, load_json_object
19 
20 from .const import DOMAIN
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 # For discovery integration import
25 CONFIG_FILE: Final = ".nanoleaf.conf"
26 
27 USER_SCHEMA: Final = vol.Schema(
28  {
29  vol.Required(CONF_HOST): str,
30  }
31 )
32 
33 
34 class NanoleafConfigFlow(ConfigFlow, domain=DOMAIN):
35  """Nanoleaf config flow."""
36 
37  nanoleaf: Nanoleaf
38 
39  # For discovery integration import
40  discovery_conf: JsonObjectType
41  device_id: str
42 
43  VERSION = 1
44 
45  async def async_step_user(
46  self, user_input: dict[str, Any] | None = None
47  ) -> ConfigFlowResult:
48  """Handle Nanoleaf flow initiated by the user."""
49  if user_input is None:
50  return self.async_show_formasync_show_formasync_show_form(
51  step_id="user", data_schema=USER_SCHEMA, last_step=False
52  )
53  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
54  self.nanoleafnanoleaf = Nanoleaf(
55  async_get_clientsession(self.hass), user_input[CONF_HOST]
56  )
57  try:
58  await self.nanoleafnanoleaf.authorize()
59  except Unavailable:
60  return self.async_show_formasync_show_formasync_show_form(
61  step_id="user",
62  data_schema=USER_SCHEMA,
63  errors={"base": "cannot_connect"},
64  last_step=False,
65  )
66  except Unauthorized:
67  pass
68  except Exception:
69  _LOGGER.exception("Unknown error connecting to Nanoleaf")
70  return self.async_show_formasync_show_formasync_show_form(
71  step_id="user",
72  data_schema=USER_SCHEMA,
73  last_step=False,
74  errors={"base": "unknown"},
75  )
76  return await self.async_step_linkasync_step_link()
77 
78  async def async_step_reauth(
79  self, entry_data: Mapping[str, Any]
80  ) -> ConfigFlowResult:
81  """Handle Nanoleaf reauth flow if token is invalid."""
82  self.nanoleafnanoleaf = Nanoleaf(
83  async_get_clientsession(self.hass), entry_data[CONF_HOST]
84  )
85  self.context["title_placeholders"] = {"name": self._get_reauth_entry_get_reauth_entry().title}
86  return await self.async_step_linkasync_step_link()
87 
89  self, discovery_info: zeroconf.ZeroconfServiceInfo
90  ) -> ConfigFlowResult:
91  """Handle Nanoleaf Zeroconf discovery."""
92  _LOGGER.debug("Zeroconf discovered: %s", discovery_info)
93  return await self._async_homekit_zeroconf_discovery_handler_async_homekit_zeroconf_discovery_handler(discovery_info)
94 
95  async def async_step_homekit(
96  self, discovery_info: zeroconf.ZeroconfServiceInfo
97  ) -> ConfigFlowResult:
98  """Handle Nanoleaf Homekit discovery."""
99  _LOGGER.debug("Homekit discovered: %s", discovery_info)
100  return await self._async_homekit_zeroconf_discovery_handler_async_homekit_zeroconf_discovery_handler(discovery_info)
101 
103  self, discovery_info: zeroconf.ZeroconfServiceInfo
104  ) -> ConfigFlowResult:
105  """Handle Nanoleaf Homekit and Zeroconf discovery."""
106  return await self._async_discovery_handler_async_discovery_handler(
107  discovery_info.host,
108  discovery_info.name.replace(f".{discovery_info.type}", ""),
109  discovery_info.properties[zeroconf.ATTR_PROPERTIES_ID],
110  )
111 
112  async def async_step_ssdp(
113  self, discovery_info: ssdp.SsdpServiceInfo
114  ) -> ConfigFlowResult:
115  """Handle Nanoleaf SSDP discovery."""
116  _LOGGER.debug("SSDP discovered: %s", discovery_info)
117  return await self._async_discovery_handler_async_discovery_handler(
118  discovery_info.ssdp_headers["_host"],
119  discovery_info.ssdp_headers["nl-devicename"],
120  discovery_info.ssdp_headers["nl-deviceid"],
121  )
122 
124  self, host: str, name: str, device_id: str
125  ) -> ConfigFlowResult:
126  """Handle Nanoleaf discovery."""
127  # The name is unique and printed on the device and cannot be changed.
128  await self.async_set_unique_idasync_set_unique_id(name)
129  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_HOST: host})
130 
131  # Import from discovery integration
132  self.device_iddevice_id = device_id
133  self.discovery_confdiscovery_conf = await self.hass.async_add_executor_job(
134  load_json_object, self.hass.config.path(CONFIG_FILE)
135  )
136 
137  auth_token: JsonValueType = None
138  if device_conf := self.discovery_confdiscovery_conf.get(self.device_iddevice_id): # >= 2021.4
139  auth_token = cast(JsonObjectType, device_conf).get("token")
140  if not auth_token and (host_conf := self.discovery_confdiscovery_conf.get(host)): # < 2021.4
141  auth_token = cast(JsonObjectType, host_conf).get("token")
142 
143  if auth_token is not None:
144  self.nanoleafnanoleaf = Nanoleaf(
145  async_get_clientsession(self.hass), host, cast(str, auth_token)
146  )
147  _LOGGER.warning(
148  "Importing Nanoleaf %s from the discovery integration", name
149  )
150  return await self.async_setup_finishasync_setup_finish(discovery_integration_import=True)
151  self.nanoleafnanoleaf = Nanoleaf(async_get_clientsession(self.hass), host)
152  self.context["title_placeholders"] = {"name": name}
153  return await self.async_step_linkasync_step_link()
154 
155  async def async_step_link(
156  self, user_input: dict[str, Any] | None = None
157  ) -> ConfigFlowResult:
158  """Handle Nanoleaf link step."""
159  if user_input is None:
160  return self.async_show_formasync_show_formasync_show_form(step_id="link")
161 
162  try:
163  await self.nanoleafnanoleaf.authorize()
164  except Unauthorized:
165  return self.async_show_formasync_show_formasync_show_form(
166  step_id="link", errors={"base": "not_allowing_new_tokens"}
167  )
168  except Unavailable:
169  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
170  except Exception:
171  _LOGGER.exception("Unknown error authorizing Nanoleaf")
172  return self.async_show_formasync_show_formasync_show_form(step_id="link", errors={"base": "unknown"})
173 
174  if self.sourcesourcesourcesource == SOURCE_REAUTH:
175  return self.async_update_reload_and_abortasync_update_reload_and_abort(
176  self._get_reauth_entry_get_reauth_entry(),
177  data_updates={CONF_TOKEN: self.nanoleafnanoleaf.auth_token},
178  )
179 
180  return await self.async_setup_finishasync_setup_finish()
181 
183  self, discovery_integration_import: bool = False
184  ) -> ConfigFlowResult:
185  """Finish Nanoleaf config flow."""
186  try:
187  await self.nanoleafnanoleaf.get_info()
188  except Unavailable:
189  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
190  except InvalidToken:
191  return self.async_abortasync_abortasync_abort(reason="invalid_token")
192  except Exception:
193  _LOGGER.exception(
194  "Unknown error connecting with Nanoleaf at %s", self.nanoleafnanoleaf.host
195  )
196  return self.async_abortasync_abortasync_abort(reason="unknown")
197  name = self.nanoleafnanoleaf.name
198 
199  await self.async_set_unique_idasync_set_unique_id(name)
200  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_HOST: self.nanoleafnanoleaf.host})
201 
202  if discovery_integration_import:
203  if self.nanoleafnanoleaf.host in self.discovery_confdiscovery_conf:
204  self.discovery_confdiscovery_conf.pop(self.nanoleafnanoleaf.host)
205  if self.device_iddevice_id in self.discovery_confdiscovery_conf:
206  self.discovery_confdiscovery_conf.pop(self.device_iddevice_id)
207  _LOGGER.debug(
208  "Successfully imported Nanoleaf %s from the discovery integration",
209  name,
210  )
211  if self.discovery_confdiscovery_conf:
212  await self.hass.async_add_executor_job(
213  save_json, self.hass.config.path(CONFIG_FILE), self.discovery_confdiscovery_conf
214  )
215  else:
216  await self.hass.async_add_executor_job(
217  os.remove, self.hass.config.path(CONFIG_FILE)
218  )
219 
220  return self.async_create_entryasync_create_entryasync_create_entry(
221  title=name,
222  data={
223  CONF_HOST: self.nanoleafnanoleaf.host,
224  CONF_TOKEN: self.nanoleafnanoleaf.auth_token,
225  },
226  )
ConfigFlowResult async_step_link(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:157
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:47
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:80
ConfigFlowResult _async_discovery_handler(self, str host, str name, str device_id)
Definition: config_flow.py:125
ConfigFlowResult async_step_homekit(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:97
ConfigFlowResult _async_homekit_zeroconf_discovery_handler(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:104
ConfigFlowResult async_step_ssdp(self, ssdp.SsdpServiceInfo discovery_info)
Definition: config_flow.py:114
ConfigFlowResult async_setup_finish(self, bool discovery_integration_import=False)
Definition: config_flow.py:184
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:90
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_update_reload_and_abort(self, ConfigEntry entry, *str|None|UndefinedType unique_id=UNDEFINED, str|UndefinedType title=UNDEFINED, Mapping[str, Any]|UndefinedType data=UNDEFINED, Mapping[str, Any]|UndefinedType data_updates=UNDEFINED, Mapping[str, Any]|UndefinedType options=UNDEFINED, str|UndefinedType reason=UNDEFINED, bool reload_even_if_entry_is_unchanged=True)
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)
str|None source(self)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
dict[str, Any]|None get_info(HomeAssistant hass)
Definition: coordinator.py:69
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)