-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapi.py
More file actions
3274 lines (2893 loc) · 138 KB
/
Copy pathapi.py
File metadata and controls
3274 lines (2893 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 datetime, timedelta
from api_conversion import (
convert_keys_to_camel_case,
convert_keys_to_snake_case,
)
from api_dataclasses import (
_ENTITY_ID_RE,
APIConsumptionForecastComparison,
APIDashboardHourlyData,
APIDashboardResponse,
APIPredictionSnapshot,
APISetupCompletePayload,
APISnapshotComparison,
APIStrategyForecast,
FormattedValue,
create_formatted_value,
)
from fastapi import APIRouter, HTTPException, Query
from loguru import logger
from settings_store import VALID_PLATFORMS
from core.bess import time_utils
from core.bess.health_check import run_system_health_checks
from core.bess.settings import BatterySettings as _BatterySettings
from core.bess.time_utils import get_period_count
router = APIRouter()
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 _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._run_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",
}
# Derived from the BatterySettings dataclass — fields with init=True are the
# writable attributes; init=False fields (min_soe_kwh, max_soe_kwh,
# reserved_capacity) are computed and must not be sent to update_settings().
# temperature_derating is a nested dict handled separately below.
_BATTERY_MODEL_ATTRS: frozenset[str] = frozenset(
f.name for f in dataclasses.fields(_BatterySettings) if f.init
)
@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
# 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}",
)
# 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)
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":
bess_controller.system.update_settings({"home": section})
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":
if "device_id" in section:
bess_controller.ha_controller.growatt_device_id = section[
"device_id"
]
# Map legacy inverter_type to platform and switch controller
inverter_type = section.get("inverter_type")
if inverter_type:
platform_map = bess_controller.system._INVERTER_TYPE_TO_PLATFORM
if inverter_type not in platform_map:
raise HTTPException(
status_code=400,
detail=f"Unknown inverter_type '{inverter_type}', "
f"expected one of {list(platform_map)}",
)
bess_controller.system.switch_inverter_platform(
platform_map[inverter_type]
)
elif store_key == "inverter":
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",
)
elif store_key == "sensors":
# Update live ha_controller.sensors from the merged flat view
active = bess_controller.settings_store.get_active_sensors()
bess_controller.ha_controller.sensors = {
k: v for k, v in active.items() if v
}
elif store_key == "demo_mode":
enabled = section.get("enabled", False)
bess_controller.system.set_demo_mode(enabled)
_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,
}
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
period_intents = [p.strategicIntent for p in quarter_periods]
intent_counts = {}
for intent_item in period_intents:
intent_counts[intent_item] = intent_counts.get(intent_item, 0) + 1
# Find max count, then use priority as tie-breaker
max_count = max(intent_counts.values())
candidates = [i for i, c in intent_counts.items() if c == max_count]
dominant_intent = max(candidates, key=lambda x: intent_priority.get(x, 0))
# Sum energy values across the 4 quarters
hourly_period = APIDashboardHourlyData(
period=hour,
dataSource=last_period.dataSource, # Use last period's data source
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,
),
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
hourlyCost=create_formatted_value(
sum(p.hourlyCost.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
),
# Use dominant strategic intent with tie-breaking (same logic as Growatt schedule)
strategicIntent=dominant_intent,
observedIntent=last_period.observedIntent,
directSolar=sum(p.directSolar for p in quarter_periods),
)
hourly_periods.append(hourly_period)
return hourly_periods
@router.get("/api/dashboard")
async def get_dashboard_data(
resolution: str = Query("quarter-hourly", pattern="^(hourly|quarter-hourly)$"),
):
"""Unified dashboard endpoint using dataclass-based implementation for type safety.
Args:
resolution: Data resolution - 'hourly' (24 periods) or 'quarter-hourly' (96 periods)
"""
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,
}
try:
logger.debug(f"Starting dashboard data retrieval with resolution={resolution}")
# 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
tomorrow_data: list[APIDashboardHourlyData] | None = None
try:
stored_schedule = (
bess_controller.system.schedule_store.get_latest_schedule()
)
if stored_schedule:
opt_result = stored_schedule.optimization_result
opt_period = stored_schedule.optimization_period
today_period_count = get_period_count(time_utils.today())
tomorrow_period_count = get_period_count(
time_utils.today() + timedelta(days=1)
)
tomorrow_periods = []
# Standalone next-day schedule (prepare_next_day path): opt_period=0
# and period_data[0] carries tomorrow's date. In that case
# period_data[0..95] maps to tomorrow's periods 0..95, so the anchor
# is today_period_count rather than opt_period.
# Regular schedules (including midnight runs with extended horizon)
# have opt_period > 0 or period_data large enough to include tomorrow,
# so they continue to use opt_period as the anchor.
is_next_day_only = (
opt_period == 0
and bool(opt_result.period_data)
and opt_result.period_data[0].timestamp is not None
and opt_result.period_data[0].timestamp.date()
== time_utils.today() + timedelta(days=1)
)
period_data_anchor = (
today_period_count if is_next_day_only else opt_period
)
for period_idx in range(
today_period_count,
today_period_count + tomorrow_period_count,
):
data_idx = period_idx - period_data_anchor
if 0 <= data_idx < len(opt_result.period_data):
tomorrow_periods.append(opt_result.period_data[data_idx])
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
)
costs = {
"gridOnly": total_grid_only_cost,
"solarOnly": total_solar_only_cost,
"optimized": total_optimized_cost,
}
battery_soc: float = 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,
)
logger.debug("Dashboard response created successfully using dataclasses")
# Return dataclass directly - already has camelCase fields
return response.__dict__
except Exception as e:
logger.error(f"Error generating dashboard data: {e}")
raise HTTPException(status_code=500, detail=str(e)) from e
############################################################################################
# API Endpoints for Decision Insights
############################################################################################
def convert_real_data_to_mock_format(period_data_list, current_period, currency):
"""
Convert real PeriodData with enhanced DecisionData to proper FormattedValue format.
Args:
period_data_list: List of PeriodData from DailyView (quarterly or hourly resolution)
current_period: Current period index for marking is_current_hour
currency: Currency code for formatting
Returns:
Dictionary with FormattedValue objects for proper frontend display
"""
patterns = []
for period_data in period_data_list:
# Convert quarterly period (0-95) to hour (0-23) for display
period = period_data.period
hour = period // 4 # Quarterly to hourly conversion
energy = period_data.energy
economic = period_data.economic
decision = period_data.decision
# Determine if this is current period and actual vs predicted
is_current = period == current_period
is_actual = period_data.data_source == "actual"
# Create flows dictionary with FormattedValue objects
flows = {
"solar_to_home": create_formatted_value(
energy.solar_to_home, "energy_kwh_only", currency
),
"solar_to_battery": create_formatted_value(
energy.solar_to_battery, "energy_kwh_only", currency
),
"solar_to_grid": create_formatted_value(
energy.solar_to_grid, "energy_kwh_only", currency
),
"grid_to_home": create_formatted_value(
energy.grid_to_home, "energy_kwh_only", currency
),
"grid_to_battery": create_formatted_value(
energy.grid_to_battery, "energy_kwh_only", currency
),
"battery_to_home": create_formatted_value(
energy.battery_to_home, "energy_kwh_only", currency
),
"battery_to_grid": create_formatted_value(
energy.battery_to_grid, "energy_kwh_only", currency
),
}
# Create immediate_flow_values using enhanced decision intelligence data
immediate_flow_values = {}
# Enhanced decision intelligence should always provide detailed flow values
# For historical data, detailed_flow_values might not be populated yet
if not decision.detailed_flow_values:
# Detailed flow values are only available for predicted periods;
# historical periods use an empty dict for now.
decision.detailed_flow_values = {}
# Use the advanced flow value calculations from decision intelligence
for flow_name, flow_value in decision.detailed_flow_values.items():
immediate_flow_values[flow_name] = create_formatted_value(
flow_value, "currency", currency
)
# Calculate immediate_total_value as sum of all flow values (extract numeric values)
total_value = sum(fv.value for fv in immediate_flow_values.values())
immediate_total_value = create_formatted_value(
total_value, "currency", currency
)
# Create future_opportunity with enhanced data
future_opportunity = {
"description": f"Future value realization from {decision.strategic_intent.lower().replace('_', ' ')} strategy",
"target_hours": (
decision.future_target_hours if decision.future_target_hours else []
),
"expected_value": create_formatted_value(
decision.future_value or 0.0, "currency", currency
),
"dependencies": [
"Price forecast accuracy",
"Battery state management",
"Solar production forecast",
],
}
# Create the pattern object with enhanced decision intelligence fields
pattern = {
"hour": hour,
"pattern_name": decision.pattern_name
or f"{decision.strategic_intent} Strategy",
"flow_description": decision.description or "No significant energy flows",
"economic_context_description": f"Strategic intent: {decision.strategic_intent} - {decision.pattern_name or 'Standard operation'}",
"flows": flows,
"immediate_flow_values": immediate_flow_values,
"immediate_total_value": immediate_total_value,
"future_opportunity": future_opportunity,
"economic_chain": decision.economic_chain
or f"Hour {hour:02d}: No enhanced economic reasoning available",
"net_strategy_value": create_formatted_value(
decision.net_strategy_value or 0.0, "currency", currency
),
"electricity_price": create_formatted_value(
economic.buy_price, "currency", currency
),
"is_current_hour": is_current,
"is_actual": is_actual,
# Simple enhanced fields that actually work
"advanced_flow_pattern": decision.advanced_flow_pattern
or "NO_PATTERN_DETECTED",
}
patterns.append(pattern)
# Calculate summary statistics matching mock format
if patterns:
# Extract numeric values from FormattedValue objects before summing
total_net_value = sum(p["net_strategy_value"].value for p in patterns)
actual_patterns = [p for p in patterns if p["is_actual"]]
predicted_patterns = [p for p in patterns if not p["is_actual"]]
best_decision = max(patterns, key=lambda p: p["net_strategy_value"].value)
summary = {
"total_net_value": create_formatted_value(
total_net_value, "currency", currency
),
"best_decision_hour": best_decision["hour"],
"best_decision_value": best_decision["net_strategy_value"],
"actual_hours_count": len(actual_patterns),
"predicted_hours_count": len(predicted_patterns),
}
else:
summary = {
"total_net_value": create_formatted_value(0.0, "currency", currency),
"best_decision_hour": 0,
"best_decision_value": create_formatted_value(0.0, "currency", currency),
"actual_hours_count": 0,
"predicted_hours_count": 0,
}
# Create response matching exact mock format
response = {"patterns": patterns, "summary": summary}
# Process future_opportunity objects for camelCase conversion (matching mock logic)
for pattern in patterns:
opportunity = pattern.get("future_opportunity")
if opportunity:
pattern["future_opportunity"] = {
"description": opportunity["description"],
"targetHours": opportunity["target_hours"],
"expectedValue": opportunity["expected_value"],
"dependencies": opportunity["dependencies"],
}
return response
@router.get("/api/decision-intelligence")
async def get_decision_intelligence():
"""
Get decision intelligence data using real optimization results.
Converts real HourlyData to exact mock format for frontend compatibility.
"""
from app import bess_controller
_require_configured_system(bess_controller)
try:
# Get the daily view with real optimization data (same as dashboard)
daily_view = bess_controller.system.get_current_daily_view()
# Get currency from settings
currency = bess_controller.system.home_settings.currency
# Calculate current period index (for quarterly resolution)
now = time_utils.now()
current_period = now.hour * 4 + now.minute // 15
# Convert real PeriodData to mock format
response = convert_real_data_to_mock_format(
daily_view.periods, current_period, currency
)
# Convert snake_case to camelCase for frontend (matching mock behavior)
return convert_keys_to_camel_case(response)
except Exception as e:
logger.warning(
f"Decision intelligence not available yet (insights page under construction): {e}"
)
# Return minimal empty response instead of crashing - insights page is under construction
return convert_keys_to_camel_case(
{
"hours": [],
"summary": {
"total_battery_actions": 0,
"charging_hours": 0,
"discharging_hours": 0,
"idle_hours": 0,
"peak_charge_rate": 0.0,
"peak_discharge_rate": 0.0,
},
"message": "Decision intelligence data not yet available - insights page under construction",
}
)
# @router.get("/api/decision-intelligence")
async def get_decision_intelligence_mock():
"""
Get decision intelligence data with detailed flow patterns and economic reasoning.
Returns comprehensive energy flow analysis for each hour showing:
- Battery actions (charge/discharge decisions)
- Energy flow patterns between solar, grid, home, and battery
- Economic context and future opportunities
- Multi-hour strategy explanations
"""
try:
current_hour = time_utils.now().hour
patterns = []
# Real historical prices from 2024-08-16 (extreme volatility day)
prices = [
0.9827,
0.8419,
0.0321,
0.0097,
0.0098,
0.9136,
1.4433,
1.5162, # 00-07: High→Low→High
1.4029,
1.1346,
0.8558,
0.6485,
0.2895,
0.1363,
0.1253,
0.62, # 08-15: Morning high, midday drop
0.888,
1.1662,
1.5163,
2.5908,
2.7325,
1.9312,
1.5121,