WimaPlaner.cc 23.3 KB
Newer Older
1 2
#include "WimaPlaner.h"

3 4
#include "CircularSurveyComplexItem.h"

5 6


7 8 9 10 11 12
const char* WimaPlaner::wimaFileExtension   = "wima";
const char* WimaPlaner::areaItemsName       = "AreaItems";
const char* WimaPlaner::missionItemsName    = "MissionItems";

WimaPlaner::WimaPlaner(QObject *parent)
    : QObject               (parent)
13
    , _missionReady         (false)
14 15 16
    , _currentAreaIndex     (-1)
    , _container            (nullptr)
    , _joinedArea           (this)
17 18
    , _measurementArea      (this)
    , _serviceArea          (this)
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    , _corridor             (this)
{
    connect(this, &WimaPlaner::currentPolygonIndexChanged, this, &WimaPlaner::recalcPolygonInteractivity);
}

QmlObjectListModel* WimaPlaner::visualItems()
{
    return &_visualItems;
}

QStringList WimaPlaner::loadNameFilters() const
{
    QStringList filters;

    filters << tr("Supported types (*.%1 *.%2)").arg(wimaFileExtension).arg(AppSettings::planFileExtension) <<
               tr("All Files (*.*)");
    return filters;
}

QStringList WimaPlaner::saveNameFilters() const
{
    QStringList filters;

    filters << tr("Supported types (*.%1 *.%2)").arg(wimaFileExtension).arg(AppSettings::planFileExtension);
    return filters;
}

QGeoCoordinate WimaPlaner::joinedAreaCenter() const
{
    return _joinedArea.center();
}

void WimaPlaner::setMasterController(PlanMasterController *masterC)
{
    _masterController = masterC;
    emit masterControllerChanged();
}

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

void WimaPlaner::setCurrentPolygonIndex(int index)
{
    if(index >= 0 && index < _visualItems.count() && index != _currentAreaIndex){
        _currentAreaIndex = index;

        emit currentPolygonIndexChanged(index);
    }
}

void WimaPlaner::setDataContainer(WimaDataContainer *container)
{
74 75
    if (container != nullptr) {
        if (_container != nullptr) {
76
           disconnect(this, &WimaPlaner::missionReadyChanged, _container, &WimaDataContainer::newDataAvailable);
77 78
        }

79
        _container = container;
80
        connect(this, &WimaPlaner::missionReadyChanged, _container, &WimaDataContainer::newDataAvailable);
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

        emit dataContainerChanged();
    }
}

void WimaPlaner::removeArea(int index)
{
    if(index >= 0 && index < _visualItems.count()){
        WimaArea* area = qobject_cast<WimaArea*>(_visualItems.removeAt(index));

        if ( area == nullptr) {
            qWarning("WimaPlaner::removeArea(): nullptr catched, internal error.");
            return;
        }
        area->clear();
96
        area->borderPolygon()->clear();
97 98 99 100 101 102

        emit visualItemsChanged();

        if (_visualItems.count() == 0) {
            // this branch is reached if all items are removed
            // to guarentee proper behavior, _currentAreaIndex must be set to a invalid value, as on constructor init.
103
            resetAllInteractive();
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
            _currentAreaIndex = -1;
            return;
        }

        if(_currentAreaIndex >= _visualItems.count()){
            setCurrentPolygonIndex(_visualItems.count() - 1);
        }else{
            recalcPolygonInteractivity(_currentAreaIndex);
        }
    }else{
        qWarning("Index out of bounds!");
    }

}

119
bool WimaPlaner::addMeasurementArea()
120
{
121 122
    if (!_visualItems.contains(&_measurementArea)) {
        _visualItems.append(&_measurementArea);
123 124 125 126 127 128 129 130 131 132 133 134 135

        int newIndex = _visualItems.count()-1;
        setCurrentPolygonIndex(newIndex);

        emit visualItemsChanged();
        return true;
    } else {
        return false;
    }
}

bool WimaPlaner::addServiceArea()
{
136 137
    if (!_visualItems.contains(&_serviceArea)) {
        _visualItems.append(&_serviceArea);
138 139 140 141 142 143 144 145 146 147 148

        int newIndex = _visualItems.count()-1;
        setCurrentPolygonIndex(newIndex);

        emit visualItemsChanged();
        return true;
    } else {
        return false;
    }
}

149
bool WimaPlaner::addCorridor()
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
{
    if (!_visualItems.contains(&_corridor)) {
        _visualItems.append(&_corridor);

        int newIndex = _visualItems.count()-1;
        setCurrentPolygonIndex(newIndex);

        emit visualItemsChanged();
        return true;
    } else {
        return false;
    }
}

void WimaPlaner::removeAll()
{
    bool changesApplied = false;
    while (_visualItems.count() > 0) {
        removeArea(0);
        changesApplied = true;
    }

    _missionController->removeAll();

    _currentFile = "";

    emit currentFileChanged();
    if ( changesApplied )
         emit visualItemsChanged();
}

bool WimaPlaner::updateMission()
{
183

184 185
    QString errorString;
    setMissionReady(false);
186 187
    #define debug 0

188 189
    if ( !recalcJoinedArea(errorString)) {
        qgcApp()->showMessage(tr(errorString.toLocal8Bit().data()));
190 191 192 193 194 195 196
        return false;
    }

    #if debug
        _visualItems.append(&_joinedArea);
    #endif

Valentin Platzgummer's avatar
Valentin Platzgummer committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    // extract old survey data
    QmlObjectListModel* missionItems        = _missionController->visualItems();
    CircularSurveyComplexItem* OldSurveyPt  = nullptr;

    QGeoCoordinate oldSurveyRef;
    bool oldSurveyExists = false;

    for (int i = 0; i < _missionController->visualItems()->count(); i++) {
        OldSurveyPt = qobject_cast<CircularSurveyComplexItem*>(missionItems->get(i));
        if ( OldSurveyPt != nullptr) {
            oldSurveyRef        = OldSurveyPt->refPoint();
            oldSurveyExists     = true;
            break;
        }

    }

214 215
    // reset visual items
    _missionController->removeAll();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
216
    missionItems        = _missionController->visualItems();
217 218 219 220 221 222 223
    // set home position to serArea center
    MissionSettingsItem* settingsItem= qobject_cast<MissionSettingsItem*>(missionItems->get(0));
    if (settingsItem == nullptr){
        qWarning("WimaPlaner::updateMission(): settingsItem == nullptr");
        return false;
    }
    // set altitudes, temporary measure to solve bugs
224
    QGeoCoordinate center = _serviceArea.center();
225
    center.setAltitude(0);
226 227
    _serviceArea.setCenter(center);
    center = _measurementArea.center();
228
    center.setAltitude(0);
229
    _measurementArea.setCenter(center);
230 231 232 233
    center = _corridor.center();
    center.setAltitude(0);
    _corridor.setCenter(center);
    // set HomePos. to serArea center
234
    settingsItem->setCoordinate(_serviceArea.center());
235 236

    // create take off position item
237
    int sequenceNumber = _missionController->insertSimpleMissionItem(_serviceArea.center(), missionItems->count());
238

239 240 241 242 243 244 245 246
    _missionController->setCurrentPlanViewIndex(sequenceNumber, true);
    SimpleMissionItem* takeOffItem = qobject_cast<SimpleMissionItem*>(missionItems->get(missionItems->count()-1));
    if (takeOffItem == nullptr){
        qWarning("WimaPlaner::updateMission(): takeOffItem == nullptr");
        return false;
    } else {
        takeOffItem->setCoordinate(_serviceArea.center()); //necessary, insertSimpleMissionItem does not copy coordinate (why?)
    }
247 248

    // create survey item, will be extened with more()-> mission types in the future
249 250
    _missionController->insertComplexMissionItem(_missionController->circularSurveyComplexItemName(), _measurementArea.center(), missionItems->count());
    CircularSurveyComplexItem* survey = qobject_cast<CircularSurveyComplexItem*>(missionItems->get(missionItems->count()-1));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
251

252 253 254 255
    if (survey == nullptr){
        qWarning("WimaPlaner::updateMission(): survey == nullptr");
        return false;
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
256 257 258 259 260 261 262
        if ( oldSurveyExists ) {
           survey->setRefPoint(oldSurveyRef);
        } else  {
            survey->setRefPoint(_measurementArea.center());
        }

        survey->setAutoGenerated(true); // prevents reinitialisation from gui
263
        survey->surveyAreaPolygon()->clear();
264
        survey->surveyAreaPolygon()->appendVertices(_measurementArea.coordinateList());
265 266
    }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
267

268
    // calculate path from take off to opArea
269 270 271 272
    if (survey->visualTransectPoints().size() == 0) {
        qWarning("WimaPlaner::updateMission(): survey no points.");
        return false;
    }
273
    QGeoCoordinate start = _serviceArea.center();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
274
    QGeoCoordinate end = survey->coordinate();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
275 276

#ifdef QT_DEBUG
Valentin Platzgummer's avatar
Valentin Platzgummer committed
277 278
    if (!_visualItems.contains(&_joinedArea))
        _visualItems.append(&_joinedArea);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
279
#endif
Valentin Platzgummer's avatar
Valentin Platzgummer committed
280

281
    QList<QGeoCoordinate> path;
282 283
    if ( !calcShortestPath(start, end, path)) {
        qgcApp()->showMessage( QString(tr("Not able to calculate the path from takeoff position to measurement area.")).toLocal8Bit().data());
284 285
        return false;
    }
286
    _arrivalPathLength = path.size()-1; // -1: last item is first measurement point
287 288 289 290 291 292
    for (int i = 1; i < path.count()-1; i++) {
        sequenceNumber = _missionController->insertSimpleMissionItem(path.value(i), missionItems->count()-1);
        _missionController->setCurrentPlanViewIndex(sequenceNumber, true);
    }

    // calculate return path
Valentin Platzgummer's avatar
Valentin Platzgummer committed
293
    start   = survey->exitCoordinate();
294
    end     = _serviceArea.center();
295
    path.clear();
296 297
    if ( !calcShortestPath(start, end, path)) {
        qgcApp()->showMessage(QString(tr("Not able to calculate the path from measurement area to landing position.")).toLocal8Bit().data());
298 299
        return false;
    }
300
    _returnPathLength = path.size()-1; // -1: fist item is last measurement point
301 302 303 304 305 306
    for (int i = 1; i < path.count()-1; i++) {
        sequenceNumber = _missionController->insertSimpleMissionItem(path.value(i), missionItems->count());
        _missionController->setCurrentPlanViewIndex(sequenceNumber, true);
    }

    // create land position item
307
    sequenceNumber = _missionController->insertSimpleMissionItem(_serviceArea.center(), missionItems->count());
308 309 310 311 312 313
    _missionController->setCurrentPlanViewIndex(sequenceNumber, true);
    SimpleMissionItem* landItem = qobject_cast<SimpleMissionItem*>(missionItems->get(missionItems->count()-1));
    if (landItem == nullptr){
        qWarning("WimaPlaner::updateMission(): landItem == nullptr");
        return false;
    } else {
314
        if (!_missionController->setLandCommand(*landItem, *_masterController->controllerVehicle()))
315
            return false;
316 317
    }

318 319
    pushToContainer(); // exchange plan data with the WimaController via the _container
    setMissionReady(true);
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    return true;
}

void WimaPlaner::saveToCurrent()
{
    saveToFile(_currentFile);
}

void WimaPlaner::saveToFile(const QString& filename)
{
    if (filename.isEmpty()) {
        return;
    }

    QString planFilename = filename;
    if (!QFileInfo(filename).fileName().contains(".")) {
        planFilename += QString(".%1").arg(wimaFileExtension);
    }

    QFile file(planFilename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qgcApp()->showMessage(tr("Plan save error %1 : %2").arg(filename).arg(file.errorString()));
        _currentFile.clear();
        emit currentFileChanged();
    } else {
        FileType fileType = FileType::WimaFile;
        if ( planFilename.contains(QString(".%1").arg(wimaFileExtension)) ) {
            fileType = FileType::WimaFile;
        } else if ( planFilename.contains(QString(".%1").arg(AppSettings::planFileExtension)) ) {
            fileType = FileType::PlanFile;
        } else {
            if ( planFilename.contains(".") ) {
                qgcApp()->showMessage(tr("File format not supported"));
            } else {
                qgcApp()->showMessage(tr("File without file extension not accepted."));
                return;
            }
        }

        QJsonDocument saveDoc = saveToJson(fileType);
        file.write(saveDoc.toJson());
        if(_currentFile != planFilename) {
            _currentFile = planFilename;
            emit currentFileChanged();
        }
    }
}

bool WimaPlaner::loadFromCurrent()
{
    return loadFromFile(_currentFile);
}

bool WimaPlaner::loadFromFile(const QString &filename)
{
    #define debug 0
    QString errorString;
    QString errorMessage = tr("Error loading Plan file (%1). %2").arg(filename).arg("%1");

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

    QFileInfo fileInfo(filename);
    QFile file(filename);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        errorString = file.errorString() + QStringLiteral(" ") + filename;
        qgcApp()->showMessage(errorMessage.arg(errorString));
        return false;
    }

    if(fileInfo.suffix() == wimaFileExtension) {
        QJsonDocument   jsonDoc;
        QByteArray      bytes = file.readAll();

        if (!JsonHelper::isJsonFile(bytes, jsonDoc, errorString)) {
            qgcApp()->showMessage(errorMessage.arg(errorString));
            return false;
        }

        QJsonObject json = jsonDoc.object();
        // AreaItems
        QJsonArray areaArray = json[areaItemsName].toArray();
        _visualItems.clear();

        int validAreaCounter = 0;
        for( int i = 0; i < areaArray.size() && validAreaCounter < 3; i++) {
            QJsonObject jsonArea = areaArray[i].toObject();

            if (jsonArea.contains(WimaArea::areaTypeName) && jsonArea[WimaArea::areaTypeName].isString()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
411
                if ( jsonArea[WimaArea::areaTypeName] == WimaMeasurementArea::WimaMeasurementAreaName) {
412 413 414
                    print(_measurementArea);
                    bool success = _measurementArea.loadFromJson(jsonArea, errorString);
                    print(_measurementArea);
415 416 417 418 419 420 421

                    if ( !success ) {
                        qgcApp()->showMessage(errorMessage.arg(errorString));
                        return false;
                    }

                    validAreaCounter++;
422
                    _visualItems.append(&_measurementArea);
423 424
                    emit visualItemsChanged();
                } else if ( jsonArea[WimaArea::areaTypeName] == WimaServiceArea::wimaServiceAreaName) {
425
                    bool success = _serviceArea.loadFromJson(jsonArea, errorString);
426 427 428 429 430 431 432

                    if ( !success ) {
                        qgcApp()->showMessage(errorMessage.arg(errorString));
                        return false;
                    }

                    validAreaCounter++;
433
                    _visualItems.append(&_serviceArea);
434
                    emit visualItemsChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
435
                } else if ( jsonArea[WimaArea::areaTypeName] == WimaCorridor::WimaCorridorName) {
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
                    bool success = _corridor.loadFromJson(jsonArea, errorString);

                    if ( !success ) {
                        qgcApp()->showMessage(errorMessage.arg(errorString));
                        return false;
                    }

                    validAreaCounter++;
                    _visualItems.append(&_corridor);
                    emit visualItemsChanged();
                } else {
                    errorString += QString(tr("%s not supported.\n").arg(WimaArea::areaTypeName));
                    qgcApp()->showMessage(errorMessage.arg(errorString));
                    return false;
                }
            } else {
                errorString += QString(tr("Invalid or non existing entry for %s.\n").arg(WimaArea::areaTypeName));
                return false;
            }
        }

        _currentFile.sprintf("%s/%s.%s", fileInfo.path().toLocal8Bit().data(), fileInfo.completeBaseName().toLocal8Bit().data(), wimaFileExtension);

        emit currentFileChanged();
460
        //recalcJoinedArea();
461

Valentin Platzgummer's avatar
Valentin Platzgummer committed
462
        // MissionItems
463
        // extrac MissionItems part
Valentin Platzgummer's avatar
Valentin Platzgummer committed
464 465 466 467 468 469 470 471 472

//        bool ret = json.contains(missionItemsName);
//        qWarning() << ret;

        QJsonObject missionObject = json[missionItemsName].toObject();

        //qWarning() << json[missionItemsName].type();

        QJsonDocument missionJsonDoc = QJsonDocument(missionObject);
473 474 475 476 477 478 479 480
        // create temporary file with missionItems
        QFile temporaryFile;
        QString cropedFileName = filename.section("/",0,-2);
        #if debug
            qWarning() << cropedFileName;
        #endif
        QString temporaryFileName;
        for (int i = 0; ; i++) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
481 482
            temporaryFileName = cropedFileName + QString("/temp%1.%2").arg(i).arg(AppSettings::planFileExtension);
            // qWarning() << temporaryFileName;
483 484 485 486 487 488 489 490 491 492 493 494 495 496

            if ( !QFile::exists(temporaryFileName) ) {
                temporaryFile.setFileName(temporaryFileName);
                if ( temporaryFile.open(QIODevice::WriteOnly | QIODevice::Text) ) {
                    break;
                }
            }

            if ( i > 1000) {
                qWarning("WimaPlaner::loadFromFile(): not able to create temporary file.");
                return false;
            }
        }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
497
        // qWarning() << missionJsonDoc.toVariant().toString();
498
        temporaryFile.write(missionJsonDoc.toJson());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
499
        temporaryFile.close();
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527

        // load from temporary file
        _masterController->loadFromFile(temporaryFileName);

        // remove temporary file
        if ( !temporaryFile.remove() ){
            qWarning("WimaPlaner::loadFromFile(): not able to remove temporary file.");
        }

        return true;

    } else if ( fileInfo.suffix() == AppSettings::planFileExtension ){
        _masterController->loadFromFile(filename);

        return true;// might be wrong return value
    } else {
        errorString += QString(tr("File extension not supported.\n"));
        qgcApp()->showMessage(errorMessage.arg(errorString));

        return false;
    }
}

void WimaPlaner::recalcPolygonInteractivity(int index)
{
    if (index >= 0 && index < _visualItems.count()) {
        resetAllInteractive();
        WimaArea* interactivePoly = qobject_cast<WimaArea*>(_visualItems.get(index));
528
        interactivePoly->setWimaAreaInteractive(true);
529 530 531
    }
}

532
bool WimaPlaner::recalcJoinedArea(QString &errorString)
533
{
534
    // check if area paths form simple polygons
535
    if ( !_serviceArea.isSimplePolygon() ) {
536 537 538 539
        errorString.append(tr("Service area is self intersecting and thus not a simple polygon. Only simple polygons allowed.\n"));
        return false;
    }

540
    if ( !_corridor.isSimplePolygon() && _corridor.count() > 0) {
541 542 543 544
        errorString.append(tr("Corridor is self intersecting and thus not a simple polygon. Only simple polygons allowed.\n"));
        return false;
    }

545
    if ( !_measurementArea.isSimplePolygon() ) {
546 547 548 549
        errorString.append(tr("Measurement area is self intersecting and thus not a simple polygon. Only simple polygons allowed.\n"));
        return false;
    }

550
    _joinedArea.setPath(_serviceArea.path());
551
    _joinedArea.join(_corridor);
552
    if ( !_joinedArea.join(_measurementArea) ) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
553
        errorString.append(tr("Not able to join areas. Service area and measurement"
554
                           " must have a overlapping section, or be connected through a corridor."));
555
        return false; // this happens if all areas are pairwise disjoint
556
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
557 558
    // join service area, op area and corridor
    return true;
559 560
}

561 562 563 564 565 566 567
/*!
 * \fn void WimaPlaner::pushToContainer()
 * Pushes the \c WimaPlanData object generated by \c toPlanData() to the \c WimaDataContainer.
 * Should be called only after \c updateMission() was successful.
 *
 * \sa WimaDataContainer, WimaPlanData
 */
568 569 570
void WimaPlaner::pushToContainer()
{
    if (_container != nullptr) {
571 572
        WimaPlanData planData = toPlanData();
        _container->push(planData);
573 574 575 576 577
    } else {
        qWarning("WimaPlaner::uploadToContainer(): no container assigned.");
    }
}

578 579 580 581 582 583
bool WimaPlaner::calcShortestPath(const QGeoCoordinate &start, const QGeoCoordinate &destination, QList<QGeoCoordinate> &path)
{
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
    QList<QPointF> path2D;
    bool retVal = PolygonCalculus::shortestPath(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
584
                                   toQPolygonF(toCartesian2D(_joinedArea.coordinateList(), /*origin*/ start)),
585
                                   /*start point*/ QPointF(0,0),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
586 587
                                   /*destination*/ toCartesian2D(destination, start),
                                   /*shortest path*/ path2D);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
588
    path.append(toGeo(path2D, /*origin*/ start));
589 590 591 592

    return  retVal;
}

593
void WimaPlaner::resetAllInteractive()
594
{
595 596 597 598 599
    // Marks all areas as inactive (area.interactive == false)
    int itemCount = _visualItems.count();
    if (itemCount > 0){
        for (int i = 0; i < itemCount; i++) {
            WimaArea* iteratorPoly = qobject_cast<WimaArea*>(_visualItems.get(i));
600
            iteratorPoly->setWimaAreaInteractive(false);
601 602 603 604 605 606 607 608 609
        }
    }
}

void WimaPlaner::setInteractive()
{
    recalcPolygonInteractivity(_currentAreaIndex);
}

610 611 612 613 614 615 616 617 618 619 620 621
/*!
 * \fn WimaPlanData WimaPlaner::toPlanData()
 *
 * Returns a \c WimaPlanData object containing information about the current mission.
 * The \c WimaPlanData object holds only the data which is relevant for the \c WimaController class.
 * Should only be called if updateMission() was successful.
 *
 * \sa WimaController, WimaPlanData
 */
WimaPlanData WimaPlaner::toPlanData()
{
    WimaPlanData planData;
622 623

    // store areas
624 625 626
    planData.append(WimaMeasurementAreaData(_measurementArea));
    planData.append(WimaServiceAreaData(_serviceArea));
    planData.append(WimaCorridorData(_corridor));
627
    planData.append(WimaJoinedAreaData(_joinedArea));
628

629 630 631
    // convert mission items to mavlink commands
    QList<MissionItem*> rgMissionItems;
    MissionController::convertToMissionItems(_missionController->visualItems(), rgMissionItems, this);
632

633
    // add const qualifier...
634
    QList<const MissionItem*> rgMissionItemsConst;
635 636 637 638
    for (int i = _arrivalPathLength + 1; i < rgMissionItems.size() - _returnPathLength; i++) { // i = _arrivalPathLength + 1: + 1 = MissionSettingsItem ...
        rgMissionItemsConst.append(rgMissionItems.value(i));
    }

639 640
    // store mavlink commands
    planData.append(rgMissionItemsConst);
641 642

    return planData;
643 644 645 646 647 648 649 650 651 652 653 654
}

void WimaPlaner::setMissionReady(bool ready)
{
    if(_missionReady != ready)
    {
        _missionReady = ready;

        emit missionReadyChanged(_missionReady);
    }
}

655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
QJsonDocument WimaPlaner::saveToJson(FileType fileType)
{
    /// This function save all areas (of WimaPlaner) and all mission items (of MissionController) to a QJsonDocument
    /// @param fileType is either WimaFile or PlanFile (enum), if fileType == PlanFile only mission items are stored
    QJsonObject json;

    if ( fileType == FileType::WimaFile ) {
        QJsonArray jsonArray;

        for (int i = 0; i < _visualItems.count(); i++) {
            QJsonObject json;

            WimaArea* area = qobject_cast<WimaArea*>(_visualItems.get(i));

            if (area == nullptr) {
                qWarning("WimaPlaner::saveToJson(): Internal error, area == nullptr!");
                return QJsonDocument();
            }

            // check the type of area, create and append the JsonObject to the JsonArray once determined
Valentin Platzgummer's avatar
Valentin Platzgummer committed
675
            WimaMeasurementArea* opArea =  qobject_cast<WimaMeasurementArea*>(area);
676 677 678 679 680
            if (opArea != nullptr) {
                opArea->saveToJson(json);
                jsonArray.append(json);
                continue;
            }
681

682 683 684 685 686 687 688
            WimaServiceArea* serArea =  qobject_cast<WimaServiceArea*>(area);
            if (serArea != nullptr) {
                serArea->saveToJson(json);
                jsonArray.append(json);
                continue;
            }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
689
            WimaCorridor* corridor =  qobject_cast<WimaCorridor*>(area);
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
            if (corridor != nullptr) {
                corridor->saveToJson(json);
                jsonArray.append(json);
                continue;
            }

            // if non of the obove branches was trigger, type must be WimaArea
            area->saveToJson(json);
            jsonArray.append(json);
        }

        json[areaItemsName] = jsonArray;
        json[missionItemsName] = _masterController->saveToJson().object();

        return QJsonDocument(json);
    } else if (fileType == FileType::PlanFile) {
        return _masterController->saveToJson();
    }

    return QJsonDocument(json);
710
}
711 712 713