LinkManager.cc 32.9 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.
 *
 ****************************************************************************/
lm's avatar
lm committed
9

10

pixhawk's avatar
pixhawk committed
11 12 13 14 15 16 17 18 19 20
/**
 * @file
 *   @brief Brief Description
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QList>
#include <QApplication>
21
#include <QDebug>
22
#include <QSignalSpy>
dogmaphobic's avatar
dogmaphobic committed
23 24

#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
25
#include "QGCSerialPortInfo.h"
dogmaphobic's avatar
dogmaphobic committed
26
#endif
27

28
#include "LinkManager.h"
29
#include "QGCApplication.h"
Don Gagne's avatar
Don Gagne committed
30 31
#include "UDPLink.h"
#include "TCPLink.h"
dogmaphobic's avatar
dogmaphobic committed
32
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
33 34
#include "BluetoothLink.h"
#endif
35

Don Gagne's avatar
Don Gagne committed
36 37 38 39
#ifndef __mobile__
    #include "GPSManager.h"
#endif

Don Gagne's avatar
Don Gagne committed
40
QGC_LOGGING_CATEGORY(LinkManagerLog, "LinkManagerLog")
Don Gagne's avatar
Don Gagne committed
41 42
QGC_LOGGING_CATEGORY(LinkManagerVerboseLog, "LinkManagerVerboseLog")

43 44 45 46 47 48 49 50
const char* LinkManager::_settingsGroup =            "LinkManager";
const char* LinkManager::_autoconnectUDPKey =        "AutoconnectUDP";
const char* LinkManager::_autoconnectPixhawkKey =    "AutoconnectPixhawk";
const char* LinkManager::_autoconnect3DRRadioKey =   "Autoconnect3DRRadio";
const char* LinkManager::_autoconnectPX4FlowKey =    "AutoconnectPX4Flow";
const char* LinkManager::_autoconnectRTKGPSKey =     "AutoconnectRTKGPS";
const char* LinkManager::_autoconnectLibrePilotKey = "AutoconnectLibrePilot";
const char* LinkManager::_defaultUPDLinkName =       "Default UDP Link";
51

52 53 54 55 56 57 58 59
const int LinkManager::_autoconnectUpdateTimerMSecs =   1000;
#ifdef Q_OS_WIN
// Have to manually let the bootloader go by on Windows to get a working connect
const int LinkManager::_autoconnectConnectDelayMSecs =  6000;
#else
const int LinkManager::_autoconnectConnectDelayMSecs =  1000;
#endif

60 61
LinkManager::LinkManager(QGCApplication* app)
    : QGCTool(app)
62 63 64
    , _configUpdateSuspended(false)
    , _configurationsLoaded(false)
    , _connectionsSuspended(false)
65
    , _mavlinkChannelsUsedBitMask(1)    // We never use channel 0 to avoid sequence numbering problems
66
    , _mavlinkProtocol(NULL)
Don Gagne's avatar
Don Gagne committed
67 68 69 70
    , _autoconnectUDP(true)
    , _autoconnectPixhawk(true)
    , _autoconnect3DRRadio(true)
    , _autoconnectPX4Flow(true)
Don Gagne's avatar
Don Gagne committed
71
    , _autoconnectRTKGPS(true)
72
    , _autoconnectLibrePilot(true)
pixhawk's avatar
pixhawk committed
73
{
Don Gagne's avatar
Don Gagne committed
74 75 76 77 78
    qmlRegisterUncreatableType<LinkManager>         ("QGroundControl", 1, 0, "LinkManager",         "Reference only");
    qmlRegisterUncreatableType<LinkConfiguration>   ("QGroundControl", 1, 0, "LinkConfiguration",   "Reference only");
    qmlRegisterUncreatableType<LinkInterface>       ("QGroundControl", 1, 0, "LinkInterface",       "Reference only");

    QSettings settings;
79

Don Gagne's avatar
Don Gagne committed
80
    settings.beginGroup(_settingsGroup);
81 82 83 84 85 86
    _autoconnectUDP =        settings.value(_autoconnectUDPKey, true).toBool();
    _autoconnectPixhawk =    settings.value(_autoconnectPixhawkKey, true).toBool();
    _autoconnect3DRRadio =   settings.value(_autoconnect3DRRadioKey, true).toBool();
    _autoconnectPX4Flow =    settings.value(_autoconnectPX4FlowKey, true).toBool();
    _autoconnectRTKGPS =     settings.value(_autoconnectRTKGPSKey, true).toBool();
    _autoconnectLibrePilot = settings.value(_autoconnectLibrePilotKey, true).toBool();
Don Gagne's avatar
Don Gagne committed
87

Don Gagne's avatar
Don Gagne committed
88
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
89 90 91
    _activeLinkCheckTimer.setInterval(_activeLinkCheckTimeoutMSecs);
    _activeLinkCheckTimer.setSingleShot(false);
    connect(&_activeLinkCheckTimer, &QTimer::timeout, this, &LinkManager::_activeLinkCheck);
Don Gagne's avatar
Don Gagne committed
92
#endif
pixhawk's avatar
pixhawk committed
93 94 95 96
}

LinkManager::~LinkManager()
{
97

pixhawk's avatar
pixhawk committed
98 99
}

100 101 102 103 104 105
void LinkManager::setToolbox(QGCToolbox *toolbox)
{
   QGCTool::setToolbox(toolbox);

   _mavlinkProtocol = _toolbox->mavlinkProtocol();

Don Gagne's avatar
Don Gagne committed
106
    connect(&_portListTimer, &QTimer::timeout, this, &LinkManager::_updateAutoConnectLinks);
107
    _portListTimer.start(_autoconnectUpdateTimerMSecs); // timeout must be long enough to get past bootloader on second pass
108

109 110
}

Don Gagne's avatar
Don Gagne committed
111
LinkInterface* LinkManager::createConnectedLink(LinkConfiguration* config)
112 113 114 115
{
    Q_ASSERT(config);
    LinkInterface* pLink = NULL;
    switch(config->type()) {
dogmaphobic's avatar
dogmaphobic committed
116
#ifndef __ios__
117
        case LinkConfiguration::TypeSerial:
Don Gagne's avatar
Don Gagne committed
118 119 120 121 122
        {
            SerialConfiguration* serialConfig = dynamic_cast<SerialConfiguration*>(config);
            if (serialConfig) {
                pLink = new SerialLink(serialConfig);
                if (serialConfig->usbDirect()) {
123
                    _activeLinkCheckList.append((SerialLink*)pLink);
Don Gagne's avatar
Don Gagne committed
124 125 126 127 128 129 130
                    if (!_activeLinkCheckTimer.isActive()) {
                        _activeLinkCheckTimer.start();
                    }
                }
            }
        }
        break;
dogmaphobic's avatar
dogmaphobic committed
131
#endif
132 133 134
        case LinkConfiguration::TypeUdp:
            pLink = new UDPLink(dynamic_cast<UDPConfiguration*>(config));
            break;
135 136 137
        case LinkConfiguration::TypeTcp:
            pLink = new TCPLink(dynamic_cast<TCPConfiguration*>(config));
            break;
dogmaphobic's avatar
dogmaphobic committed
138
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
139 140 141 142
        case LinkConfiguration::TypeBluetooth:
            pLink = new BluetoothLink(dynamic_cast<BluetoothConfiguration*>(config));
            break;
#endif
dogmaphobic's avatar
dogmaphobic committed
143
#ifndef __mobile__
Don Gagne's avatar
Don Gagne committed
144 145 146
        case LinkConfiguration::TypeLogReplay:
            pLink = new LogReplayLink(dynamic_cast<LogReplayLinkConfiguration*>(config));
            break;
dogmaphobic's avatar
dogmaphobic committed
147
#endif
148
#ifdef QT_DEBUG
149 150 151
        case LinkConfiguration::TypeMock:
            pLink = new MockLink(dynamic_cast<MockConfiguration*>(config));
            break;
152
#endif
153 154 155
        case LinkConfiguration::TypeLast:
        default:
            break;
156 157
    }
    if(pLink) {
158 159
        _addLink(pLink);
        connectLink(pLink);
160 161 162 163
    }
    return pLink;
}

Don Gagne's avatar
Don Gagne committed
164
LinkInterface* LinkManager::createConnectedLink(const QString& name)
165 166 167
{
    Q_ASSERT(name.isEmpty() == false);
    for(int i = 0; i < _linkConfigurations.count(); i++) {
Don Gagne's avatar
Don Gagne committed
168
        LinkConfiguration* conf = _linkConfigurations.value<LinkConfiguration*>(i);
169
        if(conf && conf->name() == name)
Don Gagne's avatar
Don Gagne committed
170
            return createConnectedLink(conf);
171 172 173 174
    }
    return NULL;
}

175
void LinkManager::_addLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
176
{
Don Gagne's avatar
Don Gagne committed
177 178 179 180
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }
181

Don Gagne's avatar
Don Gagne committed
182 183 184
    if (!link) {
        return;
    }
185

Don Gagne's avatar
Don Gagne committed
186
    if (!_links.contains(link)) {
187 188
        bool channelSet = false;

189 190
        // Find a mavlink channel to use for this link
        for (int i=0; i<32; i++) {
191
            if (!(_mavlinkChannelsUsedBitMask & 1 << i)) {
192
                mavlink_reset_channel_status(i);
193
                link->_setMavlinkChannel(i);
Don Gagne's avatar
Don Gagne committed
194
                _mavlinkChannelsUsedBitMask |= 1 << i;
195
                channelSet = true;
196 197 198
                break;
            }
        }
199

200 201 202 203
        if (!channelSet) {
            qWarning() << "Ran out of mavlink channels";
        }

Don Gagne's avatar
Don Gagne committed
204
        _links.append(link);
205 206
        emit newLink(link);
    }
207

Don Gagne's avatar
Don Gagne committed
208 209
    connect(link, &LinkInterface::communicationError,   _app,               &QGCApplication::criticalMessageBoxOnMainThread);
    connect(link, &LinkInterface::bytesReceived,        _mavlinkProtocol,   &MAVLinkProtocol::receiveBytes);
210

211
    _mavlinkProtocol->resetMetadataForLink(link);
212

213 214 215 216 217 218
    connect(link, &LinkInterface::connected,            this, &LinkManager::_linkConnected);
    connect(link, &LinkInterface::disconnected,         this, &LinkManager::_linkDisconnected);

    // This connection is queued since it will cloe the link. So we want the link emitter to return otherwise we would
    // close the link our from under itself.
    connect(link, &LinkInterface::connectionRemoved,    this, &LinkManager::_linkConnectionRemoved, Qt::QueuedConnection);
219
}
pixhawk's avatar
pixhawk committed
220

Don Gagne's avatar
Don Gagne committed
221
void LinkManager::disconnectAll(void)
pixhawk's avatar
pixhawk committed
222
{
Don Gagne's avatar
Don Gagne committed
223 224
    // Walk list in reverse order to preserve indices during delete
    for (int i=_links.count()-1; i>=0; i--) {
Don Gagne's avatar
Don Gagne committed
225
        disconnectLink(_links.value<LinkInterface*>(i));
226
    }
pixhawk's avatar
pixhawk committed
227 228 229 230
}

bool LinkManager::connectLink(LinkInterface* link)
{
231
    Q_ASSERT(link);
232

233 234 235 236
    if (_connectionsSuspendedMsg()) {
        return false;
    }

237
    return link->_connect();
pixhawk's avatar
pixhawk committed
238 239
}

Don Gagne's avatar
Don Gagne committed
240
void LinkManager::disconnectLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
241
{
242 243 244
    if (!link || !_links.contains(link)) {
        return;
    }
Don Gagne's avatar
Don Gagne committed
245

Don Gagne's avatar
Don Gagne committed
246 247
    link->_disconnect();
    LinkConfiguration* config = link->getLinkConfiguration();
248 249 250 251
    if (config) {
        if (_autoconnectConfigurations.contains(config)) {
            config->setLink(NULL);
        }
252
    }
Don Gagne's avatar
Don Gagne committed
253
    _deleteLink(link);
254
    if (_autoconnectConfigurations.contains(config)) {
255
        qCDebug(LinkManagerLog) << "Removing disconnected autoconnect config" << config->name();
256 257 258
        _autoconnectConfigurations.removeOne(config);
        delete config;
    }
pixhawk's avatar
pixhawk committed
259 260
}

261
void LinkManager::_deleteLink(LinkInterface* link)
262
{
Don Gagne's avatar
Don Gagne committed
263 264 265 266 267 268 269 270
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }

    if (!link) {
        return;
    }
271

272 273
    // Free up the mavlink channel associated with this link
    _mavlinkChannelsUsedBitMask &= ~(1 << link->getMavlinkChannel());
274

Don Gagne's avatar
Don Gagne committed
275 276
    _links.removeOne(link);
    delete link;
277

Don Gagne's avatar
Don Gagne committed
278
    // Emit removal of link
279
    emit linkDeleted(link);
pixhawk's avatar
pixhawk committed
280 281
}

282 283 284 285 286
/// @brief If all new connections should be suspended a message is displayed to the user and true
///         is returned;
bool LinkManager::_connectionsSuspendedMsg(void)
{
    if (_connectionsSuspended) {
287
        qgcApp()->showMessage(QString("Connect not allowed: %1").arg(_connectionsSuspendedReason));
288 289 290 291 292 293 294 295 296 297 298 299
        return true;
    } else {
        return false;
    }
}

void LinkManager::setConnectionsSuspended(QString reason)
{
    _connectionsSuspended = true;
    _connectionsSuspendedReason = reason;
    Q_ASSERT(!reason.isEmpty());
}
300

301 302 303 304 305 306 307 308 309
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

void LinkManager::_linkDisconnected(void)
{
    emit linkDisconnected((LinkInterface*)sender());
}
310

311 312 313 314 315 316
void LinkManager::_linkConnectionRemoved(LinkInterface* link)
{
    // Link has been removed from system, disconnect it automatically
    disconnectLink(link);
}

317 318 319 320 321 322 323 324 325
void LinkManager::suspendConfigurationUpdates(bool suspend)
{
    _configUpdateSuspended = suspend;
}

void LinkManager::saveLinkConfigurationList()
{
    QSettings settings;
    settings.remove(LinkConfiguration::settingsRoot());
326 327
    int trueCount = 0;
    for (int i = 0; i < _linkConfigurations.count(); i++) {
Don Gagne's avatar
Don Gagne committed
328 329 330 331 332
        LinkConfiguration* linkConfig = _linkConfigurations.value<LinkConfiguration*>(i);
        if (linkConfig) {
            if(!linkConfig->isDynamic())
            {
                QString root = LinkConfiguration::settingsRoot();
333
                root += QString("/Link%1").arg(trueCount++);
Don Gagne's avatar
Don Gagne committed
334 335
                settings.setValue(root + "/name", linkConfig->name());
                settings.setValue(root + "/type", linkConfig->type());
336
                settings.setValue(root + "/auto", linkConfig->isAutoConnect());
Don Gagne's avatar
Don Gagne committed
337 338 339 340
                // Have the instance save its own values
                linkConfig->saveSettings(settings, root);
            }
        } else {
341
            qWarning() << "Internal error for link configuration in LinkManager";
dogmaphobic's avatar
dogmaphobic committed
342
        }
343
    }
dogmaphobic's avatar
dogmaphobic committed
344
    QString root(LinkConfiguration::settingsRoot());
345 346
    settings.setValue(root + "/count", trueCount);
    emit linkConfigurationsChanged();
347 348 349 350
}

void LinkManager::loadLinkConfigurationList()
{
351
    bool linksChanged = false;
352
#ifdef QT_DEBUG
353
    bool mockPresent  = false;
354
#endif
355 356 357 358 359 360 361 362 363 364
    QSettings settings;
    // Is the group even there?
    if(settings.contains(LinkConfiguration::settingsRoot() + "/count")) {
        // Find out how many configurations we have
        int count = settings.value(LinkConfiguration::settingsRoot() + "/count").toInt();
        for(int i = 0; i < count; i++) {
            QString root(LinkConfiguration::settingsRoot());
            root += QString("/Link%1").arg(i);
            if(settings.contains(root + "/type")) {
                int type = settings.value(root + "/type").toInt();
365
                if((LinkConfiguration::LinkType)type < LinkConfiguration::TypeLast) {
366 367 368 369
                    if(settings.contains(root + "/name")) {
                        QString name = settings.value(root + "/name").toString();
                        if(!name.isEmpty()) {
                            LinkConfiguration* pLink = NULL;
370 371
                            bool autoConnect = settings.value(root + "/auto").toBool();
                            switch((LinkConfiguration::LinkType)type) {
dogmaphobic's avatar
dogmaphobic committed
372
#ifndef __ios__
373 374 375
                                case LinkConfiguration::TypeSerial:
                                    pLink = (LinkConfiguration*)new SerialConfiguration(name);
                                    break;
dogmaphobic's avatar
dogmaphobic committed
376
#endif
377 378 379
                                case LinkConfiguration::TypeUdp:
                                    pLink = (LinkConfiguration*)new UDPConfiguration(name);
                                    break;
380 381 382
                                case LinkConfiguration::TypeTcp:
                                    pLink = (LinkConfiguration*)new TCPConfiguration(name);
                                    break;
dogmaphobic's avatar
dogmaphobic committed
383
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
384 385 386 387
                                case LinkConfiguration::TypeBluetooth:
                                    pLink = (LinkConfiguration*)new BluetoothConfiguration(name);
                                    break;
#endif
dogmaphobic's avatar
dogmaphobic committed
388
#ifndef __mobile__
Don Gagne's avatar
Don Gagne committed
389 390 391
                                case LinkConfiguration::TypeLogReplay:
                                    pLink = (LinkConfiguration*)new LogReplayLinkConfiguration(name);
                                    break;
dogmaphobic's avatar
dogmaphobic committed
392
#endif
393
#ifdef QT_DEBUG
394 395
                                case LinkConfiguration::TypeMock:
                                    pLink = (LinkConfiguration*)new MockConfiguration(name);
396
                                    mockPresent = true;
397
                                    break;
398
#endif
399 400 401
                                default:
                                case LinkConfiguration::TypeLast:
                                    break;
402 403
                            }
                            if(pLink) {
404 405
                                //-- Have the instance load its own values
                                pLink->setAutoConnect(autoConnect);
406
                                pLink->loadSettings(settings, root);
Don Gagne's avatar
Don Gagne committed
407
                                _linkConfigurations.append(pLink);
408
                                linksChanged = true;
409 410
                            }
                        } else {
411
                            qWarning() << "Link Configuration" << root << "has an empty name." ;
412 413
                        }
                    } else {
414
                        qWarning() << "Link Configuration" << root << "has no name." ;
415 416
                    }
                } else {
417
                    qWarning() << "Link Configuration" << root << "an invalid type: " << type;
418 419
                }
            } else {
420
                qWarning() << "Link Configuration" << root << "has no type." ;
421 422 423
            }
        }
    }
424
    // Debug buids always add MockLink automatically (if one is not already there)
425
#ifdef QT_DEBUG
426 427 428 429 430 431 432
    if(!mockPresent)
    {
        MockConfiguration* pMock = new MockConfiguration("Mock Link PX4");
        pMock->setDynamic(true);
        _linkConfigurations.append(pMock);
        linksChanged = true;
    }
433
#endif
434 435

    if(linksChanged) {
436
        emit linkConfigurationsChanged();
437 438
    }
    // Enable automatic Serial PX4/3DR Radio hunting
439 440 441
    _configurationsLoaded = true;
}

dogmaphobic's avatar
dogmaphobic committed
442
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
443
SerialConfiguration* LinkManager::_autoconnectConfigurationsContainsPort(const QString& portName)
444 445
{
    QString searchPort = portName.trimmed();
Don Gagne's avatar
Don Gagne committed
446 447 448 449 450 451 452

    for (int i=0; i<_autoconnectConfigurations.count(); i++) {
        SerialConfiguration* linkConfig = _autoconnectConfigurations.value<SerialConfiguration*>(i);

        if (linkConfig) {
            if (linkConfig->portName() == searchPort) {
                return linkConfig;
453
            }
Don Gagne's avatar
Don Gagne committed
454 455
        } else {
            qWarning() << "Internal error";
456 457 458 459
        }
    }
    return NULL;
}
dogmaphobic's avatar
dogmaphobic committed
460
#endif
461

Don Gagne's avatar
Don Gagne committed
462
void LinkManager::_updateAutoConnectLinks(void)
463
{
Don Gagne's avatar
Don Gagne committed
464
    if (_connectionsSuspended || qgcApp()->runningUnitTests()) {
465 466
        return;
    }
Don Gagne's avatar
Don Gagne committed
467

Don Gagne's avatar
Don Gagne committed
468 469 470 471 472 473 474 475 476
    // Re-add UDP if we need to
    bool foundUDP = false;
    for (int i=0; i<_links.count(); i++) {
        LinkConfiguration* linkConfig = _links.value<LinkInterface*>(i)->getLinkConfiguration();
        if (linkConfig->type() == LinkConfiguration::TypeUdp && linkConfig->name() == _defaultUPDLinkName) {
            foundUDP = true;
            break;
        }
    }
Don Gagne's avatar
Don Gagne committed
477
    if (!foundUDP && _autoconnectUDP) {
Don Gagne's avatar
Don Gagne committed
478
        qCDebug(LinkManagerLog) << "New auto-connect UDP port added";
Don Gagne's avatar
Don Gagne committed
479 480 481
        UDPConfiguration* udpConfig = new UDPConfiguration(_defaultUPDLinkName);
        udpConfig->setLocalPort(QGC_UDP_LOCAL_PORT);
        udpConfig->setDynamic(true);
482
        _linkConfigurations.append(udpConfig);
Don Gagne's avatar
Don Gagne committed
483
        createConnectedLink(udpConfig);
484
        emit linkConfigurationsChanged();
Don Gagne's avatar
Don Gagne committed
485 486
    }

487
#ifndef __ios__
dogmaphobic's avatar
dogmaphobic committed
488
    QStringList currentPorts;
Don Gagne's avatar
Don Gagne committed
489
    QList<QGCSerialPortInfo> portList = QGCSerialPortInfo::availablePorts();
Don Gagne's avatar
Don Gagne committed
490

491
    // Iterate Comm Ports
Don Gagne's avatar
Don Gagne committed
492
    foreach (QGCSerialPortInfo portInfo, portList) {
Don Gagne's avatar
Don Gagne committed
493 494 495 496 497 498 499 500 501
        qCDebug(LinkManagerVerboseLog) << "-----------------------------------------------------";
        qCDebug(LinkManagerVerboseLog) << "portName:          " << portInfo.portName();
        qCDebug(LinkManagerVerboseLog) << "systemLocation:    " << portInfo.systemLocation();
        qCDebug(LinkManagerVerboseLog) << "description:       " << portInfo.description();
        qCDebug(LinkManagerVerboseLog) << "manufacturer:      " << portInfo.manufacturer();
        qCDebug(LinkManagerVerboseLog) << "serialNumber:      " << portInfo.serialNumber();
        qCDebug(LinkManagerVerboseLog) << "vendorIdentifier:  " << portInfo.vendorIdentifier();
        qCDebug(LinkManagerVerboseLog) << "productIdentifier: " << portInfo.productIdentifier();

dogmaphobic's avatar
dogmaphobic committed
502 503
        // Save port name
        currentPorts << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
504 505 506 507 508 509

        QGCSerialPortInfo::BoardType_t boardType = portInfo.boardType();

        if (boardType != QGCSerialPortInfo::BoardTypeUnknown) {
            if (portInfo.isBootloader()) {
                // Don't connect to bootloader
510
                qCDebug(LinkManagerLog) << "Waiting for bootloader to finish" << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
511 512
                continue;
            }
513

514 515 516 517 518 519 520
            if (_autoconnectConfigurationsContainsPort(portInfo.systemLocation())) {
                qCDebug(LinkManagerVerboseLog) << "Skipping existing autoconnect" << portInfo.systemLocation();
            } else if (!_autoconnectWaitList.contains(portInfo.systemLocation())) {
                // We don't connect to the port the first time we see it. The ability to correctly detect whether we
                // are in the bootloader is flaky from a cross-platform standpoint. So by putting it on a wait list
                // and only connect on the second pass we leave enough time for the board to boot up.
                qCDebug(LinkManagerLog) << "Waiting for next autoconnect pass" << portInfo.systemLocation();
521 522
                _autoconnectWaitList[portInfo.systemLocation()] = 1;
            } else if (++_autoconnectWaitList[portInfo.systemLocation()] * _autoconnectUpdateTimerMSecs > _autoconnectConnectDelayMSecs) {
Don Gagne's avatar
Don Gagne committed
523 524
                SerialConfiguration* pSerialConfig = NULL;

525
                _autoconnectWaitList.remove(portInfo.systemLocation());
526

Don Gagne's avatar
Don Gagne committed
527 528 529
                switch (boardType) {
                case QGCSerialPortInfo::BoardTypePX4FMUV1:
                case QGCSerialPortInfo::BoardTypePX4FMUV2:
530
                case QGCSerialPortInfo::BoardTypePX4FMUV4:
Don Gagne's avatar
Don Gagne committed
531 532
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("Pixhawk on %1").arg(portInfo.portName().trimmed()));
533
                        pSerialConfig->setUsbDirect(true);
Don Gagne's avatar
Don Gagne committed
534
                    }
Don Gagne's avatar
Don Gagne committed
535 536
                    break;
                case QGCSerialPortInfo::BoardTypeAeroCore:
Don Gagne's avatar
Don Gagne committed
537 538
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("AeroCore on %1").arg(portInfo.portName().trimmed()));
539
                        pSerialConfig->setUsbDirect(true);
Don Gagne's avatar
Don Gagne committed
540
                    }
Don Gagne's avatar
Don Gagne committed
541
                    break;
Henry Zhang's avatar
Henry Zhang committed
542 543 544 545 546 547
                case QGCSerialPortInfo::BoardTypeMINDPXFMUV2:
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("MindPX on %1").arg(portInfo.portName().trimmed()));
                        pSerialConfig->setUsbDirect(true);
                    }
                    break;
548 549 550 551 552 553 554 555 556 557 558 559
                case QGCSerialPortInfo::BoardTypeTAPV1:
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("TAP on %1").arg(portInfo.portName().trimmed()));
                        pSerialConfig->setUsbDirect(true);
                    }
                    break;
                case QGCSerialPortInfo::BoardTypeASCV1:
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("ASC on %1").arg(portInfo.portName().trimmed()));
                        pSerialConfig->setUsbDirect(true);
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
560
                case QGCSerialPortInfo::BoardTypePX4Flow:
Don Gagne's avatar
Don Gagne committed
561 562 563
                    if (_autoconnectPX4Flow) {
                        pSerialConfig = new SerialConfiguration(QString("PX4Flow on %1").arg(portInfo.portName().trimmed()));
                    }
Don Gagne's avatar
Don Gagne committed
564
                    break;
Don Gagne's avatar
Don Gagne committed
565
                case QGCSerialPortInfo::BoardTypeSikRadio:
Don Gagne's avatar
Don Gagne committed
566
                    if (_autoconnect3DRRadio) {
567
                        pSerialConfig = new SerialConfiguration(QString("SiK Radio on %1").arg(portInfo.portName().trimmed()));
Don Gagne's avatar
Don Gagne committed
568 569
                    }
                    break;
570 571 572 573 574
                case QGCSerialPortInfo::BoardTypeLibrePilot:
                    if (_autoconnectLibrePilot) {
                        pSerialConfig = new SerialConfiguration(QString("LibrePilot on %1").arg(portInfo.portName().trimmed()));
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
575 576 577 578 579 580 581 582
#ifndef __mobile__
                case QGCSerialPortInfo::BoardTypeRTKGPS:
                    if (_autoconnectRTKGPS && !_toolbox->gpsManager()->connected()) {
                        qCDebug(LinkManagerLog) << "RTK GPS auto-connected";
                        _toolbox->gpsManager()->connectGPS(portInfo.systemLocation());
                    }
                    break;
#endif
Don Gagne's avatar
Don Gagne committed
583 584
                default:
                    qWarning() << "Internal error";
Don Gagne's avatar
Don Gagne committed
585
                    continue;
dogmaphobic's avatar
dogmaphobic committed
586
                }
Don Gagne's avatar
Don Gagne committed
587

Don Gagne's avatar
Don Gagne committed
588 589
                if (pSerialConfig) {
                    qCDebug(LinkManagerLog) << "New auto-connect port added: " << pSerialConfig->name() << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
590
                    pSerialConfig->setBaud(boardType == QGCSerialPortInfo::BoardTypeSikRadio ? 57600 : 115200);
Don Gagne's avatar
Don Gagne committed
591 592 593
                    pSerialConfig->setDynamic(true);
                    pSerialConfig->setPortName(portInfo.systemLocation());
                    _autoconnectConfigurations.append(pSerialConfig);
Don Gagne's avatar
Don Gagne committed
594
                    createConnectedLink(pSerialConfig);
Don Gagne's avatar
Don Gagne committed
595
                }
dogmaphobic's avatar
dogmaphobic committed
596 597 598
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
599

dogmaphobic's avatar
dogmaphobic committed
600 601
    // Now we go through the current configuration list and make sure any dynamic config has gone away
    QList<LinkConfiguration*>  _confToDelete;
Don Gagne's avatar
Don Gagne committed
602 603 604 605
    for (int i=0; i<_autoconnectConfigurations.count(); i++) {
        SerialConfiguration* linkConfig = _autoconnectConfigurations.value<SerialConfiguration*>(i);
        if (linkConfig) {
            if (!currentPorts.contains(linkConfig->portName())) {
606 607 608 609 610 611 612 613 614
                if (linkConfig->link()) {
                    if (linkConfig->link()->isConnected()) {
                        if (linkConfig->link()->active()) {
                            // We don't remove links which are still connected which have been active with a vehicle on them
                            // even though at this point the cable may have been pulled. Instead we wait for the user to
                            // Disconnect. Once the user disconnects, the link will be removed.
                            continue;
                        }
                    }
Don Gagne's avatar
Don Gagne committed
615
                }
616
                _confToDelete.append(linkConfig);
dogmaphobic's avatar
dogmaphobic committed
617
            }
Don Gagne's avatar
Don Gagne committed
618 619
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
620 621
        }
    }
Don Gagne's avatar
Don Gagne committed
622

Don Gagne's avatar
Don Gagne committed
623
    // Now remove all configs that are gone
Don Gagne's avatar
Don Gagne committed
624
    foreach (LinkConfiguration* pDeleteConfig, _confToDelete) {
Don Gagne's avatar
Don Gagne committed
625
        qCDebug(LinkManagerLog) << "Removing unused autoconnect config" << pDeleteConfig->name();
Don Gagne's avatar
Don Gagne committed
626
        _autoconnectConfigurations.removeOne(pDeleteConfig);
627 628 629
        if (pDeleteConfig->link()) {
            disconnectLink(pDeleteConfig->link());
        }
Don Gagne's avatar
Don Gagne committed
630
        delete pDeleteConfig;
631
    }
632
#endif // __ios__
633 634
}

Don Gagne's avatar
Don Gagne committed
635 636 637
void LinkManager::shutdown(void)
{
    setConnectionsSuspended("Shutdown");
Don Gagne's avatar
Don Gagne committed
638
    disconnectAll();
Don Gagne's avatar
Don Gagne committed
639 640
}

Don Gagne's avatar
Don Gagne committed
641
bool LinkManager::_setAutoconnectWorker(bool& currentAutoconnect, bool newAutoconnect, const char* autoconnectKey)
Don Gagne's avatar
Don Gagne committed
642
{
Don Gagne's avatar
Don Gagne committed
643
    if (currentAutoconnect != newAutoconnect) {
Don Gagne's avatar
Don Gagne committed
644 645 646
        QSettings settings;

        settings.beginGroup(_settingsGroup);
Don Gagne's avatar
Don Gagne committed
647 648 649 650 651 652 653
        settings.setValue(autoconnectKey, newAutoconnect);
        currentAutoconnect = newAutoconnect;
        return true;
    }

    return false;
}
Don Gagne's avatar
Don Gagne committed
654

Don Gagne's avatar
Don Gagne committed
655 656 657
void LinkManager::setAutoconnectUDP(bool autoconnect)
{
    if (_setAutoconnectWorker(_autoconnectUDP, autoconnect, _autoconnectUDPKey)) {
Don Gagne's avatar
Don Gagne committed
658
        emit autoconnectUDPChanged(autoconnect);
659
    }
Don Gagne's avatar
Don Gagne committed
660 661 662 663
}

void LinkManager::setAutoconnectPixhawk(bool autoconnect)
{
Don Gagne's avatar
Don Gagne committed
664
    if (_setAutoconnectWorker(_autoconnectPixhawk, autoconnect, _autoconnectPixhawkKey)) {
Don Gagne's avatar
Don Gagne committed
665 666 667 668 669 670
        emit autoconnectPixhawkChanged(autoconnect);
    }
}

void LinkManager::setAutoconnect3DRRadio(bool autoconnect)
{
Don Gagne's avatar
Don Gagne committed
671
    if (_setAutoconnectWorker(_autoconnect3DRRadio, autoconnect, _autoconnect3DRRadioKey)) {
Don Gagne's avatar
Don Gagne committed
672 673 674 675 676 677
        emit autoconnect3DRRadioChanged(autoconnect);
    }
}

void LinkManager::setAutoconnectPX4Flow(bool autoconnect)
{
Don Gagne's avatar
Don Gagne committed
678
    if (_setAutoconnectWorker(_autoconnectPX4Flow, autoconnect, _autoconnectPX4FlowKey)) {
Don Gagne's avatar
Don Gagne committed
679 680
        emit autoconnectPX4FlowChanged(autoconnect);
    }
Don Gagne's avatar
Don Gagne committed
681
}
Don Gagne's avatar
Don Gagne committed
682

Don Gagne's avatar
Don Gagne committed
683 684 685 686 687
void LinkManager::setAutoconnectRTKGPS(bool autoconnect)
{
    if (_setAutoconnectWorker(_autoconnectRTKGPS, autoconnect, _autoconnectRTKGPSKey)) {
        emit autoconnectRTKGPSChanged(autoconnect);
    }
688
}
689

690 691 692 693 694 695 696
void LinkManager::setAutoconnectLibrePilot(bool autoconnect)
{
    if (_setAutoconnectWorker(_autoconnectLibrePilot, autoconnect, _autoconnectLibrePilotKey)) {
        emit autoconnectLibrePilotChanged(autoconnect);
    }
}

697 698 699 700 701 702 703 704 705 706 707
QStringList LinkManager::linkTypeStrings(void) const
{
    //-- Must follow same order as enum LinkType in LinkConfiguration.h
    static QStringList list;
    if(!list.size())
    {
#ifndef __ios__
        list += "Serial";
#endif
        list += "UDP";
        list += "TCP";
dogmaphobic's avatar
dogmaphobic committed
708
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
709 710
        list += "Bluetooth";
#endif
dogmaphobic's avatar
dogmaphobic committed
711
#ifdef QT_DEBUG
712
        list += "Mock Link";
dogmaphobic's avatar
dogmaphobic committed
713 714
#endif
#ifndef __mobile__
715
        list += "Log Replay";
dogmaphobic's avatar
dogmaphobic committed
716
#endif
dogmaphobic's avatar
dogmaphobic committed
717
        Q_ASSERT(list.size() == (int)LinkConfiguration::TypeLast);
718 719 720 721
    }
    return list;
}

722
void LinkManager::_updateSerialPorts()
723
{
724 725
    _commPortList.clear();
    _commPortDisplayList.clear();
726
#ifndef __ios__
727 728
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
    foreach (const QSerialPortInfo &info, portList)
729
    {
730 731 732
        QString port = info.systemLocation().trimmed();
        _commPortList += port;
        _commPortDisplayList += SerialConfiguration::cleanPortDisplayname(port);
733 734
    }
#endif
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
}

QStringList LinkManager::serialPortStrings(void)
{
    if(!_commPortDisplayList.size())
    {
        _updateSerialPorts();
    }
    return _commPortDisplayList;
}

QStringList LinkManager::serialPorts(void)
{
    if(!_commPortList.size())
    {
        _updateSerialPorts();
    }
752 753 754 755 756 757 758 759 760 761 762 763
    return _commPortList;
}

QStringList LinkManager::serialBaudRates(void)
{
#ifdef __ios__
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
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

bool LinkManager::endConfigurationEditing(LinkConfiguration* config, LinkConfiguration* editedConfig)
{
    Q_ASSERT(config != NULL);
    Q_ASSERT(editedConfig != NULL);
    _fixUnnamed(editedConfig);
    config->copyFrom(editedConfig);
    saveLinkConfigurationList();
    // Tell link about changes (if any)
    config->updateSettings();
    // Discard temporary duplicate
    delete editedConfig;
    return true;
}

bool LinkManager::endCreateConfiguration(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
    _fixUnnamed(config);
    _linkConfigurations.append(config);
    saveLinkConfigurationList();
    return true;
}

LinkConfiguration* LinkManager::createConfiguration(int type, const QString& name)
{
dogmaphobic's avatar
dogmaphobic committed
790
#ifndef __ios__
791 792
    if((LinkConfiguration::LinkType)type == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
793
#endif
794 795 796 797 798 799
    return LinkConfiguration::createSettings(type, name);
}

LinkConfiguration* LinkManager::startConfigurationEditing(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
dogmaphobic's avatar
dogmaphobic committed
800
#ifndef __ios__
801 802
    if(config->type() == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
803
#endif
804 805 806 807 808 809 810 811 812 813 814 815 816
    return LinkConfiguration::duplicateSettings(config);
}


void LinkManager::_fixUnnamed(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
    //-- Check for "Unnamed"
    if (config->name() == "Unnamed") {
        switch(config->type()) {
#ifndef __ios__
            case LinkConfiguration::TypeSerial: {
                QString tname = dynamic_cast<SerialConfiguration*>(config)->portName();
817
#ifdef Q_OS_WIN
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
                tname.replace("\\\\.\\", "");
#else
                tname.replace("/dev/cu.", "");
                tname.replace("/dev/", "");
#endif
                config->setName(QString("Serial Device on %1").arg(tname));
                break;
                }
#endif
            case LinkConfiguration::TypeUdp:
                config->setName(
                    QString("UDP Link on Port %1").arg(dynamic_cast<UDPConfiguration*>(config)->localPort()));
                break;
            case LinkConfiguration::TypeTcp: {
                    TCPConfiguration* tconfig = dynamic_cast<TCPConfiguration*>(config);
                    if(tconfig) {
                        config->setName(
                            QString("TCP Link %1:%2").arg(tconfig->address().toString()).arg((int)tconfig->port()));
                    }
                }
                break;
dogmaphobic's avatar
dogmaphobic committed
839
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
840 841 842
            case LinkConfiguration::TypeBluetooth: {
                    BluetoothConfiguration* tconfig = dynamic_cast<BluetoothConfiguration*>(config);
                    if(tconfig) {
843
                        config->setName(QString("%1 (Bluetooth Device)").arg(tconfig->device().name));
dogmaphobic's avatar
dogmaphobic committed
844 845 846 847
                    }
                }
                break;
#endif
dogmaphobic's avatar
dogmaphobic committed
848
#ifndef __mobile__
849
            case LinkConfiguration::TypeLogReplay: {
dogmaphobic's avatar
dogmaphobic committed
850 851 852 853
                    LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
                    if(tconfig) {
                        config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
                    }
854 855
                }
                break;
dogmaphobic's avatar
dogmaphobic committed
856
#endif
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
#ifdef QT_DEBUG
            case LinkConfiguration::TypeMock:
                config->setName(
                    QString("Mock Link"));
                break;
#endif
            case LinkConfiguration::TypeLast:
            default:
                break;
        }
    }
}

void LinkManager::removeConfiguration(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
    LinkInterface* iface = config->link();
    if(iface) {
        disconnectLink(iface);
    }
    // Remove configuration
    _linkConfigurations.removeOne(config);
    delete config;
    // Save list
    saveLinkConfigurationList();
}
883

884 885 886 887
bool LinkManager::isAutoconnectLink(LinkInterface* link)
{
    return _autoconnectConfigurations.contains(link->getLinkConfiguration());
}
dogmaphobic's avatar
dogmaphobic committed
888 889 890 891 892

bool LinkManager::isBluetoothAvailable(void)
{
    return qgcApp()->isBluetoothAvailable();
}
Don Gagne's avatar
Don Gagne committed
893

Don Gagne's avatar
Don Gagne committed
894
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
895 896
void LinkManager::_activeLinkCheck(void)
{
897
    SerialLink* link = NULL;
Don Gagne's avatar
Don Gagne committed
898 899 900
    bool found = false;

    if (_activeLinkCheckList.count() != 0) {
901
        link = _activeLinkCheckList.takeFirst();
Don Gagne's avatar
Don Gagne committed
902 903 904 905 906 907 908 909 910 911
        if (_links.contains(link) && link->isConnected()) {
            // Make sure there is a vehicle on the link
            QmlObjectListModel* vehicles = _toolbox->multiVehicleManager()->vehicles();
            for (int i=0; i<vehicles->count(); i++) {
                Vehicle* vehicle = qobject_cast<Vehicle*>(vehicles->get(i));
                if (vehicle->containsLink(link)) {
                    found = true;
                    break;
                }
            }
912 913
        } else {
            link = NULL;
Don Gagne's avatar
Don Gagne committed
914 915 916 917 918 919 920
        }
    }

    if (_activeLinkCheckList.count() == 0) {
        _activeLinkCheckTimer.stop();
    }

921 922 923
    if (!found && link) {
        // See if we can get an NSH prompt on this link
        bool foundNSHPrompt = false;
924
        link->writeBytesSafe("\r", 1);
925 926 927 928 929 930 931 932 933 934 935
        QSignalSpy spy(link, SIGNAL(bytesReceived(LinkInterface*, QByteArray)));
        if (spy.wait(100)) {
            QList<QVariant> arguments = spy.takeFirst();
            if (arguments[1].value<QByteArray>().contains("nsh>")) {
                foundNSHPrompt = true;
            }
        }

        qgcApp()->showMessage(foundNSHPrompt ?
                                  QStringLiteral("Please check to make sure you have an SD Card inserted in your Vehicle and try again.") :
                                  QStringLiteral("Your Vehicle is not responding. If this continues shutdown QGroundControl, restart the Vehicle letting it boot completely, then start QGroundControl."));
Don Gagne's avatar
Don Gagne committed
936 937
    }
}
Don Gagne's avatar
Don Gagne committed
938
#endif