-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdbus-aggregate-smartshunts.py
More file actions
1881 lines (1595 loc) · 100 KB
/
dbus-aggregate-smartshunts.py
File metadata and controls
1881 lines (1595 loc) · 100 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 Victron SmartShunts into a single virtual battery monitor.
Designed for parallel battery banks where each battery has its own SmartShunt.
Combines current, voltage, and SoC readings to present a unified battery to the system.
Author: Based on dbus-aggregate-batteries by Dr-Gigavolt
License: MIT
"""
from gi.repository import GLib
import logging
import sys
import os
import platform
import dbus
import time as tt
from datetime import datetime as dt
# Add ext folder to sys.path
sys.path.insert(1, os.path.join(os.path.dirname(__file__), "ext", "velib_python"))
from vedbus import VeDbusService
from dbusmonitor import DbusMonitor
from settingsdevice import SettingsDevice
VERSION = "1.0.0"
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():
return SessionBus() if "DBUS_SESSION_BUS_ADDRESS" in os.environ else SystemBus()
class DbusAggregateSmartShunts:
def __init__(self, config, servicename="com.victronenergy.battery.aggregateshunts"):
self.config = config
self._shunts = []
self._dbusConn = get_bus()
self._searchTrials = 1
self._readTrials = 1
# Track if we're in the middle of an update to prevent recursion
self._updating = False
# Exponential backoff for device discovery
self._device_search_interval = config['UPDATE_INTERVAL_FIND_DEVICES'] # Current interval
self._initial_search_interval = config['UPDATE_INTERVAL_FIND_DEVICES'] # Store initial
self._max_search_interval = config['MAX_UPDATE_INTERVAL_FIND_DEVICES'] # Max interval
self._devices_stable_since = None # Track when devices became stable
self._last_device_count = 0 # Track device count changes
# Flag to track if we've already logged TTG divergence warning (only log once per session)
self._ttg_divergence_logged = False
# Switch management for discovered shunts
self.discovery_enabled = True # Default to enabled (may be overridden below)
self.shunt_switches = {} # Maps service_name -> {'relay_id': str, 'enabled': bool}
# Early load of discovery setting (before switches are created)
# This ensures discovery_enabled is correct before _find_smartshunts runs
try:
settings_obj = self._dbusConn.get_object('com.victronenergy.settings',
'/Settings/Devices/aggregateshunts_AGGREGATE01/DiscoveryEnabled')
settings_iface = dbus.Interface(settings_obj, 'com.victronenergy.BusItem')
saved_discovery = settings_iface.GetValue()
if saved_discovery is not None:
self.discovery_enabled = bool(saved_discovery)
logging.info(f"Early load: discovery_enabled = {self.discovery_enabled}")
except Exception as e:
logging.debug(f"No saved discovery setting found (fresh install): {e}")
logging.info("### Initializing VeDbusService")
self._dbusservice = VeDbusService(servicename, self._dbusConn, register=False)
# Create management objects
self._dbusservice.add_path("/Mgmt/ProcessName", __file__)
self._dbusservice.add_path("/Mgmt/ProcessVersion", "Python " + platform.python_version())
self._dbusservice.add_path("/Mgmt/Connection", "Virtual SmartShunt Aggregator")
# Find an available device instance (check what's already in use)
device_instance = self._find_available_device_instance()
logging.info(f"### Using device instance: {device_instance}")
# Create mandatory objects
self._dbusservice.add_path("/DeviceInstance", device_instance)
# Use ProductId and ProductName from first physical shunt (for VRM compatibility)
# This ensures VRM recognizes the aggregate as the same type of device
product_id = config.get('PRODUCT_ID', 0xA389) # Default to SmartShunt if not found
product_name = config.get('PRODUCT_NAME', 'SmartShunt 500A/50mV') # Default to common SmartShunt model
# CustomName can be overridden in config, but ProductName should match physical shunt
custom_name = config['DEVICE_NAME'] if config['DEVICE_NAME'] else "SmartShunt Aggregate"
self._dbusservice.add_path("/ProductId", product_id,
gettextcallback=lambda a, x: f"0x{x:X}" if x and isinstance(x, int) else "")
self._dbusservice.add_path("/ProductName", product_name)
# Mirror firmware version from first physical shunt (must be integer like physical shunts)
self._dbusservice.add_path("/FirmwareVersion", config['FIRMWARE_VERSION_INT'])
# Hardware version: physical SmartShunts don't have one (empty), so we shouldn't either
self._dbusservice.add_path("/HardwareVersion", [],
gettextcallback=lambda a, x: "")
self._dbusservice.add_path("/Connected", 1)
self._dbusservice.add_path("/Serial", "AGGREGATE01")
self._dbusservice.add_path("/CustomName", custom_name)
# Create DC paths
self._dbusservice.add_path("/Dc/0/Voltage", None, writeable=True,
gettextcallback=lambda a, x: "{:.2f}V".format(x) if x is not None else "")
self._dbusservice.add_path("/Dc/0/Current", None, writeable=True,
gettextcallback=lambda a, x: "{:.2f}A".format(x) if x is not None else "")
self._dbusservice.add_path("/Dc/0/Power", None, writeable=True,
gettextcallback=lambda a, x: "{:.0f}W".format(x) if x is not None else "")
self._dbusservice.add_path("/Dc/0/Temperature", None, writeable=True,
gettextcallback=lambda a, x: "{:.0f}C".format(x) if x is not None else "")
# Create capacity paths
# Initialize with None - will be populated by _update() before registration
# GetText returns "--" for None to avoid showing "0%" during startup
self._dbusservice.add_path("/Soc", None, writeable=True,
gettextcallback=lambda a, x: "{:.1f}%".format(x) if x is not None else "--")
# Note: /Capacity and /InstalledCapacity are NOT included - these are BMS-specific paths
# Physical SmartShunts don't expose these paths
# For BMS functionality with these paths, use dbus-smartshunt-to-bms project
self._dbusservice.add_path("/ConsumedAmphours", None,
gettextcallback=lambda a, x: "{:.1f}Ah".format(x) if x is not None else "")
self._dbusservice.add_path("/TimeToGo", None, writeable=True,
gettextcallback=lambda a, x: "{:.0f}s".format(x) if x is not None and x != [] else "")
# Pure SmartShunt monitoring only - no charge control paths
# For BMS functionality (CVL/CCL/DCL, AllowToCharge/Discharge), use dbus-smartshunt-to-bms project
logging.info("Monitor mode only - no charge control (pure SmartShunt aggregation)")
# Alarms (pass through from physical shunts)
self._dbusservice.add_path("/Alarms/Alarm", None, writeable=True)
self._dbusservice.add_path("/Alarms/LowVoltage", None, writeable=True)
self._dbusservice.add_path("/Alarms/HighVoltage", None, writeable=True)
self._dbusservice.add_path("/Alarms/LowSoc", 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/MidVoltage", 0)
self._dbusservice.add_path("/Alarms/LowStarterVoltage", 0)
self._dbusservice.add_path("/Alarms/HighStarterVoltage", 0)
# History data (aggregated from physical shunts)
self._dbusservice.add_path("/History/ChargeCycles", None, writeable=True)
self._dbusservice.add_path("/History/TotalAhDrawn", None, writeable=True,
gettextcallback=lambda a, x: "{:.1f}Ah".format(x) if x is not None else "")
self._dbusservice.add_path("/History/MinimumVoltage", None, writeable=True,
gettextcallback=lambda a, x: "{:.2f}V".format(x) if x is not None else "")
self._dbusservice.add_path("/History/MaximumVoltage", None, writeable=True,
gettextcallback=lambda a, x: "{:.2f}V".format(x) if x is not None else "")
self._dbusservice.add_path("/History/TimeSinceLastFullCharge", None, writeable=True,
gettextcallback=lambda a, x: "{:.0f}s".format(x) if x is not None else "")
self._dbusservice.add_path("/History/AutomaticSyncs", None, writeable=True)
self._dbusservice.add_path("/History/LowVoltageAlarms", None, writeable=True)
self._dbusservice.add_path("/History/HighVoltageAlarms", None, writeable=True)
self._dbusservice.add_path("/History/LastDischarge", None, writeable=True,
gettextcallback=lambda a, x: "{:.1f}Ah".format(x) if x is not None else "")
self._dbusservice.add_path("/History/AverageDischarge", None, writeable=True,
gettextcallback=lambda a, x: "{:.1f}Ah".format(x) if x is not None else "")
self._dbusservice.add_path("/History/ChargedEnergy", None, writeable=True,
gettextcallback=lambda a, x: "{:.2f}kWh".format(x) if x is not None else "")
self._dbusservice.add_path("/History/DischargedEnergy", None, writeable=True,
gettextcallback=lambda a, x: "{:.2f}kWh".format(x) if x is not None else "")
self._dbusservice.add_path("/History/FullDischarges", None, writeable=True)
self._dbusservice.add_path("/History/DeepestDischarge", None, writeable=True,
gettextcallback=lambda a, x: "{:.1f}Ah".format(x) if x is not None else "")
def _empty_or_value_str(a, x):
"""Return empty string for None or empty arrays/lists, otherwise stringify"""
logging.debug(f"_empty_or_value_str called with: type={type(x)}, value={x}, len={len(x) if hasattr(x, '__len__') else 'N/A'}")
if x is None:
return ""
try:
if len(x) == 0:
return ""
except (TypeError, AttributeError):
pass
return str(x)
def _empty_or_value_v(a, x):
"""Return empty string for None or empty arrays/lists, otherwise format as voltage"""
logging.debug(f"_empty_or_value_v called with: type={type(x)}, value={x}")
if x is None:
return ""
try:
if len(x) == 0:
return ""
except (TypeError, AttributeError):
pass
return "{:.2f}V".format(x)
self._dbusservice.add_path("/History/LowStarterVoltageAlarms", [], writeable=True,
gettextcallback=_empty_or_value_str)
self._dbusservice.add_path("/History/HighStarterVoltageAlarms", [], writeable=True,
gettextcallback=_empty_or_value_str)
self._dbusservice.add_path("/History/MinimumStarterVoltage", [], writeable=True,
gettextcallback=_empty_or_value_v)
self._dbusservice.add_path("/History/MaximumStarterVoltage", [], writeable=True,
gettextcallback=_empty_or_value_v)
# Settings flags
self._dbusservice.add_path("/Settings/HasTemperature", 1)
self._dbusservice.add_path("/Settings/HasStarterVoltage", 0)
self._dbusservice.add_path("/Settings/HasMidVoltage", 0)
self._dbusservice.add_path("/Settings/RelayMode", [],
gettextcallback=lambda a, x: "")
# Group ID (not used for aggregate)
self._dbusservice.add_path("/GroupId", [],
gettextcallback=lambda a, x: "")
# Relay state (not used for aggregate, but for compatibility)
self._dbusservice.add_path("/Relay/0/State", [],
gettextcallback=lambda a, x: "")
# Additional DC paths for compatibility
self._dbusservice.add_path("/Dc/0/MidVoltage", [],
gettextcallback=lambda a, x: "")
self._dbusservice.add_path("/Dc/0/MidVoltageDeviation", [],
gettextcallback=lambda a, x: "")
self._dbusservice.add_path("/Dc/1/Voltage", [],
gettextcallback=lambda a, x: "")
# Initialize D-Bus monitor
logging.info("### Starting D-Bus monitor")
self._init_dbusmonitor()
# Note: /InstalledCapacity is NOT set - this is a BMS-specific path
# Physical SmartShunts don't expose this path
# For BMS functionality, use dbus-smartshunt-to-bms project
# Track created device paths for cleanup
self._device_paths = {} # {instance: [list of paths]}
# Create /Devices/0/* paths for the aggregate itself (like physical shunts do)
self._dbusservice.add_path("/Devices/0/CustomName", custom_name)
self._dbusservice.add_path("/Devices/0/DeviceInstance", device_instance) # Use same instance as main device
# Use firmware version from first detected shunt (integer format)
self._dbusservice.add_path("/Devices/0/FirmwareVersion",
config.get('FIRMWARE_VERSION_INT'),
gettextcallback=lambda a, x: f"v{(x >> 8) & 0xFF}.{x & 0xFF:x}" if x and isinstance(x, int) else "")
self._dbusservice.add_path("/Devices/0/ProductId", product_id,
gettextcallback=lambda a, x: f"0x{x:X}" if x and isinstance(x, int) else "")
self._dbusservice.add_path("/Devices/0/ProductName", f"{product_name} (Aggregate)")
self._dbusservice.add_path("/Devices/0/ServiceName", "com.victronenergy.battery.aggregateshunts")
self._dbusservice.add_path("/Devices/0/VregLink", [],
gettextcallback=lambda a, x: "")
# Flag to identify this as a virtual aggregate (so dbus-smartshunt-to-bms can exclude it)
self._dbusservice.add_path("/Devices/0/Virtual", 1)
# Create /VEDirect/* paths to aggregate communication errors from all shunts
self._dbusservice.add_path("/VEDirect/HexChecksumErrors", None)
self._dbusservice.add_path("/VEDirect/HexInvalidCharacterErrors", None)
self._dbusservice.add_path("/VEDirect/HexUnfinishedErrors", None)
self._dbusservice.add_path("/VEDirect/TextChecksumErrors", None)
self._dbusservice.add_path("/VEDirect/TextParseError", None)
self._dbusservice.add_path("/VEDirect/TextUnfinishedErrors", None)
# Store device_instance for later registration
self._device_instance = device_instance
# Add master discovery switch (relay_discovery)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Name', '* SmartShunt Discovery')
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Type', 1) # Toggle switch
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/State', 1,
writeable=True, onchangecallback=self._on_discovery_changed)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Status', 0x00)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Current', 0)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Settings/CustomName', '', writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Settings/Type', 1, writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Settings/ValidTypes', 2)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Settings/Function', 2, writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Settings/ValidFunctions', 4)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Settings/Group', '', writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Settings/ShowUIControl', 1, writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_discovery/Settings/PowerOnState', 1)
# Add temperature threshold switches (using reserved relay IDs)
# Defaults: 50°F (10°C) for cold limit, 106°F (41°C) for hot limit
# Note: GUI slider is hardcoded 1-100, so we map slider values to actual temperature range:
# - Cold slider: 1-100 maps to -10°C to 89°C (99°C range = exactly 1°C per slider step)
# - Hot slider: 1-100 maps to 0°C to 99°C (99°C range = exactly 1°C per slider step)
DEFAULT_TEMP_LOW = 10.0 # 50°F / 10°C
DEFAULT_TEMP_HIGH = 41.0 # ~106°F / 41°C
# Temperature range constants - separate ranges for cold and hot
# Cold: -10°C to 89°C (slider 1=-10°C, slider 100=89°C)
# Hot: 0°C to 99°C (slider 1=0°C, slider 100=99°C)
self._temp_low_min = -10.0 # Cold slider minimum
self._temp_low_max = 89.0 # Cold slider maximum
self._temp_high_min = 0.0 # Hot slider minimum
self._temp_high_max = 99.0 # Hot slider maximum
# Convert default temperatures to slider positions (1-100 range)
initial_low_slider = self._temp_to_slider_low(DEFAULT_TEMP_LOW)
initial_high_slider = self._temp_to_slider_high(DEFAULT_TEMP_HIGH)
# Low temp threshold (relay_temp_low)
# Note: Using Type 2 (Dimmable/PWM) because GUI only displays Types 0, 1, and 2 in switches pane
# GUI slider is hardcoded 1-100, so DimmingMin/Max are informational only
# Initial display name with both C and F
initial_low_f = DEFAULT_TEMP_LOW * 9/5 + 32
self._default_temp_low = DEFAULT_TEMP_LOW
self._default_temp_low_slider = initial_low_slider
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Name', f'Cold Limit: {DEFAULT_TEMP_LOW:.0f}°C / {initial_low_f:.0f}°F')
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Type', 2) # Dimmable
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/State', 1, writeable=True,
onchangecallback=self._on_temp_low_state_changed)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Status', 0x09, writeable=True) # On status (no badge)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Current', 0)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Dimming', initial_low_slider,
writeable=True, onchangecallback=self._on_temp_low_changed)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Measurement', DEFAULT_TEMP_LOW, writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/CustomName', '', writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/Type', 2, writeable=False)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/ValidTypes', 4) # Only dimmable (bit 2)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/Function', 2, writeable=True) # Manual
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/ValidFunctions', 4) # Bit 2 = Manual only
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/Group', '', writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/PowerOnState', 1)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/DimmingMin', 1.0) # Slider min (= 0°C)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/DimmingMax', 100.0) # Slider max (= 99°C)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/StepSize', 1.0) # 1°C per step
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/Decimals', 0) # Integer degrees
self._dbusservice.add_path('/SwitchableOutput/relay_temp_low/Settings/ShowUIControl', 1, writeable=True)
# High temp threshold (relay_temp_high)
# Note: Using Type 2 (Dimmable/PWM) because GUI only displays Types 0, 1, and 2 in switches pane
# GUI slider is hardcoded 1-100, so DimmingMin/Max are informational only
# Initial display name with both C and F
initial_high_f = DEFAULT_TEMP_HIGH * 9/5 + 32
self._default_temp_high = DEFAULT_TEMP_HIGH
self._default_temp_high_slider = initial_high_slider
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Name', f'Hot Limit: {DEFAULT_TEMP_HIGH:.0f}°C / {initial_high_f:.0f}°F')
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Type', 2) # Dimmable
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/State', 1, writeable=True,
onchangecallback=self._on_temp_high_state_changed)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Status', 0x09, writeable=True) # On status (no badge)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Current', 0)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Dimming', initial_high_slider,
writeable=True, onchangecallback=self._on_temp_high_changed)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Measurement', DEFAULT_TEMP_HIGH, writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/CustomName', '', writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/Type', 2, writeable=False)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/ValidTypes', 4) # Only dimmable (bit 2)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/Function', 2, writeable=True) # Manual
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/ValidFunctions', 4) # Bit 2 = Manual only
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/Group', '', writeable=True)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/PowerOnState', 1)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/DimmingMin', 1.0) # Slider min (= 0°C)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/DimmingMax', 100.0) # Slider max (= 99°C)
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/StepSize', 1.0) # 1°C per step
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/Decimals', 0) # Integer degrees
self._dbusservice.add_path('/SwitchableOutput/relay_temp_high/Settings/ShowUIControl', 1, writeable=True)
# Store defaults for fallback use in aggregation
self._default_temp_low = DEFAULT_TEMP_LOW
self._default_temp_high = DEFAULT_TEMP_HIGH
# Don't register yet - wait until main loop is ready
# This prevents D-Bus timeout issues when DbusMonitor tries to call GetItems
# before the main loop is running
# Note: SmartShunt discovery timer is started in register() after settings are loaded
def register(self):
"""Register the D-Bus service and device settings.
Should be called after __init__ but before starting the main loop.
This ensures the service is ready to handle D-Bus method calls.
"""
logging.info("### Registering VeDbusService")
self._dbusservice.register()
# Register device in settings (for GUI device list)
# This also restores discovery_enabled state from saved settings
self._register_device_settings(self._device_instance)
# Start searching for SmartShunts AFTER settings are loaded
# This ensures discovery_enabled state is correct before first search
GLib.timeout_add_seconds(self.config['UPDATE_INTERVAL_FIND_DEVICES'], self._find_smartshunts)
logging.info("Service registered and ready")
def _find_available_device_instance(self):
"""Find an available device instance number that's not already in use"""
# Get all battery services and their device instances
used_instances = set()
try:
for service in self._dbusConn.list_names():
if "com.victronenergy.battery" in service:
try:
obj = self._dbusConn.get_object(service, '/DeviceInstance')
iface = dbus.Interface(obj, 'com.victronenergy.BusItem')
instance = iface.GetValue()
if instance is not None:
used_instances.add(int(instance))
except:
pass # Service might not have DeviceInstance yet
except Exception as e:
logging.warning(f"Error checking used device instances: {e}")
# Start from 100 and find first available
for candidate in range(100, 300):
if candidate not in used_instances:
return candidate
# Fallback to 100 if somehow all are taken (unlikely)
logging.warning("All device instances 100-299 appear to be in use, using 100 anyway")
return 100
def _register_device_settings(self, device_instance):
"""Register device in com.victronenergy.settings for GUI device list"""
try:
# Create unique identifier for settings path (using serial number)
unique_id = "aggregateshunts_AGGREGATE01"
settings_path = f"/Settings/Devices/{unique_id}"
# Create ClassAndVrmInstance setting
class_and_vrm_instance = f"battery:{device_instance}"
# Use SettingsDevice to register the device
# This makes it appear in the GUI device list
settings = {
"ClassAndVrmInstance": [
f"{settings_path}/ClassAndVrmInstance",
class_and_vrm_instance,
0,
0,
],
"DiscoveryEnabled": [
f"{settings_path}/DiscoveryEnabled",
1, # Default: ON
0,
1,
],
"TempLowSlider": [
f"{settings_path}/TempLowSlider",
self._default_temp_low_slider, # Default slider position
1, # Min
100, # Max
],
"TempHighSlider": [
f"{settings_path}/TempHighSlider",
self._default_temp_high_slider, # Default slider position
1, # Min
100, # Max
],
}
# Initialize SettingsDevice (will create the settings if they don't exist)
self._settings = SettingsDevice(
self._dbusConn,
settings,
eventCallback=None, # No callback needed for now
timeout=10
)
logging.info(f"Registered device settings: {settings_path}/ClassAndVrmInstance = {class_and_vrm_instance}")
# Restore discovery state from saved settings
discovery_state = self._settings['DiscoveryEnabled']
self._dbusservice['/SwitchableOutput/relay_discovery/State'] = discovery_state
self.discovery_enabled = bool(discovery_state)
if discovery_state:
logging.info("Discovery enabled from saved settings")
else:
logging.info("Discovery disabled from saved settings")
# Hide temperature threshold switches when discovery is disabled
self._dbusservice['/SwitchableOutput/relay_temp_low/Settings/ShowUIControl'] = 0
self._dbusservice['/SwitchableOutput/relay_temp_high/Settings/ShowUIControl'] = 0
# Restore temperature slider values from saved settings
saved_low_slider = self._settings['TempLowSlider']
saved_high_slider = self._settings['TempHighSlider']
if saved_low_slider != self._default_temp_low_slider:
self._dbusservice['/SwitchableOutput/relay_temp_low/Dimming'] = saved_low_slider
actual_temp = self._slider_to_temp_low(saved_low_slider)
temp_f = actual_temp * 9/5 + 32
self._dbusservice['/SwitchableOutput/relay_temp_low/Name'] = f'Cold Limit: {actual_temp:.0f}°C / {temp_f:.0f}°F'
self._dbusservice['/SwitchableOutput/relay_temp_low/Measurement'] = actual_temp
logging.info(f"Restored cold limit: {actual_temp:.0f}°C from slider {saved_low_slider}")
if saved_high_slider != self._default_temp_high_slider:
self._dbusservice['/SwitchableOutput/relay_temp_high/Dimming'] = saved_high_slider
actual_temp = self._slider_to_temp_high(saved_high_slider)
temp_f = actual_temp * 9/5 + 32
self._dbusservice['/SwitchableOutput/relay_temp_high/Name'] = f'Hot Limit: {actual_temp:.0f}°C / {temp_f:.0f}°F'
self._dbusservice['/SwitchableOutput/relay_temp_high/Measurement'] = actual_temp
logging.info(f"Restored hot limit: {actual_temp:.0f}°C from slider {saved_high_slider}")
except Exception as e:
logging.error(f"Failed to register device settings: {e}")
# Don't fail the whole service if settings registration fails
def _init_dbusmonitor(self):
"""Initialize D-Bus monitor for SmartShunt services with reactive updates"""
dummy = {"code": None, "whenToLog": "configChange", "accessLevel": None}
monitorlist = {
"com.victronenergy.battery": {
"/ProductName": dummy,
"/ProductId": dummy,
"/CustomName": dummy,
"/Serial": dummy,
"/DeviceInstance": dummy,
"/FirmwareVersion": dummy,
"/HardwareVersion": dummy,
"/Dc/0/Voltage": dummy,
"/Dc/0/Current": dummy,
"/Dc/0/Power": dummy,
"/Dc/0/Temperature": dummy,
"/Soc": dummy,
"/ConsumedAmphours": dummy,
"/TimeToGo": dummy,
"/Connected": dummy,
"/Alarms/Alarm": dummy,
"/Alarms/LowVoltage": dummy,
"/Alarms/HighVoltage": dummy,
"/Alarms/LowSoc": dummy,
"/Alarms/HighTemperature": dummy,
"/Alarms/LowTemperature": dummy,
# History data
"/History/ChargeCycles": dummy,
"/History/TotalAhDrawn": dummy,
"/History/MinimumVoltage": dummy,
"/History/MaximumVoltage": dummy,
"/History/TimeSinceLastFullCharge": dummy,
"/History/AutomaticSyncs": dummy,
"/History/LowVoltageAlarms": dummy,
"/History/HighVoltageAlarms": dummy,
"/History/LastDischarge": dummy,
"/History/AverageDischarge": dummy,
"/History/ChargedEnergy": dummy,
"/History/DischargedEnergy": dummy,
"/History/FullDischarges": dummy,
"/History/DeepestDischarge": dummy,
"/History/MinimumStarterVoltage": dummy,
"/History/MaximumStarterVoltage": dummy,
# Relay
"/Relay/0/State": dummy,
# VE.Direct communication error counters
"/VEDirect/HexChecksumErrors": dummy,
"/VEDirect/HexInvalidCharacterErrors": dummy,
"/VEDirect/HexUnfinishedErrors": dummy,
"/VEDirect/TextChecksumErrors": dummy,
"/VEDirect/TextParseError": dummy,
"/VEDirect/TextUnfinishedErrors": dummy,
}
}
# Set up reactive updates - callback fires whenever any monitored value changes
# IMPORTANT: Exclude our own service from monitoring to prevent "GetItems failed" errors
self._dbusmon = DbusMonitor(monitorlist, valueChangedCallback=self._on_value_changed,
deviceAddedCallback=None, deviceRemovedCallback=None,
ignoreServices=['com.victronenergy.battery.aggregateshunts'])
def _on_value_changed(self, dbusServiceName, dbusPath, options, changes, deviceInstance):
"""
Called whenever any monitored D-Bus value changes.
This enables reactive updates instead of polling.
"""
# Only trigger updates for our tracked SmartShunts, not our own service
if "aggregate_shunts" in dbusServiceName:
return
# Only update for relevant paths (voltage, current, power, SoC, etc.)
if dbusPath in ["/Dc/0/Voltage", "/Dc/0/Current", "/Dc/0/Power", "/Soc",
"/ConsumedAmphours", "/TimeToGo", "/Dc/0/Temperature"]:
# Schedule an update if we have shunts configured
if self._shunts and not self._updating:
# Use GLib.idle_add to avoid blocking the D-Bus callback
GLib.idle_add(self._update)
def _on_temp_low_state_changed(self, path: str, value):
"""Handle low temp threshold on/off state - reset to default when turned off"""
new_state = bool(int(value) if isinstance(value, str) else value)
logging.info(f"Low temp threshold state changed to {'On' if new_state else 'Off'}")
if not new_state:
# When turned off, reset to default and turn back on
# Use timeout_add with 500ms delay to let the UI settle before resetting
def reset_to_default():
try:
self._dbusservice['/SwitchableOutput/relay_temp_low/Dimming'] = self._default_temp_low_slider
self._dbusservice['/SwitchableOutput/relay_temp_low/Measurement'] = self._default_temp_low
default_f = self._default_temp_low * 9/5 + 32
self._dbusservice['/SwitchableOutput/relay_temp_low/Name'] = f'Cold Limit: {self._default_temp_low:.0f}°C / {default_f:.0f}°F'
# Turn it back on automatically after resetting
self._dbusservice['/SwitchableOutput/relay_temp_low/State'] = 1
logging.info(f"Reset Cold Limit to default ({self._default_temp_low:.0f}°C)")
except Exception as e:
logging.error(f"Failed to reset low temp to default: {e}")
return False # Don't repeat
GLib.timeout_add(500, reset_to_default) # 500ms delay
return True
def _on_temp_high_state_changed(self, path: str, value):
"""Handle high temp threshold on/off state - reset to default when turned off"""
new_state = bool(int(value) if isinstance(value, str) else value)
logging.info(f"High temp threshold state changed to {'On' if new_state else 'Off'}")
if not new_state:
# When turned off, reset to default and turn back on
# Use timeout_add with 500ms delay to let the UI settle before resetting
def reset_to_default():
try:
self._dbusservice['/SwitchableOutput/relay_temp_high/Dimming'] = self._default_temp_high_slider
self._dbusservice['/SwitchableOutput/relay_temp_high/Measurement'] = self._default_temp_high
default_f = self._default_temp_high * 9/5 + 32
self._dbusservice['/SwitchableOutput/relay_temp_high/Name'] = f'Hot Limit: {self._default_temp_high:.0f}°C / {default_f:.0f}°F'
# Turn it back on automatically after resetting
self._dbusservice['/SwitchableOutput/relay_temp_high/State'] = 1
logging.info(f"Reset Hot Limit to default ({self._default_temp_high:.0f}°C)")
except Exception as e:
logging.error(f"Failed to reset high temp to default: {e}")
return False # Don't repeat
GLib.timeout_add(500, reset_to_default) # 500ms delay
return True
def _temp_to_slider_low(self, temp: float) -> float:
"""Convert cold temperature (-10 to 89°C) to slider value (1-100)
Each slider step = exactly 1°C:
slider 1 = -10°C, slider 11 = 0°C, slider 21 = 10°C, ..., slider 100 = 89°C
"""
return 1.0 + ((temp - self._temp_low_min) / (self._temp_low_max - self._temp_low_min)) * 99.0
def _slider_to_temp_low(self, slider: float) -> float:
"""Convert slider value (1-100) to cold temperature (-10 to 89°C)
Each slider step = exactly 1°C:
slider 1 = -10°C, slider 11 = 0°C, slider 21 = 10°C, ..., slider 100 = 89°C
"""
return self._temp_low_min + ((slider - 1.0) / 99.0) * (self._temp_low_max - self._temp_low_min)
def _temp_to_slider_high(self, temp: float) -> float:
"""Convert hot temperature (0 to 99°C) to slider value (1-100)
Each slider step = exactly 1°C:
slider 1 = 0°C, slider 2 = 1°C, ..., slider 100 = 99°C
"""
return 1.0 + ((temp - self._temp_high_min) / (self._temp_high_max - self._temp_high_min)) * 99.0
def _slider_to_temp_high(self, slider: float) -> float:
"""Convert slider value (1-100) to hot temperature (0 to 99°C)
Each slider step = exactly 1°C:
slider 1 = 0°C, slider 2 = 1°C, ..., slider 100 = 99°C
"""
return self._temp_high_min + ((slider - 1.0) / 99.0) * (self._temp_high_max - self._temp_high_min)
def _on_temp_low_changed(self, path: str, value):
"""Handle low temperature threshold changes - value is slider position (1-100)"""
slider_value = float(value) if value is not None else 21 # Default to 10°C (slider 21 = 10°C with -10 to 89 range)
# Convert slider value to actual temperature
actual_temp = self._slider_to_temp_low(slider_value)
temp_f = actual_temp * 9/5 + 32
logging.info(f"Low temp threshold slider changed to {slider_value:.1f} -> {actual_temp:.1f}°C / {temp_f:.1f}°F")
# Update paths to display the value in the UI
try:
self._dbusservice['/SwitchableOutput/relay_temp_low/Measurement'] = actual_temp
# Update Name to show the temperature in both C and F
self._dbusservice['/SwitchableOutput/relay_temp_low/Name'] = f'Cold Limit: {actual_temp:.0f}°C / {temp_f:.0f}°F'
except Exception as e:
logging.error(f"Failed to update low temp measurement: {e}")
# Save to persistent settings
if hasattr(self, '_settings') and self._settings:
self._settings['TempLowSlider'] = int(slider_value)
return True
def _on_temp_high_changed(self, path: str, value):
"""Handle high temperature threshold changes - value is slider position (1-100)"""
slider_value = float(value) if value is not None else 42 # Default to 41°C (slider 42 = 41°C with 0 to 99 range)
# Convert slider value to actual temperature
actual_temp = self._slider_to_temp_high(slider_value)
temp_f = actual_temp * 9/5 + 32
logging.info(f"High temp threshold slider changed to {slider_value:.1f} -> {actual_temp:.1f}°C / {temp_f:.1f}°F")
# Update paths to display the value in the UI
try:
self._dbusservice['/SwitchableOutput/relay_temp_high/Measurement'] = actual_temp
# Update Name to show the temperature in both C and F
self._dbusservice['/SwitchableOutput/relay_temp_high/Name'] = f'Hot Limit: {actual_temp:.0f}°C / {temp_f:.0f}°F'
except Exception as e:
logging.error(f"Failed to update high temp measurement: {e}")
# Save to persistent settings
if hasattr(self, '_settings') and self._settings:
self._settings['TempHighSlider'] = int(slider_value)
return True
def _on_discovery_changed(self, path: str, value):
"""Handle discovery switch state changes - show/hide all shunt switches"""
new_enabled = bool(int(value) if isinstance(value, str) else value)
logging.info(f"Discovery switch changed: new_enabled={new_enabled}, old={self.discovery_enabled}")
# Save to persistent settings
if hasattr(self, '_settings') and self._settings:
self._settings['DiscoveryEnabled'] = 1 if new_enabled else 0
if self.discovery_enabled != new_enabled:
self.discovery_enabled = new_enabled
# Update ShowUIControl for all shunt switches
show_value = 1 if new_enabled else 0
for service_name, switch_info in self.shunt_switches.items():
relay_id = switch_info.get('relay_id')
if relay_id:
output_path = f'/SwitchableOutput/relay_{relay_id}/Settings/ShowUIControl'
try:
self._dbusservice[output_path] = show_value
logging.debug(f"Set {output_path} = {show_value}")
except Exception as e:
logging.error(f"Failed to set {output_path}: {e}")
# Also hide/show the temperature threshold switches
try:
self._dbusservice['/SwitchableOutput/relay_temp_low/Settings/ShowUIControl'] = show_value
self._dbusservice['/SwitchableOutput/relay_temp_high/Settings/ShowUIControl'] = show_value
logging.debug(f"Set temperature threshold switches ShowUIControl = {show_value}")
except Exception as e:
logging.error(f"Failed to set temperature threshold switches visibility: {e}")
# Note: Discovery switch (relay_0) is NEVER hidden - users need it to re-enable discovery
logging.info(f"SmartShunt Discovery {'enabled' if new_enabled else 'disabled'} - all switches {'visible' if new_enabled else 'hidden'}")
return True
def _on_shunt_switch_changed(self, service_name: str, path: str, value):
"""Handle individual shunt switch state changes - enable/disable from aggregation"""
new_enabled = bool(int(value) if isinstance(value, str) else value)
if service_name in self.shunt_switches:
old_enabled = self.shunt_switches[service_name].get('enabled', True)
if old_enabled != new_enabled:
self.shunt_switches[service_name]['enabled'] = new_enabled
# Save to settings
self._set_shunt_enabled_setting(service_name, new_enabled)
logging.info(f"Shunt switch changed: {service_name} -> {'enabled' if new_enabled else 'disabled'}")
# Trigger aggregation update
if not self._updating:
self._update_values()
return True
def _get_shunt_setting_key(self, service_name: str) -> str:
"""Convert service name to a valid settings key.
Uses just the port name to match relay ID format.
e.g., com.victronenergy.battery.ttyS6 -> ttyS6
"""
parts = service_name.split('.')
if len(parts) >= 4:
return parts[3] # Just the port, e.g., ttyS6
return service_name.replace('.', '_')
def _get_shunt_enabled_setting(self, service_name: str) -> bool:
"""Get shunt enabled state from settings"""
try:
key = self._get_shunt_setting_key(service_name)
settings_path = f"/Settings/Devices/aggregateshunts/shunt_{key}"
settings_obj = self._dbusConn.get_object('com.victronenergy.settings', settings_path)
settings_iface = dbus.Interface(settings_obj, 'com.victronenergy.BusItem')
value = settings_iface.GetValue()
return bool(value)
except:
# Setting doesn't exist yet - default to enabled
return None
def _set_shunt_enabled_setting(self, service_name: str, enabled: bool):
"""Save shunt enabled state to settings"""
try:
key = self._get_shunt_setting_key(service_name)
settings_path = f"/Settings/Devices/aggregateshunts/shunt_{key}"
settings_obj = self._dbusConn.get_object('com.victronenergy.settings', '/Settings')
settings_iface = dbus.Interface(settings_obj, 'com.victronenergy.Settings')
# AddSetting(group, name, default, type, min, max)
settings_iface.AddSetting(
'Devices/aggregateshunts',
f'shunt_{key}',
1, # Default: enabled
'i', # integer
0,
1
)
# Now set the actual value
shunt_obj = self._dbusConn.get_object('com.victronenergy.settings', settings_path)
shunt_iface = dbus.Interface(shunt_obj, 'com.victronenergy.BusItem')
shunt_iface.SetValue(1 if enabled else 0)
logging.debug(f"Saved shunt {service_name} enabled={enabled} to settings")
except Exception as e:
logging.error(f"Failed to save shunt setting: {e}")
def _get_relay_id_from_service(self, service_name: str) -> str:
"""Generate a stable relay ID from service name.
Examples:
com.victronenergy.battery.ttyS5 -> shunt_ttyS5
com.victronenergy.battery.ttyS6 -> shunt_ttyS6
"""
# Extract the last part of the service name (e.g., ttyS5)
parts = service_name.split('.')
if len(parts) >= 4:
port = parts[3] # e.g., ttyS5
return f"shunt_{port}"
# Fallback: use sanitized service name
return f"shunt_{service_name.replace('.', '_').replace('com_victronenergy_battery_', '')}"
def _create_shunt_switch(self, service_name: str, custom_name: str):
"""Create a switch for a discovered SmartShunt
Uses context manager to emit ItemsChanged signal so GUI picks up new switches.
"""
# Check if switch already exists
if service_name in self.shunt_switches:
return
# Generate stable relay_id from service name (e.g., shunt_ttyS5)
relay_id = self._get_relay_id_from_service(service_name)
# Check settings for persisted enabled state
persisted_enabled = self._get_shunt_enabled_setting(service_name)
enabled = persisted_enabled if persisted_enabled is not None else True
# Store switch info
self.shunt_switches[service_name] = {
'relay_id': relay_id,
'enabled': enabled,
'custom_name': custom_name
}
# Save to settings (creates setting if needed)
self._set_shunt_enabled_setting(service_name, enabled)
output_path = f'/SwitchableOutput/relay_{relay_id}'
show_ui = 1 if self.discovery_enabled else 0
# Create switch paths using context manager to emit ItemsChanged signal
with self._dbusservice as ctx:
ctx.add_path(f'{output_path}/Name', custom_name)
ctx.add_path(f'{output_path}/Type', 1) # Toggle switch
ctx.add_path(f'{output_path}/State', 1 if enabled else 0,
writeable=True, onchangecallback=lambda p, v: self._on_shunt_switch_changed(service_name, p, v))
ctx.add_path(f'{output_path}/Status', 0x00)
ctx.add_path(f'{output_path}/Current', 0)
# Settings - match relay_0 structure
ctx.add_path(f'{output_path}/Settings/CustomName', '', writeable=True)
ctx.add_path(f'{output_path}/Settings/Type', 1, writeable=True)
ctx.add_path(f'{output_path}/Settings/ValidTypes', 2)
ctx.add_path(f'{output_path}/Settings/Function', 2, writeable=True)
ctx.add_path(f'{output_path}/Settings/ValidFunctions', 4)
ctx.add_path(f'{output_path}/Settings/Group', '', writeable=True)
ctx.add_path(f'{output_path}/Settings/ShowUIControl', show_ui, writeable=True)
ctx.add_path(f'{output_path}/Settings/PowerOnState', 1 if enabled else 0)
logging.info(f"Created switch for {custom_name} ({service_name}) at {output_path}, enabled={enabled}")
def _find_smartshunts(self):
"""Search for SmartShunt services on D-Bus
Note: Discovery controls whether NEW switches are created, not whether we find/aggregate.
We always search for SmartShunts, but only create switches for new ones when discovery is enabled.
"""
# Only log at INFO level during initial search or when explicitly looking for new devices
if not self._shunts:
logging.info(f"Searching for SmartShunts: Trial #{self._searchTrials}")
else:
logging.debug(f"Checking for SmartShunt changes (interval: {self._device_search_interval}s)")
found_shunts = []
try:
for service in self._dbusConn.list_names():
if "com.victronenergy.battery" in service:
product_name = self._dbusmon.get_value(service, "/ProductName")
# Check if this is a SmartShunt (but not a virtual aggregate)
if product_name and "SmartShunt" in product_name:
# Skip if this is a virtual/aggregate device (to avoid aggregating ourselves)
is_virtual = self._dbusmon.get_value(service, "/Devices/0/Virtual")
if is_virtual == 1:
logging.debug(f"Skipping virtual device: {service}")
continue
device_instance = self._dbusmon.get_value(service, "/DeviceInstance")
custom_name = self._dbusmon.get_value(service, "/CustomName")
# Add all SmartShunts (filtering via switches instead of config)
found_shunts.append({
'service': service,
'instance': device_instance,
'name': custom_name or f"Shunt {device_instance}",
'product': product_name
})
# Only log at INFO level during initial discovery
if not self._shunts:
logging.info(f"|- Found: {custom_name} [{device_instance}] - {product_name}")
else:
logging.debug(f"|- Found: {custom_name} [{device_instance}] - {product_name}")
except Exception as e:
logging.error(f"Error searching for SmartShunts: {e}")
# Check if device count changed (new device appeared or disappeared)
if self._shunts and len(found_shunts) != len(self._shunts):
logging.warning(f"Device count changed: {len(self._shunts)} -> {len(found_shunts)}")
logging.warning(f"Resetting search interval to {self._initial_search_interval}s")
self._device_search_interval = self._initial_search_interval
self._devices_stable_since = None
# Check if we found any SmartShunts
if len(found_shunts) > 0:
# Check if this is initial discovery or device count changed
if not self._shunts or len(found_shunts) != self._last_device_count:
self._shunts = found_shunts
self._last_device_count = len(found_shunts)
logging.info(f"✓ Found {len(found_shunts)} SmartShunt(s) to aggregate")
# Create switches for newly discovered shunts
for shunt in found_shunts:
service_name = shunt['service']
if service_name not in self.shunt_switches:
# Check if this shunt has a persisted enabled setting
persisted = self._get_shunt_enabled_setting(service_name)
if self.discovery_enabled:
# Discovery enabled: create visible switch
self._create_shunt_switch(service_name, shunt['name'])
elif persisted is not None:
# Discovery disabled but has persisted setting: create hidden switch
self._create_shunt_switch(service_name, shunt['name'])
logging.info(f"Restored switch for {shunt['name']} (discovery disabled)")
else:
# Discovery disabled and no persisted setting: skip
logging.debug(f"Discovery disabled, skipping new shunt {shunt['name']}")
# Update /Devices/* paths to show info about aggregated SmartShunts
self._update_device_paths(found_shunts)
# Start device stability timer
self._devices_stable_since = tt.time()
# Do an initial update immediately
self._update()
# Set up periodic logging (every LOG_PERIOD seconds)
if self.config['LOG_PERIOD'] > 0:
GLib.timeout_add_seconds(self.config['LOG_PERIOD'], self._periodic_log)
else:
# Devices haven't changed - check if stable for 15 seconds
if self._devices_stable_since and (tt.time() - self._devices_stable_since) >= 15:
# Apply exponential backoff
old_interval = self._device_search_interval
self._device_search_interval = min(
self._device_search_interval * 2,
self._max_search_interval
)
if self._device_search_interval != old_interval:
logging.info(f"Devices stable, increasing search interval: {old_interval}s -> {self._device_search_interval}s")
# Reset stability timer for next backoff cycle
self._devices_stable_since = tt.time()
# Schedule next search with current interval
GLib.timeout_add_seconds(int(self._device_search_interval), self._find_smartshunts)
return False # Stop the current timer (we scheduled a new one)
elif self._searchTrials < self.config['SEARCH_TRIALS']:
self._searchTrials += 1
return True # Continue searching at initial rate
else:
logging.error(f"No SmartShunts found after {self.config['SEARCH_TRIALS']} trials")
logging.error(f"Check that SmartShunts are connected and not all excluded")