forked from snaptec/openWB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisss.py
executable file
·300 lines (270 loc) · 12.8 KB
/
isss.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
#!/usr/bin/python
import logging
import os
import re
import threading
import time
from typing import Dict, List, Optional
import RPi.GPIO as GPIO
from helpermodules.pub import pub_single
from helpermodules import compatibility
from modules.common.store import ramdisk_read, ramdisk_write
from modules.common.store._util import get_rounding_function_by_digits
from modules.common.fault_state import FaultState
from modules.common.component_state import ChargepointState
from modules.common.modbus import ModbusSerialClient_
from modules.internal_openwb import chargepoint_module, socket
from modules.internal_openwb.chargepoint_module import InternalOpenWB
basePath = "/var/www/html/openWB"
ramdiskPath = basePath + "/ramdisk"
logFilename = ramdiskPath + "/isss.log"
MAP_LOG_LEVEL = [logging.ERROR, logging.WARNING, logging.DEBUG]
logging.basicConfig(filename=ramdiskPath+'/isss.log',
format='%(asctime)s - {%(name)s:%(lineno)s} - %(levelname)s - %(message)s',
level=MAP_LOG_LEVEL[int(os.environ.get('debug'))])
log = logging.getLogger()
log.error("Loglevel: "+str(int(os.environ.get('debug'))))
pymodbus_logger = logging.getLogger("pymodbus")
pymodbus_logger.setLevel(logging.WARNING)
class UpdateValues:
MAP_KEY_TO_OLD_TOPIC = {
"imported": "kWhCounter",
"exported": None,
"power": "W",
"voltages": ["VPhase1", "VPhase2", "VPhase3"],
"currents": ["APhase1", "APhase2", "APhase3"],
"power_factors": None,
"phases_in_use": "countPhasesInUse",
"charge_state": "boolChargeStat",
"plug_state": "boolPlugStat",
"rfid": "LastScannedRfidTag",
}
def __init__(self, local_charge_point_num: int) -> None:
self.local_charge_point_num_str = str(local_charge_point_num)
self.cp_num_str = str(Isss.get_cp_num(local_charge_point_num))
self.old_counter_state = None
def update_values(self, counter_state: ChargepointState) -> None:
self.parent_wb = Isss.get_parent_wb()
if self.old_counter_state:
# iterate over counterstate
vars_old_counter_state = vars(self.old_counter_state)
for key, value in vars(counter_state).items():
if value != vars_old_counter_state[key]:
self._pub_values_to_1_9(key, value)
self._pub_values_to_2(key, value)
self.old_counter_state = counter_state
else:
# Bei Neustart alles publishen
for key, value in vars(counter_state).items():
self._pub_values_to_1_9(key, value)
self._pub_values_to_2(key, value)
self.old_counter_state = counter_state
def _pub_values_to_1_9(self, key: str, value) -> None:
def pub_value(topic: str, value):
pub_single("openWB/lp/"+self.local_charge_point_num_str+"/"+topic, payload=str(value), no_json=True)
pub_single("openWB/lp/"+self.cp_num_str+"/"+topic,
payload=str(value), hostname=self.parent_wb, no_json=True)
topic = self.MAP_KEY_TO_OLD_TOPIC[key]
rounding = get_rounding_function_by_digits(2)
if topic is not None:
if isinstance(topic, List):
for i in range(0, 3):
pub_value(topic[i], rounding(value[i]))
else:
if "power" == key:
value = int(value)
elif "imported" == key:
value = value / 1000
if "rfid" == key:
pub_value(self.MAP_KEY_TO_OLD_TOPIC[key], value)
else:
pub_value(self.MAP_KEY_TO_OLD_TOPIC[key], rounding(value))
def _pub_values_to_2(self, topic: str, value) -> None:
rounding = get_rounding_function_by_digits(2)
# fix rfid default value
if topic == "rfid" and value == "0":
value = None
if isinstance(value, (str, bool, type(None))):
pub_single("openWB/set/chargepoint/" + self.cp_num_str +
"/get/"+topic, payload=value, hostname=self.parent_wb)
else:
if isinstance(value, list):
pub_single("openWB/set/chargepoint/" + self.cp_num_str+"/get/"+topic,
payload=[rounding(v) for v in value], hostname=self.parent_wb)
else:
pub_single("openWB/set/chargepoint/" + self.cp_num_str+"/get/"+topic,
payload=rounding(value), hostname=self.parent_wb)
class UpdateState:
def __init__(self, cp_module: chargepoint_module.ChargepointModule) -> None:
self.old_phases_to_use = 3
self.old_set_current = 0
self.phase_switch_thread = None # type: Optional[threading.Thread]
self.cp_interruption_thread = None # type: Optional[threading.Thread]
self.actor_cooldown_thread = None # type: Optional[threading.Thread]
self.cp_module = cp_module
self.__set_current_error = 0
def update_state(self) -> None:
if self.cp_module.config.id == 1:
suffix = ""
else:
suffix = "s1"
try:
heartbeat = int(ramdisk_read("heartbeat"))
except (FileNotFoundError, ValueError):
log.error("Error reading heartbeat. Setting to default 0.")
heartbeat = 0
if heartbeat > 80:
set_current = 0
log.error("Heartbeat Fehler seit " + str(heartbeat) + "Sekunden keine Verbindung, Stoppe Ladung.")
else:
try:
set_current = int(float(ramdisk_read("llsoll"+suffix)))
self.__set_current_error = 0
except (FileNotFoundError, ValueError) as e:
if isinstance(e, FileNotFoundError):
log.error("Didn't find llsoll"+suffix+".")
else:
log.error("Couldn't convert "+str(ramdisk_read("llsoll"+suffix))+" in llsoll"+suffix+" to number.")
self.__set_current_error += 1
if self.__set_current_error > 3:
log.error("Error reading llsoll. Error counter exceed, setting to default 0.")
set_current = 0
else:
log.error("Error reading llsoll. Error counter not exceed, leaving set current unchanged.")
return
try:
cp_interruption_duration = int(float(ramdisk_read("extcpulp1")))
except (FileNotFoundError, ValueError):
log.error("Error reading extcpulp1. Setting to default 3.")
cp_interruption_duration = 3
try:
phases_to_use = int(float(ramdisk_read("u1p3pstat")))
except (FileNotFoundError, ValueError):
log.error("Error reading u1p3pstat. Setting to default 3.")
phases_to_use = 3
log.debug("Values from ramdisk: set_current"+str(set_current) +
" heartbeat "+str(heartbeat) + " phases_to_use "+str(phases_to_use) + "cp_interruption_duration" + str(cp_interruption_duration))
if self.phase_switch_thread:
if self.phase_switch_thread.is_alive():
log.debug("Thread zur Phasenumschaltung an LP"+str(self.cp_module.config.id) +
" noch aktiv. Es muss erst gewartet werden, bis die Phasenumschaltung abgeschlossen ist.")
return
if self.cp_interruption_thread:
if self.cp_interruption_thread.is_alive():
log.debug("Thread zur CP-Unterbrechung an LP"+str(self.cp_module.config.id) +
" noch aktiv. Es muss erst gewartet werden, bis die CP-Unterbrechung abgeschlossen ist.")
return
self.cp_module.set_current(set_current)
if self.old_phases_to_use != phases_to_use and phases_to_use != 0:
log.debug("Switch Phases from "+str(self.old_phases_to_use) + " to " + str(phases_to_use))
self.__thread_phase_switch(phases_to_use)
self.old_phases_to_use = phases_to_use
if cp_interruption_duration > 0:
self.__thread_cp_interruption(cp_interruption_duration)
def __thread_phase_switch(self, phases_to_use: int) -> None:
self.phase_switch_thread = threading.Thread(
target=self.cp_module.perform_phase_switch, args=(phases_to_use, 5))
self.phase_switch_thread.start()
log.debug("Thread zur Phasenumschaltung an LP"+str(self.cp_module.config.id)+" gestartet.")
def __thread_cp_interruption(self, duration: int) -> None:
self.cp_interruption_thread = threading.Thread(
target=self.cp_module.perform_cp_interruption, args=(duration,))
self.cp_interruption_thread.start()
log.debug("Thread zur CP-Unterbrechung an LP"+str(self.cp_module.config.id)+" gestartet.")
ramdisk_write("extcpulp1", "0")
class Isss:
def __init__(self) -> None:
log.debug("Init isss")
self.serial_client = ModbusSerialClient_(self.detect_modbus_usb_port())
self.cp1 = IsssChargepoint(self.serial_client, 1)
try:
if int(ramdisk_read("issslp2act")) == 1:
self.cp2 = IsssChargepoint(self.serial_client, 2)
else:
self.cp2 = None
except (FileNotFoundError, ValueError) as e:
log.error("Error reading issslp2act! Guessing cp2 is not configured.")
self.cp2 = None
self.init_gpio()
def init_gpio(self) -> None:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(37, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(29, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
# GPIOs for socket
GPIO.setup(23, GPIO.OUT)
GPIO.setup(26, GPIO.OUT)
GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def loop(self) -> None:
# connect with USB/modbus device
with self.serial_client:
# start our control loop
while True:
log.setLevel(MAP_LOG_LEVEL[int(os.environ.get('debug'))])
log.debug("***Start***")
self.cp1.update()
if self.cp2:
self.cp2.update()
time.sleep(1.1)
def detect_modbus_usb_port(self) -> str:
"""guess USB/modbus device name"""
try:
with open("/dev/ttyUSB0"):
return "/dev/ttyUSB0"
except FileNotFoundError:
return "/dev/serial0"
@staticmethod
def get_cp_num(local_charge_point_num) -> int:
try:
if local_charge_point_num == 1:
return int(re.sub(r'\D', '', ramdisk_read("parentCPlp1")))
else:
return int(re.sub(r'\D', '', ramdisk_read("parentCPlp2")))
except Exception:
FaultState.warning("Es konnte keine Ladepunkt-Nummer ermittelt werden. Auf Default-Wert 0 gesetzt.")
return 0
@staticmethod
def get_parent_wb() -> str:
# check for parent openWB
try:
return ramdisk_read("parentWB").replace('\\n', '').replace('\"', '')
except Exception:
FaultState.warning("Für den Betrieb im Nur-Ladepunkt-Modus ist zwingend eine Master-openWB erforderlich.")
return ""
class IsssChargepoint:
def __init__(self, serial_client, local_charge_point_num) -> None:
self.local_charge_point_num = local_charge_point_num
if local_charge_point_num == 1:
try:
with open('/home/pi/ppbuchse', 'r') as f:
max_current = int(f.read())
self.module = socket.Socket(max_current, InternalOpenWB(1, serial_client))
except (FileNotFoundError, ValueError):
self.module = chargepoint_module.ChargepointModule(InternalOpenWB(1, serial_client))
else:
self.module = chargepoint_module.ChargepointModule(InternalOpenWB(2, serial_client))
self.update_values = UpdateValues(local_charge_point_num)
self.update_state = UpdateState(self.module)
self.old_plug_state = False
def update(self):
def __thread_active(thread: Optional[threading.Thread]) -> bool:
if thread:
return thread.is_alive()
else:
return False
try:
if self.local_charge_point_num == 2:
time.sleep(0.1)
phase_switch_cp_active = __thread_active(self.update_state.cp_interruption_thread) or __thread_active(
self.update_state.phase_switch_thread)
state, _ = self.module.get_values(phase_switch_cp_active)
log.debug("Published plug state "+str(state.plug_state))
self.update_values.update_values(state)
self.update_state.update_state()
except Exception:
log.exception("Fehler bei Ladepunkt "+str(self.local_charge_point_num))
Isss().loop()