AirMapFlightPlanManager.cc 38.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
#include "QGCMAVLink.h"

#include "airmap/date_time.h"
#include "airmap/flight_plans.h"
22
#include "airmap/flights.h"
Gus Grubba's avatar
Gus Grubba committed
23
#include "airmap/geometry.h"
24
#include "airmap/pilots.h"
Gus Grubba's avatar
Gus Grubba committed
25 26 27

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 64 65 66 67 68 69 70 71 72
    //-- Load bounding box geometry
    const Geometry& geometry = flight.geometry;
    if(geometry.type() == Geometry::Type::polygon) {
        const Geometry::Polygon& polygon = geometry.details_for_polygon();
        for (const auto& vertex :  polygon.outer_ring.coordinates) {
            QGeoCoordinate coord;
            if (vertex.altitude) {
                coord = QGeoCoordinate(vertex.latitude, vertex.longitude, vertex.altitude.get());
            } else {
                coord = QGeoCoordinate(vertex.latitude, vertex.longitude);
            }
            _boundingBox.append(QVariant::fromValue(coord));
        }
    }
Gus Grubba's avatar
Gus Grubba committed
73 74
}

Gus Grubba's avatar
Gus Grubba committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88
//-----------------------------------------------------------------------------
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");
}

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
//-----------------------------------------------------------------------------
QDateTime
AirMapFlightInfo::qStartTime()
{
    return QDateTime::fromMSecsSinceEpoch((quint64)airmap::milliseconds_since_epoch(_flight.start_time));
}

//-----------------------------------------------------------------------------
bool
AirMapFlightInfo::active()
{
    QDateTime end = QDateTime::fromMSecsSinceEpoch((quint64)airmap::milliseconds_since_epoch(_flight.end_time));
    QDateTime now = QDateTime::currentDateTime();
    return end > now;
}

//-----------------------------------------------------------------------------
void
AirMapFlightInfo::setEndFlight(DateTime end)
{
    _flight.end_time = end;
    emit activeChanged();
}

Gus Grubba's avatar
Gus Grubba committed
113 114 115 116 117 118 119
//-----------------------------------------------------------------------------
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
120 121 122 123 124 125 126 127
//-----------------------------------------------------------------------------
AirMapFlightPlanManager::AirMapFlightPlanManager(AirMapSharedState& shared, QObject *parent)
    : AirspaceFlightPlanProvider(parent)
    , _shared(shared)
{
    connect(&_pollTimer, &QTimer::timeout, this, &AirMapFlightPlanManager::_pollBriefing);
}

Gus Grubba's avatar
Gus Grubba committed
128 129 130 131 132 133 134
//-----------------------------------------------------------------------------
AirMapFlightPlanManager::~AirMapFlightPlanManager()
{
    _advisories.deleteListAndContents();
    _rulesets.deleteListAndContents();
}

Gus Grubba's avatar
Gus Grubba committed
135 136
//-----------------------------------------------------------------------------
void
137 138
AirMapFlightPlanManager::setFlightStartTime(QDateTime start)
{
139
    quint64 startt = start.toUTC().toMSecsSinceEpoch();
140
    if(_flightPlan.start_time != airmap::from_milliseconds_since_epoch(airmap::milliseconds((long long)startt))) {
141 142 143
        //-- Can't start in the past
        if(start < QDateTime::currentDateTime()) {
            start = QDateTime::currentDateTime().addSecs(5 * 60);
144
            startt = start.toUTC().toMSecsSinceEpoch();
145
        }
146
        _flightPlan.start_time = airmap::from_milliseconds_since_epoch(airmap::milliseconds((long long)startt));
147 148 149 150 151 152 153 154
        emit flightStartTimeChanged();
    }
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::setFlightEndTime(QDateTime end)
{
155
    quint64 endt = end.toUTC().toMSecsSinceEpoch();
156
    if(_flightPlan.end_time != airmap::from_milliseconds_since_epoch(airmap::milliseconds((long long)endt))) {
157
        //-- End has to be after start
158 159 160
        if(end < flightStartTime()) {
            end = flightStartTime().addSecs(30 * 60);
            endt = end.toUTC().toMSecsSinceEpoch();
161
        }
162
        _flightPlan.end_time = airmap::from_milliseconds_since_epoch(airmap::milliseconds((long long)endt));
163 164 165 166
        emit flightEndTimeChanged();
    }
}

167 168 169 170 171 172 173 174 175 176 177 178 179 180
//-----------------------------------------------------------------------------
QDateTime
AirMapFlightPlanManager::flightStartTime() const
{
    return QDateTime::fromMSecsSinceEpoch((quint64)airmap::milliseconds_since_epoch(_flightPlan.start_time));
}

//-----------------------------------------------------------------------------
QDateTime
AirMapFlightPlanManager::flightEndTime() const
{
    return QDateTime::fromMSecsSinceEpoch((quint64)airmap::milliseconds_since_epoch(_flightPlan.end_time));
}

181 182
//-----------------------------------------------------------------------------
void
183
AirMapFlightPlanManager::startFlightPlanning(PlanMasterController *planController)
Gus Grubba's avatar
Gus Grubba committed
184 185 186 187 188 189 190
{
    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
191
        qCWarning(AirMapManagerLog) << "AirMapFlightPlanManager::startFlightPlanning: State not idle";
Gus Grubba's avatar
Gus Grubba committed
192 193 194
        return;
    }

195
    //-- TODO: Check if there is an ongoing flight plan and do something about it (Delete it?)
196 197

    /*
198
     * if(!flightPlanID().isEmpty()) {
199 200 201 202
     *     do something;
     * }
     */

203 204
    if(!_planController) {
        _planController = planController;
205
        //-- Get notified of mission changes
206
        connect(planController->missionController(), &MissionController::missionBoundingCubeChanged, this, &AirMapFlightPlanManager::_missionChanged);
Gus Grubba's avatar
Gus Grubba committed
207 208 209
    }
}

210 211 212 213
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::submitFlightPlan()
{
214
    if(flightPlanID().isEmpty()) {
215 216 217
        qCWarning(AirMapManagerLog) << "Submit flight with no flight plan.";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
218
    _flightId.clear();
219 220 221
    _state = State::FlightSubmit;
    FlightPlans::Submit::Parameters params;
    params.authorization = _shared.loginToken().toStdString();
222
    params.id            = flightPlanID().toStdString();
223 224 225 226 227
    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) {
228 229 230
            _flightPlan = result.value();
            _flightId = QString::fromStdString(_flightPlan.flight_id.get());
            _state = State::Idle;
231 232 233 234 235 236
            _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
237 238
            _flightPermitStatus = AirspaceFlightPlanProvider::PermitRejected;
            emit flightPermitStatusChanged();
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
        }
    });
}

//-----------------------------------------------------------------------------
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();
257
    _updateFlightPlan(true);
258 259
}

Gus Grubba's avatar
Gus Grubba committed
260 261
//-----------------------------------------------------------------------------
void
262
AirMapFlightPlanManager::endFlight(QString flightID)
Gus Grubba's avatar
Gus Grubba committed
263
{
264 265
    qCDebug(AirMapManagerLog) << "End flight";
    _flightToEnd = flightID;
Gus Grubba's avatar
Gus Grubba committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    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;
282
                    _endFlight();
Gus Grubba's avatar
Gus Grubba committed
283 284 285 286 287 288 289 290 291
                } 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 {
292
        _endFlight();
Gus Grubba's avatar
Gus Grubba committed
293 294 295 296 297
    }
}

//-----------------------------------------------------------------------------
void
298
AirMapFlightPlanManager::_endFlight()
Gus Grubba's avatar
Gus Grubba committed
299
{
300 301
    if(_flightToEnd.isEmpty()) {
        qCDebug(AirMapManagerLog) << "End non existing flight";
Gus Grubba's avatar
Gus Grubba committed
302 303
        return;
    }
304
    qCDebug(AirMapManagerLog) << "End Flight. State:" << (int)_state;
Gus Grubba's avatar
Gus Grubba committed
305
    if(_state != State::Idle) {
306
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_endFlight);
Gus Grubba's avatar
Gus Grubba committed
307 308
        return;
    }
309 310
    qCDebug(AirMapManagerLog) << "Ending flight:" << _flightToEnd;
    _state = State::FlightEnd;
Gus Grubba's avatar
Gus Grubba committed
311
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
312
    Flights::EndFlight::Parameters params;
Gus Grubba's avatar
Gus Grubba committed
313
    params.authorization = _shared.loginToken().toStdString();
314 315 316
    params.id = _flightToEnd.toStdString();
    //-- End flight
    _shared.client()->flights().end_flight(params, [this, isAlive](const Flights::EndFlight::Result& result) {
Gus Grubba's avatar
Gus Grubba committed
317
        if (!isAlive.lock()) return;
318
        if (_state != State::FlightEnd) return;
Gus Grubba's avatar
Gus Grubba committed
319
        if (result) {
320 321 322 323 324 325 326 327
            qCDebug(AirMapManagerLog) << "Flight Ended";
            int idx = _flightList.findFlightID(_flightToEnd);
            if(idx >= 0) {
                AirMapFlightInfo* pInfo = qobject_cast<AirMapFlightInfo*>(_flightList.get(idx));
                if(pInfo) {
                    pInfo->setEndFlight(result.value().end_time);
                }
            }
Gus Grubba's avatar
Gus Grubba committed
328 329
        } else {
            QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
330
            emit error("End flight failed", QString::fromStdString(result.error().message()), description);
Gus Grubba's avatar
Gus Grubba committed
331
        }
332
        _flightToEnd.clear();
Gus Grubba's avatar
Gus Grubba committed
333 334 335 336
        _state = State::Idle;
    });
}

Gus Grubba's avatar
Gus Grubba committed
337
//-----------------------------------------------------------------------------
338 339
bool
AirMapFlightPlanManager::_collectFlightDtata()
Gus Grubba's avatar
Gus Grubba committed
340
{
341 342 343
    if(!_planController || !_planController->missionController()) {
        return false;
    }
Gus Grubba's avatar
Gus Grubba committed
344
    //-- Get flight bounding cube and prepare (box) polygon
345 346
    QGCGeoBoundingCube bc = *_planController->missionController()->travelBoundingCube();
    if(!bc.isValid() || !bc.area()) {
347
        //-- TODO: If single point, we need to set a point and a radius instead
348 349
        qCDebug(AirMapManagerLog) << "Not enough points for a flight plan.";
        return false;
350
    }
Gus Grubba's avatar
Gus Grubba committed
351
    _flight.maxAltitude   = fmax(bc.pointNW.altitude(), bc.pointSE.altitude());
352
    _flight.takeoffCoord  = _planController->missionController()->takeoffCoordinate();
353
    _flight.coords        = bc.polygon2D();
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
    _flight.bc            = bc;
    emit missionAreaChanged();
    return true;
}

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

    //-- Get flight data
    if(!_collectFlightDtata()) {
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
369 370 371

    qCDebug(AirMapManagerLog) << "About to create flight plan";
    qCDebug(AirMapManagerLog) << "Takeoff:     " << _flight.takeoffCoord;
372
    qCDebug(AirMapManagerLog) << "Bounding box:" << _flight.bc.pointNW << _flight.bc.pointSE;
373 374
    qCDebug(AirMapManagerLog) << "Flight Start:" << flightStartTime().toString();
    qCDebug(AirMapManagerLog) << "Flight End:  " << flightEndTime().toString();
Gus Grubba's avatar
Gus Grubba committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

    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;
391
                    _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
392 393
                    _uploadFlightPlan();
                } else {
394
                    _flightPermitStatus = AirspaceFlightPlanProvider::PermitNone;
Gus Grubba's avatar
Gus Grubba committed
395 396 397 398
                    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);
399
                    return;
Gus Grubba's avatar
Gus Grubba committed
400 401 402 403 404 405 406 407 408 409 410
                }
            });
        });
    } else {
        _uploadFlightPlan();
    }

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

411 412
//-----------------------------------------------------------------------------
void
413
AirMapFlightPlanManager::_updateRulesAndFeatures(std::vector<RuleSet::Id>& rulesets, std::unordered_map<std::string, RuleSet::Feature::Value>& features, bool updateFeatures)
414 415 416 417 418 419 420 421
{
    AirMapRulesetsManager* pRulesMgr = dynamic_cast<AirMapRulesetsManager*>(qgcApp()->toolbox()->airspaceManager()->ruleSets());
    if(pRulesMgr) {
        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()) {
                rulesets.push_back(ruleSet->id().toStdString());
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
                //-- Features within each rule (only when updating)
                if(updateFeatures) {
                    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(features.find(feature->name().toStdString()) != features.end()) {
                                    qCDebug(AirMapManagerLog) << "Removing duplicate:" << feature->name();
                                    continue;
                                }
                                if(feature && feature->value().isValid()) {
                                    switch(feature->type()) {
                                    case AirspaceRuleFeature::Boolean:
                                        if(feature->value().toInt() == 0 || feature->value().toInt() == 1) {
                                            features[feature->name().toStdString()] = RuleSet::Feature::Value(feature->value().toBool());
                                        } else {
                                            //-- If not set, default to false
                                            features[feature->name().toStdString()] = RuleSet::Feature::Value(false);
                                        }
                                        break;
                                    case AirspaceRuleFeature::Float:
                                        //-- Sanity check for floats
                                        if(std::isfinite(feature->value().toFloat())) {
                                            features[feature->name().toStdString()] = RuleSet::Feature::Value(feature->value().toFloat());
                                        }
                                        break;
                                    case AirspaceRuleFeature::String:
                                        //-- Skip empty responses
                                        if(!feature->value().toString().isEmpty()) {
                                            features[feature->name().toStdString()] = RuleSet::Feature::Value(feature->value().toString().toStdString());
                                        }
                                        break;
                                    default:
                                        qCWarning(AirMapManagerLog) << "Unknown type for feature" << feature->name();
457 458 459 460 461 462 463 464 465 466 467
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Gus Grubba's avatar
Gus Grubba committed
468 469 470 471
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_uploadFlightPlan()
{
472
    qCDebug(AirMapManagerLog) << "Uploading flight plan. State:" << (int)_state;
Gus Grubba's avatar
Gus Grubba committed
473 474 475 476
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_uploadFlightPlan);
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
477 478 479 480 481 482 483
    _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;
484
        params.min_altitude = 0.0;
Gus Grubba's avatar
Gus Grubba committed
485 486 487 488
        params.buffer       = 2.f;
        params.latitude     = _flight.takeoffCoord.latitude();
        params.longitude    = _flight.takeoffCoord.longitude();
        params.pilot.id     = _pilotID.toStdString();
489 490
        quint64 start       = QDateTime::currentDateTimeUtc().toMSecsSinceEpoch();
        quint64 end         = start + 60 * 30 * 1000;
491 492
        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));
493 494
        //-- Rules & Features
        _updateRulesAndFeatures(params.rulesets, params.features);
495 496
        //-- Geometry: polygon
        Geometry::Polygon polygon;
Gus Grubba's avatar
Gus Grubba committed
497 498 499 500
        for (const auto& qcoord : _flight.coords) {
            Geometry::Coordinate coord;
            coord.latitude  = qcoord.latitude();
            coord.longitude = qcoord.longitude();
501
            polygon.outer_ring.coordinates.push_back(coord);
Gus Grubba's avatar
Gus Grubba committed
502
        }
503
        params.geometry = Geometry(polygon);
Gus Grubba's avatar
Gus Grubba committed
504 505 506 507 508
        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;
509
            _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
510
            if (result) {
511 512
                _flightPlan = result.value();
                qCDebug(AirMapManagerLog) << "Flight plan created:" << flightPlanID();
Gus Grubba's avatar
Gus Grubba committed
513 514 515
                _pollBriefing();
            } else {
                QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
Gus Grubba's avatar
Gus Grubba committed
516
                emit error("Flight Plan creation failed", QString::fromStdString(result.error().message()), description);
Gus Grubba's avatar
Gus Grubba committed
517 518 519 520 521
            }
        });
    });
}

522 523
//-----------------------------------------------------------------------------
void
524
AirMapFlightPlanManager::_updateFlightPlanOnTimer()
525
{
526 527
    _updateFlightPlan(false);
}
528

529 530 531 532
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_updateFlightPlan(bool interactive)
{
533
    qCDebug(AirMapManagerLog) << "Updating flight plan. State:" << (int)_state;
Gus Grubba's avatar
Gus Grubba committed
534 535

    if(_state != State::Idle) {
536
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_updateFlightPlanOnTimer);
Gus Grubba's avatar
Gus Grubba committed
537 538
        return;
    }
539 540 541 542 543 544 545
    //-- Get flight data
    if(!_collectFlightDtata()) {
        return;
    }

    qCDebug(AirMapManagerLog) << "Takeoff:     " << _flight.takeoffCoord;
    qCDebug(AirMapManagerLog) << "Bounding box:" << _flight.bc.pointNW << _flight.bc.pointSE;
546 547 548 549 550 551 552 553 554
    qCDebug(AirMapManagerLog) << "Flight Start:" << flightStartTime().toString();
    qCDebug(AirMapManagerLog) << "Flight End:  " << flightEndTime().toString();

    //-- Update local instance of the flight plan
    _flightPlan.altitude_agl.max  = _flight.maxAltitude;
    _flightPlan.altitude_agl.min  = 0.0f;
    _flightPlan.buffer            = 2.f;
    _flightPlan.takeoff.latitude  = _flight.takeoffCoord.latitude();
    _flightPlan.takeoff.longitude = _flight.takeoffCoord.longitude();
555 556 557
    //-- Rules & Features
    _flightPlan.rulesets.clear();
    _flightPlan.features.clear();
558 559
    //-- If interactive, we collect features otherwise we don't
    _updateRulesAndFeatures(_flightPlan.rulesets, _flightPlan.features, interactive);
560 561 562 563 564 565 566 567 568
    //-- Geometry: polygon
    Geometry::Polygon polygon;
    for (const auto& qcoord : _flight.coords) {
        Geometry::Coordinate coord;
        coord.latitude  = qcoord.latitude();
        coord.longitude = qcoord.longitude();
        polygon.outer_ring.coordinates.push_back(coord);
    }
    _flightPlan.geometry = Geometry(polygon);
569 570 571 572 573
    _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;
574 575
        FlightPlans::Update::Parameters params = {};
        params.authorization                 = login_token.toStdString();
576
        params.flight_plan                   = _flightPlan;
577 578 579 580
        //-- 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;
581
            _state = State::Idle;
582
            if (result) {
583
                qCDebug(AirMapManagerLog) << "Flight plan updated:" << flightPlanID();
584 585 586
                _pollBriefing();
            } else {
                QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
Gus Grubba's avatar
Gus Grubba committed
587
                emit error("Flight Plan update failed", QString::fromStdString(result.error().message()), description);
588 589 590 591 592
            }
        });
    });
}

593 594 595 596 597 598 599 600 601 602
//-----------------------------------------------------------------------------
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
603 604 605 606 607 608 609 610 611 612
//-----------------------------------------------------------------------------
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();
}

613 614 615 616 617 618 619 620 621 622 623 624 625
//-----------------------------------------------------------------------------
bool
AirMapFlightPlanManager::_findBriefFeature(const QString& name)
{
    for(int i = 0; i < _briefFeatures.count(); i++ ) {
        AirMapRuleFeature* feature = qobject_cast<AirMapRuleFeature*>(_briefFeatures.get(i));
        if (feature && feature->name() == name) {
            return true;
        }
    }
    return false;
}

Gus Grubba's avatar
Gus Grubba committed
626 627 628 629
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_pollBriefing()
{
630 631 632
    qCDebug(AirMapManagerLog) << "Poll Briefing. State:" << (int)_state;
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_pollBriefing);
Gus Grubba's avatar
Gus Grubba committed
633 634
        return;
    }
635
    _state = State::FlightPolling;
Gus Grubba's avatar
Gus Grubba committed
636 637
    FlightPlans::RenderBriefing::Parameters params;
    params.authorization = _shared.loginToken().toStdString();
638
    params.id            = flightPlanID().toStdString();
Gus Grubba's avatar
Gus Grubba committed
639 640 641
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    _shared.client()->flight_plans().render_briefing(params, [this, isAlive](const FlightPlans::RenderBriefing::Result& result) {
        if (!isAlive.lock()) return;
642
        if (_state != State::FlightPolling) return;
Gus Grubba's avatar
Gus Grubba committed
643 644 645
        if (result) {
            const FlightPlan::Briefing& briefing = result.value();
            qCDebug(AirMapManagerLog) << "Flight polling/briefing response";
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
            //-- 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
665
            //-- Collect Rulesets
Gus Grubba's avatar
Gus Grubba committed
666
            _authorizations.clearAndDeleteContents();
667 668 669 670
            _rulesViolation.clearAndDeleteContents();
            _rulesInfo.clearAndDeleteContents();
            _rulesReview.clearAndDeleteContents();
            _rulesFollowing.clearAndDeleteContents();
671
            _briefFeatures.clear();
Gus Grubba's avatar
Gus Grubba committed
672 673 674 675 676 677
            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);
678 679 680 681
                    //-- Iterate Rule Features
                    for (const auto& feature : rule.features) {
                        AirMapRuleFeature* pFeature = new AirMapRuleFeature(feature, this);
                        pRule->_features.append(pFeature);
682
                        if(rule.status == RuleSet::Rule::Status::missing_info) {
683 684 685 686 687 688
                            if(!_findBriefFeature(pFeature->name())) {
                                _briefFeatures.append(pFeature);
                                qCDebug(AirMapManagerLog) << "Adding briefing feature" << pFeature->name() << pFeature->description() << pFeature->type();
                            } else {
                                qCDebug(AirMapManagerLog) << "Skipping briefing feature duplicate" << pFeature->name() << pFeature->description() << pFeature->type();
                            }
689
                        }
690
                    }
Gus Grubba's avatar
Gus Grubba committed
691
                    pRuleSet->_rules.append(pRule);
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
                    //-- 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
709 710
                }
                //-- Sort rules by relevance order
711
                pRuleSet->_rules.beginReset();
Gus Grubba's avatar
Gus Grubba committed
712
                std::sort(pRuleSet->_rules.objectList()->begin(), pRuleSet->_rules.objectList()->end(), rules_sort);
713
                pRuleSet->_rules.endReset();
Gus Grubba's avatar
Gus Grubba committed
714 715 716
                _rulesets.append(pRuleSet);
                qCDebug(AirMapManagerLog) << "Adding briefing ruleset" << pRuleSet->id();
            }
717
            //-- Evaluate briefing status
Gus Grubba's avatar
Gus Grubba committed
718 719 720 721
            bool rejected = false;
            bool accepted = false;
            bool pending  = false;
            for (const auto& authorization : briefing.evaluation.authorizations) {
Gus Grubba's avatar
Gus Grubba committed
722 723 724
                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
725 726 727 728 729 730 731 732 733 734 735 736
                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
737 738 739 740
                //-- If we don't know, accept it
                default:
                    accepted = true;
                    break;
Gus Grubba's avatar
Gus Grubba committed
741 742 743 744 745 746
                }
            }
            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
747 748
            emit advisoryChanged();
            emit rulesChanged();
Gus Grubba's avatar
Gus Grubba committed
749
            qCDebug(AirMapManagerLog) << "Flight approval: accepted=" << accepted << "rejected" << rejected << "pending" << pending;
750
            _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
751 752 753 754 755 756 757
            if ((rejected || accepted) && !pending) {
                if (rejected) { // rejected has priority
                    _flightPermitStatus = AirspaceFlightPlanProvider::PermitRejected;
                } else {
                    _flightPermitStatus = AirspaceFlightPlanProvider::PermitAccepted;
                }
                emit flightPermitStatusChanged();
758 759
            } else {
                //-- Pending. Try again.
Gus Grubba's avatar
Gus Grubba committed
760
                _pollTimer.setSingleShot(true);
761
                _pollTimer.start(1000);
Gus Grubba's avatar
Gus Grubba committed
762 763
            }
        } else {
764
            _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
765 766 767 768 769 770 771 772 773
            QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
            emit error("Brief Request failed",
                    QString::fromStdString(result.error().message()), description);
        }
    });
}

//-----------------------------------------------------------------------------
void
774
AirMapFlightPlanManager::_missionChanged()
Gus Grubba's avatar
Gus Grubba committed
775
{
776 777 778 779 780 781 782 783
    //-- 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
784
    //-- Creating a new flight plan?
785
    if(_state == State::Idle) {
786
        if(flightPlanID().isEmpty()) {
787 788 789
            _createFlightPlan();
        } else {
            //-- Plan is being modified
790
            _updateFlightPlan();
791
        }
Gus Grubba's avatar
Gus Grubba committed
792 793
    }
}
Gus Grubba's avatar
Gus Grubba committed
794 795 796

//-----------------------------------------------------------------------------
void
Gus Grubba's avatar
Gus Grubba committed
797
AirMapFlightPlanManager::loadFlightList(QDateTime startTime, QDateTime endTime)
Gus Grubba's avatar
Gus Grubba committed
798
{
Gus Grubba's avatar
Gus Grubba committed
799 800 801 802 803 804 805 806
    //-- 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
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    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
828 829
                    _loadingFlightList = false;
                    emit loadingFlightListChanged();
Gus Grubba's avatar
Gus Grubba committed
830 831 832 833 834 835 836 837 838 839 840 841 842
                    return;
                }
            });
        });
    } else {
        _loadFlightList();
    }
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_loadFlightList()
{
843
    qCDebug(AirMapManagerLog) << "Load flight list. State:" << (int)_state;
Gus Grubba's avatar
Gus Grubba committed
844 845 846 847
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_loadFlightList);
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
848
    _flightList.clear();
Gus Grubba's avatar
Gus Grubba committed
849 850 851 852 853 854 855 856
    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
857 858
        quint64 start   = _rangeStart.toUTC().toMSecsSinceEpoch();
        quint64 end     = _rangeEnd.toUTC().toMSecsSinceEpoch();
859 860
        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));
Gus Grubba's avatar
Gus Grubba committed
861
        params.limit    = 250;
Gus Grubba's avatar
Gus Grubba committed
862 863 864 865 866 867 868 869 870
        params.pilot_id = _pilotID.toStdString();
        _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);
871
                    qCDebug(AirMapManagerLog) << "Found:" << pFlight->flightID() << pFlight->flightPlanID() << pFlight->endTime();
Gus Grubba's avatar
Gus Grubba committed
872
                }
873
                _flightList.sortStartFlight();
Gus Grubba's avatar
Gus Grubba committed
874 875 876 877 878 879 880
                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
881 882 883
            _state = State::Idle;
            _loadingFlightList = false;
            emit loadingFlightListChanged();
Gus Grubba's avatar
Gus Grubba committed
884 885 886 887
        });
    });
}