MissionController.cc 38.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*=====================================================================

QGroundControl Open Source Ground Control Station

(c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

This file is part of the QGROUNDCONTROL project

    QGROUNDCONTROL is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    QGROUNDCONTROL is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

#include "MissionController.h"
#include "MultiVehicleManager.h"
#include "MissionManager.h"
#include "CoordinateVector.h"
28
#include "FirmwarePlugin.h"
29
#include "QGCApplication.h"
30 31
#include "SimpleMissionItem.h"
#include "ComplexMissionItem.h"
32
#include "JsonHelper.h"
33

34 35 36 37
#ifndef __mobile__
#include "QGCFileDialog.h"
#endif

38 39
QGC_LOGGING_CATEGORY(MissionControllerLog, "MissionControllerLog")

40 41
const char* MissionController::jsonSimpleItemsKey = "items";

42 43 44 45
const char* MissionController::_settingsGroup =                 "MissionController";
const char* MissionController::_jsonVersionKey =                "version";
const char* MissionController::_jsonGroundStationKey =          "groundStation";
const char* MissionController::_jsonMavAutopilotKey =           "MAV_AUTOPILOT";
46
const char* MissionController::_jsonComplexItemsKey =           "complexItems";
47
const char* MissionController::_jsonPlannedHomePositionKey =    "plannedHomePosition";
48 49 50

MissionController::MissionController(QObject *parent)
    : QObject(parent)
51
    , _editMode(false)
52 53
    , _visualItems(NULL)
    , _complexItems(NULL)
54
    , _activeVehicle(NULL)
55
    , _autoSync(false)
56
    , _firstItemsFromVehicle(false)
57 58
    , _missionItemsRequested(false)
    , _queuedSend(false)
59
{
60 61 62 63 64

}

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

66 67 68 69
}

void MissionController::start(bool editMode)
{
70 71
    qCDebug(MissionControllerLog) << "start editMode" << editMode;

72 73
    _editMode = editMode;

74
    MultiVehicleManager* multiVehicleMgr = qgcApp()->toolbox()->multiVehicleManager();
75

76
    connect(multiVehicleMgr, &MultiVehicleManager::activeVehicleChanged, this, &MissionController::_activeVehicleChanged);
77
    _activeVehicleChanged(multiVehicleMgr->activeVehicle());
78

79
    // We start with an empty mission
80 81 82
    _visualItems = new QmlObjectListModel(this);
    _addPlannedHomePosition(_visualItems, false /* addToCenter */);
    _initAllVisualItems();
83 84
}

85
// Called when new mission items have completed downloading from Vehicle
86
void MissionController::_newMissionItemsAvailableFromVehicle(void)
87
{
88 89
    qCDebug(MissionControllerLog) << "_newMissionItemsAvailableFromVehicle";

90
    if (!_editMode || _missionItemsRequested || _visualItems->count() == 1) {
91 92 93 94 95
        // Fly Mode:
        //      - Always accepts new items fromthe vehicle so Fly view is kept up to date
        // Edit Mode:
        //      - Either a load from vehicle was manually requested or
        //      - The initial automatic load from a vehicle completed and the current editor it empty
96

97 98
        QmlObjectListModel* newControllerMissionItems = new QmlObjectListModel(this);
        const QList<MissionItem*>& newMissionItems = _activeVehicle->missionManager()->missionItems();
99

100 101 102 103 104 105 106 107 108 109 110 111
        qCDebug(MissionControllerLog) << "loading from vehicle: count"<< _visualItems->count();
        foreach(const MissionItem* missionItem, newMissionItems) {
            newControllerMissionItems->append(new SimpleMissionItem(_activeVehicle, *missionItem, this));
        }

        _deinitAllVisualItems();

        _visualItems->deleteListAndContents();
        _visualItems = newControllerMissionItems;

        if (!_activeVehicle->firmwarePlugin()->sendHomePositionToVehicle() || _visualItems->count() == 0) {
            _addPlannedHomePosition(_visualItems,true /* addToCenter */);
112 113
        }

114
        _missionItemsRequested = false;
115

116
        _initAllVisualItems();
117
        emit newItemsFromVehicle();
118 119 120
    }
}

121
void MissionController::getMissionItems(void)
122
{
123
    Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle();
124

125 126 127 128 129 130 131 132
    if (activeVehicle) {
        _missionItemsRequested = true;
        activeVehicle->missionManager()->requestMissionItems();
    }
}

void MissionController::sendMissionItems(void)
{
133 134 135 136 137 138 139
    if (_activeVehicle) {
        // Convert to MissionItems so we can send to vehicle
        QList<MissionItem*> missionItems;

        for (int i=0; i<_visualItems->count(); i++) {
            VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
            if (visualItem->isSimpleItem()) {
140
                missionItems.append(new MissionItem(qobject_cast<SimpleMissionItem*>(visualItem)->missionItem()));
141
            } else {
142
                ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(visualItem);
143 144 145
                QmlObjectListModel* complexMissionItems = complexItem->getMissionItems();
                for (int j=0; j<complexMissionItems->count(); j++) {
                    missionItems.append(new MissionItem(*qobject_cast<MissionItem*>(complexMissionItems->get(j))));
146
                }
147
                delete complexMissionItems;
148 149 150 151 152
            }
        }

        _activeVehicle->missionManager()->writeMissionItems(missionItems);
        _visualItems->setDirty(false);
153 154 155 156

        for (int i=0; i<missionItems.count(); i++) {
            delete missionItems[i];
        }
157 158
    }
}
159

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
int MissionController::_nextSequenceNumber(void)
{
    if (_visualItems->count() == 0) {
        qWarning() << "Internal error: Empty visual item list";
        return 0;
    } else {
        VisualMissionItem* lastItem = qobject_cast<VisualMissionItem*>(_visualItems->get(_visualItems->count() - 1));

        if (lastItem->isSimpleItem()) {
            return lastItem->sequenceNumber() + 1;
        } else {
            return qobject_cast<ComplexMissionItem*>(lastItem)->lastSequenceNumber() + 1;
        }
    }
}

176
int MissionController::insertSimpleMissionItem(QGeoCoordinate coordinate, int i)
177
{
178
    int sequenceNumber = _nextSequenceNumber();
179
    SimpleMissionItem * newItem = new SimpleMissionItem(_activeVehicle, this);
180
    newItem->setSequenceNumber(sequenceNumber);
181
    newItem->setCoordinate(coordinate);
182 183 184
    newItem->setCommand(MavlinkQmlSingleton::MAV_CMD_NAV_WAYPOINT);
    _initVisualItem(newItem);
    if (_visualItems->count() == 1) {
185 186
        newItem->setCommand(MavlinkQmlSingleton::MAV_CMD_NAV_TAKEOFF);
    }
187
    newItem->setDefaultsForCommand();
Don Gagne's avatar
Don Gagne committed
188
    if ((MAV_CMD)newItem->command() == MAV_CMD_NAV_WAYPOINT) {
189 190 191
        double lastValue;

        if (_findLastAcceptanceRadius(&lastValue)) {
192
            newItem->missionItem().setParam2(lastValue);
193 194
        }
        if (_findLastAltitude(&lastValue)) {
195
            newItem->missionItem().setParam7(lastValue);
196
        }
197
    }
198
    _visualItems->insert(i, newItem);
199 200 201

    _recalcAll();

202
    return sequenceNumber;
203 204
}

205 206
int MissionController::insertComplexMissionItem(QGeoCoordinate coordinate, int i)
{
207
    int sequenceNumber = _nextSequenceNumber();
208
    ComplexMissionItem* newItem = new ComplexMissionItem(_activeVehicle, this);
209
    newItem->setSequenceNumber(sequenceNumber);
210
    newItem->setCoordinate(coordinate);
211
    _initVisualItem(newItem);
212

213 214
    _visualItems->insert(i, newItem);
    _complexItems->append(newItem);
215 216 217

    _recalcAll();

218
    return sequenceNumber;
219 220
}

221 222
void MissionController::removeMissionItem(int index)
{
223
    VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->removeAt(index));
224

225 226 227 228 229 230 231 232 233
    _deinitVisualItem(item);
    if (!item->isSimpleItem()) {
        ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(_complexItems->removeOne(item));
        if (complexItem) {
            complexItem->deleteLater();
        } else {
            qWarning() << "Complex item missing";
        }
    }
234
    item->deleteLater();
235 236 237 238 239

    _recalcAll();

    // Set the new current item

240
    if (index >= _visualItems->count()) {
241 242
        index--;
    }
243
    for (int i=0; i<_visualItems->count(); i++) {
Don Gagne's avatar
Don Gagne committed
244
        VisualMissionItem* item =  qobject_cast<VisualMissionItem*>(_visualItems->get(i));
245 246
        item->setIsCurrentItem(i == index);
    }
247
    _visualItems->setDirty(true);
248 249
}

250 251
void MissionController::removeAllMissionItems(void)
{
252 253 254 255 256 257
    if (_visualItems) {
        _deinitAllVisualItems();
        _visualItems->deleteListAndContents();
        _visualItems = new QmlObjectListModel(this);
        _addPlannedHomePosition(_visualItems, false /* addToCenter */);
        _initAllVisualItems();
258
    }
259
}
260

261
bool MissionController::_loadJsonMissionFile(const QByteArray& bytes, QmlObjectListModel* visualItems, QmlObjectListModel* complexItems, QString& errorString)
262 263 264 265 266 267 268 269 270 271 272
{
    QJsonParseError jsonParseError;
    QJsonDocument   jsonDoc(QJsonDocument::fromJson(bytes, &jsonParseError));

    if (jsonParseError.error != QJsonParseError::NoError) {
        errorString = jsonParseError.errorString();
        return false;
    }

    QJsonObject json = jsonDoc.object();

273 274 275 276 277 278 279 280 281 282 283 284 285
    // Check for required keys
    QStringList requiredKeys;
    requiredKeys << _jsonVersionKey << _jsonPlannedHomePositionKey;
    if (!JsonHelper::validateRequiredKeys(json, requiredKeys, errorString)) {
        return false;
    }

    // Validate base key types
    QStringList             keyList;
    QList<QJsonValue::Type> typeList;
    keyList << jsonSimpleItemsKey << _jsonVersionKey << _jsonGroundStationKey << _jsonMavAutopilotKey << _jsonComplexItemsKey << _jsonPlannedHomePositionKey;
    typeList << QJsonValue::Array << QJsonValue::String << QJsonValue::String << QJsonValue::Double << QJsonValue::Array << QJsonValue::Object;
    if (!JsonHelper::validateKeyTypes(json, keyList, typeList, errorString)) {
286 287
        return false;
    }
288 289

    // Version check
290 291 292 293 294
    if (json[_jsonVersionKey].toString() != "1.0") {
        errorString = QStringLiteral("QGroundControl does not support this file version");
        return false;
    }

295 296 297 298 299
    // Read complex items
    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];
300

301 302 303 304 305 306 307 308 309 310 311
        if (!itemValue.isObject()) {
            errorString = QStringLiteral("Mission item is not an object");
            return false;
        }

        ComplexMissionItem* item = new ComplexMissionItem(_activeVehicle, this);
        if (item->load(itemValue.toObject(), errorString)) {
            qCDebug(MissionControllerLog) << "Json load: complex item start:stop" << item->sequenceNumber() << item->lastSequenceNumber();
            complexItems->append(item);
        } else {
            return false;
312
        }
313
    }
314

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    // 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
    QJsonArray itemArray(json[jsonSimpleItemsKey].toArray());

    qCDebug(MissionControllerLog) << "Json load: simple item loop start simpleItemCount:ComplexItemCount" << itemArray.count() << complexItems->count();
    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
        if (nextComplexItemIndex < complexItems->count()) {
            ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(complexItems->get(nextComplexItemIndex));

            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++];

343 344 345 346 347
            if (!itemValue.isObject()) {
                errorString = QStringLiteral("Mission item is not an object");
                return false;
            }

348
            SimpleMissionItem* item = new SimpleMissionItem(_activeVehicle, this);
349
            if (item->load(itemValue.toObject(), errorString)) {
350 351
                qCDebug(MissionControllerLog) << "Json load: adding simple item expectedSequence:actualSequence" << nextSequenceNumber << item->sequenceNumber();
                visualItems->append(item);
352 353 354
            } else {
                return false;
            }
355 356

            nextSequenceNumber++;
357
        }
Don Gagne's avatar
Don Gagne committed
358
    } while (nextSimpleItemIndex < itemArray.count() || nextComplexItemIndex < complexItems->count());
359 360

    if (json.contains(_jsonPlannedHomePositionKey)) {
361
        SimpleMissionItem* item = new SimpleMissionItem(_activeVehicle, this);
362 363

        if (item->load(json[_jsonPlannedHomePositionKey].toObject(), errorString)) {
364
            visualItems->insert(0, item);
365 366 367 368
        } else {
            return false;
        }
    } else {
369
        _addPlannedHomePosition(visualItems, true /* addToCenter */);
370 371 372 373 374
    }

    return true;
}

375
bool MissionController::_loadTextMissionFile(QTextStream& stream, QmlObjectListModel* visualItems, QString& errorString)
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
{
    bool addPlannedHomePosition = false;

    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;
        } else if (version[2] == "120") {
            // Old QGC file, no planned home position
            versionOk = true;
            addPlannedHomePosition = true;
        }
    }

    if (versionOk) {
        while (!stream.atEnd()) {
396
            SimpleMissionItem* item = new SimpleMissionItem(_activeVehicle, this);
397 398

            if (item->load(stream)) {
399
                visualItems->append(item);
400 401 402 403 404 405 406 407 408 409
            } else {
                errorString = QStringLiteral("The mission file is corrupted.");
                return false;
            }
        }
    } else {
        errorString = QStringLiteral("The mission file is not compatible with this version of QGroundControl.");
        return false;
    }

410 411
    if (addPlannedHomePosition || visualItems->count() == 0) {
        _addPlannedHomePosition(visualItems, true /* addToCenter */);
Don Gagne's avatar
Don Gagne committed
412

413 414 415 416 417
        // 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));
            if (item && item->command() == MavlinkQmlSingleton::MAV_CMD_DO_JUMP) {
                item->missionItem().setParam1((int)item->missionItem().param1() + 1);
Don Gagne's avatar
Don Gagne committed
418 419
            }
        }
420 421 422
    }

    return true;
423 424
}

Don Gagne's avatar
Don Gagne committed
425
void MissionController::loadMissionFromFile(const QString& filename)
426 427 428 429 430 431 432
{
    QString errorString;

    if (filename.isEmpty()) {
        return;
    }

433 434
    QmlObjectListModel* newVisualItems = new QmlObjectListModel(this);
    QmlObjectListModel* newComplexItems = new QmlObjectListModel(this);
435 436 437 438 439 440

    QFile file(filename);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        errorString = file.errorString();
    } else {
441 442
        QByteArray  bytes = file.readAll();
        QTextStream stream(&bytes);
443

444 445 446
        QString firstLine = stream.readLine();
        if (firstLine.contains(QRegExp("QGC.*WPL"))) {
            stream.seek(0);
447
            _loadTextMissionFile(stream, newVisualItems, errorString);
448
        } else {
449
            _loadJsonMissionFile(bytes, newVisualItems, newComplexItems, errorString);
450 451
        }
    }
452

453
    if (!errorString.isEmpty()) {
454 455 456 457 458 459 460 461 462
        for (int i=0; i<newVisualItems->count(); i++) {
            newVisualItems->get(i)->deleteLater();
        }
        for (int i=0; i<newComplexItems->count(); i++) {
            newComplexItems->get(i)->deleteLater();
        }
        delete newVisualItems;
        delete newComplexItems;

463
        qgcApp()->showMessage(errorString);
464
        return;
465 466
    }

467 468 469
    if (_visualItems) {
        _deinitAllVisualItems();
        _visualItems->deleteListAndContents();
470
    }
471 472 473 474 475 476 477
    if (_complexItems) {
        _complexItems->deleteLater();
    }

    _visualItems = newVisualItems;
    _complexItems = newComplexItems;

478 479
    if (_visualItems->count() == 0) {
        _addPlannedHomePosition(_visualItems, true /* addToCenter */);
480 481
    }

482
    _initAllVisualItems();
483 484
}

Don Gagne's avatar
Don Gagne committed
485
void MissionController::loadMissionFromFilePicker(void)
486
{
487
#ifndef __mobile__
488 489 490 491 492
    QString filename = QGCFileDialog::getOpenFileName(NULL, "Select Mission File to load", QString(), "Mission file (*.mission);;All Files (*.*)");

    if (filename.isEmpty()) {
        return;
    }
Don Gagne's avatar
Don Gagne committed
493
    loadMissionFromFile(filename);
494 495 496
#endif
}

Don Gagne's avatar
Don Gagne committed
497
void MissionController::saveMissionToFile(const QString& filename)
498 499
{
    qDebug() << filename;
500 501 502 503

    if (filename.isEmpty()) {
        return;
    }
504

505
    QString missionFilename = filename;
506
    if (!QFileInfo(filename).fileName().contains(".")) {
Don Gagne's avatar
Don Gagne committed
507
        missionFilename += QString(".%1").arg(QGCApplication::missionFileExtension);
508 509
    }

510
    QFile file(missionFilename);
511

512
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
513
        qgcApp()->showMessage(file.errorString());
514
    } else {
515 516 517
        QJsonObject missionFileObject;      // top level json object
        QJsonArray  simpleItemsObject;
        QJsonArray  complexItemsObject;
518

519 520
        missionFileObject[_jsonVersionKey] =        "1.0";
        missionFileObject[_jsonGroundStationKey] =  "QGroundControl";
521

522 523 524 525 526 527 528 529 530 531
        MAV_AUTOPILOT firmwareType = MAV_AUTOPILOT_GENERIC;
        if (_activeVehicle) {
            firmwareType = _activeVehicle->firmwareType();
        } else {
            // FIXME: Hack duplicated code from QGroundControlQmlGlobal. Had to do this for now since
            // QGroundControlQmlGlobal is not available from C++ side.

            QSettings settings;
            firmwareType = (MAV_AUTOPILOT)settings.value("OfflineEditingFirmwareType", MAV_AUTOPILOT_ARDUPILOTMEGA).toInt();
        }
532
        missionFileObject[_jsonMavAutopilotKey] = firmwareType;
533

534
        // Save planned home position
535
        QJsonObject homePositionObject;
536 537 538 539 540 541 542
        SimpleMissionItem* homeItem = qobject_cast<SimpleMissionItem*>(_visualItems->get(0));
        if (homeItem) {
            homeItem->missionItem().save(homePositionObject);
        } else {
            qgcApp()->showMessage(QStringLiteral("Internal error: VisualMissionItem at index 0 not SimpleMissionItem"));
            return;
        }
543
        missionFileObject[_jsonPlannedHomePositionKey] = homePositionObject;
544

545
        // Save the visual items
546
        for (int i=1; i<_visualItems->count(); i++) {
547 548
            QJsonObject itemObject;

549
            VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
550 551 552 553 554 555
            visualItem->save(itemObject);

            if (visualItem->isSimpleItem()) {
                simpleItemsObject.append(itemObject);
            } else {
                complexItemsObject.append(itemObject);
556
            }
557
        }
558

559 560 561 562
        missionFileObject[jsonSimpleItemsKey] = simpleItemsObject;
        missionFileObject[_jsonComplexItemsKey] = complexItemsObject;

        QJsonDocument saveDoc(missionFileObject);
563
        file.write(saveDoc.toJson());
564 565
    }

566
    _visualItems->setDirty(false);
567 568
}

Don Gagne's avatar
Don Gagne committed
569
void MissionController::saveMissionToFilePicker(void)
570 571 572 573 574 575 576
{
#ifndef __mobile__
    QString filename = QGCFileDialog::getSaveFileName(NULL, "Select file to save mission to", QString(), "Mission file (*.mission);;All Files (*.*)");

    if (filename.isEmpty()) {
        return;
    }
Don Gagne's avatar
Don Gagne committed
577
    saveMissionToFile(filename);
578
#endif
579 580
}

581
void MissionController::_calcPrevWaypointValues(double homeAlt, VisualMissionItem* currentItem, VisualMissionItem* prevItem, double* azimuth, double* distance, double* altDifference)
582
{
Don Gagne's avatar
Don Gagne committed
583
    QGeoCoordinate  currentCoord =  currentItem->coordinate();
584
    QGeoCoordinate  prevCoord =     prevItem->exitCoordinate();
585 586 587 588
    bool            distanceOk =    false;

    // Convert to fixed altitudes

589
    qCDebug(MissionControllerLog) << homeAlt
590 591
                                  << currentItem->coordinateHasRelativeAltitude() << currentItem->coordinate().altitude()
                                  << prevItem->exitCoordinateHasRelativeAltitude() << prevItem->exitCoordinate().altitude();
592

593
    distanceOk = true;
594
    if (currentItem->coordinateHasRelativeAltitude()) {
595 596
        currentCoord.setAltitude(homeAlt + currentCoord.altitude());
    }
597
    if (prevItem->exitCoordinateHasRelativeAltitude()) {
598
        prevCoord.setAltitude(homeAlt + prevCoord.altitude());
599 600 601 602 603
    }

    qCDebug(MissionControllerLog) << "distanceOk" << distanceOk;

    if (distanceOk) {
Don Gagne's avatar
Don Gagne committed
604 605 606
        *altDifference = currentCoord.altitude() - prevCoord.altitude();
        *distance = prevCoord.distanceTo(currentCoord);
        *azimuth = prevCoord.azimuthTo(currentCoord);
607
    } else {
Don Gagne's avatar
Don Gagne committed
608
        *altDifference = 0.0;
609
        *azimuth = 0.0;
Don Gagne's avatar
Don Gagne committed
610
        *distance = -1.0;   // Signals no values
611 612 613
    }
}

614 615
void MissionController::_recalcWaypointLines(void)
{
616 617 618 619 620 621 622 623 624 625 626
    bool                firstCoordinateItem =   true;
    VisualMissionItem*  lastCoordinateItem =    qobject_cast<VisualMissionItem*>(_visualItems->get(0));

    SimpleMissionItem*  homeItem = qobject_cast<SimpleMissionItem*>(lastCoordinateItem);

    if (!homeItem) {
        qWarning() << "Home item is not SimpleMissionItem";
    }

    bool    showHomePosition =  homeItem->showHomePosition();
    double  homeAlt =           homeItem->coordinate().altitude();
627 628 629 630 631 632

    qCDebug(MissionControllerLog) << "_recalcWaypointLines";

    // If home position is valid we can calculate distances between all waypoints.
    // If home position is not valid we can only calculate distances between waypoints which are
    // both relative altitude.
633

634
    // No values for first item
635
    lastCoordinateItem->setAltDifference(0.0);
636
    lastCoordinateItem->setAzimuth(0.0);
637 638
    lastCoordinateItem->setDistance(-1.0);

639 640 641 642 643
    double minAltSeen = 0.0;
    double maxAltSeen = 0.0;
    double homePositionAltitude = homeItem->coordinate().altitude();
    minAltSeen = maxAltSeen = homeItem->coordinate().altitude();

644 645
    _waypointLines.clear();

Don Gagne's avatar
Don Gagne committed
646
    bool linkBackToHome = false;
647 648
    for (int i=1; i<_visualItems->count(); i++) {
        VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
649

650 651 652
        // Assume the worst
        item->setAzimuth(0.0);
        item->setDistance(-1.0);
653

654 655 656 657
        // If we still haven't found the first coordinate item and we hit a a takeoff command link back to home
        if (firstCoordinateItem &&
                item->isSimpleItem() &&
                qobject_cast<SimpleMissionItem*>(item)->command() == MavlinkQmlSingleton::MAV_CMD_NAV_TAKEOFF) {
Don Gagne's avatar
Don Gagne committed
658 659 660
            linkBackToHome = true;
        }

661
        if (item->specifiesCoordinate()) {
662 663
            // Keep track of the min/max altitude for all waypoints so we can show altitudes as a percentage

664
            double absoluteAltitude = item->coordinate().altitude();
665
            if (item->coordinateHasRelativeAltitude()) {
666 667 668 669 670
                absoluteAltitude += homePositionAltitude;
            }
            minAltSeen = std::min(minAltSeen, absoluteAltitude);
            maxAltSeen = std::max(maxAltSeen, absoluteAltitude);

671 672 673 674 675 676 677 678 679 680
            if (!item->exitCoordinateSameAsEntry()) {
                absoluteAltitude = item->exitCoordinate().altitude();
                if (item->exitCoordinateHasRelativeAltitude()) {
                    absoluteAltitude += homePositionAltitude;
                }
                minAltSeen = std::min(minAltSeen, absoluteAltitude);
                maxAltSeen = std::max(maxAltSeen, absoluteAltitude);
            }

            if (!item->isStandaloneCoordinate()) {
Don Gagne's avatar
Don Gagne committed
681
                firstCoordinateItem = false;
682
                if (lastCoordinateItem != homeItem || (showHomePosition && linkBackToHome)) {
683 684 685 686
                    double azimuth, distance, altDifference;

                    // Subsequent coordinate items link to last coordinate item. If the last coordinate item
                    // is an invalid home position we skip the line
687
                    _calcPrevWaypointValues(homeAlt, item, lastCoordinateItem, &azimuth, &distance, &altDifference);
688 689 690
                    item->setAltDifference(altDifference);
                    item->setAzimuth(azimuth);
                    item->setDistance(distance);
691
                    _waypointLines.append(new CoordinateVector(lastCoordinateItem->isSimpleItem() ? lastCoordinateItem->coordinate() : lastCoordinateItem->exitCoordinate(), item->coordinate()));
692
                }
693 694 695 696 697 698 699
                lastCoordinateItem = item;
            }
        }
    }

    // Walk the list again calculating altitude percentages
    double altRange = maxAltSeen - minAltSeen;
700 701
    for (int i=0; i<_visualItems->count(); i++) {
        VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
702 703 704

        if (item->specifiesCoordinate()) {
            double absoluteAltitude = item->coordinate().altitude();
705
            if (item->coordinateHasRelativeAltitude()) {
706 707 708 709 710 711
                absoluteAltitude += homePositionAltitude;
            }
            if (altRange == 0.0) {
                item->setAltPercent(0.0);
            } else {
                item->setAltPercent((absoluteAltitude - minAltSeen) / altRange);
712
            }
713 714
        }
    }
715 716

    emit waypointLinesChanged();
717 718
}

719 720 721
// This will update the sequence numbers to be sequential starting from 0
void MissionController::_recalcSequence(void)
{
722 723 724 725 726 727 728 729 730
    // Setup ascending sequence numbers for all visual items

    int sequenceNumber = 0;
    for (int i=0; i<_visualItems->count(); i++) {
        VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));

        item->setSequenceNumber(sequenceNumber++);
        if (!item->isSimpleItem()) {
            ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(item);
731

732
            if (complexItem) {
733
                 sequenceNumber = complexItem->lastSequenceNumber() + 1;
734 735 736 737
            } else {
                qWarning() << "isSimpleItem == false, yet not ComplexMissionItem";
            }
        }
738 739 740
    }
}

741 742 743
// This will update the child item hierarchy
void MissionController::_recalcChildItems(void)
{
744
    VisualMissionItem* currentParentItem = qobject_cast<VisualMissionItem*>(_visualItems->get(0));
745 746 747

    currentParentItem->childItems()->clear();

748 749
    for (int i=1; i<_visualItems->count(); i++) {
        VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
750 751 752 753 754

        // Set up non-coordinate item child hierarchy
        if (item->specifiesCoordinate()) {
            item->childItems()->clear();
            currentParentItem = item;
755
        } else if (item->isSimpleItem()) {
756 757 758 759 760
            currentParentItem->childItems()->append(item);
        }
    }
}

761 762
void MissionController::_recalcAll(void)
{
763
    _recalcSequence();
764 765 766 767
    _recalcChildItems();
    _recalcWaypointLines();
}

768
/// Initializes a new set of mission items
769
void MissionController::_initAllVisualItems(void)
770
{
771 772 773 774 775 776 777 778 779
    SimpleMissionItem* homeItem = NULL;

    // Setup home position at index 0

    homeItem = qobject_cast<SimpleMissionItem*>(_visualItems->get(0));
    if (!homeItem) {
        qWarning() << "homeItem not SimpleMissionItem";
        return;
    }
780

Don Gagne's avatar
Don Gagne committed
781
    homeItem->setHomePositionSpecialCase(true);
782
    homeItem->setShowHomePosition(_editMode);
783 784
    homeItem->missionItem().setCommand(MAV_CMD_NAV_WAYPOINT);
    homeItem->missionItem().setFrame(MAV_FRAME_GLOBAL);
785 786 787 788 789
    homeItem->setIsCurrentItem(true);

    if (!_editMode && _activeVehicle && _activeVehicle->homePositionAvailable()) {
        homeItem->setCoordinate(_activeVehicle->homePosition());
        homeItem->setShowHomePosition(true);
790
    }
791

792
    QmlObjectListModel* newComplexItems = new QmlObjectListModel(this);
793 794 795
    for (int i=0; i<_visualItems->count(); i++) {
        VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
        _initVisualItem(item);
796

797 798 799
        // Set up complex item list
        if (!item->isSimpleItem()) {
            ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(item);
800

801 802 803 804 805
            if (complexItem) {
                newComplexItems->append(item);
            } else {
                qWarning() << "isSimpleItem == false, but not ComplexMissionItem";
            }
806
        }
807 808
    }

809 810 811 812
    if (_complexItems) {
        _complexItems->deleteLater();
    }
    _complexItems = newComplexItems;
813

814
    _recalcAll();
815

816 817
    emit visualItemsChanged();
    emit complexVisualItemsChanged();
818

819
    _visualItems->setDirty(false);
820

821
    connect(_visualItems, &QmlObjectListModel::dirtyChanged, this, &MissionController::_dirtyChanged);
822 823
}

824
void MissionController::_deinitAllVisualItems(void)
825
{
826 827
    for (int i=0; i<_visualItems->count(); i++) {
        _deinitVisualItem(qobject_cast<VisualMissionItem*>(_visualItems->get(i)));
828 829
    }

830
    connect(_visualItems, &QmlObjectListModel::dirtyChanged, this, &MissionController::_dirtyChanged);
831 832
}

833
void MissionController::_initVisualItem(VisualMissionItem* visualItem)
834
{
835 836 837
    _visualItems->setDirty(false);

    connect(visualItem, &VisualMissionItem::coordinateChanged,                          this, &MissionController::_itemCoordinateChanged);
838
    connect(visualItem, &VisualMissionItem::specifiesCoordinateChanged,                 this, &MissionController::_recalcWaypointLines);
839 840
    connect(visualItem, &VisualMissionItem::coordinateHasRelativeAltitudeChanged,       this, &MissionController::_recalcWaypointLines);
    connect(visualItem, &VisualMissionItem::exitCoordinateHasRelativeAltitudeChanged,   this, &MissionController::_recalcWaypointLines);
841

842 843 844 845 846 847 848 849
    if (visualItem->isSimpleItem()) {
        // We need to track commandChanged on simple item since recalc has special handling for takeoff command
        SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem);
        if (simpleItem) {
            connect(&simpleItem->missionItem()._commandFact, &Fact::valueChanged, this, &MissionController::_itemCommandChanged);
        } else {
            qWarning() << "isSimpleItem == true, yet not SimpleMissionItem";
        }
850 851 852 853
    } else {
        // We need to track changes of lastSequenceNumber so we can recalc sequence numbers for subsequence items
        ComplexMissionItem* complexItem = qobject_cast<ComplexMissionItem*>(visualItem);
        connect(complexItem, &ComplexMissionItem::lastSequenceNumberChanged, this, &MissionController::_recalcSequence);
854
    }
855 856
}

857
void MissionController::_deinitVisualItem(VisualMissionItem* visualItem)
858
{
859 860
    // Disconnect all signals
    disconnect(visualItem, 0, 0, 0);
861 862 863 864 865 866 867 868
}

void MissionController::_itemCoordinateChanged(const QGeoCoordinate& coordinate)
{
    Q_UNUSED(coordinate);
    _recalcWaypointLines();
}

869
void MissionController::_itemCommandChanged(void)
870
{
871 872
    _recalcChildItems();
    _recalcWaypointLines();
873 874 875 876
}

void MissionController::_activeVehicleChanged(Vehicle* activeVehicle)
{
877 878
    qCDebug(MissionControllerLog) << "_activeVehicleChanged activeVehicle" << activeVehicle;

879 880
    if (_activeVehicle) {
        MissionManager* missionManager = _activeVehicle->missionManager();
881

882
        disconnect(missionManager, &MissionManager::newMissionItemsAvailable,   this, &MissionController::_newMissionItemsAvailableFromVehicle);
883
        disconnect(missionManager, &MissionManager::inProgressChanged,          this, &MissionController::_inProgressChanged);
884
        disconnect(missionManager, &MissionManager::currentItemChanged,         this, &MissionController::_currentMissionItemChanged);
885 886
        disconnect(_activeVehicle, &Vehicle::homePositionAvailableChanged,      this, &MissionController::_activeVehicleHomePositionAvailableChanged);
        disconnect(_activeVehicle, &Vehicle::homePositionChanged,               this, &MissionController::_activeVehicleHomePositionChanged);
887
        _activeVehicle = NULL;
Don Gagne's avatar
Don Gagne committed
888 889
    }

890
    _activeVehicle = activeVehicle;
891

892 893
    if (_activeVehicle) {
        MissionManager* missionManager = activeVehicle->missionManager();
894

895
        connect(missionManager, &MissionManager::newMissionItemsAvailable,  this, &MissionController::_newMissionItemsAvailableFromVehicle);
896
        connect(missionManager, &MissionManager::inProgressChanged,         this, &MissionController::_inProgressChanged);
897
        connect(missionManager, &MissionManager::currentItemChanged,        this, &MissionController::_currentMissionItemChanged);
898 899 900
        connect(_activeVehicle, &Vehicle::homePositionAvailableChanged,     this, &MissionController::_activeVehicleHomePositionAvailableChanged);
        connect(_activeVehicle, &Vehicle::homePositionChanged,              this, &MissionController::_activeVehicleHomePositionChanged);

901 902 903
        if (!_editMode) {
            removeAllMissionItems();
        }
904 905 906 907

        _activeVehicleHomePositionChanged(_activeVehicle->homePosition());
        _activeVehicleHomePositionAvailableChanged(_activeVehicle->homePositionAvailable());
    }
908 909 910

    // Whenever vehicle changes we need to update syncInProgress
    emit syncInProgressChanged(syncInProgress());
911 912 913 914
}

void MissionController::_activeVehicleHomePositionAvailableChanged(bool homePositionAvailable)
{
915 916 917 918 919 920 921 922 923
    if (!_editMode && _visualItems) {
        SimpleMissionItem* homeItem = qobject_cast<SimpleMissionItem*>(_visualItems->get(0));

        if (homeItem) {
            homeItem->setShowHomePosition(homePositionAvailable);
            _recalcWaypointLines();
        } else {
            qWarning() << "Unabled to cast home item to SimpleMissionItem";
        }
924
    }
925 926 927 928
}

void MissionController::_activeVehicleHomePositionChanged(const QGeoCoordinate& homePosition)
{
929 930
    if (!_editMode && _visualItems) {
        qobject_cast<VisualMissionItem*>(_visualItems->get(0))->setCoordinate(homePosition);
931 932
        _recalcWaypointLines();
    }
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
}

void MissionController::setAutoSync(bool autoSync)
{
    // FIXME: AutoSync temporarily turned off
#if 0
    _autoSync = autoSync;
    emit autoSyncChanged(_autoSync);

    if (_autoSync) {
        _dirtyChanged(true);
    }
#else
    Q_UNUSED(autoSync)
#endif
}

void MissionController::_dirtyChanged(bool dirty)
{
    if (dirty && _autoSync) {
953
        Vehicle* activeVehicle = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle();
954 955 956 957 958 959 960 961 962 963 964 965 966 967

        if (activeVehicle && !activeVehicle->armed()) {
            if (_activeVehicle->missionManager()->inProgress()) {
                _queuedSend = true;
            } else {
                _autoSyncSend();
            }
        }
    }
}

void MissionController::_autoSyncSend(void)
{
    _queuedSend = false;
968
    if (_visualItems) {
969
        sendMissionItems();
970
        _visualItems->setDirty(false);
971 972
    }
}
973

974
void MissionController::_inProgressChanged(bool inProgress)
975
{
976
    emit syncInProgressChanged(inProgress);
977 978 979 980
    if (!inProgress && _queuedSend) {
        _autoSyncSend();
    }
}
981

982
bool MissionController::_findLastAltitude(double* lastAltitude)
983
{
984 985
    bool found = false;
    double foundAltitude;
986

987
    // Don't use home position
988 989
    for (int i=1; i<_visualItems->count(); i++) {
        VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
990

991 992
        if (item->specifiesCoordinate() && !item->isStandaloneCoordinate()) {
            foundAltitude = item->exitCoordinate().altitude();
993
            found = true;
994 995 996
        }
    }

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    if (found) {
        *lastAltitude = foundAltitude;
    }

    return found;
}

bool MissionController::_findLastAcceptanceRadius(double* lastAcceptanceRadius)
{
    bool found = false;
    double foundAcceptanceRadius;

1009 1010
    for (int i=0; i<_visualItems->count(); i++) {
        VisualMissionItem* visualItem = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
1011

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        if (visualItem->isSimpleItem()) {
            SimpleMissionItem* simpleItem = qobject_cast<SimpleMissionItem*>(visualItem);

            if (simpleItem) {
                if ((MAV_CMD)simpleItem->command() == MAV_CMD_NAV_WAYPOINT) {
                    foundAcceptanceRadius = simpleItem->missionItem().param2();
                    found = true;
                }
            } else {
                qWarning() << "isSimpleItem == true, yet not SimpleMissionItem";
            }
1023 1024 1025 1026 1027 1028 1029 1030
        }
    }

    if (found) {
        *lastAcceptanceRadius = foundAcceptanceRadius;
    }

    return found;
1031
}
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

double MissionController::_normalizeLat(double lat)
{
    // Normalize latitude to range: 0 to 180, S to N
    return lat + 90.0;
}

double MissionController::_normalizeLon(double lon)
{
    // Normalize longitude to range: 0 to 360, W to E
    return lon  + 180.0;
}

/// Add the home position item to the front of the list
1046
void MissionController::_addPlannedHomePosition(QmlObjectListModel* visualItems, bool addToCenter)
1047
{
1048 1049
    SimpleMissionItem* homeItem = new SimpleMissionItem(_activeVehicle, this);
    visualItems->insert(0, homeItem);
1050

1051 1052
    if (visualItems->count() > 1  && addToCenter) {
        VisualMissionItem* item = qobject_cast<VisualMissionItem*>(visualItems->get(1));
1053 1054 1055 1056 1057 1058

        double north = _normalizeLat(item->coordinate().latitude());
        double south = north;
        double east = _normalizeLon(item->coordinate().longitude());
        double west = east;

1059 1060
        for (int i=2; i<visualItems->count(); i++) {
            item = qobject_cast<VisualMissionItem*>(visualItems->get(i));
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075

            double lat = _normalizeLat(item->coordinate().latitude());
            double lon = _normalizeLon(item->coordinate().longitude());

            north = fmax(north, lat);
            south = fmin(south, lat);
            east = fmax(east, lon);
            west = fmin(west, lon);
        }

        homeItem->setCoordinate(QGeoCoordinate((south + ((north - south) / 2)) - 90.0, (west + ((east - west) / 2)) - 180.0, 0.0));
    } else {
        homeItem->setCoordinate(qgcApp()->lastKnownHomePosition());
    }
}
1076 1077 1078 1079 1080 1081 1082 1083

void MissionController::_currentMissionItemChanged(int sequenceNumber)
{
    if (!_editMode) {
        if (!_activeVehicle->firmwarePlugin()->sendHomePositionToVehicle()) {
            sequenceNumber++;
        }

1084 1085
        for (int i=0; i<_visualItems->count(); i++) {
            VisualMissionItem* item = qobject_cast<VisualMissionItem*>(_visualItems->get(i));
1086 1087 1088 1089
            item->setIsCurrentItem(item->sequenceNumber() == sequenceNumber);
        }
    }
}
1090

1091 1092
bool MissionController::syncInProgress(void)
{
1093 1094 1095 1096 1097
    if (_activeVehicle) {
        return _activeVehicle->missionManager()->inProgress();
    } else {
        return false;
    }
1098
}