QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
MAVLinkProtocol.cc
Go to the documentation of this file.
1#include "MAVLinkProtocol.h"
2
3#include <QtCore/QApplicationStatic>
4#include <QtCore/QDir>
5#include <QtCore/QFile>
6#include <QtCore/QFileInfo>
7#include <QtCore/QMetaType>
8#include <QtCore/QSettings>
9#include <QtCore/QStandardPaths>
10#include <QtCore/QTimer>
11#include <cstring>
12
13#include "AppMessages.h"
14#include "AppSettings.h"
15#include "LinkManager.h"
16#include "MAVLinkLib.h"
17#include "LinkInterface.h"
18#include "MAVLinkSigning.h"
19#include "SigningController.h"
20#include "MavlinkSettings.h"
21#include "MultiVehicleManager.h"
22#include "QGCFileHelper.h"
23#include "QGCLoggingCategory.h"
24#include "QmlObjectListModel.h"
25#include "SettingsManager.h"
26
27QGC_LOGGING_CATEGORY(MAVLinkProtocolLog, "Comms.MAVLinkProtocol")
28
29Q_APPLICATION_STATIC(MAVLinkProtocol, _mavlinkProtocolInstance);
30
31MAVLinkProtocol::MAVLinkProtocol(QObject* parent) : QObject(parent), _tempLogFile(new QFile(this))
32{
33 // Bound memory for arbitrary sender IDs, retaining the most recently active streams.
34 for (auto& sequences : _lastIndex) {
35 sequences.setMaxCost(4096);
36 }
37 qCDebug(MAVLinkProtocolLog) << this;
38}
39
41{
42 _closeLogFile();
43
44 qCDebug(MAVLinkProtocolLog) << this;
45}
46
48{
49 return _mavlinkProtocolInstance();
50}
51
53{
54 if (_initialized) {
55 return;
56 }
57
59 &MAVLinkProtocol::_vehicleCountChanged);
60
61 _initialized = true;
62}
63
65{
66 const uint8_t channel = link->mavlinkChannel();
67 _totalReceiveCounter[channel] = 0;
68 _totalLossCounter[channel] = 0;
69 _runningLossPercent[channel] = 0.f;
70
73}
74
76{
77 // Clear per-(sysid,compid) sequence state so next packet isn't counted as a gap.
78 const uint8_t channel = link->mavlinkChannel();
79 _lastIndex[channel].clear();
80}
81
82void MAVLinkProtocol::logSentBytes(const LinkInterface* link, const QByteArray& data)
83{
84 Q_UNUSED(link);
85
86 if (_logSuspendError || _logSuspendReplay || !_tempLogFile->isOpen()) {
87 return;
88 }
89
90 const quint64 time = static_cast<quint64>(QDateTime::currentMSecsSinceEpoch() * 1000);
91 uint8_t bytes_time[sizeof(quint64)]{};
92 qToBigEndian(time, bytes_time);
93
94 QByteArray logData = data;
95 QByteArray timeData = QByteArray::fromRawData(reinterpret_cast<const char*>(bytes_time), sizeof(bytes_time));
96 (void)logData.prepend(timeData);
97 if (_tempLogFile->write(logData) != logData.length()) {
98 const QString message = QStringLiteral("MAVLink Logging failed. Could not write to file %1, logging disabled.")
99 .arg(_tempLogFile->fileName());
100 QGC::showAppMessage(message, getName());
101 _stopLogging();
102 _logSuspendError = true;
103 }
104}
105
106void MAVLinkProtocol::receiveBytes(LinkInterface* link, const QByteArray& data)
107{
109 if (!linkPtr) {
110 qCDebug(MAVLinkProtocolLog) << "receiveBytes: link gone!" << data.size() << "bytes arrived too late";
111 return;
112 }
113
114 for (uint8_t byte : data) {
115 const uint8_t mavlinkChannel = link->mavlinkChannel();
116 mavlink_message_t message{};
117 mavlink_status_t status{};
118
119 const uint8_t framing = mavlink_parse_char(mavlinkChannel, byte, &message, &status);
120 if (framing == MAVLINK_FRAMING_OK || framing == MAVLINK_FRAMING_BAD_SIGNATURE) {
121 if (SigningController* const sigCtrl = link->signing()) {
122 // Auto-detected key: reset sequence tracking so the key-install gap isn't counted as loss.
123 if (sigCtrl->processFrame(framing == MAVLINK_FRAMING_OK, message)) {
125 }
126 }
127 }
128 if (framing != MAVLINK_FRAMING_OK) {
129 continue;
130 }
131
132 if (message.msgid == MAVLINK_MSG_ID_RADIO_STATUS) {
134 }
135
136 // v1/v2 share per-(sysid,compid) sequence counters; counting v1 makes every v2 appear lost. Skip v1 non-heartbeats.
137 // RADIO_STATUS is exempt: SiK radios always frame it as v1, so it is processed and never triggers the v1 warning.
138 const bool isV1 = (status.flags & MAVLINK_STATUS_FLAG_IN_MAVLINK1);
139 if (isV1 && (message.msgid != MAVLINK_MSG_ID_HEARTBEAT) && (message.msgid != MAVLINK_MSG_ID_RADIO_STATUS)) {
141 continue;
142 }
143
144 if (!isV1) {
146 _updateCounters(mavlinkChannel, message);
147 }
148 if (!linkPtr->linkConfiguration()->isForwarding()) {
149 _forward(message);
150 _forwardSupport(message);
151 }
152 _logData(link, message);
153
154 if (!_updateStatus(link, linkPtr, mavlinkChannel, message)) {
155 break;
156 }
157 }
158}
159
160void MAVLinkProtocol::_updateCounters(uint8_t mavlinkChannel, const mavlink_message_t& message)
161{
162 _totalReceiveCounter[mavlinkChannel]++;
163
164 const QPair<quint32, uint8_t> key(message.sysid, message.compid);
165 auto& sequences = _lastIndex[mavlinkChannel];
166 auto* const previous = sequences.object(key);
167 uint8_t expectedSeq;
168 if (!previous) {
169 expectedSeq = message.seq;
170 } else if (message.seq == *previous) {
171 // v1/v2 of the same message share sequence numbers — duplicate seq isn't loss.
172 return;
173 } else {
174 expectedSeq = *previous + 1;
175 }
176
177 uint64_t lostMessages;
178 if (message.seq >= expectedSeq) {
179 lostMessages = message.seq - expectedSeq;
180 } else {
181 lostMessages = static_cast<uint64_t>(message.seq) + 256ULL - expectedSeq;
182 }
183 _totalLossCounter[mavlinkChannel] += lostMessages;
184
185 if (previous) {
186 *previous = message.seq;
187 } else {
188 sequences.insert(key, new uint8_t(message.seq));
189 }
190
191 const uint64_t totalSent = _totalReceiveCounter[mavlinkChannel] + _totalLossCounter[mavlinkChannel];
192 const float currentLossPercent = (static_cast<double>(_totalLossCounter[mavlinkChannel]) / totalSent) * 100.0f;
193 _runningLossPercent[mavlinkChannel] = (currentLossPercent + _runningLossPercent[mavlinkChannel]) * 0.5f;
194}
195
196void MAVLinkProtocol::_forward(const mavlink_message_t& message)
197{
198 if (message.msgid == MAVLINK_MSG_ID_SETUP_SIGNING) {
199 return;
200 }
201
202 if (!SettingsManager::instance()->mavlinkSettings()->forwardMavlink()->rawValue().toBool()) {
203 return;
204 }
205
207 if (!forwardingLink) {
208 return;
209 }
210
211 // Strip signature on forward: foreign key would BAD_SIGNATURE on downstream signing-aware parsers.
212 const QByteArray bytes = MAVLinkSigning::serializeUnsignedCopy(message);
213 (void)forwardingLink->writeBytesThreadSafe(bytes.constData(), bytes.size());
214}
215
216void MAVLinkProtocol::_forwardSupport(const mavlink_message_t& message)
217{
218 if (message.msgid == MAVLINK_MSG_ID_SETUP_SIGNING) {
219 return;
220 }
221
222 if (!LinkManager::instance()->mavlinkSupportForwardingEnabled()) {
223 return;
224 }
225
227 if (!forwardingSupportLink) {
228 return;
229 }
230
231 const QByteArray bytes = MAVLinkSigning::serializeUnsignedCopy(message);
232 (void)forwardingSupportLink->writeBytesThreadSafe(bytes.constData(), bytes.size());
233}
234
235void MAVLinkProtocol::_logData(LinkInterface* link, const mavlink_message_t& message)
236{
237 if (!_logSuspendError && !_logSuspendReplay && _tempLogFile->isOpen()) {
238 // MAVLink spec §Logging: omit SETUP_SIGNING (contains secret key)
239 if (message.msgid != MAVLINK_MSG_ID_SETUP_SIGNING) {
240 // MAVLink spec §Logging: strip signature block from logged packets.
241 const QByteArray msgBytes = MAVLinkSigning::serializeUnsignedCopy(message);
242 const quint64 timestamp = static_cast<quint64>(QDateTime::currentMSecsSinceEpoch() * 1000);
243 QByteArray log_data;
244 log_data.resize(static_cast<qsizetype>(sizeof(timestamp)) + msgBytes.size());
245 qToBigEndian(timestamp, reinterpret_cast<uint8_t*>(log_data.data()));
246 std::memcpy(log_data.data() + sizeof(timestamp), msgBytes.constData(), msgBytes.size());
247 if (_tempLogFile->write(log_data) != log_data.size()) {
248 const QString logErrorMessage =
249 QStringLiteral("MAVLink Logging failed. Could not write to file %1, logging disabled.")
250 .arg(_tempLogFile->fileName());
251 QGC::showAppMessage(logErrorMessage, getName());
252 _stopLogging();
253 _logSuspendError = true;
254 }
255 }
256
257 if ((message.msgid == MAVLINK_MSG_ID_HEARTBEAT) && !_vehicleWasArmed) {
258 if (mavlink_msg_heartbeat_get_base_mode(&message) & MAV_MODE_FLAG_DECODE_POSITION_SAFETY) {
259 _vehicleWasArmed = true;
260 }
261 }
262 }
263
264 // Keep foreign traffic in the log, but do not discover vehicles from headers addressed elsewhere.
265 if (message.incompat_flags & MAVLINK_IFLAG_TARGET32) {
266 const uint8_t targetComponent = mavlink_msg_get_target_compid(&message, mavlink_get_msg_entry(message.msgid));
267 if ((message.target_sysid != 0 && message.target_sysid != getSystemId()) ||
268 (targetComponent != 0 && targetComponent != getComponentId())) {
269 return;
270 }
271 }
272
273 switch (message.msgid) {
274 case MAVLINK_MSG_ID_HEARTBEAT: {
275 _startLogging();
276 mavlink_heartbeat_t heartbeat{};
277 mavlink_msg_heartbeat_decode(&message, &heartbeat);
278 emit vehicleHeartbeatInfo(link, message.sysid, message.compid, heartbeat.autopilot, heartbeat.type);
279 break;
280 }
281 case MAVLINK_MSG_ID_HIGH_LATENCY: {
282 _startLogging();
283 mavlink_high_latency_t highLatency{};
284 mavlink_msg_high_latency_decode(&message, &highLatency);
285 // HIGH_LATENCY does not provide autopilot or type information, generic is our safest bet
286 emit vehicleHeartbeatInfo(link, message.sysid, message.compid, MAV_AUTOPILOT_GENERIC, MAV_TYPE_GENERIC);
287 break;
288 }
289 case MAVLINK_MSG_ID_HIGH_LATENCY2: {
290 _startLogging();
291 mavlink_high_latency2_t highLatency2{};
292 mavlink_msg_high_latency2_decode(&message, &highLatency2);
293 emit vehicleHeartbeatInfo(link, message.sysid, message.compid, highLatency2.autopilot, highLatency2.type);
294 break;
295 }
296 default:
297 break;
298 }
299}
300
301bool MAVLinkProtocol::_updateStatus(LinkInterface* link, const SharedLinkInterfacePtr linkPtr, uint8_t mavlinkChannel,
302 const mavlink_message_t& message)
303{
304 if ((_totalReceiveCounter[mavlinkChannel] % 31) == 0) {
305 const uint64_t totalSent = _totalReceiveCounter[mavlinkChannel] + _totalLossCounter[mavlinkChannel];
306 emit mavlinkMessageStatus(message.sysid, totalSent, _totalReceiveCounter[mavlinkChannel],
307 _totalLossCounter[mavlinkChannel], _runningLossPercent[mavlinkChannel]);
308 }
309
310 emit messageReceived(link, message);
311
312 if (linkPtr.use_count() == 1) {
313 return false;
314 }
315
316 return true;
317}
318
319bool MAVLinkProtocol::_closeLogFile()
320{
321 if (!_tempLogFile->isOpen()) {
322 return false;
323 }
324
325 if (_tempLogFile->size() == 0) {
326 (void)_tempLogFile->remove();
327 return false;
328 }
329
330 (void)_tempLogFile->flush();
331 _tempLogFile->close();
332 return true;
333}
334
335void MAVLinkProtocol::_startLogging()
336{
337 if (QGC::runningUnitTests()) {
338 return;
339 }
340
341 AppSettings* const appSettings = SettingsManager::instance()->appSettings();
342 if (appSettings->disableAllPersistence()->rawValue().toBool()) {
343 return;
344 }
345
346#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
347 if (!SettingsManager::instance()->mavlinkSettings()->telemetrySave()->rawValue().toBool()) {
348 return;
349 }
350#endif
351
352 if (_tempLogFile->isOpen()) {
353 return;
354 }
355
356 if (_logSuspendReplay) {
357 return;
358 }
359
360 // Generate unique temp file path for this logging session
361 const QString logPath =
362 QGCFileHelper::uniqueTempPath(QStringLiteral("%1.%2").arg(_tempLogFileTemplate, _logFileExtension));
363 if (logPath.isEmpty()) {
364 qCWarning(MAVLinkProtocolLog) << "Failed to generate temp log path";
365 _logSuspendError = true;
366 return;
367 }
368
369 _tempLogFile->setFileName(logPath);
370 if (!_tempLogFile->open(QIODevice::WriteOnly)) {
371 const QString message = QStringLiteral(
372 "Opening Flight Data file for writing failed. "
373 "Unable to write to %1. Please choose a different file location.")
374 .arg(_tempLogFile->fileName());
375 QGC::showAppMessage(message, getName());
376 _closeLogFile();
377 _logSuspendError = true;
378 return;
379 }
380
381 qCDebug(MAVLinkProtocolLog) << "Temp log" << _tempLogFile->fileName();
382 (void)_checkTelemetrySavePath();
383
384 _logSuspendError = false;
385}
386
387void MAVLinkProtocol::_stopLogging()
388{
389 if (_tempLogFile->isOpen() && _closeLogFile()) {
390 auto appSettings = SettingsManager::instance()->appSettings();
391 auto mavlinkSettings = SettingsManager::instance()->mavlinkSettings();
392 if ((_vehicleWasArmed || mavlinkSettings->telemetrySaveNotArmed()->rawValue().toBool()) &&
393 mavlinkSettings->telemetrySave()->rawValue().toBool() &&
394 !appSettings->disableAllPersistence()->rawValue().toBool()) {
395 _saveTelemetryLog(_tempLogFile->fileName());
396 } else {
397 (void)QFile::remove(_tempLogFile->fileName());
398 }
399 }
400
401 _vehicleWasArmed = false;
402}
403
405{
406 static const QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
407 static const QString filter(QStringLiteral("*.%1").arg(_logFileExtension));
408 static const QStringList filterList(filter);
409
410 const QFileInfoList fileInfoList = tempDir.entryInfoList(filterList, QDir::Files);
411 qCDebug(MAVLinkProtocolLog) << "Orphaned log file count" << fileInfoList.count();
412
413 for (const QFileInfo& fileInfo : fileInfoList) {
414 qCDebug(MAVLinkProtocolLog) << "Orphaned log file" << fileInfo.filePath();
415 if (fileInfo.size() == 0) {
416 (void)QFile::remove(fileInfo.filePath());
417 continue;
418 }
419 _saveTelemetryLog(fileInfo.filePath());
420 }
421}
422
424{
425 static const QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
426 static const QString filter(QStringLiteral("*.%1").arg(_logFileExtension));
427
428 const QFileInfoList fileInfoList = tempDir.entryInfoList(QStringList(filter), QDir::Files);
429 qCDebug(MAVLinkProtocolLog) << "Temp log file count" << fileInfoList.count();
430
431 for (const QFileInfo& fileInfo : fileInfoList) {
432 qCDebug(MAVLinkProtocolLog) << "Temp log file" << fileInfo.filePath();
433 (void)QFile::remove(fileInfo.filePath());
434 }
435}
436
437void MAVLinkProtocol::_saveTelemetryLog(const QString& tempLogfile)
438{
439 if (_checkTelemetrySavePath()) {
440 const QString saveDirPath = SettingsManager::instance()->appSettings()->telemetrySavePath();
441 const QDir saveDir(saveDirPath);
442
443 const QString nameFormat("%1%2.%3");
444 const QString dtFormat("yyyy-MM-dd hh-mm-ss");
445
446 int tryIndex = 1;
447 QString saveFileName = nameFormat.arg(QDateTime::currentDateTime().toString(dtFormat), QString(),
449 while (saveDir.exists(saveFileName)) {
450 saveFileName = nameFormat.arg(QDateTime::currentDateTime().toString(dtFormat),
451 QStringLiteral(".%1").arg(tryIndex++), AppSettings::telemetryFileExtension);
452 }
453
454 const QString saveFilePath = saveDir.absoluteFilePath(saveFileName);
455
456 QFile in(tempLogfile);
457 if (!in.open(QIODevice::ReadOnly)) {
458 const QString error =
459 tr("Unable to save telemetry log. Error opening source '%1': '%2'.").arg(tempLogfile, in.errorString());
460 QGC::showAppMessage(error);
461 (void)QFile::remove(tempLogfile);
462 return;
463 }
464
465 QSaveFile out(saveFilePath);
466 out.setDirectWriteFallback(true); // allows non-atomic fallback where rename isn’t possible
467
468 if (!out.open(QIODevice::WriteOnly)) {
469 const QString error = tr("Unable to save telemetry log. Error opening destination '%1': '%2'.")
470 .arg(saveFilePath, out.errorString());
471 QGC::showAppMessage(error);
472 (void)QFile::remove(tempLogfile);
473 return;
474 }
475
476 // Stream copy to avoid large allocations.
477 QByteArray buffer;
478 constexpr int bufferSize = 256 * 1024; // 256 KiB
479 buffer.resize(bufferSize);
480 while (true) {
481 const qint64 n = in.read(buffer.data(), buffer.size());
482 if (n == 0) {
483 break;
484 }
485 if (n < 0) {
486 const QString error = tr("Unable to save telemetry log. Error reading source '%1': '%2'.")
487 .arg(tempLogfile, in.errorString());
488 QGC::showAppMessage(error);
489 out.cancelWriting();
490 (void)QFile::remove(tempLogfile);
491 return;
492 }
493 if (out.write(buffer.constData(), n) != n) {
494 const QString error = tr("Unable to save telemetry log. Error writing destination '%1': '%2'.")
495 .arg(saveFilePath, out.errorString());
496 QGC::showAppMessage(error);
497 out.cancelWriting();
498 (void)QFile::remove(tempLogfile);
499 return;
500 }
501 }
502
503 // QSaveFile applies permissions during commit().
504 constexpr QFileDevice::Permissions perms =
505 QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther;
506 (void) out.setPermissions(perms);
507
508 if (!out.commit()) {
509 const QString error =
510 tr("Unable to finalize telemetry log '%1': '%2'.").arg(saveFilePath, out.errorString());
511 QGC::showAppMessage(error);
512 (void)QFile::remove(tempLogfile);
513 return;
514 }
515 }
516
517 (void)QFile::remove(tempLogfile);
518}
519
520bool MAVLinkProtocol::_checkTelemetrySavePath()
521{
522 const QString saveDirPath = SettingsManager::instance()->appSettings()->telemetrySavePath();
523 if (saveDirPath.isEmpty()) {
524 const QString error = tr("Unable to save telemetry log. Application save directory is not set.");
525 QGC::showAppMessage(error);
526 return false;
527 }
528
529 const QDir saveDir(saveDirPath);
530 if (!saveDir.exists()) {
531 const QString error =
532 tr("Unable to save telemetry log. Telemetry save directory \"%1\" does not exist.").arg(saveDirPath);
533 QGC::showAppMessage(error);
534 return false;
535 }
536
537 return true;
538}
539
540void MAVLinkProtocol::_vehicleCountChanged()
541{
542 if (MultiVehicleManager::instance()->vehicles()->count() == 0) {
543 _stopLogging();
544 }
545}
546
548{
549 return SettingsManager::instance()->mavlinkSettings()->gcsMavlinkSystemID()->rawValue().toUInt();
550}
Q_APPLICATION_STATIC(ADSBVehicleManager, _adsbVehicleManager, SettingsManager::instance() ->adsbVehicleManagerSettings())
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
struct __mavlink_high_latency2_t mavlink_high_latency2_t
QString telemetrySavePath()
static constexpr const char * telemetryFileExtension
The link interface defines the interface for all links used to communicate with the ground station ap...
void setDecodedFirstMavlinkPacket(bool decodedFirstMavlinkPacket)
uint8_t mavlinkChannel() const
void reportMavlinkV1Traffic()
void reportMavlinkV2Traffic()
Called when a v2 message is received: permanently suppresses the v1-only warning for this link.
SigningController * signing()
Per-link signing state and confirmation state machine. Non-null after channel allocation.
void reportRadioStatusReceived()
SharedLinkInterfacePtr sharedLinkInterfacePointerForLink(const LinkInterface *link)
static LinkManager * instance()
SharedLinkInterfacePtr mavlinkForwardingSupportLink()
Returns pointer to the mavlink support forwarding link, or nullptr if it does not exist.
SharedLinkInterfacePtr mavlinkForwardingLink()
Returns pointer to the mavlink forwarding link, or nullptr if it does not exist.
MAVLink micro air vehicle protocol reference implementation.
void receiveBytes(LinkInterface *link, const QByteArray &data)
void mavlinkMessageStatus(quint32 sysid, uint64_t totalSent, uint64_t totalReceived, uint64_t totalLoss, float lossPercent)
static int getComponentId()
void messageReceived(LinkInterface *link, const mavlink_message_t &message)
quint32 getSystemId() const
void resetSequenceTracking(LinkInterface *link)
Reset sequence tracking so signing transitions don't inflate loss counters.
void vehicleHeartbeatInfo(LinkInterface *link, quint32 vehicleId, int componentId, int vehicleFirmwareType, int vehicleType)
void logSentBytes(const LinkInterface *link, const QByteArray &data)
static MAVLinkProtocol * instance()
void resetMetadataForLink(LinkInterface *link)
MAVLinkProtocol(QObject *parent=nullptr)
static QString getName()
static void deleteTempLogFiles()
static MultiVehicleManager * instance()
void vehicleRemoved(Vehicle *vehicle)
static SettingsManager * instance()
AppSettings * appSettings() const
MavlinkSettings * mavlinkSettings() const
Owns MAVLink signing state and the deferred-confirmation state machine for one LinkInterface.
QByteArray serializeUnsignedCopy(const mavlink_message_t &message)
QString uniqueTempPath(const QString &templateName)
bool runningUnitTests()
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9