-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod_utils.py
380 lines (305 loc) · 8.96 KB
/
mod_utils.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
#!/usr/bin/env python
'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
import sys
import os
import string
import signal
import atexit
import subprocess
import mod_globals
try:
import webbrowser
except:
pass
def Choice(list, question ):
'''Util for make simple choice'''
d = {};
c = 1
exitNumber = 0
for s in list:
if s.lower()=='<up>' or s.lower()=='<exit>':
exitNumber = c
print "%-2s - %s" % ('Q', pyren_encode(s))
d['Q']=s
else:
print "%-2s - %s" % (c, pyren_encode(s))
d[str(c)]=s
c = c+1
while (True):
try:
ch = raw_input(question)
except (KeyboardInterrupt, SystemExit):
print
print
sys.exit()
if ch=='q': ch = 'Q'
if ch=='cmd': mod_globals.opt_cmd = True
if ch in d.keys():
return [d[ch],ch]
def ChoiceLong(list, question, header = '' ):
'''Util for make choice from long list'''
d = {};
c = 1
exitNumber = 0
page = 0
page_size = 20
for s in list:
if s.lower()=='<up>' or s.lower()=='<exit>':
exitNumber = c
d['Q']=s
else:
d[str(c)]=s
c = c+1
while( 1 ):
clearScreen()
#os.system('cls' if os.name == 'nt' else 'clear') # clear screen
#print chr(27)+"[2J"+chr(27)+"[;H", # clear ANSI screen (thanks colorama for windows)
if len( header ): print pyren_encode(header)
c = page*page_size
for s in list[page*page_size:(page+1)*page_size]:
c = c + 1
if s.lower()=='<up>' or s.lower()=='<exit>':
print "%-2s - %s" % ('Q', pyren_encode(s))
else:
print "%-2s - %s" % (c, pyren_encode(s))
if len(list)>page_size:
if page>0:
print "%-2s - %s" % ('P', '<prev page>')
if (page+1)*page_size<len(list):
print "%-2s - %s" % ('N', '<next page>')
while (True):
try:
ch = raw_input(question)
except (KeyboardInterrupt, SystemExit):
print
print
sys.exit()
if ch=='q': ch = 'Q'
if ch=='p': ch = 'P'
if ch=='n': ch = 'N'
if ch=='N' and (page+1)*page_size<len(list):
page = page + 1
break
if ch=='P' and page>0:
page = page - 1
break
if ch=='cmd': mod_globals.opt_cmd = True
if ch in d.keys():
return [d[ch],ch]
def ChoiceFromDict(dict, question, showId = True ):
'''Util for make choice from dictionary'''
d = {};
c = 1
exitNumber = 0
for k in sorted(dict.keys()):
s = dict[k]
if k.lower()=='<up>' or k.lower()=='<exit>':
exitNumber = c
print "%s - %s" % ('Q',pyren_encode(s))
d['Q']=k
else:
if showId:
print "%s - (%s) %s" % (c,pyren_encode(k),pyren_encode(s))
else:
print "%s - %s" % (c,pyren_encode(s))
d[str(c)]=k
c = c+1
while (True):
try:
ch = raw_input(question)
except (KeyboardInterrupt, SystemExit):
print
print
sys.exit()
if ch=='q': ch = 'Q'
if ch in d.keys():
return [d[ch],ch]
def pyren_encode( inp ):
if mod_globals.os == 'android':
return inp.encode('utf-8', errors='replace')
else:
return inp.encode(sys.stdout.encoding, errors='replace')
def pyren_decode( inp ):
if mod_globals.os == 'android':
return inp.decode('utf-8', errors='replace')
else:
return inp.decode(sys.stdout.encoding, errors='replace')
def pyren_decode_i( inp ):
if mod_globals.os == 'android':
return inp.decode('utf-8', errors='ignore')
else:
return inp.decode(sys.stdout.encoding, errors='ignore')
def clearScreen():
# https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
# [2J - clear entire screen
# [x;yH - move cursor to x:y
sys.stdout.write(chr(27)+"[2J"+chr(27)+"[;H")
def upScreen():
sys.stdout.write(chr(27)+"[;H")
def hex_VIN_plus_CRC( VIN, plusCRC=True):
'''The VIN must be composed of 17 alphanumeric characters apart from "I" and "O"'''
#VIN ='VF1LM1B0H11111111'
VIN = VIN.upper()
hexVIN = ''
CRC = 0xFFFF
for c in VIN: # for every byte in VIN
b = ord(c) # get ASCII
hexVIN = hexVIN + hex(b)[2:].upper()
for i in range( 8 ): # for every bit
if ((CRC ^ b) & 0x1):
CRC = CRC >> 1
CRC = CRC ^ 0x8408
b = b >> 1
else:
CRC = CRC >> 1
b = b >> 1
# invert
CRC = CRC ^ 0xFFFF
# swap bytes
b1 = (CRC >> 8) & 0xFF
b2 = CRC & 0xFF
CRC = ((b2 << 8) | b1) & 0xFFFF
sCRC = hex( CRC )[2:].upper()
sCRC = '0'*(4-len(sCRC))+sCRC
# result
if plusCRC:
return hexVIN+sCRC
else:
return hexVIN
# Test
if __name__ == "__main__":
kb = KBHit()
print('Hit any key, or ESC to exit')
while True:
if kb.kbhit():
c = kb.getch()
if ord(c) == 27: # ESC
break
print(c)
kb.set_normal_term()
# Convert ASCII to HEX
def ASCIITOHEX( ATH ):
ATH = ATH.upper()
hexATH = ''.join("{:02X}".format(ord(c)) for c in ATH)
#Result
return hexATH
# Convert ch str to int then to Hexadecimal digits
def StringToIntToHex(DEC):
DEC = int(DEC)
hDEC = hex(DEC)
#Result
return hDEC[2:].zfill(2).upper()
def loadDumpToELM( ecuname, elm ):
ecudump = {}
dumpname = ''
flist = []
for root, dirs, files in os.walk(mod_globals.dumps_dir):
for f in files:
if (ecuname+'.txt') in f:
flist.append(f)
if len(flist)==0: return
flist.sort()
dumpname = os.path.join(mod_globals.dumps_dir, flist[-1])
#debug
print "Loading:", dumpname
df = open(dumpname,'rt')
lines = df.readlines()
df.close()
for l in lines:
l = l.strip().replace('\n','')
if ':' in l:
req,rsp = l.split(':')
ecudump[req] = rsp
elm.setDump( ecudump )
def chkDirTree():
'''Check direcories'''
if not os.path.exists(mod_globals.cache_dir):
os.makedirs(mod_globals.cache_dir)
if not os.path.exists(mod_globals.log_dir):
os.makedirs(mod_globals.log_dir)
if not os.path.exists(mod_globals.dumps_dir):
os.makedirs(mod_globals.dumps_dir)
def getVIN( de, elm, getFirst = False ):
''' getting VINs from every ECU '''
''' de - list of detected ECUs '''
''' elm - reference to ELM class '''
m_vin = set([])
for e in de:
# init elm
if mod_globals.opt_demo: #try to load dump
loadDumpToELM( e['ecuname'], elm )
else:
if e['pin'].lower()=='can':
elm.init_can()
elm.set_can_addr( e['dst'], e )
else:
elm.init_iso()
elm.set_iso_addr( e['dst'], e )
elm.start_session( e['startDiagReq'] )
# read VIN
if e['stdType'].lower()=='uds':
rsp = elm.request( req = '22F190', positive = '62', cache = False )[9:59]
else:
rsp = elm.request( req = '2181', positive = '61', cache = False )[6:56]
try:
vin = rsp.replace(' ','').decode('HEX')
except:
continue
#debug
#print e['dst'],' : ', vin
if len(vin)==17:
m_vin.add(vin)
if getFirst:
return vin
l_vin = m_vin
if os.path.exists('savedVIN.txt'):
with open('savedVIN.txt') as vinfile:
vinlines = vinfile.readlines()
for l in vinlines:
l = l.strip()
if '#' in l: continue
if len(l)==17:
l_vin.add(l.upper())
if len(l_vin)==0 and not getFirst:
print "ERROR!!! Can't find any VIN. Check connection"
exit()
if len(l_vin)<2:
try:
ret = next(iter(l_vin))
except:
ret = ''
return ret
print "\nFound ",len(l_vin), " VINs\n"
choice = Choice(l_vin, "Choose VIN : ")
return choice[0]
def DBG( tag, s ):
if mod_globals.opt_debug and mod_globals.debug_file!=None:
mod_globals.debug_file.write( '### ' + tag + '\n')
mod_globals.debug_file.write( '"' + s + '"\n')
def isHex(s):
return all(c in string.hexdigits for c in s)
def kill_server():
if mod_globals.doc_server_proc is None:
pass
else:
os.kill(mod_globals.doc_server_proc.pid, signal.SIGTERM)
def show_doc( addr, id ):
if mod_globals.vin == '':
return
if mod_globals.doc_server_proc == None:
mod_globals.doc_server_proc = subprocess.Popen(["python", "-m", "SimpleHTTPServer", "59152"])
atexit.register(kill_server)
if mod_globals.opt_sd:
url = 'http://localhost:59152/doc/' + id[1:] + '.htm'
else:
url = 'http://localhost:59152/doc/'+mod_globals.vin+'.htm'+id
webbrowser.open(url, new=0)