-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_batterycontrol.py
More file actions
executable file
·426 lines (353 loc) · 17.2 KB
/
simple_batterycontrol.py
File metadata and controls
executable file
·426 lines (353 loc) · 17.2 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
#!/usr/bin/env python3
from pv_fronius.fronius_symo import Symo
from influxdb_cli2.influxdb_cli2 import influxdb_cli2
from configparser import RawConfigParser
import paho.mqtt.client as paho
import time
import datetime
import sys
import logging
import os
config = RawConfigParser(delimiters='=')
config.configfile = os.path.dirname(os.path.realpath(__file__)) + '/config/simple_batterycontrol.cfg'
config.read(config.configfile)
logging.basicConfig(format='simple_batterycontrol: %(message)s', level=logging.INFO)
gen24 = Symo(ipaddr=config.get('symo','ipaddr'))
if gen24 is None:
logging.warning("Gen24 don't like to talk to us")
sys.exit(1)
class battery:
def __init__(self, gen24):
self.operate = self.normal_operation
self.override = False
self.state_change = True
self.state = 0
self.cur_price = 10
self.price_lim_discharge = 0.06
self.price_lim_charge = 0.01
self.soc_lim_discharge = 95 # First discharge to xx %, then stop if price is low
self.summer_power_cap = 6500
self.summer_min_charge = 50
self.pv_remaining = 60
self.iteration_delay_default = 5 * 60
self.iteration_delay = self.iteration_delay_default
def set_soc_lim_discharge(self, soc):
if isinstance(soc, (int, float)):
self.soc_lim_discharge = soc
self.state_change = True
def set_price_lim_discharge(self, price):
if isinstance(price, (int, float)):
self.price_lim_discharge = price
self.state_change = True
def set_price_lim_charge(self, price):
if isinstance(price, (int, float)):
self.price_lim_charge = price
self.state_change = True
def set_state(self, state):
self.state = state
if state == None or int(state) == 0:
self.operate = self.normal_operation
self.override = False
self.state_change = True
logging.info("Set State to Auto")
elif int(state) == 1:
self.operate = self.normal_operation
self.override = True
self.state_change = True
logging.info("Set State to Normal Operation (forced)")
elif int(state) == 2:
self.operate = self.charge_only
self.override = True
self.state_change = True
logging.info("Set State to Charge Only (forced)")
#elif int(state) == 3:
#self.operate = self.slow_charge
#self.override = False
#self.state_change = True
#print("Set State to Slow Charge (until 25%)")
elif int(state) == 4:
self.operate = self.summer_mode
self.override = False
self.state_change = True
logging.info("Set State to optimized for lot of sun")
elif int(state) == 5:
self.operate = self.low_price
self.override = False
self.state_change = True
logging.info("Set State low price on grid")
elif int(state) == 6:
self.operate = self.very_low_price
self.override = False
self.state_change = True
logging.info("Set State very low price on grid")
elif int(state) == 7:
self.operate = self.battery_empty
self.override = False
self.state_change = True
logging.info("Set State Battery empty")
else:
logging.warning("unknown state, nothing changed")
def get_state(self):
return self.state
def normal_operation(self):
self.state = 1
# Enable
gen24.enable(auto=False, enable=True)
if self.state_change:
# Wait after enable for startup
time.sleep(30)
logging.info("Battery: Setting Charge unlim, Discharge unlim")
gen24.set_battery_discharge_rate(None)
gen24.set_battery_charge_rate(None)
self.state_change = False
battery_soc = gen24.read_data("Battery_SoC")
logging.info("Battery SOC {0}%, Lim SOC Discharge {1}%, Override {2}".format(battery_soc, self.soc_lim_discharge, self.override))
logging.info("Current Price {0}, Lim Price Discharge {1}, Lim Price Charge {2}".format(self.cur_price, self.price_lim_discharge, self.price_lim_charge))
if (self.cur_price < self.price_lim_discharge) and (battery_soc < self.soc_lim_discharge) and not self.override:
logging.info("Set state to low_price")
self.operate = self.low_price
self.state_change = True
elif battery_soc < 15.0 and not self.override:
logging.info("Set state to battery_empty")
self.operate = self.battery_empty
self.state_change = True
else:
logging.info("Keep state Normal Operation")
self.state_change = False
def charge_only(self):
self.state = 2
if self.state_change:
logging.info("Battery: Setting Charge unlim, Discharge 0")
gen24.set_battery_discharge_rate(0)
gen24.set_battery_charge_rate(None)
self.state_change = False
# Disable, if no voltage on PV (and battery should be used)
gen24.enable(auto=True)
battery_soc = gen24.read_data("Battery_SoC")
logging.info("Battery SOC {0}%, Lim SOC Discharge {1}%".format(battery_soc, self.soc_lim_discharge))
logging.info("Current Price {0}, Lim Price Discharge {1}, Lim Price Charge {2}".format(self.cur_price, self.price_lim_discharge, self.price_lim_charge))
if self.cur_price < self.price_lim_charge and not self.override:
logging.info("Set state to Very low price")
self.operate = self.very_low_price
self.state_change = True
elif (battery_soc > 25 and self.cur_price > self.price_lim_discharge) and not self.override:
logging.info("Set state to Normal Operation")
self.operate = self.normal_operation
self.state_change = True
else:
logging.info("Keep state Charge Only")
self.state_change = False
#def slow_charge(self):
#self.state = 3
#if self.state_change:
#print("Battery: Setting Charge 1000, Discharge unlim")
#gen24.set_battery_discharge_rate(None)
#gen24.set_battery_charge_rate(10)
#self.state_change = False
#battery_soc = gen24.read_data("Battery_SoC")
#print("Battery SOC {0}%".format(battery_soc))
#if battery_soc < 25 and not self.override:
#print("Set state to Normal Operation")
#self.operate = self.normal_operation
#self.state_change = True
#else:
#print("Keep state Slow Charge")
#self.state_change = False
def summer_mode(self):
self.state = 4
if self.state_change:
logging.info("Battery: Setting Charge 0, Discharge unlim")
gen24.set_battery_discharge_rate(None)
gen24.set_battery_charge_rate(0)
self.state_change = False
battery_soc = gen24.read_data("Battery_SoC")
pwr_pv = gen24.read_calculated_value("PV_Power")
pwr_consumption = gen24.read_calculated_value("Consumption_Sum")
logging.info("Battery SOC {0}%, PV PWR = {1}W, Consumption = {2}W".format(battery_soc, pwr_pv, pwr_consumption))
if battery_soc < self.summer_min_charge and not self.override:
logging.info("Battery below {0}%, Charge with full power".format(self.summer_min_charge))
gen24.set_battery_charge_rate(None)
elif ((100-battery_soc)*11) > (self.pv_remaining/2000):
logging.info("Battery {0}%, PV Remaining {1}, Charge with full power".format(battery_soc, self.pv_remaining))
gen24.set_battery_charge_rate(None)
else:
logging.info("Battery only for surplus charges")
pwr_charge = pwr_pv - (pwr_consumption + self.summer_power_cap)
logging.info("Calculated charge power: {0}".format(pwr_charge))
if pwr_charge > 0:
gen24.set_battery_charge_rate(pwr_charge / 100)
else:
gen24.set_battery_charge_rate(0)
if pwr_pv > self.summer_power_cap - 1000:
self.iteration_delay = 30
else:
self.iteration_delay = self.iteration_delay_default
# Fallback, should no thappen
if battery_soc < 25 and not self.override:
logging.info("Fallback... Set state to Normal Operation")
self.operate = self.normal_operation
self.state_change = True
else:
logging.info("Keep state Summer mode")
self.state_change = False
def low_price(self):
self.state = 5
if self.state_change:
logging.info("Battery: Setting Charge unlim, Discharge 0")
gen24.set_battery_discharge_rate(0)
gen24.set_battery_charge_rate(None)
self.state_change = False
# Disable, if no voltage on PV (and battery should be used)
gen24.enable(auto=True)
battery_soc = gen24.read_data("Battery_SoC")
logging.info("Battery SOC {0}%, Lim SOC Discharge {1}%".format(battery_soc, self.soc_lim_discharge))
logging.info("Current Price {0}, Lim Price Discharge {1}, Lim Price Charge {2}".format(self.cur_price, self.price_lim_discharge, self.price_lim_charge))
if self.cur_price < self.price_lim_charge and not self.override:
logging.info("Set state to Very Low Price")
self.operate = self.very_low_price
self.state_change = True
elif (battery_soc >= 15 and self.cur_price > self.price_lim_discharge) and not self.override:
logging.info("Set state to Normal Operation")
self.operate = self.normal_operation
self.state_change = True
elif (battery_soc > self.soc_lim_discharge) and not self.override:
logging.info("Set state to Normal Operation")
self.operate = self.normal_operation
self.state_change = True
elif battery_soc < 15:
logging.info("Set state to battery_empty")
self.operate = self.battery_empty
self.state_change = True
else:
logging.info("Keep state Low Price")
self.state_change = False
def very_low_price(self):
self.state = 6
# Enable, since battery should be charged
gen24.enable(auto=False, enable=True)
if self.state_change:
# Wait for startup after enable
time.sleep(30)
logging.info("Battery: Setting Charge unlim, Discharge -5kW (=Charge Battery")
gen24.set_battery_discharge_rate(-50)
gen24.set_battery_charge_rate(None)
self.state_change = False
battery_soc = gen24.read_data("Battery_SoC")
logging.info("Battery SOC {0}%, Lim SOC Discharge {1}%".format(battery_soc, self.soc_lim_discharge))
logging.info("Current Price {0}, Lim Price Discharge {1}, Lim Price Charge {2}".format(self.cur_price, self.price_lim_discharge, self.price_lim_charge))
if self.cur_price > self.price_lim_charge and not self.override:
logging.info("Set state to Low Price")
self.operate = self.low_price
self.state_change = True
else:
logging.info("Keep state Very Low Price")
self.state_change = False
def battery_empty(self):
self.state = 7
if self.state_change:
logging.info("Battery empty: Setting Charge unlim, Discharge 0")
gen24.set_battery_discharge_rate(0)
gen24.set_battery_charge_rate(None)
self.state_change = False
# Disable if no Voltage on PV (and battery is anyway empty)
gen24.enable(auto=True)
battery_soc = gen24.read_data("Battery_SoC")
logging.info("Battery SOC {0}%".format(battery_soc))
logging.info("Current Price {0}, Lim Price Discharge {1}, Lim Price Charge {2}".format(self.cur_price, self.price_lim_discharge, self.price_lim_charge))
if self.cur_price < self.price_lim_charge and not self.override:
logging.info("Set state to Very low price")
self.operate = self.very_low_price
self.state_change = True
elif (battery_soc > 25 and self.cur_price > self.price_lim_discharge) and not self.override:
logging.info("Set state to Normal Operation")
self.operate = self.normal_operation
self.state_change = True
else:
logging.info("Keep state Charge Only")
influxdb = influxdb_cli2(config.get('influxdb','url', raw=True),
token=config.get('influxdb','token'),
org=config.get('influxdb','org'),
bucket=config.get('influxdb','bucket'),
debug=False,
)
def get_last_from_db(name, searchinterval=24, location='pv_fronius'):
results = influxdb.query_data(location, name, datetime.datetime.utcnow()+datetime.timedelta(hours=(searchinterval*-1)), datetime.datetime.utcnow())
# print(name)
if results:
# print(results)
# print(results[-1][3])
return results[-1][3]
def get_current_price():
return get_last_from_db(name='price_total', searchinterval=1, location='grid_tibber')
def get_pv_remaining():
return get_last_from_db(name='prediction_remaining', searchinterval=2, location='pv_prediction')
def on_connect(client, userdata, flags, rc):
# print("Connection returned result: " + str(rc))
client.subscribe(client.bat_topic + "/battery_state_set", 1)
client.subscribe(client.bat_topic + "/battery_price_lim_discharge", 1)
client.subscribe(client.bat_topic + "/battery_price_lim_charge", 1)
client.subscribe(client.bat_topic + "/battery_soc_lim_discharge", 1)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
logging.info(msg.topic+": {0}".format(msg.payload) )
if msg.topic == client.bat_topic + "/battery_state_set":
if int(msg.payload) >= 0 and int(msg.payload) <= 5:
logging.info("MQTT: receive battery_state_set {0}".format(msg.payload))
bat.set_state(int(msg.payload))
if msg.topic == client.bat_topic + "/battery_price_lim_discharge":
if float(msg.payload) >= 0 and float(msg.payload) <= 30.0:
logging.info("MQTT: receive battery_price_lim_discharge {0}".format(msg.payload))
bat.set_price_lim_discharge(float(msg.payload))
if msg.topic == client.bat_topic + "/battery_price_lim_charge":
if float(msg.payload) >= 0 and float(msg.payload) <= 30.0:
logging.info("MQTT: receive battery_price_lim_charge {0}".format(msg.payload))
bat.set_price_lim_charge(float(msg.payload))
if msg.topic == client.bat_topic + "/battery_soc_lim_discharge":
if float(msg.payload) >= 0 and float(msg.payload) <= 100.0:
logging.info("MQTT: receive battery_soc_lim_discharge {0}".format(msg.payload))
bat.set_soc_lim_discharge(float(msg.payload))
mqtt= paho.Client()
mqtt.on_connect = on_connect
mqtt.on_message = on_message
mqtt.bat_topic = config.get('mqtt','topic')
mqtt.connect(config.get('mqtt','server'),config.getint('mqtt','port'))
mqtt.loop_start()
bat = battery(gen24)
bat.set_soc_lim_discharge(get_last_from_db('battery_soc_lim_discharge', searchinterval=96))
bat.set_price_lim_discharge(get_last_from_db('battery_price_lim_discharge', searchinterval=96))
bat.set_price_lim_charge(get_last_from_db('battery_price_lim_charge', searchinterval=96))
bat.summer_min_charge = config.getint('battery','summer_min_charge', fallback = 50)
bat.summer_power_cap = config.getint('battery','summer_power_cap', fallback = 6500)
laststate = get_last_from_db('battery_state', searchinterval=2)
if laststate == None:
laststate = config.getint('battery','state')
elif laststate == 4:
bat.set_state(laststate)
while True:
price = get_current_price()
if isinstance(price, float):
bat.cur_price = price
else:
logging.warning("No price found in DB, using 10.0 as fallback")
bat.cur_price = 10.0
pv_remaining = get_pv_remaining()
logging.info("Found in DB estimated pv_remaining {0} Wh".format(pv_remaining))
if isinstance(pv_remaining, float):
bat.pv_remaining = pv_remaining
else:
bat.pv_remaining = 0
bat.operate()
logging.info("battery_state {0}".format(int(bat.get_state())))
influxdb.write_sensordata('pv_fronius', 'battery_state', int(bat.get_state()))
# config.set('battery','state',int(bat.get_state()))
influxdb.write_sensordata('pv_fronius', 'battery_price_lim_discharge', bat.price_lim_discharge)
influxdb.write_sensordata('pv_fronius', 'battery_price_lim_charge', bat.price_lim_charge)
influxdb.write_sensordata('pv_fronius', 'battery_soc_lim_discharge', bat.soc_lim_discharge)
logging.info("--------")
# config.write(config.configfile)
for i in range(int(bat.iteration_delay/5.0)):
time.sleep(5)
#print(i)
if bat.state_change == True:
logging.info("break")
break