-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsettings_store.py
More file actions
717 lines (638 loc) · 28.2 KB
/
Copy pathsettings_store.py
File metadata and controls
717 lines (638 loc) · 28.2 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
"""Unified persistent settings store for BESS Manager.
All operational settings (battery, home, electricity_price, energy_provider,
growatt, sensors) are stored in /data/bess_settings.json, which is owned and
managed by this add-on. InfluxDB credentials are the only settings that remain
in the HA Supervisor-controlled /data/options.json.
On first boot the store migrates existing settings from options.json so existing
users are not affected by the transition.
"""
import errno
import json
import logging
import os
import tempfile
logger = logging.getLogger(__name__)
SETTINGS_PATH = "/data/bess_settings.json"
# Top-level sections that live in bess_settings.json (not options.json).
OWNED_SECTIONS = (
"home",
"battery",
"electricity_price",
"energy_provider",
"growatt",
"inverter",
"sensors",
"ai_analyst",
"demo_mode",
)
# All valid inverter platform IDs.
VALID_PLATFORMS = (
"growatt_server_min",
"growatt_server_sph",
"solax_modbus_growatt_min",
"solax_modbus_growatt_sph",
"solax_modbus_native",
"solis_modbus",
"huawei_solar_luna2000",
)
# Sensor keys that are shared across all platforms (not inverter-specific).
SHARED_SENSOR_KEYS = frozenset(
{
"solar_forecast_today",
"solar_forecast_tomorrow",
"48h_avg_grid_import",
"consumption_forecast_series",
"current_l1",
"current_l2",
"current_l3",
"discharge_inhibit",
"weather_entity",
}
)
# Control strategies for solax_modbus_growatt_min/solax_modbus_growatt_sph.
# GEN4 (solax_modbus_growatt_min) supports both; GEN3
# (solax_modbus_growatt_sph) has no working TOU path, so "vpp" is its only
# real choice (see issue #118).
VALID_CONTROL_MODES = ("tou", "vpp")
# All valid inverter platform IDs.
VALID_PLATFORMS = (
"growatt_server_min",
"growatt_server_sph",
"solax_modbus_growatt_min",
"solax_modbus_growatt_sph",
"solax_modbus_native",
"solis_modbus",
"huawei_solar_luna2000",
)
# Sensor keys that are shared across all platforms (not inverter-specific).
SHARED_SENSOR_KEYS = frozenset(
{
"solar_forecast_today",
"solar_forecast_tomorrow",
"48h_avg_grid_import",
"consumption_forecast_series",
"current_l1",
"current_l2",
"current_l3",
"discharge_inhibit",
"weather_entity",
}
)
class SettingsStore:
"""Read/write /data/bess_settings.json with atomic writes.
The in-memory representation mirrors the JSON structure exactly so callers
can treat ``store.data`` as a plain dict.
"""
def __init__(self) -> None:
self.data: dict = {}
self._use_direct_write: bool = False # set after first EBUSY
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def load(self, options: dict) -> None:
"""Load settings, migrating from options.json on first boot.
Args:
options: Full contents of /data/options.json (provided by HA
Supervisor). Used only when bess_settings.json is absent
or empty (first-boot migration).
"""
if os.path.exists(SETTINGS_PATH):
loaded = self._read()
if loaded:
self.data = loaded
logger.info(
"Loaded settings from %s (%d sections)",
SETTINGS_PATH,
len(self.data),
)
self._migrate_schema()
# Always overlay sensors/discovery from options if bess_settings
# has empty sensors (handles wizard flow after fresh migration).
self._overlay_discovered(options)
return
# First boot: migrate from options.json
logger.info("bess_settings.json absent or empty — migrating from options.json")
self.data = self._migrate_from_options(options)
self._migrate_schema() # normalise any legacy field names copied from options.json
self._write(self.data)
logger.info(
"Migration complete: wrote %d sections to %s",
len(self.data),
SETTINGS_PATH,
)
def get_section(self, name: str) -> dict:
"""Return a copy of a settings section dict.
Args:
name: Section key (e.g. 'battery', 'sensors').
Returns:
Dict copy of that section (empty dict if missing).
"""
return dict(self.data.get(name, {}))
def save_section(self, name: str, data: dict) -> None:
"""Persist a single section atomically.
Args:
name: Section key.
data: New section contents (replaces existing).
"""
self.data[name] = dict(data)
self._write(self.data)
logger.info("Saved settings section '%s'", name)
def save_all(self, data: dict) -> None:
"""Replace all owned sections atomically.
Args:
data: Full settings dict (may contain only owned sections).
"""
for section in OWNED_SECTIONS:
if section in data:
self.data[section] = dict(data[section])
self._write(self.data)
logger.info("Saved all settings to %s", SETTINGS_PATH)
def get_active_sensors(self) -> dict:
"""Return a flat sensor dict merging the active platform's sensors with shared sensors.
Internal consumers (scheduler, controllers) call this to get a flat
dict of sensor_key → entity_id without needing to know about the
per-platform storage structure.
"""
sensors = self.data.get("sensors", {})
if not isinstance(sensors, dict):
return {}
# Legacy flat format (no "platform" key) — return as-is
if "platform" not in sensors:
return {k: v for k, v in sensors.items() if isinstance(v, str)}
platform = sensors.get("platform", "")
platform_sensors = sensors.get(platform, {})
shared_sensors = sensors.get("shared", {})
result = {}
if isinstance(shared_sensors, dict):
result.update(shared_sensors)
if isinstance(platform_sensors, dict):
result.update(platform_sensors)
return result
def apply_discovered(
self,
sensor_map: dict,
nordpool_area: str | None = None,
nordpool_config_entry_id: str | None = None,
growatt_device_id: str | None = None,
huawei_device_id: str | None = None,
) -> None:
"""Merge auto-discovered values into the store and persist.
Sensors: non-empty discovered values always overwrite existing ones so
that re-running discovery can correct previously wrong entity IDs.
Empty strings are ignored so that a partial discovery run does not
erase sensors that were already configured.
Nordpool area, config_entry_id, and Growatt/Huawei device_id are
additive: they are only written when the field is currently empty.
Args:
sensor_map: Mapping of bess_sensor_key -> entity_id.
nordpool_area: Nordpool price area (e.g. ``"SE4"``).
nordpool_config_entry_id: HA config entry UUID for Nordpool.
growatt_device_id: HA device registry ID for the Growatt device.
huawei_device_id: HA device registry ID for the Huawei battery
device.
"""
sensors = dict(self.data.get("sensors", {}))
# Per-platform format: route each sensor to the correct sub-dict
if "platform" in sensors:
platform = sensors.get("platform", "")
for key, entity_id in sensor_map.items():
if not entity_id:
continue
if key in SHARED_SENSOR_KEYS:
shared = dict(sensors.get("shared", {}))
shared[key] = entity_id
sensors["shared"] = shared
else:
plat_dict = dict(sensors.get(platform, {}))
plat_dict[key] = entity_id
sensors[platform] = plat_dict
else:
# Legacy flat format
for key, entity_id in sensor_map.items():
if entity_id:
sensors[key] = entity_id
self.data["sensors"] = sensors
# Nordpool area — always update when discovery provides a value
if nordpool_area:
price = dict(self.data.get("electricity_price", {}))
price["area"] = nordpool_area
self.data["electricity_price"] = price
# Nordpool config_entry_id — always update when discovery provides a value
# (previous guard blocked updates when a stale/mock value existed)
if nordpool_config_entry_id:
ep = dict(self.data.get("energy_provider", {}))
nordpool_official = dict(ep.get("nordpool_official", {}))
nordpool_official["config_entry_id"] = nordpool_config_entry_id
ep["nordpool_official"] = nordpool_official
self.data["energy_provider"] = ep
# Growatt device_id — always update when discovery provides a value
if growatt_device_id:
growatt = dict(self.data.get("growatt", {}))
growatt["device_id"] = growatt_device_id
self.data["growatt"] = growatt
# Huawei device_id — always update when discovery provides a value.
# Stored in the generic "inverter" section's device_id field (the
# current pattern for non-legacy platforms; growatt's own legacy
# device_id is migrated into inverter.device_id by _migrate_schema).
if huawei_device_id:
inverter = dict(self.data.get("inverter", {}))
inverter["device_id"] = huawei_device_id
self.data["inverter"] = inverter
self._write(self.data)
logger.info("Persisted discovered config (%d sensors)", len(sensor_map))
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _read(self) -> dict:
"""Read bess_settings.json, returning empty dict on error."""
try:
with open(SETTINGS_PATH, encoding="utf-8") as f:
return json.load(f)
except OSError as e:
logger.warning("Could not read %s: %s", SETTINGS_PATH, e)
return {}
def _write(self, data: dict) -> None:
"""Write data to bess_settings.json via a temp file.
Attempts an atomic rename first. Some container filesystems (overlayfs,
CIFS) return EBUSY on rename — in that case fall back to a direct
overwrite. Once EBUSY is seen the fallback is used for all subsequent
writes so the failing syscall is not retried every time.
"""
data_dir = os.path.dirname(SETTINGS_PATH)
tmp_path: str | None = None
try:
fd, tmp_path = tempfile.mkstemp(dir=data_dir, suffix=".json")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
if self._use_direct_write:
self._copy_and_remove(tmp_path)
else:
try:
os.replace(tmp_path, SETTINGS_PATH)
except OSError as e:
if e.errno != errno.EBUSY:
raise
logger.warning(
"os.replace EBUSY on %s — switching to direct write for all future saves",
SETTINGS_PATH,
)
self._use_direct_write = True
self._copy_and_remove(tmp_path)
except OSError as e:
logger.error("Failed to write %s: %s", SETTINGS_PATH, e)
if tmp_path is not None:
try:
os.unlink(tmp_path)
except OSError:
pass
raise
def _copy_and_remove(self, tmp_path: str) -> None:
"""Overwrite SETTINGS_PATH with tmp_path content, then delete tmp_path."""
with open(tmp_path, encoding="utf-8") as src:
content = src.read()
with open(SETTINGS_PATH, "w", encoding="utf-8") as dst:
dst.write(content)
os.unlink(tmp_path)
@staticmethod
def _migrate_from_options(options: dict) -> dict:
"""Extract owned sections from options.json into a settings dict.
Falls back to bootstrap defaults (from core constants) when options
contains no operational sections — i.e. on a fresh installation before
the setup wizard has run.
Args:
options: Full /data/options.json contents.
Returns:
Dict containing only OWNED_SECTIONS extracted from options.
"""
result: dict = {}
for section in OWNED_SECTIONS:
if section in options:
result[section] = dict(options[section])
if not result:
result = SettingsStore._bootstrap_defaults()
logger.info("No operational settings found — applying bootstrap defaults")
return result
@staticmethod
def _bootstrap_defaults() -> dict:
"""Minimal default settings for first boot before the setup wizard runs.
Values are sourced from core/bess/settings.py constants so there is a
single source of truth. The wizard overwrites these with the user's
actual values.
"""
from core.bess.settings import (
ADDITIONAL_COSTS,
BATTERY_CHARGE_CYCLE_COST,
BATTERY_MAX_CHARGE_DISCHARGE_POWER_KW,
BATTERY_MAX_SOC,
BATTERY_MIN_ACTION_PROFIT_THRESHOLD,
BATTERY_MIN_SOC,
BATTERY_STORAGE_SIZE_KWH,
DEFAULT_AREA,
DEFAULT_CURRENCY,
EXPORT_SPOT_MULTIPLIER,
HOME_HOURLY_CONSUMPTION_KWH,
HOUSE_MAX_FUSE_CURRENT_A,
HOUSE_VOLTAGE_V,
MARKUP_RATE,
SAFETY_MARGIN_FACTOR,
SPOT_MULTIPLIER,
TAX_REDUCTION,
USE_ACTUAL_PRICE,
VAT_MULTIPLIER,
)
return {
"battery": {
"total_capacity": BATTERY_STORAGE_SIZE_KWH,
"min_soc": BATTERY_MIN_SOC,
"max_soc": BATTERY_MAX_SOC,
"max_charge_power_kw": BATTERY_MAX_CHARGE_DISCHARGE_POWER_KW,
"max_discharge_power_kw": BATTERY_MAX_CHARGE_DISCHARGE_POWER_KW,
"cycle_cost_per_kwh": BATTERY_CHARGE_CYCLE_COST,
"min_action_profit_threshold": BATTERY_MIN_ACTION_PROFIT_THRESHOLD,
},
"home": {
"default_hourly": HOME_HOURLY_CONSUMPTION_KWH,
"currency": DEFAULT_CURRENCY,
"consumption_strategy": "sensor",
"max_fuse_current": HOUSE_MAX_FUSE_CURRENT_A,
"voltage": HOUSE_VOLTAGE_V,
"safety_margin": SAFETY_MARGIN_FACTOR,
"phase_count": 1,
"power_monitoring_enabled": False,
},
"electricity_price": {
"markup_rate": MARKUP_RATE,
"vat_multiplier": VAT_MULTIPLIER,
"additional_costs": ADDITIONAL_COSTS,
"tax_reduction": TAX_REDUCTION,
"area": DEFAULT_AREA,
"spot_multiplier": SPOT_MULTIPLIER,
"export_spot_multiplier": EXPORT_SPOT_MULTIPLIER,
"use_actual_price": USE_ACTUAL_PRICE,
},
"energy_provider": {
"provider": "nordpool_official",
"nordpool_official": {"config_entry_id": ""},
"nordpool_hacs": {"entity": ""},
"octopus": {},
"entsoe": {"entity": ""},
},
"growatt": {"inverter_type": "", "device_id": ""},
"inverter": {"platform": "", "device_id": "", "control_mode": "tou"},
"sensors": {
"platform": "",
"growatt_server_min": {},
"growatt_server_sph": {},
"solax_modbus_growatt_min": {},
"solax_modbus_growatt_sph": {},
"solax_modbus_native": {},
"shared": {},
},
"demo_mode": {"enabled": False},
}
def _migrate_schema(self) -> None:
"""Add missing keys and normalize field names introduced in newer schema versions.
Called after loading bess_settings.json so that old files are silently
upgraded in place. Values are sourced from core constants so there is a
single source of truth.
"""
from core.bess.settings import (
BATTERY_CHARGE_CYCLE_COST,
BATTERY_DEFAULT_CHARGING_POWER_RATE,
BATTERY_EFFICIENCY_CHARGE,
BATTERY_EFFICIENCY_DISCHARGE,
BATTERY_MIN_ACTION_PROFIT_THRESHOLD,
EXPORT_SPOT_MULTIPLIER,
INVERTER_AC_POWER_MARGIN,
INVERTER_MAX_AC_POWER_KW,
SPOT_MULTIPLIER,
USE_ACTUAL_PRICE,
)
changed = False
battery = self.data.get("battery")
if isinstance(battery, dict):
# Rename: max_charge_discharge_power → max_charge_power_kw + max_discharge_power_kw
if (
"max_charge_discharge_power" in battery
and "max_charge_power_kw" not in battery
):
power = battery.pop("max_charge_discharge_power")
battery["max_charge_power_kw"] = power
battery["max_discharge_power_kw"] = power
logger.info(
"Schema migration: renamed max_charge_discharge_power → max_charge_power_kw/max_discharge_power_kw = %s",
power,
)
changed = True
# Rename: cycle_cost → cycle_cost_per_kwh
if "cycle_cost" in battery and "cycle_cost_per_kwh" not in battery:
battery["cycle_cost_per_kwh"] = battery.pop("cycle_cost")
logger.info(
"Schema migration: renamed cycle_cost → cycle_cost_per_kwh = %s",
battery["cycle_cost_per_kwh"],
)
changed = True
# Add missing fields with defaults
for key, default in (
("cycle_cost_per_kwh", BATTERY_CHARGE_CYCLE_COST),
("min_action_profit_threshold", BATTERY_MIN_ACTION_PROFIT_THRESHOLD),
("charging_power_rate", BATTERY_DEFAULT_CHARGING_POWER_RATE),
("efficiency_charge", BATTERY_EFFICIENCY_CHARGE),
("efficiency_discharge", BATTERY_EFFICIENCY_DISCHARGE),
("inverter_max_ac_power_kw", INVERTER_MAX_AC_POWER_KW),
("inverter_ac_power_margin", INVERTER_AC_POWER_MARGIN),
):
if key not in battery:
battery[key] = default
logger.info("Schema migration: added battery.%s = %s", key, default)
changed = True
if changed:
self.data["battery"] = battery
home = self.data.get("home")
if isinstance(home, dict):
# Rename: consumption → default_hourly (matches HomeSettings attribute name)
if "consumption" in home and "default_hourly" not in home:
home["default_hourly"] = home.pop("consumption")
logger.info(
"Schema migration: renamed home.consumption → home.default_hourly = %s",
home["default_hourly"],
)
changed = True
# Rename: safety_margin_factor → safety_margin (matches HomeSettings attribute name)
if "safety_margin_factor" in home and "safety_margin" not in home:
home["safety_margin"] = home.pop("safety_margin_factor")
logger.info(
"Schema migration: renamed home.safety_margin_factor → home.safety_margin = %s",
home["safety_margin"],
)
changed = True
if changed:
self.data["home"] = home
# --- electricity_price: spot_multiplier / export_spot_multiplier / use_actual_price ---
# Added after these fields were introduced on PriceSettings; without a
# default, build_system_settings() would raise ValueError at startup
# for any config written before this migration existed.
price = self.data.get("electricity_price")
if isinstance(price, dict):
for key, default in (
("spot_multiplier", SPOT_MULTIPLIER),
("export_spot_multiplier", EXPORT_SPOT_MULTIPLIER),
("use_actual_price", USE_ACTUAL_PRICE),
):
if key not in price:
price[key] = default
logger.info(
"Schema migration: added electricity_price.%s = %s",
key,
default,
)
changed = True
if changed:
self.data["electricity_price"] = price
ep = self.data.get("energy_provider")
if isinstance(ep, dict):
# Migrate legacy "nordpool" key → "nordpool_hacs"
nordpool = ep.get("nordpool")
if isinstance(nordpool, dict):
# Rename: today_entity + tomorrow_entity → entity (single sensor)
if "today_entity" in nordpool and "entity" not in nordpool:
nordpool["entity"] = nordpool.pop("today_entity")
nordpool.pop("tomorrow_entity", None)
logger.info(
"Schema migration: renamed nordpool.today_entity → nordpool.entity = %s",
nordpool["entity"],
)
ep["nordpool_hacs"] = nordpool
del ep["nordpool"]
if ep.get("provider") == "nordpool":
ep["provider"] = "nordpool_hacs"
self.data["energy_provider"] = ep
changed = True
growatt = self.data.get("growatt")
if isinstance(growatt, dict):
from api_conversion import UI_TYPE_TO_PLATFORM
old_type = growatt.get("inverter_type", "")
inverter = dict(self.data.get("inverter", {}))
if (
old_type
and not inverter.get("platform")
and old_type in UI_TYPE_TO_PLATFORM
):
platform = UI_TYPE_TO_PLATFORM[old_type]
inverter["platform"] = platform
if not inverter.get("device_id") and growatt.get("device_id"):
inverter["device_id"] = growatt["device_id"]
self.data["inverter"] = inverter
logger.info(
"Schema migration: growatt.inverter_type=%s → inverter.platform=%s",
old_type,
platform,
)
changed = True
# Add missing inverter.control_mode. GEN3 (solax_modbus_growatt_sph)
# has no working TOU path, so it defaults straight to "vpp" (see
# issue #118); every other existing install defaults to "tou" so
# nobody's working setup silently changes control strategy.
inverter = self.data.get("inverter")
if isinstance(inverter, dict) and "control_mode" not in inverter:
inverter["control_mode"] = (
"vpp"
if inverter.get("platform") == "solax_modbus_growatt_sph"
else "tou"
)
self.data["inverter"] = inverter
logger.info(
"Schema migration: added inverter.control_mode = %s",
inverter["control_mode"],
)
changed = True
# Migrate flat sensors → per-platform structure
sensors = self.data.get("sensors")
if isinstance(sensors, dict) and "platform" not in sensors:
# Flat format — migrate to per-platform structure.
# Determine the active platform from the inverter section.
inverter = self.data.get("inverter", {})
platform = inverter.get("platform", "")
if platform and platform in VALID_PLATFORMS:
new_sensors: dict = {"platform": platform}
shared: dict = {}
platform_dict: dict = {}
for key, value in sensors.items():
if key in SHARED_SENSOR_KEYS:
shared[key] = value
else:
platform_dict[key] = value
new_sensors[platform] = platform_dict
new_sensors["shared"] = shared
self.data["sensors"] = new_sensors
logger.info(
"Schema migration: flat sensors → per-platform (%s: %d sensors, shared: %d)",
platform,
len(platform_dict),
len(shared),
)
changed = True
# --- demo_mode section (added v9.5) ---
if "demo_mode" not in self.data:
self.data["demo_mode"] = {"enabled": False}
changed = True
# --- ai_analyst: rewrite deprecated Claude 4.0 launch model IDs ---
# claude-{sonnet,opus}-4-20250514 return 404 ahead of their 2026-06-15
# retirement; rewrite persisted configs so existing users don't have to
# touch Settings → System → AI Analyst manually.
ai_analyst = self.data.get("ai_analyst")
if isinstance(ai_analyst, dict):
_AI_MODEL_RENAMES = {
"claude-sonnet-4-20250514": "claude-sonnet-4-6",
"claude-opus-4-20250514": "claude-opus-4-8",
}
current_model = ai_analyst.get("model")
if current_model in _AI_MODEL_RENAMES:
new_model = _AI_MODEL_RENAMES[current_model]
ai_analyst["model"] = new_model
logger.info(
"Schema migration: ai_analyst.model %s → %s (legacy ID retired)",
current_model,
new_model,
)
changed = True
if changed:
self._write(self.data)
def _overlay_discovered(self, options: dict) -> None:
"""Apply legacy bess_discovered_config.json values if present.
This handles the transition period where some users may have a
bess_discovered_config.json written by the previous code. Values are
only applied when the corresponding field is empty in the store.
"""
legacy_path = "/data/bess_discovered_config.json"
if not os.path.exists(legacy_path):
# Also check if sensors section from options should be merged
# (e.g. wizard was never run but options has sensors)
sensors_in_options = options.get("sensors", {})
configured = sum(
1 for v in sensors_in_options.values() if isinstance(v, str) and v
)
if configured > 0:
active = self.get_active_sensors()
own_configured = sum(1 for v in active.values() if v)
if own_configured == 0:
logger.info(
"Overlaying %d sensors from options.json into store",
configured,
)
# Options has flat format — apply via apply_discovered which
# handles both flat and per-platform formats.
self.apply_discovered(sensor_map=sensors_in_options)
return
try:
with open(legacy_path, encoding="utf-8") as f:
discovered = json.load(f)
logger.info("Applying legacy bess_discovered_config.json overlay")
self.apply_discovered(
sensor_map=discovered.get("sensors", {}),
nordpool_area=discovered.get("nordpool_area"),
nordpool_config_entry_id=discovered.get("nordpool_config_entry_id"),
growatt_device_id=discovered.get("growatt_device_id"),
)
except (OSError, ValueError) as e:
logger.warning("Could not apply legacy discovered config: %s", e)