-
-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathpredbat.py
More file actions
1899 lines (1706 loc) · 87.7 KB
/
Copy pathpredbat.py
File metadata and controls
1899 lines (1706 loc) · 87.7 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 sys
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 = "v8.50.0"
from download import predbat_update_move, predbat_update_download, check_install, 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:
# 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))
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,
)
from config import APPS_SCHEMA, CONFIG_ITEMS
from utils import minutes_since_yesterday, dp1, dp2, dp3
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
# 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={}, required_unit=None):
"""
Wrapper function to get state from HA
"""
if not self.ha_interface:
self.log("Error: set_state_wrapper - No HA interface available")
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 + timedelta(minutes=self.minutes_now)).strftime("%H:%M:%S")
def time_abs_str(self, minute):
"""
Return time absolute as human string
"""
return (self.midnight + 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.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.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.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_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.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
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.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.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_export_cost_threshold = 99
self.rate_import_cost_threshold = 99
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.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.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]
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
self.octopus_intelligent_charging = False
self.octopus_intelligent_ignore_unplugged = False
self.octopus_intelligent_consider_full = False
self.notify_devices = ["notify"]
self.octopus_url_cache = {}
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.load_last_car_slot = False
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.set_read_only = True
self.set_read_only_axle = False
self.set_reserve_enable = 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.rate_import = {}
self.rate_import_replicated = {}
self.rate_export = {}
self.rate_export_replicated = {}
self.rate_slots = []
self.low_rates = []
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 = {}
# (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.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.all_active_keep = {}
self.set_charge_low_power = False
self.set_export_low_power = False
self.config_root = "./"
self.inverter_can_charge_during_export = True
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
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 = datetime.now() + timedelta(minutes=skew)
now = now.replace(second=0, microsecond=0, minute=(now.minute - (now.minute % PREDICT_STEP)))
now_utc = now_utc.replace(second=0, microsecond=0, minute=(now_utc.minute - (now_utc.minute % PREDICT_STEP)))
self.now_utc = now_utc
self.now = now
self.midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
self.midnight_utc = now_utc.replace(hour=0, minute=0, second=0, microsecond=0)
self.difference_minutes = minutes_since_yesterday(now)
self.minutes_now = int((now - self.midnight).seconds / 60 / PREDICT_STEP) * PREDICT_STEP
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": 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:
expiry = self.now_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", [])
self.export_limits_best = 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")
self.plan_preclip = tuple(preclip) if isinstance(preclip, (list, tuple)) and len(preclip) == 4 else 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 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:
# Component is active but not alive - error state
component_status[component_name] = "error"
all_healthy = False
error_count += 1
component = self.components.get_component(component_name)
if not component.is_calculating():
failed_components.append(COMPONENT_LIST.get(component_name, {}).get("name", component_name))
elif is_active:
component_status[component_name] = "running"
else:
component_status[component_name] = "disabled"
self.dashboard_item(
"binary_sensor." + self.prefix + "_components_healthy",
state="on" if all_healthy else "off",
attributes={
"friendly_name": "Predbat components healthy",
"icon": "mdi:cog-outline" if all_healthy else "mdi:cog-off-outline",
"components": component_status,
"component_error_count": component_error_count,
"active_count": len(active_components),
"total_count": len(all_components),
"error_count": error_count,
},
)
if self.had_errors:
self.log("Error: Completed run status {} with Errors reported (check log)".format(status))
elif failed_components:
error_status = "Error: Complete run status {} with component errors: {}".format(status, ", ".join(failed_components))
self.log(error_status)
self.record_status(
error_status,
debug="best_charge_limit={} best_charge_window={} best_export_limit= {} best_export_window={}".format(self.charge_limit_best, self.charge_window_best, self.export_limits_best, self.export_window_best),
notify=True,
had_errors=True,
)
else:
self.log("Info: Completed run status {}".format(status))
self.record_status(
status,
debug="best_charge_limit={} best_charge_window={} best_export_limit= {} best_export_window={}".format(self.charge_limit_best, self.charge_window_best, self.export_limits_best, self.export_window_best),
notify=True,
extra=status_extra,
)
def update_pred(self, scheduled=True):
"""
Update the prediction state, everything is called from here right now
"""
recompute = False
status_extra = ""
self.had_errors = False
self.update_time()
self.save_current_config()
# Check our version, don't check for cloud version which can't update directly
if not self.get_arg("user_id", None):
self.download_predbat_releases()
# Check if we are still running the template configuration, if so don't run the plan
if self.get_arg("template", False):
self.log("Error: You have not completed editing the apps.yaml template, Predbat cannot run. Please comment out 'Template: True' line in apps.yaml to start Predbat running")
self.record_status("Error: Template Configuration, remove 'Template: True' line in apps.yaml to start predbat running", had_errors=True)
return
self.expose_config("active", True)
self.fetch_config_options()
sensor_force_replan = self.fetch_sensor_data()
# Check if any sensor changes require a replan
if sensor_force_replan:
self.log("Sensor changes require a replan, will recompute the plan")
recompute = True
# Open the control-ledger cycle BEFORE the first inverter read. fetch_inverter_data()
# runs update_status(), which writes scheduled_charge_enable through write_and_poll_switch
# and so CONFIRMS ownership - stamping those with the previous cycle number made the next
# observe() of them hit the STALE rung whenever execute_plan() had written the entity in
# the prior run. Every write in a run must share that run's cycle number.
self.control_ledger.begin_cycle()
# Fetch inverter data
if not self.fetch_inverter_data():
self.log("Error: Failed to fetch inverter data, not able to compute a plan")
self.record_status("Error: Failed to fetch inverter data, not able to compute a plan", had_errors=True)
return
# Check if we have valid import rates
if self.rate_min == self.rate_max == 0:
self.log("Error: Import rates are all zero, not able to compute a plan")
self.record_status("Error: Import rates are all zero, not able to compute a plan", had_errors=True)
return
if self.dynamic_load():
self.log("Dynamic load adjustment changed, will recompute the plan")
recompute = True
if not scheduled or not self.plan_valid or recompute:
self.log("Will recompute the plan as it is invalid")
recompute = True
else:
plan_age = self.now_utc - self.plan_last_updated
plan_age_minutes = plan_age.seconds / 60.0
self.log("Plan was last updated on {} and is now {} minutes old".format(self.plan_last_updated, dp1(plan_age_minutes)))
# Calculate the new plan (or re-use existing)
recompute = self.calculate_plan(recompute=recompute)
# Persist the plan so it can be restored immediately on next startup
if recompute and self.plan_valid:
self.save_plan()
# Publish rate data
self.publish_rate_and_threshold()
# Execute the plan, re-read the inverter first if we had to calculate (as time passes during calculations)
if recompute:
if not self.fetch_inverter_data():
self.log("Error: Failed to fetch inverter data, not able to execute the plan")
self.record_status("Error: Failed to fetch inverter data, not able to execute the plan", had_errors=True)
return
status, status_extra = self.execute_plan()
# If the plan was not updated, and the time has expired lets update it now
if not recompute:
plan_age = self.now_utc - self.plan_last_updated
plan_age_minutes = plan_age.seconds / 60.0
if (plan_age_minutes + RUN_EVERY) > self.calculate_plan_every:
recompute = True
self.log("Will recompute the plan as it is now {} minutes old and will exceed the max age of {} minutes before the next run".format(dp1(plan_age_minutes), self.calculate_plan_every))
plan_random_delay = self.get_arg("plan_random_delay", 0)
if plan_random_delay > 0:
delay = random.uniform(0, plan_random_delay)
self.log("Adding a random delay of {:.1f} seconds before recalculating the plan....".format(delay))
time.sleep(delay)
# Calculate an updated plan, fetch the inverter data again and execute the plan
self.calculate_plan(recompute=True)
if not self.fetch_inverter_data():
self.log("Error: Failed to fetch inverter data, not able to execute the plan")
self.record_status("Error: Failed to fetch inverter data, not able to execute the plan", had_errors=True)
return
status, status_extra = self.execute_plan()
else:
self.log("Will not recompute the plan, it is {} minutes old and max age is {} minutes".format(dp1(plan_age_minutes), self.calculate_plan_every))
# Notify listeners that plan has been executed (consumed by gateway, plugins, etc.)
if self.plugin_system:
self.plugin_system.call_hooks(
"on_plan_executed",
charge_windows=self.charge_window_best,
charge_limits=self.charge_limit_best,
export_windows=self.export_window_best,
export_limits=self.export_limits_best,
charge_rate_w=int(self.battery_rate_max_charge * MINUTE_WATT),
discharge_rate_w=int(self.battery_rate_max_discharge * MINUTE_WATT),
soc_max=self.soc_max,
reserve=self.reserve,
timezone=str(self.local_tz),
)
# iBoost solar diverter model update state, only on 5 minute intervals
if self.iboost_enable and scheduled:
if self.iboost_energy_today:
# If we have a realtime sensor just use that data
self.iboost_next = self.iboost_today
elif recompute and (self.minutes_now >= 0) and (self.minutes_now < self.calculate_plan_every):
# Reset at midnight
self.iboost_next = 0
# Save next iBoost model value
self.expose_config("iboost_today", self.iboost_next)
self.log("iBoost model today updated to {}".format(self.iboost_next))
# Update register writes counter
previous_inverter_writes = self.load_previous_value_from_ha(self.prefix + ".inverter_register_writes")
try:
previous_inverter_writes = int(previous_inverter_writes)
except (ValueError, TypeError):
previous_inverter_writes = 0
for id in self.count_inverter_writes.keys():
previous_inverter_writes += self.count_inverter_writes[id]
self.count_inverter_writes[id] = 0
self.dashboard_item(
self.prefix + ".inverter_register_writes",
state=dp2(previous_inverter_writes),
attributes={
"friendly_name": "Total register writes (all inverters)",
"state_class": "measurement",
"unit_of_measurement": "writes",
"icon": "mdi:counter",
},
)
self.log("Total inverter register writes now {}".format(previous_inverter_writes))
# Control interference detection. Restored once per process from the entity's own
# attributes so the 24h window survives a pod restart - without this "3 in 24h"
# silently means "3 since the last restart".
now_ts = time.time()
if not self.control_ledger_restored:
self.control_ledger.restore(self.load_previous_value_from_ha(self.prefix + ".control_conflicts", attribute="events"))
self.control_ledger_restored = True
# prune() and recent_events() are NOT the same filter and neither can stand in for the
# other. prune() maintains the durable store, dropping only what has genuinely aged out;
# a future-dated event (a clock behind NTP) stays, because the clock corrects and the
# history must survive until it does. recent_events() is what can be JUDGED right now, so
# it is what the count and the sustained list are built from. The "events" attribute
# publishes the stored list, because that attribute IS the store restore() reads back -
# publishing only the events it can judge would delete the rest on the next run.
self.control_ledger.prune(now_ts)
conflict_events = self.control_ledger.recent_events(now_ts)
sustained = self.control_ledger.sustained_controls(conflict_events)
self.dashboard_item(
self.prefix + ".control_conflicts",
state=len(conflict_events),
attributes={
"friendly_name": "Settings changed outside Predbat (24h)",
"state_class": "measurement",
"unit_of_measurement": "changes",
"icon": "mdi:account-alert",
# Newest 20 BY TIME. The stored list is sorted by restore(), so on a pod whose clock
# is behind, this run's real event carries a small "at", sorts to index 0, and a
# plain [-20:] tail discarded the very event just detected - from the attribute that
# IS the durable store.