forked from Dr-Gigavolt/dbus-aggregate-batteries
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbus-aggregate-batteries.py
More file actions
1431 lines (1234 loc) · 68.4 KB
/
dbus-aggregate-batteries.py
File metadata and controls
1431 lines (1234 loc) · 68.4 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
#!/usr/bin/env python3
"""
Service to aggregate multiple serial batteries https://github.com/mr-manuel/venus-os_dbus-serialbattery
to one virtual battery.
Python location on Venus:
/usr/bin/python3.8
/usr/lib/python3.8/site-packages/
References:
https://dbus.freedesktop.org/doc/dbus-python/tutorial.html
https://github.com/victronenergy/venus/wiki/dbus
https://github.com/victronenergy/velib_python
"""
from gi.repository import GLib
import logging
import sys
import os
import platform
import dbus
import re
import settings
from functions import Functions
# for UTC time stamps for logging
from datetime import datetime as dt
# for charge measurement
import time as tt
from dbusmon import DbusMon
from threading import Thread
# add ext folder to sys.path
sys.path.insert(1, os.path.join(os.path.dirname(__file__), "ext"))
# optionally from victron
# sys.path.insert(1, "/opt/victronenergy/dbus-systemcalc-py/ext/velib_python")
from vedbus import VeDbusService # noqa: E402
VERSION = "4.0.20251023-beta"
class SystemBus(dbus.bus.BusConnection):
def __new__(cls):
return dbus.bus.BusConnection.__new__(cls, dbus.bus.BusConnection.TYPE_SYSTEM)
class SessionBus(dbus.bus.BusConnection):
def __new__(cls):
return dbus.bus.BusConnection.__new__(cls, dbus.bus.BusConnection.TYPE_SESSION)
def get_bus() -> dbus.bus.BusConnection:
return SessionBus() if "DBUS_SESSION_BUS_ADDRESS" in os.environ else SystemBus()
class DbusAggBatService(object):
def __init__(self, servicename="com.victronenergy.battery.aggregate"):
self._fn = Functions()
self._batteries_dict = {}
""" dictionary with battery name as key and dbus service as value """
self._multi = None
""" dbus service of MultiPlus/Quattro, if found """
self._mppts_list = []
""" list of dbus services of MPPTs, if found """
# store list of SmartShunts as specified in settings.py
self._smartShunt_list = []
""" list of dbus services of SmartShunts, if found """
# Initialize tread as None
self._dbusMon = None
# the number of SmartShunts at the beginning of _smartShunt_list that are in the
# battery service (dc_load are listed behind)
self._num_battery_shunts = 0
self._searchTrials = 1
self._readTrials = 1
self._MaxChargeVoltage_old = 0
self._MaxChargeCurrent_old = 0
self._MaxDischargeCurrent_old = 0
# Keep track of MultiPlus/Quattro connection status
# so connect/disconnect notice is output only once
# - prevents log overflowing when MultiPlus/Quattro is
# switched off for longer periods of time (i.e. in mobile applications)
self._multi_connected = True
# implementing hysteresis for allowing discharge
self._fullyDischarged = False
self._dbusConn = get_bus()
logging.info("### Initialise VeDbusService ")
self._dbusservice = VeDbusService(servicename, self._dbusConn, register=False)
logging.info("|- Done: Init of VeDbusService ")
self._timeOld = tt.time()
# written when dynamic CVL limit activated
self._DCfeedActive = False
# Set True when starting dynamic CVL reduction. Set False when balancing is finished.
self._dynCVLactivated = False
# 0: inactive; 1: goal reached, waiting for discharging under nominal voltage; 2: nominal voltage reached
self._balancing = 0
# Day in year
self._lastBalancing = 0
# set if the CVL needs to be reduced due to peaking
self._dynamicCVL = False
# last timestamp then the log was printed
self._logLastPrintTimeStamp = 0
# read initial charge from text file
try:
self._charge_file = open("/data/apps/dbus-aggregate-batteries/storedvalue_charge", "r") # read
self._ownCharge = float(self._charge_file.readline().strip())
self._charge_file.close()
self._ownCharge_old = self._ownCharge
logging.info("Initial Ah read from file: %.0fAh" % (self._ownCharge))
except Exception:
logging.error("Charge file read error. Exiting...")
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
# read the day of the last balancing from text file
if settings.OWN_CHARGE_PARAMETERS:
try:
self._lastBalancing_file = open(
"/data/apps/dbus-aggregate-batteries/storedvalue_last_balancing",
"r",
)
self._lastBalancing = int(self._lastBalancing_file.readline().strip())
self._lastBalancing_file.close()
# in days
time_unbalanced = int((dt.now()).strftime("%j")) - self._lastBalancing
if time_unbalanced < 0:
# year change
time_unbalanced += 365
logging.info("Last balancing done at the %d. day of the year" % (self._lastBalancing))
logging.info("Batteries balanced %d days ago." % time_unbalanced)
except Exception:
logging.error("Last balancing file read error. Exiting...")
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
# Create the management objects, as specified in the ccgx dbus-api document
self._dbusservice.add_path("/Mgmt/ProcessName", __file__)
self._dbusservice.add_path("/Mgmt/ProcessVersion", "Python " + platform.python_version())
self._dbusservice.add_path("/Mgmt/Connection", "Virtual")
# Create the mandatory objects
self._dbusservice.add_path("/DeviceInstance", 99)
# this product ID was randomly selected - please exchange, if interference with another component
self._dbusservice.add_path("/ProductId", 0xBA44)
self._dbusservice.add_path("/ProductName", "AggregateBatteries")
self._dbusservice.add_path("/FirmwareVersion", VERSION)
self._dbusservice.add_path("/HardwareVersion", VERSION)
self._dbusservice.add_path("/Connected", 1)
# Create DC paths
self._dbusservice.add_path(
"/Dc/0/Voltage",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.2f}V".format(x),
)
self._dbusservice.add_path(
"/Dc/0/Current",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.2f}A".format(x),
)
self._dbusservice.add_path(
"/Dc/0/Power",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.0f}W".format(x),
)
# Create capacity paths
self._dbusservice.add_path("/Soc", None, writeable=True)
self._dbusservice.add_path(
"/Capacity",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.0f}Ah".format(x),
)
self._dbusservice.add_path(
"/InstalledCapacity",
None,
gettextcallback=lambda a, x: "{:.0f}Ah".format(x),
)
self._dbusservice.add_path("/ConsumedAmphours", None, gettextcallback=lambda a, x: "{:.0f}Ah".format(x))
# Create temperature paths
self._dbusservice.add_path("/Dc/0/Temperature", None, writeable=True)
self._dbusservice.add_path("/System/MinCellTemperature", None, writeable=True)
self._dbusservice.add_path("/System/MaxCellTemperature", None, writeable=True)
# Create extras paths
self._dbusservice.add_path(
"/System/MinCellVoltage",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.3f}V".format(x),
)
self._dbusservice.add_path("/System/MinVoltageCellId", None, writeable=True)
self._dbusservice.add_path(
"/System/MaxCellVoltage",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.3f}V".format(x),
)
self._dbusservice.add_path("/System/MaxVoltageCellId", None, writeable=True)
self._dbusservice.add_path("/System/NrOfCellsPerBattery", None, writeable=True)
self._dbusservice.add_path("/System/NrOfModulesOnline", None, writeable=True)
self._dbusservice.add_path("/System/NrOfModulesOffline", None, writeable=True)
self._dbusservice.add_path("/System/NrOfModulesBlockingCharge", None, writeable=True)
self._dbusservice.add_path("/System/NrOfModulesBlockingDischarge", None, writeable=True)
self._dbusservice.add_path(
"/Voltages/Sum",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.3f}V".format(x),
)
self._dbusservice.add_path(
"/Voltages/Diff",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.3f}V".format(x),
)
self._dbusservice.add_path("/TimeToGo", None, writeable=True)
# Create alarm paths
self._dbusservice.add_path("/Alarms/LowVoltage", None, writeable=True)
self._dbusservice.add_path("/Alarms/HighVoltage", None, writeable=True)
self._dbusservice.add_path("/Alarms/LowCellVoltage", None, writeable=True)
# self._dbusservice.add_path('/Alarms/HighCellVoltage', None, writeable=True)
self._dbusservice.add_path("/Alarms/LowSoc", None, writeable=True)
self._dbusservice.add_path("/Alarms/HighChargeCurrent", None, writeable=True)
self._dbusservice.add_path("/Alarms/HighDischargeCurrent", None, writeable=True)
self._dbusservice.add_path("/Alarms/CellImbalance", None, writeable=True)
self._dbusservice.add_path("/Alarms/InternalFailure", None, writeable=True)
self._dbusservice.add_path("/Alarms/HighChargeTemperature", None, writeable=True)
self._dbusservice.add_path("/Alarms/LowChargeTemperature", None, writeable=True)
self._dbusservice.add_path("/Alarms/HighTemperature", None, writeable=True)
self._dbusservice.add_path("/Alarms/LowTemperature", None, writeable=True)
self._dbusservice.add_path("/Alarms/BmsCable", None, writeable=True)
# Create control paths
self._dbusservice.add_path(
"/Info/MaxChargeCurrent",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.1f}A".format(x),
)
self._dbusservice.add_path(
"/Info/MaxDischargeCurrent",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.1f}A".format(x),
)
self._dbusservice.add_path(
"/Info/MaxChargeVoltage",
None,
writeable=True,
gettextcallback=lambda a, x: "{:.2f}V".format(x),
)
self._dbusservice.add_path("/Io/AllowToCharge", None, writeable=True)
self._dbusservice.add_path("/Io/AllowToDischarge", None, writeable=True)
self._dbusservice.add_path("/Io/AllowToBalance", None, writeable=True)
x = Thread(target=self._startMonitor)
x.start()
# wait that Dbus monitor is running else there is no data
while self._dbusMon is None:
tt.sleep(1)
# register VeDbusService after all paths where added
logging.info("### Registering VeDbusService")
self._dbusservice.register()
# search com.victronenergy.settings
GLib.timeout_add_seconds(settings.UPDATE_INTERVAL_FIND_DEVICES, self._find_settings)
# #############################################################################################################
# #############################################################################################################
# ## Starting battery dbus monitor in external thread (otherwise collision with AggregateBatteries service) ###
# #############################################################################################################
# #############################################################################################################
def _startMonitor(self):
logging.info("Starting dbusmonitor...")
self._dbusMon = DbusMon()
logging.info("dbusmonitor started")
# ####################################################################
# ####################################################################
# ## search Settings, to maintain CCL during dynamic CVL reduction ###
# https://www.victronenergy.com/upload/documents/Cerbo_GX/140558-CCGX__Venus_GX__Cerbo_GX__Cerbo-S_GX_Manual-pdf-en.pdf, P72 # noqa: E501
# ####################################################################
# ####################################################################
def _find_settings(self):
logging.info("Searching Settings: Trial Nr. %d" % self._searchTrials)
try:
for service in self._dbusConn.list_names():
if "com.victronenergy.settings" in service:
self._settings = service
logging.info("|- com.victronenergy.settings found")
except Exception:
(
exception_type,
exception_object,
exception_traceback,
) = sys.exc_info()
file = exception_traceback.tb_frame.f_code.co_filename
line = exception_traceback.tb_lineno
logging.debug(f"Exception occurred: {repr(exception_object)} of type {exception_type} in {file} line #{line}")
pass
if self._settings is not None:
self._searchTrials = 1
# search batteries on DBus if present
GLib.timeout_add_seconds(settings.UPDATE_INTERVAL_FIND_DEVICES, self._find_batteries)
# all OK, stop calling this function
return False
elif self._searchTrials < settings.SEARCH_TRIALS:
self._searchTrials += 1
# next trial
return True
else:
logging.error("com.victronenergy.settings not found. Exiting...")
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
# #####################################################################
# #####################################################################
# ## search physical batteries and optional SmartShunts on DC loads ###
# #####################################################################
# #####################################################################
def _find_batteries(self):
self._batteries_dict = {}
# SmartShunt list - will be populated so battery category SmartShunts are at the beginning of the list
self._smartShunt_list = []
# no SmartShunts in the battery category have been found yet
self._num_battery_shunts = 0
batteriesCount = 0
# the following two variables are used when self._ownCharge (read from
# the charge file), is negative
# to accumulate the SoC of the aggregated batteries from their BMSes
Soc = 0
# to accumulate the overall capacity of the aggregated batteries from their BMSes
InstalledCapacity = 0
##################################################
# Logic to interpret the USE_SMARTSHUNTS setting #
##################################################
use_smartshunts = False
# list to keep track of which SmartShunts have been included to not match the same shunt twice and
# to make sure the correct number is matched
included_smartshunts = []
# need to find >= 0 NR_OF_SMARTSHUNTS
NR_OF_SMARTSHUNTS = 0
if isinstance(settings.USE_SMARTSHUNTS, bool):
# True: use all available SmartShunts, False: don't use any SmartShunt
use_smartshunts = settings.USE_SMARTSHUNTS
elif isinstance(settings.USE_SMARTSHUNTS, (list, tuple)):
# empty list -> don't use any SmartShunt
use_smartshunts = len(settings.USE_SMARTSHUNTS) > 0
if use_smartshunts:
# NR_SMARTSHUNTS is the number of SmartShunts specified by the user
NR_SMARTSHUNTS = len(settings.USE_SMARTSHUNTS)
# initially, no SmartShunt has been found yet
included_smartshunts = [False] * NR_SMARTSHUNTS
productName = ""
# keep track of SmartShunt (user-defined) name as specified by SMARTSHUNT_INSTANCE_NAME_PATH
shuntName = ""
logging.info("Searching batteries: Trial Nr. %d" % self._searchTrials)
# if Dbus monitor not running yet, new trial instead of exception
try:
service_names = [str(name) for name in self._dbusConn.list_names() if "com.victronenergy" in str(name)]
for service in sorted(service_names):
logging.info("|- Dbusmonitor sees: %s" % (service))
# Current device is in Victron "battery" service
battery_service = settings.BATTERY_SERVICE_NAME in service
# Current device is in Victron "dcload" service (i.e. a SmartShunt set to DC metering)
dcload_service = settings.DCLOAD_SERVICE_NAME in service
if battery_service or dcload_service:
productName = self._dbusMon.dbusmon.get_value(service, settings.BATTERY_PRODUCT_NAME_PATH)
shuntName = self._dbusMon.dbusmon.get_value(service, settings.SMARTSHUNT_INSTANCE_NAME_PATH)
if battery_service:
if (productName is not None) and (settings.BATTERY_PRODUCT_NAME in productName):
logging.info(' |- Correct battery product name "%s" found' % productName)
# Custom name, if exists
try:
BatteryName = self._dbusMon.dbusmon.get_value(service, settings.BATTERY_INSTANCE_NAME_PATH)
except Exception:
(
exception_type,
exception_object,
exception_traceback,
) = sys.exc_info()
file = exception_traceback.tb_frame.f_code.co_filename
line = exception_traceback.tb_lineno
logging.debug(f"Exception occurred: {repr(exception_object)} of type {exception_type} in {file} line #{line}")
BatteryName = "Battery%d" % (batteriesCount + 1)
# Check if all batteries have custom names
if BatteryName in self._batteries_dict:
BatteryName = "%s%d" % (BatteryName, batteriesCount + 1)
self._batteries_dict[BatteryName] = service
logging.info(" |- Battery name: %s" % BatteryName)
logging.info(" |- Custom name: %s" % self._dbusMon.dbusmon.get_value(service, "/CustomName"))
logging.info(" |- Product name: %s" % self._dbusMon.dbusmon.get_value(service, "/ProductName"))
batteriesCount += 1
# accumulate battery capacities and Soc if not read from charge file
if self._ownCharge < 0:
battery_capacity = self._dbusMon.dbusmon.get_value(service, "/InstalledCapacity")
battery_soc = self._dbusMon.dbusmon.get_value(service, "/Soc") * battery_capacity
InstalledCapacity += battery_capacity
Soc += battery_soc
logging.info(" |- SoC: %f / %f Ah" % (battery_soc / 100.0, battery_capacity))
# Create voltage paths with battery names
if settings.SEND_CELL_VOLTAGES == 1:
for cellId in range(1, (settings.NR_OF_CELLS_PER_BATTERY) + 1):
self._dbusservice.add_path(
"/Voltages/%s_Cell%d"
% (
re.sub("[^A-Za-z0-9_]+", "", BatteryName),
cellId,
),
None,
writeable=True,
gettextcallback=lambda a, x: "{:.3f}V".format(x),
)
# Check if Nr. of cells is equal
if self._dbusMon.dbusmon.get_value(service, "/System/NrOfCellsPerBattery") != settings.NR_OF_CELLS_PER_BATTERY:
logging.error(" |- Number of battery cells does not match config:")
logging.error(
" |- Cells found in battery: %d" % (self._dbusMon.dbusmon.get_value(service, "/System/NrOfCellsPerBattery"))
)
logging.error(" |- Cells specified in config file: %d" % (settings.NR_OF_CELLS_PER_BATTERY))
logging.error("Exiting...")
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
# end of section
##########################################################
# Find SmartShunts in either Battery or DC Load services #
##########################################################
if battery_service or dcload_service:
# if SmartShunt found, can be used for battery monitoring or DC load current
# depending on how it is set
if (productName is not None) and (settings.SMARTSHUNT_NAME_KEYWORD in productName):
shunt_vrm_id = self._dbusMon.dbusmon.get_value(service, "/DeviceInstance")
logging.info(' |- Correct SmartShunt product name "%s" found' % productName)
# user specified to use SmartShunts
if use_smartshunts:
# if USE_SMARTSHUNTS is set to `True` and not a list, the conditional below won't
# run and every SmartShunt is included
include_shunt = True
# user-specified list of SmartShunts
if isinstance(settings.USE_SMARTSHUNTS, (list, tuple)):
# go over user-list and see if we can match current shunt
for shunt_id in range(0, len(settings.USE_SMARTSHUNTS)):
# already included, move along
if included_smartshunts[shunt_id]:
continue
# match by VRM Id
if isinstance(settings.USE_SMARTSHUNTS[shunt_id], int):
include_shunt = settings.USE_SMARTSHUNTS[shunt_id] == shunt_vrm_id
# match by shuntName (as specified in the SMARTSHUNT_INSTANCE_NAME_PATH field)
elif isinstance(settings.USE_SMARTSHUNTS[shunt_id], str):
include_shunt = settings.USE_SMARTSHUNTS[shunt_id] == shuntName
# Bail out with an error if list entry is neither string integer nor string
else:
logging.error(
' |- Bad element #%d in "%s" in USE_SMARTSHUNTS list. Entries need to be '
+ " VRM instancmbers or Name strings. Exiting...",
shunt_id + 1,
settings.USE_SMARTSHUNTS[shunt_id],
)
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
# if a shunt has been matched as one the user defined and we haven't included it
# yet, we can get out of this loop
if include_shunt:
break
# SmartShunt is added to list
if include_shunt:
# battery SmartShunts are inserted at the end of the battery part of the list
if battery_service:
self._smartShunt_list.insert(self._num_battery_shunts, service)
self._num_battery_shunts += 1
# dcload SmartShunts get added to the end of the list
# (which is the end of the dcload part of the list)
else:
self._smartShunt_list.append(service)
logging.info(
" |- %s [%d] added, named as: %s."
% (
productName,
shunt_vrm_id,
shuntName,
)
)
# end of SmartShunt detection (AT, 2025)
except Exception:
(
exception_type,
exception_object,
exception_traceback,
) = sys.exc_info()
file = exception_traceback.tb_frame.f_code.co_filename
line = exception_traceback.tb_lineno
logging.debug(f"Exception occurred: {repr(exception_object)} of type {exception_type} in {file} line #{line}")
pass
# when SmartShunts have been found, add their overall number in addition to
# the number of batteries aggregated to the log output
if len(self._smartShunt_list) > 0:
logging.info(
"%d batteries and %d SmartShunts found"
% (
batteriesCount,
len(self._smartShunt_list),
)
)
else:
logging.info("> %d batteries found." % (batteriesCount))
# make sure the correct number of batteries and SmartShunts has been found
if (batteriesCount == settings.NR_OF_BATTERIES) and (len(self._smartShunt_list) >= NR_OF_SMARTSHUNTS):
if self._ownCharge < 0:
self._ownCharge = Soc / 100.0
Soc /= InstalledCapacity
if settings.CURRENT_FROM_VICTRON:
self._searchTrials = 1
# if current from Victron stuff search multi/quattro on DBus
GLib.timeout_add_seconds(settings.UPDATE_INTERVAL_FIND_DEVICES, self._find_multis)
else:
self._timeOld = tt.time()
# if current from BMS start the _update loop
GLib.timeout_add_seconds(settings.UPDATE_INTERVAL_DATA, self._update)
# all OK, stop calling this function
return False
# if the correct number has not been found yet, repeat until SEARCH_TRIALS is reached
elif self._searchTrials < settings.SEARCH_TRIALS:
self._searchTrials += 1
# next trial
return True
# bail out if correct number of batteries and SmartShunts can not be found after SEARCH_TRIALS tries
else:
if NR_OF_SMARTSHUNTS > 0:
logging.error(
"Required nr of batteries (%d) or SmartShunts (%d) not found. Exiting...",
settings.NR_OF_BATTERIES,
NR_OF_SMARTSHUNTS,
)
else:
logging.info(self._batteries_dict)
logging.error("Required number of batteries not found. Exiting...")
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
# #########################################################################
# #########################################################################
# ## search Multis or Quattros (if selected for DC current measurement) ###
# #########################################################################
# #########################################################################
def _find_multis(self):
# only search for MultiPlus/Quattro devices if that is specified, possible use-cases:
# - no MultiPlus/Quattro device installed (examples: a pure DC system, a different inverter/charger is used)
# - current detection of MultiPlus/Quattro is not wanted (i.e. SmartShunts are used instead)
# may still want to aggregate their batteries when using no inverter/no Victron inverter/charger)
if len(settings.MULTI_KEYWORD) > 0:
logging.info("Searching MultiPlus/Quattro VEbus: Trial Nr. %d" % self._searchTrials)
try:
for service in self._dbusConn.list_names():
if settings.MULTI_KEYWORD in service:
self._multi = service
logging.info("|- %s found." % ((self._dbusMon.dbusmon.get_value(service, "/ProductName")),))
except Exception:
(
exception_type,
exception_object,
exception_traceback,
) = sys.exc_info()
file = exception_traceback.tb_frame.f_code.co_filename
line = exception_traceback.tb_lineno
logging.debug(f"Exception occurred: {repr(exception_object)} of type {exception_type} in {file} line #{line}")
pass
logging.info("> 1 MultiPlus/Quattro found.")
if self._multi is None:
if self._searchTrials < settings.SEARCH_TRIALS:
self._searchTrials += 1
# next trial
return True
else:
logging.error("Multi/Quattro not found. Exiting...")
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
if settings.NR_OF_MPPTS > 0:
self._searchTrials = 1
# search MPPTs on DBus if present
GLib.timeout_add_seconds(settings.UPDATE_INTERVAL_FIND_DEVICES, self._find_mppts)
else:
self._timeOld = tt.time()
# if no MPPTs start the _update loop
GLib.timeout_add_seconds(settings.UPDATE_INTERVAL_DATA, self._update)
# all OK, stop calling this function
return False
# ############################################################
# ############################################################
# ## search MPPTs (if selected for DC current measurement) ###
# ############################################################
# ############################################################
def _find_mppts(self):
self._mppts_list = []
mpptsCount = 0
logging.info("Searching MPPT(s): Trial Nr. %d" % self._searchTrials)
try:
for service in self._dbusConn.list_names():
if settings.MPPT_KEYWORD in service:
self._mppts_list.append(service)
logging.info("|- %s found." % ((self._dbusMon.dbusmon.get_value(service, "/ProductName")),))
mpptsCount += 1
except Exception:
(
exception_type,
exception_object,
exception_traceback,
) = sys.exc_info()
file = exception_traceback.tb_frame.f_code.co_filename
line = exception_traceback.tb_lineno
logging.debug(f"Exception occurred: {repr(exception_object)} of type {exception_type} in {file} line #{line}")
pass
logging.info("> %d MPPT(s) found." % (mpptsCount))
if mpptsCount == settings.NR_OF_MPPTS:
self._timeOld = tt.time()
GLib.timeout_add_seconds(settings.UPDATE_INTERVAL_DATA, self._update)
# all OK, stop calling this function
return False
elif self._searchTrials < settings.SEARCH_TRIALS:
self._searchTrials += 1
# next trial
return True
else:
logging.error("Required number of MPPTs not found. Exiting...")
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
# #################################################################################
# #################################################################################
# ### aggregate values of physical batteries, perform calculations, update Dbus ###
# #################################################################################
# #################################################################################
def _update(self):
# DC
Voltage = 0
Current = 0
Power = 0
# Capacity
Soc = 0
Capacity = 0
InstalledCapacity = 0
ConsumedAmphours = 0
TimeToGo = 0
# Temperature
Temperature = 0
# list, maxima of all physical batteries
MaxCellTemp_list = []
# list, minima of all physical batteries
MinCellTemp_list = []
# Extras
cellVoltages_dict = {}
# dictionary {'ID' : MaxCellVoltage, ... } for all physical batteries
MaxCellVoltage_dict = {}
# dictionary {'ID' : MinCellVoltage, ... } for all physical batteries
MinCellVoltage_dict = {}
NrOfModulesOnline = 0
NrOfModulesOffline = 0
NrOfModulesBlockingCharge = 0
NrOfModulesBlockingDischarge = 0
# battery voltages from sum of cells
VoltagesSum_dict = {}
chargeVoltageReduced_list = []
# Alarms
# lists to find maxima
LowVoltage_alarm_list = []
HighVoltage_alarm_list = []
LowCellVoltage_alarm_list = []
LowSoc_alarm_list = []
HighChargeCurrent_alarm_list = []
HighDischargeCurrent_alarm_list = []
CellImbalance_alarm_list = []
InternalFailure_alarm_list = []
HighChargeTemperature_alarm_list = []
LowChargeTemperature_alarm_list = []
HighTemperature_alarm_list = []
LowTemperature_alarm_list = []
BmsCable_alarm_list = []
# Charge/discharge parameters
# the minimum of MaxChargeCurrent * NR_OF_BATTERIES to be transmitted
MaxChargeCurrent_list = []
# the minimum of MaxDischargeCurrent * NR_OF_BATTERIES to be transmitted
MaxDischargeCurrent_list = []
# if some cells are above MAX_CELL_VOLTAGE, store here the sum of differences for each battery
MaxChargeVoltage_list = []
# minimum of all to be transmitted
AllowToCharge_list = []
# minimum of all to be transmitted
AllowToDischarge_list = []
# minimum of all to be transmitted
AllowToBalance_list = []
# Bulk, Absorption, Float, Keep always max voltage
ChargeMode_list = []
####################################################
# Get DBus values from all SerialBattery instances #
####################################################
try:
for i in self._batteries_dict:
# DC
# to detect error
step = "Read V, I, P"
Voltage += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Dc/0/Voltage")
Current += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Dc/0/Current")
Power += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Dc/0/Power")
# Capacity
step = "Read and calculate capacity, SoC, Time to go"
InstalledCapacity += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/InstalledCapacity")
if not settings.OWN_SOC:
ConsumedAmphours += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/ConsumedAmphours")
Capacity += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Capacity")
Soc += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Soc") * self._dbusMon.dbusmon.get_value(
self._batteries_dict[i], "/InstalledCapacity"
)
ttg = self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/TimeToGo")
if (ttg is not None) and (TimeToGo is not None):
TimeToGo += ttg * self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/InstalledCapacity")
else:
TimeToGo = None
# Temperature
step = "Read temperatures"
Temperature += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Dc/0/Temperature")
MaxCellTemp_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/MaxCellTemperature"))
MinCellTemp_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/MinCellTemperature"))
# Cell voltages
# cell ID : its voltage
step = "Read max. and min cell voltages and voltage sum"
MaxCellVoltage_dict[
"%s_%s"
% (
i,
self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/MaxVoltageCellId"),
)
] = self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/MaxCellVoltage")
MinCellVoltage_dict[
"%s_%s"
% (
i,
self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/MinVoltageCellId"),
)
] = self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/MinCellVoltage")
# here an exception is raised and new read trial initiated if None is on Dbus
volt_sum_get = self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Voltages/Sum")
if volt_sum_get is not None:
VoltagesSum_dict[i] = volt_sum_get
else:
raise TypeError(
f"Battery {i} returns None value of /Voltages/Sum. Please check, if the setting "
+ "'BATTERY_CELL_DATA_FORMAT=1' in dbus-serialbattery config"
)
# Battery state
step = "Read battery state"
NrOfModulesOnline += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/NrOfModulesOnline")
NrOfModulesOffline += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/NrOfModulesOffline")
NrOfModulesBlockingCharge += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/NrOfModulesBlockingCharge")
# sum of modules blocking discharge
NrOfModulesBlockingDischarge += self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/System/NrOfModulesBlockingDischarge")
step = "Read cell voltages"
for j in range(settings.NR_OF_CELLS_PER_BATTERY):
cellVoltages_dict["%s_Cell%d" % (i, j + 1)] = self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Voltages/Cell%d" % (j + 1))
# Alarms
step = "Read alarms"
LowVoltage_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/LowVoltage"))
HighVoltage_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/HighVoltage"))
LowCellVoltage_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/LowCellVoltage"))
LowSoc_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/LowSoc"))
HighChargeCurrent_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/HighChargeCurrent"))
HighDischargeCurrent_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/HighDischargeCurrent"))
CellImbalance_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/CellImbalance"))
InternalFailure_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/InternalFailure_alarm"))
HighChargeTemperature_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/HighChargeTemperature"))
LowChargeTemperature_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/LowChargeTemperature"))
HighTemperature_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/HighTemperature"))
LowTemperature_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/LowTemperature"))
BmsCable_alarm_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Alarms/BmsCable"))
# calculate reduction of charge voltage as sum of overvoltages of all cells
if settings.OWN_CHARGE_PARAMETERS:
step = "Calculate CVL reduction"
cellOvervoltage = 0
for j in range(settings.NR_OF_CELLS_PER_BATTERY):
cellVoltage = self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Voltages/Cell%d" % (j + 1))
if cellVoltage > settings.MAX_CELL_VOLTAGE:
cellOvervoltage += cellVoltage - settings.MAX_CELL_VOLTAGE
chargeVoltageReduced_list.append(VoltagesSum_dict[i] - cellOvervoltage)
# Aggregate charge/discharge parameters
else:
step = "Read charge parameters"
# list of max. charge currents to find minimum
MaxChargeCurrent_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Info/MaxChargeCurrent"))
# list of max. discharge currents to find minimum
MaxDischargeCurrent_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Info/MaxDischargeCurrent"))
# list of max. charge voltages to find minimum
MaxChargeVoltage_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Info/MaxChargeVoltage"))
# list of charge modes of batteries (Bulk, Absorption, Float, Keep always max voltage)
ChargeMode_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Info/ChargeMode"))
step = "Read Allow to"
# list of AllowToCharge to find minimum
AllowToCharge_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Io/AllowToCharge"))
# list of AllowToDischarge to find minimum
AllowToDischarge_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Io/AllowToDischarge"))
# list of AllowToBalance to find minimum
AllowToBalance_list.append(self._dbusMon.dbusmon.get_value(self._batteries_dict[i], "/Io/AllowToBalance"))
step = "Find max. and min. cell voltage of all batteries"
# placed in try-except structure for the case if some values are of None.
# The _max() and _min() don't work with dictionaries
MaxVoltageCellId = max(MaxCellVoltage_dict, key=MaxCellVoltage_dict.get)
MaxCellVoltage = MaxCellVoltage_dict[MaxVoltageCellId]
MinVoltageCellId = min(MinCellVoltage_dict, key=MinCellVoltage_dict.get)
MinCellVoltage = MinCellVoltage_dict[MinVoltageCellId]
except Exception:
(
exception_type,
exception_object,
exception_traceback,
) = sys.exc_info()
file = exception_traceback.tb_frame.f_code.co_filename
line = exception_traceback.tb_lineno
locals_at_error = exception_traceback.tb_frame.f_locals
logging.error(f"Exception occurred: {repr(exception_object)} of type {exception_type} in {file} line #{line}")
logging.error(f"Local variables at error: {locals_at_error}")
logging.error("Occured during step %s, Battery %s." % (step, i))
logging.error("Read trial nr. %d" % self._readTrials)
self._readTrials += 1
if self._readTrials > settings.READ_TRIALS:
logging.error("DBus read failed. Exiting...")
tt.sleep(settings.TIME_BEFORE_RESTART)
sys.exit(1)
else:
# next call allowed
return True
#####################################################
# Process collected values (except of dictionaries) #
#####################################################
# averaging
Voltage = Voltage / settings.NR_OF_BATTERIES
Temperature = Temperature / settings.NR_OF_BATTERIES
VoltagesSum = sum(VoltagesSum_dict.values()) / settings.NR_OF_BATTERIES
# find max and min cell temperature (have no ID)
MaxCellTemp = self._fn._max(MaxCellTemp_list)
MinCellTemp = self._fn._min(MinCellTemp_list)
# find max in alarms
LowVoltage_alarm = self._fn._max(LowVoltage_alarm_list)
HighVoltage_alarm = self._fn._max(HighVoltage_alarm_list)
LowCellVoltage_alarm = self._fn._max(LowCellVoltage_alarm_list)
LowSoc_alarm = self._fn._max(LowSoc_alarm_list)
HighChargeCurrent_alarm = self._fn._max(HighChargeCurrent_alarm_list)
HighDischargeCurrent_alarm = self._fn._max(HighDischargeCurrent_alarm_list)
CellImbalance_alarm = self._fn._max(CellImbalance_alarm_list)
InternalFailure_alarm = self._fn._max(InternalFailure_alarm_list)
HighChargeTemperature_alarm = self._fn._max(HighChargeTemperature_alarm_list)
LowChargeTemperature_alarm = self._fn._max(LowChargeTemperature_alarm_list)
HighTemperature_alarm = self._fn._max(HighTemperature_alarm_list)
LowTemperature_alarm = self._fn._max(LowTemperature_alarm_list)
BmsCable_alarm = self._fn._max(BmsCable_alarm_list)
# find max. charge voltage (if needed)
if not settings.OWN_CHARGE_PARAMETERS:
if settings.KEEP_MAX_CVL and any("Float" in item for item in ChargeMode_list):
MaxChargeVoltage = self._fn._max(MaxChargeVoltage_list)
else:
MaxChargeVoltage = self._fn._min(MaxChargeVoltage_list)
MaxChargeCurrent = self._fn._min(MaxChargeCurrent_list) * settings.NR_OF_BATTERIES
MaxDischargeCurrent = self._fn._min(MaxDischargeCurrent_list) * settings.NR_OF_BATTERIES
AllowToCharge = self._fn._min(AllowToCharge_list)
AllowToDischarge = self._fn._min(AllowToDischarge_list)
AllowToBalance = self._fn._min(AllowToBalance_list)
####################################
# Measure current by Victron stuff #
####################################
if settings.CURRENT_FROM_VICTRON:
success = True
# variable to accumulate currents measured by Victron stuff (i.e. MultiPlus/Quattro, SmartShunts, MPPTs)
Current_VE = 0
try:
# Read MultiPlus/Quattro data only when one is used and has been found
# MultiPlus/Quattro `Connected` value will go to 0 if it exists but is switch off (VE-BUS remains connected)
# by the user (either via Digital Multi Control, Cerbo, VRM, or the device itself)
if self._multi is not None:
Multi_Connected = self._dbusMon.dbusmon.get_value(self._multi, "/Connected")
# Read current only when MultiPlus/Quattro is connected
if Multi_Connected > 0:
# get DC current of multiPlus/quattro (or system of them)
Current_VE = self._dbusMon.dbusmon.get_value(self._multi, "/Dc/0/Current")
# Output to log that MultiPlus/Quattro is connected again
if not self._multi_connected:
logging.info("MultiPlus/Quattro is connected")
self._multi_connected = True # keep track of state to notice if state changes at next round
else:
# Output to log when MultiPlus/Quattro state changed from connected (at last read) to not connected
if self._multi_connected:
logging.info("MultiPlus/Quattro is not connected")
self._multi_connected = False # keep track of state to notice if state changes at next round
for i in range(settings.NR_OF_MPPTS):
# add DC current of all MPPTs (if present)
Current_VE += self._dbusMon.dbusmon.get_value(self._mppts_list[i], "/Dc/0/Current")
except Exception:
(
exception_type,