forked from jepefe/dbus_generator
-
Notifications
You must be signed in to change notification settings - Fork 9
/
startstop.py
1356 lines (1141 loc) · 51.1 KB
/
startstop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python -u
# -*- coding: utf-8 -*-
# Function
# dbus_generator monitors the dbus for batteries (com.victronenergy.battery.*) and
# vebus com.victronenergy.vebus.*
# Battery and vebus monitors can be configured through the gui.
# It then monitors SOC, AC loads, battery current and battery voltage,to auto start/stop the generator based
# on the configuration settings. Generator can be started manually or periodically setting a tes trun period.
# Time zones function allows to use different values for the conditions along the day depending on time
import dbus
import datetime
import calendar
import time
import sys
import json
import os
import logging
from collections import OrderedDict
import monotonic_time
from gen_utils import SettingsPrefix, Errors, States, enum
from gen_utils import create_dbus_service
# Victron packages
sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'ext', 'velib_python'))
from ve_utils import exit_on_error
from settingsdevice import SettingsDevice
RunningConditions = enum(
Stopped = 0,
Manual = 1,
TestRun = 2,
LossOfCommunication = 3,
Soc = 4,
Acload = 5,
BatteryCurrent = 6,
BatteryVoltage = 7,
InverterHighTemp = 8,
InverterOverload = 9,
StopOnAc1 = 10,
StopOnAc2 = 11)
Capabilities = enum(
WarmupCooldown = 1
)
SYSTEM_SERVICE = 'com.victronenergy.system'
BATTERY_PREFIX = '/Dc/Battery'
HISTORY_DAYS = 30
AUTOSTART_DISABLED_ALARM_TIME = 600
def safe_max(args):
try:
return max(x for x in args if x is not None)
except ValueError:
return None
class Condition(object):
def __init__(self, parent):
self.parent = parent
self.reached = False
self.start_timer = 0
self.stop_timer = 0
self.valid = True
self.enabled = False
self.retries = 0
def __getitem__(self, key):
try:
return getattr(self, key)
except AttributeError:
raise KeyError(key)
def __setitem__(self, key, value):
setattr(self, key, value)
def get_value(self):
raise NotImplementedError("get_value")
@property
def multi_service(self):
return self.parent.multiservice
@property
def multi_service_type(self):
return self.parent.multiservice_type
@property
def monitor(self):
return self.parent._dbusmonitor
class SocCondition(Condition):
name = 'soc'
monitoring = 'battery'
boolean = False
timed = True
def get_value(self):
return self.parent._get_battery().soc
class AcLoadCondition(Condition):
name = 'acload'
monitoring = 'vebus'
boolean = False
timed = True
def get_value(self):
loadOnAcOut = []
totalConsumption = []
for phase in ['L1', 'L2', 'L3']:
# Get the values directly from the inverter, systemcalc doesn't provide raw inverted power
loadOnAcOut.append(self.monitor.get_value(self.multi_service, ('/Ac/Out/%s/P' % phase)))
# Calculate total consumption, '/Ac/Consumption/%s/Power' is deprecated
c_i = self.monitor.get_value(SYSTEM_SERVICE, ('/Ac/ConsumptionOnInput/%s/Power' % phase))
c_o = self.monitor.get_value(SYSTEM_SERVICE, ('/Ac/ConsumptionOnOutput/%s/Power' % phase))
totalConsumption.append(sum(filter(None, (c_i, c_o))))
# Invalidate if vebus is not available
if loadOnAcOut[0] == None:
return None
# Total consumption
if self.parent._settings['acloadmeasurement'] == 0:
return sum(filter(None, totalConsumption))
# Load on inverter AC out
if self.parent._settings['acloadmeasurement'] == 1:
return sum(filter(None, loadOnAcOut))
# Highest phase load
if self.parent._settings['acloadmeasurement'] == 2:
return safe_max(loadOnAcOut)
class BatteryCurrentCondition(Condition):
name = 'batterycurrent'
monitoring = 'battery'
boolean = False
timed = True
def get_value(self):
c = self.parent._get_battery().current
if c is not None:
c *= -1
return c
class BatteryVoltageCondition(Condition):
name = 'batteryvoltage'
monitoring = 'battery'
boolean = False
timed = True
def get_value(self):
return self.parent._get_battery().voltage
class InverterTempCondition(Condition):
name = 'inverterhightemp'
monitoring = 'vebus'
boolean = True
timed = True
def get_value(self):
v = self.monitor.get_value(self.multi_service,
'/Alarms/HighTemperature')
# When multi is connected to CAN-bus, alarms are published to
# /Alarms/HighTemperature... but when connected to vebus alarms are
# splitted in three phases and published to /Alarms/LX/HighTemperature...
if v is None:
inverterHighTemp = []
for phase in ['L1', 'L2', 'L3']:
# Inverter alarms must be fetched directly from the inverter service
inverterHighTemp.append(self.monitor.get_value(self.multi_service, ('/Alarms/%s/HighTemperature' % phase)))
return safe_max(inverterHighTemp)
return v
class InverterOverloadCondition(Condition):
name = 'inverteroverload'
monitoring = 'vebus'
boolean = True
timed = True
def get_value(self):
v = self.monitor.get_value(self.multi_service,
'/Alarms/Overload')
# When multi is connected to CAN-bus, alarms are published to
# /Alarms/Overload... but when connected to vebus alarms are
# splitted in three phases and published to /Alarms/LX/Overload...
if v is None:
inverterOverload = []
for phase in ['L1', 'L2', 'L3']:
# Inverter alarms must be fetched directly from the inverter service
inverterOverload.append(self.monitor.get_value(self.multi_service, ('/Alarms/%s/Overload' % phase)))
return safe_max(inverterOverload)
return v
# The 'Stop on AC [1/2] conditions are disabled for the Multi RS (acsystem)
# The 'stop on AC' condition stops the generator, which is connected to one AC input when there is AC detected on the other.
# Since the Multi RS only has one AC input, these conditions cannot be used.
class StopOnAc1Condition(Condition):
name = 'stoponac1'
monitoring = 'vebus'
boolean = True
timed = False
def get_value(self):
# AC input 1
if self.multi_service_type == 'vebus':
available = self.monitor.get_value(self.multi_service,
'/Ac/State/AcIn1Available')
if available is None:
# Not supported in firmware, fall back to old behaviour
activein = self.monitor.get_value(self.multi_service,
'/Ac/ActiveIn/ActiveInput')
# Active input is connected
connected = self.monitor.get_value(self.multi_service,
'/Ac/ActiveIn/Connected')
if None not in (activein, connected):
return activein == 0 and connected == 1
return None
return bool(available)
else:
# Disabled
return False
# The StopOnAc2 condition cannot have the fallback to evaluating based on`/Ac/ActiveIn/ActiveInput` + `/Ac/ActiveIn/Connected`
# Because these paths were present in the vebus firmware before `/Ac/State/AcIn2Available` was,
# but switching over to AC input 2 was not supported in that firmware version.
# So if the fallback were implemented for this condition as well, it would stop the
# generator when AC in 2 becomes available but the quattro would not switch over.
class StopOnAc2Condition(Condition):
name = 'stoponac2'
monitoring = 'vebus'
boolean = True
timed = False
def get_value(self):
if self.multi_service_type == 'vebus':
# AC input 2 available (used when grid is on AC-in-2)
available = self.monitor.get_value(self.multi_service,
'/Ac/State/AcIn2Available')
return None if available is None else bool(available)
else:
# Disabled
return False
class Battery(object):
def __init__(self, monitor, service, prefix):
self.monitor = monitor
self.service = service
self.prefix = prefix
@property
def voltage(self):
return self.monitor.get_value(self.service, self.prefix + '/Voltage')
@property
def current(self):
return self.monitor.get_value(self.service, self.prefix + '/Current')
@property
def soc(self):
# Soc from the device doesn't have the '/Dc/0' prefix like the current and voltage do, but it does
# have the same prefix on systemcalc
return self.monitor.get_value(self.service, (BATTERY_PREFIX if self.prefix == BATTERY_PREFIX else '') + '/Soc')
class StartStop(object):
_driver = None
def __init__(self, instance):
self._dbusservice = None
self._settings = None
self._dbusmonitor = None
self._remoteservice = None
self._name = None
self._enabled = False
self._generator_running = False
self._useGensetHours = False # Sync with genset operatinghours.
self._instance = instance
# One second per retry
self.RETRIES_ON_ERROR = 300
self._testrun_soc_retries = 0
self._last_counters_check = 0
# Two different starttime values.
# starttime_fb is set by the modules (relay.py, genset.py) and will be set to the current time when
# the feedback mechanism (digital input / `/StatusCode`) indicates that the generator is running.
# The other one is set by startstop when commanding the module to start the generator and is used by the
# warm-up mechanism to ensure warm-up finishes without needing feedback that the generator has actually started.
# If there is no feedback mechanism in place, the values will be equal as the module will call '_generator_started()`
# right after receiving the start command from startstop.
self._starttime_fb = 0 # Starttime of the generator as reported by the feedback mechanism (e.g., digital input), if present
self._starttime = 0 # Starttime of the generator, maintained by startstop. Not influenced by feedback mechanism.
self._stoptime = 0 # Used for cooldown
self._manualstarttimer = 0
self._last_runtime_update = 0
self._timer_runnning = 0
# The installer left autostart disabled
self._autostart_last_time = self._get_monotonic_seconds()
self._remote_start_mode_last_time = self._get_monotonic_seconds()
# Manual battery service selection is deprecated in favour
# of getting the values directly from systemcalc, we keep
# manual selected services handling for compatibility reasons.
self._vebusservice = None
self._acsystemservice = None
self._errorstate = 0
self._battery_service = None
self._battery_prefix = None
self._acpower_inverter_input = {
'timeout': 0,
'unabletostart': False
}
# Order is important. Conditions are evaluated in the order listed.
self._condition_stack = OrderedDict({
SocCondition.name: SocCondition(self),
AcLoadCondition.name: AcLoadCondition(self),
BatteryCurrentCondition.name: BatteryCurrentCondition(self),
BatteryVoltageCondition.name: BatteryVoltageCondition(self),
InverterTempCondition.name: InverterTempCondition(self),
InverterOverloadCondition.name: InverterOverloadCondition(self),
StopOnAc1Condition.name: StopOnAc1Condition(self),
StopOnAc2Condition.name: StopOnAc2Condition(self)
})
# Return the active vebusservice or the acsystemservice.
@property
def multiservice(self):
return self._vebusservice if self._vebusservice else self._acsystemservice if self._acsystemservice else None
@property
def multiservice_type(self):
return self.multiservice.split('.')[2] if self.multiservice is not None else None
def set_sources(self, dbusmonitor, settings, name, remoteservice):
self._settings = SettingsPrefix(settings, name)
self._dbusmonitor = dbusmonitor
self._remoteservice = remoteservice
self._name = name
self.log_info('Start/stop instance created for %s.' % self._remoteservice)
self._remote_setup()
def _create_service(self):
self._dbusservice = self._create_dbus_service()
# The driver used for this start/stop service
self._dbusservice.add_path('/Type', value=self._driver)
# State: None = invalid, 0 = stopped, 1 = running, 2=Warm-up, 3=Cool-down
self._dbusservice.add_path('/State', value=None, gettextcallback=lambda p, v: States.get_description(v))
self._dbusservice.add_path('/Enabled', value=1)
# RunningByConditionCode: Numeric Companion to /RunningByCondition below, but
# also encompassing a Stopped state.
self._dbusservice.add_path('/RunningByConditionCode', value=None)
# Error
self._dbusservice.add_path('/Error', value=None, gettextcallback=lambda p, v: Errors.get_description(v))
# Condition that made the generator start
self._dbusservice.add_path('/RunningByCondition', value=None)
# Runtime
self._dbusservice.add_path('/Runtime', value=None, gettextcallback=self._seconds_to_text)
# Today runtime
self._dbusservice.add_path('/TodayRuntime', value=None, gettextcallback=self._seconds_to_text)
# Test run runtime
self._dbusservice.add_path('/TestRunIntervalRuntime', value=None , gettextcallback=self._seconds_to_text)
# Next test run date, values is 0 for test run disabled
self._dbusservice.add_path('/NextTestRun', value=None, gettextcallback=lambda p, v: datetime.datetime.fromtimestamp(v).strftime('%c'))
# Next test run is needed 1, not needed 0
self._dbusservice.add_path('/SkipTestRun', value=None)
# Manual start
self._dbusservice.add_path('/ManualStart', value=None, writeable=True)
# Manual start timer
self._dbusservice.add_path('/ManualStartTimer', value=None, writeable=True)
# Silent mode active
self._dbusservice.add_path('/QuietHours', value=None)
# Alarms
self._dbusservice.add_path('/Alarms/NoGeneratorAtAcIn', value=None)
self._dbusservice.add_path('/Alarms/ServiceIntervalExceeded', value=None)
self._dbusservice.add_path('/Alarms/AutoStartDisabled', value=None)
self._dbusservice.add_path('/Alarms/RemoteStartModeDisabled', value=None)
# Autostart
self._dbusservice.add_path('/AutoStartEnabled', value=None, writeable=True, onchangecallback=self._set_autostart)
# Accumulated runtime
self._dbusservice.add_path('/AccumulatedRuntime', value=None)
# Service interval
self._dbusservice.add_path('/ServiceInterval', value=None)
# Capabilities, where we can add bits
self._dbusservice.add_path('/Capabilities', value=0)
# Service countdown, calculated by running time and service interval
self._dbusservice.add_path('/ServiceCounter', value=None)
self._dbusservice.add_path('/ServiceCounterReset', value=None, writeable=True, onchangecallback=self._reset_service_counter)
# Publish what service we're controlling, and the productid
self._dbusservice.add_path('/GensetService', value=self._remoteservice)
self._dbusservice.add_path('/GensetServiceType',
value=self._remoteservice.split('.')[2] if self._remoteservice is not None else None)
self._dbusservice.add_path('/GensetInstance',
value=self._dbusmonitor.get_value(self._remoteservice, '/DeviceInstance'))
self._dbusservice.add_path('/GensetProductId',
value=self._dbusmonitor.get_value(self._remoteservice, '/ProductId'))
self._dbusservice.add_path('/DigitalInput/Running', value=None, writeable=True, onchangecallback=self._running_by_digital_input)
self._dbusservice.add_path('/DigitalInput/Input', value=None, writeable=True, onchangecallback=self._running_by_digital_input)
self._dbusservice.register()
# We need to set the values after creating the paths to trigger the 'onValueChanged' event for the gui
# otherwise the gui will report the paths as invalid if we remove and recreate the paths without
# restarting the dbusservice.
self._dbusservice['/State'] = 0
self._dbusservice['/RunningByConditionCode'] = RunningConditions.Stopped
self._dbusservice['/Error'] = 0
self._dbusservice['/RunningByCondition'] = ''
self._dbusservice['/Runtime'] = 0
self._dbusservice['/TodayRuntime'] = 0
self._dbusservice['/TestRunIntervalRuntime'] = self._interval_runtime(self._settings['testruninterval'])
self._dbusservice['/NextTestRun'] = None
self._dbusservice['/SkipTestRun'] = None
self._dbusservice['/ProductName'] = "Generator start/stop"
self._dbusservice['/ManualStart'] = 0
self._dbusservice['/ManualStartTimer'] = 0
self._dbusservice['/QuietHours'] = 0
self._dbusservice['/Alarms/NoGeneratorAtAcIn'] = 0
self._dbusservice['/Alarms/ServiceIntervalExceeded'] = 0
self._dbusservice['/Alarms/AutoStartDisabled'] = 0 # GX auto start/stop
self._dbusservice['/Alarms/RemoteStartModeDisabled'] = 0 # Genset remote start mode
self._dbusservice['/AutoStartEnabled'] = self._settings['autostart']
self._dbusservice['/AccumulatedRuntime'] = int(self._settings['accumulatedtotal'])
self._dbusservice['/ServiceInterval'] = int(self._settings['serviceinterval'])
self._dbusservice['/ServiceCounter'] = None
self._dbusservice['/ServiceCounterReset'] = 0
self._dbusservice['/DigitalInput/Running'] = 0
self._dbusservice['/DigitalInput/Input'] = 0
# When this startstop instance controls a genset which reports operatinghours, make sure to synchronize with that.
self._useGensetHours = self._dbusmonitor.get_value(self._remoteservice, '/Engine/OperatingHours', None) is not None
@property
def _is_running(self):
return self._generator_running
@property
def capabilities(self):
return self._dbusservice['/Capabilities']
def _set_autostart(self, path, value):
if 0 <= value <= 1:
self._settings['autostart'] = int(value)
return True
return False
def enable(self):
if self._enabled:
return
self.log_info('Enabling auto start/stop and taking control of remote switch')
self._create_service()
self._determineservices()
self._update_remote_switch()
# If cooldown or warmup is enabled, the Quattro may be left in a bad
# state if there is an unfortunate crash or a reboot. Set the ignore_ac
# flag to a sane value on startup.
if self._settings['cooldowntime'] > 0 or \
self._settings['warmuptime'] > 0:
self._set_ignore_ac(False)
self._enabled = True
def disable(self):
if not self._enabled:
return
self.log_info('Disabling auto start/stop, releasing control of remote switch')
self._remove_service()
self._enabled = False
def remove(self):
self.disable()
self.log_info('Removed from start/stop instances')
def _remove_service(self):
self._dbusservice.__del__()
self._dbusservice = None
def device_added(self, dbusservicename, instance):
self._determineservices()
def device_removed(self, dbusservicename, instance):
self._determineservices()
def get_error(self):
return self._dbusservice['/Error']
def set_error(self, errorn):
self._dbusservice['/Error'] = errorn
def clear_error(self):
self._dbusservice['/Error'] = Errors.NONE
def dbus_value_changed(self, dbusServiceName, dbusPath, options, changes, deviceInstance):
if self._dbusservice is None:
return
# AcIn1Available is needed to determine capabilities, but may
# only show up later. So we have to wait for it here.
if self.multiservice is not None and \
dbusServiceName == self.multiservice and \
dbusPath == '/Ac/State/AcIn1Available' or dbusPath == '/Ac/Control/IgnoreAcIn1':
self._set_capabilities()
# If gensethours is updated, update the accumulated time.
if dbusPath == '/Engine/OperatingHours' and self._useGensetHours:
self._update_accumulated_time(gensetHours=changes['Value'])
if dbusServiceName != 'com.victronenergy.system':
return
if dbusPath == '/AutoSelectedBatteryMeasurement' and self._settings['batterymeasurement'] == 'default':
self._determineservices()
if dbusPath == '/VebusService':
self._determineservices()
def handlechangedsetting(self, setting, oldvalue, newvalue):
if self._dbusservice is None:
return
if self._name not in setting:
# Not our setting
return
s = self._settings.removeprefix(setting)
if s == 'batterymeasurement':
self._determineservices()
# Reset retries and valid if service changes
for condition in self._condition_stack.values():
if condition['monitoring'] == 'battery':
condition['valid'] = True
condition['retries'] = 0
if s == 'autostart':
self.log_info('Autostart function %s.' % ('enabled' if newvalue == 1 else 'disabled'))
self._dbusservice['/AutoStartEnabled'] = self._settings['autostart']
if self._dbusservice is not None and s == 'testruninterval':
self._dbusservice['/TestRunIntervalRuntime'] = self._interval_runtime(
self._settings['testruninterval'])
if s == 'serviceinterval':
try:
self._dbusservice['/ServiceInterval'] = int(newvalue)
except TypeError:
pass
if newvalue == 0:
self._dbusservice['/ServiceCounter'] = None
else:
self._update_accumulated_time()
if s == 'lastservicereset':
self._update_accumulated_time()
def _reset_service_counter(self, path, value):
if (path == '/ServiceCounterReset' and value == int(1) and self._dbusservice['/AccumulatedRuntime']):
self._settings['lastservicereset'] = self._dbusservice['/AccumulatedRuntime']
self._update_accumulated_time()
self.log_info('Service counter reset triggered.')
return True
def _seconds_to_text(self, path, value):
m, s = divmod(value, 60)
h, m = divmod(m, 60)
return '%dh, %dm, %ds' % (h, m, s)
def log_info(self, msg):
logging.info(self._name + ': %s' % msg)
def tick(self):
if not self._enabled:
return
self._check_remote_status()
self._evaluate_startstop_conditions()
self._evaluate_autostart_disabled_alarm()
self._detect_generator_at_acinput()
if self._dbusservice['/ServiceCounterReset'] == 1:
self._dbusservice['/ServiceCounterReset'] = 0
def _evaluate_startstop_conditions(self):
if self.get_error() != Errors.NONE:
# First evaluation after an error, log it
if self._errorstate == 0:
self._errorstate = 1
self._dbusservice['/State'] = States.ERROR
self.log_info('Error: #%i - %s, stop controlling remote.' %
(self.get_error(),
Errors.get_description(self.get_error())))
elif self._errorstate == 1:
# Error cleared
self._errorstate = 0
self._dbusservice['/State'] = States.STOPPED
self.log_info('Error state cleared, taking control of remote switch.')
start = False
startbycondition = None
activecondition = self._dbusservice['/RunningByCondition']
today = calendar.timegm(datetime.date.today().timetuple())
self._timer_runnning = False
connection_lost = False
running = self._dbusservice['/State'] in (States.RUNNING, States.WARMUP)
self._check_quiet_hours()
# New day, register it
if self._last_counters_check < today and self._dbusservice['/State'] == States.STOPPED:
self._last_counters_check = today
self._update_accumulated_time()
self._update_runtime()
if self._evaluate_manual_start():
startbycondition = 'manual'
start = True
# Conditions will only be evaluated if the autostart functionality is enabled
if self._settings['autostart'] == 1:
if self._evaluate_testrun_condition():
startbycondition = 'testrun'
start = True
# Evaluate stop on AC IN conditions first, when this conditions are enabled and reached the generator
# will stop as soon as AC IN in active. Manual and testrun conditions will make the generator start
# or keep it running.
stop_on_ac_reached = (self._evaluate_condition(self._condition_stack[StopOnAc1Condition.name]) or
self._evaluate_condition(self._condition_stack[StopOnAc2Condition.name]))
stop_by_ac1_ac2 = startbycondition not in ['manual', 'testrun'] and stop_on_ac_reached
if stop_by_ac1_ac2 and running and activecondition not in ['manual', 'testrun']:
self.log_info('AC input available, stopping')
# Evaluate value conditions
for condition, data in self._condition_stack.items():
# Do not evaluate rest of conditions if generator is configured to stop
# when AC IN is available
if stop_by_ac1_ac2:
start = False
if running:
self._reset_condition(data)
continue
else:
break
# Don't short-circuit this, _evaluate_condition sets .reached
start = self._evaluate_condition(data) or start
startbycondition = condition if start and startbycondition is None else startbycondition
# Connection lost is set to true if the number of retries of one or more enabled conditions
# >= RETRIES_ON_ERROR
if data.enabled:
connection_lost = data.retries >= self.RETRIES_ON_ERROR
# If none condition is reached check if connection is lost and start/keep running the generator
# depending on '/OnLossCommunication' setting
if not start and connection_lost:
# Start always
if self._settings['onlosscommunication'] == 1:
start = True
startbycondition = 'lossofcommunication'
# Keep running if generator already started
if running and self._settings['onlosscommunication'] == 2:
start = True
startbycondition = 'lossofcommunication'
if not start and self._errorstate:
self._stop_generator()
if self._errorstate:
return
mtime = monotonic_time.monotonic_time().to_seconds_double()
if start:
self._start_generator(startbycondition)
elif (int(mtime - self._starttime) >= self._settings['minimumruntime'] * 60
or activecondition == 'manual'):
self._stop_generator()
def _update_runtime(self, just_stopped=False):
# Update current and accumulated runtime.
# By performance reasons, accumulated runtime is only updated
# once per 60s. When the generator stops is also updated.
if self._is_running or just_stopped:
mtime = monotonic_time.monotonic_time().to_seconds_double()
if (mtime - self._starttime_fb) - self._last_runtime_update >= 60 or just_stopped:
self._dbusservice['/Runtime'] = int(mtime - self._starttime_fb)
self._update_accumulated_time()
elif self._last_runtime_update == 0:
self._dbusservice['/Runtime'] = int(mtime - self._starttime_fb)
def _evaluate_autostart_disabled_alarm(self):
if self._settings['autostartdisabledalarm'] == 0:
self._autostart_last_time = self._get_monotonic_seconds()
self._remote_start_mode_last_time = self._get_monotonic_seconds()
if self._dbusservice['/Alarms/AutoStartDisabled'] != 0:
self._dbusservice['/Alarms/AutoStartDisabled'] = 0
if self._dbusservice['/Alarms/RemoteStartModeDisabled'] != 0:
self._dbusservice['/Alarms/RemoteStartModeDisabled'] = 0
return
# GX auto start/stop alarm
if self._settings['autostart'] == 1:
self._autostart_last_time = self._get_monotonic_seconds()
if self._dbusservice['/Alarms/AutoStartDisabled'] != 0:
self._dbusservice['/Alarms/AutoStartDisabled'] = 0
else:
timedisabled = self._get_monotonic_seconds() - self._autostart_last_time
if timedisabled > AUTOSTART_DISABLED_ALARM_TIME and self._dbusservice['/Alarms/AutoStartDisabled'] != 2:
self.log_info("Autostart was left for more than %i seconds, triggering alarm." % int(timedisabled))
self._dbusservice['/Alarms/AutoStartDisabled'] = 2
# Genset remote start mode alarm
if self.get_error() != Errors.REMOTEDISABLED:
self._remote_start_mode_last_time = self._get_monotonic_seconds()
if self._dbusservice['/Alarms/RemoteStartModeDisabled'] != 0:
self._dbusservice['/Alarms/RemoteStartModeDisabled'] = 0
else:
timedisabled = self._get_monotonic_seconds() - self._remote_start_mode_last_time
if timedisabled > AUTOSTART_DISABLED_ALARM_TIME and self._dbusservice['/Alarms/RemoteStartModeDisabled'] != 2:
self.log_info("Autostart was left for more than %i seconds, triggering alarm." % int(timedisabled))
self._dbusservice['/Alarms/RemoteStartModeDisabled'] = 2
def _detect_generator_at_acinput(self):
state = self._dbusservice['/State']
if state in [States.STOPPED, States.COOLDOWN, States.WARMUP]:
self._reset_acpower_inverter_input()
return
if self._settings['nogeneratoratacinalarm'] == 0:
self._reset_acpower_inverter_input()
return
if self.multiservice_type == 'vebus':
activein_state = self._dbusmonitor.get_value(
self.multiservice, '/Ac/ActiveIn/Connected')
else:
active_input = self._dbusmonitor.get_value(
self.multiservice, '/Ac/ActiveIn/ActiveInput')
activein_state = None if active_input is None else 1 if 0 <= active_input <= 1 else 0
# Path not supported, skip evaluation
if activein_state == None:
return
# Sources 0 = Not available, 1 = Grid, 2 = Generator, 3 = Shore
generator_acsource = self._dbusmonitor.get_value(
SYSTEM_SERVICE, '/Ac/ActiveIn/Source') == 2
# Not connected = 0, connected = 1
activein_connected = activein_state == 1
if generator_acsource and activein_connected:
if self._acpower_inverter_input['unabletostart']:
self.log_info('Generator detected at inverter AC input, alarm removed')
self._reset_acpower_inverter_input()
elif self._acpower_inverter_input['timeout'] < self.RETRIES_ON_ERROR:
self._acpower_inverter_input['timeout'] += 1
elif not self._acpower_inverter_input['unabletostart']:
self._acpower_inverter_input['unabletostart'] = True
self._dbusservice['/Alarms/NoGeneratorAtAcIn'] = 2
self.log_info('Generator not detected at inverter AC input, triggering alarm')
def _reset_acpower_inverter_input(self, clear_error=True):
if self._acpower_inverter_input['timeout'] != 0:
self._acpower_inverter_input['timeout'] = 0
if self._acpower_inverter_input['unabletostart'] != 0:
self._acpower_inverter_input['unabletostart'] = 0
self._dbusservice['/Alarms/NoGeneratorAtAcIn'] = 0
def _reset_condition(self, condition):
condition['reached'] = False
if condition['timed']:
condition['start_timer'] = 0
condition['stop_timer'] = 0
def _check_condition(self, condition, value):
name = condition['name']
if self._settings[name + 'enabled'] == 0:
if condition['enabled']:
condition['enabled'] = False
self.log_info('Disabling (%s) condition' % name)
condition['retries'] = 0
condition['valid'] = True
self._reset_condition(condition)
return False
elif not condition['enabled']:
condition['enabled'] = True
self.log_info('Enabling (%s) condition' % name)
if (condition['monitoring'] == 'battery') and (self._settings['batterymeasurement'] == 'nobattery'):
# If no battery monitor is selected reset the condition
self._reset_condition(condition)
return False
if value is None and condition['valid']:
if condition['retries'] >= self.RETRIES_ON_ERROR:
logging.info('Error getting (%s) value, skipping evaluation till get a valid value' % name)
self._reset_condition(condition)
self._comunnication_lost = True
condition['valid'] = False
else:
condition['retries'] += 1
if condition['retries'] == 1 or (condition['retries'] % 10) == 0:
self.log_info('Error getting (%s) value, retrying(#%i)' % (name, condition['retries']))
return False
elif value is not None and not condition['valid']:
self.log_info('Success getting (%s) value, resuming evaluation' % name)
condition['valid'] = True
condition['retries'] = 0
# Reset retries if value is valid
if value is not None and condition['retries'] > 0:
self.log_info('Success getting (%s) value, resuming evaluation' % name)
condition['retries'] = 0
return condition['valid']
def _evaluate_condition(self, condition):
name = condition['name']
value = condition.get_value()
setting = ('qh_' if self._dbusservice['/QuietHours'] == 1 else '') + name
startvalue = self._settings[setting + 'start'] if not condition['boolean'] else 1
stopvalue = self._settings[setting + 'stop'] if not condition['boolean'] else 0
# Check if the condition has to be evaluated
if not self._check_condition(condition, value):
# If generator is started by this condition and value is invalid
# wait till RETRIES_ON_ERROR to skip the condition
if condition['reached'] and condition['retries'] <= self.RETRIES_ON_ERROR:
if condition['retries'] > 0:
return True
return False
# As this is a generic evaluation method, we need to know how to compare the values
# first check if start value should be greater than stop value and then compare
start_is_greater = startvalue > stopvalue
# When the condition is already reached only the stop value can set it to False
start = condition['reached'] or (value >= startvalue if start_is_greater else value <= startvalue)
stop = value <= stopvalue if start_is_greater else value >= stopvalue
# Timed conditions must start/stop after the condition has been reached for a minimum
# time.
if condition['timed']:
if not condition['reached'] and start:
condition['start_timer'] += time.time() if condition['start_timer'] == 0 else 0
start = time.time() - condition['start_timer'] >= self._settings[name + 'starttimer']
condition['stop_timer'] *= int(not start)
self._timer_runnning = True
else:
condition['start_timer'] = 0
if condition['reached'] and stop:
condition['stop_timer'] += time.time() if condition['stop_timer'] == 0 else 0
stop = time.time() - condition['stop_timer'] >= self._settings[name + 'stoptimer']
condition['stop_timer'] *= int(not stop)
self._timer_runnning = True
else:
condition['stop_timer'] = 0
condition['reached'] = start and not stop
return condition['reached']
def _evaluate_manual_start(self):
if self._dbusservice['/ManualStart'] == 0:
if self._dbusservice['/RunningByCondition'] == 'manual':
self._dbusservice['/ManualStartTimer'] = 0
return False
start = True
# If /ManualStartTimer has a value greater than zero will use it to set a stop timer.
# If no timer is set, the generator will not stop until the user stops it manually.
# Once started by manual start, each evaluation the timer is decreased
if self._dbusservice['/ManualStartTimer'] != 0:
self._manualstarttimer += time.time() if self._manualstarttimer == 0 else 0
self._dbusservice['/ManualStartTimer'] -= int(time.time()) - int(self._manualstarttimer)
self._manualstarttimer = time.time()
start = self._dbusservice['/ManualStartTimer'] > 0
self._dbusservice['/ManualStart'] = int(start)
# Reset if timer is finished
self._manualstarttimer *= int(start)
self._dbusservice['/ManualStartTimer'] *= int(start)
return start
def _evaluate_testrun_condition(self):
if self._settings['testrunenabled'] == 0:
self._dbusservice['/SkipTestRun'] = None
self._dbusservice['/NextTestRun'] = None
return False
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1) # Should deal well with DST
now = time.time()
runtillbatteryfull = self._settings['testruntillbatteryfull'] == 1
soc = self._condition_stack['soc'].get_value()
batteryisfull = runtillbatteryfull and soc == 100
duration = 60 if runtillbatteryfull else self._settings['testrunruntime']
try:
startdate = datetime.date.fromtimestamp(self._settings['testrunstartdate'])
_starttime = time.mktime(yesterday.timetuple()) + self._settings['testrunstarttimer']
# today might in fact still be yesterday, if this test run started
# before midnight and finishes after. If `now` still falls in
# yesterday's window, then by the temporal anthropic principle,
# which I just made up but loosely states that time must have
# these properties for observers to exist, it must be yesterday
# because we are here to observe it.
if _starttime <= now <= _starttime + duration:
today = yesterday
starttime = _starttime
else:
starttime = time.mktime(today.timetuple()) + self._settings['testrunstarttimer']
except ValueError:
logging.debug('Invalid dates, skipping testrun')
return False
# If start date is in the future set as NextTestRun and stop evaluating
if startdate > today:
self._dbusservice['/NextTestRun'] = time.mktime(startdate.timetuple())
return False
start = False
# If the accumulated runtime during the test run interval is greater than '/TestRunIntervalRuntime'
# the test run must be skipped
needed = (self._settings['testrunskipruntime'] > self._dbusservice['/TestRunIntervalRuntime']
or self._settings['testrunskipruntime'] == 0)
self._dbusservice['/SkipTestRun'] = int(not needed)
interval = self._settings['testruninterval']
stoptime = starttime + duration
elapseddays = (today - startdate).days
mod = elapseddays % interval
start = not bool(mod) and starttime <= now <= stoptime
if runtillbatteryfull:
if soc is not None:
self._testrun_soc_retries = 0
start = (start or self._dbusservice['/RunningByCondition'] == 'testrun') and not batteryisfull
elif self._dbusservice['/RunningByCondition'] == 'testrun':
if self._testrun_soc_retries < self.RETRIES_ON_ERROR:
self._testrun_soc_retries += 1
start = True
if (self._testrun_soc_retries % 10) == 0:
self.log_info('Test run failed to get SOC value, retrying(#%i)' % self._testrun_soc_retries)
else:
self.log_info('Failed to get SOC after %i retries, terminating test run condition' % self._testrun_soc_retries)
start = False
else:
start = False
if not bool(mod) and (now <= stoptime):
self._dbusservice['/NextTestRun'] = starttime
else:
self._dbusservice['/NextTestRun'] = (time.mktime((today + datetime.timedelta(days=interval - mod)).timetuple()) +
self._settings['testrunstarttimer'])
return start and needed
def _check_quiet_hours(self):
active = False
if self._settings['quiethoursenabled'] == 1:
# Seconds after today 00:00
timeinseconds = time.time() - time.mktime(datetime.date.today().timetuple())
quiethoursstart = self._settings['quiethoursstarttime']
quiethoursend = self._settings['quiethoursendtime']
# Check if the current time is between the start time and end time
if quiethoursstart < quiethoursend:
active = quiethoursstart <= timeinseconds and timeinseconds < quiethoursend
else: # End time is lower than start time, example Start: 21:00, end: 08:00
active = not (quiethoursend < timeinseconds and timeinseconds < quiethoursstart)
if self._dbusservice['/QuietHours'] == 0 and active:
self.log_info('Entering to quiet mode')
elif self._dbusservice['/QuietHours'] == 1 and not active:
self.log_info('Leaving quiet mode')
self._dbusservice['/QuietHours'] = int(active)
return active
def _update_accumulated_time(self, gensetHours=None):
# Check if this instance is connected to a genset which reports operating hours.