WimaController.cc 40.3 KB
Newer Older
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1
#include "WimaController.h"
2

3 4 5 6 7 8 9 10 11 12
const char* WimaController::wimaFileExtension           = "wima";
const char* WimaController::areaItemsName               = "AreaItems";
const char* WimaController::missionItemsName            = "MissionItems";
const char* WimaController::settingsGroup               = "WimaController";
const char* WimaController::enableWimaControllerName    = "EnableWimaController";
const char* WimaController::overlapWaypointsName        = "OverlapWaypoints";
const char* WimaController::maxWaypointsPerPhaseName    = "MaxWaypointsPerPhase";
const char* WimaController::startWaypointIndexName      = "StartWaypointIndex";
const char* WimaController::showAllMissionItemsName     = "ShowAllMissionItems";
const char* WimaController::showCurrentMissionItemsName = "ShowCurrentMissionItems";
13
const char* WimaController::flightSpeedName             = "FlightSpeed";
14
const char* WimaController::arrivalReturnSpeedName      = "ArrivalReturnSpeed";
15
const char* WimaController::altitudeName                = "Altitude";
16
const char* WimaController::reverseName                 = "Reverse";
17

18
WimaController::WimaController(QObject *parent)
19 20 21 22 23 24 25 26 27 28 29
    : QObject                   (parent)
    , _container                (nullptr)
    , _joinedArea               (this)
    , _measurementArea          (this)
    , _serviceArea              (this)
    , _corridor                 (this)
    , _localPlanDataValid       (false)
    , _metaDataMap              (FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/WimaController.SettingsGroup.json"), this))
    , _enableWimaController     (settingsGroup, _metaDataMap[enableWimaControllerName])
    , _overlapWaypoints         (settingsGroup, _metaDataMap[overlapWaypointsName])
    , _maxWaypointsPerPhase     (settingsGroup, _metaDataMap[maxWaypointsPerPhaseName])
30
    , _nextPhaseStartWaypointIndex       (settingsGroup, _metaDataMap[startWaypointIndexName])
31
    , _showAllMissionItems      (settingsGroup, _metaDataMap[showAllMissionItemsName])
32 33
    , _showCurrentMissionItems  (settingsGroup, _metaDataMap[showCurrentMissionItemsName])    
    , _flightSpeed              (settingsGroup, _metaDataMap[flightSpeedName])
34
    , _arrivalReturnSpeed       (settingsGroup, _metaDataMap[arrivalReturnSpeedName])
35
    , _altitude                 (settingsGroup, _metaDataMap[altitudeName])
36
    , _reverse                  (settingsGroup, _metaDataMap[reverseName])
Valentin Platzgummer's avatar
Valentin Platzgummer committed
37
    , _endWaypointIndex         (0)
38 39
    , _startWaypointIndex       (0)
    , _uploadOverrideRequired   (false)
40 41 42
    , _measurementPathLength              (-1)
    , _arrivalPathLength        (-1)
    , _returnPathLength         (-1)
43 44 45
    , _phaseDistance            (-1)
    , _phaseDuration            (-1)
    , _vehicleHasLowBattery     (false)
46
    , _lowBatteryHandlingTriggered(false)
47
    , _executingSmartRTL        (false)
48

49 50 51
{
    _showAllMissionItems.setRawValue(true);
    _showCurrentMissionItems.setRawValue(true);
52 53 54
    connect(&_overlapWaypoints,             &Fact::rawValueChanged, this, &WimaController::updateNextWaypoint);
    connect(&_maxWaypointsPerPhase,         &Fact::rawValueChanged, this, &WimaController::recalcCurrentPhase);
    connect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
55
    connect(&_flightSpeed,                  &Fact::rawValueChanged, this, &WimaController::updateflightSpeed);
56
    connect(&_arrivalReturnSpeed,           &Fact::rawValueChanged, this, &WimaController::updateArrivalReturnSpeed);
57
    connect(&_altitude,                     &Fact::rawValueChanged, this, &WimaController::updateAltitude);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
58
    connect(&_reverse,                      &Fact::rawValueChanged, this, &WimaController::reverseChangedHandler);
59

60
    // setup low battery handling
61 62
    connect(&_checkBatteryTimer, &QTimer::timeout, this, &WimaController::checkBatteryLevel);
    _checkBatteryTimer.setInterval(500);
63 64 65
    Fact *enableLowBatteryHandling = qgcApp()->toolbox()->settingsManager()->wimaSettings()->enableLowBatteryHandling();
    connect(enableLowBatteryHandling, &Fact::rawValueChanged, this, &WimaController::enableDisableLowBatteryHandling);
    enableDisableLowBatteryHandling(enableLowBatteryHandling->rawValue());
66 67
}

68
QmlObjectVectorModel* WimaController::visualItems()
69
{
70
    return &_visualItems;
71 72
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
73 74 75 76
QStringList WimaController::loadNameFilters() const
{
    QStringList filters;

77
    filters << tr("Supported types (*.%1 *.%2)").arg(wimaFileExtension).arg(AppSettings::planFileExtension) <<
Valentin Platzgummer's avatar
Valentin Platzgummer committed
78 79
               tr("All Files (*.*)");
    return filters;
80 81 82 83 84
}

QStringList WimaController::saveNameFilters() const
{
    QStringList filters;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
85

86 87
    filters << tr("Supported types (*.%1 *.%2)").arg(wimaFileExtension).arg(AppSettings::planFileExtension);
    return filters;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
88 89
}

90
WimaDataContainer *WimaController::dataContainer()
91
{
92
    return _container;
93 94
}

95
QmlObjectVectorModel *WimaController::missionItems()
96 97 98 99
{
    return &_missionItems;
}

100
QmlObjectVectorModel *WimaController::currentMissionItems()
101 102 103 104
{
    return &_currentMissionItems;
}

105 106 107 108 109
QVariantList WimaController::waypointPath()
{
    return  _waypointPath;
}

110 111 112 113 114
QVariantList WimaController::currentWaypointPath()
{
    return _currentWaypointPath;
}

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
Fact *WimaController::enableWimaController()
{
    return &_enableWimaController;
}

Fact *WimaController::overlapWaypoints()
{
    return &_overlapWaypoints;
}

Fact *WimaController::maxWaypointsPerPhase()
{
    return &_maxWaypointsPerPhase;
}

Fact *WimaController::showAllMissionItems()
{
    return &_showAllMissionItems;
}

Fact *WimaController::showCurrentMissionItems()
{
    return &_showCurrentMissionItems;
}

140 141 142 143 144
Fact *WimaController::flightSpeed()
{
    return &_flightSpeed;
}

145 146 147 148 149
Fact *WimaController::arrivalReturnSpeed()
{
    return &_arrivalReturnSpeed;
}

150 151 152 153 154
Fact *WimaController::altitude()
{
    return &_altitude;
}

155 156 157 158 159
Fact *WimaController::reverse()
{
    return &_reverse;
}

160 161 162 163 164
bool WimaController::uploadOverrideRequired() const
{
    return _uploadOverrideRequired;
}

165 166 167 168 169 170 171 172 173 174
double WimaController::phaseDistance() const
{
    return _phaseDistance;
}

double WimaController::phaseDuration() const
{
    return _phaseDuration;
}

175 176 177 178 179
bool WimaController::vehicleHasLowBattery() const
{
    return _vehicleHasLowBattery;
}

180 181
Fact *WimaController::startWaypointIndex()
{
182
    return &_nextPhaseStartWaypointIndex;
183 184
}

185 186 187 188 189 190 191 192 193 194 195 196
void WimaController::setMasterController(PlanMasterController *masterC)
{
    _masterController = masterC;
    emit masterControllerChanged();
}

void WimaController::setMissionController(MissionController *missionC)
{
    _missionController = missionC;
    emit missionControllerChanged();
}

197 198 199 200 201 202
/*!
 * \fn void WimaController::setDataContainer(WimaDataContainer *container)
 * Sets the pointer to the \c WimaDataContainer, which is meant to exchange data between the \c WimaController and the \c WimaPlaner.
 *
 * \sa WimaPlaner, WimaDataContainer, WimaPlanData
 */
203 204
void WimaController::setDataContainer(WimaDataContainer *container)
{
205 206
    if (container != nullptr) {
        if (_container != nullptr) {
207
           disconnect(_container, &WimaDataContainer::newDataAvailable, this, &WimaController::fetchContainerData);
208 209
        }

210
        _container = container;
211
        connect(_container, &WimaDataContainer::newDataAvailable, this, &WimaController::fetchContainerData);
212 213 214 215 216

        emit dataContainerChanged();
    }
}

217 218 219 220 221 222 223 224 225
void WimaController::setUploadOverrideRequired(bool overrideRequired)
{
    if (_uploadOverrideRequired != overrideRequired) {
        _uploadOverrideRequired = overrideRequired;

        emit uploadOverrideRequiredChanged();
    }
}

226 227
void WimaController::nextPhase()
{
228
    calcNextPhase();
229 230
}

231
void WimaController::previousPhase()
Valentin Platzgummer's avatar
Valentin Platzgummer committed
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
{    
    bool reverseBool = _reverse.rawValue().toBool();
    if (!reverseBool){
        int startIndex = _nextPhaseStartWaypointIndex.rawValue().toInt();
        if (startIndex > 0) {
            _nextPhaseStartWaypointIndex.setRawValue(1+std::max(_startWaypointIndex
                                                              - _maxWaypointsPerPhase.rawValue().toInt()
                                                              + _overlapWaypoints.rawValue().toInt(), 0));
        }
    }
    else {
        int startIndex = _nextPhaseStartWaypointIndex.rawValue().toInt();
        if (startIndex <= _missionItems.count()) {
            _nextPhaseStartWaypointIndex.setRawValue(1+std::min(_startWaypointIndex
                                                              + _maxWaypointsPerPhase.rawValue().toInt()
                                                              - _overlapWaypoints.rawValue().toInt(), _missionItems.count()-1));
        }
249
    }
250 251 252 253
}

void WimaController::resetPhase()
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
254 255 256 257 258 259 260
    bool reverseBool = _reverse.rawValue().toBool();
    if (!reverseBool) {
        _nextPhaseStartWaypointIndex.setRawValue(int(1));
    }
    else {
        _nextPhaseStartWaypointIndex.setRawValue(_missionItems.count());
    }
261 262
}

263
bool WimaController::uploadToVehicle()
264
{
265 266
    if (   !_serviceArea.containsCoordinate(_masterController->managerVehicle()->coordinate())
        && _currentMissionItems.count() > 0) {
267 268 269 270 271 272 273 274 275 276
        setUploadOverrideRequired(true);
        return false;
    }

    return forceUploadToVehicle();
}

bool WimaController::forceUploadToVehicle()
{
    setUploadOverrideRequired(false);
277
    if (_currentMissionItems.count() < 1)
278
        return false;
279 280 281 282 283 284 285

    _missionController->removeAll();
    // set homeposition of settingsItem
    QmlObjectListModel* visuals = _missionController->visualItems();
    MissionSettingsItem* settingsItem = visuals->value<MissionSettingsItem *>(0);
    if (settingsItem == nullptr) {
        qWarning("WimaController::updateCurrentMissionItems(): nullptr");
286
        return false;
287 288 289 290 291 292 293 294 295
    }
    settingsItem->setCoordinate(_takeoffLandPostion);

    // copy mission items from _currentMissionItems to _missionController
    for (int i = 0; i < _currentMissionItems.count(); i++){
        SimpleMissionItem *item = _currentMissionItems.value<SimpleMissionItem *>(i);
        _missionController->insertSimpleMissionItem(*item, visuals->count());
    }

296
    _masterController->sendToVehicle();
297 298

    return true;
299
}
300

301 302 303
void WimaController::removeFromVehicle()
{
    _masterController->removeAllFromVehicle();
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    _missionController->removeAll();
}

bool WimaController::checkSmartRTLPreCondition()
{
    QString errorString;
    bool retValue = _checkSmartRTLPreCondition(errorString);
    if (retValue == false) {
        qgcApp()->showMessage(errorString);
        return false;
    }
    return true;
}

bool WimaController::calcReturnPath()
{
    QString errorString;
    bool retValue = _calcReturnPath(errorString);
    if (retValue == false) {
        qgcApp()->showMessage(errorString);
        return false;
    }
    return true;
327 328
}

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
bool WimaController::executeSmartRTL()
{
    QString errorString;
    bool retValue = _executeSmartRTL(errorString);
    if (!retValue) {
        qgcApp()->showMessage(errorString);
    }

    return retValue;
}

bool WimaController::initSmartRTL()
{
    masterController()->managerVehicle()->pauseVehicle();
    QString errorString;
    bool retValue = calcReturnPath();
    if (!retValue)
        return false;
    return true;
}

350
void WimaController::saveToCurrent()
351
{
352

353 354
}

355 356
void WimaController::saveToFile(const QString& filename)
{
357
    QString file = filename;
358 359
}

360
bool WimaController::loadFromCurrent()
361
{
362
    return true;
363 364 365 366
}

bool WimaController::loadFromFile(const QString &filename)
{
367
    QString file = filename;
368
    return true;
369 370 371
}


372

373
QJsonDocument WimaController::saveToJson(FileType fileType)
374
{
375 376 377 378
    if(fileType)
    {

    }
379
    return QJsonDocument();
380 381
}

382
bool WimaController::calcShortestPath(const QGeoCoordinate &start, const QGeoCoordinate &destination, QVector<QGeoCoordinate> &path)
383 384 385
{
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
386
    QVector<QPointF> path2D;
387 388 389 390 391 392 393 394 395 396
    bool retVal = PolygonCalculus::shortestPath(
                                   toQPolygonF(toCartesian2D(_joinedArea.coordinateList(), /*origin*/ start)),
                                   /*start point*/ QPointF(0,0),
                                   /*destination*/ toCartesian2D(destination, start),
                                   /*shortest path*/ path2D);
    path.append(toGeo(path2D, /*origin*/ start));

    return  retVal;
}

397
bool WimaController::extractCoordinateList(QmlObjectVectorModel &missionItems, QVector<QGeoCoordinate> &coordinateList)
398 399 400 401
{
    return extractCoordinateList(missionItems, coordinateList, 0, missionItems.count()-1);
}

402
bool WimaController::extractCoordinateList(QmlObjectVectorModel &missionItems, QVector<QGeoCoordinate> &coordinateList, int startIndex, int endIndex)
403 404 405 406 407 408 409 410 411 412 413 414
{
    if (   startIndex >= 0
        && startIndex < missionItems.count()
        && endIndex >= 0
        && endIndex < missionItems.count()) {
        if (startIndex > endIndex) {
            if (!extractCoordinateList(missionItems, coordinateList, startIndex, missionItems.count()-1))
                return false;
            if (!extractCoordinateList(missionItems, coordinateList, 0, endIndex))
                return false;
        } else {
            for (int i = startIndex; i <= endIndex; i++) {
415
                SimpleMissionItem *mItem = missionItems.value<SimpleMissionItem *>(i);
416 417 418 419 420 421 422 423 424 425 426 427 428 429

                if (mItem == nullptr) {
                    coordinateList.clear();
                    return false;
                }
                coordinateList.append(mItem->coordinate());
            }
        }
    } else
        return false;

    return true;
}

430
bool WimaController::extractCoordinateList(QmlObjectVectorModel &missionItems, QVariantList &coordinateList)
431 432 433 434
{
    return extractCoordinateList(missionItems, coordinateList, 0 , missionItems.count()-1);
}

435
bool WimaController::extractCoordinateList(QmlObjectVectorModel &missionItems, QVariantList &coordinateList, int startIndex, int endIndex)
436
{
437
    QVector<QGeoCoordinate> geoCoordintateList;
438 439 440

    bool retValue = extractCoordinateList(missionItems, geoCoordintateList, startIndex, endIndex);

441 442 443
    if (!retValue)
        return false;

444 445
    for (int i = 0; i < geoCoordintateList.size(); i++) {
        QGeoCoordinate vertex = geoCoordintateList[i];
Valentin Platzgummer's avatar
Valentin Platzgummer committed
446 447
        if (   (qFuzzyIsNull(vertex.latitude()) && qFuzzyIsNull(vertex.longitude()))
            || !vertex.isValid())
448 449 450
            geoCoordintateList.removeAt(i);
    }

451 452 453 454 455 456
    for (auto coordinate : geoCoordintateList)
        coordinateList.append(QVariant::fromValue(coordinate));

    return true;
}

457 458 459 460 461 462 463
/*!
 * \fn void WimaController::containerDataValidChanged(bool valid)
 * Pulls plan data generated by \c WimaPlaner from the \c _container if the data is valid (\a valid equals true).
 * Is connected to the dataValidChanged() signal of the \c WimaDataContainer.
 *
 * \sa WimaDataContainer, WimaPlaner, WimaPlanData
 */
464
bool WimaController::fetchContainerData()
465
{
466
    // fetch only if valid, return true on sucess
467

468 469
    // reset visual items
    _visualItems.clear();
470 471
    _missionItems.clearAndDeleteContents();
    _currentMissionItems.clearAndDeleteContents();
472 473
    _waypointPath.clear();
    _currentWaypointPath.clear();
474

475 476 477 478
    emit visualItemsChanged();
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
479

480
    _localPlanDataValid = false;
481

482 483 484 485
    if (_container == nullptr) {
        qWarning("WimaController::fetchContainerData(): No container assigned!");
        return false;
    }
486

487
    QSharedPointer<const WimaPlanData> planData = _container->pull();
488

489
    // extract list with WimaAreas
490
    QList<const WimaAreaData*> areaList = planData->areaList();
491

492 493 494 495
    int areaCounter = 0;
    int numAreas = 4; // extract only numAreas Areas, if there are more they are invalid and ignored
    for (int i = 0; i < areaList.size(); i++) {
        const WimaAreaData *areaData = areaList[i];
496

497 498 499 500
        if (areaData->type() == WimaServiceAreaData::typeString) { // is it a service area?
            _serviceArea = *qobject_cast<const WimaServiceAreaData*>(areaData);
            areaCounter++;
            _visualItems.append(&_serviceArea);
501

502 503
            continue;
        }
504

505 506 507 508
        if (areaData->type() == WimaMeasurementAreaData::typeString) { // is it a measurement area?
            _measurementArea =  *qobject_cast<const WimaMeasurementAreaData*>(areaData);
            areaCounter++;
            _visualItems.append(&_measurementArea);
509

510
            continue;
511
        }
512

513 514 515 516
        if (areaData->type() == WimaCorridorData::typeString) { // is it a corridor?
            _corridor =  *qobject_cast<const WimaCorridorData*>(areaData);
            areaCounter++;
            //_visualItems.append(&_corridor); // not needed
517

518 519
            continue;
        }
520

521 522 523 524
        if (areaData->type() == WimaJoinedAreaData::typeString) { // is it a corridor?
            _joinedArea =  *qobject_cast<const WimaJoinedAreaData*>(areaData);
            areaCounter++;
            _visualItems.append(&_joinedArea);
525

526 527
            continue;
        }
528

529 530 531
        if (areaCounter >= numAreas)
            break;
    }
532

533
    // extract mission items
534
    QList<QSharedPointer<const MissionItem>> tempMissionItems = planData->missionItems();
535 536
    if (tempMissionItems.size() < 1)
        return false;
537

538 539 540 541 542 543
    // create mission items
    _missionController->removeAll();
    QmlObjectListModel* missionControllerVisualItems = _missionController->visualItems();

    // create SimpleMissionItem by using _missionController
    for ( int i = 0; i < tempMissionItems.size(); i++) {
544
        _missionController->insertSimpleMissionItem(*tempMissionItems[i], missionControllerVisualItems->count());
545 546 547 548 549 550 551
    }
    // copy mission items from _missionController to _missionItems
    for ( int i = 1; i < missionControllerVisualItems->count(); i++) {
        SimpleMissionItem *visualItem     = qobject_cast<SimpleMissionItem *>((*missionControllerVisualItems)[i]);
        if (visualItem == nullptr) {
            qWarning("WimaController::fetchContainerData(): Nullptr at SimpleMissionItem!");
            return false;
552
        }
553 554 555 556 557
        SimpleMissionItem *visualItemCopy = new SimpleMissionItem(*visualItem, true, this);
        _missionItems.append(visualItemCopy);
    }
    if (areaCounter != numAreas)
        return false;
558

559 560
    if (!setTakeoffLandPosition())
        return false;
561

562
    updateWaypointPath();
563

564 565
    // set _nextPhaseStartWaypointIndex to 1
    disconnect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
566 567
    bool reverse = _reverse.rawValue().toBool();
    _nextPhaseStartWaypointIndex.setRawValue(reverse? _missionItems.count() : int(1));
568
    connect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
569

570
    /*
571 572
    if(!calcNextPhase())
        return false;
573
    */
574

575 576

    emit visualItemsChanged();
577
    emit missionItemsChanged();
578

579 580 581

    _localPlanDataValid = true;
    return true;
582 583
}

584
bool WimaController::calcNextPhase()
585
{
586
    auto start = std::chrono::high_resolution_clock::now();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
587 588 589
    if (_missionItems.count() < 1) {
        _startWaypointIndex = 0;
        _endWaypointIndex = 0;
590
        return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
591
    }
592

593
    _currentMissionItems.clearAndDeleteContents();
594 595 596 597
    _currentWaypointPath.clear();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
598 599 600 601
    bool reverse = _reverse.rawValue().toBool(); // Reverses the phase direction. Phases go from high to low waypoint numbers, if true.
    int startIndex = _nextPhaseStartWaypointIndex.rawValue().toInt()-1;
    if (!reverse) {
        if (startIndex > _missionItems.count()-1)
602 603 604
            return false;
    }
    else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
605
        if (startIndex < 0)
606
            return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
607 608
    }    
    _startWaypointIndex = startIndex;
609

Valentin Platzgummer's avatar
Valentin Platzgummer committed
610
    int maxWaypointsPerPhase = _maxWaypointsPerPhase.rawValue().toInt();
611
    // determine end waypoint index
Valentin Platzgummer's avatar
Valentin Platzgummer committed
612 613 614
    bool lastMissionPhaseReached = false;
    if (!reverse) {
        _endWaypointIndex = std::min(_startWaypointIndex + maxWaypointsPerPhase - 1, _missionItems.count()-1);
615
        if (_endWaypointIndex == _missionItems.count() - 1)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
616
            lastMissionPhaseReached = true;
617 618
    }
    else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
619
        _endWaypointIndex = std::max(_startWaypointIndex - maxWaypointsPerPhase + 1, 0);
620
        if (_endWaypointIndex == 0)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
621
            lastMissionPhaseReached = true;
622 623
    }

624

625
    // extract waypoints
626
    QVector<QGeoCoordinate> CSWpList; // list with potential waypoints (from _missionItems), for _currentMissionItems
627

Valentin Platzgummer's avatar
Valentin Platzgummer committed
628
    if (!reverse) {
629
        if (!extractCoordinateList(_missionItems, CSWpList, _startWaypointIndex, _endWaypointIndex)) {
630 631 632 633
            qWarning("WimaController::calcNextPhase(): error on waypoint extraction.");
            return false;
        }
    } else {
634
        if (!extractCoordinateList(_missionItems, CSWpList, _endWaypointIndex, _startWaypointIndex)) {
635 636 637 638 639
            qWarning("WimaController::calcNextPhase(): error on waypoint extraction.");
            return false;
        }

        // reverse path
640 641
        QVector<QGeoCoordinate> reversePath;
        for (QGeoCoordinate c : CSWpList)
642
            reversePath.prepend(c);
643 644
        CSWpList.clear();
        CSWpList.append(reversePath);
645
    }
646

647

648 649 650 651 652 653
    // calculate phase length
    _measurementPathLength = 0;
    for (int i = 0; i < CSWpList.size()-1; ++i)
        _measurementPathLength += CSWpList[i].distanceTo(CSWpList[i+1]);


654
    // set start waypoint index for next phase
Valentin Platzgummer's avatar
Valentin Platzgummer committed
655
    if (!lastMissionPhaseReached) {
656
        disconnect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
657
        if (!reverse) {
658 659 660 661 662 663 664 665 666
            int untruncated = std::max(_endWaypointIndex + 1 - _overlapWaypoints.rawValue().toInt(), 0);
            int truncated   = std::min(untruncated , _missionItems.count()-1);
            _nextPhaseStartWaypointIndex.setRawValue(truncated  + 1);
        }
        else {
            int untruncated = std::min(_endWaypointIndex - 1 + _overlapWaypoints.rawValue().toInt(), _missionItems.count()-1);
            int truncated   = std::max(untruncated , 0);
            _nextPhaseStartWaypointIndex.setRawValue(truncated  + 1);
        }
667
        connect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
668
    }
669 670

    // calculate path from home to first waypoint
671
    QVector<QGeoCoordinate> arrivalPath;
672 673 674 675
    if (!_takeoffLandPostion.isValid()){
        qWarning("WimaController::calcNextPhase(): _takeoffLandPostion not valid.");
        return false;
    }
676
    if ( !calcShortestPath(_takeoffLandPostion, CSWpList.first(), arrivalPath) ) {
677 678
        qWarning("WimaController::calcNextPhase(): Not able to calc path from home to first waypoint.");
        return false;
679
    }
680 681 682 683 684 685

    // calculate arrival path length
    _arrivalPathLength = 0;
    for (int i = 0; i < arrivalPath.size()-1; ++i)
        _arrivalPathLength += arrivalPath[i].distanceTo(arrivalPath[i+1]);

686
    arrivalPath.removeFirst();
687
    //arrivalPath.removeLast();
688 689

    // calculate path from last waypoint to home
690 691
    QVector<QGeoCoordinate> returnPath;
    if ( !calcShortestPath(CSWpList.last(), _takeoffLandPostion, returnPath) ) {
692 693
        qWarning("WimaController::calcNextPhase(): Not able to calc path from home to first waypoint.");
        return false;
694 695 696 697 698 699 700
    }

    // calculate arrival path length
    _returnPathLength = 0;
    for (int i = 0; i < returnPath.size()-1; ++i)
        _returnPathLength += returnPath[i].distanceTo(returnPath[i+1]);

701 702
    returnPath.removeFirst();
    returnPath.removeLast();
703

704

705

706 707 708
    // create Mission Items
    _missionController->removeAll();
    QmlObjectListModel* missionControllerVisuals = _missionController->visualItems();
709 710 711 712

    // set homeposition of settingsItem
    MissionSettingsItem* settingsItem = missionControllerVisuals->value<MissionSettingsItem *>(0);
    if (settingsItem == nullptr) {
713 714
        qWarning("WimaController::calcNextPhase(): nullptr");
        return false;
715 716 717
    }
    settingsItem->setCoordinate(_takeoffLandPostion);

718
    // set takeoff position for first mission item (bug)
719
    missionController()->insertSimpleMissionItem(_takeoffLandPostion, 1);
720 721 722 723
    SimpleMissionItem *takeoffItem = missionControllerVisuals->value<SimpleMissionItem*>(1);
    if (takeoffItem == nullptr) {
        qWarning("WimaController::calcNextPhase(): nullptr");
        return false;
724
    }
725
    takeoffItem->setCoordinate(_takeoffLandPostion);
726

727
    // create change speed item, after take off
728 729 730 731 732 733
    _missionController->insertSimpleMissionItem(_takeoffLandPostion, 2);
    SimpleMissionItem *speedItem = missionControllerVisuals->value<SimpleMissionItem*>(2);
    if (speedItem == nullptr) {
        qWarning("WimaController::calcNextPhase(): nullptr");
        return false;
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
734
    speedItem->setCommand(MAV_CMD_DO_CHANGE_SPEED);// set coordinate must be after setCommand (setCommand sets coordinate to zero)
735
    speedItem->setCoordinate(_takeoffLandPostion);
736 737 738 739 740 741 742 743 744 745 746 747 748 749
    speedItem->missionItem().setParam2(_arrivalReturnSpeed.rawValue().toDouble());

    // insert arrival path
    for (auto coordinate : arrivalPath)
        _missionController->insertSimpleMissionItem(coordinate, missionControllerVisuals->count());

    // create change speed item, after arrival path
    int index = missionControllerVisuals->count();
    _missionController->insertSimpleMissionItem(CSWpList.first(), index);
    speedItem = missionControllerVisuals->value<SimpleMissionItem*>(index);
    if (speedItem == nullptr) {
        qWarning("WimaController::calcNextPhase(): nullptr");
        return false;
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
750
    speedItem->setCommand(MAV_CMD_DO_CHANGE_SPEED); // set coordinate must be after setCommand (setCommand sets coordinate to zero)
751
    speedItem->setCoordinate(CSWpList.first());
752 753
    speedItem->missionItem().setParam2(_flightSpeed.rawValue().toDouble());

754 755 756 757 758 759 760 761 762 763 764 765
    // insert Circular Survey coordinates
    for (auto coordinate : CSWpList)
        _missionController->insertSimpleMissionItem(coordinate, missionControllerVisuals->count());

    // create change speed item, after circular survey
    index = missionControllerVisuals->count();
    _missionController->insertSimpleMissionItem(CSWpList.last(), index);
    speedItem = missionControllerVisuals->value<SimpleMissionItem*>(index);
    if (speedItem == nullptr) {
        qWarning("WimaController::calcNextPhase(): nullptr");
        return false;
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
766 767
    speedItem->setCommand(MAV_CMD_DO_CHANGE_SPEED); // set coordinate must be after setCommand (setCommand sets coordinate to zero)
    speedItem->setCoordinate(CSWpList.last());
768 769 770 771 772
    speedItem->missionItem().setParam2(_arrivalReturnSpeed.rawValue().toDouble());

    // insert return path coordinates
    for (auto coordinate : returnPath)
        _missionController->insertSimpleMissionItem(coordinate, missionControllerVisuals->count());
773 774

    // set land command for last mission item
775 776 777
    index = missionControllerVisuals->count();
    _missionController->insertSimpleMissionItem(_takeoffLandPostion, index);
    SimpleMissionItem *landItem = missionControllerVisuals->value<SimpleMissionItem*>(index);
778
    if (landItem == nullptr) {
779 780
        qWarning("WimaController::calcNextPhase(): nullptr");
        return false;
781
    }
782
    _missionController->setLandCommand(*landItem);
783

784
    // copy to _currentMissionItems
785 786 787
    for ( int i = 1; i < missionControllerVisuals->count(); i++) {
        SimpleMissionItem *visualItem     = missionControllerVisuals->value<SimpleMissionItem*>(i);
        if (visualItem == nullptr) {
788
            qWarning("WimaController::calcNextPhase(): Nullptr at SimpleMissionItem!");
789
            _currentMissionItems.clear();
790
            return false;
791
        }
792

793
        SimpleMissionItem *visualItemCopy = new SimpleMissionItem(*visualItem, true, this);
794 795
        _currentMissionItems.append(visualItemCopy);
    }
796

797 798 799 800
    _setPhaseDistance(_measurementPathLength + _arrivalPathLength + _returnPathLength);
    _setPhaseDuration(_measurementPathLength/_flightSpeed.rawValue().toDouble()
                      + (_arrivalPathLength + _returnPathLength)
                      / _arrivalReturnSpeed.rawValue().toDouble());
801
    _missionController->removeAll(); // remove items from _missionController, will be added on upload
802
    updateAltitude();
803

804
    updateCurrentPath();
805
    emit currentMissionItemsChanged();
806

807 808 809 810
    qWarning() << "WimaController::calcNextPhase()"
               << std::chrono::duration_cast<std::chrono::milliseconds>(
                      std::chrono::high_resolution_clock::now()-start).count()
               << " ms";
811
    return true;
812
}
813

814 815 816
void WimaController::updateWaypointPath()
{
    _waypointPath.clear();
817
    extractCoordinateList(_missionItems, _waypointPath, 0, _missionItems.count()-1);
818

819 820 821 822 823
    emit waypointPathChanged();
}
void WimaController::updateCurrentPath()
{
    _currentWaypointPath.clear();
824
    extractCoordinateList(_currentMissionItems, _currentWaypointPath, 0, _currentMissionItems.count()-1);
825

826 827
    emit currentWaypointPathChanged();
}
828

829 830 831
void WimaController::updateNextWaypoint()
{
    if (_endWaypointIndex < _missionItems.count()-2) {
832 833 834
        disconnect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
        _nextPhaseStartWaypointIndex.setRawValue(1 + std::max(_endWaypointIndex + 1 - _overlapWaypoints.rawValue().toInt(), 0));
        connect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
835 836 837
    }
}

838 839
void WimaController::recalcCurrentPhase()
{
840 841 842 843
    disconnect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
    _nextPhaseStartWaypointIndex.setRawValue(_startWaypointIndex + 1);    
    connect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
    calcNextPhase();
844 845 846 847 848 849 850 851 852
}

bool WimaController::setTakeoffLandPosition()
{
    _takeoffLandPostion.setAltitude(0);
    _takeoffLandPostion.setLongitude(_serviceArea.center().longitude());
    _takeoffLandPostion.setLatitude(_serviceArea.center().latitude());

    return true;
853 854
}

855
void WimaController::updateflightSpeed()
856
{
857 858 859 860 861 862 863 864 865
    int speedItemCounter = 0;
    for (int i = 0; i < _currentMissionItems.count(); i++) {
        SimpleMissionItem *item = _currentMissionItems.value<SimpleMissionItem *>(i);
        if (item != nullptr && item->command() == MAV_CMD_DO_CHANGE_SPEED) {
            speedItemCounter++;
            if (speedItemCounter == 2) {
                item->missionItem().setParam2(_flightSpeed.rawValue().toDouble());
            }
        }
866
    }
867

868 869 870 871
    _setPhaseDuration(_phaseDistance/_flightSpeed.rawValue().toDouble()
                      + (_arrivalPathLength + _returnPathLength)
                      / _arrivalReturnSpeed.rawValue().toDouble());

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
    if (speedItemCounter != 3)
        qWarning("WimaController::updateflightSpeed(): internal error.");
}

void WimaController::updateArrivalReturnSpeed()
{
    int speedItemCounter = 0;
    for (int i = 0; i < _currentMissionItems.count(); i++) {
        SimpleMissionItem *item = _currentMissionItems.value<SimpleMissionItem *>(i);
        if (item != nullptr && item->command() == MAV_CMD_DO_CHANGE_SPEED) {
            speedItemCounter++;
            if (speedItemCounter != 2) {
                item->missionItem().setParam2(_arrivalReturnSpeed.rawValue().toDouble());
            }
        }
887
    }
888

889 890 891 892
    _setPhaseDuration(_phaseDistance/_flightSpeed.rawValue().toDouble()
                      + (_arrivalPathLength + _returnPathLength)
                      / _arrivalReturnSpeed.rawValue().toDouble());

893 894 895
    if (speedItemCounter != 3)
        qWarning("WimaController::updateArrivalReturnSpeed(): internal error.");

896 897 898 899 900 901 902 903 904 905 906 907 908 909
}

void WimaController::updateAltitude()
{
    for (int i = 0; i < _currentMissionItems.count(); i++) {
        SimpleMissionItem *item = _currentMissionItems.value<SimpleMissionItem *>(i);
        if (item == nullptr) {
            qWarning("WimaController::updateAltitude(): nullptr");
            return;
        }
        item->altitude()->setRawValue(_altitude.rawValue().toDouble());
    }
}

910 911 912
void WimaController::checkBatteryLevel()
{
    Vehicle *managerVehicle = masterController()->managerVehicle();
913 914
    WimaSettings* wimaSettings = qgcApp()->toolbox()->settingsManager()->wimaSettings();
    int batteryThreshold = wimaSettings->lowBatteryThreshold()->rawValue().toInt();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
915
    bool enabled = _enableWimaController.rawValue().toBool();
916

Valentin Platzgummer's avatar
Valentin Platzgummer committed
917 918
    static long attemptCounter = 0;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
919
    if (managerVehicle != nullptr && enabled == true) {
920 921 922 923 924 925 926 927 928
        Fact *battery1percentRemaining = managerVehicle->battery1FactGroup()->getFact(VehicleBatteryFactGroup::_percentRemainingFactName);
        Fact *battery2percentRemaining = managerVehicle->battery2FactGroup()->getFact(VehicleBatteryFactGroup::_percentRemainingFactName);


        if (battery1percentRemaining->rawValue().toDouble() < batteryThreshold
                && battery2percentRemaining->rawValue().toDouble() < batteryThreshold) {
            _setVehicleHasLowBattery(true);
            if (!_lowBatteryHandlingTriggered) {
                QString errorString;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
929 930 931 932 933
                attemptCounter++;
                if (attemptCounter > 3) {
                    _lowBatteryHandlingTriggered = true;
                    attemptCounter = 0;
                }
934 935
                if (_checkSmartRTLPreCondition(errorString) == true) {
                    managerVehicle->pauseVehicle();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
936
                    if (_calcReturnPath(errorString)) {
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
                        emit returnBatteryLowConfirmRequired();
                    } else {
                        qgcApp()->showMessage(tr("Battery level is low. Smart RTL not possible."));
                        qgcApp()->showMessage(errorString);
                    }
                }
            }
        }
        else {
            _setVehicleHasLowBattery(false);
            _lowBatteryHandlingTriggered = false;
        }

    }
}

953 954 955 956 957 958 959 960 961 962 963 964 965
void WimaController::smartRTLCleanUp(bool flying)
{

    if ( !flying) { // vehicle has landed
        if (_executingSmartRTL) {
            _executingSmartRTL = false;
            _loadCurrentMissionItemsFromBuffer();
            _showAllMissionItems.setRawValue(true);
            disconnect(masterController()->managerVehicle(), &Vehicle::flyingChanged, this, &WimaController::smartRTLCleanUp);
        }
    }
}

966 967 968 969 970 971 972 973 974
void WimaController::enableDisableLowBatteryHandling(QVariant enable)
{
    if (enable.toBool()) {
        _checkBatteryTimer.start();
    } else {
        _checkBatteryTimer.stop();
    }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
975 976 977 978 979 980 981 982 983
void WimaController::reverseChangedHandler()
{
    disconnect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
    _nextPhaseStartWaypointIndex.setRawValue(_endWaypointIndex+1);
    connect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged, this, &WimaController::calcNextPhase);

    calcNextPhase();
}

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
void WimaController::_setPhaseDistance(double distance)
{
    if (!qFuzzyCompare(distance, _phaseDistance)) {
        _phaseDistance = distance;

        emit phaseDistanceChanged();
    }
}

void WimaController::_setPhaseDuration(double duration)
{
    if (!qFuzzyCompare(duration, _phaseDuration)) {
        _phaseDuration = duration;

        emit phaseDurationChanged();
    }
}

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
bool WimaController::_checkSmartRTLPreCondition(QString &errorString)
{
    if (!_localPlanDataValid) {
        errorString.append(tr("No WiMA data available. Please define at least a measurement and a service area."));
        return false;
    }
    Vehicle *managerVehicle = masterController()->managerVehicle();
   if (!managerVehicle->flying()) {
        errorString.append(tr("Vehicle is not flying. Smart RTL not available."));
        return false;
   }
1013 1014

   return true;
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
}

bool WimaController::_calcReturnPath(QString &errorSring)
{
    // it is assumed that checkSmartRTLPreCondition() was called first and true was returned


    Vehicle *managerVehicle = masterController()->managerVehicle();

    QGeoCoordinate currentVehiclePosition = managerVehicle->coordinate();
    // check if vehicle inside _joinedArea, this statement is not inside checkSmartRTLPreCondition() because during checkSmartRTLPreCondition() vehicle is not paused yet
    if (!_joinedArea.containsCoordinate(currentVehiclePosition)) {
        errorSring.append(tr("Vehicle not inside joined area. Action not supported."));
        return false;
    }

    // calculate return path
1032
    QVector<QGeoCoordinate> returnPath;
1033 1034 1035 1036 1037 1038 1039 1040
    calcShortestPath(currentVehiclePosition, _takeoffLandPostion, returnPath);
    // successful?
    if (returnPath.isEmpty()) {
        errorSring.append(tr("Not able to calculate return path."));
        return false;
    }
    // qWarning() << "returnPath.size()" << returnPath.size();

1041
    _saveCurrentMissionItemsToBuffer();
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

    // create Mission Items
    removeFromVehicle();
    QmlObjectListModel* missionControllerVisuals = _missionController->visualItems();

    // set homeposition of settingsItem
    MissionSettingsItem* settingsItem = missionControllerVisuals->value<MissionSettingsItem *>(0);
    if (settingsItem == nullptr) {
        qWarning("WimaController: nullptr");
        return false;
    }
    settingsItem->setCoordinate(_takeoffLandPostion);

    // copy from returnPath to _missionController
    QGeoCoordinate speedItemCoordinate = returnPath.first();
    for (auto coordinate : returnPath) {
        _missionController->insertSimpleMissionItem(coordinate, missionControllerVisuals->count());
    }
    //qWarning() << "missionControllerVisuals->count()" << missionControllerVisuals->count();

    // create speed item
    int speedItemIndex = 1;
    _missionController->insertSimpleMissionItem(speedItemCoordinate, speedItemIndex);
    SimpleMissionItem *speedItem = missionControllerVisuals->value<SimpleMissionItem*>(speedItemIndex);
    if (speedItem == nullptr) {
        qWarning("WimaController: nullptr");
        return false;
    }
    speedItem->setCommand(MAV_CMD_DO_CHANGE_SPEED);
1071 1072
    speedItem->setCoordinate(speedItemCoordinate);
    speedItem->missionItem().setParam2(_arrivalReturnSpeed.rawValue().toDouble());
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

    // set second item command to ordinary waypoint (is takeoff)
    SimpleMissionItem *secondItem = missionControllerVisuals->value<SimpleMissionItem*>(2);
    if (secondItem == nullptr) {
        qWarning("WimaController: nullptr");
        return false;
    }
    secondItem->setCoordinate(speedItemCoordinate);
    secondItem->setCommand(MAV_CMD_NAV_WAYPOINT);


    // set land command for last mission item
    SimpleMissionItem *landItem = missionControllerVisuals->value<SimpleMissionItem*>(missionControllerVisuals->count()-1);
    if (landItem == nullptr) {
        qWarning("WimaController: nullptr");
        return false;
    }
    _missionController->setLandCommand(*landItem);

    // copy to _currentMissionItems
    //qWarning() << "_currentMissionItems.count()" << _currentMissionItems.count();
    for ( int i = 1; i < missionControllerVisuals->count(); i++) {
        SimpleMissionItem *visualItem     = missionControllerVisuals->value<SimpleMissionItem*>(i);
        if (visualItem == nullptr) {
            qWarning("WimaController: Nullptr at SimpleMissionItem!");
            _currentMissionItems.clear();
            return false;
        }

        SimpleMissionItem *visualItemCopy = new SimpleMissionItem(*visualItem, true, this);
        _currentMissionItems.append(visualItemCopy);
    }
    //qWarning() << "_currentMissionItems.count()" << _currentMissionItems.count();

1107 1108 1109 1110
    _setPhaseDistance(_phaseDistance + _arrivalPathLength + _returnPathLength);
    _setPhaseDuration(_phaseDistance/_flightSpeed.rawValue().toDouble()
                      + (_arrivalPathLength + _returnPathLength)
                      / _arrivalReturnSpeed.rawValue().toDouble());
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    _missionController->removeAll(); // remove items from _missionController, will be added on upload
    updateAltitude();

    updateCurrentPath();
    emit currentMissionItemsChanged();


    //qWarning() << "_currentMissionItems.count()" << _currentMissionItems.count();
    _showAllMissionItems.setRawValue(false);
    managerVehicle->trajectoryPoints()->clear();

    emit uploadAndExecuteConfirmRequired();
    return true;
}

void WimaController::_setVehicleHasLowBattery(bool batteryLow)
{
    if (_vehicleHasLowBattery != batteryLow) {
        _vehicleHasLowBattery = batteryLow;

        emit vehicleHasLowBatteryChanged();
    }
}

1135 1136
bool WimaController::_executeSmartRTL(QString &errorSring)
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1137
    Q_UNUSED(errorSring)
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    _executingSmartRTL = true;
    connect(masterController()->managerVehicle(), &Vehicle::flyingChanged, this, &WimaController::smartRTLCleanUp);
    forceUploadToVehicle();
    masterController()->managerVehicle()->startMission();

    return true;
}

void WimaController::_loadCurrentMissionItemsFromBuffer()
{
    _currentMissionItems.clear();
    int numItems = _missionItemsBuffer.count();
    for (int i = 0; i < numItems; i++)
        _currentMissionItems.append(_missionItemsBuffer.removeAt(0));
1152 1153

    updateCurrentPath();
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
}


void WimaController::_saveCurrentMissionItemsToBuffer()
{
    _missionItemsBuffer.clear();
    int numCurrentMissionItems = _currentMissionItems.count();
    for (int i = 0; i < numCurrentMissionItems; i++)
        _missionItemsBuffer.append(_currentMissionItems.removeAt(0));
}

1165 1166