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

#include "MavlinkLogManager.h"
#include "QGCApplication.h"
#include <QQmlContext>
#include <QQmlProperty>
#include <QQmlEngine>
#include <QtQml>
#include <QSettings>
#include <QHttpPart>
#include <QNetworkReply>
#include <QFile>
#include <QFileInfo>

22 23
#define kTimeOutMilliseconds 1000

Gus Grubba's avatar
Gus Grubba committed
24 25
QGC_LOGGING_CATEGORY(MavlinkLogManagerLog, "MavlinkLogManagerLog")

26 27 28 29 30 31 32
static const char* kEmailAddressKey         = "MavlinkLogEmail";
static const char* kDescriptionsKey         = "MavlinkLogDescription";
static const char* kDefaultDescr            = "QGroundControl Session";
static const char* kPx4URLKey               = "MavlinkLogURL";
static const char* kDefaultPx4URL           = "http://logs.px4.io/upload";
static const char* kEnableAutoUploadKey     = "EnableAutoUploadKey";
static const char* kEnableAutoStartKey      = "EnableAutoStartKey";
33
static const char* kEnableDeletetKey        = "EnableDeleteKey";
Gus Grubba's avatar
Gus Grubba committed
34 35
static const char* kUlogExtension           = ".ulg";
static const char* kSidecarExtension        = ".uploaded";
Gus Grubba's avatar
Gus Grubba committed
36 37

//-----------------------------------------------------------------------------
Gus Grubba's avatar
Gus Grubba committed
38
MavlinkLogFiles::MavlinkLogFiles(MavlinkLogManager* manager, const QString& filePath, bool newFile)
Gus Grubba's avatar
Gus Grubba committed
39 40 41 42 43
    : _manager(manager)
    , _size(0)
    , _selected(false)
    , _uploading(false)
    , _progress(0)
Gus Grubba's avatar
Gus Grubba committed
44
    , _writing(false)
Gus Grubba's avatar
Gus Grubba committed
45
    , _uploaded(false)
Gus Grubba's avatar
Gus Grubba committed
46 47 48
{
    QFileInfo fi(filePath);
    _name = fi.baseName();
Gus Grubba's avatar
Gus Grubba committed
49 50 51 52 53 54 55
    if(!newFile) {
        _size = (quint32)fi.size();
        QString sideCar = filePath;
        sideCar.replace(kUlogExtension, kSidecarExtension);
        QFileInfo sc(sideCar);
        _uploaded = sc.exists();
    }
Gus Grubba's avatar
Gus Grubba committed
56 57
}

58 59 60 61 62 63 64 65
//-----------------------------------------------------------------------------
void
MavlinkLogFiles::setSize(quint32 size)
{
    _size = size;
    emit sizeChanged();
}

Gus Grubba's avatar
Gus Grubba committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
//-----------------------------------------------------------------------------
void
MavlinkLogFiles::setSelected(bool selected)
{
    _selected = selected;
    emit selectedChanged();
    emit _manager->selectedCountChanged();
}

//-----------------------------------------------------------------------------
void
MavlinkLogFiles::setUploading(bool uploading)
{
    _uploading = uploading;
    emit uploadingChanged();
}

//-----------------------------------------------------------------------------
void
MavlinkLogFiles::setProgress(qreal progress)
{
    _progress = progress;
    emit progressChanged();
}

91 92 93 94 95 96 97 98
//-----------------------------------------------------------------------------
void
MavlinkLogFiles::setWriting(bool writing)
{
    _writing = writing;
    emit writingChanged();
}

Gus Grubba's avatar
Gus Grubba committed
99 100 101 102 103 104 105 106
//-----------------------------------------------------------------------------
void
MavlinkLogFiles::setUploaded(bool uploaded)
{
    _uploaded = uploaded;
    emit uploadedChanged();
}

Gus Grubba's avatar
Gus Grubba committed
107 108
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
Gus Grubba's avatar
Gus Grubba committed
109 110 111 112 113 114 115 116
MavlinkLogProcessor::MavlinkLogProcessor()
    : _fd(NULL)
    , _written(0)
    , _sequence(-1)
    , _numDrops(0)
    , _gotHeader(false)
    , _error(false)
    , _record(NULL)
Gus Grubba's avatar
Gus Grubba committed
117
{
Gus Grubba's avatar
Gus Grubba committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
}

//-----------------------------------------------------------------------------
MavlinkLogProcessor::~MavlinkLogProcessor()
{
    close();
}

//-----------------------------------------------------------------------------
void
MavlinkLogProcessor::close()
{
    if(_fd) {
        fclose(_fd);
        _fd = NULL;
Gus Grubba's avatar
Gus Grubba committed
133 134 135
    }
}

Gus Grubba's avatar
Gus Grubba committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
//-----------------------------------------------------------------------------
bool
MavlinkLogProcessor::valid()
{
    return (_fd != NULL) && (_record != NULL);
}

//-----------------------------------------------------------------------------
bool
MavlinkLogProcessor::create(MavlinkLogManager* manager, const QString path, uint8_t id)
{
    _fileName.sprintf("%s/%03d-%s%s",
        path.toLatin1().data(),
        id,
        QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss-zzz").toLatin1().data(),
        kUlogExtension);
    _fd = fopen(_fileName.toLatin1().data(), "wb");
    if(_fd) {
        _record = new MavlinkLogFiles(manager, _fileName, true);
        _record->setWriting(true);
        _sequence = -1;
        return true;
    }
    return false;
}

//-----------------------------------------------------------------------------
bool
MavlinkLogProcessor::_checkSequence(uint16_t seq, int& num_drops)
{
    num_drops = 0;
    //-- Check if a sequence is newer than the one previously received and if
    //   there were dropped messages between the last one and this.
    if(_sequence == -1) {
        _sequence = seq;
        return true;
    }
    if((uint16_t)_sequence == seq) {
        return false;
    }
    if(seq > (uint16_t)_sequence) {
        // Account for wrap-arounds, sequence is 2 bytes
        if((seq - _sequence) > (1 << 15)) { // Assume reordered
            return false;
        }
        num_drops = seq - _sequence - 1;
        _numDrops += num_drops;
        _sequence = seq;
        return true;
    } else {
        if((_sequence - seq) > (1 << 15)) {
            num_drops = (1 << 16) - _sequence - 1 + seq;
            _numDrops += num_drops;
            _sequence = seq;
            return true;
        }
        return false;
    }
}

//-----------------------------------------------------------------------------
void
MavlinkLogProcessor::_writeData(void* data, int len)
{
    if(!_error) {
        _error = fwrite(data, 1, len, _fd) != (size_t)len;
        if(!_error) {
            _written += len;
            if(_record) {
                _record->setSize(_written);
            }
        } else {
            qCDebug(MavlinkLogManagerLog) << "File IO error:" << len << "bytes into" << _fileName;
        }
    }
}

//-----------------------------------------------------------------------------
QByteArray
MavlinkLogProcessor::_writeUlogMessage(QByteArray& data)
{
    //-- Write ulog data w/o integrity checking, assuming data starts with a
    //   valid ulog message. returns the remaining data at the end.
    while(data.length() > 2) {
        uint8_t* ptr = (uint8_t*)data.data();
        int message_length = ptr[0] + (ptr[1] * 256) + 3; // 3 = ULog msg header
        if(message_length > data.length())
            break;
        _writeData(data.data(), message_length);
        data.remove(0, message_length);
        return data;
    }
    return data;
}

//-----------------------------------------------------------------------------
bool
MavlinkLogProcessor::processStreamData(uint16_t sequence, uint8_t first_message, QByteArray data)
{
    int num_drops = 0;
    _error = false;
    while(_checkSequence(sequence, num_drops)) {
        //-- The first 16 bytes need special treatment (this sounds awfully brittle)
        if(!_gotHeader) {
            if(data.size() < 16) {
                //-- Shouldn't happen but if it does, we might as well close shop.
                qCCritical(MavlinkLogManagerLog) << "Corrupt log header. Canceling log download.";
                return false;
            }
            //-- Write header
            _writeData(data.data(), 16);
            data.remove(0, 16);
            _gotHeader = true;
            // What about data start offset now that we removed 16 bytes off the start?
        }
        if(_gotHeader && num_drops > 0) {
            if(num_drops > 25) num_drops = 25;
            //-- Hocus Pocus
            //   Write a dropout message. We don't really know the actual duration,
            //   so just use the number of drops * 10 ms
            uint8_t bogus[] = {2, 0, 79, 0, 0};
            bogus[3] = num_drops * 10;
            _writeData(bogus, sizeof(bogus));
        }
        if(num_drops > 0) {
            _writeUlogMessage(_ulogMessage);
            _ulogMessage.clear();
            //-- If no usefull information in this message. Drop it.
            if(first_message == 255) {
                break;
            }
            if(first_message > 0) {
                data.remove(0, first_message);
                first_message = 0;
            }
        }
        if(first_message == 255 && _ulogMessage.length() > 0) {
            _ulogMessage.append(data);
            break;
        }
        if(_ulogMessage.length()) {
            _writeData(_ulogMessage.data(), _ulogMessage.length());
            if(first_message) {
                _writeData(data.left(first_message).data(), first_message);
            }
            _ulogMessage.clear();
        }
        if(first_message) {
            data.remove(0, first_message);
        }
        _ulogMessage = _writeUlogMessage(data);
        break;
    }
    return !_error;
}

Gus Grubba's avatar
Gus Grubba committed
292
//-----------------------------------------------------------------------------
Gus Grubba's avatar
Gus Grubba committed
293 294 295
//-----------------------------------------------------------------------------
MavlinkLogManager::MavlinkLogManager(QGCApplication* app)
    : QGCTool(app)
296 297
    , _enableAutoUpload(true)
    , _enableAutoStart(true)
Gus Grubba's avatar
Gus Grubba committed
298 299
    , _nam(NULL)
    , _currentLogfile(NULL)
300 301
    , _vehicle(NULL)
    , _logRunning(false)
Gus Grubba's avatar
Gus Grubba committed
302
    , _loggingDisabled(false)
Gus Grubba's avatar
Gus Grubba committed
303
    , _logProcessor(NULL)
304
    , _deleteAfterUpload(false)
305
    , _loggingCmdTryCount(0)
Gus Grubba's avatar
Gus Grubba committed
306 307 308 309 310 311
{
    //-- Get saved settings
    QSettings settings;
    setEmailAddress(settings.value(kEmailAddressKey, QString()).toString());
    setDescription(settings.value(kDescriptionsKey, QString(kDefaultDescr)).toString());
    setUploadURL(settings.value(kPx4URLKey, QString(kDefaultPx4URL)).toString());
312 313
    setEnableAutoUpload(settings.value(kEnableAutoUploadKey, true).toBool());
    setEnableAutoStart(settings.value(kEnableAutoStartKey, true).toBool());
314
    setDeleteAfterUpload(settings.value(kEnableDeletetKey, false).toBool());
Gus Grubba's avatar
Gus Grubba committed
315 316 317 318
    //-- Logging location
    _logPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    _logPath += "/MavlinkLogs";
    if(!QDir(_logPath).exists()) {
Gus Grubba's avatar
Gus Grubba committed
319
        if(!QDir().mkpath(_logPath)) {
Gus Grubba's avatar
Gus Grubba committed
320
            qCCritical(MavlinkLogManagerLog) << "Could not create Mavlink log download path:" << _logPath;
Gus Grubba's avatar
Gus Grubba committed
321
            _loggingDisabled = true;
Gus Grubba's avatar
Gus Grubba committed
322 323
        }
    }
Gus Grubba's avatar
Gus Grubba committed
324 325
    if(!_loggingDisabled) {
        //-- Load current list of logs
Gus Grubba's avatar
Gus Grubba committed
326 327 328
        QString filter = "*";
        filter += kUlogExtension;
        QDirIterator it(_logPath, QStringList() << filter, QDir::Files);
Gus Grubba's avatar
Gus Grubba committed
329
        while(it.hasNext()) {
330
            _insertNewLog(new MavlinkLogFiles(this, it.next()));
Gus Grubba's avatar
Gus Grubba committed
331 332
        }
        qCDebug(MavlinkLogManagerLog) << "Mavlink logs directory:" << _logPath;
Gus Grubba's avatar
Gus Grubba committed
333 334 335 336 337 338 339 340 341 342 343
    }
}

//-----------------------------------------------------------------------------
MavlinkLogManager::~MavlinkLogManager()
{
    _logFiles.clear();
}

//-----------------------------------------------------------------------------
void
Gus Grubba's avatar
Gus Grubba committed
344
MavlinkLogManager::setToolbox(QGCToolbox* toolbox)
Gus Grubba's avatar
Gus Grubba committed
345
{
Gus Grubba's avatar
Gus Grubba committed
346 347 348 349 350
    QGCTool::setToolbox(toolbox);
    QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
    qmlRegisterUncreatableType<MavlinkLogManager>("QGroundControl.MavlinkLogManager", 1, 0, "MavlinkLogManager", "Reference only");
    if(!_loggingDisabled) {
        connect(toolbox->multiVehicleManager(), &MultiVehicleManager::activeVehicleChanged, this, &MavlinkLogManager::_activeVehicleChanged);
351
        connect(&_ackTimer, &QTimer::timeout, this, &MavlinkLogManager::_processCmdAck);
Gus Grubba's avatar
Gus Grubba committed
352
    }
Gus Grubba's avatar
Gus Grubba committed
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::setEmailAddress(QString email)
{
    _emailAddress = email;
    QSettings settings;
    settings.setValue(kEmailAddressKey, email);
    emit emailAddressChanged();
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::setDescription(QString description)
{
    _description = description;
    QSettings settings;
    settings.setValue(kDescriptionsKey, description);
    emit descriptionChanged();
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::setUploadURL(QString url)
{
    _uploadURL = url;
    if(_uploadURL.isEmpty()) {
        _uploadURL = kDefaultPx4URL;
    }
    QSettings settings;
    settings.setValue(kPx4URLKey, _uploadURL);
    emit uploadURLChanged();
}

//-----------------------------------------------------------------------------
void
390 391 392 393 394 395 396 397 398 399 400
MavlinkLogManager::setEnableAutoUpload(bool enable)
{
    _enableAutoUpload = enable;
    QSettings settings;
    settings.setValue(kEnableAutoUploadKey, enable);
    emit enableAutoUploadChanged();
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::setEnableAutoStart(bool enable)
Gus Grubba's avatar
Gus Grubba committed
401
{
402
    _enableAutoStart = enable;
Gus Grubba's avatar
Gus Grubba committed
403
    QSettings settings;
404 405
    settings.setValue(kEnableAutoStartKey, enable);
    emit enableAutoStartChanged();
Gus Grubba's avatar
Gus Grubba committed
406 407
}

408 409 410 411 412 413 414 415 416 417
//-----------------------------------------------------------------------------
void
MavlinkLogManager::setDeleteAfterUpload(bool enable)
{
    _deleteAfterUpload = enable;
    QSettings settings;
    settings.setValue(kEnableDeletetKey, enable);
    emit deleteAfterUploadChanged();
}

Gus Grubba's avatar
Gus Grubba committed
418 419
//-----------------------------------------------------------------------------
bool
420
MavlinkLogManager::uploading()
Gus Grubba's avatar
Gus Grubba committed
421 422 423 424 425 426 427 428 429 430 431
{
    return _currentLogfile != NULL;
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::uploadLog()
{
    if(_currentLogfile) {
        _currentLogfile->setUploading(false);
    }
Gus Grubba's avatar
Gus Grubba committed
432
    for(int i = 0; i < _logFiles.count(); i++) {
Gus Grubba's avatar
Gus Grubba committed
433 434 435 436
        _currentLogfile = qobject_cast<MavlinkLogFiles*>(_logFiles.get(i));
        Q_ASSERT(_currentLogfile);
        if(_currentLogfile->selected()) {
            _currentLogfile->setSelected(false);
Gus Grubba's avatar
Gus Grubba committed
437 438 439 440 441 442 443 444
            if(!_currentLogfile->uploaded() && !_emailAddress.isEmpty() && !_uploadURL.isEmpty()) {
                _currentLogfile->setUploading(true);
                _currentLogfile->setProgress(0.0);
                QString filePath = _makeFilename(_currentLogfile->name());
                _sendLog(filePath);
                emit uploadingChanged();
                return;
            }
Gus Grubba's avatar
Gus Grubba committed
445 446 447
        }
    }
    _currentLogfile = NULL;
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    emit uploadingChanged();
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::_insertNewLog(MavlinkLogFiles* newLog)
{
    //-- Simpler than trying to sort this thing
    int count = _logFiles.count();
    if(!count) {
        _logFiles.append(newLog);
    } else {
        for(int i = 0; i < count; i++) {
            MavlinkLogFiles* f = qobject_cast<MavlinkLogFiles*>(_logFiles.get(i));
            if(newLog->name() < f->name()) {
                _logFiles.insert(i, newLog);
                return;
            }
        }
        _logFiles.append(newLog);
    }
Gus Grubba's avatar
Gus Grubba committed
469 470
}

Gus Grubba's avatar
Gus Grubba committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484
//-----------------------------------------------------------------------------
int
MavlinkLogManager::_getFirstSelected()
{
    for(int i = 0; i < _logFiles.count(); i++) {
        MavlinkLogFiles* f = qobject_cast<MavlinkLogFiles*>(_logFiles.get(i));
        Q_ASSERT(f);
        if(f->selected()) {
            return i;
        }
    }
    return -1;
}

Gus Grubba's avatar
Gus Grubba committed
485 486 487 488
//-----------------------------------------------------------------------------
void
MavlinkLogManager::deleteLog()
{
Gus Grubba's avatar
Gus Grubba committed
489 490 491 492 493
    while (true) {
        int idx = _getFirstSelected();
        if(idx < 0) {
            break;
        }
494 495
        MavlinkLogFiles* log = qobject_cast<MavlinkLogFiles*>(_logFiles.get(idx));
        _deleteLog(log);
Gus Grubba's avatar
Gus Grubba committed
496
    }
Gus Grubba's avatar
Gus Grubba committed
497 498
}

499 500 501 502
//-----------------------------------------------------------------------------
void
MavlinkLogManager::_deleteLog(MavlinkLogFiles* log)
{
Gus Grubba's avatar
Gus Grubba committed
503
    QString filePath = _makeFilename(log->name());
504 505 506 507
    QFile gone(filePath);
    if(!gone.remove()) {
        qCWarning(MavlinkLogManagerLog) << "Could not delete Mavlink log file:" << _logPath;
    }
Gus Grubba's avatar
Gus Grubba committed
508 509 510 511 512 513 514
    //-- Remove sidecar file (if any)
    filePath.replace(kUlogExtension, kSidecarExtension);
    QFile sgone(filePath);
    if(sgone.exists()) {
        sgone.remove();
    }
    //-- Remove file from list and delete record
515 516 517 518 519
    _logFiles.removeOne(log);
    delete log;
    emit logFilesChanged();
}

Gus Grubba's avatar
Gus Grubba committed
520 521 522 523
//-----------------------------------------------------------------------------
void
MavlinkLogManager::cancelUpload()
{
Gus Grubba's avatar
Gus Grubba committed
524
    for(int i = 0; i < _logFiles.count(); i++) {
Gus Grubba's avatar
Gus Grubba committed
525 526 527 528 529 530 531 532 533 534 535
        MavlinkLogFiles* pLogFile = qobject_cast<MavlinkLogFiles*>(_logFiles.get(i));
        Q_ASSERT(pLogFile);
        if(pLogFile->selected() && pLogFile != _currentLogfile) {
            pLogFile->setSelected(false);
        }
    }
    if(_currentLogfile) {
        emit abortUpload();
    }
}

536 537 538 539 540
//-----------------------------------------------------------------------------
void
MavlinkLogManager::startLogging()
{
    if(_vehicle) {
Gus Grubba's avatar
Gus Grubba committed
541 542 543
        if(_createNewLog()) {
            _vehicle->startMavlinkLog();
            _logRunning = true;
544 545
            _loggingCmdTryCount = 0;
            _ackTimer.start(kTimeOutMilliseconds);
Gus Grubba's avatar
Gus Grubba committed
546 547
            emit logRunningChanged();
        }
548 549 550 551 552 553 554 555
    }
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::stopLogging()
{
    if(_vehicle) {
556
        //-- Tell vehicle to stop sending logs
557
        _vehicle->stopMavlinkLog();
558
    }
Gus Grubba's avatar
Gus Grubba committed
559 560 561 562
    if(_logProcessor) {
        _logProcessor->close();
        if(_logProcessor->record()) {
            _logProcessor->record()->setWriting(false);
563 564
            if(_enableAutoUpload) {
                //-- Queue log for auto upload (set selected flag)
Gus Grubba's avatar
Gus Grubba committed
565
                _logProcessor->record()->setSelected(true);
566 567
                if(!uploading()) {
                    uploadLog();
568
                }
Gus Grubba's avatar
Gus Grubba committed
569 570
            }
        }
Gus Grubba's avatar
Gus Grubba committed
571 572
        delete _logProcessor;
        _logProcessor = NULL;
573 574 575 576 577 578 579
        _logRunning = false;
        if(_vehicle) {
            //-- Setup a timer to make sure vehicle received the command
            _loggingCmdTryCount = 0;
            _ackTimer.start(kTimeOutMilliseconds);
        }
        emit logRunningChanged();
580 581 582
    }
}

Gus Grubba's avatar
Gus Grubba committed
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
//-----------------------------------------------------------------------------
QHttpPart
create_form_part(const QString& name, const QString& value)
{
    QHttpPart formPart;
    formPart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"%1\"").arg(name));
    formPart.setBody(value.toUtf8());
    return formPart;
}

//-----------------------------------------------------------------------------
bool
MavlinkLogManager::_sendLog(const QString& logFile)
{
    QString defaultDescription = _description;
    if(_description.isEmpty()) {
        qCWarning(MavlinkLogManagerLog) << "Log description missing. Using defaults.";
        defaultDescription = kDefaultDescr;
    }
    if(_emailAddress.isEmpty()) {
        qCCritical(MavlinkLogManagerLog) << "User email missing.";
        return false;
    }
    if(_uploadURL.isEmpty()) {
        qCCritical(MavlinkLogManagerLog) << "Upload URL missing.";
        return false;
    }
    QFileInfo fi(logFile);
    if(!fi.exists()) {
        qCCritical(MavlinkLogManagerLog) << "Log file missing:" << logFile;
        return false;
    }
Gus Grubba's avatar
Gus Grubba committed
615
    QFile* file = new QFile(logFile);
Gus Grubba's avatar
Gus Grubba committed
616
    if(!file || !file->open(QIODevice::ReadOnly)) {
Gus Grubba's avatar
Gus Grubba committed
617 618 619
        if(file) {
            delete file;
        }
Gus Grubba's avatar
Gus Grubba committed
620 621 622 623
        qCCritical(MavlinkLogManagerLog) << "Could not open log file:" << logFile;
        return false;
    }
    if(!_nam) {
Gus Grubba's avatar
Gus Grubba committed
624
        _nam = new QNetworkAccessManager(this);
Gus Grubba's avatar
Gus Grubba committed
625 626 627 628 629 630
    }
    QNetworkProxy savedProxy = _nam->proxy();
    QNetworkProxy tempProxy;
    tempProxy.setType(QNetworkProxy::DefaultProxy);
    _nam->setProxy(tempProxy);
    //-- Build POST request
Gus Grubba's avatar
Gus Grubba committed
631
    QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
Gus Grubba's avatar
Gus Grubba committed
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
    QHttpPart emailPart = create_form_part("email", _emailAddress);
    QHttpPart descriptionPart = create_form_part("description", _description);
    QHttpPart sourcePart = create_form_part("source", "QGroundControl");
    QHttpPart versionPart = create_form_part("version", _app->applicationVersion());
    QHttpPart logPart;
    logPart.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    logPart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"filearg\"; filename=\"%1\"").arg(fi.fileName()));
    logPart.setBodyDevice(file);
    //-- Assemble request and POST it
    multiPart->append(emailPart);
    multiPart->append(descriptionPart);
    multiPart->append(sourcePart);
    multiPart->append(versionPart);
    multiPart->append(logPart);
    file->setParent(multiPart);
    QNetworkRequest request(_uploadURL);
648
#if QT_VERSION > 0x050600
Gus Grubba's avatar
Gus Grubba committed
649
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
650
#endif
Gus Grubba's avatar
Gus Grubba committed
651
    QNetworkReply* reply = _nam->post(request, multiPart);
Gus Grubba's avatar
Gus Grubba committed
652 653 654 655 656 657 658 659 660 661 662 663
    connect(reply, &QNetworkReply::finished,  this, &MavlinkLogManager::_uploadFinished);
    connect(this, &MavlinkLogManager::abortUpload, reply, &QNetworkReply::abort);
    //connect(reply, &QNetworkReply::readyRead, this, &MavlinkLogManager::_dataAvailable);
    connect(reply, &QNetworkReply::uploadProgress, this, &MavlinkLogManager::_uploadProgress);
    multiPart->setParent(reply);
    qCDebug(MavlinkLogManagerLog) << "Log" << fi.baseName() << "Uploading." << fi.size() << "bytes.";
    _nam->setProxy(savedProxy);
    return true;
}

//-----------------------------------------------------------------------------
bool
Gus Grubba's avatar
Gus Grubba committed
664
MavlinkLogManager::_processUploadResponse(int http_code, QByteArray& data)
Gus Grubba's avatar
Gus Grubba committed
665 666 667 668 669 670 671 672 673 674
{
    qCDebug(MavlinkLogManagerLog) << "Uploaded response:" << QString::fromUtf8(data);
    emit readyRead(data);
    return http_code == 200;
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::_dataAvailable()
{
Gus Grubba's avatar
Gus Grubba committed
675
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
Gus Grubba's avatar
Gus Grubba committed
676 677 678 679 680 681 682 683 684 685 686
    if(!reply) {
        return;
    }
    QByteArray data = reply->readAll();
    qCDebug(MavlinkLogManagerLog) << "Uploaded response data:" << QString::fromUtf8(data);
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::_uploadFinished()
{
Gus Grubba's avatar
Gus Grubba committed
687
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
Gus Grubba's avatar
Gus Grubba committed
688 689 690 691 692 693 694 695
    if(!reply) {
        return;
    }
    const int http_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    QByteArray data = reply->readAll();
    if(_processUploadResponse(http_code, data)) {
        qCDebug(MavlinkLogManagerLog) << "Log uploaded.";
        emit succeed();
696 697 698 699 700
        if(_deleteAfterUpload) {
            if(_currentLogfile) {
                _deleteLog(_currentLogfile);
                _currentLogfile = NULL;
            }
Gus Grubba's avatar
Gus Grubba committed
701 702 703 704 705 706 707 708 709 710 711
        } else {
            if(_currentLogfile) {
                _currentLogfile->setUploaded(true);
                //-- Write side-car file to flag it as uploaded
                QString sideCar = _makeFilename(_currentLogfile->name());
                sideCar.replace(kUlogExtension, kSidecarExtension);
                FILE* f = fopen(sideCar.toLatin1().data(), "wb");
                if(f) {
                    fclose(f);
                }
            }
712
        }
Gus Grubba's avatar
Gus Grubba committed
713
    } else {
714
        qCWarning(MavlinkLogManagerLog) << QString("Log Upload Error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString());
Gus Grubba's avatar
Gus Grubba committed
715 716 717 718 719 720 721 722 723 724 725 726 727
        emit failed();
    }
    reply->deleteLater();
    //-- Next (if any)
    uploadLog();
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::_uploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
    if(bytesTotal) {
        qreal progress = (qreal)bytesSent / (qreal)bytesTotal;
Gus Grubba's avatar
Gus Grubba committed
728
        if(_currentLogfile) {
Gus Grubba's avatar
Gus Grubba committed
729
            _currentLogfile->setProgress(progress);
Gus Grubba's avatar
Gus Grubba committed
730
        }
Gus Grubba's avatar
Gus Grubba committed
731 732 733
    }
    qCDebug(MavlinkLogManagerLog) << bytesSent << "of" << bytesTotal;
}
734 735 736 737 738 739 740 741 742

//-----------------------------------------------------------------------------
void
MavlinkLogManager::_activeVehicleChanged(Vehicle* vehicle)
{
    //-- TODO: This is not quite right. This is being used to detect when a vehicle
    //   connects/disconnects. In reality, if QGC is connected to multiple vehicles,
    //   this is called each time the user switches from one vehicle to another. So
    //   far, I'm working on the assumption that multiple vehicles is a rare exception.
Gus Grubba's avatar
Gus Grubba committed
743
    //   For now, we only handle one log download at a time.
744
    // Disconnect the previous one (if any)
Gus Grubba's avatar
Gus Grubba committed
745
    if(_vehicle) {
746 747
        disconnect(_vehicle, &Vehicle::armedChanged,   this, &MavlinkLogManager::_armedChanged);
        disconnect(_vehicle, &Vehicle::mavlinkLogData, this, &MavlinkLogManager::_mavlinkLogData);
748
        disconnect(_vehicle, &Vehicle::commandLongAck, this, &MavlinkLogManager::_commandLongAck);
749
        _vehicle = NULL;
750 751
        //-- Stop logging (if that's the case)
        stopLogging();
752 753 754
        emit canStartLogChanged();
    }
    // Connect new system
Gus Grubba's avatar
Gus Grubba committed
755
    if(vehicle) {
756 757 758
        _vehicle = vehicle;
        connect(_vehicle, &Vehicle::armedChanged,   this, &MavlinkLogManager::_armedChanged);
        connect(_vehicle, &Vehicle::mavlinkLogData, this, &MavlinkLogManager::_mavlinkLogData);
759
        connect(_vehicle, &Vehicle::commandLongAck, this, &MavlinkLogManager::_commandLongAck);
760 761 762 763
        emit canStartLogChanged();
    }
}

764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
//-----------------------------------------------------------------------------
void
MavlinkLogManager::_processCmdAck()
{
    if(_loggingCmdTryCount++ > 3) {
        _ackTimer.stop();
        //-- Give up
        if(_logRunning) {
            qCWarning(MavlinkLogManagerLog) << "Start MAVLink log command had no response.";
            _discardLog();
        } else {
            qCWarning(MavlinkLogManagerLog) << "Stop MAVLink log command had no response.";
        }
    } else {
        if(_vehicle) {
            if(_logRunning) {
                _vehicle->startMavlinkLog();
                qCWarning(MavlinkLogManagerLog) << "Start MAVLink log command sent again.";
            } else {
                _vehicle->stopMavlinkLog();
                qCWarning(MavlinkLogManagerLog) << "Stop MAVLink log command sent again.";
            }
            _ackTimer.start(kTimeOutMilliseconds);
        } else {
            //-- Vehicle went away on us
            _ackTimer.stop();
        }
    }
}

794 795
//-----------------------------------------------------------------------------
void
Gus Grubba's avatar
Gus Grubba committed
796
MavlinkLogManager::_mavlinkLogData(Vehicle* /*vehicle*/, uint8_t /*target_system*/, uint8_t /*target_component*/, uint16_t sequence, uint8_t first_message, QByteArray data, bool /*acked*/)
Gus Grubba's avatar
Gus Grubba committed
797
{
798 799 800 801
    //-- Disable timer if we got a message before an ACK for the start command
    if(_logRunning) {
        _ackTimer.stop();
    }
Gus Grubba's avatar
Gus Grubba committed
802 803 804 805 806
    if(_logProcessor && _logProcessor->valid()) {
        if(!_logProcessor->processStreamData(sequence, first_message, data)) {
            qCCritical(MavlinkLogManagerLog) << "Error writing Mavlink log file:" << _logProcessor->fileName();
            delete _logProcessor;
            _logProcessor = NULL;
Gus Grubba's avatar
Gus Grubba committed
807 808 809 810 811 812 813 814 815
            _logRunning = false;
            _vehicle->stopMavlinkLog();
            emit logRunningChanged();
        }
    } else {
        qCWarning(MavlinkLogManagerLog) << "Mavlink log data received when not expected.";
    }
}

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
//-----------------------------------------------------------------------------
void
MavlinkLogManager::_commandLongAck(uint8_t /*compID*/, uint16_t command, uint8_t result)
{
    if(command == MAV_CMD_LOGGING_START || command == MAV_CMD_LOGGING_STOP) {
        _ackTimer.stop();
        //-- Did it fail?
        if(result) {
            if(command == MAV_CMD_LOGGING_STOP) {
                //-- Not that it could happen but...
                qCWarning(MavlinkLogManagerLog) << "Stop MAVLink log command failed.";
            } else {
                //-- Could not start logging for some reason.
                qCWarning(MavlinkLogManagerLog) << "Start MAVLink log command failed.";
                _discardLog();
            }
        }
    }
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::_discardLog()
{
    //-- Delete (empty) log file (and record)
Gus Grubba's avatar
Gus Grubba committed
841 842 843 844
    if(_logProcessor) {
        _logProcessor->close();
        if(_logProcessor->record()) {
            _deleteLog(_logProcessor->record());
845
        }
Gus Grubba's avatar
Gus Grubba committed
846 847
        delete _logProcessor;
        _logProcessor = NULL;
848 849 850 851 852
    }
    _logRunning = false;
    emit logRunningChanged();
}

Gus Grubba's avatar
Gus Grubba committed
853 854 855
//-----------------------------------------------------------------------------
bool
MavlinkLogManager::_createNewLog()
856
{
Gus Grubba's avatar
Gus Grubba committed
857 858 859
    if(_logProcessor) {
        delete _logProcessor;
        _logProcessor = NULL;
Gus Grubba's avatar
Gus Grubba committed
860
    }
Gus Grubba's avatar
Gus Grubba committed
861 862 863
    _logProcessor = new MavlinkLogProcessor;
    if(_logProcessor->create(this, _logPath, _vehicle->id())) {
        _insertNewLog(_logProcessor->record());
864 865
        emit logFilesChanged();
    } else {
Gus Grubba's avatar
Gus Grubba committed
866 867 868
        qCCritical(MavlinkLogManagerLog) << "Could not create Mavlink log file:" << _logProcessor->fileName();
        delete _logProcessor;
        _logProcessor = NULL;
Gus Grubba's avatar
Gus Grubba committed
869
    }
Gus Grubba's avatar
Gus Grubba committed
870
    return _logProcessor != NULL;
871 872 873 874 875 876 877 878 879
}

//-----------------------------------------------------------------------------
void
MavlinkLogManager::_armedChanged(bool armed)
{
    if(_vehicle) {
        if(armed) {
            if(_enableAutoStart) {
Gus Grubba's avatar
Gus Grubba committed
880
                startLogging();
881 882 883
            }
        } else {
            if(_logRunning && _enableAutoStart) {
Gus Grubba's avatar
Gus Grubba committed
884
                stopLogging();
885 886 887 888
            }
        }
    }
}
Gus Grubba's avatar
Gus Grubba committed
889 890 891 892 893 894 895 896 897 898 899

//-----------------------------------------------------------------------------
QString
MavlinkLogManager::_makeFilename(const QString& baseName)
{
    QString filePath = _logPath;
    filePath += "/";
    filePath += baseName;
    filePath += kUlogExtension;
    return filePath;
}