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

3 4 5 6 7 8
#include "MissionController.h"
#include "MissionSettingsItem.h"
#include "PlanMasterController.h"
#include "QGCApplication.h"
#include "QGCMapPolygon.h"
#include "SimpleMissionItem.h"
9

10 11 12
#include "Geometry/GeoUtilities.h"
#include "Geometry/PlanimetryCalculus.h"
#include "OptimisationTools.h"
13

14 15 16 17
#include "CircularSurvey.h"
#include "Geometry/WimaArea.h"
#include "Geometry/WimaAreaData.h"
#include "WimaBridge.h"
18

19 20 21
const char *WimaPlaner::wimaFileExtension = "wima";
const char *WimaPlaner::areaItemsName = "AreaItems";
const char *WimaPlaner::missionItemsName = "MissionItems";
22 23

WimaPlaner::WimaPlaner(QObject *parent)
24
    : QObject(parent), _masterController(nullptr), _missionController(nullptr),
25 26 27
      _currentAreaIndex(-1), _wimaBridge(nullptr), _mAreaChanged(true),
      _sAreaChanged(true), _corridorChanged(true), _joinedArea(this),
      _arrivalPathLength(0), _returnPathLength(0), _TSComplexItem(nullptr),
28
      _surveyChanged(true), _synchronized(false), _needsUpdate(true) {
29 30

  connect(this, &WimaPlaner::currentPolygonIndexChanged, this,
31 32 33 34 35 36 37 38 39
          &WimaPlaner::updatePolygonInteractivity);
  connect(&this->_measurementArea, &WimaArea::pathChanged, [this] {
    this->_mAreaChanged = true;
    this->setNeedsUpdate(true);
  });
  connect(&this->_serviceArea, &WimaArea::pathChanged, [this] {
    this->_sAreaChanged = true;
    this->setNeedsUpdate(true);
  });
40 41 42 43
  connect(&this->_serviceArea, &WimaServiceArea::depotChanged, [this] {
    this->_sAreaChanged = true;
    this->setNeedsUpdate(true);
  });
44 45 46 47
  connect(&this->_corridor, &WimaArea::pathChanged, [this] {
    this->_corridorChanged = true;
    this->setNeedsUpdate(true);
  });
Valentin Platzgummer's avatar
Valentin Platzgummer committed
48
#ifndef NDEBUG
49 50 51 52 53
  // for debugging and testing purpose, remove if not needed anymore
  connect(&_autoLoadTimer, &QTimer::timeout, this,
          &WimaPlaner::autoLoadMission);
  _autoLoadTimer.setSingleShot(true);
  _autoLoadTimer.start(300);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
54
#endif
55
}
56

57 58 59 60 61 62
PlanMasterController *WimaPlaner::masterController() {
  return _masterController;
}

MissionController *WimaPlaner::missionController() {
  return _missionController;
63 64
}

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

67 68 69 70
int WimaPlaner::currentPolygonIndex() const { return _currentAreaIndex; }

QString WimaPlaner::currentFile() const { return _currentFile; }

71 72
QStringList WimaPlaner::loadNameFilters() const {
  QStringList filters;
73

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

81 82
QStringList WimaPlaner::saveNameFilters() const {
  QStringList filters;
83

84 85 86 87
  filters << tr("Supported types (*.%1 *.%2)")
                 .arg(wimaFileExtension)
                 .arg(AppSettings::planFileExtension);
  return filters;
88 89
}

90 91
QString WimaPlaner::fileExtension() const { return wimaFileExtension; }

92 93
QGeoCoordinate WimaPlaner::joinedAreaCenter() const {
  return _joinedArea.center();
94 95
}

96 97
WimaBridge *WimaPlaner::wimaBridge() { return _wimaBridge; }

98 99 100
void WimaPlaner::setMasterController(PlanMasterController *masterC) {
  _masterController = masterC;
  emit masterControllerChanged();
101 102
}

103 104 105
void WimaPlaner::setMissionController(MissionController *missionC) {
  _missionController = missionC;
  emit missionControllerChanged();
106 107
}

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

113 114
    emit currentPolygonIndexChanged(index);
  }
115 116
}

117 118 119 120 121
void WimaPlaner::setWimaBridge(WimaBridge *bridge) {
  if (bridge != nullptr) {
    _wimaBridge = bridge;
    emit wimaBridgeChanged();
  }
122 123
}

124
bool WimaPlaner::synchronized() { return _synchronized; }
125

126
bool WimaPlaner::needsUpdate() { return _needsUpdate; }
127

128
WimaPlaner *WimaPlaner::thisPointer() { return this; }
129

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

134 135 136
    if (area == nullptr) {
      qWarning("WimaPlaner::removeArea(): nullptr catched, internal error.");
      return;
137
    }
138 139
    area->clear();
    area->borderPolygon()->clear();
140

141
    emit visualItemsChanged();
142

143 144 145 146 147 148 149
    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.
      resetAllInteractive();
      _currentAreaIndex = -1;
      return;
150 151
    }

152 153
    if (_currentAreaIndex >= _visualItems.count()) {
      setCurrentPolygonIndex(_visualItems.count() - 1);
154
    } else {
155
      updatePolygonInteractivity(_currentAreaIndex);
156
    }
157 158 159
  } else {
    qWarning("Index out of bounds!");
  }
160 161
}

162 163 164
bool WimaPlaner::addMeasurementArea() {
  if (!_visualItems.contains(&_measurementArea)) {
    _visualItems.append(&_measurementArea);
165

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

169 170 171 172 173
    emit visualItemsChanged();
    return true;
  } else {
    return false;
  }
174 175
}

176 177 178
bool WimaPlaner::addServiceArea() {
  if (!_visualItems.contains(&_serviceArea)) {
    _visualItems.append(&_serviceArea);
179

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

183 184 185 186 187 188
    emit visualItemsChanged();
    return true;
  } else {
    return false;
  }
}
189

190 191 192
bool WimaPlaner::addCorridor() {
  if (!_visualItems.contains(&_corridor)) {
    _visualItems.append(&_corridor);
193

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

197 198 199 200 201
    emit visualItemsChanged();
    return true;
  } else {
    return false;
  }
202 203
}

204 205 206 207 208 209
void WimaPlaner::removeAll() {
  bool changesApplied = false;
  while (_visualItems.count() > 0) {
    removeArea(0);
    changesApplied = true;
  }
210

211
  _missionController->removeAll();
212

213
  _currentFile = "";
214

215
  _TSComplexItem = nullptr;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
216

217 218 219 220
  emit currentFileChanged();
  if (changesApplied)
    emit visualItemsChanged();
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
bool WimaPlaner::update() {
  this->_synchronized = false;
  emit synchronizedChanged();

  // ====================== update joined area ======================
  // check if at least service area and measurement area are available
  if (_visualItems.indexOf(&_serviceArea) == -1 ||
      _visualItems.indexOf(&_measurementArea) == -1)
    return false;

  // Check if polygons have at least three vertices
  if (_serviceArea.count() < 3) {
    qgcApp()->showMessage(tr("Service area has less than three vertices."));
    return false;
  }

  if (_measurementArea.count() < 3) {
    qgcApp()->showMessage(tr("Measurement area has less than three vertices."));
    return false;
  }

  // Check for simple polygons
  if (!_serviceArea.isSimplePolygon()) {
    qgcApp()->showMessage(tr("Service area is not a simple polygon. "
                             "Only simple polygons allowed.\n"));
    return false;
  }
249

250 251 252 253 254
  if (!_corridor.isSimplePolygon() && _corridor.count() > 0) {
    qgcApp()->showMessage(tr("Corridor is not a simple polygon. Only "
                             "simple polygons allowed.\n"));
    return false;
  }
255

256 257 258
  if (!_measurementArea.isSimplePolygon()) {
    qgcApp()->showMessage(tr("Measurement area is not a simple "
                             "polygon. Only simple polygons allowed.\n"));
259
    return false;
260 261
  }

262 263 264 265 266
  if (!_serviceArea.containsCoordinate(_serviceArea.depot())) {
    qgcApp()->showMessage(tr("Depot not inside service area."));
    return false;
  }

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  // Join areas.
  bool jAreaChanged =
      this->_mAreaChanged || this->_sAreaChanged || this->_corridorChanged;
  if (jAreaChanged) {
    _joinedArea.setPath(_serviceArea.path());
    if (_corridor.count() >= 3) {
      _joinedArea.join(_corridor);
    }
    if (!_joinedArea.join(_measurementArea)) {
      qgcApp()->showMessage(
          tr("Not able to join areas. Service and measurement area"
             " must be overlapping, or connected through a "
             "corridor."));
      return false;
    }
  }
283

284 285 286
  // ===========================================================
  // ====================== update survey ======================
  bool updateSurveyArea = jAreaChanged;
287 288 289 290 291 292 293 294 295 296
  // extract old survey data
  QmlObjectListModel *missionItems = _missionController->visualItems();
  int surveyIndex = missionItems->indexOf(_TSComplexItem);
  // create survey item if not yet present
  if (surveyIndex == -1) {
    _missionController->insertComplexMissionItem(
        _missionController->circularSurveyComplexItemName(),
        _measurementArea.center(), missionItems->count());
    _TSComplexItem = qobject_cast<CircularSurvey *>(
        missionItems->get(missionItems->count() - 1));
297

298
    if (_TSComplexItem == nullptr) {
299
      qWarning("WimaPlaner::update(): survey == nullptr");
300
      return false;
301 302
    }

303 304
    // establish connections
    _TSComplexItem->setRefPoint(_measurementArea.center());
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    _TSComplexItem->setHidePolygon(true);
    connect(_TSComplexItem, &CircularSurvey::missionItemReady, [this] {
      this->_surveyChanged = true;
      this->setNeedsUpdate(true);
    });
    updateSurveyArea = true;
  }

  if (updateSurveyArea) {
    // update survey area
    _TSComplexItem->surveyAreaPolygon()->clear();
    _TSComplexItem->surveyAreaPolygon()->appendVertices(
        _measurementArea.coordinateList());
    _TSComplexItem->setDepot(this->_serviceArea.depot());
    _TSComplexItem->setSafeArea(this->_joinedArea.coordinateList());
    this->_mAreaChanged = false;
    this->_sAreaChanged = false;
    this->_corridorChanged = false;
  } else if (this->_surveyChanged) {

    // ==========================================================
    // ====================== update paths ======================

    surveyIndex = missionItems->indexOf(_TSComplexItem);

    if (surveyIndex == -1) {
      qWarning("WimaPlaner::update(): no survey item");
      return false;
    }
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
    // 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::update(): settingsItem == nullptr");
      return false;
    }
    // set altitudes
    QGeoCoordinate point = _serviceArea.depot();
    point.setAltitude(0);
    _serviceArea.setDepot(point);
    point = _measurementArea.center();
    point.setAltitude(0);
    _measurementArea.setCenter(point);
    point = _corridor.center();
    point.setAltitude(0);
    _corridor.setCenter(point);
    settingsItem->setCoordinate(_serviceArea.depot());

    // set takeoff position
    bool setCommandNeeded = false;
    if (missionItems->count() < 3) {
      setCommandNeeded = true;
      _missionController->insertSimpleMissionItem(_serviceArea.depot(), 1);
    }
    SimpleMissionItem *takeOffItem =
        qobject_cast<SimpleMissionItem *>(missionItems->get(1));
    if (takeOffItem == nullptr) {
      qWarning("WimaPlaner::update(): takeOffItem == nullptr");
      return false;
    }
    if (setCommandNeeded)
      _missionController->setTakeoffCommand(*takeOffItem);
    takeOffItem->setCoordinate(_serviceArea.depot());
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 411 412 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
    if (_TSComplexItem->visualTransectPoints().size() == 0) {
      qWarning("WimaPlaner::update(): survey no points.");
      return false;
    }

    // calculate path from take off to survey
    QGeoCoordinate start = _serviceArea.depot();
    QGeoCoordinate end = _TSComplexItem->coordinate();
#ifdef QT_DEBUG
// if (!_visualItems.contains(&_joinedArea))
//_visualItems.append(&_joinedArea);
#endif
    QVector<QGeoCoordinate> path;
    if (!shortestPath(start, end, path)) {
      qgcApp()->showMessage(QString(tr("Not able to calculate path from "
                                       "takeoff position to measurement area."))
                                .toLocal8Bit()
                                .data());
      return false;
    }
    _arrivalPathLength = path.size() - 1;
    int sequenceNumber = 0;
    for (int i = 1; i < path.count() - 1; i++) {
      sequenceNumber = _missionController->insertSimpleMissionItem(
          path[i], missionItems->count() - 1);
      _missionController->setCurrentPlanViewIndex(sequenceNumber, true);
    }

    // calculate return path
    start = _TSComplexItem->exitCoordinate();
    end = _serviceArea.depot();
    path.clear();
    if (!shortestPath(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[i], missionItems->count());
      _missionController->setCurrentPlanViewIndex(sequenceNumber, true);
    }

    // create land position item
    sequenceNumber = _missionController->insertSimpleMissionItem(
        _serviceArea.depot(), 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;
    }
    this->_surveyChanged = false;
438
    setNeedsUpdate(false);
439 440
  }

441 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
  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;
468
    } else {
469 470 471 472 473 474 475
      if (planFilename.contains(".")) {
        qgcApp()->showMessage(tr("File format not supported"));
      } else {
        qgcApp()->showMessage(tr("File without file extension not accepted."));
        return;
      }
    }
476

477 478 479 480 481
    QJsonDocument saveDoc = saveToJson(fileType);
    file.write(saveDoc.toJson());
    if (_currentFile != planFilename) {
      _currentFile = planFilename;
      emit currentFileChanged();
482
    }
483
  }
484 485
}

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

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

494 495 496
  if (filename.isEmpty()) {
    return false;
  }
497

498 499
  QFileInfo fileInfo(filename);
  QFile file(filename);
500

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

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

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

516 517 518 519
    QJsonObject json = jsonDoc.object();
    // AreaItems
    QJsonArray areaArray = json[areaItemsName].toArray();
    _visualItems.clear();
520

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

525 526 527 528 529
      if (jsonArea.contains(WimaArea::areaTypeName) &&
          jsonArea[WimaArea::areaTypeName].isString()) {
        if (jsonArea[WimaArea::areaTypeName] ==
            WimaMeasurementArea::WimaMeasurementAreaName) {
          bool success = _measurementArea.loadFromJson(jsonArea, errorString);
530

531 532
          if (!success) {
            qgcApp()->showMessage(errorMessage.arg(errorString));
533
            return false;
534 535 536 537 538 539 540 541 542 543 544
          }

          validAreaCounter++;
          _visualItems.append(&_measurementArea);
          emit visualItemsChanged();
        } else if (jsonArea[WimaArea::areaTypeName] ==
                   WimaServiceArea::wimaServiceAreaName) {
          bool success = _serviceArea.loadFromJson(jsonArea, errorString);

          if (!success) {
            qgcApp()->showMessage(errorMessage.arg(errorString));
545
            return false;
546 547 548 549 550 551 552 553 554 555 556 557 558
          }

          validAreaCounter++;
          _visualItems.append(&_serviceArea);
          emit visualItemsChanged();
        } else if (jsonArea[WimaArea::areaTypeName] ==
                   WimaCorridor::WimaCorridorName) {
          bool success = _corridor.loadFromJson(jsonArea, errorString);

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

560 561 562 563 564 565 566 567
          validAreaCounter++;
          _visualItems.append(&_corridor);
          emit visualItemsChanged();
        } else {
          errorString +=
              QString(tr("%s not supported.\n").arg(WimaArea::areaTypeName));
          qgcApp()->showMessage(errorMessage.arg(errorString));
          return false;
568
        }
569 570 571
      } else {
        errorString += QString(tr("Invalid or non existing entry for %s.\n")
                                   .arg(WimaArea::areaTypeName));
572
        return false;
573
      }
574 575
    }

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

580
    emit currentFileChanged();
581

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

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

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    QJsonDocument missionJsonDoc = QJsonDocument(missionObject);
    // 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++) {
      temporaryFileName =
          cropedFileName +
          QString("/temp%1.%2").arg(i).arg(AppSettings::planFileExtension);
      // qWarning() << temporaryFileName;

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

607 608 609
      if (i > 1000) {
        qWarning(
            "WimaPlaner::loadFromFile(): not able to create temporary file.");
610
        return false;
611
      }
612 613
    }

614 615 616
    // qWarning() << missionJsonDoc.toVariant().toString();
    temporaryFile.write(missionJsonDoc.toJson());
    temporaryFile.close();
617

618 619 620 621 622 623 624
    // load from temporary file
    _masterController->loadFromFile(temporaryFileName);
    QmlObjectListModel *missionItems = _missionController->visualItems();
    _TSComplexItem = nullptr;
    for (int i = 0; i < missionItems->count(); i++) {
      _TSComplexItem = missionItems->value<CircularSurvey *>(i);
      if (_TSComplexItem != nullptr) {
625 626 627 628 629
        _TSComplexItem->setHidePolygon(true);
        connect(_TSComplexItem, &CircularSurvey::missionItemReady, [this] {
          this->_surveyChanged = true;
          this->setNeedsUpdate(true);
        });
630 631
        break;
      }
632 633
    }

634
    if (!update())
635
      return false;
636

637 638 639 640
    // remove temporary file
    if (!temporaryFile.remove()) {
      qWarning(
          "WimaPlaner::loadFromFile(): not able to remove temporary file.");
641 642
    }

643 644
    this->_synchronized = false;
    emit synchronizedChanged();
645
    return true;
646

647 648 649 650 651 652 653 654 655 656
  } 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;
  }
}

657
void WimaPlaner::updatePolygonInteractivity(int index) {
658 659 660 661 662 663 664 665 666
  if (index >= 0 && index < _visualItems.count()) {
    resetAllInteractive();
    WimaArea *interactivePoly =
        qobject_cast<WimaArea *>(_visualItems.get(index));
    if (interactivePoly != nullptr)
      interactivePoly->setWimaAreaInteractive(true);
  }
}

667
void WimaPlaner::synchronize() {
668
  if (_wimaBridge != nullptr) {
669 670 671 672 673 674
    if (readyForSynchronization()) {
      auto planData = toPlanData();
      (void)_wimaBridge->setWimaPlanData(planData);
      this->_synchronized = true;
      emit synchronizedChanged();
    }
675 676 677
  } else {
    qWarning("WimaPlaner::uploadToContainer(): no container assigned.");
  }
678 679
}

680 681 682 683
bool WimaPlaner::readyForSynchronization() {
  return !_needsUpdate && _measurementArea.ready();
}

684 685 686
bool WimaPlaner::shortestPath(const QGeoCoordinate &start,
                              const QGeoCoordinate &destination,
                              QVector<QGeoCoordinate> &path) {
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
  using namespace GeoUtilities;
  using namespace PolygonCalculus;
  QPolygonF polygon2D;
  toCartesianList(_joinedArea.coordinateList(), /*origin*/ start, polygon2D);
  QPointF start2D(0, 0);
  QPointF end2D;
  QVector<QPointF> path2D;
  toCartesian(destination, start, end2D);
  bool retVal =
      PolygonCalculus::shortestPath(polygon2D, start2D, end2D, path2D);
  toGeoList(path2D, /*origin*/ start, path);

  return retVal;
}

702 703 704 705 706 707 708
void WimaPlaner::setNeedsUpdate(bool needsUpdate) {
  if (this->_needsUpdate != needsUpdate) {
    this->_needsUpdate = needsUpdate;
    emit needsUpdateChanged();
  }
}

709 710 711 712 713 714 715
void WimaPlaner::resetAllInteractive() {
  // 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));
      iteratorPoly->setWimaAreaInteractive(false);
716
    }
717
  }
718 719
}

720
void WimaPlaner::setInteractive() {
721
  updatePolygonInteractivity(_currentAreaIndex);
722 723
}

724 725 726
/*!
 * \fn WimaPlanData WimaPlaner::toPlanData()
 *
727
 * Returns a \c WimaPlanData object containing information about the current
728 729
 * mission. The \c WimaPlanData object holds only the data which is relevant
 * for the \c WimaController class. Should only be called if update() was
730
 * successful.
731 732 733
 *
 * \sa WimaController, WimaPlanData
 */
734 735
QSharedPointer<WimaPlanData> WimaPlaner::toPlanData() {
  QSharedPointer<WimaPlanData> planData(new WimaPlanData());
736 737

  // store areas
738 739 740 741
  planData->append(WimaMeasurementAreaData(_measurementArea));
  planData->append(WimaServiceAreaData(_serviceArea));
  planData->append(WimaCorridorData(_corridor));
  planData->append(WimaJoinedAreaData(_joinedArea));
742 743

  // convert mission items to mavlink commands
744
  QList<MissionItem *> missionItems;
745 746 747 748 749 750
  if (_missionController && _missionController->visualItems()) {
    int surveyIndex =
        _missionController->visualItems()->indexOf(_TSComplexItem);
    if (surveyIndex > 0) {
      _TSComplexItem->appendMissionItems(missionItems, nullptr);
    }
751
  }
752
  // store mavlink commands
753
  planData->append(missionItems);
754 755 756 757 758 759 760
  return planData;
}

#ifndef NDEBUG
void WimaPlaner::autoLoadMission() {
  loadFromFile("/home/valentin/Desktop/drones/qgroundcontrol/Paths/"
               "KlingenbachTest.wima");
761
  synchronize();
762
}
763
#endif
764

765 766 767 768 769 770
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;
771

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

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

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

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

785 786 787 788 789 790 791 792
      // check the type of area, create and append the JsonObject to the
      // JsonArray once determined
      WimaMeasurementArea *opArea = qobject_cast<WimaMeasurementArea *>(area);
      if (opArea != nullptr) {
        opArea->saveToJson(json);
        jsonArray.append(json);
        continue;
      }
793

794 795 796 797 798 799
      WimaServiceArea *serArea = qobject_cast<WimaServiceArea *>(area);
      if (serArea != nullptr) {
        serArea->saveToJson(json);
        jsonArray.append(json);
        continue;
      }
800

801 802 803 804 805 806
      WimaCorridor *corridor = qobject_cast<WimaCorridor *>(area);
      if (corridor != nullptr) {
        corridor->saveToJson(json);
        jsonArray.append(json);
        continue;
      }
807

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

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

816 817 818 819
    return QJsonDocument(json);
  } else if (fileType == FileType::PlanFile) {
    return _masterController->saveToJson();
  }
820

821 822
  return QJsonDocument(json);
}