Repository navigation
Expand file tree
/
Copy pathpredbat.py
More file actions
2279 lines (2063 loc) · 111 KB
/
Copy pathpredbat.py
File metadata and controls
2279 lines (2063 loc) · 111 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
# -----------------------------------------------------------------------------
# Predbat Home Battery System
# Copyright Trefor Southwell 2025-2026 - All Rights Reserved
# This application maybe used for personal use only and not for commercial use
# -----------------------------------------------------------------------------
# fmt off
# pylint: disable=consider-using-f-string
# pylint: disable=line-too-long
# pylint: disable=attribute-defined-outside-init
"""Main PredBat orchestrator module.
Entry point for the battery prediction and optimisation system. The PredBat class
uses multiple inheritance to combine Home Assistant interface, data fetching,
planning, execution, output publishing, and user interface capabilities into a
single orchestrator that runs the main prediction/optimisation loop every 5 minutes.
"""
import copy
import os
import sys
from datetime import datetime, timedelta, timezone
import traceback
import gc
import random
import time
# from memory_profiler import profile
IS_COMPILED = getattr(sys, "frozen", False)
import hass as hass
import pytz
import asyncio
THIS_VERSION = "v9.3.7"
THIS_VERSION_DISPLAY = THIS_VERSION
from download import predbat_update_move, predbat_update_download, check_install, read_deploy_git_version, DEFAULT_PREDBAT_REPOSITORY
from const import MINUTE_WATT
# Only do the self-install/self-update logic if we are NOT compiled.
if not IS_COMPILED:
# Show the actual commit for a dev deploy (coverage/deploy) or standalone git
# checkout (hass.py) rather than just the release tag - see git_version.txt
git_version = read_deploy_git_version(os.path.dirname(__file__))
if git_version:
THIS_VERSION_DISPLAY = "{} ({})".format(THIS_VERSION, git_version)
# Sanity check the install and re-download if corrupted
passed, modified = check_install(THIS_VERSION, repository=DEFAULT_PREDBAT_REPOSITORY)
if not passed:
print("Warn: Predbat files are not installed correctly, trying to download them")
files = predbat_update_download(THIS_VERSION, repository=DEFAULT_PREDBAT_REPOSITORY)
if files:
predbat_update_move(THIS_VERSION, files)
sys.exit(1)
elif modified:
print("Warn: Predbat files are installed but have modifications")
else:
print("Predbat files are installed correctly for version {}".format(THIS_VERSION_DISPLAY))
else:
# In compiled mode, we skip the entire self-update logic
print("Running in compiled mode; skipping local file checks and auto-update.")
from const import (
TIME_FORMAT,
PREDICT_STEP,
RUN_EVERY,
INVERTER_TEST,
CONFIG_ROOTS,
CONFIG_REFRESH_PERIOD,
INVERTER_QUICK_UPDATE_SECONDS,
DEBUG_ENABLE_MAX_HOURS,
)
from config import APPS_SCHEMA, CONFIG_ITEMS
import debug_history
from utils import (
minutes_since_yesterday,
minutes_since_midnight,
dp1,
dp2,
dp3,
find_unmasked_secret_paths,
is_entity_id,
mask_secret_args,
malloc_trim,
limit_malloc_arenas,
MALLOC_ARENA_LIMIT,
export_limits_to_stored,
export_limits_from_stored,
)
from predheat import PredHeat
from octopus import Octopus
from energydataservice import Energidataservice
from stromligning import Stromligning
from components import Components, COMPONENT_LIST
from execute import Execute
from marginal import Marginal
from plan import Plan
from fetch import Fetch
from output import Output
from userinterface import UserInterface
from compare import Compare
from plugin_system import PluginSystem
from github import GitHub
from ha import run_async
from control_ledger import ControlLedger
class PredBat(hass.Hass, Octopus, Energidataservice, Stromligning, Fetch, Plan, Marginal, Execute, Output, UserInterface, GitHub):
"""Main PredBat orchestrator combining all subsystems via multiple inheritance.
Inherits from Hass (HA interface), Octopus (rate loading), Energidataservice, Stromligning,
Fetch (data loading), Plan (optimisation), Execute (inverter control),
Output (sensor publishing), and UserInterface (config management).
Runs the main prediction/optimisation loop every 5 minutes via update_pred().
"""
def unit_conversion(self, entity_id, state, units, required_unit, going_to=False):
"""
Convert state to the required unit if necessary
"""
if not required_unit:
return state
if not units:
units = self.ha_interface.get_state(entity_id=entity_id, default="", attribute="unit_of_measurement")
if not units:
return state
units = str(units).strip()
required_unit = str(required_unit).strip()
try:
state = float(state)
except (ValueError, TypeError):
pass
# Swap order for going to conversion
if going_to:
units, required_unit = required_unit, units
if isinstance(state, float) and units and required_unit and units != required_unit:
units_lhs = units[0]
if units_lhs == "K":
units_lhs = "k"
if units_lhs not in ["k", "M", "m"]:
units_lhs = ""
required_lhs = required_unit[0]
if required_lhs not in ["k", "M", "m"]:
required_lhs = ""
if required_lhs == "K":
required_lhs = "k"
if units_lhs == "M" and required_lhs == "k":
# Convert MW to kW
state *= 1000.0
units = "k" + units[1:]
elif units_lhs == "k" and required_lhs == "M":
# Convert kW to MW
state /= 1000.0
units = "M" + units[1:]
elif units_lhs == "k" and required_lhs == "":
# Convert kWh to Wh
state *= 1000.0
units = units[1:] # Remove 'k' from units
elif units_lhs == "" and required_lhs == "k":
# Convert Wh to kWh
state /= 1000.0
units = "k" + units # Add 'k' to units
elif units_lhs == "m" and required_lhs == "":
# Convert mW to W
state /= 1000.0
units = units[1:] # Remove 'm' from units
elif units_lhs == "" and required_lhs == "m":
# Convert W to mW
state *= 1000.0
units = "m" + units # Add 'm' to units
if units != required_unit:
self.log("Warn: unit_conversion - Units mismatch for {}: expected {}, got {} after conversion".format(entity_id, required_unit, units))
return state
def get_state_wrapper(self, entity_id=None, default=None, attribute=None, refresh=False, required_unit=None, raw=False):
"""
Wrapper function to get state from HA
entity_id = The entity id to get
default = Default value if not found
attribute = Specific attribute to get, if not set defaults to the current state
refresh = Force a refresh of the state from HA
required_unit = Convert the state to this unit if different
raw = Fetch the raw database information which includes state and all the attributes
"""
if not self.ha_interface:
self.log("Error: get_state_wrapper - No HA interface available")
return None
# A literal is not something a state can be read from. Anything fetched with indirect=False
# can arrive here as one - several apps.yaml settings accept a fixed value in place of an
# entity, which the huawei and sofar templates use for reserve - and indexing into it raised
# rather than reading nothing, taking inverter creation down with it (GH#5003). entity_id of
# None is left alone: that is the documented "give me every state" call.
if entity_id is not None and not is_entity_id(entity_id):
self.log("Warn: get_state_wrapper - {} is a fixed value, not an entity id, so no state can be read from it".format(entity_id))
return default
# Entity with coded attribute
if entity_id and "$" in entity_id:
entity_id, attribute = entity_id.split("$")
state = self.ha_interface.get_state(entity_id=entity_id, default=default, attribute=attribute, refresh=refresh, raw=raw)
if not raw and required_unit:
state = self.unit_conversion(entity_id, state, None, required_unit)
return state
def set_state_wrapper(self, entity_id, state, attributes=None, required_unit=None):
"""
Wrapper function to get state from HA
"""
if attributes is None:
attributes = {}
if not self.ha_interface:
self.log("Error: set_state_wrapper - No HA interface available")
return False
# Same as get_state_wrapper - a fixed value in apps.yaml is not somewhere a state can be
# written, so say so rather than creating an entity named after a number (GH#5003)
if not is_entity_id(entity_id):
self.log("Warn: set_state_wrapper - {} is a fixed value, not an entity id, so {} can not be written to it".format(entity_id, state))
return False
state = self.unit_conversion(entity_id, state, None, required_unit, going_to=True)
return self.ha_interface.set_state(entity_id, state, attributes=attributes)
def fire_event_wrapper(self, domain, service):
"""
Wrapper function to fire a HA event
"""
if not self.ha_interface:
self.log("Error: fire_event_wrapper - No HA interface available")
return False
return self.call_service_wrapper("fire_event/service_registered", event_domain=domain, event_service=service)
def call_service_wrapper(self, service, **kwargs):
"""
Wrapper function to call a HA service
"""
if not self.ha_interface:
self.log("Error: call_service_wrapper - No HA interface available")
return False
return self.ha_interface.call_service(service, **kwargs)
def get_services_wrapper(self):
"""
Wrapper function to get services from HA
"""
if not self.ha_interface:
self.log("Error: get_services_wrapper - No HA interface available")
return False
return self.ha_interface.get_services()
def get_history_wrapper(self, entity_id, days=30, required=True, tracked=True):
"""
Wrapper function to get history from HA
"""
if not self.ha_interface:
self.log("Error: get_history_wrapper - No HA interface available")
return None
# If history cache is enabled then use it
ha_history = None
if self.components:
ha_history = self.components.get_component("ha_history")
if ha_history:
history = ha_history.get_history(entity_id, days=days, tracked=tracked)
else:
history = self.ha_interface.get_history(entity_id, days=days, now=self.now_utc)
if history and isinstance(history, list):
## Get default units and patch it into missing entries in the history
unit_of_measurement = self.get_state_wrapper(entity_id, attribute="unit_of_measurement")
if unit_of_measurement:
for record in history[0]:
if "attributes" not in record or not record["attributes"]:
record["attributes"] = {}
if "unit_of_measurement" not in record["attributes"]:
record["attributes"]["unit_of_measurement"] = unit_of_measurement
if required and (history is None):
self.log("Error: Failure to fetch history for {}".format(entity_id))
raise ValueError
else:
return history
def time_now_str(self):
"""
Return time now as human string
"""
return (self.midnight_utc + timedelta(minutes=self.minutes_now)).strftime("%H:%M:%S")
def time_abs_str(self, minute):
"""
Return time absolute as human string
"""
return (self.midnight_utc + timedelta(minutes=minute)).strftime("%m-%d %H:%M:%S")
def reset(self):
"""
Init stub
"""
self.text_plan = "Computing please wait..."
self.prediction_cache_enable = True
self.base_load = 0
self.plan_interval_minutes = self.args.get("plan_interval_minutes", 30)
self.db_manager = None
self.plan_debug = False
self.arg_errors = {}
self.arg_warnings = {}
self.validate_config_retries_remaining = 0
self.validate_config_next_retry_time = None
self.ha_interface = None
self.num_cars = 0
self.fatal_error = False
self.components = None
self.CONFIG_ITEMS = copy.deepcopy(CONFIG_ITEMS)
self.comparison = None
self.predheat = None
self.predbat_mode = "Monitor"
self.soc_kwh_history = {}
self.unmatched_args = {}
self.define_service_list()
self.stop_thread = False
# Forecast.solar API request metrics for monitoring
self.currency_symbols = self.args.get("currency_symbols", "£p")
self.watch_list = []
self.restart_active = False
self.clock_skew_warn_time = {} # Per-inverter time the moderate clock-skew warning was last logged, so it repeats hourly rather than every cycle
self.control_ledger = ControlLedger()
self.control_ledger_restored = False
self.inverter_needs_reset = False
self.inverter_needs_reset_force = ""
self.inverters = []
self.manual_charge_times = []
self.manual_export_times = []
self.manual_freeze_charge_times = []
self.manual_freeze_export_times = []
self.manual_demand_times = []
self.manual_all_times = []
self.manual_api = []
self.manual_import_rates = {}
self.manual_export_rates = {}
self.manual_load_adjust = {}
self.config_index = {}
self.dashboard_index = []
self.dashboard_index_app = {}
self.dashboard_values = {}
self.prefix = self.args.get("prefix", "predbat")
self.current_status = None
self.previous_status = None
self.had_errors = False
self.plan_valid = False
self.plan_preclip = None
self.plan_last_updated = None
self.plan_last_updated_minutes = 0
self.plugin_system = None
self.calculate_plan_every = 5
self.prediction_started = False
self.inverter_rate_intent = {}
self.inverter_balance_overridden = {}
self.update_pending = True
self.midnight_utc = None
self.difference_minutes = 0
self.minutes_to_midnight = 0
self.days_previous = [7]
self.days_previous_weight = [1]
self.max_days_previous = max(self.days_previous) + 1
self.forecast_days = 0
self.forecast_minutes = 0
self.soc_kw = 0
self.soc_percent = 0
self.soc_max = 10.0
self.battery_temperature = 20
self.end_record = 24 * 60 * 2
self.predict_soc = {}
self.predict_soc_best = {}
self.predict_iboost_best = {}
self.predict_car_hold_best = {}
self.predict_metric_best = {}
self.metric_min_improvement = 0.0
self.metric_min_improvement_export = 0.1
self.metric_min_improvement_export_freeze = 0.1
self.metric_min_improvement_plan = 2.0
self.export_more_solar = False
self.export_more_solar_threshold = 1.0
self.export_more_solar_warned_reason = None
self.metric_battery_cycle = 0.0
self.metric_battery_value_scaling = 1.0
self.metric_battery_value_export_scaling = 0.8
self.calculate_pv90_plan = False
self.pv_metric90_weight = 0.15
# DC array size in kWp, capping the p90 cloud model's extrapolation. Auto-detected from the
# forecast provider (see resolve_pv_array_kwp); 0 leaves the cap inert.
self.pv_array_kwp = 0.0
self.load_scaling90 = 0.7
self.metric_future_rate_offset_import = 0.0
self.metric_future_rate_offset_export = 0.0
self.metric_inday_adjust_damping = 1.0
self.metric_standing_charge = 0.0
self.metric_self_sufficiency = 0.0
self.metric_dynamic_load_adjust = False
self.metric_pv_calibration_enable = True
self.dynamic_load_baseline = {}
self.iboost_value_scaling = 1.0
self.rate_import = {}
self.rate_import_no_io = {}
self.rate_import_base = {}
self.rate_export = {}
self.rate_export_base = {}
self.rate_gas = {}
self.rate_slots = []
self.low_rates = []
self.low_rates_tariff = []
self.high_export_rates = []
self.cost_today_sofar = 0
self.carbon_today_sofar = 0
self.octopus_free_slots = []
self.octopus_saving_slots = []
self.car_charging_slots = []
self.car_charging_now_slots = []
self.reserve = 0
self.reserve_percent = 0.0
self.reserve_current = 0
self.reserve_current_percent = 0.0
self.battery_loss = 1.0
self.battery_loss_discharge = 1.0
self.inverter_loss = 1.0
self.inverter_freeze_export_discharge_rate = 0.0
self.inverter_hybrid = True
self.pv_ac_limit = 0
self.inverter_soc_reset = False
self.inverter_set_charge_before = True
self.best_soc_min = 0
self.best_soc_max = 0
self.best_soc_keep = 0
self.best_soc_keep_weight = 0.5
self.rate_min = 0
self.rate_min_minute = 0
self.rate_min_forward = {}
self.rate_min_base = 0
self.rate_max = 0
self.rate_max_minute = 0
self.rate_max_base = 0
self.rate_import_tariff_max = 0
self.rate_export_cost_threshold = 99
self.rate_import_cost_threshold = 99
self.rate_import_pre_event_end = None
self.rate_import_pre_event_threshold = None
self.rate_best_cost_threshold_charge = None
self.rate_best_cost_threshold_export = None
self.rate_average = 0
self.rate_export_min = 0
self.rate_export_min_minute = 0
self.rate_export_max = 0
self.rate_export_max_minute = 0
self.rate_export_max_forward = {}
self.rate_export_average = 0
self.rate_gas_min = 0
self.rate_gas_max = 0
self.rate_gas_average = 0
self.rate_gas_min_minute = 0
self.rate_gas_max_minute = 0
self.set_soc_minutes = 5
self.set_window_minutes = 5
self.debug_enable = False
self.debug_enable_started = None
self.debug_history_last_capture = None
self.debug_history_storage_warned = None
self.import_today = {}
self.import_today_now = 0
self.export_today = {}
self.export_today_now = 0
self.pv_today = {}
self.pv_today_now = 0
self.pv_power = 0
self.load_power = 0
self.battery_power = 0
self.grid_power = 0
self.car_charging_power = 0
self.car_charging_power_configured = False
self.io_adjusted = {}
self.current_charge_limit = 0.0
self.current_charge_limit_kwh = 0.0
self.inverter_limit = 0.0
self.export_limit = 0.0
self.charge_limit = []
self.charge_limit_best = []
self.charge_window = []
self.charge_window_best = []
self.car_charging_battery_size = [100]
self.car_charging_limit = [100]
# Per-car charge limit as the prediction model should see it, or None to use car_charging_limit.
# Set by fetch_sensor_data_cars() for cars on Octopus Intelligent dispatch slots (#4967).
self.car_charging_limit_model = None
self.car_charging_soc = [0]
self.car_charging_soc_next = [None]
self.car_charging_rate = [7.4]
self.car_charging_loss = 1.0
self.export_window = []
self.export_limits = []
self.export_limits_best = []
self.export_window_best = []
self.battery_rate_max_charge = 0.0333
self.battery_rate_max_charge_dc = 0
self.battery_rate_max_discharge = 0.0333
self.battery_rate_max_export = 0.0333
self.battery_rate_min = 0
self.battery_rate_max_scaling = 1.0
self.battery_rate_max_scaling_discharge = 1.0
self.car_energy_reported_load = False
self.charge_rate_now = 0
self.discharge_rate_now = 0
self.car_charging_hold = False
self.car_charging_manual_soc = []
self.car_charging_threshold = 99
self.car_charging_energy = {}
self.car_charging_energy_warned = False
# Which component's automatic_config() owns octopus_intelligent_slot/ready_time/charge_limit.
# Both OctopusAPI and OhmeAPI can wire the car slots, and Octopus re-runs its automatic_config
# whenever the tariff or intelligent device set moves - without a claim it silently takes the
# args back off Ohme part way through a run. None means nobody has claimed them.
self.car_slot_owner = None
self.octopus_intelligent_charging = False
self.octopus_intelligent_ignore_unplugged = False
self.octopus_intelligent_consider_full = False
self.octopus_intelligent_trust_slots = True
self.octopus_intelligent_dynamic = True
self.notify_devices = ["notify"]
self.octopus_url_cache = {}
self.dispatch_timeline_last = {}
self.dispatch_timeline_pending = []
self.dispatch_unconfirmed_last = {}
self.ge_url_cache = {}
self.github_url_cache = {}
self.load_minutes = {}
self.load_minutes_now = 0
self.load_minutes_age = 0
self.load_last_period = 0
self.load_last_status = "baseline"
self.dynamic_load_car_since = {}
self.dynamic_load_car_cancelled = {}
self.dynamic_load_car_warned = []
self.dynamic_load_car_warned_iog_off = False
self.dynamic_load_car_warned_dynamic_off = False
self.dynamic_load_car_run = {}
self.dynamic_load_car_confirmed = {}
self.dynamic_load_car_saved = {}
self.dynamic_load_car_sensors = {}
self.dynamic_load_car_effective = {}
self.dynamic_load_car_stripped = 0
self.octopus_surplus = set()
self.battery_capacity_nominal = False
self.battery_scaling_auto = False
self.releases = {}
self.balance_inverters_enable = False
self.balance_inverters_charge = True
self.balance_inverters_discharge = True
self.balance_inverters_crosscharge = True
self.balance_inverters_threshold_charge = 1.0
self.balance_inverters_threshold_discharge = 1.0
self.load_inday_adjustment = 1.0
self.holiday_load_scaling = 0.7
self.set_read_only = True
self.set_read_only_axle = False
self.set_reserve_enable = False
self.set_charge_freeze_only = False
self.metric_cloud_coverage = 0.0
self.future_energy_rates_import = {}
self.future_energy_rates_export = {}
self.load_scaling_dynamic = {}
self.battery_charge_power_curve = {}
self.battery_charge_power_curve_default = {}
self.battery_charge_power_curve_auto = False
self.battery_discharge_power_curve = {}
self.battery_discharge_power_curve_default = {}
self.battery_discharge_power_curve_auto = False
self.computed_charge_curve = False
self.computed_discharge_curve = False
self.isCharging = False
self.isCharging_Target = 0
self.isExporting = False
self.isExporting_Target = 0
self.savings_today_predbat = 0.0
self.savings_today_predbat_soc = 0.0
self.savings_today_pvbat = 0.0
self.savings_today_actual = 0.0
self.savings_last_updated = None
self.cost_yesterday_car = 0.0
self.cost_total_car = 0.0
self.carbon_yesterday = 0.0
self.rate_import = {}
self.rate_import_replicated = {}
self.rate_import_saving_minutes = set()
self.rate_import_pre_saving = {}
self.rate_export = {}
self.rate_export_replicated = {}
self.rate_export_saving_minutes = set()
self.rate_export_pre_saving = {}
self.rate_slots = []
self.low_rates = []
self.low_rates_tariff = []
self.high_export_rates = []
self.axle_sessions = []
self.cost_today_sofar = 0
self.carbon_today_sofar = 0
self.import_today = {}
self.export_today = {}
self.pv_today = {}
self.load_minutes = {}
self.load_minutes_age = 0
self.load_forecast = {}
self.load_forecast_array = []
self.pv_forecast_minute = {}
self.pv_forecast_minute10 = {}
self.pv_forecast_minute90 = {}
self.pv_light_dark = {}
# (p50, p90) content signatures from the previous plan run, used to spot a p90 that has been
# left behind by a p50 reassigned underneath it - see Plan.refresh_pv_forecast_minute90()
self.pv_forecast_minute90_signatures = None
self.load_scaling_dynamic = {}
self.carbon_intensity = {}
self.carbon_history = {}
self.carbon_enable = False
self.iboost_enable = False
self.iboost_gas = False
self.iboost_solar = False
self.iboost_solar_excess = False
self.iboost_gas_export = False
self.iboost_smart = False
self.iboost_smart_min_length = 30
self.iboost_on_export = False
self.iboost_prevent_discharge = False
self.iboost_smart_threshold = 0
self.iboost_rate_threshold = 9999
self.iboost_rate_threshold_export = 9999
self.iboost_plan = []
self.iboost_energy_subtract = True
self.iboost_running = False
self.iboost_running_full = False
self.iboost_running_solar = False
self.last_service_hash = {}
self.count_inverter_writes = {}
self.rate_slots = []
self.low_rates = []
self.low_rates_tariff = []
self.high_export_rates = []
self.octopus_slots = [[] for _ in range(8)]
self.cost_today_sofar = 0
self.carbon_today_sofar = 0
self.import_today = {}
self.export_today = {}
self.pv_today = {}
self.load_minutes = {}
self.load_minutes_age = 0
self.battery_temperature_charge_curve = {}
self.battery_temperature_discharge_curve = {}
self.battery_temperature_history = {}
self.battery_temperature_prediction = {}
self.alerts = []
self.alert_active_keep = {}
self.manual_soc_keep = {}
self.manual_soc_max_keep = {}
self.all_active_keep = {}
self.all_active_keep_max = {}
self.set_charge_low_power = False
self.set_export_low_power = False
self.config_root = "./"
self.inverter_can_charge_during_export = True
self.inverter_support_feedin_first = False
self.octopus_last_joined_try = None
# None = not yet confirmed, True = the current Power Down join service is confirmed registered.
# Deliberately never set to False - a failed probe still re-tries every join rather than being
# cached, since the underlying result can be an ambiguous timeout, not just "not registered".
# See the join logic in octopus.py and TODO(#4599).
self.octopus_join_service_power_down = None
self.calculate_savings_max_charge_slots = 1
self.inverter_data_last_fetch = None
# Pre-initialise the inverter clock skew offsets (set for real in fetch_config_options());
# anything that runs before that first fetch, e.g. in template mode, must read 0 rather
# than AttributeError on an unset attribute (#4965)
self.inverter_clock_skew_start = 0
self.inverter_clock_skew_end = 0
self.inverter_clock_skew_discharge_start = 0
self.inverter_clock_skew_discharge_end = 0
self.octopus_url_cache_loaded = False
self.github_url_cache_loaded = False
self.load_forecast_history = False
self.prediction_kernel_enable = False
for root in CONFIG_ROOTS:
if os.path.exists(root):
self.config_root = root
break
self.config_root_p = self.config_root
self.log("Config root is {}".format(self.config_root))
def update_time(self, print=True):
"""
Update the current time/date
"""
self.local_tz = pytz.timezone(self.args.get("timezone", "Europe/London"))
skew = self.args.get("clock_skew", 0)
if skew:
self.log("Warn: Clock skew is set to {} minutes".format(skew))
self.now_utc_real = datetime.now(self.local_tz)
now_utc = self.now_utc_real + timedelta(minutes=skew)
now_utc = now_utc.replace(second=0, microsecond=0, minute=(now_utc.minute - (now_utc.minute % PREDICT_STEP)))
self.now_utc = now_utc
self.midnight_utc = now_utc.replace(hour=0, minute=0, second=0, microsecond=0)
# Everything below is measured against now_utc, the configured timezone's clock. This used
# to run off a second, naive clock (datetime.now(), the host's), which agreed with now_utc
# only while the container's timezone matched the timezone: setting - and silently offset
# minutes_now and every rendered timestamp from the midnight_utc-keyed data they describe
# when it did not. now_utc and the midnight derived from it share a tzinfo, so these stay
# wall-clock differences, exactly as the naive arithmetic was.
self.difference_minutes = minutes_since_yesterday(now_utc)
self.minutes_now = minutes_since_midnight(now_utc, self.midnight_utc)
self.minutes_to_midnight = 24 * 60 - self.minutes_now
self.log("--------------- PredBat - update at {} with clock skew {} minutes, minutes now {}".format(now_utc, skew, self.minutes_now))
# @profile
def _emit_snapshot_metrics(self):
"""Emit point-in-time metrics after each update cycle."""
from predbat_metrics import metrics
m = metrics()
m.up.labels(version=THIS_VERSION).set(1)
m.last_update_timestamp.set_to_current_time()
# Plan age
if self.plan_last_updated:
plan_age = self.now_utc - self.plan_last_updated
m.plan_age_minutes.set(plan_age.total_seconds() / 60.0)
# Battery state
m.battery_soc_kwh.set(self.soc_kw)
m.battery_soc_percent.set(self.soc_percent)
m.battery_max_kwh.set(self.soc_max)
m.charge_rate_kw.set(self.charge_rate_now * MINUTE_WATT / 1000.0)
m.discharge_rate_kw.set(self.discharge_rate_now * MINUTE_WATT / 1000.0)
m.grid_power.set(self.grid_power / 1000.0)
m.battery_power.set(self.battery_power / 1000.0)
m.load_power.set(self.load_power / 1000.0)
m.pv_power.set(self.pv_power / 1000.0)
# Currency symbol
m.currency_symbol = self.currency_symbols[0]
# Cost and savings
m.cost_today.set(self.cost_today_sofar)
m.savings_today_pvbat.set(self.savings_today_pvbat)
m.savings_today_actual.set(self.savings_today_actual)
m.savings_today_predbat.set(self.savings_today_predbat)
# Config validity
m.config_valid.set(0 if self.arg_errors else 1)
m.config_warnings.set(len(self.arg_errors) if self.arg_errors else 0)
# Errors
if self.had_errors:
m.errors_total.labels(type="general").inc()
# Control ownership ledger
conflict_events = self.control_ledger.recent_events(time.time())
m.control_conflicts_24h.set(len(conflict_events))
sustained = self.control_ledger.sustained_controls(conflict_events)
m.control_conflicts_sustained_total.set(len(sustained))
m.control_conflicts_events = self.control_ledger.newest_events(20)
m.control_conflicts_sustained_controls = sustained
def save_plan(self):
"""Save the current best plan via the storage component so it can be restored on next startup."""
storage = self.components.get_component("storage") if self.components else None
if not storage:
self.log("Warning: Storage component unavailable, cannot save plan")
return
plan_data = {
"charge_window_best": self.charge_window_best,
"charge_limit_best": self.charge_limit_best,
"export_window_best": self.export_window_best,
"export_limits_best": export_limits_to_stored(self.export_limits_best),
"plan_preclip": self.plan_preclip,
"plan_last_updated": self.plan_last_updated.isoformat() if self.plan_last_updated else None,
"plan_last_updated_minutes": self.plan_last_updated_minutes,
}
try:
# storage.load() checks expiry against real wall-clock time (datetime.now(timezone.utc)),
# the same convention every other expiry-bearing storage.save() call in the codebase
# uses (github.py, octopus.py, enphase.py, fox.py, kraken.py, solax.py, etc.) - self.now_utc
# is Predbat's own simulated/plan clock, which is deliberately not real time during a
# debug-file replay or a test, and can drift from it. Using it here made a freshly-saved
# plan look already-expired the instant it was written whenever that drift exceeded 8
# hours (#5079).
expiry = datetime.now(timezone.utc) + timedelta(hours=8)
run_async(storage.save("predbat", "plan", plan_data, format="json", expiry=expiry))
self.log("Saved plan to storage")
except Exception as e:
self.log("Warning: Failed to save plan: {}".format(e))
def load_plan(self):
"""Restore a previously saved plan from storage if it is recent enough."""
storage = self.components.get_component("storage") if self.components else None
if not storage:
self.log("Warning: Storage component unavailable, cannot load plan")
return
try:
plan_data = run_async(storage.load("predbat", "plan"))
except Exception as e:
self.log("Warning: Failed to load saved plan: {}".format(e))
return
if not plan_data:
self.log("No saved plan found in storage")
return
if not isinstance(plan_data, dict):
self.log("Warning: Saved plan has unexpected type {}, ignoring".format(type(plan_data).__name__))
return
saved_updated = plan_data.get("plan_last_updated")
if not saved_updated:
self.log("Saved plan has no timestamp, ignoring")
return
try:
saved_dt = datetime.fromisoformat(saved_updated)
except (ValueError, TypeError):
self.log("Warning: Saved plan timestamp is invalid, ignoring")
return
if saved_dt.tzinfo is None:
saved_dt = saved_dt.replace(tzinfo=timezone.utc)
age_minutes = (self.now_utc - saved_dt).total_seconds() / 60
self.charge_window_best = plan_data.get("charge_window_best", [])
self.charge_limit_best = plan_data.get("charge_limit_best", [])
self.export_window_best = plan_data.get("export_window_best", [])
# Accepts the self-describing mapping form, the 3-element sequences a JSON round trip makes
# of the tuples, and the bare packed floats written by versions before the split.
self.export_limits_best = export_limits_from_stored(plan_data.get("export_limits_best", []))
# The pre-clip snapshot plan selection scores against. Older saves predate it, and it is only ever a
# four part plan, so anything else is discarded and the comparison falls back to the clipped plans.
preclip = plan_data.get("plan_preclip")
if isinstance(preclip, (list, tuple)) and len(preclip) == 4:
preclip_parts = list(preclip)
preclip_parts[3] = export_limits_from_stored(preclip_parts[3])
self.plan_preclip = tuple(preclip_parts)
else:
self.plan_preclip = None
self.plan_last_updated = saved_dt
self.plan_last_updated_minutes = plan_data.get("plan_last_updated_minutes", 0)
self.plan_valid = True
self.log("Restored saved plan from {:.0f} minutes ago: {} charge windows, {} export windows".format(age_minutes, len(self.charge_window_best), len(self.export_window_best)))
def _debug_enable_auto_scope(self):
"""Write a raw debug.yaml this cycle if switch.predbat_debug_enable is on, and
auto-disable the switch after DEBUG_ENABLE_MAX_HOURS rather than let it run forever.
debug_enable also gates verbose logging and the C++ kernel bypass (a more accurate but far
slower prediction path, see #4453) - both genuinely useful while actively watching a live
issue develop cycle to cycle, at a finer grain than the rotating debug-history buffer's
(#4417) coarsest interval of 1 hour. So this does not remove the raw per-cycle write, only
bounds how long it - and the slow-path logging it's normally turned on alongside - can run
unattended, since leaving it on by accident causes both unbounded predbat_debug_*.yaml disk
growth and a standing performance cost, not just the former.
"""
if not self.debug_enable:
self.debug_enable_started = None
return
if self.debug_enable_started is None:
self.debug_enable_started = self.now_utc
if (self.now_utc - self.debug_enable_started) >= timedelta(hours=DEBUG_ENABLE_MAX_HOURS):
self.log("Warn: debug_enable has been on for over {} hours - auto-disabling to bound disk writes and the slower debug prediction path. Re-enable if you need more time.".format(DEBUG_ENABLE_MAX_HOURS))
self.expose_config("debug_enable", False)
self.debug_enable = False
self.debug_enable_started = None
return
self.create_debug_yaml()
def _capture_debug_history(self):
"""Capture a rolling debug-history snapshot if due, for #4417.
Independent of switch.predbat_debug_enable - runs on a coarse interval so
there is always some recent history to replay a bug report against, rather
than only when the switch happened to already be on before the problem
occurred. switch.predbat_debug_history_enable disables the routine capture
entirely (default on), but debug_history_force_capture still works even
then - an explicit "give me one right now" request (e.g. from an automation
that just noticed something worth investigating) is a different intent to
"keep a rolling background history" and must not be silently skipped by
that switch. debug_history_count has a config-schema minimum of 1 (not 0)
precisely so it can't also mean "off" - the switch is the only off-switch,
avoiding two independent, potentially-conflicting ways to disable this.
debug_history_last_capture and the force-capture switch are both only
updated on a genuine successful capture, per @springfall2008's #4438 review
(items 1-3): previously both reset unconditionally, so a failed attempt
(an exception, or storage simply being unavailable) was silently treated
as if it had succeeded - deferring the next *routine* retry a full
debug_history_interval for no reason, and (for a forced request) resetting
the switch before the snapshot the docs promise it waits for was actually
taken. A failed forced capture now leaves the switch on, so it retries
every cycle until it succeeds or the switch is turned off - a routine
capture retries at its normal interval either way, since a failure simply
leaves last_capture at its previous (possibly-None) value rather than
artificially advancing it.
The "storage unavailable" warning is throttled separately
(debug_history_storage_warned), on the same interval, so a persistent
outage logs once per interval instead of every ~5-minute cycle - this is
deliberately independent of the capture throttle above, so a later
genuine capture attempt is never skipped just because the warning was
recently logged.
"""
count = int(self.get_arg("debug_history_count", 15))
interval_hours = max(1, int(self.get_arg("debug_history_interval", 3)))
enabled = self.get_arg("debug_history_enable", True)
forced = self.get_arg("debug_history_force_capture", False)
if not enabled and not forced:
return
if not forced:
if self.debug_history_last_capture is not None and (self.now_utc - self.debug_history_last_capture) < timedelta(hours=interval_hours):
return
storage = self.components.get_component("storage") if self.components else None
if not storage:
if self.debug_history_storage_warned is None or (self.now_utc - self.debug_history_storage_warned) >= timedelta(hours=interval_hours):
self.log("Warning: Storage component unavailable, cannot capture debug history")
self.debug_history_storage_warned = self.now_utc
return
try:
yaml_text = self.create_debug_yaml(write_file=False)
# Label the snapshot with the plan slot it falls in, not the arbitrary moment the
# ~5-minute cycle happened to trigger the capture - so it lines up exactly with one
# plan row's own timestamp (both are minute_relative offsets from self.midnight_utc
# in steps of self.plan_interval_minutes, see output.py's raw_plan builder) instead of
# needing a fuzzy nearest-match window in the plan's History view.
slot_minutes = max(1, self.plan_interval_minutes)
minutes_since_midnight = int((self.now_utc - self.midnight_utc).total_seconds() // 60)
capture_time = self.midnight_utc + timedelta(minutes=(minutes_since_midnight // slot_minutes) * slot_minutes)
# The window this buffer is meant to cover, e.g. 15 x 3h = 45h - a snapshot older
# than that gets pruned even if max_count hasn't been reached yet, so a burst of
# close-together captures (several force-captures, or a shortened interval) can't
# leave something far older than the intended window lingering just because the
# count cap alone hasn't caught up to it. count's config-schema minimum is 1, but
# clamp defensively anyway in case a stale persisted value predates that minimum.
count = max(count, 1)
max_age = timedelta(hours=interval_hours * count)
run_async(debug_history.capture_snapshot(storage, yaml_text, capture_time, count, max_age=max_age))
except Exception as e:
self.log("Warning: Failed to capture debug history snapshot: {}".format(e))
return
self.debug_history_last_capture = self.now_utc
if forced:
# Only reset once the snapshot has genuinely been taken, matching docs/customisation.md -
# an automation should never have to remember to turn it back off, but a failed attempt
# should retry rather than being silently swallowed by an early reset.
self.expose_config("debug_history_force_capture", False)
def record_final_run_status(self, status, status_extra):
"""
Publish the component health dashboard item and record the final run status for this cycle.
Any component that is active but not alive fails the run, even if the plan itself computed successfully.
"""
failed_components = []
if self.components:
all_components = self.components.get_all()
active_components = self.components.get_active()
error_count = 0
component_status = {}
component_error_count = {}
all_healthy = True
for component_name in all_components:
is_active = self.components.is_active(component_name)
is_alive = self.components.is_alive(component_name)
component_error_count[component_name] = self.components.get_error_count(component_name)
if is_active and not is_alive: