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


11
#include "MissionCommandUIInfo.h"
12 13 14 15
#include "MissionController.h"
#include "MultiVehicleManager.h"
#include "MissionManager.h"
#include "CoordinateVector.h"
16
#include "FirmwarePlugin.h"
17
#include "QGCApplication.h"
18
#include "SimpleMissionItem.h"
19
#include "SurveyComplexItem.h"
20
#include "FixedWingLandingComplexItem.h"
21
#include "StructureScanComplexItem.h"
22
#include "CorridorScanComplexItem.h"
23
#include "JsonHelper.h"
24
#include "ParameterManager.h"
25
#include "QGroundControlQmlGlobal.h"
26
#include "SettingsManager.h"
27
#include "AppSettings.h"
28
#include "MissionSettingsItem.h"
29
#include "QGCQGeoCoordinate.h"
30
#include "PlanMasterController.h"
31
#include "KML.h"
32
#include "QGCCorePlugin.h"
33
#include "TakeoffMissionItem.h"
34
#include "PlanViewSettings.h"
35

36 37
#define UPDATE_TIMEOUT 5000 ///< How often we check for bounding box changes

38 39
QGC_LOGGING_CATEGORY(MissionControllerLog, "MissionControllerLog")

40
const char* MissionController::_settingsGroup =                 "MissionController";
Don Gagne's avatar
Don Gagne committed
41 42
const char* MissionController::_jsonFileTypeValue =             "Mission";
const char* MissionController::_jsonItemsKey =                  "items";
43
const char* MissionController::_jsonPlannedHomePositionKey =    "plannedHomePosition";
Don Gagne's avatar
Don Gagne committed
44
const char* MissionController::_jsonFirmwareTypeKey =           "firmwareType";
45 46 47
const char* MissionController::_jsonVehicleTypeKey =            "vehicleType";
const char* MissionController::_jsonCruiseSpeedKey =            "cruiseSpeed";
const char* MissionController::_jsonHoverSpeedKey =             "hoverSpeed";
Don Gagne's avatar
Don Gagne committed
48 49 50 51 52 53 54
const char* MissionController::_jsonParamsKey =                 "params";

// Deprecated V1 format keys
const char* MissionController::_jsonComplexItemsKey =           "complexItems";
const char* MissionController::_jsonMavAutopilotKey =           "MAV_AUTOPILOT";

const int   MissionController::_missionFileVersion =            2;
55

DonLakeFlyer's avatar
DonLakeFlyer committed
56 57 58 59
const QString MissionController::patternSurveyName          (QT_TRANSLATE_NOOP("MissionController", "Survey"));
const QString MissionController::patternFWLandingName       (QT_TRANSLATE_NOOP("MissionController", "Fixed Wing Landing"));
const QString MissionController::patternStructureScanName   (QT_TRANSLATE_NOOP("MissionController", "Structure Scan"));
const QString MissionController::patternCorridorScanName    (QT_TRANSLATE_NOOP("MissionController", "Corridor Scan"));
60

61
MissionController::MissionController(PlanMasterController* masterController, QObject *parent)
62
    : PlanElementController     (masterController, parent)
63
    , _planViewSettings         (qgcApp()->toolbox()->settingsManager()->planViewSettings())
64 65 66 67 68 69 70 71 72
    , _missionManager           (_managerVehicle->missionManager())
    , _missionItemCount         (0)
    , _visualItems              (nullptr)
    , _settingsItem             (nullptr)
    , _firstItemsFromVehicle    (false)
    , _itemsRequested           (false)
    , _inRecalcSequence         (false)
    , _appSettings              (qgcApp()->toolbox()->settingsManager()->appSettings())
    , _progressPct              (0)
73 74
    , _currentPlanViewSeqNum    (-1)
    , _currentPlanViewVIIndex   (-1)
75
    , _currentPlanViewItem      (nullptr)
76
    , _splitSegment             (nullptr)
77
{
78
    _resetMissionFlightStatus();
79
    managerVehicleChanged(_managerVehicle);
80 81
    _updateTimer.setSingleShot(true);
    connect(&_updateTimer, &QTimer::timeout, this, &MissionController::_updateTimeout);
82 83

    connect(_planViewSettings->takeoffItemNotRequired(), &Fact::rawValueChanged, this, &MissionController::_takeoffItemNotRequiredChanged);
84 85 86 87
}

MissionController::~MissionController()
{
Don Gagne's avatar
Don Gagne committed
88

89 90
}

91 92 93 94 95 96 97 98 99
void MissionController::_resetMissionFlightStatus(void)
{
    _missionFlightStatus.totalDistance =        0.0;
    _missionFlightStatus.maxTelemetryDistance = 0.0;
    _missionFlightStatus.totalTime =            0.0;
    _missionFlightStatus.hoverTime =            0.0;
    _missionFlightStatus.cruiseTime =           0.0;
    _missionFlightStatus.hoverDistance =        0.0;
    _missionFlightStatus.cruiseDistance =       0.0;
100 101 102
    _missionFlightStatus.cruiseSpeed =          _controllerVehicle->defaultCruiseSpeed();
    _missionFlightStatus.hoverSpeed =           _controllerVehicle->defaultHoverSpeed();
    _missionFlightStatus.vehicleSpeed =         _controllerVehicle->multiRotor() || _managerVehicle->vtol() ? _missionFlightStatus.hoverSpeed : _missionFlightStatus.cruiseSpeed;
103
    _missionFlightStatus.vehicleYaw =           0.0;
104
    _missionFlightStatus.gimbalYaw =            std::numeric_limits<double>::quiet_NaN();
105
    _missionFlightStatus.gimbalPitch =          std::numeric_limits<double>::quiet_NaN();
106 107 108 109 110 111 112 113 114 115 116 117

    // Battery information

    _missionFlightStatus.mAhBattery =           0;
    _missionFlightStatus.hoverAmps =            0;
    _missionFlightStatus.cruiseAmps =           0;
    _missionFlightStatus.ampMinutesAvailable =  0;
    _missionFlightStatus.hoverAmpsTotal =       0;
    _missionFlightStatus.cruiseAmpsTotal =      0;
    _missionFlightStatus.batteryChangePoint =   -1;
    _missionFlightStatus.batteriesRequired =    -1;

118 119 120
    _controllerVehicle->firmwarePlugin()->batteryConsumptionData(_controllerVehicle, _missionFlightStatus.mAhBattery, _missionFlightStatus.hoverAmps, _missionFlightStatus.cruiseAmps);
    if (_missionFlightStatus.mAhBattery != 0) {
        double batteryPercentRemainingAnnounce = qgcApp()->toolbox()->settingsManager()->appSettings()->batteryPercentRemainingAnnounce()->rawValue().toDouble();
121
        _missionFlightStatus.ampMinutesAvailable = static_cast<double>(_missionFlightStatus.mAhBattery) / 1000.0 * 60.0 * ((100.0 - batteryPercentRemainingAnnounce) / 100.0);
122
    }
123 124 125 126 127 128 129 130 131 132 133

    emit missionDistanceChanged(_missionFlightStatus.totalDistance);
    emit missionTimeChanged();
    emit missionHoverDistanceChanged(_missionFlightStatus.hoverDistance);
    emit missionCruiseDistanceChanged(_missionFlightStatus.cruiseDistance);
    emit missionHoverTimeChanged();
    emit missionCruiseTimeChanged();
    emit missionMaxTelemetryChanged(_missionFlightStatus.maxTelemetryDistance);
    emit batteryChangePointChanged(_missionFlightStatus.batteryChangePoint);
    emit batteriesRequiredChanged(_missionFlightStatus.batteriesRequired);

134 135
}

136
void MissionController::start(bool flyView)
137
{
138
    qCDebug(MissionControllerLog) << "start flyView" << flyView;
139

140
    PlanElementController::start(flyView);
141 142 143 144 145
    _init();
}

void MissionController::_init(void)
{
146
    // We start with an empty mission
147
    _visualItems = new QmlObjectListModel(this);
148
    _addMissionSettings(_visualItems);
149
    _initAllVisualItems();
150 151
}

152
// Called when new mission items have completed downloading from Vehicle
153
void MissionController::_newMissionItemsAvailableFromVehicle(bool removeAllRequested)
154
{
155
    qCDebug(MissionControllerLog) << "_newMissionItemsAvailableFromVehicle flyView:count" << _flyView << _missionManager->missionItems().count();
156

DonLakeFlyer's avatar
DonLakeFlyer committed
157
    // Fly view always reloads on _loadComplete
158 159 160 161
    // Plan view only reloads if:
    //  - Load was specifically requested
    //  - There is no current Plan
    if (_flyView || removeAllRequested || _itemsRequested || isEmpty()) {
162
        // Fly Mode (accept if):
Don Gagne's avatar
Don Gagne committed
163
        //      - Always accepts new items from the vehicle so Fly view is kept up to date
164
        // Edit Mode (accept if):
165 166
        //      - Remove all was requested from Fly view (clear mission on flight end)
        //      - A load from vehicle was manually requested
Don Gagne's avatar
Don Gagne committed
167
        //      - The initial automatic load from a vehicle completed and the current editor is empty
168

169 170 171
        _deinitAllVisualItems();
        _visualItems->deleteLater();
        _visualItems  = nullptr;
172
        _settingsItem = nullptr;
173 174
        _updateContainsItems(); // This will clear containsItems which will be set again below. This will re-pop Start Mission confirmation.

175
        QmlObjectListModel* newControllerMissionItems = new QmlObjectListModel(this);
176
        const QList<MissionItem*>& newMissionItems = _missionManager->missionItems();
177 178
        qCDebug(MissionControllerLog) << "loading from vehicle: count"<< newMissionItems.count();

179 180 181
        _missionItemCount = newMissionItems.count();
        emit missionItemCountChanged(_missionItemCount);

182
        MissionSettingsItem* settingsItem = _addMissionSettings(newControllerMissionItems);
183 184

        int i=0;
185
        if (_controllerVehicle->firmwarePlugin()->sendHomePositionToVehicle() && newMissionItems.count() != 0) {
186
            // First item is fake home position
187 188
            MissionItem* fakeHomeItem = newMissionItems[0];
            if (fakeHomeItem->coordinate().latitude() != 0 || fakeHomeItem->coordinate().longitude() != 0) {
189
                settingsItem->setInitialHomePosition(fakeHomeItem->coordinate());
190
            }
191 192
            i = 1;
        }
193

194
        for (; i < newMissionItems.count(); i++) {
195
            const MissionItem* missionItem = newMissionItems[i];
196 197 198
            SimpleMissionItem* simpleItem = new SimpleMissionItem(_controllerVehicle, _flyView, *missionItem, this);
            if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(simpleItem->command()))) {
                // This needs to be a TakeoffMissionItem
199
                TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(*missionItem, _controllerVehicle, _flyView, settingsItem, this);
200 201 202 203
                simpleItem->deleteLater();
                simpleItem = takeoffItem;
            }
            newControllerMissionItems->append(simpleItem);
204 205 206
        }

        _visualItems = newControllerMissionItems;
207
        _settingsItem = settingsItem;
208

209
        MissionController::_scanForAdditionalSettings(_visualItems, _controllerVehicle);
210

211
        _initAllVisualItems();
212
        _updateContainsItems();
213
        emit newItemsFromVehicle();
214
    }
DonLakeFlyer's avatar
DonLakeFlyer committed
215
    _itemsRequested = false;
216 217
}

218
void MissionController::loadFromVehicle(void)
219
{
DonLakeFlyer's avatar
DonLakeFlyer committed
220 221 222 223 224 225 226 227
    if (_masterController->offline()) {
        qCWarning(MissionControllerLog) << "MissionControllerLog::loadFromVehicle called while offline";
    } else if (syncInProgress()) {
        qCWarning(MissionControllerLog) << "MissionControllerLog::loadFromVehicle called while syncInProgress";
    } else {
        _itemsRequested = true;
        _managerVehicle->missionManager()->loadFromVehicle();
    }
228 229
}

230 231 232 233
void MissionController::_warnIfTerrainFrameUsed(void)
{
    for (int i=1; i<_visualItems->count(); i++) {
        SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(_visualItems->get(i));
234
        if (simpleItem && simpleItem->altitudeMode() == QGroundControlQmlGlobal::AltitudeModeTerrainFrame) {
235 236 237 238 239 240
            qgcApp()->showMessage(tr("Warning: You are using MAV_FRAME_GLOBAL_TERRAIN_ALT in a mission. %1 does not support sending terrain tiles to vehicle.").arg(qgcApp()->applicationName()));
            break;
        }
    }
}

241
void MissionController::sendToVehicle(void)
242
{
DonLakeFlyer's avatar
DonLakeFlyer committed
243 244 245 246 247
    if (_masterController->offline()) {
        qCWarning(MissionControllerLog) << "MissionControllerLog::sendToVehicle called while offline";
    } else if (syncInProgress()) {
        qCWarning(MissionControllerLog) << "MissionControllerLog::sendToVehicle called while syncInProgress";
    } else {
DonLakeFlyer's avatar
DonLakeFlyer committed
248
        qCDebug(MissionControllerLog) << "MissionControllerLog::sendToVehicle";
249
        _warnIfTerrainFrameUsed();
DonLakeFlyer's avatar
DonLakeFlyer committed
250 251 252 253 254 255 256 257 258
        if (_visualItems->count() == 1) {
            // This prevents us from sending a possibly bogus home position to the vehicle
            QmlObjectListModel emptyModel;
            sendItemsToVehicle(_managerVehicle, &emptyModel);
        } else {
            sendItemsToVehicle(_managerVehicle, _visualItems);
        }
        setDirty(false);
    }
Don Gagne's avatar
Don Gagne committed
259 260
}

261 262 263 264 265
/// Converts from visual items to MissionItems
///     @param missionItemParent QObject parent for newly allocated MissionItems
/// @return true: Mission end action was added to end of list
bool MissionController::_convertToMissionItems(QmlObjectListModel* visualMissionItems, QList<MissionItem*>& rgMissionItems, QObject* missionItemParent)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
266 267 268 269
    if (visualMissionItems->count() == 0) {
        return false;
    }

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    bool endActionSet = false;
    int lastSeqNum = 0;

    for (int i=0; i<visualMissionItems->count(); i++) {
        VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(visualMissionItems->get(i));

        lastSeqNum = visualItem->lastSequenceNumber();
        visualItem->appendMissionItems(rgMissionItems, missionItemParent);

        qCDebug(MissionControllerLog) << "_convertToMissionItems seqNum:lastSeqNum:command"
                                      << visualItem->sequenceNumber()
                                      << lastSeqNum
                                      << visualItem->commandName();
    }

    // Mission settings has a special case for end mission action
286
    MissionSettingsItem* settingsItem = visualMissionItems->value<MissionSettingsItem*>(0);
287 288 289 290 291 292 293
    if (settingsItem) {
        endActionSet = settingsItem->addMissionEndAction(rgMissionItems, lastSeqNum + 1, missionItemParent);
    }

    return endActionSet;
}

294 295
void MissionController::convertToKMLDocument(QDomDocument& document)
{
296 297
    QObject*            deleteParent = new QObject();
    QList<MissionItem*> rgMissionItems;
298

299 300
    _convertToMissionItems(_visualItems, rgMissionItems, deleteParent);
    if (rgMissionItems.count() == 0) {
301 302
        return;
    }
303

304
    const double homePositionAltitude = _settingsItem->coordinate().altitude();
305 306 307 308 309

    QString coord;
    QStringList coords;
    // Drop home position
    bool dropPoint = true;
310
    for(const auto& item : rgMissionItems) {
311 312 313 314 315
        if(dropPoint) {
            dropPoint = false;
            continue;
        }
        const MissionCommandUIInfo* uiInfo = \
316
                qgcApp()->toolbox()->missionCommandTree()->getUIInfo(_controllerVehicle, item->command());
317 318

        if (uiInfo && uiInfo->specifiesCoordinate() && !uiInfo->isStandaloneCoordinate()) {
319
            double amslAltitude = item->param7() + (item->frame() == MAV_FRAME_GLOBAL ? 0 : homePositionAltitude);
yaoling's avatar
yaoling committed
320
            coord = QString::number(item->param6(),'f',7) \
321 322 323
                    + "," \
                    + QString::number(item->param5(),'f',7) \
                    + "," \
324
                    + QString::number(amslAltitude,'f',2);
325 326 327
            coords.append(coord);
        }
    }
328 329 330

    deleteParent->deleteLater();

331 332 333 334 335
    Kml kml;
    kml.points(coords);
    kml.save(document);
}

Don Gagne's avatar
Don Gagne committed
336 337 338
void MissionController::sendItemsToVehicle(Vehicle* vehicle, QmlObjectListModel* visualMissionItems)
{
    if (vehicle) {
339
        QList<MissionItem*> rgMissionItems;
340

341
        _convertToMissionItems(visualMissionItems, rgMissionItems, vehicle);
342

343
        // PlanManager takes control of MissionItems so no need to delete
344
        vehicle->missionManager()->writeMissionItems(rgMissionItems);
345 346
    }
}
347

348 349 350 351 352 353
int MissionController::_nextSequenceNumber(void)
{
    if (_visualItems->count() == 0) {
        qWarning() << "Internal error: Empty visual item list";
        return 0;
    } else {
354 355
        VisualMissionItem* lastItem = _visualItems->value<VisualMissionItem*>(_visualItems->count() - 1);
        return lastItem->lastSequenceNumber() + 1;
356 357 358
    }
}

359
VisualMissionItem* MissionController::_insertSimpleMissionItemWorker(QGeoCoordinate coordinate, MAV_CMD command, int visualItemIndex, bool makeCurrentItem)
360
{
361
    int sequenceNumber = _nextSequenceNumber();
362
    SimpleMissionItem * newItem = new SimpleMissionItem(_controllerVehicle, _flyView, this);
363
    newItem->setSequenceNumber(sequenceNumber);
364
    newItem->setCoordinate(coordinate);
365
    newItem->setCommand(command);
366
    _initVisualItem(newItem);
367 368 369 370 371 372 373 374

    if (newItem->specifiesAltitude()) {
        double  prevAltitude;
        int     prevAltitudeMode;

        if (_findPreviousAltitude(visualItemIndex, &prevAltitude, &prevAltitudeMode)) {
            newItem->altitude()->setRawValue(prevAltitude);
            newItem->setAltitudeMode(static_cast<QGroundControlQmlGlobal::AltitudeMode>(prevAltitudeMode));
375
        }
376
    }
377 378 379 380 381 382 383 384
    newItem->setMissionFlightStatus(_missionFlightStatus);
    if (visualItemIndex == -1) {
        _visualItems->append(newItem);
    } else {
        _visualItems->insert(visualItemIndex, newItem);
    }

    // We send the click coordinate through here to be able to set the planned home position from the user click location if needed
385
    _recalcAllWithCoordinate(coordinate);
386 387

    if (makeCurrentItem) {
388
        setCurrentPlanViewSeqNum(newItem->sequenceNumber(), true);
389 390 391 392 393
    }

    return newItem;
}

394 395 396 397 398 399

VisualMissionItem* MissionController::insertSimpleMissionItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem)
{
    return _insertSimpleMissionItemWorker(coordinate, MAV_CMD_NAV_WAYPOINT, visualItemIndex, makeCurrentItem);
}

400
VisualMissionItem* MissionController::insertTakeoffItem(QGeoCoordinate /*coordinate*/, int visualItemIndex, bool makeCurrentItem)
401 402
{
    int sequenceNumber = _nextSequenceNumber();
DonLakeFlyer's avatar
DonLakeFlyer committed
403
    TakeoffMissionItem * newItem = new TakeoffMissionItem(_controllerVehicle->vtol() ? MAV_CMD_NAV_VTOL_TAKEOFF : MAV_CMD_NAV_TAKEOFF, _controllerVehicle, _flyView, _settingsItem, this);
404 405 406
    newItem->setSequenceNumber(sequenceNumber);
    _initVisualItem(newItem);

407 408 409
    if (newItem->specifiesAltitude()) {
        double  prevAltitude;
        int     prevAltitudeMode;
410

Don Gagne's avatar
Don Gagne committed
411
        if (_findPreviousAltitude(visualItemIndex, &prevAltitude, &prevAltitudeMode)) {
412
            newItem->altitude()->setRawValue(prevAltitude);
413
            newItem->setAltitudeMode(static_cast<QGroundControlQmlGlobal::AltitudeMode>(prevAltitudeMode));
414
        }
415
    }
416
    newItem->setMissionFlightStatus(_missionFlightStatus);
417 418 419 420 421
    if (visualItemIndex == -1) {
        _visualItems->append(newItem);
    } else {
        _visualItems->insert(visualItemIndex, newItem);
    }
422

423
    _recalcAll();
424

425
    if (makeCurrentItem) {
426
        setCurrentPlanViewSeqNum(newItem->sequenceNumber(), true);
427 428 429
    }

    return newItem;
430 431
}

432
VisualMissionItem* MissionController::insertLandItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem)
433
{
434 435 436 437
    if (_managerVehicle->fixedWing()) {
        FixedWingLandingComplexItem* fwLanding = qobject_cast<FixedWingLandingComplexItem*>(insertComplexMissionItem(MissionController::patternFWLandingName, coordinate, visualItemIndex, makeCurrentItem));
        fwLanding->setLoiterDragAngleOnly(true);
        return fwLanding;
438
    } else {
439
        return _insertSimpleMissionItemWorker(coordinate, MAV_CMD_NAV_RETURN_TO_LAUNCH, visualItemIndex, makeCurrentItem);
440
    }
441
}
442

443 444
VisualMissionItem* MissionController::insertROIMissionItem(QGeoCoordinate coordinate, int visualItemIndex, bool makeCurrentItem)
{
445 446 447 448 449 450
    SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(_insertSimpleMissionItemWorker(coordinate, MAV_CMD_DO_SET_ROI_LOCATION, visualItemIndex, makeCurrentItem));

    if (!_controllerVehicle->firmwarePlugin()->supportedMissionCommands().contains(MAV_CMD_DO_SET_ROI_LOCATION)) {
        simpleItem->setCommand(MAV_CMD_DO_SET_ROI)  ;
        simpleItem->missionItem().setParam1(MAV_ROI_LOCATION);
    }
451
    _recalcROISpecialVisuals();
452 453 454 455 456 457 458 459 460 461 462
    return simpleItem;
}

VisualMissionItem* MissionController::insertCancelROIMissionItem(int visualItemIndex, bool makeCurrentItem)
{
    SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(_insertSimpleMissionItemWorker(QGeoCoordinate(), MAV_CMD_DO_SET_ROI_NONE, visualItemIndex, makeCurrentItem));

    if (!_controllerVehicle->firmwarePlugin()->supportedMissionCommands().contains(MAV_CMD_DO_SET_ROI_NONE)) {
        simpleItem->setCommand(MAV_CMD_DO_SET_ROI)  ;
        simpleItem->missionItem().setParam1(MAV_ROI_NONE);
    }
463
    _recalcROISpecialVisuals();
464
    return simpleItem;
465 466
}

467
VisualMissionItem* MissionController::insertComplexMissionItem(QString itemName, QGeoCoordinate mapCenterCoordinate, int visualItemIndex, bool makeCurrentItem)
468
{
469
    ComplexMissionItem* newItem = nullptr;
470

DonLakeFlyer's avatar
DonLakeFlyer committed
471
    if (itemName == patternSurveyName) {
472
        newItem = new SurveyComplexItem(_controllerVehicle, _flyView, QString() /* kmlFile */, _visualItems /* parent */);
473
        newItem->setCoordinate(mapCenterCoordinate);
474
    } else if (itemName == patternFWLandingName) {
475
        newItem = new FixedWingLandingComplexItem(_controllerVehicle, _flyView, _visualItems /* parent */);
476
    } else if (itemName == patternStructureScanName) {
477
        newItem = new StructureScanComplexItem(_controllerVehicle, _flyView, QString() /* kmlFile */, _visualItems /* parent */);
478
    } else if (itemName == patternCorridorScanName) {
479
        newItem = new CorridorScanComplexItem(_controllerVehicle, _flyView, QString() /* kmlFile */, _visualItems /* parent */);
480 481
    } else {
        qWarning() << "Internal error: Unknown complex item:" << itemName;
482
        return nullptr;
483 484
    }

485
    _insertComplexMissionItemWorker(mapCenterCoordinate, newItem, visualItemIndex, makeCurrentItem);
486 487

    return newItem;
488 489
}

490
VisualMissionItem* MissionController::insertComplexMissionItemFromKMLOrSHP(QString itemName, QString file, int visualItemIndex, bool makeCurrentItem)
491
{
492
    ComplexMissionItem* newItem = nullptr;
493

DonLakeFlyer's avatar
DonLakeFlyer committed
494
    if (itemName == patternSurveyName) {
495
        newItem = new SurveyComplexItem(_controllerVehicle, _flyView, file, _visualItems);
496
    } else if (itemName == patternStructureScanName) {
497
        newItem = new StructureScanComplexItem(_controllerVehicle, _flyView, file, _visualItems);
498
    } else if (itemName == patternCorridorScanName) {
499
        newItem = new CorridorScanComplexItem(_controllerVehicle, _flyView, file, _visualItems);
500 501
    } else {
        qWarning() << "Internal error: Unknown complex item:" << itemName;
502
        return nullptr;
503 504
    }

505
    _insertComplexMissionItemWorker(QGeoCoordinate(), newItem, visualItemIndex, makeCurrentItem);
506 507

    return newItem;
508 509
}

510
void MissionController::_insertComplexMissionItemWorker(const QGeoCoordinate& mapCenterCoordinate, ComplexMissionItem* complexItem, int visualItemIndex, bool makeCurrentItem)
511 512
{
    int sequenceNumber = _nextSequenceNumber();
513
    bool surveyStyleItem = qobject_cast<SurveyComplexItem*>(complexItem) ||
514 515
            qobject_cast<CorridorScanComplexItem*>(complexItem) ||
            qobject_cast<StructureScanComplexItem*>(complexItem);
516

517
    if (surveyStyleItem) {
518
        bool rollSupported  = false;
519
        bool pitchSupported = false;
520
        bool yawSupported   = false;
521 522 523

        // If the vehicle is known to have a gimbal then we automatically point the gimbal straight down if not already set

524 525
        MissionSettingsItem* settingsItem = _visualItems->value<MissionSettingsItem*>(0);
        CameraSection* cameraSection = settingsItem->cameraSection();
526

527
        // Set camera to photo mode (leave alone if user already specified)
528
        if (cameraSection->cameraModeSupported() && !cameraSection->specifyCameraMode()) {
529
            cameraSection->setSpecifyCameraMode(true);
530
            cameraSection->cameraMode()->setRawValue(CAMERA_MODE_IMAGE_SURVEY);
531
        }
532

533
        // Point gimbal straight down
534
        if (_controllerVehicle->firmwarePlugin()->hasGimbal(_controllerVehicle, rollSupported, pitchSupported, yawSupported) && pitchSupported) {
535 536 537
            // If the user already specified a gimbal angle leave it alone
            if (!cameraSection->specifyGimbal()) {
                cameraSection->setSpecifyGimbal(true);
538
                cameraSection->gimbalPitch()->setRawValue(-90.0);
539 540
            }
        }
541
    }
542

543
    complexItem->setSequenceNumber(sequenceNumber);
544
    complexItem->setWizardMode(true);
545
    _initVisualItem(complexItem);
546

Don Gagne's avatar
Don Gagne committed
547
    if (visualItemIndex == -1) {
548 549
        _visualItems->append(complexItem);
    } else {
Don Gagne's avatar
Don Gagne committed
550
        _visualItems->insert(visualItemIndex, complexItem);
551
    }
552

553
    //-- Keep track of bounding box changes in complex items
554 555
    if(!complexItem->isSimpleItem()) {
        connect(complexItem, &ComplexMissionItem::boundingCubeChanged, this, &MissionController::_complexBoundingBoxChanged);
556
    }
557
    _recalcAllWithCoordinate(mapCenterCoordinate);
558

559
    if (makeCurrentItem) {
560
        setCurrentPlanViewSeqNum(complexItem->sequenceNumber(), true);
561
    }
562 563
}

564
void MissionController::removeMissionItem(int viIndex)
565
{
566 567
    if (viIndex <= 0 || viIndex >= _visualItems->count()) {
        qWarning() << "MissionController::removeMissionItem called with bad index - count:index" << _visualItems->count() << viIndex;
568 569 570
        return;
    }

571 572
    bool removeSurveyStyle = _visualItems->value<SurveyComplexItem*>(viIndex) || _visualItems->value<CorridorScanComplexItem*>(viIndex);
    VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->removeAt(viIndex));
573

574
    _deinitVisualItem(item);
575
    item->deleteLater();
576

577 578
    if (removeSurveyStyle) {
        // Determine if the mission still has another survey style item in it
579 580
        bool foundSurvey = false;
        for (int i=1; i<_visualItems->count(); i++) {
581
            if (_visualItems->value<SurveyComplexItem*>(i) || _visualItems->value<CorridorScanComplexItem*>(i)) {
582 583 584 585 586
                foundSurvey = true;
                break;
            }
        }

587
        // If there is no longer a survey item in the mission remove added commands
588 589 590 591
        if (!foundSurvey) {
            bool rollSupported = false;
            bool pitchSupported = false;
            bool yawSupported = false;
592
            CameraSection* cameraSection = _settingsItem->cameraSection();
593
            if (_controllerVehicle->firmwarePlugin()->hasGimbal(_controllerVehicle, rollSupported, pitchSupported, yawSupported) && pitchSupported) {
594
                if (cameraSection->specifyGimbal() && cameraSection->gimbalPitch()->rawValue().toDouble() == -90.0 && cameraSection->gimbalYaw()->rawValue().toDouble() == 0.0) {
595 596 597
                    cameraSection->setSpecifyGimbal(false);
                }
            }
598
            if (cameraSection->cameraModeSupported() && cameraSection->specifyCameraMode() && cameraSection->cameraMode()->rawValue().toInt() == 0) {
599 600
                cameraSection->setSpecifyCameraMode(false);
            }
601 602 603
        }
    }

604
    _recalcAll();
605 606 607 608 609 610 611 612 613 614

    // Adjust current item
    int newVIIndex;
    if (viIndex >= _visualItems->count()) {
        newVIIndex = _visualItems->count() - 1;
    } else {
        newVIIndex = viIndex;
    }
    setCurrentPlanViewSeqNum(_visualItems->value<VisualMissionItem*>(newVIIndex)->sequenceNumber(), true);

615
    setDirty(true);
616 617
}

618
void MissionController::removeAll(void)
619
{
620 621
    if (_visualItems) {
        _deinitAllVisualItems();
DonLakeFlyer's avatar
DonLakeFlyer committed
622
        _visualItems->clearAndDeleteContents();
Don Gagne's avatar
Don Gagne committed
623
        _visualItems->deleteLater();
624
        _settingsItem = nullptr;
625
        _visualItems = new QmlObjectListModel(this);
626
        _addMissionSettings(_visualItems);
627
        _initAllVisualItems();
628
        setDirty(true);
629
        _resetMissionFlightStatus();
Don Gagne's avatar
Don Gagne committed
630 631 632
    }
}

633
bool MissionController::_loadJsonMissionFileV1(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString)
Don Gagne's avatar
Don Gagne committed
634 635 636 637 638 639 640 641 642
{
    // Validate root object keys
    QList<JsonHelper::KeyValidateInfo> rootKeyInfoList = {
        { _jsonPlannedHomePositionKey,      QJsonValue::Object, true },
        { _jsonItemsKey,                    QJsonValue::Array,  true },
        { _jsonMavAutopilotKey,             QJsonValue::Double, true },
        { _jsonComplexItemsKey,             QJsonValue::Array,  true },
    };
    if (!JsonHelper::validateKeys(json, rootKeyInfoList, errorString)) {
643 644 645
        return false;
    }

646
    // Read complex items
647
    QList<SurveyComplexItem*> surveyItems;
648 649 650 651
    QJsonArray complexArray(json[_jsonComplexItemsKey].toArray());
    qCDebug(MissionControllerLog) << "Json load: complex item count" << complexArray.count();
    for (int i=0; i<complexArray.count(); i++) {
        const QJsonValue& itemValue = complexArray[i];
652

653 654 655 656 657
        if (!itemValue.isObject()) {
            errorString = QStringLiteral("Mission item is not an object");
            return false;
        }

658
        SurveyComplexItem* item = new SurveyComplexItem(_controllerVehicle, _flyView, QString() /* kmlFile */, visualItems /* parent */);
Don Gagne's avatar
Don Gagne committed
659 660
        const QJsonObject itemObject = itemValue.toObject();
        if (item->load(itemObject, itemObject["id"].toInt(), errorString)) {
661
            surveyItems.append(item);
662 663
        } else {
            return false;
664
        }
665
    }
666

667 668 669 670 671
    // Read simple items, interspersing complex items into the full list

    int nextSimpleItemIndex= 0;
    int nextComplexItemIndex= 0;
    int nextSequenceNumber = 1; // Start with 1 since home is in 0
Don Gagne's avatar
Don Gagne committed
672
    QJsonArray itemArray(json[_jsonItemsKey].toArray());
673

674
    MissionSettingsItem* settingsItem = _addMissionSettings(visualItems);
675 676 677
    if (json.contains(_jsonPlannedHomePositionKey)) {
        SimpleMissionItem* item = new SimpleMissionItem(_controllerVehicle, _flyView, visualItems);
        if (item->load(json[_jsonPlannedHomePositionKey].toObject(), 0, errorString)) {
678
            settingsItem->setInitialHomePositionFromUser(item->coordinate());
679 680 681 682 683 684
            item->deleteLater();
        } else {
            return false;
        }
    }

685
    qCDebug(MissionControllerLog) << "Json load: simple item loop start simpleItemCount:ComplexItemCount" << itemArray.count() << surveyItems.count();
686 687 688 689
    do {
        qCDebug(MissionControllerLog) << "Json load: simple item loop nextSimpleItemIndex:nextComplexItemIndex:nextSequenceNumber" << nextSimpleItemIndex << nextComplexItemIndex << nextSequenceNumber;

        // If there is a complex item that should be next in sequence add it in
690
        if (nextComplexItemIndex < surveyItems.count()) {
691
            SurveyComplexItem* complexItem = surveyItems[nextComplexItemIndex];
692 693 694 695 696 697 698 699 700 701 702 703 704 705

            if (complexItem->sequenceNumber() == nextSequenceNumber) {
                qCDebug(MissionControllerLog) << "Json load: injecting complex item expectedSequence:actualSequence:" << nextSequenceNumber << complexItem->sequenceNumber();
                visualItems->append(complexItem);
                nextSequenceNumber = complexItem->lastSequenceNumber() + 1;
                nextComplexItemIndex++;
                continue;
            }
        }

        // Add the next available simple item
        if (nextSimpleItemIndex < itemArray.count()) {
            const QJsonValue& itemValue = itemArray[nextSimpleItemIndex++];

706 707 708 709 710
            if (!itemValue.isObject()) {
                errorString = QStringLiteral("Mission item is not an object");
                return false;
            }

Don Gagne's avatar
Don Gagne committed
711
            const QJsonObject itemObject = itemValue.toObject();
712
            SimpleMissionItem* item = new SimpleMissionItem(_controllerVehicle, _flyView, visualItems);
Don Gagne's avatar
Don Gagne committed
713
            if (item->load(itemObject, itemObject["id"].toInt(), errorString)) {
714 715
                if (TakeoffMissionItem::isTakeoffCommand(item->mavCommand())) {
                    // This needs to be a TakeoffMissionItem
716
                    TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_controllerVehicle, _flyView, settingsItem, visualItems);
717 718 719 720
                    takeoffItem->load(itemObject, itemObject["id"].toInt(), errorString);
                    item->deleteLater();
                    item = takeoffItem;
                }
721
                qCDebug(MissionControllerLog) << "Json load: adding simple item expectedSequence:actualSequence" << nextSequenceNumber << item->sequenceNumber();
722
                nextSequenceNumber = item->lastSequenceNumber() + 1;
723
                visualItems->append(item);
724 725 726 727
            } else {
                return false;
            }
        }
728
    } while (nextSimpleItemIndex < itemArray.count() || nextComplexItemIndex < surveyItems.count());
729 730 731 732

    return true;
}

733
bool MissionController::_loadJsonMissionFileV2(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString)
Don Gagne's avatar
Don Gagne committed
734 735 736 737 738 739
{
    // Validate root object keys
    QList<JsonHelper::KeyValidateInfo> rootKeyInfoList = {
        { _jsonPlannedHomePositionKey,      QJsonValue::Array,  true },
        { _jsonItemsKey,                    QJsonValue::Array,  true },
        { _jsonFirmwareTypeKey,             QJsonValue::Double, true },
740
        { _jsonVehicleTypeKey,              QJsonValue::Double, false },
741 742
        { _jsonCruiseSpeedKey,              QJsonValue::Double, false },
        { _jsonHoverSpeedKey,               QJsonValue::Double, false },
Don Gagne's avatar
Don Gagne committed
743 744 745 746 747 748 749
    };
    if (!JsonHelper::validateKeys(json, rootKeyInfoList, errorString)) {
        return false;
    }

    qCDebug(MissionControllerLog) << "MissionController::_loadJsonMissionFileV2 itemCount:" << json[_jsonItemsKey].toArray().count();

750
    // Mission Settings
751
    AppSettings* appSettings = qgcApp()->toolbox()->settingsManager()->appSettings();
752

753 754
    if (_masterController->offline()) {
        // We only update if offline since if we are online we use the online vehicle settings
755
        appSettings->offlineEditingFirmwareType()->setRawValue(AppSettings::offlineEditingFirmwareTypeFromFirmwareType(static_cast<MAV_AUTOPILOT>(json[_jsonFirmwareTypeKey].toInt())));
756
        if (json.contains(_jsonVehicleTypeKey)) {
757
            appSettings->offlineEditingVehicleType()->setRawValue(AppSettings::offlineEditingVehicleTypeFromVehicleType(static_cast<MAV_TYPE>(json[_jsonVehicleTypeKey].toInt())));
758
        }
759
    }
760
    if (json.contains(_jsonCruiseSpeedKey)) {
761
        appSettings->offlineEditingCruiseSpeed()->setRawValue(json[_jsonCruiseSpeedKey].toDouble());
762 763
    }
    if (json.contains(_jsonHoverSpeedKey)) {
764
        appSettings->offlineEditingHoverSpeed()->setRawValue(json[_jsonHoverSpeedKey].toDouble());
765 766
    }

767 768 769 770
    QGeoCoordinate homeCoordinate;
    if (!JsonHelper::loadGeoCoordinate(json[_jsonPlannedHomePositionKey], true /* altitudeRequired */, homeCoordinate, errorString)) {
        return false;
    }
771 772 773
    MissionSettingsItem* settingsItem = new MissionSettingsItem(_controllerVehicle, _flyView, visualItems);
    settingsItem->setCoordinate(homeCoordinate);
    visualItems->insert(0, settingsItem);
Don Gagne's avatar
Don Gagne committed
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    qCDebug(MissionControllerLog) << "plannedHomePosition" << homeCoordinate;

    // Read mission items

    int nextSequenceNumber = 1; // Start with 1 since home is in 0
    const QJsonArray rgMissionItems(json[_jsonItemsKey].toArray());
    for (int i=0; i<rgMissionItems.count(); i++) {
        // Convert to QJsonObject
        const QJsonValue& itemValue = rgMissionItems[i];
        if (!itemValue.isObject()) {
            errorString = tr("Mission item %1 is not an object").arg(i);
            return false;
        }
        const QJsonObject itemObject = itemValue.toObject();

        // Load item based on type

        QList<JsonHelper::KeyValidateInfo> itemKeyInfoList = {
            { VisualMissionItem::jsonTypeKey,  QJsonValue::String, true },
        };
        if (!JsonHelper::validateKeys(itemObject, itemKeyInfoList, errorString)) {
            return false;
        }
        QString itemType = itemObject[VisualMissionItem::jsonTypeKey].toString();

        if (itemType == VisualMissionItem::jsonTypeSimpleItemValue) {
800
            SimpleMissionItem* simpleItem = new SimpleMissionItem(_controllerVehicle, _flyView, visualItems);
801
            if (simpleItem->load(itemObject, nextSequenceNumber, errorString)) {
802 803
                if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(simpleItem->command()))) {
                    // This needs to be a TakeoffMissionItem
804
                    TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_controllerVehicle, _flyView, settingsItem, this);
805 806 807 808
                    takeoffItem->load(itemObject, nextSequenceNumber, errorString);
                    simpleItem->deleteLater();
                    simpleItem = takeoffItem;
                }
809
                qCDebug(MissionControllerLog) << "Loading simple item: nextSequenceNumber:command" << nextSequenceNumber << simpleItem->command();
810
                nextSequenceNumber = simpleItem->lastSequenceNumber() + 1;
Don Gagne's avatar
Don Gagne committed
811 812 813 814 815 816 817 818 819 820 821 822 823
                visualItems->append(simpleItem);
            } else {
                return false;
            }
        } else if (itemType == VisualMissionItem::jsonTypeComplexItemValue) {
            QList<JsonHelper::KeyValidateInfo> complexItemKeyInfoList = {
                { ComplexMissionItem::jsonComplexItemTypeKey,  QJsonValue::String, true },
            };
            if (!JsonHelper::validateKeys(itemObject, complexItemKeyInfoList, errorString)) {
                return false;
            }
            QString complexItemType = itemObject[ComplexMissionItem::jsonComplexItemTypeKey].toString();

824
            if (complexItemType == SurveyComplexItem::jsonComplexItemTypeValue) {
Don Gagne's avatar
Don Gagne committed
825
                qCDebug(MissionControllerLog) << "Loading Survey: nextSequenceNumber" << nextSequenceNumber;
826
                SurveyComplexItem* surveyItem = new SurveyComplexItem(_controllerVehicle, _flyView, QString() /* kmlFile */, visualItems);
Don Gagne's avatar
Don Gagne committed
827 828 829 830 831 832
                if (!surveyItem->load(itemObject, nextSequenceNumber++, errorString)) {
                    return false;
                }
                nextSequenceNumber = surveyItem->lastSequenceNumber() + 1;
                qCDebug(MissionControllerLog) << "Survey load complete: nextSequenceNumber" << nextSequenceNumber;
                visualItems->append(surveyItem);
833
            } else if (complexItemType == FixedWingLandingComplexItem::jsonComplexItemTypeValue) {
DonLakeFlyer's avatar
DonLakeFlyer committed
834
                qCDebug(MissionControllerLog) << "Loading Fixed Wing Landing Pattern: nextSequenceNumber" << nextSequenceNumber;
835
                FixedWingLandingComplexItem* landingItem = new FixedWingLandingComplexItem(_controllerVehicle, _flyView, visualItems);
DonLakeFlyer's avatar
DonLakeFlyer committed
836 837 838 839 840 841
                if (!landingItem->load(itemObject, nextSequenceNumber++, errorString)) {
                    return false;
                }
                nextSequenceNumber = landingItem->lastSequenceNumber() + 1;
                qCDebug(MissionControllerLog) << "FW Landing Pattern load complete: nextSequenceNumber" << nextSequenceNumber;
                visualItems->append(landingItem);
842 843
            } else if (complexItemType == StructureScanComplexItem::jsonComplexItemTypeValue) {
                qCDebug(MissionControllerLog) << "Loading Structure Scan: nextSequenceNumber" << nextSequenceNumber;
844
                StructureScanComplexItem* structureItem = new StructureScanComplexItem(_controllerVehicle, _flyView, QString() /* kmlFile */, visualItems);
845 846 847 848 849 850
                if (!structureItem->load(itemObject, nextSequenceNumber++, errorString)) {
                    return false;
                }
                nextSequenceNumber = structureItem->lastSequenceNumber() + 1;
                qCDebug(MissionControllerLog) << "Structure Scan load complete: nextSequenceNumber" << nextSequenceNumber;
                visualItems->append(structureItem);
851 852
            } else if (complexItemType == CorridorScanComplexItem::jsonComplexItemTypeValue) {
                qCDebug(MissionControllerLog) << "Loading Corridor Scan: nextSequenceNumber" << nextSequenceNumber;
853
                CorridorScanComplexItem* corridorItem = new CorridorScanComplexItem(_controllerVehicle, _flyView, QString() /* kmlFile */, visualItems);
854 855 856 857 858 859
                if (!corridorItem->load(itemObject, nextSequenceNumber++, errorString)) {
                    return false;
                }
                nextSequenceNumber = corridorItem->lastSequenceNumber() + 1;
                qCDebug(MissionControllerLog) << "Corridor Scan load complete: nextSequenceNumber" << nextSequenceNumber;
                visualItems->append(corridorItem);
Don Gagne's avatar
Don Gagne committed
860 861 862 863 864 865 866 867 868 869 870 871 872
            } else {
                errorString = tr("Unsupported complex item type: %1").arg(complexItemType);
            }
        } else {
            errorString = tr("Unknown item type: %1").arg(itemType);
            return false;
        }
    }

    // Fix up the DO_JUMP commands jump sequence number by finding the item with the matching doJumpId
    for (int i=0; i<visualItems->count(); i++) {
        if (visualItems->value<VisualMissionItem*>(i)->isSimpleItem()) {
            SimpleMissionItem* doJumpItem = visualItems->value<SimpleMissionItem*>(i);
873
            if (doJumpItem->command() == MAV_CMD_DO_JUMP) {
Don Gagne's avatar
Don Gagne committed
874
                bool found = false;
875
                int findDoJumpId = static_cast<int>(doJumpItem->missionItem().param1());
Don Gagne's avatar
Don Gagne committed
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
                for (int j=0; j<visualItems->count(); j++) {
                    if (visualItems->value<VisualMissionItem*>(j)->isSimpleItem()) {
                        SimpleMissionItem* targetItem = visualItems->value<SimpleMissionItem*>(j);
                        if (targetItem->missionItem().doJumpId() == findDoJumpId) {
                            doJumpItem->missionItem().setParam1(targetItem->sequenceNumber());
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    errorString = tr("Could not find doJumpId: %1").arg(findDoJumpId);
                    return false;
                }
            }
        }
    }

    return true;
}

897 898 899 900 901 902 903 904
bool MissionController::_loadItemsFromJson(const QJsonObject& json, QmlObjectListModel* visualItems, QString& errorString)
{
    // V1 file format has no file type key and version key is string. Convert to new format.
    if (!json.contains(JsonHelper::jsonFileTypeKey)) {
        json[JsonHelper::jsonFileTypeKey] = _jsonFileTypeValue;
    }

    int fileVersion;
905 906 907 908 909 910
    JsonHelper::validateQGCJsonFile(json,
                                    _jsonFileTypeValue,    // expected file type
                                    1,                     // minimum supported version
                                    2,                     // maximum supported version
                                    fileVersion,
                                    errorString);
911 912

    if (fileVersion == 1) {
913
        return _loadJsonMissionFileV1(json, visualItems, errorString);
914
    } else {
915
        return _loadJsonMissionFileV2(json, visualItems, errorString);
916 917 918
    }
}

919
bool MissionController::_loadTextMissionFile(QTextStream& stream, QmlObjectListModel* visualItems, QString& errorString)
920
{
921 922
    bool firstItem = true;
    bool plannedHomePositionInFile = false;
923 924 925 926 927 928 929 930 931

    QString firstLine = stream.readLine();
    const QStringList& version = firstLine.split(" ");

    bool versionOk = false;
    if (version.size() == 3 && version[0] == "QGC" && version[1] == "WPL") {
        if (version[2] == "110") {
            // ArduPilot file, planned home position is already in position 0
            versionOk = true;
932
            plannedHomePositionInFile = true;
933 934 935
        } else if (version[2] == "120") {
            // Old QGC file, no planned home position
            versionOk = true;
936
            plannedHomePositionInFile = false;
937 938 939 940
        }
    }

    if (versionOk) {
941
        MissionSettingsItem* settingsItem = _addMissionSettings(visualItems);
942

943
        while (!stream.atEnd()) {
944
            SimpleMissionItem* item = new SimpleMissionItem(_controllerVehicle, _flyView, visualItems);
945
            if (item->load(stream)) {
946
                if (firstItem && plannedHomePositionInFile) {
947
                    settingsItem->setInitialHomePositionFromUser(item->coordinate());
948
                } else {
949 950
                    if (TakeoffMissionItem::isTakeoffCommand(static_cast<MAV_CMD>(item->command()))) {
                        // This needs to be a TakeoffMissionItem
951
                        TakeoffMissionItem* takeoffItem = new TakeoffMissionItem(_controllerVehicle, _flyView, settingsItem, visualItems);
952 953 954 955
                        takeoffItem->load(stream);
                        item->deleteLater();
                        item = takeoffItem;
                    }
956 957 958
                    visualItems->append(item);
                }
                firstItem = false;
959
            } else {
960
                errorString = tr("The mission file is corrupted.");
961 962 963 964
                return false;
            }
        }
    } else {
965
        errorString = tr("The mission file is not compatible with this version of %1.").arg(qgcApp()->applicationName());
966 967 968
        return false;
    }

969
    if (!plannedHomePositionInFile) {
970 971 972
        // Update sequence numbers in DO_JUMP commands to take into account added home position in index 0
        for (int i=1; i<visualItems->count(); i++) {
            SimpleMissionItem* item = qobject_cast<SimpleMissionItem*>(visualItems->get(i));
973
            if (item && item->command() == MAV_CMD_DO_JUMP) {
974
                item->missionItem().setParam1(static_cast<int>(item->missionItem().param1()) + 1);
Don Gagne's avatar
Don Gagne committed
975 976
            }
        }
977 978 979
    }

    return true;
980 981
}

982
void MissionController::_initLoadedVisualItems(QmlObjectListModel* loadedVisualItems)
983
{
Don Gagne's avatar
Don Gagne committed
984 985 986
    if (_visualItems) {
        _deinitAllVisualItems();
        _visualItems->deleteLater();
987
        _settingsItem = nullptr;
Don Gagne's avatar
Don Gagne committed
988 989
    }

990
    _visualItems = loadedVisualItems;
Don Gagne's avatar
Don Gagne committed
991 992

    if (_visualItems->count() == 0) {
993
        _addMissionSettings(_visualItems);
994 995
    } else {
        _settingsItem = _visualItems->value<MissionSettingsItem*>(0);
Don Gagne's avatar
Don Gagne committed
996 997
    }

998
    MissionController::_scanForAdditionalSettings(_visualItems, _controllerVehicle);
999

Don Gagne's avatar
Don Gagne committed
1000
    _initAllVisualItems();
1001
}
1002

1003 1004 1005 1006 1007 1008
bool MissionController::load(const QJsonObject& json, QString& errorString)
{
    QString errorStr;
    QString errorMessage = tr("Mission: %1");
    QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this);

1009
    if (!_loadJsonMissionFileV2(json, loadedVisualItems, errorStr)) {
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
        errorString = errorMessage.arg(errorStr);
        return false;
    }
    _initLoadedVisualItems(loadedVisualItems);

    return true;
}

bool MissionController::loadJsonFile(QFile& file, QString& errorString)
{
    QString         errorStr;
    QString         errorMessage = tr("Mission: %1");
    QJsonDocument   jsonDoc;
    QByteArray      bytes = file.readAll();

    if (!JsonHelper::isJsonFile(bytes, jsonDoc, errorStr)) {
        errorString = errorMessage.arg(errorStr);
        return false;
    }

    QJsonObject json = jsonDoc.object();
    QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this);
    if (!_loadItemsFromJson(json, loadedVisualItems, errorStr)) {
        errorString = errorMessage.arg(errorStr);
        return false;
1035
    }
1036

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    _initLoadedVisualItems(loadedVisualItems);

    return true;
}

bool MissionController::loadTextFile(QFile& file, QString& errorString)
{
    QString     errorStr;
    QString     errorMessage = tr("Mission: %1");
    QByteArray  bytes = file.readAll();
    QTextStream stream(bytes);

    QmlObjectListModel* loadedVisualItems = new QmlObjectListModel(this);
1050
    if (!_loadTextMissionFile(stream, loadedVisualItems, errorStr)) {
1051 1052 1053 1054 1055 1056
        errorString = errorMessage.arg(errorStr);
        return false;
    }

    _initLoadedVisualItems(loadedVisualItems);

Don Gagne's avatar
Don Gagne committed
1057
    return true;
1058 1059
}

1060
int MissionController::readyForSaveState(void) const
1061 1062 1063
{
    for (int i=0; i<_visualItems->count(); i++) {
        VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
DonLakeFlyer's avatar
DonLakeFlyer committed
1064
        if (visualItem->readyForSaveState() != VisualMissionItem::ReadyForSave) {
1065
            return visualItem->readyForSaveState();
1066 1067 1068
        }
    }

1069
    return VisualMissionItem::ReadyForSave;
1070 1071
}

1072
void MissionController::save(QJsonObject& json)
1073
{
1074
    json[JsonHelper::jsonVersionKey] = _missionFileVersion;
1075

1076
    // Mission settings
1077

1078 1079 1080 1081 1082 1083 1084
    MissionSettingsItem* settingsItem = _visualItems->value<MissionSettingsItem*>(0);
    if (!settingsItem) {
        qWarning() << "First item is not MissionSettingsItem";
        return;
    }
    QJsonValue coordinateValue;
    JsonHelper::saveGeoCoordinate(settingsItem->coordinate(), true /* writeAltitude */, coordinateValue);
1085 1086 1087 1088 1089
    json[_jsonPlannedHomePositionKey]   = coordinateValue;
    json[_jsonFirmwareTypeKey]          = _controllerVehicle->firmwareType();
    json[_jsonVehicleTypeKey]           = _controllerVehicle->vehicleType();
    json[_jsonCruiseSpeedKey]           = _controllerVehicle->defaultCruiseSpeed();
    json[_jsonHoverSpeedKey]            = _controllerVehicle->defaultHoverSpeed();
1090

1091
    // Save the visual items
1092

1093 1094 1095
    QJsonArray rgJsonMissionItems;
    for (int i=0; i<_visualItems->count(); i++) {
        VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
1096

1097 1098
        visualItem->save(rgJsonMissionItems);
    }
1099

1100 1101 1102
    // Mission settings has a special case for end mission action
    if (settingsItem) {
        QList<MissionItem*> rgMissionItems;
1103

1104 1105 1106 1107 1108
        if (_convertToMissionItems(_visualItems, rgMissionItems, this /* missionItemParent */)) {
            QJsonObject saveObject;
            MissionItem* missionItem = rgMissionItems[rgMissionItems.count() - 1];
            missionItem->save(saveObject);
            rgJsonMissionItems.append(saveObject);
1109
        }
1110 1111
        for (int i=0; i<rgMissionItems.count(); i++) {
            rgMissionItems[i]->deleteLater();
1112 1113 1114
        }
    }

1115
    json[_jsonItemsKey] = rgJsonMissionItems;
1116 1117
}

1118