-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathcarclient.cpp
1012 lines (854 loc) · 27.9 KB
/
carclient.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
/*
Copyright 2016-2017 Benjamin Vedder benjamin@vedder.se
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "carclient.h"
#include <QDebug>
#include <QDateTime>
#include <QDir>
#include <sys/time.h>
#include <sys/reboot.h>
#include <unistd.h>
#include <QEventLoop>
#include <QCoreApplication>
#include <QNetworkInterface>
#include <QBuffer>
#include "rtcm3_simple.h"
namespace {
void rtcm_rx(uint8_t *data, int len, int type) {
if (CarClient::currentMsgHandler) {
QByteArray rtcm_data((const char*)data, len);
CarClient::currentMsgHandler->rtcmRx(rtcm_data, type);
}
}
}
// Static member initialization
CarClient *CarClient::currentMsgHandler = 0;
rtcm3_state CarClient::rtcmState;
CarClient::CarClient(QObject *parent) : QObject(parent)
{
mSettings.nmeaConnect = false;
mSettings.serialConnect = false;
mSettings.serialRtcmConnect = false;
mSerialPort = new SerialPort(this);
mSerialPortRtcm = new QSerialPort(this);
mPacketInterface = new PacketInterface(this);
mRtcmBroadcaster = new TcpBroadcast(this);
mUbxBroadcaster = new TcpBroadcast(this);
mLogBroadcaster = new TcpBroadcast(this);
mUblox = new Ublox(this);
mTcpSocket = new QTcpSocket(this);
mTcpServer = new TcpServerSimple(this);
mRtcmClient = new RtcmClient(this);
mCarId = 255;
mReconnectTimer = new QTimer(this);
mReconnectTimer->start(2000);
mTcpConnected = false;
mLogFlushTimer = new QTimer(this);
mLogFlushTimer->start(2000);
mRtklibRunning = false;
mBatteryCells = 10;
mCarIdToSet = -1;
mOverrideUwbPos = false;
mOverrideUwbX = 0.0;
mOverrideUwbY = 0.0;
mHostAddress = QHostAddress("0.0.0.0");
mUdpPort = 0;
mUdpSocket = new QUdpSocket(this);
mRtcmBaseLat = 0.0;
mRtcmBaseLon = 0.0;
mRtcmBaseHeight = 0.0;
mRtcmSendBase = false;
currentMsgHandler = this;
rtcm3_init_state(&rtcmState);
rtcm3_set_rx_callback(rtcm_rx, &rtcmState);
mTcpServer->setUsePacket(true);
connect(mSerialPort, SIGNAL(serial_data_available()),
this, SLOT(serialDataAvailable()));
connect(mSerialPort, SIGNAL(serial_port_error(int)),
this, SLOT(serialPortError(int)));
connect(mSerialPortRtcm, SIGNAL(readyRead()),
this, SLOT(serialRtcmDataAvailable()));
connect(mSerialPortRtcm, SIGNAL(error(QSerialPort::SerialPortError)),
this, SLOT(serialRtcmPortError(QSerialPort::SerialPortError)));
connect(mTcpSocket, SIGNAL(readyRead()), this, SLOT(tcpDataAvailable()));
connect(mTcpSocket, SIGNAL(connected()), this, SLOT(tcpConnected()));
connect(mTcpSocket, SIGNAL(disconnected()), this, SLOT(tcpDisconnected()));
connect(mPacketInterface, SIGNAL(rtcmUsbReceived(quint8,QByteArray)),
this, SLOT(rtcmUsbRx(quint8,QByteArray)));
connect(mPacketInterface, SIGNAL(dataToSend(QByteArray&)),
this, SLOT(packetDataToSend(QByteArray&)));
connect(mReconnectTimer, SIGNAL(timeout()),
this, SLOT(reconnectTimerSlot()));
connect(mUdpSocket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
connect(mPacketInterface, SIGNAL(packetReceived(quint8,CMD_PACKET,QByteArray)),
this, SLOT(carPacketRx(quint8,CMD_PACKET,QByteArray)));
connect(mPacketInterface, SIGNAL(logLineUsbReceived(quint8,QString)),
this, SLOT(logLineUsbReceived(quint8,QString)));
connect(mLogFlushTimer, SIGNAL(timeout()),
this, SLOT(logFlushTimerSlot()));
connect(mPacketInterface, SIGNAL(systemTimeReceived(quint8,qint32,qint32)),
this, SLOT(systemTimeReceived(quint8,qint32,qint32)));
connect(mPacketInterface, SIGNAL(rebootSystemReceived(quint8,bool)),
this, SLOT(rebootSystemReceived(quint8,bool)));
connect(mUblox, SIGNAL(ubxRx(QByteArray)), this, SLOT(ubxRx(QByteArray)));
connect(mUblox, SIGNAL(rxRawx(ubx_rxm_rawx)), this, SLOT(rxRawx(ubx_rxm_rawx)));
connect(mTcpServer->packet(), SIGNAL(packetReceived(QByteArray&)),
this, SLOT(tcpRx(QByteArray&)));
connect(mTcpServer, SIGNAL(connectionChanged(bool,QString)),
this, SLOT(tcpConnectionChanged(bool,QString)));
connect(mRtcmClient, SIGNAL(rtcmReceived(QByteArray,int,bool)),
this, SLOT(rtcmReceived(QByteArray,int,bool)));
connect(mPacketInterface, SIGNAL(logEthernetReceived(quint8,QByteArray)),
this, SLOT(logEthernetReceived(quint8,QByteArray)));
connect(mLogBroadcaster, SIGNAL(dataReceived(QByteArray&)),
this, SLOT(logBroadcasterDataReceived(QByteArray&)));
#if HAS_CAMERA
mCameraJpgQuality = -1;
mCameraSkipFrames = 0;
mCameraSkipFrameCnt = 0;
mCameraNoAckCnt = 0;
mCamera = new Camera(this);
connect(mCamera->video(), SIGNAL(imageCaptured(QImage)),
this, SLOT(cameraImageCaptured(QImage)));
#endif
}
CarClient::~CarClient()
{
logStop();
}
void CarClient::connectSerial(QString port, int baudrate)
{
if(mSerialPort->isOpen()) {
mSerialPort->closePort();
}
mSerialPort->openPort(port, baudrate);
mSettings.serialConnect = true;
mSettings.serialPort = port;
mSettings.serialBaud = baudrate;
if(!mSerialPort->isOpen()) {
return;
}
qDebug() << "Serial port connected";
mPacketInterface->stopUdpConnection();
mPacketInterface->getState(255); // To get car ID
}
void CarClient::connectSerialRtcm(QString port, int baudrate)
{
if(mSerialPortRtcm->isOpen()) {
mSerialPortRtcm->close();
}
mSerialPortRtcm->setPortName(port);
mSerialPortRtcm->open(QIODevice::ReadWrite);
mSettings.serialRtcmConnect = true;
mSettings.serialRtcmPort = port;
mSettings.serialRtcmBaud = baudrate;
if(!mSerialPortRtcm->isOpen()) {
return;
}
qDebug() << "Serial port RTCM connected";
mSerialPortRtcm->setBaudRate(baudrate);
mSerialPortRtcm->setDataBits(QSerialPort::Data8);
mSerialPortRtcm->setParity(QSerialPort::NoParity);
mSerialPortRtcm->setStopBits(QSerialPort::OneStop);
mSerialPortRtcm->setFlowControl(QSerialPort::NoFlowControl);
}
void CarClient::startRtcmServer(int port)
{
mRtcmBroadcaster->startTcpServer(port);
}
void CarClient::startUbxServer(int port)
{
mUbxBroadcaster->startTcpServer(port);
}
void CarClient::startLogServer(int port)
{
mLogBroadcaster->startTcpServer(port);
}
void CarClient::connectNmea(QString server, int port)
{
mTcpSocket->close();
mTcpSocket->connectToHost(server, port);
mSettings.nmeaConnect = true;
mSettings.nmeaServer = server;
mSettings.nmeaPort = port;
}
void CarClient::startUdpServer(int port)
{
mUdpPort = port + 1;
mUdpSocket->close();
mUdpSocket->bind(QHostAddress::Any, port);
}
bool CarClient::startTcpServer(int port, QHostAddress addr)
{
bool res = mTcpServer->startServer(port,addr);
if (!res) {
qWarning() << "Starting TCP server failed:" << mTcpServer->errorString();
}
return res;
}
bool CarClient::enableLogging(QString directory)
{
if (mLog.isOpen()) {
mLog.close();
}
QString name = QDateTime::currentDateTime().
toString("LOG_yyyy-MM-dd_hh.mm.ss.log");
QDir dir;
dir.mkpath(directory);
mLog.setFileName(directory + "/" + name);
return mLog.open(QIODevice::ReadWrite | QIODevice::Truncate);
}
void CarClient::logStop()
{
if (mLog.isOpen()) {
qDebug() << "Closing log:" << mLog.fileName();
mLog.close();
} else {
qDebug() << "Log not open";
}
}
void CarClient::rtcmRx(QByteArray data, int type)
{
(void)type;
QString str;
// Print the packet in the car terminal. NOTE: This is for debugging
for (int i = 0;i < data.size();i++) {
str.append(QString().sprintf("%02X ", data.at(i)));
if (i >= 50) {
break;
}
}
printTerminal(str);
}
void CarClient::restartRtklib()
{
QFile ublox("/dev/ublox");
if (!ublox.exists()) {
mRtklibRunning = false;
return;
}
mRtklibRunning = true;
mUblox->disconnectSerial();
if (mUblox->connectSerial(ublox.fileName())) {
// Serial port baud rate
// if it is too low the buffer will overfill and it won't work properly.
ubx_cfg_prt_uart uart;
uart.baudrate = 115200;
uart.in_ubx = true;
uart.in_nmea = true;
uart.in_rtcm2 = false;
uart.in_rtcm3 = true;
uart.out_ubx = true;
uart.out_nmea = true;
uart.out_rtcm3 = true;
mUblox->ubxCfgPrtUart(&uart);
// Set configuration
// Switch on RAWX and NMEA messages, set rate to 1 Hz and time reference to UTC
mUblox->ubxCfgRate(200, 1, 0);
mUblox->ubxCfgMsg(UBX_CLASS_RXM, UBX_RXM_RAWX, 1); // Every second
mUblox->ubxCfgMsg(UBX_CLASS_RXM, UBX_RXM_SFRBX, 1); // Every second
mUblox->ubxCfgMsg(UBX_CLASS_NMEA, UBX_NMEA_GGA, 1); // Every second
// Automotive dynamic model
ubx_cfg_nav5 nav5;
memset(&nav5, 0, sizeof(ubx_cfg_nav5));
nav5.apply_dyn = true;
nav5.dyn_model = 4;
mUblox->ubxCfgNav5(&nav5);
// Time pulse configuration
ubx_cfg_tp5 tp5;
memset(&tp5, 0, sizeof(ubx_cfg_tp5));
tp5.active = true;
tp5.polarity = true;
tp5.alignToTow = true;
tp5.lockGnssFreq = true;
tp5.lockedOtherSet = true;
tp5.syncMode = false;
tp5.isFreq = false;
tp5.isLength = true;
tp5.freq_period = 1000000;
tp5.pulse_len_ratio = 0;
tp5.freq_period_lock = 1000000;
tp5.pulse_len_ratio_lock = 100000;
tp5.gridUtcGnss = 0;
tp5.user_config_delay = 0;
tp5.rf_group_delay = 0;
tp5.ant_cable_delay = 50;
mUblox->ubloxCfgTp5(&tp5);
}
QString user = qgetenv("USER");
if (user.isEmpty()) {
user = qgetenv("USERNAME");
}
if (user.isEmpty()) {
QProcess process;
process.setEnvironment(QProcess::systemEnvironment());
process.start("whoami");
waitProcess(process);
user = QString(process.readAllStandardOutput());
user.replace("\n", "");
}
QProcess process;
process.setEnvironment(QProcess::systemEnvironment());
process.start("screen", QStringList() <<
"-X" << "-S" << "rtklib" << "quit");
waitProcess(process);
QProcess process2;
process2.setEnvironment(QProcess::systemEnvironment());
process2.start("killall", QStringList() << "rtkrcv");
waitProcess(process2);
QProcess process3;
process3.setEnvironment(QProcess::systemEnvironment());
process3.start("screen", QStringList() <<
"-d" << "-m" << "-S" << "rtklib" << "bash" << "-c" <<
QString("cd /home/%1/rise_sdvp/Linux/RTK/rtkrcv_arm && ./start_ublox ; bash").arg(user));
waitProcess(process3);
}
PacketInterface *CarClient::packetInterface()
{
return mPacketInterface;
}
bool CarClient::isRtklibRunning()
{
return mRtklibRunning;
}
quint8 CarClient::carId()
{
return mCarId;
}
void CarClient::setCarId(quint8 id)
{
mCarId = id;
}
void CarClient::connectNtrip(QString server, QString stream, QString user, QString pass, int port)
{
mRtcmClient->connectNtrip(server, stream, user, pass, port);
}
void CarClient::setSendRtcmBasePos(bool send, double lat, double lon, double height)
{
mRtcmSendBase = send;
mRtcmBaseLat = lat;
mRtcmBaseLon = lon;
mRtcmBaseHeight = height;
}
void CarClient::rebootSystem(bool powerOff)
{
// https://askubuntu.com/questions/159007/how-do-i-run-specific-sudo-commands-without-a-password
QStringList args;
QString cmd = "sudo";
if (powerOff) {
args << "shutdown" << "-h" << "now";
} else {
args << "reboot";
}
QProcess process;
process.setEnvironment(QProcess::systemEnvironment());
process.start(cmd, args);
waitProcess(process);
qApp->quit();
}
QVariantList CarClient::getNetworkAddresses()
{
QVariantList res;
for(QHostAddress a: QNetworkInterface::allAddresses()) {
if(!a.isLoopback()) {
if (a.protocol() == QAbstractSocket::IPv4Protocol) {
res << a.toString();
}
}
}
return res;
}
int CarClient::getBatteryCells()
{
return mBatteryCells;
}
void CarClient::setBatteryCells(int cells)
{
mBatteryCells = cells;
}
void CarClient::addSimulatedCar(int id)
{
CarSim *car = new CarSim(this);
car->setId(id);
connect(car, SIGNAL(dataToSend(QByteArray)), this, SLOT(processCarData(QByteArray)));
mSimulatedCars.append(car);
}
CarSim *CarClient::getSimulatedCar(int id)
{
CarSim *sim = 0;
for (CarSim *s: mSimulatedCars) {
if (s->id() == id) {
sim = s;
break;
}
}
return sim;
}
void CarClient::serialDataAvailable()
{
while (mSerialPort->bytesAvailable() > 0) {
processCarData(mSerialPort->readAll());
}
}
void CarClient::serialPortError(int error)
{
qDebug() << "Serial error:" << error;
if(mSerialPort->isOpen()) {
mSerialPort->closePort();
}
}
void CarClient::serialRtcmDataAvailable()
{
while (mSerialPortRtcm->bytesAvailable() > 0) {
QByteArray data = mSerialPortRtcm->readAll();
for (int i = 0;i < data.size();i++) {
rtcm3_input_data((uint8_t)data.at(i), &rtcmState);
}
}
}
void CarClient::serialRtcmPortError(QSerialPort::SerialPortError error)
{
QString message;
switch (error) {
case QSerialPort::NoError:
break;
case QSerialPort::DeviceNotFoundError:
message = tr("Device not found");
break;
case QSerialPort::OpenError:
message = tr("Can't open device");
break;
case QSerialPort::NotOpenError:
message = tr("Not open error");
break;
case QSerialPort::ResourceError:
message = tr("Port disconnected");
break;
case QSerialPort::PermissionError:
message = tr("Permission error");
break;
case QSerialPort::UnknownError:
message = tr("Unknown error");
break;
default:
message = "Error number: " + QString::number(error);
break;
}
if(!message.isEmpty()) {
qDebug() << "Serial error:" << message;
if(mSerialPortRtcm->isOpen()) {
mSerialPortRtcm->close();
}
}
}
void CarClient::packetDataToSend(QByteArray &data)
{
// This is a packet from RControlStation going to the car.
// Inspect data and possibly process it here.
bool packetConsumed = false;
VByteArray vb(data);
vb.remove(0, data[0]);
quint8 id = vb.vbPopFrontUint8();
CMD_PACKET cmd = (CMD_PACKET)vb.vbPopFrontUint8();
vb.chop(3);
(void)id;
if (id == mCarId || id == 255) {
if (cmd == CMD_CAMERA_STREAM_START) {
#if HAS_CAMERA
int camera = vb.vbPopFrontInt16();
mCameraJpgQuality = vb.vbPopFrontInt16();
int width = vb.vbPopFrontInt16();
int height = vb.vbPopFrontInt16();
int fps = vb.vbPopFrontInt16();
mCameraSkipFrames = vb.vbPopFrontInt16();
mCameraNoAckCnt = 0;
mCamera->closeCamera();
if (camera >= 0) {
mCamera->openCamera(camera);
mCamera->startCameraStream(width, height, fps);
}
} else if (cmd == CMD_CAMERA_FRAME_ACK) {
mCameraNoAckCnt--;
#endif
} else if (cmd == CMD_TERMINAL_CMD) {
QString str(vb);
if (str == "help") {
#if HAS_CAMERA
printTerminal("camera_info\n"
" Print information about the available camera.");
#endif
} else if (str == "camera_info") {
#if HAS_CAMERA
bool res = true;
if (!mCamera->isLoaded()) {
res = mCamera->openCamera();
}
if (res) {
printTerminal(mCamera->cameraInfo());
} else {
printTerminal("No camera available.");
}
packetConsumed = true;
#endif
}
} else if (cmd == CMD_CLEAR_UWB_ANCHORS) {
mUwbAnchorsNow.clear();
} else if (cmd == CMD_ADD_UWB_ANCHOR) {
UWB_ANCHOR a;
a.id = vb.vbPopFrontInt16();
a.px = vb.vbPopFrontDouble32Auto();
a.py = vb.vbPopFrontDouble32Auto();
a.height = vb.vbPopFrontDouble32Auto();
mUwbAnchorsNow.append(a);
}
}
if (!packetConsumed) {
if (mSerialPort->isOpen()) {
mSerialPort->writeData(data);
}
for (CarSim *s: mSimulatedCars) {
s->processData(data);
}
}
}
void CarClient::tcpDataAvailable()
{
while (!mTcpSocket->atEnd()) {
QByteArray data = mTcpSocket->readAll();
// TODO: Collect data and split at newline. (seems ok)
mPacketInterface->sendNmeaRadio(mCarId, data);
}
}
void CarClient::tcpConnected()
{
qDebug() << "NMEA TCP Connected";
mTcpConnected = true;
}
void CarClient::tcpDisconnected()
{
qDebug() << "NMEA TCP Disconnected";
mTcpConnected = false;
}
void CarClient::rtcmUsbRx(quint8 id, QByteArray data)
{
mCarId = id;
mRtcmBroadcaster->broadcastData(data);
}
void CarClient::reconnectTimerSlot()
{
// Try to reconnect if the connections are lost
if (mSettings.serialConnect && !mSerialPort->isOpen()) {
qDebug() << "Trying to reconnect serial...";
connectSerial(mSettings.serialPort, mSettings.serialBaud);
}
if (mSettings.serialRtcmConnect && !mSerialPortRtcm->isOpen()) {
qDebug() << "Trying to reconnect RTCM serial...";
connectSerialRtcm(mSettings.serialRtcmPort, mSettings.serialRtcmBaud);
}
if (mSettings.nmeaConnect && !mTcpConnected) {
qDebug() << "Trying to reconnect nmea tcp...";
connectNmea(mSettings.nmeaServer, mSettings.nmeaPort);
}
if ((mRtcmClient->isTcpConnected() || mRtcmClient->isSerialConnected()) && mRtcmSendBase) {
mPacketInterface->sendRtcmUsb(255, mRtcmClient->encodeBasePos(mRtcmBaseLat,
mRtcmBaseLon,
mRtcmBaseHeight,
0.0));
}
// Set ID of board on regular basis. In case reprogramming is done.
if (mSerialPort->isOpen() && mCarIdToSet >= 0 && mCarIdToSet < 255) {
mPacketInterface->sendTerminalCmd(255, QString("set_id_quiet %1").arg(mCarIdToSet));
}
}
void CarClient::logFlushTimerSlot()
{
if (mLog.isOpen()) {
mLog.flush();
}
}
void CarClient::readPendingDatagrams()
{
while (mUdpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(mUdpSocket->pendingDatagramSize());
quint16 senderPort;
mUdpSocket->readDatagram(datagram.data(), datagram.size(),
&mHostAddress, &senderPort);
mPacketInterface->sendPacket(datagram);
}
}
void CarClient::carPacketRx(quint8 id, CMD_PACKET cmd, const QByteArray &data)
{
QByteArray toSend = data;
if (cmd == CMD_GET_STATE && mOverrideUwbPos) {
VByteArray vb;
vb.append(data.mid(0, 99));
vb.vbAppendDouble32(mOverrideUwbX, 1e4);
vb.vbAppendDouble32(mOverrideUwbY, 1e4);
toSend = vb;
}
if (id != 254) {
mCarId = id;
if (QString::compare(mHostAddress.toString(), "0.0.0.0") != 0) {
mUdpSocket->writeDatagram(toSend, mHostAddress, mUdpPort);
}
mTcpServer->packet()->sendPacket(toSend);
}
}
void CarClient::logLineUsbReceived(quint8 id, QString str)
{
(void)id;
if (mLog.isOpen()) {
mLog.write(str.toLocal8Bit());
}
}
void CarClient::systemTimeReceived(quint8 id, qint32 sec, qint32 usec)
{
(void)id;
(void)usec;
// struct timeval now;
// int rc;
// now.tv_sec = sec;
// now.tv_usec = usec;
// rc = settimeofday(&now, NULL);
if(setUnixTime(sec)) {
qDebug() << "Sucessfully set system time";
restartRtklib();
} else {
qDebug() << "Setting system time failed";
}
}
void CarClient::rebootSystemReceived(quint8 id, bool powerOff)
{
(void)id;
logStop();
sync();
// if (powerOff) {
// reboot(RB_POWER_OFF);
// } else {
// reboot(RB_AUTOBOOT);
// }
rebootSystem(powerOff);
}
void CarClient::ubxRx(const QByteArray &data)
{
mUbxBroadcaster->broadcastData(data);
}
void CarClient::rxRawx(ubx_rxm_rawx rawx)
{
if (!rawx.leap_sec) {
// Leap seconds are not known...
return;
}
QDateTime dateGps(QDate(1980, 1, 6), QTime(0, 0, 0));
dateGps.setOffsetFromUtc(0);
dateGps = dateGps.addDays(rawx.week * 7);
dateGps = dateGps.addMSecs((rawx.rcv_tow - (double)rawx.leaps) * 1000.0);
QDateTime date = QDateTime::currentDateTime();
qint64 diff = dateGps.toMSecsSinceEpoch() - date.toMSecsSinceEpoch();
if (abs(diff) > 60000) {
// Set the system time if the difference is over 10 seconds.
qDebug() << "System time is different from GPS time. Difference: " << diff << " ms";
// struct timeval now;
// int rc;
// now.tv_sec = dateGps.toTime_t();
// now.tv_usec = dateGps.time().msec() * 1000.0;
// rc = settimeofday(&now, NULL);
if(setUnixTime(dateGps.toTime_t())) {
qDebug() << "Sucessfully updated system time";
restartRtklib();
} else {
qDebug() << "Setting system time failed";
}
}
}
void CarClient::tcpRx(QByteArray &data)
{
mPacketInterface->sendPacket(data);
}
void CarClient::tcpConnectionChanged(bool connected, QString address)
{
if (connected) {
qDebug() << "TCP connection from" << address << "accepted";
} else {
qDebug() << "Disconnected TCP from" << address;
}
}
void CarClient::rtcmReceived(QByteArray data, int type, bool sync)
{
(void)type;
(void)sync;
mPacketInterface->sendRtcmUsb(255, data);
}
void CarClient::logEthernetReceived(quint8 id, QByteArray data)
{
(void)id;
mLogBroadcaster->broadcastData(data);
}
void CarClient::processCarData(QByteArray data)
{
mPacketInterface->processData(data);
}
void CarClient::cameraImageCaptured(QImage img)
{
#if HAS_CAMERA
if (mCameraSkipFrames > 0) {
mCameraSkipFrameCnt++;
if (mCameraSkipFrameCnt <= mCameraSkipFrames) {
return;
}
}
// No ack has been received for a couple of frames, meaning that
// the connection probably is bad. Drop frame.
if (mCameraNoAckCnt >= 3) {
return;
}
mCameraSkipFrameCnt = 0;
QByteArray data;
data.append((quint8)mCarId);
data.append((char)CMD_CAMERA_IMAGE);
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
img.save(&buffer, "jpg", mCameraJpgQuality);
buffer.close();
data.append(buffer.buffer());
if (data.size() > 100) {
carPacketRx(mCarId, CMD_CAMERA_IMAGE, data);
mCameraNoAckCnt++;
}
#else
(void)img;
#endif
}
void CarClient::logBroadcasterDataReceived(QByteArray &data)
{
mLogBroadcasterDataBuffer.append(data);
int newLineIndex = mLogBroadcasterDataBuffer.indexOf("\n");
while (newLineIndex >= 0) {
QString line = mLogBroadcasterDataBuffer.left(newLineIndex);
mLogBroadcasterDataBuffer.remove(0, newLineIndex + 1);
QStringList tokens = line.split(" ");
if (tokens.at(0) == "plot_init") {
if (tokens.size() == 3) {
QByteArray data;
data.append((quint8)mCarId);
data.append((char)CMD_PLOT_INIT);
data.append(tokens.at(1).toLocal8Bit());
data.append('\0');
data.append(tokens.at(2).toLocal8Bit());
data.append('\0');
carPacketRx(mCarId, CMD_PLOT_INIT, data);
}
} else if (tokens.at(0) == "plot_add_graph") {
if (tokens.size() == 2) {
QByteArray data;
data.append((quint8)mCarId);
data.append((char)CMD_PLOT_ADD_GRAPH);
data.append(tokens.at(1).toLocal8Bit());
data.append('\0');
carPacketRx(mCarId, CMD_PLOT_ADD_GRAPH, data);
}
} else if (tokens.at(0) == "plot_set_graph") {
if (tokens.size() == 2) {
QByteArray data;
data.append((quint8)mCarId);
data.append((char)CMD_PLOT_SET_GRAPH);
data.append(tokens.at(1).toInt());
data.append('\0');
carPacketRx(mCarId, CMD_PLOT_SET_GRAPH, data);
}
} else if (tokens.at(0) == "plot_add_sample") {
if (tokens.size() == 3) {
VByteArray data;
data.append((quint8)mCarId);
data.append((char)CMD_PLOT_DATA);
data.vbAppendDouble32Auto(tokens.at(1).toDouble());
data.vbAppendDouble32Auto(tokens.at(2).toDouble());
carPacketRx(mCarId, CMD_PLOT_DATA, data);
}
} else if (tokens.at(0) == "uwb_pos_override") {
if (tokens.size() == 3) {
mOverrideUwbPos = true;
mOverrideUwbX = tokens.at(1).toDouble();
mOverrideUwbY = tokens.at(2).toDouble();
}
} else if (tokens.at(0) == "uwb_pos_override_stop") {
if (tokens.size() == 1) {
mOverrideUwbPos = false;
}
} else if (tokens.at(0) == "get_uwb_anchor_list") {
QString reply;
reply.append("anchors");
for (UWB_ANCHOR a: mUwbAnchorsNow) {
reply.append(QString(" %1 %2 %3 %4").
arg(a.id).
arg(a.px, 0, 'f', 3).
arg(a.py, 0, 'f', 3).
arg(a.height, 0, 'f', 3));
}
reply.append("\r\n");
mLogBroadcaster->broadcastData(reply.toLocal8Bit());
}
newLineIndex = mLogBroadcasterDataBuffer.indexOf("\n");
}
}
int CarClient::getCarIdToSet() const
{
return mCarIdToSet;
}
/**
* @brief CarClient::setCarIdToSet
* Set ID that the connected board will be updated with every 2 seconds.
*
* @param carIdToSet
* The ID.
*/
void CarClient::setCarIdToSet(int carIdToSet)
{
mCarIdToSet = carIdToSet;
}
bool CarClient::setUnixTime(qint64 t)
{
// https://askubuntu.com/questions/159007/how-do-i-run-specific-sudo-commands-without-a-password
QProcess process;
process.setEnvironment(QProcess::systemEnvironment());
process.start("sudo", QStringList() << "date" << "+%s" << "-s" << QString("@%1").arg(t));
return waitProcess(process, 5000);
}
void CarClient::printTerminal(QString str)
{
QByteArray packet;
packet.append((quint8)mCarId);
packet.append((char)CMD_PRINTF);
packet.append(str.toLocal8Bit());
carPacketRx(mCarId, CMD_PRINTF, packet);
}
bool CarClient::waitProcess(QProcess &process, int timeoutMs)
{
bool killed = false;
process.waitForStarted();
QEventLoop loop;
QTimer timeoutTimer;
timeoutTimer.setSingleShot(true);
timeoutTimer.start(timeoutMs);