Repository navigation
Expand file tree
/
Copy pathconfig_flow.py
More file actions
316 lines (264 loc) · 13 KB
/
Copy pathconfig_flow.py
File metadata and controls
316 lines (264 loc) · 13 KB
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
"""Configuration flow for Lumentree integration."""
from __future__ import annotations
import logging
from typing import Any
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries import ConfigFlowResult
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (
CONF_DEVICE_ID,
CONF_DEVICE_NAME,
CONF_DEVICE_SN,
CONF_HTTP_TOKEN,
DOMAIN,
)
from .core.api_client import LumentreeHttpApiClient
from .core.exceptions import ApiException, AuthException
_LOGGER = logging.getLogger(__name__)
class LumentreeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Config flow for Lumentree (Device ID based auth)."""
VERSION = 1
MINOR_VERSION = 1
def __init__(self) -> None:
"""Initialize config flow."""
self._device_id_input: str | None = None
self._http_token: str | None = None
self._device_sn_from_api: str | None = None
self._device_name: str | None = None
self._api_client: LumentreeHttpApiClient | None = None
self._reauth_entry: config_entries.ConfigEntry | None = None
async def _get_api_client(self) -> LumentreeHttpApiClient:
"""Get or create HTTP API client.
Returns:
API client instance
Raises:
ApiException: If client creation fails
"""
_LOGGER.debug("Attempting to get API client instance...")
if self._api_client is None:
_LOGGER.debug("API client is None, creating new instance")
try:
session = async_get_clientsession(self.hass)
_LOGGER.debug("aiohttp client session obtained: %s", repr(session))
if session is None:
_LOGGER.error("Failed to get aiohttp client session! (session is None)")
raise ApiException("Could not get client session")
# Create instance
try:
_LOGGER.debug("Creating LumentreeApiClient with session")
self._api_client = LumentreeHttpApiClient(session)
_LOGGER.debug("Created new API client instance: %s", type(self._api_client))
except Exception as create_exc:
_LOGGER.exception("Error creating LumentreeApiClient instance: %s", create_exc)
raise ApiException("Failed to create API client instance") from create_exc
except Exception as session_exc:
_LOGGER.error(f"Failed to initialize API client: {session_exc}")
raise ApiException(
f"API Client Initialization failed: {session_exc}"
) from session_exc
else:
_LOGGER.debug(f"Reusing existing API client instance: {type(self._api_client)}")
# Check again before setting token and return
if self._api_client is None:
_LOGGER.critical("API client is unexpectedly None after initialization attempt!")
raise ApiException("API client is None after creation attempt")
# Assign token if available
if self._http_token:
if hasattr(self._api_client, "set_token"):
try:
self._api_client.set_token(self._http_token)
masked = (self._http_token[:6] + "...") if len(self._http_token) > 6 else "***"
_LOGGER.debug("Set token on API client (masked): %s", masked)
except Exception as token_exc:
_LOGGER.exception("Failed to set token on API client: %s", token_exc)
raise ApiException("Failed to set token on API client") from token_exc
else:
_LOGGER.warning("API client missing 'set_token' method")
return self._api_client
async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
api: LumentreeHttpApiClient | None = None
if user_input is not None:
self._device_id_input = user_input[CONF_DEVICE_ID].strip()
try:
# Get API client
api = await self._get_api_client()
_LOGGER.info("Authenticating with Device ID: %s", self._device_id_input)
_LOGGER.debug("Using API client instance: %s", type(api))
token = await api.authenticate_device(self._device_id_input)
self._http_token = token
masked_token = (token[:6] + "...") if token and len(token) > 6 else "***"
_LOGGER.info(
"Auth success for %s (token masked: %s)", self._device_id_input, masked_token
)
return await self.async_step_confirm_device()
except AuthException as exc:
_LOGGER.warning(f"Auth failed {self._device_id_input}: {exc}")
errors["base"] = "invalid_auth"
except ApiException as exc:
_LOGGER.error(f"API conn/init error auth {self._device_id_input}: {exc}")
errors["base"] = "cannot_connect"
except Exception as exc:
_LOGGER.exception(f"Unexpected auth error {self._device_id_input}: {exc}")
errors["base"] = "unknown"
schema = vol.Schema(
{vol.Required(CONF_DEVICE_ID, default=self._device_id_input or ""): str}
)
return self.async_show_form(step_id="user", data_schema=schema, errors=errors)
async def async_step_confirm_device(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle device confirmation step."""
errors: dict[str, str] = {}
api: LumentreeHttpApiClient | None = None
if not self._http_token:
_LOGGER.error("Token missing")
return self.async_abort(reason="token_missing")
try:
api = await self._get_api_client()
except ApiException as exc:
_LOGGER.exception("Failed to get API client in confirm step: %s", exc)
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="confirm_device",
description_placeholders={"device_name": "Error", "device_sn": "Error"},
errors=errors,
)
if user_input is None:
if not self._device_id_input:
_LOGGER.error("Device ID missing")
return self.async_abort(reason="cannot_connect")
try:
_LOGGER.info("Fetching device info for %s via API...", self._device_id_input)
device_info_api = await api.get_device_info(self._device_id_input)
_LOGGER.debug("Device info raw response: %s", device_info_api)
if isinstance(device_info_api, dict) and "_error" in device_info_api:
api_error = device_info_api["_error"]
_LOGGER.error("API error when getting device info: %s", api_error)
errors["base"] = (
"invalid_auth" if "Auth" in api_error else "cannot_connect_deviceinfo"
)
return self.async_show_form(
step_id="confirm_device",
description_placeholders={"device_name": "Err", "device_sn": "Err"},
errors=errors,
)
self._device_sn_from_api = (
device_info_api.get("deviceId") if isinstance(device_info_api, dict) else None
)
if not self._device_sn_from_api:
_LOGGER.warning(
"deviceId not found for %s. Using input ID.", self._device_id_input
)
self._device_sn_from_api = self._device_id_input
elif self._device_sn_from_api != self._device_id_input:
_LOGGER.warning(
"API deviceId '%s' differs from input '%s'. Using API ID.",
self._device_sn_from_api,
self._device_id_input,
)
self._device_name = (
(
device_info_api.get("remarkName")
if isinstance(device_info_api, dict)
else None
)
or (
device_info_api.get("deviceType")
if isinstance(device_info_api, dict)
else None
)
or f"Lumentree {self._device_sn_from_api}"
)
_LOGGER.info(
"Device Info: ID/SN='%s', Name='%s', Type='%s'",
self._device_sn_from_api,
self._device_name,
(
device_info_api.get("deviceType")
if isinstance(device_info_api, dict)
else None
),
)
await self.async_set_unique_id(self._device_sn_from_api)
updates = {
CONF_DEVICE_NAME: self._device_name,
CONF_DEVICE_ID: self._device_id_input,
CONF_HTTP_TOKEN: self._http_token,
}
if self._reauth_entry:
pass
else:
self._abort_if_unique_id_configured(updates=updates)
return self.async_show_form(
step_id="confirm_device",
description_placeholders={
CONF_DEVICE_NAME: self._device_name,
CONF_DEVICE_SN: self._device_sn_from_api,
},
errors={},
)
except AuthException as exc:
_LOGGER.error(f"Auth error get info {self._device_id_input}: {exc}")
errors["base"] = "invalid_auth"
except ApiException as exc:
_LOGGER.error(f"API error get info {self._device_id_input}: {exc}")
errors["base"] = "cannot_connect_deviceinfo"
except Exception:
_LOGGER.exception(f"Unexpected confirm error {self._device_id_input}")
errors["base"] = "unknown"
return self.async_show_form(
step_id="confirm_device",
description_placeholders={"device_name": "Err", "device_sn": "Err"},
errors=errors,
)
config_data = {
CONF_DEVICE_ID: self._device_id_input,
CONF_DEVICE_SN: self._device_sn_from_api,
CONF_DEVICE_NAME: self._device_name,
CONF_HTTP_TOKEN: self._http_token,
}
if self._reauth_entry:
_LOGGER.info(
f"Updating entry {self._reauth_entry.entry_id} for {self._device_sn_from_api} reauth"
)
self.hass.config_entries.async_update_entry(self._reauth_entry, data=config_data)
await self.hass.config_entries.async_reload(self._reauth_entry.entry_id)
return self.async_abort(reason="reauth_successful")
_LOGGER.info(f"Creating new entry for SN/ID: {self._device_sn_from_api}")
return self.async_create_entry(title=self._device_name, data=config_data)
async def async_step_reauth(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
"""Handle reauth flow."""
_LOGGER.info("Reauth flow started")
self._reauth_entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
if not self._reauth_entry:
return self.async_abort(reason="unknown_entry")
self._device_id_input = self._reauth_entry.data.get(CONF_DEVICE_ID)
if not self._device_id_input:
_LOGGER.error(f"Cannot reauth {self._reauth_entry.entry_id}: Device ID missing")
return self.async_abort(reason="missing_device_id")
self._http_token = None
self._api_client = None
return await self.async_step_user(user_input={CONF_DEVICE_ID: self._device_id_input})
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfigure flow (HA 2024.3+)."""
_LOGGER.info("Reconfigure flow started")
reconfigure_entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
if not reconfigure_entry:
return self.async_abort(reason="unknown_entry")
if user_input is not None:
device_id = user_input[CONF_DEVICE_ID]
self._device_id_input = device_id
self._api_client = None
self._http_token = None
self._reauth_entry = reconfigure_entry
return await self.async_step_user(user_input={CONF_DEVICE_ID: device_id})
current_device_id = reconfigure_entry.data.get(CONF_DEVICE_ID, "")
return self.async_show_form(
step_id="reconfigure",
data_schema=vol.Schema({vol.Required(CONF_DEVICE_ID, default=current_device_id): str}),
)