-
-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathfetch.py
More file actions
2266 lines (1988 loc) · 115 KB
/
fetch.py
File metadata and controls
2266 lines (1988 loc) · 115 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 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
# pyright: reportAttributeAccessIssue=false
from datetime import datetime, timedelta
from utils import minutes_to_time, str2time, dp1, dp2, dp3, dp4, time_string_to_stamp, minute_data, get_now_from_cumulative
from const import MINUTE_WATT, PREDICT_STEP, TIME_FORMAT, PREDBAT_MODE_OPTIONS, PREDBAT_MODE_CONTROL_SOC, PREDBAT_MODE_CONTROL_CHARGEDISCHARGE, PREDBAT_MODE_CONTROL_CHARGE, PREDBAT_MODE_MONITOR
from futurerate import FutureRate
from axle import fetch_axle_sessions, load_axle_slot, fetch_axle_active
class Fetch:
def get_cloud_factor(self, minutes_now, pv_data, pv_data10):
"""
Work out approximated cloud factor
"""
pv_total = 0
pv_total10 = 0
for minute in range(self.forecast_minutes):
pv_total += pv_data.get(minute + minutes_now, 0.0)
pv_total10 += pv_data10.get(minute + minutes_now, 0.0)
pv_factor = None
if pv_total > 0 and (pv_total > pv_total10):
pv_diff = pv_total - pv_total10
pv_factor = dp2(pv_diff / pv_total) / 2.0
pv_factor = min(pv_factor, 1.0)
if self.metric_cloud_enable:
pv_factor_round = pv_factor
if pv_factor_round:
pv_factor_round = dp1(pv_factor_round)
self.log("PV Forecast {} kWh and 10% Forecast {} kWh pv cloud factor {}".format(dp1(pv_total), dp1(pv_total10), pv_factor_round))
return pv_factor
else:
return None
def filtered_today(self, time_data, resetmidnight=False, stamp=None):
"""
Grab figure for today (midnight)
"""
if stamp is None:
stamp = self.midnight_utc + timedelta(days=1)
stamp_minus = stamp - timedelta(minutes=PREDICT_STEP)
if resetmidnight:
stamp = stamp_minus
tomorrow_value = time_data.get(stamp.strftime(TIME_FORMAT), time_data.get(stamp_minus.strftime(TIME_FORMAT), None))
return tomorrow_value
def filtered_times(self, time_data):
"""
Filter out duplicate values in time series data
"""
prev = None
new_data = {}
keys = list(time_data.keys())
for id in range(len(keys)):
stamp = keys[id]
value = time_data[stamp]
next_value = time_data[keys[id + 1]] if id + 1 < len(keys) else None
if prev is None or value != prev or next_value != value:
new_data[stamp] = value
prev = value
id += 1
return new_data
def step_data_history(
self,
item,
minutes_now,
forward,
step=PREDICT_STEP,
scale_today=1.0,
scale_fixed=1.0,
type_load=False,
load_forecast={},
cloud_factor=None,
load_scaling_dynamic=None,
base_offset=None,
flip=False,
load_adjust={},
load_baseline={},
):
"""
Create cached step data for historical array
"""
values = {}
cloud_diff = 0
for minute in range(0, self.forecast_minutes + self.plan_interval_minutes, step):
value = 0
minute_absolute = minute + minutes_now
scaling_dynamic = 1.0
if load_scaling_dynamic:
scaling_dynamic = load_scaling_dynamic.get(minute_absolute, scaling_dynamic)
# Reset in-day adjustment for tomorrow
if (minute + minutes_now) > 24 * 60:
scale_today = 1.0
if type_load and not forward:
if self.load_forecast_only:
load_yesterday, load_yesterday_raw = (0, 0)
else:
load_yesterday, load_yesterday_raw = self.get_filtered_load_minute(item, minute, historical=True, step=step)
value += load_yesterday
else:
for offset in range(step):
if forward:
value += item.get(minute + minutes_now + offset, 0.0)
else:
if base_offset:
value += self.get_historical_base(item, minute + offset, base_offset)
else:
value += self.get_historical(item, minute + offset)
# Extra load adding in (e.g. heat pump)
load_extra = 0
if load_forecast:
for offset in range(step):
load_extra += self.get_from_incrementing(load_forecast, minute_absolute, backwards=False)
if load_adjust:
load_extra += load_adjust.get(minute_absolute, 0) * step / float(self.plan_interval_minutes) # The kWh figure is for the plan interval period, so divide by plan_interval_minutes and times by step
load_extra = max(load_extra, -value) # Don't allow going to negative load values
values[minute] = dp4((value + load_extra) * scaling_dynamic * scale_today * scale_fixed)
# Apply dynamic baseline
if minute_absolute in load_baseline:
values[minute] = max(values[minute], load_baseline[minute_absolute])
# Simple divergence model keeps the same total but brings PV/Load up and down every 5 minutes
if cloud_factor and cloud_factor > 0:
for minute in range(0, self.forecast_minutes, step):
cloud_on = (int((minute + self.minutes_now) / 5) + 1 if flip else 0) % 2
if cloud_on > 0:
cloud_diff += min(values[minute] * cloud_factor, values.get(minute + 5, 0) * cloud_factor)
values[minute] += cloud_diff
else:
subtract = min(cloud_diff, values[minute])
values[minute] -= subtract
cloud_diff = 0
values[minute] = dp4(values[minute])
return values
def get_filtered_load_minute(self, data, minute_previous, historical, step=1):
"""
Gets a previous load minute after filtering for car charging
"""
load_yesterday_raw = 0
for offset in range(step):
if historical:
load_yesterday_raw += self.get_historical(data, minute_previous + offset)
else:
load_yesterday_raw += self.get_from_incrementing(data, minute_previous + offset)
load_yesterday = load_yesterday_raw
# Subtract car charging energy and iboost energy (if enabled)
subtract_energy = 0
for offset in range(step):
if historical:
if self.car_charging_hold and self.car_charging_energy:
subtract_energy += self.get_historical(self.car_charging_energy, minute_previous + offset)
if self.iboost_energy_subtract and self.iboost_energy_today:
subtract_energy += self.get_historical(self.iboost_energy_today, minute_previous + offset)
else:
if self.car_charging_hold and self.car_charging_energy:
subtract_energy += self.get_from_incrementing(self.car_charging_energy, minute_previous + offset)
if self.iboost_energy_subtract and self.iboost_energy_today:
subtract_energy += self.get_from_incrementing(self.iboost_energy_today, minute_previous + offset)
load_yesterday = max(0, load_yesterday - subtract_energy)
if self.car_charging_hold and (not self.car_charging_energy) and (load_yesterday >= (self.car_charging_threshold * step)):
# Car charging hold - ignore car charging in computation based on threshold
load_yesterday = max(load_yesterday - (self.car_charging_rate[0] * step / 60.0), 0)
# Apply base load
base_load = self.base_load * step / 60.0
if load_yesterday < base_load:
add_to_base = base_load - load_yesterday
load_yesterday += add_to_base
load_yesterday_raw += add_to_base
return load_yesterday, load_yesterday_raw
def fill_load_from_power(self, load_minutes, load_power_data):
"""
This function helps to deal with load sensors which don't increment very often leading to poor quality load data
For example if its in kWh units then it might take many hours to increment.
Predbat actually wants a much more real time estimate, but integrating power sensors alone leads to drift over time.
Strategy: Divide data into 30-minute periods. For each period:
1. Calculate total load consumed (difference between start and end of period)
2. Integrate power data over that period
3. Scale power data to match the total load
4. Generate smooth minute-by-minute load curve
Since data goes backwards in time (minute 0 is now, higher minutes are further in past),
the load value DECREASES as we go forward in time (backwards through minutes).
"""
if not load_power_data:
self.log("Warn: No power data provided to fill_load_from_power")
return load_minutes
# Create a copy to avoid modifying the original
new_load_minutes = load_minutes.copy()
# Find all the minutes we have data for
max_minute = max(max(load_minutes.keys()) if load_minutes else 0, max(load_power_data.keys()) if load_power_data else 0)
# Determine gap size threshold for zero-load detection
# This uses the same threshold as the gap filling logic
gap_size = max(self.get_arg("load_filter_threshold", self.plan_interval_minutes), 5)
# Preprocessing: Fill periods of zero load where power data exists
# Find zero-load periods by looking for consecutive minutes with the same value (or 0)
zero_periods = []
period_start = None
last_value = None
for minute in range(0, max_minute + 1):
current_value = new_load_minutes.get(minute, 0)
# Check if this is a zero or constant period
if minute == 0:
last_value = current_value
if current_value == 0 or current_value == new_load_minutes.get(minute + 1, 0):
period_start = minute
else:
# If value is same as previous and same as next, it's a flat period
next_value = new_load_minutes.get(minute + 1, current_value)
if current_value == last_value and current_value == next_value:
if period_start is None:
period_start = minute
else:
# End of constant period
if period_start is not None and period_start < minute:
period_length = minute - period_start
# Only consider it zero load if it exceeds the gap_size threshold
if period_length >= gap_size:
# Check if there's power data in this period
has_power = any(load_power_data.get(m, 0) > 0 for m in range(period_start, minute))
if has_power and (last_value == 0 or last_value == new_load_minutes.get(minute, 0)):
zero_periods.append((period_start, minute - 1, last_value))
period_start = None
last_value = current_value
# Check final period
if period_start is not None and period_start < max_minute:
period_length = max_minute - period_start + 1
# Only consider it zero load if it exceeds the gap_size threshold
if period_length >= gap_size:
has_power = any(load_power_data.get(m, 0) > 0 for m in range(period_start, max_minute + 1))
if has_power and last_value == 0:
zero_periods.append((period_start, max_minute, last_value))
# Fill zero periods with integrated power data
if zero_periods:
for period_start, period_end, base_value in zero_periods:
# Integrate power data over this period
# First calculate total energy consumed in this period
total_energy = 0
for minute in range(period_start, period_end + 1):
power = load_power_data.get(minute, 0)
total_energy += power / 60.0 / 1000.0
amount_to_fill = 0
for minute in range(period_end, period_start, -1):
power = load_power_data.get(minute, 0)
energy = power / 60.0 / 1000.0
amount_to_fill += energy
new_load_minutes[minute] = new_load_minutes.get(minute, 0) + amount_to_fill
# Fill to start
for minute in range(period_start, -1, -1):
new_load_minutes[minute] = new_load_minutes.get(minute, 0) + amount_to_fill
# Process in 30-minute periods
period_length = 30
num_periods = (max_minute + period_length) // period_length
self.log("Processing {} 30-minute periods for power integration".format(num_periods))
for period_idx in range(num_periods):
period_start = period_idx * period_length
period_end = min(period_start + period_length - 1, max_minute)
# Get load at start and end of period (going backwards in time)
# period_start is more recent (higher cumulative value)
# period_end is further in past (lower cumulative value)
load_at_start = new_load_minutes.get(period_start, 0)
load_at_end = new_load_minutes.get(period_end + 1, new_load_minutes.get(period_end, 0))
# Total energy consumed in this period (going backwards means decrement)
load_total = load_at_start - load_at_end
# Integrate power data over this period (convert W to kWh)
integrated_energy = 0.0
power_count = 0
for minute in range(period_start, period_end + 1):
power = max(load_power_data.get(minute, 0), 0)
if power > 0:
power_count += 1
# Convert watts to kWh per minute: W * (1 hour / 60 minutes) / 1000
integrated_energy += power / 60.0 / 1000.0
# If we have both power data and load consumption, scale the power integration
if integrated_energy > 0 and load_total > 0:
# Calculate scaling factor to match load total
scale_factor = load_total / integrated_energy
# Apply scaled power integration to create smooth load curve
# Start from the highest value (at period_start = most recent)
# and decrement going backwards in time
running_total = load_at_start
for minute in range(period_start, period_end + 1):
new_load_minutes[minute] = dp4(running_total)
power = load_power_data.get(minute, 0)
energy_decrement = (power / 60.0 / 1000.0) * scale_factor
running_total -= energy_decrement
elif load_total > 0:
# No power data but we have load consumption
# Distribute the load evenly across the period
energy_per_minute = load_total / (period_end - period_start + 1)
running_total = load_at_start
for minute in range(period_start, period_end + 1):
new_load_minutes[minute] = dp4(running_total)
running_total -= energy_per_minute
return new_load_minutes
def previous_days_modal_filter(self, data):
"""
Look at the data from previous days and discard the best case one
"""
total_points = len(self.days_previous)
sum_days = []
sum_days_id = {}
min_sum = 99999999
min_sum_day = 0
sum_all_days = {}
days_list = self.days_previous.copy()
# Sort days list in numerical order with highest number day first
days_list.sort(reverse=True)
max_days = max(max(days_list), self.load_minutes_age)
for days in range(1, max_days + 1):
sum_day = 0
full_days = 24 * 60 * (days - 1)
for minute in range(0, 24 * 60, PREDICT_STEP):
minute_previous = 24 * 60 - minute + full_days - 1
load_yesterday, load_yesterday_raw = self.get_filtered_load_minute(data, minute_previous, historical=False, step=PREDICT_STEP)
sum_day += load_yesterday
if days in days_list:
sum_days.append(dp2(sum_day))
sum_days_id[days] = sum_day
if sum_day < min_sum:
min_sum_day = days
min_sum = dp2(sum_day)
sum_all_days[days] = dp2(sum_day)
# Work out the average non-zero day
average_non_zero_day = 0
average_non_zero_count = 0
for day_sum in sum_all_days.values():
# Sensible threshold to ignore zero days
if day_sum > 2.5:
average_non_zero_day += day_sum
average_non_zero_count += 1
if average_non_zero_count > 0:
average_non_zero_day /= average_non_zero_count
else:
average_non_zero_day = 24 # Assume a nominal 24kWh day if no data
self.log("Historical load totals for days {} are {}kWh, minimum value {}kWh".format(days_list, sum_days, min_sum))
if self.load_filter_modal and total_points >= 3 and (min_sum_day > 0):
self.log("Modal filter enabled - Discarding day {} as it is the lowest of the {} datapoints".format(min_sum_day, len(days_list)))
min_sum_day_idx = days_list.index(min_sum_day)
del days_list[min_sum_day_idx]
# Remove day 'min_sum_day' from self.days_previous
min_sum_day_idx = self.days_previous.index(min_sum_day)
del self.days_previous[min_sum_day_idx]
del self.days_previous_weight[min_sum_day_idx]
# Fill all the gaps including days we don't use
gap_size = max(self.get_arg("load_filter_threshold", self.plan_interval_minutes), 5)
gap_minutes = 0
gap_start_minute_previous = None
gap_list = []
num_gaps = 0
max_minute = max(max_days * 24 * 60, max(data.keys()) if data else 0)
# Find all the gaps
for minute_previous in range(0, max_minute, PREDICT_STEP):
if data.get(minute_previous, 0) == data.get(minute_previous + PREDICT_STEP, 0):
gap_minutes += PREDICT_STEP
if gap_start_minute_previous is None:
gap_start_minute_previous = minute_previous
else:
if gap_minutes >= gap_size:
num_gaps += gap_minutes
gap_list.append((gap_start_minute_previous, gap_minutes))
gap_minutes = 0
gap_start_minute_previous = None
if gap_minutes >= gap_size:
num_gaps += gap_minutes
gap_list.append((gap_start_minute_previous, gap_minutes))
# Work out total number of gap_minutes
if num_gaps > 0:
self.log("Warn: Found {} gaps in load_today totalling {} minutes to fill using average data".format(len(gap_list), num_gaps))
# Do the filling
for gap in gap_list:
gap_start_minute_previous = gap[0]
gap_minutes = gap[1]
gap_end_minute_previous = gap_start_minute_previous + gap_minutes
total_to_add = 0
# Fill the gap region by stepping backward through time (decrementing minute_previous)
# gap_start_minute_previous is the highest index (earliest in gap)
# We fill from there down to the end of the gap
minute_previous = gap_end_minute_previous
gap_day = None
while minute_previous > gap_start_minute_previous and minute_previous >= 0:
# Change of day?
new_gap_day = max(minute_previous // (24 * 60), 1)
if gap_day is None or (new_gap_day != gap_day):
gap_day = new_gap_day
average_day = sum_all_days.get(gap_day, average_non_zero_day)
if average_day <= 2.5:
average_day = average_non_zero_day
per_minute_increment = average_day / (24 * 60)
gap_day = new_gap_day
data[minute_previous] = dp4(data.get(minute_previous, 0) + total_to_add)
minute_previous -= 1
total_to_add += per_minute_increment
# Now ensure the sensor is incrementing all the way to 0
while minute_previous >= 0:
data[minute_previous] = dp4(data.get(minute_previous, 0) + total_to_add)
minute_previous -= 1
return data
def get_historical_base(self, data, minute, base_minutes):
"""
Get historical data from base minute ago
"""
# No data?
if not data:
return 0
minute_previous = base_minutes - minute
return self.get_from_incrementing(data, minute_previous)
def get_historical(self, data, minute):
"""
Get historical data across N previous days in days_previous array based on current minute
"""
total = 0
total_weight = 0
this_point = 0
# No data?
if not data:
return 0
for days in self.days_previous:
use_days = max(min(days, self.load_minutes_age), 1)
weight = self.days_previous_weight[this_point]
full_days = 24 * 60 * (use_days - 1)
minute_previous = 24 * 60 - minute + full_days
value = self.get_from_incrementing(data, minute_previous)
total += value * weight
total_weight += weight
this_point += 1
# Zero data?
if total_weight == 0:
return 0
else:
return total / total_weight
def get_from_incrementing(self, data, index, backwards=True):
"""
Get a single value from an incrementing series e.g. kWh today -> kWh this minute
"""
while index < 0:
index += 24 * 60
if backwards:
return max(data.get(index, 0) - data.get(index + 1, 0), 0)
else:
return max(data.get(index + 1, 0) - data.get(index, 0), 0)
def minute_data_import_export(self, max_days_previous, now_utc, key, scale=1.0, required_unit=None, increment=True, smoothing=True):
"""
Download one or more entities for import/export data
"""
if "." not in key:
entity_ids = self.get_arg(key, indirect=False)
else:
entity_ids = key
if isinstance(entity_ids, str):
entity_ids = [entity_ids]
if entity_ids is None:
self.log("Error: No entity IDs provided for {}".format(key))
entity_ids = []
import_today = {}
for entity_id in entity_ids:
# Ignore invalid entity IDs, they might be fixed values
if (not entity_id) or ("." not in entity_id):
continue
try:
history = self.get_history_wrapper(entity_id=entity_id, days=max_days_previous)
except (ValueError, TypeError) as exc:
self.log("Warn: No history data found for {} : {}".format(entity_id, exc))
history = []
if history and len(history) > 0:
import_today, _ = minute_data(
history[0],
max_days_previous,
now_utc,
"state",
"last_updated",
backwards=True,
smoothing=smoothing,
scale=scale,
clean_increment=increment,
accumulate=import_today,
required_unit=required_unit,
)
else:
if history is None:
# Only record as a failure if it was None (not just empty but failure)
self.log("Warn: Failure to fetch history for {}".format(entity_id))
self.record_status("Warn: Failure to fetch history from {}".format(entity_id), had_errors=True)
else:
self.log("Warn: Unable to fetch history for {}".format(entity_id))
return import_today
def minute_data_load(self, now_utc, entity_name, max_days_previous, load_scaling=1.0, required_unit=None, interpolate=False):
"""
Download one or more entities for load data
"""
entity_ids = self.get_arg(entity_name, indirect=False)
if isinstance(entity_ids, str):
entity_ids = [entity_ids]
load_minutes = {}
age_days = None
for entity_id in entity_ids:
if (not entity_id) or ("." not in entity_id):
# Invalid entity ID, might be a fixed value
continue
try:
history = self.get_history_wrapper(entity_id=entity_id, days=max_days_previous)
except (ValueError, TypeError):
history = []
if isinstance(history, list) and history and history[0]:
item = history[0][0]
try:
last_updated_time = str2time(item["last_updated"])
except (ValueError, TypeError):
last_updated_time = now_utc
age = now_utc - last_updated_time
if age_days is None:
age_days = age.days
else:
age_days = min(age_days, age.days)
load_minutes, _ = minute_data(
history[0],
max_days_previous,
now_utc,
"state",
"last_updated",
backwards=True,
smoothing=True,
scale=load_scaling,
clean_increment=True,
accumulate=load_minutes,
required_unit=required_unit,
interpolate=interpolate,
)
else:
if history is None:
# Only record as a failure if it was None (not just empty but failure)
self.log("Warn: Failure to fetch history for {}".format(entity_id))
self.record_status("Warn: Failure to fetch history from {}".format(entity_id), had_errors=True)
else:
self.log("Warn: Unable to fetch history for {}".format(entity_id))
if age_days is None:
age_days = 0
return load_minutes, age_days
def fetch_sensor_data(self, save=True):
"""
Fetch all the data, e.g. energy rates, load, PV predictions, car plan etc.
"""
prev_octopus_slots = self.octopus_slots.copy()
prev_octopus_saving_slots = self.octopus_saving_slots.copy()
prev_octopus_free_slots = self.octopus_free_slots.copy()
prev_axle_sessions = self.axle_sessions.copy()
self.rate_import = {}
self.rate_import_replicated = {}
self.rate_export = {}
self.rate_export_replicated = {}
self.rate_slots = []
self.io_adjusted = {}
self.low_rates = []
self.high_export_rates = []
self.octopus_slots = []
self.cost_today_sofar = 0
self.carbon_today_sofar = 0
self.import_today = {}
self.export_today = {}
self.battery_temperature_history = {}
self.battery_temperature_prediction = {}
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.load_scaling_dynamic = {}
self.carbon_intensity = {}
self.carbon_history = {}
curr = self.currency_symbols[1]
# Alert feed if enabled
if self.components:
alert_feed = self.components.get_component("alert_feed")
if alert_feed:
self.alerts, self.alert_active_keep = alert_feed.process_alerts(self.minutes_now, self.midnight_utc)
# Combine keep from alerts and manual SOC into all_active_keep
self.all_active_keep = self.alert_active_keep.copy()
if self.manual_soc_keep:
for minute, soc_value in self.manual_soc_keep.items():
if minute in self.all_active_keep:
self.all_active_keep[minute] = max(self.all_active_keep[minute], soc_value)
else:
self.all_active_keep[minute] = soc_value
# iBoost load data
if "iboost_energy_today" in self.args:
self.iboost_energy_today, iboost_energy_age = self.minute_data_load(self.now_utc, "iboost_energy_today", self.max_days_previous, required_unit="kWh", load_scaling=1.0)
if iboost_energy_age >= 1:
self.iboost_today = dp2(abs(self.iboost_energy_today[0] - self.iboost_energy_today[self.minutes_now]))
self.log("iBoost energy today from sensor reads {} kWh".format(self.iboost_today))
# Fetch ML forecast if enabled
load_ml_forecast = {}
if self.get_arg("load_ml_enable", False) and self.get_arg("load_ml_source", False):
load_ml_forecast = self.fetch_ml_load_forecast(self.now_utc)
if load_ml_forecast:
self.load_forecast_only = True # Use only ML forecast for load if enabled and we have data
# Fetch extra load forecast
self.load_forecast, self.load_forecast_array = self.fetch_extra_load_forecast(self.now_utc, load_ml_forecast)
# Load previous load data
if self.get_arg("ge_cloud_data", False):
self.download_ge_data(self.now_utc)
if ("load_power" in self.args) and self.get_arg("load_power_fill_enable", True):
# Use power data to make load data more accurate
self.log("Using load_power data to fill gaps in load_today data")
load_power_data, _ = self.minute_data_load(self.now_utc, "load_power", self.max_days_previous, required_unit="W", load_scaling=1.0, interpolate=True)
self.load_minutes = self.fill_load_from_power(self.load_minutes, load_power_data)
else:
# Load data
if "load_today" in self.args:
self.load_minutes, self.load_minutes_age = self.minute_data_load(self.now_utc, "load_today", self.max_days_previous, required_unit="kWh", load_scaling=self.load_scaling, interpolate=True)
self.log("Found {} load_today datapoints going back {} days".format(len(self.load_minutes), self.load_minutes_age))
self.load_minutes_now = get_now_from_cumulative(self.load_minutes, self.minutes_now, backwards=True)
self.load_last_period = (self.load_minutes.get(0, 0) - self.load_minutes.get(PREDICT_STEP, 0)) * 60 / PREDICT_STEP
if ("load_power" in self.args) and self.get_arg("load_power_fill_enable", True):
# Use power data to make load data more accurate
self.log("Using load_power data to fill gaps in load_today data")
load_power_data, _ = self.minute_data_load(self.now_utc, "load_power", self.max_days_previous, required_unit="W", load_scaling=1.0, interpolate=True)
self.load_minutes = self.fill_load_from_power(self.load_minutes, load_power_data)
else:
if self.load_forecast:
self.log("Using load forecast from load_forecast sensor")
self.load_minutes_now = self.load_forecast.get(0, 0)
self.load_minutes_age = 0
self.load_last_period = 0
else:
self.log("Error: You have not set load_today or load_forecast in apps.yaml, you will have no load data")
self.record_status(message="Error: load_today not set correctly", had_errors=True)
raise ValueError
# Load import today data
if "import_today" in self.args:
self.import_today = self.minute_data_import_export(self.max_days_previous, self.now_utc, "import_today", scale=self.import_export_scaling, required_unit="kWh")
self.import_today_now = get_now_from_cumulative(self.import_today, self.minutes_now, backwards=True)
else:
self.log("Warn: You have not set import_today in apps.yaml, you will have no previous import data")
# Load export today data
if "export_today" in self.args:
self.export_today = self.minute_data_import_export(self.max_days_previous, self.now_utc, "export_today", scale=self.import_export_scaling, required_unit="kWh")
self.export_today_now = get_now_from_cumulative(self.export_today, self.minutes_now, backwards=True)
else:
self.log("Warn: You have not set export_today in apps.yaml, you will have no previous export data")
# PV today data
if "pv_today" in self.args:
self.pv_today = self.minute_data_import_export(self.max_days_previous, self.now_utc, "pv_today", required_unit="kWh")
self.pv_today_now = get_now_from_cumulative(self.pv_today, self.minutes_now, backwards=True)
else:
self.log("Warn: You have not set pv_today in apps.yaml, you will have no previous PV data")
# Battery temperature
if "battery_temperature_history" in self.args:
self.battery_temperature_history = self.minute_data_import_export(self.max_days_previous, self.now_utc, "battery_temperature_history", scale=1.0, increment=False, smoothing=False)
data = []
for minute in range(0, 24 * 60, 5):
data.append({minute: self.battery_temperature_history.get(minute, 0)})
self.battery_temperature_prediction = self.predict_battery_temperature(self.battery_temperature_history, step=PREDICT_STEP)
self.log("Fetched battery temperature history data, current temperature {}°C".format(self.battery_temperature_history.get(0, None)))
# Car charging hold - when enabled battery is held during car charging in simulation
self.car_charging_energy = self.load_car_energy(self.now_utc)
# Log current values
self.log("Current data so far today: load {}kWh, import {}kWh, export {}kWh, PV {}kWh".format(dp2(self.load_minutes_now), dp2(self.import_today_now), dp2(self.export_today_now), dp2(self.pv_today_now)))
if "rates_import_octopus_url" in self.args:
# Fixed URL for rate import
self.log("Downloading import rates directly from URL {}".format(self.get_arg("rates_import_octopus_url", indirect=False)))
self.rate_import = self.download_octopus_rates(self.get_arg("rates_import_octopus_url", indirect=False))
elif "metric_octopus_import" in self.args:
# Octopus import rates
entity_id = self.get_arg("metric_octopus_import", None, indirect=False)
self.rate_import = self.fetch_octopus_rates(entity_id, adjust_key="is_intelligent_adjusted")
if not self.rate_import:
self.log("Error: metric_octopus_import is not set correctly in apps.yaml, or no energy rates can be read")
self.record_status(message="Error: metric_octopus_import not set correctly in apps.yaml, or no energy rates can be read", had_errors=True)
raise ValueError
elif "metric_energidataservice_import" in self.args:
# Octopus import rates
entity_id = self.get_arg("metric_energidataservice_import", None, indirect=False)
self.rate_import = self.fetch_energidataservice_rates(entity_id, adjust_key="is_intelligent_adjusted")
if not self.rate_import:
self.log("Error: metric_energidataservice_import is not set correctly in apps.yaml, or no energy rates can be read")
self.record_status(message="Error: metric_energidataservice_import not set correctly in apps.yaml, or no energy rates can be read", had_errors=True)
raise ValueError
else:
# Basic rates defined by user over time
self.rate_import = self.basic_rates(self.get_arg("rates_import", [], indirect=False), "rates_import")
# Gas rates if set
if "metric_octopus_gas" in self.args:
entity_id = self.get_arg("metric_octopus_gas", None, indirect=False)
self.rate_gas = self.fetch_octopus_rates(entity_id)
if not self.rate_gas:
self.log("Warn: metric_octopus_gas is not set correctly in apps.yaml, or no energy rates can be read")
self.record_status(message="Warn: rate_import_gas not set correctly in apps.yaml, or no energy rates can be read", had_errors=True)
else:
self.rate_gas, self.rate_gas_replicated = self.rate_replicate(self.rate_gas, is_import=False, is_gas=False)
self.rate_scan_gas(self.rate_gas, print=True)
elif "rates_gas" in self.args:
self.rate_gas = self.basic_rates(self.get_arg("rates_gas", [], indirect=False), "rates_gas")
self.rate_gas, self.rate_gas_replicated = self.rate_replicate(self.rate_gas, is_import=False, is_gas=False)
self.rate_scan_gas(self.rate_gas, print=True)
# Carbon intensity data
if self.carbon_enable and ("carbon_intensity" in self.args):
entity_id = self.get_arg("carbon_intensity", None, indirect=False)
self.carbon_intensity, self.carbon_history = self.fetch_carbon_intensity(entity_id)
# SoC history
soc_kwh_data = self.get_history_wrapper(entity_id=self.prefix + ".soc_kw_h0", days=2, required=False)
if soc_kwh_data:
self.soc_kwh_history, _ = minute_data(
soc_kwh_data[0],
2,
self.now_utc,
"state",
"last_updated",
backwards=True,
clean_increment=False,
smoothing=False,
divide_by=1.0,
scale=1.0,
required_unit="kWh",
)
# Work out current car SoC and limit
self.car_charging_loss = 1 - float(self.get_arg("car_charging_loss"))
entity_id = self.get_arg("octopus_intelligent_slot", indirect=False)
ohme_automatic = self.get_arg("ohme_automatic", False)
if entity_id:
completed = []
planned = []
if entity_id and "octopus_intelligent_slot_action_config" in self.args:
config_entry = self.get_arg("octopus_intelligent_slot_action_config", None, indirect=False)
service_name = entity_id.replace(".", "/")
result = self.call_service_wrapper(service_name, config_entry=config_entry, return_response=True)
if result and ("slots" in result):
planned = result["slots"]
else:
self.log("Warn: Unable to get data from {} - octopus_intelligent_slot using action config {}, result was {}".format(entity_id, config_entry, result))
else:
try:
completed = self.get_state_wrapper(entity_id=entity_id, attribute="completed_dispatches") or self.get_state_wrapper(entity_id=entity_id, attribute="completedDispatches")
planned = self.get_state_wrapper(entity_id=entity_id, attribute="planned_dispatches") or self.get_state_wrapper(entity_id=entity_id, attribute="plannedDispatches")
except (ValueError, TypeError):
self.log("Warn: Unable to get data from {} - octopus_intelligent_slot may not be set correctly in apps.yaml".format(entity_id))
self.record_status(message="Error: octopus_intelligent_slot not set correctly in apps.yaml", had_errors=True)
# Completed and planned slots
if completed:
self.octopus_slots += completed
if planned and (not self.octopus_intelligent_ignore_unplugged or self.car_charging_planned[0]):
# We only count planned slots if the car is plugged in or we are ignoring unplugged cars
self.octopus_slots += planned
# Get rate for import to compute charging costs
if self.rate_import:
self.rate_scan(self.rate_import, print=False)
if self.num_cars >= 1:
# Extract vehicle data if we can get it
size = self.get_state_wrapper(entity_id=entity_id, attribute="vehicle_battery_size_in_kwh")
rate = self.get_state_wrapper(entity_id=entity_id, attribute="charge_point_power_in_kw")
try:
size = float(size)
except (ValueError, TypeError):
size = None
try:
rate = float(rate)
except (ValueError, TypeError):
rate = None
if size:
self.car_charging_battery_size[0] = size
if rate:
# Take the max as Octopus over reports
self.car_charging_rate[0] = max(rate, self.car_charging_rate[0])
# Get car charging limit again from car based on new battery size
self.car_charging_limit[0] = dp3((float(self.get_arg("car_charging_limit", 100.0, index=0)) * self.car_charging_battery_size[0]) / 100.0)
# Extract vehicle preference if we can get it
if self.octopus_intelligent_charging:
octopus_ready_time = self.get_arg("octopus_ready_time", None)
if isinstance(octopus_ready_time, str) and len(octopus_ready_time) == 5:
octopus_ready_time += ":00"
octopus_limit = self.get_arg("octopus_charge_limit", None)
if octopus_limit:
try:
octopus_limit = float(octopus_limit)
except (ValueError, TypeError):
self.log("Warn: octopus_charge_limit is set to a bad value {} in apps.yaml, must be a number".format(octopus_limit))
octopus_limit = None
if octopus_limit:
octopus_limit = dp3(float(octopus_limit) * self.car_charging_battery_size[0] / 100.0)
self.car_charging_limit[0] = min(self.car_charging_limit[0], octopus_limit)
if octopus_ready_time:
self.car_charging_plan_time[0] = octopus_ready_time
# Use octopus slots for charging?
self.octopus_slots = self.add_now_to_octopus_slot(self.octopus_slots, self.now_utc)
if not self.octopus_intelligent_ignore_unplugged or self.car_charging_planned[0]:
self.car_charging_slots[0] = self.load_octopus_slots(self.octopus_slots, self.octopus_intelligent_consider_full)
if self.car_charging_slots[0]:
self.log("Car 0 using Octopus Intelligent, charging planned - charging limit {}, ready time {} - battery size {}".format(self.car_charging_limit[0], self.car_charging_plan_time[0], self.car_charging_battery_size[0]))
self.car_charging_planned[0] = True
else:
self.log("Car 0 using Octopus Intelligent, no charging is planned")
self.car_charging_planned[0] = False
else:
self.log("Car 0 using Octopus Intelligent is unplugged")
self.car_charging_planned[0] = False
else:
# Disable octopus charging if we don't have the slot sensor
self.octopus_intelligent_charging = False
# Work out car SoC and reset next
self.car_charging_soc = [0.0 for car_n in range(self.num_cars)]
self.car_charging_soc_next = [None for car_n in range(self.num_cars)]
for car_n in range(self.num_cars):
if car_n < len(self.car_charging_manual_soc) and self.car_charging_manual_soc[car_n]:
car_postfix = "" if car_n == 0 else "_" + str(car_n)
self.car_charging_soc[car_n] = self.get_arg("car_charging_manual_soc_kwh" + car_postfix, 0.0)
else:
self.car_charging_soc[car_n] = (self.get_arg("car_charging_soc", 0.0, index=car_n) * self.car_charging_battery_size[car_n]) / 100.0
if self.num_cars:
self.log("Cars: SoC: {}kWh, Charge limit {}%, plan time {}, battery size {}kWh".format(self.car_charging_soc, self.car_charging_limit, self.car_charging_plan_time, self.car_charging_battery_size))
if "rates_export_octopus_url" in self.args:
# Fixed URL for rate export
self.log("Downloading export rates directly from URL {}".format(self.get_arg("rates_export_octopus_url", indirect=False)))
self.rate_export = self.download_octopus_rates(self.get_arg("rates_export_octopus_url", indirect=False))
elif "metric_octopus_export" in self.args:
# Octopus export rates
entity_id = self.get_arg("metric_octopus_export", None, indirect=False)
self.rate_export = self.fetch_octopus_rates(entity_id)
if not self.rate_export:
self.log("Warning: metric_octopus_export is not set correctly in apps.yaml, or no energy rates can be read")
self.record_status(message="Error: metric_octopus_export not set correctly in apps.yaml, or no energy rates can be read", had_errors=True)
elif "metric_energidataservice_export" in self.args:
# Octopus export rates
entity_id = self.get_arg("metric_energidataservice_export", None, indirect=False)
self.rate_export = self.fetch_energidataservice_rates(entity_id)
if not self.rate_export:
self.log("Warning: metric_energidataservice_export is not set correctly in apps.yaml, or no energy rates can be read")
self.record_status(message="Error: metric_energidataservice_export not set correctly in apps.yaml, or no energy rates can be read", had_errors=True)
else:
# Basic rates defined by user over time
self.rate_export = self.basic_rates(self.get_arg("rates_export", [], indirect=False), "rates_export")
# Fetch octopus saving sessions and free sessions
self.octopus_free_slots, self.octopus_saving_slots = self.fetch_octopus_sessions()
self.axle_sessions = fetch_axle_sessions(self)
# Standing charge
self.metric_standing_charge = self.get_arg("metric_standing_charge", 0.0) * 100.0
self.log("Standing charge is set to {}{}".format(dp2(self.metric_standing_charge), curr))
# futurerate data
futurerate = FutureRate(self)
self.future_energy_rates_import, self.future_energy_rates_export = futurerate.futurerate_analysis(self.rate_import, self.rate_export)
# Replicate and scan import rates
if self.rate_import:
self.rate_scan(self.rate_import, print=False)
self.rate_import, self.rate_import_replicated = self.rate_replicate(self.rate_import, self.io_adjusted, is_import=True)
# Persist base import rates to storage (only non-replicated/non-override data)
if self.rate_store:
today = datetime.now()
for minute in self.rate_import:
# Only persist true API data, not replicated or override data
if minute not in self.rate_import_replicated or self.rate_import_replicated[minute] == "got":
# Get corresponding export rate or use 0
export_rate = self.rate_export.get(minute, 0) if self.rate_export else 0
self.rate_store.write_base_rate(today, minute, self.rate_import[minute], export_rate)
# Rehydrate finalized rates from storage - these take priority over fresh API data
for minute in range(0, self.minutes_now):
finalized_rate = self.rate_store.get_rate(today, minute, is_import=True)
if finalized_rate is not None:
self.rate_import[minute] = finalized_rate
self.rate_import_no_io = self.rate_import.copy()
self.rate_import = self.rate_add_io_slots(self.rate_import, self.octopus_slots)
self.load_saving_slot(self.octopus_saving_slots, export=False, rate_replicate=self.rate_import_replicated)
self.load_free_slot(self.octopus_free_slots, export=False, rate_replicate=self.rate_import_replicated)
self.rate_import = self.basic_rates(self.get_arg("rates_import_override", [], indirect=False), "rates_import_override", self.rate_import, self.rate_import_replicated)
self.rate_import = self.apply_manual_rates(self.rate_import, self.manual_import_rates, is_import=True, rate_replicate=self.rate_import_replicated)
self.rate_scan(self.rate_import, print=True)
else:
self.rate_import_no_io = {}
self.log("Warning: No import rate data provided")
self.record_status(message="Error: No import rate data provided", had_errors=True)
# Replicate and scan export rates
if self.rate_export:
self.rate_scan_export(self.rate_export, print=False)
self.rate_export, self.rate_export_replicated = self.rate_replicate(self.rate_export, is_import=False)
# Persist base export rates to storage (only non-replicated/non-override data)
if self.rate_store:
today = datetime.now()
for minute in self.rate_export:
# Only persist true API data, not replicated or override data
if minute not in self.rate_export_replicated or self.rate_export_replicated[minute] == "got":
# Get corresponding import rate or use 0