-
-
Notifications
You must be signed in to change notification settings - Fork 236
/
ecu.py
1793 lines (1499 loc) · 66.4 KB
/
ecu.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import glob
import math
import os
import re
import string
import xml.dom.minidom
import zipfile
from io import BytesIO
import elm
import json
import options
_ = options.translator('ddt4all')
addressing = {}
# Returns signed value from 16 bits (2 bytes)
def hex16_tosigned(value):
return -(value & 0x8000) | (value & 0x7fff)
# Returns signed value from 8 bits (1 byte)
def hex8_tosigned(value):
return -(value & 0x80) | (value & 0x7f)
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
def getChildNodesByName(parent, name):
nodes = []
for node in parent.childNodes:
if node.nodeType == node.ELEMENT_NODE and node.localName == name:
nodes.append(node)
return nodes
class Data_item:
def __init__(self, item, req_endian, name=''):
self.firstbyte = 0
self.bitoffset = 0
self.ref = False
self.endian = ''
self.req_endian = req_endian
if isinstance(item, dict):
self.name = name
if 'firstbyte' in item:
self.firstbyte = item['firstbyte']
if 'bitoffset' in item:
self.bitoffset = item['bitoffset']
if 'ref' in item:
self.ref = item['ref']
if 'endian' in item:
self.endian = item['endian']
else:
self.name = item.getAttribute("Name")
fb = item.getAttribute("FirstByte")
if fb:
self.firstbyte = int(fb)
bo = item.getAttribute("BitOffset")
if bo:
self.bitoffset = int(bo)
endian = item.getAttribute("Endian")
if endian:
self.endian = endian
ref = item.getAttribute("Ref")
if ref and ref == '1':
self.ref = True
def dump(self):
js = {}
if self.firstbyte != 0:
js['firstbyte'] = self.firstbyte
if self.bitoffset != 0:
js['bitoffset'] = self.bitoffset
if self.ref != False:
js['ref'] = self.ref
if self.endian != '':
js['endian'] = self.endian
return js
class Ecu_device:
def __init__(self, dev):
self.dtc = 0
self.dtctype = 0
self.devicedata = {}
self.name = ''
if isinstance(dev, dict):
# Json data
self.name = dev['name']
self.dtctype = dev['dtctype']
self.devicedata = dev['devicedata']
self.dtc = dev['dtc']
else:
self.name = dev.getAttribute("Name")
dtc = dev.getAttribute("DTC")
if dtc: self.dtc = int(dtc)
dtctype = dev.getAttribute("Type")
if dtctype: self.dtctype = int(dtctype)
devicedata = dev.getElementsByTagName("DeviceData")
if devicedata:
for data in devicedata:
name = data.getAttribute("Name")
failureflag = data.getAttribute("FailureFlag")
self.devicedata[name] = failureflag
def dump(self):
js = {}
js['dtc'] = self.dtc
js['dtctype'] = self.dtctype
js['devicedata'] = self.devicedata
js['name'] = self.name
return js
class Ecu_request:
def __init__(self, data, ecu_file):
self.minbytes = 0
self.shiftbytescount = 0
self.replybytes = ''
self.manualsend = False
self.sentbytes = ''
self.dataitems = {}
self.sendbyte_dataitems = {}
self.name = ''
self.ecu_file = ecu_file
# StartDiagSession requirements
# Seems relatively useless...
self.sds = {'nosds': True,
'plant': True,
'aftersales': True,
'engineering': True,
'supplier': True}
if isinstance(data, dict):
if 'minbytes' in data: self.minbytes = data['minbytes']
if 'shiftbytescount' in data: self.shiftbytescount = data['shiftbytescount']
if 'replybytes' in data: self.replybytes = data['replybytes']
if 'manualsend' in data: self.manualsend = data['manualsend']
if 'sentbytes' in data: self.sentbytes = data['sentbytes']
self.name = data['name']
if 'deny_sds' in data:
if 'nosds' in data['deny_sds']:
self.sds['nosds'] = False
if 'plant' in data['deny_sds']:
self.sds['plant'] = False
if 'aftersales' in data['deny_sds']:
self.sds['aftersales'] = False
if 'engineering' in data['deny_sds']:
self.sds['engineering'] = False
if 'supplier' in data['deny_sds']:
self.sds['supplier'] = False
if 'sendbyte_dataitems' in data:
sbdi = data['sendbyte_dataitems']
for k, v in sbdi.items():
di = Data_item(v, self.ecu_file.endianness, k)
self.sendbyte_dataitems[k] = di
if 'receivebyte_dataitems' in data:
rbdi = data['receivebyte_dataitems']
for k, v in rbdi.items():
di = Data_item(v, self.ecu_file.endianness, k)
self.dataitems[k] = di
elif isinstance(data, str):
# Create a blank, new one
self.name = data
else:
self.xmldoc = data
self.name = self.xmldoc.getAttribute("Name")
accessdata = self.xmldoc.getElementsByTagName("DenyAccess").item(0)
if accessdata:
for accessdatachild in accessdata.childNodes:
if accessdatachild.nodeName == "NoSDS":
self.sds['nosds'] = False
elif accessdatachild.nodeName == "Plant":
self.sds['plant'] = False
elif accessdatachild.nodeName == "AfterSales":
self.sds['aftersales'] = False
elif accessdatachild.nodeName == "Engineering":
self.sds['engineering'] = False
elif accessdatachild.nodeName == "Supplier":
self.sds['supplier'] = False
manualsenddata = self.xmldoc.getElementsByTagName("ManuelSend").item(0)
if manualsenddata:
self.manualsend = True
shiftbytescount = self.xmldoc.getElementsByTagName("ShiftBytesCount")
if shiftbytescount:
self.shiftbytescount = int(shiftbytescount.item(0).firstChild.nodeValue)
replybytes = self.xmldoc.getElementsByTagName("ReplyBytes")
if replybytes:
self.replybytes = replybytes.item(0).firstChild.nodeValue
receiveddata = self.xmldoc.getElementsByTagName("Received").item(0)
if receiveddata:
minbytes = receiveddata.getAttribute("MinBytes")
if minbytes:
self.minbytes = int(minbytes)
dataitems = receiveddata.getElementsByTagName("DataItem")
if dataitems:
for dataitem in dataitems:
di = Data_item(dataitem, self.ecu_file.endianness)
self.dataitems[di.name] = di
sentdata = self.xmldoc.getElementsByTagName("Sent")
if sentdata:
sent = sentdata.item(0)
sentbytesdata = sent.getElementsByTagName("SentBytes")
if sentbytesdata:
if sentbytesdata.item(0).firstChild:
self.sentbytes = sentbytesdata.item(0).firstChild.nodeValue
dataitems = sent.getElementsByTagName("DataItem")
if dataitems:
for dataitem in dataitems:
di = Data_item(dataitem, self.ecu_file.endianness)
self.sendbyte_dataitems[di.name] = di
def send_request(self, inputvalues=None, test_data=None):
if inputvalues is None:
inputvalues = {}
request_stream = self.build_data_stream(inputvalues)
request_stream = " ".join(request_stream)
if options.debug:
print(_("Generated stream "), request_stream)
if options.simulation_mode:
if test_data is not None:
elmstream = test_data
print(_("Send request stream "), request_stream)
else:
# return default reply bytes...
elmstream = self.replybytes
else:
elmstream = options.elm.request(request_stream)
if options.debug:
print(_("Received stream "), elmstream)
if elmstream.startswith('WRONG RESPONSE'):
return None
if elmstream.startswith('7F'):
nrsp = options.elm.errorval(elmstream[6:8])
print(_("Request ECU Error"), nrsp)
return None
values = self.get_values_from_stream(elmstream)
if options.debug:
print(_("Decoded values"), values)
return values
def get_data_inputs(self):
return self.sendbyte_dataitems.keys()
def build_data_stream(self, data):
data_stream = self.get_formatted_sentbytes()
for k, v in data.items():
if k in self.sendbyte_dataitems:
datatitem = self.sendbyte_dataitems[k]
else:
raise KeyError('Ecurequest::build_data_stream : Data item %s does not exist' % k)
if k in self.ecu_file.data:
data = self.ecu_file.data[k]
else:
raise KeyError('Ecurequest::build_data_stream : Data %s does not exist' % k)
if v in data.items:
v = hex(data.items[v])[2:].upper()
data.setValue(v, data_stream, datatitem, self.ecu_file.endianness)
return data_stream
def get_values_from_stream(self, stream):
values = {}
for k, v in self.dataitems.items():
if k in self.ecu_file.data:
data = self.ecu_file.data[k]
values[k] = data.getDisplayValue(stream, v, self.ecu_file.endianness)
else:
raise KeyError('Ecurequest::get_values_from_stream : Data %s does not exist' % k)
return values
def get_formatted_sentbytes(self):
bytes_to_send_ascii = self.sentbytes
return [str(bytes_to_send_ascii[i:i + 2]) for i in range(0, len(bytes_to_send_ascii), 2)]
def dump(self):
js = {}
if self.minbytes != 0:
js['minbytes'] = self.minbytes
if self.shiftbytescount != 0:
js['shiftbytescount'] = self.shiftbytescount
if self.replybytes != '':
js['replybytes'] = self.replybytes
if self.manualsend:
js['manualsend'] = self.manualsend
if self.sentbytes != '':
js['sentbytes'] = self.sentbytes
js['name'] = self.name
js['deny_sds'] = []
if self.sds['nosds'] is False:
js['deny_sds'].append('nosds')
if self.sds['plant'] is False:
js['deny_sds'].append('plant')
if self.sds['aftersales'] is False:
js['deny_sds'].append('aftersales')
if self.sds['engineering'] is False:
js['deny_sds'].append('engineering')
if self.sds['supplier'] is False:
js['deny_sds'].append('supplier')
sdi = {}
for key, value in self.sendbyte_dataitems.items():
sdi[key] = value.dump()
if len(sdi):
js['sendbyte_dataitems'] = sdi
rdi = {}
for key, value in self.dataitems.items():
rdi[key] = value.dump()
if len(rdi):
js['receivebyte_dataitems'] = rdi
return js
def dump_dataitems(self):
di = {}
for key, value in self.dataitems.items():
di[key] = value.dump()
return di
def dump_sentdataitems(self):
di = {}
for key, value in self.sendbyte_dataitems.items():
di[key] = value.dump()
return di
class Ecu_data:
def __init__(self, data, name=''):
self.bitscount = 8
self.scaled = False
self.signed = False
self.byte = False
self.binary = False
self.bytescount = 1
self.bytesascii = False
self.step = 1.0
self.offset = 0.0
self.divideby = 1.0
self.format = ""
self.lists = {}
self.items = {}
self.description = ''
self.unit = ""
self.comment = ''
self.name = name
if data:
self.init(data)
def init(self, data):
if isinstance(data, dict):
if 'bitscount' in data:
self.bitscount = data['bitscount']
if 'bytesascii' in data:
self.bytesascii = data['bytesascii']
if 'scaled' in data:
self.scaled = data['scaled']
if 'signed' in data:
self.signed = data['signed']
if 'byte' in data:
self.byte = data['byte']
if 'binary' in data:
self.binary = data['binary']
if 'step' in data:
self.step = data['step']
if 'offset' in data:
self.offset = data['offset']
if 'divideby' in data:
self.divideby = data['divideby']
if 'format' in data:
self.format = data['format']
if 'bytescount' in data:
self.bytescount = data['bytescount']
if 'unit' in data:
self.unit = data['unit']
if 'comment' in data:
self.comment = data['comment']
if 'lists' in data:
for k, v in data['lists'].items():
self.lists[int(k)] = v
self.items[v] = int(k)
else:
self.xmldoc = data
self.name = self.xmldoc.getAttribute("Name")
description = self.xmldoc.getElementsByTagName("Description")
if description:
self.description = description.item(0).firstChild.nodeValue.replace('<![CDATA[', '').replace(']]>', '')
comment = self.xmldoc.getElementsByTagName("Comment")
if comment:
self.comment = comment.item(0).firstChild.nodeValue.replace('<![CDATA[', '').replace(']]>', '')
lst = self.xmldoc.getElementsByTagName("List")
if lst:
for l in lst:
items = l.getElementsByTagName("Item")
for item in items:
key = int(item.getAttribute('Value'))
val = item.getAttribute('Text')
self.lists[int(key)] = val
self.items[val] = int(key)
bytes = self.xmldoc.getElementsByTagName("Bytes")
if bytes:
self.byte = True
bytescount = bytes.item(0).getAttribute("count").replace(',', '.')
if '.' in bytescount:
self.bytescount = math.ceil(float(bytescount))
self.bitscount = int(float(bytescount) * 8)
elif bytescount:
self.bytescount = int(bytescount)
self.bitscount = self.bytescount * 8
bytesascii = bytes.item(0).getAttribute("ascii")
if bytesascii and bytesascii == '1': self.bytesascii = True
bits = self.xmldoc.getElementsByTagName("Bits")
if bits:
bitscount = bits.item(0).getAttribute("count")
if bitscount:
self.bitscount = int(bitscount)
self.bytescount = int(math.ceil(float(bitscount) / 8.0))
signed = bits.item(0).getAttribute("signed")
if signed:
self.signed = True
binary = bits.item(0).getElementsByTagName("Binary")
if binary:
self.binary = True
scaled_value = bits.item(0).getElementsByTagName("Scaled")
if scaled_value:
self.scaled = True
sc = scaled_value.item(0)
step = sc.getAttribute("Step")
if step:
self.step = float(step)
offset = sc.getAttribute("Offset")
if offset:
self.offset = float(offset)
divideby = sc.getAttribute("DivideBy")
if divideby:
self.divideby = float(divideby)
format = sc.getAttribute("Format")
if format:
self.format = format
unit = sc.getAttribute("Unit")
if unit:
self.unit = unit
def dump(self):
js = {}
if self.bitscount != 8:
js['bitscount'] = self.bitscount
if self.scaled != False:
js['scaled'] = self.scaled
if self.signed != False:
js['signed'] = self.signed
if self.byte != False:
js['byte'] = self.byte
if self.binary != False:
js['binary'] = self.binary
if self.bytescount != 1:
js['bytescount'] = self.bytescount
if self.bytesascii != False:
js['bytesascii'] = self.bytesascii
if self.step != 1:
js['step'] = self.step
if self.offset != 0:
js['offset'] = self.offset
if self.divideby != 1:
js['divideby'] = self.divideby
if self.format != '':
js['format'] = self.format
if len(self.lists) > 0:
lst = {}
for k, v in self.lists.items():
lst[int(k)] = v
js['lists'] = lst
if self.unit != '':
js['unit'] = self.unit
if self.comment != '':
js['comment'] = cleanhtml(self.comment)
return self.name, js
def setValue(self, value, bytes_list, dataitem, ecu_endian, test_mode=False):
start_byte = dataitem.firstbyte - 1
start_bit = dataitem.bitoffset
little_endian = False
if ecu_endian == "Little":
little_endian = True
# It seems that DataItem can override Request endianness
if dataitem.endian == "Little":
little_endian = True
if dataitem.endian == "Big":
little_endian = False
if self.bytesascii:
value = str(value)
if self.bytescount > len(value):
value = value.ljust(self.bytescount)
if self.bytescount < len(value):
value = value[0:self.bytescount]
asciival = ""
for i in range(self.bytescount):
if not test_mode:
asciival += hex(ord(value[i]))[2:].upper()
else:
asciival += "FF"
value = asciival
if self.scaled:
if not test_mode:
try:
value = float(value)
except:
return None
# Input value must be base 10
value = int((value * float(self.divideby) - float(self.offset)) / float(self.step))
else:
value = int("0x" + value, 16)
else:
if not test_mode:
# Check input length and validity
if not all(c in string.hexdigits for c in value):
return None
# Value is base 16
value = int('0x' + str(value), 16)
else:
value = int("0x" + value, 16)
valueasbin = bin(value)[2:].zfill(self.bitscount)
numreqbytes = int(math.ceil(float(self.bitscount + start_bit) / 8.))
request_bytes = bytes_list[start_byte:start_byte + numreqbytes]
requestasbin = ""
for r in request_bytes:
requestasbin += bin(int(r, 16))[2:].zfill(8)
requestasbin = list(requestasbin)
if little_endian:
# Little endian coding is really weird :/
# Cannot figure out why it's being used
# But tried to do my best to mimic the read/write process
# Actually, need to do it in 3 steps
remainingbits = self.bitscount
# Step 1
lastbit = 7 - start_bit + 1
firstbit = lastbit - self.bitscount
if firstbit < 0:
firstbit = 0
count = 0
for i in range(firstbit, lastbit):
requestasbin[i] = valueasbin[count]
count += 1
remainingbits -= count
# Step 2
currentbyte = 1
while remainingbits >= 8:
for i in range(0, 8):
requestasbin[currentbyte * 8 + i] = valueasbin[count]
count += 1
remainingbits -= 8
currentbyte += 1
# Step 3
if remainingbits > 0:
lastbit = 8
firstbit = lastbit - remainingbits
for i in range(firstbit, lastbit):
requestasbin[currentbyte * 8 + i] = valueasbin[count]
count += 1
else:
for i in range(self.bitscount):
requestasbin[i + start_bit] = valueasbin[i]
requestasbin = "".join(requestasbin)
valueasint = int("0b" + requestasbin, 2)
valueashex = hex(valueasint)[2:].replace("L", "").zfill(numreqbytes * 2).upper()
for i in range(numreqbytes):
bytes_list[i + start_byte] = valueashex[i * 2:i * 2 + 2].zfill(2)
return bytes_list
def getDisplayValue(self, elm_data, dataitem, ecu_endian):
value = self.getHexValue(elm_data, dataitem, ecu_endian)
if value is None:
return None
if self.bytesascii:
return bytes.fromhex(value).decode('utf-8', errors="ignore")
# I think we want Hex format for non scaled values
if not self.scaled:
val = int('0x' + value, 16)
# Manage signed values
if self.signed:
if self.bytescount == 1:
val = hex8_tosigned(val)
elif self.bytescount == 2:
val = hex16_tosigned(val)
else:
print(_("Warning, cannot get signed value for") + " %s" % dataitem.name)
# Manage mapped values if exists
if val in self.lists:
return self.lists[val]
# Return default hex value
return value
value = int('0x' + value, 16)
# Manage signed values
if self.signed:
if self.bytescount == 1:
value = hex8_tosigned(value)
elif self.bytescount == 2:
value = hex16_tosigned(value)
if self.divideby == 0:
print(_("Division by zero, please check data item: "), dataitem.name)
return None
res = (float(value) * float(self.step) + float(self.offset)) / float(self.divideby)
if len(self.format) and '.' in self.format:
acc = len(self.format.split('.')[1])
fmt = '%.' + str(acc) + 'f'
res = fmt % res
else:
if int(res) == res:
return str(int(res))
return str(res)
def getIntValue(self, resp, dataitem, ecu_endian):
val = self.getHexValue(resp, dataitem, ecu_endian)
if val is None:
return None
return int("0x" + val, 16)
def getHexValue(self, resp, dataitem, ecu_endian):
little_endian = False
if ecu_endian == "Little":
little_endian = True
if dataitem.endian == "Little":
little_endian = True
if dataitem.endian == "Big":
little_endian = False
# Data cleaning
resp = resp.strip().replace(' ', '')
if not all(c in string.hexdigits for c in resp): resp = ''
resp.replace(' ', '')
res_bytes = [resp[i:i + 2] for i in range(0, len(resp), 2)]
# Data count
startByte = dataitem.firstbyte
startBit = dataitem.bitoffset
bits = self.bitscount
databytelen = int(math.ceil(float(self.bitscount) / 8.0))
reqdatabytelen = int(math.ceil(float(self.bitscount + startBit) / 8.0))
sb = startByte - 1
if (sb * 2 + databytelen * 2) > (len(resp)):
return None
hexval = resp[sb * 2:(sb + reqdatabytelen) * 2]
hextobin = ""
for b in res_bytes[sb:sb + reqdatabytelen]:
hextobin += bin(int(b, 16))[2:].zfill(8)
if len(hexval) == 0:
return None
if little_endian:
# Don't like this method
totalremainingbits = bits
lastbit = 7 - startBit + 1
firstbit = lastbit - bits
if firstbit < 0:
firstbit = 0
tmp_bin = hextobin[firstbit:lastbit]
totalremainingbits -= lastbit - firstbit
if totalremainingbits > 8:
offset1 = 8
offset2 = offset1 + ((reqdatabytelen - 2) * 8)
tmp_bin += hextobin[offset1:offset2]
totalremainingbits -= offset2 - offset1
if totalremainingbits > 0:
offset1 = (reqdatabytelen - 1) * 8
offset2 = offset1 - totalremainingbits
tmp_bin += hextobin[offset2:offset1]
totalremainingbits -= offset1 - offset2
if totalremainingbits != 0:
print(_("getHexValue >> abnormal remaining bytes "), bits, totalremainingbits)
hexval = hex(int("0b" + tmp_bin, 2))[2:].replace("L", "")
else:
valtmp = "0b" + hextobin[startBit:startBit + bits]
hexval = hex(int(valtmp, 2))[2:].replace("L", "")
# Resize to original length
hexval = hexval.zfill(databytelen * 2)
return hexval
class Ecu_file:
def __init__(self, data, isfile=False):
self.requests = {}
self.devices = {}
self.data = {}
self.endianness = ''
self.ecu_protocol = ''
self.ecu_send_id = "00"
self.ecu_recv_id = "00"
self.fastinit = False
self.kw1 = ""
self.kw2 = ""
self.funcname = ""
self.funcaddr = "00"
self.ecuname = ""
self.projects = []
self.autoidents = []
self.baudrate = 0
if not data:
return
if isfile:
if not os.path.exists(data):
if os.path.exists("./ecus/" + data + ".xml"):
data = "./ecus/" + data + ".xml"
if isfile and ".xml" not in data[-4:] and ".json" not in data[-5:]:
xmlname = data + ".xml"
if os.path.exists(xmlname):
data = xmlname
else:
data += ".json"
if isfile and '.json' in data:
data2 = "./json/" + os.path.basename(data)
jsdata = None
if os.path.exists(data):
jsfile = open(data, "r")
jsdata = jsfile.read()
jsfile.close()
elif os.path.exists(data2):
jsfile = open(data2, "r")
jsdata = jsfile.read()
jsfile.close()
else:
# Zipped json here
if os.path.exists('ecu.zip'):
zf = zipfile.ZipFile('ecu.zip', mode='r')
if data in zf.namelist():
jsdata = zf.read(data)
elif os.path.basename(data) in zf.namelist():
jsdata = zf.read(os.path.basename(data))
else:
print(_("Cannot find file "), data)
return
if jsdata is None:
return
ecudict = json.loads(jsdata)
if "obd" in ecudict:
self.ecu_protocol = ecudict['obd']['protocol']
if self.ecu_protocol == "CAN":
self.ecu_send_id = ecudict['obd']['send_id']
self.ecu_recv_id = ecudict['obd']['recv_id']
if 'baudrate' in ecudict['obd']:
self.baudrate = int(ecudict['obd']['baudrate'])
if self.ecu_protocol == "KWP2000":
self.fastinit = ecudict['obd']['fastinit']
self.funcaddr = ecudict['obd']['funcaddr']
if 'funcname' in ecudict['obd']:
self.funcname = ecudict['obd']['funcname']
if "kw1" in ecudict['obd']:
self.kw1 = ecudict['obd']['kw1']
self.kw2 = ecudict['obd']['kw2']
if 'endian' in ecudict:
self.endianness = ecudict['endian']
if 'ecuname' in ecudict:
self.ecuname = ecudict['ecuname']
devices = ecudict['devices']
for device in devices:
ecu_dev = Ecu_device(device)
self.devices[ecu_dev.name] = ecu_dev
requests = ecudict['requests']
for request in requests:
ecu_req = Ecu_request(request, self)
self.requests[ecu_req.name] = ecu_req
datalist = ecudict['data']
for k, v in datalist.items():
self.data[k] = Ecu_data(v, k)
else:
if isfile:
if not os.path.exists(data):
print(_("Cannot load ECU file"), data)
return
xdom = xml.dom.minidom.parse(data)
self.xmldoc = xdom.documentElement
if not self.xmldoc:
print(_("XML not found"))
return
target = getChildNodesByName(self.xmldoc, u"Target")
if target:
self.ecuname = target[0].getAttribute("Name")
autoidents = getChildNodesByName(target[0], u"AutoIdents")
if autoidents:
autoident = getChildNodesByName(autoidents[0], u"AutoIdent")
for ai in autoident:
autoident_dict = {}
autoident_dict['diagversion'] = ai.getAttribute("DiagVersion")
autoident_dict['supplier'] = ai.getAttribute("Supplier")
autoident_dict['soft'] = ai.getAttribute("Soft")
autoident_dict['version'] = ai.getAttribute("Version")
self.autoidents.append(autoident_dict)
projects = getChildNodesByName(target[0], u"Projects")
if projects:
for project in projects[0].childNodes:
self.projects.append(project.nodeName)
functions = getChildNodesByName(target[0], u"Function")
if functions:
self.funcaddr = hex(int(functions[0].getAttribute("Address")))[2:].upper().zfill(2)
self.funcname = functions[0].getAttribute("Name")
can = getChildNodesByName(target[0], u"CAN")
if can:
self.ecu_protocol = "CAN"
self.baudrate = int(can[0].getAttribute("BaudRate"))
send_ids = getChildNodesByName(can[0], "SendId")
if send_ids:
send_id = send_ids[0]
can_id = getChildNodesByName(send_id, "CANId")
if can_id:
self.ecu_send_id = hex(int(can_id[0].getAttribute("Value")))[2:].upper()
rcv_ids = getChildNodesByName(can[0], "ReceiveId")
if rcv_ids:
rcv_id = rcv_ids[0]
can_id = getChildNodesByName(rcv_id, "CANId")
if can_id:
self.ecu_recv_id = hex(int(can_id[0].getAttribute("Value")))[2:].upper()
k = getChildNodesByName(target[0], u"K")
if k:
kwp = getChildNodesByName(k[0], u"KWP")
iso8 = getChildNodesByName(k[0], u"ISO8")
if kwp:
kwp = kwp[0]
self.ecu_protocol = u"KWP2000"
fastinit = getChildNodesByName(kwp, u"FastInit")
if fastinit:
self.fastinit = True
KW1 = getChildNodesByName(fastinit[0], "KW1")
KW2 = getChildNodesByName(fastinit[0], "KW2")
else:
iso8 = getChildNodesByName(kwp, u"ISO8")
KW1 = getChildNodesByName(iso8[0], "KW1")
KW2 = getChildNodesByName(iso8[0], "KW2")
self.kw1 = hex(int(KW1[0].getAttribute("Value")))[2:].upper()
self.kw2 = hex(int(KW2[0].getAttribute("Value")))[2:].upper()
elif iso8:
self.fastinit = False
self.ecu_protocol = "ISO8"
self.kw1 = hex(
int(getChildNodesByName(iso8[0], "KW1")[0].getAttribute("Value")))[2:].upper()
self.kw2 = hex(
int(getChildNodesByName(iso8[0], "KW2")[0].getAttribute("Value")))[2:].upper()
devices = self.xmldoc.getElementsByTagName("Device")
for d in devices:
ecu_dev = Ecu_device(d)
self.devices[ecu_dev.name] = ecu_dev
requests_tag = self.xmldoc.getElementsByTagName("Requests")
if requests_tag:
for request_tag in requests_tag:
endian = ''
endian_attr = request_tag.getAttribute("Endian")
if endian_attr:
self.endianness = endian_attr
requests = request_tag.getElementsByTagName("Request")
for f in requests:
ecu_req = Ecu_request(f, self)
self.requests[ecu_req.name] = ecu_req
data = self.xmldoc.getElementsByTagName("Data")
for f in data:
ecu_data = Ecu_data(f)
self.data[ecu_data.name] = ecu_data
def get_request(self, name):
if name in self.requests:
return self.requests[name]
for k, v in self.requests.items():
if k.lower() == name.lower():
return v
return None