-
Notifications
You must be signed in to change notification settings - Fork 1
/
pyobd.py
761 lines (624 loc) · 28.9 KB
/
pyobd.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
#!/usr/bin/env python
############################################################################
#
# wxgui.py
#
# Copyright 2004 Donour Sizemore ([email protected])
# Copyright 2009 Secons Ltd. (www.obdtester.com)
#
# This file is part of pyOBD.
#
# pyOBD is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# pyOBD 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.
#
# You should have received a copy of the GNU General Public License
# along with pyOBD; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
############################################################################
#import wxversion
#wxversion.select("2.6")
import wx
import obd_io #OBD2 funcs
import os #os.environ
import threading
import sys
import serial
import platform
import time
import ConfigParser #safe application configuration
import webbrowser #open browser from python
import glob #
from obd2_codes import pcodes
from obd2_codes import ptest
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
ID_ABOUT = 101
ID_EXIT = 110
ID_CONFIG = 500
ID_CLEAR = 501
ID_GETC = 502
ID_RESET = 503
ID_LOOK = 504
ALL_ON = 505
ALL_OFF = 506
ID_DISCONNECT = 507
ID_HELP_ABOUT = 508
ID_HELP_VISIT = 509
ID_HELP_ORDER = 510
# Define notification event for sensor result window
EVT_RESULT_ID = 1000
def EVT_RESULT(win, func,id):
"""Define Result Event."""
win.Connect(-1, -1, id, func)
#event pro akutalizaci Trace tabu
class ResultEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data
#event pro aktualizaci DTC tabu
EVT_DTC_ID = 1001
class DTCEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_DTC_ID)
self.data = data
#event pro aktualizaci status tabu
EVT_STATUS_ID = 1002
class StatusEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_STATUS_ID)
self.data = data
#event pro aktualizaci tests tabu
EVT_TESTS_ID = 1003
class TestEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_TESTS_ID)
self.data = data
#defines notification event for debug tracewindow
from debugEvent import *
class MyApp(wx.App):
# A listctrl which auto-resizes the column boxes to fill
class MyListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
def __init__(self, parent, id, pos = wx.DefaultPosition,
size = wx.DefaultSize, style = 0):
wx.ListCtrl.__init__(self,parent,id,pos,size,style)
ListCtrlAutoWidthMixin.__init__(self)
class sensorProducer(threading.Thread):
def __init__(self, _notify_window,portName,BAUD,SERTIMEOUT,RECONNATTEMPTS,_nb):
from Queue import Queue
self.portName = portName
self.BAUD=BAUD
self.RECONNATTEMPTS=RECONNATTEMPTS
self.SERTIMEOUT=SERTIMEOUT
self.port = None
self._notify_window=_notify_window
self._nb=_nb
threading.Thread.__init__ ( self )
def initCommunication(self):
self.port = obd_io.OBDPort(self.portName,self._notify_window,self.BAUD,self.SERTIMEOUT,self.RECONNATTEMPTS)
if self.port.State==0: #Cant open serial port
return None
self.active = []
self.supp = self.port.sensor(0)[1] #read supported PIDS
self.active.append(1); #PID 0 is always supported
wx.PostEvent(self._notify_window, ResultEvent([0,0,"X"]))
wx.PostEvent(self._notify_window, DebugEvent([1,"Communication initialized..."]))
for i in range(1, len(self.supp)):
if self.supp[i-1] == "1": #put X in coloum if PID is supported
self.active.append(1)
wx.PostEvent(self._notify_window, ResultEvent([i,0,"X"]))
else:
self.active.append(0)
wx.PostEvent(self._notify_window, ResultEvent([i,0,""]))
return "OK"
def run(self):
wx.PostEvent(self._notify_window, StatusEvent([0,1,"Connecting...."]))
self.initCommunication()
if self.port.State==0: #cant connect, exit thread
self.stop()
wx.PostEvent(self._notify_window, StatusEvent([666])) #signal apl, that communication was disconnected
wx.PostEvent(self._notify_window, StatusEvent([0,1,"Error cant connect..."]))
return None
wx.PostEvent(self._notify_window, StatusEvent([0,1,"Connected"]))
wx.PostEvent(self._notify_window, StatusEvent([2,1,self.port.ELMver]))
prevstate=-1
curstate=-1
while self._notify_window.ThreadControl!=666:
prevstate=curstate
curstate=self._nb.GetSelection()
if curstate==0: #show status tab
pass
elif curstate==1: #show tests tab
res=self.port.get_tests_MIL()
for i in range(0,len(res)):
wx.PostEvent(self._notify_window, TestEvent([i,1,res[i]]))
elif curstate==2: #show sensor tab
for i in range(3, len(self.active)):
if self.active[i]:
s = self.port.sensor(i)
wx.PostEvent(self._notify_window, ResultEvent([i,2,"%s (%s)" % (s[1], s[2])]))
if self._notify_window.ThreadControl==666:
break
elif curstate==3: #show DTC tab
if self._notify_window.ThreadControl == 1: #clear DTC
self.port.clear_dtc()
if self._notify_window.ThreadControl==666: #before reset ThreadControl we must check if main thread did not want us to finish
break
self._notify_window.ThreadControl=0
prevstate=-1 # to reread DTC
if self._notify_window.ThreadControl == 2: #reread DTC
prevstate=-1
if self._notify_window.ThreadControl==666:
break
self._notify_window.ThreadControl=0
if prevstate!=3:
wx.PostEvent(self._notify_window, DTCEvent(0)) #clear list
DTCCodes=self.port.get_dtc()
if len(DTCCodes)==0:
wx.PostEvent(self._notify_window, DTCEvent(["","","No DTC codes (codes cleared)"]))
for i in range (0,len(DTCCodes)):
wx.PostEvent(self._notify_window, DTCEvent([DTCCodes[i][1],DTCCodes[i][0],pcodes[DTCCodes[i][1]]]))
else:
pass
self.stop()
def off(self, id):
if id >= 0 and id < len(self.active):
self.active[id] = 0
else:
debug("Invalid sensor id")
def on(self, id):
if id >= 0 and id < len(self.active):
self.active[id] = 1
else:
debug("Invalid sensor id")
def all_off(self):
for i in range(0, len(self.active)):
self.off(i)
def all_on(self):
for i in range(0, len(self.active)):
self.off(i)
def stop(self):
if self.port != None: #if stop is called before any connection port is not defined (and not connected )
self.port.close()
wx.PostEvent(self._notify_window, StatusEvent([0,1,"Disconnected"]))
wx.PostEvent(self._notify_window, StatusEvent([2,1,"----"]))
#class producer end
def sensor_control_on(self): #after connection enable few buttons
self.settingmenu.Enable(ID_CONFIG,False)
self.settingmenu.Enable(ID_RESET,False)
self.settingmenu.Enable(ID_DISCONNECT,True)
self.dtcmenu.Enable(ID_GETC,True)
self.dtcmenu.Enable(ID_CLEAR,True)
self.GetDTCButton.Enable(True)
self.ClearDTCButton.Enable(True)
def sensor_toggle(e):
sel = e.m_itemIndex
state = self.senprod.active[sel]
print sel, state
if state == 0:
self.senprod.on(sel)
self.sensors.SetItem(sel,1,"1")
elif state == 1:
self.senprod.off(sel)
self.sensors.SetItem(sel,1,"0")
else:
debug("Incorrect sensor state")
self.sensors.Bind(wx.EVT_LIST_ITEM_ACTIVATED,sensor_toggle,id=self.sensor_id)
def sensor_control_off(self): #after disconnect disable fer buttons
self.dtcmenu.Enable(ID_GETC,False)
self.dtcmenu.Enable(ID_CLEAR,False)
self.settingmenu.Enable(ID_DISCONNECT,False)
self.settingmenu.Enable(ID_CONFIG,True)
self.settingmenu.Enable(ID_RESET,True)
self.GetDTCButton.Enable(False)
self.ClearDTCButton.Enable(False)
#http://pyserial.sourceforge.net/ empty function
#EVT_LIST_ITEM_ACTIVATED(self.sensors,self.sensor_id, lambda : None)
def build_sensor_page(self):
HOFFSET_LIST=0
tID = wx.NewId()
self.sensor_id = tID
panel = wx.Panel(self.nb, -1)
self.sensors = self.MyListCtrl(panel, tID, pos=wx.Point(0,HOFFSET_LIST),
style=
wx.LC_REPORT |
wx.SUNKEN_BORDER |
wx.LC_HRULES |
wx.LC_SINGLE_SEL)
self.sensors.InsertColumn(0, "Supported",width=70)
self.sensors.InsertColumn(1, "Sensor",format=wx.LIST_FORMAT_RIGHT, width=250)
self.sensors.InsertColumn(2, "Value")
for i in range(0, len(obd_io.obd_sensors.SENSORS)):
s = obd_io.obd_sensors.SENSORS[i].name
self.sensors.InsertItem(i, "")
self.sensors.SetItem(i, 1, s)
####################################################################
# This little bit of magic keeps the list the same size as the frame
def OnPSize(e, win = panel):
panel.SetSize(e.GetSize())
self.sensors.SetSize(e.GetSize())
w,h = self.frame.GetClientSize()
self.sensors.SetSize(0,HOFFSET_LIST, w-10 , h - 35 )
panel.Bind(wx.EVT_SIZE,OnPSize)
####################################################################
self.nb.AddPage(panel, "Sensors")
def build_DTC_page(self):
HOFFSET_LIST=30 #offset from the top of panel (space for buttons)
tID = wx.NewId()
self.DTCpanel = wx.Panel(self.nb, -1)
self.GetDTCButton = wx.Button(self.DTCpanel,-1 ,"Get DTC" , wx.Point(15,0))
self.ClearDTCButton = wx.Button(self.DTCpanel,-1,"Clear DTC", wx.Point(100,0))
#bind functions to button click action
self.DTCpanel.Bind(wx.EVT_BUTTON,self.GetDTC,self.GetDTCButton)
self.DTCpanel.Bind(wx.EVT_BUTTON,self.QueryClear,self.ClearDTCButton)
self.dtc = self.MyListCtrl(self.DTCpanel,tID, pos=wx.Point(0,HOFFSET_LIST),
style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_HRULES|wx.LC_SINGLE_SEL)
self.dtc.InsertColumn(0, "Code", width=100)
self.dtc.InsertColumn(1, "Status",width=100)
self.dtc.InsertColumn(2, "Trouble code")
####################################################################
# This little bit of magic keeps the list the same size as the frame
def OnPSize(e, win = self.DTCpanel):
self.DTCpanel.SetSize(e.GetSize())
self.dtc.SetSize(e.GetSize())
w,h = self.frame.GetClientSize()
# I have no idea where 70 comes from
self.dtc.SetSize(0,HOFFSET_LIST, w-16 , h - 70 )
self.DTCpanel.Bind(wx.EVT_SIZE,OnPSize)
####################################################################
self.nb.AddPage(self.DTCpanel, "DTC")
def TraceDebug(self,level,msg):
if self.DEBUGLEVEL<=level:
self.trace.Append([str(level),msg])
def OnInit(self):
self.ThreadControl = 0 #say thread what to do
self.COMPORT = 0
self.senprod = None
self.DEBUGLEVEL = 0 #debug everthing
tID = wx.NewId()
#read settings from file
self.config = ConfigParser.RawConfigParser()
#print platform.system()
#print platform.mac_ver()[]
if "OS" in os.environ.keys(): #runnig under windows
self.configfilepath="pyobd.ini"
else:
self.configfilepath=os.environ['HOME']+'/.pyobdrc'
if self.config.read(self.configfilepath)==[]:
self.COMPORT="/dev/cu.OBDII-SPP"
self.BAUD=9600
self.RECONNATTEMPTS=5
self.SERTIMEOUT=2
else:
self.COMPORT=self.config.get("pyOBD","COMPORT")
try:
self.BAUD=self.config.getint("pyOBD","BAUD")
except:
self.BAUD = 9600
self.RECONNATTEMPTS=self.config.getint("pyOBD","RECONNATTEMPTS")
self.SERTIMEOUT=self.config.getint("pyOBD","SERTIMEOUT")
frame = wx.Frame(None, -1, "pyOBD-II")
self.frame=frame
EVT_RESULT(self,self.OnResult,EVT_RESULT_ID)
EVT_RESULT(self,self.OnDebug, EVT_DEBUG_ID)
EVT_RESULT(self,self.OnDtc,EVT_DTC_ID)
EVT_RESULT(self,self.OnStatus,EVT_STATUS_ID)
EVT_RESULT(self,self.OnTests,EVT_TESTS_ID)
# Main notebook frames
self.nb = wx.Notebook(frame, -1, style = wx.NB_TOP)
self.status = self.MyListCtrl(self.nb, tID,style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.status.InsertColumn(0, "Description",width=200)
self.status.InsertColumn(1, "Value")
self.status.Append(["Link State","Disconnnected"]);
self.status.Append(["Protocol","---"]);
self.status.Append(["Cable version","---"]);
self.status.Append(["COM port",self.COMPORT]);
self.nb.AddPage(self.status, "Status")
self.OBDTests = self.MyListCtrl(self.nb, tID,style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.OBDTests.InsertColumn(0, "Description",width=200)
self.OBDTests.InsertColumn(1, "Value")
self.nb.AddPage(self.OBDTests, "Tests")
for i in range(0,len(ptest)): #fill MODE 1 PID 1 test description
self.OBDTests.Append([ptest[i],"---"]);
self.build_sensor_page()
self.build_DTC_page()
self.trace = self.MyListCtrl(self.nb, tID,style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.trace.InsertColumn(0, "Level",width=40)
self.trace.InsertColumn(1, "Message")
self.nb.AddPage(self.trace, "Trace")
self.TraceDebug(1,"Application started")
# Setting up the menu.
self.filemenu= wx.Menu()
self.filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
self.settingmenu = wx.Menu()
self.settingmenu.Append(ID_CONFIG,"Configure"," Configure pyOBD")
self.settingmenu.Append(ID_RESET,"Connect"," Reopen and connect to device")
self.settingmenu.Append(ID_DISCONNECT,"Disconnect","Close connection to device")
self.dtcmenu= wx.Menu()
# tady toto nastavi automaticky tab DTC a provede akci
self.dtcmenu.Append(ID_GETC ,"Get DTCs", " Get DTC Codes")
self.dtcmenu.Append(ID_CLEAR ,"Clear DTC", " Clear DTC Codes")
self.dtcmenu.Append(ID_LOOK ,"Code Lookup"," Lookup DTC Codes")
self.helpmenu = wx.Menu()
self.helpmenu.Append(ID_HELP_ABOUT ,"About this program", " Get DTC Codes")
self.helpmenu.Append(ID_HELP_VISIT ,"Visit program homepage"," Lookup DTC Codes")
self.helpmenu.Append(ID_HELP_ORDER ,"Order OBD-II interface", " Clear DTC Codes")
# Creating the menubar.
self.menuBar = wx.MenuBar()
self.menuBar.Append(self.filemenu,"&File") # Adding the "filemenu" to the MenuBar
self.menuBar.Append(self.settingmenu,"&OBD-II")
self.menuBar.Append(self.dtcmenu,"&Trouble codes")
self.menuBar.Append(self.helpmenu,"&Help")
frame.SetMenuBar(self.menuBar) # Adding the MenuBar to the Frame content.
frame.Bind(wx.EVT_MENU,self.OnExit,id=ID_EXIT)# attach the menu-event ID_EXIT to the
frame.Bind(wx.EVT_MENU,self.QueryClear,id=ID_CLEAR)
frame.Bind(wx.EVT_MENU,self.Configure,id=ID_CONFIG)
frame.Bind(wx.EVT_MENU,self.OpenPort,id=ID_RESET)
frame.Bind(wx.EVT_MENU,self.OnDisconnect,id=ID_DISCONNECT)
frame.Bind(wx.EVT_MENU,self.GetDTC,id=ID_GETC)
frame.Bind(wx.EVT_MENU,self.CodeLookup,id=ID_LOOK)
frame.Bind(wx.EVT_MENU,self.OnHelpAbout,id=ID_HELP_ABOUT)
frame.Bind(wx.EVT_MENU,self.OnHelpVisit,id=ID_HELP_VISIT)
frame.Bind(wx.EVT_MENU,self.OnHelpOrder,id=ID_HELP_ORDER)
self.SetTopWindow(frame)
frame.Show(True)
frame.SetSize((520,400))
self.sensor_control_off()
return True
def OnHelpVisit(self,event):
webbrowser.open("http://www.obdtester.com/pyobd")
def OnHelpOrder(self,event):
webbrowser.open("http://www.obdtester.com/order")
def OnHelpAbout(self,event): #todo about box
Text = """ PyOBD is an automotive OBD2 diagnosting application using ELM237 cable.
(C) 2008-2009 SeCons Ltd.
(C) 2004 Charles Donour Sizemore
http://www.obdtester.com/
http://www.secons.com/
PyOBD is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.
PyOBD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MEHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details. You should have received a copy of
the GNU General Public License along with PyOBD; if not, write to
the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
#HelpAboutDlg = wx.Dialog(self.frame, id, title="About")
#box = wx.BoxSizer(wx.HORIZONTAL)
#box.Add(wx.StaticText(reconnectPanel,-1,Text,pos=(0,0),size=(200,200)))
#box.Add(wx.Button(HelpAboutDlg,wx.ID_OK),0)
#box.Add(wx.Button(HelpAboutDlg,wx.ID_CANCEL),1)
#HelpAboutDlg.SetSizer(box)
#HelpAboutDlg.SetAutoLayout(True)
#sizer.Fit(HelpAboutDlg)
#HelpAboutDlg.ShowModal()
self.HelpAboutDlg = wx.MessageDialog(self.frame, Text, 'About',wx.OK | wx.ICON_INFORMATION)
self.HelpAboutDlg.ShowModal()
self.HelpAboutDlg.Destroy()
def OnResult(self,event):
self.sensors.SetItem(event.data[0], event.data[1], event.data[2])
def OnStatus(self,event):
if event.data[0] == 666: #signal, that connection falied
self.sensor_control_off()
else:
self.status.SetItem(event.data[0], event.data[1], event.data[2])
def OnTests(self,event):
self.OBDTests.SetItem(event.data[0], event.data[1], event.data[2])
def OnDebug(self,event):
self.TraceDebug(event.data[0],event.data[1])
def OnDtc(self,event):
if event.data == 0: #signal, that DTC was cleared
self.dtc.DeleteAllItems()
else:
self.dtc.Append(event.data)
def OnDisconnect(self,event): #disconnect connection to ECU
self.ThreadControl=666
self.sensor_control_off()
def OpenPort(self,e):
if self.senprod: # signal current producers to finish
self.senprod.stop()
self.ThreadControl = 0
self.senprod = self.sensorProducer(self,self.COMPORT,self.BAUD,self.SERTIMEOUT,self.RECONNATTEMPTS,self.nb)
self.senprod.start()
self.sensor_control_on()
def GetDTC(self,e):
self.nb.SetSelection(3)
self.ThreadControl=2
def AddDTC(self, code):
self.dtc.InsertItem(0, "")
self.dtc.SetItem(0, 0, code[0])
self.dtc.SetItem(0, 1, code[1])
def CodeLookup(self,e = None):
id = 0
diag = wx.Frame(None, id, title="Diagnostic Trouble Codes")
tree = wx.TreeCtrl(diag, id, style = wx.TR_HAS_BUTTONS)
root = tree.AddRoot("Code Reference")
proot = root; # tree.AppendItem(root,"Powertrain (P) Codes")
codes = pcodes.keys()
codes.sort()
group = ""
for c in codes:
if c[:3] != group:
group_root = tree.AppendItem(proot, c[:3]+"XX")
group = c[:3]
leaf = tree.AppendItem(group_root, c)
tree.AppendItem(leaf, pcodes[c])
diag.SetSize((400,500))
diag.Show(True)
def QueryClear(self,e):
id = 0
diag = wx.Dialog(self.frame, id, title="Clear DTC?")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(wx.StaticText(diag, -1, "Are you sure you wish to"),0)
sizer.Add(wx.StaticText(diag, -1, "clear all DTC codes and "),0)
sizer.Add(wx.StaticText(diag, -1, "freeze frame data? "),0)
box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(wx.Button(diag,wx.ID_OK, "Ok" ),0)
box.Add(wx.Button(diag,wx.ID_CANCEL, "Cancel"),0)
sizer.Add(box, 0)
diag.SetSizer(sizer)
diag.SetAutoLayout(True)
sizer.Fit(diag)
r = diag.ShowModal()
if r == wx.ID_OK:
self.ClearDTC()
def ClearDTC(self):
self.ThreadControl=1
self.nb.SetSelection(3)
def scanSerialOld(self):
"""scan for available ports. return a list of serial names"""
available = []
for i in range(256):
try: #scan standart ttyS*
print i
s = serial.Serial(i)
available.append(s.portstr)
s.close() # explicit close 'cause of delayed GC in java
except (OSError, serial.SerialException): # OSError for macOS
pass
for i in range(256):
try: #scan USB ttyACM
s = serial.Serial("/dev/ttyACM"+str(i))
available.append(s.portstr)
s.close() # explicit close 'cause of delayed GC in java
except serial.SerialException:
pass
for i in range(256):
try:
s = serial.Serial("/dev/ttyUSB"+str(i))
available.append(s.portstr)
s.close() # explicit close 'cause of delayed GC in java
except serial.SerialException:
pass
for i in range(256):
try:
s = serial.Serial("/dev/ttyd"+str(i))
available.append(s.portstr)
s.close() # explicit close 'cause of delayed GC in java
except serial.SerialException:
pass
# ELM-USB shows up as /dev/tty.usbmodemXXXX, where XXXX is a changing hex string
# on connection; so we have to search through all 64K options
if len(platform.mac_ver()[0])!=0: #search only on MAC
for i in range (65535):
extension = hex(i).replace("0x","", 1)
try:
s = serial.Serial("/dev/tty.usbmodem"+extension)
available.append(s.portstr)
s.close()
except serial.SerialException:
pass
return available
def scanSerial(self):
""" Lists serial port names - http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
ports = []
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports.extend(glob.glob('/dev/tty.*'))
#ports.extend(glob.glob('/dev/cu.*'))
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
#s = serial.Serial(port)
#s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
def Configure(self,e = None):
id = 0
diag = wx.Dialog(self.frame, id, title="Configure")
sizer = wx.BoxSizer(wx.VERTICAL)
#serial port
portPanel = wx.Panel(diag, -1)
ports = self.scanSerial()
portCtrl = wx.ComboBox(portPanel, id, "Choose Serial Port", pos=(143,0), size=(70, 25),
choices = ports, style = wx.CB_READONLY)
portStatic = wx.StaticText(portPanel,-1,'Serial port:',pos=(3,5),size=(140,20))
#baud rate input control
baudPanel = wx.Panel(diag, -1)
baudCtrl = wx.TextCtrl(baudPanel, -1, '',pos=(143,0), size=(55, 25))
baudStatic = wx.StaticText(baudPanel,-1,'Baud rate:',pos=(3,5),size=(140,20))
baudCtrl.SetValue(str(self.BAUD))
#timeOut input control
timeoutPanel = wx.Panel(diag, -1)
timeoutCtrl = wx.TextCtrl(timeoutPanel, -1, '',pos=(143,0), size=(35, 25))
timeoutStatic = wx.StaticText(timeoutPanel,-1,'Timeout:',pos=(3,5),size=(140,20))
timeoutCtrl.SetValue(str(self.SERTIMEOUT))
#reconnect attempt input control
reconnectPanel = wx.Panel(diag, -1)
reconnectCtrl = wx.TextCtrl(reconnectPanel, -1, '',pos=(143,0), size=(35, 25))
reconnectStatic = wx.StaticText(reconnectPanel,-1,'Reconnect attempts:',pos=(3,5),size=(140,20))
reconnectCtrl.SetValue(str(self.RECONNATTEMPTS))
#web open link button
self.OpenLinkButton = wx.Button(diag,-1,"Click here to order ELM-USB interface",size=(260,30))
diag.Bind(wx.EVT_BUTTON,self.OnHelpOrder,self.OpenLinkButton)
#set actual serial port choice
if (self.COMPORT != 0) and (self.COMPORT in ports):
portCtrl.SetSelection(ports.index(self.COMPORT))
sizer.Add(self.OpenLinkButton)
sizer.Add(portPanel,0)
sizer.Add(baudPanel,0)
sizer.Add(timeoutPanel,0)
sizer.Add(reconnectPanel,0)
box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(wx.Button(diag,wx.ID_OK),0)
box.Add(wx.Button(diag,wx.ID_CANCEL),1)
sizer.Add(box, 0)
diag.SetSizer(sizer)
diag.SetAutoLayout(True)
sizer.Fit(diag)
r = diag.ShowModal()
if r == wx.ID_OK:
#create section
if self.config.sections()==[]:
self.config.add_section("pyOBD")
#set and save COMPORT
self.COMPORT = ports[portCtrl.GetSelection()]
self.config.set("pyOBD","COMPORT",self.COMPORT)
#set and save BAUD
self.BAUD = int(baudCtrl.GetValue())
self.config.set("pyOBD","BAUD",self.BAUD)
#set and save SERTIMEOUT
self.SERTIMEOUT = int(timeoutCtrl.GetValue())
self.config.set("pyOBD","SERTIMEOUT",self.SERTIMEOUT)
self.status.SetItem(3,1,self.COMPORT);
#set and save RECONNATTEMPTS
self.RECONNATTEMPTS = int(reconnectCtrl.GetValue())
self.config.set("pyOBD","RECONNATTEMPTS",self.RECONNATTEMPTS)
#write configuration to cfg file
self.config.write(open(self.configfilepath, 'wb'))
def OnExit(self,e = None):
import sys
sys.exit(0)
app = MyApp(0)
app.MainLoop()