forked from Barracuda09/PyPSADiag
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
892 lines (754 loc) · 36.6 KB
/
main.py
File metadata and controls
892 lines (754 loc) · 36.6 KB
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
"""
main.py
Copyright (C) 2024 - 2025 Marc Postema (mpostema09 -at- gmail.com)
This program 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.
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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Or, point your browser to http://www.gnu.org/copyleft/gpl.html
"""
import sys
import random
import json
import csv
import time
import os
from datetime import datetime
from PySide6.QtCore import Qt, Slot, QIODevice, QTranslator, QEventLoop
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox, QDialog, QVBoxLayout, QLabel, QPushButton, QHBoxLayout
from PySide6.QtCore import QTimer
from PyPSADiagGUI import PyPSADiagGUI
import FileLoader
from ParseDTC import ParseDTC
from DiagnosticCommunication import DiagnosticCommunication
from SeedKeyAlgorithm import SeedKeyAlgorithm
from SerialPort import SerialPort
from FileConverter import FileConverter
from EcuZoneTreeView import EcuZoneTreeView
from MessageDialog import MessageDialog
from i18n import i18n
from DecodeCalUlpFile import DecodeCalUlpFile
from DiagnosticAdapter import DiagnosticAdapter
"""
- Change GUI in: PyPSADiagGUI.py
- Run with: python main.py
"""
class VisioparkCalibrationDialog(QDialog):
"""Dialog for Visiopark dynamic camera calibration with status polling."""
STATUS_MESSAGES = {
"0101": "Waiting for white lines to be visible...",
"0102": "Get out of parking spot (max 5km/h)...",
"0103": "Get back in parking spot (max 5km/h)...",
}
def __init__(self, udsCommunication, writeToOutputView, parent=None):
super().__init__(parent)
self.udsCommunication = udsCommunication
self.writeToOutputView = writeToOutputView
self.setWindowTitle("Visiopark Calibration")
self.setMinimumWidth(400)
self.setModal(True)
# Layout
layout = QVBoxLayout(self)
self.statusLabel = QLabel("Calibration started. Polling ECU...")
self.statusLabel.setWordWrap(True)
self.statusLabel.setStyleSheet("font-size: 14px; padding: 10px;")
layout.addWidget(self.statusLabel)
self.stepLabel = QLabel("")
self.stepLabel.setStyleSheet("font-size: 11px; color: gray; padding: 0 10px;")
layout.addWidget(self.stepLabel)
# Buttons
btnLayout = QHBoxLayout()
btnLayout.addStretch()
self.cancelBtn = QPushButton("Cancel")
self.cancelBtn.clicked.connect(self.onCancel)
btnLayout.addWidget(self.cancelBtn)
layout.addLayout(btnLayout)
# Polling timer — every 1 second
self.pollTimer = QTimer(self)
self.pollTimer.timeout.connect(self.pollStatus)
self.pollTimer.start(1000)
def pollStatus(self):
"""Send 3103DF0C and interpret response."""
receiveData = self.udsCommunication.writeECUCommand("3103DF0C")
if receiveData == "Timeout" or len(receiveData) < 12:
self.stepLabel.setText("Response: " + receiveData)
return
# Expected: 7103DF0C + status (2 bytes = 4 hex chars)
if receiveData[:8] != "7103DF0C":
self.stepLabel.setText("Unexpected: " + receiveData)
return
status = receiveData[8:12]
statusByte1 = receiveData[8:10]
statusCode = receiveData[8:12]
self.stepLabel.setText("Status: " + receiveData)
# Check known status codes
if statusCode in self.STATUS_MESSAGES:
self.statusLabel.setText(self.STATUS_MESSAGES[statusCode])
self.writeToOutputView("[Visiopark] " + self.STATUS_MESSAGES[statusCode])
elif statusByte1 == "02":
# Procedure completed (7103DF0C02XX)
self.pollTimer.stop()
msg = "Visiopark calibration completed successfully!"
self.statusLabel.setText(msg)
self.statusLabel.setStyleSheet("font-size: 14px; padding: 10px; color: green;")
self.writeToOutputView("[Visiopark] " + msg)
self.cancelBtn.setText("Close")
elif statusByte1 == "03":
# Procedure failed (7103DF0C03XX)
self.pollTimer.stop()
msg = "Visiopark calibration failed."
self.statusLabel.setText(msg)
self.statusLabel.setStyleSheet("font-size: 14px; padding: 10px; color: red;")
self.writeToOutputView("[Visiopark] " + msg)
self.cancelBtn.setText("Close")
def onCancel(self):
self.pollTimer.stop()
if self.cancelBtn.text() == "Cancel":
self.writeToOutputView("[Visiopark] Calibration cancelled by user.")
self.accept()
class MainWindow(QMainWindow):
ui = PyPSADiagGUI()
ecuObjectList = {}
diagtool_type = "serial"
simulation = False
scan = False
flashEnable = False
stream = None
csvWriter = None
app: QApplication
def __init__(self, app: QApplication):
super(MainWindow, self).__init__()
self.app = app
self.lang_code = "en"
self.lang = False
if len(sys.argv) >= 2:
for arg in sys.argv:
if arg == "--lang":
self.lang = True
elif self.lang:
self.lang = False
self.lang_code = str(arg)
elif arg == "--simu":
self.simulation = True
elif arg == "--scan":
self.scan = True
elif arg == "--flash":
self.flashEnable = True
elif arg == "--checkcalc":
calc = SeedKeyAlgorithm()
calc.testCalculations()
sys.exit(1)
elif arg == "--help":
print("Use --simu For simulation")
print("Use --lang nl For NL translation")
print("Use --flash Enable flash option (Work In Progress: use at your own risk!!)")
sys.exit(1)
self.addTranslators()
self.ui.setupGUI(app, self, self.scan, self.lang_code)
# Disable Sync Zone files with github (Still Work In Progress)
self.ui.syncZoneFiles.setVisible(False)
# Disable flash when not explicit enabled at startup (Still Work In Progress use at your own risk)
if self.flashEnable == False:
self.ui.flashEcu.setVisible(False)
# Connect button signals to slots
self.ui.sendCommand.clicked.connect(self.sendCommand)
self.ui.openCSVFile.clicked.connect(self.openCSVFile)
self.ui.saveCSVFile.clicked.connect(self.saveCSVFile)
self.ui.openZoneFile.clicked.connect(self.openZoneFile)
self.ui.readZone.clicked.connect(self.readZone)
self.ui.writeZone.clicked.connect(self.writeZone)
self.ui.flashEcu.clicked.connect(self.flashEcu)
self.ui.rebootEcu.clicked.connect(self.rebootEcu)
self.ui.readEcuFaults.clicked.connect(self.readEcuFaults)
self.ui.clearEcuFaults.clicked.connect(self.clearEcuFaults)
self.ui.SearchConnectPort.clicked.connect(self.searchConnectPort)
self.ui.ConnectPort.clicked.connect(self.connectPort)
self.ui.DisconnectPort.clicked.connect(self.disconnectPort)
self.ui.disableEcoMode.clicked.connect(self.disableEcoMode)
self.ui.disableEcoModeAction.triggered.connect(self.disableEcoMode)
self.ui.visioparkCalibrationAction.triggered.connect(self.visioparkCalibration)
self.ui.hideNoResponseZone.stateChanged.connect(self.hideNoResponseZones)
# Connect Other/General signals to slots
self.ui.command.returnPressed.connect(self.sendCommand)
self.ui.searchZoneLineEdit.textChanged.connect(self.searchZones)
self.ui.diagtoolTypeComboBox.currentIndexChanged.connect(self.changeDiagtoolType)
self.ui.languageActionGroup.triggered.connect(self.changeLanguage)
# Setup serial controller and Search for Ports
self.serialController = DiagnosticAdapter(logger=self.writeToOutputView, mode="serial", simulation=self.simulation)
self.searchConnectPort()
# Set initial button states
self.ui.DisconnectPort.setEnabled(False)
self.ui.readZone.setEnabled(False)
self.ui.writeZone.setEnabled(False)
self.ui.flashEcu.setEnabled(False)
self.ui.rebootEcu.setEnabled(False)
self.ui.clearEcuFaults.setEnabled(False)
self.ui.readEcuFaults.setEnabled(False)
self.ui.commandsMenu.setEnabled(False)
self.ui.disableEcoMode.setEnabled(False)
self.ui.visioparkCalibrationAction.setEnabled(False)
self.ui.virginWriteZone.setCheckState(Qt.Unchecked)
self.ui.writeSecureTraceability.setCheckState(Qt.Checked)
# self.ui.useSketchSeedGenerator.setCheckState(Qt.Unchecked)
self.setupCommunication()
# Open CSV reader, load file with method "enable(path)"
self.fileLoaderThread = FileLoader.FileLoaderThread()
self.fileLoaderThread.newRowSignal.connect(self.csvReadCallback)
def setupCommunication(self):
# UDS
self.udsCommunication = DiagnosticCommunication(self.serialController, "uds")
self.udsCommunication.receivedPacketSignal.connect(self.serialPacketReceiverCallback)
self.udsCommunication.outputToTextEditSignal.connect(self.outputToTextEditCallback)
self.udsCommunication.updateZoneDataSignal.connect(self.updateZoneDataback)
self.udsCommunication.readZoneListDoneSignal.connect(self.readZoneListDoneCallback)
# KWP_IS
self.kwpisCommunication = DiagnosticCommunication(self.serialController, "kwp_is")
self.kwpisCommunication.receivedPacketSignal.connect(self.serialPacketReceiverCallback)
self.kwpisCommunication.outputToTextEditSignal.connect(self.outputToTextEditCallback)
self.kwpisCommunication.updateZoneDataSignal.connect(self.updateZoneDataback)
self.kwpisCommunication.readZoneListDoneSignal.connect(self.readZoneListDoneCallback)
# KWP_HAB
self.kwphabCommunication = DiagnosticCommunication(self.serialController, "kwp_hab")
self.kwphabCommunication.receivedPacketSignal.connect(self.serialPacketReceiverCallback)
self.kwphabCommunication.outputToTextEditSignal.connect(self.outputToTextEditCallback)
self.kwphabCommunication.updateZoneDataSignal.connect(self.updateZoneDataback)
self.kwphabCommunication.readZoneListDoneSignal.connect(self.readZoneListDoneCallback)
def addTranslators(self):
self.translator = QTranslator()
self.loadTranslator()
QApplication.instance().installTranslator(self.translator)
def changeLanguage(self, action):
# Action data returns variant [code, language, iconPath]
lang_code = action.data()[0]
if lang_code:
self.lang_code = lang_code
self.loadTranslator()
self.ui.translateGUI()
if self.ecuObjectList is not None and not (isinstance(self.ecuObjectList, dict) and len(self.ecuObjectList) == 0):
self.updateEcuZonesAndKeys(self.ecuObjectList)
self.updateEcuTxRxLabel()
def changeDiagtoolType(self, index):
self.diagtool_type = self.ui.diagtoolTypeComboBox.itemData(index)
if self.diagtool_type.lower() == "serial" or self.diagtool_type.lower() == "bluetooth":
# Arduino and Bluetooth both use COM port selection
self.ui.portNameComboBox.setEnabled(True)
self.ui.SearchConnectPort.setEnabled(True)
self.ui.portNameComboBox.setVisible(True)
self.ui.canPinsComboBox.setVisible(False)
self.ui.wsIpInput.setVisible(False)
if self.ui.portNameComboBox.count() > 0:
self.ui.ConnectPort.setEnabled(True)
else:
self.ui.ConnectPort.setEnabled(False)
elif self.diagtool_type.lower() == "vci":
# VCI mode - no COM port needed, show CAN pins
self.ui.portNameComboBox.setEnabled(False)
self.ui.SearchConnectPort.setEnabled(False)
self.ui.canPinsComboBox.setVisible(True)
self.ui.wsIpInput.setVisible(False)
self.ui.ConnectPort.setEnabled(True)
elif self.diagtool_type.lower() == "websocket":
# Websocket mode - no COM port needed, show IP input
self.ui.portNameComboBox.setEnabled(False)
self.ui.SearchConnectPort.setEnabled(False)
self.ui.canPinsComboBox.setVisible(False)
self.ui.portNameComboBox.setVisible(False)
self.ui.wsIpInput.setVisible(True)
self.ui.ConnectPort.setEnabled(True)
def loadTranslator(self):
qm_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "i18n", "translations", f"PyPSADiag_{self.lang_code}.qm")
self.translator.load(qm_path)
# Update ECU Combobox and Zone Tree view with "new" Zone file
def updateEcuZonesAndKeys(self, ecuObjectList: dict):
# Update ECU Zone ComboBox
self.ui.ecuComboBox.clear()
name = ecuObjectList["name"]
self.ui.ecuComboBox.addItem(name)
if "zones" in ecuObjectList:
zoneObjectList = ecuObjectList["zones"]
# Update ECU Key ComboBox
self.ui.ecuKeyComboBox.clear()
keyType = ecuObjectList["key_type"]
if keyType == "single":
key = str(ecuObjectList["keys"])
item = name + " - " + key
self.ui.ecuKeyComboBox.addItem(item, key)
elif keyType == "multi":
for keyItem in ecuObjectList["keys"]:
key = str(ecuObjectList["keys"][keyItem])
item = str(keyItem) + " - " + key
self.ui.ecuKeyComboBox.addItem(item, key)
elif "ecu" in ecuObjectList:
zoneObjectList = ecuObjectList["ecu"]
else:
self.writeToOutputView(i18n().tr("Not correct JSON file"))
return;
for zoneObject in zoneObjectList:
self.ui.ecuComboBox.addItem(str(zoneObject))
self.ui.treeView.updateView(ecuObjectList)
def updateEcuTxRxLabel(self):
txId = "-"
rxId = "-"
protocol = "-"
if isinstance(self.ecuObjectList, dict) and len(self.ecuObjectList) > 0:
txId = self.ecuObjectList.get("tx_id", "-")
rxId = self.ecuObjectList.get("rx_id", "-")
protocol = self.ecuObjectList.get("protocol", "-")
self.ui.setEcuTxRxText(txId, rxId, protocol)
def writeToOutputView(self, text: str):
self.ui.output.append(str(datetime.now()) + " --| " + text)
self.ui.output.viewport().repaint()
def configureCommunication(self):
if self.serialController.isOpen():
bus = self.ui.canPinsComboBox.currentData() or "DIAG"
success = self.serialController.configure(
self.ecuObjectList.get("tx_id", ""),
self.ecuObjectList.get("rx_id", ""),
self.ecuObjectList.get("protocol", ""),
bus=bus
)
ecuName = self.ecuObjectList.get("name", "")
if not success:
if ecuName != "":
self.writeToOutputView("Diag tool configuration failed for ECU: " + ecuName)
else:
self.writeToOutputView("Diag tool configuration failed")
else:
if ecuName != "":
self.writeToOutputView("Diag tool configuration successful for ECU: " + ecuName)
else:
self.writeToOutputView("Diag tool configuration successful")
return True
else:
self.writeToOutputView(i18n().tr("Port not open!"))
return False
@Slot()
def searchConnectPort(self):
self.serialController.fillPortNameCombobox(self.ui.portNameComboBox)
if self.ui.portNameComboBox.count() > 0:
self.ui.ConnectPort.setEnabled(True)
else:
self.ui.ConnectPort.setEnabled(False)
@Slot()
def connectPort(self):
self.serialController = DiagnosticAdapter(logger=self.writeToOutputView, mode=self.diagtool_type, simulation=self.simulation, ipAddress=self.ui.wsIpInput.text())
self.setupCommunication()
# Set begin connecting button states
self.ui.ConnectPort.setEnabled(False)
self.ui.DisconnectPort.setEnabled(False)
# TODO: Make this more elegant
# Give time to Close Dialog and Repaint
QApplication.processEvents(QEventLoop.AllEvents, 1000)
portName = self.ui.portNameComboBox.currentData() or self.ui.portNameComboBox.currentText()
error = self.serialController.open(portName, 115200)
if error == "":
success = self.configureCommunication()
if not success:
self.serialController.close()
self.ui.ConnectPort.setEnabled(True)
return
# Set button states
self.ui.diagtoolTypeComboBox.setEnabled(False)
self.ui.canPinsComboBox.setEnabled(False)
self.ui.portNameComboBox.setEnabled(False)
self.ui.SearchConnectPort.setEnabled(False)
self.ui.ConnectPort.setEnabled(False)
self.ui.wsIpInput.setEnabled(False)
self.ui.DisconnectPort.setEnabled(True)
self.ui.commandsMenu.setEnabled(True)
self.ui.disableEcoMode.setEnabled(True)
self.ui.visioparkCalibrationAction.setEnabled(True)
if isinstance(self.ecuObjectList, dict) and len(self.ecuObjectList) > 0:
self.setEcuCommandsState(True)
else:
self.ui.ConnectPort.setEnabled(True)
self.writeToOutputView(error)
@Slot()
def disconnectPort(self):
if self.stream != None:
self.stream.close()
self.serialController.close()
self.ui.diagtoolTypeComboBox.setEnabled(True)
self.ui.canPinsComboBox.setEnabled(True)
self.ui.portNameComboBox.setEnabled(True)
self.ui.SearchConnectPort.setEnabled(True)
self.ui.ConnectPort.setEnabled(True)
self.ui.wsIpInput.setEnabled(True)
self.ui.DisconnectPort.setEnabled(False)
self.setEcuCommandsState(False)
# self.ui.useSketchSeedGenerator.setCheckState(Qt.Unchecked)
# self.ui.useSketchSeedGenerator.setEnabled(True)
def setEcuCommandsState(self, enabled):
self.ui.readZone.setEnabled(enabled)
self.ui.writeZone.setEnabled(enabled)
self.ui.flashEcu.setEnabled(enabled)
self.ui.clearEcuFaults.setEnabled(enabled)
self.ui.readEcuFaults.setEnabled(enabled)
self.ui.rebootEcu.setEnabled(enabled)
self.ui.commandsMenu.setEnabled(enabled)
self.ui.disableEcoMode.setEnabled(enabled)
self.ui.visioparkCalibrationAction.setEnabled(enabled)
@Slot()
def hideNoResponseZones(self, state):
self.ui.treeView.hideNoResponseZones(state == 2)
@Slot(str)
def searchZones(self, text):
self.ui.treeView.filterZones(text)
@Slot()
def sendCommand(self):
if self.serialController.isOpen():
cmd = self.ui.command.text()
self.ui.command.clear()
self.writeToOutputView(cmd)
self.receiveData = self.serialController.sendReceive(cmd)
self.writeToOutputView(self.receiveData)
else:
self.writeToOutputView(i18n().tr("Port not open!"))
@Slot()
def openCSVFile(self):
path = os.path.join(os.path.dirname(__file__), "csv")
fileName = QFileDialog.getOpenFileName(self, i18n().tr("Open CSV Zone File"), path, i18n().tr("CSV Files") + "(*.csv)")
if fileName[0] == "":
return
self.ui.treeView.clearZoneListValues()
self.ui.setFilePathInWindowsTitle(fileName[0])
self.fileLoaderThread.enable(fileName[0], 0)
@Slot()
def saveCSVFile(self):
path = os.path.join(os.path.dirname(__file__), "csv")
fileName = QFileDialog.getSaveFileName(self, i18n().tr("Save CSV Zone File"), path, i18n().tr("CSV Files") + "(*.csv)")
if fileName[0] == "":
return
# Open CSV for writing
self.ui.setFilePathInWindowsTitle(fileName[0])
self.stream = open(fileName[0], 'w', newline='', encoding='utf-8')
self.csvWriter = csv.writer(self.stream)
if self.stream != None:
valueList = self.ui.treeView.getValuesAsCSV()
for tabList in valueList:
for zone in tabList:
self.csvWriter.writerow(zone)
self.stream.flush()
@Slot()
def openZoneFile(self):
path = os.path.join(os.path.dirname(__file__), "json")
fileName = QFileDialog.getOpenFileName(self, i18n().tr("Open JSON Zone File"), path, i18n().tr("JSON Files") + "(*.json)")
if fileName[0] == "":
return
file = open(fileName[0], 'r', encoding='utf-8')
jsonFile = file.read()
self.ecuObjectList = json.loads(jsonFile.encode("utf-8"))
# Do we need to include a JSON File and attach it to 'zones'
if "include_zone_object" in self.ecuObjectList:
includeZonePath = os.path.join(os.path.dirname(__file__), self.ecuObjectList["include_zone_object"])
if os.path.exists(includeZonePath):
includeZoneFile = open(includeZonePath, 'r', encoding='utf-8')
includeJsonFile = includeZoneFile.read()
includeObjectList = json.loads(includeJsonFile.encode("utf-8"))
self.ecuObjectList["zones"].update(includeObjectList)
else:
self.writeToOutputView(i18n().tr("Include Zone file not found: ") + includeZonePath)
self.updateEcuZonesAndKeys(self.ecuObjectList)
self.ui.setFilePathInWindowsTitle("")
success = self.configureCommunication()
if success:
self.ui.readZone.setEnabled(True)
self.ui.writeZone.setEnabled(True)
self.ui.flashEcu.setEnabled(False)
self.ui.clearEcuFaults.setEnabled(True)
self.ui.readEcuFaults.setEnabled(True)
self.ui.rebootEcu.setEnabled(True)
self.ui.commandsMenu.setEnabled(True)
self.ui.disableEcoMode.setEnabled(True)
self.ui.visioparkCalibrationAction.setEnabled(True)
self.updateEcuTxRxLabel()
@Slot()
def readZone(self):
if self.serialController.isOpen():
path = os.path.join(os.path.dirname(__file__), "csv")
fileName = QFileDialog.getSaveFileName(self, i18n().tr("Save CSV Zone File"), path, i18n().tr("CSV Files") + "(*.csv)")
if fileName[0] == "":
return
self.ui.treeView.clearZoneListValues()
# Open CSV for writing
self.ui.setFilePathInWindowsTitle(fileName[0])
self.stream = open(fileName[0], 'w', newline='', encoding='utf-8')
self.csvWriter = csv.writer(self.stream)
# Disable UI to prevent interruption
self.setEnabled(False)
# Setup CAN_EMIT_ID
ecu = ">" + self.ecuObjectList["tx_id"] + ":" + self.ecuObjectList["rx_id"]
# Setup LIN_ID if present
lin = ""
if "lin_id" in self.ecuObjectList:
lin = "L" + self.ecuObjectList["lin_id"]
if self.ecuObjectList["protocol"] == "uds":
# Read Requested Zone or ALL Zones from ECU
if self.ui.ecuComboBox.currentIndex() == 0:
self.udsCommunication.setZonesToRead(ecu, lin, self.ecuObjectList["zones"])
else:
zone = {}
zone[self.ui.ecuComboBox.currentText()] = self.ecuObjectList["zones"][self.ui.ecuComboBox.currentText()];
self.udsCommunication.setZonesToRead(ecu, lin, zone)
elif self.ecuObjectList["protocol"] == "kwp_is":
# Read Requested Zone or ALL Zones from ECU
if self.ui.ecuComboBox.currentIndex() == 0:
self.kwpisCommunication.setZonesToRead(ecu, lin, self.ecuObjectList["zones"])
else:
zone = {}
zone[self.ui.ecuComboBox.currentText()] = self.ecuObjectList["zones"][self.ui.ecuComboBox.currentText()];
self.kwpisCommunication.setZonesToRead(ecu, lin, zone)
elif self.ecuObjectList["protocol"] == "kwp_hab":
# Read Requested Zone or ALL Zones from ECU
if self.ui.ecuComboBox.currentIndex() == 0:
self.kwphabCommunication.setZonesToRead(ecu, lin, self.ecuObjectList["zones"])
else:
zone = {}
zone[self.ui.ecuComboBox.currentText()] = self.ecuObjectList["zones"][self.ui.ecuComboBox.currentText()];
self.kwphabCommunication.setZonesToRead(ecu, lin, zone)
else:
self.writeToOutputView(i18n().tr("Protocol not supported yet!"))
else:
self.writeToOutputView(i18n().tr("Port not open!"))
@Slot()
def writeZone(self):
if self.serialController.isOpen():
# Setup text of changed zones and put it into MessageBox
virginWrite = self.ui.virginWriteZone.isChecked()
self.ui.virginWriteZone.setCheckState(Qt.Unchecked)
text = ""
changeCount = 0
valueList = self.ui.treeView.getZoneListOfHexValue(virginWrite)
for tabList in valueList:
for zone in tabList:
text += str(zone) + "\r\n"
changeCount += 1
if changeCount == 0:
self.writeToOutputView(i18n().tr("Nothing changed"))
return
# Give some option to check values and to cancel the write
changedialog = MessageDialog(self, i18n().tr("Write zone(s) to ECU"), i18n().tr("Write"), text)
if MessageDialog.Rejected == changedialog.exec():
return
# Get the corresponding ECU Key from Combobox
index = self.ui.ecuKeyComboBox.currentIndex()
key = self.ui.ecuKeyComboBox.itemData(index)
# Setup CAN_EMIT_ID
ecu = ">" + self.ecuObjectList["tx_id"] + ":" + self.ecuObjectList["rx_id"]
# Setup LIN_ID if present
lin = ""
if "lin_id" in self.ecuObjectList:
lin = "L" + self.ecuObjectList["lin_id"]
if self.ecuObjectList["protocol"] == "uds":
self.udsCommunication.writeZoneList(False, ecu, lin, key, valueList, self.ui.writeSecureTraceability.isChecked())
elif self.ecuObjectList["protocol"] == "kwp_is":
self.kwpisCommunication.writeZoneList(False, ecu, lin, key, valueList, self.ui.writeSecureTraceability.isChecked())
elif self.ecuObjectList["protocol"] == "kwp_hab":
self.kwphabCommunication.writeZoneList(False, ecu, lin, key, valueList, self.ui.writeSecureTraceability.isChecked())
else:
self.writeToOutputView(i18n().tr("Protocol not supported yet!"))
else:
self.writeToOutputView(i18n().tr("Port not open!"))
@Slot()
def flashEcu(self):
if self.serialController.isOpen():
if self.ecuObjectList["protocol"] != "uds":
self.writeToOutputView(i18n().tr("Protocol not supported yet!"))
return
# Check if we have the correct sketch version. Only Vlud V1.9 sketch is supported.
cmd = "V"
self.writeToOutputView("> " + cmd)
receiveData = self.serialController.sendReceive(cmd)
self.writeToOutputView("< " + receiveData)
if float(receiveData) > 1.9:
self.writeToOutputView(i18n().tr("Flashing only supported with sketch version V1.9"))
return
path = os.path.join(os.path.dirname(__file__), "ulp")
fileName = QFileDialog.getOpenFileName(self, i18n().tr("CAUTION... Flash CAL/ULP File"), path, i18n().tr("CAL Files") + "(*.cal)" + ";;" + i18n().tr("ULP Files") + "(*.ulp)")
if fileName[0] == "":
return
# TODO: Make this more elegant
# Give time to Close Dialog and Repaint
QApplication.processEvents(QEventLoop.AllEvents, 1000)
flashFile = DecodeCalUlpFile()
fileOk = flashFile.decodeCalUlpFile(fileName[0], False)
if fileOk == False:
self.writeToOutputView(i18n().tr("File contains errors") + ": " + fileName[0])
return
# Give a warning and some option to cancel the Flash
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.addButton(QMessageBox.Cancel)
msg.addButton(QMessageBox.Ok)
msg.setDefaultButton(QMessageBox.Cancel)
msg.setWindowTitle(i18n().tr("CAUTION: Use at your own RISK!!!"))
msg.setText(i18n().tr("Flashing ECU with:") + os.linesep + fileName[0] + os.linesep + os.linesep + i18n().tr("Do NOT Interrupt the flashing process!!!"))
if QMessageBox.Cancel == msg.exec():
return
# Disable UI to prevent interruption
self.setEnabled(False)
self.writeToOutputView(i18n().tr("Fashing file") + ":" + fileName[0] )
# Setup CAN_EMIT_ID
ecu = ">" + self.ecuObjectList["tx_id"] + ":" + self.ecuObjectList["rx_id"]
if self.ecuObjectList["protocol"] == "uds":
self.udsCommunication.flashEcu(ecu, flashFile)
else:
self.writeToOutputView(i18n().tr("Protocol not supported yet!"))
# Enable UI again
self.setEnabled(True)
else:
self.writeToOutputView(i18n().tr("Port not open!"))
@Slot()
def rebootEcu(self):
if self.serialController.isOpen():
# Setup CAN_EMIT_ID
ecu = ">" + self.ecuObjectList["tx_id"] + ":" + self.ecuObjectList["rx_id"]
if self.ecuObjectList.get("name") in ("IVI", "BSRF", "RTBM"):
# IVI/BSRF/RTBM require extended session and DTC read before reboot
commands = [ecu, "1003", "190209", "1103"]
for cmd in commands:
self.writeToOutputView("> " + cmd)
receiveData = self.serialController.sendReceive(cmd)
self.writeToOutputView("< " + receiveData)
if receiveData == "Timeout":
break
elif self.ecuObjectList["protocol"] == "uds":
self.udsCommunication.rebootEcu(ecu)
elif self.ecuObjectList["protocol"] == "kwp_hab":
self.kwphabCommunication.rebootEcu(ecu)
else:
self.writeToOutputView(i18n().tr("Protocol not supported yet!"))
else:
self.writeToOutputView(i18n().tr("Port not open!"))
@Slot()
def readEcuFaults(self):
if self.serialController.isOpen():
# Setup CAN_EMIT_ID
ecu = ">" + self.ecuObjectList["tx_id"] + ":" + self.ecuObjectList["rx_id"]
if self.ecuObjectList["protocol"] == "uds":
dtc = self.udsCommunication.readEcuFaults(ecu)
ParseDTC.parse(dtc, self.ecuObjectList.get("dtc_lookup", ""))
else:
self.writeToOutputView(i18n().tr("Protocol not supported yet!"))
else:
self.writeToOutputView(i18n().tr("Port not open!"))
@Slot()
def clearEcuFaults(self):
if self.serialController.isOpen():
# Setup CAN_EMIT_ID
ecu = ">" + self.ecuObjectList["tx_id"] + ":" + self.ecuObjectList["rx_id"]
# Give some option to cancel the Clear Fault Codes
changedialog = MessageDialog(self, i18n().tr("Clearing Fault Codes of ECU:"), i18n().tr("Ok"), ecu)
if MessageDialog.Rejected == changedialog.exec():
return
if self.ecuObjectList["protocol"] == "uds":
self.udsCommunication.clearEcuFaults(ecu)
else:
self.writeToOutputView(i18n().tr("Protocol not supported yet!"))
else:
self.writeToOutputView(i18n().tr("Port not open!"))
@Slot()
def disableEcoMode(self):
if self.serialController.isOpen():
ecu = ">752:652"
key = "B4E0"
# Select BSI
self.writeToOutputView("> " + ecu)
receiveData = self.serialController.sendReceive(ecu)
self.writeToOutputView("< " + receiveData)
if receiveData == "Timeout":
return
# Start diagnostic session (1003)
if not self.udsCommunication.startDiagnosticMode():
return
# Unlock ECU with BSI key (2703 -> compute seed -> 2704)
seed = self.udsCommunication.unlockingServiceForConfiguration(key)
if len(seed) == 0:
self.udsCommunication.stopDiagnosticMode()
return
time.sleep(2)
if not self.udsCommunication.sendUnlockingResponseForConfiguration(seed):
self.udsCommunication.stopDiagnosticMode()
return
# Send Disable Eco Mode routine
self.udsCommunication.writeECUCommand("3101DF0A3C")
# Stop diagnostic session (1001)
self.udsCommunication.stopDiagnosticMode()
else:
self.writeToOutputView(i18n().tr("Port not open!"))
@Slot()
def visioparkCalibration(self):
if not self.serialController.isOpen():
self.writeToOutputView(i18n().tr("Port not open!"))
return
# Get key from currently loaded JSON
index = self.ui.ecuKeyComboBox.currentIndex()
if index < 0:
self.writeToOutputView("No ECU key selected. Load NAC or RCC zone file first.")
return
key = self.ui.ecuKeyComboBox.itemData(index)
ecu = ">764:664"
# Select NAC/RCC ECU
self.writeToOutputView("> " + ecu)
receiveData = self.serialController.sendReceive(ecu)
self.writeToOutputView("< " + receiveData)
if receiveData == "Timeout":
return
# Start diagnostic session (1003)
if not self.udsCommunication.startDiagnosticMode():
return
# Unlock ECU with key from JSON (2703 -> compute seed -> 2704)
seed = self.udsCommunication.unlockingServiceForConfiguration(key)
if len(seed) == 0:
self.udsCommunication.stopDiagnosticMode()
return
time.sleep(2)
if not self.udsCommunication.sendUnlockingResponseForConfiguration(seed):
self.udsCommunication.stopDiagnosticMode()
return
# Start dynamic Visiopark calibration routine
self.writeToOutputView("Starting Visiopark dynamic calibration...")
receiveData = self.udsCommunication.writeECUCommand("3101DF0C")
if len(receiveData) < 4 or receiveData[:4] != "7101":
self.writeToOutputView("Failed to start calibration: " + receiveData)
self.udsCommunication.stopDiagnosticMode()
return
# Open polling dialog
dialog = VisioparkCalibrationDialog(self.udsCommunication, self.writeToOutputView, self)
dialog.exec()
# Stop diagnostic session (1001)
self.udsCommunication.stopDiagnosticMode()
@Slot()
def csvReadCallback(self, value: list):
# Did we had an empty line in CSV? Then skip it.
if len(value) >= 2:
self.ui.treeView.changeZoneOption(value[0], value[1])
@Slot()
def readZoneListDoneCallback(self):
self.ui.flashEcu.setEnabled(True)
# Enable UI again
self.setEnabled(True)
@Slot()
def updateZoneDataback(self, zoneData: str, value: str):
self.ui.treeView.changeZoneOption(zoneData, value)
@Slot()
def outputToTextEditCallback(self, text: str):
self.writeToOutputView(text)
@Slot()
def serialPacketReceiverCallback(self, packet: list, time: float):
self.writeToOutputView(str(packet))
if self.stream != None:
self.csvWriter.writerow(packet)
self.stream.flush()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow(app)
window.show()
sys.exit(app.exec())