AirMapFlightPlanManager.cc 36.4 KB
Newer Older
Gus Grubba's avatar
Gus Grubba committed
1 2 3 4 5 6 7 8 9 10 11 12
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "AirMapFlightPlanManager.h"
#include "AirMapManager.h"
#include "AirMapRulesetsManager.h"
13
#include "AirMapAdvisoryManager.h"
Gus Grubba's avatar
Gus Grubba committed
14
#include "QGCApplication.h"
15
#include "SettingsManager.h"
Gus Grubba's avatar
Gus Grubba committed
16

17
#include "PlanMasterController.h"
Gus Grubba's avatar
Gus Grubba committed
18 19 20 21 22 23 24 25 26 27
#include "QGCMAVLink.h"

#include "airmap/pilots.h"
#include "airmap/flights.h"
#include "airmap/date_time.h"
#include "airmap/flight_plans.h"
#include "airmap/geometry.h"

using namespace airmap;

Gus Grubba's avatar
Gus Grubba committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
//-----------------------------------------------------------------------------
AirMapFlightAuthorization::AirMapFlightAuthorization(const Evaluation::Authorization auth, QObject *parent)
    : AirspaceFlightAuthorization(parent)
    , _auth(auth)
{
}

//-----------------------------------------------------------------------------
AirspaceFlightAuthorization::AuthorizationStatus
AirMapFlightAuthorization::status()
{
    switch(_auth.status) {
    case Evaluation::Authorization::Status::accepted:
        return AirspaceFlightAuthorization::Accepted;
    case Evaluation::Authorization::Status::rejected:
        return AirspaceFlightAuthorization::Rejected;
    case Evaluation::Authorization::Status::pending:
        return AirspaceFlightAuthorization::Pending;
    case Evaluation::Authorization::Status::accepted_upon_submission:
        return AirspaceFlightAuthorization::AcceptedOnSubmission;
    case Evaluation::Authorization::Status::rejected_upon_submission:
        return AirspaceFlightAuthorization::RejectedOnSubmission;
    }
    return AirspaceFlightAuthorization::Unknown;
}

Gus Grubba's avatar
Gus Grubba committed
54 55 56
//-----------------------------------------------------------------------------
AirMapFlightInfo::AirMapFlightInfo(const airmap::Flight& flight, QObject *parent)
    : AirspaceFlightInfo(parent)
Gus Grubba's avatar
Gus Grubba committed
57
    , _flight(flight)
Gus Grubba's avatar
Gus Grubba committed
58 59 60 61 62 63
{
    //-- TODO: Load bounding box geometry


}

Gus Grubba's avatar
Gus Grubba committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
//-----------------------------------------------------------------------------
QString
AirMapFlightInfo::createdTime()
{
    return QDateTime::fromMSecsSinceEpoch((quint64)airmap::milliseconds_since_epoch(_flight.created_at)).toString("yyyy MM dd - hh:mm:ss");
}

//-----------------------------------------------------------------------------
QString
AirMapFlightInfo::startTime()
{
    return QDateTime::fromMSecsSinceEpoch((quint64)airmap::milliseconds_since_epoch(_flight.start_time)).toString("yyyy MM dd - hh:mm:ss");
}

//-----------------------------------------------------------------------------
QString
AirMapFlightInfo::endTime()
{
    return QDateTime::fromMSecsSinceEpoch((quint64)airmap::milliseconds_since_epoch(_flight.end_time)).toString("yyyy MM dd - hh:mm:ss");
}

Gus Grubba's avatar
Gus Grubba committed
85 86 87 88 89 90
//-----------------------------------------------------------------------------
AirMapFlightPlanManager::AirMapFlightPlanManager(AirMapSharedState& shared, QObject *parent)
    : AirspaceFlightPlanProvider(parent)
    , _shared(shared)
{
    connect(&_pollTimer, &QTimer::timeout, this, &AirMapFlightPlanManager::_pollBriefing);
91 92 93
    //-- Set some valid, initial start/end time
    _flightStartTime = QDateTime::currentDateTime().addSecs(10 * 60);
    _flightEndTime   = _flightStartTime.addSecs(30 * 60);
Gus Grubba's avatar
Gus Grubba committed
94 95
}

Gus Grubba's avatar
Gus Grubba committed
96 97 98 99 100 101 102
//-----------------------------------------------------------------------------
AirMapFlightPlanManager::~AirMapFlightPlanManager()
{
    _advisories.deleteListAndContents();
    _rulesets.deleteListAndContents();
}

Gus Grubba's avatar
Gus Grubba committed
103 104
//-----------------------------------------------------------------------------
void
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
AirMapFlightPlanManager::setFlightStartTime(QDateTime start)
{
    if(_flightStartTime != start) {
        //-- Can't start in the past
        if(start < QDateTime::currentDateTime()) {
            start = QDateTime::currentDateTime().addSecs(5 * 60);
        }
        _flightStartTime = start;
        emit flightStartTimeChanged();
    }
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::setFlightEndTime(QDateTime end)
{
    if(_flightEndTime != end) {
        //-- End has to be after start
        if(end < _flightStartTime) {
            end = _flightStartTime.addSecs(30 * 60);
        }
        _flightEndTime = end;
        emit flightEndTimeChanged();
    }
}

//-----------------------------------------------------------------------------
void
133
AirMapFlightPlanManager::startFlightPlanning(PlanMasterController *planController)
Gus Grubba's avatar
Gus Grubba committed
134 135 136 137 138 139 140
{
    if (!_shared.client()) {
        qCDebug(AirMapManagerLog) << "No AirMap client instance. Will not create a flight";
        return;
    }

    if (_state != State::Idle) {
Gus Grubba's avatar
Gus Grubba committed
141
        qCWarning(AirMapManagerLog) << "AirMapFlightPlanManager::startFlightPlanning: State not idle";
Gus Grubba's avatar
Gus Grubba committed
142 143 144
        return;
    }

145
    //-- TODO: Check if there is an ongoing flight plan and do something about it (Delete it?)
146 147 148 149 150 151 152

    /*
     * if(!_flightPlan.isEmpty()) {
     *     do something;
     * }
     */

153 154
    if(!_planController) {
        _planController = planController;
155
        //-- Get notified of mission changes
156
        connect(planController->missionController(), &MissionController::missionBoundingCubeChanged, this, &AirMapFlightPlanManager::_missionChanged);
Gus Grubba's avatar
Gus Grubba committed
157 158 159
    }
}

160 161 162 163 164 165 166 167
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::submitFlightPlan()
{
    if(_flightPlan.isEmpty()) {
        qCWarning(AirMapManagerLog) << "Submit flight with no flight plan.";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
168
    _flightId.clear();
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    _state = State::FlightSubmit;
    FlightPlans::Submit::Parameters params;
    params.authorization = _shared.loginToken().toStdString();
    params.id            = _flightPlan.toStdString();
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    _shared.client()->flight_plans().submit(params, [this, isAlive](const FlightPlans::Submit::Result& result) {
        if (!isAlive.lock()) return;
        if (_state != State::FlightSubmit) return;
        if (result) {
            _flightId = QString::fromStdString(result.value().flight_id.get());
            _state    = State::FlightPolling;
            _pollBriefing();
        } else {
            QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
            emit error("Failed to submit Flight Plan",
                    QString::fromStdString(result.error().message()), description);
            _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
186 187
            _flightPermitStatus = AirspaceFlightPlanProvider::PermitRejected;
            emit flightPermitStatusChanged();
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        }
    });
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::updateFlightPlan()
{
    //-- Are we enabled?
    if(!qgcApp()->toolbox()->settingsManager()->airMapSettings()->enableAirMap()->rawValue().toBool()) {
        return;
    }
    //-- Do we have a license?
    if(!_shared.hasAPIKey()) {
        return;
    }
    _flightPermitStatus = AirspaceFlightPlanProvider::PermitPending;
    emit flightPermitStatusChanged();
    _updateFlightPlan();
}

Gus Grubba's avatar
Gus Grubba committed
209 210 211 212 213 214 215 216 217 218 219 220 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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::deleteSelectedFlightPlans()
{
    qCDebug(AirMapManagerLog) << "Delete flight plan";
    _flightsToDelete.clear();
    for(int i = 0; i < _flightList.count(); i++) {
        AirspaceFlightInfo* pInfo = _flightList.get(i);
        if(pInfo && pInfo->selected()) {
            _flightsToDelete << pInfo->flightPlanID();
        }
    }
    if(_flightsToDelete.count()) {
        deleteFlightPlan(QString());
    }
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::deleteFlightPlan(QString flightPlanID)
{
    qCDebug(AirMapManagerLog) << "Delete flight plan";
    if(!flightPlanID.isEmpty()) {
        _flightsToDelete.clear();
        _flightsToDelete << flightPlanID;
    }
    if (_pilotID == "") {
        //-- Need to get the pilot id
        qCDebug(AirMapManagerLog) << "Getting pilot ID";
        _state = State::GetPilotID;
        std::weak_ptr<LifetimeChecker> isAlive(_instance);
        _shared.doRequestWithLogin([this, isAlive](const QString& login_token) {
            if (!isAlive.lock()) return;
            Pilots::Authenticated::Parameters params;
            params.authorization = login_token.toStdString();
            _shared.client()->pilots().authenticated(params, [this, isAlive](const Pilots::Authenticated::Result& result) {
                if (!isAlive.lock()) return;
                if (_state != State::GetPilotID) return;
                if (result) {
                    _pilotID = QString::fromStdString(result.value().id);
                    qCDebug(AirMapManagerLog) << "Got Pilot ID:"<<_pilotID;
                    _state = State::Idle;
                    _deleteFlightPlan();
                } else {
                    _state = State::Idle;
                    QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
                    emit error("Failed to get pilot ID", QString::fromStdString(result.error().message()), description);
                    return;
                }
            });
        });
    } else {
        _deleteFlightPlan();
    }
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_deleteFlightPlan()
{
    if(_flightsToDelete.count() < 1) {
        qCDebug(AirMapManagerLog) << "Delete non existing flight plan";
        return;
    }
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_deleteFlightPlan);
        return;
    }
    int idx = _flightList.findFlightPlanID(_flightsToDelete.last());
    if(idx >= 0) {
        AirspaceFlightInfo* pInfo = _flightList.get(idx);
        if(pInfo) {
            pInfo->setBeingDeleted(true);
        }
    }
    qCDebug(AirMapManagerLog) << "Deleting flight plan:" << _flightsToDelete.last();
    _state = State::FlightDelete;
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    FlightPlans::Delete::Parameters params;
    params.authorization = _shared.loginToken().toStdString();
    params.id = _flightsToDelete.last().toStdString();
    //-- Delete flight plan
    _shared.client()->flight_plans().delete_(params, [this, isAlive](const FlightPlans::Delete::Result& result) {
        if (!isAlive.lock()) return;
        if (_state != State::FlightDelete) return;
        if (result) {
            qCDebug(AirMapManagerLog) << "Flight plan deleted";
            _flightList.remove(_flightsToDelete.last());
        } else {
            QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
            emit error("Flight Plan deletion failed", QString::fromStdString(result.error().message()), description);
            AirspaceFlightInfo* pFlight = _flightList.get(_flightList.findFlightPlanID(_flightsToDelete.last()));
            if(pFlight) {
                pFlight->setBeingDeleted(false);
            }
        }
        _flightsToDelete.removeLast();
        //-- Keep at it until all flights are deleted
        //   TODO: This is ineficient. These whole airmapd transactions need to be moved into a separate
        //   worker thread.
        if(_flightsToDelete.count()) {
            QTimer::singleShot(10, this, &AirMapFlightPlanManager::_deleteFlightPlan);
        }
        _state = State::Idle;
    });
}

Gus Grubba's avatar
Gus Grubba committed
316
//-----------------------------------------------------------------------------
317 318
bool
AirMapFlightPlanManager::_collectFlightDtata()
Gus Grubba's avatar
Gus Grubba committed
319
{
320 321 322
    if(!_planController || !_planController->missionController()) {
        return false;
    }
Gus Grubba's avatar
Gus Grubba committed
323
    //-- Get flight bounding cube and prepare (box) polygon
324 325
    QGCGeoBoundingCube bc = *_planController->missionController()->travelBoundingCube();
    if(!bc.isValid() || !bc.area()) {
326
        //-- TODO: If single point, we need to set a point and a radius instead
327 328
        qCDebug(AirMapManagerLog) << "Not enough points for a flight plan.";
        return false;
329
    }
Gus Grubba's avatar
Gus Grubba committed
330
    _flight.maxAltitude   = fmax(bc.pointNW.altitude(), bc.pointSE.altitude());
331
    _flight.takeoffCoord  = _planController->missionController()->takeoffCoordinate();
332
    _flight.coords        = bc.polygon2D();
333 334
    _flight.bc            = bc;
    emit missionAreaChanged();
335
    //-- Flight Date/Time
336 337 338 339 340 341 342 343
    if(_flightStartTime.isNull() || _flightStartTime < QDateTime::currentDateTime()) {
        _flightStartTime = QDateTime::currentDateTime().addSecs(5 * 60);
        emit flightStartTimeChanged();
    }
    if(_flightEndTime.isNull() || _flightEndTime < _flightStartTime) {
        _flightEndTime = _flightStartTime.addSecs(30 * 60);
        emit flightEndTimeChanged();
    }
344 345 346 347 348 349 350 351 352 353 354 355 356
    return true;
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_createFlightPlan()
{
    _flight.reset();

    //-- Get flight data
    if(!_collectFlightDtata()) {
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
357 358 359

    qCDebug(AirMapManagerLog) << "About to create flight plan";
    qCDebug(AirMapManagerLog) << "Takeoff:     " << _flight.takeoffCoord;
360
    qCDebug(AirMapManagerLog) << "Bounding box:" << _flight.bc.pointNW << _flight.bc.pointSE;
361 362
    qCDebug(AirMapManagerLog) << "Flight Start:" << _flightStartTime;
    qCDebug(AirMapManagerLog) << "Flight End:  " << _flightEndTime;
Gus Grubba's avatar
Gus Grubba committed
363

364
    //-- Not Yet
365
    //return;
Gus Grubba's avatar
Gus Grubba committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

    if (_pilotID == "") {
        //-- Need to get the pilot id before uploading the flight plan
        qCDebug(AirMapManagerLog) << "Getting pilot ID";
        _state = State::GetPilotID;
        std::weak_ptr<LifetimeChecker> isAlive(_instance);
        _shared.doRequestWithLogin([this, isAlive](const QString& login_token) {
            if (!isAlive.lock()) return;
            Pilots::Authenticated::Parameters params;
            params.authorization = login_token.toStdString();
            _shared.client()->pilots().authenticated(params, [this, isAlive](const Pilots::Authenticated::Result& result) {
                if (!isAlive.lock()) return;
                if (_state != State::GetPilotID) return;
                if (result) {
                    _pilotID = QString::fromStdString(result.value().id);
                    qCDebug(AirMapManagerLog) << "Got Pilot ID:"<<_pilotID;
382
                    _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
383 384
                    _uploadFlightPlan();
                } else {
385
                    _flightPermitStatus = AirspaceFlightPlanProvider::PermitNone;
Gus Grubba's avatar
Gus Grubba committed
386 387 388 389
                    emit flightPermitStatusChanged();
                    _state = State::Idle;
                    QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
                    emit error("Failed to create Flight Plan", QString::fromStdString(result.error().message()), description);
390
                    return;
Gus Grubba's avatar
Gus Grubba committed
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
                }
            });
        });
    } else {
        _uploadFlightPlan();
    }

    _flightPermitStatus = AirspaceFlightPlanProvider::PermitPending;
    emit flightPermitStatusChanged();
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_uploadFlightPlan()
{
    qCDebug(AirMapManagerLog) << "Uploading flight plan";
Gus Grubba's avatar
Gus Grubba committed
407 408 409 410
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_uploadFlightPlan);
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
411 412 413 414 415 416 417
    _state = State::FlightUpload;
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    _shared.doRequestWithLogin([this, isAlive](const QString& login_token) {
        if (!isAlive.lock()) return;
        if (_state != State::FlightUpload) return;
        FlightPlans::Create::Parameters params;
        params.max_altitude = _flight.maxAltitude;
418
        params.min_altitude = 0.0;
Gus Grubba's avatar
Gus Grubba committed
419 420 421 422
        params.buffer       = 2.f;
        params.latitude     = _flight.takeoffCoord.latitude();
        params.longitude    = _flight.takeoffCoord.longitude();
        params.pilot.id     = _pilotID.toStdString();
Gus Grubba's avatar
Gus Grubba committed
423 424 425 426
        quint64 start       = _flightStartTime.toUTC().toMSecsSinceEpoch();
        quint64 end         = _flightEndTime.toUTC().toMSecsSinceEpoch();
        params.start_time   = airmap::from_milliseconds_since_epoch(airmap::Milliseconds{(long long)start});
        params.end_time     = airmap::from_milliseconds_since_epoch(airmap::Milliseconds{(long long)end});
Gus Grubba's avatar
Gus Grubba committed
427 428 429
        //-- Rules
        AirMapRulesetsManager* pRulesMgr = dynamic_cast<AirMapRulesetsManager*>(qgcApp()->toolbox()->airspaceManager()->ruleSets());
        if(pRulesMgr) {
Gus Grubba's avatar
Gus Grubba committed
430 431 432 433 434 435
            for(int rs = 0; rs < pRulesMgr->ruleSets()->count(); rs++) {
                AirMapRuleSet* ruleSet = qobject_cast<AirMapRuleSet*>(pRulesMgr->ruleSets()->get(rs));
                //-- If this ruleset is selected
                if(ruleSet && ruleSet->selected()) {
                    params.rulesets.push_back(ruleSet->id().toStdString());
                    //-- Features within each rule
436
                    /*
Gus Grubba's avatar
Gus Grubba committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
                    for(int r = 0; r < ruleSet->rules()->count(); r++) {
                        AirMapRule* rule = qobject_cast<AirMapRule*>(ruleSet->rules()->get(r));
                        if(rule) {
                            for(int f = 0; f < rule->features()->count(); f++) {
                                AirMapRuleFeature* feature = qobject_cast<AirMapRuleFeature*>(rule->features()->get(f));
                                if(feature && feature->value().isValid()) {
                                    switch(feature->type()) {
                                    case AirspaceRuleFeature::Boolean:
                                        params.features[feature->name().toStdString()] = RuleSet::Feature::Value(feature->value().toBool());
                                        break;
                                    case AirspaceRuleFeature::Float:
                                        params.features[feature->name().toStdString()] = RuleSet::Feature::Value(feature->value().toFloat());
                                        break;
                                    case AirspaceRuleFeature::String:
                                        params.features[feature->name().toStdString()] = RuleSet::Feature::Value(feature->value().toString().toStdString());
                                        break;
                                    default:
                                        qCWarning(AirMapManagerLog) << "Unknown type for feature" << feature->name();
                                    }
                                }
                            }
                        }
                    }
460
                    */
Gus Grubba's avatar
Gus Grubba committed
461
                }
Gus Grubba's avatar
Gus Grubba committed
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
            }
        }
        //-- Geometry: LineString
        Geometry::LineString lineString;
        for (const auto& qcoord : _flight.coords) {
            Geometry::Coordinate coord;
            coord.latitude  = qcoord.latitude();
            coord.longitude = qcoord.longitude();
            lineString.coordinates.push_back(coord);
        }
        params.geometry = Geometry(lineString);
        params.authorization = login_token.toStdString();
        //-- Create flight plan
        _shared.client()->flight_plans().create_by_polygon(params, [this, isAlive](const FlightPlans::Create::Result& result) {
            if (!isAlive.lock()) return;
            if (_state != State::FlightUpload) return;
            if (result) {
                _flightPlan = QString::fromStdString(result.value().id);
                qCDebug(AirMapManagerLog) << "Flight plan created:" << _flightPlan;
481
                _state = State::FlightPlanPolling;
Gus Grubba's avatar
Gus Grubba committed
482 483
                _pollBriefing();
            } else {
484
                _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
485
                QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
Gus Grubba's avatar
Gus Grubba committed
486
                emit error("Flight Plan creation failed", QString::fromStdString(result.error().message()), description);
Gus Grubba's avatar
Gus Grubba committed
487 488 489 490 491
            }
        });
    });
}

492 493 494 495
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_updateFlightPlan()
{
496 497 498
    //-- TODO: This is broken as the parameters for updating the plan have
    //   little to do with those used when creating it.

499
    qCDebug(AirMapManagerLog) << "Updating flight plan";
Gus Grubba's avatar
Gus Grubba committed
500 501 502 503 504

    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_updateFlightPlan);
        return;
    }
505 506 507 508 509 510 511 512 513 514
    //-- Get flight data
    if(!_collectFlightDtata()) {
        return;
    }

    qCDebug(AirMapManagerLog) << "Takeoff:     " << _flight.takeoffCoord;
    qCDebug(AirMapManagerLog) << "Bounding box:" << _flight.bc.pointNW << _flight.bc.pointSE;
    qCDebug(AirMapManagerLog) << "Flight Start:" << _flightStartTime;
    qCDebug(AirMapManagerLog) << "Flight End:  " << _flightEndTime;

515 516 517 518 519
    _state = State::FlightUpdate;
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    _shared.doRequestWithLogin([this, isAlive](const QString& login_token) {
        if (!isAlive.lock()) return;
        if (_state != State::FlightUpdate) return;
520 521 522 523 524 525 526
        FlightPlans::Update::Parameters params = {};
        params.authorization                 = login_token.toStdString();
        params.flight_plan.id                = _flightPlan.toStdString();
        params.flight_plan.pilot.id          = _pilotID.toStdString();
        params.flight_plan.altitude_agl.max  = _flight.maxAltitude;
        params.flight_plan.altitude_agl.min  = 0.0f;
        params.flight_plan.buffer            = 2.f;
527 528
        params.flight_plan.takeoff.latitude  = _flight.takeoffCoord.latitude();
        params.flight_plan.takeoff.longitude = _flight.takeoffCoord.longitude();
Gus Grubba's avatar
Gus Grubba committed
529 530 531 532
        quint64 start                        = _flightStartTime.toUTC().toMSecsSinceEpoch();
        quint64 end                          = _flightEndTime.toUTC().toMSecsSinceEpoch();
        params.flight_plan.start_time        = airmap::from_milliseconds_since_epoch(airmap::Milliseconds{(long long)start});
        params.flight_plan.end_time          = airmap::from_milliseconds_since_epoch(airmap::Milliseconds{(long long)end});
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
        //-- Rules
        /*
        AirMapRulesetsManager* pRulesMgr = dynamic_cast<AirMapRulesetsManager*>(qgcApp()->toolbox()->airspaceManager()->ruleSets());
        if(pRulesMgr) {
            foreach(QString ruleset, pRulesMgr->rulesetsIDs()) {
                params.flight_plan.rulesets.push_back(ruleset.toStdString());
            }
        }
        */
        //-- Geometry: LineString
        Geometry::LineString lineString;
        for (const auto& qcoord : _flight.coords) {
            Geometry::Coordinate coord;
            coord.latitude  = qcoord.latitude();
            coord.longitude = qcoord.longitude();
            lineString.coordinates.push_back(coord);
        }
        params.flight_plan.geometry = Geometry(lineString);
        //-- Update flight plan
        _shared.client()->flight_plans().update(params, [this, isAlive](const FlightPlans::Update::Result& result) {
            if (!isAlive.lock()) return;
            if (_state != State::FlightUpdate) return;
            if (result) {
556
                _state = State::FlightPlanPolling;
557 558 559
                qCDebug(AirMapManagerLog) << "Flight plan updated:" << _flightPlan;
                _pollBriefing();
            } else {
560
                _state = State::Idle;
561
                QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
Gus Grubba's avatar
Gus Grubba committed
562
                emit error("Flight Plan update failed", QString::fromStdString(result.error().message()), description);
563 564 565 566 567
            }
        });
    });
}

568 569 570 571 572 573 574 575 576 577
//-----------------------------------------------------------------------------
static bool
adv_sort(QObject* a, QObject* b)
{
    AirMapAdvisory* aa = qobject_cast<AirMapAdvisory*>(a);
    AirMapAdvisory* bb = qobject_cast<AirMapAdvisory*>(b);
    if(!aa || !bb) return false;
    return (int)aa->color() > (int)bb->color();
}

Gus Grubba's avatar
Gus Grubba committed
578 579 580 581 582 583 584 585 586 587
//-----------------------------------------------------------------------------
static bool
rules_sort(QObject* a, QObject* b)
{
    AirMapRule* aa = qobject_cast<AirMapRule*>(a);
    AirMapRule* bb = qobject_cast<AirMapRule*>(b);
    if(!aa || !bb) return false;
    return (int)aa->status() > (int)bb->status();
}

Gus Grubba's avatar
Gus Grubba committed
588 589 590 591
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_pollBriefing()
{
592
    if (_state != State::FlightPlanPolling && _state != State::FlightPolling) {
Gus Grubba's avatar
Gus Grubba committed
593 594 595 596
        return;
    }
    FlightPlans::RenderBriefing::Parameters params;
    params.authorization = _shared.loginToken().toStdString();
597
    params.id            = _flightPlan.toStdString();
Gus Grubba's avatar
Gus Grubba committed
598 599 600
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    _shared.client()->flight_plans().render_briefing(params, [this, isAlive](const FlightPlans::RenderBriefing::Result& result) {
        if (!isAlive.lock()) return;
601
        if (_state != State::FlightPlanPolling && _state != State::FlightPolling) return;
Gus Grubba's avatar
Gus Grubba committed
602 603 604
        if (result) {
            const FlightPlan::Briefing& briefing = result.value();
            qCDebug(AirMapManagerLog) << "Flight polling/briefing response";
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
            //-- Collect advisories
            _valid = false;
            _advisories.clearAndDeleteContents();
            const std::vector<Status::Advisory> advisories = briefing.airspace.advisories;
            _airspaceColor = (AirspaceAdvisoryProvider::AdvisoryColor)(int)briefing.airspace.color;
            for (const auto& advisory : advisories) {
                AirMapAdvisory* pAdvisory = new AirMapAdvisory(this);
                pAdvisory->_id          = QString::fromStdString(advisory.airspace.id());
                pAdvisory->_name        = QString::fromStdString(advisory.airspace.name());
                pAdvisory->_type        = (AirspaceAdvisory::AdvisoryType)(int)advisory.airspace.type();
                pAdvisory->_color       = (AirspaceAdvisoryProvider::AdvisoryColor)(int)advisory.color;
                _advisories.append(pAdvisory);
                qCDebug(AirMapManagerLog) << "Adding briefing advisory" << pAdvisory->name();
            }
            //-- Sort in order of color (priority)
            _advisories.beginReset();
            std::sort(_advisories.objectList()->begin(), _advisories.objectList()->end(), adv_sort);
            _advisories.endReset();
            _valid = true;
Gus Grubba's avatar
Gus Grubba committed
624
            //-- Collect Rulesets
Gus Grubba's avatar
Gus Grubba committed
625
            _authorizations.clearAndDeleteContents();
626 627 628 629
            _rulesViolation.clearAndDeleteContents();
            _rulesInfo.clearAndDeleteContents();
            _rulesReview.clearAndDeleteContents();
            _rulesFollowing.clearAndDeleteContents();
630
            _briefFeatures.clear();
Gus Grubba's avatar
Gus Grubba committed
631 632 633 634 635 636
            for(const auto& ruleset : briefing.evaluation.rulesets) {
                AirMapRuleSet* pRuleSet = new AirMapRuleSet(this);
                pRuleSet->_id = QString::fromStdString(ruleset.id);
                //-- Iterate Rules
                for (const auto& rule : ruleset.rules) {
                    AirMapRule* pRule = new AirMapRule(rule, this);
637 638 639 640
                    //-- Iterate Rule Features
                    for (const auto& feature : rule.features) {
                        AirMapRuleFeature* pFeature = new AirMapRuleFeature(feature, this);
                        pRule->_features.append(pFeature);
641 642 643 644
                        if(rule.status == RuleSet::Rule::Status::missing_info) {
                            _briefFeatures.append(pFeature);
                            qCDebug(AirMapManagerLog) << "Adding briefing feature" << pFeature->name() << pFeature->description() << pFeature->type();
                        }
645
                    }
Gus Grubba's avatar
Gus Grubba committed
646
                    pRuleSet->_rules.append(pRule);
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
                    //-- Rules separated by status for presentation
                    switch(rule.status) {
                    case RuleSet::Rule::Status::conflicting:
                        _rulesViolation.append(new AirMapRule(rule, this));
                        break;
                    case RuleSet::Rule::Status::not_conflicting:
                        _rulesFollowing.append(new AirMapRule(rule, this));
                        break;
                    case RuleSet::Rule::Status::missing_info:
                        _rulesInfo.append(new AirMapRule(rule, this));
                        break;
                    case RuleSet::Rule::Status::informational:
                        _rulesReview.append(new AirMapRule(rule, this));
                        break;
                    default:
                        break;
                    }
Gus Grubba's avatar
Gus Grubba committed
664 665
                }
                //-- Sort rules by relevance order
666
                pRuleSet->_rules.beginReset();
Gus Grubba's avatar
Gus Grubba committed
667
                std::sort(pRuleSet->_rules.objectList()->begin(), pRuleSet->_rules.objectList()->end(), rules_sort);
668
                pRuleSet->_rules.endReset();
Gus Grubba's avatar
Gus Grubba committed
669 670 671
                _rulesets.append(pRuleSet);
                qCDebug(AirMapManagerLog) << "Adding briefing ruleset" << pRuleSet->id();
            }
672
            //-- Evaluate briefing status
Gus Grubba's avatar
Gus Grubba committed
673 674 675 676
            bool rejected = false;
            bool accepted = false;
            bool pending  = false;
            for (const auto& authorization : briefing.evaluation.authorizations) {
Gus Grubba's avatar
Gus Grubba committed
677 678 679
                AirMapFlightAuthorization* pAuth = new AirMapFlightAuthorization(authorization, this);
                _authorizations.append(pAuth);
                qCDebug(AirMapManagerLog) << "Autorization:" << pAuth->name() << " (" << pAuth->message() << ")" << (int)pAuth->status();
Gus Grubba's avatar
Gus Grubba committed
680 681 682 683 684 685 686 687 688 689 690 691
                switch (authorization.status) {
                case Evaluation::Authorization::Status::accepted:
                case Evaluation::Authorization::Status::accepted_upon_submission:
                    accepted = true;
                    break;
                case Evaluation::Authorization::Status::rejected:
                case Evaluation::Authorization::Status::rejected_upon_submission:
                    rejected = true;
                    break;
                case Evaluation::Authorization::Status::pending:
                    pending = true;
                    break;
Gus Grubba's avatar
Gus Grubba committed
692 693 694 695
                //-- If we don't know, accept it
                default:
                    accepted = true;
                    break;
Gus Grubba's avatar
Gus Grubba committed
696 697 698 699 700 701
                }
            }
            if (briefing.evaluation.authorizations.size() == 0) {
                // If we don't get any authorizations, we assume it's accepted
                accepted = true;
            }
Gus Grubba's avatar
Gus Grubba committed
702 703
            emit advisoryChanged();
            emit rulesChanged();
Gus Grubba's avatar
Gus Grubba committed
704 705 706 707 708 709 710 711 712
            qCDebug(AirMapManagerLog) << "Flight approval: accepted=" << accepted << "rejected" << rejected << "pending" << pending;
            if ((rejected || accepted) && !pending) {
                if (rejected) { // rejected has priority
                    _flightPermitStatus = AirspaceFlightPlanProvider::PermitRejected;
                } else {
                    _flightPermitStatus = AirspaceFlightPlanProvider::PermitAccepted;
                }
                emit flightPermitStatusChanged();
                _state = State::Idle;
713 714
            } else {
                //-- Pending. Try again.
Gus Grubba's avatar
Gus Grubba committed
715
                _pollTimer.setSingleShot(true);
716
                _pollTimer.start(1000);
Gus Grubba's avatar
Gus Grubba committed
717 718
            }
        } else {
719
            _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
720 721 722 723 724 725 726 727 728
            QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
            emit error("Brief Request failed",
                    QString::fromStdString(result.error().message()), description);
        }
    });
}

//-----------------------------------------------------------------------------
void
729
AirMapFlightPlanManager::_missionChanged()
Gus Grubba's avatar
Gus Grubba committed
730
{
731 732 733 734 735 736 737 738
    //-- Are we enabled?
    if(!qgcApp()->toolbox()->settingsManager()->airMapSettings()->enableAirMap()->rawValue().toBool()) {
        return;
    }
    //-- Do we have a license?
    if(!_shared.hasAPIKey()) {
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
739
    //-- Creating a new flight plan?
740 741 742 743 744
    if(_state == State::Idle) {
        if(_flightPlan.isEmpty()) {
            _createFlightPlan();
        } else {
            //-- Plan is being modified
745
            _updateFlightPlan();
746
        }
Gus Grubba's avatar
Gus Grubba committed
747 748
    }
}
Gus Grubba's avatar
Gus Grubba committed
749 750 751

//-----------------------------------------------------------------------------
void
Gus Grubba's avatar
Gus Grubba committed
752
AirMapFlightPlanManager::loadFlightList(QDateTime startTime, QDateTime endTime)
Gus Grubba's avatar
Gus Grubba committed
753
{
Gus Grubba's avatar
Gus Grubba committed
754 755 756 757 758 759 760 761
    //-- TODO: This is not checking if the state is Idle. Again, these need to
    //   queued up and handled by a worker thread.
    qCDebug(AirMapManagerLog) << "Preparing load flight list";
    _loadingFlightList = true;
    emit loadingFlightListChanged();
    _rangeStart = startTime;
    _rangeEnd   = endTime;
    qCDebug(AirMapManagerLog) << "List flights from:" << _rangeStart.toString("yyyy MM dd - hh:mm:ss") << "to" << _rangeEnd.toString("yyyy MM dd - hh:mm:ss");
Gus Grubba's avatar
Gus Grubba committed
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
    if (_pilotID == "") {
        //-- Need to get the pilot id
        qCDebug(AirMapManagerLog) << "Getting pilot ID";
        _state = State::GetPilotID;
        std::weak_ptr<LifetimeChecker> isAlive(_instance);
        _shared.doRequestWithLogin([this, isAlive](const QString& login_token) {
            if (!isAlive.lock()) return;
            Pilots::Authenticated::Parameters params;
            params.authorization = login_token.toStdString();
            _shared.client()->pilots().authenticated(params, [this, isAlive](const Pilots::Authenticated::Result& result) {
                if (!isAlive.lock()) return;
                if (_state != State::GetPilotID) return;
                if (result) {
                    _pilotID = QString::fromStdString(result.value().id);
                    qCDebug(AirMapManagerLog) << "Got Pilot ID:"<<_pilotID;
                    _state = State::Idle;
                    _loadFlightList();
                } else {
                    _state = State::Idle;
                    QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
                    emit error("Failed to get pilot ID", QString::fromStdString(result.error().message()), description);
Gus Grubba's avatar
Gus Grubba committed
783 784
                    _loadingFlightList = false;
                    emit loadingFlightListChanged();
Gus Grubba's avatar
Gus Grubba committed
785 786 787 788 789 790 791 792 793 794 795 796 797
                    return;
                }
            });
        });
    } else {
        _loadFlightList();
    }
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_loadFlightList()
{
Gus Grubba's avatar
Gus Grubba committed
798 799 800 801 802
    qCDebug(AirMapManagerLog) << "Load flight list";
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_loadFlightList);
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
803
    _flightList.clear();
Gus Grubba's avatar
Gus Grubba committed
804 805 806 807 808 809 810 811
    emit flightListChanged();
    _state = State::LoadFlightList;
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    _shared.doRequestWithLogin([this, isAlive](const QString& login_token) {
        if (!isAlive.lock()) return;
        if (_state != State::LoadFlightList) return;
        Flights::Search::Parameters params;
        params.authorization = login_token.toStdString();
Gus Grubba's avatar
Gus Grubba committed
812 813 814 815 816
        quint64 start   = _rangeStart.toUTC().toMSecsSinceEpoch();
        quint64 end     = _rangeEnd.toUTC().toMSecsSinceEpoch();
        params.start_after  = airmap::from_milliseconds_since_epoch(airmap::Milliseconds{(long long)start});
        params.start_before = airmap::from_milliseconds_since_epoch(airmap::Milliseconds{(long long)end});
        params.limit    = 250;
Gus Grubba's avatar
Gus Grubba committed
817
        params.pilot_id = _pilotID.toStdString();
Gus Grubba's avatar
Gus Grubba committed
818
        qCDebug(AirMapManagerLog) << "List flights from:" << _rangeStart.toUTC().toString("yyyy MM dd - hh:mm:ss") << "to" << _rangeEnd.toUTC().toString("yyyy MM dd - hh:mm:ss");
Gus Grubba's avatar
Gus Grubba committed
819 820 821 822 823 824 825 826
        _shared.client()->flights().search(params, [this, isAlive](const Flights::Search::Result& result) {
            if (!isAlive.lock()) return;
            if (_state != State::LoadFlightList) return;
            if (result && result.value().flights.size() > 0) {
                const Flights::Search::Response& response = result.value();
                for (const auto& flight : response.flights) {
                    AirMapFlightInfo* pFlight = new AirMapFlightInfo(flight, this);
                    _flightList.append(pFlight);
Gus Grubba's avatar
Gus Grubba committed
827
                    qCDebug(AirMapManagerLog) << "Found:" << pFlight->flightID() << pFlight->flightPlanID();
Gus Grubba's avatar
Gus Grubba committed
828 829 830 831 832 833 834 835
                }
                emit flightListChanged();
            } else {
                if(!result) {
                    QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
                    emit error("Flight search failed", QString::fromStdString(result.error().message()), description);
                }
            }
Gus Grubba's avatar
Gus Grubba committed
836 837 838
            _state = State::Idle;
            _loadingFlightList = false;
            emit loadingFlightListChanged();
Gus Grubba's avatar
Gus Grubba committed
839 840 841 842
        });
    });
}