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

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
    , _dirty                (false)
14 15 16
    , _currentAreaIndex     (-1)
    , _container            (nullptr)
    , _joinedArea           (this)
17 18
    , _measurementArea      (this)
    , _serviceArea          (this)
19
    , _corridor             (this)
20 21
    , _circularSurvey       (nullptr)
    , _surveyRefChanging    (false)
22 23
{
    connect(this, &WimaPlaner::currentPolygonIndexChanged, this, &WimaPlaner::recalcPolygonInteractivity);
24 25 26
    connect(&_updateTimer, &QTimer::timeout, this, &WimaPlaner::updateTimerSlot);
    _updateTimer.setInterval(250); // 250 ms means: max update time 2*250 ms
    _updateTimer.start();
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 74 75 76 77 78
}

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)
{
79 80
    if (container != nullptr) {
        if (_container != nullptr) {
81
           disconnect(this, &WimaPlaner::dirtyChanged, _container, &WimaDataContainer::newDataAvailable);
82 83
        }

84
        _container = container;
85
        connect(this, &WimaPlaner::dirtyChanged, _container, &WimaDataContainer::newDataAvailable);
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

        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();
101
        area->borderPolygon()->clear();
102 103 104 105 106 107

        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.
108
            resetAllInteractive();
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
            _currentAreaIndex = -1;
            return;
        }

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

}

124
bool WimaPlaner::addMeasurementArea()
125
{
126 127
    if (!_visualItems.contains(&_measurementArea)) {
        _visualItems.append(&_measurementArea);
128 129 130 131 132 133 134 135 136 137 138 139 140

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

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

bool WimaPlaner::addServiceArea()
{
141 142
    if (!_visualItems.contains(&_serviceArea)) {
        _visualItems.append(&_serviceArea);
143 144 145 146 147 148 149 150 151 152 153

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

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

154
bool WimaPlaner::addCorridor()
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 183 184 185 186 187
{
    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()
{
188

189
    QString errorString;
190 191
    #define debug 0

192 193
    if ( !recalcJoinedArea(errorString)) {
        qgcApp()->showMessage(tr(errorString.toLocal8Bit().data()));
194 195 196 197 198 199 200
        return false;
    }

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
201 202 203
    // extract old survey data
    QmlObjectListModel* missionItems        = _missionController->visualItems();

204
    int surveyIndex = missionItems->indexOf(_circularSurvey);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
205

206
    // create survey item if not yet present
207
    if (surveyIndex == -1) {
208
        _missionController->insertComplexMissionItem(_missionController->circularSurveyComplexItemName(), _measurementArea.center(), missionItems->count());
209
        _circularSurvey = qobject_cast<CircularSurveyComplexItem*>(missionItems->get(missionItems->count()-1));
210

211
        if (_circularSurvey == nullptr){
212 213 214 215
            qWarning("WimaPlaner::updateMission(): survey == nullptr");
            return false;
        }

216 217 218 219 220 221 222
        // establish connections
        _circularSurvey->setRefPoint(_measurementArea.center());
        _circularSurvey->setAutoGenerated(true); // prevents reinitialisation from gui
        connect(_circularSurvey->deltaR(),               &Fact::rawValueChanged, this, &WimaPlaner::calcArrivalAndReturnPath);
        connect(_circularSurvey->deltaAlpha(),           &Fact::rawValueChanged, this, &WimaPlaner::calcArrivalAndReturnPath);
        connect(_circularSurvey->isSnakePath(),          &Fact::rawValueChanged, this, &WimaPlaner::calcArrivalAndReturnPath);
        connect(_circularSurvey->transectMinLength(),    &Fact::rawValueChanged, this, &WimaPlaner::calcArrivalAndReturnPath);
223 224
    }

225 226 227
    // update survey area
    _circularSurvey->surveyAreaPolygon()->clear();
    _circularSurvey->surveyAreaPolygon()->appendVertices(_measurementArea.coordinateList());
228

229
    calcArrivalAndReturnPath();
230

231
    pushToContainer(); // exchange plan data with the WimaController via the _container
232
    setDirty(false);
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    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
324
                if ( jsonArea[WimaArea::areaTypeName] == WimaMeasurementArea::WimaMeasurementAreaName) {
325 326 327
                    print(_measurementArea);
                    bool success = _measurementArea.loadFromJson(jsonArea, errorString);
                    print(_measurementArea);
328 329 330 331 332 333 334

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

                    validAreaCounter++;
335
                    _visualItems.append(&_measurementArea);
336 337
                    emit visualItemsChanged();
                } else if ( jsonArea[WimaArea::areaTypeName] == WimaServiceArea::wimaServiceAreaName) {
338
                    bool success = _serviceArea.loadFromJson(jsonArea, errorString);
339 340 341 342 343 344 345

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

                    validAreaCounter++;
346
                    _visualItems.append(&_serviceArea);
347
                    emit visualItemsChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
348
                } else if ( jsonArea[WimaArea::areaTypeName] == WimaCorridor::WimaCorridorName) {
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                    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();
373
        //recalcJoinedArea();
374

Valentin Platzgummer's avatar
Valentin Platzgummer committed
375
        // MissionItems
376
        // extrac MissionItems part
Valentin Platzgummer's avatar
Valentin Platzgummer committed
377 378 379 380 381 382 383 384 385

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

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

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

        QJsonDocument missionJsonDoc = QJsonDocument(missionObject);
386 387 388 389 390 391 392 393
        // 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
394 395
            temporaryFileName = cropedFileName + QString("/temp%1.%2").arg(i).arg(AppSettings::planFileExtension);
            // qWarning() << temporaryFileName;
396 397 398 399 400 401 402 403 404 405 406 407 408 409

            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
410
        // qWarning() << missionJsonDoc.toVariant().toString();
411
        temporaryFile.write(missionJsonDoc.toJson());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
412
        temporaryFile.close();
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

        // 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));
441
        interactivePoly->setWimaAreaInteractive(true);
442 443 444
    }
}

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 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 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
bool WimaPlaner::calcArrivalAndReturnPath()
{
    // extract old survey data
    QmlObjectListModel          *missionItems   = _missionController->visualItems();

    int surveyIndex = missionItems->indexOf(_circularSurvey);

    if (surveyIndex == -1) {
        qWarning("WimaPlaner::calcArrivalAndReturnPath(): no survey item");
        return false;
    }

    // remove old arrival and return path
    int size = missionItems->count();
    for (int i = surveyIndex+1; i < size; i++)
        _missionController->removeMissionItem(surveyIndex+1);
    for (int i = surveyIndex-1; i > 1; i--)
        _missionController->removeMissionItem(i);

    // set home position to serArea center
    MissionSettingsItem* settingsItem= qobject_cast<MissionSettingsItem*>(missionItems->get(0));
    if (settingsItem == nullptr){
        qWarning("WimaPlaner::calcArrivalAndReturnPath(): settingsItem == nullptr");
        return false;
    }

    // set altitudes, temporary measure to solve bugs
    QGeoCoordinate center = _serviceArea.center();
    center.setAltitude(0);
    _serviceArea.setCenter(center);
    center = _measurementArea.center();
    center.setAltitude(0);
    _measurementArea.setCenter(center);
    center = _corridor.center();
    center.setAltitude(0);
    _corridor.setCenter(center);
    // set HomePos. to serArea center
    settingsItem->setCoordinate(_serviceArea.center());

    // set takeoff position
    bool setCommandNeeded = false;
    if (missionItems->count() < 3) {
        setCommandNeeded = true;
        _missionController->insertSimpleMissionItem(_serviceArea.center(), 1);
    }
    SimpleMissionItem* takeOffItem = qobject_cast<SimpleMissionItem*>(missionItems->get(1));
    if (takeOffItem == nullptr){
        qWarning("WimaPlaner::calcArrivalAndReturnPath(): takeOffItem == nullptr");
        return false;
    }
    if (setCommandNeeded)
        _missionController->setTakeoffCommand(*takeOffItem);
    takeOffItem->setCoordinate(_serviceArea.center());

    if (_circularSurvey->visualTransectPoints().size() == 0) {
        qWarning("WimaPlaner::calcArrivalAndReturnPath(): survey no points.");
        return false;
    }

    // calculate path from take off to survey
    QGeoCoordinate start = _serviceArea.center();
    QGeoCoordinate end = _circularSurvey->coordinate();

    #ifdef QT_DEBUG
    if (!_visualItems.contains(&_joinedArea))
        _visualItems.append(&_joinedArea);
    #endif

    QList<QGeoCoordinate> path;
    if ( !calcShortestPath(start, end, path)) {
        qgcApp()->showMessage( QString(tr("Not able to calculate the path from takeoff position to measurement area.")).toLocal8Bit().data());
        return false;
    }
    _arrivalPathLength = path.size()-1; // -1: last item is first measurement point
    int sequenceNumber = 0;
    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
    start   = _circularSurvey->exitCoordinate();
    end     = _serviceArea.center();
    path.clear();
    if ( !calcShortestPath(start, end, path)) {
        qgcApp()->showMessage(QString(tr("Not able to calculate the path from measurement area to landing position.")).toLocal8Bit().data());
        return false;
    }
    _returnPathLength = path.size()-1; // -1: fist item is last measurement point
    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
    sequenceNumber = _missionController->insertSimpleMissionItem(_serviceArea.center(), missionItems->count());
    _missionController->setCurrentPlanViewIndex(sequenceNumber, true);
    SimpleMissionItem* landItem = qobject_cast<SimpleMissionItem*>(missionItems->get(missionItems->count()-1));
    if (landItem == nullptr){
        qWarning("WimaPlaner::calcArrivalAndReturnPath(): landItem == nullptr");
        return false;
    } else {
        if (!_missionController->setLandCommand(*landItem))
            return false;
    }


    return true;
}

555
bool WimaPlaner::recalcJoinedArea(QString &errorString)
556
{
557
    // check if area paths form simple polygons
558
    if ( !_serviceArea.isSimplePolygon() ) {
559 560 561 562
        errorString.append(tr("Service area is self intersecting and thus not a simple polygon. Only simple polygons allowed.\n"));
        return false;
    }

563
    if ( !_corridor.isSimplePolygon() && _corridor.count() > 0) {
564 565 566 567
        errorString.append(tr("Corridor is self intersecting and thus not a simple polygon. Only simple polygons allowed.\n"));
        return false;
    }

568
    if ( !_measurementArea.isSimplePolygon() ) {
569 570 571 572
        errorString.append(tr("Measurement area is self intersecting and thus not a simple polygon. Only simple polygons allowed.\n"));
        return false;
    }

573
    _joinedArea.setPath(_serviceArea.path());
574
    _joinedArea.join(_corridor);
575
    if ( !_joinedArea.join(_measurementArea) ) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
576
        errorString.append(tr("Not able to join areas. Service area and measurement"
577
                           " must have a overlapping section, or be connected through a corridor."));
578
        return false; // this happens if all areas are pairwise disjoint
579
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
580 581
    // join service area, op area and corridor
    return true;
582 583
}

584 585 586 587 588 589 590
/*!
 * \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
 */
591 592 593
void WimaPlaner::pushToContainer()
{
    if (_container != nullptr) {
594 595
        WimaPlanData planData = toPlanData();
        _container->push(planData);
596 597 598 599 600
    } else {
        qWarning("WimaPlaner::uploadToContainer(): no container assigned.");
    }
}

601 602 603 604 605 606
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
607
                                   toQPolygonF(toCartesian2D(_joinedArea.coordinateList(), /*origin*/ start)),
608
                                   /*start point*/ QPointF(0,0),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
609 610
                                   /*destination*/ toCartesian2D(destination, start),
                                   /*shortest path*/ path2D);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
611
    path.append(toGeo(path2D, /*origin*/ start));
612 613 614 615

    return  retVal;
}

616
void WimaPlaner::resetAllInteractive()
617
{
618 619 620 621 622
    // 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));
623
            iteratorPoly->setWimaAreaInteractive(false);
624 625 626 627 628 629 630 631 632
        }
    }
}

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

633 634 635 636 637 638 639 640 641 642 643 644
/*!
 * \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;
645 646

    // store areas
647 648 649
    planData.append(WimaMeasurementAreaData(_measurementArea));
    planData.append(WimaServiceAreaData(_serviceArea));
    planData.append(WimaCorridorData(_corridor));
650
    planData.append(WimaJoinedAreaData(_joinedArea));
651

652 653 654
    // convert mission items to mavlink commands
    QList<MissionItem*> rgMissionItems;
    MissionController::convertToMissionItems(_missionController->visualItems(), rgMissionItems, this);
655

656
    // add const qualifier...
657
    QList<const MissionItem*> rgMissionItemsConst;
658 659 660 661
    for (int i = _arrivalPathLength + 1; i < rgMissionItems.size() - _returnPathLength; i++) { // i = _arrivalPathLength + 1: + 1 = MissionSettingsItem ...
        rgMissionItemsConst.append(rgMissionItems.value(i));
    }

662 663
    // store mavlink commands
    planData.append(rgMissionItemsConst);
664 665

    return planData;
666 667
}

668
void WimaPlaner::setDirty(bool dirty)
669
{
670
    if(_dirty != dirty)
671
    {
672
        _dirty = dirty;
673

674
        emit dirtyChanged(_dirty);
675 676 677
    }
}

678
void WimaPlaner::setDirtyTrue()
679
{
680
    setDirty(true);
681 682
}

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
void WimaPlaner::updateTimerSlot()
{
    // General operation of this function:
    // Check if parameter has changed, wait until it stops changing, update mission

    // circular survey reference point
    if (_circularSurvey != nullptr) {
        if (_surveyRefChanging) {
            if (_circularSurvey->refPoint() == _lastSurveyRefPoint) { // is it still changing?
                calcArrivalAndReturnPath();
                _surveyRefChanging = false;
            }
        } else {
            if (_circularSurvey->refPoint() != _lastSurveyRefPoint) // does it started changing?
                _surveyRefChanging = true;
        }
    }


    // update old values
    if (_circularSurvey != nullptr)
        _lastSurveyRefPoint = _circularSurvey->refPoint() ;
}

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
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
727
            WimaMeasurementArea* opArea =  qobject_cast<WimaMeasurementArea*>(area);
728 729 730 731 732
            if (opArea != nullptr) {
                opArea->saveToJson(json);
                jsonArray.append(json);
                continue;
            }
733

734 735 736 737 738 739 740
            WimaServiceArea* serArea =  qobject_cast<WimaServiceArea*>(area);
            if (serArea != nullptr) {
                serArea->saveToJson(json);
                jsonArray.append(json);
                continue;
            }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
741
            WimaCorridor* corridor =  qobject_cast<WimaCorridor*>(area);
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
            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);
762
}
763 764 765