MultiVehicleManager.cc 12.7 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

19
#if defined (__ios__) || defined(__android__)
Don Gagne's avatar
Don Gagne committed
20
#include "MobileScreenMgr.h"
21 22
#endif

Don Gagne's avatar
Don Gagne committed
23 24
#include <QQmlEngine>

Don Gagne's avatar
Don Gagne committed
25 26
QGC_LOGGING_CATEGORY(MultiVehicleManagerLog, "MultiVehicleManagerLog")

27
const char* MultiVehicleManager::_gcsHeartbeatEnabledKey = "gcsHeartbeatEnabled";
28

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

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

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

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

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

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

63
   connect(_mavlinkProtocol, &MAVLinkProtocol::vehicleHeartbeatInfo, this, &MultiVehicleManager::_vehicleHeartbeatInfo);
64 65 66 67 68

   _offlineEditingVehicle = new Vehicle(static_cast<MAV_AUTOPILOT>(QGroundControlQmlGlobal::offlineEditingFirmwareType()->rawValue().toInt()),
                                        static_cast<MAV_TYPE>(QGroundControlQmlGlobal::offlineEditingVehicleType()->rawValue().toInt()),
                                        _firmwarePluginManager,
                                        this);
69 70
}

71
void MultiVehicleManager::_vehicleHeartbeatInfo(LinkInterface* link, int vehicleId, int vehicleMavlinkVersion, int vehicleFirmwareType, int vehicleType)
72
{
73 74
    if (_ignoreVehicleIds.contains(vehicleId) || getVehicleById(vehicleId)
            || vehicleId == 0) {
75 76 77 78 79 80 81 82 83
        return;
    }

    qCDebug(MultiVehicleManagerLog()) << "Adding new vehicle link:vehicleId:vehicleMavlinkVersion:vehicleFirmwareType:vehicleType "
                                      << link->getName()
                                      << vehicleId
                                      << vehicleMavlinkVersion
                                      << vehicleFirmwareType
                                      << vehicleType;
dogmaphobic's avatar
dogmaphobic committed
84

85 86 87
    if (vehicleId == _mavlinkProtocol->getSystemId()) {
        _app->showMessage(QString("Warning: A vehicle is using the same system id as QGroundControl: %1").arg(vehicleId));
    }
dogmaphobic's avatar
dogmaphobic committed
88

89 90 91 92 93 94 95 96 97
//    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 QGroundControl differ! "
//                                  "It is unsafe to use different MAVLink versions. "
//                                  "QGroundControl therefore refuses to connect to vehicle #%1, which sends MAVLink version %2 (QGroundControl uses version %3).").arg(vehicleId).arg(vehicleMavlinkVersion).arg(MAVLINK_VERSION));
//        return;
//    }
dogmaphobic's avatar
dogmaphobic committed
98

99
    Vehicle* vehicle = new Vehicle(link, vehicleId, (MAV_AUTOPILOT)vehicleFirmwareType, (MAV_TYPE)vehicleType, _firmwarePluginManager, _joystickManager);
100
    connect(vehicle, &Vehicle::allLinksInactive, this, &MultiVehicleManager::_deleteVehiclePhase1);
101
    connect(vehicle->parameterManager(), &ParameterManager::parametersReadyChanged, this, &MultiVehicleManager::_vehicleParametersReadyChanged);
102

103
    _vehicles.append(vehicle);
dogmaphobic's avatar
dogmaphobic committed
104

105 106 107
    // Send QGC heartbeat ASAP, this allows PX4 to start accepting commands
    _sendGCSHeartbeat();

108
    emit vehicleAdded(vehicle);
dogmaphobic's avatar
dogmaphobic committed
109

110 111 112 113 114
    if (_vehicles.count() > 1) {
        qgcApp()->showMessage(tr("Connected to Vehicle %1").arg(vehicleId));
    } else {
        setActiveVehicle(vehicle);
    }
115

116 117 118
    // Mark link as active
    link->setActive(true);

119
#if defined (__ios__) || defined(__android__)
120
    if(_vehicles.count() == 1) {
Don Gagne's avatar
Don Gagne committed
121
        //-- Once a vehicle is connected, keep screen from going off
122
        qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::keepScreenOn";
Don Gagne's avatar
Don Gagne committed
123
        MobileScreenMgr::setKeepScreenOn(true);
124 125 126
    }
#endif

127 128 129 130
}

/// 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.
131
void MultiVehicleManager::_deleteVehiclePhase1(Vehicle* vehicle)
132
{
Don Gagne's avatar
Don Gagne committed
133
    qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase1" << vehicle;
Don Gagne's avatar
Don Gagne committed
134

Don Gagne's avatar
Don Gagne committed
135
    _vehiclesBeingDeleted << vehicle;
136 137

    // Remove from map
138 139
    bool found = false;
    for (int i=0; i<_vehicles.count(); i++) {
Don Gagne's avatar
Don Gagne committed
140
        if (_vehicles[i] == vehicle) {
141
            _vehicles.removeAt(i);
142 143 144 145 146 147 148
            found = true;
            break;
        }
    }
    if (!found) {
        qWarning() << "Vehicle not found in map!";
    }
dogmaphobic's avatar
dogmaphobic committed
149

150
    vehicle->setActive(false);
Don Gagne's avatar
Don Gagne committed
151
    vehicle->uas()->shutdownVehicle();
dogmaphobic's avatar
dogmaphobic committed
152

153 154 155 156 157 158
    // First we must signal that a vehicle is no longer available.
    _activeVehicleAvailable = false;
    _parameterReadyVehicleAvailable = false;
    emit activeVehicleAvailableChanged(false);
    emit parameterReadyVehicleAvailableChanged(false);
    emit vehicleRemoved(vehicle);
dogmaphobic's avatar
dogmaphobic committed
159

160
#if defined (__ios__) || defined(__android__)
161
    if(_vehicles.count() == 0) {
Don Gagne's avatar
Don Gagne committed
162
        //-- Once no vehicles are connected, we no longer need to keep screen from going off
163
        qCDebug(MultiVehicleManagerLog) << "QAndroidJniObject::restoreScreenOn";
164
        MobileScreenMgr::setKeepScreenOn(false);
165 166 167
    }
#endif

168 169 170 171 172 173 174 175 176
    // 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
177
void MultiVehicleManager::_deleteVehiclePhase2(void)
178
{
Don Gagne's avatar
Don Gagne committed
179
    qCDebug(MultiVehicleManagerLog) << "_deleteVehiclePhase2" << _vehiclesBeingDeleted[0];
Don Gagne's avatar
Don Gagne committed
180

181 182
    /// 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
183

184
    Vehicle* newActiveVehicle = NULL;
185 186
    if (_vehicles.count()) {
        newActiveVehicle = qobject_cast<Vehicle*>(_vehicles[0]);
187
    }
dogmaphobic's avatar
dogmaphobic committed
188

189 190
    _activeVehicle = newActiveVehicle;
    emit activeVehicleChanged(newActiveVehicle);
dogmaphobic's avatar
dogmaphobic committed
191

192
    if (_activeVehicle) {
193
        _activeVehicle->setActive(true);
194
        emit activeVehicleAvailableChanged(true);
195
        if (_activeVehicle->parameterManager()->parametersReady()) {
196 197 198
            emit parameterReadyVehicleAvailableChanged(true);
        }
    }
dogmaphobic's avatar
dogmaphobic committed
199

Don Gagne's avatar
Don Gagne committed
200 201
    delete _vehiclesBeingDeleted[0];
    _vehiclesBeingDeleted.removeAt(0);
202 203 204 205
}

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

208
    if (vehicle != _activeVehicle) {
Don Gagne's avatar
Don Gagne committed
209
        if (_activeVehicle) {
210
            _activeVehicle->setActive(false);
dogmaphobic's avatar
dogmaphobic committed
211

Don Gagne's avatar
Don Gagne committed
212 213
            // 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
214

Don Gagne's avatar
Don Gagne committed
215 216 217 218 219 220 221
            // 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
222

223 224 225 226 227 228 229 230
        // See explanation in _deleteVehiclePhase1
        _vehicleBeingSetActive = vehicle;
        QTimer::singleShot(20, this, &MultiVehicleManager::_setActiveVehiclePhase2);
    }
}

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

233 234 235
    // Now we signal the new active vehicle
    _activeVehicle = _vehicleBeingSetActive;
    emit activeVehicleChanged(_activeVehicle);
dogmaphobic's avatar
dogmaphobic committed
236

237 238
    // And finally vehicle availability
    if (_activeVehicle) {
239
        _activeVehicle->setActive(true);
240 241
        _activeVehicleAvailable = true;
        emit activeVehicleAvailableChanged(true);
dogmaphobic's avatar
dogmaphobic committed
242

243
        if (_activeVehicle->parameterManager()->parametersReady()) {
244 245 246 247 248 249
            _parameterReadyVehicleAvailable = true;
            emit parameterReadyVehicleAvailableChanged(true);
        }
    }
}

250
void MultiVehicleManager::_vehicleParametersReadyChanged(bool parametersReady)
251
{
252
    ParameterManager* paramMgr = dynamic_cast<ParameterManager*>(sender());
dogmaphobic's avatar
dogmaphobic committed
253

254
    if (!paramMgr) {
255 256 257
        qWarning() << "Dynamic cast failed!";
        return;
    }
dogmaphobic's avatar
dogmaphobic committed
258

259
    if (paramMgr->vehicle() == _activeVehicle) {
260 261
        _parameterReadyVehicleAvailable = parametersReady;
        emit parameterReadyVehicleAvailableChanged(parametersReady);
262 263 264
    }
}

265 266 267 268 269 270 271 272 273 274 275
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();
}
276 277 278 279 280 281 282 283 284 285 286 287

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;
}
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

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)
{
308
    // Send a heartbeat out on each link
309 310 311
    LinkManager* linkMgr = _toolbox->linkManager();
    for (int i=0; i<linkMgr->links().count(); i++) {
        LinkInterface* link = linkMgr->links()[i];
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
        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);
        }
329 330
    }
}
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

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;
}