-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_flow.py
More file actions
379 lines (338 loc) · 13.8 KB
/
config_flow.py
File metadata and controls
379 lines (338 loc) · 13.8 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
"""
Config Flow für die EcoFlow PowerOcean Plus Integration.
Der Config Flow führt den Benutzer durch die Einrichtung der Integration:
Schritt 1 (user): Eingabe von E-Mail, Passwort und Seriennummer
Schritt 2: Validierung der Zugangsdaten gegen die EcoFlow API
Schritt 3: Erstellung des Config Entry bei Erfolg
Bei ungültigen Zugangsdaten wird eine aussagekräftige Fehlermeldung angezeigt
und der Benutzer kann die Eingabe korrigieren.
Die Seriennummer kann optional leer gelassen werden — in diesem Fall versucht
der Coordinator beim ersten Start, das Gerät automatisch zu erkennen. Da EcoFlow
Accounts in der Regel nur ein PowerOcean-Gerät enthalten, funktioniert die
automatische Erkennung in den meisten Fällen.
"""
from __future__ import annotations
import asyncio
import base64
import logging
from typing import Any
import aiohttp
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult, OptionsFlow
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import callback
from homeassistant.helpers.selector import (
BooleanSelector,
BooleanSelectorConfig,
NumberSelector,
NumberSelectorConfig,
NumberSelectorMode,
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from .const import (
API_LOGIN_URL,
API_TIMEOUT,
BACKUP_CRITICAL_RUNTIME_MINUTES_MAX,
BACKUP_CRITICAL_RUNTIME_MINUTES_MIN,
BACKUP_RESERVED_SOC_PERCENT_MAX,
BACKUP_RESERVED_SOC_PERCENT_MIN,
BACKUP_RUNTIME_SMOOTHING_MINUTES_MAX,
BACKUP_RUNTIME_SMOOTHING_MINUTES_MIN,
CONF_BACKUP_CRITICAL_RUNTIME_MINUTES,
CONF_BACKUP_RESERVED_SOC_PERCENT,
CONF_BACKUP_RUNTIME_SMOOTHING_MINUTES,
CONF_DEBUG_MODE,
CONF_ENABLE_BACKUP_HELPERS,
CONF_NUM_BATTERY_PACKS,
CONF_POWER_OUTAGE_FREQUENCY_MIN_HZ,
CONF_POWER_OUTAGE_GRID_POWER_THRESHOLD_W,
CONF_SERIAL_NUMBER,
DEFAULT_BACKUP_CRITICAL_RUNTIME_MINUTES,
DEFAULT_BACKUP_RESERVED_SOC_PERCENT,
DEFAULT_BACKUP_RUNTIME_SMOOTHING_MINUTES,
DEFAULT_DEBUG_MODE,
DEFAULT_ENABLE_BACKUP_HELPERS,
DEFAULT_NUM_BATTERY_PACKS,
DEFAULT_POWER_OUTAGE_FREQUENCY_MIN_HZ,
DEFAULT_POWER_OUTAGE_GRID_POWER_THRESHOLD_W,
DOMAIN,
MANUFACTURER,
MAX_BATTERY_PACKS,
MODEL,
POWER_OUTAGE_FREQUENCY_MIN_HZ_MAX,
POWER_OUTAGE_FREQUENCY_MIN_HZ_MIN,
POWER_OUTAGE_GRID_POWER_THRESHOLD_W_MAX,
POWER_OUTAGE_GRID_POWER_THRESHOLD_W_MIN,
)
from .backup_helpers import normalize_backup_helper_options
_LOGGER = logging.getLogger(__name__)
# Validierungsschema für das Einrichtungsformular
STEP_USER_SCHEMA = vol.Schema(
{
vol.Required(CONF_EMAIL): TextSelector(
TextSelectorConfig(type=TextSelectorType.EMAIL, autocomplete="email")
),
vol.Required(CONF_PASSWORD): TextSelector(
TextSelectorConfig(type=TextSelectorType.PASSWORD)
),
vol.Required(CONF_SERIAL_NUMBER): TextSelector(
TextSelectorConfig(type=TextSelectorType.TEXT)
),
vol.Optional(CONF_NUM_BATTERY_PACKS, default=DEFAULT_NUM_BATTERY_PACKS): NumberSelector(
NumberSelectorConfig(
min=1,
max=MAX_BATTERY_PACKS,
step=1,
mode=NumberSelectorMode.BOX,
)
),
}
)
async def _validate_credentials(email: str, password: str) -> tuple[str, str]:
"""
Validiert die EcoFlow-Zugangsdaten durch einen Test-Login.
Das Passwort wird Base64-kodiert — exakt so wie die EcoFlow-App es überträgt.
MD5-Hashing (wie bei manchen anderen EcoFlow-Projekten dokumentiert) ist für
die Private API nicht korrekt.
Args:
email: EcoFlow-Konto-E-Mail-Adresse.
password: EcoFlow-Konto-Passwort (Klartext, wird hier kodiert).
Returns:
Tuple aus (token, user_id) bei Erfolg.
Raises:
ValueError: Bei falschen Zugangsdaten (Code 2026).
ConnectionError: Bei Netzwerkproblemen.
"""
password_b64 = base64.b64encode(password.encode("utf-8")).decode("utf-8")
payload = {
"email": email,
"password": password_b64,
"scene": "IOT_APP",
"userType": "ECOFLOW",
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
API_LOGIN_URL,
json=payload,
timeout=aiohttp.ClientTimeout(total=API_TIMEOUT),
) as resp:
data = await resp.json()
except aiohttp.ClientError as exc:
raise ConnectionError(f"Netzwerkfehler: {exc}") from exc
except asyncio.TimeoutError as exc:
raise ConnectionError("Verbindungs-Timeout zur EcoFlow API") from exc
code = str(data.get("code", ""))
if code != "0":
msg = data.get("message", "Unbekannter Fehler")
raise ValueError(f"Login fehlgeschlagen (Code {code}): {msg}")
user_data = data.get("data", {})
token = user_data.get("token", "")
user_id = str(user_data.get("user", {}).get("userId", ""))
return token, user_id
class EcoFlowOptionsFlow(OptionsFlow):
"""Options Flow — erlaubt nachträgliche Konfigurationsänderungen."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Zeigt das Options-Formular und speichert Änderungen."""
if user_input is not None:
# NumberSelector liefert je nach UI-Pfad manchmal float (z. B. 2.0).
# Für die weitere Verarbeitung benötigen wir einen sicheren int-Wert.
normalized_input = dict(user_input)
normalized_input[CONF_NUM_BATTERY_PACKS] = int(
normalized_input[CONF_NUM_BATTERY_PACKS]
)
normalized_input.update(normalize_backup_helper_options(normalized_input))
return self.async_create_entry(data=normalized_input)
normalized_options = normalize_backup_helper_options(self.config_entry.options)
current_packs = int(
self.config_entry.options.get(
CONF_NUM_BATTERY_PACKS,
self.config_entry.data.get(
CONF_NUM_BATTERY_PACKS,
DEFAULT_NUM_BATTERY_PACKS,
),
)
)
current_debug_mode = bool(
self.config_entry.options.get(CONF_DEBUG_MODE, DEFAULT_DEBUG_MODE)
)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema({
vol.Required(CONF_NUM_BATTERY_PACKS, default=current_packs): NumberSelector(
NumberSelectorConfig(
min=1,
max=MAX_BATTERY_PACKS,
step=1,
mode=NumberSelectorMode.BOX,
)
),
vol.Required(CONF_DEBUG_MODE, default=current_debug_mode): BooleanSelector(
BooleanSelectorConfig()
),
vol.Required(
CONF_ENABLE_BACKUP_HELPERS,
default=bool(
normalized_options.get(
CONF_ENABLE_BACKUP_HELPERS,
DEFAULT_ENABLE_BACKUP_HELPERS,
)
),
): BooleanSelector(BooleanSelectorConfig()),
vol.Required(
CONF_BACKUP_RESERVED_SOC_PERCENT,
default=int(
normalized_options.get(
CONF_BACKUP_RESERVED_SOC_PERCENT,
DEFAULT_BACKUP_RESERVED_SOC_PERCENT,
)
),
): NumberSelector(
NumberSelectorConfig(
min=BACKUP_RESERVED_SOC_PERCENT_MIN,
max=BACKUP_RESERVED_SOC_PERCENT_MAX,
step=1,
mode=NumberSelectorMode.BOX,
)
),
vol.Required(
CONF_POWER_OUTAGE_GRID_POWER_THRESHOLD_W,
default=int(
normalized_options.get(
CONF_POWER_OUTAGE_GRID_POWER_THRESHOLD_W,
DEFAULT_POWER_OUTAGE_GRID_POWER_THRESHOLD_W,
)
),
): NumberSelector(
NumberSelectorConfig(
min=POWER_OUTAGE_GRID_POWER_THRESHOLD_W_MIN,
max=POWER_OUTAGE_GRID_POWER_THRESHOLD_W_MAX,
step=1,
mode=NumberSelectorMode.BOX,
)
),
vol.Required(
CONF_POWER_OUTAGE_FREQUENCY_MIN_HZ,
default=float(
normalized_options.get(
CONF_POWER_OUTAGE_FREQUENCY_MIN_HZ,
DEFAULT_POWER_OUTAGE_FREQUENCY_MIN_HZ,
)
),
): NumberSelector(
NumberSelectorConfig(
min=POWER_OUTAGE_FREQUENCY_MIN_HZ_MIN,
max=POWER_OUTAGE_FREQUENCY_MIN_HZ_MAX,
step=0.1,
mode=NumberSelectorMode.BOX,
)
),
vol.Required(
CONF_BACKUP_RUNTIME_SMOOTHING_MINUTES,
default=int(
normalized_options.get(
CONF_BACKUP_RUNTIME_SMOOTHING_MINUTES,
DEFAULT_BACKUP_RUNTIME_SMOOTHING_MINUTES,
)
),
): NumberSelector(
NumberSelectorConfig(
min=BACKUP_RUNTIME_SMOOTHING_MINUTES_MIN,
max=BACKUP_RUNTIME_SMOOTHING_MINUTES_MAX,
step=1,
mode=NumberSelectorMode.BOX,
)
),
vol.Required(
CONF_BACKUP_CRITICAL_RUNTIME_MINUTES,
default=int(
normalized_options.get(
CONF_BACKUP_CRITICAL_RUNTIME_MINUTES,
DEFAULT_BACKUP_CRITICAL_RUNTIME_MINUTES,
)
),
): NumberSelector(
NumberSelectorConfig(
min=BACKUP_CRITICAL_RUNTIME_MINUTES_MIN,
max=BACKUP_CRITICAL_RUNTIME_MINUTES_MAX,
step=5,
mode=NumberSelectorMode.BOX,
)
),
}),
)
class EcoFlowPowerOceanConfigFlow(ConfigFlow, domain=DOMAIN):
"""
Konfigurationsflow für die EcoFlow PowerOcean Plus Integration.
Führt eine vollständige Credential-Validierung durch, bevor der
Config Entry angelegt wird. Verhindert so fehlerhafte Einträge
durch Tippfehler in E-Mail oder Passwort.
Version 1: Basisversion mit E-Mail, Passwort und Seriennummer.
"""
VERSION = 1
@staticmethod
@callback
def async_get_options_flow(config_entry: ConfigEntry) -> EcoFlowOptionsFlow:
"""Gibt den Options Flow zurück."""
return EcoFlowOptionsFlow()
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""
Erster Schritt: Eingabe der Zugangsdaten.
Wird angezeigt wenn der Benutzer die Integration über die
Home Assistant Oberfläche hinzufügt. Validiert die Eingaben
live gegen die EcoFlow API.
Args:
user_input: Vom Benutzer ausgefüllte Formularfelder, oder None
wenn das Formular erstmalig angezeigt wird.
Returns:
ConfigFlowResult — entweder Formularanzeige oder fertig.
"""
errors: dict[str, str] = {}
if user_input is not None:
email = user_input[CONF_EMAIL].strip().lower()
password = user_input[CONF_PASSWORD]
serial = user_input[CONF_SERIAL_NUMBER].strip().upper()
# Seriennummer-Format grob prüfen (PowerOcean Plus beginnt mit R37)
if serial and not (len(serial) >= 8):
errors[CONF_SERIAL_NUMBER] = "invalid_serial"
if not errors:
try:
_token, _user_id = await _validate_credentials(email, password)
_LOGGER.info(
"EcoFlow Zugangsdaten validiert für Gerät %s", serial
)
except ValueError:
errors["base"] = "invalid_auth"
except ConnectionError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unerwarteter Fehler bei Credential-Validierung")
errors["base"] = "unknown"
if not errors:
# Eindeutige ID setzen, um Doppeleinträge zu verhindern
await self.async_set_unique_id(serial)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"{MANUFACTURER} {MODEL} ({serial})",
data={
CONF_EMAIL: email,
CONF_PASSWORD: password,
CONF_SERIAL_NUMBER: serial,
CONF_NUM_BATTERY_PACKS: int(user_input[CONF_NUM_BATTERY_PACKS]),
},
)
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_SCHEMA,
errors=errors,
description_placeholders={
"manufacturer": MANUFACTURER,
"model": MODEL,
},
)