-
-
Notifications
You must be signed in to change notification settings - Fork 32k
/
Copy pathconfig_flow.py
333 lines (265 loc) · 10.5 KB
/
config_flow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
"""Config flow to configure deCONZ component."""
from __future__ import annotations
import asyncio
from collections.abc import Mapping
import logging
from pprint import pformat
from typing import Any, cast
from urllib.parse import urlparse
from pydeconz.errors import LinkButtonNotPressed, RequestError, ResponseError
from pydeconz.gateway import DeconzSession
from pydeconz.utils import (
DiscoveredBridge,
discovery as deconz_discovery,
get_bridge_id as deconz_get_bridge_id,
normalize_bridge_id,
)
import voluptuous as vol
from homeassistant.components import ssdp
from homeassistant.config_entries import (
SOURCE_HASSIO,
ConfigEntry,
ConfigFlow,
ConfigFlowResult,
OptionsFlow,
)
from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.service_info.hassio import HassioServiceInfo
from .const import (
CONF_ALLOW_CLIP_SENSOR,
CONF_ALLOW_DECONZ_GROUPS,
CONF_ALLOW_NEW_DEVICES,
DEFAULT_ALLOW_CLIP_SENSOR,
DEFAULT_ALLOW_DECONZ_GROUPS,
DEFAULT_ALLOW_NEW_DEVICES,
DEFAULT_PORT,
DOMAIN,
HASSIO_CONFIGURATION_URL,
LOGGER,
)
from .hub import DeconzHub
DECONZ_MANUFACTURERURL = "http://www.dresden-elektronik.de"
CONF_SERIAL = "serial"
CONF_MANUAL_INPUT = "Manually define gateway"
@callback
def get_master_hub(hass: HomeAssistant) -> DeconzHub:
"""Return the gateway which is marked as master."""
for hub in hass.data[DOMAIN].values():
if hub.master:
return cast(DeconzHub, hub)
raise ValueError
class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
"""Handle a deCONZ config flow."""
VERSION = 1
_hassio_discovery: dict[str, Any]
bridges: list[DiscoveredBridge]
host: str
port: int
api_key: str
@staticmethod
@callback
def async_get_options_flow(
config_entry: ConfigEntry,
) -> DeconzOptionsFlowHandler:
"""Get the options flow for this handler."""
return DeconzOptionsFlowHandler()
def __init__(self) -> None:
"""Initialize the deCONZ config flow."""
self.bridge_id = ""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a deCONZ config flow start.
Let user choose between discovered bridges and manual configuration.
If no bridge is found allow user to manually input configuration.
"""
if user_input is not None:
if user_input[CONF_HOST] == CONF_MANUAL_INPUT:
return await self.async_step_manual_input()
for bridge in self.bridges:
if bridge[CONF_HOST] == user_input[CONF_HOST]:
self.bridge_id = bridge["id"]
self.host = bridge[CONF_HOST]
self.port = bridge[CONF_PORT]
return await self.async_step_link()
session = aiohttp_client.async_get_clientsession(self.hass)
try:
async with asyncio.timeout(10):
self.bridges = await deconz_discovery(session)
except (TimeoutError, ResponseError):
self.bridges = []
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("Discovered deCONZ gateways %s", pformat(self.bridges))
if self.bridges:
hosts = [bridge[CONF_HOST] for bridge in self.bridges]
hosts.append(CONF_MANUAL_INPUT)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({vol.Optional(CONF_HOST): vol.In(hosts)}),
)
return await self.async_step_manual_input()
async def async_step_manual_input(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Manual configuration."""
if user_input:
self.host = user_input[CONF_HOST]
self.port = user_input[CONF_PORT]
return await self.async_step_link()
return self.async_show_form(
step_id="manual_input",
data_schema=vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
}
),
)
async def async_step_link(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Attempt to link with the deCONZ bridge."""
errors: dict[str, str] = {}
LOGGER.debug(
"Preparing linking with deCONZ gateway %s %d", self.host, self.port
)
if user_input is not None:
session = aiohttp_client.async_get_clientsession(self.hass)
deconz_session = DeconzSession(session, self.host, self.port)
try:
async with asyncio.timeout(10):
api_key = await deconz_session.get_api_key()
except LinkButtonNotPressed:
errors["base"] = "linking_not_possible"
except (ResponseError, RequestError, TimeoutError):
errors["base"] = "no_key"
else:
self.api_key = api_key
return await self._create_entry()
return self.async_show_form(step_id="link", errors=errors)
async def _create_entry(self) -> ConfigFlowResult:
"""Create entry for gateway."""
if not self.bridge_id:
session = aiohttp_client.async_get_clientsession(self.hass)
try:
async with asyncio.timeout(10):
self.bridge_id = await deconz_get_bridge_id(
session, self.host, self.port, self.api_key
)
await self.async_set_unique_id(self.bridge_id)
self._abort_if_unique_id_configured(
updates={
CONF_HOST: self.host,
CONF_PORT: self.port,
CONF_API_KEY: self.api_key,
}
)
except TimeoutError:
return self.async_abort(reason="no_bridges")
return self.async_create_entry(
title=self.bridge_id,
data={
CONF_HOST: self.host,
CONF_PORT: self.port,
CONF_API_KEY: self.api_key,
},
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Trigger a reauthentication flow."""
self.context["title_placeholders"] = {CONF_HOST: entry_data[CONF_HOST]}
self.host = entry_data[CONF_HOST]
self.port = entry_data[CONF_PORT]
return await self.async_step_link()
async def async_step_ssdp(
self, discovery_info: ssdp.SsdpServiceInfo
) -> ConfigFlowResult:
"""Handle a discovered deCONZ bridge."""
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("deCONZ SSDP discovery %s", pformat(discovery_info))
self.bridge_id = normalize_bridge_id(discovery_info.upnp[ssdp.ATTR_UPNP_SERIAL])
parsed_url = urlparse(discovery_info.ssdp_location)
entry = await self.async_set_unique_id(self.bridge_id)
if entry and entry.source == SOURCE_HASSIO:
return self.async_abort(reason="already_configured")
self.host = cast(str, parsed_url.hostname)
self.port = cast(int, parsed_url.port)
self._abort_if_unique_id_configured(
updates={
CONF_HOST: self.host,
CONF_PORT: self.port,
}
)
self.context.update(
{
"title_placeholders": {"host": self.host},
"configuration_url": f"http://{self.host}:{self.port}",
}
)
return await self.async_step_link()
async def async_step_hassio(
self, discovery_info: HassioServiceInfo
) -> ConfigFlowResult:
"""Prepare configuration for a Hass.io deCONZ bridge.
This flow is triggered by the discovery component.
"""
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("deCONZ HASSIO discovery %s", pformat(discovery_info.config))
self.bridge_id = normalize_bridge_id(discovery_info.config[CONF_SERIAL])
await self.async_set_unique_id(self.bridge_id)
self.host = discovery_info.config[CONF_HOST]
self.port = discovery_info.config[CONF_PORT]
self.api_key = discovery_info.config[CONF_API_KEY]
self._abort_if_unique_id_configured(
updates={
CONF_HOST: self.host,
CONF_PORT: self.port,
CONF_API_KEY: self.api_key,
}
)
self.context["configuration_url"] = HASSIO_CONFIGURATION_URL
self._hassio_discovery = discovery_info.config
return await self.async_step_hassio_confirm()
async def async_step_hassio_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm a Hass.io discovery."""
if user_input is not None:
return await self._create_entry()
return self.async_show_form(
step_id="hassio_confirm",
description_placeholders={"addon": self._hassio_discovery["addon"]},
)
class DeconzOptionsFlowHandler(OptionsFlow):
"""Handle deCONZ options."""
gateway: DeconzHub
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Manage the deCONZ options."""
return await self.async_step_deconz_devices()
async def async_step_deconz_devices(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Manage the deconz devices options."""
if user_input is not None:
return self.async_create_entry(data=self.config_entry.options | user_input)
schema_options = {}
for option, default in (
(CONF_ALLOW_CLIP_SENSOR, DEFAULT_ALLOW_CLIP_SENSOR),
(CONF_ALLOW_DECONZ_GROUPS, DEFAULT_ALLOW_DECONZ_GROUPS),
(CONF_ALLOW_NEW_DEVICES, DEFAULT_ALLOW_NEW_DEVICES),
):
schema_options[
vol.Optional(
option,
default=self.config_entry.options.get(option, default),
)
] = bool
return self.async_show_form(
step_id="deconz_devices",
data_schema=vol.Schema(schema_options),
)