forked from collin80/SavvyCAN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
framefileio.cpp
5091 lines (4488 loc) · 170 KB
/
framefileio.cpp
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
#include "framefileio.h"
#include <QMessageBox>
#include <QProgressDialog>
#include <QDateTime>
#include <QRegularExpression>
#include <QtEndian>
#include <QSettings>
#include <iostream>
#include <memory>
#include "pcaplite.h"
#include "utility.h"
#include "blfhandler.h"
QFile FrameFileIO::continuousFile;
struct TeslaAPCANRecord
{
#pragma pack(push, 1)
int64_t sec;
int32_t nano;
int32_t padding1;
uint16_t id;
uint8_t ctr;
uint8_t data[8];
uint8_t padding2;
#pragma pack(pop)
};
FrameFileIO::FrameFileIO()
{
}
bool FrameFileIO::saveFrameFile(QString &fileName, const QVector<CANFrame>* frameCache)
{
QString filename;
QFileDialog dialog(qApp->activeWindow());
QSettings settings;
bool result = false;
QStringList filters;
filters.append(QString(tr("GVRET Logs (*.csv *.CSV)")));
filters.append(QString(tr("CRTD Logs (*.crt *.crtd *.CRT *.CRTD)")));
filters.append(QString(tr("Generic ID/Data CSV (*.csv *.CSV)")));
filters.append(QString(tr("BusMaster Log (*.log *.LOG)")));
filters.append(QString(tr("Microchip Log (*.can *.CAN *.log *.LOG)")));
filters.append(QString(tr("Vector Trace Files (*.trace *.TRACE)")));
filters.append(QString(tr("IXXAT MiniLog (*.csv *.CSV)")));
filters.append(QString(tr("CAN-DO Log (*.can *.avc *.evc *.qcc *.CAN *.AVC *.EVC *.QCC)")));
filters.append(QString(tr("Vehicle Spy (*.csv *.CSV)")));
filters.append(QString(tr("Candump/Kayak (*.log)")));
filters.append(QString(tr("Cabana Log (*.csv *.CSV)")));
filters.append(QString(tr("CANalyzer Ascii Log (*.asc *.ASC)")));
filters.append(QString(tr("CARBUS Analyzer (*.trc *.TRC)")));
dialog.setDirectory(settings.value("FileIO/LoadSaveDirectory", dialog.directory().path()).toString());
dialog.setFileMode(QFileDialog::AnyFile);
dialog.setNameFilters(filters);
dialog.setViewMode(QFileDialog::Detail);
dialog.setAcceptMode(QFileDialog::AcceptSave);
if (dialog.exec() == QDialog::Accepted)
{
filename = dialog.selectedFiles()[0];
QProgressDialog progress(qApp->activeWindow());
progress.setWindowModality(Qt::WindowModal);
progress.setLabelText("Saving file...");
progress.setCancelButton(nullptr);
progress.setRange(0,0);
progress.setMinimumDuration(0);
progress.show();
qApp->processEvents();
if (dialog.selectedNameFilter() == filters[0])
{
if (!filename.contains('.')) filename += ".csv";
result = saveNativeCSVFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[1])
{
if (!filename.contains('.')) filename += ".txt";
result = saveCRTDFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[2])
{
if (!filename.contains('.')) filename += ".csv";
result = saveGenericCSVFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[3])
{
if (!filename.contains('.')) filename += ".log";
result = saveLogFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[4])
{
if (!filename.contains('.')) filename += ".log";
result = saveMicrochipFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[5])
{
if (!filename.contains('.')) filename += ".trace";
result = saveTraceFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[6])
{
if (!filename.contains('.')) filename += ".csv";
result = saveIXXATFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[7])
{
if (!filename.contains('.')) filename += ".can";
result = saveCANDOFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[8])
{
if (!filename.contains('.')) filename += ".csv";
result = saveVehicleSpyFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[9])
{
if (!filename.contains('.')) filename += ".log";
saveCanDumpFile(filename,frameCache);
}
if (dialog.selectedNameFilter() == filters[10])
{
if (!filename.contains('.')) filename += ".csv";
result = saveCabanaFile(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[11])
{
if (!filename.contains('.')) filename += ".asc";
result = saveCanalyzerASC(filename, frameCache);
}
if (dialog.selectedNameFilter() == filters[12])
{
if (!filename.contains('.')) filename += ".trc";
result = saveCARBUSAnalzyer(filename, frameCache);
}
progress.cancel();
if (result)
{
QStringList fileList = filename.split('/');
fileName = fileList[fileList.length() - 1];
settings.setValue("FileIO/LoadSaveDirectory", dialog.directory().path());
return true;
}
return false;
}
return false;
}
bool FrameFileIO::loadFrameFile(QString &fileName, QVector<CANFrame>* frameCache)
{
QString filename;
QFileDialog dialog;
QSettings settings;
bool result = false;
QStringList filters;
filters.append(QString(tr("Autodetect File Type (*.*)")));
filters.append(QString(tr("GVRET Logs (*.csv *.CSV)")));
filters.append(QString(tr("CRTD Logs (*.crt *.crtd *.CRT *.CRTD)")));
filters.append(QString(tr("BusMaster Log (*.log *.LOG)")));
filters.append(QString(tr("Microchip Log (*.can *.CAN *.log *.LOG)")));
filters.append(QString(tr("Vector trace files (*.trace *.TRACE)")));
filters.append(QString(tr("IXXAT MiniLog (*.csv *.CSV)")));
filters.append(QString(tr("CAN-DO Log (*.avc *.can *.evc *.qcc *.AVC *.CAN *.EVC *.QCC)")));
filters.append(QString(tr("Vehicle Spy (*.csv *.CSV)")));
filters.append(QString(tr("Candump/Kayak (*.log *.LOG)")));
filters.append(QString(tr("CANDump Lawicel (*.txt *.TXT *.LOG *.log)")));
filters.append(QString(tr("PCAN Viewer (*.trc *.TRC)")));
filters.append(QString(tr("Kvaser Log Decimal (*.txt *.TXT)")));
filters.append(QString(tr("Kvaser Log Hex (*.txt *.TXT)")));
filters.append(QString(tr("CANalyzer Ascii Log (*.asc *.ASC)")));
filters.append(QString(tr("CANalyzer Binary Log Files (*.blf *.BLF)")));
filters.append(QString(tr("CARBUS Analyzer Trace Files (*.trc *.TRC)")));
filters.append(QString(tr("CANHacker Trace Files (*.trc *.TRC)")));
filters.append(QString(tr("Generic ID/Data CSV (*.csv *.CSV)")));
filters.append(QString(tr("Cabana Log (*.csv *.CSV)")));
filters.append(QString(tr("CANOpen Magic (*.csv *.CSV)")));
filters.append(QString(tr("Tesla Autopilot Snapshot (*.CAN *.can)")));
filters.append(QString(tr("CLX000 (*.txt *.TXT)")));
filters.append(QString(tr("CANServer Binary Log (*.log *.LOG)")));
filters.append(QString(tr("Wireshark (*.pcap *.PCAP *.pcapng *.PCAPNG)")));
dialog.setDirectory(settings.value("FileIO/LoadSaveDirectory", dialog.directory().path()).toString());
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.setNameFilters(filters);
dialog.setViewMode(QFileDialog::Detail);
if (dialog.exec() == QDialog::Accepted)
{
filename = dialog.selectedFiles()[0];
QString selectedNameFilter = dialog.selectedNameFilter();
QProgressDialog progress(qApp->activeWindow());
progress.setWindowModality(Qt::WindowModal);
progress.setLabelText("Loading file...");
progress.setCancelButton(nullptr);
progress.setRange(0,0);
progress.setMinimumDuration(0);
progress.show();
qApp->processEvents();
if (selectedNameFilter == filters[0]) result = autoDetectLoadFile(filename, frameCache);
if (selectedNameFilter == filters[1]) result = loadNativeCSVFile(filename, frameCache);
if (selectedNameFilter == filters[2]) result = loadCRTDFile(filename, frameCache);
if (selectedNameFilter == filters[3]) result = loadLogFile(filename, frameCache);
if (selectedNameFilter == filters[4]) result = loadMicrochipFile(filename, frameCache);
if (selectedNameFilter == filters[5]) result = loadTraceFile(filename, frameCache);
if (selectedNameFilter == filters[6]) result = loadIXXATFile(filename, frameCache);
if (selectedNameFilter == filters[7]) result = loadCANDOFile(filename, frameCache);
if (selectedNameFilter == filters[8]) result = loadVehicleSpyFile(filename, frameCache);
if (selectedNameFilter == filters[9]) result = loadCanDumpFile(filename, frameCache);
if (selectedNameFilter == filters[10]) result = loadLawicelFile(filename, frameCache);
if (selectedNameFilter == filters[11]) result = loadPCANFile(filename, frameCache);
if (selectedNameFilter == filters[12]) result = loadKvaserFile(filename, frameCache, false);
if (selectedNameFilter == filters[13]) result = loadKvaserFile(filename, frameCache, true);
if (selectedNameFilter == filters[14]) result = loadCanalyzerASC(filename, frameCache);
if (selectedNameFilter == filters[15]) result = loadCanalyzerBLF(filename, frameCache);
if (selectedNameFilter == filters[16]) result = loadCARBUSAnalyzerFile(filename, frameCache);
if (selectedNameFilter == filters[17]) result = loadCANHackerFile(filename, frameCache);
if (selectedNameFilter == filters[18]) result = loadGenericCSVFile(filename, frameCache);
if (selectedNameFilter == filters[19]) result = loadCabanaFile(filename, frameCache);
if (selectedNameFilter == filters[20]) result = loadCANOpenFile(filename, frameCache);
if (selectedNameFilter == filters[21]) result = loadTeslaAPFile(filename, frameCache);
if (selectedNameFilter == filters[22]) result = loadCLX000File(filename, frameCache);
if (selectedNameFilter == filters[23]) result = loadCANServerFile(filename, frameCache);
if (selectedNameFilter == filters[24]) result = loadWiresharkFile(filename, frameCache);
progress.cancel();
if (result)
{
QStringList fileList = filename.split('/');
fileName = fileList[fileList.length() - 1];
settings.setValue("FileIO/LoadSaveDirectory", dialog.directory().path());
return true;
}
else
{
if (dialog.selectedNameFilter() != filters[0])
{
QMessageBox msgBox;
msgBox.setText("File load completed with errors.\r\nPerhaps you selected the wrong file type?");
msgBox.exec();
}
return false;
}
}
return false;
}
//Try every format by first using the "is" functions which try to detect whether a given file is a good match to that
//file format or not. Those functions are much less tolerant than the load functions and so should help to discriminate
//whether a file could be loaded or not by a given loader. The loader return is still used in case the guess was wrong.
bool FrameFileIO::autoDetectLoadFile(QString filename, QVector<CANFrame>* frames)
{
qDebug() << "Attempting Canalyzer BLF";
if (isCanalyzerBLF(filename))
{
if (loadCanalyzerBLF(filename, frames))
{
qDebug() << "Loaded as Canalyzer BLF successfully!";
return true;
}
}
qDebug() << "Attempting native CSV";
if (isNativeCSVFile(filename))
{
if (loadNativeCSVFile(filename, frames))
{
qDebug() << "Loaded as native CSV successfully!";
return true;
}
}
qDebug() << "Attempting Tesla AP Snapshot";
if (isTeslaAPFile(filename))
{
if (loadTeslaAPFile(filename, frames))
{
qDebug() << "Loaded as Tesla AP Snapshot successfully!";
return true;
}
}
qDebug() << "Attempting CANServer Binary Log";
if (isCANServerFile(filename))
{
if (loadCANServerFile(filename, frames))
{
qDebug() << "Loaded as CANServer Binary Log successfully!";
return true;
}
}
qDebug() << "Attempting Wireshark Log";
if (isWiresharkFile(filename))
{
if (loadWiresharkFile(filename, frames))
{
qDebug() << "Loaded as Wireshark Log successfully!";
return true;
}
}
qDebug() << "Attempting canalyzer ASC";
if (isCanalyzerASC(filename))
{
if (loadCanalyzerASC(filename, frames))
{
qDebug() << "Loaded as Canalyzer ASC successfully!";
return true;
}
}
qDebug() << "Attempting CRTD";
if (isCRTDFile(filename))
{
if (loadCRTDFile(filename, frames))
{
qDebug() << "Loaded as CRTD successfully!";
return true;
}
}
qDebug() << "Attempting trace file";
if (isTraceFile(filename))
{
if (loadTraceFile(filename, frames))
{
qDebug() << "Loaded as trace successfully!";
return true;
}
}
qDebug() << "Attempting vehicle spy";
if (isVehicleSpyFile(filename))
{
if (loadVehicleSpyFile(filename, frames))
{
qDebug() << "Loaded as vehicle spy successfully!";
return true;
}
}
qDebug() << "Attempting candump";
if (isCanDumpFile(filename))
{
if (loadCanDumpFile(filename, frames))
{
qDebug() << "Loaded as candump successfully!";
return true;
}
}
qDebug() << "Attempting 'CARBUS Analyzer'";
if (isCARBUSAnalyzerFile(filename))
{
if (loadCARBUSAnalyzerFile(filename, frames))
{
qDebug() << "Loaded as 'CARBUS Analyzer' successfully!";
return true;
}
}
qDebug() << "Attempting canhacker";
if (isCANHackerFile(filename))
{
if (loadCANHackerFile(filename, frames))
{
qDebug() << "Loaded as CANHacker successfully!";
return true;
}
}
qDebug() << "Attempting cabana";
if (isCabanaFile(filename))
{
if (loadCabanaFile(filename, frames))
{
qDebug() << "Loaded as Cabana successfully!";
return true;
}
}
qDebug() << "Attempting canopen";
if (isCANOpenFile(filename))
{
if (loadCANOpenFile(filename, frames))
{
qDebug() << "Loaded as CANOpen Magic successfully!";
return true;
}
}
qDebug() << "Attempting busmaster log";
if (isLogFile(filename))
{
if (loadLogFile(filename, frames))
{
qDebug() << "Loaded as Busmaster Log successfully!";
return true;
}
}
qDebug() << "Attempting pcan";
if (isPCANFile(filename))
{
if (loadPCANFile(filename, frames))
{
qDebug() << "Loaded as PCAN successfully!";
return true;
}
}
qDebug() << "Attempting ixxat";
if (isIXXATFile(filename))
{
if (loadIXXATFile(filename, frames))
{
qDebug() << "Loaded as IXXAT successfully!";
return true;
}
}
qDebug() << "Attempting microchip";
if (isMicrochipFile(filename))
{
if (loadMicrochipFile(filename, frames))
{
qDebug() << "Loaded as microchip successfully!";
return true;
}
}
qDebug() << "Attempting CANDo";
if (isCANDOFile(filename))
{
if (loadCANDOFile(filename, frames))
{
qDebug() << "Loaded as CANDO successfully!";
return true;
}
}
qDebug() << "Attempting kvaser";
if (isKvaserFile(filename))
{
if (loadKvaserFile(filename, frames,true))
{
qDebug() << "Loaded as Kvaser HEX successfully!";
return true;
}
if (loadKvaserFile(filename, frames,false))
{
qDebug() << "Loaded as KVaser Decimal successfully!";
return true;
}
}
qDebug() << "Attempting CLX000";
if (isCLX000File(filename))
{
if (loadCLX000File(filename, frames))
{
qDebug() << "Loaded as CLX000 successfully!";
return true;
}
}
qDebug() << "Attempting lawicel";
if (isLawicelFile(filename))
{
if (loadLawicelFile(filename, frames))
{
qDebug() << "Loaded as lawicel successfully!";
return true;
}
}
qDebug() << "Attempting generic CSV";
if (isGenericCSVFile(filename))
{
if (loadGenericCSVFile(filename, frames))
{
qDebug() << "Loaded as generic CSV successfully!";
return true;
}
}
QMessageBox msgBox;
msgBox.setText("Could not autodetect the file type.\rPlease try to manually select the file format.");
msgBox.exec();
qDebug() << "Nothing worked... sorry...";
return false;
}
bool FrameFileIO::isVehicleSpyFile(QString filename)
{
QFile *inFile = new QFile(filename);
QByteArray line;
bool foundProbableHeader = false;
bool isMatch = false;
if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
{
delete inFile;
return false;
}
try {
for (int i = 0; i < 10; i++)
{
if (!inFile->atEnd())
{
line = inFile->readLine().simplified().toUpper();
if (line.startsWith("LINE") && line.contains("TIME") && line.contains("B1"))
{
foundProbableHeader = true;
}
}
}
if (foundProbableHeader)
{
if (!inFile->atEnd())
{
line = inFile->readLine().simplified().toUpper();
inFile->close();
QList<QByteArray> tokens = line.split(',');
if (tokens.length() > 20)
{
if (tokens[9].toInt(nullptr, 16) > 0) isMatch = true;
}
}
}
}
catch (...)
{
isMatch = false;
}
inFile->close();
return isMatch;
}
//2,2550.368293675,0.003818174999651092,67371008,F,F,HS CAN $119,HS CAN,,119,F,F,00,00,00,00,00,00,0D,8B,,,
//Line,Abs Time(Sec),Rel Time (Sec),Status,Er,Tx,Description,Network,Node,Arb ID,Remote,Xtd,B1,B2,B3,B4,B5,B6,B7,B8,Value,Trigger,Signals
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
bool FrameFileIO::loadVehicleSpyFile(QString filename, QVector<CANFrame> *frames)
{
QFile *inFile = new QFile(filename);
CANFrame thisFrame;
QByteArray line;
int lineCounter = 0;
bool pastHeader = false;
bool foundErrors = false;
QDateTime now = QDateTime::currentDateTime();
QDateTime tempTime;
if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
{
delete inFile;
return false;
}
while (!inFile->atEnd() && !pastHeader)
{
line = inFile->readLine().simplified().toUpper();
if (line.startsWith("LINE")) lineCounter++;
if (lineCounter == 2) pastHeader = true;
}
if (inFile->atEnd()) foundErrors = true;
while (!inFile->atEnd()) {
lineCounter++;
if (lineCounter > 100)
{
qApp->processEvents();
lineCounter = 0;
}
line = inFile->readLine().simplified().toUpper();
QList<QByteArray> tokens = line.split(',');
if (tokens.length() > 20)
{
thisFrame.bus = 0;
thisFrame.setFrameType(QCanBusFrame::DataFrame);
tempTime = now;
tempTime = tempTime.addMSecs(static_cast<int64_t>(tokens[1].toDouble() * 1000.0));
thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast<uint64_t>(tempTime.toMSecsSinceEpoch() * 1000)));
if (tokens[5].startsWith("T")) thisFrame.isReceived = false;
else thisFrame.isReceived = true;
thisFrame.setFrameId(static_cast<uint32_t>(tokens[9].toInt(nullptr, 16)));
if (tokens[11].startsWith("T")) thisFrame.setExtendedFrameFormat(true);
else thisFrame.setExtendedFrameFormat(false);
QByteArray bytes;
for (int i = 0; i < 8; i++)
{
if (tokens[12 + i].length() > 0)
{
bytes.append(static_cast<char>(tokens[12 + i].toInt(nullptr, 16)));
}
else break;
}
thisFrame.setPayload(bytes);
frames->append(thisFrame);
}
else foundErrors = true;
}
inFile->close();
delete inFile;
return !foundErrors;
}
bool FrameFileIO::saveVehicleSpyFile(QString filename, const QVector<CANFrame> *frames)
{
Q_UNUSED(filename);
Q_UNUSED(frames);
return true;
}
bool FrameFileIO::isCRTDFile(QString filename)
{
QFile *inFile = new QFile(filename);
QByteArray line;
int lineCounter = 0;
bool isMatch = false;
if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
{
delete inFile;
return false;
}
try
{
line = inFile->readLine().toUpper(); //read out the header first and discard it.
while (!inFile->atEnd() && lineCounter < 100) {
lineCounter++;
line = inFile->readLine().simplified();
if (line.length() > 2)
{
QList<QByteArray> tokens = line.split(' ');
if (tokens.length() > 2)
{
char firstChar = tokens[1].left(1)[0];
if (firstChar >= '1' && firstChar <= '9')
{
tokens[1].remove(0,1); // Remove leading digit (bus number)
firstChar = tokens[1].left(1)[0];
}
if (firstChar == 'R' || firstChar == 'T')
{
if (tokens[1] == "R29" || tokens[1] == "T29") isMatch = true;
if (tokens[1] == "R11" || tokens[1] == "T11") isMatch = true;
}
}
else isMatch = false;
}
if (lineCounter > 10) break;
}
}
catch (...)
{
isMatch = false;
}
inFile->close();
delete inFile;
return isMatch;
}
//CRTD format from Mark Webb-Johnson / OVMS project
// Specification at: https://docs.openvehicles.com/en/latest/crtd/
/*
Sample data in CRTD format
Timestamp appears to be seconds since the epoch
1320745424.000 CXX OVMS Tesla Roadster cando2crtd converted log
1320745424.000 CXX OVMS Tesla roadster log: charge.20111108.csv
1320745424.002 R11 402 FA 01 C3 A0 96 00 07 01
1320745424.015 R11 400 02 9E 01 80 AB 80 55 00
1320745424.066 R11 400 01 01 00 00 00 00 4C 1D
1320745424.105 R11 100 A4 53 46 5A 52 45 38 42
1320745424.106 R11 100 A5 31 35 42 33 30 30 30
1320745424.106 R11 100 A6 35 36 39
1320745424.106 CEV Open charge port door
1320745424.106 R11 100 9B 97 A6 31 03 15 05 06
1320745424.107 R11 100 07 64
123.431 2R11 27E 00 00 00 00 00 00 00 00
123.441 2R11 7C8 00 00 00 00 00 00 00 00
123.451 2R11 402 FD 04 04 0F 10 00 00 07
123.461 2R11 318 92 08 33 0D 07 00 00 00
tokens:
0 = timestamp
1 = line type
2 = ID
3-x = The data bytes
*/
bool FrameFileIO::loadCRTDFile(QString filename, QVector<CANFrame>* frames)
{
QFile *inFile = new QFile(filename);
CANFrame thisFrame;
QByteArray line;
int lineCounter = 0;
bool foundErrors = false;
if (!inFile->open(QIODevice::ReadOnly | QIODevice::Text))
{
delete inFile;
return false;
}
line = inFile->readLine().toUpper(); //read out the header first and discard it.
while (!inFile->atEnd()) {
lineCounter++;
if (lineCounter > 100)
{
qApp->processEvents();
lineCounter = 0;
}
line = inFile->readLine().simplified();
if (line.length() > 2)
{
QList<QByteArray> tokens = line.split(' ');
int multiplier;
if (tokens.length() > 2)
{
int idxOfDecimal = tokens[0].indexOf('.');
if (idxOfDecimal > -1) {
//int decimalPlaces = tokens[0].length() - tokens[0].indexOf('.') - 1;
//the result of the above is the # of digits after the decimal.
//This program deals in microsecond so turn the value into microseconds
multiplier = 1000000; //turn the decimal into full microseconds
}
else
{
multiplier = 1; //special case. Assume no decimal means microseconds
}
//qDebug() << "decimal places " << decimalPlaces;
thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast<int64_t>((tokens[0].toDouble() * multiplier))));
thisFrame.bus = 0;
char firstChar = tokens[1].left(1)[0];
if (firstChar >= '1' && firstChar <= '9')
{
thisFrame.bus = tokens[1].left(1)[0] - '1';
tokens[1].remove(0,1); // Remove leading digit (bus number)
firstChar = tokens[1].left(1)[0];
}
if (firstChar == 'R' || firstChar == 'T')
{
thisFrame.setFrameId(static_cast<uint32_t>(tokens[2].toInt(nullptr, 16)));
if (tokens[1] == "R29" || tokens[1] == "T29") thisFrame.setExtendedFrameFormat(true);
else thisFrame.setExtendedFrameFormat(false);
if (firstChar == 'T') thisFrame.isReceived = false;
else thisFrame.isReceived = true;
QByteArray bytes(tokens.length() - 3, 0);
thisFrame.setFrameType(QCanBusFrame::DataFrame);
for (int d = 0; d < bytes.length(); d++)
{
if (tokens[d + 3] != "")
{
bytes[d] = static_cast<char>(tokens[d + 3].toInt(nullptr, 16));
}
else bytes[d] = 0;
}
thisFrame.setPayload(bytes);
frames->append(thisFrame);
}
}
else foundErrors = true;
}
}
inFile->close();
delete inFile;
return !foundErrors;
}
bool FrameFileIO::isCARBUSAnalyzerFile(QString filename)
{
QFile *inFile = new QFile(filename);
QByteArray line;
bool isMatch = false;
// not Text mode because file contains `\r` new lines
if (!inFile->open(QIODevice::ReadOnly))
{
delete inFile;
return false;
}
try
{
//read header
line = inFile->readLine().toUpper();
if (line.startsWith("@ TEXT @")) return true;
} catch (...)
{
isMatch = false;
}
inFile->close();
delete inFile;
return isMatch;
}
// CARBUS Analayzer trace format https://canhacker.ru/can-trace-format/ :
// header
//@ TEXT @ 2 @ 64 @ 0 @ 591 @ 38782 @ 00:00:38.782 @
// 2 - format version
//14,687 1 0004 4E0 8 24 00 00 00 00 00 00 00 00000000 $
// timestamp: sec,ms - for version 2
// sec,us - for version 3
bool FrameFileIO::loadCARBUSAnalyzerFile(QString filename, QVector<CANFrame>* frames)
{
QFile *inFile = new QFile(filename);
if (!inFile->open(QIODevice::ReadOnly))
{
delete inFile;
return false;
}
CANFrame thisFrame;
QString line;
int lineCounter = 0;
bool foundErrors = false;
// readLine() works only with "\n" and "\r\n"
QString localReadAll = inFile->readAll().replace("\r", "\r\n");
QTextStream txt(&localReadAll);
line = txt.readLine().toUpper(); //read out the header
int version = 3; // current default
QRegularExpression re("@ TEXT @ (?<version>\\d) @.*");
QRegularExpressionMatch match = re.match(line);
if (match.hasMatch()) {
version = match.captured("version").toInt();
}
while (!txt.atEnd()) {
lineCounter++;
if (lineCounter > 100)
{
qApp->processEvents();
lineCounter = 0;
}
line = txt.readLine().simplified();
if (line.length() > 2)
{
QList<QString> tokens = line.split(QRegularExpression("\\s+"));
if (tokens.length() > 3)
{
QString time = tokens[0].replace(",", "");
int64_t timeStamp = time.toInt();
if (version == 2) {
timeStamp *= 1000; // ms -> us
}
thisFrame.isReceived = true;
thisFrame.setFrameType(QCanBusFrame::DataFrame);
thisFrame.setTimeStamp(QCanBusFrame::TimeStamp(0, static_cast<int64_t>(timeStamp)));
thisFrame.bus = tokens[1].toInt();
thisFrame.setFrameId(static_cast<uint32_t>(tokens[3].toInt(nullptr, 16)));
thisFrame.setExtendedFrameFormat(thisFrame.frameId() > 0x7FF);
int numBytes = tokens[4].toInt(nullptr, 16);
QByteArray bytes(numBytes , 0);
for (int d = 0; d < numBytes; d++)
{
if (tokens[d + 5] != "")
{
bytes[d] = static_cast<unsigned char>(tokens[d + 5].toInt(nullptr, 16));
}
else bytes[d] = 0;
}
thisFrame.setPayload(bytes);
frames->append(thisFrame);
}
else
{
foundErrors = true;
}
}
}
inFile->close();
delete inFile;
return !foundErrors;
}
bool FrameFileIO::saveCARBUSAnalzyer(QString filename, const QVector<CANFrame>* frames)
{
QFile *outFile = new QFile(filename);
if (!outFile->open(QIODevice::WriteOnly | QIODevice::Text))
{
delete outFile;
return false;
}
QTextStream outTextStream(outFile);
int lineCounter = 0;
qint64 minTime = frames->at(0).timeStamp().microSeconds();
qint64 maxTime = minTime;
for (int c = 0; c < frames->count(); c++)
{
if (frames->at(c).timeStamp().microSeconds() < minTime) minTime = frames->at(c).timeStamp().microSeconds();
if (frames->at(c).timeStamp().microSeconds() > maxTime) maxTime = frames->at(c).timeStamp().microSeconds();
}
qint64 totalTime = maxTime - minTime;
// looks like a bug in CARBUS format for 3 version. time is in ms, while packets in us.
totalTime /= 1000;
QTime someTime(0,0,0);
someTime = someTime.addMSecs(totalTime);
// header:
// @see #loadCARBUSAnalyzer()
// 14012 = number of packets
// 15688 = max time - start time in ms
//
// "@ TEXT @ 3 @ 64 @ 0 @ 14012 @ 15688 @ 00:00:15.688 @"
// saving in version format 3 with microseconds in packets time
outTextStream << "@ TEXT @ 3 @ 64 @ 0 @ " << frames->count() << " @ " << totalTime
<<" @ " << someTime.toString("hh:mm:ss.zzz") <<" @\r";
const unsigned char *data;
for (int c = 0; c < frames->count(); c++)
{
lineCounter++;
if (lineCounter > 100)
{
qApp->processEvents();
lineCounter = 0;
}
auto frame = frames->at(c);
uint64_t timeStamp = frame.timeStamp().microSeconds();
QString canId = QString::number(frame.frameId(), 16).toUpper().rightJustified(3, '0').toUtf8();
QString canDlc = QString::number(frame.payload().length()).toUtf8();
QString ascii = "";
QString finalCanData;
data = reinterpret_cast<const unsigned char *>(frame.payload().constData());
for (int d = 0; d < frame.payload().length(); d++)
{
auto octet = data[d];
finalCanData.append(QString::number(octet, 16).toUpper().rightJustified(2, '0').toUtf8());
finalCanData.append(" ");
QString strCode = QString::number(octet, 16);
bool conv;
uint symbolCode = strCode.toInt(&conv, 16);
if ((symbolCode >= 32 && symbolCode < 126)) {
QChar localQChar = QChar(symbolCode);
if (localQChar.toLatin1() != 0) {
ascii += QString::fromLocal8Bit(QByteArray::fromHex(strCode.toLatin1()));
}
} else {
ascii += " ";
}
}
finalCanData = finalCanData.trimmed().leftJustified(23, ' ');
ascii = ascii.leftJustified(8, ' ');
auto seconds = QString::number(timeStamp / 1000000);
auto uSeconds = QString::number(timeStamp % 1000000);
QString localArg = "";
localArg.append(seconds).append(",").append(uSeconds).append("\t")
.append(QString::number(frame.bus)).append("\t") // bus channel
.append("0004").append("\t") // it's CAN frame
.append(canId).append("\t")
.append(canDlc).append("\t")
.append(finalCanData).append("\t")
.append("00000000").append("\t")
.append(ascii).append("\t")
.append("\r");
qDebug() << localArg;
outTextStream << localArg;
}