WimaController.cc 31.6 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 22
#define SMART_RTL_MAX_ATTEMPTS 3 // times
#define SMART_RTL_ATTEMPT_INTERVAL 200 // ms
#define EVENT_TIMER_INTERVAL 50 // ms

23

24

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

44 45 46 47
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")};
48

Valentin Platzgummer's avatar
Valentin Platzgummer committed
49 50
using namespace snake;
using namespace snake_geometry;
51

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

103 104 105 106 107 108 109 110 111 112 113 114 115 116
    // 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);
    }
117

118
    // Periodic.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
119
    connect(&_eventTimer, &QTimer::timeout, this, &WimaController::_eventTimerHandler);
120 121
    //_eventTimer.setInterval(EVENT_TIMER_INTERVAL);
    _eventTimer.start(EVENT_TIMER_INTERVAL);
122

Valentin Platzgummer's avatar
Valentin Platzgummer committed
123
    // Snake Worker Thread.
124 125 126
    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
127

128
    // Snake.
129 130 131 132
    connect(&_enableSnake, &Fact::rawValueChanged, this, &WimaController::_initStartSnakeWorker);
    _initStartSnakeWorker();
    connect(&_enableSnake, &Fact::rawValueChanged, this, &WimaController::_switchSnakeManager);
    _switchSnakeManager(_enableSnake.rawValue());
133 134
}

135 136 137 138 139 140 141 142 143
PlanMasterController *WimaController::masterController() {
    return _masterController;
}

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

QmlObjectListModel *WimaController::visualItems() {
144 145 146 147
    return &_areas;
}

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

QmlObjectListModel *WimaController::currentMissionItems() {
152
    return const_cast<QmlObjectListModel*>(&_currentManager->currentMissionItems());
153 154 155 156
}

QVariantList WimaController::waypointPath()
{
157
    return const_cast<QVariantList&>(_currentManager->waypointsVariant());
158 159
}

160
QVariantList WimaController::currentWaypointPath()
161
{
162
    return const_cast<QVariantList&>(_currentManager->currentWaypointsVariant());
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 197 198 199 200
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;
}

201 202 203 204 205 206 207
QVector<int> WimaController::nemoProgress() {
    if ( _nemoProgress.progress().size() == _snakeTileCenterPoints.size() )
        return _nemoProgress.progress();
    else
        return QVector<int>(_snakeTileCenterPoints.size(), 0);
}

208 209
double WimaController::phaseDistance() const
{
210
    return 0.0;
211 212 213 214
}

double WimaController::phaseDuration() const
{
215
    return 0.0;
216 217
}

218 219 220 221 222 223
int WimaController::nemoStatus() const
{
    return _nemoHeartbeat.status();
}

QString WimaController::nemoStatusString() const
Valentin Platzgummer's avatar
Valentin Platzgummer committed
224
{
225
    return _nemoStatusMap.at(_nemoHeartbeat.status());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
226 227 228 229 230 231 232
}

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

233 234 235
void WimaController::setMasterController(PlanMasterController *masterC)
{
    _masterController = masterC;
236
    _managerSettings.setMasterController(masterC);
237 238 239 240 241 242
    emit masterControllerChanged();
}

void WimaController::setMissionController(MissionController *missionC)
{
    _missionController = missionC;
243
    _managerSettings.setMissionController(missionC);
244 245 246
    emit missionControllerChanged();
}

247 248
void WimaController::nextPhase()
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
249
    _calcNextPhase();
250 251
}

252
void WimaController::previousPhase()
253
{        
254 255
    if ( !_currentManager->previous() ) {
        Q_ASSERT(false);
256
    }
257 258 259 260 261

    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
262 263 264 265
}

void WimaController::resetPhase()
{
266 267
    if ( !_currentManager->reset() ) {
        Q_ASSERT(false);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
268
    }
269 270 271 272 273

    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
274 275
}

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

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

295
    return forceUpload();
296 297
}

298
bool WimaController::forceUpload()
299
{
300 301
    auto &currentMissionItems = _defaultManager.currentMissionItems();
    if (currentMissionItems.count() < 1)
302
        return false;
303 304

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

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

321
    _masterController->sendToVehicle();
322 323

    return true;
324
}
325

326 327 328
void WimaController::removeFromVehicle()
{
    _masterController->removeAllFromVehicle();
329 330 331
    _missionController->removeAll();
}

332
void WimaController::executeSmartRTL()
333
{
334 335
    forceUpload();
    masterController()->managerVehicle()->startMission();
336 337
}

338
void WimaController::initSmartRTL()
339
{
340
    _initSmartRTL();
341 342
}

343 344 345 346 347 348
void WimaController::removeVehicleTrajectoryHistory()
{
    Vehicle *managerVehicle = masterController()->managerVehicle();
    managerVehicle->trajectoryPoints()->clear();
}

349
bool WimaController::_calcShortestPath(const QGeoCoordinate &start, const QGeoCoordinate &destination, QVector<QGeoCoordinate> &path)
350 351 352
{
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
353 354 355 356 357
    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
358
    QVector<QPointF> path2D;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
359 360 361

    bool retVal = PolygonCalculus::shortestPath(polygon2D, start2D, end2D, path2D);
    toGeoList(path2D, /*origin*/ start, path);
362 363 364 365

    return  retVal;
}

366
bool WimaController::setWimaPlanData(const WimaPlanData &planData)
367
{
368
    // reset visual items
369 370
    _areas.clear();
    _defaultManager.clear();
371 372
    _snakeTiles.polygons().clear();
    _snakeTilesLocal.polygons().clear();
373
    _snakeTileCenterPoints.clear();
374

375 376 377
    emit visualItemsChanged();
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
378
    emit waypointPathChanged();
379
    emit currentWaypointPathChanged();
380
    emit snakeTilesChanged();
381
    emit snakeTileCenterPointsChanged();
382

383
    _localPlanDataValid = false;
384

385 386
    // extract list with WimaAreas
    QList<const WimaAreaData*> areaList = planData.areaList();
387

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

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

398 399
            continue;
        }
400

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

406
            continue;
407
        }
408

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

414 415
            continue;
        }
416

417 418 419
        if (areaData->type() == WimaJoinedAreaData::typeString) { // is it a corridor?
            _joinedArea =  *qobject_cast<const WimaJoinedAreaData*>(areaData);
            areaCounter++;
420
            _areas.append(&_joinedArea);
421

422 423
            continue;
        }
424

425 426 427
        if (areaCounter >= numAreas)
            break;
    }
428

429
    if (areaCounter != numAreas) {
430
        Q_ASSERT(false);
431 432
        return false;
    }
433

434 435
    emit visualItemsChanged();

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

443
    for (auto item : tempMissionItems) {
444
        _defaultManager.push_back(item.coordinate());
445
    }
446

447 448 449
    _managerSettings.setHomePosition( QGeoCoordinate(_serviceArea.center().latitude(),
                                                     _serviceArea.center().longitude(),
                                                     0) );
450

451
    if( !_defaultManager.reset() ){
452
        Q_ASSERT(false);
453
        return false;
454
    }
455

456 457 458 459 460 461 462
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit waypointPathChanged();
    emit currentWaypointPathChanged();



Valentin Platzgummer's avatar
Valentin Platzgummer committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    // 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;
484

Valentin Platzgummer's avatar
Valentin Platzgummer committed
485 486 487 488
    _scenario.addArea(mArea);
    _scenario.addArea(sArea);
    _scenario.addArea(corridor);

489
    // Check if scenario is defined.
490 491 492
    if ( !_scenario.defined(_snakeTileWidth.rawValue().toUInt(),
                            _snakeTileHeight.rawValue().toUInt(),
                            _snakeMinTileArea.rawValue().toUInt()) ) {
493
        Q_ASSERT(false);
494
        return false;
495
    }
496

497
    {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
498 499 500 501 502
        // Get tiles and origin.
        auto origin = _scenario.getOrigin();
        _snakeOrigin.setLatitude(origin[0]);
        _snakeOrigin.setLongitude(origin[1]);
        _snakeOrigin.setAltitude(origin[2]);
503 504
        const auto &tiles = _scenario.getTiles();
        const auto &cps = _scenario.getTileCenterPoints();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
505
        for ( unsigned int i=0; i < tiles.size(); ++i ) {
506 507 508 509 510 511 512 513 514 515 516
            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));
517
        }
518 519 520 521 522
    }

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

536 537 538
    _localPlanDataValid = true;
    return true;
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
539

540 541 542 543 544 545 546 547 548 549 550
WimaController *WimaController::thisPointer()
{
    return this;
}

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

552
    emit missionItemsChanged();
553 554
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
555
    emit waypointPathChanged();
556

557
    return true;
558 559
}

560
bool WimaController::_setStartIndex()
561
{
562
    bool value;
563
    _currentManager->setStartIndex(_nextPhaseStartWaypointIndex.rawValue().toUInt(&value)-1);
564 565 566 567 568
    Q_ASSERT(value);
    (void)value;

    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
569 570
        return false;
    }
571

572
    emit missionItemsChanged();
573
    emit currentMissionItemsChanged();
574 575
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
576 577

    return true;
578
}
579

580
void WimaController::_recalcCurrentPhase()
581
{
582 583
    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
584
    }
585

586 587 588
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
589 590
    emit waypointPathChanged();
}
591 592

void WimaController::_updateOverlap()
593
{
594
    bool value;
595
    _currentManager->setOverlap(_overlapWaypoints.rawValue().toUInt(&value));
596 597
    Q_ASSERT(value);
    (void)value;
598

599
    if ( !_currentManager->update() ) {
600 601 602 603 604
        assert(false);
    }

    emit missionItemsChanged();
    emit currentMissionItemsChanged();
605
    emit currentWaypointPathChanged();
606
    emit waypointPathChanged();
607
}
608

609
void WimaController::_updateMaxWaypoints()
610
{
611
    bool value;
612
    _currentManager->setN(_maxWaypointsPerPhase.rawValue().toUInt(&value));
613 614
    Q_ASSERT(value);
    (void)value;
615

616 617
    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
618
    }
619

620 621 622 623
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
624 625
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
626
void WimaController::_updateflightSpeed()
627
{
628
    bool value;
629
    _managerSettings.setFlightSpeed(_flightSpeed.rawValue().toDouble(&value));
630 631 632 633 634 635
    Q_ASSERT(value);
    (void)value;

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

637 638 639 640
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
641 642
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
643
void WimaController::_updateArrivalReturnSpeed()
644
{
645
    bool value;
646
    _managerSettings.setArrivalReturnSpeed(_arrivalReturnSpeed.rawValue().toDouble(&value));
647 648 649 650 651 652
    Q_ASSERT(value);
    (void)value;

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

654 655 656 657
    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
658 659
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
660
void WimaController::_updateAltitude()
661
{
662
    bool value;
663
    _managerSettings.setAltitude(_altitude.rawValue().toDouble(&value));
664 665 666 667 668 669
    Q_ASSERT(value);
    (void)value;

    if ( !_currentManager->update() ) {
        Q_ASSERT(false);
    }
670 671 672 673 674

    emit missionItemsChanged();
    emit currentMissionItemsChanged();
    emit currentWaypointPathChanged();
    emit waypointPathChanged();
675 676
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
677
void WimaController::_checkBatteryLevel()
678
{
679 680 681 682 683
    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();
684

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


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

    }
}

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

    // Snake flight plan update necessary?
714 715 716 717
//    if ( snakeEventLoopTicker.ready() ) {
//        if ( _enableSnake.rawValue().toBool() && _localPlanDataValid && !_snakeCalcInProgress && _scenarioDefinedBool) {
//        }
//    }
718

719
    if ( _nemoTimeoutTicker.ready() && _enableSnake.rawValue().toBool() ) {
720 721 722 723 724
        this->_nemoHeartbeat.setStatus(_fallbackStatus);
        emit WimaController::nemoStatusChanged();
        emit WimaController::nemoStatusStringChanged();
    }

725 726
    if ( _snakeTicker.ready() ) {
        if ( _enableSnake.rawValue().toBool() ) {
727
            if ( !_pRosBridge->isRunning() && _pRosBridge->connected() ) {
728
                _setupTopicService();
729
            } else if ( _pRosBridge->isRunning() && !_pRosBridge->connected() ){
730
                _pRosBridge->reset();
731
            }
732
        } else  if ( _pRosBridge->isRunning() ) {
733
                _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;

    });
}