AirMapTrafficMonitor.cc 2.37 KB
Newer Older
1 2 3 4 5 6 7 8 9
/****************************************************************************
 *
 *   (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.
 *
 ****************************************************************************/

10
#include "AirMapTrafficMonitor.h"
Gus Grubba's avatar
Gus Grubba committed
11
#include "AirMapManager.h"
12

Gus Grubba's avatar
Gus Grubba committed
13 14
using namespace airmap;

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
AirMapTrafficMonitor::~AirMapTrafficMonitor()
{
    stop();
}

void
AirMapTrafficMonitor::startConnection(const QString& flightID)
{
    _flightID = flightID;
    std::weak_ptr<LifetimeChecker> isAlive(_instance);
    auto handler = [this, isAlive](const Traffic::Monitor::Result& result) {
        if (!isAlive.lock()) return;
        if (result) {
            _monitor = result.value();
            _subscriber = std::make_shared<Traffic::Monitor::FunctionalSubscriber>(
                    std::bind(&AirMapTrafficMonitor::_update, this, std::placeholders::_1,  std::placeholders::_2));
            _monitor->subscribe(_subscriber);
        } else {
            QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : "");
            emit error("Failed to start Traffic Monitoring",
                    QString::fromStdString(result.error().message()), description);
        }
    };
    Traffic::Monitor::Params params{flightID.toStdString(), _shared.loginToken().toStdString()};
    _shared.client()->traffic().monitor(params, handler);
}

void
AirMapTrafficMonitor::_update(Traffic::Update::Type type, const std::vector<Traffic::Update>& update)
{
    qCDebug(AirMapManagerLog) << "Traffic update with" << update.size() << "elements";
    if (type != Traffic::Update::Type::situational_awareness)
        return; // currently we're only interested in situational awareness
    for (const auto& traffic : update) {
        QString traffic_id = QString::fromStdString(traffic.id);
        QString vehicle_id = QString::fromStdString(traffic.aircraft_id);
Gus Grubba's avatar
Gus Grubba committed
51 52
        emit trafficUpdate(type == Traffic::Update::Type::alert, traffic_id, vehicle_id,
            QGeoCoordinate(traffic.latitude, traffic.longitude, traffic.altitude), traffic.heading);
53 54 55 56 57 58 59 60 61 62 63 64 65
    }
}

void
AirMapTrafficMonitor::stop()
{
    if (_monitor) {
        _monitor->unsubscribe(_subscriber);
        _subscriber.reset();
        _monitor.reset();
    }
}