FirmwareUpgradeController.cc 46.2 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (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.
 *
 ****************************************************************************/
9

10 11 12 13 14 15

/// @file
///     @brief PX4 Firmware Upgrade UI
///     @author Don Gagne <don@thegagnes.com>

#include "FirmwareUpgradeController.h"
16
#include "Bootloader.h"
17
#include "QGCQFileDialog.h"
18
#include "QGCApplication.h"
19
#include "QGCFileDownload.h"
20 21
#include "QGCOptions.h"
#include "QGCCorePlugin.h"
Pritam Ghanghas's avatar
Pritam Ghanghas committed
22

Don Gagne's avatar
Don Gagne committed
23 24
#include <QStandardPaths>
#include <QRegularExpression>
Don Gagne's avatar
Don Gagne committed
25 26
#include <QJsonDocument>
#include <QJsonObject>
27
#include <QJsonArray>
28
#include <QNetworkProxy>
Don Gagne's avatar
Don Gagne committed
29

Pritam Ghanghas's avatar
Pritam Ghanghas committed
30 31 32 33 34 35 36
struct FirmwareToUrlElement_t {
    FirmwareUpgradeController::AutoPilotStackType_t    stackType;
    FirmwareUpgradeController::FirmwareType_t          firmwareType;
    FirmwareUpgradeController::FirmwareVehicleType_t   vehicleType;
    QString                                            url;
};

37
uint qHash(const FirmwareUpgradeController::FirmwareIdentifier& firmwareId)
38
{
39
    return static_cast<uint>(( firmwareId.autopilotStackType |
40
             (firmwareId.firmwareType << 8) |
41
             (firmwareId.firmwareVehicleType << 16) ));
42 43
}

44
/// @Brief Constructs a new FirmwareUpgradeController Widget. This widget is used within the PX4VehicleConfig set of screens.
45
FirmwareUpgradeController::FirmwareUpgradeController(void)
46 47 48 49 50 51 52 53
    : _singleFirmwareURL                (qgcApp()->toolbox()->corePlugin()->options()->firmwareUpgradeSingleURL())
    , _singleFirmwareMode               (!_singleFirmwareURL.isEmpty())
    , _downloadManager                  (nullptr)
    , _downloadNetworkReply             (nullptr)
    , _statusLog                        (nullptr)
    , _selectedFirmwareType             (StableFirmware)
    , _image                            (nullptr)
    , _apmBoardDescriptionReplaceText   ("<APMBoardDescription>")
54 55 56 57
{
    _threadController = new PX4FirmwareUpgradeThreadController(this);
    Q_CHECK_PTR(_threadController);

58 59 60 61 62 63 64 65 66 67 68 69 70
    connect(_threadController, &PX4FirmwareUpgradeThreadController::foundBoard,             this, &FirmwareUpgradeController::_foundBoard);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::noBoardFound,           this, &FirmwareUpgradeController::_noBoardFound);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::boardGone,              this, &FirmwareUpgradeController::_boardGone);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::foundBootloader,        this, &FirmwareUpgradeController::_foundBootloader);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::bootloaderSyncFailed,   this, &FirmwareUpgradeController::_bootloaderSyncFailed);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::error,                  this, &FirmwareUpgradeController::_error);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::updateProgress,         this, &FirmwareUpgradeController::_updateProgress);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::status,                 this, &FirmwareUpgradeController::_status);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::eraseStarted,           this, &FirmwareUpgradeController::_eraseStarted);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::eraseComplete,          this, &FirmwareUpgradeController::_eraseComplete);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::flashComplete,          this, &FirmwareUpgradeController::_flashComplete);
    connect(_threadController, &PX4FirmwareUpgradeThreadController::updateProgress,         this, &FirmwareUpgradeController::_updateProgress);
    
71
    connect(&_eraseTimer, &QTimer::timeout, this, &FirmwareUpgradeController::_eraseProgressTick);
72 73

    _initFirmwareHash();
Don Gagne's avatar
Don Gagne committed
74
    _determinePX4StableVersion();
75 76
}

Don Gagne's avatar
Don Gagne committed
77 78 79 80 81
FirmwareUpgradeController::~FirmwareUpgradeController()
{
    qgcApp()->toolbox()->linkManager()->setConnectionsAllowed();
}

82
void FirmwareUpgradeController::startBoardSearch(void)
83
{
Don Gagne's avatar
Don Gagne committed
84 85 86 87
    LinkManager* linkMgr = qgcApp()->toolbox()->linkManager();

    linkMgr->setConnectionsSuspended(tr("Connect not allowed during Firmware Upgrade."));

88 89
    // FIXME: Why did we get here with active vehicle?
    if (!qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()) {
Don Gagne's avatar
Don Gagne committed
90 91 92
        // We have to disconnect any inactive links
        linkMgr->disconnectAll();
    }
93

94 95 96
    _bootloaderFound = false;
    _startFlashWhenBootloaderFound = false;
    _threadController->startFindBoardLoop();
97 98
}

99 100 101
void FirmwareUpgradeController::flash(AutoPilotStackType_t stackType,
                                      FirmwareType_t firmwareType,
                                      FirmwareVehicleType_t vehicleType)
102
{
103
    qCDebug(FirmwareUpgradeLog) << "_flash stackType:firmwareType:vehicleType" << stackType << firmwareType << vehicleType;
104
    FirmwareIdentifier firmwareId = FirmwareIdentifier(stackType, firmwareType, vehicleType);
105
    if (_bootloaderFound) {
106
        _getFirmwareFile(firmwareId);
107 108 109
    } else {
        // We haven't found the bootloader yet. Need to wait until then to flash
        _startFlashWhenBootloaderFound = true;
110
        _startFlashWhenBootloaderFoundFirmwareIdentity = firmwareId;
111
    }
112 113
}

114 115 116 117 118
void FirmwareUpgradeController::flash(const FirmwareIdentifier& firmwareId)
{
    flash(firmwareId.autopilotStackType, firmwareId.firmwareType, firmwareId.firmwareVehicleType);
}

Gus Grubba's avatar
Gus Grubba committed
119
void FirmwareUpgradeController::flashSingleFirmwareMode(FirmwareType_t firmwareType)
120
{
Gus Grubba's avatar
Gus Grubba committed
121
    flash(SingleFirmwareMode, firmwareType, DefaultVehicleFirmware);
122 123
}

124
void FirmwareUpgradeController::cancel(void)
125
{
126 127 128
    _eraseTimer.stop();
    _threadController->cancel();
}
129

130
void FirmwareUpgradeController::_foundBoard(bool firstAttempt, const QSerialPortInfo& info, int boardType, QString boardName)
131 132
{
    _foundBoardInfo = info;
133
    _foundBoardType = static_cast<QGCSerialPortInfo::BoardType_t>(boardType);
134 135
    _foundBoardTypeName = boardName;
    _startFlashWhenBootloaderFound = false;
136

137
    if (_foundBoardType == QGCSerialPortInfo::BoardTypeSiKRadio) {
138 139 140 141 142 143 144 145
        if (!firstAttempt) {
            // Radio always flashes latest firmware, so we can start right away without
            // any further user input.
            _startFlashWhenBootloaderFound = true;
            _startFlashWhenBootloaderFoundFirmwareIdentity = FirmwareIdentifier(ThreeDRRadio,
                                                                                StableFirmware,
                                                                                DefaultVehicleFirmware);
        }
146
    }
147
    
148
    qCDebug(FirmwareUpgradeLog) << _foundBoardType << _foundBoardTypeName;
149
    emit boardFound();
150 151
}

152 153

void FirmwareUpgradeController::_noBoardFound(void)
154
{
155 156 157 158 159 160
    emit noBoardFound();
}

void FirmwareUpgradeController::_boardGone(void)
{
    emit boardGone();
161 162 163 164 165 166
}

/// @brief Called when the bootloader is connected to by the findBootloader process. Moves the state machine
///         to the next step.
void FirmwareUpgradeController::_foundBootloader(int bootloaderVersion, int boardID, int flashSize)
{
167
    _bootloaderFound = true;
168 169 170
    _bootloaderVersion = static_cast<uint32_t>(bootloaderVersion);
    _bootloaderBoardID = static_cast<uint32_t>(boardID);
    _bootloaderBoardFlashSize = static_cast<uint32_t>(flashSize);
171
    
172 173 174 175
    _appendStatusLog(tr("Connected to bootloader:"));
    _appendStatusLog(tr("  Version: %1").arg(_bootloaderVersion));
    _appendStatusLog(tr("  Board ID: %1").arg(_bootloaderBoardID));
    _appendStatusLog(tr("  Flash size: %1").arg(_bootloaderBoardFlashSize));
176
    
177
    if (_startFlashWhenBootloaderFound) {
178
        flash(_startFlashWhenBootloaderFoundFirmwareIdentity);
179
    }
180 181

    _loadAPMVersions(_bootloaderBoardID);
182 183 184
}


Pritam Ghanghas's avatar
Pritam Ghanghas committed
185 186 187
/// @brief intializes the firmware hashes with proper urls.
/// This happens only once for a class instance first time when it is needed.
void FirmwareUpgradeController::_initFirmwareHash()
188
{
Pritam Ghanghas's avatar
Pritam Ghanghas committed
189 190 191 192 193
    // indirect check whether this function has been called before or not
    // may have to be modified if _rgPX4FMUV2Firmware disappears
    if (!_rgPX4FMUV2Firmware.isEmpty()) {
        return;
    }
194

Pritam Ghanghas's avatar
Pritam Ghanghas committed
195 196 197 198 199
    //////////////////////////////////// PX4FMU aerocore firmwares //////////////////////////////////////////////////
    FirmwareToUrlElement_t  rgAeroCoreFirmwareArray[] = {
        { AutoPilotStackPX4, StableFirmware,    DefaultVehicleFirmware, "http://gumstix-aerocore.s3.amazonaws.com/PX4/stable/aerocore_default.px4"},
        { AutoPilotStackPX4, BetaFirmware,      DefaultVehicleFirmware, "http://gumstix-aerocore.s3.amazonaws.com/PX4/beta/aerocore_default.px4"},
        { AutoPilotStackPX4, DeveloperFirmware, DefaultVehicleFirmware, "http://gumstix-aerocore.s3.amazonaws.com/PX4/master/aerocore_default.px4"},
200
    #if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
201
        { AutoPilotStackAPM, BetaFirmware,      CopterFirmware,         "http://firmware.ardupilot.org/Copter/beta/PX4/ArduCopter-v2.px4"},
Pritam Ghanghas's avatar
Pritam Ghanghas committed
202 203 204
        { AutoPilotStackAPM, StableFirmware,    HeliFirmware,           "http://gumstix-aerocore.s3.amazonaws.com/Copter/stable/PX4-heli/ArduCopter-v2.px4"},
        { AutoPilotStackAPM, StableFirmware,    PlaneFirmware,          "http://gumstix-aerocore.s3.amazonaws.com/Plane/stable/PX4/ArduPlane-v2.px4"},
        { AutoPilotStackAPM, StableFirmware,    RoverFirmware,          "http://gumstix-aerocore.s3.amazonaws.com/Rover/stable/PX4/APMrover2-v2.px4"},
205 206 207
        { AutoPilotStackAPM, BetaFirmware,      HeliFirmware,           "http://firmware.ardupilot.org/Copter/beta/PX4-heli/ArduCopter-v2.px4"},
        { AutoPilotStackAPM, BetaFirmware,      PlaneFirmware,          "http://firmware.ardupilot.org/Plane/beta/PX4/ArduPlane-v2.px4"},
        { AutoPilotStackAPM, BetaFirmware,      RoverFirmware,          "http://firmware.ardupilot.org/Rover/beta/PX4/APMrover2-v2.px4"},
Don Gagne's avatar
Don Gagne committed
208
        { AutoPilotStackAPM, DeveloperFirmware, CopterFirmware,         "http://gumstix-aerocore.s3.amazonaws.com/Copter/latest/PX4/ArduCopter-v2.px4"},
Pritam Ghanghas's avatar
Pritam Ghanghas committed
209 210 211
        { AutoPilotStackAPM, DeveloperFirmware, HeliFirmware,           "http://gumstix-aerocore.s3.amazonaws.com/Copter/latest/PX4-heli/ArduCopter-v2.px4"},
        { AutoPilotStackAPM, DeveloperFirmware, PlaneFirmware,          "http://gumstix-aerocore.s3.amazonaws.com/Plane/latest/PX4/ArduPlane-v2.px4"},
        { AutoPilotStackAPM, DeveloperFirmware, RoverFirmware,          "http://gumstix-aerocore.s3.amazonaws.com/Rover/latest/PX4/APMrover2-v2.px4"}
212
    #endif
Pritam Ghanghas's avatar
Pritam Ghanghas committed
213
    };
214

215 216 217 218 219
    //////////////////////////////////// AUAVX2_1 firmwares //////////////////////////////////////////////////
    FirmwareToUrlElement_t rgAUAVX2_1FirmwareArray[] = {
        { AutoPilotStackPX4, StableFirmware,    DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/stable/auav-x21_default.px4"},
        { AutoPilotStackPX4, BetaFirmware,      DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/beta/auav-x21_default.px4"},
        { AutoPilotStackPX4, DeveloperFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/master/auav-x21_default.px4"},
220
    #if !defined(NO_ARDUPILOT_DIALECT)
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        { AutoPilotStackAPM, StableFirmware,    CopterFirmware,         "http://firmware.ardupilot.org/Copter/stable/PX4/ArduCopter-v3.px4"},
        { AutoPilotStackAPM, StableFirmware,    HeliFirmware,           "http://firmware.ardupilot.org/Copter/stable/PX4-heli/ArduCopter-v3.px4"},
        { AutoPilotStackAPM, StableFirmware,    PlaneFirmware,          "http://firmware.ardupilot.org/Plane/stable/PX4/ArduPlane-v2.px4"},
        { AutoPilotStackAPM, StableFirmware,    RoverFirmware,          "http://firmware.ardupilot.org/Rover/stable/PX4/APMrover2-v2.px4"},
        { AutoPilotStackAPM, StableFirmware,    SubFirmware,            "http://firmware.ardupilot.org/Sub/stable/PX4/ArduSub-v2.px4"},
        { AutoPilotStackAPM, BetaFirmware,      CopterFirmware,         "http://firmware.ardupilot.org/Copter/beta/PX4/ArduCopter-v3.px4"},
        { AutoPilotStackAPM, BetaFirmware,      HeliFirmware,           "http://firmware.ardupilot.org/Copter/beta/PX4-heli/ArduCopter-v3.px4"},
        { AutoPilotStackAPM, BetaFirmware,      PlaneFirmware,          "http://firmware.ardupilot.org/Plane/beta/PX4/ArduPlane-v3.px4"},
        { AutoPilotStackAPM, BetaFirmware,      RoverFirmware,          "http://firmware.ardupilot.org/Rover/beta/PX4/APMrover2-v3.px4"},
        { AutoPilotStackAPM, BetaFirmware,      SubFirmware,            "http://firmware.ardupilot.org/Sub/beta/PX4/ArduSub-v3.px4"},
        { AutoPilotStackAPM, DeveloperFirmware, CopterFirmware,         "http://firmware.ardupilot.org/Copter/latest/PX4/ArduCopter-v3.px4"},
        { AutoPilotStackAPM, DeveloperFirmware, HeliFirmware,           "http://firmware.ardupilot.org/Copter/latest/PX4-heli/ArduCopter-v3.px4"},
        { AutoPilotStackAPM, DeveloperFirmware, PlaneFirmware,          "http://firmware.ardupilot.org/Plane/latest/PX4/ArduPlane-v3.px4"},
        { AutoPilotStackAPM, DeveloperFirmware, RoverFirmware,          "http://firmware.ardupilot.org/Rover/latest/PX4/APMrover2-v3.px4"},
        { AutoPilotStackAPM, DeveloperFirmware, SubFirmware,            "http://firmware.ardupilot.org/Sub/latest/PX4/ArduSub-v3.px4"}
236
    #endif
237
    };
Henry Zhang's avatar
Henry Zhang committed
238 239 240 241 242 243
    //////////////////////////////////// MindPXFMUV2 firmwares //////////////////////////////////////////////////
    FirmwareToUrlElement_t rgMindPXFMUV2FirmwareArray[] = {
        { AutoPilotStackPX4, StableFirmware,    DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/stable/mindpx-v2_default.px4"},
        { AutoPilotStackPX4, BetaFirmware,      DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/beta/mindpx-v2_default.px4"},
        { AutoPilotStackPX4, DeveloperFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/master/mindpx-v2_default.px4"},
    };
244 245 246 247 248
    //////////////////////////////////// TAPV1 firmwares //////////////////////////////////////////////////
    FirmwareToUrlElement_t rgTAPV1FirmwareArray[] = {
        { AutoPilotStackPX4, StableFirmware,    DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/stable/tap-v1_default.px4"},
        { AutoPilotStackPX4, BetaFirmware,      DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/beta/tap-v1_default.px4"},
        { AutoPilotStackPX4, DeveloperFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/master/tap-v1_default.px4"},
249
        { SingleFirmwareMode,StableFirmware,    DefaultVehicleFirmware, _singleFirmwareURL},
250 251 252 253 254 255 256
    };
    //////////////////////////////////// ASCV1 firmwares //////////////////////////////////////////////////
    FirmwareToUrlElement_t rgASCV1FirmwareArray[] = {
        { AutoPilotStackPX4, StableFirmware,    DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/stable/asc-v1_default.px4"},
        { AutoPilotStackPX4, BetaFirmware,      DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/beta/asc-v1_default.px4"},
        { AutoPilotStackPX4, DeveloperFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/master/asc-v1_default.px4"},
    };
257 258 259 260 261 262 263 264

    //////////////////////////////////// Crazyflie 2.0 firmwares //////////////////////////////////////////////////
    FirmwareToUrlElement_t rgCrazyflie2FirmwareArray[] = {
        { AutoPilotStackPX4, StableFirmware,    DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/stable/crazyflie_default.px4"},
        { AutoPilotStackPX4, BetaFirmware,      DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/beta/crazyflie_default.px4"},
        { AutoPilotStackPX4, DeveloperFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/master/crazyflie_default.px4"},
    };

265 266 267 268 269 270
    FirmwareToUrlElement_t rgOmnibusF4SDFirmwareArray[] = {
        { AutoPilotStackPX4, StableFirmware,    DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/stable/omnibus_f4sd_default.px4"},
        { AutoPilotStackPX4, BetaFirmware,      DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/beta/omnibus_f4sd_default.px4"},
        { AutoPilotStackPX4, DeveloperFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/master/omnibus_f4sd_default.px4"},
    };

Pritam Ghanghas's avatar
Pritam Ghanghas committed
271 272
    /////////////////////////////// px4flow firmwares ///////////////////////////////////////
    FirmwareToUrlElement_t rgPX4FLowFirmwareArray[] = {
273
        { PX4FlowPX4, StableFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Flow/master/px4flow.px4" },
274
    #if !defined(NO_ARDUPILOT_DIALECT)
DonLakeFlyer's avatar
DonLakeFlyer committed
275
        { PX4FlowAPM, StableFirmware, DefaultVehicleFirmware, "http://firmware.ardupilot.org/Tools/PX4Flow/px4flow-klt-latest.px4" },
276
    #endif
Pritam Ghanghas's avatar
Pritam Ghanghas committed
277 278 279 280
    };

    /////////////////////////////// 3dr radio firmwares ///////////////////////////////////////
    FirmwareToUrlElement_t rg3DRRadioFirmwareArray[] = {
281
        { ThreeDRRadio, StableFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/SiK/stable/radio~hm_trp.ihx"}
Pritam Ghanghas's avatar
Pritam Ghanghas committed
282 283
    };

Don Gagne's avatar
Don Gagne committed
284 285 286 287 288 289 290 291 292 293
    // We build the maps for PX4 and ArduPilot firmwares dynamically using the data below

#if 0
    Example URLs for PX4 and ArduPilot
    { AutoPilotStackPX4, StableFirmware,    DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Firmware/stable/px4fmu-v4_default.px4"},
    { AutoPilotStackAPM, StableFirmware,    CopterFirmware,         "http://firmware.ardupilot.org/Copter/stable/PX4/ArduCopter-v4.px4"},
    { AutoPilotStackAPM, DeveloperFirmware, CopterChibiosFirmware,  "http://firmware.ardupilot.org/Copter/latest/fmuv4/arducopter.apj"},
#endif

    QString px4Url          ("http://px4-travis.s3.amazonaws.com/Firmware/%1/px4fmu-%2_default.px4");
Don Gagne's avatar
Don Gagne committed
294
    QString apmUrl          ("http://firmware.ardupilot.org/%1/%2/%3/%4-v%5.px4");
Don Gagne's avatar
Don Gagne committed
295 296 297
    QString apmChibiOSUrl   ("http://firmware.ardupilot.org/%1/%2/fmuv%3%4/%5.apj");

    QMap<FirmwareType_t, QString> px4MapFirmwareTypeToDir;
Don Gagne's avatar
Don Gagne committed
298 299 300
    px4MapFirmwareTypeToDir[StableFirmware] =       QStringLiteral("stable");
    px4MapFirmwareTypeToDir[BetaFirmware] =         QStringLiteral("beta");
    px4MapFirmwareTypeToDir[DeveloperFirmware] =    QStringLiteral("master");
Don Gagne's avatar
Don Gagne committed
301

302
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
303
    QMap<FirmwareVehicleType_t, QString> apmMapVehicleTypeToDir;
Don Gagne's avatar
Don Gagne committed
304 305 306 307 308
    apmMapVehicleTypeToDir[CopterFirmware] =    QStringLiteral("Copter");
    apmMapVehicleTypeToDir[HeliFirmware] =      QStringLiteral("Copter");
    apmMapVehicleTypeToDir[PlaneFirmware] =     QStringLiteral("Plane");
    apmMapVehicleTypeToDir[RoverFirmware] =     QStringLiteral("Rover");
    apmMapVehicleTypeToDir[SubFirmware] =       QStringLiteral("Sub");
309
#endif
Don Gagne's avatar
Don Gagne committed
310

311
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
312 313 314 315 316 317
    QMap<FirmwareVehicleType_t, QString> apmChibiOSMapVehicleTypeToDir;
    apmChibiOSMapVehicleTypeToDir[CopterChibiOSFirmware] =  QStringLiteral("Copter");
    apmChibiOSMapVehicleTypeToDir[HeliChibiOSFirmware] =    QStringLiteral("Copter");
    apmChibiOSMapVehicleTypeToDir[PlaneChibiOSFirmware] =   QStringLiteral("Plane");
    apmChibiOSMapVehicleTypeToDir[RoverChibiOSFirmware] =   QStringLiteral("Rover");
    apmChibiOSMapVehicleTypeToDir[SubChibiOSFirmware] =     QStringLiteral("Sub");
318
#endif
Don Gagne's avatar
Don Gagne committed
319

320
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
321
    QMap<FirmwareType_t, QString> apmMapFirmwareTypeToDir;
Don Gagne's avatar
Don Gagne committed
322 323 324
    apmMapFirmwareTypeToDir[StableFirmware] =       QStringLiteral("stable");
    apmMapFirmwareTypeToDir[BetaFirmware] =         QStringLiteral("beta");
    apmMapFirmwareTypeToDir[DeveloperFirmware] =    QStringLiteral("latest");
325
#endif
Don Gagne's avatar
Don Gagne committed
326

327
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
328
    QMap<FirmwareVehicleType_t, QString> apmMapVehicleTypeToPX4Dir;
Don Gagne's avatar
Don Gagne committed
329 330 331 332 333
    apmMapVehicleTypeToPX4Dir[CopterFirmware] = QStringLiteral("PX4");
    apmMapVehicleTypeToPX4Dir[HeliFirmware] =   QStringLiteral("PX4-heli");
    apmMapVehicleTypeToPX4Dir[PlaneFirmware] =  QStringLiteral("PX4");
    apmMapVehicleTypeToPX4Dir[RoverFirmware] =  QStringLiteral("PX4");
    apmMapVehicleTypeToPX4Dir[SubFirmware] =    QStringLiteral("PX4");
334
#endif
Don Gagne's avatar
Don Gagne committed
335

336
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
337
    QMap<FirmwareVehicleType_t, QString> apmMapVehicleTypeToFilename;
Don Gagne's avatar
Don Gagne committed
338
    apmMapVehicleTypeToFilename[CopterFirmware] =   QStringLiteral("ArduCopter");
Don Gagne's avatar
Don Gagne committed
339
    apmMapVehicleTypeToFilename[HeliFirmware] =     QStringLiteral("ArduCopter");
Don Gagne's avatar
Don Gagne committed
340 341 342
    apmMapVehicleTypeToFilename[PlaneFirmware] =    QStringLiteral("ArduPlane");
    apmMapVehicleTypeToFilename[RoverFirmware] =    QStringLiteral("APMrover2");
    apmMapVehicleTypeToFilename[SubFirmware] =      QStringLiteral("ArduSub");
343
#endif
Don Gagne's avatar
Don Gagne committed
344

345
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
346
    QMap<FirmwareVehicleType_t, QString> apmChibiOSMapVehicleTypeToFmuDir;
Don Gagne's avatar
Don Gagne committed
347 348 349 350 351
    apmChibiOSMapVehicleTypeToFmuDir[CopterChibiOSFirmware] =   QString();
    apmChibiOSMapVehicleTypeToFmuDir[HeliChibiOSFirmware] =     QStringLiteral("-heli");
    apmChibiOSMapVehicleTypeToFmuDir[PlaneChibiOSFirmware] =    QString();
    apmChibiOSMapVehicleTypeToFmuDir[RoverChibiOSFirmware] =    QString();
    apmChibiOSMapVehicleTypeToFmuDir[SubChibiOSFirmware] =      QString();
352
#endif
Don Gagne's avatar
Don Gagne committed
353

354
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
355
    QMap<FirmwareVehicleType_t, QString> apmChibiOSMapVehicleTypeToFilename;
Don Gagne's avatar
Don Gagne committed
356
    apmChibiOSMapVehicleTypeToFilename[CopterChibiOSFirmware] = QStringLiteral("arducopter");
Don Gagne's avatar
Don Gagne committed
357
    apmChibiOSMapVehicleTypeToFilename[HeliChibiOSFirmware] =   QStringLiteral("arducopter-heli");
Don Gagne's avatar
Don Gagne committed
358 359 360
    apmChibiOSMapVehicleTypeToFilename[PlaneChibiOSFirmware] =  QStringLiteral("arduplane");
    apmChibiOSMapVehicleTypeToFilename[RoverChibiOSFirmware] =  QStringLiteral("ardurover");
    apmChibiOSMapVehicleTypeToFilename[SubChibiOSFirmware] =    QStringLiteral("ardusub");
361
#endif
Don Gagne's avatar
Don Gagne committed
362 363

    // PX4 Firmwares
364
    for (const FirmwareType_t& firmwareType: px4MapFirmwareTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
365
        QString dir = px4MapFirmwareTypeToDir[firmwareType];
366 367 368 369 370
        _rgFMUV5Firmware.insert     (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v5"));
        _rgFMUV4PROFirmware.insert  (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v4pro"));
        _rgFMUV4Firmware.insert     (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v4"));
        _rgFMUV3Firmware.insert     (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v3"));
        _rgPX4FMUV2Firmware.insert  (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v2"));
Don Gagne's avatar
Don Gagne committed
371 372
    }

373
#if !defined(NO_ARDUPILOT_DIALECT)
374
    // ArduPilot non-ChibiOS Firmwares for direct board id to fmu mappings
375
    for (const FirmwareType_t& firmwareType: apmMapFirmwareTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
376
        QString firmwareTypeDir = apmMapFirmwareTypeToDir[firmwareType];
377
        for (const FirmwareVehicleType_t& vehicleType: apmMapVehicleTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
378 379 380
            QString vehicleTypeDir = apmMapVehicleTypeToDir[vehicleType];
            QString px4Dir = apmMapVehicleTypeToPX4Dir[vehicleType];
            QString filename = apmMapVehicleTypeToFilename[vehicleType];
381 382 383
            _rgFMUV5Firmware.insert     (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(px4Dir).arg(filename).arg("5"));
            _rgFMUV4Firmware.insert     (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(px4Dir).arg(filename).arg("4"));
            _rgFMUV3Firmware.insert     (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(px4Dir).arg(filename).arg("3"));
Don Gagne's avatar
Don Gagne committed
384 385
            _rgPX4FMUV2Firmware.insert  (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(px4Dir).arg(filename).arg("2"));
        }
DonLakeFlyer's avatar
DonLakeFlyer committed
386 387
    }

388
    // ArduPilot ChibiOS Firmwares for direct board id to fmu mappings. Used when bootloader is not new ArduPilot bootloader.
389
    for (const FirmwareType_t& firmwareType: apmMapFirmwareTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
390
        QString firmwareTypeDir = apmMapFirmwareTypeToDir[firmwareType];
391
        for (const FirmwareVehicleType_t& vehicleType: apmChibiOSMapVehicleTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
392 393 394
            QString vehicleTypeDir = apmChibiOSMapVehicleTypeToDir[vehicleType];
            QString fmuDir = apmChibiOSMapVehicleTypeToFmuDir[vehicleType];
            QString filename = apmChibiOSMapVehicleTypeToFilename[vehicleType];
395 396 397 398
            _rgFMUV5Firmware.insert     (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmChibiOSUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg("5").arg(fmuDir).arg(filename));
            _rgFMUV4Firmware.insert     (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmChibiOSUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg("4").arg(fmuDir).arg(filename));
            _rgFMUV3Firmware.insert     (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmChibiOSUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg("3").arg(fmuDir).arg(filename));
            _rgPX4FMUV2Firmware.insert  (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmChibiOSUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg("2").arg(fmuDir).arg(filename));
Don Gagne's avatar
Don Gagne committed
399
        }
Pritam Ghanghas's avatar
Pritam Ghanghas committed
400
    }
401

402
    // ArduPilot ChibiOS Firmwares when board id is an unknown type but follows ArduPilot port info naming conventions.
403
    // This is only used if the board is using the new ArduPilot bootloader port naming scheme.
404 405 406 407 408 409 410 411 412 413 414 415
    for (const FirmwareType_t& firmwareType: apmMapFirmwareTypeToDir.keys()) {
        QString firmwareTypeDir = apmMapFirmwareTypeToDir[firmwareType];
        for (const FirmwareVehicleType_t& vehicleType: apmChibiOSMapVehicleTypeToDir.keys()) {
            QString namedURL("http://firmware.ardupilot.org/%1/%2/%3%4/%5.apj");
            QString vehicleTypeDir = apmChibiOSMapVehicleTypeToDir[vehicleType];
            QString fmuDir = apmChibiOSMapVehicleTypeToFmuDir[vehicleType];
            QString filename = apmChibiOSMapVehicleTypeToFilename[vehicleType];
            _rgAPMChibiosReplaceNamedBoardFirmware.insert(FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), namedURL.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(_apmBoardDescriptionReplaceText).arg(fmuDir).arg(filename));
        }
    }
#endif

Don Gagne's avatar
Don Gagne committed
416
    int size = sizeof(rgAeroCoreFirmwareArray)/sizeof(rgAeroCoreFirmwareArray[0]);
Pritam Ghanghas's avatar
Pritam Ghanghas committed
417 418 419 420
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgAeroCoreFirmwareArray[i];
        _rgAeroCoreFirmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }
421

422 423 424 425 426 427
    size = sizeof(rgAUAVX2_1FirmwareArray)/sizeof(rgAUAVX2_1FirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgAUAVX2_1FirmwareArray[i];
        _rgAUAVX2_1Firmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }

Henry Zhang's avatar
Henry Zhang committed
428 429 430 431 432 433
    size = sizeof(rgMindPXFMUV2FirmwareArray)/sizeof(rgMindPXFMUV2FirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgMindPXFMUV2FirmwareArray[i];
        _rgMindPXFMUV2Firmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }

434 435 436 437 438 439 440 441 442 443 444 445
    size = sizeof(rgTAPV1FirmwareArray)/sizeof(rgTAPV1FirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgTAPV1FirmwareArray[i];
        _rgTAPV1Firmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }

    size = sizeof(rgASCV1FirmwareArray)/sizeof(rgASCV1FirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgASCV1FirmwareArray[i];
        _rgASCV1Firmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }

446 447 448 449 450 451
    size = sizeof(rgCrazyflie2FirmwareArray)/sizeof(rgCrazyflie2FirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgCrazyflie2FirmwareArray[i];
        _rgCrazyflie2Firmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }

452 453 454 455 456 457
    size = sizeof(rgOmnibusF4SDFirmwareArray)/sizeof(rgOmnibusF4SDFirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgOmnibusF4SDFirmwareArray[i];
        _rgOmnibusF4SDFirmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }

Pritam Ghanghas's avatar
Pritam Ghanghas committed
458 459 460 461 462
    size = sizeof(rgPX4FLowFirmwareArray)/sizeof(rgPX4FLowFirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgPX4FLowFirmwareArray[i];
        _rgPX4FLowFirmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }
463

Pritam Ghanghas's avatar
Pritam Ghanghas committed
464 465 466 467 468
    size = sizeof(rg3DRRadioFirmwareArray)/sizeof(rg3DRRadioFirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rg3DRRadioFirmwareArray[i];
        _rg3DRRadioFirmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }
469 470 471 472 473 474

    size = sizeof(rg3DRRadioFirmwareArray)/sizeof(rg3DRRadioFirmwareArray[0]);
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rg3DRRadioFirmwareArray[i];
        _rg3DRRadioFirmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }
Pritam Ghanghas's avatar
Pritam Ghanghas committed
475
}
476

Pritam Ghanghas's avatar
Pritam Ghanghas committed
477 478 479 480 481 482
/// @brief Called when the findBootloader process is unable to sync to the bootloader. Moves the state
///         machine to the appropriate error state.
void FirmwareUpgradeController::_bootloaderSyncFailed(void)
{
    _errorCancel("Unable to sync with bootloader.");
}
483

484
QHash<FirmwareUpgradeController::FirmwareIdentifier, QString>* FirmwareUpgradeController::_firmwareHashForBoardId(int boardId)
Pritam Ghanghas's avatar
Pritam Ghanghas committed
485
{
486 487

    _rgFirmwareDynamic.clear();
488

489 490
    switch (boardId) {
    case Bootloader::boardIDPX4Flow:
491
        _rgFirmwareDynamic = _rgPX4FLowFirmware;
492
        break;
493
    case Bootloader::boardIDPX4FMUV2:
494
        _rgFirmwareDynamic = _rgPX4FMUV2Firmware;
495
        break;
DonLakeFlyer's avatar
DonLakeFlyer committed
496
    case Bootloader::boardIDPX4FMUV3:
497
        _rgFirmwareDynamic = _rgFMUV3Firmware;
498
        break;
499
    case Bootloader::boardIDPX4FMUV4:
500
        _rgFirmwareDynamic = _rgFMUV4Firmware;
501
        break;
502
    case Bootloader::boardIDPX4FMUV4PRO:
503
        _rgFirmwareDynamic = _rgFMUV4PROFirmware;
504
        break;
505
    case Bootloader::boardIDPX4FMUV5:
506
        _rgFirmwareDynamic = _rgFMUV5Firmware;
507
        break;
508
    case Bootloader::boardIDAeroCore:
509
        _rgFirmwareDynamic = _rgAeroCoreFirmware;
510
        break;
511
    case Bootloader::boardIDAUAVX2_1:
512
        _rgFirmwareDynamic = _rgAUAVX2_1Firmware;
513
        break;
Henry Zhang's avatar
Henry Zhang committed
514
    case Bootloader::boardIDMINDPXFMUV2:
515
        _rgFirmwareDynamic = _rgMindPXFMUV2Firmware;
516
        break;
517
    case Bootloader::boardIDTAPV1:
518
        _rgFirmwareDynamic = _rgTAPV1Firmware;
519
        break;
520
    case Bootloader::boardIDASCV1:
521
        _rgFirmwareDynamic = _rgASCV1Firmware;
522
        break;
523
    case Bootloader::boardIDCrazyflie2:
524
        _rgFirmwareDynamic = _rgCrazyflie2Firmware;
525
        break;
526
    case Bootloader::boardIDOmnibusF4SD:
527
        _rgFirmwareDynamic = _rgOmnibusF4SDFirmware;
528
        break;
529 530
    case Bootloader::boardIDFMUK66V3:
        _rgFirmwareDynamic = _rgFMUK66V3Firmware;
531
        break;
532
    case Bootloader::boardID3DRRadio:
533
        _rgFirmwareDynamic = _rg3DRRadioFirmware;
534
        break;
535
    default:
536 537
        // Unknown board id
        break;
538 539
    }

540 541 542 543 544
    // Check for ArduPilot ChibiOS bootloader
    QStringList rgManufacturers = { QStringLiteral("ArduPilot"), QStringLiteral("Hex/ProfiCNC"), QStringLiteral("Holybro") };
    QString apmDescriptionSuffix("-BL");
    if (rgManufacturers.contains(_foundBoardInfo.manufacturer()) && _foundBoardInfo.description().endsWith(apmDescriptionSuffix)) {
        // Board ios using a ChibiOS bootloader. Prefer naming scheme from that over board ids for ArduPilot entries.
545

546 547 548
        // First remove the ChibiOS by board id entries from the list
        for (const FirmwareIdentifier& firmwareId: _rgAPMChibiosReplaceNamedBoardFirmware.keys()) {
            _rgFirmwareDynamic.remove(firmwareId);
549 550
        }

551
        // Now add the ChibiOS by board description entries to the list
552 553
        for (const FirmwareIdentifier& firmwareId: _rgAPMChibiosReplaceNamedBoardFirmware.keys()) {
            QString namedUrl = _rgAPMChibiosReplaceNamedBoardFirmware[firmwareId];
554
            _rgFirmwareDynamic.insert(firmwareId, namedUrl.replace(_apmBoardDescriptionReplaceText, _foundBoardInfo.description().left(_foundBoardInfo.description().length() - apmDescriptionSuffix.length())));
555 556 557 558
        }
    }

    return &_rgFirmwareDynamic;
559
}
Lorenz Meier's avatar
Lorenz Meier committed
560

561 562 563
/// @brief Prompts the user to select a firmware file if needed and moves the state machine to the next state.
void FirmwareUpgradeController::_getFirmwareFile(FirmwareIdentifier firmwareId)
{
564
    QHash<FirmwareIdentifier, QString>* prgFirmware = _firmwareHashForBoardId(static_cast<int>(_bootloaderBoardID));
565
    
566
    if (firmwareId.firmwareType == CustomFirmware) {
567 568 569
        _firmwareFilename = QGCQFileDialog::getOpenFileName(nullptr,                                                                // Parent to main window
                                                            tr("Select Firmware File"),                                             // Dialog Caption
                                                            QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),    // Initial directory
570
                                                            tr("Firmware Files (*.px4 *.apj *.bin *.ihx)"));                              // File filter
571
    } else {
572 573
        if (prgFirmware->contains(firmwareId)) {
            _firmwareFilename = prgFirmware->value(firmwareId);
574
        } else {
575
            _errorCancel(tr("Unable to find specified firmware for board type"));
576 577
            return;
        }
578 579 580
    }
    
    if (_firmwareFilename.isEmpty()) {
581
        _errorCancel(tr("No firmware file selected"));
582 583 584 585 586 587 588 589 590 591
    } else {
        _downloadFirmware();
    }
}

/// @brief Begins the process of downloading the selected firmware file.
void FirmwareUpgradeController::_downloadFirmware(void)
{
    Q_ASSERT(!_firmwareFilename.isEmpty());
    
592 593
    _appendStatusLog(tr("Downloading firmware..."));
    _appendStatusLog(tr(" From: %1").arg(_firmwareFilename));
594
    
595 596 597 598 599
    QGCFileDownload* downloader = new QGCFileDownload(this);
    connect(downloader, &QGCFileDownload::downloadFinished, this, &FirmwareUpgradeController::_firmwareDownloadFinished);
    connect(downloader, &QGCFileDownload::downloadProgress, this, &FirmwareUpgradeController::_firmwareDownloadProgress);
    connect(downloader, &QGCFileDownload::error,            this, &FirmwareUpgradeController::_firmwareDownloadError);
    downloader->download(_firmwareFilename);
600 601 602
}

/// @brief Updates the progress indicator while downloading
603
void FirmwareUpgradeController::_firmwareDownloadProgress(qint64 curr, qint64 total)
604 605 606
{
    // Take care of cases where 0 / 0 is emitted as error return value
    if (total > 0) {
607
        _progressBar->setProperty("value", static_cast<float>(curr) / static_cast<float>(total));
608 609 610 611
    }
}

/// @brief Called when the firmware download completes.
612
void FirmwareUpgradeController::_firmwareDownloadFinished(QString remoteFile, QString localFile)
613
{
614 615
    Q_UNUSED(remoteFile);

616
    _appendStatusLog(tr("Download complete"));
617
    
618
    FirmwareImage* image = new FirmwareImage(this);
619
    
620 621
    connect(image, &FirmwareImage::statusMessage, this, &FirmwareUpgradeController::_status);
    connect(image, &FirmwareImage::errorMessage, this, &FirmwareUpgradeController::_error);
622
    
623
    if (!image->load(localFile, _bootloaderBoardID)) {
624
        _errorCancel(tr("Image load failed"));
625
        return;
626 627
    }
    
628 629
    // We can't proceed unless we have the bootloader
    if (!_bootloaderFound) {
630
        _errorCancel(tr("Bootloader not found"));
631 632
        return;
    }
633
    
634
    if (_bootloaderBoardFlashSize != 0 && image->imageSize() > _bootloaderBoardFlashSize) {
635
        _errorCancel(tr("Image size of %1 is too large for board flash size %2").arg(image->imageSize()).arg(_bootloaderBoardFlashSize));
636
        return;
637
    }
638 639

    _threadController->flash(image);
640 641
}

642
/// @brief Called when an error occurs during download
643
void FirmwareUpgradeController::_firmwareDownloadError(QString errorMsg)
644
{
645
    _errorCancel(errorMsg);
646 647
}

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
/// @brief returns firmware type as a string
QString FirmwareUpgradeController::firmwareTypeAsString(FirmwareType_t type) const
{
    switch (type) {
    case StableFirmware:
        return "stable";
    case DeveloperFirmware:
        return "developer";
    case BetaFirmware:
        return "beta";
    default:
        return "custom";
    }
}

663 664 665
/// @brief Signals completion of one of the specified bootloader commands. Moves the state machine to the
///         appropriate next step.
void FirmwareUpgradeController::_flashComplete(void)
666
{
667
    delete _image;
668
    _image = nullptr;
669
    
670
    _appendStatusLog(tr("Upgrade complete"), true);
671 672
    _appendStatusLog("------------------------------------------", false);
    emit flashComplete();
673
    qgcApp()->toolbox()->linkManager()->setConnectionsAllowed();
674 675
}

676
void FirmwareUpgradeController::_error(const QString& errorString)
677
{
678
    delete _image;
679
    _image = nullptr;
680 681
    
    _errorCancel(QString("Error: %1").arg(errorString));
682 683
}

684
void FirmwareUpgradeController::_status(const QString& statusString)
685
{
686
    _appendStatusLog(statusString);
687 688 689 690 691
}

/// @brief Updates the progress bar from long running bootloader commands
void FirmwareUpgradeController::_updateProgress(int curr, int total)
{
692 693
    // Take care of cases where 0 / 0 is emitted as error return value
    if (total > 0) {
694
        _progressBar->setProperty("value", static_cast<float>(curr) / static_cast<float>(total));
695
    }
696 697 698 699 700 701
}

/// @brief Moves the progress bar ahead on tick while erasing the board
void FirmwareUpgradeController::_eraseProgressTick(void)
{
    _eraseTickCount++;
702
    _progressBar->setProperty("value", static_cast<float>(_eraseTickCount*_eraseTickMsec) / static_cast<float>(_eraseTotalMsec));
703 704 705
}

/// Appends the specified text to the status log area in the ui
706
void FirmwareUpgradeController::_appendStatusLog(const QString& text, bool critical)
707 708 709 710
{
    Q_ASSERT(_statusLog);
    
    QVariant returnedValue;
711 712 713 714 715 716 717 718
    QVariant varText;
    
    if (critical) {
        varText = QString("<font color=\"yellow\">%1</font>").arg(text);
    } else {
        varText = text;
    }
    
719 720 721 722
    QMetaObject::invokeMethod(_statusLog,
                              "append",
                              Q_RETURN_ARG(QVariant, returnedValue),
                              Q_ARG(QVariant, varText));
Don Gagne's avatar
Don Gagne committed
723
}
724

725 726 727
void FirmwareUpgradeController::_errorCancel(const QString& msg)
{
    _appendStatusLog(msg, false);
728
    _appendStatusLog(tr("Upgrade cancelled"), true);
729 730 731
    _appendStatusLog("------------------------------------------", false);
    emit error();
    cancel();
732
    qgcApp()->toolbox()->linkManager()->setConnectionsAllowed();
733 734 735 736 737 738 739 740 741 742
}

void FirmwareUpgradeController::_eraseStarted(void)
{
    // We set up our own progress bar for erase since the erase command does not provide one
    _eraseTickCount = 0;
    _eraseTimer.start(_eraseTickMsec);
}

void FirmwareUpgradeController::_eraseComplete(void)
743
{
744
    _eraseTimer.stop();
745
}
746

747
void FirmwareUpgradeController::_loadAPMVersions(uint32_t bootloaderBoardID)
748 749 750
{
    _apmVersionMap.clear();

751
    QHash<FirmwareIdentifier, QString>* prgFirmware = _firmwareHashForBoardId(static_cast<int>(bootloaderBoardID));
752

753
    for (FirmwareIdentifier firmwareId: prgFirmware->keys()) {
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 783 784
        if (firmwareId.autopilotStackType == AutoPilotStackAPM) {
            QString versionFile = QFileInfo(prgFirmware->value(firmwareId)).path() + "/git-version.txt";

            qCDebug(FirmwareUpgradeLog) << "Downloading" << versionFile;
            QGCFileDownload* downloader = new QGCFileDownload(this);
            connect(downloader, &QGCFileDownload::downloadFinished, this, &FirmwareUpgradeController::_apmVersionDownloadFinished);
            downloader->download(versionFile);
        }
    }
}

void FirmwareUpgradeController::_apmVersionDownloadFinished(QString remoteFile, QString localFile)
{
    qCDebug(FirmwareUpgradeLog) << "Download complete" << remoteFile << localFile;

    // Now read the version file and pull out the version string

    QFile versionFile(localFile);
    versionFile.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream stream(&versionFile);
    QString versionContents = stream.readAll();

    QString version;
    QRegularExpression re("APMVERSION: (.*)$");
    QRegularExpressionMatch match = re.match(versionContents);
    if (match.hasMatch()) {
        version = match.captured(1);
    }

    if (version.isEmpty()) {
        qWarning() << "Unable to parse version info from file" << remoteFile;
Don Gagne's avatar
Don Gagne committed
785
        sender()->deleteLater();
786 787 788 789 790
        return;
    }

    // In order to determine the firmware and vehicle type for this file we find the matching entry in the firmware list

791
    QHash<FirmwareIdentifier, QString>* prgFirmware = _firmwareHashForBoardId(static_cast<int>(_bootloaderBoardID));
792 793

    QString remotePath = QFileInfo(remoteFile).path();
794
    for (FirmwareIdentifier firmwareId: prgFirmware->keys()) {
795 796 797 798 799 800 801
        if (remotePath == QFileInfo((*prgFirmware)[firmwareId]).path()) {
            qCDebug(FirmwareUpgradeLog) << "Adding version to map, version:firwmareType:vehicleType" << version << firmwareId.firmwareType << firmwareId.firmwareVehicleType;
            _apmVersionMap[firmwareId.firmwareType][firmwareId.firmwareVehicleType] = version;
        }
    }

    emit apmAvailableVersionsChanged();
Don Gagne's avatar
Don Gagne committed
802
    sender()->deleteLater();
803 804 805 806 807 808 809 810 811 812 813
}

void FirmwareUpgradeController::setSelectedFirmwareType(FirmwareType_t firmwareType)
{
    _selectedFirmwareType = firmwareType;
    emit selectedFirmwareTypeChanged(_selectedFirmwareType);
    emit apmAvailableVersionsChanged();
}

QStringList FirmwareUpgradeController::apmAvailableVersions(void)
{
814 815 816
    QStringList                     list;
    QList<FirmwareVehicleType_t>    vehicleTypes;

817 818
    // This allows us to force the order of the combo box display
    vehicleTypes << CopterChibiOSFirmware << HeliChibiOSFirmware << PlaneChibiOSFirmware << RoverChibiOSFirmware << SubChibiOSFirmware << CopterFirmware << HeliFirmware << PlaneFirmware << RoverFirmware << SubFirmware;
819 820 821

    _apmVehicleTypeFromCurrentVersionList.clear();

822
    for (FirmwareVehicleType_t vehicleType: vehicleTypes) {
823 824 825 826
        if (_apmVersionMap[_selectedFirmwareType].contains(vehicleType)) {
            QString version;

            switch (vehicleType) {
Don Gagne's avatar
Don Gagne committed
827
            case CopterFirmware:
828
                version = tr("NuttX - MultiRotor:");
829 830
                break;
            case HeliFirmware:
831
                version = tr("NuttX - Heli:");
832
                break;
Don Gagne's avatar
Don Gagne committed
833
            case CopterChibiOSFirmware:
834
                version = tr("ChibiOS- MultiRotor:");
Don Gagne's avatar
Don Gagne committed
835 836
                break;
            case HeliChibiOSFirmware:
837
                version = tr("ChibiOS - Heli:");
838
                break;
Don Gagne's avatar
Don Gagne committed
839 840 841 842
            case PlaneChibiOSFirmware:
            case RoverChibiOSFirmware:
            case SubChibiOSFirmware:
                version = tr("ChibiOS - ");
843
                break;
Don Gagne's avatar
Don Gagne committed
844
            default:
845
                version = tr("NuttX - ");
846 847 848 849 850 851 852
                break;
            }

            version += _apmVersionMap[_selectedFirmwareType][vehicleType];
            _apmVehicleTypeFromCurrentVersionList.append(vehicleType);

            list << version;
853 854 855 856 857 858 859 860 861 862
        }
    }

    return list;
}

FirmwareUpgradeController::FirmwareVehicleType_t FirmwareUpgradeController::vehicleTypeFromVersionIndex(int index)
{
    if (index < 0 || index >= _apmVehicleTypeFromCurrentVersionList.count()) {
        qWarning() << "Invalid index, index:count" << index << _apmVehicleTypeFromCurrentVersionList.count();
Don Gagne's avatar
Don Gagne committed
863
        return CopterFirmware;
864 865 866 867
    }

    return _apmVehicleTypeFromCurrentVersionList[index];
}
Don Gagne's avatar
Don Gagne committed
868 869 870 871

void FirmwareUpgradeController::_determinePX4StableVersion(void)
{
    QGCFileDownload* downloader = new QGCFileDownload(this);
872 873 874
    connect(downloader, &QGCFileDownload::downloadFinished, this, &FirmwareUpgradeController::_px4ReleasesGithubDownloadFinished);
    connect(downloader, &QGCFileDownload::error, this, &FirmwareUpgradeController::_px4ReleasesGithubDownloadError);
    downloader->download(QStringLiteral("https://api.github.com/repos/PX4/Firmware/releases"));
Don Gagne's avatar
Don Gagne committed
875 876
}

877
void FirmwareUpgradeController::_px4ReleasesGithubDownloadFinished(QString remoteFile, QString localFile)
Don Gagne's avatar
Don Gagne committed
878 879 880 881 882
{
    Q_UNUSED(remoteFile);

    QFile jsonFile(localFile);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
883
        qCWarning(FirmwareUpgradeLog) << "Unable to open github px4 releases json file" << localFile << jsonFile.errorString();
Don Gagne's avatar
Don Gagne committed
884 885 886 887 888 889 890 891
        return;
    }
    QByteArray bytes = jsonFile.readAll();
    jsonFile.close();

    QJsonParseError jsonParseError;
    QJsonDocument doc = QJsonDocument::fromJson(bytes, &jsonParseError);
    if (jsonParseError.error != QJsonParseError::NoError) {
892
        qCWarning(FirmwareUpgradeLog) <<  "Unable to open px4 releases json document" << localFile << jsonParseError.errorString();
Don Gagne's avatar
Don Gagne committed
893 894 895
        return;
    }

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
    // Json should be an array of release objects
    if (!doc.isArray()) {
        qCWarning(FirmwareUpgradeLog) <<  "px4 releases json document is not an array" << localFile;
        return;
    }
    QJsonArray releases = doc.array();

    // The first release marked prerelease=false is stable
    // The first release marked prerelease=true is beta
    bool foundStable = false;
    bool foundBeta = false;
    for (int i=0; i<releases.count() && (!foundStable || !foundBeta); i++) {
        QJsonObject release = releases[i].toObject();
        if (!foundStable && !release["prerelease"].toBool()) {
            _px4StableVersion = release["name"].toString();
            emit px4StableVersionChanged(_px4StableVersion);
            qCDebug(FirmwareUpgradeLog()) << "Found px4 stable version" << _px4StableVersion;
            foundStable = true;
        } else if (!foundBeta && release["prerelease"].toBool()) {
            _px4BetaVersion = release["name"].toString();
            emit px4StableVersionChanged(_px4BetaVersion);
            qCDebug(FirmwareUpgradeLog()) << "Found px4 beta version" << _px4BetaVersion;
            foundBeta = true;
        }
    }

    if (!foundStable) {
        qCDebug(FirmwareUpgradeLog()) << "Unable to find px4 stable version" << localFile;
    }
    if (!foundBeta) {
        qCDebug(FirmwareUpgradeLog()) << "Unable to find px4 beta version" << localFile;
    }
Don Gagne's avatar
Don Gagne committed
928 929
}

930
void FirmwareUpgradeController::_px4ReleasesGithubDownloadError(QString errorMsg)
Don Gagne's avatar
Don Gagne committed
931
{
932
    qCWarning(FirmwareUpgradeLog) << "PX4 releases github download failed" << errorMsg;
Don Gagne's avatar
Don Gagne committed
933
}