-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapi.py
More file actions
3328 lines (2918 loc) · 138 KB
/
Copy pathapi.py
File metadata and controls
3328 lines (2918 loc) · 138 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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
API endpoints for battery and electricity settings, dashboard data, and decision intelligence.
"""
import dataclasses
import threading
from datetime import date as date_cls
from datetime import datetime, timedelta
from api_conversion import (
BATTERY_MODEL_ATTRS as _BATTERY_MODEL_ATTRS,
)
from api_conversion import (
HOME_MODEL_ATTRS as _HOME_MODEL_ATTRS,
)
from api_conversion import (
convert_keys_to_camel_case,
convert_keys_to_snake_case,
)
from api_dataclasses import (
_ENTITY_ID_RE,
_HA_DOMAIN_RE,
APIConsumptionForecastComparison,
APIDashboardHourlyData,
APIDashboardResponse,
APIPredictionSnapshot,
APISavingsBucket,
APISetupCompletePayload,
APISnapshotComparison,
APIStrategyForecast,
FormattedValue,
create_formatted_value,
)
from fastapi import APIRouter, HTTPException, Query
from loguru import logger
from core.bess import time_utils
from core.bess.health_check import describe_failing_checks, run_system_health_checks
from core.bess.savings_aggregator import DEFAULT_COUNTS, build_buckets
from core.bess.settings_store import VALID_PLATFORMS, flatten_sensors
from core.bess.time_utils import get_period_count
router = APIRouter()
#: The wizard payload field each energy provider cannot work without.
#: Mirrors BatterySystemManager._create_price_source, which needs exactly
#: these to construct a usable PriceSource (#549).
_PROVIDER_REQUIRED_FIELD: dict[str, str] = {
"nordpool_official": "nordpoolConfigEntryId",
"nordpool_hacs": "nordpoolEntity",
"octopus": "octopusImportTodayEntity",
"entsoe": "entsoeEntity",
}
def _get_hourly_settings_from_periods(schedule_manager, hour: int) -> dict:
"""Build hourly settings from period-level data.
Compatibility layer for API endpoints that return hourly data to the
frontend. Picks the dominant intent (majority vote, alphabetical
tie-break) from the 4 quarterly periods of the given hour and returns
the corresponding control settings.
"""
intents = schedule_manager.strategic_intents
if not intents:
raise ValueError("No strategic intents available")
num_periods = len(intents)
start_p = hour * 4
end_p = min(start_p + 4, num_periods)
if start_p >= num_periods:
raise ValueError(f"Hour {hour} out of range")
period_intents = intents[start_p:end_p]
counts: dict[str, int] = {}
for i in period_intents:
counts[i] = counts.get(i, 0) + 1
max_count = max(counts.values())
dominant = min(i for i, c in counts.items() if c == max_count)
# Find a period with the dominant intent and return its settings
for p in range(start_p, end_p):
if intents[p] == dominant:
return schedule_manager.get_period_settings(p)
return schedule_manager.get_period_settings(start_p)
def _deep_merge(base: dict, updates: dict) -> dict:
"""Recursively merge *updates* into *base*, preserving nested dict values.
Nested dicts are merged key-by-key so that a partial update (e.g. only
``config_entry_id``) cannot erase sibling keys that already exist in the
stored section. All other value types are overwritten as normal.
"""
result = dict(base)
for key, value in updates.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = _deep_merge(result[key], value)
else:
result[key] = value
return result
def _strip_empty_sensor_values(sensors: dict) -> dict:
"""Remove empty-string values from sensor sub-dicts.
Sensor sections have structure like:
{"platform": "growatt_server_min", "shared": {...}, "growatt_server_min": {...}}
For each sub-dict (shared, platform-specific), strip keys whose values are
empty strings. This ensures cleared sensors are fully removed from persistent
storage rather than lingering as zombie entries.
"""
result = {}
for key, value in sensors.items():
if isinstance(value, dict):
cleaned = {k: v for k, v in value.items() if v != ""}
result[key] = cleaned
else:
result[key] = value
return result
def _validate_power_monitoring_sensors(
home_section: dict, active_sensors: dict
) -> None:
"""Raise HTTPException(422) if power monitoring is being enabled without
the phase-current sensors its phase_count requires.
Mirrors the frontend gating in HomeFormSection.tsx/SetupWizardPage.tsx —
this is the server-side backstop so the API itself refuses the invalid
combination regardless of which client called it.
"""
if not home_section.get("power_monitoring_enabled"):
return
phase_count = home_section.get("phase_count", 3)
required_keys = (
["current_l1"]
if phase_count == 1
else [
"current_l1",
"current_l2",
"current_l3",
]
)
required_keys = [*required_keys, "battery_charging_power_rate"]
missing = [k for k in required_keys if not active_sensors.get(k)]
if missing:
raise HTTPException(
status_code=422,
detail=(
"Cannot enable power monitoring: missing required sensor(s) "
f"for {phase_count}-phase: {', '.join(missing)}. "
"Configure them in Settings → Sensors first."
),
)
_CONSUMPTION_STRATEGIES = ("fixed", "sensor", "influxdb_7d_avg", "ha_statistics")
def _validate_consumption_strategy(home_section: dict, active_sensors: dict) -> None:
"""Raise HTTPException(422) for a consumption strategy that cannot work.
Mirrors the frontend gating in HomeFormSection.tsx — the server-side
backstop so the API refuses the combination regardless of which client
called it. Only ``sensor`` is checked against its sensor: it is the one
strategy with no fallback, so without ``48h_avg_grid_import`` every
optimization run aborts, no schedule is ever built, and the dashboard
sits on "Initializing" forever (#558). ``ha_statistics`` and
``influxdb_7d_avg`` are left alone — they degrade to the fixed profile
and report it, rather than stalling.
"""
strategy = home_section.get("consumption_strategy")
if strategy is None:
return
if strategy not in _CONSUMPTION_STRATEGIES:
raise HTTPException(
status_code=422,
detail=(
f"Unknown consumption strategy '{strategy}'. Valid values: "
f"{', '.join(_CONSUMPTION_STRATEGIES)}."
),
)
if strategy == "sensor" and not active_sensors.get("48h_avg_grid_import"):
raise HTTPException(
status_code=422,
detail=(
"Consumption strategy 'sensor' requires the "
"'48h_avg_grid_import' sensor, which is not configured. "
"Configure it in Settings → Sensors first, or choose a "
"strategy that does not need it."
),
)
def _require_configured_system(bess_controller) -> None:
"""Raise HTTP 503 if the BESS system has not been configured yet.
Call this at the top of any endpoint that requires a fully initialised
``BatterySystemManager`` (inverter controller, scheduler, etc.).
The setup wizard endpoints intentionally skip this check so they remain
reachable on a fresh install.
Args:
bess_controller: The global BESSController instance (already imported
by the calling endpoint via ``from app import bess_controller``).
"""
if not bess_controller.system.is_configured:
raise HTTPException(
status_code=503,
detail="System not configured. Complete the setup wizard first.",
)
if not bess_controller.startup_complete:
raise HTTPException(
status_code=503,
detail="System is starting up. Please wait.",
)
def _refresh_health(bess_controller) -> None:
"""Re-run the health check so the dashboard banner reflects the latest state.
Called after any settings mutation that could affect sensor or component
health (home, sensors, energy-provider, inverter, battery, electricity).
Failures are non-fatal — the banner will self-correct on the next poll.
"""
try:
bess_controller.system.refresh_health_check()
except Exception as exc:
logger.warning("Could not refresh health state after settings update: %s", exc)
# ---------------------------------------------------------------------------
# Unified settings endpoints
# ---------------------------------------------------------------------------
# Maps camelCase section names (from the API) to snake_case store keys.
_SECTION_MAP: dict[str, str] = {
"battery": "battery",
"home": "home",
"electricityPrice": "electricity_price",
"energyProvider": "energy_provider",
"growatt": "growatt",
"inverter": "inverter",
"sensors": "sensors",
"aiAnalyst": "ai_analyst",
"demoMode": "demo_mode",
}
@router.get("/api/settings")
async def get_settings():
"""Return all settings enriched with computed battery fields.
Sensor keys are system identifiers (snake_case) and are intentionally
not converted to camelCase — all other sections use camelCase field names.
"""
from copy import deepcopy
from app import bess_controller
try:
data = deepcopy(bess_controller.settings_store.data)
# Enrich battery section with computed kWh fields derived from SOC limits
battery = data.get("battery", {})
total = battery.get("total_capacity", 0.0)
battery["min_soe_kwh"] = total * battery.get("min_soc", 0.0) / 100.0
battery["max_soe_kwh"] = total * battery.get("max_soc", 0.0) / 100.0
battery["reserved_capacity"] = battery["min_soe_kwh"]
data["battery"] = battery
# Enrich the inverter section with the domain vendor service calls
# actually go to, so the UI can show the platform default as a
# placeholder without duplicating PLATFORM_SERVICE_DOMAIN client-side.
inverter = data.get("inverter", {})
inverter["resolved_service_domain"] = (
bess_controller.settings_store.get_service_domain()
)
data["inverter"] = inverter
# Return the full per-platform sensors structure from the store.
# Also include a flat "activeSensors" view for backwards compatibility.
data.pop("sensors", None)
result = convert_keys_to_camel_case(data)
result["sensors"] = bess_controller.settings_store.data.get("sensors", {})
return result
except Exception as e:
logger.error(f"Error getting settings: {e}")
raise HTTPException(status_code=500, detail=str(e)) from e
@router.patch("/api/settings")
async def patch_settings(updates: dict):
"""Partial-update settings — only provided sections are touched.
Each top-level key must be a known section name (camelCase). Field values
within each section are converted from camelCase to snake_case before being
merged into the persistent store and applied to the running system.
"""
from app import bess_controller
try:
for camel_key, section_data in updates.items():
store_key = _SECTION_MAP.get(camel_key)
if store_key is None:
raise HTTPException(
status_code=400, detail=f"Unknown settings section: {camel_key!r}"
)
# Sensor keys are system identifiers — skip camelCase conversion
if store_key == "sensors":
snake_data = section_data
else:
snake_data = convert_keys_to_snake_case(section_data)
# Validate before persisting — sensors need entity ID format checked first.
if store_key == "sensors":
for key, value in snake_data.items():
if isinstance(value, dict):
# Per-platform sub-dict — validate entity IDs within
for v in value.values():
if v and isinstance(v, str) and not _ENTITY_ID_RE.match(v):
raise HTTPException(
status_code=422,
detail=f"Invalid entity ID format: {v!r}",
)
elif isinstance(value, str) and value and key != "platform":
if not _ENTITY_ID_RE.match(value):
raise HTTPException(
status_code=422,
detail=f"Invalid entity ID format: {value!r}",
)
if store_key == "inverter":
domain = snake_data.get("service_domain")
if domain and not _HA_DOMAIN_RE.match(domain):
raise HTTPException(
status_code=422,
detail=(
f"Invalid Home Assistant integration domain: {domain!r}"
),
)
# Read-modify-write: merge into the existing section.
# Use deep merge so that partial updates to nested sub-dicts (e.g.
# nordpool_official.config_entry_id) do not erase sibling keys.
section = bess_controller.settings_store.get_section(store_key)
section = _deep_merge(section, snake_data)
# Strip empty-string sensor values so they don't persist as
# zombie entries. An empty string means "remove this sensor".
if store_key == "sensors":
section = _strip_empty_sensor_values(section)
# Validate power-monitoring sensor requirements BEFORE persisting —
# must run ahead of save_section so an invalid combination is never
# written to disk, even though the client still gets a 422.
if store_key == "home":
effective_sensors = {
**bess_controller.settings_store.get_active_sensors(),
**flatten_sensors(updates.get("sensors") or {}),
}
_validate_power_monitoring_sensors(section, effective_sensors)
_validate_consumption_strategy(section, effective_sensors)
if store_key == "sensors":
# A sensor removal (e.g. unmapping a phase-current sensor) can
# break an already-enabled power-monitoring config just as
# much as an explicit disable-without-sensors on the home
# section can — validate against the persisted home config.
persisted_home = bess_controller.settings_store.get_section("home")
_validate_power_monitoring_sensors(
persisted_home, flatten_sensors(section)
)
_validate_consumption_strategy(persisted_home, flatten_sensors(section))
bess_controller.settings_store.save_section(store_key, section)
# Apply in-memory updates for sections that drive live behaviour
if store_key == "battery":
in_mem = {k: v for k, v in section.items() if k in _BATTERY_MODEL_ATTRS}
if in_mem:
bess_controller.system.update_settings({"battery": in_mem})
td = section.get("temperature_derating")
if isinstance(td, dict):
obj = bess_controller.system.temperature_derating
if "enabled" in td:
obj.enabled = td["enabled"]
if "weather_entity" in td:
obj.weather_entity = td["weather_entity"]
elif store_key == "home":
# Filtered to known HomeSettings fields — a stale pre-migration
# key (e.g. 'consumption') can coexist with its renamed
# successor if a migration was ever interrupted (see
# HOME_MODEL_ATTRS's comment in api_conversion.py); passing it
# straight through would raise AttributeError.
# (Power-monitoring sensor validation already ran above, before
# save_section, so the invalid combination is never persisted.)
in_mem = {k: v for k, v in section.items() if k in _HOME_MODEL_ATTRS}
bess_controller.system.update_settings({"home": in_mem})
elif store_key == "electricity_price":
# PriceSettings attribute names match the store field names directly
bess_controller.system.update_settings({"price": section})
elif store_key == "energy_provider":
# Apply the new provider live so a restart is not required when
# switching between nordpool, nordpool_official, and octopus.
bess_controller.system.update_settings({"energy_provider": section})
elif store_key == "growatt":
# Platform switching lives in the "inverter" branch below;
# this section only carries the Growatt cloud device_id.
if "device_id" in section:
bess_controller.ha_controller.growatt_device_id = section[
"device_id"
]
elif store_key == "inverter":
# device_id here is the Huawei battery device (the Growatt
# cloud device_id lives in the growatt section above). Apply
# it live for the same reason that branch does — otherwise an
# edit in Settings only takes effect after a restart.
if "device_id" in section:
bess_controller.ha_controller.huawei_device_id = section[
"device_id"
]
platform = section.get("platform")
if platform:
bess_controller.system.switch_inverter_platform(platform)
else:
raise HTTPException(
status_code=400,
detail="Inverter section requires a 'platform' field",
)
# Only GEN4 (solax_modbus_growatt_min) accepts an explicit
# control_mode here: GEN3 (solax_modbus_growatt_sph) was
# already resolved to "vpp" by switch_inverter_platform()
# above, and re-applying a stale client-side "tou" default
# would raise, since GEN3 rejects any other value.
control_mode = section.get("control_mode")
if control_mode and platform == "solax_modbus_growatt_min":
bess_controller.system.switch_control_mode(control_mode)
elif store_key == "demo_mode":
enabled = section.get("enabled", False)
bess_controller.system.set_demo_mode(enabled)
# Any of the sections above (sensors directly, or growatt/inverter via
# a platform switch) can change service_domain and the grid/battery
# signed-sensor polarities — refresh those unconditionally rather
# than only on a key match.
# ha_controller.sensors is a live settings_store view (#334) and
# needs no equivalent refresh.
bess_controller.refresh_service_domain()
bess_controller.refresh_power_polarities()
_refresh_health(bess_controller)
return await get_settings()
except HTTPException:
raise
except Exception as e:
logger.error(f"Error updating settings: {e}")
raise HTTPException(status_code=500, detail=str(e)) from e
def _aggregate_quarterly_to_hourly(
quarterly_periods: list[APIDashboardHourlyData],
_battery_capacity: float,
currency: str,
) -> list[APIDashboardHourlyData]:
"""Aggregate quarterly (15-min) periods into hourly periods.
Args:
quarterly_periods: List of quarterly period data (96 periods for normal day)
battery_capacity: Battery capacity in kWh
currency: Currency code
Returns:
List of hourly aggregated data (24 hours for normal day)
"""
if not quarterly_periods:
return []
# Priority order for tie-breaking: prioritize action over inaction
intent_priority = {
"GRID_CHARGING": 5,
"BATTERY_EXPORT": 4,
"LOAD_SUPPORT": 3,
"SOLAR_STORAGE": 2,
"IDLE": 1,
}
def dominant_intent(intents: list[str]) -> str:
"""Most common intent among the 4 quarters; ties broken by priority."""
intent_counts: dict[str, int] = {}
for intent_item in intents:
intent_counts[intent_item] = intent_counts.get(intent_item, 0) + 1
max_count = max(intent_counts.values())
candidates = [i for i, c in intent_counts.items() if c == max_count]
return max(candidates, key=lambda x: intent_priority.get(x, 0))
hourly_periods = []
num_hours = (len(quarterly_periods) + 3) // 4 # Round up to handle DST
for hour in range(num_hours):
# Get the 4 quarterly periods for this hour
start_idx = hour * 4
end_idx = min(start_idx + 4, len(quarterly_periods))
quarter_periods = quarterly_periods[start_idx:end_idx]
if not quarter_periods:
continue
# Use the last period's values for state-based fields
last_period = quarter_periods[-1]
# Determine dominant strategic intent (most common in the 4 periods)
# If there's a tie, prioritize action over inaction
dominant_strategic_intent = dominant_intent(
[p.strategicIntent for p in quarter_periods]
)
# Curtailment (#501) is independent of intent -- a curtailed quarter
# can classify as SOLAR_STORAGE (battery still charging at its rate
# limit while the surplus above it curtails), so never filter by the
# dominant intent. If any quarter was curtailed, the hour as
# displayed is (at least partly) a curtailed export, not a purely
# profitable one.
hour_curtailed = any(p.curtailed for p in quarter_periods)
# Observed intent must aggregate across all 4 quarters too, not just
# the last one — a re-plan only updates strategicIntent going
# forward, so a stale strategicIntent can persist for an elapsed hour
# even though most/all of its quarters were genuinely observed
# executing something else (#486). dataSource itself stays tied to
# the last quarter (unchanged) — actualSavingsSoFar/predictedRemaining
# Savings (api_dataclasses.py) bucket a whole hour's summed
# hourlySavings by this field, so flipping it to "actual" as soon as
# any one quarter is actual would count still-predicted quarters'
# costs as realized.
actual_quarters = [p for p in quarter_periods if p.dataSource == "actual"]
observed_intents = [
p.observedIntent for p in actual_quarters if p.observedIntent
]
hour_observed_intent = (
dominant_intent(observed_intents)
if observed_intents
else last_period.observedIntent
)
# Sum energy values across the 4 quarters
hourly_period = APIDashboardHourlyData(
period=hour,
dataSource=last_period.dataSource,
timestamp=last_period.timestamp,
# Sum energy flows
solarProduction=create_formatted_value(
sum(p.solarProduction.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
homeConsumption=create_formatted_value(
sum(p.homeConsumption.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
gridImported=create_formatted_value(
sum(p.gridImported.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
gridExported=create_formatted_value(
sum(p.gridExported.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
batteryCharged=create_formatted_value(
sum(p.batteryCharged.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
batteryDischarged=create_formatted_value(
sum(p.batteryDischarged.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
batteryAction=create_formatted_value(
sum(p.batteryAction.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
# Average prices
buyPrice=create_formatted_value(
sum(p.buyPrice.value for p in quarter_periods) / len(quarter_periods),
"price",
currency,
),
sellPrice=create_formatted_value(
sum(p.sellPrice.value for p in quarter_periods) / len(quarter_periods),
"price",
currency,
),
# Use last period's SOC and SOE
batterySocStart=last_period.batterySocStart,
batterySocEnd=last_period.batterySocEnd,
batterySoeStart=last_period.batterySoeStart,
batterySoeEnd=last_period.batterySoeEnd,
# Sum detailed energy flows
solarToHome=create_formatted_value(
sum(p.solarToHome.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
solarToBattery=create_formatted_value(
sum(p.solarToBattery.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
solarToGrid=create_formatted_value(
sum(p.solarToGrid.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
clippedSolar=create_formatted_value(
sum(p.clippedSolar.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
gridToHome=create_formatted_value(
sum(p.gridToHome.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
gridToBattery=create_formatted_value(
sum(p.gridToBattery.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
batteryToHome=create_formatted_value(
sum(p.batteryToHome.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
batteryToGrid=create_formatted_value(
sum(p.batteryToGrid.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
# Solar-only scenario fields
gridImportNeeded=create_formatted_value(
sum(p.gridImportNeeded.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
# Sum costs and savings
importCost=create_formatted_value(
sum(p.importCost.value for p in quarter_periods), "currency", currency
),
exportRevenue=create_formatted_value(
sum(p.exportRevenue.value for p in quarter_periods),
"currency",
currency,
),
hourlyCost=create_formatted_value(
sum(p.hourlyCost.value for p in quarter_periods), "currency", currency
),
gridCost=create_formatted_value(
sum(p.gridCost.value for p in quarter_periods), "currency", currency
),
batteryCycleCost=create_formatted_value(
sum(p.batteryCycleCost.value for p in quarter_periods),
"currency",
currency,
),
hourlySavings=create_formatted_value(
sum(p.hourlySavings.value for p in quarter_periods),
"currency",
currency,
),
gridOnlyCost=create_formatted_value(
sum(p.gridOnlyCost.value for p in quarter_periods), "currency", currency
),
solarOnlyCost=create_formatted_value(
sum(p.solarOnlyCost.value for p in quarter_periods),
"currency",
currency,
),
solarExcess=create_formatted_value(
sum(p.solarExcess.value for p in quarter_periods),
"energy_kwh_only",
currency,
),
solarSavings=create_formatted_value(
sum(p.solarSavings.value for p in quarter_periods), "currency", currency
),
batterySavings=create_formatted_value(
sum(p.batterySavings.value for p in quarter_periods),
"currency",
currency,
),
netSavings=create_formatted_value(
sum(p.netSavings.value for p in quarter_periods), "currency", currency
),
# Use dominant strategic intent with tie-breaking (same logic as Growatt schedule)
strategicIntent=dominant_strategic_intent,
observedIntent=hour_observed_intent,
curtailed=hour_curtailed,
directSolar=sum(p.directSolar for p in quarter_periods),
)
hourly_periods.append(hourly_period)
return hourly_periods
@router.get("/api/dashboard/available-dates")
async def get_dashboard_available_dates():
"""List ISO dates that have dashboard data available (for date-picker greying).
Today is always included even though it is deliberately excluded from
DailyViewStore.list_available_dates() by design — today's view is
persisted continuously, but only past days are listed as history.
"""
from app import bess_controller
if not bess_controller.system.is_configured:
raise HTTPException(
status_code=503,
detail="System not configured. Complete the setup wizard first.",
)
persisted_dates = bess_controller.system.daily_view_store.list_available_dates()
today = time_utils.today().isoformat()
dates = sorted(set(persisted_dates) | {today})
return {"dates": dates}
@router.get("/api/dashboard")
async def get_dashboard_data(
resolution: str = Query("quarter-hourly", pattern="^(hourly|quarter-hourly)$"),
date: str | None = Query(
None, description="ISO date (YYYY-MM-DD) for a historical day; omit for today"
),
):
"""Unified dashboard endpoint using dataclass-based implementation for type safety.
Args:
resolution: Data resolution - 'hourly' (24 periods) or 'quarter-hourly' (96 periods)
date: Optional historical date. Past days are read from the persisted
DailyViewStore rather than the live in-memory system state, so
tomorrow's schedule and real-time battery SOC don't apply.
"""
from app import bess_controller
# On a fresh install, the system is unconfigured — 503 so the frontend
# redirects to the setup wizard.
if not bess_controller.system.is_configured:
raise HTTPException(
status_code=503,
detail="System not configured. Complete the setup wizard first.",
)
# During startup (configured system, background init still running) or
# post-wizard backfill, return an "initializing" response so the
# frontend shows a spinner instead of an error.
if not bess_controller.startup_complete:
logger.info("Dashboard requested during startup — returning initializing state")
return {
"error": "initializing",
"message": "System is starting up. The optimization schedule will be ready shortly.",
"status": bess_controller.startup_status,
}
target_date = date_cls.fromisoformat(date) if date else None
is_historical = target_date is not None and target_date != time_utils.today()
try:
logger.debug(
f"Starting dashboard data retrieval with resolution={resolution}, date={date}"
)
if is_historical:
daily_view = bess_controller.system.daily_view_store.load_day(target_date)
if daily_view is None:
raise HTTPException(
status_code=404,
detail=f"No historical data available for {target_date.isoformat()}",
)
else:
# Guard: if no schedule exists yet the system is still initializing
# (post-wizard backfill running in background).
if not bess_controller.system.schedule_store.get_latest_schedule():
logger.info(
"Dashboard requested before schedule is ready — returning initializing state"
)
return {
"error": "initializing",
"message": "System is initializing. The optimization schedule will be ready shortly.",
}
# Get daily view data (always quarterly internally)
daily_view = bess_controller.system.get_current_daily_view()
logger.debug(f"Daily view retrieved with {len(daily_view.periods)} periods")
# Get system components
controller = bess_controller.ha_controller
settings = bess_controller.system.get_settings()
battery_capacity = settings["battery"].total_capacity
currency = bess_controller.system.home_settings.currency
# Convert periods to API format (works for both hourly and quarterly)
hourly_dataclass_instances = [
APIDashboardHourlyData.from_internal(
period_data, battery_capacity, currency
)
for period_data in daily_view.periods
]
# Convert to hourly if requested
if resolution == "hourly":
logger.debug(
f"Converting {len(hourly_dataclass_instances)} quarterly periods to hourly"
)
hourly_dataclass_instances = _aggregate_quarterly_to_hourly(
hourly_dataclass_instances, battery_capacity, currency
)
logger.debug(
f"Aggregated to {len(hourly_dataclass_instances)} hourly periods"
)
# Extract tomorrow's optimization data from ScheduleStore.
# Not applicable when browsing a historical day — there's no "tomorrow"
# schedule relative to a past date.
tomorrow_data: list[APIDashboardHourlyData] | None = None
if not is_historical:
try:
today_period_count = get_period_count(time_utils.today())
tomorrow_period_count = get_period_count(
time_utils.today() + timedelta(days=1)
)
tomorrow_periods = []
# Resolved by exact timestamp (not positional index -
# optimization_period) so a standalone next-day schedule
# (period_data[0] anchored to tomorrow 00:00 despite
# optimization_period=0) is read correctly without needing
# to special-case its anchor.
for period_idx in range(
today_period_count,
today_period_count + tomorrow_period_count,
):
period_data = (
bess_controller.system.schedule_store.get_period_data_at(
time_utils.period_index_to_timestamp(period_idx)
)
)
if period_data is not None:
tomorrow_periods.append(period_data)
if tomorrow_periods:
tomorrow_data = [
APIDashboardHourlyData.from_internal(
p, battery_capacity, currency
)
for p in tomorrow_periods
]
if resolution == "hourly":
tomorrow_data = _aggregate_quarterly_to_hourly(
tomorrow_data, battery_capacity, currency
)
else:
# Tomorrow's periods are indexed relative to the start of the
# optimization window (e.g. 96..191 for a 96-period day).
# The frontend maps period index to wall-clock time, so period 0
# must represent 00:00 of the displayed day.
tomorrow_data = [
dataclasses.replace(p, period=i)
for i, p in enumerate(tomorrow_data)
]
except (AttributeError, KeyError, ValueError) as e:
logger.warning(f"Failed to get tomorrow's optimization data: {e}")
tomorrow_data = None
# Calculate basic totals from dataclass fields directly (no dict access)
basic_totals = {
"totalSolarProduction": sum(
h.solarProduction.value for h in hourly_dataclass_instances
),
"totalHomeConsumption": sum(
h.homeConsumption.value for h in hourly_dataclass_instances
),
"totalBatteryCharged": sum(
h.batteryCharged.value for h in hourly_dataclass_instances
),
"totalBatteryDischarged": sum(
h.batteryDischarged.value for h in hourly_dataclass_instances
),
"totalGridImport": sum(
h.gridImported.value for h in hourly_dataclass_instances
),
"totalGridExport": sum(
h.gridExported.value for h in hourly_dataclass_instances
),
"avgBuyPrice": (
sum(h.buyPrice.value for h in hourly_dataclass_instances)
/ len(hourly_dataclass_instances)
if hourly_dataclass_instances
else 0
),
}
# Calculate costs from dataclass fields directly - using ACTUAL backend calculations
total_optimized_cost = sum(
h.hourlyCost.value for h in hourly_dataclass_instances
)
total_grid_only_cost = sum(
h.gridOnlyCost.value for h in hourly_dataclass_instances
)
total_solar_only_cost = sum(
h.solarOnlyCost.value for h in hourly_dataclass_instances
)
total_net_grid_cost = sum(h.gridCost.value for h in hourly_dataclass_instances)
costs = {
"gridOnly": total_grid_only_cost,
"solarOnly": total_solar_only_cost,
"optimized": total_optimized_cost,
"netGrid": total_net_grid_cost,
}
# Issue #287: when a 2-day DP plan is active, tomorrow_data already
# holds the deferred-to-tomorrow slice — fold it into a full-horizon
# total so the dashboard doesn't make a correctly-deferred decision
# look like a loss.
if tomorrow_data:
costs["netGridFullHorizon"] = total_net_grid_cost + sum(
h.gridCost.value for h in tomorrow_data
)
costs["gridOnlyFullHorizon"] = total_grid_only_cost + sum(
h.gridOnlyCost.value for h in tomorrow_data
)
costs["horizonDays"] = 2
else:
costs["horizonDays"] = 1
if is_historical:
# No live sensor state applies to a past day — derive SOC from the
# last persisted period instead of reading the current battery sensor.
last_period = daily_view.periods[-1]
battery_soc: float = (
last_period.energy.battery_soe_end / battery_capacity
) * 100.0
strategic_summary: dict[str, int] = {}
for period_data in daily_view.periods:
intent = period_data.decision.strategic_intent
strategic_summary[intent] = strategic_summary.get(intent, 0) + 1
else:
battery_soc = controller.get_battery_soc()
# Strategic intent summary from actual schedule data
try:
schedule_manager = bess_controller.system._inverter_controller
strategic_summary_data = schedule_manager.get_strategic_intent_summary()
# Convert to count format expected by frontend
strategic_summary = {
intent: data.get("count", 0)
for intent, data in strategic_summary_data.items()
}
except Exception as e:
logger.error(f"Failed to get strategic intent summary: {e}")
raise ValueError(
f"Strategic intent summary is required but failed to load: {e}"
) from e
# Create the dataclass response using pre-created hourly instances
response = APIDashboardResponse.from_dashboard_data(
daily_view=daily_view,
controller=controller,
totals=basic_totals,
costs=costs,
strategic_summary=strategic_summary,
battery_soc=battery_soc,
battery_capacity=battery_capacity,
currency=currency,
hourly_data_instances=hourly_dataclass_instances,
resolution=resolution,
tomorrow_data=tomorrow_data,
)
if is_historical:
# currentPeriod is computed from wall-clock "now" in from_dashboard_data,
# which doesn't apply to a past day — no row should show as "Current".
response.currentPeriod = -1