-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathbattery.py
2309 lines (1957 loc) · 99 KB
/
battery.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
# -*- coding: utf-8 -*-
from typing import Union, Tuple, List, Callable
from utils import logger
import utils
import logging
import math
from datetime import datetime
from time import time
from abc import ABC, abstractmethod
import sys
class Protection(object):
"""
This class holds warning and alarm states for different types of checks.
The alarm name in the GUI is the same as the variable name.
They are of type integer
2 = alarm
1 = warning
0 = ok, everything is fine
"""
ALARM = 2
WARNING = 1
OK = 0
def __init__(self):
# current values
self.high_voltage: int = None
self.high_cell_voltage: int = None
self.low_voltage: int = None
self.low_cell_voltage: int = None
self.low_soc: int = None
self.high_charge_current: int = None
self.high_discharge_current: int = None
self.cell_imbalance: int = None
self.internal_failure: int = None
self.high_charge_temperature: int = None
self.low_charge_temperature: int = None
self.high_temperature: int = None
self.low_temperature: int = None
self.high_internal_temperature: int = None
self.fuse_blown: int = None
# previous values to check if the value has changed
self.previous_high_voltage: int = None
self.previous_high_cell_voltage: int = None
self.previous_low_voltage: int = None
self.previous_low_cell_voltage: int = None
self.previous_low_soc: int = None
self.previous_high_charge_current: int = None
self.previous_high_discharge_current: int = None
self.previous_cell_imbalance: int = None
self.previous_internal_failure: int = None
self.previous_high_charge_temperature: int = None
self.previous_low_charge_temperature: int = None
self.previous_high_temperature: int = None
self.previous_low_temperature: int = None
self.previous_high_internal_temperature: int = None
self.previous_fuse_blown: int = None
def set_previous(self) -> None:
"""
Set the previous values to the current values.
:return: None
"""
self.previous_high_voltage = self.high_voltage
self.previous_high_cell_voltage = self.high_cell_voltage
self.previous_low_voltage = self.low_voltage
self.previous_low_cell_voltage = self.low_cell_voltage
self.previous_low_soc = self.low_soc
self.previous_high_charge_current = self.high_charge_current
self.previous_high_discharge_current = self.high_discharge_current
self.previous_cell_imbalance = self.cell_imbalance
self.previous_internal_failure = self.internal_failure
self.previous_high_charge_temperature = self.high_charge_temperature
self.previous_low_charge_temperature = self.low_charge_temperature
self.previous_high_temperature = self.high_temperature
self.previous_low_temperature = self.low_temperature
self.previous_high_internal_temperature = self.high_internal_temperature
self.previous_fuse_blown = self.fuse_blown
class History:
"""
This class holds the history data of the battery.
"""
def __init__(self):
self.exclude_values_to_calculate: list = []
"""
List of values to exclude from calculation, because they are fetched from the BMS.
"""
self.clear: int = 0
"""
Clear the history values, if set to 1. Set to 0 after clearing.
You can set it manually via `dbus-spy --history` to:
- 1 to clear all the history values (default)
- 2 to clear only the capacity values
- 3 to clear only the voltage values
- 4 to clear only the time values
- 5 to clear only the alarm values
- 6 to clear only the temperature values
- 7 to clear only the energy values
"""
# Discharge information in Ah
self.deepest_discharge: float = None
"""
Deepest discharge in Ampere hours (lifetime).
Overwritten each time the battery discharges deeper.
**Should be negative.**
"""
self.last_discharge: float = None
"""
Last discharge in Ampere hours until the battery was charged again.
**Should be negative.**
"""
self.average_discharge: float = None
"""
Average discharge in Ampere hours.
Cumulative Ah drawn divided by total cycles.
**Should be negative.**
"""
self.total_ah_drawn: float = None
"""
Total Ah drawn (lifetime).
Cumulative Amp hours drawn from the battery.
**Should be negative.**
"""
# Charge
self.charge_cycles: int = None
"""
Number of charge cycles (lifetime).
Total Amp hours drawn from the battery divided by the capacity.
"""
self.timestamp_last_full_charge: int = None
"""
Timestamp of full charge.
"""
self.full_discharges: int = None
"""
Number of full discharges (lifetime).
Counted when state of charge reaches 0%.
"""
# Battery voltage
self.minimum_voltage: float = None
"""
Minimum voltage in Volts (lifetime).
"""
self.maximum_voltage: float = None
"""
Maximum voltage in Volts (lifetime).
"""
self.minimum_cell_voltage: float = None
"""
Minimum cell voltage in Volts (lifetime).
"""
self.maximum_cell_voltage: float = None
"""
Maximum cell voltage in Volts (lifetime).
"""
# Voltage alarms
self.low_voltage_alarms: int = None
"""
Number of low voltage alarms (lifetime).
"""
self.high_voltage_alarms: int = None
"""
Number of high voltage alarms (lifetime).
"""
# Battery temperature
self.minimum_temperature: float = None
"""
Minimum temperature in Celsius (lifetime).
"""
self.maximum_temperature: float = None
"""
Maximum temperature in Celsius (lifetime).
"""
# Energy in kWh
self.discharged_energy: int = None
"""
Total discharged energy in Kilowatt-hour (lifetime).
"""
self.charged_energy: int = None
"""
Total charged energy in Kilowatt-hour.
"""
def reset_values(self, attributes: list = []) -> None:
"""
Reset all calculated values that are not excluded.
:param attributes: list of attributes to reset, if empty all attributes are reset
:return: None
"""
attributes = (
[
"deepest_discharge",
"last_discharge",
"average_discharge",
"total_ah_drawn",
"charge_cycles",
"timestamp_last_full_charge",
"full_discharges",
"minimum_voltage",
"maximum_voltage",
"minimum_cell_voltage",
"maximum_cell_voltage",
"low_voltage_alarms",
"high_voltage_alarms",
"minimum_temperature",
"maximum_temperature",
"discharged_energy",
"charged_energy",
]
if not attributes
else attributes
)
for attribute in attributes:
if attribute not in self.exclude_values_to_calculate:
setattr(self, attribute, None)
class Cell:
"""
This class holds information about a single cell
:param voltage: float = the voltage of the cell in Volts
:param balance: bool = the balance status of the cell
"""
voltage: float = None
"""
The voltage of a specific cell in Volts
"""
balance: bool = None
"""
The balance status of a specific cell
"""
def __init__(self, balance: bool = None):
self.balance = balance
class Battery(ABC):
"""
This Class is the abstract baseclass for all batteries. For each BMS this class needs to be extended
and the abstract methods need to be implemented. The main program in dbus-serialbattery.py will then
use the individual implementations as type Battery and work with it.
"""
def __init__(self, port: str, baud: int, address: str):
self.port: str = port
self.baud_rate: int = baud
self.address: str = address
self.can_transport_interface: object = None
self.role: str = "battery"
self.type: str = "Generic"
self.poll_interval: int = 1000
self.dbus_external_objects: dict = None
self.online: bool = True
self.connection_info: str = "Initializing..."
self.hardware_version: str = None
self.cell_count: int = None
self.start_time: int = int(time())
"""
Timestamp of when the battery was initialized
"""
# max battery charge/discharge current
self.max_battery_charge_current: float = utils.MAX_BATTERY_CHARGE_CURRENT
self.max_battery_discharge_current: float = utils.MAX_BATTERY_DISCHARGE_CURRENT
self.has_settings: bool = False
# this values should only be initialized once,
# else the BMS turns off the inverter on disconnect
self.soc_calc_capacity_remain: float = None
self.soc_calc_capacity_remain_last_time: float = None
self.soc_calc_reset_start_time: int = None
self.soc_calc: float = None # save soc_calc to preserve on restart
self.soc: float = None
self.charge_fet: bool = None
self.discharge_fet: bool = None
self.balance_fet: bool = None
self.block_because_disconnect: bool = False
self.control_charge_current: int = None
self.control_discharge_current: int = None
self.control_allow_charge: bool = None
self.control_allow_discharge: bool = None
self.current_avg: float = None
self.current_avg_lst: list = []
self.previous_current_avg: float = None
self.current_external: float = None
self.capacity_remain: float = None
self.capacity: float = None
self.production = None
self.protection = Protection()
self.history = History()
self.version = None
self.time_to_soc_update: int = 0
self.temperature_1: float = None
self.temperature_2: float = None
self.temperature_3: float = None
self.temperature_4: float = None
self.temperature_mos: float = None
self.cells: List[Cell] = []
self.control_voltage: float = None
self.soc_reset_requested: bool = False
self.soc_reset_last_reached: int = 0 # save state to preserve on restart
self.soc_reset_battery_voltage: int = None
self.max_battery_voltage: float = None
self.min_battery_voltage: float = None
self.allow_max_voltage: bool = True # save state to preserve on restart
self.max_voltage_start_time: int = None # save state to preserve on restart
self.transition_start_time: int = None
self.charge_mode: str = None
self.charge_mode_debug: str = ""
self.charge_mode_debug_float: str = ""
self.charge_mode_debug_bulk: str = ""
self.charge_limitation: str = None
self.discharge_limitation: str = None
self.linear_cvl_last_set: int = 0
self.linear_ccl_last_set: int = 0
self.linear_dcl_last_set: int = 0
# Needed for history calculation
self.full_discharge_active: bool = False
"""
True if the battery discharged to 0%. Reset to False after reaching at least 15% again.
"""
# Calculation of charge
self.current_calc_last_time: int = None
self.charge_charged: float = 0
self.charge_discharged: float = 0
self.charge_discharged_last: float = 0
# Calculation of energy
self.power_calc_last_time: int = None
self.energy_charged: float = 0
self.energy_discharged: float = 0
# list of available callbacks, in order to display the buttons in the GUI
self.available_callbacks: List[str] = []
# display errors in the GUI
# https://github.com/victronenergy/veutil/blob/master/inc/veutil/ve_regs_payload.h
# https://github.com/victronenergy/veutil/blob/master/src/qt/bms_error.cpp
self.state: int = 0
"""
State to show in the GUI.
Can block charge/discharge.
"""
self.error_code: Union[int, None] = None
"""
Error code to show in the GUI.
Does not block charge/discharge.
"""
self.error_code_last_reset_check: int = 0
"""
Timestamp when it was last checked, if the error could be reset.
"""
self.error_timestamps: list = []
"""
List of timestamps when an error occurred.
"""
self.custom_field: str = None
"""
Custom field that the user can define in the BMS settings via the BMS app.
"""
self.init_values()
def init_values(self) -> None:
"""
Used to initialize and reset values, if battery unexpectly disconnects.
:return: None
"""
self.voltage: float = None
self.current: float = None
self.current_calc: float = None
self.current_corrected: float = None
self.power_calc: float = None
self.driver_start_time: int = int(time())
@abstractmethod
def test_connection(self) -> bool:
"""
This abstract method needs to be implemented for each BMS. Each driver has to override this function
to test, if a connection to the BMS can be made.
:return: True if the connection was successful else False
"""
return False
def unique_identifier(self) -> str:
"""
Used to identify a BMS when multiple BMS are connected and the port changes for whatever reason.
If not provided by the BMS/driver then the hardware version and capacity is used as fallback.
By slightly changing the capacity of each battery, this can make every battery unique.
On +/- 5 Ah you can identify 11 different batteries.
For some BMS it's not possible to change the capacity or other values. In this case the port has
to be used as `unique_identifier`. Custom values for this battery like the custom name, will be
swapped or lost, if the port changes.
See https://github.com/Louisvdw/dbus-serialbattery/issues/1035
:return: the unique identifier
"""
if utils.USE_PORT_AS_UNIQUE_ID:
return self.port + ("__" + utils.bytearray_to_string(self.address).replace("\\", "0") if self.address is not None else "")
else:
string = "".join(filter(str.isalnum, str(self.hardware_version))) + "_" if self.hardware_version is not None and self.hardware_version != "" else ""
string += str(self.capacity) + "Ah"
return string
def connection_name(self) -> str:
"""
Shown in the GUI under `Device -> Connection`
:return: the connection name
"""
return "Serial " + self.port + ("__" + utils.bytearray_to_string(self.address).replace("\\", "0") if self.address is not None else "")
def custom_name(self) -> str:
"""
Shown in the GUI under `Device -> Name`
Overwritten, if the user set a custom name via GUI
:return: the connection name
"""
return "SerialBattery(" + self.type + ")"
def product_name(self) -> str:
"""
Shown in the GUI under `Device -> Product`
:return: the connection name
"""
return "SerialBattery(" + self.type + ")"
def use_callback(self, callback: Callable) -> bool:
"""
Each driver may override this function to indicate whether it is able to provide value
updates on its own.
:return:
False when the battery cannot provide updates by itself, then it will be polled
every `poll_interval` milliseconds for new values
True if callable should be used for updates as they arrive from the battery
"""
return False
def set_can_transport_interface(self, can_transport_interface: object) -> None:
"""
Set the access object for the can interface.
:param can_transport_interface: the can_transport_interface object
:return: None
"""
self.can_transport_interface: object = can_transport_interface
@abstractmethod
def get_settings(self) -> bool:
"""
Each driver must override this function to read the battery settings.
It's called only once after a successful connection by `DbusHelper.setup_vedbus()`.
See `battery_template.py` for an example.
:return: False when fail, True if successful
"""
return False
@abstractmethod
def refresh_data(self) -> bool:
"""
Each driver must override this function to read battery data and populate this class.
It's called each poll inverval just before the data is published to the vedbus.
:return: False when fail, True if successful
"""
return False
def to_temperature(self, sensor: int, value: float) -> None:
"""
Keep the temp value between -20 and 100 to handle sensor issues or no data.
The BMS should already have protected the battery before those limits have been reached.
:param sensor: temperature sensor number
:param value: the sensor value
:return: None
"""
if sensor == 0:
self.temperature_mos = round(min(max(value, -20), 100), 1)
if sensor == 1:
self.temperature_1 = round(min(max(value, -20), 100), 1)
if sensor == 2:
self.temperature_2 = round(min(max(value, -20), 100), 1)
if sensor == 3:
self.temperature_3 = round(min(max(value, -20), 100), 1)
if sensor == 4:
self.temperature_4 = round(min(max(value, -20), 100), 1)
def manage_charge_voltage(self) -> None:
"""
Manages the charge voltage by setting `self.control_voltage`.
:return: None
"""
# set min and max battery voltage if cell count is known
if self.cell_count is not None:
# set min battery voltage once
if self.min_battery_voltage is None:
self.min_battery_voltage = round(utils.MIN_CELL_VOLTAGE * self.cell_count, 2)
# set max battery voltage once
if self.max_battery_voltage is None:
self.max_battery_voltage = round(utils.MAX_CELL_VOLTAGE * self.cell_count, 2)
else:
logger.debug("Cell count is not known yet. Can't set min and max battery voltage.")
# enable soc reset voltage management only if needed
if utils.SOC_RESET_AFTER_DAYS is not False:
self.soc_reset_voltage_management()
# apply dynamic charging voltage
if utils.CVCM_ENABLE:
# apply linear charging voltage
if utils.LINEAR_LIMITATION_ENABLE:
self.manage_charge_voltage_linear()
# apply step charging voltage
else:
self.manage_charge_voltage_step()
# apply fixed charging voltage
else:
self.control_voltage = round(self.max_battery_voltage, 2)
self.charge_mode = "Keep always max voltage"
def soc_calculation(self) -> float:
"""
Calculates the SoC based on the coulomb counting method.
:return: The calculated state of charge
"""
current_time = time()
SOC_RESET_TIME = 60
if self.soc_calc_capacity_remain is not None:
# calculate remaining capacity based on current
self.soc_calc_capacity_remain = self.soc_calc_capacity_remain + self.current_calc * (current_time - self.soc_calc_capacity_remain_last_time) / 3600
# limit soc_calc_capacity_remain to capacity and zero
# in case 100% is reached and the battery is not fully charged
# in case 0% is reached and the battery is not fully discharged
self.soc_calc_capacity_remain = max(min(self.soc_calc_capacity_remain, self.capacity), 0)
self.soc_calc_capacity_remain_last_time = current_time
# execute checks only if one cell reaches min voltage
# use lowest cell voltage, since in this case the battery is empty
# else a unbalanced battery won't reach 0% and the BMS will shut down
if self.get_min_cell_voltage() <= utils.MIN_CELL_VOLTAGE:
# check if battery is still being discharged
if self.current_calc < 0 and self.soc_calc_reset_start_time:
# set soc to 0%, if SOC_RESET_TIME is reached and soc_calc is not rounded 0%
if (int(current_time) - self.soc_calc_reset_start_time) > SOC_RESET_TIME and round(self.soc_calc, 0) != 0:
logger.info("SOC set to 0%")
self.soc_calc_capacity_remain = 0
self.soc_calc_reset_start_time = None
else:
self.soc_calc_reset_start_time = int(current_time)
else:
# if soc_calc is not available initialize it from the BMS
if self.soc_calc is None:
# if there is a SOC from the BMS then use it
if self.soc is not None:
self.soc_calc_capacity_remain = self.capacity * self.soc / 100
logger.debug("SOC initialized from BMS and set to " + str(self.soc) + "%")
# else set it to 100%
# this is currently (2024.04.13) not possible, since then the driver won't start, if there is no SOC
# but leave it in case a BMS without SOC should be added
else:
self.soc_calc_capacity_remain = self.capacity
logger.debug("SOC initialized and set to 100%")
# else initialize it from dbus
else:
self.soc_calc_capacity_remain = self.capacity * self.soc_calc / 100 if self.soc_calc > 0 else 0
logger.debug("SOC initialized from dbus and set to " + str(self.soc_calc) + "%")
self.soc_calc_capacity_remain_last_time = current_time
# calculate the SOC based on remaining capacity
return round(max(min((self.soc_calc_capacity_remain / self.capacity) * 100, 100), 0), 3)
def soc_reset_voltage_management(self) -> None:
"""
Call this method only, if `SOC_RESET_AFTER_DAYS` is not False.
It sets the `self.max_battery_voltage` to the `SOC_RESET_VOLTAGE` once needed.
:return: None
"""
soc_reset_last_reached_days_ago = 0 if self.soc_reset_last_reached == 0 else (((int(time()) - self.soc_reset_last_reached) / 60 / 60 / 24))
# set soc_reset_requested to True, if the days are over
# it gets set to False once the bulk voltage was reached once
if (
utils.SOC_RESET_AFTER_DAYS is not False
and self.soc_reset_requested is False
and self.allow_max_voltage
and (self.soc_reset_last_reached == 0 or utils.SOC_RESET_AFTER_DAYS < soc_reset_last_reached_days_ago)
):
self.soc_reset_requested = True
self.soc_reset_battery_voltage = round(utils.SOC_RESET_VOLTAGE * self.cell_count, 2)
if self.soc_reset_requested:
self.max_battery_voltage = self.soc_reset_battery_voltage
else:
self.max_battery_voltage = round(utils.MAX_CELL_VOLTAGE * self.cell_count, 2)
def manage_charge_voltage_linear(self) -> None:
"""
Manages the charge voltage using linear interpolation by setting `self.control_voltage`.
:return: None
"""
found_high_cell_voltage = False
voltage_sum = 0
penalty_sum = 0
time_diff = 0
control_voltage = 0
current_time = int(time())
# meassurment and variation tolerance in volts
measurement_tolerance_variation = 0.5
try:
# calculate voltage sum and check for cell overvoltage
for i in range(self.cell_count):
voltage = self.get_cell_voltage(i)
if voltage:
voltage_sum += voltage
# calculate penalty sum to prevent single cell overcharge by using current cell voltage
if self.max_battery_voltage != self.soc_reset_battery_voltage and voltage > utils.MAX_CELL_VOLTAGE:
# found_high_cell_voltage: reset to False is not needed, since it is recalculated every second
found_high_cell_voltage = True
penalty_sum += voltage - utils.MAX_CELL_VOLTAGE
elif self.max_battery_voltage == self.soc_reset_battery_voltage and voltage > utils.SOC_RESET_VOLTAGE:
# found_high_cell_voltage: reset to False is not needed, since it is recalculated every second
found_high_cell_voltage = True
penalty_sum += voltage - utils.SOC_RESET_VOLTAGE
voltage_cell_diff = self.get_max_cell_voltage() - self.get_min_cell_voltage()
if self.max_voltage_start_time is None:
# start timer, if max voltage is reached and cells are balanced
if (
(self.max_battery_voltage - utils.VOLTAGE_DROP) <= voltage_sum
and voltage_cell_diff <= utils.CELL_VOLTAGE_DIFF_KEEP_MAX_VOLTAGE_UNTIL
and self.allow_max_voltage
):
self.max_voltage_start_time = current_time
# allow max voltage again, if:
# - SoC threshold is reached
# - Cells are unbalanced
# - SoC reset was requested
elif (
utils.SWITCH_TO_BULK_SOC_THRESHOLD > self.soc_calc
or voltage_cell_diff >= utils.CELL_VOLTAGE_DIFF_TO_RESET_VOLTAGE_LIMIT
or self.soc_reset_requested
) and not self.allow_max_voltage:
self.allow_max_voltage = True
# do nothing (only for readability)
else:
pass
# timer started
else:
if voltage_cell_diff > utils.CELL_VOLTAGE_DIFF_KEEP_MAX_VOLTAGE_TIME_RESTART:
self.max_voltage_start_time = current_time
time_diff = current_time - self.max_voltage_start_time
# keep max voltage for MAX_VOLTAGE_TIME_SEC more seconds
if utils.MAX_VOLTAGE_TIME_SEC < time_diff:
self.allow_max_voltage = False
self.max_voltage_start_time = None
if self.soc_calc <= utils.SWITCH_TO_BULK_SOC_THRESHOLD:
# set error code, to show in the GUI that something is wrong
self.manage_error_code(8)
# write to log, that reset to float was not possible
logger.error(
f"Could not change to float voltage. Battery SoC ({self.soc_calc}%) is lower"
+ f" than SWITCH_TO_BULK_SOC_THRESHOLD ({utils.SWITCH_TO_BULK_SOC_THRESHOLD}%)."
+ " Please reset SoC manually or lower the SWITCH_TO_BULK_SOC_THRESHOLD in the"
+ ' "config.ini".'
)
# we don't forget to reset max_voltage_start_time wenn we going to bulk(dynamic) mode
# regardless of whether we were in absorption mode or not
if voltage_sum < self.max_battery_voltage - measurement_tolerance_variation:
self.max_voltage_start_time = None
# Bulk or Absorption mode
if self.allow_max_voltage:
# use I-Controller
if utils.CVL_ICONTROLLER_MODE:
if self.control_voltage:
# 6 decimals are needed for a proper I-controller working
# https://github.com/Louisvdw/dbus-serialbattery/issues/1041
control_voltage = round(
self.control_voltage
- (
(
self.get_max_cell_voltage()
- (utils.SOC_RESET_VOLTAGE if self.soc_reset_requested else utils.MAX_CELL_VOLTAGE)
- utils.CELL_VOLTAGE_DIFF_KEEP_MAX_VOLTAGE_UNTIL
)
* utils.CVL_ICONTROLLER_FACTOR
),
6,
)
else:
control_voltage = self.max_battery_voltage
control_voltage = min(
max(control_voltage, self.min_battery_voltage),
self.max_battery_voltage,
)
# use P-Controller
else:
if found_high_cell_voltage:
# reduce voltage by penalty sum
# keep penalty above min battery voltage and below max battery voltage
control_voltage = round(
min(
max(
voltage_sum - penalty_sum,
self.min_battery_voltage,
),
self.max_battery_voltage,
),
6,
)
else:
control_voltage = self.max_battery_voltage
self.control_voltage = control_voltage
self.charge_mode = "Bulk" if self.max_voltage_start_time is None else "Absorption"
if found_high_cell_voltage:
self.charge_mode += " Dynamic"
if self.max_battery_voltage == self.soc_reset_battery_voltage:
self.charge_mode += " & SoC Reset"
if self.get_balancing() and voltage_cell_diff >= utils.CELL_VOLTAGE_DIFF_TO_RESET_VOLTAGE_LIMIT:
self.charge_mode += " + Balancing"
# Float mode
else:
float_voltage = round((utils.FLOAT_CELL_VOLTAGE * self.cell_count), 2)
charge_mode = "Float"
# reset bulk when going into float
if self.soc_reset_requested:
# logger.info("set soc_reset_requested to False")
self.soc_reset_requested = False
self.soc_reset_last_reached = current_time
if self.control_voltage:
# check if battery changed from bulk/absoprtion to float
if self.charge_mode is not None and not self.charge_mode.startswith("Float"):
self.transition_start_time = current_time
self.initial_control_voltage = self.control_voltage
charge_mode = "Float Transition"
# Assume battery SOC ist 100% at this stage
self.trigger_soc_reset()
# Set timestamp of full charge for history
if "timestamp_last_full_charge" not in self.history.exclude_values_to_calculate:
self.history.timestamp_last_full_charge = int(time())
if utils.SOC_CALCULATION:
logger.info("SOC set to 100%")
self.soc_calc_capacity_remain = self.capacity
self.soc_calc_reset_start_time = None
elif self.charge_mode.startswith("Float Transition"):
elapsed_time = current_time - self.transition_start_time
# Voltage reduction per second
VOLTAGE_REDUCTION_PER_SECOND = 0.01 / 10
voltage_reduction = min(
VOLTAGE_REDUCTION_PER_SECOND * elapsed_time,
self.initial_control_voltage - float_voltage,
)
self.control_voltage = self.initial_control_voltage - voltage_reduction
if self.control_voltage <= float_voltage:
self.control_voltage = float_voltage
charge_mode = "Float"
else:
charge_mode = "Float Transition"
else:
self.control_voltage = float_voltage
self.charge_mode = charge_mode
self.charge_mode += " (Linear Mode)"
# debug information
if utils.GUI_PARAMETERS_SHOW_ADDITIONAL_INFO or logger.isEnabledFor(logging.DEBUG):
soc_reset_days_ago = round((current_time - self.soc_reset_last_reached) / 60 / 60 / 24, 2)
soc_reset_in_days = round(utils.SOC_RESET_AFTER_DAYS - soc_reset_days_ago, 2)
driver_start_time_dt = datetime.fromtimestamp(self.driver_start_time)
formatted_time = driver_start_time_dt.strftime("%Y.%m.%d %H:%M:%S")
self.charge_mode_debug = (
f"driver started: {formatted_time} • running since: {self.get_seconds_to_string(int(time()) - self.driver_start_time)}\n"
+ f"max_battery_voltage: {(self.max_battery_voltage):.2f} V • "
+ f"control_voltage: {self.control_voltage:.2f} V\n"
+ f"voltage: {self.voltage:.2f} V • "
+ f"VOLTAGE_DROP: {utils.VOLTAGE_DROP:.2f} V\n"
+ f"voltage_sum: {voltage_sum:.2f} V • "
+ f"voltage_cell_diff: {voltage_cell_diff:.3f} V\n"
+ f"max_cell_voltage: {self.get_max_cell_voltage()} V • penalty_sum: {penalty_sum:.3f} V\n"
+ f"soc: {self.soc}% • soc_calc: {self.soc_calc}%\n"
+ f"current: {self.current:.2f}A"
+ (f" • current_calc: {self.current_calc:.2f} A\n" if self.current_calc is not None else "\n")
+ f"current_time: {current_time}\n"
+ f"linear_cvl_last_set: {self.linear_cvl_last_set}\n"
+ f"charge_fet: {self.charge_fet} • control_allow_charge: {self.control_allow_charge}\n"
+ f"discharge_fet: {self.discharge_fet} • "
+ f"control_allow_discharge: {self.control_allow_discharge}\n"
+ f"block_because_disconnect: {self.block_because_disconnect}\n"
+ "soc_reset_last_reached: "
+ ("Never" if self.soc_reset_last_reached == 0 else f"{soc_reset_days_ago}")
+ f" d ago, next in {soc_reset_in_days} d\n"
+ (
f"soc_calc_capacity_remain: {self.soc_calc_capacity_remain:.3f}/{self.capacity} Ah\n"
if self.soc_calc_capacity_remain is not None
else ""
)
+ "soc_calc_reset_start_time: "
+ (f"{int(current_time - self.soc_calc_reset_start_time)}/60" if self.soc_calc_reset_start_time is not None else "None")
)
self.charge_mode_debug_float = (
"-- switch to float requirements (Linear Mode) --\n"
+ f"max_battery_voltage: {(self.max_battery_voltage - utils.VOLTAGE_DROP):.2f} <= "
+ f"{voltage_sum:.2f} :voltage_sum\n"
+ "AND\n"
+ f"voltage_cell_diff: {voltage_cell_diff:.3f} <= "
+ f"{utils.CELL_VOLTAGE_DIFF_KEEP_MAX_VOLTAGE_UNTIL:.3f} "
+ ":CELL_VOLTAGE_DIFF_KEEP_MAX_VOLTAGE_UNTIL\n"
+ "AND\n"
+ f"allow_max_voltage: {self.allow_max_voltage} == True\n"
+ "AND\n"
+ f"MAX_VOLTAGE_TIME_SEC: {utils.MAX_VOLTAGE_TIME_SEC} < {time_diff} :time_diff"
)
self.charge_mode_debug_bulk = (
"-- switch to bulk requirements (Linear Mode) --\n"
+ "a) SWITCH_TO_BULK_SOC_THRESHOLD: "
+ f"{utils.SWITCH_TO_BULK_SOC_THRESHOLD} > {self.soc_calc} :soc_calc\n"
+ "OR\n"
+ f"b) voltage_cell_diff: {voltage_cell_diff:.3f} >= "
+ f"{utils.CELL_VOLTAGE_DIFF_TO_RESET_VOLTAGE_LIMIT:.3f} "
+ ":CELL_VOLTAGE_DIFF_TO_RESET_VOLTAGE_LIMIT\n"
+ "AND\n"
+ f"allow_max_voltage: {self.allow_max_voltage} == False"
)
except TypeError:
self.control_voltage = round((utils.FLOAT_CELL_VOLTAGE * self.cell_count), 2)
self.charge_mode = "Error, please check the logs!"
# set error code, to show in the GUI that something is wrong
self.manage_error_code(8)
exception_type, exception_object, exception_traceback = sys.exc_info()
file = exception_traceback.tb_frame.f_code.co_filename
line = exception_traceback.tb_lineno
logger.error("Non blocking exception occurred: " + f"{repr(exception_object)} of type {exception_type} in {file} line #{line}")
def set_cvl_linear(self, control_voltage: float) -> bool:
"""
Set CVL only once every `LINEAR_RECALCULATION_EVERY` seconds or if the CVL changes more than
`LINEAR_RECALCULATION_ON_PERC_CHANGE` percent.
TODO: Seems to not be needed anymore. Will be removed in future.
:return: The status, if the CVL was set
"""
current_time = int(time())
diff = abs(self.control_voltage - control_voltage) if self.control_voltage is not None else 0
if utils.LINEAR_RECALCULATION_EVERY <= current_time - self.linear_cvl_last_set or (
diff >= self.control_voltage * utils.LINEAR_RECALCULATION_ON_PERC_CHANGE / 100 / 10 # for more precision, since the changes are small in this case
):
self.control_voltage = control_voltage
self.linear_cvl_last_set = current_time
return True
return False
def manage_charge_voltage_step(self) -> None:
"""
Manages the charge voltage using a step function by setting `self.control_voltage`.
:return: None
"""
voltage_sum = 0
time_diff = 0
current_time = int(time())
try:
# calculate battery sum
for i in range(self.cell_count):
voltage = self.get_cell_voltage(i)
if voltage:
voltage_sum += voltage
voltage_cell_diff = self.get_max_cell_voltage() - self.get_min_cell_voltage()
if self.max_voltage_start_time is None:
# start timer, if max voltage is reached
if (self.max_battery_voltage - utils.VOLTAGE_DROP) <= voltage_sum and self.allow_max_voltage:
self.max_voltage_start_time = current_time
# allow max voltage again, if:
# - SoC threshold is reached
# - SoC reset was requested
elif (utils.SWITCH_TO_BULK_SOC_THRESHOLD > self.soc_calc or self.soc_reset_requested) and not self.allow_max_voltage:
self.allow_max_voltage = True
# do nothing (only for readability)
else:
pass
# timer started
else:
time_diff = current_time - self.max_voltage_start_time
if utils.MAX_VOLTAGE_TIME_SEC < time_diff:
self.allow_max_voltage = False
self.max_voltage_start_time = None
# Bulk or Absorption mode
if self.allow_max_voltage: