QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
OnboardLogController.cc
Go to the documentation of this file.
2#include "AppSettings.h"
3#include "FTPManager.h"
4#include "OnboardLogEntry.h"
5#include "MAVLinkLib.h"
6#include "MAVLinkProtocol.h"
8#include "ParameterManager.h"
9#include "QGCFormat.h"
10#include "QGCLoggingCategory.h"
11#include "QmlObjectListModel.h"
12#include "SettingsManager.h"
13#include "Vehicle.h"
14#include "VehicleLinkManager.h"
15
16#include <algorithm>
17
18#include <QtCore/QApplicationStatic>
19#include <QtCore/QDir>
20#include <QtCore/QTimeZone>
21#include <QtCore/QTimer>
22
23QGC_LOGGING_CATEGORY(OnboardLogControllerLog, "AnalyzeView.OnboardLogController")
24
25// MAVLink FTP defines "@MAV_LOG" as the virtual log directory.
26// Older firmware that doesn't implement the alias requires the physical path
27// instead — which is firmware-specific.
28static constexpr const char *kMavlinkLogRoot = "@MAV_LOG";
29static constexpr const char *kPx4LogRootFallback = "/fs/microsd/log";
30static constexpr const char *kApmLogRootFallback = "/APM/LOGS";
31
33 : QObject(parent)
34 , _timer(new QTimer(this))
35 , _logEntriesModel(new QmlObjectListModel(this))
36{
37 qCDebug(OnboardLogControllerLog) << this;
38
39 (void) connect(MultiVehicleManager::instance(), &MultiVehicleManager::activeVehicleChanged, this, &OnboardLogController::_setActiveVehicle);
40 (void) connect(_timer, &QTimer::timeout, this, &OnboardLogController::_processDownload);
41
42 _timer->setSingleShot(false);
43
44 _setActiveVehicle(MultiVehicleManager::instance()->activeVehicle());
45}
46
48{
49 qCDebug(OnboardLogControllerLog) << this;
50}
51
52bool OnboardLogController::_vehicleArmed() const
53{
54 return _vehicle && _vehicle->armed();
55}
56
57void OnboardLogController::_vehicleArmedChanged(bool armed)
58{
59 if (armed && (_requestingLogEntries || _downloadingLogs)) {
60 qCDebug(OnboardLogControllerLog) << "vehicle armed - canceling log transfer";
61 cancel();
62 }
63}
64
65void OnboardLogController::download(const QString &path)
66{
67 if (_vehicleArmed()) {
68 qCWarning(OnboardLogControllerLog) << "ignored - vehicle is armed";
69 return;
70 }
71
72 const QString dir = path.isEmpty() ? SettingsManager::instance()->appSettings()->logSavePath() : path;
73 if (_transport == Transport::Ftp) {
74 _ftpDownloadToDirectory(dir);
75 } else {
76 _downloadToDirectory(dir);
77 }
78}
79
80void OnboardLogController::_downloadToDirectory(const QString &dir)
81{
82 _receivedAllEntries();
83
84 _downloadData.reset();
85
86 _downloadPath = dir;
87 if (_downloadPath.isEmpty()) {
88 return;
89 }
90
91 if (!_downloadPath.endsWith(QDir::separator())) {
92 _downloadPath += QDir::separator();
93 }
94
95 QGCOnboardLogEntry *const log = _getNextSelected();
96 if (log) {
97 log->setStatus(tr("Waiting"));
98 }
99
100 _setDownloading(true);
101 _receivedAllData();
102}
103
104void OnboardLogController::_processDownload()
105{
106 if (_requestingLogEntries) {
107 _findMissingEntries();
108 } else if (_downloadingLogs) {
109 _findMissingData();
110 }
111}
112
113void OnboardLogController::_findMissingEntries()
114{
115 const int num_logs = _logEntriesModel->count();
116 int start = -1;
117 int end = -1;
118 for (int i = 0; i < num_logs; i++) {
119 const QGCOnboardLogEntry *const entry = _logEntriesModel->value<const QGCOnboardLogEntry*>(i);
120 if (!entry) {
121 continue;
122 }
123
124 if (!entry->received()) {
125 if (start < 0) {
126 start = i;
127 } else {
128 end = i;
129 }
130 } else if (start >= 0) {
131 break;
132 }
133 }
134
135 if (start < 0) {
136 _receivedAllEntries();
137 return;
138 }
139
140 if (_retries++ > 2) {
141 for (int i = 0; i < num_logs; i++) {
142 QGCOnboardLogEntry *const entry = _logEntriesModel->value<QGCOnboardLogEntry*>(i);
143 if (entry && !entry->received()) {
144 entry->setStatus(tr("Error"));
145 }
146 }
147
148 _receivedAllEntries();
149 qCWarning(OnboardLogControllerLog) << "Too many errors retreiving log list. Giving up.";
150 return;
151 }
152
153 if (end < 0) {
154 end = start;
155 }
156
157 start += _apmOffset;
158 end += _apmOffset;
159
160 _requestLogList(static_cast<uint32_t>(start), static_cast<uint32_t>(end));
161}
162
163void OnboardLogController::_setActiveVehicle(Vehicle *vehicle)
164{
165 if (vehicle == _vehicle) {
166 return;
167 }
168
169 if (_vehicle) {
170 // Tear down any in-progress messages-transport activity before the entries
171 // it references are deleted with the model
172 _timer->stop();
173 if (_downloadData) {
174 if (_downloadData->file.exists()) {
175 (void) _downloadData->file.remove();
176 }
177 _downloadData.reset();
178 }
179 _setDownloading(false);
180 _setListing(false);
181
182 _logEntriesModel->clearAndDeleteContents();
183 (void) disconnect(_vehicle, &Vehicle::logEntry, this, &OnboardLogController::_logEntry);
184 (void) disconnect(_vehicle, &Vehicle::logData, this, &OnboardLogController::_logData);
185 (void) disconnect(_vehicle, &Vehicle::armedChanged, this, &OnboardLogController::_vehicleArmedChanged);
186
187 FTPManager *const ftp = _vehicle->ftpManager();
188 (void) disconnect(ftp, &FTPManager::listDirectoryComplete, this, &OnboardLogController::_ftpListDirComplete);
189 (void) disconnect(ftp, &FTPManager::downloadComplete, this, &OnboardLogController::_ftpDownloadComplete);
190 (void) disconnect(ftp, &FTPManager::commandProgress, this, &OnboardLogController::_ftpDownloadProgress);
191 (void) disconnect(ftp, &FTPManager::deleteComplete, this, &OnboardLogController::_ftpDeleteComplete);
192
193 _ftpListState = FtpListState::Idle;
194 _ftpDirsToList.clear();
195 _ftpLogIdCounter = 0;
196 _ftpDownloadQueue.clear();
197 _ftpDeleteQueue.clear();
198 _ftpDeleting = false;
199 _ftpCurrentDownloadEntry = nullptr;
200 _ftpDisabled = false;
201 _ftpDownloadHadError = false;
202 _setTransport(Transport::Messages);
203 }
204
205 _vehicle = vehicle;
206
207 if (_vehicle) {
208 (void) connect(_vehicle, &Vehicle::logEntry, this, &OnboardLogController::_logEntry);
209 (void) connect(_vehicle, &Vehicle::logData, this, &OnboardLogController::_logData);
210 (void) connect(_vehicle, &Vehicle::armedChanged, this, &OnboardLogController::_vehicleArmedChanged);
211
212 FTPManager *const ftp = _vehicle->ftpManager();
213 (void) connect(ftp, &FTPManager::listDirectoryComplete, this, &OnboardLogController::_ftpListDirComplete);
214 (void) connect(ftp, &FTPManager::downloadComplete, this, &OnboardLogController::_ftpDownloadComplete);
215 (void) connect(ftp, &FTPManager::commandProgress, this, &OnboardLogController::_ftpDownloadProgress);
216 (void) connect(ftp, &FTPManager::deleteComplete, this, &OnboardLogController::_ftpDeleteComplete);
217 }
218}
219
220void OnboardLogController::_logEntry(uint32_t time_utc, uint32_t size, uint16_t id, uint16_t num_logs, uint16_t last_log_num)
221{
222 Q_UNUSED(last_log_num);
223
224 if (!_requestingLogEntries || (_transport != Transport::Messages)) {
225 return;
226 }
227
228 if ((_logEntriesModel->count() == 0) && (num_logs > 0)) {
229 if (_vehicle->firmwareType() == MAV_AUTOPILOT_ARDUPILOTMEGA) {
230 // APM ID starts at 1
231 _apmOffset = 1;
232 }
233
234 for (int i = 0; i < num_logs; i++) {
235 QGCOnboardLogEntry *const entry = new QGCOnboardLogEntry(i);
237 _logEntriesModel->append(entry);
238 }
239 }
240
241 if (num_logs > 0) {
242 if ((size > 0) || (_vehicle->firmwareType() != MAV_AUTOPILOT_ARDUPILOTMEGA)) {
243 id -= _apmOffset;
244 if (id < _logEntriesModel->count()) {
245 QGCOnboardLogEntry *const entry = _logEntriesModel->value<QGCOnboardLogEntry*>(id);
246 entry->setSize(size);
247 entry->setTime(QDateTime::fromSecsSinceEpoch(time_utc));
248 entry->setReceived(true);
249 entry->setStatus(tr("Available"));
250 } else {
251 qCWarning(OnboardLogControllerLog) << "Received onboard log entry for out-of-bound index:" << id;
252 }
253 }
254 } else {
255 _receivedAllEntries();
256 }
257
258 _retries = 0;
259
260 if (_entriesComplete()) {
261 _receivedAllEntries();
262 } else {
263 _timer->start(kTimeOutMs);
264 }
265}
266
267void OnboardLogController::_receivedAllEntries()
268{
269 _timer->stop();
270 _setListing(false);
271}
272
273bool OnboardLogController::_entriesComplete() const
274{
275 const int num_logs = _logEntriesModel->count();
276 for (int i = 0; i < num_logs; i++) {
277 const QGCOnboardLogEntry *const entry = _logEntriesModel->value<const QGCOnboardLogEntry*>(i);
278 if (!entry) {
279 continue;
280 }
281
282 if (!entry->received()) {
283 return false;
284 }
285 }
286
287 return true;
288}
289
290void OnboardLogController::_logData(uint32_t ofs, uint16_t id, uint8_t count, const uint8_t *data)
291{
292 if (!_downloadingLogs || !_downloadData || (_transport != Transport::Messages)) {
293 return;
294 }
295
296 id -= _apmOffset;
297 if (_downloadData->ID != id) {
298 qCWarning(OnboardLogControllerLog) << "Received log data for wrong log";
299 return;
300 }
301
302 if ((ofs % MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN) != 0) {
303 qCWarning(OnboardLogControllerLog) << "Ignored misaligned incoming packet @" << ofs;
304 return;
305 }
306
307 bool result = false;
308 if (ofs <= _downloadData->entry->size()) {
309 const uint32_t chunk = ofs / OnboardLogDownloadData::kChunkSize;
310 // qCDebug(OnboardLogControllerLog) << "Received data - Offset:" << ofs << "Chunk:" << chunk;
311 if (chunk != _downloadData->current_chunk) {
312 qCWarning(OnboardLogControllerLog) << "Ignored packet for out of order chunk actual:expected" << chunk << _downloadData->current_chunk;
313 return;
314 }
315
316 const uint16_t bin = (ofs - (chunk * OnboardLogDownloadData::kChunkSize)) / MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN;
317 if (bin >= _downloadData->chunk_table.size()) {
318 qCWarning(OnboardLogControllerLog) << "Out of range bin received";
319 } else {
320 _downloadData->chunk_table.setBit(bin);
321 }
322
323 if (_downloadData->file.pos() != ofs) {
324 if (!_downloadData->file.seek(ofs)) {
325 qCWarning(OnboardLogControllerLog) << "Error while seeking log file offset";
326 return;
327 }
328 }
329
330 if (_downloadData->file.write(reinterpret_cast<const char*>(data), count)) {
331 _downloadData->written += count;
332 _downloadData->rate_bytes += count;
333 _updateDataRate();
334
335 result = true;
336 _retries = 0;
337
338 _timer->start(kTimeOutMs);
339 if (_logComplete()) {
340 _downloadData->entry->setStatus(tr("Downloaded"));
341 _receivedAllData();
342 } else if (_chunkComplete()) {
343 _downloadData->advanceChunk();
344 _requestLogData(_downloadData->ID,
345 _downloadData->current_chunk * OnboardLogDownloadData::kChunkSize,
346 _downloadData->chunk_table.size() * MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN);
347 } else if ((bin < (_downloadData->chunk_table.size() - 1)) && _downloadData->chunk_table.at(bin + 1)) {
348 // Likely to be grabbing fragments and got to the end of a gap
349 _findMissingData();
350 }
351 } else {
352 qCWarning(OnboardLogControllerLog) << "Error while writing log file chunk";
353 }
354 } else {
355 qCWarning(OnboardLogControllerLog) << "Received log offset greater than expected";
356 }
357
358 if (!result) {
359 _downloadData->entry->setStatus(tr("Error"));
360 }
361}
362
363void OnboardLogController::_findMissingData()
364{
365 if (_logComplete()) {
366 _receivedAllData();
367 return;
368 }
369
370 if (_chunkComplete()) {
371 _downloadData->advanceChunk();
372 }
373
374 _retries++;
375
376 _updateDataRate();
377
378 uint16_t start = 0, end = 0;
379 const int size = _downloadData->chunk_table.size();
380 for (; start < size; start++) {
381 if (!_downloadData->chunk_table.testBit(start)) {
382 break;
383 }
384 }
385
386 for (end = start; end < size; end++) {
387 if (_downloadData->chunk_table.testBit(end)) {
388 break;
389 }
390 }
391
392 const uint32_t pos = (_downloadData->current_chunk * OnboardLogDownloadData::kChunkSize) + (start * MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN);
393 const uint32_t len = (end - start) * MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN;
394 _requestLogData(_downloadData->ID, pos, len, _retries);
395}
396
397void OnboardLogController::_updateDataRate()
398{
399 constexpr uint kSizeUpdateThreshold = 102400; // 0.1 MB
400 const bool timeThresholdMet = _downloadData->elapsed.elapsed() >= kGUIRateMs;
401 const bool sizeThresholdMet = (_downloadData->written - _downloadData->last_status_written) >= kSizeUpdateThreshold;
402
403 if (!timeThresholdMet && !sizeThresholdMet) {
404 return;
405 }
406
407 QString status;
408 if (timeThresholdMet) {
409 // Update both rate and size
410 const qreal rate = _downloadData->rate_bytes / (_downloadData->elapsed.elapsed() / 1000.0);
411 _downloadData->rate_avg = (_downloadData->rate_avg * 0.95) + (rate * 0.05);
412 _downloadData->rate_bytes = 0;
413
414 status = QStringLiteral("%1 (%2/s)").arg(QGC::bigSizeToString(_downloadData->written),
415 QGC::bigSizeToString(_downloadData->rate_avg));
416 _downloadData->elapsed.start();
417 } else {
418 // Update size only, keep previous rate
419 status = QStringLiteral("%1 (%2/s)").arg(QGC::bigSizeToString(_downloadData->written),
420 QGC::bigSizeToString(_downloadData->rate_avg));
421 }
422
423 _downloadData->entry->setStatus(status);
424 _downloadData->last_status_written = _downloadData->written;
425}
426
427bool OnboardLogController::_chunkComplete() const
428{
429 return _downloadData->chunkEquals(true);
430}
431
432bool OnboardLogController::_logComplete() const
433{
434 return (_chunkComplete() && ((_downloadData->current_chunk + 1) == _downloadData->numChunks()));
435}
436
437void OnboardLogController::_receivedAllData()
438{
439 _timer->stop();
440 while (_prepareLogDownload()) {
441 if (_downloadData->chunk_table.isEmpty()) {
442 // Nothing to request (0 byte log): _logComplete() can never become true and the
443 // vehicle never answers a zero-length request, so the download would stall
444 // forever (issue #15068). The empty file already exists.
445 _downloadData->entry->setStatus(tr("Downloaded"));
446 _downloadData.reset();
447 continue;
448 }
449
450 _requestLogData(_downloadData->ID, 0, _downloadData->chunk_table.size() * MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN);
451 _timer->start(kTimeOutMs);
452 return;
453 }
454
455 _resetSelection();
456 _setDownloading(false);
457}
458
459bool OnboardLogController::_prepareLogDownload()
460{
461 _downloadData.reset();
462
463 QGCOnboardLogEntry *const entry = _getNextSelected();
464 if (!entry) {
465 return false;
466 }
467
468 entry->setSelected(false);
469 emit selectionChanged();
470
471 const QString ftime = (entry->time().date().year() >= 2010) ? entry->time().toString(QStringLiteral("yyyy-M-d-hh-mm-ss")) : QStringLiteral("UnknownDate");
472
473 _downloadData = std::make_unique<OnboardLogDownloadData>(entry);
474 _downloadData->filename = QStringLiteral("log_") + QString::number(entry->id()) + "_" + ftime;
475
476 if (_vehicle->firmwareType() == MAV_AUTOPILOT_PX4) {
477 const QString loggerParam = QStringLiteral("SYS_LOGGER");
478 ParameterManager *const parameterManager = _vehicle->parameterManager();
479 Fact *const loggerFact = parameterManager->parameterExists(ParameterManager::defaultComponentId, loggerParam) ? parameterManager->getParameter(ParameterManager::defaultComponentId, loggerParam) : nullptr;
480 if (loggerFact && (loggerFact->rawValue().toInt() == 0)) {
481 _downloadData->filename += ".px4log";
482 } else {
483 _downloadData->filename += ".ulg";
484 }
485 } else {
486 _downloadData->filename += ".bin";
487 }
488
489 _downloadData->file.setFileName(_downloadPath + _downloadData->filename);
490
491 if (_downloadData->file.exists()) {
492 uint32_t numDups = 0;
493 const QStringList filename_spl = _downloadData->filename.split('.');
494 do {
495 numDups += 1;
496 const QString filename = filename_spl[0] + '_' + QString::number(numDups) + '.' + filename_spl[1];
497 _downloadData->file.setFileName(_downloadPath + filename);
498 } while ( _downloadData->file.exists());
499 }
500
501 bool result = false;
502 if (!_downloadData->file.open(QIODevice::WriteOnly)) {
503 qCWarning(OnboardLogControllerLog) << "Failed to create log file:" << _downloadData->filename;
504 } else if (!_downloadData->file.resize(entry->size())) {
505 qCWarning(OnboardLogControllerLog) << "Failed to allocate space for log file:" << _downloadData->filename;
506 } else {
507 _downloadData->current_chunk = 0;
508 _downloadData->chunk_table = QBitArray(_downloadData->chunkBins(), false);
509 _downloadData->elapsed.start();
510 result = true;
511 }
512
513 if (!result) {
514 if (_downloadData->file.exists()) {
515 (void) _downloadData->file.remove();
516 }
517
518 _downloadData->entry->setStatus(tr("Error"));
519 _downloadData.reset();
520 }
521
522 return result;
523}
524
526{
527 if (_downloadingLogs || _requestingLogEntries || _ftpDeleting) {
528 // Re-entering the page while a transfer is active must not clear the model:
529 // the transfer holds pointers into it (issue #14881)
530 qCDebug(OnboardLogControllerLog) << "refresh: ignored - transfer in progress";
531 return;
532 }
533
534 if (_vehicleArmed()) {
535 qCWarning(OnboardLogControllerLog) << "ignored - vehicle is armed";
536 return;
537 }
538
539 _logEntriesModel->clearAndDeleteContents();
540 emit selectionChanged();
541
542 if (_vehicle && !_ftpDisabled && _vehicle->capabilitiesKnown() && (_vehicle->capabilityBits() & MAV_PROTOCOL_CAPABILITY_FTP)) {
543 qCDebug(OnboardLogControllerLog) << "refresh: using ftp transport";
544 _setTransport(Transport::Ftp);
545 _ftpStartListing();
546 } else {
547 qCDebug(OnboardLogControllerLog) << "refresh: using message transport - ftpDisabled:" << _ftpDisabled
548 << "capabilitiesKnown:" << (_vehicle && _vehicle->capabilitiesKnown())
549 << "ftpCapable:" << bool(_vehicle && (_vehicle->capabilityBits() & MAV_PROTOCOL_CAPABILITY_FTP));
550 _setTransport(Transport::Messages);
551 _requestLogList(0, 0xffff);
552 }
553}
554
555QGCOnboardLogEntry *OnboardLogController::_getNextSelected() const
556{
557 const int numLogs = _logEntriesModel->count();
558 for (int i = 0; i < numLogs; i++) {
559 QGCOnboardLogEntry *const entry = _logEntriesModel->value<QGCOnboardLogEntry*>(i);
560 if (!entry) {
561 continue;
562 }
563
564 if (entry->selected()) {
565 return entry;
566 }
567 }
568
569 return nullptr;
570}
571
573{
574 if (_transport == Transport::Ftp) {
575 if (_vehicle) {
576 if (_requestingLogEntries) {
577 // Idle first: cancelListDirectory() completes synchronously and the abort
578 // completion must not start the fallback-root listing
579 _ftpListState = FtpListState::Idle;
580 _ftpDirsToList.clear();
581 _vehicle->ftpManager()->cancelListDirectory();
582 _setListing(false);
583 }
584
585 if (_ftpDeleting) {
586 // The in-flight delete can't be aborted. Drop the queued deletes and let
587 // _ftpDeleteComplete finish the cycle with an automatic refresh.
588 _ftpDeleteQueue.clear();
589 _resetSelection(true);
590 return;
591 }
592
593 if (_downloadingLogs) {
594 // cancelDownload completes synchronously; detach the entry first so it is not stamped as an error
595 if (_ftpCurrentDownloadEntry) {
596 _ftpCurrentDownloadEntry->setStatus(tr("Canceled"));
597 _ftpCurrentDownloadEntry = nullptr;
598 }
599 _ftpDownloadQueue.clear();
600 _vehicle->ftpManager()->cancelDownload();
601 }
602 }
603 } else {
604 _requestLogEnd();
605 _receivedAllEntries();
606
607 if (_downloadData) {
608 _downloadData->entry->setStatus(tr("Canceled"));
609 if (_downloadData->file.exists()) {
610 (void) _downloadData->file.remove();
611 }
612
613 _downloadData.reset();
614 }
615 }
616
617 _resetSelection(true);
618 _setDownloading(false);
619}
620
622{
623 const int count = _logEntriesModel->count();
624 for (int i = 0; i < count; i++) {
625 QGCOnboardLogEntry *const entry = _logEntriesModel->value<QGCOnboardLogEntry*>(i);
626 if (!entry || !entry->received()) {
627 continue;
628 }
629
630 if (entry->selected() != select) {
631 // Suppress the per-entry connection to avoid O(n²) allLogsSelected()
632 // re-evaluations. The entry still notifies its own QML bindings.
633 // A single selectionChanged() is emitted after the loop.
635 entry->setSelected(select);
637 }
638 }
639 emit selectionChanged();
640}
641
643{
644 int selected = 0;
645 const int count = _logEntriesModel->count();
646 for (int i = 0; i < count; i++) {
647 const QGCOnboardLogEntry *const entry = _logEntriesModel->value<const QGCOnboardLogEntry*>(i);
648 if (entry && entry->received() && entry->selected()) {
649 selected++;
650 }
651 }
652
653 return selected;
654}
655
657{
658 int selectable = 0;
659 int selected = 0;
660 const int count = _logEntriesModel->count();
661 for (int i = 0; i < count; i++) {
662 const QGCOnboardLogEntry *const entry = _logEntriesModel->value<const QGCOnboardLogEntry*>(i);
663 if (entry && entry->received()) {
664 selectable++;
665 if (entry->selected()) {
666 selected++;
667 }
668 }
669 }
670
671 return (selectable > 0) && (selected == selectable);
672}
673
675{
676 setSortAscending(!_sortAscending);
677}
678
680{
681 if (_sortAscending == ascending) {
682 return;
683 }
684
685 _sortAscending = ascending;
686 _sortEntriesByTimestamp();
688}
689
690void OnboardLogController::_resetSelection(bool canceled)
691{
692 const int num_logs = _logEntriesModel->count();
693 for (int i = 0; i < num_logs; i++) {
694 QGCOnboardLogEntry *const entry = _logEntriesModel->value<QGCOnboardLogEntry*>(i);
695 if (!entry) {
696 continue;
697 }
698
699 if (entry->selected()) {
700 if (canceled) {
701 entry->setStatus(tr("Canceled"));
702 }
703 entry->setSelected(false);
704 }
705 }
706
707 emit selectionChanged();
708}
709
710void OnboardLogController::_sortEntriesByTimestamp()
711{
712 QObjectList sortedEntries = *_logEntriesModel->objectList();
713 std::stable_sort(sortedEntries.begin(), sortedEntries.end(), [this](const QObject *lhsObj, const QObject *rhsObj) {
714 const QGCOnboardLogEntry *const lhs = qobject_cast<const QGCOnboardLogEntry*>(lhsObj);
715 const QGCOnboardLogEntry *const rhs = qobject_cast<const QGCOnboardLogEntry*>(rhsObj);
716 if (lhs == rhs) {
717 return false;
718 }
719 if (!lhs) {
720 return false;
721 }
722 if (!rhs) {
723 return true;
724 }
725
726 const bool lhsHasTime = lhs->received() && (lhs->time().toSecsSinceEpoch() > 0);
727 const bool rhsHasTime = rhs->received() && (rhs->time().toSecsSinceEpoch() > 0);
728 if (lhsHasTime != rhsHasTime) {
729 // Keep entries with valid timestamps grouped first.
730 return lhsHasTime;
731 }
732
733 if (lhsHasTime && rhsHasTime) {
734 if (lhs->time() == rhs->time()) {
735 return _sortAscending ? (lhs->id() < rhs->id()) : (lhs->id() > rhs->id());
736 }
737
738 return _sortAscending ? (lhs->time() < rhs->time()) : (lhs->time() > rhs->time());
739 }
740
741 // Fallback for entries with missing/invalid time.
742 return _sortAscending ? (lhs->id() < rhs->id()) : (lhs->id() > rhs->id());
743 });
744
745 (void) _logEntriesModel->swapObjectList(sortedEntries);
746}
747
749{
750 if (!_vehicle) {
751 qCWarning(OnboardLogControllerLog) << "Vehicle Unavailable";
752 return;
753 }
754
755 if (_vehicleArmed()) {
756 qCWarning(OnboardLogControllerLog) << "ignored - vehicle is armed";
757 return;
758 }
759
760 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
761 if (!sharedLink) {
762 qCWarning(OnboardLogControllerLog) << "Link Unavailable";
763 return;
764 }
765
766 mavlink_message_t msg{};
767 (void) mavlink_msg_log_erase_pack_chan(
768 MAVLinkProtocol::instance()->getSystemId(),
770 sharedLink->mavlinkChannel(),
771 &msg,
772 _vehicle->id(),
773 _vehicle->defaultComponentId()
774 );
775
776 if (!_vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg)) {
777 qCWarning(OnboardLogControllerLog) << "Failed to send";
778 return;
779 }
780
781 refresh();
782}
783
785{
786 if (!_vehicle) {
787 qCWarning(OnboardLogControllerLog) << "Vehicle Unavailable";
788 return;
789 }
790
791 if (_vehicleArmed()) {
792 qCWarning(OnboardLogControllerLog) << "ignored - vehicle is armed";
793 return;
794 }
795
796 if (_transport != Transport::Ftp) {
797 qCWarning(OnboardLogControllerLog) << "ftp: selective erase requires the FTP transport";
798 return;
799 }
800
801 _ftpDeleteQueue.clear();
802 const int numLogs = _logEntriesModel->count();
803 for (int i = 0; i < numLogs; i++) {
804 QGCOnboardLogEntry *const entry = _logEntriesModel->value<QGCOnboardLogEntry*>(i);
805 if (entry && entry->selected() && !entry->ftpPath().isEmpty()) {
806 _ftpDeleteQueue.enqueue(entry);
807 }
808 }
809
810 if (_ftpDeleteQueue.isEmpty()) {
811 qCWarning(OnboardLogControllerLog) << "ftp: no selected logs have FTP paths for erase";
812 return;
813 }
814
815 qCDebug(OnboardLogControllerLog) << "ftp: erasing" << _ftpDeleteQueue.size() << "selected logs";
816 _ftpDeleting = true;
817 _setDownloading(true);
818 _ftpDeleteNext();
819}
820
821void OnboardLogController::_ftpDeleteNext()
822{
823 if (_ftpDeleteQueue.isEmpty()) {
824 _ftpDeleting = false;
825 _setDownloading(false);
826 if (_vehicleArmed()) {
827 // The in-flight delete's outcome is unknown, so drop the list instead of leaving a stale entry selectable
828 _logEntriesModel->clearAndDeleteContents();
829 emit selectionChanged();
830 } else {
831 refresh();
832 }
833 return;
834 }
835
836 QGCOnboardLogEntry *const entry = _ftpDeleteQueue.dequeue();
837 entry->setSelected(false);
838 entry->setStatus(tr("Erasing"));
839
840 qCDebug(OnboardLogControllerLog) << "ftp: deleting" << entry->ftpPath();
841
842 if (!_vehicle->ftpManager()->deleteFile(MAV_COMP_ID_AUTOPILOT1, entry->ftpPath())) {
843 qCWarning(OnboardLogControllerLog) << "ftp: failed to start delete for" << entry->ftpPath();
844 entry->setStatus(tr("Error"));
845 _ftpDeleteNext();
846 }
847}
848
849void OnboardLogController::_ftpDeleteComplete(const QString &file, const QString &errorMsg)
850{
851 if (!_ftpDeleting) {
852 return;
853 }
854
855 if (!errorMsg.isEmpty()) {
856 qCWarning(OnboardLogControllerLog) << "ftp: delete error:" << file << errorMsg;
857 }
858
859 _ftpDeleteNext();
860}
861
862void OnboardLogController::_requestLogList(uint32_t start, uint32_t end)
863{
864 if (!_vehicle) {
865 qCWarning(OnboardLogControllerLog) << "Vehicle Unavailable";
866 return;
867 }
868
869 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
870 if (!sharedLink) {
871 qCWarning(OnboardLogControllerLog) << "Link Unavailable";
872 return;
873 }
874
875 mavlink_message_t msg{};
876 (void) mavlink_msg_log_request_list_pack_chan(
877 MAVLinkProtocol::instance()->getSystemId(),
879 sharedLink->mavlinkChannel(),
880 &msg,
881 _vehicle->id(),
882 _vehicle->defaultComponentId(),
883 start,
884 end
885 );
886
887 if (!_vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg)) {
888 qCWarning(OnboardLogControllerLog) << "Failed to send";
889 return;
890 }
891
892 qCDebug(OnboardLogControllerLog) << "Request onboard log entry list (" << start << "through" << end << ")";
893 _setListing(true);
894 _timer->start(kRequestLogListTimeoutMs);
895}
896
897void OnboardLogController::_requestLogData(uint16_t id, uint32_t offset, uint32_t count, int retryCount)
898{
899 if (!_vehicle) {
900 qCWarning(OnboardLogControllerLog) << "Vehicle Unavailable";
901 return;
902 }
903
904 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
905 if (!sharedLink) {
906 qCWarning(OnboardLogControllerLog) << "Link Unavailable";
907 return;
908 }
909
910 id += _apmOffset;
911 qCDebug(OnboardLogControllerLog) << "Request log data (id:" << id << "offset:" << offset << "size:" << count << "retryCount" << retryCount << ")";
912
913 mavlink_message_t msg{};
914 (void) mavlink_msg_log_request_data_pack_chan(
915 MAVLinkProtocol::instance()->getSystemId(),
917 sharedLink->mavlinkChannel(),
918 &msg,
919 _vehicle->id(),
920 _vehicle->defaultComponentId(),
921 id,
922 offset,
923 count
924 );
925
926 if (!_vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg)) {
927 qCWarning(OnboardLogControllerLog) << "Failed to send";
928 }
929}
930
931void OnboardLogController::_requestLogEnd()
932{
933 if (!_vehicle) {
934 qCWarning(OnboardLogControllerLog) << "Vehicle Unavailable";
935 return;
936 }
937
938 SharedLinkInterfacePtr sharedLink = _vehicle->vehicleLinkManager()->primaryLink().lock();
939 if (!sharedLink) {
940 qCWarning(OnboardLogControllerLog) << "Link Unavailable";
941 return;
942 }
943
944 mavlink_message_t msg{};
945 (void) mavlink_msg_log_request_end_pack_chan(
946 MAVLinkProtocol::instance()->getSystemId(),
948 sharedLink->mavlinkChannel(),
949 &msg,
950 _vehicle->id(),
951 _vehicle->defaultComponentId()
952 );
953
954 if (!_vehicle->sendMessageOnLinkThreadSafe(sharedLink.get(), msg)) {
955 qCWarning(OnboardLogControllerLog) << "Failed to send";
956 }
957}
958
959void OnboardLogController::_setDownloading(bool active)
960{
961 if (_downloadingLogs != active) {
962 _downloadingLogs = active;
963 if (_vehicle) {
964 _vehicle->vehicleLinkManager()->setCommunicationLostEnabled(!active);
965 }
967 }
968}
969
970void OnboardLogController::_setListing(bool active)
971{
972 if (_requestingLogEntries != active) {
973 _requestingLogEntries = active;
974 if (_vehicle) {
975 _vehicle->vehicleLinkManager()->setCommunicationLostEnabled(!active);
976 }
977 if (!active) {
978 _sortEntriesByTimestamp();
979 }
981 }
982}
983
984void OnboardLogController::_setTransport(Transport transport)
985{
986 if (_transport != transport) {
987 _transport = transport;
988 emit transportChanged();
989 }
990}
991
992void OnboardLogController::_ftpStartListing()
993{
994 _ftpDirsToList.clear();
995 _ftpLogIdCounter = 0;
996 _ftpLogRoot = QString::fromLatin1(kMavlinkLogRoot);
997 _ftpTriedFallbackRoot = false;
998
999 _setListing(true);
1000 _ftpListRoot();
1001}
1002
1003void OnboardLogController::_ftpListRoot()
1004{
1005 _ftpListState = FtpListState::ListingRoot;
1006
1007 qCDebug(OnboardLogControllerLog) << "ftp: listing root" << _ftpLogRoot;
1008
1009 if (!_vehicle->ftpManager()->listDirectory(MAV_COMP_ID_AUTOPILOT1, _ftpLogRoot)) {
1010 qCWarning(OnboardLogControllerLog) << "ftp: failed to start root listing for" << _ftpLogRoot;
1011 _ftpFallbackToMessages();
1012 }
1013}
1014
1015void OnboardLogController::_ftpListDirComplete(const QStringList &dirList, const QString &errorMsg)
1016{
1017 if (_ftpListState == FtpListState::Idle) {
1018 return;
1019 }
1020
1021 if (!errorMsg.isEmpty()) {
1022 if ((_ftpListState == FtpListState::ListingRoot) && !_ftpTriedFallbackRoot && _vehicle) {
1023 const char *fallback = nullptr;
1024 if (_vehicle->px4Firmware()) {
1025 fallback = kPx4LogRootFallback;
1026 } else if (_vehicle->apmFirmware()) {
1027 fallback = kApmLogRootFallback;
1028 }
1029
1030 if (fallback) {
1031 qCDebug(OnboardLogControllerLog) << "ftp: root listing of" << _ftpLogRoot << "failed (" << errorMsg
1032 << "), falling back to" << fallback;
1033 _ftpTriedFallbackRoot = true;
1034 _ftpLogRoot = QString::fromLatin1(fallback);
1035 _ftpListRoot();
1036 return;
1037 }
1038 }
1039
1040 qCWarning(OnboardLogControllerLog) << "ftp: listing error:" << errorMsg;
1041 _ftpFallbackToMessages();
1042 return;
1043 }
1044
1045 // Raw entries expose whether the server included the optional mtime field (date/time diagnosis)
1046 qCDebug(OnboardLogControllerLog) << "ftp: raw entries for"
1047 << ((_ftpListState == FtpListState::ListingRoot) ? _ftpLogRoot : (_ftpDirsToList.isEmpty() ? QString() : _ftpDirsToList.first()))
1048 << dirList;
1049
1050 if (_ftpListState == FtpListState::ListingRoot) {
1051 // The root listing may contain log files directly (flat layout, e.g. @MAV_LOG)
1052 // and/or date subdirectories to descend into (PX4 fallback /fs/microsd/log).
1053 const uint flatLogs = _ftpProcessFileEntries(dirList, QString());
1054
1055 // A kCmdListDirectoryWithTime listing may give a directory the same trailing
1056 // fields as a file: "D<name>\t<size>\t<modification time>". Servers differ on
1057 // whether they send them (MAVSDK does, PX4 does not), so tolerate either. A
1058 // plain kCmdListDirectory entry is just "D<name>", where a tab would be part
1059 // of the name, so only strip the fields when times were asked for.
1060 const bool withTime = _vehicle && !_vehicle->ftpManager()->listDirectoryWithTimeUnsupported();
1061
1062 for (const QString &entry : dirList) {
1063 if (entry.startsWith(QLatin1Char('D'))) {
1064 QString dirName = entry.mid(1);
1065 if (withTime) {
1066 dirName = dirName.section(QLatin1Char('\t'), 0, 0);
1067 }
1068 // Some servers list "." and ".."; descending into those would
1069 // list this directory again, or its parent (ArduPilot sends
1070 // them, PX4 does not).
1071 if (!dirName.isEmpty() &&
1072 (dirName != QStringLiteral(".")) && (dirName != QStringLiteral(".."))) {
1073 _ftpDirsToList.append(dirName);
1074 }
1075 }
1076 }
1077
1078 _ftpDirsToList.sort();
1079 qCDebug(OnboardLogControllerLog) << "ftp: root listing of" << _ftpLogRoot
1080 << "found" << flatLogs << "flat logs and" << _ftpDirsToList.size() << "subdirectories";
1081
1082 _ftpListState = FtpListState::ListingSubdir;
1083 _ftpListNextSubdir();
1084 return;
1085 }
1086
1087 const QString currentDir = _ftpDirsToList.isEmpty() ? QString() : _ftpDirsToList.first();
1088 const uint logsFoundInDir = _ftpProcessFileEntries(dirList, currentDir);
1089
1090 qCDebug(OnboardLogControllerLog) << "ftp:" << currentDir << "->" << logsFoundInDir << "logs";
1091
1092 if (!_ftpDirsToList.isEmpty()) {
1093 _ftpDirsToList.removeFirst();
1094 }
1095
1096 _ftpListNextSubdir();
1097}
1098
1099uint OnboardLogController::_ftpProcessFileEntries(const QStringList &dirList, const QString &subdir)
1100{
1101 const QDate dirDate = subdir.isEmpty() ? QDate() : QDate::fromString(subdir, QStringLiteral("yyyy-MM-dd"));
1102 uint logsFound = 0;
1103
1104 for (const QString &entry : dirList) {
1105 if (!entry.startsWith(QLatin1Char('F'))) {
1106 continue;
1107 }
1108
1109 // Entry format is "F<name>\t<size>" and, when the server supports kCmdListDirectoryWithTime,
1110 // "F<name>\t<size>\t<modification time in seconds since UNIX epoch UTC>".
1111 const QString fileInfo = entry.mid(1);
1112 const int tabIdx = fileInfo.indexOf(QLatin1Char('\t'));
1113 if (tabIdx < 0) {
1114 continue;
1115 }
1116
1117 const QString fileName = fileInfo.left(tabIdx);
1118 const QString sizeStr = fileInfo.section(QLatin1Char('\t'), 1, 1);
1119 const QString mtimeStr = fileInfo.section(QLatin1Char('\t'), 2, 2);
1120
1121 if (!fileName.endsWith(QStringLiteral(".ulg"), Qt::CaseInsensitive) &&
1122 !fileName.endsWith(QStringLiteral(".bin"), Qt::CaseInsensitive)) {
1123 continue;
1124 }
1125
1126 bool sizeOk = false;
1127 const uint fileSize = sizeStr.toUInt(&sizeOk);
1128 if (!sizeOk) {
1129 continue;
1130 }
1131
1132 QDateTime dateTime;
1133
1134 // Prefer the modification time reported by the vehicle when available (0 means unknown).
1135 bool mtimeOk = false;
1136 const qint64 mtimeSecs = mtimeStr.toLongLong(&mtimeOk);
1137 if (mtimeOk && (mtimeSecs > 0)) {
1138 dateTime = QDateTime::fromSecsSinceEpoch(mtimeSecs, QTimeZone::UTC);
1139 }
1140
1141 // Otherwise reconstruct the date from the date sub-directory name and the filename time.
1142 if (!dateTime.isValid() && dirDate.isValid()) {
1143 const QString baseName = fileName.left(fileName.lastIndexOf(QLatin1Char('.')));
1144 const QTime fileTime = QTime::fromString(baseName, QStringLiteral("HH_mm_ss"));
1145 if (fileTime.isValid()) {
1146 dateTime = QDateTime(dirDate, fileTime, QTimeZone::UTC);
1147 } else {
1148 dateTime = QDateTime(dirDate, QTime(), QTimeZone::UTC);
1149 }
1150 }
1151
1152 const QString ftpPath = subdir.isEmpty()
1153 ? (_ftpLogRoot + QStringLiteral("/") + fileName)
1154 : (_ftpLogRoot + QStringLiteral("/") + subdir + QStringLiteral("/") + fileName);
1155
1156 QGCOnboardLogEntry *const logEntry = new QGCOnboardLogEntry(_ftpLogIdCounter++, dateTime, fileSize, true);
1157 logEntry->setFtpPath(ftpPath);
1158 logEntry->setStatus(tr("Available"));
1160 _logEntriesModel->append(logEntry);
1161 logsFound++;
1162 }
1163
1164 return logsFound;
1165}
1166
1167void OnboardLogController::_ftpListNextSubdir()
1168{
1169 if (_ftpDirsToList.isEmpty()) {
1170 qCDebug(OnboardLogControllerLog) << "ftp: listing complete, found" << _logEntriesModel->count() << "logs";
1171 _ftpFinishListing();
1172 return;
1173 }
1174
1175 const QString subdir = _ftpDirsToList.first();
1176 const QString path = _ftpLogRoot + QStringLiteral("/") + subdir;
1177
1178 qCDebug(OnboardLogControllerLog) << "ftp: listing subdir" << path;
1179
1180 if (!_vehicle->ftpManager()->listDirectory(MAV_COMP_ID_AUTOPILOT1, path)) {
1181 qCWarning(OnboardLogControllerLog) << "ftp: failed to list subdir" << path;
1182 _ftpDirsToList.removeFirst();
1183 _ftpListNextSubdir();
1184 }
1185}
1186
1187void OnboardLogController::_ftpFinishListing()
1188{
1189 _ftpListState = FtpListState::Idle;
1190
1191 // Firmware which NAKs kCmdListDirectoryWithTime (PX4 <= 1.17) reports no modification times
1192 // over FTP. Fall back to the message based transport where LOG_ENTRY reports the dates (issue #14789).
1193 if (_vehicle && _vehicle->ftpManager()->listDirectoryWithTimeUnsupported()) {
1194 _ftpFallbackToMessages();
1195 return;
1196 }
1197
1198 _setListing(false);
1199}
1200
1201void OnboardLogController::_ftpFallbackToMessages()
1202{
1203 qCDebug(OnboardLogControllerLog) << "ftp: transport failed, falling back to message based log download";
1204
1205 _ftpListState = FtpListState::Idle;
1206 _ftpDirsToList.clear();
1207 _ftpDisabled = true;
1208 _setTransport(Transport::Messages);
1209
1210 _logEntriesModel->clearAndDeleteContents();
1211 emit selectionChanged();
1212
1213 // Listing state stays active across the transport switch so the UI sees a single refresh
1214 _requestLogList(0, 0xffff);
1215}
1216
1217void OnboardLogController::_ftpDownloadToDirectory(const QString &dir)
1218{
1219 _downloadPath = dir;
1220 if (_downloadPath.isEmpty()) {
1221 return;
1222 }
1223
1224 if (!_downloadPath.endsWith(QDir::separator())) {
1225 _downloadPath += QDir::separator();
1226 }
1227
1228 _ftpDownloadQueue.clear();
1229 _ftpDownloadHadError = false;
1230 const int numLogs = _logEntriesModel->count();
1231 for (int i = 0; i < numLogs; i++) {
1232 QGCOnboardLogEntry *const entry = _logEntriesModel->value<QGCOnboardLogEntry*>(i);
1233 if (entry && entry->selected() && !entry->ftpPath().isEmpty()) {
1234 entry->setStatus(tr("Waiting"));
1235 _ftpDownloadQueue.enqueue(entry);
1236 }
1237 }
1238
1239 if (_ftpDownloadQueue.isEmpty()) {
1240 qCWarning(OnboardLogControllerLog) << "ftp: no selected logs have FTP paths for download";
1241 return;
1242 }
1243
1244 qCDebug(OnboardLogControllerLog) << "ftp: queued" << _ftpDownloadQueue.size() << "logs for download to" << _downloadPath;
1245 _setDownloading(true);
1246
1247 _ftpDownloadEntry(_ftpDownloadQueue.dequeue());
1248}
1249
1250void OnboardLogController::_ftpDownloadEntry(QGCOnboardLogEntry *entry)
1251{
1252 if (!entry || !_vehicle) {
1253 return;
1254 }
1255
1256 entry->setSelected(false);
1257
1258 _ftpCurrentDownloadEntry = entry;
1259 _ftpDownloadBytesAtLastUpdate = 0;
1260 _ftpDownloadRateAvg = 0.;
1261 _ftpDownloadElapsed.start();
1262
1263 entry->setStatus(tr("Downloading"));
1264
1265 // Save under the remote log file name
1266 QString localFilename = entry->ftpPath().section(QLatin1Char('/'), -1);
1267 if (localFilename.isEmpty()) {
1268 localFilename = QStringLiteral("log_") + QString::number(entry->id()) + QStringLiteral(".ulg");
1269 }
1270
1271 if (QFile::exists(_downloadPath + localFilename)) {
1272 const int dotIdx = localFilename.lastIndexOf(QLatin1Char('.'));
1273 const QString base = (dotIdx > 0) ? localFilename.left(dotIdx) : localFilename;
1274 const QString ext = (dotIdx > 0) ? localFilename.mid(dotIdx) : QString();
1275 uint numDups = 0;
1276 do {
1277 numDups++;
1278 localFilename = base + QStringLiteral("_") + QString::number(numDups) + ext;
1279 } while (QFile::exists(_downloadPath + localFilename));
1280 }
1281
1282 qCDebug(OnboardLogControllerLog) << "ftp: downloading" << entry->ftpPath() << "to" << _downloadPath + localFilename;
1283
1284 if (!_vehicle->ftpManager()->download(MAV_COMP_ID_AUTOPILOT1, entry->ftpPath(), _downloadPath, localFilename, true)) {
1285 qCWarning(OnboardLogControllerLog) << "ftp: failed to start download for" << entry->ftpPath();
1286 entry->setStatus(tr("Error"));
1287 _ftpCurrentDownloadEntry = nullptr;
1288 _ftpDownloadHadError = true;
1289 _ftpDownloadQueueNext();
1290 }
1291}
1292
1293void OnboardLogController::_ftpDownloadQueueNext()
1294{
1295 if (!_ftpDownloadQueue.isEmpty()) {
1296 _ftpDownloadEntry(_ftpDownloadQueue.dequeue());
1297 return;
1298 }
1299
1300 if (_ftpDownloadHadError) {
1301 qCDebug(OnboardLogControllerLog) << "ftp: download errors occurred, using message based transport for subsequent refreshes";
1302 _ftpDisabled = true;
1303 }
1304
1305 _setDownloading(false);
1306}
1307
1308void OnboardLogController::_ftpDownloadComplete(const QString &file, const QString &errorMsg)
1309{
1310 if (!_ftpCurrentDownloadEntry) {
1311 return;
1312 }
1313
1314 if (errorMsg.isEmpty()) {
1315 _ftpCurrentDownloadEntry->setStatus(tr("Downloaded"));
1316 qCDebug(OnboardLogControllerLog) << "ftp: download complete" << file;
1317 } else {
1318 _ftpCurrentDownloadEntry->setStatus(tr("Error"));
1319 _ftpDownloadHadError = true;
1320 qCWarning(OnboardLogControllerLog) << "ftp: download error:" << errorMsg;
1321 }
1322
1323 _ftpCurrentDownloadEntry = nullptr;
1324 _ftpDownloadQueueNext();
1325}
1326
1327void OnboardLogController::_ftpDownloadProgress(float value)
1328{
1329 if (!_ftpCurrentDownloadEntry) {
1330 return;
1331 }
1332
1333 if (_ftpDownloadElapsed.elapsed() < kGUIRateMs) {
1334 return;
1335 }
1336
1337 const size_t totalBytes = static_cast<size_t>(static_cast<qreal>(_ftpCurrentDownloadEntry->size()) * static_cast<qreal>(value));
1338 if (totalBytes < _ftpDownloadBytesAtLastUpdate) {
1339 // Guard against non-monotonic progress which would underflow the unsigned delta
1340 _ftpDownloadBytesAtLastUpdate = totalBytes;
1341 return;
1342 }
1343
1344 const size_t bytesSinceLastUpdate = totalBytes - _ftpDownloadBytesAtLastUpdate;
1345 const qreal elapsedSec = _ftpDownloadElapsed.elapsed() / 1000.0;
1346 const qreal rate = (elapsedSec > 0) ? (bytesSinceLastUpdate / elapsedSec) : 0;
1347 _ftpDownloadRateAvg = (_ftpDownloadRateAvg * 0.95) + (rate * 0.05);
1348 _ftpDownloadBytesAtLastUpdate = totalBytes;
1349 _ftpDownloadElapsed.start();
1350
1351 const QString status = QStringLiteral("%1 (%2/s)").arg(
1352 QGC::bigSizeToString(totalBytes),
1353 QGC::bigSizeToString(_ftpDownloadRateAvg));
1354
1355 _ftpCurrentDownloadEntry->setStatus(status);
1356}
1357
1359{
1360 if (_compressLogs != compress) {
1361 _compressLogs = compress;
1362 emit compressLogsChanged();
1363 }
1364}
1365
1366bool OnboardLogController::compressLogFile(const QString &logPath)
1367{
1368 Q_UNUSED(logPath)
1369 qCWarning(OnboardLogControllerLog) << "Log compression not yet implemented (decompression-only API)";
1370 return false;
1371}
1372
1374{
1375 // Not implemented - compression API is decompression-only
1376}
1377
1378void OnboardLogController::_handleCompressionProgress(qreal progress)
1379{
1380 Q_UNUSED(progress)
1381 // Not implemented - compression API is decompression-only
1382}
1383
1384void OnboardLogController::_handleCompressionFinished(bool success)
1385{
1386 Q_UNUSED(success)
1387 // Not implemented - compression API is decompression-only
1388}
@ Transport
The link could not read, write, or change its baud rate.
Definition GPSCommand.h:26
std::shared_ptr< LinkInterface > SharedLinkInterfacePtr
static constexpr const char * kApmLogRootFallback
static constexpr const char * kPx4LogRootFallback
static constexpr const char * kMavlinkLogRoot
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
QString logSavePath()
void commandProgress(float value)
void downloadComplete(const QString &file, const QString &errorMsg)
void deleteComplete(const QString &file, const QString &errorMsg)
void listDirectoryComplete(const QStringList &dirList, const QString &errorMsg)
QVariant rawValue() const
Definition Fact.h:87
static int getComponentId()
static MAVLinkProtocol * instance()
static MultiVehicleManager * instance()
void activeVehicleChanged(Vehicle *activeVehicle)
QString transport() const
Transport currently used to list/download logs: "messages" (LOG_* messages) or "ftp" (MAVLink FTP).
Q_INVOKABLE void selectAll(bool select)
Q_INVOKABLE void eraseAll()
Q_INVOKABLE void eraseSelected()
Q_INVOKABLE void download(const QString &path=QString())
OnboardLogController(QObject *parent=nullptr)
Q_INVOKABLE void toggleSortByDate()
void setCompressLogs(bool compress)
void setSortAscending(bool ascending)
Q_INVOKABLE bool compressLogFile(const QString &logPath)
Compress a single log file.
Q_INVOKABLE void cancelCompression()
Cancel compression.
bool parameterExists(int componentId, const QString &paramName) const
Fact * getParameter(int componentId, const QString &paramName)
static constexpr int defaultComponentId
bool received() const
void setStatus(const QString &stat)
void setFtpPath(const QString &path)
void setSelected(bool sel)
bool selected() const
void setSize(uint size)
void setTime(const QDateTime &date)
void setReceived(bool rec)
QString ftpPath() const
Remote path when the entry was listed via MAVLink FTP; empty for message-based entries.
QDateTime time() const
T value(int index) const
int count() const override final
void clearAndDeleteContents() override final
Clears the list and calls deleteLater on each entry.
static SettingsManager * instance()
AppSettings * appSettings() const
void armedChanged(bool armed)
void logEntry(uint32_t time_utc, uint32_t size, uint16_t id, uint16_t num_logs, uint16_t last_log_num)
bool armed() const
Definition Vehicle.h:470
void logData(uint32_t ofs, uint16_t id, uint8_t count, const uint8_t *data)
QString bigSizeToString(quint64 size)
Byte size with unit: B, KB, MB, GB, TB. 1 fractional digit above 1 KB.
Definition QGCFormat.cc:20
GPSCommandSequence base(QByteArrayView port, const GPSBaseStationConfig &base)
Streams RTCM3 corrections and the PVTGeodetic survey status over port in the mode base selects.
Definition SBFPlan.cc:49
static const uint32_t kChunkSize