FirmwareUpgradeController.cc 42.5 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
    : _singleFirmwareURL(qgcApp()->toolbox()->corePlugin()->options()->firmwareUpgradeSingleURL())
    , _singleFirmwareMode(!_singleFirmwareURL.isEmpty())
48 49 50
    , _downloadManager(nullptr)
    , _downloadNetworkReply(nullptr)
    , _statusLog(nullptr)
51
    , _selectedFirmwareType(StableFirmware)
52
    , _image(nullptr)
53 54 55 56
{
    _threadController = new PX4FirmwareUpgradeThreadController(this);
    Q_CHECK_PTR(_threadController);

57 58 59 60 61 62 63 64 65 66 67 68 69
    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);
    
70
    connect(&_eraseTimer, &QTimer::timeout, this, &FirmwareUpgradeController::_eraseProgressTick);
71 72

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

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

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

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

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

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

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

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

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

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

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

136
    if (_foundBoardType == QGCSerialPortInfo::BoardTypeSiKRadio) {
137 138 139 140 141 142 143 144
        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);
        }
145
    }
146
    
147
    qCDebug(FirmwareUpgradeLog) << _foundBoardType << _foundBoardTypeName;
148
    emit boardFound();
149 150
}

151 152

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

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

/// @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)
{
166
    _bootloaderFound = true;
167 168 169
    _bootloaderVersion = static_cast<uint32_t>(bootloaderVersion);
    _bootloaderBoardID = static_cast<uint32_t>(boardID);
    _bootloaderBoardFlashSize = static_cast<uint32_t>(flashSize);
170
    
171 172 173 174
    _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));
175
    
176
    if (_startFlashWhenBootloaderFound) {
177
        flash(_startFlashWhenBootloaderFoundFirmwareIdentity);
178
    }
179 180

    _loadAPMVersions(_bootloaderBoardID);
181 182 183
}


Pritam Ghanghas's avatar
Pritam Ghanghas committed
184 185 186
/// @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()
187
{
Pritam Ghanghas's avatar
Pritam Ghanghas committed
188 189 190 191 192
    // indirect check whether this function has been called before or not
    // may have to be modified if _rgPX4FMUV2Firmware disappears
    if (!_rgPX4FMUV2Firmware.isEmpty()) {
        return;
    }
193

Pritam Ghanghas's avatar
Pritam Ghanghas committed
194 195 196 197 198
    //////////////////////////////////// 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"},
199
    #if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
200
        { AutoPilotStackAPM, BetaFirmware,      CopterFirmware,         "http://firmware.ardupilot.org/Copter/beta/PX4/ArduCopter-v2.px4"},
Pritam Ghanghas's avatar
Pritam Ghanghas committed
201 202 203
        { 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"},
204 205 206
        { 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
207
        { AutoPilotStackAPM, DeveloperFirmware, CopterFirmware,         "http://gumstix-aerocore.s3.amazonaws.com/Copter/latest/PX4/ArduCopter-v2.px4"},
Pritam Ghanghas's avatar
Pritam Ghanghas committed
208 209 210
        { 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"}
211
    #endif
Pritam Ghanghas's avatar
Pritam Ghanghas committed
212
    };
213

214 215 216 217 218
    //////////////////////////////////// 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"},
219
    #if !defined(NO_ARDUPILOT_DIALECT)
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        { 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"}
235
    #endif
236
    };
Henry Zhang's avatar
Henry Zhang committed
237 238 239 240 241 242
    //////////////////////////////////// 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"},
    };
243 244 245 246 247
    //////////////////////////////////// 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"},
248
        { SingleFirmwareMode,StableFirmware,    DefaultVehicleFirmware, _singleFirmwareURL},
249 250 251 252 253 254 255
    };
    //////////////////////////////////// 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"},
    };
256 257 258 259 260 261 262 263

    //////////////////////////////////// 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"},
    };

Pritam Ghanghas's avatar
Pritam Ghanghas committed
264 265
    /////////////////////////////// px4flow firmwares ///////////////////////////////////////
    FirmwareToUrlElement_t rgPX4FLowFirmwareArray[] = {
266
        { PX4FlowPX4, StableFirmware, DefaultVehicleFirmware, "http://px4-travis.s3.amazonaws.com/Flow/master/px4flow.px4" },
267
    #if !defined(NO_ARDUPILOT_DIALECT)
DonLakeFlyer's avatar
DonLakeFlyer committed
268
        { PX4FlowAPM, StableFirmware, DefaultVehicleFirmware, "http://firmware.ardupilot.org/Tools/PX4Flow/px4flow-klt-latest.px4" },
269
    #endif
Pritam Ghanghas's avatar
Pritam Ghanghas committed
270 271 272 273
    };

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

Don Gagne's avatar
Don Gagne committed
277 278 279 280 281 282 283 284 285 286
    // 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
287
    QString apmUrl          ("http://firmware.ardupilot.org/%1/%2/%3/%4-v%5.px4");
Don Gagne's avatar
Don Gagne committed
288 289 290
    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
291 292 293
    px4MapFirmwareTypeToDir[StableFirmware] =       QStringLiteral("stable");
    px4MapFirmwareTypeToDir[BetaFirmware] =         QStringLiteral("beta");
    px4MapFirmwareTypeToDir[DeveloperFirmware] =    QStringLiteral("master");
Don Gagne's avatar
Don Gagne committed
294

295
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
296
    QMap<FirmwareVehicleType_t, QString> apmMapVehicleTypeToDir;
Don Gagne's avatar
Don Gagne committed
297 298 299 300 301
    apmMapVehicleTypeToDir[CopterFirmware] =    QStringLiteral("Copter");
    apmMapVehicleTypeToDir[HeliFirmware] =      QStringLiteral("Copter");
    apmMapVehicleTypeToDir[PlaneFirmware] =     QStringLiteral("Plane");
    apmMapVehicleTypeToDir[RoverFirmware] =     QStringLiteral("Rover");
    apmMapVehicleTypeToDir[SubFirmware] =       QStringLiteral("Sub");
302
#endif
Don Gagne's avatar
Don Gagne committed
303

304
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
305 306 307 308 309 310
    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");
311
#endif
Don Gagne's avatar
Don Gagne committed
312

313
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
314
    QMap<FirmwareType_t, QString> apmMapFirmwareTypeToDir;
Don Gagne's avatar
Don Gagne committed
315 316 317
    apmMapFirmwareTypeToDir[StableFirmware] =       QStringLiteral("stable");
    apmMapFirmwareTypeToDir[BetaFirmware] =         QStringLiteral("beta");
    apmMapFirmwareTypeToDir[DeveloperFirmware] =    QStringLiteral("latest");
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<FirmwareVehicleType_t, QString> apmMapVehicleTypeToPX4Dir;
Don Gagne's avatar
Don Gagne committed
322 323 324 325 326
    apmMapVehicleTypeToPX4Dir[CopterFirmware] = QStringLiteral("PX4");
    apmMapVehicleTypeToPX4Dir[HeliFirmware] =   QStringLiteral("PX4-heli");
    apmMapVehicleTypeToPX4Dir[PlaneFirmware] =  QStringLiteral("PX4");
    apmMapVehicleTypeToPX4Dir[RoverFirmware] =  QStringLiteral("PX4");
    apmMapVehicleTypeToPX4Dir[SubFirmware] =    QStringLiteral("PX4");
327
#endif
Don Gagne's avatar
Don Gagne committed
328

329
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
330
    QMap<FirmwareVehicleType_t, QString> apmMapVehicleTypeToFilename;
Don Gagne's avatar
Don Gagne committed
331
    apmMapVehicleTypeToFilename[CopterFirmware] =   QStringLiteral("ArduCopter");
Don Gagne's avatar
Don Gagne committed
332
    apmMapVehicleTypeToFilename[HeliFirmware] =     QStringLiteral("ArduCopter");
Don Gagne's avatar
Don Gagne committed
333 334 335
    apmMapVehicleTypeToFilename[PlaneFirmware] =    QStringLiteral("ArduPlane");
    apmMapVehicleTypeToFilename[RoverFirmware] =    QStringLiteral("APMrover2");
    apmMapVehicleTypeToFilename[SubFirmware] =      QStringLiteral("ArduSub");
336
#endif
Don Gagne's avatar
Don Gagne committed
337

338
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
339
    QMap<FirmwareVehicleType_t, QString> apmChibiOSMapVehicleTypeToFmuDir;
Don Gagne's avatar
Don Gagne committed
340 341 342 343 344
    apmChibiOSMapVehicleTypeToFmuDir[CopterChibiOSFirmware] =   QString();
    apmChibiOSMapVehicleTypeToFmuDir[HeliChibiOSFirmware] =     QStringLiteral("-heli");
    apmChibiOSMapVehicleTypeToFmuDir[PlaneChibiOSFirmware] =    QString();
    apmChibiOSMapVehicleTypeToFmuDir[RoverChibiOSFirmware] =    QString();
    apmChibiOSMapVehicleTypeToFmuDir[SubChibiOSFirmware] =      QString();
345
#endif
Don Gagne's avatar
Don Gagne committed
346

347
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
348
    QMap<FirmwareVehicleType_t, QString> apmChibiOSMapVehicleTypeToFilename;
Don Gagne's avatar
Don Gagne committed
349
    apmChibiOSMapVehicleTypeToFilename[CopterChibiOSFirmware] = QStringLiteral("arducopter");
Don Gagne's avatar
Don Gagne committed
350
    apmChibiOSMapVehicleTypeToFilename[HeliChibiOSFirmware] =   QStringLiteral("arducopter-heli");
Don Gagne's avatar
Don Gagne committed
351 352 353
    apmChibiOSMapVehicleTypeToFilename[PlaneChibiOSFirmware] =  QStringLiteral("arduplane");
    apmChibiOSMapVehicleTypeToFilename[RoverChibiOSFirmware] =  QStringLiteral("ardurover");
    apmChibiOSMapVehicleTypeToFilename[SubChibiOSFirmware] =    QStringLiteral("ardusub");
354
#endif
Don Gagne's avatar
Don Gagne committed
355 356

    // PX4 Firmwares
357
    for (const FirmwareType_t& firmwareType: px4MapFirmwareTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
358 359 360 361 362 363 364 365
        QString dir = px4MapFirmwareTypeToDir[firmwareType];
        _rgPX4FMUV5Firmware.insert      (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v5"));
        _rgPX4FMUV4PROFirmware.insert   (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v4pro"));
        _rgPX4FMUV4Firmware.insert      (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v4"));
        _rgPX4FMUV3Firmware.insert      (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v3"));
        _rgPX4FMUV2Firmware.insert      (FirmwareIdentifier(AutoPilotStackPX4, firmwareType, DefaultVehicleFirmware), px4Url.arg(dir).arg("v2"));
    }

366
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
367
    // ArduPilot Firmwares
368
    for (const FirmwareType_t& firmwareType: apmMapFirmwareTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
369
        QString firmwareTypeDir = apmMapFirmwareTypeToDir[firmwareType];
370
        for (const FirmwareVehicleType_t& vehicleType: apmMapVehicleTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
371 372 373 374 375 376 377 378
            QString vehicleTypeDir = apmMapVehicleTypeToDir[vehicleType];
            QString px4Dir = apmMapVehicleTypeToPX4Dir[vehicleType];
            QString filename = apmMapVehicleTypeToFilename[vehicleType];
            _rgPX4FMUV5Firmware.insert  (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(px4Dir).arg(filename).arg("5"));
            _rgPX4FMUV4Firmware.insert  (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(px4Dir).arg(filename).arg("4"));
            _rgPX4FMUV3Firmware.insert  (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(px4Dir).arg(filename).arg("3"));
            _rgPX4FMUV2Firmware.insert  (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg(px4Dir).arg(filename).arg("2"));
        }
DonLakeFlyer's avatar
DonLakeFlyer committed
379
    }
380
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
381

382
#if !defined(NO_ARDUPILOT_DIALECT)
Don Gagne's avatar
Don Gagne committed
383
    // ArduPilot ChibiOS Firmwares
384
    for (const FirmwareType_t& firmwareType: apmMapFirmwareTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
385
        QString firmwareTypeDir = apmMapFirmwareTypeToDir[firmwareType];
386
        for (const FirmwareVehicleType_t& vehicleType: apmChibiOSMapVehicleTypeToDir.keys()) {
Don Gagne's avatar
Don Gagne committed
387 388 389 390 391 392 393 394
            QString vehicleTypeDir = apmChibiOSMapVehicleTypeToDir[vehicleType];
            QString fmuDir = apmChibiOSMapVehicleTypeToFmuDir[vehicleType];
            QString filename = apmChibiOSMapVehicleTypeToFilename[vehicleType];
            _rgPX4FMUV5Firmware.insert      (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmChibiOSUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg("5").arg(fmuDir).arg(filename));
            _rgPX4FMUV4Firmware.insert      (FirmwareIdentifier(AutoPilotStackAPM, firmwareType, vehicleType), apmChibiOSUrl.arg(vehicleTypeDir).arg(firmwareTypeDir).arg("4").arg(fmuDir).arg(filename));
            _rgPX4FMUV3Firmware.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));
        }
Pritam Ghanghas's avatar
Pritam Ghanghas committed
395
    }
396
#endif
397

Don Gagne's avatar
Don Gagne committed
398
    int size = sizeof(rgAeroCoreFirmwareArray)/sizeof(rgAeroCoreFirmwareArray[0]);
Pritam Ghanghas's avatar
Pritam Ghanghas committed
399 400 401 402
    for (int i = 0; i < size; i++) {
        const FirmwareToUrlElement_t& element = rgAeroCoreFirmwareArray[i];
        _rgAeroCoreFirmware.insert(FirmwareIdentifier(element.stackType, element.firmwareType, element.vehicleType), element.url);
    }
403

404 405 406 407 408 409
    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
410 411 412 413 414 415
    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);
    }

416 417 418 419 420 421 422 423 424 425 426 427
    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);
    }

428 429 430 431 432 433
    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);
    }

Pritam Ghanghas's avatar
Pritam Ghanghas committed
434 435 436 437 438
    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);
    }
439

Pritam Ghanghas's avatar
Pritam Ghanghas committed
440 441 442 443 444
    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);
    }
445 446 447 448 449 450

    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
451
}
452

Pritam Ghanghas's avatar
Pritam Ghanghas committed
453 454 455 456 457 458
/// @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.");
}
459

460
QHash<FirmwareUpgradeController::FirmwareIdentifier, QString>* FirmwareUpgradeController::_firmwareHashForBoardId(int boardId)
Pritam Ghanghas's avatar
Pritam Ghanghas committed
461
{
462 463 464 465 466
    switch (boardId) {
    case Bootloader::boardIDPX4Flow:
        return &_rgPX4FLowFirmware;
    case Bootloader::boardIDPX4FMUV2:
        return &_rgPX4FMUV2Firmware;
DonLakeFlyer's avatar
DonLakeFlyer committed
467 468
    case Bootloader::boardIDPX4FMUV3:
        return &_rgPX4FMUV3Firmware;
469 470
    case Bootloader::boardIDPX4FMUV4:
        return &_rgPX4FMUV4Firmware;
471 472 473 474
    case Bootloader::boardIDPX4FMUV4PRO:
        return &_rgPX4FMUV4PROFirmware;
    case Bootloader::boardIDPX4FMUV5:
        return &_rgPX4FMUV5Firmware;
475 476
    case Bootloader::boardIDAeroCore:
        return &_rgAeroCoreFirmware;
477 478
    case Bootloader::boardIDAUAVX2_1:
        return &_rgAUAVX2_1Firmware;
Henry Zhang's avatar
Henry Zhang committed
479 480
    case Bootloader::boardIDMINDPXFMUV2:
        return &_rgMindPXFMUV2Firmware;
481 482 483 484
    case Bootloader::boardIDTAPV1:
        return &_rgTAPV1Firmware;
    case Bootloader::boardIDASCV1:
        return &_rgASCV1Firmware;
485 486
    case Bootloader::boardIDCrazyflie2:
        return &_rgCrazyflie2Firmware;
487 488
    case Bootloader::boardIDNXPHliteV3:
        return &_rgNXPHliteV3Firmware;
489 490 491
    case Bootloader::boardID3DRRadio:
        return &_rg3DRRadioFirmware;
    default:
492
        return nullptr;
493 494
    }
}
Lorenz Meier's avatar
Lorenz Meier committed
495

496 497 498
/// @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)
{
499
    QHash<FirmwareIdentifier, QString>* prgFirmware = _firmwareHashForBoardId(static_cast<int>(_bootloaderBoardID));
500
    
501
    if (!prgFirmware && firmwareId.firmwareType != CustomFirmware) {
502
        _errorCancel(tr("Attempting to flash an unknown board type, you must select 'Custom firmware file'"));
503
        return;
504 505
    }
    
506
    if (firmwareId.firmwareType == CustomFirmware) {
507 508 509
        _firmwareFilename = QGCQFileDialog::getOpenFileName(nullptr,                                                                // Parent to main window
                                                            tr("Select Firmware File"),                                             // Dialog Caption
                                                            QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),    // Initial directory
510
                                                            tr("Firmware Files (*.px4 *.bin *.ihx)"));                              // File filter
511
    } else {
512 513
        if (prgFirmware->contains(firmwareId)) {
            _firmwareFilename = prgFirmware->value(firmwareId);
514
        } else {
515
            _errorCancel(tr("Unable to find specified firmware download location"));
516 517
            return;
        }
518 519 520
    }
    
    if (_firmwareFilename.isEmpty()) {
521
        _errorCancel(tr("No firmware file selected"));
522 523 524 525 526 527 528 529 530 531
    } else {
        _downloadFirmware();
    }
}

/// @brief Begins the process of downloading the selected firmware file.
void FirmwareUpgradeController::_downloadFirmware(void)
{
    Q_ASSERT(!_firmwareFilename.isEmpty());
    
532 533
    _appendStatusLog(tr("Downloading firmware..."));
    _appendStatusLog(tr(" From: %1").arg(_firmwareFilename));
534
    
535 536 537 538 539
    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);
540 541 542
}

/// @brief Updates the progress indicator while downloading
543
void FirmwareUpgradeController::_firmwareDownloadProgress(qint64 curr, qint64 total)
544 545 546
{
    // Take care of cases where 0 / 0 is emitted as error return value
    if (total > 0) {
547
        _progressBar->setProperty("value", static_cast<float>(curr) / static_cast<float>(total));
548 549 550 551
    }
}

/// @brief Called when the firmware download completes.
552
void FirmwareUpgradeController::_firmwareDownloadFinished(QString remoteFile, QString localFile)
553
{
554 555
    Q_UNUSED(remoteFile);

556
    _appendStatusLog(tr("Download complete"));
557
    
558
    FirmwareImage* image = new FirmwareImage(this);
559
    
560 561
    connect(image, &FirmwareImage::statusMessage, this, &FirmwareUpgradeController::_status);
    connect(image, &FirmwareImage::errorMessage, this, &FirmwareUpgradeController::_error);
562
    
563
    if (!image->load(localFile, _bootloaderBoardID)) {
564
        _errorCancel(tr("Image load failed"));
565
        return;
566 567
    }
    
568 569
    // We can't proceed unless we have the bootloader
    if (!_bootloaderFound) {
570
        _errorCancel(tr("Bootloader not found"));
571 572
        return;
    }
573
    
574
    if (_bootloaderBoardFlashSize != 0 && image->imageSize() > _bootloaderBoardFlashSize) {
575
        _errorCancel(tr("Image size of %1 is too large for board flash size %2").arg(image->imageSize()).arg(_bootloaderBoardFlashSize));
576
        return;
577
    }
578 579

    _threadController->flash(image);
580 581
}

582
/// @brief Called when an error occurs during download
583
void FirmwareUpgradeController::_firmwareDownloadError(QString errorMsg)
584
{
585
    _errorCancel(errorMsg);
586 587
}

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
/// @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";
    }
}

603 604 605
/// @brief Signals completion of one of the specified bootloader commands. Moves the state machine to the
///         appropriate next step.
void FirmwareUpgradeController::_flashComplete(void)
606
{
607
    delete _image;
608
    _image = nullptr;
609
    
610
    _appendStatusLog(tr("Upgrade complete"), true);
611 612
    _appendStatusLog("------------------------------------------", false);
    emit flashComplete();
613
    qgcApp()->toolbox()->linkManager()->setConnectionsAllowed();
614 615
}

616
void FirmwareUpgradeController::_error(const QString& errorString)
617
{
618
    delete _image;
619
    _image = nullptr;
620 621
    
    _errorCancel(QString("Error: %1").arg(errorString));
622 623
}

624
void FirmwareUpgradeController::_status(const QString& statusString)
625
{
626
    _appendStatusLog(statusString);
627 628 629 630 631
}

/// @brief Updates the progress bar from long running bootloader commands
void FirmwareUpgradeController::_updateProgress(int curr, int total)
{
632 633
    // Take care of cases where 0 / 0 is emitted as error return value
    if (total > 0) {
634
        _progressBar->setProperty("value", static_cast<float>(curr) / static_cast<float>(total));
635
    }
636 637 638 639 640 641
}

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

/// Appends the specified text to the status log area in the ui
646
void FirmwareUpgradeController::_appendStatusLog(const QString& text, bool critical)
647 648 649 650
{
    Q_ASSERT(_statusLog);
    
    QVariant returnedValue;
651 652 653 654 655 656 657 658
    QVariant varText;
    
    if (critical) {
        varText = QString("<font color=\"yellow\">%1</font>").arg(text);
    } else {
        varText = text;
    }
    
659 660 661 662
    QMetaObject::invokeMethod(_statusLog,
                              "append",
                              Q_RETURN_ARG(QVariant, returnedValue),
                              Q_ARG(QVariant, varText));
Don Gagne's avatar
Don Gagne committed
663
}
664

665 666 667
void FirmwareUpgradeController::_errorCancel(const QString& msg)
{
    _appendStatusLog(msg, false);
668
    _appendStatusLog(tr("Upgrade cancelled"), true);
669 670 671
    _appendStatusLog("------------------------------------------", false);
    emit error();
    cancel();
672
    qgcApp()->toolbox()->linkManager()->setConnectionsAllowed();
673 674 675 676 677 678 679 680 681 682
}

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)
683
{
684
    _eraseTimer.stop();
685
}
686

687
void FirmwareUpgradeController::_loadAPMVersions(uint32_t bootloaderBoardID)
688 689 690
{
    _apmVersionMap.clear();

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

693
    for (FirmwareIdentifier firmwareId: prgFirmware->keys()) {
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
        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
725
        sender()->deleteLater();
726 727 728 729 730
        return;
    }

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

731
    QHash<FirmwareIdentifier, QString>* prgFirmware = _firmwareHashForBoardId(static_cast<int>(_bootloaderBoardID));
732 733

    QString remotePath = QFileInfo(remoteFile).path();
734
    for (FirmwareIdentifier firmwareId: prgFirmware->keys()) {
735 736 737 738 739 740 741
        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
742
    sender()->deleteLater();
743 744 745 746 747 748 749 750 751 752 753
}

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

QStringList FirmwareUpgradeController::apmAvailableVersions(void)
{
754 755 756 757
    QStringList                     list;
    QList<FirmwareVehicleType_t>    vehicleTypes;

    // This allows up to force the order of the combo box display
Don Gagne's avatar
Don Gagne committed
758
    vehicleTypes << CopterFirmware << HeliFirmware << PlaneFirmware << RoverFirmware << SubFirmware << CopterChibiOSFirmware << HeliChibiOSFirmware << PlaneChibiOSFirmware << RoverChibiOSFirmware << SubChibiOSFirmware;
759 760 761

    _apmVehicleTypeFromCurrentVersionList.clear();

762
    for (FirmwareVehicleType_t vehicleType: vehicleTypes) {
763 764 765 766
        if (_apmVersionMap[_selectedFirmwareType].contains(vehicleType)) {
            QString version;

            switch (vehicleType) {
Don Gagne's avatar
Don Gagne committed
767 768
            case CopterFirmware:
                version = tr("MultiRotor - ");
769 770
                break;
            case HeliFirmware:
Don Gagne's avatar
Don Gagne committed
771
                version = tr("Heli - ");
772
                break;
Don Gagne's avatar
Don Gagne committed
773 774 775 776 777
            case CopterChibiOSFirmware:
                version = tr("ChibiOS:MultiRotor - ");
                break;
            case HeliChibiOSFirmware:
                version = tr("ChibiOS:Heli - ");
778
                break;
Don Gagne's avatar
Don Gagne committed
779 780 781 782
            case PlaneChibiOSFirmware:
            case RoverChibiOSFirmware:
            case SubChibiOSFirmware:
                version = tr("ChibiOS - ");
783
                break;
Don Gagne's avatar
Don Gagne committed
784
            default:
785 786 787 788 789 790 791
                break;
            }

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

            list << version;
792 793 794 795 796 797 798 799 800 801
        }
    }

    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
802
        return CopterFirmware;
803 804 805 806
    }

    return _apmVehicleTypeFromCurrentVersionList[index];
}
Don Gagne's avatar
Don Gagne committed
807 808 809 810

void FirmwareUpgradeController::_determinePX4StableVersion(void)
{
    QGCFileDownload* downloader = new QGCFileDownload(this);
811 812 813
    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
814 815
}

816
void FirmwareUpgradeController::_px4ReleasesGithubDownloadFinished(QString remoteFile, QString localFile)
Don Gagne's avatar
Don Gagne committed
817 818 819 820 821
{
    Q_UNUSED(remoteFile);

    QFile jsonFile(localFile);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
822
        qCWarning(FirmwareUpgradeLog) << "Unable to open github px4 releases json file" << localFile << jsonFile.errorString();
Don Gagne's avatar
Don Gagne committed
823 824 825 826 827 828 829 830
        return;
    }
    QByteArray bytes = jsonFile.readAll();
    jsonFile.close();

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

835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    // 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
867 868
}

869
void FirmwareUpgradeController::_px4ReleasesGithubDownloadError(QString errorMsg)
Don Gagne's avatar
Don Gagne committed
870
{
871
    qCWarning(FirmwareUpgradeLog) << "PX4 releases github download failed" << errorMsg;
Don Gagne's avatar
Don Gagne committed
872
}