-
Notifications
You must be signed in to change notification settings - Fork 0
/
wattwise.py
1775 lines (1542 loc) · 71.8 KB
/
wattwise.py
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
# This file is part of WattWise.
# Origin: https://github.com/bullitt186/ha-wattwise
# Author: Bastian Stahmer
#
# WattWise is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WattWise is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
import json
import os
from datetime import timedelta
import appdaemon.plugins.hass.hassapi as hass
import numpy as np
import pulp
import tzlocal
class WattWise(hass.Hass):
"""
WattWise is an AppDaemon application for Home Assistant that optimizes battery usage
based on consumption forecasts, solar production forecasts, and energy price forecasts.
It schedules charging and discharging actions to minimize energy costs and maximize
battery efficiency.
"""
def initialize(self):
"""
Initializes the WattWise AppDaemon application.
This method sets up the initial configuration, schedules the hourly optimization
process, and listens for manual optimization triggers. It fetches initial states
of charger and discharger switches to track current charging and discharging statuses.
"""
# Get user-specific settings from app configuration
self.BATTERY_CAPACITY = float(self.args.get("battery_capacity", 11.2)) # kWh
self.BATTERY_EFFICIENCY = float(self.args.get("battery_efficiency", 0.9))
self.CHARGE_RATE_MAX = float(self.args.get("charge_rate_max", 6)) # kW
self.DISCHARGE_RATE_MAX = float(self.args.get("discharge_rate_max", 6)) # kW
self.TIME_HORIZON = int(self.args.get("time_horizon", 48)) # hours
self.FEED_IN_TARIFF = float(self.args.get("feed_in_tariff", 7)) # ct/kWh
self.CONSUMPTION_HISTORY_DAYS = int(
self.args.get("consumption_history_days", 7)
) # days
self.LOWER_BATTERY_LIMIT = float(
self.args.get("lower_battery_limit", 1.0)
) # kWh
# Get Home Assistant Entity IDs from app configuration
self.CONSUMPTION_SENSOR = self.args.get(
"consumption_sensor", "sensor.s10x_house_consumption"
)
self.SOLAR_FORECAST_SENSOR_TODAY = self.args.get(
"solar_forecast_sensor_today", "sensor.solcast_pv_forecast_prognose_heute"
)
self.SOLAR_FORECAST_SENSOR_TOMORROW = self.args.get(
"solar_forecast_sensor_tomorrow",
"sensor.solcast_pv_forecast_prognose_morgen",
)
self.BATTERY_SOC_SENSOR = self.args.get(
"battery_soc_sensor", "sensor.s10x_state_of_charge"
)
# Constants for Switches - No need to touch.
self.BATTERY_CHARGING_SWITCH = (
"input_boolean.wattwise_battery_charging_from_grid"
)
self.BATTERY_DISCHARGING_SWITCH = (
"input_boolean.wattwise_battery_discharging_enabled"
)
# Constants for State Tracking Binary Sensors - No need to touch.
self.BINARY_SENSOR_CHARGING = (
"binary_sensor.wattwise_battery_charging_from_grid"
)
self.BINARY_SENSOR_DISCHARGING = (
"binary_sensor.wattwise_battery_discharging_enabled"
)
# Constants for Forecast Sensors - No need to touch.
self.SENSOR_CHARGE_SOLAR = "sensor.wattwise_battery_charge_from_solar" # kW
self.SENSOR_CHARGE_GRID = "sensor.wattwise_battery_charge_from_grid" # kW
self.SENSOR_CHARGE_GRID_SESSION = (
"sensor.wattwise_battery_charge_grid_session" # kW
)
self.SENSOR_DISCHARGE = "sensor.wattwise_battery_discharge" # kW
self.SENSOR_GRID_EXPORT = "sensor.wattwise_grid_export" # kW
self.SENSOR_GRID_IMPORT = "sensor.wattwise_grid_import" # kW
self.SENSOR_SOC = "sensor.wattwise_state_of_charge" # kWh
self.SENSOR_SOC_PERCENTAGE = "sensor.wattwise_state_of_charge_percentage" # %
self.SENSOR_CONSUMPTION_FORECAST = "sensor.wattwise_consumption_forecast" # kW
self.SENSOR_SOLAR_PRODUCTION_FORECAST = (
"sensor.wattwise_solar_production_forecast" # kW
)
self.BINARY_SENSOR_FULL_CHARGE_STATUS = (
"binary_sensor.wattwise_battery_full_charge_status" # Binary (0/1)
)
self.SENSOR_MAX_POSSIBLE_DISCHARGE = (
"sensor.wattwise_maximum_discharge_possible" # kW
)
self.PRICE_FORECAST_SENSOR = "sensor.wattwise_tibber_prices"
self.SENSOR_FORECAST_HORIZON = "sensor.wattwise_forecast_horizon" # hours
self.SENSOR_HISTORY_HORIZON = "sensor.wattwise_history_horizon" # hours
# Cheap window binary sensors
self.BINARY_SENSOR_WITHIN_CHEAPEST_1_HOUR = (
"binary_sensor.wattwise_within_cheapest_hour" # hours
)
self.BINARY_SENSOR_WITHIN_CHEAPEST_2_HOURS = (
"binary_sensor.wattwise_within_cheapest_2_hours" # hours
)
self.BINARY_SENSOR_WITHIN_CHEAPEST_3_HOURS = (
"binary_sensor.wattwise_within_cheapest_3_hours" # hours
)
self.BINARY_SENSOR_WITHIN_CHEAPEST_4_HOURS = (
"binary_sensor.wattwise_within_cheapest_4_hours" # hours
)
self.BINARY_SENSOR_WITHIN_CHEAPEST_5_HOURS = (
"binary_sensor.wattwise_within_cheapest_5_hours" # hours
)
self.BINARY_SENSOR_WITHIN_CHEAPEST_6_HOURS = (
"binary_sensor.wattwise_within_cheapest_6_hours" # hours
)
self.BINARY_SENSOR_WITHIN_CHEAPEST_7_HOURS = (
"binary_sensor.wattwise_within_cheapest_7_hours" # hours
)
self.BINARY_SENSOR_WITHIN_CHEAPEST_8_HOURS = (
"binary_sensor.wattwise_within_cheapest_8_hours" # hours
)
# Expensive window binary sensors
self.BINARY_SENSOR_WITHIN_MOST_EXPENSIVE_1_HOUR = (
"binary_sensor.wattwise_within_most_expensive_hour" # hours
)
self.BINARY_SENSOR_WITHIN_MOST_EXPENSIVE_2_HOURS = (
"binary_sensor.wattwise_within_most_expensive_2_hours" # hours
)
self.BINARY_SENSOR_WITHIN_MOST_EXPENSIVE_3_HOURS = (
"binary_sensor.wattwise_within_most_expensive_3_hours" # hours
)
self.BINARY_SENSOR_WITHIN_MOST_EXPENSIVE_4_HOURS = (
"binary_sensor.wattwise_within_most_expensive_4_hours" # hours
)
self.BINARY_SENSOR_WITHIN_MOST_EXPENSIVE_5_HOURS = (
"binary_sensor.wattwise_within_most_expensive_5_hours" # hours
)
self.BINARY_SENSOR_WITHIN_MOST_EXPENSIVE_6_HOURS = (
"binary_sensor.wattwise_within_most_expensive_6_hours" # hours
)
self.BINARY_SENSOR_WITHIN_MOST_EXPENSIVE_7_HOURS = (
"binary_sensor.wattwise_within_most_expensive_7_hours" # hours
)
self.BINARY_SENSOR_WITHIN_MOST_EXPENSIVE_8_HOURS = (
"binary_sensor.wattwise_within_most_expensive_8_hours" # hours
)
# maximum price threshold to exclude excessively high prices in the cheap price windows
self.MAX_PRICE_THRESH_CT = float(
self.args.get("max_price_threshold_ct", 80)
) # ct/kWh
# Usable Time Horizon
self.T = self.TIME_HORIZON
# Get Home Assistant URL and token from app args
self.ha_url = self.args.get("ha_url")
self.token = self.args.get("token")
if not self.ha_url or not self.token:
self.error(
"Home Assistant URL and token must be provided in app configuration."
)
return
# Initialize state tracking variables
self.charging_from_grid = False
self.discharging_to_house = False
# Initialize forecast and optimization storage
self.consumption_forecast = []
self.solar_forecast = []
self.price_forecast = []
self.charging_schedule = []
self.max_discharge_possible = []
self.within_cheapest_1_hour = []
self.within_cheapest_2_hours = []
self.within_cheapest_3_hours = []
self.within_most_expensive_1_hour = []
self.within_most_expensive_2_hours = []
self.within_most_expensive_3_hours = []
# Path to store consumption history
self.CONSUMPTION_HISTORY_FILE = "/config/apps/wattwise_consumption_history.json"
self.CHEAP_WINDOWS_FILE = "/config/apps/wattwise_cheap_windows.json"
self.EXPENSIVE_WINDOWS_FILE = "/config/apps/wattwise_expensive_windows.json"
# Fetch and set initial states from Home Assistant
self.set_initial_states()
# Schedule the optimization to run hourly at the top of the hour
now = get_now_time()
next_run = now.replace(minute=0, second=0, microsecond=0)
if now >= next_run:
next_run += datetime.timedelta(hours=1)
self.run_hourly(self.optimize, next_run)
self.log(f"Scheduled hourly optimization starting at {next_run}.")
# Listen for a custom event to trigger optimization manually
self.listen_event(self.manual_trigger, event="MANUAL_BATTERY_OPTIMIZATION")
self.log(
"Listening for manual optimization trigger event 'MANUAL_BATTERY_OPTIMIZATION'."
)
# Run the optimization process 30 seconds after startup
self.run_in(self.optimize, 5)
self.log("Scheduled optimization to run 30 seconds after startup.")
def set_initial_states(self):
"""
Fetches and sets the initial states of the charger and discharger switches.
This method retrieves the current state of the battery charger and discharger
switches from Home Assistant and initializes the tracking variables
`charging_from_grid` and `discharging_to_house` accordingly.
"""
charger_state = self.get_state(self.BATTERY_CHARGING_SWITCH)
discharger_state = self.get_state(self.BATTERY_DISCHARGING_SWITCH)
if charger_state is not None:
self.charging_from_grid = charger_state.lower() == "on"
self.log(f"Initial charging_from_grid state: {self.charging_from_grid}")
if discharger_state is not None:
self.discharging_to_house = discharger_state.lower() == "on"
self.log(f"Initial discharging_to_house state: {self.discharging_to_house}")
def manual_trigger(self, event_name, data, kwargs):
"""
Handles manual optimization triggers.
This method is called when the custom event `MANUAL_BATTERY_OPTIMIZATION` is fired.
It initiates the battery optimization process.
Args:
event_name (str): The name of the event.
data (dict): The event data.
kwargs (dict): Additional keyword arguments.
"""
self.log("Manual optimization trigger received.")
self.optimize({})
def optimize(self, kwargs):
"""
Starts the optimization process by fetching forecasts.
Args:
kwargs (dict): Additional keyword arguments.
"""
self.log("############ Start Optimization ############")
# Start fetching forecasts
self.T = self.TIME_HORIZON # Reset T before each run.
self.get_consumption_forecast()
self.get_solar_production_forecast()
self.get_energy_price_forecast()
self.optimize_battery()
# Compute the maximum possible discharge per hour
self.calculate_max_discharge_possible()
# identify cheapest and most expensive hours based on grid tariffs
self.identify_cheapest_hours()
self.identify_most_expensive_hours()
# Update forecast sensors
self.update_forecast_sensors()
# Schedule actions based on the optimized schedule
# self.schedule_actions(self.charging_schedule)
# self.log("Charging and discharging actions scheduled.")
self.log("############ End Optimization ############")
return
def get_consumption_forecast(self):
"""
Retrieves the consumption forecast for the next T hours.
This method loads historical consumption data from a file, fetches any new data
from Home Assistant, updates the history, and calculates the average consumption
per hour over the past seven days.
"""
self.log("Retrieving consumption forecast.")
self.consumption_forecast = []
# Load existing history
history_data = self.load_consumption_history()
# Determine the time window
now = get_now_time()
history_days_ago = now - datetime.timedelta(days=self.CONSUMPTION_HISTORY_DAYS)
# Remove data older than 7 days
history_data = [
entry
for entry in history_data
if datetime.datetime.fromisoformat(entry["last_changed"])
>= history_days_ago
]
# Determine the last timestamp in history
if history_data:
last_timestamp = max(
datetime.datetime.fromisoformat(entry["last_changed"])
for entry in history_data
)
else:
last_timestamp = history_days_ago
# Fetch new data from last timestamp to now
new_data = self.get_history_data(self.CONSUMPTION_SENSOR, last_timestamp, now)
# Append new data to history
history_data.extend(new_data)
# Save updated history
self.save_consumption_history(history_data)
# Calculate average consumption per hour
hourly_consumption = {hour: [] for hour in range(24)}
for state in history_data:
timestamp_str = state.get("last_changed") or state.get("last_updated")
if timestamp_str is None:
continue
timestamp = datetime.datetime.fromisoformat(timestamp_str)
timestamp = timestamp.astimezone(
tzlocal.get_localzone()
) # Convert to local time
hour = timestamp.hour
value_str = state.get("state", 0)
if is_float(value_str):
value = float(value_str)
hourly_consumption[hour].append(value)
# Compute average consumption for each hour
average_consumption = []
for t in range(self.T):
hour = (now + datetime.timedelta(hours=t)).hour
values = hourly_consumption.get(hour, [])
if values:
avg_consumption = sum(values) / len(values)
else:
avg_consumption = 0 # Default if no data
average_consumption.append(avg_consumption)
self.log("Consumption forecast retrieved.")
# Store the forecast for use in optimization
self.consumption_forecast = average_consumption
def load_consumption_history(self):
"""
Loads the consumption history from a file.
Returns:
list: List of historical consumption data.
"""
if os.path.exists(self.CONSUMPTION_HISTORY_FILE):
try:
with open(self.CONSUMPTION_HISTORY_FILE, "r") as f:
filepath = os.path.abspath(self.CONSUMPTION_HISTORY_FILE)
history_data = json.load(f)
self.log(f"Loaded existing consumption history. Path: {filepath}")
except Exception as e:
self.error(f"Error loading consumption history: {e}")
history_data = []
else:
self.log("No existing consumption history found. Starting fresh.")
history_data = []
return history_data
def save_consumption_history(self, history_data):
"""
Saves the consumption history to a file.
Args:
history_data (list): List of historical consumption data.
"""
try:
with open(self.CONSUMPTION_HISTORY_FILE, "w") as f:
json.dump(history_data, f)
filepath = os.path.abspath(self.CONSUMPTION_HISTORY_FILE)
self.log(f"Consumption history saved. Path: {filepath}")
except Exception as e:
self.error(f"Error saving consumption history: {e}")
def get_history_data(self, entity_id, start_time, end_time):
"""
Retrieves historical state changes for a given entity in one-hour intervals within the specified time range.
Args:
entity_id (str): The entity ID for which to retrieve history.
start_time (datetime.datetime): The start time for the history retrieval.
end_time (datetime.datetime): The end time for the history retrieval.
Returns:
list of dict: A list of state change dictionaries for the entity.
"""
history_data = []
current_time = start_time
while current_time < end_time:
next_hour = current_time + datetime.timedelta(hours=1)
# Ensure we do not go past the end_time
if next_hour > end_time:
next_hour = end_time
# Convert current_time and next_hour to naive datetimes
current_time_naive = current_time.replace(tzinfo=None)
next_hour_naive = next_hour.replace(tzinfo=None)
try:
# Fetch history for the one-hour interval
hourly_data = self.get_history(
entity_id=entity_id,
start_time=current_time_naive,
end_time=next_hour_naive,
include_start_time_state=True,
)
if hourly_data:
history_data.extend(hourly_data[0])
except Exception as e:
self.error(
f"Error fetching history for {entity_id} from {current_time_naive} to {next_hour_naive}: {e}"
)
# Move to the next hour
current_time = next_hour
return history_data
def get_solar_production_forecast(self):
"""
Retrieves the solar production forecast for the next T hours.
This method fetches the solar production forecast data from today's and
tomorrow's forecast sensors in Home Assistant. It combines the data and
maps it to the next T hours, adjusting for any forecast errors.
"""
self.log("Retrieving solar production forecast.")
# Retrieve solar production forecast from Home Assistant entities
forecast_data_today = self.get_state(
self.SOLAR_FORECAST_SENSOR_TODAY, attribute="detailedHourly"
)
forecast_data_tomorrow = self.get_state(
self.SOLAR_FORECAST_SENSOR_TOMORROW, attribute="detailedHourly"
)
if not forecast_data_today:
self.error("Solar production forecast data for today is unavailable.")
return
if not forecast_data_tomorrow:
forecast_data_tomorrow = []
self.log(
"Solar production forecast data for tomorrow is not available yet."
)
# Combine today's and tomorrow's data
combined_forecast_data = forecast_data_today + forecast_data_tomorrow
self.solar_forecast = []
now = get_now_time()
for t in range(self.T):
forecast_time = now + datetime.timedelta(hours=t)
forecast_time = forecast_time.astimezone()
value = None
for entry in combined_forecast_data:
entry_time = datetime.datetime.fromisoformat(entry["period_start"])
entry_time = entry_time.astimezone()
if (
entry_time.hour == forecast_time.hour
and entry_time.date() == forecast_time.date()
):
value = entry["pv_estimate"]
break
if value is None:
self.log(f"Solar production forecast for hour {t} not found.")
if self.T > t:
self.T = t
self.log(f"Setting time horizon to {self.T} hours.")
break
self.solar_forecast.append(value)
self.log(f"Solar production forecast retrieved: {self.solar_forecast}")
return
def get_energy_price_forecast(self):
"""
Retrieves the energy price forecast for the next T hours.
This method fetches the energy price forecast data from Home Assistant's
price forecast sensor. It combines today's and tomorrow's data and maps
it to the next T hours, converting prices from EUR/kWh to ct/kWh.
"""
self.log("Retrieving energy price forecast.")
self.price_forecast = []
# Retrieve energy price forecast from Home Assistant entity
price_data_today = self.get_state(self.PRICE_FORECAST_SENSOR, attribute="today")
price_data_tomorrow = self.get_state(
self.PRICE_FORECAST_SENSOR, attribute="tomorrow"
)
if not price_data_today:
self.error("Energy price forecast data for today is unavailable.")
return
now = get_now_time()
current_hour = now.hour
# Combine today's and tomorrow's data
combined_price_data = price_data_today
if price_data_tomorrow:
combined_price_data += price_data_tomorrow
self.log(
"Tomorrow's energy price data is available and included in the forecast."
)
else:
self.log("Tomorrow's energy price data is not available yet.")
# Create the price forecast for the next T hours
price_forecast = []
for t in range(self.T):
index = current_hour + t
if index < len(combined_price_data):
price_entry = combined_price_data[index]
price = price_entry["total"] * 100 # Convert EUR/kWh to ct/kWh
price_forecast.append(price)
else:
# If we run out of data, use the last known price
price = combined_price_data[-1]["total"] * 100
self.log(
f"Price data for hour {index} not found. Using last known price."
)
if self.T > t:
self.T = t
self.log(f"Setting time horizon to {self.T} hours.")
break
self.log(f"Energy price forecast retrieved: {price_forecast}")
self.price_forecast = price_forecast
return
def optimize_battery(self):
"""
Executes the battery optimization process.
This method retrieves the current state of charge, formulates and solves
an optimization problem to determine the optimal charging and discharging
schedule, updates forecast sensors, and schedules charging/discharging actions.
Returns:
None
"""
self.log("Starting battery optimization process.")
self.charging_schedule = []
# Get initial State of Charge (SoC) in percentage
SoC_percentage_str = self.get_state(self.BATTERY_SOC_SENSOR)
if SoC_percentage_str is None:
self.error(
f"Could not retrieve state of {self.BATTERY_SOC_SENSOR}. Aborting optimization."
)
return
# Convert SoC from percentage to kWh
SoC_percentage = float(SoC_percentage_str)
SoC_0 = (SoC_percentage / 100) * self.BATTERY_CAPACITY
self.log(
f"Initial SoC: {SoC_0:.2f} kWh ({SoC_percentage}% of {self.BATTERY_CAPACITY} kWh)"
)
# Use stored forecasts
C_t = self.consumption_forecast
S_t = self.solar_forecast
P_t = self.price_forecast
# Log the forecasts per hour for debugging
self.log("Forecasts per hour:")
now = get_now_time()
for t in range(self.T):
forecast_time = now + datetime.timedelta(hours=t)
hour = forecast_time.hour
self.log(
f"Hour {hour:02d}: "
f"Consumption = {C_t[t]:.2f} kW, "
f"Solar = {S_t[t]:.2f} kW, "
f"Price = {P_t[t]:.2f} ct/kWh"
)
# Initialize the optimization problem
prob = pulp.LpProblem("Battery_Optimization", pulp.LpMinimize)
self.log("Optimization problem initialized.")
# Decision variables
G = pulp.LpVariable.dicts("Grid_Import", (t for t in range(self.T)), lowBound=0)
Ch_solar = pulp.LpVariable.dicts(
"Battery_Charge_Solar", (t for t in range(self.T)), lowBound=0
)
Ch_grid = pulp.LpVariable.dicts(
"Battery_Charge_Grid", (t for t in range(self.T)), lowBound=0
)
Dch = pulp.LpVariable.dicts(
"Battery_Discharge", (t for t in range(self.T)), lowBound=0
)
SoC = pulp.LpVariable.dicts(
"SoC",
(t for t in range(self.T + 1)),
lowBound=0,
upBound=self.BATTERY_CAPACITY,
)
E = pulp.LpVariable.dicts("Grid_Export", (t for t in range(self.T)), lowBound=0)
Surplus_solar = pulp.LpVariable.dicts(
"Surplus_Solar", (t for t in range(self.T)), lowBound=0
)
FullCharge = pulp.LpVariable.dicts(
"FullCharge", (t for t in range(self.T)), cat="Binary"
) # Binary variables
self.log("Decision variables created.")
# Objective function: Minimize the total cost of grid imports and grid charging, minus value of final SoC.
# Financial value of final SoC is calculated by using the minimum forecasted price, in order to not
# over-value the residual energy and by that reward saving energy in the battery too much.
P_end = np.min(P_t)
prob += (
pulp.lpSum(
[P_t[t] * G[t] - self.FEED_IN_TARIFF * E[t] for t in range(self.T)]
)
- P_end * SoC[self.T]
)
self.log(
"Objective function set to minimize total cost minus value of final SoC."
)
# Initial SoC
prob += SoC[0] == SoC_0
self.log("Initial SoC constraint added.")
M = self.BATTERY_CAPACITY * 2 # Big M value
for t in range(self.T):
# Energy balance with corrected battery efficiency
prob += (
(
S_t[t] + G[t] + Dch[t] * self.BATTERY_EFFICIENCY
== C_t[t] + Ch_solar[t] + Ch_grid[t] + E[t]
),
f"Energy_Balance_{t}",
)
# SoC update with corrected battery efficiency
prob += (
SoC[t + 1]
== SoC[t]
+ (Ch_solar[t] + Ch_grid[t]) * self.BATTERY_EFFICIENCY
- Dch[t],
f"SoC_Update_{t}",
)
# Battery capacity constraints
prob += SoC[t + 1] >= self.LOWER_BATTERY_LIMIT, f"SoC_Min_{t}"
prob += SoC[t + 1] <= self.BATTERY_CAPACITY, f"SoC_Max_{t}"
# Charging limits
prob += (
Ch_solar[t] + Ch_grid[t] <= self.CHARGE_RATE_MAX,
f"Charge_Rate_Limit_{t}",
)
prob += Ch_solar[t] <= S_t[t], f"Charge_Solar_Limit_Actual_Solar_{t}"
# Discharging limits
prob += Dch[t] <= self.DISCHARGE_RATE_MAX, f"Discharge_Rate_Limit_{t}"
# Surplus solar constraints
prob += Surplus_solar[t] >= S_t[t] - C_t[t], f"Surplus_Solar_Definition_{t}"
prob += Surplus_solar[t] >= 0, f"Surplus_Solar_NonNegative_{t}"
prob += Ch_solar[t] <= Surplus_solar[t], f"Solar_Charging_Limit_{t}"
# Charging from grid cannot exceed grid import
prob += Ch_grid[t] <= G[t], f"Grid_Charging_Limit_{t}"
# Grid export is non-negative
prob += E[t] >= 0, f"Grid_Export_NonNegative_{t}"
# Linking FullCharge[t] with SoC[t+1]
prob += (
SoC[t + 1] >= self.BATTERY_CAPACITY - (1 - FullCharge[t]) * M,
f"SoC_FullCharge_Link_{t}",
)
# Enforcing E[t] based on FullCharge[t]
prob += E[t] <= FullCharge[t] * M, f"Export_Only_When_Full_{t}"
self.log("Constraints added to the optimization problem.")
# Solve the problem using a solver that supports MILP
self.log("Starting the solver.")
solver = pulp.GLPK_CMD(msg=1)
prob.solve(solver)
self.log(f"Solver status: {pulp.LpStatus[prob.status]}")
# Check if an optimal solution was found
if pulp.LpStatus[prob.status] != "Optimal":
self.error("No optimal solution found for battery optimization.")
return
# Extract the optimized charging schedule
now = get_now_time()
for t in range(self.T):
charge_solar = Ch_solar[t].varValue
charge_grid = Ch_grid[t].varValue
discharge = Dch[t].varValue
export = E[t].varValue # Grid export
grid_import = G[t].varValue # Grid import
soc = SoC[t].varValue
consumption = C_t[t] # House consumption from forecast
solar = S_t[t] # Solar production from forecast
full_charge = FullCharge[t].varValue # FullCharge status
forecast_time = now + datetime.timedelta(hours=t)
hour = forecast_time.hour
self.log(
f"Optimized Schedule - Hour {hour:02d}: "
f"Consumption = {consumption:.2f} kW, "
f"Solar = {solar:.2f} kW, "
f"Grid Import = {grid_import:.2f} kW, "
f"Charge from Solar = {charge_solar:.2f} kW, "
f"Charge from Grid = {charge_grid:.2f} kW, "
f"Discharge = {discharge:.2f} kW, "
f"Export to Grid = {export:.2f} kW, "
f"SoC = {soc:.2f} kWh, "
f"Battery Full = {int(full_charge)}"
)
self.charging_schedule.append(
{
"time": forecast_time,
"charge_solar": charge_solar,
"charge_grid": charge_grid,
"discharge": discharge,
"export": export,
"grid_import": grid_import,
"consumption": consumption,
"soc": soc,
"full_charge": full_charge,
}
)
return
def identify_cheapest_hours(self):
# Determine the forecast date (assuming price forecasts are for the next day)
now = get_now_time()
forecast_date = now.date()
self.log(f"Forecast date determined as {forecast_date}.")
# Load existing window assignments
cheap_windows_data = self.load_cheap_windows()
cheapest_hours_1 = []
cheapest_hours_2 = []
cheapest_hours_3 = []
cheapest_hours_4 = []
cheapest_hours_5 = []
cheapest_hours_6 = []
cheapest_hours_7 = []
cheapest_hours_8 = []
cheapest_dates_1 = []
cheapest_dates_2 = []
cheapest_dates_3 = []
cheapest_dates_4 = []
cheapest_dates_5 = []
cheapest_dates_6 = []
cheapest_dates_7 = []
cheapest_dates_8 = []
# Check if window assignments are already set for the current forecast date
if (cheap_windows_data.get("forecast_date") != forecast_date.isoformat()) and (
now.hour > 13
):
# New forecast period, find and save new windows
cheapest_hours_1 = self.find_cheapest_windows(self.price_forecast, 1)
cheapest_hours_2 = self.find_cheapest_windows(self.price_forecast, 2)
cheapest_hours_3 = self.find_cheapest_windows(self.price_forecast, 3)
cheapest_hours_4 = self.find_cheapest_windows(self.price_forecast, 4)
cheapest_hours_5 = self.find_cheapest_windows(self.price_forecast, 5)
cheapest_hours_6 = self.find_cheapest_windows(self.price_forecast, 6)
cheapest_hours_7 = self.find_cheapest_windows(self.price_forecast, 7)
cheapest_hours_8 = self.find_cheapest_windows(self.price_forecast, 8)
cheapest_dates_1 = [
relativeHourToDate(hour).isoformat() for hour in cheapest_hours_1
]
cheapest_dates_2 = [
relativeHourToDate(hour).isoformat() for hour in cheapest_hours_2
]
cheapest_dates_3 = [
relativeHourToDate(hour).isoformat() for hour in cheapest_hours_3
]
cheapest_dates_4 = [
relativeHourToDate(hour).isoformat() for hour in cheapest_hours_4
]
cheapest_dates_5 = [
relativeHourToDate(hour).isoformat() for hour in cheapest_hours_5
]
cheapest_dates_6 = [
relativeHourToDate(hour).isoformat() for hour in cheapest_hours_6
]
cheapest_dates_7 = [
relativeHourToDate(hour).isoformat() for hour in cheapest_hours_7
]
cheapest_dates_8 = [
relativeHourToDate(hour).isoformat() for hour in cheapest_hours_8
]
# Save windows
windows = {
"cheapest_dates_1": cheapest_dates_1,
"cheapest_dates_2": cheapest_dates_2,
"cheapest_dates_3": cheapest_dates_3,
"cheapest_dates_4": cheapest_dates_4,
"cheapest_dates_5": cheapest_dates_5,
"cheapest_dates_6": cheapest_dates_6,
"cheapest_dates_7": cheapest_dates_7,
"cheapest_dates_8": cheapest_dates_8,
}
self.save_cheap_windows(forecast_date, windows)
self.log(f"New cheap windows found for {forecast_date}: {windows}")
else:
# Use existing windows
windows = cheap_windows_data.get("windows", {})
cheapest_dates_1 = windows.get("cheapest_dates_1", [])
cheapest_dates_2 = windows.get("cheapest_dates_2", [])
cheapest_dates_3 = windows.get("cheapest_dates_3", [])
cheapest_dates_4 = windows.get("cheapest_dates_4", [])
cheapest_dates_5 = windows.get("cheapest_dates_5", [])
cheapest_dates_6 = windows.get("cheapest_dates_6", [])
cheapest_dates_7 = windows.get("cheapest_dates_7", [])
cheapest_dates_8 = windows.get("cheapest_dates_8", [])
self.log(f"Using existing cheap windows for {forecast_date}: {windows}")
for iso_date in cheapest_dates_1:
date = datetime.datetime.fromisoformat(iso_date)
cheapest_hours_1.append(dateToRelativeHour(date))
for iso_date in cheapest_dates_2:
date = datetime.datetime.fromisoformat(iso_date)
cheapest_hours_2.append(dateToRelativeHour(date))
for iso_date in cheapest_dates_3:
date = datetime.datetime.fromisoformat(iso_date)
cheapest_hours_3.append(dateToRelativeHour(date))
for iso_date in cheapest_dates_4:
date = datetime.datetime.fromisoformat(iso_date)
cheapest_hours_4.append(dateToRelativeHour(date))
for iso_date in cheapest_dates_5:
date = datetime.datetime.fromisoformat(iso_date)
cheapest_hours_5.append(dateToRelativeHour(date))
for iso_date in cheapest_dates_6:
date = datetime.datetime.fromisoformat(iso_date)
cheapest_hours_6.append(dateToRelativeHour(date))
for iso_date in cheapest_dates_7:
date = datetime.datetime.fromisoformat(iso_date)
cheapest_hours_7.append(dateToRelativeHour(date))
for iso_date in cheapest_dates_8:
date = datetime.datetime.fromisoformat(iso_date)
cheapest_hours_8.append(dateToRelativeHour(date))
# Initialize lists to track which hours are within the cheapest and most expensive windows
self.within_cheapest_1_hour = [False] * self.T
self.within_cheapest_2_hours = [False] * self.T
self.within_cheapest_3_hours = [False] * self.T
self.within_cheapest_4_hours = [False] * self.T
self.within_cheapest_5_hours = [False] * self.T
self.within_cheapest_6_hours = [False] * self.T
self.within_cheapest_7_hours = [False] * self.T
self.within_cheapest_8_hours = [False] * self.T
# Assign window indices to the tracking lists
for idx in cheapest_hours_1:
if 0 <= idx < self.T:
self.within_cheapest_1_hour[idx] = True
for idx in cheapest_hours_2:
if 0 <= idx < self.T:
self.within_cheapest_2_hours[idx] = True
for idx in cheapest_hours_3:
if 0 <= idx < self.T:
self.within_cheapest_3_hours[idx] = True
for idx in cheapest_hours_4:
if 0 <= idx < self.T:
self.within_cheapest_4_hours[idx] = True
for idx in cheapest_hours_5:
if 0 <= idx < self.T:
self.within_cheapest_5_hours[idx] = True
for idx in cheapest_hours_6:
if 0 <= idx < self.T:
self.within_cheapest_6_hours[idx] = True
for idx in cheapest_hours_7:
if 0 <= idx < self.T:
self.within_cheapest_7_hours[idx] = True
for idx in cheapest_hours_8:
if 0 <= idx < self.T:
self.within_cheapest_8_hours[idx] = True
self.log(f"Cheapest 1-hour window indices: {cheapest_hours_1}")
self.log(f"Cheapest 2-hour window indices: {cheapest_hours_2}")
self.log(f"Cheapest 3-hour window indices: {cheapest_hours_3}")
self.log(f"Cheapest 4-hour window indices: {cheapest_hours_4}")
self.log(f"Cheapest 5-hour window indices: {cheapest_hours_5}")
self.log(f"Cheapest 6-hour window indices: {cheapest_hours_6}")
self.log(f"Cheapest 7-hour window indices: {cheapest_hours_7}")
self.log(f"Cheapest 8-hour window indices: {cheapest_hours_8}")
return
def identify_most_expensive_hours(self):
# Determine the forecast date (assuming price forecasts are for the next day)
now = get_now_time()
forecast_date = now.date()
self.log(f"Forecast date determined as {forecast_date}.")
# Load existing window assignments
expensive_windows_data = self.load_expensive_windows()
most_expensive_hours_1 = []
most_expensive_hours_2 = []
most_expensive_hours_3 = []
most_expensive_hours_4 = []
most_expensive_hours_5 = []
most_expensive_hours_6 = []
most_expensive_hours_7 = []
most_expensive_hours_8 = []
most_expensive_dates_1 = []
most_expensive_dates_2 = []
most_expensive_dates_3 = []
most_expensive_dates_4 = []
most_expensive_dates_5 = []
most_expensive_dates_6 = []
most_expensive_dates_7 = []
most_expensive_dates_8 = []
# Check if window assignments are already set for the current forecast date
if (
expensive_windows_data.get("forecast_date") != forecast_date.isoformat()
) and (now.hour > 13):
# New forecast period, find and save new windows
most_expensive_hours_1 = self.find_most_expensive_windows(
self.price_forecast, 1
)
most_expensive_hours_2 = self.find_most_expensive_windows(
self.price_forecast, 2
)
most_expensive_hours_3 = self.find_most_expensive_windows(
self.price_forecast, 3
)
most_expensive_hours_4 = self.find_most_expensive_windows(
self.price_forecast, 4
)
most_expensive_hours_5 = self.find_most_expensive_windows(
self.price_forecast, 5
)
most_expensive_hours_6 = self.find_most_expensive_windows(
self.price_forecast, 6
)
most_expensive_hours_7 = self.find_most_expensive_windows(
self.price_forecast, 7
)
most_expensive_hours_8 = self.find_most_expensive_windows(
self.price_forecast, 8
)