3#include <QtCore/QApplicationStatic>
6#include <QtCore/QFileInfo>
7#include <QtCore/QMetaType>
8#include <QtCore/QSettings>
9#include <QtCore/QStandardPaths>
10#include <QtCore/QTimer>
34 for (
auto& sequences : _lastIndex) {
35 sequences.setMaxCost(4096);
37 qCDebug(MAVLinkProtocolLog) <<
this;
44 qCDebug(MAVLinkProtocolLog) <<
this;
49 return _mavlinkProtocolInstance();
59 &MAVLinkProtocol::_vehicleCountChanged);
67 _totalReceiveCounter[channel] = 0;
68 _totalLossCounter[channel] = 0;
69 _runningLossPercent[channel] = 0.f;
79 _lastIndex[channel].clear();
86 if (_logSuspendError || _logSuspendReplay || !_tempLogFile->isOpen()) {
90 const quint64 time =
static_cast<quint64
>(QDateTime::currentMSecsSinceEpoch() * 1000);
91 uint8_t bytes_time[
sizeof(quint64)]{};
92 qToBigEndian(time, bytes_time);
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());
102 _logSuspendError =
true;
110 qCDebug(MAVLinkProtocolLog) <<
"receiveBytes: link gone!" << data.size() <<
"bytes arrived too late";
114 for (uint8_t
byte : data) {
117 mavlink_status_t status{};
119 const uint8_t framing = mavlink_parse_char(mavlinkChannel,
byte, &message, &status);
120 if (framing == MAVLINK_FRAMING_OK || framing == MAVLINK_FRAMING_BAD_SIGNATURE) {
123 if (sigCtrl->processFrame(framing == MAVLINK_FRAMING_OK, message)) {
128 if (framing != MAVLINK_FRAMING_OK) {
132 if (message.msgid == MAVLINK_MSG_ID_RADIO_STATUS) {
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)) {
146 _updateCounters(mavlinkChannel, message);
148 if (!linkPtr->linkConfiguration()->isForwarding()) {
150 _forwardSupport(message);
152 _logData(link, message);
154 if (!_updateStatus(link, linkPtr, mavlinkChannel, message)) {
160void MAVLinkProtocol::_updateCounters(uint8_t mavlinkChannel,
const mavlink_message_t& message)
162 _totalReceiveCounter[mavlinkChannel]++;
164 const QPair<quint32, uint8_t> key(message.sysid, message.compid);
165 auto& sequences = _lastIndex[mavlinkChannel];
166 auto*
const previous = sequences.object(key);
169 expectedSeq = message.seq;
170 }
else if (message.seq == *previous) {
174 expectedSeq = *previous + 1;
177 uint64_t lostMessages;
178 if (message.seq >= expectedSeq) {
179 lostMessages = message.seq - expectedSeq;
181 lostMessages =
static_cast<uint64_t
>(message.seq) + 256ULL - expectedSeq;
183 _totalLossCounter[mavlinkChannel] += lostMessages;
186 *previous = message.seq;
188 sequences.insert(key,
new uint8_t(message.seq));
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;
198 if (message.msgid == MAVLINK_MSG_ID_SETUP_SIGNING) {
207 if (!forwardingLink) {
213 (void)forwardingLink->writeBytesThreadSafe(bytes.constData(), bytes.size());
218 if (message.msgid == MAVLINK_MSG_ID_SETUP_SIGNING) {
227 if (!forwardingSupportLink) {
232 (void)forwardingSupportLink->writeBytesThreadSafe(bytes.constData(), bytes.size());
237 if (!_logSuspendError && !_logSuspendReplay && _tempLogFile->isOpen()) {
239 if (message.msgid != MAVLINK_MSG_ID_SETUP_SIGNING) {
242 const quint64 timestamp =
static_cast<quint64
>(QDateTime::currentMSecsSinceEpoch() * 1000);
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());
253 _logSuspendError =
true;
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;
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()) ||
273 switch (message.msgid) {
274 case MAVLINK_MSG_ID_HEARTBEAT: {
276 mavlink_heartbeat_t heartbeat{};
277 mavlink_msg_heartbeat_decode(&message, &heartbeat);
278 emit
vehicleHeartbeatInfo(link, message.sysid, message.compid, heartbeat.autopilot, heartbeat.type);
281 case MAVLINK_MSG_ID_HIGH_LATENCY: {
283 mavlink_high_latency_t highLatency{};
284 mavlink_msg_high_latency_decode(&message, &highLatency);
286 emit
vehicleHeartbeatInfo(link, message.sysid, message.compid, MAV_AUTOPILOT_GENERIC, MAV_TYPE_GENERIC);
289 case MAVLINK_MSG_ID_HIGH_LATENCY2: {
292 mavlink_msg_high_latency2_decode(&message, &highLatency2);
293 emit
vehicleHeartbeatInfo(link, message.sysid, message.compid, highLatency2.autopilot, highLatency2.type);
304 if ((_totalReceiveCounter[mavlinkChannel] % 31) == 0) {
305 const uint64_t totalSent = _totalReceiveCounter[mavlinkChannel] + _totalLossCounter[mavlinkChannel];
307 _totalLossCounter[mavlinkChannel], _runningLossPercent[mavlinkChannel]);
312 if (linkPtr.use_count() == 1) {
319bool MAVLinkProtocol::_closeLogFile()
321 if (!_tempLogFile->isOpen()) {
325 if (_tempLogFile->size() == 0) {
326 (void)_tempLogFile->remove();
330 (void)_tempLogFile->flush();
331 _tempLogFile->close();
335void MAVLinkProtocol::_startLogging()
342 if (appSettings->disableAllPersistence()->rawValue().toBool()) {
346#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
352 if (_tempLogFile->isOpen()) {
356 if (_logSuspendReplay) {
361 const QString logPath =
363 if (logPath.isEmpty()) {
364 qCWarning(MAVLinkProtocolLog) <<
"Failed to generate temp log path";
365 _logSuspendError =
true;
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());
377 _logSuspendError =
true;
381 qCDebug(MAVLinkProtocolLog) <<
"Temp log" << _tempLogFile->fileName();
382 (void)_checkTelemetrySavePath();
384 _logSuspendError =
false;
387void MAVLinkProtocol::_stopLogging()
389 if (_tempLogFile->isOpen() && _closeLogFile()) {
392 if ((_vehicleWasArmed || mavlinkSettings->telemetrySaveNotArmed()->rawValue().toBool()) &&
393 mavlinkSettings->telemetrySave()->rawValue().toBool() &&
394 !appSettings->disableAllPersistence()->rawValue().toBool()) {
395 _saveTelemetryLog(_tempLogFile->fileName());
397 (void)QFile::remove(_tempLogFile->fileName());
401 _vehicleWasArmed =
false;
406 static const QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
407 static const QString filter(QStringLiteral(
"*.%1").arg(_logFileExtension));
408 static const QStringList filterList(filter);
410 const QFileInfoList fileInfoList = tempDir.entryInfoList(filterList, QDir::Files);
411 qCDebug(MAVLinkProtocolLog) <<
"Orphaned log file count" << fileInfoList.count();
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());
419 _saveTelemetryLog(fileInfo.filePath());
425 static const QDir tempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
426 static const QString filter(QStringLiteral(
"*.%1").arg(_logFileExtension));
428 const QFileInfoList fileInfoList = tempDir.entryInfoList(QStringList(filter), QDir::Files);
429 qCDebug(MAVLinkProtocolLog) <<
"Temp log file count" << fileInfoList.count();
431 for (
const QFileInfo& fileInfo : fileInfoList) {
432 qCDebug(MAVLinkProtocolLog) <<
"Temp log file" << fileInfo.filePath();
433 (void)QFile::remove(fileInfo.filePath());
437void MAVLinkProtocol::_saveTelemetryLog(
const QString& tempLogfile)
439 if (_checkTelemetrySavePath()) {
441 const QDir saveDir(saveDirPath);
443 const QString nameFormat(
"%1%2.%3");
444 const QString dtFormat(
"yyyy-MM-dd hh-mm-ss");
447 QString saveFileName = nameFormat.arg(QDateTime::currentDateTime().toString(dtFormat), QString(),
449 while (saveDir.exists(saveFileName)) {
450 saveFileName = nameFormat.arg(QDateTime::currentDateTime().toString(dtFormat),
454 const QString saveFilePath = saveDir.absoluteFilePath(saveFileName);
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());
461 (void)QFile::remove(tempLogfile);
465 QSaveFile out(saveFilePath);
466 out.setDirectWriteFallback(
true);
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());
472 (void)QFile::remove(tempLogfile);
478 constexpr int bufferSize = 256 * 1024;
479 buffer.resize(bufferSize);
481 const qint64 n = in.read(buffer.data(), buffer.size());
486 const QString error = tr(
"Unable to save telemetry log. Error reading source '%1': '%2'.")
487 .arg(tempLogfile, in.errorString());
490 (void)QFile::remove(tempLogfile);
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());
498 (void)QFile::remove(tempLogfile);
504 constexpr QFileDevice::Permissions perms =
505 QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther;
506 (void) out.setPermissions(perms);
509 const QString error =
510 tr(
"Unable to finalize telemetry log '%1': '%2'.").arg(saveFilePath, out.errorString());
512 (void)QFile::remove(tempLogfile);
517 (void)QFile::remove(tempLogfile);
520bool MAVLinkProtocol::_checkTelemetrySavePath()
523 if (saveDirPath.isEmpty()) {
524 const QString error = tr(
"Unable to save telemetry log. Application save directory is not set.");
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);
540void MAVLinkProtocol::_vehicleCountChanged()
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)
void checkForLostLogFiles()
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 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)
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.