-
-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathoutput.py
More file actions
3635 lines (3325 loc) · 177 KB
/
Copy pathoutput.py
File metadata and controls
3635 lines (3325 loc) · 177 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
"""Output and sensor publishing module.
Publishes prediction results, plans, rates, status, and metrics as Home
Assistant entities. Generates HTML plan visualisations, car charging
schedules, rate window sensors, and financial metric summaries.
"""
import math
import copy
from html import escape as escape_html
from datetime import timedelta
from predbat import THIS_VERSION_DISPLAY
from const import TIME_FORMAT, PREDICT_STEP, EXPORT_LIMIT_FREEZE, EXPORT_LIMIT_IDLE, MINUTE_WATT
from utils import dp0, dp1, dp2, dp3, calc_percent_limit, minute_data, minute_data_state, find_charge_rate
from prediction import Prediction
# Per-slot plan "why" reason templates. Keyed by a stable reason code, each template is
# rendered client-side (web_helper.py) by substituting {placeholder} names against the row's
# own "reasons" params - published once here rather than duplicating the rendered sentence on
# every row (per maintainer review on PR #4311).
REASON_TEMPLATES = {
"demand_rising": "Demand — battery level is expected to rise from solar generation; no charging or exporting is scheduled this slot.",
"demand_falling": "Demand — the battery is expected to discharge to cover house load; no charging or exporting is scheduled this slot.",
"demand_steady": "Demand — battery level is expected to stay steady; no charging or exporting is scheduled this slot.",
# Used for the first half of a split slot where the export window only starts partway through -
# deliberately worded without the "nothing is scheduled this slot" clause of the plain demand
# reasons above, which would contradict the export reason sitting alongside it in the same slot.
"demand_before_export_rising": "Until {split_time}, the battery level is expected to rise from solar generation.",
"demand_before_export_falling": "Until {split_time}, the battery is expected to discharge to cover house demand.",
"demand_before_export_steady": "Until {split_time}, the battery level is expected to stay steady.",
"freeze_charge": "Freeze charging — the battery holds at the current level rather than charging further this slot (import rate {rate}p/kWh vs. the calculated {threshold}p/kWh threshold).",
"hold_charge_at_target": "Holding — the battery is already predicted to be at or above the {target_percent}% target for this window without charging further.",
"charge_low_rate": "Charging up to {target_percent}% at {rate_kw}kW at the import rate for this slot of ({rate}p/kWh).",
"freeze_export": "Freezing export — solar surplus passes straight to the grid, but it's not worth discharging the battery to sell more this slot.",
"hold_export_unreachable": "Export window active but not triggered — the battery isn't predicted to reach the {target_percent}% level needed to export this slot.",
"export_high_rate": "Exporting down to {target_percent}% at {rate_kw}kW at the export rate of ({rate}p/kWh) using stored energy back to the grid.",
"manual_override_charge": "You manually set this slot to charge.",
"manual_override_freeze_charge": "You manually set this slot to freeze charging.",
"manual_override_export": "You manually set this slot to export.",
"manual_override_freeze_export": "You manually set this slot to freeze exporting.",
"manual_override_demand": "You manually set this slot to demand mode.",
}
def yesterday_slot_is_exporting(slot_status):
"""True when a historical ``predbat.status`` string (already lower-cased) represents export
activity for the "yesterday" plan reconstruction in ``calculate_yesterday()``.
Includes "cross-charging" explicitly - it genuinely straddles both sides of the fleet at once,
but as a string it contains "charging" and not "exporting", so a plain substring check on
"exporting" alone would silently drop the export half of a real cross-charging slot.
"""
return "exporting" in slot_status or "cross-charging" in slot_status
class Output:
"""Output and sensor publishing mixin.
Publishes prediction results, plans, rates, status, and metrics as
Home Assistant entities. Generates HTML plan visualisations, car
charging schedules, and financial metric summaries.
"""
def publish_car_plan(self):
"""
Publish the car charging plan
"""
plan = []
postfix = ""
for car_n in range(self.num_cars):
if car_n > 0:
postfix = "_" + str(car_n)
if not self.car_charging_slots[car_n]:
self.dashboard_item(
"binary_sensor." + self.prefix + "_car_charging_slot" + postfix,
state="off",
attributes={"planned": plan, "cost": None, "kWh": None, "friendly_name": "Predbat car charging slot" + postfix, "icon": "mdi:home-lightning-bolt-outline"},
)
self.dashboard_item(
self.prefix + ".car_charging_start" + postfix,
state="",
attributes={
"friendly_name": "Predbat car charge start time car" + postfix,
"timestamp": None,
"minutes_to": self.forecast_minutes,
"state_class": None,
"unit_of_measurement": None,
"device_class": "timestamp",
"icon": "mdi:table-clock",
},
)
else:
window = self.car_charging_slots[car_n][0]
if self.minutes_now >= window["start"] and self.minutes_now < window["end"] and window["kwh"] > 0:
slot = True
else:
slot = False
time_format_time = "%H:%M:%S"
car_startt = self.midnight_utc + timedelta(minutes=window["start"])
car_start_time_str = car_startt.strftime(time_format_time)
minutes_to = max(window["start"] - self.minutes_now, 0)
self.dashboard_item(
self.prefix + ".car_charging_start" + postfix,
state=car_start_time_str,
attributes={
"friendly_name": "Predbat car charge start time car" + postfix,
"timestamp": car_startt.strftime(TIME_FORMAT),
"minutes_to": minutes_to,
"state_class": None,
"unit_of_measurement": None,
"device_class": "timestamp",
"icon": "mdi:table-clock",
},
)
total_kwh = 0
total_cost = 0
for window in self.car_charging_slots[car_n]:
start = self.time_abs_str(window["start"])
end = self.time_abs_str(window["end"])
kwh = dp2(window["kwh"])
average = dp2(window["average"])
cost = dp2(window["cost"])
show = {}
show["start"] = start
show["end"] = end
show["kwh"] = kwh
show["average"] = average
show["cost"] = cost
total_cost += cost
total_kwh += kwh
plan.append(show)
self.dashboard_item(
"binary_sensor." + self.prefix + "_car_charging_slot" + postfix,
state="on" if slot else "off",
attributes={
"planned": plan,
"cost": dp2(total_cost),
"kwh": dp2(total_kwh),
"friendly_name": "Predbat car charging slot" + postfix,
"icon": "mdi:home-lightning-bolt-outline",
},
)
def publish_rates_export(self):
"""
Publish the export rates
"""
window_str = ""
if self.high_export_rates:
window_n = 0
for window in self.high_export_rates:
rate_high_start = window["start"]
rate_high_end = window["end"]
rate_high_average = window["average"]
rate_high_minutes_to_start = max(rate_high_start - self.minutes_now, 0)
rate_high_minutes_to_end = max(rate_high_end - self.minutes_now, 0)
if window_str:
window_str += ", "
window_str += "{}: {} - {} @ {}".format(window_n, self.time_abs_str(rate_high_start), self.time_abs_str(rate_high_end), rate_high_average)
rate_high_start_date = self.midnight_utc + timedelta(minutes=rate_high_start)
rate_high_end_date = self.midnight_utc + timedelta(minutes=rate_high_end)
time_format_time = "%H:%M:%S"
if window_n == 0:
self.dashboard_item(
self.prefix + ".high_rate_export_start",
state=rate_high_start_date.strftime(time_format_time),
attributes={
"date": rate_high_start_date.strftime(TIME_FORMAT),
"friendly_name": "Next high export rate start",
"state_class": "timestamp",
"icon": "mdi:table-clock",
"minutes_to": rate_high_minutes_to_start,
"rate": dp2(rate_high_average),
},
)
self.dashboard_item(
self.prefix + ".high_rate_export_end",
state=rate_high_end_date.strftime(time_format_time),
attributes={
"date": rate_high_end_date.strftime(TIME_FORMAT),
"friendly_name": "Next high export rate end",
"state_class": "timestamp",
"icon": "mdi:table-clock",
"minutes_to": rate_high_minutes_to_end,
"rate": dp2(rate_high_average),
},
)
self.dashboard_item(
self.prefix + ".high_rate_export_cost",
state=dp2(rate_high_average),
attributes={
"friendly_name": "Next high export rate cost",
"state_class": "measurement",
"unit_of_measurement": self.currency_symbols[1],
"icon": "mdi:currency-usd",
},
)
in_high_rate = self.minutes_now >= rate_high_start and self.minutes_now <= rate_high_end
self.dashboard_item(
"binary_sensor." + self.prefix + "_high_rate_export_slot",
state="on" if in_high_rate else "off",
attributes={"friendly_name": "Predbat high rate slot", "icon": "mdi:home-lightning-bolt-outline"},
)
high_rate_minutes = (rate_high_end - self.minutes_now) if in_high_rate else (rate_high_end - rate_high_start)
self.dashboard_item(
self.prefix + ".high_rate_export_duration",
state=high_rate_minutes,
attributes={"friendly_name": "Next high export rate duration", "state_class": "measurement", "unit_of_measurement": "minutes", "icon": "mdi:table-clock"},
)
if window_n == 1:
self.dashboard_item(
self.prefix + ".high_rate_export_start_2",
state=rate_high_start_date.strftime(time_format_time),
attributes={
"date": rate_high_start_date.strftime(TIME_FORMAT),
"friendly_name": "Next+1 high export rate start",
"state_class": "timestamp",
"icon": "mdi:table-clock",
"rate": dp2(rate_high_average),
"minutes_to": rate_high_minutes_to_start,
},
)
self.dashboard_item(
self.prefix + ".high_rate_export_end_2",
state=rate_high_end_date.strftime(time_format_time),
attributes={
"date": rate_high_end_date.strftime(TIME_FORMAT),
"friendly_name": "Next+1 high export rate end",
"state_class": "timestamp",
"icon": "mdi:table-clock",
"rate": dp2(rate_high_average),
"minutes_to": rate_high_minutes_to_end,
},
)
self.dashboard_item(
self.prefix + ".high_rate_export_cost_2",
state=dp2(rate_high_average),
attributes={
"friendly_name": "Next+1 high export rate cost",
"state_class": "measurement",
"unit_of_measurement": self.currency_symbols[1],
"icon": "mdi:currency-usd",
},
)
window_n += 1
if window_str:
self.log("High export rate windows [{}]".format(window_str))
# Clear rates that aren't available
if not self.high_export_rates:
self.log("No high rate period found")
self.dashboard_item(
self.prefix + ".high_rate_export_start",
state="undefined",
attributes={
"date": None,
"friendly_name": "Next high export rate start",
"device_class": "timestamp",
"icon": "mdi:table-clock",
"minutes_to": self.forecast_minutes,
"rate": None,
},
)
self.dashboard_item(
self.prefix + ".high_rate_export_end",
state="undefined",
attributes={
"date": None,
"friendly_name": "Next high export rate end",
"device_class": "timestamp",
"icon": "mdi:table-clock",
"minutes_to": self.forecast_minutes,
"rate": None,
},
)
self.dashboard_item(
self.prefix + ".high_rate_export_cost",
state=dp2(self.rate_export_average),
attributes={
"friendly_name": "Next high export rate cost",
"state_class": "measurement",
"unit_of_measurement": self.currency_symbols[1],
"icon": "mdi:currency-usd",
},
)
self.dashboard_item(
"binary_sensor." + self.prefix + "_high_rate_export_slot",
state="off",
attributes={"friendly_name": "Predbat high export rate slot", "icon": "mdi:home-lightning-bolt-outline"},
)
self.dashboard_item(
self.prefix + ".high_rate_export_duration",
state=0,
attributes={"friendly_name": "Next high export rate duration", "state_class": "measurement", "unit_of_measurement": "minutes", "icon": "mdi:table-clock"},
)
if len(self.high_export_rates) < 2:
self.dashboard_item(
self.prefix + ".high_rate_export_start_2",
state="undefined",
attributes={
"date": None,
"friendly_name": "Next+1 high export rate start",
"device_class": "timestamp",
"icon": "mdi:table-clock",
"minutes_to": self.forecast_minutes,
"rate": None,
},
)
self.dashboard_item(
self.prefix + ".high_rate_export_end_2",
state="undefined",
attributes={
"date": None,
"friendly_name": "Next+1 high export rate end",
"device_class": "timestamp",
"icon": "mdi:table-clock",
"minutes_to": self.forecast_minutes,
"rate": None,
},
)
self.dashboard_item(
self.prefix + ".high_rate_export_cost_2",
state=dp2(self.rate_export_average),
attributes={
"friendly_name": "Next+1 high export rate cost",
"state_class": "measurement",
"unit_of_measurement": self.currency_symbols[1],
"icon": "mdi:currency-usd",
},
)
def publish_rates_import(self):
"""
Publish the import rates
"""
window_str = ""
# Output rate info
if self.low_rates:
window_n = 0
for window in self.low_rates:
rate_low_start = window["start"]
rate_low_end = window["end"]
rate_low_average = window["average"]
rate_low_minutes_to_start = max(rate_low_start - self.minutes_now, 0)
rate_low_minutes_to_end = max(rate_low_end - self.minutes_now, 0)
if window_str:
window_str += ", "
window_str += "{}: {} - {} @ {}".format(window_n, self.time_abs_str(rate_low_start), self.time_abs_str(rate_low_end), rate_low_average)
rate_low_start_date = self.midnight_utc + timedelta(minutes=rate_low_start)
rate_low_end_date = self.midnight_utc + timedelta(minutes=rate_low_end)
time_format_time = "%H:%M:%S"
if window_n == 0:
self.dashboard_item(
self.prefix + ".low_rate_start",
state=rate_low_start_date.strftime(time_format_time),
attributes={
"date": rate_low_start_date.strftime(TIME_FORMAT),
"friendly_name": "Next low rate start",
"minutes_to": rate_low_minutes_to_start,
"device_class": "timestamp",
"state_class": None,
"rate": dp2(rate_low_average),
"icon": "mdi:table-clock",
},
)
self.dashboard_item(
self.prefix + ".low_rate_end",
state=rate_low_end_date.strftime(time_format_time),
attributes={
"date": rate_low_end_date.strftime(TIME_FORMAT),
"minutes_to": rate_low_minutes_to_end,
"friendly_name": "Next low rate end",
"device_class": "timestamp",
"state_class": None,
"rate": dp2(rate_low_average),
"icon": "mdi:table-clock",
},
)
self.dashboard_item(
self.prefix + ".low_rate_cost",
state=dp2(rate_low_average),
attributes={
"friendly_name": "Next low rate cost",
"state_class": "measurement",
"unit_of_measurement": self.currency_symbols[1],
"icon": "mdi:currency-usd",
},
)
in_low_rate = self.minutes_now >= rate_low_start and self.minutes_now <= rate_low_end
self.dashboard_item(
"binary_sensor." + self.prefix + "_low_rate_slot",
state="on" if in_low_rate else "off",
attributes={"friendly_name": "Predbat low rate slot", "icon": "mdi:home-lightning-bolt-outline"},
)
low_rate_minutes = (rate_low_end - self.minutes_now) if in_low_rate else (rate_low_end - rate_low_start)
self.dashboard_item(
self.prefix + ".low_rate_duration",
state=low_rate_minutes,
attributes={"friendly_name": "Next low rate duration", "state_class": "measurement", "unit_of_measurement": "minutes", "icon": "mdi:table-clock"},
)
if window_n == 1:
self.dashboard_item(
self.prefix + ".low_rate_start_2",
state=rate_low_start_date.strftime(time_format_time),
attributes={
"date": rate_low_start_date.strftime(TIME_FORMAT),
"friendly_name": "Next+1 low rate start",
"device_class": "timestamp",
"state_class": None,
"rate": dp2(rate_low_average),
"minutes_to": rate_low_minutes_to_start,
"icon": "mdi:table-clock",
},
)
self.dashboard_item(
self.prefix + ".low_rate_end_2",
state=rate_low_end_date.strftime(time_format_time),
attributes={
"date": rate_low_end_date.strftime(TIME_FORMAT),
"friendly_name": "Next+1 low rate end",
"device_class": "timestamp",
"state_class": None,
"rate": dp2(rate_low_average),
"minutes_to": rate_low_minutes_to_end,
"icon": "mdi:table-clock",
},
)
self.dashboard_item(
self.prefix + ".low_rate_cost_2",
state=rate_low_average,
attributes={
"friendly_name": "Next+1 low rate cost",
"state_class": "measurement",
"unit_of_measurement": self.currency_symbols[1],
"icon": "mdi:currency-usd",
},
)
window_n += 1
self.log("Low import rate windows [{}]".format(window_str))
# Clear rates that aren't available
if not self.low_rates:
self.log("No low rate period found")
self.dashboard_item(
self.prefix + ".low_rate_start",
state="undefined",
attributes={
"date": None,
"friendly_name": "Next low rate start",
"device_class": "timestamp",
"state_class": None,
"minutes_to": self.forecast_minutes,
"rate": None,
"icon": "mdi:table-clock",
},
)
self.dashboard_item(
self.prefix + ".low_rate_end",
state="undefined",
attributes={
"date": None,
"friendly_name": "Next low rate end",
"device_class": "timestamp",
"state_class": None,
"minutes_to": self.forecast_minutes,
"rate": None,
"icon": "mdi:table-clock",
},
)
self.dashboard_item(
self.prefix + ".low_rate_cost",
state=self.rate_average,
attributes={"friendly_name": "Next low rate cost", "state_class": "measurement", "unit_of_measurement": self.currency_symbols[1], "icon": "mdi:currency-usd"},
)
self.dashboard_item(
self.prefix + ".low_rate_duration",
state=0,
attributes={"friendly_name": "Next low rate duration", "state_class": "measurement", "unit_of_measurement": "minutes", "icon": "mdi:table-clock"},
)
self.dashboard_item("binary_sensor." + self.prefix + "_low_rate_slot", state="off", attributes={"friendly_name": "Predbat low rate slot", "icon": "mdi:home-lightning-bolt-outline"})
if len(self.low_rates) < 2:
self.dashboard_item(
self.prefix + ".low_rate_start_2",
state="undefined",
attributes={
"date": None,
"friendly_name": "Next+1 low rate start",
"device_class": "timestamp",
"state_class": None,
"minutes_to": self.forecast_minutes,
"rate": None,
"icon": "mdi:table-clock",
},
)
self.dashboard_item(
self.prefix + ".low_rate_end_2",
state="undefined",
attributes={
"date": None,
"friendly_name": "Next+1 low rate end",
"device_class": "timestamp",
"state_class": None,
"minutes_to": self.forecast_minutes,
"rate": None,
"icon": "mdi:table-clock",
},
)
self.dashboard_item(
self.prefix + ".low_rate_cost_2",
state=self.rate_average,
attributes={"friendly_name": "Next+1 low rate cost", "state_class": "measurement", "unit_of_measurement": self.currency_symbols[1], "icon": "mdi:currency-usd"},
)
def rate_range_text(self, rate_dict, start_minute, end_minute, fallback_value):
"""
Format a rate as a single value, or a "{min}-{max}" range when the minutes from
start_minute to end_minute (a merged/rowspan plan cell) don't all share the same rate.
"""
values = set()
for minute in range(start_minute, end_minute, self.plan_interval_minutes):
values.add(dp2(rate_dict.get(minute, fallback_value)))
if not values:
return "{:.2f}".format(fallback_value)
low, high = min(values), max(values)
if low == high:
return "{:.2f}".format(low)
return "{:.2f}-{:.2f}".format(low, high)
def adjust_symbol(self, adjust_type):
"""
Returns an HTML symbol based on the adjust rate type.
Parameters:
- adjust_type (str): The type of adjustment.
Returns:
- symbol (str): The symbol corresponding to the adjust_type.
"""
symbol = ""
if adjust_type:
if adjust_type == "offset":
symbol = "? ⅆ"
elif adjust_type == "future":
symbol = "? ⚖"
elif adjust_type == "user":
symbol = "="
elif adjust_type == "manual":
symbol = "ⅎ"
elif adjust_type == "increment":
symbol = "±"
elif adjust_type == "saving":
symbol = "$"
else:
symbol = "?"
return symbol
def get_html_plan_header(self, plan_debug):
"""
Returns the header row for the HTML plan.
"""
html = ""
html += "<tr>"
html += "<th><b>Time</b></th>"
if plan_debug:
html += "<th><b>Import {} (w/loss)</b></th>".format(self.currency_symbols[1])
html += "<th><b>Export {} (w/loss)</b></th>".format(self.currency_symbols[1])
else:
html += "<th><b>Import {}</b></th>".format(self.currency_symbols[1])
html += "<th><b>Export {}</b></th>".format(self.currency_symbols[1])
html += "<th colspan=2><b>State</b></th>" # state can potentially be two cells for charging and exporting in the same slot
html += "<th><b>Limit %</b></th>"
if plan_debug:
html += "<th><b>PV kWh (10%)</b></th>"
html += "<th><b>Load kWh (10%)</b></th>"
html += "<th><b>Clip kWh</b></th>"
else:
html += "<th><b>PV kWh</b></th>"
html += "<th><b>Load kWh</b></th>"
if plan_debug and self.load_forecast:
html += "<th><b>XLoad kWh</b></th>"
if self.num_cars > 0:
html += "<th><b>Car kWh</b></th>"
if self.iboost_enable:
html += "<th><b>iBoost kWh</b></th>"
html += "<th><b>SoC %</b></th>"
html += "<th><b>Cost</b></th>"
html += "<th><b>Total</b></th>"
if self.carbon_enable:
html += "<th><b>CO2 g/kWh</b></th>"
html += "<th><b>CO2 kg</b></th>"
html += "</tr>"
return html
def band_rate_text(self, rate, export=False):
"""
Turn the rate into some text
"""
rate = dp2(rate)
if not export:
if self.rate_min == self.rate_max:
text = "fixed"
elif rate == 0:
text = "free"
elif rate < 0:
text = "negative"
else:
rate_frac = (rate - self.rate_min) / (self.rate_max - self.rate_min)
if rate_frac <= 0.33:
text = "cheap"
elif rate_frac <= 0.67:
text = "expensive"
else:
text = "very expensive"
else:
if self.rate_export_min == self.rate_export_max:
text = "fixed"
elif rate == 0:
text = "zero"
elif rate < 0:
text = "negative"
else:
rate_frac = (rate - self.rate_export_min) / (self.rate_export_max - self.rate_export_min)
if rate_frac <= 0.25:
text = "very low"
elif rate_frac <= 0.5:
text = "low"
elif rate_frac <= 0.75:
text = "good"
else:
text = "very good"
return text
def get_rate_text(self, minute, export=False, with_value=False):
"""
Get the rate text for the given minute
"""
if not export:
rate_import = dp1(self.rate_import.get(minute, 0))
band = self.band_rate_text(rate_import)
if with_value:
band += " ({}{})".format(rate_import, self.currency_symbols[1])
else:
rate_export = dp1(self.rate_export.get(minute, 0))
band = self.band_rate_text(rate_export, export=True)
if with_value:
band += " ({}{})".format(rate_export, self.currency_symbols[1])
return band
def rate_text_scan(self, export=False):
"""
Create text description for each rate band
"""
rate_array = []
end_plan = min(self.end_record, self.forecast_minutes) + self.minutes_now
rate_text = self.get_rate_text(self.minutes_now, export=export)
if export:
rate_amount = dp1(self.rate_export.get(self.minutes_now, 0))
else:
rate_amount = dp1(self.rate_import.get(self.minutes_now, 0))
rate_amount_min = rate_amount
rate_amount_max = rate_amount
start_minute = self.minutes_now
for minute in range(self.minutes_now, end_plan):
if export:
rate_amount = dp1(self.rate_export.get(minute, 0))
else:
rate_amount = dp1(self.rate_import.get(minute, 0))
rate_text_new = self.get_rate_text(minute, export=export)
if rate_text != rate_text_new:
rate_array.append({"start": start_minute, "end": minute, "rate": rate_text, "range": rate_range})
start_minute = minute
rate_text = rate_text_new
rate_amount_min = rate_amount
rate_amount_max = rate_amount
rate_amount_min = min(rate_amount_min, rate_amount)
rate_amount_max = max(rate_amount_max, rate_amount)
if rate_amount_min == rate_amount_max:
rate_range = "({}{})".format(rate_amount_min, self.currency_symbols[1])
else:
rate_range = "({}{} - {}{})".format(rate_amount_min, self.currency_symbols[1], rate_amount_max, self.currency_symbols[1])
# Add the last rate band
if minute > start_minute:
rate_array.append({"start": start_minute, "end": end_plan, "rate": rate_text, "range": rate_range})
return rate_array
def duration_string(self, minutes):
"""
Convert a number of minutes into a string
"""
text = ""
if minutes < 60:
text = "{} minutes".format(minutes)
else:
hours = int(minutes / 60)
minutes = minutes - (hours * 60)
# Round minutes to nearest 15 minutes
minutes = round(minutes / 15)
if hours >= 8:
text = "{} hours".format(hours)
elif minutes == 0:
if hours == 1:
text = "{} hour".format(hours)
else:
text = "{} hours".format(hours)
else:
minutes_text = ""
if minutes == 1:
minutes_text = "and a quarter"
elif minutes == 2:
minutes_text = "and a half"
elif minutes == 3:
minutes_text = "and three quarters"
if hours == 1 and minutes == 0:
text = "{} {}".format(hours, minutes_text)
else:
text = "{} {} hours".format(hours, minutes_text)
return text
def get_next_charge_window(self, minute_now):
# Work out when the next charge or export window is
charge_window_n = -1
for minute in range(minute_now, self.forecast_minutes + minute_now, PREDICT_STEP):
charge_window_n = self.in_charge_window(self.charge_window_best, minute)
if charge_window_n >= 0 and self.charge_limit_best[charge_window_n] == 0:
charge_window_n = -1
if charge_window_n >= 0:
break
return charge_window_n
def get_next_export_window(self, minutes_now):
# Work out when the next charge or export window is
export_window_n = -1
for minute in range(minutes_now, self.forecast_minutes + minutes_now, PREDICT_STEP):
export_window_n = self.in_charge_window(self.export_window_best, minute)
if export_window_n >= 0 and self.export_limits_best[export_window_n] == EXPORT_LIMIT_IDLE:
export_window_n = -1
if export_window_n >= 0:
break
return export_window_n
def get_charge_export_text(self, minutes_now, charge_window_n, export_window_n):
"""
Get the charge export text for the given minute
"""
if export_window_n >= 0:
target_export = self.export_window_best[export_window_n].get("target", self.export_limits_best[export_window_n])
if self.export_limits_best[export_window_n] == EXPORT_LIMIT_FREEZE:
text = "freeze exporting for the next {}".format(self.duration_string(self.export_window_best[export_window_n]["end"] - minutes_now)) # don't include target % for freeze exporting as (the 99%) is meaningless
else:
text = "force exporting to {}% for the next {}".format(target_export, self.duration_string(self.export_window_best[export_window_n]["end"] - minutes_now))
elif charge_window_n >= 0:
target_charge = calc_percent_limit(self.charge_window_best[charge_window_n].get("target", self.charge_limit_best[charge_window_n]), self.soc_max)
if self.charge_limit_best[charge_window_n] == self.reserve:
text = "freeze charging to {}% for the next {}".format(target_charge, self.duration_string(self.charge_window_best[charge_window_n]["end"] - minutes_now))
else:
text = "charging to {}% for the next {}".format(target_charge, self.duration_string(self.charge_window_best[charge_window_n]["end"] - minutes_now))
else:
charge_window_n = self.get_next_charge_window(minutes_now)
export_window_n = self.get_next_export_window(minutes_now)
next_charge_export = minutes_now + self.forecast_minutes
if charge_window_n >= 0:
next_charge_export = min(self.charge_window_best[charge_window_n]["start"], next_charge_export)
if export_window_n >= 0:
next_charge_export = min(self.export_window_best[export_window_n]["start"], next_charge_export)
if next_charge_export < minutes_now + self.forecast_minutes:
text = "in eco mode for the next {}".format(self.duration_string(next_charge_export - minutes_now))
else:
text = "in eco mode"
return text
def get_charge_type(self, charge_limit, current=False):
"""
Get the charge type for the given charge limit
"""
if self.is_freeze_charge(charge_limit):
if current:
return "freeze charging"
else:
return "charge freeze"
else:
if current:
return "charging"
else:
return "charge"
def get_export_type(self, export_limit, current=False):
"""
Get the export type for the given export limit
"""
if export_limit == EXPORT_LIMIT_FREEZE:
if current:
return "freeze exporting"
else:
return "export freeze"
else:
if current:
return "exporting"
else:
return "export"
def get_pv_forecast_slots(self, pv_forecast_minute_step):
pv_forecast_slots = []
for minute_relative in range(0, self.forecast_minutes, self.plan_interval_minutes):
minute_relative_start = minute_relative
minute_relative_slot_end = minute_relative + self.plan_interval_minutes
pv_forecast = 0.0
for offset in range(minute_relative_start, minute_relative_slot_end, PREDICT_STEP):
pv_forecast += pv_forecast_minute_step.get(offset, 0.0)
if pv_forecast <= 0.01:
text = "no solar generation"
elif pv_forecast <= 0.1:
text = "hardly any solar generation"
elif pv_forecast <= 0.2:
text = "some solar generation"
elif pv_forecast <= 0.5:
text = "a good amount of solar generation"
else:
text = "a lot of solar generation"
minute_abs_start = self.minutes_now + minute_relative_start
minute_abs_slot_end = self.minutes_now + minute_relative_slot_end
if len(pv_forecast_slots) > 0 and pv_forecast_slots[-1]["text"] == text:
pv_forecast_slots[-1]["end"] = minute_abs_slot_end
else:
pv_forecast_slots.append({"start": minute_abs_start, "end": minute_abs_slot_end, "text": text, "pv_forecast": pv_forecast})
return pv_forecast_slots
def get_text_plan_html(self, sentence):
"""
Return the Predbat plan as an html text string
"""
sentence_clean = sentence
sentence_clean = sentence_clean.replace("&", "&")
sentence_clean = sentence_clean.replace("%", "%")
sentence_clean = sentence_clean.replace("<", "<")
sentence_clean = sentence_clean.replace(">", ">")
sentence_lines = sentence_clean.split("\n")
sentence_clean = ""
for line in sentence_lines:
line = line.strip()
if line.startswith("- "):
line = line[2:]
if line:
sentence_clean += "<li>{}</li>\n".format(line)
sentence_clean = "<ul>\n" + sentence_clean + "</ul>\n"
return sentence_clean
def short_textual_plan(self, soc_min, soc_min_minute, pv_forecast_minute_step, pv_forecast_minute_step10, load_minutes_step, load_minutes_step10, end_record, publish=True):
"""
The short textual plan gives a summary in text format of the current plan
"""
sentence = ""
pv_forecast_slots = self.get_pv_forecast_slots(pv_forecast_minute_step)
# Step 1 find out the textual name of all the rates in the next 24 hours and put them into buckets
rate_bucket_import = self.rate_text_scan(export=False)
rate_bucket_export = self.rate_text_scan(export=True)
self.log("Rate array import {} export {}".format(rate_bucket_import, rate_bucket_export))
rate_import_str = rate_bucket_import[0]["rate"]
rate_import_duration = rate_bucket_import[0]["end"] - rate_bucket_import[0]["start"]
rate_export_str = rate_bucket_export[0]["rate"]
rate_export_duration = rate_bucket_export[0]["end"] - rate_bucket_export[0]["start"]
midnight_today_minute = 24 * 60 - self.minutes_now
midnight_tomorrow_minute = 24 * 60 + midnight_today_minute
metric_midnight_today = self.predict_metric_best.get(midnight_today_minute, 0.0)
metric_midnight_tomorrow = self.predict_metric_best.get(midnight_tomorrow_minute, None)
if metric_midnight_tomorrow is not None:
metric_midnight_tomorrow -= metric_midnight_today
if metric_midnight_tomorrow is None:
sentence += "- Your estimated bill for today is {}{:.2f}\n".format(self.currency_symbols[0], dp2(metric_midnight_today / 100))
else:
sentence += "- Your estimated bill for today is {}{:.2f} and tomorrow is {}{:.2f}\n".format(
self.currency_symbols[0],
dp2(metric_midnight_today / 100),
self.currency_symbols[0],
dp2(metric_midnight_tomorrow / 100),
)
if rate_import_str != "fixed":
sentence += "- Import rates are {} {} for the next {}".format(rate_import_str, rate_bucket_import[0]["range"], self.duration_string(rate_import_duration))
if len(rate_bucket_import) > 1:
sentence += " and then {} {} for the next {}".format(rate_bucket_import[1]["rate"], rate_bucket_import[1]["range"], self.duration_string(rate_bucket_import[1]["end"] - rate_bucket_import[1]["start"]))
sentence += ".\n"
if rate_export_str != "fixed":
sentence += "- Export rates are {} {} for the next {}".format(rate_export_str, rate_bucket_export[0]["range"], self.duration_string(rate_export_duration))
if len(rate_bucket_export) > 1:
sentence += " and then {} {} for the next {}".format(rate_bucket_export[1]["rate"], rate_bucket_export[1]["range"], self.duration_string(rate_bucket_export[1]["end"] - rate_bucket_export[1]["start"]))
sentence += ".\n"
# Step 2 - find the current state of charge
soc_percent = calc_percent_limit(self.predict_soc_best.get(0, 0.0), self.soc_max)
# Find if the battery is charging, discharging or force exporting
charge_window_n = self.in_charge_window(self.charge_window_best, self.minutes_now)
if charge_window_n >= 0 and self.charge_limit_best[charge_window_n] == 0:
charge_window_n = -1
export_window_n = self.in_charge_window(self.export_window_best, self.minutes_now)
if export_window_n >= 0 and self.export_limits_best[export_window_n] == EXPORT_LIMIT_IDLE:
export_window_n = -1
charge_export_text = self.get_charge_export_text(self.minutes_now, charge_window_n, export_window_n)
sentence += "- The battery is currently at {}% and is {}.\n".format(soc_percent, charge_export_text)
# Solar
solar_ramp = ""
if len(pv_forecast_slots) > 1:
if pv_forecast_slots[1]["pv_forecast"] > pv_forecast_slots[0]["pv_forecast"]:
solar_ramp = " and then it will increase"
elif pv_forecast_slots[1]["pv_forecast"] < pv_forecast_slots[0]["pv_forecast"]:
solar_ramp = " and then it will decrease"
else:
solar_ramp = " and then remaining stable"
sentence += "- For the next {} there will be {}{}.\n".format(self.duration_string(pv_forecast_slots[0]["end"] - pv_forecast_slots[0]["start"]), pv_forecast_slots[0]["text"], solar_ramp)
# Battery
soc_min_percent = calc_percent_limit(soc_min, self.soc_max)
if soc_min_minute < self.forecast_minutes + self.minutes_now:
if soc_min_percent <= self.reserve_percent:
if soc_min_minute <= self.minutes_now:
# We know we ran out as it says the percentage above anyhow
pass
else:
if self.in_charge_window(self.charge_window_best, soc_min_minute) >= 0 or self.in_charge_window(self.charge_window_best, soc_min_minute + 10) >= 0:
sentence += "- You have enough battery to reach the next charge.\n"
else:
sentence += "- You will run out of battery in {}.\n".format(self.duration_string(soc_min_minute - self.minutes_now))
else:
sentence += "- You will reach a minimum of {}% battery in {}.\n".format(soc_min_percent, self.duration_string(soc_min_minute - self.minutes_now))
car_charging_kwh = self.car_charge_slot_kwh(self.minutes_now, self.minutes_now + 5)
if car_charging_kwh > 0:
sentence += "- Your car is currently charging.\n"
charge_window_n_next = self.get_next_charge_window(self.minutes_now)
export_window_n_next = self.get_next_export_window(self.minutes_now)
if charge_window_n < 0 and charge_window_n_next >= 0:
charge_type = self.get_charge_type(self.charge_limit_best[charge_window_n_next])
car_charging_kwh = self.car_charge_slot_kwh(self.charge_window_best[charge_window_n_next]["start"], self.charge_window_best[charge_window_n_next]["end"])
sentence += "- Your next {} slot will be in {} where import rates will be {}".format(
charge_type, self.duration_string(self.charge_window_best[charge_window_n_next]["start"] - self.minutes_now), self.get_rate_text(self.charge_window_best[charge_window_n_next]["start"], export=False, with_value=True)
)
if car_charging_kwh > 0:
sentence += " and your car will be charged with {} kWh.\n".format(car_charging_kwh)
else:
sentence += ".\n"
elif charge_window_n < 0:
sentence += "- No charging is planned.\n"
if export_window_n < 0 and export_window_n_next >= 0:
export_type = self.get_export_type(self.export_limits_best[export_window_n_next])
sentence += "- Your next {} slot will be in {} where export rates will be {}.\n".format(
export_type, self.duration_string(self.export_window_best[export_window_n_next]["start"] - self.minutes_now), self.get_rate_text(self.export_window_best[export_window_n_next]["start"], export=True, with_value=True)
)
if publish:
self.text_plan = self.get_text_plan_html(sentence)
return sentence