WimaController.cc 41.7 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
    , _phaseDistance            (-1)
    , _phaseDuration            (-1)
    , _vehicleHasLowBattery     (false)
43
    , _lowBatteryHandlingTriggered(false)
44
    , _executingSmartRTL        (false)
45

46
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
47
    //_nextPhaseStartWaypointIndex.setRawValue(int(1));
48 49
    _showAllMissionItems.setRawValue(true);
    _showCurrentMissionItems.setRawValue(true);
50 51 52
    connect(&_overlapWaypoints,             &Fact::rawValueChanged, this, &WimaController::updateNextWaypoint);
    connect(&_maxWaypointsPerPhase,         &Fact::rawValueChanged, this, &WimaController::recalcCurrentPhase);
    connect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
53
    connect(&_flightSpeed,                  &Fact::rawValueChanged, this, &WimaController::updateflightSpeed);
54
    connect(&_altitude,                     &Fact::rawValueChanged, this, &WimaController::updateAltitude);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
55
    connect(&_reverse,                      &Fact::rawValueChanged, this, &WimaController::reverseChangedHandler);
56

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

65
QmlObjectListModel* WimaController::visualItems()
66
{
67
    return &_visualItems;
68 69
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
70 71 72 73
QStringList WimaController::loadNameFilters() const
{
    QStringList filters;

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

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

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

87
WimaDataContainer *WimaController::dataContainer()
88
{
89
    return _container;
90 91
}

92 93 94 95 96
QmlObjectListModel *WimaController::missionItems()
{
    return &_missionItems;
}

97 98 99 100 101
QmlObjectListModel *WimaController::currentMissionItems()
{
    return &_currentMissionItems;
}

102 103 104 105 106
QVariantList WimaController::waypointPath()
{
    return  _waypointPath;
}

107 108 109 110 111
QVariantList WimaController::currentWaypointPath()
{
    return _currentWaypointPath;
}

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
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;
}

137 138 139 140 141
Fact *WimaController::flightSpeed()
{
    return &_flightSpeed;
}

142 143 144 145 146
Fact *WimaController::arrivalReturnSpeed()
{
    return &_arrivalReturnSpeed;
}

147 148 149 150 151
Fact *WimaController::altitude()
{
    return &_altitude;
}

152 153 154 155 156
Fact *WimaController::reverse()
{
    return &_reverse;
}

157 158 159 160 161
bool WimaController::uploadOverrideRequired() const
{
    return _uploadOverrideRequired;
}

162 163 164 165 166 167 168 169 170 171
double WimaController::phaseDistance() const
{
    return _phaseDistance;
}

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

172 173 174 175 176
bool WimaController::vehicleHasLowBattery() const
{
    return _vehicleHasLowBattery;
}

177 178
Fact *WimaController::startWaypointIndex()
{
179
    return &_nextPhaseStartWaypointIndex;
180 181
}

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

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

194 195 196 197 198 199
/*!
 * \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
 */
200 201
void WimaController::setDataContainer(WimaDataContainer *container)
{
202 203
    if (container != nullptr) {
        if (_container != nullptr) {
204
           disconnect(_container, &WimaDataContainer::newDataAvailable, this, &WimaController::fetchContainerData);
205 206
        }

207
        _container = container;
208
        connect(_container, &WimaDataContainer::newDataAvailable, this, &WimaController::fetchContainerData);
209 210 211 212 213

        emit dataContainerChanged();
    }
}

214 215 216 217 218 219 220 221 222
void WimaController::setUploadOverrideRequired(bool overrideRequired)
{
    if (_uploadOverrideRequired != overrideRequired) {
        _uploadOverrideRequired = overrideRequired;

        emit uploadOverrideRequiredChanged();
    }
}

223 224
void WimaController::nextPhase()
{
225
    calcNextPhase();
226 227
}

228
void WimaController::previousPhase()
Valentin Platzgummer's avatar
Valentin Platzgummer committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
{    
    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));
        }
246
    }
247 248 249 250
}

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

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

    return forceUploadToVehicle();
}

bool WimaController::forceUploadToVehicle()
{
    setUploadOverrideRequired(false);
274
    if (_currentMissionItems.count() < 1)
275
        return false;
276 277 278 279 280 281 282

    _missionController->removeAll();
    // set homeposition of settingsItem
    QmlObjectListModel* visuals = _missionController->visualItems();
    MissionSettingsItem* settingsItem = visuals->value<MissionSettingsItem *>(0);
    if (settingsItem == nullptr) {
        qWarning("WimaController::updateCurrentMissionItems(): nullptr");
283
        return false;
284 285 286 287 288 289 290 291 292
    }
    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());
    }

293
    _masterController->sendToVehicle();
294 295

    return true;
296
}
297

298 299 300
void WimaController::removeFromVehicle()
{
    _masterController->removeAllFromVehicle();
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    _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;
324 325
}

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
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;
}

347
void WimaController::saveToCurrent()
348
{
349

350 351
}

352 353
void WimaController::saveToFile(const QString& filename)
{
354
    QString file = filename;
355 356
}

357
bool WimaController::loadFromCurrent()
358
{
359
    return true;
360 361 362 363
}

bool WimaController::loadFromFile(const QString &filename)
{
364
    QString file = filename;
365
    return true;
366 367 368
}


369

370
QJsonDocument WimaController::saveToJson(FileType fileType)
371
{
372 373 374 375
    if(fileType)
    {

    }
376
    return QJsonDocument();
377 378
}

379
bool WimaController::calcShortestPath(const QGeoCoordinate &start, const QGeoCoordinate &destination, QVector<QGeoCoordinate> &path)
380 381 382
{
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
383
    QVector<QPointF> path2D;
384 385 386 387 388 389 390 391 392 393
    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;
}

394
bool WimaController::extractCoordinateList(QmlObjectListModel &missionItems, QVector<QGeoCoordinate> &coordinateList)
395 396 397 398
{
    return extractCoordinateList(missionItems, coordinateList, 0, missionItems.count()-1);
}

399
bool WimaController::extractCoordinateList(QmlObjectListModel &missionItems, QVector<QGeoCoordinate> &coordinateList, int startIndex, int endIndex)
400 401 402 403 404 405 406 407 408 409 410 411
{
    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++) {
412
                SimpleMissionItem *mItem = missionItems.value<SimpleMissionItem *>(i);
413 414 415 416 417 418 419 420 421 422 423 424 425 426

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

    return true;
}

427
bool WimaController::extractCoordinateList(QmlObjectListModel &missionItems, QVariantList &coordinateList)
428 429 430 431
{
    return extractCoordinateList(missionItems, coordinateList, 0 , missionItems.count()-1);
}

432
bool WimaController::extractCoordinateList(QmlObjectListModel &missionItems, QVariantList &coordinateList, int startIndex, int endIndex)
433
{
434
    QVector<QGeoCoordinate> geoCoordintateList;
435 436 437

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

438 439 440
    if (!retValue)
        return false;

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

448 449 450 451 452 453
    for (auto coordinate : geoCoordintateList)
        coordinateList.append(QVariant::fromValue(coordinate));

    return true;
}

454 455 456 457 458 459 460
/*!
 * \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
 */
461
bool WimaController::fetchContainerData()
462
{
463
    // fetch only if valid, return true on sucess
464

465 466
    // reset visual items
    _visualItems.clear();
467 468
    _missionItems.clearAndDeleteContents();
    _currentMissionItems.clearAndDeleteContents();
469 470
    _waypointPath.clear();
    _currentWaypointPath.clear();
471

472 473 474 475
    emit visualItemsChanged();
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
476

477
    _localPlanDataValid = false;
478

479 480 481 482
    if (_container == nullptr) {
        qWarning("WimaController::fetchContainerData(): No container assigned!");
        return false;
    }
483

484
    WimaPlanData planData = _container->pull();
485

486 487
    // extract list with WimaAreas
    QList<const WimaAreaData*> areaList = planData.areaList();
488

489 490 491 492
    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];
493

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

499 500
            continue;
        }
501

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

507
            continue;
508
        }
509

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

515 516
            continue;
        }
517

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

523 524
            continue;
        }
525

526 527 528
        if (areaCounter >= numAreas)
            break;
    }
529

530
    // extract mission items
531
    QList<MissionItem> tempMissionItems = planData.missionItems();
532 533
    if (tempMissionItems.size() < 1)
        return false;
534

535 536 537 538 539 540
    // create mission items
    _missionController->removeAll();
    QmlObjectListModel* missionControllerVisualItems = _missionController->visualItems();

    // create SimpleMissionItem by using _missionController
    for ( int i = 0; i < tempMissionItems.size(); i++) {
541
        _missionController->insertSimpleMissionItem(tempMissionItems[i], missionControllerVisualItems->count());
542 543 544 545 546 547 548
    }
    // 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;
549
        }
550 551 552 553 554
        SimpleMissionItem *visualItemCopy = new SimpleMissionItem(*visualItem, true, this);
        _missionItems.append(visualItemCopy);
    }
    if (areaCounter != numAreas)
        return false;
555

556 557
    if (!setTakeoffLandPosition())
        return false;
558

559
    updateWaypointPath();
560

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

567 568
    if(!calcNextPhase())
        return false;
569

570

571 572

    emit visualItemsChanged();
573
    emit missionItemsChanged();
574

575 576 577

    _localPlanDataValid = true;
    return true;
578 579
}

580
bool WimaController::calcNextPhase()
581
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
582 583 584
    if (_missionItems.count() < 1) {
        _startWaypointIndex = 0;
        _endWaypointIndex = 0;
585
        return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
586
    }
587

588
    _currentMissionItems.clearAndDeleteContents();
589 590 591 592
    _currentWaypointPath.clear();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
593 594 595 596
    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)
597 598 599
            return false;
    }
    else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
600
        if (startIndex < 0)
601
            return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
602 603
    }    
    _startWaypointIndex = startIndex;
604

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

619

620
    // extract waypoints
621
    QVector<QGeoCoordinate> CSWpList; // list with potential waypoints (from _missionItems), for _currentMissionItems
622

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

        // reverse path
635 636
        QVector<QGeoCoordinate> reversePath;
        for (QGeoCoordinate c : CSWpList)
637
            reversePath.prepend(c);
638 639
        CSWpList.clear();
        CSWpList.append(reversePath);
640
    }
641

642

643
    // set start waypoint index for next phase
Valentin Platzgummer's avatar
Valentin Platzgummer committed
644
    if (!lastMissionPhaseReached) {
645
        disconnect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
646
        if (!reverse) {
647 648 649 650 651 652 653 654 655
            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);
        }
656
        connect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
657
    }
658 659

    // calculate path from home to first waypoint
660
    QVector<QGeoCoordinate> arrivalPath;
661 662 663 664
    if (!_takeoffLandPostion.isValid()){
        qWarning("WimaController::calcNextPhase(): _takeoffLandPostion not valid.");
        return false;
    }
665
    if ( !calcShortestPath(_takeoffLandPostion, CSWpList.first(), arrivalPath) ) {
666 667
        qWarning("WimaController::calcNextPhase(): Not able to calc path from home to first waypoint.");
        return false;
668
    }
669 670
    arrivalPath.removeFirst();
    arrivalPath.removeLast();
671 672

    // calculate path from last waypoint to home
673 674
    QVector<QGeoCoordinate> returnPath;
    if ( !calcShortestPath(CSWpList.last(), _takeoffLandPostion, returnPath) ) {
675 676
        qWarning("WimaController::calcNextPhase(): Not able to calc path from home to first waypoint.");
        return false;
677 678 679 680
    }    
    int returnPathLength = returnPath.size()-2;
    returnPath.removeFirst();
    returnPath.removeLast();
681

682

683 684 685
    // create Mission Items
    _missionController->removeAll();
    QmlObjectListModel* missionControllerVisuals = _missionController->visualItems();
686 687 688 689

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
695 696 697 698 699 700 701 702 703 704
//    qDebug("homeposition");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

705
    // set takeoff position for first mission item (bug)
706
    missionController()->insertSimpleMissionItem(_takeoffLandPostion, 1);
707 708 709 710
    SimpleMissionItem *takeoffItem = missionControllerVisuals->value<SimpleMissionItem*>(1);
    if (takeoffItem == nullptr) {
        qWarning("WimaController::calcNextPhase(): nullptr");
        return false;
711
    }
712
    takeoffItem->setCoordinate(_takeoffLandPostion);
713

Valentin Platzgummer's avatar
Valentin Platzgummer committed
714 715 716 717 718 719 720 721 722 723
//    qDebug("takeoff");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

724
    // create change speed item, after take off
725 726 727 728 729 730
    _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
731
    speedItem->setCommand(MAV_CMD_DO_CHANGE_SPEED);// set coordinate must be after setCommand (setCommand sets coordinate to zero)
732
    speedItem->setCoordinate(_takeoffLandPostion);
733 734
    speedItem->missionItem().setParam2(_arrivalReturnSpeed.rawValue().toDouble());

Valentin Platzgummer's avatar
Valentin Platzgummer committed
735 736 737 738 739 740 741 742 743 744
//    qDebug("speed");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
749 750 751 752 753 754 755 756 757 758
//    qDebug("arrival");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

759 760 761 762 763 764 765 766
    // 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
767
    speedItem->setCommand(MAV_CMD_DO_CHANGE_SPEED); // set coordinate must be after setCommand (setCommand sets coordinate to zero)
768
    speedItem->setCoordinate(CSWpList.first());
769 770
    speedItem->missionItem().setParam2(_flightSpeed.rawValue().toDouble());

Valentin Platzgummer's avatar
Valentin Platzgummer committed
771 772 773 774 775 776 777 778 779 780
//    qDebug("speed");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

781 782 783 784
    // insert Circular Survey coordinates
    for (auto coordinate : CSWpList)
        _missionController->insertSimpleMissionItem(coordinate, missionControllerVisuals->count());

Valentin Platzgummer's avatar
Valentin Platzgummer committed
785 786 787 788 789 790 791 792 793 794
//    qDebug("survey");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

795 796 797 798 799 800 801 802
    // 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
803 804
    speedItem->setCommand(MAV_CMD_DO_CHANGE_SPEED); // set coordinate must be after setCommand (setCommand sets coordinate to zero)
    speedItem->setCoordinate(CSWpList.last());
805 806
    speedItem->missionItem().setParam2(_arrivalReturnSpeed.rawValue().toDouble());

Valentin Platzgummer's avatar
Valentin Platzgummer committed
807 808 809 810 811 812 813 814 815 816
//    qDebug("speed");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

817 818 819
    // insert return path coordinates
    for (auto coordinate : returnPath)
        _missionController->insertSimpleMissionItem(coordinate, missionControllerVisuals->count());
820

Valentin Platzgummer's avatar
Valentin Platzgummer committed
821 822 823 824 825 826 827 828 829 830
//    qDebug("return path");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

831
    // set land command for last mission item
832 833 834
    index = missionControllerVisuals->count();
    _missionController->insertSimpleMissionItem(_takeoffLandPostion, index);
    SimpleMissionItem *landItem = missionControllerVisuals->value<SimpleMissionItem*>(index);
835
    if (landItem == nullptr) {
836 837
        qWarning("WimaController::calcNextPhase(): nullptr");
        return false;
838
    }
839
    _missionController->setLandCommand(*landItem);
840

Valentin Platzgummer's avatar
Valentin Platzgummer committed
841 842 843 844 845 846 847 848 849 850
//    qDebug("land");
//    for (int i = 0; i < missionControllerVisuals->count(); ++i) {
//        VisualMissionItem *item =  missionControllerVisuals->value<VisualMissionItem*>(i);
//        if (item != nullptr) {
//            qDebug() << item->coordinate();
//        } else {
//            qDebug("Error");
//        }
//    }

851
    // copy to _currentMissionItems
852 853 854
    for ( int i = 1; i < missionControllerVisuals->count(); i++) {
        SimpleMissionItem *visualItem     = missionControllerVisuals->value<SimpleMissionItem*>(i);
        if (visualItem == nullptr) {
855
            qWarning("WimaController::calcNextPhase(): Nullptr at SimpleMissionItem!");
856
            _currentMissionItems.clear();
857
            return false;
858
        }
859

860
        SimpleMissionItem *visualItemCopy = new SimpleMissionItem(*visualItem, true, this);
861 862
        _currentMissionItems.append(visualItemCopy);
    }
863

864 865
    _setPhaseDistance(_missionController->missionDistance());
    _setPhaseDuration(_missionController->missionDistance()/_flightSpeed.rawValue().toDouble());
866
    _missionController->removeAll(); // remove items from _missionController, will be added on upload
867
    updateAltitude();
868

869
    updateCurrentPath();
870
    emit currentMissionItemsChanged();
871 872

    return true;
873
}
874

875 876 877
void WimaController::updateWaypointPath()
{
    _waypointPath.clear();
878
    extractCoordinateList(_missionItems, _waypointPath, 0, _missionItems.count()-1);
879

880 881 882 883 884
    emit waypointPathChanged();
}
void WimaController::updateCurrentPath()
{
    _currentWaypointPath.clear();
885
    extractCoordinateList(_currentMissionItems, _currentWaypointPath, 0, _currentMissionItems.count()-1);
886

887 888
    emit currentWaypointPathChanged();
}
889

890 891 892
void WimaController::updateNextWaypoint()
{
    if (_endWaypointIndex < _missionItems.count()-2) {
893 894 895
        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);
896 897 898
    }
}

899 900
void WimaController::recalcCurrentPhase()
{
901 902 903 904
    disconnect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
    _nextPhaseStartWaypointIndex.setRawValue(_startWaypointIndex + 1);    
    connect(&_nextPhaseStartWaypointIndex,   &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
    calcNextPhase();
905 906 907 908 909 910 911 912 913
}

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

    return true;
914 915
}

916
void WimaController::updateflightSpeed()
917
{
918 919 920 921 922 923 924 925 926 927 928
    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());
                _setPhaseDuration(_phaseDistance/_flightSpeed.rawValue().toDouble());
                break;
            }
        }
929
    }
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948

    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());
            }

            if (speedItemCounter == 3)
                break;
        }
949
    }
950 951 952 953

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

954 955 956 957 958 959 960 961 962 963 964 965 966 967
}

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());
    }
}

968 969 970
void WimaController::checkBatteryLevel()
{
    Vehicle *managerVehicle = masterController()->managerVehicle();
971 972
    WimaSettings* wimaSettings = qgcApp()->toolbox()->settingsManager()->wimaSettings();
    int batteryThreshold = wimaSettings->lowBatteryThreshold()->rawValue().toInt();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
973
    bool enabled = _enableWimaController.rawValue().toBool();
974

Valentin Platzgummer's avatar
Valentin Platzgummer committed
975 976
    static long attemptCounter = 0;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
977
    if (managerVehicle != nullptr && enabled == true) {
978 979 980 981 982 983 984 985 986
        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
987 988 989 990 991
                attemptCounter++;
                if (attemptCounter > 3) {
                    _lowBatteryHandlingTriggered = true;
                    attemptCounter = 0;
                }
992 993
                if (_checkSmartRTLPreCondition(errorString) == true) {
                    managerVehicle->pauseVehicle();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
994
                    if (_calcReturnPath(errorString)) {
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
                        emit returnBatteryLowConfirmRequired();
                    } else {
                        qgcApp()->showMessage(tr("Battery level is low. Smart RTL not possible."));
                        qgcApp()->showMessage(errorString);
                    }
                }
            }
        }
        else {
            _setVehicleHasLowBattery(false);
            _lowBatteryHandlingTriggered = false;
        }

    }
}

1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
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);
        }
    }
}

1024 1025 1026 1027 1028 1029 1030 1031 1032
void WimaController::enableDisableLowBatteryHandling(QVariant enable)
{
    if (enable.toBool()) {
        _checkBatteryTimer.start();
    } else {
        _checkBatteryTimer.stop();
    }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1033 1034 1035 1036 1037 1038 1039 1040 1041
void WimaController::reverseChangedHandler()
{
    disconnect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged, this, &WimaController::calcNextPhase);
    _nextPhaseStartWaypointIndex.setRawValue(_endWaypointIndex+1);
    connect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged, this, &WimaController::calcNextPhase);

    calcNextPhase();
}

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
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();
    }
}

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
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;
   }
1071 1072

   return true;
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
}

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
1090
    QVector<QGeoCoordinate> returnPath;
1091 1092 1093 1094 1095 1096 1097 1098
    calcShortestPath(currentVehiclePosition, _takeoffLandPostion, returnPath);
    // successful?
    if (returnPath.isEmpty()) {
        errorSring.append(tr("Not able to calculate return path."));
        return false;
    }
    // qWarning() << "returnPath.size()" << returnPath.size();

1099
    _saveCurrentMissionItemsToBuffer();
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190

    // 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->setCoordinate(speedItemCoordinate);
    speedItem->setCommand(MAV_CMD_DO_CHANGE_SPEED);
    speedItem->missionItem().setParam2(_flightSpeed.rawValue().toDouble());

    // 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();

    _setPhaseDistance(_missionController->missionDistance());
    _setPhaseDuration(_missionController->missionDistance()/_flightSpeed.rawValue().toDouble());
    _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();
    }
}

1191 1192
bool WimaController::_executeSmartRTL(QString &errorSring)
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1193
    Q_UNUSED(errorSring)
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    _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));
1208 1209

    updateCurrentPath();
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
}


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

1221 1222