-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFronius_manager.py
More file actions
165 lines (144 loc) · 5.65 KB
/
Copy pathFronius_manager.py
File metadata and controls
165 lines (144 loc) · 5.65 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
#!/usr/bin/python3.11
import subprocess
from time import sleep
import systemd.daemon
import threading
import asyncio
import requests
from config import URL_PANELEN, READER_DATA_JSON, SETPOINTS_JSON, PV_VALUES_JSON, MIN_LIMIT
from shared_store import set_key, get_key
from logger_setup import get_logger
logger = get_logger("PV_reader")
class FroniusPowerLimitAPI:
def __init__(self, ip, unit=1):
self.ip = ip
self.unit = unit
# Model 123 begint bij 40238
self.base = 40238
self.reg_conn = 40242
self.reg_limit = 40243
self.reg_enable = 40247
def _write(self, reg, value):
cmd = [
"modpoll",
"-m", "tcp",
"-t", "4",
"-r", str(reg),
"-1",
self.ip,
str(value)
]
subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def _read_block(self, start, count):
cmd = [
"modpoll",
"-m", "tcp",
"-t", "4",
"-r", str(start),
"-c", str(count),
"-1",
self.ip
]
result = subprocess.run(cmd, capture_output=True, text=True)
return result.stdout
def set_limit(self, percent):
"""Zet WMaxLimPct en enable."""
self._write(self.reg_enable, 1)
self._write(self.reg_limit, percent)
def get_limit(self):
"""Leest alleen WMaxLimPct terug."""
output = self._read_block(self.reg_limit, 1)
for line in output.splitlines():
if "[" in line and "]" in line:
parts = line.split("]:")
if len(parts) == 2:
return int(parts[1].strip())
return None
def get_status(self):
"""Leest Model 123 (20 registers) en geeft dict terug."""
output = self._read_block(self.base, 20)
regs = {}
for line in output.splitlines():
if "[" in line and "]" in line:
addr = int(line.split("]")[0].replace("[", ""))
val = int(line.split("]:")[1].strip())
regs[addr] = val
if regs.get(self.reg_conn) is None:
return False
return {
"Conn": regs.get(self.reg_conn),
"WMaxLimPct": regs.get(self.reg_limit),
"WMaxLim_Ena": regs.get(self.reg_enable),
"Raw": regs
}
def watchdog_task() -> None:
while True:
systemd.daemon.notify("WATCHDOG=1")
sleep(1)
def write_fronius_limit(limit):
api.set_limit(limit)
status2 = api.get_status()
if status2["WMaxLimPct"] == limit:
logger.warning(f"Fronius limit update succesvol naar {status2['WMaxLimPct']}\n")
return True
else:
logger.error(f"Fronius limit update mislukt: {status2}\n")
return False
def changeFronius():
while True:
try:
new_limit = get_key("PV_reader", default={"limit": 100}, path=SETPOINTS_JSON)["limit"]
if new_limit < MIN_LIMIT:
new_limit = MIN_LIMIT
data = requests.get(api_PRODUCTION, timeout=10).json()
production = data["Body"]["Data"]["PAC"]["Values"]["1"]
set_key("PV_reader", {"production": production}, path=READER_DATA_JSON)
status = api.get_status()
if status:
logger.info(f"{status}")
limit = status["WMaxLimPct"]
if new_limit != limit:
check = False
attempts = 0
max_attempts = 3
while check == False and attempts < max_attempts:
attempts += 1
check = write_fronius_limit(new_limit)
if not check:
logger.warning(f"Poging {attempts}/{max_attempts} om limiet te zetten mislukt")
sleep(10)
if not check:
logger.error(f"Limiet zetten definitief mislukt na {max_attempts} pogingen (gewenst: {new_limit})")
except requests.exceptions.ConnectionError:
# Verwacht 's nachts: de omvormer is dan offline, geen ERROR-spam.
logger.info("changeFronius: geen verbinding (omvormer waarschijnlijk offline, bijv. 's nachts)")
except Exception as error:
logger.error(f"changeFronius mislukt: {error}")
sleep(180)
def readFronius():
while True:
try:
data = requests.get(api_DATA, timeout=10).json()
for key in data["Body"]["Data"]:
if key != "DeviceStatus":
value = data["Body"]["Data"][key]["Value"]
set_key("PV_reader", {key: value}, path=PV_VALUES_JSON)
except requests.exceptions.ConnectionError:
# Verwacht 's nachts: de omvormer schakelt zichzelf uit zodra er
# geen productie meer is en accepteert dan geen requests meer.
# Geen ERROR-spam voor iets dat elke dag opnieuw normaal gebeurt.
logger.info("readFronius: geen verbinding (omvormer waarschijnlijk offline, bijv. 's nachts)")
except Exception as error:
logger.error(f"readFronius mislukt: {error}")
sleep(60)
if __name__ == "__main__":
api = FroniusPowerLimitAPI(URL_PANELEN)
api_PRODUCTION = f"http://{URL_PANELEN}/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System"
api_DATA = f"http://{URL_PANELEN}/solar_api/v1/GetInverterRealtimeData.cgi?DeviceId=1&Scope=Device&DataCollection=CommonInverterData"
systemd.daemon.notify("READY=1")
threading.Thread(target=watchdog_task, daemon=True).start()
threading.Thread(target=changeFronius, daemon=True).start()
threading.Thread(target=readFronius, daemon=True).start()
# hoofdthread blijft leven
while True:
sleep(10)