MultiVehicleManager.cc 15.1 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (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.
 *
 ****************************************************************************/
dogmaphobic's avatar
dogmaphobic committed
9

10 11
#include "MultiVehicleManager.h"
#include "AutoPilotPlugin.h"
12 13
#include "MAVLinkProtocol.h"
#include "UAS.h"
14
#include "QGCApplication.h"
Jimmy Johnson's avatar
Jimmy Johnson committed
15
#include "FollowMe.h"
16
#include "QGroundControlQmlGlobal.h"
17
#include "ParameterManager.h"
18
#include "SettingsManager.h"
19 20
#include "QGCCorePlugin.h"
#include "QGCOptions.h"
21

22
#if defined (__ios__) || defined(__android__)
Don Gagne's avatar
Don Gagne committed
23
#include "MobileScreenMgr.h"
24 25
#endif

Don Gagne's avatar
Don Gagne committed
26 27
#include <QQmlEngine>

Don Gagne's avatar
Don Gagne committed
28 29
QGC_LOGGING_CATEGORY(MultiVehicleManagerLog, "MultiVehicleManagerLog")

30
const char* MultiVehicleManager::_gcsHeartbeatEnabledKey = "gcsHeartbeatEnabled";
31

32 33
MultiVehicleManager::MultiVehicleManager(QGCApplication* app, QGCToolbox* toolbox)
    : QGCTool(app, toolbox)
34 35 36
    , _activeVehicleAvailable(false)
    , _parameterReadyVehicleAvailable(false)
    , _activeVehicle(NULL)
37
    , _offlineEditingVehicle(NULL)
38 39 40
    , _firmwarePluginManager(NULL)
    , _joystickManager(NULL)
    , _mavlinkProtocol(NULL)
41
    , _gcsHeartbeatEnabled(true)
42
{
43 44 45
    QSettings settings;

    _gcsHeartbeatEnabled = settings.value(_gcsHeartbeatEnabledKey, true).toBool();
46

47 48 49 50 51 52
    _gcsHeartbeatTimer.setInterval(_gcsHeartbeatRateMSecs);
    _gcsHeartbeatTimer.setSingleShot(false);
    connect(&_gcsHeartbeatTimer, &QTimer::timeout, this, &MultiVehicleManager::_sendGCSHeartbeat);
    if (_gcsHeartbeatEnabled) {
        _gcsHeartbeatTimer.start();
    }
53 54
}

55
void MultiVehicleManager::setToolbox(QGCToolbox *toolbox)
56
{
57
    QGCTool::setToolbox(toolbox);
58

59 60 61
    _firmwarePluginManager =     _toolbox->firmwarePluginManager();
    _joystickManager =           _toolbox->joystickManager();
    _mavlinkProtocol =           _toolbox->mavlinkProtocol();
62

63 64
    QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
    qmlRegisterUncreatableType<MultiVehicleManager>("QGroundControl.MultiVehicleManager", 1, 0, "MultiVehicleManager", "Reference only");
dogmaphobic's avatar
dogmaphobic committed
65

66
    connect(_mavlinkProtocol, &MAVLinkProtocol::vehicleHeartbeatInfo, this, &MultiVehicleManager::_vehicleHeartbeatInfo);
67

68 69 70 71 72
    SettingsManager* settingsManager = toolbox->settingsManager();
    _offlineEditingVehicle = new Vehicle(static_cast<MAV_AUTOPILOT>(settingsManager->appSettings()->offlineEditingFirmwareType()->rawValue().toInt()),
                                         static_cast<MAV_TYPE>(settingsManager->appSettings()->offlineEditingVehicleType()->rawValue().toInt()),
                                         _firmwarePluginManager,
                                         this);
73 74
}

75
void MultiVehicleManager::_vehicleHeartbeatInfo(LinkInterface* link, int vehicleId, int componentId, int vehicleMavlinkVersion, int vehicleFirmwareType, int vehicleType)
76
{
77
    if (componentId != MAV_COMP_ID_AUTOPILOT1) {
78 79 80
        // Special case for PX4 Flow
        if (vehicleId != 81 || componentId != 50) {
            // Don't create vehicles for components other than the autopilot
81 82 83 84 85 86 87
            qCDebug(MultiVehicleManagerLog()) << "Ignoring heartbeat from unknown component "
                                              << link->getName()
                                              << vehicleId
                                              << componentId
                                              << vehicleMavlinkVersion
                                              << vehicleFirmwareType
                                              << vehicleType;
88
            return;
89 90 91
        }
    }

92 93 94
    if (_vehicles.count() > 0 && !qgcApp()->toolbox()->corePlugin()->options()->multiVehicleEnabled()) {
        return;
    }
95
    if (_ignoreVehicleIds.contains(vehicleId) || getVehicleById(vehicleId) || vehicleId == 0) {
96 97 98
        return;
    }

99 100 101 102 103 104 105 106 107 108 109 110
    switch (vehicleType) {
    case MAV_TYPE_GCS:
    case MAV_TYPE_ONBOARD_CONTROLLER:
    case MAV_TYPE_GIMBAL:
    case MAV_TYPE_ADSB:
        // These are not vehicles, so don't create a vehicle for them
        return;
    default:
        // All other MAV_TYPEs create vehicles
        break;
    }

111
    qCDebug(MultiVehicleManagerLog()) << "Adding new vehicle link:vehicleId:componentId:vehicleMavlinkVersion:vehicleFirmwareType:vehicleType "
112 113
                                      << link->getName()
                                      << vehicleId
114
                                      << componentId
115 116 117
                                      << vehicleMavlinkVersion
                                      << vehicleFirmwareType
                                      << vehicleType;
dogmaphobic's avatar
dogmaphobic committed
118

119
    if (vehicleId == _mavlinkProtocol->getSystemId()) {
120
        _app->showMessage(tr("Warning: A vehicle is using the same system id as %1: %2").arg(qgcApp()->applicationName()).arg(vehicleId));
121
    }
dogmaphobic's avatar
dogmaphobic committed
122

123 124 125 126 127 128 129 130 131
    //    QSettings settings;
    //    bool mavlinkVersionCheck = settings.value("VERSION_CHECK_ENABLED", true).toBool();
    //    if (mavlinkVersionCheck && vehicleMavlinkVersion != MAVLINK_VERSION) {
    //        _ignoreVehicleIds += vehicleId;
    //        _app->showMessage(QString("The MAVLink protocol version on vehicle #%1 and %2 differ! "
    //                                  "It is unsafe to use different MAVLink versions. "
    //                                  "%2 therefore refuses to connect to vehicle #%1, which sends MAVLink version %3 (%2 uses version %4).").arg(vehicleId).arg(qgcApp()->applicationName()).arg(vehicleMavlinkVersion).arg(MAVLINK_VERSION));
    //        return;
    //    }
dogmaphobic's avatar
dogmaphobic committed
132

133
    Vehicle* vehicle = new Vehicle(link, vehicleId, componentId, (MAV_AUTOPILOT)vehicleFirmwareType, (MAV_TYPE)vehicleType, _firmwarePluginManager, _joystickManager);
134
    connect(vehicle, &Vehicle::allLinksInactive, this, &MultiVehicleManager::_deleteVehiclePhase1);
135
    connect(vehicle, &Vehicle::requestProtocolVersion, this, &MultiVehicleManager::_requestProtocolVersion);
136
    connect(vehicle->parameterManager(), &ParameterManager::parametersReadyChanged, this, &MultiVehicleManager::_vehicleParametersReadyChanged);
137

138
    _vehicles.append(vehicle);
dogmaphobic's avatar
dogmaphobic committed
139

140 141 142
    // Send QGC heartbeat ASAP, this allows PX4 to start accepting commands
    _sendGCSHeartbeat();

143 144
    qgcApp()->toolbox()->settingsManager()->appSettings()->defaultFirmwareType()->setRawValue(vehicleFirmwareType);

145
    emit vehicleAdded(vehicle);
dogmaphobic's avatar
dogmaphobic committed
146

147 148 149 150 151
    if (_vehicles.count() > 1) {
        qgcApp()->showMessage(tr("Connected to Vehicle %1").arg(vehicleId));
    } else {
        setActiveVehicle(vehicle);
    }
152

153 154 155
    // Mark link as active
    link->setActive(true);

156
#if defined (__ios__) || defined(__android__)
157
    if(_vehicles.count() == 1) {
Don Gagne's avatar
Don Gagne committed
158
        //-- Once a vehicle is connected, keep screen from going off
159
        qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::keepScreenOn";
Don Gagne's avatar
Don Gagne committed
160
        MobileScreenMgr::setKeepScreenOn(true);
161 162 163
    }
#endif

164 165
}

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
/// This slot is connected to the Vehicle::requestProtocolVersion signal such that the vehicle manager
/// tries to switch MAVLink to v2 if all vehicles support it
void MultiVehicleManager::_requestProtocolVersion(unsigned version)
{
    unsigned maxversion = 0;

    if (_vehicles.count() == 0) {
        _mavlinkProtocol->setVersion(version);
        return;
    }

    for (int i=0; i<_vehicles.count(); i++) {

        Vehicle *v = qobject_cast<Vehicle*>(_vehicles[i]);
        if (v && v->maxProtoVersion() > maxversion) {
181
            maxversion = v->maxProtoVersion();
182 183 184 185 186 187 188 189
        }
    }

    if (_mavlinkProtocol->getCurrentVersion() != maxversion) {
        _mavlinkProtocol->setVersion(maxversion);
    }
}

190 191
/// This slot is connected to the Vehicle::allLinksDestroyed signal such that the Vehicle is deleted
/// and all other right things happen when the Vehicle goes away.
192
void MultiVehicleManager::_deleteVehiclePhase1(Vehicle* vehicle)
193
{
Don Gagne's avatar
Don Gagne committed
194
    qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase1" << vehicle;
Don Gagne's avatar
Don Gagne committed
195

Don Gagne's avatar
Don Gagne committed
196
    _vehiclesBeingDeleted << vehicle;
197 198

    // Remove from map
199 200
    bool found = false;
    for (int i=0; i<_vehicles.count(); i++) {
Don Gagne's avatar
Don Gagne committed
201
        if (_vehicles[i] == vehicle) {
202
            _vehicles.removeAt(i);
203 204 205 206 207 208 209
            found = true;
            break;
        }
    }
    if (!found) {
        qWarning() << "Vehicle not found in map!";
    }
dogmaphobic's avatar
dogmaphobic committed
210

211
    vehicle->setActive(false);
Don Gagne's avatar
Don Gagne committed
212
    vehicle->uas()->shutdownVehicle();
dogmaphobic's avatar
dogmaphobic committed
213

214 215 216 217 218 219
    // First we must signal that a vehicle is no longer available.
    _activeVehicleAvailable = false;
    _parameterReadyVehicleAvailable = false;
    emit activeVehicleAvailableChanged(false);
    emit parameterReadyVehicleAvailableChanged(false);
    emit vehicleRemoved(vehicle);
220
    vehicle->prepareDelete();
dogmaphobic's avatar
dogmaphobic committed
221

222
#if defined (__ios__) || defined(__android__)
223
    if(_vehicles.count() == 0) {
Don Gagne's avatar
Don Gagne committed
224
        //-- Once no vehicles are connected, we no longer need to keep screen from going off
225
        qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::restoreScreenOn";
226
        MobileScreenMgr::setKeepScreenOn(false);
227 228 229
    }
#endif

230 231 232 233 234 235 236 237 238
    // We must let the above signals flow through the system as well as get back to the main loop event queue
    // before we can actually delete the Vehicle. The reason is that Qml may be holding on the references to it.
    // Even though the above signals should unload any Qml which has references, that Qml will not be destroyed
    // until we get back to the main loop. So we set a short timer which will then fire after Qt has finished
    // doing all of its internal nastiness to clean up the Qml. This works for both the normal running case
    // as well as the unit testing case whichof course has a different signal flow!
    QTimer::singleShot(20, this, &MultiVehicleManager::_deleteVehiclePhase2);
}

Don Gagne's avatar
Don Gagne committed
239
void MultiVehicleManager::_deleteVehiclePhase2(void)
240
{
Don Gagne's avatar
Don Gagne committed
241
    qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase2" << _vehiclesBeingDeleted[0];
Don Gagne's avatar
Don Gagne committed
242

243 244
    /// Qml has been notified of vehicle about to go away and should be disconnected from it by now.
    /// This means we can now clear the active vehicle property and delete the Vehicle for real.
dogmaphobic's avatar
dogmaphobic committed
245

246
    Vehicle* newActiveVehicle = NULL;
247 248
    if (_vehicles.count()) {
        newActiveVehicle = qobject_cast<Vehicle*>(_vehicles[0]);
249
    }
dogmaphobic's avatar
dogmaphobic committed
250

251 252
    _activeVehicle = newActiveVehicle;
    emit activeVehicleChanged(newActiveVehicle);
dogmaphobic's avatar
dogmaphobic committed
253

254
    if (_activeVehicle) {
255
        _activeVehicle->setActive(true);
256
        emit activeVehicleAvailableChanged(true);
257
        if (_activeVehicle->parameterManager()->parametersReady()) {
258 259 260
            emit parameterReadyVehicleAvailableChanged(true);
        }
    }
dogmaphobic's avatar
dogmaphobic committed
261

Don Gagne's avatar
Don Gagne committed
262 263
    delete _vehiclesBeingDeleted[0];
    _vehiclesBeingDeleted.removeAt(0);
264 265 266 267
}

void MultiVehicleManager::setActiveVehicle(Vehicle* vehicle)
{
Don Gagne's avatar
Don Gagne committed
268 269
    qCDebug(MultiVehicleManagerLog) << "setActiveVehicle" << vehicle;

270
    if (vehicle != _activeVehicle) {
Don Gagne's avatar
Don Gagne committed
271
        if (_activeVehicle) {
272
            _activeVehicle->setActive(false);
dogmaphobic's avatar
dogmaphobic committed
273

Don Gagne's avatar
Don Gagne committed
274 275
            // The sequence of signals is very important in order to not leave Qml elements connected
            // to a non-existent vehicle.
dogmaphobic's avatar
dogmaphobic committed
276

Don Gagne's avatar
Don Gagne committed
277 278 279 280 281 282 283
            // First we must signal that there is no active vehicle available. This will disconnect
            // any existing ui from the currently active vehicle.
            _activeVehicleAvailable = false;
            _parameterReadyVehicleAvailable = false;
            emit activeVehicleAvailableChanged(false);
            emit parameterReadyVehicleAvailableChanged(false);
        }
dogmaphobic's avatar
dogmaphobic committed
284

285 286 287 288 289 290 291 292
        // See explanation in _deleteVehiclePhase1
        _vehicleBeingSetActive = vehicle;
        QTimer::singleShot(20, this, &MultiVehicleManager::_setActiveVehiclePhase2);
    }
}

void MultiVehicleManager::_setActiveVehiclePhase2(void)
{
Don Gagne's avatar
Don Gagne committed
293
    qCDebug(MultiVehicleManagerLog) << "_setActiveVehiclePhase2 _vehicleBeingSetActive" << _vehicleBeingSetActive;
Don Gagne's avatar
Don Gagne committed
294

295 296 297
    // Now we signal the new active vehicle
    _activeVehicle = _vehicleBeingSetActive;
    emit activeVehicleChanged(_activeVehicle);
dogmaphobic's avatar
dogmaphobic committed
298

299 300
    // And finally vehicle availability
    if (_activeVehicle) {
301
        _activeVehicle->setActive(true);
302 303
        _activeVehicleAvailable = true;
        emit activeVehicleAvailableChanged(true);
dogmaphobic's avatar
dogmaphobic committed
304

305
        if (_activeVehicle->parameterManager()->parametersReady()) {
306 307 308 309 310 311
            _parameterReadyVehicleAvailable = true;
            emit parameterReadyVehicleAvailableChanged(true);
        }
    }
}

312
void MultiVehicleManager::_vehicleParametersReadyChanged(bool parametersReady)
313
{
314
    ParameterManager* paramMgr = dynamic_cast<ParameterManager*>(sender());
dogmaphobic's avatar
dogmaphobic committed
315

316
    if (!paramMgr) {
317 318 319
        qWarning() << "Dynamic cast failed!";
        return;
    }
dogmaphobic's avatar
dogmaphobic committed
320

321
    if (paramMgr->vehicle() == _activeVehicle) {
322 323
        _parameterReadyVehicleAvailable = parametersReady;
        emit parameterReadyVehicleAvailableChanged(parametersReady);
324 325 326
    }
}

327 328 329 330 331 332 333 334 335 336 337
void MultiVehicleManager::saveSetting(const QString &name, const QString& value)
{
    QSettings settings;
    settings.setValue(name, value);
}

QString MultiVehicleManager::loadSetting(const QString &name, const QString& defaultValue)
{
    QSettings settings;
    return settings.value(name, defaultValue).toString();
}
338 339 340 341 342 343 344 345 346 347 348 349

Vehicle* MultiVehicleManager::getVehicleById(int vehicleId)
{
    for (int i=0; i< _vehicles.count(); i++) {
        Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]);
        if (vehicle->id() == vehicleId) {
            return vehicle;
        }
    }

    return NULL;
}
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

void MultiVehicleManager::setGcsHeartbeatEnabled(bool gcsHeartBeatEnabled)
{
    if (gcsHeartBeatEnabled != _gcsHeartbeatEnabled) {
        _gcsHeartbeatEnabled = gcsHeartBeatEnabled;
        emit gcsHeartBeatEnabledChanged(gcsHeartBeatEnabled);

        QSettings settings;
        settings.setValue(_gcsHeartbeatEnabledKey, gcsHeartBeatEnabled);

        if (gcsHeartBeatEnabled) {
            _gcsHeartbeatTimer.start();
        } else {
            _gcsHeartbeatTimer.stop();
        }
    }
}

void MultiVehicleManager::_sendGCSHeartbeat(void)
{
370
    // Send a heartbeat out on each link
371 372 373
    LinkManager* linkMgr = _toolbox->linkManager();
    for (int i=0; i<linkMgr->links().count(); i++) {
        LinkInterface* link = linkMgr->links()[i];
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        if (link->isConnected()) {
            mavlink_message_t message;
            mavlink_msg_heartbeat_pack_chan(_mavlinkProtocol->getSystemId(),
                                            _mavlinkProtocol->getComponentId(),
                                            link->mavlinkChannel(),
                                            &message,
                                            MAV_TYPE_GCS,            // MAV_TYPE
                                            MAV_AUTOPILOT_INVALID,   // MAV_AUTOPILOT
                                            MAV_MODE_MANUAL_ARMED,   // MAV_MODE
                                            0,                       // custom mode
                                            MAV_STATE_ACTIVE);       // MAV_STATE

            uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
            int len = mavlink_msg_to_send_buffer(buffer, &message);

            link->writeBytesSafe((const char*)buffer, len);
        }
391 392
    }
}
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

bool MultiVehicleManager::linkInUse(LinkInterface* link, Vehicle* skipVehicle)
{
    for (int i=0; i< _vehicles.count(); i++) {
        Vehicle* vehicle = qobject_cast<Vehicle*>(_vehicles[i]);

        if (vehicle != skipVehicle) {
            if (vehicle->containsLink(link)) {
                return true;
            }
        }
    }

    return false;
}