WimaController.cc 31.5 KB
Newer Older
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1
#include "WimaController.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
2
#include "utilities.h"
3
#include "ros_bridge/include/JsonMethodes.h"
4 5 6
#include "ros_bridge/rapidjson/include/rapidjson/document.h"
#include "ros_bridge/rapidjson/include/rapidjson/writer.h"
#include "ros_bridge/rapidjson/include/rapidjson/ostreamwrapper.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
7
#include "ros_bridge/include/CasePacker.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
8

9 10 11
#include "Snake/QtROSJsonFactory.h"
#include "Snake/QtROSTypeFactory.h"
#include "Snake/QNemoProgress.h"
12
#include "Snake/QNemoHeartbeat.h"
13

14
#include "QVector3D"
15
#include <QScopedPointer>
16

17 18
#include <memory>

19

20

21
// const char* WimaController::wimaFileExtension           = "wima";
22 23 24 25 26 27 28 29 30
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";
31
const char* WimaController::flightSpeedName             = "FlightSpeed";
32
const char* WimaController::arrivalReturnSpeedName      = "ArrivalReturnSpeed";
33
const char* WimaController::altitudeName                = "Altitude";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
34 35
const char* WimaController::snakeTileWidthName          = "SnakeTileWidth";
const char* WimaController::snakeTileHeightName         = "SnakeTileHeight";
36
const char* WimaController::snakeMinTileAreaName        = "SnakeMinTileArea";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
37 38 39
const char* WimaController::snakeLineDistanceName       = "SnakeLineDistance";
const char* WimaController::snakeMinTransectLengthName  = "SnakeMinTransectLength";

40 41 42 43
WimaController::StatusMap WimaController::_nemoStatusMap{
    std::make_pair<int, QString>(0, "No Heartbeat"),
    std::make_pair<int, QString>(1, "Connected"),
    std::make_pair<int, QString>(-1, "Timeout")};
44

Valentin Platzgummer's avatar
Valentin Platzgummer committed
45 46
using namespace snake;
using namespace snake_geometry;
47

48
WimaController::WimaController(QObject *parent)
49
    : QObject                   (parent)
50 51 52 53
    , _joinedArea               ()
    , _measurementArea          ()
    , _serviceArea              ()
    , _corridor                 ()
54
    , _localPlanDataValid       (false)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
55 56 57 58
    , _areaInterface            (&_measurementArea, &_serviceArea, &_corridor, &_joinedArea)
    , _managerSettings          ()
    , _defaultManager           (_managerSettings, _areaInterface)
    , _snakeManager             (_managerSettings, _areaInterface)
59 60
    , _rtlManager               (_managerSettings, _areaInterface)
    , _currentManager           (&_defaultManager)
61 62 63
    , _managerList              {&_defaultManager, &_snakeManager, &_rtlManager}
    , _metaDataMap              (FactMetaData::createMapFromJsonFile(
                                     QStringLiteral(":/json/WimaController.SettingsGroup.json"), this))
64 65 66
    , _enableWimaController     (settingsGroup, _metaDataMap[enableWimaControllerName])
    , _overlapWaypoints         (settingsGroup, _metaDataMap[overlapWaypointsName])
    , _maxWaypointsPerPhase     (settingsGroup, _metaDataMap[maxWaypointsPerPhaseName])
67
    , _nextPhaseStartWaypointIndex       (settingsGroup, _metaDataMap[startWaypointIndexName])
68
    , _showAllMissionItems      (settingsGroup, _metaDataMap[showAllMissionItemsName])
69 70
    , _showCurrentMissionItems  (settingsGroup, _metaDataMap[showCurrentMissionItemsName])    
    , _flightSpeed              (settingsGroup, _metaDataMap[flightSpeedName])
71
    , _arrivalReturnSpeed       (settingsGroup, _metaDataMap[arrivalReturnSpeedName])
72
    , _altitude                 (settingsGroup, _metaDataMap[altitudeName])
73 74
    , _measurementPathLength    (-1)
    , _lowBatteryHandlingTriggered  (false)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
75 76 77 78 79 80
    , _snakeCalcInProgress      (false)
    , _snakeTileWidth           (settingsGroup, _metaDataMap[snakeTileWidthName])
    , _snakeTileHeight          (settingsGroup, _metaDataMap[snakeTileHeightName])
    , _snakeMinTileArea         (settingsGroup, _metaDataMap[snakeMinTileAreaName])
    , _snakeLineDistance        (settingsGroup, _metaDataMap[snakeLineDistanceName])
    , _snakeMinTransectLength   (settingsGroup, _metaDataMap[snakeMinTransectLengthName])
81
    , _nemoHeartbeat            (0 /*status: not connected*/)
82
    , _fallbackStatus           (0 /*status: not connected*/)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
83
    , _pRosBridge               (new ROSBridge::ROSBridge())
84 85 86 87
    , _pCasePacker              (_pRosBridge->casePacker())
    , _batteryLevelTicker       (EVENT_TIMER_INTERVAL, 1000 /*ms*/)
    , _snakeTicker              (EVENT_TIMER_INTERVAL, 200 /*ms*/)
    , _nemoTimeoutTicker        (EVENT_TIMER_INTERVAL, 5000 /*ms*/)
88
{
89
    // Set up facts.
90 91
    _showAllMissionItems.setRawValue(true);
    _showCurrentMissionItems.setRawValue(true);
92 93
    connect(&_overlapWaypoints,             &Fact::rawValueChanged, this, &WimaController::_updateOverlap);
    connect(&_maxWaypointsPerPhase,         &Fact::rawValueChanged, this, &WimaController::_updateMaxWaypoints);
94
    connect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged, this, &WimaController::_setStartIndex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
95 96 97
    connect(&_flightSpeed,                  &Fact::rawValueChanged, this, &WimaController::_updateflightSpeed);
    connect(&_arrivalReturnSpeed,           &Fact::rawValueChanged, this, &WimaController::_updateArrivalReturnSpeed);
    connect(&_altitude,                     &Fact::rawValueChanged, this, &WimaController::_updateAltitude);
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112
    // Init waypoint managers.
    bool value;
    size_t overlap  = _overlapWaypoints.rawValue().toUInt(&value);
    Q_ASSERT(value);
    size_t N        = _maxWaypointsPerPhase.rawValue().toUInt(&value);
    Q_ASSERT(value);
    size_t startIdx = _nextPhaseStartWaypointIndex.rawValue().toUInt(&value);
    Q_ASSERT(value);
    (void)value;
    for (auto manager : _managerList){
        manager->setOverlap(overlap);
        manager->setN(N);
        manager->setStartIndex(startIdx);
    }
113

114
    // Periodic.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
115
    connect(&_eventTimer, &QTimer::timeout, this, &WimaController::_eventTimerHandler);
116 117
    //_eventTimer.setInterval(EVENT_TIMER_INTERVAL);
    _eventTimer.start(EVENT_TIMER_INTERVAL);
118

Valentin Platzgummer's avatar
Valentin Platzgummer committed
119
    // Snake Worker Thread.
120 121 122
    connect(&_snakeWorker, &SnakeWorker::finished, this, &WimaController::_snakeStoreWorkerResults);
    connect(this, &WimaController::nemoProgressChanged, this, &WimaController::_initStartSnakeWorker);
    connect(this, &QObject::destroyed, &this->_snakeWorker, &SnakeWorker::quit);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
123

124
    // Snake.
125 126 127 128
    connect(&_enableSnake, &Fact::rawValueChanged, this, &WimaController::_initStartSnakeWorker);
    _initStartSnakeWorker();
    connect(&_enableSnake, &Fact::rawValueChanged, this, &WimaController::_switchSnakeManager);
    _switchSnakeManager(_enableSnake.rawValue());
129 130
}

131 132 133 134 135 136 137 138 139
PlanMasterController *WimaController::masterController() {
    return _masterController;
}

MissionController *WimaController::missionController() {
    return _missionController;
}

QmlObjectListModel *WimaController::visualItems() {
140 141 142 143
    return &_areas;
}

QmlObjectListModel *WimaController::missionItems() {
144
    return const_cast<QmlObjectListModel*>(&_currentManager->missionItems());
145 146 147
}

QmlObjectListModel *WimaController::currentMissionItems() {
148
    return const_cast<QmlObjectListModel*>(&_currentManager->currentMissionItems());
149 150 151 152
}

QVariantList WimaController::waypointPath()
{
153
    return const_cast<QVariantList&>(_currentManager->waypointsVariant());
154 155
}

156
QVariantList WimaController::currentWaypointPath()
157
{
158
    return const_cast<QVariantList&>(_currentManager->currentWaypointsVariant());
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 188 189 190 191 192 193 194 195 196
Fact *WimaController::enableWimaController() {
    return &_enableWimaController;
}

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

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

Fact *WimaController::startWaypointIndex() {
    return &_nextPhaseStartWaypointIndex;
}

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

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

Fact *WimaController::flightSpeed() {
    return &_flightSpeed;
}

Fact *WimaController::arrivalReturnSpeed() {
    return &_arrivalReturnSpeed;
}

Fact *WimaController::altitude() {
    return &_altitude;
}

197 198 199 200 201 202 203
QVector<int> WimaController::nemoProgress() {
    if ( _nemoProgress.progress().size() == _snakeTileCenterPoints.size() )
        return _nemoProgress.progress();
    else
        return QVector<int>(_snakeTileCenterPoints.size(), 0);
}

204 205
double WimaController::phaseDistance() const
{
206
    return 0.0;
207 208 209 210
}

double WimaController::phaseDuration() const
{
211
    return 0.0;
212 213
}

214 215 216 217 218 219
int WimaController::nemoStatus() const
{
    return _nemoHeartbeat.status();
}

QString WimaController::nemoStatusString() const
Valentin Platzgummer's avatar
Valentin Platzgummer committed
220
{
221
    return _nemoStatusMap.at(_nemoHeartbeat.status());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
222 223 224 225 226 227 228
}

bool WimaController::snakeCalcInProgress() const
{
    return _snakeCalcInProgress;
}

229 230 231
void WimaController::setMasterController(PlanMasterController *masterC)
{
    _masterController = masterC;
232
    _managerSettings.setMasterController(masterC);
233 234 235 236 237 238
    emit masterControllerChanged();
}

void WimaController::setMissionController(MissionController *missionC)
{
    _missionController = missionC;
239
    _managerSettings.setMissionController(missionC);
240 241 242
    emit missionControllerChanged();
}

243 244
void WimaController::nextPhase()
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
245
    _calcNextPhase();
246 247
}

248
void WimaController::previousPhase()
249
{        
250 251
    if ( !_currentManager->previous() ) {
        Q_ASSERT(false);
252
    }
253 254 255 256 257

    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
258 259 260 261
}

void WimaController::resetPhase()
{
262 263
    if ( !_currentManager->reset() ) {
        Q_ASSERT(false);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
264
    }
265 266 267 268 269

    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
270 271
}

272 273
void WimaController::requestSmartRTL()
{
274 275 276 277 278
    QString errorString("Smart RTL requested. ");
    if ( !_checkSmartRTLPreCondition(errorString) ){
        qgcApp()->showMessage(errorString);
        return;
    }
279 280 281 282
    emit smartRTLRequestConfirm();
}

bool WimaController::upload()
283
{
284
    auto &currentMissionItems = _defaultManager.currentMissionItems();
285
    if (   !_serviceArea.containsCoordinate(_masterController->managerVehicle()->coordinate())
286
        && currentMissionItems.count() > 0) {
287
        emit forceUploadConfirm();
288 289 290
        return false;
    }

291
    return forceUpload();
292 293
}

294
bool WimaController::forceUpload()
295
{
296 297
    auto &currentMissionItems = _defaultManager.currentMissionItems();
    if (currentMissionItems.count() < 1)
298
        return false;
299 300

    _missionController->removeAll();
301
    // Set homeposition of settingsItem.
302 303 304
    QmlObjectListModel* visuals = _missionController->visualItems();
    MissionSettingsItem* settingsItem = visuals->value<MissionSettingsItem *>(0);
    if (settingsItem == nullptr) {
305
        Q_ASSERT(false);
306
        qWarning("WimaController::updateCurrentMissionItems(): nullptr");
307
        return false;
308
    }
309
    settingsItem->setCoordinate(_managerSettings.homePosition());
310

311
    // Copy mission items to _missionController.
312
    for (int i = 1; i < currentMissionItems.count(); i++){
313
        auto *item = currentMissionItems.value<const SimpleMissionItem *>(i);
314 315 316
        _missionController->insertSimpleMissionItem(*item, visuals->count());
    }

317
    _masterController->sendToVehicle();
318 319

    return true;
320
}
321

322 323 324
void WimaController::removeFromVehicle()
{
    _masterController->removeAllFromVehicle();
325 326 327
    _missionController->removeAll();
}

328
void WimaController::executeSmartRTL()
329
{
330 331
    forceUpload();
    masterController()->managerVehicle()->startMission();
332 333
}

334
void WimaController::initSmartRTL()
335
{
336
    _initSmartRTL();
337 338
}

339 340 341 342 343 344
void WimaController::removeVehicleTrajectoryHistory()
{
    Vehicle *managerVehicle = masterController()->managerVehicle();
    managerVehicle->trajectoryPoints()->clear();
}

345
bool WimaController::_calcShortestPath(const QGeoCoordinate &start, const QGeoCoordinate &destination, QVector<QGeoCoordinate> &path)
346 347 348
{
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
349 350 351 352 353
    QPolygonF polygon2D;
    toCartesianList(_joinedArea.coordinateList(), /*origin*/ start, polygon2D);
    QPointF start2D(0,0);
    QPointF end2D;
    toCartesian(destination, start, end2D);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
354
    QVector<QPointF> path2D;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
355 356 357

    bool retVal = PolygonCalculus::shortestPath(polygon2D, start2D, end2D, path2D);
    toGeoList(path2D, /*origin*/ start, path);
358 359 360 361

    return  retVal;
}

362
bool WimaController::setWimaPlanData(const WimaPlanData &planData)
363
{
364
    // reset visual items
365 366
    _areas.clear();
    _defaultManager.clear();
367 368
    _snakeTiles.polygons().clear();
    _snakeTilesLocal.polygons().clear();
369
    _snakeTileCenterPoints.clear();
370

371 372 373
    emit visualItemsChanged();
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
374
    emit waypointPathChanged();
375
    emit currentWaypointPathChanged();
376
    emit snakeTilesChanged();
377
    emit snakeTileCenterPointsChanged();
378

379
    _localPlanDataValid = false;
380

381 382
    // extract list with WimaAreas
    QList<const WimaAreaData*> areaList = planData.areaList();
383

384
    int areaCounter = 0;
385
    const int numAreas = 4; // extract only numAreas Areas, if there are more they are invalid and ignored
386 387
    for (int i = 0; i < areaList.size(); i++) {
        const WimaAreaData *areaData = areaList[i];
388

389 390 391
        if (areaData->type() == WimaServiceAreaData::typeString) { // is it a service area?
            _serviceArea = *qobject_cast<const WimaServiceAreaData*>(areaData);
            areaCounter++;
392
            _areas.append(&_serviceArea);
393

394 395
            continue;
        }
396

397 398 399
        if (areaData->type() == WimaMeasurementAreaData::typeString) { // is it a measurement area?
            _measurementArea =  *qobject_cast<const WimaMeasurementAreaData*>(areaData);
            areaCounter++;
400
            _areas.append(&_measurementArea);
401

402
            continue;
403
        }
404

405 406 407 408
        if (areaData->type() == WimaCorridorData::typeString) { // is it a corridor?
            _corridor =  *qobject_cast<const WimaCorridorData*>(areaData);
            areaCounter++;
            //_visualItems.append(&_corridor); // not needed
409

410 411
            continue;
        }
412

413 414 415
        if (areaData->type() == WimaJoinedAreaData::typeString) { // is it a corridor?
            _joinedArea =  *qobject_cast<const WimaJoinedAreaData*>(areaData);
            areaCounter++;
416
            _areas.append(&_joinedArea);
417

418 419
            continue;
        }
420

421 422 423
        if (areaCounter >= numAreas)
            break;
    }
424

425
    if (areaCounter != numAreas) {
426
        Q_ASSERT(false);
427 428
        return false;
    }
429

430 431
    emit visualItemsChanged();

432 433 434
    // extract mission items
    QList<MissionItem> tempMissionItems = planData.missionItems();
    if (tempMissionItems.size() < 1) {
435
        qWarning("WimaController: Mission items from WimaPlaner empty!");
436
        return false;
437
    }
438

439
    for (auto item : tempMissionItems) {
440
        _defaultManager.push_back(item.coordinate());
441
    }
442

443 444 445
    _managerSettings.setHomePosition( QGeoCoordinate(_serviceArea.center().latitude(),
                                                     _serviceArea.center().longitude(),
                                                     0) );
446

447
    if( !_defaultManager.reset() ){
448
        Q_ASSERT(false);
449
        return false;
450
    }
451

452 453 454 455 456 457 458
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit waypointPathChanged();
    emit currentWaypointPathChanged();



Valentin Platzgummer's avatar
Valentin Platzgummer committed
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    // Initialize _scenario.
    Area mArea;
    for (auto variant : _measurementArea.path()){
        QGeoCoordinate c{variant.value<QGeoCoordinate>()};
        mArea.geoPolygon.push_back(GeoPoint2D{c.latitude(), c.longitude()});
    }
    mArea.type = AreaType::MeasurementArea;

    Area sArea;
    for (auto variant : _serviceArea.path()){
        QGeoCoordinate c{variant.value<QGeoCoordinate>()};
        sArea.geoPolygon.push_back(GeoPoint2D{c.latitude(), c.longitude()});
    }
    sArea.type = AreaType::ServiceArea;

    Area corridor;
    for (auto variant : _corridor.path()){
        QGeoCoordinate c{variant.value<QGeoCoordinate>()};
        corridor.geoPolygon.push_back(GeoPoint2D{c.latitude(), c.longitude()});
    }
    corridor.type = AreaType::Corridor;
480

Valentin Platzgummer's avatar
Valentin Platzgummer committed
481 482 483 484
    _scenario.addArea(mArea);
    _scenario.addArea(sArea);
    _scenario.addArea(corridor);

485
    // Check if scenario is defined.
486 487 488
    if ( !_scenario.defined(_snakeTileWidth.rawValue().toUInt(),
                            _snakeTileHeight.rawValue().toUInt(),
                            _snakeMinTileArea.rawValue().toUInt()) ) {
489
        Q_ASSERT(false);
490
        return false;
491
    }
492

493
    {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
494 495 496 497 498
        // Get tiles and origin.
        auto origin = _scenario.getOrigin();
        _snakeOrigin.setLatitude(origin[0]);
        _snakeOrigin.setLongitude(origin[1]);
        _snakeOrigin.setAltitude(origin[2]);
499 500
        const auto &tiles = _scenario.getTiles();
        const auto &cps = _scenario.getTileCenterPoints();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
501
        for ( unsigned int i=0; i < tiles.size(); ++i ) {
502 503 504 505 506 507 508 509 510 511 512
            const auto &tile = tiles[i];
            SnakeTile Tile;
            for ( const auto &vertex : tile) {
                QGeoCoordinate QVertex(vertex[0], vertex[1], vertex[2]);
                Tile.append(QVertex);
            }
            const auto &centerPoint = cps[i];
            QGeoCoordinate QCenterPoint(centerPoint[0], centerPoint[1], centerPoint[2]);
            Tile.setCenter(QCenterPoint);
            _snakeTiles.polygons().append(Tile);
            _snakeTileCenterPoints.append(QVariant::fromValue(QCenterPoint));
513
        }
514 515 516 517 518
    }

    {
        // Get local tiles.
        const auto &tiles = _scenario.getTilesENU();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
519
        for ( unsigned int i=0; i < tiles.size(); ++i ) {
520 521 522 523
            const auto &tile = tiles[i];
            Polygon2D Tile;
            for ( const auto &vertex : tile.outer()) {
                QPointF QVertex(vertex.get<0>(), vertex.get<1>());
524
                Tile.path().append(QVertex);
525 526 527
            }
            _snakeTilesLocal.polygons().append(Tile);
        }
528
    }
529 530
    emit snakeTilesChanged();
    emit snakeTileCenterPointsChanged();
531

532 533 534
    _localPlanDataValid = true;
    return true;
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
535

536 537 538 539 540 541 542 543 544 545 546
WimaController *WimaController::thisPointer()
{
    return this;
}

bool WimaController::_calcNextPhase()
{
    if ( !_currentManager->next() ) {
        Q_ASSERT(false);
        return false;
    }
547

548
    emit missionItemsChanged();
549 550
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
551
    emit waypointPathChanged();
552

553
    return true;
554 555
}

556
bool WimaController::_setStartIndex()
557
{
558
    bool value;
559
    _currentManager->setStartIndex(_nextPhaseStartWaypointIndex.rawValue().toUInt(&value)-1);
560 561 562 563 564
    Q_ASSERT(value);
    (void)value;

    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
565 566
        return false;
    }
567

568
    emit missionItemsChanged();
569
    emit currentMissionItemsChanged();
570 571
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
572 573

    return true;
574
}
575

576
void WimaController::_recalcCurrentPhase()
577
{
578 579
    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
580
    }
581

582 583 584
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
585 586
    emit waypointPathChanged();
}
587 588

void WimaController::_updateOverlap()
589
{
590
    bool value;
591
    _currentManager->setOverlap(_overlapWaypoints.rawValue().toUInt(&value));
592 593
    Q_ASSERT(value);
    (void)value;
594

595
    if ( !_currentManager->update() ) {
596 597 598 599 600
        assert(false);
    }

    emit missionItemsChanged();
    emit currentMissionItemsChanged();
601
    emit currentWaypointPathChanged();
602
    emit waypointPathChanged();
603
}
604

605
void WimaController::_updateMaxWaypoints()
606
{
607
    bool value;
608
    _currentManager->setN(_maxWaypointsPerPhase.rawValue().toUInt(&value));
609 610
    Q_ASSERT(value);
    (void)value;
611

612 613
    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
614
    }
615

616 617 618 619
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
620 621
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
622
void WimaController::_updateflightSpeed()
623
{
624
    bool value;
625
    _managerSettings.setFlightSpeed(_flightSpeed.rawValue().toDouble(&value));
626 627 628 629 630 631
    Q_ASSERT(value);
    (void)value;

    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
    }
632

633 634 635 636
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
637 638
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
639
void WimaController::_updateArrivalReturnSpeed()
640
{
641
    bool value;
642
    _managerSettings.setArrivalReturnSpeed(_arrivalReturnSpeed.rawValue().toDouble(&value));
643 644 645 646 647 648
    Q_ASSERT(value);
    (void)value;

    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
    }
649

650 651 652 653
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
654 655
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
656
void WimaController::_updateAltitude()
657
{
658
    bool value;
659
    _managerSettings.setAltitude(_altitude.rawValue().toDouble(&value));
660 661 662 663 664 665
    Q_ASSERT(value);
    (void)value;

    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
    }
666 667 668 669 670

    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
671 672
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
673
void WimaController::_checkBatteryLevel()
674
{
675 676 677 678 679
    Vehicle *managerVehicle     = masterController()->managerVehicle();
    WimaSettings* wimaSettings  = qgcApp()->toolbox()->settingsManager()->wimaSettings();
    int batteryThreshold        = wimaSettings->lowBatteryThreshold()->rawValue().toInt();
    bool enabled                = _enableWimaController.rawValue().toBool();
    unsigned int minTime        = wimaSettings->minimalRemainingMissionTime()->rawValue().toUInt();
680

Valentin Platzgummer's avatar
Valentin Platzgummer committed
681
    if (managerVehicle != nullptr && enabled == true) {
682 683 684 685 686 687
        Fact *battery1percentRemaining = managerVehicle->battery1FactGroup()->getFact(VehicleBatteryFactGroup::_percentRemainingFactName);
        Fact *battery2percentRemaining = managerVehicle->battery2FactGroup()->getFact(VehicleBatteryFactGroup::_percentRemainingFactName);


        if (battery1percentRemaining->rawValue().toDouble() < batteryThreshold
                && battery2percentRemaining->rawValue().toDouble() < batteryThreshold) {
688 689 690
            if (!_lowBatteryHandlingTriggered) {                
                _lowBatteryHandlingTriggered = true;
                if ( !(_missionController->remainingTime() <= minTime) ) {
691
                    requestSmartRTL();
692 693 694 695 696 697 698 699 700 701
                }
            }
        }
        else {
            _lowBatteryHandlingTriggered = false;
        }

    }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
702 703 704
void WimaController::_eventTimerHandler()
{
    // Battery level check necessary?
705
    Fact *enableLowBatteryHandling = qgcApp()->toolbox()->settingsManager()->wimaSettings()->enableLowBatteryHandling();
706
    if ( enableLowBatteryHandling->rawValue().toBool() && _batteryLevelTicker.ready() )
Valentin Platzgummer's avatar
Valentin Platzgummer committed
707 708 709
        _checkBatteryLevel();

    // Snake flight plan update necessary?
710 711 712 713
//    if ( snakeEventLoopTicker.ready() ) {
//        if ( _enableSnake.rawValue().toBool() && _localPlanDataValid && !_snakeCalcInProgress && _scenarioDefinedBool) {
//        }
//    }
714

715
    if ( _nemoTimeoutTicker.ready() && _enableSnake.rawValue().toBool() ) {
716 717 718 719 720
        this->_nemoHeartbeat.setStatus(_fallbackStatus);
        emit WimaController::nemoStatusChanged();
        emit WimaController::nemoStatusStringChanged();
    }

721 722 723 724 725 726 727 728
    if ( _snakeTicker.ready() ) {
        if ( _enableSnake.rawValue().toBool() ) {
            if ( !_pRosBridge->isRunning() && _pRosBridge->ping() ) {
                _setupTopicService();
            }

            if ( !_pRosBridge->ping() ){
                _pRosBridge->reset();
729
            }
730 731 732 733

        } else {
            if ( _pRosBridge->isRunning() )
                _pRosBridge->reset();
734
        }
735
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
736 737 738
}

void WimaController::_smartRTLCleanUp(bool flying)
739
{
740 741 742 743 744
    if ( !flying) { // vehicle has landed
        _switchWaypointManager(_defaultManager);
        _missionController->removeAllFromVehicle();
        _missionController->removeAll();
        disconnect(masterController()->managerVehicle(), &Vehicle::flyingChanged, this, &WimaController::_smartRTLCleanUp);
745 746 747
    }
}

748 749
void WimaController::_setPhaseDistance(double distance)
{
750 751 752
    (void)distance;
//    if (!qFuzzyCompare(distance, _phaseDistance)) {
//        _phaseDistance = distance;
753

754 755
//        emit phaseDistanceChanged();
//    }
756 757 758 759
}

void WimaController::_setPhaseDuration(double duration)
{
760 761 762
    (void)duration;
//    if (!qFuzzyCompare(duration, _phaseDuration)) {
//        _phaseDuration = duration;
763

764 765
//        emit phaseDurationChanged();
//    }
766 767
}

768
bool WimaController::_checkSmartRTLPreCondition(QString &errorString)
769 770
{
    if (!_localPlanDataValid) {
771 772
        errorString.append(tr("No WiMA data available. Please define at least a measurement and a service area."));
        return false;
773
    }
774

775
    return _rtlManager.checkPrecondition(errorString);
776 777
}

778
void WimaController::_switchWaypointManager(WaypointManager::ManagerBase &manager)
779
{
780 781 782
    if (_currentManager != &manager) {
        _currentManager = &manager;

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        disconnect(&_overlapWaypoints,             &Fact::rawValueChanged,
                   this, &WimaController::_updateOverlap);
        disconnect(&_maxWaypointsPerPhase,         &Fact::rawValueChanged,
                   this, &WimaController::_updateMaxWaypoints);
        disconnect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged,
                   this, &WimaController::_setStartIndex);

        _maxWaypointsPerPhase.setRawValue(_currentManager->N());
        _overlapWaypoints.setRawValue(_currentManager->overlap());
        _nextPhaseStartWaypointIndex.setRawValue(_currentManager->startIndex());

        connect(&_overlapWaypoints,             &Fact::rawValueChanged,
                this, &WimaController::_updateOverlap);
        connect(&_maxWaypointsPerPhase,         &Fact::rawValueChanged,
                this, &WimaController::_updateMaxWaypoints);
        connect(&_nextPhaseStartWaypointIndex,  &Fact::rawValueChanged,
                this, &WimaController::_setStartIndex);
800

801 802 803 804
        emit missionItemsChanged();
        emit currentMissionItemsChanged();
        emit waypointPathChanged();
        emit currentWaypointPathChanged();
805

806
        qWarning() << "WimaController::_switchWaypointManager: statistics update missing.";
807 808 809
    }
}

810 811
void WimaController::_initSmartRTL()
{
812 813 814 815
    QString errorString;
    static int attemptCounter = 0;
    attemptCounter++;

816
    if ( _checkSmartRTLPreCondition(errorString) ) {
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
        _masterController->managerVehicle()->pauseVehicle();
        connect(masterController()->managerVehicle(), &Vehicle::flyingChanged, this, &WimaController::_smartRTLCleanUp);
        if ( _rtlManager.update() ) { // Calculate return path.
            _switchWaypointManager(_rtlManager);
            attemptCounter = 0;
            emit smartRTLPathConfirm();
            return;
        }
    } else if (attemptCounter > SMART_RTL_MAX_ATTEMPTS) {
        errorString.append(tr("Smart RTL: No success after maximum number of attempts."));
        qgcApp()->showMessage(errorString);
        attemptCounter = 0;
    } else {
        _smartRTLTimer.singleShot(SMART_RTL_ATTEMPT_INTERVAL, this, &WimaController::_initSmartRTL);
    }
832 833
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
834 835 836 837 838 839 840 841
void WimaController::_setSnakeCalcInProgress(bool inProgress)
{
    if (_snakeCalcInProgress != inProgress){
        _snakeCalcInProgress = inProgress;
        emit snakeCalcInProgressChanged();
    }
}

842 843
void WimaController::_snakeStoreWorkerResults()
{
844
    _setSnakeCalcInProgress(false);
845
    auto start = std::chrono::high_resolution_clock::now();
846 847
    _snakeManager.clear();

848
    const WorkerResult_t &r = _snakeWorker.getResult();
849
    if (!r.success) {
850
        //qgcApp()->showMessage(r.errorMessage);
851 852 853 854 855
        return;
    }

    // create Mission items from r.waypoints
    long n = r.waypoints.size() - r.returnPathIdx.size() - r.arrivalPathIdx.size() + 2;
856
    if (n < 1) {
857 858
        return;
    }
859 860 861

    // Create QVector<QGeoCoordinate> containing all waypoints;
    unsigned long startIdx = r.arrivalPathIdx.last();
862 863
    unsigned  long endIdx = r.returnPathIdx.first();
    for (unsigned long i = startIdx; i <= endIdx; ++i) {
864
        _snakeManager.push_back(r.waypoints[int(i)].value<QGeoCoordinate>());
865 866
    }

867
    _snakeManager.update();
868

869
    emit missionItemsChanged();
870 871 872
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
873 874 875 876

    auto end = std::chrono::high_resolution_clock::now();
    double duration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
    qWarning() << "WimaController::_snakeStoreWorkerResults execution time: " << duration << " ms.";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
877 878
}

879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
void WimaController::_initStartSnakeWorker()
{
    if ( !_enableSnake.rawValue().toBool() )
        return;

    // Stop worker thread if running.
    if ( _snakeWorker.isRunning() ) {
        _snakeWorker.quit();
    }

    // Initialize _snakeWorker.
    _snakeWorker.setScenario(_scenario);
    _snakeWorker.setProgress(_nemoProgress.progress());
    _snakeWorker.setLineDistance(_snakeLineDistance.rawValue().toDouble());
    _snakeWorker.setMinTransectLength(_snakeMinTransectLength.rawValue().toDouble());
    _setSnakeCalcInProgress(true);

    // Start worker thread.
    _snakeWorker.start();
}

900 901 902 903 904 905 906 907
void WimaController::_switchSnakeManager(QVariant variant)
{
    if (variant.value<bool>()){
        _switchWaypointManager(_snakeManager);
    } else {
        _switchWaypointManager(_defaultManager);
    }
}
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967

void WimaController::_setupTopicService()
{
    _pRosBridge->start();
    _pRosBridge->publish(_snakeOrigin, "/snake/origin");
    _pRosBridge->publish(_snakeTilesLocal, "/snake/tiles");
    _pRosBridge->subscribe("/nemo/progress",
                           /* callback */ [this](JsonDocUPtr pDoc){
        int requiredSize = this->_snakeTilesLocal.polygons().size();
        auto& progress = this->_nemoProgress;
        if ( !this->_pRosBridge->casePacker()->unpack(pDoc, progress)
             || progress.progress().size() != requiredSize ) {
            progress.progress().fill(0, requiredSize);
        }

        emit WimaController::nemoProgressChanged();
    });
    _pRosBridge->subscribe("/nemo/heartbeat",
                           /* callback */ [this](JsonDocUPtr pDoc){
        if ( !this->_pRosBridge->casePacker()->unpack(pDoc, this->_nemoHeartbeat) ) {
            if ( this->_nemoHeartbeat.status() == this->_fallbackStatus )
                return;
            this->_nemoHeartbeat.setStatus(this->_fallbackStatus);
        }

        this->_nemoTimeoutTicker.reset();
        this->_fallbackStatus = -1; /*Timeout*/
        emit WimaController::nemoStatusChanged();
        emit WimaController::nemoStatusStringChanged();
    });

    auto pOrigin = &_snakeOrigin;
    auto casePacker = _pCasePacker;
    _pRosBridge->advertiseService("/snake/get_origin", "snake_msgs/GetOrigin",
                                  [casePacker, pOrigin](JsonDocUPtr) -> JsonDocUPtr {
        JsonDocUPtr pDoc = casePacker->pack(*pOrigin, "");
        casePacker->removeTag(pDoc);
        rapidjson::Document value(rapidjson::kObjectType);
        JsonDocUPtr         pReturn(new rapidjson::Document(rapidjson::kObjectType));
        value.CopyFrom(*pDoc, pReturn->GetAllocator());
        pReturn->AddMember("origin", value, pReturn->GetAllocator());

        return pReturn;

    });

    auto pTiles = &_snakeTilesLocal;
    _pRosBridge->advertiseService("/snake/get_tiles", "snake_msgs/GetTiles",
                                  [casePacker, pTiles](JsonDocUPtr) -> JsonDocUPtr {

        JsonDocUPtr pDoc =  casePacker->pack(*pTiles, "");
        casePacker->removeTag(pDoc);
        rapidjson::Document value(rapidjson::kObjectType);
        JsonDocUPtr         pReturn(new rapidjson::Document(rapidjson::kObjectType));
        value.CopyFrom(*pDoc, pReturn->GetAllocator());
        pReturn->AddMember("tiles", value, pReturn->GetAllocator());
        return pReturn;

    });
}