forked from klyqa/home-assistant-integration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_flow.py
321 lines (267 loc) · 10.9 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
"""Config flow for Klyqa."""
from __future__ import annotations
from typing import Any
import asyncio
from requests.exceptions import ConnectTimeout, HTTPError
import voluptuous as vol
from klyqa_ctl import klyqa_ctl as api
from homeassistant.config_entries import ConfigEntry
from .datacoordinator import HAKlyqaAccount
from .const import CONF_POLLING, DOMAIN, LOGGER, CONF_SYNC_ROOMS
import homeassistant.helpers.config_validation as cv
from homeassistant import config_entries
from homeassistant.const import (
CONF_PASSWORD,
CONF_HOST,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
)
from homeassistant.data_entry_flow import FlowResult
user_step_data_schema = vol.Schema(
{
vol.Required(CONF_USERNAME, default=""): cv.string,
vol.Required(CONF_PASSWORD, default=""): cv.string,
vol.Required(CONF_SCAN_INTERVAL, default=120): int,
vol.Required(
CONF_SYNC_ROOMS, default=True, msg="sync r", description="sync R"
): bool,
vol.Required(CONF_POLLING, default=True): bool,
vol.Required(CONF_HOST, default="https://app-api.prod.qconnex.io"): str,
}
)
NoneType = type(None)
class OptionsFlowHandler(config_entries.OptionsFlow):
"""Handle a config flow."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry
self.username = ""
self.password = ""
self.scan_interval = -1
self.sync_rooms = False
self.polling = False
self.host = ""
self.klyqa: HAKlyqaAccount | None = None
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Manage the options."""
if user_input is not None:
self.username = str(user_input[CONF_USERNAME])
self.password = str(user_input[CONF_PASSWORD])
self.scan_interval = int(user_input[CONF_SCAN_INTERVAL])
self.sync_rooms = user_input[CONF_SYNC_ROOMS]
self.polling = user_input[CONF_POLLING]
self.host = str(user_input[CONF_HOST])
return await self._async_klyqa_login(step_id="user")
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(
CONF_USERNAME, default=self.config_entry.data[CONF_USERNAME]
): cv.string,
vol.Required(
CONF_PASSWORD, default=self.config_entry.data[CONF_PASSWORD]
): cv.string,
vol.Required(
CONF_POLLING, default=self.config_entry.data[CONF_POLLING]
): bool,
vol.Required(
CONF_SCAN_INTERVAL,
default=self.config_entry.data[CONF_SCAN_INTERVAL],
): int,
vol.Required(
CONF_SYNC_ROOMS, default=self.config_entry.data[CONF_SYNC_ROOMS]
): bool,
vol.Required(
CONF_HOST, default=self.config_entry.data[CONF_HOST]
): str,
}
),
)
async def _async_klyqa_login(self, step_id: str) -> FlowResult:
"""Handle login with Klyqa."""
try:
klyqa: HAKlyqaAccount = HAKlyqaAccount(
None,
None,
self.username,
self.password,
self.host,
self.hass,
sync_rooms=self.sync_rooms,
polling=self.polling,
scan_interval=self.scan_interval,
)
login = self.hass.async_run_job(
klyqa.login,
)
if login:
await asyncio.wait_for(login, timeout=30)
self.klyqa = klyqa
except Exception as ex: # pylint: disable=bare-except,broad-except
LOGGER.error("Unable to connect to Klyqa: %s", ex)
return await self._async_create_entry()
async def _async_create_entry(self) -> FlowResult:
"""Create the config entry."""
config_data = {
CONF_USERNAME: self.username,
CONF_PASSWORD: self.password,
CONF_SCAN_INTERVAL: self.scan_interval,
CONF_SYNC_ROOMS: self.sync_rooms,
CONF_POLLING: self.polling,
CONF_HOST: self.host,
}
return self.async_create_entry(title=self.username, data=config_data)
class KlyqaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Example config flow."""
# The schema version of the entries that it creates
# Home Assistant will call your migrate method if the version changes
# (this is not implemented yet)
VERSION = 1
def __init__(self) -> None:
"""Initialize."""
self.inited = False
self.username: str | None = None
self.password: str | None = None
self.cache: str | None = None
self.scan_interval: int = 120
self.host: str | None = None
self.sync_rooms: bool | None = None
self.polling: bool | None = None
self.klyqa: HAKlyqaAccount | None = None
pass
async def init(self) -> None:
"""Initialize."""
if self.inited:
return
self.inited = True
integration_data, cached = await api.async_json_cache(
None, "last.klyqa_integration_data.cache.json"
)
if not self.host:
self.host = "https://app-api.prod.qconnex.io"
if cached:
if CONF_USERNAME in integration_data:
self.username = str(integration_data[CONF_USERNAME])
if CONF_PASSWORD in integration_data:
self.password = str(integration_data[CONF_PASSWORD])
if CONF_SCAN_INTERVAL in integration_data:
self.scan_interval = int(integration_data[CONF_SCAN_INTERVAL])
if CONF_HOST in integration_data:
self.host = str(integration_data[CONF_HOST])
if CONF_SYNC_ROOMS in integration_data:
self.sync_rooms = bool(integration_data[CONF_SYNC_ROOMS])
if CONF_POLLING in integration_data:
self.polling = bool(integration_data[CONF_POLLING])
def get_klyqa(self) -> HAKlyqaAccount | NoneType:
if self.klyqa:
return self.klyqa
if (
not self.hass
or DOMAIN not in self.hass.data
or not self.hass.data[DOMAIN].klyqa_accounts
or not len(self.hass.data[DOMAIN].klyqa_accounts)
):
return None
self.klyqa = self.hass.data[DOMAIN].klyqa_accounts[0]
return self.klyqa
async def _show_setup_form(
self, errors: dict[Any, Any] | None = None
) -> FlowResult:
"""Show the setup form to the user."""
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_USERNAME, default=self.username): cv.string,
vol.Required(CONF_PASSWORD, default=self.password): cv.string,
vol.Required(CONF_POLLING, default=self.polling): bool,
vol.Required(CONF_SCAN_INTERVAL, default=self.scan_interval): int,
vol.Required(CONF_SYNC_ROOMS, default=self.sync_rooms): bool,
vol.Required(CONF_HOST, default=self.host): str,
}
),
errors=errors or {},
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle a flow initialized by the user."""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
if self.get_klyqa():
# already logged in from platform or other way
return self.async_abort(reason="single_instance_allowed")
await self.init()
login_failed = False
if user_input is None or login_failed:
return await self._show_setup_form()
self.username = str(user_input[CONF_USERNAME])
self.password = str(user_input[CONF_PASSWORD])
self.scan_interval = int(user_input[CONF_SCAN_INTERVAL])
self.sync_rooms = bool(user_input[CONF_SYNC_ROOMS])
self.polling = bool(user_input[CONF_POLLING])
self.host = str(user_input[CONF_HOST])
return await self._async_klyqa_login(step_id="user")
async def _async_klyqa_login(self, step_id: str) -> FlowResult:
"""Handle login with Klyqa."""
errors = {}
try:
klyqa: HAKlyqaAccount = HAKlyqaAccount(
None,
None,
self.username,
self.password,
self.host,
self.hass,
sync_rooms=self.sync_rooms,
polling=self.polling,
scan_interval=self.scan_interval,
)
login = self.hass.async_run_job(
klyqa.login,
)
if login:
await asyncio.wait_for(login, timeout=30)
else:
raise Exception()
self.klyqa = klyqa
except (ConnectTimeout, HTTPError) as exception:
LOGGER.error("Unable to connect to Klyqa: %s", exception)
errors = {"base": "cannot_connect"}
except Exception as exception: # pylint: disable=bare-except,broad-except
LOGGER.error("Unable to connect to Klyqa: %s", exception)
errors = {"base": "cannot_connect"}
if not self.klyqa or not self.klyqa.access_token:
errors = {"base": "cannot_connect"}
if errors:
return await self._show_setup_form(errors)
return await self._async_create_entry()
async def _async_create_entry(self) -> FlowResult:
"""Create the config entry."""
config_data = {
CONF_USERNAME: self.username,
CONF_PASSWORD: self.password,
CONF_SCAN_INTERVAL: self.scan_interval,
CONF_SYNC_ROOMS: self.sync_rooms,
CONF_POLLING: self.polling,
CONF_HOST: self.host,
}
existing_entry = await self.async_set_unique_id(self.username)
if existing_entry:
self.hass.config_entries.async_update_entry(
existing_entry, data=config_data
)
# Reload the Klyqa config entry otherwise devices will remain unavailable
self.hass.async_create_task(
self.hass.config_entries.async_reload(existing_entry.entry_id)
)
return self.async_abort(reason="reauth_successful")
return self.async_create_entry(title=self.username, data=config_data)
# @staticmethod
# @callback
# def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlowHandler:
# """Get the options flow for this handler."""
# return OptionsFlowHandler(config_entry)