forked from Sevenstax/FreeV2G
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFramingInterface.py
378 lines (306 loc) · 12.8 KB
/
FramingInterface.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
import time
import sys
from multiprocessing import Process, Manager
from binascii import hexlify, unhexlify
import EthernetAdapter
from FramingAPIDef import *
sys.path.append("..")
def log(x): return print(x)
def debug_log(x): pass
class FramingInterface():
def __init__(self):
log("Initiating framing interface")
self.encryption_configured = False
self.encryption_initiated = False
self.connection_mode = "ETHERNET"
self.limited_host_simulation = False
self.sut_ip = ""
self.sut_mac = ""
self.sut_interface = ""
self.request_id = 0
self.seq_nr = -1
self.last_sent = None
self.last_frame_fetch_time = None
self.sut_adapter = None
self.cmd_sut_adapter = None
self.notification_frames = []
self.data_frames = []
self.frame_backlog = []
self.verbose_tx = False
self.verbose_rx = False
self.initialized = False
def isInitialized(self):
return self.initialized
"""
top level function for initializing the SUT adapter for framing
"""
def initialize_framing(self):
"""Top level function for initializing the SUT adapter for framing
"""
if self.connection_mode == "ETHERNET":
self.sut_adapter = EthernetAdapter.EthernetAdapter()
if self.sut_mac != "":
self.sut_adapter.dut_mac = self.sut_mac
else:
self.sut_adapter.sut_ip = self.sut_ip
self.sut_adapter.sut_interface = self.sut_interface
self.sut_adapter.start()
self.seq_nr = 1
self.initialized = True
def set_plain_config(self, connection_mode):
self.connection_mode = connection_mode
def receive_next_unencrypted_frame(self, break_on_data, break_on_notification):
if not self.sut_adapter.holding_data():
return None
else:
return self.sut_adapter.receive()
def reload_communication_interface(self):
if self.connection_mode == "ETHERNET":
self.reload_eth_interface()
"""
reloading ethernet interface after module restart or similar
possibly no action required
"""
def reload_eth_interface(self):
pass
"""
reloading UART interface after module start or similar
"""
def reload_serial_interface(self, baudrate):
log("Reloading serial interface with baudrate: " + str(baudrate))
self.sut_adapter.stop()
self.sut_adapter.process_start(self.bin_uart_port,
baudrate,
self.bin_uart_timeout,
self.bin_uart_stopbits,
self.bin_uart_parity,
self.bin_uart_bytesize,
self.bin_uart_rtscts,
single_byte_mode=True,
lim_res_sim=False)
def send_unencrypted_frame(self, frame):
self.write_output(frame)
def read_input(self, nbytes, timeout=0.3):
data = b""
for i in range(0, nbytes):
end_time = time.time() + timeout
while not self.sut_adapter.holding_data():
if time.time() > end_time:
return None
data += self.sut_adapter.receive()
return data
def write_output(self, data):
"""
Logging frame
"""
if self.verbose_tx and not self.encryption_initiated:
debug_log("Adding the following frame to the send buffer:\n\t" +
self.printable_frame(self.pack_and_parse_frame(data, nocrc=True)) + "\n")
elif self.verbose_tx and self.encryption_initiated:
debug_log("Adding the following frame to the send buffer:\n\t" +
"-".join(str(hexlify(data))[i:i+2] for i in range(0, len(str(hexlify(data))), 2)))
"""
Giving it to the SUT adapter
"""
self.sut_adapter.send(data)
"""
receive a frame from the sut adapters data queue
a frame has to be received within a certain time window
"""
def receive_next_frame(self, break_on_data=False,
break_on_notification=False,
timeout=5,
noisy_timeout=True,
filter_mod=None,
filter_sub=None,
filter_req_id=None,
search_backlog=True):
frame = None
satisfied = False
timeout_point = time.time() + timeout
temp_backlog = []
if self.encryption_initiated:
debug_log("Fetching next encrypted frame from buffer")
else:
debug_log("Fetching next normal frame from buffer")
while not satisfied:
satisfied = True
""" make sure to get frames every x milliseconds """
if self.limited_host_simulation and len(self.frame_backlog) == 0:
if not self.last_frame_fetch_time:
self.last_frame_fetch_time = time.time()
debug_log("Host simulation activated, delaying")
while self.last_frame_fetch_time + 0.002 > time.time():
time.sleep(0.001)
if self.encryption_initiated:
frame = self.receive_next_encrypted_frame()
else:
frame = self.receive_next_unencrypted_frame(
break_on_data, break_on_notification)
# check if we got a frame or no input on uart
if frame is None:
if self.frame_backlog and search_backlog:
debug_log("Retrieving frame from backlog, current size: {}".format(
len(self.frame_backlog)))
frame = self.frame_backlog.pop(0)
# debug_log(self.printable_frame(frame))
if frame is not None:
# convert ids to lists for backwards compatibility
if filter_req_id and isinstance(filter_req_id, int):
id_temp = filter_req_id
filter_req_id = list()
filter_req_id.append(id_temp)
if filter_mod and isinstance(filter_mod, int):
id_temp = filter_mod
filter_mod = list()
filter_mod.append(id_temp)
if filter_sub and isinstance(filter_sub, int):
id_temp = filter_sub
filter_sub = list()
filter_sub.append(id_temp)
# got frame, apply filters
if filter_req_id and not frame.req_id in filter_req_id:
satisfied = False
if filter_mod and not frame.mod_id in filter_mod:
satisfied = False
if filter_sub and not frame.sub_id in filter_sub:
satisfied = False
# for backwards compatibility
if frame.sub_id > 127:
if not break_on_notification and not filter_sub and not filter_mod \
and not filter_req_id:
satisfied = False
elif frame.sub_id == 1:
if break_on_data or 1 in filter_sub:
self.data_frames.append(frame)
else:
satisfied = False
if not satisfied:
temp_backlog.append(frame)
else:
satisfied = False
if timeout == 0:
self.frame_backlog += temp_backlog
if satisfied == False:
frame = None
if self.sut_adapter.holding_data():
continue
break
if time.time() > timeout_point:
self.frame_backlog += temp_backlog
debug_log("Im over timeout {}: timeout_point is {} and i am {}".format(
str(timeout), str(timeout_point), str(time.time())))
if noisy_timeout:
raise AssertionError("Frame reception timed out")
return None
else:
return None
self.frame_backlog += temp_backlog
return frame
def send_frame_and_get_answer(self, module_id, sub_id, payload, timeout=5,
noisy_timeout=False):
req_id = self.build_and_send_frame(module_id, sub_id, payload)
return self.receive_next_frame(filter_req_id=req_id, timeout=timeout,
noisy_timeout=noisy_timeout)
"""
get last sent frame
"""
def get_last_sent(self):
return self.last_sent
"""
send raw frame
"""
def send_frame(self, frame):
self.last_sent = frame
if self.encryption_initiated:
self.send_encrypted_frame(frame)
else:
self.send_unencrypted_frame(frame)
def arg2bytes(self, hexstr, num):
bytearr = b''
bytearr = unhexlify(hexstr)
if len(bytearr) != num:
raise AssertionError(
'Expected a {} bit hexadecimal number.'.format(8*num))
return bytearr
def compute_payload_checksum(self, data):
sum = 0
for i in range(len(data)):
sum += data[i]
sum = (sum & 0xFFFF) + (sum >> 16)
sum = (sum & 0xFF) + (sum >> 8)
sum = (sum & 0xFF) + (sum >> 8)
if(sum != 0xFF):
sum = (~sum & 0xFF)
return sum.to_bytes(1, byteorder="big", signed=False)
def printable_frame(self, frame):
prettystring = "\n###### FRAME ######"
for key in frame.__dict__.keys():
if key[0] == "_":
continue
prettystring += "\n| " + key + ": " + \
str(frame.__dict__[key]) + "\t\t\t"
return prettystring + "\n"
def build_and_send_frame(self, module_id, sub_id, payload, req_id=None):
payload_length_and_payload = len(payload).to_bytes(
2, "big") + payload if payload else b"\x00\x00"
request_id_num = self.generate_next_request_id() if req_id == None else req_id
request_id = request_id_num.to_bytes(1, "big")
frame_without_checksum = (START_OF_FRAME.to_bytes(1, "big") + module_id.to_bytes(1, "big") +
sub_id.to_bytes(1, "big") + request_id +
payload_length_and_payload + b"\x00" + END_OF_FRAME.to_bytes(1,"big"))
self.send_frame(START_OF_FRAME.to_bytes(1, "big") + module_id.to_bytes(1, "big") + sub_id.to_bytes(1, "big")
+ request_id + payload_length_and_payload +
self.compute_payload_checksum(frame_without_checksum) + END_OF_FRAME.to_bytes(1, "big"))
return request_id_num
def generate_next_request_id(self):
if self.request_id == 255:
self.request_id = 0
else:
self.request_id += 1
return self.request_id
def generate_next_seq_nr(self):
if self.seq_nr == 200055:
self.seq_nr = 0
else:
self.seq_nr += 1
return self.seq_nr
def holding_data(self):
return self.sut_adapter.holding_data() or len(self.frame_backlog) > 0
def drain_all_data_frames(self):
time.sleep(2)
while self.holding_data():
self.receive_next_frame(break_on_data=True, timeout=7, search_backlog=True,
noisy_timeout=False)
time.sleep(2)
def clear_all_data_frames(self):
self.drain_data()
self.data_frames.clear()
self.frame_backlog.clear()
def drain_data(self):
self.sut_adapter.clear_queues()
def clear_backlog(self):
self.clear_all_data_frames()
def get_backlog_frames(self):
pass
def get_module_name_by_id(self, id):
for module_name, module_details in MODULE_IDS.items():
if module_details[0] == id:
return module_name
def get_module_id_by_name(self, name):
for module_name, module_details in MODULE_IDS.items():
if module_name == name:
return module_details[0]
def get_sub_name_by_id(self, module_id, sub_id):
for module_name, module_details in MODULE_IDS.items():
if module_details[0] == module_id:
return module_details[1][sub_id][0] if sub_id in module_details[1].keys() else "None"
def get_sub_id_by_name(self, module_name, sub_name):
for s_name, s_id in MODULE_IDS[module_name][1]:
if sub_name == s_name:
return s_id
def shut_down_interface(self):
self.clear_backlog()
self.sut_adapter.clear_queues()
self.sut_adapter.stop()
self.initialized = False