AirMapFlightPlanManager.cc 40.2 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
//-----------------------------------------------------------------------------
QString
AirMapFlightInfo::createdTime()
{
Gus Grubba's avatar
Gus Grubba committed
79
    return QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(airmap::milliseconds_since_epoch(_flight.created_at))).toString("yyyy MM dd - hh:mm:ss");
Gus Grubba's avatar
Gus Grubba committed
80 81 82 83 84 85
}

//-----------------------------------------------------------------------------
QString
AirMapFlightInfo::startTime()
{
Gus Grubba's avatar
Gus Grubba committed
86
    return QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(airmap::milliseconds_since_epoch(_flight.start_time))).toString("yyyy MM dd - hh:mm:ss");
Gus Grubba's avatar
Gus Grubba committed
87 88
}

89 90 91 92
//-----------------------------------------------------------------------------
QDateTime
AirMapFlightInfo::qStartTime()
{
Gus Grubba's avatar
Gus Grubba committed
93
    return QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(airmap::milliseconds_since_epoch(_flight.start_time)));
94 95 96 97 98 99
}

//-----------------------------------------------------------------------------
bool
AirMapFlightInfo::active()
{
Gus Grubba's avatar
Gus Grubba committed
100
    QDateTime end = QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(airmap::milliseconds_since_epoch(_flight.end_time)));
101 102 103 104 105 106 107 108 109 110 111 112
    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
//-----------------------------------------------------------------------------
QString
AirMapFlightInfo::endTime()
{
Gus Grubba's avatar
Gus Grubba committed
117
    return QDateTime::fromMSecsSinceEpoch(static_cast<qint64>(airmap::milliseconds_since_epoch(_flight.end_time))).toString("yyyy MM dd - hh:mm:ss");
Gus Grubba's avatar
Gus Grubba committed
118 119
}

Gus Grubba's avatar
Gus Grubba committed
120 121 122 123 124 125
//-----------------------------------------------------------------------------
AirMapFlightPlanManager::AirMapFlightPlanManager(AirMapSharedState& shared, QObject *parent)
    : AirspaceFlightPlanProvider(parent)
    , _shared(shared)
{
    connect(&_pollTimer, &QTimer::timeout, this, &AirMapFlightPlanManager::_pollBriefing);
Gus Grubba's avatar
Gus Grubba committed
126
    _flightStartTime = QDateTime::currentDateTime().addSecs(60);
Gus Grubba's avatar
Gus Grubba committed
127 128
}

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

Gus Grubba's avatar
Gus Grubba committed
136 137
//-----------------------------------------------------------------------------
void
138 139
AirMapFlightPlanManager::setFlightStartTime(QDateTime start)
{
Gus Grubba's avatar
Gus Grubba committed
140
    if(start < QDateTime::currentDateTime()) {
141
        start = QDateTime::currentDateTime().addSecs(1);
142
        setDirty(true);
Gus Grubba's avatar
Gus Grubba committed
143 144 145
    }
    if(_flightStartTime != start) {
        _flightStartTime = start;
146
        setDirty(true);
147 148
        emit flightStartTimeChanged();
    }
149
    qCDebug(AirMapManagerLog) << "Set time start time" << _flightStartTime;
150 151 152 153
}

//-----------------------------------------------------------------------------
void
154
AirMapFlightPlanManager::setFlightStartsNow(bool now)
155
{
156
    _flightStartsNow = now;
157
    setDirty(true);
158 159 160 161 162 163 164
    emit flightStartsNowChanged();
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::setFlightDuration(int seconds)
{
165 166 167 168 169 170 171 172
    if(_flightDuration != seconds || _flightDuration < 30) {
        _flightDuration = seconds;
        if(_flightDuration < 30) {
            _flightDuration = 30;
        }
        setDirty(true);
        emit flightDurationChanged();
        qCDebug(AirMapManagerLog) << "Set time duration" << _flightDuration;
173 174 175
    }
}

176 177 178 179
//-----------------------------------------------------------------------------
QDateTime
AirMapFlightPlanManager::flightStartTime() const
{
Gus Grubba's avatar
Gus Grubba committed
180
    return _flightStartTime;
181 182 183
}

//-----------------------------------------------------------------------------
184 185
int
AirMapFlightPlanManager::flightDuration() const
186
{
187
    return _flightDuration;
188 189
}

190 191
//-----------------------------------------------------------------------------
void
192
AirMapFlightPlanManager::startFlightPlanning(PlanMasterController *planController)
Gus Grubba's avatar
Gus Grubba committed
193 194 195 196 197 198 199
{
    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
200
        qCWarning(AirMapManagerLog) << "AirMapFlightPlanManager::startFlightPlanning: State not idle";
Gus Grubba's avatar
Gus Grubba committed
201 202 203
        return;
    }

204
    //-- TODO: Check if there is an ongoing flight plan and do something about it (Delete it?)
205 206

    /*
207
     * if(!flightPlanID().isEmpty()) {
208 209 210 211
     *     do something;
     * }
     */

212 213
    if(!_planController) {
        _planController = planController;
214
        //-- Get notified of mission changes
215
        connect(planController->missionController(), &MissionController::missionBoundingCubeChanged, this, &AirMapFlightPlanManager::_missionChanged);
Gus Grubba's avatar
Gus Grubba committed
216
    }
Gus Grubba's avatar
Gus Grubba committed
217 218
    //-- Set initial flight start time
    setFlightStartTime(QDateTime::currentDateTime().addSecs(5 * 60));
Gus Grubba's avatar
Gus Grubba committed
219 220
}

221 222 223 224
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::submitFlightPlan()
{
225
    if(flightPlanID().isEmpty()) {
226 227 228
        qCWarning(AirMapManagerLog) << "Submit flight with no flight plan.";
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
229
    _flightId.clear();
Gus Grubba's avatar
Gus Grubba committed
230
    emit flightIDChanged(_flightId);
231 232 233
    _state = State::FlightSubmit;
    FlightPlans::Submit::Parameters params;
    params.authorization = _shared.loginToken().toStdString();
234
    params.id            = flightPlanID().toStdString();
235 236 237 238 239
    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) {
240 241 242
            _flightPlan = result.value();
            _flightId = QString::fromStdString(_flightPlan.flight_id.get());
            _state = State::Idle;
243
            _pollBriefing();
Gus Grubba's avatar
Gus Grubba committed
244
            emit flightIDChanged(_flightId);
245 246 247 248 249
        } 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
250 251
            _flightPermitStatus = AirspaceFlightPlanProvider::PermitRejected;
            emit flightPermitStatusChanged();
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        }
    });
}

//-----------------------------------------------------------------------------
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();
270
    setDirty(false);
271
    _updateFlightPlan(true);
272 273
}

Gus Grubba's avatar
Gus Grubba committed
274 275
//-----------------------------------------------------------------------------
void
276
AirMapFlightPlanManager::endFlight(QString flightID)
Gus Grubba's avatar
Gus Grubba committed
277
{
278 279
    qCDebug(AirMapManagerLog) << "End flight";
    _flightToEnd = flightID;
280
    if (_shared.pilotID().isEmpty()) {
Gus Grubba's avatar
Gus Grubba committed
281 282 283 284 285 286 287 288 289 290 291 292
        //-- 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) {
293 294 295
                    QString pilotID = QString::fromStdString(result.value().id);
                    _shared.setPilotID(pilotID);
                    qCDebug(AirMapManagerLog) << "Got Pilot ID:" << pilotID;
Gus Grubba's avatar
Gus Grubba committed
296
                    _state = State::Idle;
297
                    _endFlight();
Gus Grubba's avatar
Gus Grubba committed
298 299 300 301 302 303 304 305 306
                } 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 {
307
        _endFlight();
Gus Grubba's avatar
Gus Grubba committed
308 309 310 311 312
    }
}

//-----------------------------------------------------------------------------
void
313
AirMapFlightPlanManager::_endFlight()
Gus Grubba's avatar
Gus Grubba committed
314
{
315 316
    if(_flightToEnd.isEmpty()) {
        qCDebug(AirMapManagerLog) << "End non existing flight";
Gus Grubba's avatar
Gus Grubba committed
317 318
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
319
    qCDebug(AirMapManagerLog) << "End Flight. State:" << static_cast<int>(_state);
Gus Grubba's avatar
Gus Grubba committed
320
    if(_state != State::Idle) {
321
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_endFlight);
Gus Grubba's avatar
Gus Grubba committed
322 323
        return;
    }
324 325
    qCDebug(AirMapManagerLog) << "Ending flight:" << _flightToEnd;
    _state = State::FlightEnd;
Gus Grubba's avatar
Gus Grubba committed
326
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
327
    Flights::EndFlight::Parameters params;
Gus Grubba's avatar
Gus Grubba committed
328
    params.authorization = _shared.loginToken().toStdString();
329 330 331
    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
332
        if (!isAlive.lock()) return;
333
        if (_state != State::FlightEnd) return;
Gus Grubba's avatar
Gus Grubba committed
334
        if (result) {
335 336 337 338 339 340 341 342
            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
343 344
        } else {
            QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
345
            emit error("End flight failed", QString::fromStdString(result.error().message()), description);
Gus Grubba's avatar
Gus Grubba committed
346
        }
347
        _flightToEnd.clear();
Gus Grubba's avatar
Gus Grubba committed
348 349 350 351
        _state = State::Idle;
    });
}

Gus Grubba's avatar
Gus Grubba committed
352
//-----------------------------------------------------------------------------
353 354
bool
AirMapFlightPlanManager::_collectFlightDtata()
Gus Grubba's avatar
Gus Grubba committed
355
{
356 357 358
    if(!_planController || !_planController->missionController()) {
        return false;
    }
Gus Grubba's avatar
Gus Grubba committed
359
    //-- Get flight bounding cube and prepare (box) polygon
360
    QGCGeoBoundingCube bc = *_planController->missionController()->travelBoundingCube();
Gus Grubba's avatar
Gus Grubba committed
361
    if(!bc.isValid() || (fabs(bc.area()) < 0.0001)) {
362
        //-- TODO: If single point, we need to set a point and a radius instead
363 364
        qCDebug(AirMapManagerLog) << "Not enough points for a flight plan.";
        return false;
365
    }
Gus Grubba's avatar
Gus Grubba committed
366
    _flight.maxAltitude   = static_cast<float>(fmax(bc.pointNW.altitude(), bc.pointSE.altitude()));
367
    _flight.takeoffCoord  = _planController->missionController()->takeoffCoordinate();
368
    _flight.coords        = bc.polygon2D();
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    _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
384 385 386

    qCDebug(AirMapManagerLog) << "About to create flight plan";
    qCDebug(AirMapManagerLog) << "Takeoff:     " << _flight.takeoffCoord;
387
    qCDebug(AirMapManagerLog) << "Bounding box:" << _flight.bc.pointNW << _flight.bc.pointSE;
388
    qCDebug(AirMapManagerLog) << "Flight Start:" << flightStartTime().toString();
389
    qCDebug(AirMapManagerLog) << "Flight Duration:  " << flightDuration();
Gus Grubba's avatar
Gus Grubba committed
390

391
    if (_shared.pilotID().isEmpty() && !_shared.settings().userName.isEmpty() && !_shared.settings().password.isEmpty()) {
Gus Grubba's avatar
Gus Grubba committed
392 393 394 395 396 397 398 399 400 401 402 403
        //-- 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) {
404 405 406
                    QString pilotID = QString::fromStdString(result.value().id);
                    _shared.setPilotID(pilotID);
                    qCDebug(AirMapManagerLog) << "Got Pilot ID:" << pilotID;
407
                    _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
408 409
                    _uploadFlightPlan();
                } else {
410
                    _flightPermitStatus = AirspaceFlightPlanProvider::PermitNone;
Gus Grubba's avatar
Gus Grubba committed
411 412 413 414
                    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);
415
                    return;
Gus Grubba's avatar
Gus Grubba committed
416 417 418 419 420 421 422 423 424 425 426
                }
            });
        });
    } else {
        _uploadFlightPlan();
    }

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

427 428
//-----------------------------------------------------------------------------
void
429
AirMapFlightPlanManager::_updateRulesAndFeatures(std::vector<RuleSet::Id>& rulesets, std::unordered_map<std::string, RuleSet::Feature::Value>& features, bool updateFeatures)
430
{
431
    auto* pRulesMgr = qobject_cast<AirMapRulesetsManager*>(qgcApp()->toolbox()->airspaceManager()->ruleSets());
432 433 434 435 436 437
    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());
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
                //-- 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())) {
Gus Grubba's avatar
Gus Grubba committed
462
                                            features[feature->name().toStdString()] = RuleSet::Feature::Value(feature->value().toDouble());
463 464 465 466 467 468 469 470 471 472
                                        }
                                        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();
473 474 475 476 477 478 479 480 481 482 483
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Gus Grubba's avatar
Gus Grubba committed
484 485 486 487
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_updateFlightStartEndTime(DateTime& start_time, DateTime& end_time)
{
488 489
    if(_flightStartsNow || _flightStartTime < QDateTime::currentDateTime()) {
        setFlightStartTime(QDateTime::currentDateTime().addSecs(1));
Gus Grubba's avatar
Gus Grubba committed
490 491 492
    }
    quint64 startt = static_cast<quint64>(_flightStartTime.toUTC().toMSecsSinceEpoch());
    start_time = airmap::from_milliseconds_since_epoch(airmap::milliseconds(static_cast<qint64>(startt)));
493
    quint64 endt = startt + (static_cast<uint64_t>(_flightDuration) * 1000);
Gus Grubba's avatar
Gus Grubba committed
494 495 496
    end_time = airmap::from_milliseconds_since_epoch(airmap::milliseconds(static_cast<qint64>(endt)));
}

Gus Grubba's avatar
Gus Grubba committed
497 498 499 500
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_uploadFlightPlan()
{
Gus Grubba's avatar
Gus Grubba committed
501
    qCDebug(AirMapManagerLog) << "Uploading flight plan. State:" << static_cast<int>(_state);
Gus Grubba's avatar
Gus Grubba committed
502 503 504 505
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_uploadFlightPlan);
        return;
    }
506 507
    //-- Reset "relevant" features
    _importantFeatures.clear();
Gus Grubba's avatar
Gus Grubba committed
508 509 510 511 512 513 514
    _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;
515
        params.min_altitude = 0.0;
Gus Grubba's avatar
Gus Grubba committed
516
        params.buffer       = 10.f;
Gus Grubba's avatar
Gus Grubba committed
517 518
        params.latitude     = static_cast<float>(_flight.takeoffCoord.latitude());
        params.longitude    = static_cast<float>(_flight.takeoffCoord.longitude());
519
        params.pilot.id     = _shared.pilotID().toStdString();
Gus Grubba's avatar
Gus Grubba committed
520 521
        //-- Handle flight start/end
        _updateFlightStartEndTime(params.start_time, params.end_time);
522 523
        //-- Rules & Features
        _updateRulesAndFeatures(params.rulesets, params.features);
524 525
        //-- Geometry: polygon
        Geometry::Polygon polygon;
Gus Grubba's avatar
Gus Grubba committed
526 527 528 529
        for (const auto& qcoord : _flight.coords) {
            Geometry::Coordinate coord;
            coord.latitude  = qcoord.latitude();
            coord.longitude = qcoord.longitude();
530
            polygon.outer_ring.coordinates.push_back(coord);
Gus Grubba's avatar
Gus Grubba committed
531
        }
532
        params.geometry = Geometry(polygon);
Gus Grubba's avatar
Gus Grubba committed
533 534 535 536 537
        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;
538
            _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
539
            if (result) {
540 541
                _flightPlan = result.value();
                qCDebug(AirMapManagerLog) << "Flight plan created:" << flightPlanID();
Gus Grubba's avatar
Gus Grubba committed
542 543 544
                _pollBriefing();
            } else {
                QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
Gus Grubba's avatar
Gus Grubba committed
545
                emit error("Flight Plan creation failed", QString::fromStdString(result.error().message()), description);
Gus Grubba's avatar
Gus Grubba committed
546 547 548 549 550
            }
        });
    });
}

551 552
//-----------------------------------------------------------------------------
void
553
AirMapFlightPlanManager::_updateFlightPlanOnTimer()
554
{
555 556
    _updateFlightPlan(false);
}
557

558 559 560 561
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_updateFlightPlan(bool interactive)
{
Gus Grubba's avatar
Gus Grubba committed
562
    qCDebug(AirMapManagerLog) << "Updating flight plan. State:" << static_cast<int>(_state);
Gus Grubba's avatar
Gus Grubba committed
563 564

    if(_state != State::Idle) {
565
        QTimer::singleShot(250, this, &AirMapFlightPlanManager::_updateFlightPlanOnTimer);
Gus Grubba's avatar
Gus Grubba committed
566 567
        return;
    }
568 569 570 571 572
    //-- Get flight data
    if(!_collectFlightDtata()) {
        return;
    }

573 574 575 576
    //-- Update local instance of the flight plan
    _flightPlan.altitude_agl.max  = _flight.maxAltitude;
    _flightPlan.altitude_agl.min  = 0.0f;
    _flightPlan.buffer            = 2.f;
Gus Grubba's avatar
Gus Grubba committed
577 578
    _flightPlan.takeoff.latitude  = static_cast<float>(_flight.takeoffCoord.latitude());
    _flightPlan.takeoff.longitude = static_cast<float>(_flight.takeoffCoord.longitude());
579 580 581
    //-- Rules & Features
    _flightPlan.rulesets.clear();
    _flightPlan.features.clear();
582 583
    //-- If interactive, we collect features otherwise we don't
    _updateRulesAndFeatures(_flightPlan.rulesets, _flightPlan.features, interactive);
Gus Grubba's avatar
Gus Grubba committed
584 585
    //-- Handle flight start/end
    _updateFlightStartEndTime(_flightPlan.start_time, _flightPlan.end_time);
586 587 588 589 590 591 592 593 594
    //-- 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);
Gus Grubba's avatar
Gus Grubba committed
595

596 597 598 599
    qCDebug(AirMapManagerLog) << "Takeoff:        " << _flight.takeoffCoord;
    qCDebug(AirMapManagerLog) << "Bounding box:   " << _flight.bc.pointNW << _flight.bc.pointSE;
    qCDebug(AirMapManagerLog) << "Flight Start:   " << flightStartTime().toString();
    qCDebug(AirMapManagerLog) << "Flight Duration:" << flightDuration();
Gus Grubba's avatar
Gus Grubba committed
600

601 602 603 604 605
    _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;
606 607
        FlightPlans::Update::Parameters params = {};
        params.authorization                 = login_token.toStdString();
608
        params.flight_plan                   = _flightPlan;
609 610 611 612
        //-- 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;
613
            _state = State::Idle;
614
            if (result) {
615
                qCDebug(AirMapManagerLog) << "Flight plan updated:" << flightPlanID();
616 617 618
                _pollBriefing();
            } else {
                QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
Gus Grubba's avatar
Gus Grubba committed
619
                emit error("Flight Plan update failed", QString::fromStdString(result.error().message()), description);
620 621 622 623 624
            }
        });
    });
}

625 626 627 628 629 630 631
//-----------------------------------------------------------------------------
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;
632
    return static_cast<int>(aa->color()) > static_cast<int>(bb->color());
633 634
}

Gus Grubba's avatar
Gus Grubba committed
635 636 637 638 639 640 641
//-----------------------------------------------------------------------------
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;
642
    return static_cast<int>(aa->status()) > static_cast<int>(bb->status());
Gus Grubba's avatar
Gus Grubba committed
643 644
}

645 646 647 648 649 650 651 652 653 654 655 656 657
//-----------------------------------------------------------------------------
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
658 659 660 661
//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_pollBriefing()
{
662
    qCDebug(AirMapManagerLog) << "Poll Briefing. State:" << static_cast<int>(_state);
663 664
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_pollBriefing);
Gus Grubba's avatar
Gus Grubba committed
665 666
        return;
    }
667
    _state = State::FlightPolling;
Gus Grubba's avatar
Gus Grubba committed
668 669
    FlightPlans::RenderBriefing::Parameters params;
    params.authorization = _shared.loginToken().toStdString();
670
    params.id            = flightPlanID().toStdString();
Gus Grubba's avatar
Gus Grubba committed
671 672 673
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    _shared.client()->flight_plans().render_briefing(params, [this, isAlive](const FlightPlans::RenderBriefing::Result& result) {
        if (!isAlive.lock()) return;
674
        if (_state != State::FlightPolling) return;
Gus Grubba's avatar
Gus Grubba committed
675 676 677
        if (result) {
            const FlightPlan::Briefing& briefing = result.value();
            qCDebug(AirMapManagerLog) << "Flight polling/briefing response";
678 679 680 681
            //-- Collect advisories
            _valid = false;
            _advisories.clearAndDeleteContents();
            const std::vector<Status::Advisory> advisories = briefing.airspace.advisories;
Gus Grubba's avatar
Gus Grubba committed
682
            _airspaceColor = static_cast<AirspaceAdvisoryProvider::AdvisoryColor>(briefing.airspace.color);
683 684 685 686
            for (const auto& advisory : advisories) {
                AirMapAdvisory* pAdvisory = new AirMapAdvisory(this);
                pAdvisory->_id          = QString::fromStdString(advisory.airspace.id());
                pAdvisory->_name        = QString::fromStdString(advisory.airspace.name());
Gus Grubba's avatar
Gus Grubba committed
687 688
                pAdvisory->_type        = static_cast<AirspaceAdvisory::AdvisoryType>(advisory.airspace.type());
                pAdvisory->_color       = static_cast<AirspaceAdvisoryProvider::AdvisoryColor>(advisory.color);
689 690 691 692 693 694 695 696
                _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
697
            //-- Collect Rulesets
Gus Grubba's avatar
Gus Grubba committed
698
            _authorizations.clearAndDeleteContents();
699 700 701 702
            _rulesViolation.clearAndDeleteContents();
            _rulesInfo.clearAndDeleteContents();
            _rulesReview.clearAndDeleteContents();
            _rulesFollowing.clearAndDeleteContents();
703
            _briefFeatures.clear();
Gus Grubba's avatar
Gus Grubba committed
704 705 706 707 708 709
            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);
710 711 712 713
                    //-- Iterate Rule Features
                    for (const auto& feature : rule.features) {
                        AirMapRuleFeature* pFeature = new AirMapRuleFeature(feature, this);
                        pRule->_features.append(pFeature);
714
                        if(rule.status == RuleSet::Rule::Status::missing_info) {
715 716
                            if(!_findBriefFeature(pFeature->name())) {
                                _briefFeatures.append(pFeature);
Gus Grubba's avatar
Gus Grubba committed
717
                                _importantFeatures.append(pFeature);
718 719 720 721
                                qCDebug(AirMapManagerLog) << "Adding briefing feature" << pFeature->name() << pFeature->description() << pFeature->type();
                            } else {
                                qCDebug(AirMapManagerLog) << "Skipping briefing feature duplicate" << pFeature->name() << pFeature->description() << pFeature->type();
                            }
722
                        }
723
                    }
724 725
                    //-- When a flight is first created, we send no features. That means that all "missing_info" are "relevant" features.
                    //   We keep a list of them so they will be always shown to the user even when they are no longer "missing_info"
Gus Grubba's avatar
Gus Grubba committed
726 727 728 729 730
                    for(const auto& feature : _importantFeatures) {
                        if(!_findBriefFeature(feature->name())) {
                            _briefFeatures.append(feature);
                        }
                    }
Gus Grubba's avatar
Gus Grubba committed
731
                    pRuleSet->_rules.append(pRule);
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
                    //-- 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
749 750
                }
                //-- Sort rules by relevance order
751
                pRuleSet->_rules.beginReset();
Gus Grubba's avatar
Gus Grubba committed
752
                std::sort(pRuleSet->_rules.objectList()->begin(), pRuleSet->_rules.objectList()->end(), rules_sort);
753
                pRuleSet->_rules.endReset();
Gus Grubba's avatar
Gus Grubba committed
754 755 756
                _rulesets.append(pRuleSet);
                qCDebug(AirMapManagerLog) << "Adding briefing ruleset" << pRuleSet->id();
            }
757
            //-- Evaluate briefing status
Gus Grubba's avatar
Gus Grubba committed
758
            if (briefing.evaluation.authorizations.size() == 0) {
759
                _flightPermitStatus = AirspaceFlightPlanProvider::PermitNotRequired;
Gus Grubba's avatar
Gus Grubba committed
760
                emit flightPermitStatusChanged();
761
            } else {
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
                bool rejected = false;
                bool accepted = false;
                bool pending  = false;
                for (const auto& authorization : briefing.evaluation.authorizations) {
                    AirMapFlightAuthorization* pAuth = new AirMapFlightAuthorization(authorization, this);
                    _authorizations.append(pAuth);
                    qCDebug(AirMapManagerLog) << "Autorization:" << pAuth->name() << " (" << pAuth->message() << ")" << static_cast<int>(pAuth->status());
                    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;
                    }
                }
                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();
                } else {
                    //-- Pending. Try again.
                    _pollTimer.setSingleShot(true);
                    _pollTimer.start(1000);
                }
Gus Grubba's avatar
Gus Grubba committed
796
            }
797 798 799
            emit advisoryChanged();
            emit rulesChanged();
            _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
800
        } else {
801
            _state = State::Idle;
Gus Grubba's avatar
Gus Grubba committed
802 803 804 805 806 807 808 809 810
            QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
            emit error("Brief Request failed",
                    QString::fromStdString(result.error().message()), description);
        }
    });
}

//-----------------------------------------------------------------------------
void
811
AirMapFlightPlanManager::_missionChanged()
Gus Grubba's avatar
Gus Grubba committed
812
{
813 814 815 816 817 818 819 820
    //-- 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
821
    //-- Creating a new flight plan?
822
    if(_state == State::Idle) {
823
        if(flightPlanID().isEmpty()) {
824 825 826
            _createFlightPlan();
        } else {
            //-- Plan is being modified
827
            _updateFlightPlan();
828
        }
Gus Grubba's avatar
Gus Grubba committed
829 830
    }
}
Gus Grubba's avatar
Gus Grubba committed
831 832 833

//-----------------------------------------------------------------------------
void
Gus Grubba's avatar
Gus Grubba committed
834
AirMapFlightPlanManager::loadFlightList(QDateTime startTime, QDateTime endTime)
Gus Grubba's avatar
Gus Grubba committed
835
{
Gus Grubba's avatar
Gus Grubba committed
836 837 838 839 840 841 842 843
    //-- 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");
844
    if (_shared.pilotID().isEmpty()) {
Gus Grubba's avatar
Gus Grubba committed
845 846 847 848 849 850 851 852 853 854 855 856
        //-- 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) {
857 858 859
                    QString pilotID = QString::fromStdString(result.value().id);
                    _shared.setPilotID(pilotID);
                    qCDebug(AirMapManagerLog) << "Got Pilot ID:" << pilotID;
Gus Grubba's avatar
Gus Grubba committed
860 861 862 863 864 865
                    _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
866 867
                    _loadingFlightList = false;
                    emit loadingFlightListChanged();
Gus Grubba's avatar
Gus Grubba committed
868 869 870 871 872 873 874 875 876 877 878 879 880
                    return;
                }
            });
        });
    } else {
        _loadFlightList();
    }
}

//-----------------------------------------------------------------------------
void
AirMapFlightPlanManager::_loadFlightList()
{
881
    qCDebug(AirMapManagerLog) << "Load flight list. State:" << static_cast<int>(_state);
Gus Grubba's avatar
Gus Grubba committed
882 883 884 885
    if(_state != State::Idle) {
        QTimer::singleShot(100, this, &AirMapFlightPlanManager::_loadFlightList);
        return;
    }
Gus Grubba's avatar
Gus Grubba committed
886
    _flightList.clear();
Gus Grubba's avatar
Gus Grubba committed
887 888 889 890 891 892 893 894
    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();
895 896 897 898
        quint64 start   = static_cast<quint64>(_rangeStart.toUTC().toMSecsSinceEpoch());
        quint64 end     = static_cast<quint64>(_rangeEnd.toUTC().toMSecsSinceEpoch());
        params.start_after  = airmap::from_milliseconds_since_epoch(airmap::milliseconds(static_cast<long long>(start)));
        params.start_before = airmap::from_milliseconds_since_epoch(airmap::milliseconds(static_cast<long long>(end)));
Gus Grubba's avatar
Gus Grubba committed
899
        params.limit    = 250;
900
        params.pilot_id = _shared.pilotID().toStdString();
Gus Grubba's avatar
Gus Grubba committed
901 902 903 904 905 906 907 908
        _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);
909
                    qCDebug(AirMapManagerLog) << "Found:" << pFlight->flightID() << pFlight->flightPlanID() << pFlight->endTime();
Gus Grubba's avatar
Gus Grubba committed
910
                }
911
                _flightList.sortStartFlight();
Gus Grubba's avatar
Gus Grubba committed
912 913 914 915 916 917 918
                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
919 920 921
            _state = State::Idle;
            _loadingFlightList = false;
            emit loadingFlightListChanged();
Gus Grubba's avatar
Gus Grubba committed
922 923 924 925
        });
    });
}