-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge.py
More file actions
3030 lines (2680 loc) · 118 KB
/
Copy pathbridge.py
File metadata and controls
3030 lines (2680 loc) · 118 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
# -*- coding: utf-8 -*-
"""
Scheiber CAN <-> Victron connected-genset bridge
Version 5.10.2
Design rules:
* /Start is COMMAND state owned by Victron's generator manager.
CAN feedback NEVER writes /Start locally.
* /StatusCode is ACTUAL generator feedback derived from Scheiber CAN.
* A physical Scheiber START is adopted into Victron by setting the
generator manager's /ManualStart=1. The manager then writes our /Start=1;
that write is accepted without retransmitting START on CAN.
* A physical Scheiber STOP clears /ManualStart only when manual start is
actually active. Automatic Victron conditions are not silently disabled.
* No AC-panel commands are sent.
* No automatic START/STOP retries are sent.
* SocketCAN kernel filters allow only generator/battery telemetry IDs.
* Generator telemetry: frequency, gated AC voltage, starter voltage.
* Battery telemetry: six house-bank IBS channels plus confirmed
Starboard and Port engine-battery voltage channels (60A charger B1/B3)
and the generator starter battery (25A charger).
* House-bank voltage and SoC decodes are confirmed for this installation.
House-bank current sign/offset are strong; the x0.1 A scale remains a candidate.
* Engine starter battery voltages (Starboard 12.6V, Port 12.8V) are confirmed
via the 60A multi-output charger telemetry (0x00501008 / 0x00561008 x 0.1V).
* Tank telemetry: fresh water, diesel tank 1, diesel tank 2 from
confirmed Scheiber frame 0x02040580.
* Startup resynchronization detects a generator that was already running
when this bridge process starts.
* Scheiber AC/House applied-source flags are receive-only diagnostics and
are used to gate generator-voltage publication. No AC-panel CAN commands
are transmitted.
* Victron AC-input configuration is NOT rewritten by this bridge. Configure
AC input 1 = Shore power and AC input 2 = Generator in Venus OS.
* A receive-only com.victronenergy.acsystem service maps the House selector
into Venus GUI-v2 as Shore / Generator and publishes the active bus voltage.
The independent A/C selector remains available as a diagnostic path.
* Generator-manager restart recovery: if dbus-generator/startstop1 disappears
while the physical genset is starting/running, its replacement manager's
initialization /Start=0 is suppressed. Manual ownership and any numeric
ManualStartTimer are restored before normal STOP commands are accepted.
"""
import json
import os
import socket
import struct
import subprocess
import sys
import time
from datetime import datetime
from decimal import Decimal
# ---------------------------------------------------------------------------
# Find Victron velib_python
# ---------------------------------------------------------------------------
for p in (
"/opt/victronenergy/dbus-systemcalc-py/ext/velib_python",
"/opt/victronenergy/dbus_generator/ext/velib_python",
"/opt/victronenergy/dbus-generator/ext/velib_python",
"/opt/victronenergy/velib_python",
):
if os.path.isfile(os.path.join(p, "vedbus.py")):
sys.path.insert(0, p)
break
else:
for root, dirs, files in os.walk("/opt/victronenergy"):
if "vedbus.py" in files:
sys.path.insert(0, root)
break
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
from vedbus import VeDbusService
DBusGMainLoop(set_as_default=True)
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
CAN_IF = os.environ.get("CAN_IF", "can2")
SERVICE_NAME = "com.victronenergy.genset.scheiber"
DEVICE_INSTANCE = 40
PRODUCT_ID = 0xFFFF
PRODUCT_NAME = "Scheiber Generator"
BRIDGE_VERSION = "5.10.2"
# Synthetic, receive-only AC-system service used to describe the vessel's
# physical House source selector to Venus OS. Venus otherwise sees the Shore
# meter and genset as two unrelated sources and assumes Grid has priority.
AC_SYSTEM_SERVICE_NAME = "com.victronenergy.acsystem.scheiber_house"
AC_SYSTEM_DEVICE_INSTANCE = 42
LOGFILE = "/data/scheiber-gx/bridge.log"
STATUSFILE = "/data/scheiber-gx/status.json"
# Confirmed generator command ID
GEN_CONTROL_ID = 0x02460B88
GEN_START = b"\x01"
GEN_STOP = b"\x02"
# Observed generator state-machine ID
GEN_STATE_ID = 0x02440B88
# Generator-associated frequency ID; bytes 0..1 are uint16 LE x 0.1 Hz
GEN_FREQ_ID = 0x005A1020
# Shared Generator/AC module telemetry; bytes 0..1 BE voltage (V),
# 2..3 BE frequency (Hz). This is kept as a diagnostic/fallback because it can
# represent another AC source while the generator is off.
GEN_AC_ID = 0x02040898
# Confirmed Scheiber source selector feedback. RECEIVE ONLY.
# byte 0 enum: 0x01 OFF, 0x02 SHORE, 0x04 GENERATOR, 0x08 INVERTER.
AC_PANEL_APPLIED_ID = 0x02400B90
HOUSE_PANEL_APPLIED_ID = 0x02400B88
# Confirmed panel telemetry and continuous 1Hz heartbeat status frames.
# Heartbeats (0x00000B88 / 0x00000B90): bytes 2..3 uint16 BE AC line voltage.
# Byte 0 is NOT the applied-source enum: both panels emit 0x08 continuously,
# including the A/C panel, which has no inverter source. Only the confirmed
# 0x02400B88 / 0x02400B90 applied-state frames may update source selection.
HOUSE_PANEL_STATUS_ID = 0x00000B88
AC_PANEL_STATUS_ID = 0x00000B90
AC_MODULE_STATUS_ID = 0x00000898
AC_PANEL_TELEMETRY_ID = 0x02040B90
HOUSE_PANEL_TELEMETRY_ID = 0x02040B88
# Shared AC ramp transition marker (0x02140898).
# byte 0: 0x02 = Ramp-Down, 0x03 = Ramp-Up. External-source transfers also
# emit it, so it is accepted as Mastervolt enable evidence only when the House
# is not on Shore or Generator.
AC_RAMP_MARKER_ID = 0x02140898
AC_RAMP_DOWN = 0x02
AC_RAMP_UP = 0x03
# Installation default supplied by the vessel owner: the Mastervolt inverter
# is normally left enabled as a fallback, but it has a physical OFF switch.
# Ramp markers are accepted as enable/disable evidence only while the House is
# not on Shore or Generator, because external-source transfers emit the same
# markers. House applied-source feedback independently determines whether the
# inverter is actually feeding the House bus.
MASTERVOLT_DEFAULT_ENABLED = True
SOURCE_OFF = 0x01
SOURCE_SHORE = 0x02
SOURCE_GENERATOR = 0x04
SOURCE_INVERTER = 0x08
# Generator starter-battery / 0x1020 charger telemetry.
# bytes 0..1: uint16 LE x 0.1 V (strong starter-battery correlation)
# bytes 2..3: uint16 LE x 0.1 A (charger-output-current candidate; diagnostic only)
# bytes 4..5: uint16 LE x 0.1 V (AC input voltage; strong generator-specific
# candidate because it rises from 0 to ~230 V during generator
# startup and returns to 0 after shutdown)
GEN_STARTER_ID = 0x00501020
# Six established house-bank IBS-like battery frames.
# bytes 0..1: uint16 LE x 0.01 V -- CONFIRMED
# bytes 2..3: uint16 LE, offset 0x4E00, x 0.1 A -- CANDIDATE
# bytes 4..5: uint16 LE, x 1 % SoC -- CONFIRMED for this installation
HOUSE_BATTERY_IDS = (
0x06020580,
0x06060580,
0x060A0580,
0x060E0580,
0x06120580,
0x06160580,
)
HOUSE_CURRENT_ZERO = 0x4E00
HOUSE_CURRENT_SCALE = 0.1
HOUSE_VOLTAGE_SCALE = 0.01
# 60A Multi-Output Charger Telemetry (Starboard starter B1, House B2, Port starter B3)
# bytes 0..1: uint16 LE x 0.1 V -> B1: Starboard Engine Starter
CHARGER_60A_TELEMETRY_ID = 0x00501008
# bytes 0..1: uint16 LE x 0.1 V -> B2: House Bank (on 60A charger)
# bytes 2..3: uint16 LE x 0.1 V -> B3: Port Engine Starter
CHARGER_60A_DYNAMIC_ID = 0x00561008
CHARGER_60A_VOLTAGE_SCALE = 0.1
# Confirmed tank-level frame.
# bytes 0..1: fresh water level, uint16 BE x 1 %
# bytes 2..3: diesel tank 1 level, uint16 BE x 1 %
# bytes 4..5: diesel tank 2 level, uint16 BE x 1 %
TANK_LEVEL_ID = 0x02040580
# Victron tank FluidType values:
# 0 = Fuel
# 1 = Fresh water
#
# Vessel capacities are known independently of the CAN mapping and kept here
# in litres for readability. Victron tank D-Bus /Capacity and /Remaining use m3,
# so setup_tank_services() converts litres to cubic metres at publication.
FRESH_WATER_CAPACITY_L = 600.0
DIESEL1_CAPACITY_L = 500.0
DIESEL2_CAPACITY_L = 500.0
TANK_DEFS = (
# key, service suffix, device instance, custom name, FluidType,
# word index, optional capacity litres
(
"fresh",
"scheiber_fresh",
90,
"Fresh Water Tank",
1,
0,
FRESH_WATER_CAPACITY_L,
),
(
"diesel1",
"scheiber_diesel1",
91,
"Port Diesel Tank",
0,
1,
DIESEL1_CAPACITY_L,
),
(
"diesel2",
"scheiber_diesel2",
92,
"Starboard Diesel Tank",
0,
2,
DIESEL2_CAPACITY_L,
),
)
# Stale telemetry handling. House/generator frames are expected frequently;
# engine experimental frames were sparse in the capture, so allow much longer.
FAST_TELEMETRY_STALE_SECONDS = 15.0
ENGINE_TELEMETRY_STALE_SECONDS = 180.0
STATUS_SNAPSHOT_INTERVAL = 5.0
# Victron's automatic system-battery selection may choose any connected
# com.victronenergy.battery service if more than one exists. To protect the
# existing SmartShunt from being displaced, native per-bank battery services
# are registered only when the GX system battery is explicitly selected.
REQUIRE_EXPLICIT_SYSTEM_BATTERY = True
RUNNING_FREQ_MIN = 47.0
RUNNING_FREQ_MAX = 53.0
STOPPED_FREQ_MAX = 1.0
# Startup resynchronization:
# 005A1020 nominal frequency is authoritative if seen.
# 00501020 charger AC is a secondary fast hint. Require two consecutive
# high-AC samples before using it to recover an already-running generator
# after a bridge restart.
STARTUP_RESYNC_SECONDS = 30.0
STARTUP_CHARGER_AC_MIN = 170.0
STARTUP_CHARGER_AC_MAX = 300.0
STARTUP_CHARGER_AC_CONFIRM_SAMPLES = 2
# 50 Hz was first seen about 9.3 s after START in the controlled capture.
# Once nominal frequency is seen, wait a little longer before declaring RUNNING.
RUNNING_CONFIRM_DELAY = 3.0
START_CONFIRM_TIMEOUT = 35.0
# Normal STOP -> 0 Hz was about 0.9 s. An aborted start produced a much longer
# transition, so keep this diagnostic timeout generous. It does NOT trigger a
# retry or any additional CAN command.
STOP_CONFIRM_TIMEOUT = 75.0
# If a physical Scheiber command is adopted by Victron, Victron will shortly
# write the matching value to our /Start path. Suppress that duplicate CAN TX.
ADOPTION_SUPPRESS_SECONDS = 10.0
# Prevent accidental identical command retransmission from repeated D-Bus writes.
SAME_COMMAND_GUARD = 2.0
# D-Bus generator-manager service prefix created by Victron dbus_generator.
MANAGER_PREFIX = "com.victronenergy.generator.startstop"
BUSITEM_IFACE = "com.victronenergy.BusItem"
# dbus-generator can be restarted by runit. Its newly created startstop service
# initially writes /Start=0. If the physical generator is already running,
# treating that initialization write as a genuine STOP would be unsafe.
MANAGER_CACHE_INTERVAL = 0.5
MANAGER_RECOVERY_SECONDS = 30.0
# Linux SocketCAN constants
CAN_EFF_FLAG = 0x80000000
CAN_RTR_FLAG = 0x40000000
CAN_EFF_MASK = 0x1FFFFFFF
SOL_CAN_RAW = getattr(socket, "SOL_CAN_RAW", 101)
CAN_RAW_FILTER = getattr(socket, "CAN_RAW_FILTER", 1)
CAN_RAW_RECV_OWN_MSGS = getattr(socket, "CAN_RAW_RECV_OWN_MSGS", 4)
# Connected-genset StatusCode values used by Victron integrations.
STATUS_STOPPED = 0
STATUS_STARTING = 1
STATUS_RUNNING = 8
STATUS_STOPPING = 9
# Native Victron battery services. Keep the existing SmartShunt selected as
# the system battery; these are intended as additional per-battery telemetry.
BATTERY_DEFS = (
# key, service suffix, device instance, custom name, CAN ID, mode
("house1", "scheiber_house1", 80, "Scheiber House Bank 1", 0x06020580, "house"),
("house2", "scheiber_house2", 81, "Scheiber House Bank 2", 0x06060580, "house"),
("house3", "scheiber_house3", 82, "Scheiber House Bank 3", 0x060A0580, "house"),
("house4", "scheiber_house4", 83, "Scheiber House Bank 4", 0x060E0580, "house"),
("house5", "scheiber_house5", 84, "Scheiber House Bank 5", 0x06120580, "house"),
("house6", "scheiber_house6", 85, "Scheiber House Bank 6", 0x06160580, "house"),
("engine_starboard", "scheiber_engine_starboard", 86, "Starboard Engine Starter Battery", CHARGER_60A_TELEMETRY_ID, "engine_starboard"),
("engine_port", "scheiber_engine_port", 87, "Port Engine Starter Battery", CHARGER_60A_DYNAMIC_ID, "engine_port"),
("generator", "scheiber_generator_starter", 88, "Generator Starter Battery", GEN_STARTER_ID, "generator"),
)
BATTERY_KEY_BY_CAN = {row[4]: row[0] for row in BATTERY_DEFS}
HOUSE_KEY_BY_CAN = {
row[4]: row[0] for row in BATTERY_DEFS if row[5] == "house"
}
# Smart Starter Battery Low-Voltage Alarm Configuration
# Prevents false alarms during engine / generator cranking dips (< 15s transient)
STARTER_LOW_VOLTAGE_WARN = 12.2 # Warning threshold in Volts
STARTER_LOW_VOLTAGE_ALARM = 11.8 # Critical Alarm threshold in Volts
STARTER_VOLTAGE_HYSTERESIS = 0.3 # Recovery hysteresis in Volts (clears warning at >= 12.5V)
STARTER_ALARM_HOLD_SECONDS = 15.0 # Sustained low voltage duration required to trigger
CAN_FILTER_IDS = tuple(sorted(set(
(
GEN_CONTROL_ID,
GEN_STATE_ID,
GEN_FREQ_ID,
GEN_AC_ID,
GEN_STARTER_ID,
TANK_LEVEL_ID,
AC_PANEL_APPLIED_ID,
HOUSE_PANEL_APPLIED_ID,
AC_PANEL_TELEMETRY_ID,
HOUSE_PANEL_TELEMETRY_ID,
HOUSE_PANEL_STATUS_ID,
AC_PANEL_STATUS_ID,
AC_MODULE_STATUS_ID,
AC_RAMP_MARKER_ID,
CHARGER_60A_TELEMETRY_ID,
CHARGER_60A_DYNAMIC_ID,
)
+ HOUSE_BATTERY_IDS
)))
_UNSET = object()
class Bridge:
def __init__(self):
self.bus = dbus.SystemBus()
self.can = None
self.can_watch_id = None
self.can_retry_id = None
self.service = None
# Victron generator-manager service controlling this genset.
self.manager_service = None
self.manager_discovery_id = None
self.queued_manual_value = None
self.external_manual_adopted = False
# Cache the live Victron manager state so it survives a manager-process
# restart. In particular, ManualStartTimer is in-memory state inside
# dbus-generator and otherwise disappears when that process restarts.
self.manager_cache_next = 0.0
self.cached_manager_manual_start = None
self.cached_manager_manual_timer = None
self.cached_manager_running_by_code = None
self.cached_manager_running_by = None
self.cached_manager_state = None
self.cached_manager_updated = None
# Recovery guard. It is entered only when a generator manager
# disappears while the physical generator is STARTING/RUNNING, or an
# external/startup running condition is detected before a manager is
# available.
self.manager_recovery_active = False
self.manager_recovery_until = 0.0
self.manager_recovery_reason = None
self.manager_recovery_restore_manual = False
self.manager_recovery_timer = 0
self.manager_recovery_running_by_code = None
# When an external CAN command is adopted into /ManualStart, the
# generator manager will write the same state to our /Start path.
# That write is command synchronization, not a request for another
# physical CAN command.
self.expected_start_write = None
self.expected_start_write_until = 0.0
# Physical generator state.
self.actual_state = "UNKNOWN"
self.state_reason = "bridge startup"
self.last_state_code = None
self.last_frequency = None
self.last_ac_module_voltage = None
self.last_ac_module_frequency = None
self.last_starter_voltage = None
self.last_generator_charger_current = None
self.last_generator_charger_ac_voltage = None
self.gen_ac_last_update = None
self.gen_starter_last_update = None
self.gen_charger_ac_last_update = None
# Scheiber source-selection and panel telemetry.
self.ac_panel_applied_source = None
self.house_panel_applied_source = None
self.mastervolt_inverter_state = 1 if MASTERVOLT_DEFAULT_ENABLED else 0
self.last_ac_panel_voltage = None
self.last_house_panel_voltage = None
self.last_ac_panel_freq_status = None
self.last_house_panel_freq_status = None
self.ac_panel_last_update = None
self.house_panel_last_update = None
# Startup resynchronization for bridge restarts while genset is running.
self.startup_resync_active = True
self.startup_resync_started = time.monotonic()
self.startup_charger_ac_samples = 0
self.startup_running_adoption_pending = False
self.last_status_snapshot = time.monotonic()
# Additional Victron battery services and freshness timestamps.
self.battery_services = {}
self.battery_last_update = {}
# Each exported Victron service needs its own private D-Bus connection.
# D-Bus object paths are connection-scoped; reusing one connection for
# multiple VeDbusService instances that all export "/" and "/Mgmt/..."
# causes an immediate registration collision.
self.battery_buses = {}
self.starter_voltages = {}
self.battery_low_voltage_warn_start = {}
self.battery_low_voltage_alarm_start = {}
self.battery_alarm_state = {}
# Native Victron tank services. Each gets its own private D-Bus
# connection for the same reason as the per-battery services.
self.tank_services = {}
self.tank_buses = {}
self.tank_last_update = {}
# Native Victron Grid/Shore power service (receive-only).
self.shore_service = None
self.shore_bus = None
# Native Victron AC-system topology for the receive-only House source
# selector. This is deliberately separate from the two physical
# source meters and exposes no control paths.
self.acsystem_service = None
self.acsystem_bus = None
# Native Victron Inverter service for MasterVolt 2000W.
self.mastervolt_service = None
self.mastervolt_bus = None
# Transition tracking. Diagnostic only: timeouts never retry commands.
self.running_candidate_since = None
self.pending = None
self.pending_since = None
self.pending_origin = None
# Command de-duplication.
self.last_tx_command = None
self.last_tx_time = 0.0
self.log("================================================")
self.log("Scheiber connected-genset bridge V{}".format(BRIDGE_VERSION))
self.log("D-Bus service : {}".format(SERVICE_NAME))
self.log("CAN interface : {}".format(CAN_IF))
self.log("START : 02460B88#01")
self.log("STOP : 02460B88#02")
self.log("AC control : DISABLED")
self.log("Auto retries : DISABLED")
self.log("================================================")
self.setup_dbus()
self.setup_grid_service()
self.setup_acsystem_service()
self.setup_mastervolt_inverter_service()
self.setup_battery_services()
self.setup_tank_services()
self.setup_name_owner_watch()
self.log_victron_ac_configuration()
self.schedule_manager_discovery(immediate=True)
self.connect_can()
GLib.timeout_add(100, self.timer_tick)
self.write_status()
# ------------------------------------------------------------------
# Logging/status
# ------------------------------------------------------------------
def log(self, msg):
line = "{} {}\n".format(
datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg
)
print(line, end="", flush=True)
try:
with open(LOGFILE, "a") as f:
f.write(line)
except Exception:
pass
def write_status(self):
try:
command_start = self.service["/Start"] if self.service else None
status_code = self.service["/StatusCode"] if self.service else None
connected = self.service["/Connected"] if self.service else 0
except Exception:
command_start = None
status_code = None
connected = 0
batteries = {}
for key, svc in self.battery_services.items():
try:
batteries[key] = {
"name": str(svc["/CustomName"]),
"voltage_v": svc["/Dc/0/Voltage"],
"current_a": svc["/Dc/0/Current"],
"soc_percent": svc["/Soc"],
"power_w": svc["/Dc/0/Power"],
"can_id": svc["/Scheiber/CanId"],
"decode": str(svc["/Scheiber/Decode"]),
"last_update_monotonic": self.battery_last_update.get(key),
}
except Exception:
pass
tanks = {}
for key, svc in self.tank_services.items():
try:
tanks[key] = {
"name": str(svc["/CustomName"]),
"level_percent": svc["/Level"],
"fluid_type": svc["/FluidType"],
"capacity_m3": svc["/Capacity"],
"remaining_m3": svc["/Remaining"],
"raw_value": svc["/Scheiber/RawValue"],
"last_update_monotonic": self.tank_last_update.get(key),
}
except Exception:
pass
data = {
"actual_state": self.actual_state,
"state_reason": self.state_reason,
"victron_command_start": command_start,
"status_code": status_code,
"connected": connected,
"last_frequency_hz": self.last_frequency,
"last_ac_module_voltage_v": self.last_ac_module_voltage,
"last_ac_module_frequency_hz": self.last_ac_module_frequency,
"last_starter_voltage_v": self.last_starter_voltage,
"last_generator_charger_current_a": self.last_generator_charger_current,
"last_generator_charger_ac_voltage_v": self.last_generator_charger_ac_voltage,
"ac_panel_applied_source": self.ac_panel_applied_source,
"ac_panel_applied_source_text": (
self.service["/Scheiber/AcPanelAppliedSourceText"]
if self.service
else None
),
"house_panel_applied_source": (
self.service["/Scheiber/HousePanelAppliedSource"]
if self.service
else None
),
"house_panel_applied_source_text": (
self.service["/Scheiber/HousePanelAppliedSourceText"]
if self.service
else None
),
"mastervolt_inverter_state": self.mastervolt_inverter_state,
"mastervolt_inverter_state_text": (
"ON" if self.mastervolt_inverter_state == 1 else "OFF"
),
"ac_panel_voltage_v": self.last_ac_panel_voltage,
"house_panel_voltage_v": self.last_house_panel_voltage,
"startup_resync_active": self.startup_resync_active,
"startup_charger_ac_samples": self.startup_charger_ac_samples,
"last_scheiber_state_code": self.last_state_code,
"pending": self.pending,
"pending_origin": self.pending_origin,
"manager_service": self.manager_service,
"external_manual_adopted": self.external_manual_adopted,
"manager_cache": {
"manual_start": self.cached_manager_manual_start,
"manual_start_timer": self.cached_manager_manual_timer,
"running_by_code": self.cached_manager_running_by_code,
"running_by": self.cached_manager_running_by,
"state": self.cached_manager_state,
"updated_monotonic": self.cached_manager_updated,
},
"manager_recovery": {
"active": self.manager_recovery_active,
"reason": self.manager_recovery_reason,
"restore_manual": self.manager_recovery_restore_manual,
"timer": self.manager_recovery_timer,
"running_by_code": self.manager_recovery_running_by_code,
},
"batteries": batteries,
"tanks": tanks,
"updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
tmp = STATUSFILE + ".tmp"
try:
with open(tmp, "w") as f:
json.dump(data, f, indent=2, sort_keys=True)
f.write("\n")
os.replace(tmp, STATUSFILE)
except Exception as e:
self.log("WARNING: could not write status.json: {}".format(e))
# ------------------------------------------------------------------
# Victron D-Bus service
# ------------------------------------------------------------------
def setup_dbus(self):
self.service = VeDbusService(SERVICE_NAME, register=False)
self.service.add_mandatory_paths(
processname=os.path.abspath(__file__),
processversion=BRIDGE_VERSION,
connection="Scheiber CAN on {}".format(CAN_IF),
deviceinstance=DEVICE_INSTANCE,
productid=PRODUCT_ID,
productname=PRODUCT_NAME,
firmwareversion=BRIDGE_VERSION,
hardwareversion=None,
connected=0,
)
self.service.add_path("/CustomName", PRODUCT_NAME)
self.service.add_path("/Serial", "scheiber-can-{}".format(CAN_IF))
self.service.add_path("/Model", "Scheiber CAN bridge")
self.service.add_path("/Role", "genset")
self.service.add_path("/NrOfPhases", 1)
# Required by Victron's connected-genset driver.
self.service.add_path("/RemoteStartModeEnabled", 1)
# IMPORTANT: /Start is COMMAND state. It is changed only by an
# external D-Bus SetValue (normally Victron dbus_generator).
# Physical CAN feedback must never locally assign this path.
self.service.add_path(
"/Start",
0,
writeable=True,
onchangecallback=self.on_start_write,
)
# Initialize StatusCode to a valid numeric value so dbus_generator
# recognizes this genset as providing feedback from the moment it is
# discovered. CAN observations will immediately replace it as needed.
self.service.add_path("/StatusCode", STATUS_STOPPED)
# Victron genset integrations commonly expose /Ac/Frequency. Keep
# /Ac/L1/Frequency too for compatibility with existing V5.1 consumers.
self.service.add_path(
"/Ac/Frequency",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.1f} Hz".format(float(v))
),
)
self.service.add_path(
"/Ac/L1/Frequency",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.1f} Hz".format(float(v))
),
)
self.service.add_path(
"/Ac/L1/Voltage",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.0f} V".format(float(v))
),
)
self.service.add_path(
"/StarterVoltage",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.1f} V".format(float(v))
),
)
self.service.add_path("/StarterVoltageAlarm", 0)
self.service.add_path("/Alarms/StarterVoltage", 0)
# Diagnostic paths. They are ignored by normal Victron generator code.
self.service.add_path("/Scheiber/State", self.actual_state)
self.service.add_path("/Scheiber/StateCode", None)
self.service.add_path("/Scheiber/StateReason", self.state_reason)
self.service.add_path("/Scheiber/AcModuleVoltage", None)
self.service.add_path("/Scheiber/AcModuleFrequency", None)
self.service.add_path("/Scheiber/GeneratorChargerCurrent", None)
self.service.add_path("/Scheiber/GeneratorChargerAcVoltage", None)
self.service.add_path("/Scheiber/AcPanelAppliedSource", None)
self.service.add_path("/Scheiber/AcPanelAppliedSourceText", None)
self.service.add_path("/Scheiber/HousePanelAppliedSource", None)
self.service.add_path("/Scheiber/HousePanelAppliedSourceText", None)
self.service.add_path(
"/Scheiber/MastervoltInverterState",
1 if MASTERVOLT_DEFAULT_ENABLED else 0,
)
self.service.add_path(
"/Scheiber/MastervoltInverterStateText",
"ON" if MASTERVOLT_DEFAULT_ENABLED else "OFF",
)
self.service.add_path("/Scheiber/MastervoltSupplyingHouse", 0)
self.service.add_path("/Scheiber/MastervoltSupplyingHouseText", "NO")
self.service.add_path("/Scheiber/AcPanelVoltage", None)
self.service.add_path("/Scheiber/HousePanelVoltage", None)
self.service.add_path("/Scheiber/AcPanelFrequencyStatus", None)
self.service.add_path("/Scheiber/HousePanelFrequencyStatus", None)
self.service.add_path("/Scheiber/StartupResyncActive", 1)
self.service.register()
self.log("Registered {}".format(SERVICE_NAME))
def setup_grid_service(self):
"""Create native Victron grid/shore power telemetry service (receive-only)."""
service_name = "com.victronenergy.grid.scheiber_shore"
self.shore_bus = dbus.Bus.get_system(private=True)
svc = VeDbusService(
service_name,
bus=self.shore_bus,
register=False,
)
svc.add_mandatory_paths(
processname=os.path.abspath(__file__),
processversion=BRIDGE_VERSION,
connection="Scheiber CAN on {}".format(CAN_IF),
deviceinstance=41,
productid=PRODUCT_ID,
productname="Scheiber Shore Power",
firmwareversion=BRIDGE_VERSION,
hardwareversion=None,
connected=0,
)
svc.add_path("/CustomName", "Shore Power")
# GUI-v2 reads /NrOfPhases for grid/genset meter services. Keep the
# newer /Ac/NumberOfPhases path as well for other consumers.
svc.add_path("/NrOfPhases", 1)
svc.add_path("/Ac/NumberOfPhases", 1)
svc.add_path(
"/Ac/L1/Voltage",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.1f} V".format(float(v))
),
)
svc.add_path(
"/Ac/L1/Current",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.1f} A".format(float(v))
),
)
svc.add_path(
"/Ac/L1/Power",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.0f} W".format(float(v))
),
)
svc.add_path("/Ac/L1/Energy/Forward", None)
svc.add_path("/Ac/L1/Energy/Reverse", None)
svc.register()
self.shore_service = svc
self.log("Registered {}".format(service_name))
def setup_acsystem_service(self):
"""Describe the receive-only House source selector to Venus OS.
Venus AC-system input types use 3 for Shore and 2 for Generator. The
physical Scheiber applied-state feedback selects input 0 or 1. No
writable paths are exposed: this service reports topology and
measurements only and cannot operate either selector panel.
"""
self.acsystem_bus = dbus.Bus.get_system(private=True)
svc = VeDbusService(
AC_SYSTEM_SERVICE_NAME,
bus=self.acsystem_bus,
register=False,
)
svc.add_mandatory_paths(
processname=os.path.abspath(__file__),
processversion=BRIDGE_VERSION,
connection="Scheiber CAN on {} (receive-only)".format(CAN_IF),
deviceinstance=AC_SYSTEM_DEVICE_INSTANCE,
productid=PRODUCT_ID,
productname="Scheiber House AC Selector",
firmwareversion=BRIDGE_VERSION,
hardwareversion=None,
connected=0,
)
svc.add_path("/CustomName", "House AC Source Selector")
svc.add_path("/Serial", "scheiber-house-selector-{}".format(CAN_IF))
svc.add_path("/Ac/NumberOfAcInputs", 2)
svc.add_path("/Ac/NumberOfPhases", 1)
svc.add_path("/State", 0)
svc.add_path("/Ac/In/1/Type", 3) # Shore
svc.add_path("/Ac/In/2/Type", 2) # Generator
svc.add_path("/Ac/ActiveIn/ActiveInput", 0xF0)
for input_number in (1, 2):
prefix = "/Ac/In/{}/L1".format(input_number)
svc.add_path(
prefix + "/V",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.0f} V".format(float(v))
),
)
svc.add_path(prefix + "/I", None)
svc.add_path(prefix + "/P", None)
svc.add_path(prefix + "/F", None)
svc.add_path(
"/Ac/Out/L1/V",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.0f} V".format(float(v))
),
)
svc.add_path("/Ac/Out/L1/I", None)
svc.add_path("/Ac/Out/L1/P", None)
svc.add_path("/Scheiber/HousePanelAppliedSource", None)
svc.add_path("/Scheiber/HousePanelAppliedSourceText", None)
svc.add_path("/Scheiber/SelectorStateText", "House source unknown")
svc.add_path("/Scheiber/AcPanelAppliedSource", None)
svc.add_path("/Scheiber/AcPanelAppliedSourceText", None)
svc.add_path("/Scheiber/HousePanelVoltage", None)
svc.add_path("/Scheiber/AcPanelVoltage", None)
svc.register()
self.acsystem_service = svc
self.log("Registered {} (receive-only)".format(AC_SYSTEM_SERVICE_NAME))
def setup_mastervolt_inverter_service(self):
"""Create native Victron inverter telemetry service for MasterVolt 2000W."""
service_name = "com.victronenergy.inverter.scheiber_mastervolt"
self.mastervolt_bus = dbus.Bus.get_system(private=True)
svc = VeDbusService(
service_name,
bus=self.mastervolt_bus,
register=False,
)
svc.add_mandatory_paths(
processname=os.path.abspath(__file__),
processversion=BRIDGE_VERSION,
connection="Scheiber CAN on {}".format(CAN_IF),
deviceinstance=270,
productid=PRODUCT_ID,
productname="MasterVolt 2000W Inverter",
firmwareversion=BRIDGE_VERSION,
hardwareversion=None,
connected=1,
)
svc.add_path("/CustomName", "MasterVolt 2000W")
svc.add_path("/State", 0)
svc.add_path("/Mode", 4)
svc.add_path(
"/Ac/Out/L1/V",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.1f} V".format(float(v))
),
)
svc.add_path(
"/Ac/Out/L1/P",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.0f} W".format(float(v))
),
)
svc.add_path(
"/Ac/Out/L1/I",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.1f} A".format(float(v))
),
)
svc.add_path(
"/Dc/0/Voltage",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.2f} V".format(float(v))
),
)
svc.add_path("/Alarms/LowVoltage", 0)
svc.add_path("/Alarms/HighVoltage", 0)
svc.add_path("/Alarms/Overload", 0)
svc.add_path("/Alarms/HighTemperature", 0)
svc.register()
self.mastervolt_service = svc
self.log("Registered {}".format(service_name))
def setup_battery_services(self):
"""Create native Victron battery telemetry services.
House-bank voltage and SoC are confirmed for this installation.
House-bank current sign/offset are strong; the x0.1 A scale remains
a candidate and is intentionally kept easy to change.
Engine Battery A/B source IDs and voltage scale are explicitly
experimental. The raw word and scale are also exported so the mapping
can be validated without losing the original data.
"""
if REQUIRE_EXPLICIT_SYSTEM_BATTERY:
try:
selected = str(
self.dbus_get(
"com.victronenergy.settings",
"/Settings/SystemSetup/BatteryService",
)
)
except Exception as e:
self.log(
"SAFETY: could not read GX system battery selection ({}); "
"native Scheiber battery services will NOT be registered"
.format(e)
)
return
if selected in ("default", "None", ""):
self.log(
"SAFETY: GX system battery is not explicitly selected "
"(value={!r}). Native Scheiber battery services are NOT "
"registered to avoid displacing the SmartShunt. Select "
"the SmartShunt explicitly, then restart this bridge."
.format(selected)
)
return
self.log(
"GX system battery selection is explicit: {}; enabling "
"Scheiber per-battery services".format(selected)
)
for key, suffix, instance, custom_name, can_id, mode in BATTERY_DEFS:
service_name = "com.victronenergy.battery.{}".format(suffix)
# IMPORTANT: use a separate private D-Bus connection per exported
# battery service. VeDbusService exports identical object paths
# (/, /Mgmt/..., /Dc/0/...) for every service. Those paths are
# connection-scoped in dbus-python, so sharing the process-wide
# SystemBus connection makes the second service collide and crash.
battery_bus = dbus.Bus.get_system(private=True)
svc = VeDbusService(
service_name,
bus=battery_bus,
register=False,
)
svc.add_mandatory_paths(
processname=os.path.abspath(__file__),
processversion=BRIDGE_VERSION,
connection="Scheiber CAN on {}".format(CAN_IF),
deviceinstance=instance,
productid=PRODUCT_ID,
productname=custom_name,
firmwareversion=BRIDGE_VERSION,
hardwareversion=None,
connected=0,
)
svc.add_path("/CustomName", custom_name)
svc.add_path("/Serial", "{}-{:08X}".format(suffix, can_id))
svc.add_path(
"/Dc/0/Voltage",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.2f} V".format(float(v))
),
)
svc.add_path(
"/Dc/0/Current",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.1f} A".format(float(v))
),
)
svc.add_path(
"/Dc/0/Power",
None,
gettextcallback=lambda p, v: (
"---" if v is None else "{:.0f} W".format(float(v))
),
)
svc.add_path(
"/Soc",
None,