LogDownloadController.cc 25.2 KB
Newer Older
1 2
/****************************************************************************
 *
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
dogmaphobic's avatar
dogmaphobic committed
9 10 11 12 13 14 15 16


#include "LogDownloadController.h"
#include "MultiVehicleManager.h"
#include "QGCMAVLink.h"
#include "UAS.h"
#include "QGCApplication.h"
#include "QGCToolbox.h"
17
#include "QGCMapEngine.h"
18
#include "ParameterManager.h"
dogmaphobic's avatar
dogmaphobic committed
19
#include "Vehicle.h"
20
#include "SettingsManager.h"
dogmaphobic's avatar
dogmaphobic committed
21

dogmaphobic's avatar
dogmaphobic committed
22
#include <QDebug>
dogmaphobic's avatar
dogmaphobic committed
23 24
#include <QSettings>
#include <QUrl>
Don Gagne's avatar
Don Gagne committed
25 26
#include <QBitArray>
#include <QtCore/qmath.h>
dogmaphobic's avatar
dogmaphobic committed
27 28

#define kTimeOutMilliseconds 500
29
#define kGUIRateMilliseconds 17
dogmaphobic's avatar
dogmaphobic committed
30
#define kTableBins           512
31
#define kChunkSize           (kTableBins * MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN)
dogmaphobic's avatar
dogmaphobic committed
32 33 34

QGC_LOGGING_CATEGORY(LogDownloadLog, "LogDownloadLog")

35 36 37 38 39 40 41 42 43 44
//-----------------------------------------------------------------------------
struct LogDownloadData {
    LogDownloadData(QGCLogEntry* entry);
    QBitArray     chunk_table;
    uint32_t      current_chunk;
    QFile         file;
    QString       filename;
    uint          ID;
    QGCLogEntry*  entry;
    uint          written;
45 46
    size_t        rate_bytes;
    qreal         rate_avg;
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
    QElapsedTimer elapsed;

    void advanceChunk()
    {
           current_chunk++;
           chunk_table = QBitArray(chunkBins(), false);
    }

    // The number of MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN bins in the current chunk
    uint32_t chunkBins() const
    {
        return qMin(qCeil((entry->size() - current_chunk*kChunkSize)/static_cast<qreal>(MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN)),
                    kTableBins);
    }

    // The number of kChunkSize chunks in the file
    uint32_t numChunks() const
    {
        return qCeil(entry->size() / static_cast<qreal>(kChunkSize));
    }

    // True if all bins in the chunk have been set to val
    bool chunkEquals(const bool val) const
    {
        return chunk_table == QBitArray(chunk_table.size(), val);
    }

};
75

dogmaphobic's avatar
dogmaphobic committed
76 77 78 79 80
//----------------------------------------------------------------------------------------
LogDownloadData::LogDownloadData(QGCLogEntry* entry_)
    : ID(entry_->id())
    , entry(entry_)
    , written(0)
81 82
    , rate_bytes(0)
    , rate_avg(0)
dogmaphobic's avatar
dogmaphobic committed
83 84 85 86 87
{

}

//----------------------------------------------------------------------------------------
88
QGCLogEntry::QGCLogEntry(uint logId, const QDateTime& dateTime, uint logSize, bool received)
dogmaphobic's avatar
dogmaphobic committed
89 90 91 92 93 94
    : _logID(logId)
    , _logSize(logSize)
    , _logTimeUTC(dateTime)
    , _received(received)
    , _selected(false)
{
Gus Grubba's avatar
Gus Grubba committed
95
    _status = tr("Pending");
dogmaphobic's avatar
dogmaphobic committed
96 97
}

98 99 100 101
//----------------------------------------------------------------------------------------
QString
QGCLogEntry::sizeStr() const
{
102
    return QGCMapEngine::bigSizeToString(_logSize);
103 104
}

dogmaphobic's avatar
dogmaphobic committed
105
//----------------------------------------------------------------------------------------
106
LogDownloadController::LogDownloadController(void)
107 108 109
    : _uas(nullptr)
    , _downloadData(nullptr)
    , _vehicle(nullptr)
dogmaphobic's avatar
dogmaphobic committed
110 111 112
    , _requestingLogEntries(false)
    , _downloadingLogs(false)
    , _retries(0)
dogmaphobic's avatar
dogmaphobic committed
113
    , _apmOneBased(0)
dogmaphobic's avatar
dogmaphobic committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
{
    MultiVehicleManager *manager = qgcApp()->toolbox()->multiVehicleManager();
    connect(manager, &MultiVehicleManager::activeVehicleChanged, this, &LogDownloadController::_setActiveVehicle);
    connect(&_timer, &QTimer::timeout, this, &LogDownloadController::_processDownload);
    _setActiveVehicle(manager->activeVehicle());
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::_processDownload()
{
    if(_requestingLogEntries) {
        _findMissingEntries();
    } else if(_downloadingLogs) {
        _findMissingData();
    }
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::_setActiveVehicle(Vehicle* vehicle)
{
136
    if(_uas) {
dogmaphobic's avatar
dogmaphobic committed
137 138 139
        _logEntriesModel.clear();
        disconnect(_uas, &UASInterface::logEntry, this, &LogDownloadController::_logEntry);
        disconnect(_uas, &UASInterface::logData,  this, &LogDownloadController::_logData);
140
        _uas = nullptr;
dogmaphobic's avatar
dogmaphobic committed
141
    }
142 143 144 145 146 147
    _vehicle = vehicle;
    if(_vehicle) {
        _uas = vehicle->uas();
        connect(_uas, &UASInterface::logEntry, this, &LogDownloadController::_logEntry);
        connect(_uas, &UASInterface::logData,  this, &LogDownloadController::_logData);
    }
dogmaphobic's avatar
dogmaphobic committed
148 149 150 151 152 153 154 155 156 157 158
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::_logEntry(UASInterface* uas, uint32_t time_utc, uint32_t size, uint16_t id, uint16_t num_logs, uint16_t /*last_log_num*/)
{
    //-- Do we care?
    if(!_uas || uas != _uas || !_requestingLogEntries) {
        return;
    }
    //-- If this is the first, pre-fill it
159
    if(!_logEntriesModel.count() && num_logs > 0) {
dogmaphobic's avatar
dogmaphobic committed
160 161 162 163 164
        //-- Is this APM? They send a first entry with bogus ID and only the
        //   count is valid. From now on, all entries are 1-based.
        if(_vehicle->firmwareType() == MAV_AUTOPILOT_ARDUPILOTMEGA) {
            _apmOneBased = 1;
        }
dogmaphobic's avatar
dogmaphobic committed
165 166 167 168 169 170
        for(int i = 0; i < num_logs; i++) {
            QGCLogEntry *entry = new QGCLogEntry(i);
            _logEntriesModel.append(entry);
        }
    }
    //-- Update this log record
171
    if(num_logs > 0) {
dogmaphobic's avatar
dogmaphobic committed
172
        //-- Skip if empty (APM first packet)
173
        if(size || _vehicle->firmwareType() != MAV_AUTOPILOT_ARDUPILOTMEGA) {
dogmaphobic's avatar
dogmaphobic committed
174 175 176 177 178 179
            id -= _apmOneBased;
            if(id < _logEntriesModel.count()) {
                QGCLogEntry* entry = _logEntriesModel[id];
                entry->setSize(size);
                entry->setTime(QDateTime::fromTime_t(time_utc));
                entry->setReceived(true);
180
                entry->setStatus(tr("Available"));
dogmaphobic's avatar
dogmaphobic committed
181 182 183
            } else {
                qWarning() << "Received log entry for out-of-bound index:" << id;
            }
184
        }
dogmaphobic's avatar
dogmaphobic committed
185
    } else {
186 187
        //-- No logs to list
        _receivedAllEntries();
dogmaphobic's avatar
dogmaphobic committed
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
    }
    //-- Reset retry count
    _retries = 0;
    //-- Do we have it all?
    if(_entriesComplete()) {
        _receivedAllEntries();
    } else {
        //-- Reset timer
        _timer.start(kTimeOutMilliseconds);
    }
}

//----------------------------------------------------------------------------------------
bool
LogDownloadController::_entriesComplete()
{
    //-- Iterate entries and look for a gap
    int num_logs = _logEntriesModel.count();
    for(int i = 0; i < num_logs; i++) {
        QGCLogEntry* entry = _logEntriesModel[i];
        if(entry) {
            if(!entry->received()) {
               return false;
            }
        }
    }
    return true;
}

//----------------------------------------------------------------------------------------
void
dogmaphobic's avatar
dogmaphobic committed
219
LogDownloadController::_resetSelection(bool canceled)
dogmaphobic's avatar
dogmaphobic committed
220 221 222 223 224
{
    int num_logs = _logEntriesModel.count();
    for(int i = 0; i < num_logs; i++) {
        QGCLogEntry* entry = _logEntriesModel[i];
        if(entry) {
dogmaphobic's avatar
dogmaphobic committed
225 226
            if(entry->selected()) {
                if(canceled) {
227
                    entry->setStatus(tr("Canceled"));
dogmaphobic's avatar
dogmaphobic committed
228 229 230
                }
                entry->setSelected(false);
            }
dogmaphobic's avatar
dogmaphobic committed
231 232 233 234 235 236 237 238 239 240
        }
    }
    emit selectionChanged();
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::_receivedAllEntries()
{
    _timer.stop();
dogmaphobic's avatar
dogmaphobic committed
241
    _setListing(false);
dogmaphobic's avatar
dogmaphobic committed
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
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::_findMissingEntries()
{
    int start = -1;
    int end   = -1;
    int num_logs = _logEntriesModel.count();
    //-- Iterate entries and look for a gap
    for(int i = 0; i < num_logs; i++) {
        QGCLogEntry* entry = _logEntriesModel[i];
        if(entry) {
            if(!entry->received()) {
                if(start < 0)
                    start = i;
                else
                    end = i;
            } else {
                if(start >= 0) {
                    break;
                }
            }
        }
    }
    //-- Is there something missing?
    if(start >= 0) {
        //-- Have we tried too many times?
        if(_retries++ > 2) {
            for(int i = 0; i < num_logs; i++) {
                QGCLogEntry* entry = _logEntriesModel[i];
                if(entry && !entry->received()) {
274
                    entry->setStatus(tr("Error"));
dogmaphobic's avatar
dogmaphobic committed
275 276 277 278 279 280 281 282 283 284 285
                }
            }
            //-- Give up
            _receivedAllEntries();
            qWarning() << "Too many errors retreiving log list. Giving up.";
            return;
        }
        //-- Is it a sequence or just one entry?
        if(end < 0) {
            end = start;
        }
dogmaphobic's avatar
dogmaphobic committed
286 287 288
        //-- APM "Fix"
        start += _apmOneBased;
        end   += _apmOneBased;
dogmaphobic's avatar
dogmaphobic committed
289 290 291 292 293 294 295
        //-- Request these entries again
        _requestLogList((uint32_t)start, (uint32_t) end);
    } else {
        _receivedAllEntries();
    }
}

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
void LogDownloadController::_updateDataRate(void)
{
    if (_downloadData->elapsed.elapsed() >= kGUIRateMilliseconds) {
        //-- Update download rate
        qreal rrate = _downloadData->rate_bytes / (_downloadData->elapsed.elapsed() / 1000.0);
        _downloadData->rate_avg = (_downloadData->rate_avg * 0.95) + (rrate * 0.05);
        _downloadData->rate_bytes = 0;

        //-- Update status
        const QString status = QString("%1 (%2/s)").arg(QGCMapEngine::bigSizeToString(_downloadData->written),
                                                        QGCMapEngine::bigSizeToString(_downloadData->rate_avg));

        _downloadData->entry->setStatus(status);
        _downloadData->elapsed.start();
    }
}


dogmaphobic's avatar
dogmaphobic committed
314 315 316 317 318 319 320
//----------------------------------------------------------------------------------------
void
LogDownloadController::_logData(UASInterface* uas, uint32_t ofs, uint16_t id, uint8_t count, const uint8_t* data)
{
    if(!_uas || uas != _uas || !_downloadData) {
        return;
    }
dogmaphobic's avatar
dogmaphobic committed
321 322
    //-- APM "Fix"
    id -= _apmOneBased;
dogmaphobic's avatar
dogmaphobic committed
323 324 325 326
    if(_downloadData->ID != id) {
        qWarning() << "Received log data for wrong log";
        return;
    }
327

328 329 330 331 332
    if ((ofs % MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN) != 0) {
        qWarning() << "Ignored misaligned incoming packet @" << ofs;
        return;
    }

333 334
    bool result = false;
    uint32_t timeout_time = kTimeOutMilliseconds;
335
    if(ofs <= _downloadData->entry->size()) {
336 337
        const uint32_t chunk = ofs / kChunkSize;
        if (chunk != _downloadData->current_chunk) {
DonLakeFlyer's avatar
DonLakeFlyer committed
338
            qWarning() << "Ignored packet for out of order chunk actual:expected" << chunk << _downloadData->current_chunk;
339 340 341 342 343 344 345 346
            return;
        }
        const uint16_t bin = (ofs - chunk*kChunkSize) / MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN;
        if (bin >= _downloadData->chunk_table.size()) {
            qWarning() << "Out of range bin received";
        } else
            _downloadData->chunk_table.setBit(bin);
        if (_downloadData->file.pos() != ofs) {
347 348 349 350 351 352 353
            // Seek to correct position
            if (!_downloadData->file.seek(ofs)) {
                qWarning() << "Error while seeking log file offset";
                return;
            }
        }

dogmaphobic's avatar
dogmaphobic committed
354
        //-- Write chunk to file
355 356
        if(_downloadData->file.write((const char*)data, count)) {
            _downloadData->written += count;
357
            _downloadData->rate_bytes += count;
358
            _updateDataRate();
359 360 361 362
            result = true;
            //-- reset retries
            _retries = 0;
            //-- Reset timer
363
            _timer.start(timeout_time);
364 365
            //-- Do we have it all?
            if(_logComplete()) {
366
                _downloadData->entry->setStatus(tr("Downloaded"));
367 368
                //-- Check for more
                _receivedAllData();
369 370 371 372 373
            } else if (_chunkComplete()) {
                _downloadData->advanceChunk();
                _requestLogData(_downloadData->ID,
                                _downloadData->current_chunk*kChunkSize,
                                _downloadData->chunk_table.size()*MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN);
374 375 376
            } else if (bin < _downloadData->chunk_table.size() - 1 && _downloadData->chunk_table.at(bin+1)) {
                // Likely to be grabbing fragments and got to the end of a gap
                _findMissingData();
dogmaphobic's avatar
dogmaphobic committed
377 378
            }
        } else {
379
            qWarning() << "Error while writing log file chunk";
dogmaphobic's avatar
dogmaphobic committed
380 381 382 383 384
        }
    } else {
        qWarning() << "Received log offset greater than expected";
    }
    if(!result) {
385
        _downloadData->entry->setStatus(tr("Error"));
dogmaphobic's avatar
dogmaphobic committed
386 387 388
    }
}

389 390 391 392 393 394 395 396

//----------------------------------------------------------------------------------------
bool
LogDownloadController::_chunkComplete() const
{
    return _downloadData->chunkEquals(true);
}

dogmaphobic's avatar
dogmaphobic committed
397 398
//----------------------------------------------------------------------------------------
bool
399
LogDownloadController::_logComplete() const
dogmaphobic's avatar
dogmaphobic committed
400
{
401
    return _chunkComplete() && (_downloadData->current_chunk+1) == _downloadData->numChunks();
dogmaphobic's avatar
dogmaphobic committed
402 403 404 405 406 407 408 409 410 411
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::_receivedAllData()
{
    _timer.stop();
    //-- Anything queued up for download?
    if(_prepareLogDownload()) {
        //-- Request Log
412
        _requestLogData(_downloadData->ID, 0, _downloadData->chunk_table.size()*MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN);
413
        _timer.start(kTimeOutMilliseconds);
dogmaphobic's avatar
dogmaphobic committed
414 415
    } else {
        _resetSelection();
416
        _setDownloading(false);
dogmaphobic's avatar
dogmaphobic committed
417 418 419 420 421 422 423
    }
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::_findMissingData()
{
424 425 426
    if (_logComplete()) {
         _receivedAllData();
         return;
427 428
    } else if (_chunkComplete()) {
        _downloadData->advanceChunk();
dogmaphobic's avatar
dogmaphobic committed
429
    }
430

431 432 433 434 435 436
    _retries++;
#if 0
    // Trying the change to infinite log download. This way if retries hit 100% failure the data rate will
    // slowly fall to 0 and the user can Cancel. This should work better on really crappy links.
    if(_retries > 5) {
        _downloadData->entry->setStatus(tr("Timed Out"));
437 438 439 440 441
        //-- Give up
        qWarning() << "Too many errors retreiving log data. Giving up.";
        _receivedAllData();
        return;
    }
442 443 444
#endif

    _updateDataRate();
445

446 447 448 449 450 451
    uint16_t start = 0, end = 0;
    const int size = _downloadData->chunk_table.size();
    for (; start < size; start++) {
        if (!_downloadData->chunk_table.testBit(start)) {
            break;
        }
dogmaphobic's avatar
dogmaphobic committed
452
    }
453 454 455 456 457 458 459 460 461

    for (end = start; end < size; end++) {
        if (_downloadData->chunk_table.testBit(end)) {
            break;
        }
    }

    const uint32_t pos = _downloadData->current_chunk*kChunkSize + start*MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN,
                   len = (end - start)*MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN;
462
    _requestLogData(_downloadData->ID, pos, len, _retries);
dogmaphobic's avatar
dogmaphobic committed
463 464 465 466
}

//----------------------------------------------------------------------------------------
void
467
LogDownloadController::_requestLogData(uint16_t id, uint32_t offset, uint32_t count, int retryCount)
dogmaphobic's avatar
dogmaphobic committed
468 469
{
    if(_vehicle) {
dogmaphobic's avatar
dogmaphobic committed
470 471
        //-- APM "Fix"
        id += _apmOneBased;
472
        qCDebug(LogDownloadLog) << "Request log data (id:" << id << "offset:" << offset << "size:" << count << "retryCount" << retryCount << ")";
dogmaphobic's avatar
dogmaphobic committed
473
        mavlink_message_t msg;
474 475 476
        mavlink_msg_log_request_data_pack_chan(
                    qgcApp()->toolbox()->mavlinkProtocol()->getSystemId(),
                    qgcApp()->toolbox()->mavlinkProtocol()->getComponentId(),
477
                    _vehicle->vehicleLinkManager()->primaryLink()->mavlinkChannel(),
478 479 480
                    &msg,
                    qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()->id(), qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()->defaultComponentId(),
                    id, offset, count);
481
        _vehicle->sendMessageOnLinkThreadSafe(_vehicle->vehicleLinkManager()->primaryLink(), msg);
dogmaphobic's avatar
dogmaphobic committed
482 483 484 485 486 487 488 489
    }
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::refresh(void)
{
    _logEntriesModel.clear();
dogmaphobic's avatar
dogmaphobic committed
490 491
    //-- Get first 50 entries
    _requestLogList(0, 49);
dogmaphobic's avatar
dogmaphobic committed
492 493 494 495 496 497 498 499
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::_requestLogList(uint32_t start, uint32_t end)
{
    if(_vehicle && _uas) {
        qCDebug(LogDownloadLog) << "Request log entry list (" << start << "through" << end << ")";
dogmaphobic's avatar
dogmaphobic committed
500
        _setListing(true);
dogmaphobic's avatar
dogmaphobic committed
501
        mavlink_message_t msg;
502 503 504
        mavlink_msg_log_request_list_pack_chan(
                    qgcApp()->toolbox()->mavlinkProtocol()->getSystemId(),
                    qgcApp()->toolbox()->mavlinkProtocol()->getComponentId(),
505
                    _vehicle->vehicleLinkManager()->primaryLink()->mavlinkChannel(),
506 507 508 509 510
                    &msg,
                    _vehicle->id(),
                    _vehicle->defaultComponentId(),
                    start,
                    end);
511
        _vehicle->sendMessageOnLinkThreadSafe(_vehicle->vehicleLinkManager()->primaryLink(), msg);
dogmaphobic's avatar
dogmaphobic committed
512 513
        //-- Wait 5 seconds before bitching about not getting anything
        _timer.start(5000);
dogmaphobic's avatar
dogmaphobic committed
514 515 516 517 518
    }
}

//----------------------------------------------------------------------------------------
void
519
LogDownloadController::download(QString path)
520
{
521
    QString dir = path;
522
    if (dir.isEmpty()) {
523
        dir = qgcApp()->toolbox()->settingsManager()->appSettings()->logSavePath();
524
    }
525 526 527 528
    downloadToDirectory(dir);
}

void LogDownloadController::downloadToDirectory(const QString& dir)
dogmaphobic's avatar
dogmaphobic committed
529 530 531 532
{
    //-- Stop listing just in case
    _receivedAllEntries();
    //-- Reset downloads, again just in case
533 534 535
    delete _downloadData;
    _downloadData = nullptr;

536
    _downloadPath = dir;
dogmaphobic's avatar
dogmaphobic committed
537 538 539
    if(!_downloadPath.isEmpty()) {
        if(!_downloadPath.endsWith(QDir::separator()))
            _downloadPath += QDir::separator();
dogmaphobic's avatar
dogmaphobic committed
540 541 542 543 544 545
        //-- Iterate selected entries and shown them as waiting
        int num_logs = _logEntriesModel.count();
        for(int i = 0; i < num_logs; i++) {
            QGCLogEntry* entry = _logEntriesModel[i];
            if(entry) {
                if(entry->selected()) {
546
                   entry->setStatus(tr("Waiting"));
dogmaphobic's avatar
dogmaphobic committed
547 548 549
                }
            }
        }
dogmaphobic's avatar
dogmaphobic committed
550
        //-- Start download process
551
        _setDownloading(true);
dogmaphobic's avatar
dogmaphobic committed
552 553 554 555
        _receivedAllData();
    }
}

556

dogmaphobic's avatar
dogmaphobic committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570
//----------------------------------------------------------------------------------------
QGCLogEntry*
LogDownloadController::_getNextSelected()
{
    //-- Iterate entries and look for a selected file
    int num_logs = _logEntriesModel.count();
    for(int i = 0; i < num_logs; i++) {
        QGCLogEntry* entry = _logEntriesModel[i];
        if(entry) {
            if(entry->selected()) {
               return entry;
            }
        }
    }
571
    return nullptr;
dogmaphobic's avatar
dogmaphobic committed
572 573 574 575 576 577
}

//----------------------------------------------------------------------------------------
bool
LogDownloadController::_prepareLogDownload()
{
578 579 580
    delete _downloadData;
    _downloadData = nullptr;

dogmaphobic's avatar
dogmaphobic committed
581 582 583 584 585 586 587 588 589
    QGCLogEntry* entry = _getNextSelected();
    if(!entry) {
        return false;
    }
    //-- Deselect file
    entry->setSelected(false);
    emit selectionChanged();
    bool result = false;
    QString ftime;
dogmaphobic's avatar
dogmaphobic committed
590
    if(entry->time().date().year() < 2010) {
Don Gagne's avatar
Don Gagne committed
591
        ftime = tr("UnknownDate");
dogmaphobic's avatar
dogmaphobic committed
592
    } else {
Don Gagne's avatar
Don Gagne committed
593
        ftime = entry->time().toString(QStringLiteral("yyyy-M-d-hh-mm-ss"));
dogmaphobic's avatar
dogmaphobic committed
594 595
    }
    _downloadData = new LogDownloadData(entry);
596
    _downloadData->filename = QString("log_") + QString::number(entry->id()) + "_" + ftime;
597
    if (_vehicle->firmwareType() == MAV_AUTOPILOT_PX4) {
Don Gagne's avatar
Don Gagne committed
598
        QString loggerParam = QStringLiteral("SYS_LOGGER");
599 600
        if (_vehicle->parameterManager()->parameterExists(FactSystem::defaultComponentId, loggerParam) &&
                _vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, loggerParam)->rawValue().toInt() == 0) {
601 602 603 604
            _downloadData->filename += ".px4log";
        } else {
            _downloadData->filename += ".ulg";
        }
605 606 607
    } else {
        _downloadData->filename += ".bin";
    }
dogmaphobic's avatar
dogmaphobic committed
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    _downloadData->file.setFileName(_downloadPath + _downloadData->filename);
    //-- Append a number to the end if the filename already exists
    if (_downloadData->file.exists()){
        uint num_dups = 0;
        QStringList filename_spl = _downloadData->filename.split('.');
        do {
            num_dups +=1;
            _downloadData->file.setFileName(filename_spl[0] + '_' + QString::number(num_dups) + '.' + filename_spl[1]);
        } while( _downloadData->file.exists());
    }
    //-- Create file
    if (!_downloadData->file.open(QIODevice::WriteOnly)) {
        qWarning() << "Failed to create log file:" <<  _downloadData->filename;
    } else {
        //-- Preallocate file
        if(!_downloadData->file.resize(entry->size())) {
            qWarning() << "Failed to allocate space for log file:" <<  _downloadData->filename;
        } else {
626 627
            _downloadData->current_chunk = 0;
            _downloadData->chunk_table = QBitArray(_downloadData->chunkBins(), false);
628
            _downloadData->elapsed.start();
dogmaphobic's avatar
dogmaphobic committed
629 630 631 632 633 634 635
            result = true;
        }
    }
    if(!result) {
        if (_downloadData->file.exists()) {
            _downloadData->file.remove();
        }
636
        _downloadData->entry->setStatus(tr("Error"));
dogmaphobic's avatar
dogmaphobic committed
637
        delete _downloadData;
638
        _downloadData = nullptr;
dogmaphobic's avatar
dogmaphobic committed
639 640 641 642
    }
    return result;
}

643 644 645 646
//----------------------------------------------------------------------------------------
void
LogDownloadController::_setDownloading(bool active)
{
647 648
    if (_downloadingLogs != active) {
        _downloadingLogs = active;
649
        _vehicle->vehicleLinkManager()->setCommunicationLostEnabled(!active);
650 651
        emit downloadingLogsChanged();
    }
652 653
}

dogmaphobic's avatar
dogmaphobic committed
654 655 656 657
//----------------------------------------------------------------------------------------
void
LogDownloadController::_setListing(bool active)
{
658 659
    if (_requestingLogEntries != active) {
        _requestingLogEntries = active;
660
        _vehicle->vehicleLinkManager()->setCommunicationLostEnabled(!active);
661 662
        emit requestingListChanged();
    }
dogmaphobic's avatar
dogmaphobic committed
663 664
}

dogmaphobic's avatar
dogmaphobic committed
665 666 667 668 669 670
//----------------------------------------------------------------------------------------
void
LogDownloadController::eraseAll(void)
{
    if(_vehicle && _uas) {
        mavlink_message_t msg;
671 672 673
        mavlink_msg_log_erase_pack_chan(
                    qgcApp()->toolbox()->mavlinkProtocol()->getSystemId(),
                    qgcApp()->toolbox()->mavlinkProtocol()->getComponentId(),
674
                    _vehicle->vehicleLinkManager()->primaryLink()->mavlinkChannel(),
675 676
                    &msg,
                    qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()->id(), qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()->defaultComponentId());
677
        _vehicle->sendMessageOnLinkThreadSafe(_vehicle->vehicleLinkManager()->primaryLink(), msg);
678
        refresh();
dogmaphobic's avatar
dogmaphobic committed
679 680 681 682 683 684 685 686 687 688 689
    }
}

//----------------------------------------------------------------------------------------
void
LogDownloadController::cancel(void)
{
    if(_uas){
        _receivedAllEntries();
    }
    if(_downloadData) {
690
        _downloadData->entry->setStatus(tr("Canceled"));
dogmaphobic's avatar
dogmaphobic committed
691 692 693 694 695 696
        if (_downloadData->file.exists()) {
            _downloadData->file.remove();
        }
        delete _downloadData;
        _downloadData = 0;
    }
dogmaphobic's avatar
dogmaphobic committed
697
    _resetSelection(true);
698
    _setDownloading(false);
dogmaphobic's avatar
dogmaphobic committed
699 700 701 702 703 704 705 706 707 708 709 710 711 712
}

//-----------------------------------------------------------------------------
QGCLogModel::QGCLogModel(QObject* parent)
    : QAbstractListModel(parent)
{

}

//-----------------------------------------------------------------------------
QGCLogEntry*
QGCLogModel::get(int index)
{
    if (index < 0 || index >= _logEntries.count()) {
713
        return nullptr;
dogmaphobic's avatar
dogmaphobic committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
    }
    return _logEntries[index];
}

//-----------------------------------------------------------------------------
int
QGCLogModel::count() const
{
    return _logEntries.count();
}

//-----------------------------------------------------------------------------
void
QGCLogModel::append(QGCLogEntry* object)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
730
    QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
dogmaphobic's avatar
dogmaphobic committed
731 732 733 734 735 736 737 738 739 740 741 742 743
    _logEntries.append(object);
    endInsertRows();
    emit countChanged();
}

//-----------------------------------------------------------------------------
void
QGCLogModel::clear(void)
{
    if(!_logEntries.isEmpty()) {
        beginRemoveRows(QModelIndex(), 0, _logEntries.count());
        while (_logEntries.count()) {
            QGCLogEntry* entry = _logEntries.last();
744
            if(entry) entry->deleteLater();
dogmaphobic's avatar
dogmaphobic committed
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
            _logEntries.removeLast();
        }
        endRemoveRows();
        emit countChanged();
    }
}

//-----------------------------------------------------------------------------
QGCLogEntry*
QGCLogModel::operator[](int index)
{
    return get(index);
}

//-----------------------------------------------------------------------------
int
QGCLogModel::rowCount(const QModelIndex& /*parent*/) const
{
    return _logEntries.count();
}

//-----------------------------------------------------------------------------
QVariant
QGCLogModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= _logEntries.count())
        return QVariant();
    if (role == ObjectRole)
        return QVariant::fromValue(_logEntries[index.row()]);
    return QVariant();
}

//-----------------------------------------------------------------------------
QHash<int, QByteArray>
QGCLogModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[ObjectRole] = "logEntry";
    return roles;
}