Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
2398 lines (2151 loc) · 83.9 KB
/
Copy pathmain.cpp
File metadata and controls
2398 lines (2151 loc) · 83.9 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
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 <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QHash>
#include <QtCore/QMetaObject>
#include <QtCore/QSet>
#include <QtCore/QThread>
#include <QtCore/QTimer>
#include <QtCore/QElapsedTimer>
#include <QtCore/QVariant>
#include <QtCore/QVector>
#include <QtGui/QPainter>
#include <QtGui/QPainterPath>
#include <QtGui/QPen>
#include <QtGui/QMouseEvent>
#include <QtGui/QPixmap>
#include <QtGui/QWheelEvent>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QtWidgets/QApplication>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSizePolicy>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <stdexcept>
namespace {
constexpr uint8_t MavStxV1 = 0xFE;
constexpr uint8_t MavStxV2 = 0xFD;
constexpr uint8_t MavTypeGcs = 6;
constexpr uint8_t MavAutopilotInvalid = 8;
constexpr uint8_t MavStateActive = 4;
constexpr uint8_t MavFrameGlobalRelativeAltInt = 6;
constexpr uint8_t MavModeFlagCustomModeEnabled = 1;
constexpr uint8_t MavDataStreamExtendedStatus = 2;
constexpr uint8_t MavDataStreamPosition = 6;
constexpr uint8_t MavDataStreamExtra1 = 10;
constexpr uint8_t MavDataStreamExtra2 = 11;
constexpr uint8_t MavDataStreamExtra3 = 12;
constexpr uint8_t MspApiVersion = 1;
constexpr uint8_t MspFcVariant = 2;
constexpr uint8_t MspFcVersion = 3;
constexpr uint8_t MspStatus = 101;
constexpr uint8_t MspRawImu = 102;
constexpr uint8_t MspRawGps = 106;
constexpr uint8_t MspAttitude = 108;
constexpr uint8_t MspAltitude = 109;
constexpr uint8_t MspAnalog = 110;
constexpr uint8_t MspBatteryState = 130;
constexpr uint16_t MavCmdNavLand = 21;
constexpr uint16_t MavCmdNavTakeoff = 22;
constexpr uint16_t MavCmdNavReturnToLaunch = 20;
constexpr uint16_t MavCmdComponentArmDisarm = 400;
constexpr uint32_t ArduModeGuided = 4;
constexpr uint32_t ArduModeRtl = 6;
template <typename T>
T readLe(const QByteArray &data, int offset)
{
T value{};
if (offset < 0 || offset + int(sizeof(T)) > data.size()) {
return value;
}
std::memcpy(&value, data.constData() + offset, sizeof(T));
return value;
}
template <typename T>
void writeLe(QByteArray &data, int offset, T value)
{
if (offset < 0 || offset + int(sizeof(T)) > data.size()) {
return;
}
std::memcpy(data.data() + offset, &value, sizeof(T));
}
void crcAccumulate(uint8_t value, uint16_t &crc)
{
value ^= uint8_t(crc & 0xFF);
value ^= uint8_t(value << 4);
crc = uint16_t((crc >> 8) ^ (uint16_t(value) << 8) ^ (uint16_t(value) << 3) ^ (uint16_t(value) >> 4));
}
uint16_t mavCrc(const QByteArray &headerWithoutStx, const QByteArray &payload, uint8_t crcExtra)
{
uint16_t crc = 0xFFFF;
for (char b : headerWithoutStx) {
crcAccumulate(uint8_t(b), crc);
}
for (char b : payload) {
crcAccumulate(uint8_t(b), crc);
}
crcAccumulate(crcExtra, crc);
return crc;
}
uint8_t crcExtra(uint32_t msgId)
{
switch (msgId) {
case 0: return 50; // HEARTBEAT
case 1: return 124; // SYS_STATUS
case 11: return 89; // SET_MODE
case 24: return 24; // GPS_RAW_INT
case 30: return 39; // ATTITUDE
case 33: return 104; // GLOBAL_POSITION_INT
case 66: return 148; // REQUEST_DATA_STREAM
case 76: return 152; // COMMAND_LONG
case 77: return 143; // COMMAND_ACK
case 86: return 5; // SET_POSITION_TARGET_GLOBAL_INT
case 109: return 185; // RADIO_STATUS
case 253: return 83; // STATUSTEXT
default: return 0;
}
}
QString arduModeName(uint32_t customMode)
{
switch (customMode) {
case 0: return "STABILIZE";
case 1: return "ACRO";
case 2: return "ALT_HOLD";
case 3: return "AUTO";
case 4: return "GUIDED";
case 5: return "LOITER";
case 6: return "RTL";
case 7: return "CIRCLE";
case 9: return "LAND";
case 11: return "DRIFT";
case 13: return "SPORT";
case 14: return "FLIP";
case 15: return "AUTOTUNE";
case 16: return "POSHOLD";
case 17: return "BRAKE";
case 18: return "THROW";
case 19: return "AVOID_ADSB";
case 20: return "GUIDED_NOGPS";
case 21: return "SMART_RTL";
default: return QString("MODE %1").arg(customMode);
}
}
struct MavPacket {
uint32_t msgId = 0;
uint8_t sysId = 0;
uint8_t compId = 0;
QByteArray payload;
};
struct MspPacket {
uint8_t cmd = 0;
bool error = false;
QByteArray payload;
};
class MavParser {
public:
QList<MavPacket> push(const QByteArray &bytes)
{
buffer_.append(bytes);
if (buffer_.size() > maxBufferSize_) {
buffer_.remove(0, buffer_.size() - maxBufferSize_);
}
QList<MavPacket> packets;
while (!buffer_.isEmpty()) {
const uint8_t stx = uint8_t(buffer_.at(0));
if (stx != MavStxV1 && stx != MavStxV2) {
buffer_.remove(0, 1);
continue;
}
if (stx == MavStxV1) {
if (buffer_.size() < 8) {
break;
}
const int payloadLen = uint8_t(buffer_.at(1));
const int frameLen = 6 + payloadLen + 2;
if (buffer_.size() < frameLen) {
break;
}
QByteArray frame = buffer_.left(frameLen);
buffer_.remove(0, frameLen);
const uint32_t msgId = uint8_t(frame.at(5));
const QByteArray header = frame.mid(1, 5);
const QByteArray payload = frame.mid(6, payloadLen);
const uint16_t expected = readLe<uint16_t>(frame, 6 + payloadLen);
if (mavCrc(header, payload, crcExtra(msgId)) != expected) {
continue;
}
packets.append({msgId, uint8_t(frame.at(3)), uint8_t(frame.at(4)), payload});
continue;
}
if (buffer_.size() < 12) {
break;
}
const int payloadLen = uint8_t(buffer_.at(1));
const bool signedFrame = (uint8_t(buffer_.at(2)) & 0x01) != 0;
const int signatureLen = signedFrame ? 13 : 0;
const int frameLen = 10 + payloadLen + 2 + signatureLen;
if (buffer_.size() < frameLen) {
break;
}
QByteArray frame = buffer_.left(frameLen);
buffer_.remove(0, frameLen);
const uint32_t msgId = uint8_t(frame.at(7)) | (uint32_t(uint8_t(frame.at(8))) << 8) | (uint32_t(uint8_t(frame.at(9))) << 16);
const QByteArray header = frame.mid(1, 9);
const QByteArray payload = frame.mid(10, payloadLen);
const uint16_t expected = readLe<uint16_t>(frame, 10 + payloadLen);
if (mavCrc(header, payload, crcExtra(msgId)) != expected) {
continue;
}
packets.append({msgId, uint8_t(frame.at(5)), uint8_t(frame.at(6)), payload});
}
return packets;
}
void clear()
{
buffer_.clear();
}
private:
static constexpr int maxBufferSize_ = 8192;
QByteArray buffer_;
};
class MspParser {
public:
QList<MspPacket> push(const QByteArray &bytes)
{
buffer_.append(bytes);
if (buffer_.size() > maxBufferSize_) {
buffer_.remove(0, buffer_.size() - maxBufferSize_);
}
QList<MspPacket> packets;
while (buffer_.size() >= 6) {
if (uint8_t(buffer_.at(0)) != '$') {
buffer_.remove(0, 1);
continue;
}
if (buffer_.size() < 3) {
break;
}
if (uint8_t(buffer_.at(1)) != 'M') {
buffer_.remove(0, 1);
continue;
}
const uint8_t direction = uint8_t(buffer_.at(2));
if (direction != '>' && direction != '!') {
buffer_.remove(0, 1);
continue;
}
const int payloadLen = uint8_t(buffer_.at(3));
const int frameLen = 6 + payloadLen;
if (buffer_.size() < frameLen) {
break;
}
QByteArray frame = buffer_.left(frameLen);
buffer_.remove(0, frameLen);
uint8_t checksum = uint8_t(frame.at(3)) ^ uint8_t(frame.at(4));
const QByteArray payload = frame.mid(5, payloadLen);
for (char b : payload) {
checksum ^= uint8_t(b);
}
if (checksum != uint8_t(frame.at(5 + payloadLen))) {
continue;
}
packets.append({uint8_t(frame.at(4)), direction == '!', payload});
}
return packets;
}
void clear()
{
buffer_.clear();
}
private:
static constexpr int maxBufferSize_ = 8192;
QByteArray buffer_;
};
QByteArray makeV1Packet(uint8_t &seq, uint8_t sysId, uint8_t compId, uint8_t msgId, const QByteArray &payload)
{
QByteArray header;
header.append(char(payload.size()));
header.append(char(seq++));
header.append(char(sysId));
header.append(char(compId));
header.append(char(msgId));
const uint16_t crc = mavCrc(header, payload, crcExtra(msgId));
QByteArray packet;
packet.append(char(MavStxV1));
packet.append(header);
packet.append(payload);
packet.append(char(crc & 0xFF));
packet.append(char((crc >> 8) & 0xFF));
return packet;
}
QByteArray makeMspRequest(uint8_t cmd, const QByteArray &payload = QByteArray())
{
QByteArray packet;
packet.append('$');
packet.append('M');
packet.append('<');
packet.append(char(payload.size()));
packet.append(char(cmd));
uint8_t checksum = uint8_t(payload.size()) ^ cmd;
for (char b : payload) {
checksum ^= uint8_t(b);
packet.append(b);
}
packet.append(char(checksum));
return packet;
}
} // namespace
class DroneMapWidget : public QWidget {
public:
explicit DroneMapWidget(QWidget *parent = nullptr)
: QWidget(parent)
{
setMinimumHeight(420);
setMouseTracking(true);
network_ = new QNetworkAccessManager(this);
clockTimer_ = new QTimer(this);
clockTimer_->setInterval(1000);
connect(clockTimer_, &QTimer::timeout, this, [this]() {
update();
});
clockTimer_->start();
centerLat_ = 10.7769;
centerLon_ = 106.7009;
hasCenter_ = true;
}
void updatePosition(double lat, double lon, double alt)
{
currentLat_ = lat;
currentLon_ = lon;
currentAlt_ = alt;
const bool firstDronePosition = !hasPosition_;
hasPosition_ = true;
if (!hasHome_) {
homeLat_ = lat;
homeLon_ = lon;
hasHome_ = true;
}
if (firstDronePosition || !hasCenter_) {
centerLat_ = lat;
centerLon_ = lon;
hasCenter_ = true;
}
update();
}
protected:
void paintEvent(QPaintEvent *) override
{
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
p.fillRect(rect(), QColor("#0B1324"));
const QRectF mapRect = rect().adjusted(20, 20, -20, -50);
p.setPen(QPen(QColor("#243653"), 1));
p.setBrush(Qt::NoBrush);
p.drawRoundedRect(mapRect, 8, 8);
drawOsmTiles(p, mapRect);
if (!hasPosition_) {
p.setPen(QColor("#6F819F"));
p.drawText(mapRect, Qt::AlignCenter, "OSM map is ready. Waiting for drone GPS position...");
p.setPen(QColor("#D9E7FF"));
const QString info = QString("OSM tiles | Zoom %1 | Default center: Ho Chi Minh City | Use mouse wheel to zoom, drag to pan")
.arg(zoom_);
p.drawText(rect().adjusted(24, 0, -24, -16), Qt::AlignBottom | Qt::AlignLeft, info);
return;
}
if (hasHome_) {
const QPointF home = geoToWidget(homeLat_, homeLon_, mapRect);
p.setPen(QPen(QColor("#56CCF2"), 2));
p.setBrush(QColor(16, 38, 30, 210));
p.drawEllipse(home, 7, 7);
p.drawText(home + QPointF(10, -10), "HOME");
}
const QPointF drone = geoToWidget(currentLat_, currentLon_, mapRect);
p.setPen(QPen(QColor("#6EE7B7"), 2));
p.setBrush(QColor("#10B981"));
p.drawEllipse(drone, 9, 9);
p.drawText(drone + QPointF(12, -12), "DRONE");
p.setPen(QColor("#D9E7FF"));
const QString info = QString("OSM tiles | Zoom %1 | Lat %2 | Lon %3 | Alt %4 m")
.arg(zoom_)
.arg(currentLat_, 0, 'f', 7)
.arg(currentLon_, 0, 'f', 7)
.arg(currentAlt_, 0, 'f', 1);
p.drawText(rect().adjusted(24, 0, -24, -16), Qt::AlignBottom | Qt::AlignLeft, info);
drawClock(p, mapRect);
}
void wheelEvent(QWheelEvent *event) override
{
const int delta = event->angleDelta().y();
if (delta > 0 && zoom_ < 19) {
++zoom_;
} else if (delta < 0 && zoom_ > 3) {
--zoom_;
}
update();
}
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton) {
dragging_ = true;
lastMousePos_ = event->pos();
}
}
void mouseMoveEvent(QMouseEvent *event) override
{
if (!dragging_) {
return;
}
const QPoint delta = event->pos() - lastMousePos_;
lastMousePos_ = event->pos();
QPointF centerWorld = geoToWorld(centerLat_, centerLon_, zoom_);
centerWorld -= QPointF(delta.x(), delta.y());
const QPointF geo = worldToGeo(centerWorld, zoom_);
centerLat_ = geo.x();
centerLon_ = geo.y();
update();
}
void mouseReleaseEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton) {
dragging_ = false;
}
}
private:
QString tileKey(int z, int x, int y) const
{
return QString("%1/%2/%3").arg(z).arg(x).arg(y);
}
QPointF geoToWorld(double lat, double lon, int zoom) const
{
const double n = double(1 << zoom);
const double latRad = lat * 3.14159265358979323846 / 180.0;
const double x = (lon + 180.0) / 360.0 * n * tileSize_;
const double y = (1.0 - std::log(std::tan(latRad) + 1.0 / std::cos(latRad)) / 3.14159265358979323846) / 2.0 * n * tileSize_;
return QPointF(x, y);
}
QPointF worldToGeo(const QPointF &world, int zoom) const
{
const double n = double(1 << zoom);
const double x = world.x() / tileSize_;
const double y = world.y() / tileSize_;
const double lon = x / n * 360.0 - 180.0;
const double latRad = std::atan(std::sinh(3.14159265358979323846 * (1.0 - 2.0 * y / n)));
const double lat = latRad * 180.0 / 3.14159265358979323846;
return QPointF(lat, lon);
}
QPointF geoToWidget(double lat, double lon, const QRectF &mapRect) const
{
const QPointF centerWorld = geoToWorld(centerLat_, centerLon_, zoom_);
const QPointF pointWorld = geoToWorld(lat, lon, zoom_);
return mapRect.center() + (pointWorld - centerWorld);
}
void drawOsmTiles(QPainter &p, const QRectF &mapRect)
{
const QPointF centerWorld = geoToWorld(centerLat_, centerLon_, zoom_);
const QPointF topLeftWorld = centerWorld - QPointF(mapRect.width() / 2.0, mapRect.height() / 2.0);
const int minTileX = int(std::floor(topLeftWorld.x() / tileSize_));
const int minTileY = int(std::floor(topLeftWorld.y() / tileSize_));
const int maxTileX = int(std::floor((topLeftWorld.x() + mapRect.width()) / tileSize_));
const int maxTileY = int(std::floor((topLeftWorld.y() + mapRect.height()) / tileSize_));
const int tileCount = 1 << zoom_;
p.save();
p.setClipRect(mapRect);
for (int ty = minTileY; ty <= maxTileY; ++ty) {
if (ty < 0 || ty >= tileCount) {
continue;
}
for (int tx = minTileX; tx <= maxTileX; ++tx) {
const int wrappedX = ((tx % tileCount) + tileCount) % tileCount;
const QString key = tileKey(zoom_, wrappedX, ty);
requestTile(zoom_, wrappedX, ty);
const QPointF drawAt(mapRect.left() + tx * tileSize_ - topLeftWorld.x(),
mapRect.top() + ty * tileSize_ - topLeftWorld.y());
if (tileCache_.contains(key)) {
p.drawPixmap(QRectF(drawAt, QSizeF(tileSize_, tileSize_)), tileCache_[key], QRectF(0, 0, tileSize_, tileSize_));
} else {
p.fillRect(QRectF(drawAt, QSizeF(tileSize_, tileSize_)), QColor("#0D1528"));
p.setPen(QColor("#243653"));
p.drawRect(QRectF(drawAt, QSizeF(tileSize_, tileSize_)));
}
}
}
p.restore();
p.setPen(QPen(QColor(9, 15, 29, 180), 3));
p.drawRoundedRect(mapRect, 8, 8);
drawClock(p, mapRect);
}
void drawClock(QPainter &p, const QRectF &mapRect)
{
const QString timeText = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
const QFontMetrics fm(p.font());
const QRectF box(mapRect.right() - fm.horizontalAdvance(timeText) - 34, mapRect.top() + 12,
fm.horizontalAdvance(timeText) + 22, 30);
p.setPen(QPen(QColor("#314462"), 1));
p.setBrush(QColor(11, 19, 36, 220));
p.drawRoundedRect(box, 6, 6);
p.setPen(QColor("#E5F0FF"));
p.drawText(box, Qt::AlignCenter, timeText);
}
void requestTile(int z, int x, int y)
{
const QString key = tileKey(z, x, y);
if (tileCache_.contains(key) || pendingTiles_.contains(key)) {
return;
}
pendingTiles_.insert(key);
QNetworkRequest request(QUrl(QString("https://tile.openstreetmap.org/%1/%2/%3.png").arg(z).arg(x).arg(y)));
request.setRawHeader("User-Agent", "AeroLinkDroneGroundStation/1.0");
QNetworkReply *reply = network_->get(request);
connect(reply, &QNetworkReply::finished, this, [this, reply, key]() {
pendingTiles_.remove(key);
if (reply->error() == QNetworkReply::NoError) {
QPixmap pixmap;
pixmap.loadFromData(reply->readAll(), "PNG");
if (!pixmap.isNull()) {
tileCache_.insert(key, pixmap);
update();
}
}
reply->deleteLater();
});
}
bool hasHome_ = false;
bool hasPosition_ = false;
bool hasCenter_ = false;
bool dragging_ = false;
double homeLat_ = 0.0;
double homeLon_ = 0.0;
double centerLat_ = 0.0;
double centerLon_ = 0.0;
double currentLat_ = 0.0;
double currentLon_ = 0.0;
double currentAlt_ = 0.0;
int zoom_ = 17;
const int tileSize_ = 256;
QPoint lastMousePos_;
QNetworkAccessManager *network_ = nullptr;
QTimer *clockTimer_ = nullptr;
QHash<QString, QPixmap> tileCache_;
QSet<QString> pendingTiles_;
};
class AttitudeChartWidget : public QWidget {
public:
explicit AttitudeChartWidget(QWidget *parent = nullptr)
: QWidget(parent)
{
setMinimumHeight(500);
clockTimer_ = new QTimer(this);
clockTimer_->setInterval(1000);
connect(clockTimer_, &QTimer::timeout, this, [this]() {
update();
});
clockTimer_->start();
}
void addSample(double roll, double pitch, double yaw)
{
appendLimited(roll_, roll);
appendLimited(pitch_, pitch);
appendLimited(yaw_, normalizeAngle(yaw));
update();
}
protected:
void paintEvent(QPaintEvent *) override
{
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
p.fillRect(rect(), QColor("#0B1324"));
const QRectF area = rect().adjusted(36, 24, -24, -28);
const double gap = 26.0;
const double panelHeight = (area.height() - gap * 2.0) / 3.0;
drawPanel(p, QRectF(area.left(), area.top(), area.width(), panelHeight),
"ROLL", roll_, QColor("#56CCF2"));
drawPanel(p, QRectF(area.left(), area.top() + panelHeight + gap, area.width(), panelHeight),
"PITCH", pitch_, QColor("#6EE7B7"));
drawPanel(p, QRectF(area.left(), area.top() + (panelHeight + gap) * 2.0, area.width(), panelHeight),
"YAW", yaw_, QColor("#FBBF24"));
drawClock(p, area);
}
private:
void appendLimited(QVector<double> &series, double value)
{
series.append(value);
constexpr int maxSamples = 240;
while (series.size() > maxSamples) {
series.removeFirst();
}
}
double normalizeAngle(double value) const
{
while (value > 180.0) {
value -= 360.0;
}
while (value < -180.0) {
value += 360.0;
}
return value;
}
double seriesRange(const QVector<double> &series) const
{
double maxAbs = 45.0;
for (double value : series) {
maxAbs = std::max(maxAbs, std::abs(value));
}
return std::min(180.0, std::ceil(maxAbs / 15.0) * 15.0);
}
void drawPanel(QPainter &p, const QRectF &panel, const QString &title, const QVector<double> &series, const QColor &color)
{
p.setPen(QPen(QColor("#243653"), 1));
p.setBrush(QColor("#0D1528"));
p.drawRoundedRect(panel, 8, 8);
const QRectF chart = panel.adjusted(58, 38, -20, -26);
p.setPen(QPen(QColor("#1D2B44"), 1));
for (int i = 1; i < 4; ++i) {
const double y = chart.top() + chart.height() * i / 4.0;
p.drawLine(QPointF(chart.left(), y), QPointF(chart.right(), y));
}
for (int i = 1; i < 8; ++i) {
const double x = chart.left() + chart.width() * i / 8.0;
p.drawLine(QPointF(x, chart.top()), QPointF(x, chart.bottom()));
}
p.setPen(QPen(QColor("#35537A"), 1));
p.drawLine(QPointF(chart.left(), chart.center().y()), QPointF(chart.right(), chart.center().y()));
const double range = seriesRange(series);
p.setPen(color);
const QString current = series.isEmpty() ? "--" : QString("%1 deg").arg(series.last(), 0, 'f', 1);
p.drawText(panel.adjusted(16, 8, -16, -8), Qt::AlignTop | Qt::AlignLeft,
QString("%1 %2 range +/- %3 deg").arg(title, current).arg(range, 0, 'f', 0));
drawSeries(p, chart, series, color, range);
}
void drawClock(QPainter &p, const QRectF &area)
{
const QString timeText = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
const QFontMetrics fm(p.font());
const QRectF box(area.right() - fm.horizontalAdvance(timeText) - 28, area.top() - 2,
fm.horizontalAdvance(timeText) + 22, 30);
p.setPen(QPen(QColor("#314462"), 1));
p.setBrush(QColor(11, 19, 36, 220));
p.drawRoundedRect(box, 6, 6);
p.setPen(QColor("#E5F0FF"));
p.drawText(box, Qt::AlignCenter, timeText);
}
void drawSeries(QPainter &p, const QRectF &chart, const QVector<double> &series, const QColor &color, double range)
{
if (series.size() < 2) {
return;
}
QPainterPath path;
const int n = series.size();
for (int i = 0; i < n; ++i) {
const double x = chart.left() + chart.width() * i / double(std::max(1, n - 1));
const double y = chart.center().y() - (series[i] / range) * (chart.height() / 2.0);
if (i == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
}
p.setPen(QPen(color, 2));
p.save();
p.setClipRect(chart.adjusted(0, -1, 0, 1));
p.drawPath(path);
p.restore();
}
QVector<double> roll_;
QVector<double> pitch_;
QVector<double> yaw_;
QTimer *clockTimer_ = nullptr;
};
enum class LinkProtocol {
Unknown,
Mavlink,
Msp
};
class MavlinkWorker : public QObject {
Q_OBJECT
public:
explicit MavlinkWorker(QObject *parent = nullptr)
: QObject(parent),
serial_(new QSerialPort(this)),
heartbeatTimer_(new QTimer(this)),
heartbeatValidationTimer_(new QTimer(this)),
gcsHeartbeatTimer_(new QTimer(this)),
mspPollTimer_(new QTimer(this)),
reconnectTimer_(new QTimer(this)),
linkStatsTimer_(new QTimer(this))
{
heartbeatTimer_->setSingleShot(true);
heartbeatTimer_->setInterval(10000);
heartbeatValidationTimer_->setSingleShot(true);
heartbeatValidationTimer_->setInterval(500);
gcsHeartbeatTimer_->setInterval(1000);
mspPollTimer_->setInterval(100);
reconnectTimer_->setInterval(2000);
linkStatsTimer_->setInterval(1000);
linkClock_.start();
connect(serial_, &QSerialPort::readyRead, this, &MavlinkWorker::readSerial);
connect(serial_, &QSerialPort::errorOccurred, this, &MavlinkWorker::onSerialError);
connect(heartbeatTimer_, &QTimer::timeout, this, [this]() {
if (serial_->isOpen() && !heartbeatSeen_) {
failHeartbeatCheck();
}
});
connect(heartbeatValidationTimer_, &QTimer::timeout, this, [this]() {
acceptHeartbeatConnection();
});
connect(gcsHeartbeatTimer_, &QTimer::timeout, this, &MavlinkWorker::sendGcsHeartbeat);
connect(mspPollTimer_, &QTimer::timeout, this, &MavlinkWorker::pollMsp);
connect(reconnectTimer_, &QTimer::timeout, this, &MavlinkWorker::tryReconnect);
connect(linkStatsTimer_, &QTimer::timeout, this, &MavlinkWorker::publishLinkStats);
linkStatsTimer_->start();
}
bool isConnected() const { return serial_->isOpen(); }
void connectToVehicle(const QString &port, int baud)
{
if (serial_->isOpen()) {
return;
}
port_ = port;
baud_ = baud;
reconnectAttempts_ = 0;
heartbeatSeen_ = false;
heartbeatAccepted_ = false;
mspAccepted_ = false;
protocol_ = LinkProtocol::Unknown;
baudAdvertised_ = -1;
mspPollTick_ = 0;
mspIdentityLogged_ = false;
mspApiVersion_.clear();
mspFcVariant_.clear();
mspFcVersion_.clear();
wantedOpen_ = true;
serial_->setPortName(port_);
serial_->setBaudRate(baud_);
serial_->setDataBits(QSerialPort::Data8);
serial_->setParity(QSerialPort::NoParity);
serial_->setStopBits(QSerialPort::OneStop);
serial_->setFlowControl(QSerialPort::NoFlowControl);
if (!serial_->open(QIODevice::ReadWrite)) {
emit statusChanged(QString("Connection error: %1").arg(serial_->errorString()), "status-disconnected");
emit disconnected();
return;
}
serial_->setDataTerminalReady(true);
serial_->setRequestToSend(true);
parser_.clear();
mspParser_.clear();
lastHeartbeatMs_ = -1;
lastMessageMs_ = -1;
emit statusChanged(QString("Waiting for MAVLink or MSP at %1 baud...").arg(baud_), "status-warning");
emit eventLog(QString("Serial opened at %1 baud. Probing MAVLink and MSP...").arg(baud_), "info");
sendGcsHeartbeat();
gcsHeartbeatTimer_->start();
sendMspRequest(MspApiVersion);
sendMspRequest(MspFcVariant);
sendMspRequest(MspFcVersion);
mspPollTimer_->start();
heartbeatTimer_->start();
}
void disconnectFromVehicle()
{
reconnectTimer_->stop();
heartbeatTimer_->stop();
heartbeatValidationTimer_->stop();
gcsHeartbeatTimer_->stop();
mspPollTimer_->stop();
wantedOpen_ = false;
if (serial_->isOpen()) {
serial_->close();
}
emit disconnected();
emit statusChanged("Disconnected", "status-disconnected");
}
void changeBaudRate(int baud)
{
if (baud <= 0) {
emit statusChanged("Invalid baud rate", "status-warning");
emit eventLog("Rejected invalid baud rate.", "warn");
return;
}
baud_ = baud;
parser_.clear();
mspParser_.clear();
heartbeatSeen_ = false;
heartbeatAccepted_ = false;
mspAccepted_ = false;
protocol_ = LinkProtocol::Unknown;
baudAdvertised_ = -1;
mspPollTick_ = 0;
mspIdentityLogged_ = false;
mspApiVersion_.clear();
mspFcVariant_.clear();
mspFcVersion_.clear();
lastHeartbeatMs_ = -1;
lastMessageMs_ = -1;
if (!serial_->isOpen()) {
emit statusChanged(QString("Baud rate set to %1").arg(baud_), "status-warning");
emit eventLog(QString("Baud rate prepared: %1").arg(baud_), "info");
return;
}
if (!serial_->setBaudRate(baud_)) {
emit statusChanged(QString("Failed to apply baud rate: %1").arg(serial_->errorString()), "status-warning");
emit eventLog(QString("Failed to apply baud rate %1: %2").arg(baud_).arg(serial_->errorString()), "warn");
return;
}
emit statusChanged(QString("Baud rate applied: %1").arg(baud_), "status-warning");
emit eventLog(QString("Serial baud rate changed live to %1. Probing MAVLink and MSP...").arg(baud_), "info");
sendGcsHeartbeat();
sendMspRequest(MspApiVersion);
mspPollTimer_->start();
heartbeatTimer_->start();
}
void arm()
{
try {
sendCommandLong(MavCmdComponentArmDisarm, 1.0f);
} catch (const std::exception &e) {
emit statusChanged(QString("Arm error: %1").arg(e.what()), "status-warning");
}
}
void disarm()
{
try {
sendCommandLong(MavCmdComponentArmDisarm, 0.0f);
} catch (const std::exception &e) {
emit statusChanged(QString("Disarm error: %1").arg(e.what()), "status-warning");
}
}
void takeoff(double altitudeM)
{
try {
sendCommandLong(MavCmdNavTakeoff, 0, 0, 0, 0, 0, 0, float(altitudeM));
} catch (const std::exception &e) {
emit statusChanged(QString("Takeoff error: %1").arg(e.what()), "status-warning");
}
}
void land()
{
try {
sendCommandLong(MavCmdNavLand);
} catch (const std::exception &e) {
emit statusChanged(QString("Land error: %1").arg(e.what()), "status-warning");
}
}
void rth()
{
try {
setMode(ArduModeRtl);
sendCommandLong(MavCmdNavReturnToLaunch);
} catch (const std::exception &e) {
emit statusChanged(QString("RTH error: %1").arg(e.what()), "status-warning");
}
}
void goTo(double lat, double lon, double alt)
{
try {
setMode(ArduModeGuided);
QByteArray payload(53, char(0));
writeLe<uint32_t>(payload, 0, 0);
writeLe<int32_t>(payload, 4, int32_t(lat * 1e7));
writeLe<int32_t>(payload, 8, int32_t(lon * 1e7));
writeLe<float>(payload, 12, float(alt));
writeLe<uint16_t>(payload, 48, 0b0000111111111000);
payload[50] = char(targetSystem_);
payload[51] = char(targetComponent_);
payload[52] = char(MavFrameGlobalRelativeAltInt);
writePacket(86, payload);
emit statusChanged("Navigating to target", "status-connected");
} catch (const std::exception &e) {
emit statusChanged(QString("Goto error: %1").arg(e.what()), "status-warning");
}
}
signals:
void statusChanged(const QString &text, const QString &style);
void telemetryUpdate(const QVariantMap &data);
void linkStatsUpdate(const QVariantMap &data);
void eventLog(const QString &text, const QString &level);
void connected();
void disconnected();