-
-
Notifications
You must be signed in to change notification settings - Fork 33.4k
/
Copy pathconfig_flow.py
338 lines (278 loc) · 11.1 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
334
335
336
337
338
"""Config flow for Broadlink devices."""
from collections.abc import Mapping
import errno
from functools import partial
import logging
import socket
from typing import Any
import broadlink as blk
from broadlink.exceptions import (
AuthenticationError,
BroadlinkException,
NetworkTimeoutError,
)
import voluptuous as vol
from homeassistant.components import dhcp
from homeassistant.config_entries import (
SOURCE_IMPORT,
SOURCE_REAUTH,
ConfigFlow,
ConfigFlowResult,
)
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_NAME, CONF_TIMEOUT, CONF_TYPE
from homeassistant.data_entry_flow import AbortFlow
from homeassistant.helpers import config_validation as cv
from .const import DEFAULT_PORT, DEFAULT_TIMEOUT, DEVICE_TYPES, DOMAIN
from .helpers import format_mac
_LOGGER = logging.getLogger(__name__)
class BroadlinkFlowHandler(ConfigFlow, domain=DOMAIN):
"""Handle a Broadlink config flow."""
VERSION = 1
device: blk.Device
async def async_set_device(
self, device: blk.Device, raise_on_progress: bool = True
) -> None:
"""Define a device for the config flow."""
if device.type not in DEVICE_TYPES:
_LOGGER.error(
(
"Unsupported device: %s. If it worked before, please open "
"an issue at https://github.com/home-assistant/core/issues"
),
hex(device.devtype),
)
raise AbortFlow("not_supported")
await self.async_set_unique_id(
device.mac.hex(), raise_on_progress=raise_on_progress
)
self.device = device
self.context["title_placeholders"] = {
"name": device.name,
"model": device.model,
"host": device.host[0],
}
async def async_step_dhcp(
self, discovery_info: dhcp.DhcpServiceInfo
) -> ConfigFlowResult:
"""Handle dhcp discovery."""
host = discovery_info.ip
unique_id = discovery_info.macaddress.lower().replace(":", "")
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured(updates={CONF_HOST: host})
try:
device = await self.hass.async_add_executor_job(blk.hello, host)
except NetworkTimeoutError:
return self.async_abort(reason="cannot_connect")
except OSError as err:
if err.errno == errno.ENETUNREACH:
return self.async_abort(reason="cannot_connect")
return self.async_abort(reason="unknown")
if device.type not in DEVICE_TYPES:
return self.async_abort(reason="not_supported")
await self.async_set_device(device)
return await self.async_step_auth()
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a flow initiated by the user."""
errors = {}
if user_input is not None:
host = user_input[CONF_HOST]
timeout = user_input.get(CONF_TIMEOUT, DEFAULT_TIMEOUT)
try:
hello = partial(blk.hello, host, timeout=timeout)
device = await self.hass.async_add_executor_job(hello)
except NetworkTimeoutError:
errors["base"] = "cannot_connect"
err_msg = "Device not found"
except OSError as err:
if err.errno in {errno.EINVAL, socket.EAI_NONAME}:
errors["base"] = "invalid_host"
err_msg = "Invalid hostname or IP address"
elif err.errno == errno.ENETUNREACH:
errors["base"] = "cannot_connect"
err_msg = str(err)
else:
errors["base"] = "unknown"
err_msg = str(err)
else:
device.timeout = timeout
if self.source != SOURCE_REAUTH:
await self.async_set_device(device)
self._abort_if_unique_id_configured(
updates={CONF_HOST: device.host[0], CONF_TIMEOUT: timeout}
)
return await self.async_step_auth()
if device.mac == self.device.mac:
await self.async_set_device(device, raise_on_progress=False)
return await self.async_step_auth()
errors["base"] = "invalid_host"
err_msg = (
"This is not the device you are looking for. The MAC "
f"address must be {format_mac(self.device.mac)}"
)
_LOGGER.error("Failed to connect to the device at %s: %s", host, err_msg)
if self.source == SOURCE_IMPORT:
return self.async_abort(reason=errors["base"])
data_schema = {
vol.Required(CONF_HOST): str,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
}
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(data_schema),
errors=errors,
)
async def async_step_auth(self) -> ConfigFlowResult:
"""Authenticate to the device."""
device = self.device
errors: dict[str, str] = {}
try:
await self.hass.async_add_executor_job(device.auth)
except AuthenticationError:
errors["base"] = "invalid_auth"
await self.async_set_unique_id(device.mac.hex())
return await self.async_step_reset(errors=errors)
except NetworkTimeoutError as err:
errors["base"] = "cannot_connect"
err_msg = str(err)
except BroadlinkException as err:
errors["base"] = "unknown"
err_msg = str(err)
except OSError as err:
if err.errno == errno.ENETUNREACH:
errors["base"] = "cannot_connect"
err_msg = str(err)
else:
errors["base"] = "unknown"
err_msg = str(err)
else:
await self.async_set_unique_id(device.mac.hex())
if self.source == SOURCE_IMPORT:
_LOGGER.warning(
(
"%s (%s at %s) is ready to be configured. Click "
"Configuration in the sidebar, click Integrations and "
"click Configure on the device to complete the setup"
),
device.name,
device.model,
device.host[0],
)
if device.is_locked:
return await self.async_step_unlock()
return await self.async_step_finish()
await self.async_set_unique_id(device.mac.hex())
_LOGGER.error(
"Failed to authenticate to the device at %s: %s", device.host[0], err_msg
)
return self.async_show_form(step_id="auth", errors=errors)
async def async_step_reset(
self,
user_input: dict[str, Any] | None = None,
errors: dict[str, str] | None = None,
) -> ConfigFlowResult:
"""Guide the user to unlock the device manually.
We are unable to authenticate because the device is locked.
The user needs to open the Broadlink app and unlock the device.
"""
device = self.device
if user_input is None:
return self.async_show_form(
step_id="reset",
errors=errors,
description_placeholders={
"name": device.name,
"model": device.model,
"host": device.host[0],
},
)
return await self.async_step_user(
{CONF_HOST: device.host[0], CONF_TIMEOUT: device.timeout}
)
async def async_step_unlock(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Unlock the device.
The authentication succeeded, but the device is locked.
We can offer an unlock to prevent authorization errors.
"""
device = self.device
errors = {}
if user_input is None:
pass
elif user_input["unlock"]:
try:
await self.hass.async_add_executor_job(device.set_lock, False)
except NetworkTimeoutError as err:
errors["base"] = "cannot_connect"
err_msg = str(err)
except BroadlinkException as err:
errors["base"] = "unknown"
err_msg = str(err)
except OSError as err:
if err.errno == errno.ENETUNREACH:
errors["base"] = "cannot_connect"
err_msg = str(err)
else:
errors["base"] = "unknown"
err_msg = str(err)
else:
return await self.async_step_finish()
_LOGGER.error(
"Failed to unlock the device at %s: %s", device.host[0], err_msg
)
else:
return await self.async_step_finish()
data_schema = {vol.Required("unlock", default=False): bool}
return self.async_show_form(
step_id="unlock",
errors=errors,
data_schema=vol.Schema(data_schema),
description_placeholders={
"name": device.name,
"model": device.model,
"host": device.host[0],
},
)
async def async_step_finish(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Choose a name for the device and create config entry."""
device = self.device
errors: dict[str, str] = {}
# Abort reauthentication flow.
self._abort_if_unique_id_configured(
updates={CONF_HOST: device.host[0], CONF_TIMEOUT: device.timeout}
)
if user_input is not None:
return self.async_create_entry(
title=user_input[CONF_NAME],
data={
CONF_HOST: device.host[0],
CONF_MAC: device.mac.hex(),
CONF_TYPE: device.devtype,
CONF_TIMEOUT: device.timeout,
},
)
data_schema = {vol.Required(CONF_NAME, default=device.name): str}
return self.async_show_form(
step_id="finish", data_schema=vol.Schema(data_schema), errors=errors
)
async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
"""Import a device."""
self._async_abort_entries_match({CONF_HOST: import_data[CONF_HOST]})
return await self.async_step_user(import_data)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Reauthenticate to the device."""
device = blk.gendevice(
entry_data[CONF_TYPE],
(entry_data[CONF_HOST], DEFAULT_PORT),
bytes.fromhex(entry_data[CONF_MAC]),
name=entry_data[CONF_NAME],
)
device.timeout = entry_data[CONF_TIMEOUT]
await self.async_set_device(device)
return await self.async_step_reset()