LinkManager.cc 32.4 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

pixhawk's avatar
pixhawk committed
10 11
#include <QList>
#include <QApplication>
12
#include <QDebug>
13
#include <QSignalSpy>
dogmaphobic's avatar
dogmaphobic committed
14

Gus Grubba's avatar
Gus Grubba committed
15
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
16
#include "QGCSerialPortInfo.h"
dogmaphobic's avatar
dogmaphobic committed
17
#endif
18

19
#include "LinkManager.h"
20
#include "QGCApplication.h"
Don Gagne's avatar
Don Gagne committed
21 22
#include "UDPLink.h"
#include "TCPLink.h"
23
#include "SettingsManager.h"
dogmaphobic's avatar
dogmaphobic committed
24
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
25 26
#include "BluetoothLink.h"
#endif
27

Don Gagne's avatar
Don Gagne committed
28 29 30 31
#ifndef __mobile__
    #include "GPSManager.h"
#endif

Don Gagne's avatar
Don Gagne committed
32
QGC_LOGGING_CATEGORY(LinkManagerLog, "LinkManagerLog")
Don Gagne's avatar
Don Gagne committed
33 34
QGC_LOGGING_CATEGORY(LinkManagerVerboseLog, "LinkManagerVerboseLog")

Don Gagne's avatar
Don Gagne committed
35
const char* LinkManager::_defaultUPDLinkName =       "UDP Link (AutoConnect)";
36

37 38 39 40 41 42 43 44
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

45 46
LinkManager::LinkManager(QGCApplication* app, QGCToolbox* toolbox)
    : QGCTool(app, toolbox)
47 48 49
    , _configUpdateSuspended(false)
    , _configurationsLoaded(false)
    , _connectionsSuspended(false)
50
    , _mavlinkChannelsUsedBitMask(1)    // We never use channel 0 to avoid sequence numbering problems
51
    , _autoConnectSettings(NULL)
52
    , _mavlinkProtocol(NULL)
pixhawk's avatar
pixhawk committed
53
{
Don Gagne's avatar
Don Gagne committed
54 55 56 57
    qmlRegisterUncreatableType<LinkManager>         ("QGroundControl", 1, 0, "LinkManager",         "Reference only");
    qmlRegisterUncreatableType<LinkConfiguration>   ("QGroundControl", 1, 0, "LinkConfiguration",   "Reference only");
    qmlRegisterUncreatableType<LinkInterface>       ("QGroundControl", 1, 0, "LinkInterface",       "Reference only");

Gus Grubba's avatar
Gus Grubba committed
58
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
59 60 61
    _activeLinkCheckTimer.setInterval(_activeLinkCheckTimeoutMSecs);
    _activeLinkCheckTimer.setSingleShot(false);
    connect(&_activeLinkCheckTimer, &QTimer::timeout, this, &LinkManager::_activeLinkCheck);
Don Gagne's avatar
Don Gagne committed
62
#endif
pixhawk's avatar
pixhawk committed
63 64 65 66
}

LinkManager::~LinkManager()
{
67

pixhawk's avatar
pixhawk committed
68 69
}

70 71 72 73
void LinkManager::setToolbox(QGCToolbox *toolbox)
{
   QGCTool::setToolbox(toolbox);

74
   _autoConnectSettings = toolbox->settingsManager()->autoConnectSettings();
75 76
   _mavlinkProtocol = _toolbox->mavlinkProtocol();

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

80 81
}

Don Gagne's avatar
Don Gagne committed
82 83 84 85 86 87 88 89 90 91
// This should only be used by Qml code
void LinkManager::createConnectedLink(LinkConfiguration* config)
{
    for(int i = 0; i < _sharedConfigurations.count(); i++) {
        SharedLinkConfigurationPointer& sharedConf = _sharedConfigurations[i];
        if (sharedConf->name() == config->name())
            createConnectedLink(sharedConf);
    }
}

92
LinkInterface* LinkManager::createConnectedLink(SharedLinkConfigurationPointer& config)
93
{
94 95 96 97 98
    if (!config) {
        qWarning() << "LinkManager::createConnectedLink called with NULL config";
        return NULL;
    }

99 100
    LinkInterface* pLink = NULL;
    switch(config->type()) {
Gus Grubba's avatar
Gus Grubba committed
101
#ifndef NO_SERIAL_LINK
102
        case LinkConfiguration::TypeSerial:
Don Gagne's avatar
Don Gagne committed
103
        {
104
            SerialConfiguration* serialConfig = dynamic_cast<SerialConfiguration*>(config.data());
Don Gagne's avatar
Don Gagne committed
105
            if (serialConfig) {
106
                pLink = new SerialLink(config);
Don Gagne's avatar
Don Gagne committed
107
                if (serialConfig->usbDirect()) {
108
                    _activeLinkCheckList.append((SerialLink*)pLink);
Don Gagne's avatar
Don Gagne committed
109 110 111 112 113 114 115
                    if (!_activeLinkCheckTimer.isActive()) {
                        _activeLinkCheckTimer.start();
                    }
                }
            }
        }
        break;
dogmaphobic's avatar
dogmaphobic committed
116
#endif
117
        case LinkConfiguration::TypeUdp:
118
            pLink = new UDPLink(config);
119
            break;
120
        case LinkConfiguration::TypeTcp:
121
            pLink = new TCPLink(config);
122
            break;
dogmaphobic's avatar
dogmaphobic committed
123
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
124
        case LinkConfiguration::TypeBluetooth:
125
            pLink = new BluetoothLink(config);
dogmaphobic's avatar
dogmaphobic committed
126 127
            break;
#endif
dogmaphobic's avatar
dogmaphobic committed
128
#ifndef __mobile__
Don Gagne's avatar
Don Gagne committed
129
        case LinkConfiguration::TypeLogReplay:
130
            pLink = new LogReplayLink(config);
Don Gagne's avatar
Don Gagne committed
131
            break;
dogmaphobic's avatar
dogmaphobic committed
132
#endif
133
#ifdef QT_DEBUG
134
        case LinkConfiguration::TypeMock:
135
            pLink = new MockLink(config);
136
            break;
137
#endif
138 139 140
        case LinkConfiguration::TypeLast:
        default:
            break;
141
    }
142 143

    if (pLink) {
144 145
        _addLink(pLink);
        connectLink(pLink);
146
    }
147

148 149 150
    return pLink;
}

Don Gagne's avatar
Don Gagne committed
151
LinkInterface* LinkManager::createConnectedLink(const QString& name)
152 153
{
    Q_ASSERT(name.isEmpty() == false);
154 155 156
    for(int i = 0; i < _sharedConfigurations.count(); i++) {
        SharedLinkConfigurationPointer& conf = _sharedConfigurations[i];
        if (conf->name() == name)
Don Gagne's avatar
Don Gagne committed
157
            return createConnectedLink(conf);
158 159 160 161
    }
    return NULL;
}

162
void LinkManager::_addLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
163
{
Don Gagne's avatar
Don Gagne committed
164 165 166 167
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }
168

Don Gagne's avatar
Don Gagne committed
169 170 171
    if (!link) {
        return;
    }
172

173
    if (!containsLink(link)) {
174 175
        bool channelSet = false;

176 177
        // Find a mavlink channel to use for this link, Channel 0 is reserved for internal use.
        for (int i=1; i<32; i++) {
178
            if (!(_mavlinkChannelsUsedBitMask & 1 << i)) {
179
                mavlink_reset_channel_status(i);
180
                link->_setMavlinkChannel(i);
Don Gagne's avatar
Don Gagne committed
181
                // Start the channel on Mav 1 protocol
182 183
                mavlink_status_t* mavlinkStatus = mavlink_get_channel_status(i);
                mavlinkStatus->flags = mavlink_get_channel_status(i)->flags | MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
184
                qDebug() << "LinkManager mavlinkStatus:channel:flags" << mavlinkStatus << i << mavlinkStatus->flags;
Don Gagne's avatar
Don Gagne committed
185
                _mavlinkChannelsUsedBitMask |= 1 << i;
186
                channelSet = true;
187 188 189
                break;
            }
        }
190

191 192 193 194
        if (!channelSet) {
            qWarning() << "Ran out of mavlink channels";
        }

195
        _sharedLinks.append(SharedLinkInterfacePointer(link));
196 197
        emit newLink(link);
    }
198

Don Gagne's avatar
Don Gagne committed
199 200
    connect(link, &LinkInterface::communicationError,   _app,               &QGCApplication::criticalMessageBoxOnMainThread);
    connect(link, &LinkInterface::bytesReceived,        _mavlinkProtocol,   &MAVLinkProtocol::receiveBytes);
201

202
    _mavlinkProtocol->resetMetadataForLink(link);
203

204 205 206 207 208 209
    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);
210
}
pixhawk's avatar
pixhawk committed
211

Don Gagne's avatar
Don Gagne committed
212
void LinkManager::disconnectAll(void)
pixhawk's avatar
pixhawk committed
213
{
Don Gagne's avatar
Don Gagne committed
214
    // Walk list in reverse order to preserve indices during delete
215 216
    for (int i=_sharedLinks.count()-1; i>=0; i--) {
        disconnectLink(_sharedLinks[i].data());
217
    }
pixhawk's avatar
pixhawk committed
218 219 220 221
}

bool LinkManager::connectLink(LinkInterface* link)
{
222
    Q_ASSERT(link);
223

224 225 226 227
    if (_connectionsSuspendedMsg()) {
        return false;
    }

228
    return link->_connect();
pixhawk's avatar
pixhawk committed
229 230
}

Don Gagne's avatar
Don Gagne committed
231
void LinkManager::disconnectLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
232
{
233
    if (!link || !containsLink(link)) {
234 235
        return;
    }
Don Gagne's avatar
Don Gagne committed
236

Don Gagne's avatar
Don Gagne committed
237
    link->_disconnect();
238

Don Gagne's avatar
Don Gagne committed
239
    LinkConfiguration* config = link->getLinkConfiguration();
240 241 242 243 244
    for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
        if (_sharedAutoconnectConfigurations[i].data() == config) {
            qCDebug(LinkManagerLog) << "Removing disconnected autoconnect config" << config->name();
            _sharedAutoconnectConfigurations.removeAt(i);
            break;
245
        }
246
    }
247

Don Gagne's avatar
Don Gagne committed
248
    _deleteLink(link);
pixhawk's avatar
pixhawk committed
249 250
}

251
void LinkManager::_deleteLink(LinkInterface* link)
252
{
Don Gagne's avatar
Don Gagne committed
253 254 255 256 257 258 259 260
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }

    if (!link) {
        return;
    }
261

262
    // Free up the mavlink channel associated with this link
263
    _mavlinkChannelsUsedBitMask &= ~(1 << link->mavlinkChannel());
264

265 266 267 268 269 270
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            _sharedLinks.removeAt(i);
            break;
        }
    }
271

Don Gagne's avatar
Don Gagne committed
272
    // Emit removal of link
273
    emit linkDeleted(link);
pixhawk's avatar
pixhawk committed
274 275
}

276 277 278 279 280 281 282 283 284 285 286 287
SharedLinkInterfacePointer LinkManager::sharedLinkInterfacePointerForLink(LinkInterface* link)
{
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            return _sharedLinks[i];
        }
    }

    qWarning() << "LinkManager::sharedLinkInterfaceForLink returning NULL";
    return SharedLinkInterfacePointer(NULL);
}

288 289 290 291 292
/// @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) {
293
        qgcApp()->showMessage(QString("Connect not allowed: %1").arg(_connectionsSuspendedReason));
294 295 296 297 298 299 300 301 302 303 304 305
        return true;
    } else {
        return false;
    }
}

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

307 308 309 310 311 312 313 314 315
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

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

317 318 319 320 321 322
void LinkManager::_linkConnectionRemoved(LinkInterface* link)
{
    // Link has been removed from system, disconnect it automatically
    disconnectLink(link);
}

323 324 325 326 327 328 329 330 331
void LinkManager::suspendConfigurationUpdates(bool suspend)
{
    _configUpdateSuspended = suspend;
}

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

void LinkManager::loadLinkConfigurationList()
{
356
    bool linksChanged = false;
357 358 359 360 361 362 363 364 365 366
    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();
367
                if((LinkConfiguration::LinkType)type < LinkConfiguration::TypeLast) {
368 369 370 371
                    if(settings.contains(root + "/name")) {
                        QString name = settings.value(root + "/name").toString();
                        if(!name.isEmpty()) {
                            LinkConfiguration* pLink = NULL;
372 373
                            bool autoConnect = settings.value(root + "/auto").toBool();
                            switch((LinkConfiguration::LinkType)type) {
Gus Grubba's avatar
Gus Grubba committed
374
#ifndef NO_SERIAL_LINK
375 376 377
                                case LinkConfiguration::TypeSerial:
                                    pLink = (LinkConfiguration*)new SerialConfiguration(name);
                                    break;
dogmaphobic's avatar
dogmaphobic committed
378
#endif
379 380 381
                                case LinkConfiguration::TypeUdp:
                                    pLink = (LinkConfiguration*)new UDPConfiguration(name);
                                    break;
382 383 384
                                case LinkConfiguration::TypeTcp:
                                    pLink = (LinkConfiguration*)new TCPConfiguration(name);
                                    break;
dogmaphobic's avatar
dogmaphobic committed
385
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
386 387 388 389
                                case LinkConfiguration::TypeBluetooth:
                                    pLink = (LinkConfiguration*)new BluetoothConfiguration(name);
                                    break;
#endif
dogmaphobic's avatar
dogmaphobic committed
390
#ifndef __mobile__
Don Gagne's avatar
Don Gagne committed
391 392 393
                                case LinkConfiguration::TypeLogReplay:
                                    pLink = (LinkConfiguration*)new LogReplayLinkConfiguration(name);
                                    break;
dogmaphobic's avatar
dogmaphobic committed
394
#endif
395
#ifdef QT_DEBUG
396 397 398
                                case LinkConfiguration::TypeMock:
                                    pLink = (LinkConfiguration*)new MockConfiguration(name);
                                    break;
399
#endif
400 401 402
                                default:
                                case LinkConfiguration::TypeLast:
                                    break;
403 404
                            }
                            if(pLink) {
405 406
                                //-- Have the instance load its own values
                                pLink->setAutoConnect(autoConnect);
407
                                pLink->loadSettings(settings, root);
408
                                addConfiguration(pLink);
409
                                linksChanged = true;
410 411
                            }
                        } else {
412
                            qWarning() << "Link Configuration" << root << "has an empty name." ;
413 414
                        }
                    } else {
415
                        qWarning() << "Link Configuration" << root << "has no name." ;
416 417
                    }
                } else {
418
                    qWarning() << "Link Configuration" << root << "an invalid type: " << type;
419 420
                }
            } else {
421
                qWarning() << "Link Configuration" << root << "has no type." ;
422 423 424
            }
        }
    }
425 426

    if(linksChanged) {
427
        emit linkConfigurationsChanged();
428 429
    }
    // Enable automatic Serial PX4/3DR Radio hunting
430 431 432
    _configurationsLoaded = true;
}

Gus Grubba's avatar
Gus Grubba committed
433
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
434
SerialConfiguration* LinkManager::_autoconnectConfigurationsContainsPort(const QString& portName)
435 436
{
    QString searchPort = portName.trimmed();
Don Gagne's avatar
Don Gagne committed
437

438 439
    for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
        SerialConfiguration* serialConfig = qobject_cast<SerialConfiguration*>(_sharedAutoconnectConfigurations[i].data());
Don Gagne's avatar
Don Gagne committed
440

441 442 443
        if (serialConfig) {
            if (serialConfig->portName() == searchPort) {
                return serialConfig;
444
            }
Don Gagne's avatar
Don Gagne committed
445 446
        } else {
            qWarning() << "Internal error";
447 448 449 450
        }
    }
    return NULL;
}
dogmaphobic's avatar
dogmaphobic committed
451
#endif
452

Don Gagne's avatar
Don Gagne committed
453
void LinkManager::_updateAutoConnectLinks(void)
454
{
Don Gagne's avatar
Don Gagne committed
455
    if (_connectionsSuspended || qgcApp()->runningUnitTests()) {
456 457
        return;
    }
Don Gagne's avatar
Don Gagne committed
458

Don Gagne's avatar
Don Gagne committed
459 460
    // Re-add UDP if we need to
    bool foundUDP = false;
461 462
    for (int i=0; i<_sharedLinks.count(); i++) {
        LinkConfiguration* linkConfig = _sharedLinks[i]->getLinkConfiguration();
Don Gagne's avatar
Don Gagne committed
463 464 465 466 467
        if (linkConfig->type() == LinkConfiguration::TypeUdp && linkConfig->name() == _defaultUPDLinkName) {
            foundUDP = true;
            break;
        }
    }
468
    if (!foundUDP && _autoConnectSettings->autoConnectUDP()->rawValue().toBool()) {
Don Gagne's avatar
Don Gagne committed
469
        qCDebug(LinkManagerLog) << "New auto-connect UDP port added";
Don Gagne's avatar
Don Gagne committed
470 471
        UDPConfiguration* udpConfig = new UDPConfiguration(_defaultUPDLinkName);
        udpConfig->setLocalPort(QGC_UDP_LOCAL_PORT);
472 473 474
        udpConfig->setDynamic(true);        
        SharedLinkConfigurationPointer config = addConfiguration(udpConfig);
        createConnectedLink(config);
475
        emit linkConfigurationsChanged();
Don Gagne's avatar
Don Gagne committed
476 477
    }

Gus Grubba's avatar
Gus Grubba committed
478
#ifndef NO_SERIAL_LINK
dogmaphobic's avatar
dogmaphobic committed
479
    QStringList currentPorts;
480 481 482 483 484 485
    QList<QGCSerialPortInfo> portList;

#ifdef __android__
    // Android builds only support a single serial connection. Repeatedly calling availablePorts after that one serial
    // port is connected leaks file handles due to a bug somewhere in android serial code. In order to work around that
    // bug after we connect the first serial port we stop probing for additional ports.
486
    if (!_sharedAutoconnectConfigurations.count()) {
487 488
        portList = QGCSerialPortInfo::availablePorts();
    }
489 490
#else
    portList = QGCSerialPortInfo::availablePorts();
491
#endif
Don Gagne's avatar
Don Gagne committed
492

493
    // Iterate Comm Ports
Don Gagne's avatar
Don Gagne committed
494
    foreach (QGCSerialPortInfo portInfo, portList) {
Don Gagne's avatar
Don Gagne committed
495 496 497 498 499 500 501 502 503
        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
504 505
        // Save port name
        currentPorts << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
506

507 508
        QGCSerialPortInfo::BoardType_t boardType;
        QString boardName;
Don Gagne's avatar
Don Gagne committed
509

510
        if (portInfo.getBoardInfo(boardType, boardName)) {
Don Gagne's avatar
Don Gagne committed
511 512
            if (portInfo.isBootloader()) {
                // Don't connect to bootloader
513
                qCDebug(LinkManagerLog) << "Waiting for bootloader to finish" << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
514 515
                continue;
            }
516

517 518 519 520 521 522 523
            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();
524 525
                _autoconnectWaitList[portInfo.systemLocation()] = 1;
            } else if (++_autoconnectWaitList[portInfo.systemLocation()] * _autoconnectUpdateTimerMSecs > _autoconnectConnectDelayMSecs) {
Don Gagne's avatar
Don Gagne committed
526 527
                SerialConfiguration* pSerialConfig = NULL;

528
                _autoconnectWaitList.remove(portInfo.systemLocation());
529

Don Gagne's avatar
Don Gagne committed
530
                switch (boardType) {
531
                case QGCSerialPortInfo::BoardTypePixhawk:
532
                    if (_autoConnectSettings->autoConnectPixhawk()->rawValue().toBool()) {
533
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
534 535 536
                        pSerialConfig->setUsbDirect(true);
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
537
                case QGCSerialPortInfo::BoardTypePX4Flow:
538
                    if (_autoConnectSettings->autoConnectPX4Flow()->rawValue().toBool()) {
539
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
Don Gagne's avatar
Don Gagne committed
540
                    }
Don Gagne's avatar
Don Gagne committed
541
                    break;
542
                case QGCSerialPortInfo::BoardTypeSiKRadio:
543
                    if (_autoConnectSettings->autoConnectSiKRadio()->rawValue().toBool()) {
544
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
Don Gagne's avatar
Don Gagne committed
545 546
                    }
                    break;
547
                case QGCSerialPortInfo::BoardTypeOpenPilot:
548
                    if (_autoConnectSettings->autoConnectLibrePilot()->rawValue().toBool()) {
549
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
550 551
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
552 553
#ifndef __mobile__
                case QGCSerialPortInfo::BoardTypeRTKGPS:
554
                    if (_autoConnectSettings->autoConnectRTKGPS()->rawValue().toBool() && !_toolbox->gpsManager()->connected()) {
Don Gagne's avatar
Don Gagne committed
555 556 557 558 559
                        qCDebug(LinkManagerLog) << "RTK GPS auto-connected";
                        _toolbox->gpsManager()->connectGPS(portInfo.systemLocation());
                    }
                    break;
#endif
Don Gagne's avatar
Don Gagne committed
560 561
                default:
                    qWarning() << "Internal error";
Don Gagne's avatar
Don Gagne committed
562
                    continue;
dogmaphobic's avatar
dogmaphobic committed
563
                }
Don Gagne's avatar
Don Gagne committed
564

Don Gagne's avatar
Don Gagne committed
565 566
                if (pSerialConfig) {
                    qCDebug(LinkManagerLog) << "New auto-connect port added: " << pSerialConfig->name() << portInfo.systemLocation();
567
                    pSerialConfig->setBaud(boardType == QGCSerialPortInfo::BoardTypeSiKRadio ? 57600 : 115200);
Don Gagne's avatar
Don Gagne committed
568 569
                    pSerialConfig->setDynamic(true);
                    pSerialConfig->setPortName(portInfo.systemLocation());
570 571
                    _sharedAutoconnectConfigurations.append(SharedLinkConfigurationPointer(pSerialConfig));
                    createConnectedLink(_sharedAutoconnectConfigurations.last());
Don Gagne's avatar
Don Gagne committed
572
                }
dogmaphobic's avatar
dogmaphobic committed
573 574 575
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
576

577 578 579 580 581 582 583
#ifndef __android__
    // Android builds only support a single serial connection. Repeatedly calling availablePorts after that one serial
    // port is connected leaks file handles due to a bug somewhere in android serial code. In order to work around that
    // bug after we connect the first serial port we stop probing for additional ports. The means we must rely on
    // the port disconnecting itself when the radio is pulled to signal communication list as opposed to automatically
    // closing the Link.

dogmaphobic's avatar
dogmaphobic committed
584 585
    // Now we go through the current configuration list and make sure any dynamic config has gone away
    QList<LinkConfiguration*>  _confToDelete;
586 587 588 589 590 591 592
    for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
        SerialConfiguration* serialConfig = qobject_cast<SerialConfiguration*>(_sharedAutoconnectConfigurations[i].data());
        if (serialConfig) {
            if (!currentPorts.contains(serialConfig->portName())) {
                if (serialConfig->link()) {
                    if (serialConfig->link()->isConnected()) {
                        if (serialConfig->link()->active()) {
593 594 595 596 597 598
                            // 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
599
                }
600
                _confToDelete.append(serialConfig);
dogmaphobic's avatar
dogmaphobic committed
601
            }
Don Gagne's avatar
Don Gagne committed
602 603
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
604 605
        }
    }
Don Gagne's avatar
Don Gagne committed
606

Don Gagne's avatar
Don Gagne committed
607
    // Now remove all configs that are gone
Don Gagne's avatar
Don Gagne committed
608
    foreach (LinkConfiguration* pDeleteConfig, _confToDelete) {
Don Gagne's avatar
Don Gagne committed
609
        qCDebug(LinkManagerLog) << "Removing unused autoconnect config" << pDeleteConfig->name();
Don Gagne's avatar
Don Gagne committed
610 611 612
        if (pDeleteConfig->link()) {
            disconnectLink(pDeleteConfig->link());
        }
613 614 615 616 617 618
        for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
            if (_sharedAutoconnectConfigurations[i].data() == pDeleteConfig) {
                _sharedAutoconnectConfigurations.removeAt(i);
                break;
            }
        }
619
    }
620
#endif
Gus Grubba's avatar
Gus Grubba committed
621
#endif // NO_SERIAL_LINK
622 623
}

Don Gagne's avatar
Don Gagne committed
624 625 626
void LinkManager::shutdown(void)
{
    setConnectionsSuspended("Shutdown");
Don Gagne's avatar
Don Gagne committed
627
    disconnectAll();
Don Gagne's avatar
Don Gagne committed
628 629
}

630 631 632 633 634 635
QStringList LinkManager::linkTypeStrings(void) const
{
    //-- Must follow same order as enum LinkType in LinkConfiguration.h
    static QStringList list;
    if(!list.size())
    {
Gus Grubba's avatar
Gus Grubba committed
636
#ifndef NO_SERIAL_LINK
637 638 639 640
        list += "Serial";
#endif
        list += "UDP";
        list += "TCP";
dogmaphobic's avatar
dogmaphobic committed
641
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
642 643
        list += "Bluetooth";
#endif
dogmaphobic's avatar
dogmaphobic committed
644
#ifdef QT_DEBUG
645
        list += "Mock Link";
dogmaphobic's avatar
dogmaphobic committed
646 647
#endif
#ifndef __mobile__
648
        list += "Log Replay";
dogmaphobic's avatar
dogmaphobic committed
649
#endif
dogmaphobic's avatar
dogmaphobic committed
650
        Q_ASSERT(list.size() == (int)LinkConfiguration::TypeLast);
651 652 653 654
    }
    return list;
}

655
void LinkManager::_updateSerialPorts()
656
{
657 658
    _commPortList.clear();
    _commPortDisplayList.clear();
Gus Grubba's avatar
Gus Grubba committed
659
#ifndef NO_SERIAL_LINK
660 661
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
    foreach (const QSerialPortInfo &info, portList)
662
    {
663 664 665
        QString port = info.systemLocation().trimmed();
        _commPortList += port;
        _commPortDisplayList += SerialConfiguration::cleanPortDisplayname(port);
666 667
    }
#endif
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
}

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

QStringList LinkManager::serialPorts(void)
{
    if(!_commPortList.size())
    {
        _updateSerialPorts();
    }
685 686 687 688 689
    return _commPortList;
}

QStringList LinkManager::serialBaudRates(void)
{
Gus Grubba's avatar
Gus Grubba committed
690
#ifdef NO_SERIAL_LINK
691 692 693 694 695 696
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715

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);
716
    addConfiguration(config);
717 718 719 720 721 722
    saveLinkConfigurationList();
    return true;
}

LinkConfiguration* LinkManager::createConfiguration(int type, const QString& name)
{
Gus Grubba's avatar
Gus Grubba committed
723
#ifndef NO_SERIAL_LINK
724 725
    if((LinkConfiguration::LinkType)type == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
726
#endif
727 728 729 730 731 732
    return LinkConfiguration::createSettings(type, name);
}

LinkConfiguration* LinkManager::startConfigurationEditing(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
Gus Grubba's avatar
Gus Grubba committed
733
#ifndef NO_SERIAL_LINK
734 735
    if(config->type() == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
736
#endif
737 738 739 740 741 742 743 744 745 746
    return LinkConfiguration::duplicateSettings(config);
}


void LinkManager::_fixUnnamed(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
    //-- Check for "Unnamed"
    if (config->name() == "Unnamed") {
        switch(config->type()) {
Gus Grubba's avatar
Gus Grubba committed
747
#ifndef NO_SERIAL_LINK
748 749
            case LinkConfiguration::TypeSerial: {
                QString tname = dynamic_cast<SerialConfiguration*>(config)->portName();
750
#ifdef Q_OS_WIN
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
                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
772
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
773 774 775
            case LinkConfiguration::TypeBluetooth: {
                    BluetoothConfiguration* tconfig = dynamic_cast<BluetoothConfiguration*>(config);
                    if(tconfig) {
776
                        config->setName(QString("%1 (Bluetooth Device)").arg(tconfig->device().name));
dogmaphobic's avatar
dogmaphobic committed
777 778 779 780
                    }
                }
                break;
#endif
dogmaphobic's avatar
dogmaphobic committed
781
#ifndef __mobile__
782
            case LinkConfiguration::TypeLogReplay: {
dogmaphobic's avatar
dogmaphobic committed
783 784 785 786
                    LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
                    if(tconfig) {
                        config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
                    }
787 788
                }
                break;
dogmaphobic's avatar
dogmaphobic committed
789
#endif
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
#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);
    }
810 811

    _removeConfiguration(config);
812 813
    saveLinkConfigurationList();
}
814

815 816
bool LinkManager::isAutoconnectLink(LinkInterface* link)
{
817 818 819 820 821 822
    for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
        if (_sharedAutoconnectConfigurations[i].data() == link->getLinkConfiguration()) {
            return true;
        }
    }
    return false;
823
}
dogmaphobic's avatar
dogmaphobic committed
824 825 826 827 828

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

Gus Grubba's avatar
Gus Grubba committed
830
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
831 832
void LinkManager::_activeLinkCheck(void)
{
833
    SerialLink* link = NULL;
Don Gagne's avatar
Don Gagne committed
834 835 836
    bool found = false;

    if (_activeLinkCheckList.count() != 0) {
837
        link = _activeLinkCheckList.takeFirst();
838
        if (containsLink(link) && link->isConnected()) {
Don Gagne's avatar
Don Gagne committed
839 840 841 842 843 844 845 846 847
            // 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;
                }
            }
848 849
        } else {
            link = NULL;
Don Gagne's avatar
Don Gagne committed
850 851 852 853 854 855 856
        }
    }

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

857 858 859
    if (!found && link) {
        // See if we can get an NSH prompt on this link
        bool foundNSHPrompt = false;
860
        link->writeBytesSafe("\r", 1);
861 862 863 864 865 866 867 868 869
        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 ?
870 871
                                  tr("Please check to make sure you have an SD Card inserted in your Vehicle and try again.") :
                                  tr("Your Vehicle is not responding. If this continues, shutdown %1, restart the Vehicle letting it boot completely, then start %1.").arg(qgcApp()->applicationName()));
Don Gagne's avatar
Don Gagne committed
872 873
    }
}
Don Gagne's avatar
Don Gagne committed
874
#endif
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

bool LinkManager::containsLink(LinkInterface* link)
{
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            return true;
        }
    }
    return false;
}

SharedLinkConfigurationPointer LinkManager::addConfiguration(LinkConfiguration* config)
{
    _qmlConfigurations.append(config);
    _sharedConfigurations.append(SharedLinkConfigurationPointer(config));
    return _sharedConfigurations.last();
}

void LinkManager::_removeConfiguration(LinkConfiguration* config)
{
    _qmlConfigurations.removeOne(config);

    for (int i=0; i<_sharedConfigurations.count(); i++) {
        if (_sharedConfigurations[i].data() == config) {
            _sharedConfigurations.removeAt(i);
            return;
        }
    }

    qWarning() << "LinkManager::_removeConfiguration called with unknown config";
}

QList<LinkInterface*> LinkManager::links(void)
{
    QList<LinkInterface*> rawLinks;

    for (int i=0; i<_sharedLinks.count(); i++) {
        rawLinks.append(_sharedLinks[i].data());
    }

    return rawLinks;
}
917 918 919 920 921 922 923 924 925 926 927

void LinkManager::startAutoConnectedLinks(void)
{
    SharedLinkConfigurationPointer conf;

    for(int i = 0; i < _sharedConfigurations.count(); i++) {
        conf = _sharedConfigurations[i];
        if (conf->isAutoConnect())
            createConnectedLink(conf);
    }
}