-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
376 lines (323 loc) · 14.9 KB
/
main.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
"""
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
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
from PyPSADiagGUI import PyPSADiagGUI
import FileLoader
from DiagnosticCommunication import DiagnosticCommunication
from SeedKeyAlgorithm import SeedKeyAlgorithm
from SerialPort import SerialPort
from FileConverter import FileConverter
from EcuZoneTreeView import EcuZoneTreeView
"""
- Change GUI in: PyPSADiagGUI.py
- Run with: python main.py
"""
class MainWindow(QMainWindow):
ui = PyPSADiagGUI()
ecuObjectList = {}
simulation = False
stream = None
csvWriter = None
def __init__(self):
super(MainWindow, self).__init__()
if len(sys.argv) >= 2:
for arg in sys.argv:
if arg == "--simu":
self.simulation = True
if arg == "--checkcalc":
calc = SeedKeyAlgorithm()
calc.testCalculations()
exit()
if arg == "--help":
print("Use --simu For simulation")
exit()
self.ui.setupGUi(self)
#converter = FileConverter()
#converter.convertNAC("./json/test_nac_original.json", "./json/test_nac_conv.json")
#converter.convertCIROCCO("./json/test_CIROCCO_original.json", "./json/test_CIROCCO_conv.json")
# 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.rebootEcu.clicked.connect(self.rebootEcu)
self.ui.readEcuFaults.clicked.connect(self.readEcuFaults)
self.ui.SearchConnectPort.clicked.connect(self.searchConnectPort)
self.ui.ConnectPort.clicked.connect(self.connectPort)
self.ui.DisconnectPort.clicked.connect(self.disconnectPort)
# Setup serial controller
self.serialController = SerialPort()
self.serialController.fillPortNameCombobox(self.ui.portNameComboBox)
# Set initial button states
self.ui.DisconnectPort.setEnabled(False)
self.ui.readZone.setEnabled(False)
self.ui.writeZone.setEnabled(False)
self.ui.rebootEcu.setEnabled(False)
self.ui.readEcuFaults.setEnabled(False)
self.ui.writeSecureTraceability.setCheckState(Qt.Checked)
# self.ui.useSketchSeedGenerator.setCheckState(Qt.Unchecked)
# UDS
self.udsCommunication = DiagnosticCommunication(self.serialController, "uds", self.simulation)
self.udsCommunication.receivedPacketSignal.connect(self.serialPacketReceiverCallback)
self.udsCommunication.outputToTextEditSignal.connect(self.outputToTextEditCallback)
self.udsCommunication.updateZoneDataSignal.connect(self.updateZoneDataback)
# KWP_IS
self.kwpCommunication = DiagnosticCommunication(self.serialController, "kwp_is", self.simulation)
self.kwpCommunication.receivedPacketSignal.connect(self.serialPacketReceiverCallback)
self.kwpCommunication.outputToTextEditSignal.connect(self.outputToTextEditCallback)
self.kwpCommunication.updateZoneDataSignal.connect(self.updateZoneDataback)
# Open CSV reader, load file with method "enable(path)"
self.fileLoaderThread = FileLoader.FileLoaderThread()
self.fileLoaderThread.newRowSignal.connect(self.csvReadCallback)
# 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("Not correct JSON file")
return;
for zoneObject in zoneObjectList:
self.ui.ecuComboBox.addItem(str(zoneObject))
self.ui.treeView.updateView(ecuObjectList)
def writeToOutputView(self, text: str):
self.ui.output.append(str(datetime.now()) + " --| " + text)
self.ui.output.viewport().repaint()
@Slot()
def searchConnectPort(self):
self.serialController.fillPortNameCombobox(self.ui.portNameComboBox)
@Slot()
def connectPort(self):
self.serialController.open(self.ui.portNameComboBox.currentText(), 115200)
# Set button states
self.ui.ConnectPort.setEnabled(False)
self.ui.DisconnectPort.setEnabled(True)
# First send an Reset command
cmd = "R"
self.writeToOutputView("> " + cmd)
receiveData = self.serialController.sendReceive(cmd)
self.writeToOutputView("< " + receiveData)
@Slot()
def disconnectPort(self):
if self.stream != None:
self.stream.close()
self.serialController.close()
self.ui.ConnectPort.setEnabled(True)
self.ui.DisconnectPort.setEnabled(False)
self.ui.readZone.setEnabled(False)
self.ui.writeZone.setEnabled(False)
self.ui.writeZone.setEnabled(False)
self.ui.readEcuFaults.setEnabled(False)
self.ui.rebootEcu.setEnabled(False)
# self.ui.useSketchSeedGenerator.setCheckState(Qt.Unchecked)
# self.ui.useSketchSeedGenerator.setEnabled(True)
@Slot()
def sendCommand(self):
if self.serialController.isOpen():
cmd = self.ui.command.text()
self.writeToOutputView(cmd)
self.receiveData = self.serialController.sendReceive(cmd)
self.writeToOutputView(self.receiveData)
else:
self.writeToOutputView("Port not open!")
@Slot()
def openCSVFile(self):
fileName = QFileDialog.getOpenFileName(self, "Open CSV Zone File", "./csv", "CSV Files (*.csv)")
if fileName[0] == "":
return
self.fileLoaderThread.enable(fileName[0], 0);
@Slot()
def saveCSVFile(self):
fileName = QFileDialog.getSaveFileName(self, "Save CSV Zone File", "./csv", "CSV Files (*.csv)")
if fileName[0] == "":
return
# Open CSV for writing
self.stream = open(fileName[0], 'w', newline='')
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):
fileName = QFileDialog.getOpenFileName(self, "Open JSON Zone File", "./json", "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 = 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("Include Zone file not found: " + includeZonePath)
self.updateEcuZonesAndKeys(self.ecuObjectList)
self.ui.readZone.setEnabled(True)
self.ui.writeZone.setEnabled(True)
self.ui.writeZone.setEnabled(True)
self.ui.readEcuFaults.setEnabled(True)
self.ui.rebootEcu.setEnabled(True)
@Slot()
def readZone(self):
if self.serialController.isOpen():
fileName = QFileDialog.getSaveFileName(self, "Save CSV Zone File", "./csv", "CSV Files (*.csv)")
if fileName[0] == "":
return
# Open CSV for writing
self.stream = open(fileName[0], 'w', newline='')
self.csvWriter = csv.writer(self.stream)
# 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.kwpCommunication.setZonesToRead(ecu, lin, self.ecuObjectList["zones"])
else:
zone = {}
zone[self.ui.ecuComboBox.currentText()] = self.ecuObjectList["zones"][self.ui.ecuComboBox.currentText()];
self.kwpCommunication.setZonesToRead(ecu, lin, zone)
else:
self.writeToOutputView("Protocol not supported yet!")
return
else:
self.writeToOutputView("Port not open!")
@Slot()
def writeZone(self):
if self.serialController.isOpen():
# Setup text of changed zones and put it into MessageBox
text = ""
changeCount = 0
valueList = self.ui.treeView.getZoneListOfHexValue()
for tabList in valueList:
for zone in tabList:
text += str(zone) + "\r\n"
changeCount += 1
if changeCount == 0:
self.writeToOutputView("Nothing changed")
return
# Give some option to check values and to cancel the write
if QMessageBox.Cancel == QMessageBox.question(self, "Write zone(s) to ECU", text, QMessageBox.Save, QMessageBox.Cancel):
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(self.ui.useSketchSeedGenerator.isChecked(), ecu, lin, key, valueList, self.ui.writeSecureTraceability.isChecked())
self.udsCommunication.writeZoneList(False, ecu, lin, key, valueList, self.ui.writeSecureTraceability.isChecked())
elif self.ecuObjectList["protocol"] == "kwp_is":
self.kwpCommunication.writeZoneList(False, ecu, lin, key, valueList, self.ui.writeSecureTraceability.isChecked())
else:
self.writeToOutputView("Protocol not supported yet!")
return
else:
self.writeToOutputView("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["protocol"] == "uds":
self.udsCommunication.rebootEcu(ecu)
else:
self.writeToOutputView("Protocol not supported yet!")
return
else:
self.writeToOutputView("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":
self.udsCommunication.readEcuFaults(ecu)
else:
self.writeToOutputView("Protocol not supported yet!")
return
else:
self.writeToOutputView("Port not open!")
@Slot()
def csvReadCallback(self, value: list):
self.ui.treeView.changeZoneOption(value[0], value[1]);
@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()
window.show()
sys.exit(app.exec())