Repository navigation
Expand file tree
/
Copy pathfetch.py
More file actions
2299 lines (2022 loc) · 110 KB
/
Copy pathfetch.py
File metadata and controls
2299 lines (2022 loc) · 110 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 2024 - 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, dp0, dp1, dp2, dp3, dp4, time_string_to_stamp
from config import MAX_INCREMENT, MINUTE_WATT, PREDICT_STEP, TIME_FORMAT, TIME_FORMAT_SECONDS, PREDBAT_MODE_OPTIONS, PREDBAT_MODE_CONTROL_SOC, PREDBAT_MODE_CONTROL_CHARGEDISCHARGE, PREDBAT_MODE_CONTROL_CHARGE, PREDBAT_MODE_MONITOR, TIME_FORMAT_DAILY
from futurerate import FutureRate
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 + 30, 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 / 30.0 # The kWh figure is for the 30 minute period in question so divide by 30 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 clean_incrementing_reverse(self, data, max_increment=0):
"""
Cleanup an incrementing sensor data that runs backwards in time to remove the
resets (where it goes back to 0) and make it always increment
"""
new_data = {}
length = max(data) + 1
increment = 0
last = data[length - 1]
for index in range(length):
rindex = length - index - 1
nxt = data.get(rindex, last)
if nxt >= last:
if (max_increment > 0) and ((nxt - last) > max_increment):
# Smooth out big spikes
pass
else:
increment += nxt - last
last = nxt
elif nxt < last:
if nxt <= 0 or ((last - nxt) >= (1.0)):
last = nxt
new_data[rindex] = increment
return new_data
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 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
idx = 0
for days in self.days_previous:
use_days = max(min(days, self.load_minutes_age), 1)
sum_day = 0
full_days = 24 * 60 * (use_days - 1)
for minute in range(0, 24 * 60, PREDICT_STEP):
minute_previous = 24 * 60 - minute + full_days
load_yesterday, load_yesterday_raw = self.get_filtered_load_minute(data, minute_previous, historical=False, step=PREDICT_STEP)
sum_day += load_yesterday
sum_days.append(dp2(sum_day))
sum_days_id[days] = sum_day
if sum_day < min_sum:
min_sum_day = days
min_sum_day_idx = idx
min_sum = dp2(sum_day)
idx += 1
self.log("Historical data totals for days {} are {} - min {}".format(self.days_previous, sum_days, min_sum))
if self.load_filter_modal and total_points >= 3 and (min_sum_day > 0):
self.log("Model filter enabled - Discarding day {} as it is the lowest of the {} datapoints".format(min_sum_day, len(self.days_previous)))
del self.days_previous[min_sum_day_idx]
del self.days_previous_weight[min_sum_day_idx]
# Gap filling
gap_size = max(self.get_arg("load_filter_threshold", 30), 5)
for days in self.days_previous:
use_days = max(min(days, self.load_minutes_age), 1)
num_gaps = 0
full_days = 24 * 60 * (use_days - 1)
for minute in range(0, 24 * 60, PREDICT_STEP):
minute_previous = 24 * 60 - minute + full_days
if data.get(minute_previous, 0) == data.get(minute_previous + gap_size, 0):
num_gaps += PREDICT_STEP
# If we have some gaps
if num_gaps > 0:
average_day = sum_days_id[days]
if (average_day == 0) or (num_gaps >= 24 * 60):
self.log("Warn: Historical day {} has no data, unable to fill gaps normally using nominal 24kWh - you should fix your system!".format(days))
average_day = 24.0
else:
real_data_percent = ((24 * 60) - num_gaps) / (24 * 60)
average_day /= real_data_percent
self.log("Warn: Historical day {} has {} minutes of gap in the data, filled from {} kWh to make new average {} kWh (percent {}%)".format(days, num_gaps, dp2(sum_days_id[days]), dp2(average_day), dp0(real_data_percent * 100.0)))
# Do the filling
per_minute_increment = average_day / (24 * 60)
for minute in range(0, 24 * 60, PREDICT_STEP):
minute_previous = 24 * 60 - minute + full_days
if data.get(minute_previous, 0) == data.get(minute_previous + gap_size, 0):
for offset in range(minute_previous, 0, -1):
if offset in data:
data[offset] += per_minute_increment * PREDICT_STEP
else:
data[offset] = per_minute_increment * PREDICT_STEP
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, 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:
try:
history = self.get_history_wrapper(entity_id=entity_id, days=self.max_days_previous)
except (ValueError, TypeError):
history = []
if history:
import_today = self.minute_data(
history[0],
self.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:
self.log("Error: Unable to fetch history for {}".format(entity_id))
self.record_status("Error: Unable to fetch history from {}".format(entity_id), had_errors=True)
raise ValueError
return import_today
def minute_data_load(self, now_utc, entity_name, max_days_previous, load_scaling=1.0, required_unit=None):
"""
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:
try:
history = self.get_history_wrapper(entity_id=entity_id, days=max_days_previous)
except (ValueError, TypeError):
history = []
if history:
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 = self.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,
)
else:
self.log("Error: Unable to fetch history for {}".format(entity_id))
self.record_status("Error: Unable to fetch history from {}".format(entity_id), had_errors=True)
raise ValueError
if age_days is None:
age_days = 0
return load_minutes, age_days
def minute_data_state(self, history, days, now, state_key, last_updated_key, prev_last_updated_time=None):
"""
Get historical data for state (e.g. predbat status)
"""
mdata = {}
last_state = "unknown"
newest_state = 0
last_state = 0
newest_age = 999999
if not history:
self.log("Warn: Empty history passed to minute_data_state, ignoring (check your settings)...")
return mdata
# Process history
for item in history:
# Ignore data without correct keys
if state_key not in item:
continue
if last_updated_key not in item:
continue
# Unavailable or bad values
if item[state_key] == "unavailable" or item[state_key] == "unknown":
continue
state = item[state_key]
last_updated_time = str2time(item[last_updated_key])
# Update prev to the first if not set
if not prev_last_updated_time:
prev_last_updated_time = last_updated_time
last_state = state
timed = now - last_updated_time
timed_to = now - prev_last_updated_time
minutes_to = int(timed_to.seconds / 60) + int(timed_to.days * 60 * 24)
minutes = int(timed.seconds / 60) + int(timed.days * 60 * 24)
minute = minutes
while minute < minutes_to:
mdata[minute] = last_state
minute += 1
# Store previous state
prev_last_updated_time = last_updated_time
last_state = state
if minutes < newest_age:
newest_age = minutes
newest_state = state
state = newest_state
for minute in range(0, 60 * 24 * days):
rindex = 60 * 24 * days - minute - 1
state = mdata.get(rindex, state)
mdata[rindex] = state
minute += 1
return mdata
def history_attribute_to_minute_data(self, data, backwards=True):
"""
Get historical data for an attribute with history attribute filtering first
"""
history = []
oldest_date = self.now_utc
for key in data:
try:
timestamp_key = str2time(key)
oldest_date = min(oldest_date, timestamp_key)
except (ValueError, TypeError) as e:
continue
value = data[key]
history.append({"last_updated": key, "state": value})
max_age = self.now_utc - oldest_date
max_days = max(max_age.days, 1)
return [self.minute_data(history, max_days, self.now_utc, "state", "last_updated", backwards=backwards, smoothing=False, scale=1.0, clean_increment=False, required_unit=None), max_days]
def minute_data(
self,
history,
days,
now,
state_key,
last_updated_key,
backwards=False,
to_key=None,
smoothing=False,
clean_increment=False,
divide_by=0,
scale=1.0,
accumulate=[],
adjust_key=None,
spreading=None,
required_unit=None,
prev_last_updated_time=None,
last_state=0,
attributes=False,
):
"""
Turns data from HA into a hash of data indexed by minute with the data being the value
Can be backwards in time for history (N minutes ago) or forward in time (N minutes in the future)
"""
mdata = {}
adata = {}
newest_state = 0
newest_age = 999999
max_increment = MAX_INCREMENT
# Bounds on the data we store
minute_min = -days * 24 * 60
minute_max = days * 24 * 60
# Check history is valid
if not history:
self.log("Warn: Empty history passed to minute_data, ignoring (check your settings)...")
return mdata
# Glitch filter, cleans glitches in the data and removes bad values, only for incrementing data
if clean_increment and backwards:
if len(history) > 2:
prev_prev_item = history[0]
prev_item = history[1]
if state_key in prev_item and state_key in prev_prev_item:
try:
prev_value = float(prev_item[state_key])
except (ValueError, TypeError):
prev_value = 0
try:
prev_prev_value = float(prev_prev_item[state_key])
except (ValueError, TypeError):
prev_prev_value = 0
for item in history[2:]:
try:
value = float(item[state_key])
except (ValueError, TypeError):
value = prev_value
item[state_key] = value
# Filter simple glitch
if (prev_value > value) and (prev_value > prev_prev_value) and abs(prev_value - value) >= 0.1 and (value >= prev_prev_value):
prev_item[state_key] = value
prev_value = value
prev_prev_item = prev_item
prev_prev_value = prev_value
prev_value = value
prev_item = item
# Process history
for item in history:
if last_updated_key not in item:
continue
if attributes:
if state_key not in item["attributes"]:
continue
if item["attributes"][state_key] == "unavailable" or item["attributes"][state_key] == "unknown":
continue
state = item["attributes"][state_key]
else:
# Ignore data without correct keys
if state_key not in item:
continue
# Unavailable or bad values
if item[state_key] == "unavailable" or item[state_key] == "unknown":
continue
state = item[state_key]
# Get the numerical key and the timestamp and ignore if in error
try:
state = float(state) * scale
last_updated_time = str2time(item[last_updated_key])
except (ValueError, TypeError):
continue
# Find and converter units
integrate = False
if required_unit and ("attributes" in item):
if "unit_of_measurement" in item["attributes"]:
unit = item["attributes"]["unit_of_measurement"]
if unit != required_unit:
if required_unit in ["kWh"] and unit in ["W"]:
state = state / 1000.0
integrate = True
elif required_unit in ["kWh"] and unit in ["kW"]:
integrate = True
elif required_unit in ["kW", "kWh", "kg", "kg/kWh"] and unit in ["W", "Wh", "g", "g/kWh"]:
state = state / 1000.0
elif required_unit in ["W", "Wh", "g", "g/kWh"] and unit in ["kW", "kWh", "kg", "kg/kWh"]:
state = state * 1000.0
else:
# Ignore data in wrong units if we can't converter
continue
# Divide down the state if required
if divide_by:
state /= divide_by
# Update prev to the first if not set
if not prev_last_updated_time:
prev_last_updated_time = last_updated_time
last_state = state
# Intelligent adjusted?
if adjust_key:
adjusted = item.get(adjust_key, False)
else:
adjusted = False
# Work out end of time period
# If we don't get it assume it's to the previous update, this is for historical data only (backwards)
if to_key:
to_value = item[to_key]
if not to_value:
to_time = now + timedelta(minutes=24 * 60 * self.forecast_days)
else:
to_time = str2time(item[to_key])
else:
if backwards:
to_time = prev_last_updated_time
else:
if smoothing:
to_time = last_updated_time
last_updated_time = prev_last_updated_time
else:
to_time = None
if backwards:
timed = now - last_updated_time
if to_time:
timed_to = now - to_time
else:
timed = last_updated_time - now
if to_time:
timed_to = to_time - now
minutes = int(timed.total_seconds() / 60)
if to_time:
minutes_to = int(timed_to.total_seconds() / 60)
if minutes < newest_age:
newest_age = minutes
newest_state = state
# Power to Energy
if integrate and to_time:
total_minutes = abs(minutes_to - minutes)
state = last_state + state * total_minutes / 60.0
if to_time:
minute = minutes
if minute == minutes_to:
mdata[minute] = state
else:
if smoothing:
# Reset to zero, sometimes not exactly zero
if clean_increment and (state < last_state) and ((last_state - state) >= 1.0):
while minute < minutes_to:
if minute >= minute_min and minute <= minute_max:
mdata[minute] = state
minute += 1
else:
# Incrementing data can't go backwards
if clean_increment and state < last_state:
state = last_state
# Create linear function
diff = (state - last_state) / (minutes_to - minute)
# If the spike is too big don't smooth it, it will removed in the clean function later
if clean_increment and max_increment > 0 and diff > max_increment:
diff = 0
index = 0
while minute < minutes_to:
if minute >= minute_min and minute <= minute_max:
if backwards:
mdata[minute] = state - diff * index
else:
mdata[minute] = last_state + diff * index
minute += 1
index += 1
else:
while minute < minutes_to:
if minute >= minute_min and minute <= minute_max:
if backwards:
mdata[minute] = last_state
else:
mdata[minute] = state
if adjusted:
adata[minute] = True
minute += 1
else:
if spreading:
for minute in range(minutes, minutes + spreading):
if minute >= minute_min and minute <= minute_max:
mdata[minute] = state
else:
if minutes >= minute_min and minutes <= minute_max:
mdata[minutes] = state
# Store previous time & state
if to_time and not backwards:
prev_last_updated_time = to_time
else:
prev_last_updated_time = last_updated_time
last_state = state
# If we only have a start time then fill the gaps with the last values
if not to_key:
# Fill from last sample until now
for minute in range(60 * 24 * days):
if backwards:
rindex = minute
else:
rindex = 60 * 24 * days - minute - 1
if rindex not in mdata:
mdata[rindex] = newest_state
else:
break
# Fill gaps before the first value
state = 0
for minute in range(60 * 24 * days):
if backwards:
rindex = 60 * 24 * days - minute - 1
else:
rindex = minute
if rindex in mdata:
state = mdata[rindex]
break
# Fill gaps in the middle
for minute in range(60 * 24 * days):
if backwards:
rindex = 60 * 24 * days - minute - 1
else:
rindex = minute
state = mdata.get(rindex, state)
mdata[rindex] = state
# Reverse data with smoothing
if clean_increment:
mdata = self.clean_incrementing_reverse(mdata, max_increment)
# Accumulate to previous data?
if accumulate:
for minute in range(60 * 24 * days):
if minute in mdata:
mdata[minute] += accumulate.get(minute, 0)
else:
mdata[minute] = accumulate.get(minute, 0)
if adjust_key:
self.io_adjusted = adata
# Rounding
for minute in mdata.keys():
mdata[minute] = dp4(mdata[minute])
return mdata
def prune_today(self, data, prune=True, group=15, prune_future=False, intermediate=False):
"""
Remove data from before today
"""
results = {}
last_time = None
prev_value = None
for key in data:
# Convert key in format '2024-09-07T15:40:09.799567+00:00' into a datetime
if "." in key:
timekey = datetime.strptime(key, TIME_FORMAT_SECONDS)
else:
timekey = datetime.strptime(key, TIME_FORMAT)
if last_time and (timekey - last_time).seconds < group * 60:
continue
if intermediate and last_time and ((timekey - last_time).seconds > group * 60):
# Large gap, introduce intermediate data point
seconds_gap = int((timekey - last_time).total_seconds())
for i in range(1, seconds_gap // int(group * 60)):
new_time = last_time + timedelta(seconds=i * group * 60)
results[new_time.strftime(TIME_FORMAT)] = prev_value
if not prune or (timekey > self.midnight_utc):
if prune_future and (timekey > self.now_utc):
continue
results[key] = data[key]
last_time = timekey
prev_value = data[key]
return results
def history_attribute(self, history, state_key="state", last_updated_key="last_updated", scale=1.0, attributes=False, daily=False, offset_days=0, first=True, pounds=False):
results = {}
last_updated_time = None
last_day_stamp = None
if not isinstance(history, list):
return results
if history and len(history) >= 1:
history = history[0]
if not isinstance(history, list):
self.log("Warn: history_attribute expects a list of history items, got {}".format(type(history)))
return results
# Process history
for item in history:
if last_updated_key not in item:
continue
if attributes:
if state_key not in item["attributes"]:
continue
state = item["attributes"][state_key]
else:
# Ignore data without correct keys
if state_key not in item:
continue
# Unavailable or bad values
if item[state_key] == "unavailable" or item[state_key] == "unknown":
continue
state = item[state_key]
# Get the numerical key and the timestamp and ignore if in error
try:
state = float(state) * scale
if pounds:
state = dp2(state / 100)
except (ValueError, TypeError):
if isinstance(state, str):
if state.lower() in ["on", "true", "yes"]:
state = 1
elif state.lower() in ["off", "false", "no"]:
state = 0
else:
continue
else:
continue
try:
last_updated_time = item[last_updated_key]
last_updated_stamp = str2time(last_updated_time)
except (ValueError, TypeError):
continue
day_stamp = last_updated_stamp.astimezone().replace(hour=0, minute=0, second=0, microsecond=0)
if offset_days:
day_stamp += timedelta(days=offset_days)
if first and daily and day_stamp == last_day_stamp:
continue
last_day_stamp = day_stamp
# Add the state to the result
if daily:
# Convert day stamp from UTC into localtime
results[day_stamp.strftime(TIME_FORMAT_DAILY)] = state
else:
results[last_updated_time] = state
return results
def fetch_sensor_data(self):
"""
Fetch all the data, e.g. energy rates, load, PV predictions, car plan etc.
"""
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 = {}
self.octopus_free_slots = {}
self.octopus_saving_slots = {}
# Alert feed if enabled
self.process_alerts()
# 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 extra load forecast
self.load_forecast, self.load_forecast_array = self.fetch_extra_load_forecast(self.now_utc)
# Load previous load data
if self.get_arg("ge_cloud_data", False):
self.download_ge_data(self.now_utc)
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)
self.log("Found {} load_today datapoints going back {} days".format(len(self.load_minutes), self.load_minutes_age))
self.load_minutes_now = max(self.load_minutes.get(0, 0) - self.load_minutes.get(self.minutes_now, 0), 0)
self.load_last_period = (self.load_minutes.get(0, 0) - self.load_minutes.get(PREDICT_STEP, 0)) * 60 / PREDICT_STEP
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, 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.now_utc, "import_today", scale=self.import_export_scaling, required_unit="kWh")
self.import_today_now = max(self.import_today.get(0, 0) - self.import_today.get(self.minutes_now, 0), 0)
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.now_utc, "export_today", scale=self.import_export_scaling, required_unit="kWh")
self.export_today_now = max(self.export_today.get(0, 0) - self.export_today.get(self.minutes_now, 0), 0)
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.now_utc, "pv_today", required_unit="kWh")
self.pv_today_now = max(self.pv_today.get(0, 0) - self.pv_today.get(self.minutes_now, 0), 0)
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.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)})