-
Notifications
You must be signed in to change notification settings - Fork 33
/
HoymilesZeroExport.py
1673 lines (1471 loc) · 77.7 KB
/
HoymilesZeroExport.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
# HoymilesZeroExport - https://github.com/reserve85/HoymilesZeroExport
# Copyright (C) 2023, Tobias Kraft
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = "Tobias Kraft"
__version__ = "1.104"
import time
from requests.sessions import Session
from requests.auth import HTTPBasicAuth
from requests.auth import HTTPDigestAuth
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
import os
import logging
from logging.handlers import TimedRotatingFileHandler
from configparser import ConfigParser
from pathlib import Path
import sys
from packaging import version
import argparse
import subprocess
from config_provider import ConfigFileConfigProvider, MqttHandler, ConfigProviderChain
import json
session = Session()
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger()
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', help='Override configuration file path')
args = parser.parse_args()
try:
config = ConfigParser()
baseconfig = str(Path.joinpath(Path(__file__).parent.resolve(), "HoymilesZeroExport_Config.ini"))
if args.config:
config.read([baseconfig, args.config])
else:
config.read(baseconfig)
ENABLE_LOG_TO_FILE = config.getboolean('COMMON', 'ENABLE_LOG_TO_FILE')
LOG_BACKUP_COUNT = config.getint('COMMON', 'LOG_BACKUP_COUNT')
except Exception as e:
logger.info('Error on reading ENABLE_LOG_TO_FILE, set it to DISABLED')
ENABLE_LOG_TO_FILE = False
if hasattr(e, 'message'):
logger.error(e.message)
else:
logger.error(e)
if ENABLE_LOG_TO_FILE:
if not os.path.exists(Path.joinpath(Path(__file__).parent.resolve(), 'log')):
os.makedirs(Path.joinpath(Path(__file__).parent.resolve(), 'log'))
rotating_file_handler = TimedRotatingFileHandler(
filename=Path.joinpath(Path.joinpath(Path(__file__).parent.resolve(), 'log'),'log'),
when='midnight',
interval=2,
backupCount=LOG_BACKUP_COUNT)
formatter = logging.Formatter(
'%(asctime)s %(levelname)-8s %(message)s')
rotating_file_handler.setFormatter(formatter)
logger.addHandler(rotating_file_handler)
logger.info('Log write to file: %s', ENABLE_LOG_TO_FILE)
logger.info('Python Version: ' + sys.version)
try:
assert sys.version_info >= (3,8)
except:
logger.info('Error: your Python version is too old, this script requires version 3.8 or newer. Please update your Python.')
sys.exit()
def CastToInt(pValueToCast):
try:
result = int(pValueToCast)
return result
except:
result = 0
try:
result = int(float(pValueToCast))
return result
except:
logger.error("Exception at CastToInt")
raise
def SetLimit(pLimit):
try:
if not hasattr(SetLimit, "LastLimit"):
SetLimit.LastLimit = CastToInt(0)
if not hasattr(SetLimit, "LastLimitAck"):
SetLimit.LastLimitAck = bool(False)
if (SetLimit.LastLimit == CastToInt(pLimit)) and SetLimit.LastLimitAck:
logger.info("Inverterlimit was already accepted at %s Watt",CastToInt(pLimit))
CrossCheckLimit()
return
if (SetLimit.LastLimit == CastToInt(pLimit)) and not SetLimit.LastLimitAck:
logger.info("Inverterlimit %s Watt was previously not accepted by at least one inverter, trying again...",CastToInt(pLimit))
logger.info("setting new limit to %s Watt",CastToInt(pLimit))
SetLimit.LastLimit = CastToInt(pLimit)
SetLimit.LastLimitAck = True
min_watt_all_inverters = GetMinWattFromAllInverters()
if (CastToInt(pLimit) <= min_watt_all_inverters):
pLimit = min_watt_all_inverters # set only minWatt for every inv.
PublishGlobalState("limit", min_watt_all_inverters)
else:
PublishGlobalState("limit", CastToInt(pLimit))
RemainingLimit = CastToInt(pLimit)
RemainingLimit -= GetMinWattFromAllInverters()
# Handle non-battery inverters first
if RemainingLimit >= GetMaxWattFromAllNonBatteryInverters() - GetMinWattFromAllNonBatteryInverters():
nonBatteryInvertersLimit = GetMaxWattFromAllNonBatteryInverters() - GetMinWattFromAllNonBatteryInverters()
else:
nonBatteryInvertersLimit = RemainingLimit
for i in range(INVERTER_COUNT):
if not AVAILABLE[i] or HOY_BATTERY_MODE[i]:
continue
# Calculate proportional limit for non-battery inverters
NewLimit = CastToInt(nonBatteryInvertersLimit * (HOY_MAX_WATT[i] - GetMinWatt(i)) / (GetMaxWattFromAllNonBatteryInverters() - GetMinWattFromAllNonBatteryInverters()))
NewLimit += GetMinWatt(i)
# Apply the calculated limit to the inverter
NewLimit = ApplyLimitsToSetpointInverter(i, NewLimit)
if HOY_COMPENSATE_WATT_FACTOR[i] != 1:
logger.info('Ahoy: Inverter "%s": compensate Limit from %s Watt to %s Watt', NAME[i], CastToInt(NewLimit), CastToInt(NewLimit*HOY_COMPENSATE_WATT_FACTOR[i]))
NewLimit = CastToInt(NewLimit * HOY_COMPENSATE_WATT_FACTOR[i])
NewLimit = ApplyLimitsToMaxInverterLimits(i, NewLimit)
if (NewLimit == CastToInt(CURRENT_LIMIT[i])) and LASTLIMITACKNOWLEDGED[i]:
logger.info('Inverter "%s": Already at %s Watt',NAME[i],CastToInt(NewLimit))
continue
LASTLIMITACKNOWLEDGED[i] = True
PublishInverterState(i, "limit", NewLimit)
DTU.SetLimit(i, NewLimit)
if not DTU.WaitForAck(i, SET_LIMIT_TIMEOUT_SECONDS):
SetLimit.LastLimitAck = False
LASTLIMITACKNOWLEDGED[i] = False
# Adjust RemainingLimit based on what was assigned to non-battery inverters
RemainingLimit -= nonBatteryInvertersLimit
# Then handle battery inverters based on priority
for j in range(1, 6):
batteryMaxWattSamePrio = GetMaxWattFromAllBatteryInvertersSamePrio(j)
if batteryMaxWattSamePrio <= 0:
continue
if RemainingLimit >= batteryMaxWattSamePrio - GetMinWattFromAllBatteryInvertersWithSamePriority(j):
LimitPrio = batteryMaxWattSamePrio - GetMinWattFromAllBatteryInvertersWithSamePriority(j)
else:
LimitPrio = RemainingLimit
for i in range(INVERTER_COUNT):
if (not HOY_BATTERY_MODE[i]):
continue
if (not AVAILABLE[i]) or (not HOY_BATTERY_GOOD_VOLTAGE[i]):
continue
if CONFIG_PROVIDER.get_battery_priority(i) != j:
continue
# Calculate proportional limit for battery inverters
NewLimit = CastToInt(LimitPrio * (HOY_MAX_WATT[i] - GetMinWatt(i)) / (GetMaxWattFromAllBatteryInvertersSamePrio(j) - GetMinWattFromAllBatteryInvertersWithSamePriority(j)))
NewLimit += GetMinWatt(i)
NewLimit = ApplyLimitsToSetpointInverter(i, NewLimit)
if HOY_COMPENSATE_WATT_FACTOR[i] != 1:
logger.info('Ahoy: Inverter "%s": compensate Limit from %s Watt to %s Watt', NAME[i], CastToInt(NewLimit), CastToInt(NewLimit*HOY_COMPENSATE_WATT_FACTOR[i]))
NewLimit = CastToInt(NewLimit * HOY_COMPENSATE_WATT_FACTOR[i])
NewLimit = ApplyLimitsToMaxInverterLimits(i, NewLimit)
if (NewLimit == CastToInt(CURRENT_LIMIT[i])) and LASTLIMITACKNOWLEDGED[i]:
logger.info('Inverter "%s": Already at %s Watt',NAME[i],CastToInt(NewLimit))
continue
LASTLIMITACKNOWLEDGED[i] = True
PublishInverterState(i, "limit", NewLimit)
DTU.SetLimit(i, NewLimit)
if not DTU.WaitForAck(i, SET_LIMIT_TIMEOUT_SECONDS):
SetLimit.LastLimitAck = False
LASTLIMITACKNOWLEDGED[i] = False
RemainingLimit -= LimitPrio
except:
logger.error("Exception at SetLimit")
SetLimit.LastLimitAck = False
raise
def ResetInverterData(pInverterId):
attributes_to_delete = [
"LastLimit",
"LastLimitAck",
]
array_attributes_to_delete = [
{"LastPowerStatus": False},
{"SamePowerStatusCnt": 0},
]
target_objects = [
SetLimit,
GetHoymilesPanelMinVoltage,
]
for target_object in target_objects:
for attribute in attributes_to_delete:
if hasattr(target_object, attribute):
delattr(target_object, attribute)
for array_attribute in array_attributes_to_delete:
for key, value in array_attribute.items():
if hasattr(target_object, key):
target_object[key][pInverterId] = value
LASTLIMITACKNOWLEDGED[pInverterId] = False
HOY_PANEL_MIN_VOLTAGE_HISTORY_LIST[pInverterId] = []
CURRENT_LIMIT[pInverterId] = -1
HOY_BATTERY_GOOD_VOLTAGE[pInverterId] = True
TEMPERATURE[pInverterId] = str('--- degC')
def GetHoymilesAvailable():
try:
GetHoymilesAvailable = False
for i in range(INVERTER_COUNT):
try:
WasAvail = AVAILABLE[i]
AVAILABLE[i] = ENABLED[i] and DTU.GetAvailable(i)
if AVAILABLE[i]:
GetHoymilesAvailable = True
if not WasAvail:
ResetInverterData(i)
GetHoymilesInfo()
except Exception as e:
AVAILABLE[i] = False
logger.error("Exception at GetHoymilesAvailable, Inverter %s (%s) not reachable", i, NAME[i])
if hasattr(e, 'message'):
logger.error(e.message)
else:
logger.error(e)
return GetHoymilesAvailable
except:
logger.error('Exception at GetHoymilesAvailable')
raise
def GetHoymilesInfo():
try:
for i in range(INVERTER_COUNT):
try:
if not AVAILABLE[i]:
continue
DTU.GetInfo(i)
except Exception as e:
logger.error('Exception at GetHoymilesInfo, Inverter "%s" not reachable', NAME[i])
if hasattr(e, 'message'):
logger.error(e.message)
else:
logger.error(e)
except:
logger.error("Exception at GetHoymilesInfo")
raise
def GetHoymilesPanelMinVoltage(pInverterId):
try:
if not AVAILABLE[pInverterId]:
return 0
HOY_PANEL_MIN_VOLTAGE_HISTORY_LIST[pInverterId].append(DTU.GetPanelMinVoltage(pInverterId))
# calculate mean over last x values
if len(HOY_PANEL_MIN_VOLTAGE_HISTORY_LIST[pInverterId]) > HOY_BATTERY_AVERAGE_CNT[pInverterId]:
HOY_PANEL_MIN_VOLTAGE_HISTORY_LIST[pInverterId].pop(0)
from statistics import mean
logger.info('Average min-panel voltage, inverter "%s": %s Volt',NAME[pInverterId], mean(HOY_PANEL_MIN_VOLTAGE_HISTORY_LIST[pInverterId]))
return mean(HOY_PANEL_MIN_VOLTAGE_HISTORY_LIST[pInverterId])
except:
logger.error("Exception at GetHoymilesPanelMinVoltage, Inverter %s not reachable", pInverterId)
raise
def SetHoymilesPowerStatus(pInverterId, pActive):
try:
if not AVAILABLE[pInverterId]:
return
if SET_POWERSTATUS_CNT > 0:
if not hasattr(SetHoymilesPowerStatus, "LastPowerStatus"):
SetHoymilesPowerStatus.LastPowerStatus = []
SetHoymilesPowerStatus.LastPowerStatus = [False for i in range(INVERTER_COUNT)]
if not hasattr(SetHoymilesPowerStatus, "SamePowerStatusCnt"):
SetHoymilesPowerStatus.SamePowerStatusCnt = []
SetHoymilesPowerStatus.SamePowerStatusCnt = [0 for i in range(INVERTER_COUNT)]
if SetHoymilesPowerStatus.LastPowerStatus[pInverterId] == pActive:
SetHoymilesPowerStatus.SamePowerStatusCnt[pInverterId] = SetHoymilesPowerStatus.SamePowerStatusCnt[pInverterId] + 1
else:
SetHoymilesPowerStatus.LastPowerStatus[pInverterId] = pActive
SetHoymilesPowerStatus.SamePowerStatusCnt[pInverterId] = 0
if SetHoymilesPowerStatus.SamePowerStatusCnt[pInverterId] > SET_POWERSTATUS_CNT:
if pActive:
logger.info("Retry Counter exceeded: Inverter PowerStatus already ON")
else:
logger.info("Retry Counter exceeded: Inverter PowerStatus already OFF")
return
DTU.SetPowerStatus(pInverterId, pActive)
time.sleep(SET_POWER_STATUS_DELAY_IN_SECONDS)
except:
logger.error("Exception at SetHoymilesPowerStatus")
raise
def GetNumberArray(pExcludedPanels):
lclExcludedPanelsList = pExcludedPanels.split(',')
result = []
for number_str in lclExcludedPanelsList:
if number_str == '':
continue
number = int(number_str.strip())
result.append(number)
return result
def GetCheckBattery():
try:
result = False
for i in range(INVERTER_COUNT):
try:
if not AVAILABLE[i]:
continue
if not HOY_BATTERY_MODE[i]:
result = True
continue
minVoltage = GetHoymilesPanelMinVoltage(i)
if minVoltage <= HOY_BATTERY_THRESHOLD_OFF_LIMIT_IN_V[i]:
SetHoymilesPowerStatus(i, False)
HOY_BATTERY_GOOD_VOLTAGE[i] = False
HOY_MAX_WATT[i] = CONFIG_PROVIDER.get_reduce_wattage(i)
elif minVoltage <= HOY_BATTERY_THRESHOLD_REDUCE_LIMIT_IN_V[i]:
if HOY_MAX_WATT[i] != CONFIG_PROVIDER.get_reduce_wattage(i):
HOY_MAX_WATT[i] = CONFIG_PROVIDER.get_reduce_wattage(i)
SetLimit.LastLimit = -1
elif minVoltage >= HOY_BATTERY_THRESHOLD_ON_LIMIT_IN_V[i]:
SetHoymilesPowerStatus(i, True)
if not HOY_BATTERY_GOOD_VOLTAGE[i]:
DTU.SetLimit(i, GetMinWatt(i))
DTU.WaitForAck(i, SET_LIMIT_TIMEOUT_SECONDS)
SetLimit.LastLimit = -1
HOY_BATTERY_GOOD_VOLTAGE[i] = True
if (minVoltage >= HOY_BATTERY_THRESHOLD_NORMAL_LIMIT_IN_V[i]) and (HOY_MAX_WATT[i] != CONFIG_PROVIDER.get_normal_wattage(i)):
HOY_MAX_WATT[i] = CONFIG_PROVIDER.get_normal_wattage(i)
SetLimit.LastLimit = -1
elif minVoltage >= HOY_BATTERY_THRESHOLD_NORMAL_LIMIT_IN_V[i]:
if HOY_MAX_WATT[i] != CONFIG_PROVIDER.get_normal_wattage(i):
HOY_MAX_WATT[i] = CONFIG_PROVIDER.get_normal_wattage(i)
SetLimit.LastLimit = -1
if HOY_BATTERY_GOOD_VOLTAGE[i]:
result = True
except:
logger.error("Exception at CheckBattery, Inverter %s not reachable", i)
return result
except:
logger.error("Exception at CheckBattery")
raise
def GetHoymilesTemperature():
try:
for i in range(INVERTER_COUNT):
try:
DTU.GetTemperature(i)
except:
logger.error("Exception at GetHoymilesTemperature, Inverter %s not reachable", i)
except:
logger.error("Exception at GetHoymilesTemperature")
raise
def GetHoymilesActualPower():
try:
try:
Watts = abs(INTERMEDIATE_POWERMETER.GetPowermeterWatts())
logger.info(f"intermediate meter {INTERMEDIATE_POWERMETER.__class__.__name__}: {Watts} Watt")
return Watts
except Exception as e:
logger.error("Exception at GetHoymilesActualPower")
if hasattr(e, 'message'):
logger.error(e.message)
else:
logger.error(e)
logger.error("try reading actual power from DTU:")
Watts = DTU.GetPowermeterWatts()
logger.info(f"intermediate meter {DTU.__class__.__name__}: {Watts} Watt")
except:
logger.error("Exception at GetHoymilesActualPower")
if SET_INVERTER_TO_MIN_ON_POWERMETER_ERROR:
SetLimit(0)
raise
def GetPowermeterWatts():
try:
Watts = POWERMETER.GetPowermeterWatts()
logger.info(f"powermeter {POWERMETER.__class__.__name__}: {Watts} Watt")
return Watts
except:
logger.error("Exception at GetPowermeterWatts")
if SET_INVERTER_TO_MIN_ON_POWERMETER_ERROR:
SetLimit(0)
raise
def GetMinWatt(pInverter: int):
min_watt_percent = CONFIG_PROVIDER.get_min_wattage_in_percent(pInverter)
return int(HOY_INVERTER_WATT[pInverter] * min_watt_percent / 100)
def CutLimitToProduction(pSetpoint):
if pSetpoint != GetMaxWattFromAllInverters():
ActualPower = GetHoymilesActualPower()
# prevent the setpoint from running away...
if pSetpoint > ActualPower + (GetMaxWattFromAllInverters() * MAX_DIFFERENCE_BETWEEN_LIMIT_AND_OUTPUTPOWER / 100):
pSetpoint = CastToInt(ActualPower + (GetMaxWattFromAllInverters() * MAX_DIFFERENCE_BETWEEN_LIMIT_AND_OUTPUTPOWER / 100))
logger.info('Cut limit to %s Watt, limit was higher than %s percent of live-production', CastToInt(pSetpoint), MAX_DIFFERENCE_BETWEEN_LIMIT_AND_OUTPUTPOWER)
return CastToInt(pSetpoint)
def ApplyLimitsToSetpoint(pSetpoint):
if pSetpoint > GetMaxWattFromAllInverters():
pSetpoint = GetMaxWattFromAllInverters()
if pSetpoint < GetMinWattFromAllInverters():
pSetpoint = GetMinWattFromAllInverters()
return pSetpoint
def ApplyLimitsToSetpointInverter(pInverter, pSetpoint):
if pSetpoint > HOY_MAX_WATT[pInverter]:
pSetpoint = HOY_MAX_WATT[pInverter]
if pSetpoint < GetMinWatt(pInverter):
pSetpoint = GetMinWatt(pInverter)
return pSetpoint
def ApplyLimitsToMaxInverterLimits(pInverter, pSetpoint):
if pSetpoint > HOY_INVERTER_WATT[pInverter]:
pSetpoint = HOY_INVERTER_WATT[pInverter]
if pSetpoint < GetMinWatt(pInverter):
pSetpoint = GetMinWatt(pInverter)
return pSetpoint
def CrossCheckLimit():
try:
for i in range(INVERTER_COUNT):
if AVAILABLE[i]:
DTULimitInW = DTU.GetActualLimitInW(i)
LimitMax = float(CURRENT_LIMIT[i] + HOY_INVERTER_WATT[i] * 0.05)
LimitMin = float(CURRENT_LIMIT[i] - HOY_INVERTER_WATT[i] * 0.05)
if not (min(LimitMax, LimitMin) < DTULimitInW < max(LimitMax, LimitMin)):
logger.info('CrossCheckLimit: DTU ( %s ) <> SetLimit ( %s ). Resend limit to DTU', "{:.1f}".format(DTULimitInW), "{:.1f}".format(CURRENT_LIMIT[i]))
DTU.SetLimit(i, CURRENT_LIMIT[i])
except:
logger.error("Exception at CrossCheckLimit")
raise
def GetMaxWattFromAllInverters():
# Max possible Watts, can be reduced on battery mode
maxWatt = 0
for i in range(INVERTER_COUNT):
if (not AVAILABLE[i]) or (not HOY_BATTERY_GOOD_VOLTAGE[i]):
continue
maxWatt = maxWatt + HOY_MAX_WATT[i]
return maxWatt
def GetMaxWattFromAllBatteryInvertersSamePrio(pPriority):
return sum(
HOY_MAX_WATT[i] for i in range(INVERTER_COUNT)
if AVAILABLE[i] and HOY_BATTERY_GOOD_VOLTAGE[i] and HOY_BATTERY_MODE[i] and CONFIG_PROVIDER.get_battery_priority(i) == pPriority
)
def GetMaxInverterWattFromAllInverters():
# Max possible Watts (physically) - Inverter Specification!
maxWatt = 0
for i in range(INVERTER_COUNT):
if (not AVAILABLE[i]) or (not HOY_BATTERY_GOOD_VOLTAGE[i]):
continue
maxWatt = maxWatt + HOY_INVERTER_WATT[i]
return maxWatt
def GetMaxWattFromAllNonBatteryInverters():
return sum(
HOY_MAX_WATT[i] for i in range(INVERTER_COUNT)
if AVAILABLE[i] and not HOY_BATTERY_MODE[i] and HOY_BATTERY_GOOD_VOLTAGE[i]
)
def GetMinWattFromAllInverters():
minWatt = 0
for i in range(INVERTER_COUNT):
if (not AVAILABLE[i]) or (not HOY_BATTERY_GOOD_VOLTAGE[i]):
continue
minWatt = minWatt + GetMinWatt(i)
return minWatt
def GetMinWattFromAllNonBatteryInverters():
minWatt = 0
for i in range(INVERTER_COUNT):
if (not AVAILABLE[i]) or (HOY_BATTERY_MODE[i]) or (not HOY_BATTERY_GOOD_VOLTAGE[i]):
continue
minWatt = minWatt + GetMinWatt(i)
return minWatt
def GetMinWattFromAllBatteryInverters():
minWatt = 0
for i in range(INVERTER_COUNT):
if (not AVAILABLE[i]) or (not HOY_BATTERY_MODE[i]) or (not HOY_BATTERY_GOOD_VOLTAGE[i]):
continue
minWatt = minWatt + GetMinWatt(i)
return minWatt
def GetMinWattFromAllBatteryInvertersWithSamePriority(pPriority):
minWatt = 0
for i in range(INVERTER_COUNT):
if (not AVAILABLE[i]) or (not HOY_BATTERY_MODE[i]) or (not HOY_BATTERY_GOOD_VOLTAGE[i]) or (CONFIG_PROVIDER.get_battery_priority(i) != pPriority):
continue
minWatt = minWatt + GetMinWatt(i)
return minWatt
def PublishConfigState():
if MQTT is None:
return
MQTT.publish_state("on_grid_usage_jump_to_limit_percent", CONFIG_PROVIDER.on_grid_usage_jump_to_limit_percent())
MQTT.publish_state("on_grid_feed_fast_limit_decrease", CONFIG_PROVIDER.on_grid_feed_fast_limit_decrease())
MQTT.publish_state("powermeter_target_point", CONFIG_PROVIDER.get_powermeter_target_point())
MQTT.publish_state("powermeter_max_point", CONFIG_PROVIDER.get_powermeter_max_point())
MQTT.publish_state("powermeter_min_point", CONFIG_PROVIDER.get_powermeter_min_point())
MQTT.publish_state("powermeter_tolerance", CONFIG_PROVIDER.get_powermeter_tolerance())
MQTT.publish_state("inverter_count", INVERTER_COUNT)
for i in range(INVERTER_COUNT):
MQTT.publish_inverter_state(i, "min_watt_in_percent", CONFIG_PROVIDER.get_min_wattage_in_percent(i))
MQTT.publish_inverter_state(i, "normal_watt", CONFIG_PROVIDER.get_normal_wattage(i))
MQTT.publish_inverter_state(i, "reduce_watt", CONFIG_PROVIDER.get_reduce_wattage(i))
MQTT.publish_inverter_state(i, "battery_priority", CONFIG_PROVIDER.get_battery_priority(i))
def PublishGlobalState(state_name, state_value):
if MQTT is None:
return
MQTT.publish_state(state_name, state_value)
def PublishInverterState(inverter_idx, state_name, state_value):
if MQTT is None:
return
MQTT.publish_inverter_state(inverter_idx, state_name, state_value)
class Powermeter:
def GetPowermeterWatts(self) -> int:
raise NotImplementedError()
class Tasmota(Powermeter):
def __init__(self, ip: str, user: str, password: str, json_status: str, json_payload_mqtt_prefix: str, json_power_mqtt_label: str, json_power_input_mqtt_label: str, json_power_output_mqtt_label: str, json_power_calculate: bool):
self.ip = ip
self.user = user
self.password = password
self.json_status = json_status
self.json_payload_mqtt_prefix = json_payload_mqtt_prefix
self.json_power_mqtt_label = json_power_mqtt_label
self.json_power_input_mqtt_label = json_power_input_mqtt_label
self.json_power_output_mqtt_label = json_power_output_mqtt_label
self.json_power_calculate = json_power_calculate
def GetJson(self, path):
url = f'http://{self.ip}{path}'
return session.get(url, timeout=10).json()
def GetPowermeterWatts(self):
if not self.user:
ParsedData = self.GetJson('/cm?cmnd=status%2010')
else:
ParsedData = self.GetJson(f'/cm?user={self.user}&password={self.password}&cmnd=status%2010')
if not self.json_power_calculate:
return CastToInt(ParsedData[self.json_status][self.json_payload_mqtt_prefix][self.json_power_mqtt_label])
else:
input = ParsedData[self.json_status][self.json_payload_mqtt_prefix][self.json_power_input_mqtt_label]
ouput = ParsedData[self.json_status][self.json_payload_mqtt_prefix][self.json_power_output_mqtt_label]
return CastToInt(input - ouput)
class Shelly(Powermeter):
def __init__(self, ip: str, user: str, password: str, emeterindex: str):
self.ip = ip
self.user = user
self.password = password
self.emeterindex = emeterindex
def GetJson(self, path):
url = f'http://{self.ip}{path}'
headers = {"content-type": "application/json"}
return session.get(url, headers=headers, auth=(self.user, self.password), timeout=10).json()
def GetRpcJson(self, path):
url = f'http://{self.ip}/rpc{path}'
headers = {"content-type": "application/json"}
return session.get(url, headers=headers, auth=HTTPDigestAuth(self.user, self.password), timeout=10).json()
def GetPowermeterWatts(self) -> int:
raise NotImplementedError()
class Shelly1PM(Shelly):
def GetPowermeterWatts(self):
return CastToInt(self.GetJson('/status')['meters'][0]['power'])
class ShellyPlus1PM(Shelly):
def GetPowermeterWatts(self):
return CastToInt(self.GetRpcJson('/Switch.GetStatus?id=0')['apower'])
class ShellyEM(Shelly):
def GetPowermeterWatts(self):
if self.emeterindex:
return CastToInt(self.GetJson(f'/emeter/{self.emeterindex}')['power'])
else:
return sum(CastToInt(emeter['power']) for emeter in self.GetJson('/status')['emeters'])
class Shelly3EM(Shelly):
def GetPowermeterWatts(self):
return CastToInt(self.GetJson('/status')['total_power'])
class Shelly3EMPro(Shelly):
def GetPowermeterWatts(self):
return CastToInt(self.GetRpcJson('/EM.GetStatus?id=0')['total_act_power'])
class ESPHome(Powermeter):
def __init__(self, ip: str, port: str, domain: str, id: str):
self.ip = ip
self.port = port
self.domain = domain
self.id = id
def GetJson(self, path):
url = f'http://{self.ip}:{self.port}{path}'
return session.get(url, timeout=10).json()
def GetPowermeterWatts(self):
ParsedData = self.GetJson(f'/{self.domain}/{self.id}')
return CastToInt(ParsedData['value'])
class Shrdzm(Powermeter):
def __init__(self, ip: str, user: str, password: str):
self.ip = ip
self.user = user
self.password = password
def GetJson(self, path):
url = f'http://{self.ip}{path}'
return session.get(url, timeout=10).json()
def GetPowermeterWatts(self):
ParsedData = self.GetJson(f'/getLastData?user={self.user}&password={self.password}')
return CastToInt(CastToInt(ParsedData['1.7.0']) - CastToInt(ParsedData['2.7.0']))
class Emlog(Powermeter):
def __init__(self, ip: str, meterindex: str, json_power_calculate: bool):
self.ip = ip
self.meterindex = meterindex
self.json_power_calculate = json_power_calculate
def GetJson(self, path):
url = f'http://{self.ip}{path}'
return session.get(url, timeout=10).json()
def GetPowermeterWatts(self):
ParsedData = self.GetJson(f'/pages/getinformation.php?heute&meterindex={self.meterindex}')
if not self.json_power_calculate:
return CastToInt(ParsedData['Leistung170'])
else:
input = ParsedData['Leistung170']
ouput = ParsedData['Leistung270']
return CastToInt(input - ouput)
class IoBroker(Powermeter):
def __init__(self, ip: str, port: str, current_power_alias: str, power_calculate: bool, power_input_alias: str, power_output_alias: str):
self.ip = ip
self.port = port
self.current_power_alias = current_power_alias
self.power_calculate = power_calculate
self.power_input_alias = power_input_alias
self.power_output_alias = power_output_alias
def GetJson(self, path):
url = f'http://{self.ip}:{self.port}{path}'
return session.get(url, timeout=10).json()
def GetPowermeterWatts(self):
if not self.power_calculate:
ParsedData = self.GetJson(f'/getBulk/{self.current_power_alias}')
for item in ParsedData:
if item['id'] == self.current_power_alias:
return CastToInt(item['val'])
else:
ParsedData = self.GetJson(f'/getBulk/{self.power_input_alias},{self.power_output_alias}')
for item in ParsedData:
if item['id'] == self.power_input_alias:
input = CastToInt(item['val'])
if item['id'] == self.power_output_alias:
output = CastToInt(item['val'])
return CastToInt(input - output)
class HomeAssistant(Powermeter):
def __init__(self, ip: str, port: str, use_https: bool, access_token: str, current_power_entity: str, power_calculate: bool, power_input_alias: str, power_output_alias: str):
self.ip = ip
self.port = port
self.use_https = use_https
self.access_token = access_token
self.current_power_entity = current_power_entity
self.power_calculate = power_calculate
self.power_input_alias = power_input_alias
self.power_output_alias = power_output_alias
def GetJson(self, path):
if self.use_https:
url = f"https://{self.ip}:{self.port}{path}"
else:
url = f"http://{self.ip}:{self.port}{path}"
headers = {"Authorization": "Bearer " + self.access_token, "content-type": "application/json"}
return session.get(url, headers=headers, timeout=10).json()
def GetPowermeterWatts(self):
if not self.power_calculate:
ParsedData = self.GetJson(f"/api/states/{self.current_power_entity}")
return CastToInt(ParsedData['state'])
else:
ParsedData = self.GetJson(f"/api/states/{self.power_input_alias}")
input = CastToInt(ParsedData['state'])
ParsedData = self.GetJson(f"/api/states/{self.power_output_alias}")
output = CastToInt(ParsedData['state'])
return CastToInt(input - output)
class VZLogger(Powermeter):
def __init__(self, ip: str, port: str, uuid: str):
self.ip = ip
self.port = port
self.uuid = uuid
def GetJson(self):
url = f"http://{self.ip}:{self.port}/{self.uuid}"
return session.get(url, timeout=10).json()
def GetPowermeterWatts(self):
return CastToInt(self.GetJson()['data'][0]['tuples'][0][1])
class AmisReader(Powermeter):
def __init__(self, ip: str):
self.ip = ip
def GetJson(self, path):
url = f'http://{self.ip}{path}'
return session.get(url, timeout=10).json()
def GetPowermeterWatts(self):
ParsedData = self.GetJson('/rest')
return CastToInt(ParsedData['saldo'])
class DebugReader(Powermeter):
def GetPowermeterWatts(self):
return CastToInt(input("Enter Powermeter Watts: "))
class DTU(Powermeter):
def __init__(self, inverter_count: int):
self.inverter_count = inverter_count
def GetACPower(self, pInverterId: int):
raise NotImplementedError()
def GetPowermeterWatts(self):
return sum(self.GetACPower(pInverterId) for pInverterId in range(self.inverter_count) if AVAILABLE[pInverterId] and HOY_BATTERY_GOOD_VOLTAGE[pInverterId])
def CheckMinVersion(self):
raise NotImplementedError()
def GetAvailable(self, pInverterId: int):
raise NotImplementedError()
def GetActualLimitInW(self, pInverterId: int):
raise NotImplementedError()
def GetInfo(self, pInverterId: int):
raise NotImplementedError()
def GetTemperature(self, pInverterId: int):
raise NotImplementedError()
def GetPanelMinVoltage(self, pInverterId: int):
raise NotImplementedError()
def WaitForAck(self, pInverterId: int, pTimeoutInS: int):
raise NotImplementedError()
def SetLimit(self, pInverterId: int, pLimit: int):
raise NotImplementedError()
def SetPowerStatus(self, pInverterId: int, pActive: bool):
raise NotImplementedError()
class AhoyDTU(DTU):
def __init__(self, inverter_count: int, ip: str, password: str):
super().__init__(inverter_count)
self.ip = ip
self.password = password
self.Token = ''
def GetJson(self, path):
url = f'http://{self.ip}{path}'
# AhoyDTU sometimes returns literal 'null' instead of a valid json, so we retry a few times
data = None
retry_count = 3
while retry_count > 0 and data is None:
data = session.get(url, timeout=10).json()
retry_count -= 1
return data
def GetResponseJson(self, path, obj):
url = f'http://{self.ip}{path}'
return session.post(url, json = obj, timeout=10).json()
def GetACPower(self, pInverterId):
ParsedData = self.GetJson('/api/live')
ActualPower_index = ParsedData["ch0_fld_names"].index("P_AC")
ParsedData = self.GetJson(f'/api/inverter/id/{pInverterId}')
return CastToInt(ParsedData["ch"][0][ActualPower_index])
def CheckMinVersion(self):
MinVersion = '0.8.80'
ParsedData = self.GetJson('/api/system')
try:
AhoyVersion = str((ParsedData["version"]))
except:
AhoyVersion = str((ParsedData["generic"]["version"]))
logger.info('Ahoy: Current Version: %s',AhoyVersion)
if version.parse(AhoyVersion) < version.parse(MinVersion):
logger.error('Error: Your AHOY Version is too old! Please update at least to Version %s - you can find the newest dev-releases here: https://github.com/lumapu/ahoy/actions',MinVersion)
quit()
def GetAvailable(self, pInverterId: int):
ParsedData = self.GetJson('/api/index')
Available = bool(ParsedData["inverter"][pInverterId]["is_avail"])
logger.info('Ahoy: Inverter "%s" Available: %s',NAME[pInverterId], Available)
return Available
def GetActualLimitInW(self, pInverterId: int):
ParsedData = self.GetJson(f'/api/inverter/id/{pInverterId}')
LimitInPercent = float(ParsedData['power_limit_read'])
LimitInW = HOY_INVERTER_WATT[pInverterId] * LimitInPercent / 100
return LimitInW
def GetInfo(self, pInverterId: int):
ParsedData = self.GetJson('/api/live')
temp_index = ParsedData["ch0_fld_names"].index("Temp")
ParsedData = self.GetJson(f'/api/inverter/id/{pInverterId}')
SERIAL_NUMBER[pInverterId] = str(ParsedData['serial'])
NAME[pInverterId] = str(ParsedData['name'])
TEMPERATURE[pInverterId] = str(ParsedData["ch"][0][temp_index]) + ' degC'
logger.info('Ahoy: Inverter "%s" / serial number "%s" / temperature %s',NAME[pInverterId],SERIAL_NUMBER[pInverterId],TEMPERATURE[pInverterId])
def GetTemperature(self, pInverterId: int):
ParsedData = self.GetJson('/api/live')
temp_index = ParsedData["ch0_fld_names"].index("Temp")
ParsedData = self.GetJson(f'/api/inverter/id/{pInverterId}')
TEMPERATURE[pInverterId] = str(ParsedData["ch"][0][temp_index]) + ' degC'
logger.info('Ahoy: Inverter "%s" temperature: %s',NAME[pInverterId],TEMPERATURE[pInverterId])
def GetPanelMinVoltage(self, pInverterId: int):
ParsedData = self.GetJson('/api/live')
PanelVDC_index = ParsedData["fld_names"].index("U_DC")
ParsedData = self.GetJson(f'/api/inverter/id/{pInverterId}')
PanelVDC = []
ExcludedPanels = GetNumberArray(HOY_BATTERY_IGNORE_PANELS[pInverterId])
for i in range(1, len(ParsedData['ch']), 1):
if i not in ExcludedPanels:
PanelVDC.append(float(ParsedData['ch'][i][PanelVDC_index]))
minVdc = float('inf')
for i in range(len(PanelVDC)):
if (minVdc > PanelVDC[i]) and (PanelVDC[i] > 5):
minVdc = PanelVDC[i]
if minVdc == float('inf'):
minVdc = 0
# save last 5 min-values in list and return the "highest" value.
HOY_PANEL_VOLTAGE_LIST[pInverterId].append(minVdc)
if len(HOY_PANEL_VOLTAGE_LIST[pInverterId]) > 5:
HOY_PANEL_VOLTAGE_LIST[pInverterId].pop(0)
max_value = None
for num in HOY_PANEL_VOLTAGE_LIST[pInverterId]:
if (max_value is None or num > max_value):
max_value = num
logger.info('Lowest panel voltage inverter "%s": %s Volt',NAME[pInverterId],max_value)
return max_value
def WaitForAck(self, pInverterId: int, pTimeoutInS: int):
try:
timeout = pTimeoutInS
timeout_start = time.time()
while time.time() < timeout_start + timeout:
time.sleep(0.5)
ParsedData = self.GetJson(f'/api/inverter/id/{pInverterId}')
ack = bool(ParsedData['power_limit_ack'])
if ack:
break
if ack:
logger.info('Ahoy: Inverter "%s": Limit acknowledged', NAME[pInverterId])
else:
logger.info('Ahoy: Inverter "%s": Limit timeout!', NAME[pInverterId])
return ack
except Exception as e:
if hasattr(e, 'message'):
logger.error('Ahoy: Inverter "%s" WaitForAck: "%s"', NAME[pInverterId], e.message)
else:
logger.error('Ahoy: Inverter "%s" WaitForAck: "%s"', NAME[pInverterId], e)
return False
def SetLimit(self, pInverterId: int, pLimit: int):
logger.info('Ahoy: Inverter "%s": setting new limit from %s Watt to %s Watt',NAME[pInverterId],CastToInt(CURRENT_LIMIT[pInverterId]),CastToInt(pLimit))
myobj = {'cmd': 'limit_nonpersistent_absolute', 'val': pLimit, "id": pInverterId, "token": self.Token}
response = self.GetResponseJson('/api/ctrl', myobj)
if response["success"] == False and response["error"] == "ERR_PROTECTED":
self.Authenticate()
self.SetLimit(pInverterId, pLimit)
return
if response["success"] == False:
raise Exception("Error: SetLimitAhoy Request error")
CURRENT_LIMIT[pInverterId] = pLimit
def SetPowerStatus(self, pInverterId: int, pActive: bool):
if pActive:
logger.info('Ahoy: Inverter "%s": Turn on',NAME[pInverterId])
else:
logger.info('Ahoy: Inverter "%s": Turn off',NAME[pInverterId])
myobj = {'cmd': 'power', 'val': CastToInt(pActive == True), "id": pInverterId, "token": self.Token}
response = self.GetResponseJson('/api/ctrl', myobj)
if response["success"] == False and response["error"] == "ERR_PROTECTED":
self.Authenticate()
self.SetPowerStatus(pInverterId, pActive)
return
if response["success"] == False:
raise Exception("Error: SetPowerStatus Request error")
def Authenticate(self):
logger.info('Ahoy: Authenticating...')
myobj = {'auth': self.password}
response = self.GetResponseJson('/api/ctrl', myobj)
if response["success"] == False:
raise Exception("Error: Authenticate Request error")
self.Token = response["token"]
logger.info('Ahoy: Authenticating successful, received Token: %s', self.Token)
class OpenDTU(DTU):
def __init__(self, inverter_count: int, ip: str, user: str, password: str):
super().__init__(inverter_count)
self.ip = ip
self.user = user
self.password = password
def GetJson(self, path):
url = f'http://{self.ip}{path}'
return session.get(url, auth=HTTPBasicAuth(self.user, self.password), timeout=10).json()
def GetResponseJson(self, path, sendStr):
url = f'http://{self.ip}{path}'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
return session.post(url=url, headers=headers, data=sendStr, auth=HTTPBasicAuth(self.user, self.password), timeout=10).json()
def GetACPower(self, pInverterId):
ParsedData = self.GetJson(f'/api/livedata/status?inv={SERIAL_NUMBER[pInverterId]}')
return CastToInt(ParsedData['inverters'][0]['AC']['0']['Power']['v'])
def CheckMinVersion(self):
MinVersion = 'v24.2.12'
ParsedData = self.GetJson('/api/system/status')
OpenDTUVersion = str((ParsedData["git_hash"]))
if ("-Database" in OpenDTUVersion): #trim string "v24.5.27-Database"
OpenDTUVersion = OpenDTUVersion.replace("-Database", "")
logger.info('OpenDTU: Current Version: %s',OpenDTUVersion)
if version.parse(OpenDTUVersion) < version.parse(MinVersion):
logger.error('Error: Your OpenDTU Version is too old! Please update at least to Version %s - you can find the newest dev-releases here: https://github.com/tbnobody/OpenDTU/actions',MinVersion)
quit()
def GetAvailable(self, pInverterId: int):