-
Notifications
You must be signed in to change notification settings - Fork 1
/
rct.py
289 lines (260 loc) · 10.6 KB
/
rct.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
#!/usr/bin/env python3
## power_mng.soc_strategy 0: SOC-Ziel = SOC, 1: Konstant, 2: Extern, 3: Mittlere Batteriespannung, 4: Intern, 5: Zeitplan (default: 4)
## power_mng.soc_target_set Force SOC target (default: 0.5) --> (1: Konstant)
## power_mng.battery_power_extern Battery target power (positive = discharge) --> (2. Extern)
## power_mng.soc_min Min SOC target (default 0.07) --> ggf. als Ersatzstrom-Reserve
## power_mng.soc_max Max SOC target (default 0.97) --> ggf. zur Begrenzung des Max.-Ladezustandes
## power_mng.soc_charge_power Charging to power_mng.soc_min with given W (default: 100)
## power_mng.soc_charge Trigger for charing to soc_min (default: 0.05)
## p_rec_lim[1] Max. battery to grid power (default 0) --> Max. Netzeinspeisung aus Batterie in W
## Threshold values
MIN_BATTERY_POWER_EXTERN = -6000
MAX_BATTERY_POWER_EXTERN = 6000
## Imports
import sys
import os
import socket
import select
from rctclient.frame import make_frame, ReceiveFrame
from rctclient.registry import REGISTRY
from rctclient.types import Command
from rctclient.utils import decode_value, encode_value
## Testing Mode
# (set to True to use the testing_string as arguments)
# (activate for testing/debugging only and do not forget to deactivate!)
# (if command line arguments are passed while testing mode activated, the testing mode will be ignored)
testing_mode = False
testing_string = "set p_rec_lim[1] 7000 --host=192.168.0.99"
if testing_mode == True:
if len(sys.argv) < 2:
print('Testing mode activated. Do not forget to deactivate after testing/debugging!')
args = testing_string.split()
args.insert(0, os.path.basename(sys.argv[0]))
else:
print('Testing mode activated, but command line arguments provided! Skipping testing and using provided arguments!')
args = sys.argv
elif testing_mode == False:
args = sys.argv
## Help Function
def show_help():
print("Usage:")
print(" rct.py get <parameter> --host=<ip_address_or_hostname>")
print(" rct.py set <parameter> <value> --host=<ip_address_or_hostname>")
print("\nValid Parameters:")
print(" power_mng.soc_strategy - SOC charging strategy")
print(" Valid Values:")
print(" 0: SOC target = SOC (State of Charge)")
print(" 1: Konstant (Constant)")
print(" 2: Extern (External)")
print(" 3: Mittlere Batteriespannung (Average Battery Voltage)")
print(" 4: Intern (Internal)")
print(" 5: Zeitplan (Schedule)")
print(" Default Value: 4 (Internal)")
print(" power_mng.soc_target_set - Force SOC target")
print(" Valid Range: 0.00 to 1.00, with at most two decimal places")
print(" Default Value: 0.50")
print(" power_mng.battery_power_extern - Battery target power")
print(" Valid Range: {} to {}".format(MIN_BATTERY_POWER_EXTERN, MAX_BATTERY_POWER_EXTERN))
print(" Positive values indicate discharge, negative values indicate charge")
print(" Note: Values will be automatically adjusted to fit within valid ranges.")
print(" Default Value: 0")
print(" power_mng.soc_min - Min SOC target")
print(" Valid Range: 0.00 to 1.00, with at most two decimal places")
print(" Default Value: 0.07")
print(" power_mng.soc_max - Max SOC target")
print(" Valid Range: 0.00 to 1.00, with at most two decimal places")
print(" Default Value: 0.97")
print(" power_mng.soc_charge_power - Charging power to reach SOC target")
print(" Default Value: 100")
print(" power_mng.soc_charge - Trigger for charging to SOC_min")
print(" Default Value: 0.05")
print(" p_rec_lim[1] - Max. battery to grid power")
print(" Valid Range: 0 to 6000")
print(" Default Value: 0")
print(" power_mng.use_grid_power_enable - Enable or disable grid power usage")
print(" Valid Values: FALSE or TRUE")
print(" Default Value: FALSE")
## Write/Set Function
def set_value(parameter, value, host):
valid_parameters = [
"power_mng.soc_strategy",
"power_mng.soc_target_set",
"power_mng.battery_power_extern",
"power_mng.soc_min",
"power_mng.soc_max",
"power_mng.soc_charge_power",
"power_mng.soc_charge",
"p_rec_lim[1]",
"power_mng.use_grid_power_enable"
]
if parameter not in valid_parameters:
print(f"Error: Invalid parameter '{parameter}'.")
show_help()
sys.exit(1)
if parameter == "power_mng.soc_strategy" and value not in ["0", "1", "2", "3", "4", "5"]:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
elif parameter == "power_mng.soc_strategy":
try:
value = int(value)
except ValueError:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
elif parameter == "power_mng.soc_target_set":
try:
value = float(value)
if not (0.00 <= value <= 1.00) or len(str(value).split(".")[1]) > 2:
raise ValueError
except ValueError:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
elif parameter == "power_mng.battery_power_extern":
try:
value = float(value)
if value > MAX_BATTERY_POWER_EXTERN:
value = MAX_BATTERY_POWER_EXTERN
elif value < MIN_BATTERY_POWER_EXTERN:
value = MIN_BATTERY_POWER_EXTERN
except ValueError:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
elif parameter == "power_mng.soc_min":
try:
value = float(value)
if not (0.00 <= value <= 1.00) or len(str(value).split(".")[1]) > 2:
raise ValueError
except ValueError:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
elif parameter == "power_mng.soc_max":
try:
value = float(value)
if not (0.00 <= value <= 1.00) or len(str(value).split(".")[1]) > 2:
raise ValueError
except ValueError:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
elif parameter in ["power_mng.soc_charge_power", "power_mng.soc_charge"]:
try:
value = float(value)
except ValueError:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
elif parameter == "p_rec_lim[1]":
try:
value = float(value)
if not (0 <= value <= 6000):
raise ValueError
except ValueError:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
elif parameter == "power_mng.use_grid_power_enable":
value = value.lower()
if value not in ["false", "true"]:
print(f"Error: Invalid value '{value}' for parameter '{parameter}'.")
show_help()
sys.exit(1)
if value == "true":
value = True
else:
value = False
object_name = parameter
command = Command.WRITE
host_port = (host, 8899)
object_info = REGISTRY.get_by_name(object_name)
encoded_value = encode_value(data_type=object_info.request_data_type, value=value)
send_frame = make_frame(command=command, id=object_info.object_id, payload=encoded_value)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(host_port)
sock.send(send_frame)
sock.close()
output = "Setting value " + str(value) + " for parameter " + parameter + " on host " + host
return output
## Read/Get Function
def get_value(parameter, host):
valid_parameters = [
"power_mng.soc_strategy",
"power_mng.soc_target_set",
"power_mng.battery_power_extern",
"power_mng.soc_max",
"power_mng.soc_min",
"power_mng.soc_charge_power",
"power_mng.soc_charge",
"p_rec_lim[1]",
"power_mng.use_grid_power_enable"
]
if parameter not in valid_parameters:
print(f"Error: Invalid parameter '{parameter}'.")
show_help()
sys.exit(1)
object_name = parameter
command = Command.READ
host_port = (host, 8899)
object_info = REGISTRY.get_by_name(object_name)
send_frame = make_frame(command=command, id=object_info.object_id)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(host_port)
sock.send(send_frame)
# Receive the response
response_frame = ReceiveFrame()
while True:
ready_read, _, _ = select.select([sock], [], [], 2.0)
if sock in ready_read:
# receive content of the input buffer
buf = sock.recv(256)
# if there is content, let the frame consume it
if len(buf) > 0:
response_frame.consume(buf)
# if the frame is complete, we're done
if response_frame.complete():
break
else:
# the socket was closed by the device, exit
sys.exit(1)
# Decode the response value
decoded_value = decode_value(object_info.response_data_type, response_frame.data)
sock.close()
output = decoded_value
return output
## Main Function
if __name__ == "__main__":
if len(args) < 4 or args[1] in ("-h", "--help"):
show_help()
sys.exit(1)
subcommand = args[1]
host = None
# Durchlaufe die Argumente, um die Host-Adresse zu extrahieren
for arg in args[2:]:
if arg.startswith("--host="):
host = arg[len("--host="):]
break
if not host:
print("Error: Host parameter is missing.")
show_help()
sys.exit(1)
if subcommand == "set":
if len(args) != 5:
print("Error: Please provide a parameter, a value, and a host to set.")
show_help()
sys.exit(1)
output = set_value(args[2], args[3], host)
print(output)
elif subcommand == "get":
if len(args) != 4:
print("Error: Please provide a parameter and a host to get.")
show_help()
sys.exit(1)
output = get_value(args[2], host)
print(output)
else:
print(f"Error: Unknown command '{subcommand}'.")
show_help()
sys.exit(1)