PX4FirmwareUpgradeThread.cc 15.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*=====================================================================
 
 QGroundControl Open Source Ground Control Station
 
 (c) 2009, 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 
 This file is part of the QGROUNDCONTROL project
 
 QGROUNDCONTROL is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 QGROUNDCONTROL is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
 
 ======================================================================*/

/// @file
///     @brief PX4 Firmware Upgrade operations which occur on a seperate thread.
///     @author Don Gagne <don@thegagnes.com>

#include "PX4FirmwareUpgradeThread.h"
29 30 31
#include "Bootloader.h"
#include "QGCLoggingCategory.h"
#include "QGC.h"
32
#include "SerialPortIds.h"
33 34 35 36

#include <QTimer>
#include <QSerialPortInfo>
#include <QDebug>
Don Gagne's avatar
Don Gagne committed
37
#include <QSerialPort>
38

39 40
PX4FirmwareUpgradeThreadWorker::PX4FirmwareUpgradeThreadWorker(PX4FirmwareUpgradeThreadController* controller) :
    _controller(controller),
41 42
    _bootloader(NULL),
    _bootloaderPort(NULL),
43 44 45
    _timerRetry(NULL),
    _foundBoard(false),
    _findBoardFirstAttempt(true)
46
{
47
    Q_ASSERT(_controller);
48
    
49 50 51 52 53
    connect(_controller, &PX4FirmwareUpgradeThreadController::_initThreadWorker,            this, &PX4FirmwareUpgradeThreadWorker::_init);
    connect(_controller, &PX4FirmwareUpgradeThreadController::_startFindBoardLoopOnThread,  this, &PX4FirmwareUpgradeThreadWorker::_startFindBoardLoop);
    connect(_controller, &PX4FirmwareUpgradeThreadController::_flashOnThread,               this, &PX4FirmwareUpgradeThreadWorker::_flash);
    connect(_controller, &PX4FirmwareUpgradeThreadController::_rebootOnThread,              this, &PX4FirmwareUpgradeThreadWorker::_reboot);
    connect(_controller, &PX4FirmwareUpgradeThreadController::_cancel,                      this, &PX4FirmwareUpgradeThreadWorker::_cancel);
54 55 56 57 58 59 60 61 62 63 64 65
}

PX4FirmwareUpgradeThreadWorker::~PX4FirmwareUpgradeThreadWorker()
{
    if (_bootloaderPort) {
        // deleteLater so delete happens on correct thread
        _bootloaderPort->deleteLater();
    }
}

/// @brief Initializes the PX4FirmwareUpgradeThreadWorker with the various child objects which must be created
///         on the worker thread.
66
void PX4FirmwareUpgradeThreadWorker::_init(void)
67 68 69 70 71 72 73 74
{
    // We create the timers here so that they are on the right thread
    
    Q_ASSERT(_timerRetry == NULL);
    _timerRetry = new QTimer(this);
    Q_CHECK_PTR(_timerRetry);
    _timerRetry->setSingleShot(true);
    _timerRetry->setInterval(_retryTimeout);
75
    connect(_timerRetry, &QTimer::timeout, this, &PX4FirmwareUpgradeThreadWorker::_findBoardOnce);
76 77
    
    Q_ASSERT(_bootloader == NULL);
78 79
    _bootloader = new Bootloader(this);
    connect(_bootloader, &Bootloader::updateProgress, this, &PX4FirmwareUpgradeThreadWorker::_updateProgress);
80 81
}

82
void PX4FirmwareUpgradeThreadWorker::_cancel(void)
83
{
84 85 86 87 88 89 90 91 92 93
    if (_bootloaderPort) {
        _bootloaderPort->close();
        _bootloaderPort->deleteLater();
        _bootloaderPort = NULL;
    }
}

void PX4FirmwareUpgradeThreadWorker::_startFindBoardLoop(void)
{
    _foundBoard = false;
Don Gagne's avatar
Don Gagne committed
94
    _findBoardFirstAttempt = true;
95 96 97 98 99
    _findBoardOnce();
}

void PX4FirmwareUpgradeThreadWorker::_findBoardOnce(void)
{
100
    qCDebug(FirmwareUpgradeLog) << "_findBoardOnce";
101
    
102 103
    QSerialPortInfo                     portInfo;
    PX4FirmwareUpgradeFoundBoardType_t  boardType;
104
    
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    if (_findBoardFromPorts(portInfo, boardType)) {
        if (!_foundBoard) {
            _foundBoard = true;
            _foundBoardPortInfo = portInfo;
            emit foundBoard(_findBoardFirstAttempt, portInfo, boardType);
            if (!_findBoardFirstAttempt) {
                if (boardType == FoundBoard3drRadio) {
                    _3drRadioForceBootloader(portInfo);
                    return;
                } else {
                    _findBootloader(portInfo, false /* radio mode */, true /* errorOnNotFound */);
                    return;
                }
            }
        }
    } else {
        if (_foundBoard) {
            _foundBoard = false;
            qCDebug(FirmwareUpgradeLog) << "Board gone";
            emit boardGone();
        } else if (_findBoardFirstAttempt) {
            emit noBoardFound();
127 128 129
        }
    }
    
Don Gagne's avatar
Don Gagne committed
130
    _findBoardFirstAttempt = false;
131 132 133
    _timerRetry->start();
}

134
bool PX4FirmwareUpgradeThreadWorker::_findBoardFromPorts(QSerialPortInfo& portInfo, PX4FirmwareUpgradeFoundBoardType_t& type)
135
{
136
    bool found = false;
137 138
    
    foreach (QSerialPortInfo info, QSerialPortInfo::availablePorts()) {
139 140 141 142 143 144 145 146
        qCDebug(FirmwareUpgradeLog) << "Serial Port --------------";
        qCDebug(FirmwareUpgradeLog) << "\tport name:" << info.portName();
        qCDebug(FirmwareUpgradeLog) << "\tdescription:" << info.description();
        qCDebug(FirmwareUpgradeLog) << "\tsystem location:" << info.systemLocation();
        qCDebug(FirmwareUpgradeLog) << "\tvendor ID:" << info.vendorIdentifier();
        qCDebug(FirmwareUpgradeLog) << "\tproduct ID:" << info.productIdentifier();
        
        if (!info.portName().isEmpty()) {
147 148
            switch (info.vendorIdentifier()) {
                case SerialPortIds::px4VendorId:
Don Gagne's avatar
Don Gagne committed
149
                    if (info.productIdentifier() == SerialPortIds::pixhawkFMUV2ProductId || info.productIdentifier() == SerialPortIds::pixhawkFMUV2OldBootloaderProductId) {
150 151 152 153 154 155 156 157 158 159 160
                        qCDebug(FirmwareUpgradeLog) << "Found PX4 FMU V2";
                        type = FoundBoardPX4FMUV2;
                        found = true;
                    } else if (info.productIdentifier() == SerialPortIds::pixhawkFMUV1ProductId) {
                        qCDebug(FirmwareUpgradeLog) << "Found PX4 FMU V1";
                        type = FoundBoardPX4FMUV2;
                        found = true;
                    } else if (info.productIdentifier() == SerialPortIds::px4FlowProductId) {
                        qCDebug(FirmwareUpgradeLog) << "Found PX4 Flow";
                        type = FoundBoardPX4Flow;
                        found = true;
161 162 163 164
                    } else if (info.productIdentifier() == SerialPortIds::AeroCoreProductId) {
                        qCDebug(FirmwareUpgradeLog) << "Found AeroCore";
                        type = FoundBoardAeroCore;
                        found = true;
165 166 167 168 169 170 171 172 173
                    }
                    break;
                case SerialPortIds::threeDRRadioVendorId:
                    if (info.productIdentifier() == SerialPortIds::threeDRRadioProductId) {
                        qCDebug(FirmwareUpgradeLog) << "Found 3DR Radio";
                        type = FoundBoard3drRadio;
                        found = true;
                    }
                    break;
174
            }
175 176 177 178 179 180 181 182 183
            if (!found) {
                // Fall back to port name matching which could lead to incorrect board mapping. But in some cases the
                // vendor and product id do not come through correctly so this is used as a last chance detection method.
                if (info.description() == "PX4 FMU v2.x") {
                    qCDebug(FirmwareUpgradeLog) << "Found PX4 FMU V2 (by name matching fallback)";
                    type = FoundBoardPX4FMUV2;
                    found = true;
                }
            }
184 185 186 187
        }
        
        if (found) {
            portInfo = info;
188 189 190 191 192 193 194
            return true;
        }
    }
    
    return false;
}

195
void PX4FirmwareUpgradeThreadWorker::_3drRadioForceBootloader(const QSerialPortInfo& portInfo)
196
{
197 198 199 200 201 202 203 204 205
    // First make sure we can't get the bootloader
    
    if (_findBootloader(portInfo, true /* radio Mode */, false /* errorOnNotFound */)) {
        return;
    }

    // Couldn't find the bootloader. We'll need to reboot the radio into bootloader.
    
    QSerialPort port(portInfo);
Don Gagne's avatar
Don Gagne committed
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
    port.setBaudRate(QSerialPort::Baud57600);
    
    emit status("Putting radio into command mode");
    
    // Wait a little while for the USB port to initialize. 3DR Radio boot is really slow.
    for (int i=0; i<12; i++) {
        if (port.open(QIODevice::ReadWrite)) {
            break;
        } else {
            QGC::SLEEP::msleep(250);
        }
    }
    
    if (!port.isOpen()) {
        emit error(QString("Unable to open port: %1 error: %2").arg(portInfo.systemLocation()).arg(port.errorString()));
        return;
    }

    // Put radio into command mode
    port.write("+++", 3);
    if (!port.waitForReadyRead(1500)) {
        emit error("Unable to put radio into command mode");
        return;
    }
    QByteArray bytes = port.readAll();
    if (!bytes.contains("OK")) {
        emit error("Unable to put radio into command mode");
        return;
    }

    emit status("Rebooting radio to bootloader");
    
    port.write("AT&UPDATE\r\n");
    if (!port.waitForBytesWritten(1500)) {
        emit error("Unable to reboot radio");
        return;
    }
    QGC::SLEEP::msleep(2000);
    port.close();
    
    // The bootloader should be waiting for us now
    
    _findBootloader(portInfo, true /* radio mode */, true /* errorOnNotFound */);
250 251
}

252
bool PX4FirmwareUpgradeThreadWorker::_findBootloader(const QSerialPortInfo& portInfo, bool radioMode, bool errorOnNotFound)
253
{
254
    qCDebug(FirmwareUpgradeLog) << "_findBootloader";
255
    
256 257 258
    uint32_t bootloaderVersion = 0;
    uint32_t boardID;
    uint32_t flashSize = 0;
259

260
    
261
    _bootloaderPort = new QextSerialPort(QextSerialPort::Polling);
262 263
    Q_CHECK_PTR(_bootloaderPort);
    
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    // Wait a little while for the USB port to initialize.
    for (int i=0; i<10; i++) {
        if (_bootloader->open(_bootloaderPort, portInfo.systemLocation())) {
            break;
        } else {
            QGC::SLEEP::msleep(100);
        }
    }
    
    if (_bootloader->sync(_bootloaderPort)) {
        bool success;
        
        if (radioMode) {
            success = _bootloader->get3DRRadioBoardId(_bootloaderPort, boardID);
        } else {
            success = _bootloader->getPX4BoardInfo(_bootloaderPort, bootloaderVersion, boardID, flashSize);
        }
        if (success) {
            qCDebug(FirmwareUpgradeLog) << "Found bootloader";
            emit foundBootloader(bootloaderVersion, boardID, flashSize);
            return true;
285 286 287
        }
    }
    
Don Gagne's avatar
Don Gagne committed
288 289 290
    _bootloaderPort->close();
    _bootloaderPort->deleteLater();
    _bootloaderPort = NULL;
291 292 293 294 295 296
    qCDebug(FirmwareUpgradeLog) << "Bootloader error:" << _bootloader->errorString();
    if (errorOnNotFound) {
        emit error(_bootloader->errorString());
    }
    
    return false;
297 298
}

299
void PX4FirmwareUpgradeThreadWorker::_reboot(void)
300
{
301 302
    if (_bootloaderPort) {
        if (_bootloaderPort->isOpen()) {
303
            _bootloader->reboot(_bootloaderPort);
304 305 306 307
        }
        _bootloaderPort->deleteLater();
        _bootloaderPort = NULL;
    }
308 309
}

310
void PX4FirmwareUpgradeThreadWorker::_flash(void)
311
{
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    qCDebug(FirmwareUpgradeLog) << "PX4FirmwareUpgradeThreadWorker::_flash";
    
    if (_erase()) {
        emit status("Programming new version...");
        
        if (_bootloader->program(_bootloaderPort, _controller->image())) {
            qCDebug(FirmwareUpgradeLog) << "Program complete";
            emit status("Program complete");
        } else {
            _bootloaderPort->deleteLater();
            _bootloaderPort = NULL;
            qCDebug(FirmwareUpgradeLog) << "Program failed:" << _bootloader->errorString();
            emit error(_bootloader->errorString());
        }
        
        emit status("Verifying program...");
        
        if (_bootloader->verify(_bootloaderPort, _controller->image())) {
            qCDebug(FirmwareUpgradeLog) << "Verify complete";
            emit status("Verify complete");
        } else {
            qCDebug(FirmwareUpgradeLog) << "Verify failed:" << _bootloader->errorString();
            emit error(_bootloader->errorString());
        }
336
    }
337 338 339 340
    
    emit _reboot();
    
    emit flashComplete();
341 342
}

343
bool PX4FirmwareUpgradeThreadWorker::_erase(void)
344
{
345 346 347 348 349 350 351 352 353 354
    qCDebug(FirmwareUpgradeLog) << "PX4FirmwareUpgradeThreadWorker::_erase";
    
    emit eraseStarted();
    emit status("Erasing previous program...");
    
    if (_bootloader->erase(_bootloaderPort)) {
        qCDebug(FirmwareUpgradeLog) << "Erase complete";
        emit status("Erase complete");
        emit eraseComplete();
        return true;
355
    } else {
356 357 358
        qCDebug(FirmwareUpgradeLog) << "Erase failed:" << _bootloader->errorString();
        emit error(_bootloader->errorString());
        return false;
359 360 361 362 363 364
    }
}

PX4FirmwareUpgradeThreadController::PX4FirmwareUpgradeThreadController(QObject* parent) :
    QObject(parent)
{
365
    _worker = new PX4FirmwareUpgradeThreadWorker(this);
366 367 368 369 370 371
    Q_CHECK_PTR(_worker);
    
    _workerThread = new QThread(this);
    Q_CHECK_PTR(_workerThread);
    _worker->moveToThread(_workerThread);
    
372 373 374 375 376
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::updateProgress,       this, &PX4FirmwareUpgradeThreadController::_updateProgress);
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::foundBoard,           this, &PX4FirmwareUpgradeThreadController::_foundBoard);
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::noBoardFound,         this, &PX4FirmwareUpgradeThreadController::_noBoardFound);
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::boardGone,            this, &PX4FirmwareUpgradeThreadController::_boardGone);
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::foundBootloader,      this, &PX4FirmwareUpgradeThreadController::_foundBootloader);
377
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::bootloaderSyncFailed, this, &PX4FirmwareUpgradeThreadController::_bootloaderSyncFailed);
378 379 380 381 382
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::error,                this, &PX4FirmwareUpgradeThreadController::_error);
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::status,               this, &PX4FirmwareUpgradeThreadController::_status);
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::eraseStarted,         this, &PX4FirmwareUpgradeThreadController::_eraseStarted);
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::eraseComplete,        this, &PX4FirmwareUpgradeThreadController::_eraseComplete);
    connect(_worker, &PX4FirmwareUpgradeThreadWorker::flashComplete,        this, &PX4FirmwareUpgradeThreadController::_flashComplete);
383 384 385 386 387 388 389 390 391 392

    _workerThread->start();
    
    emit _initThreadWorker();
}

PX4FirmwareUpgradeThreadController::~PX4FirmwareUpgradeThreadController()
{
    _workerThread->quit();
    _workerThread->wait();
393 394
    
    delete _workerThread;
395 396
}

397
void PX4FirmwareUpgradeThreadController::startFindBoardLoop(void)
398
{
399 400
    qCDebug(FirmwareUpgradeLog) << "PX4FirmwareUpgradeThreadController::findBoard";
    emit _startFindBoardLoopOnThread();
401 402
}

403
void PX4FirmwareUpgradeThreadController::cancel(void)
404
{
405 406
    qCDebug(FirmwareUpgradeLog) << "PX4FirmwareUpgradeThreadController::cancel";
    emit _cancel();
407 408
}

409
void PX4FirmwareUpgradeThreadController::flash(const FirmwareImage* image)
410
{
411 412
    _image = image;
    emit _flashOnThread();
413
}