LinkManager.cc 33 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 195
                // Start the channel on Mav 1 protocol
                mavlink_get_channel_status(i)->flags = mavlink_get_channel_status(i)->flags | MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
Don Gagne's avatar
Don Gagne committed
196
                _mavlinkChannelsUsedBitMask |= 1 << i;
197
                channelSet = true;
198 199 200
                break;
            }
        }
201

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

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

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

213
    _mavlinkProtocol->resetMetadataForLink(link);
214

215 216 217 218 219 220
    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);
221
}
pixhawk's avatar
pixhawk committed
222

Don Gagne's avatar
Don Gagne committed
223
void LinkManager::disconnectAll(void)
pixhawk's avatar
pixhawk committed
224
{
Don Gagne's avatar
Don Gagne committed
225 226
    // 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
227
        disconnectLink(_links.value<LinkInterface*>(i));
228
    }
pixhawk's avatar
pixhawk committed
229 230 231 232
}

bool LinkManager::connectLink(LinkInterface* link)
{
233
    Q_ASSERT(link);
234

235 236 237 238
    if (_connectionsSuspendedMsg()) {
        return false;
    }

239
    return link->_connect();
pixhawk's avatar
pixhawk committed
240 241
}

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

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

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

    if (!link) {
        return;
    }
273

274
    // Free up the mavlink channel associated with this link
275
    _mavlinkChannelsUsedBitMask &= ~(1 << link->mavlinkChannel());
276

Don Gagne's avatar
Don Gagne committed
277 278
    _links.removeOne(link);
    delete link;
279

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

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

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

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

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

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

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

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

void LinkManager::loadLinkConfigurationList()
{
353
    bool linksChanged = false;
354
#ifdef QT_DEBUG
355
    bool mockPresent  = false;
356
#endif
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) {
dogmaphobic's avatar
dogmaphobic committed
374
#ifndef __ios__
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
                                case LinkConfiguration::TypeMock:
                                    pLink = (LinkConfiguration*)new MockConfiguration(name);
398
                                    mockPresent = true;
399
                                    break;
400
#endif
401 402 403
                                default:
                                case LinkConfiguration::TypeLast:
                                    break;
404 405
                            }
                            if(pLink) {
406 407
                                //-- Have the instance load its own values
                                pLink->setAutoConnect(autoConnect);
408
                                pLink->loadSettings(settings, root);
Don Gagne's avatar
Don Gagne committed
409
                                _linkConfigurations.append(pLink);
410
                                linksChanged = true;
411 412
                            }
                        } else {
413
                            qWarning() << "Link Configuration" << root << "has an empty name." ;
414 415
                        }
                    } else {
416
                        qWarning() << "Link Configuration" << root << "has no name." ;
417 418
                    }
                } else {
419
                    qWarning() << "Link Configuration" << root << "an invalid type: " << type;
420 421
                }
            } else {
422
                qWarning() << "Link Configuration" << root << "has no type." ;
423 424 425
            }
        }
    }
426
    // Debug buids always add MockLink automatically (if one is not already there)
427
#ifdef QT_DEBUG
428 429 430 431 432 433 434
    if(!mockPresent)
    {
        MockConfiguration* pMock = new MockConfiguration("Mock Link PX4");
        pMock->setDynamic(true);
        _linkConfigurations.append(pMock);
        linksChanged = true;
    }
435
#endif
436 437

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

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

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

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

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

Don Gagne's avatar
Don Gagne committed
470 471 472 473 474 475 476 477 478
    // 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
479
    if (!foundUDP && _autoconnectUDP) {
Don Gagne's avatar
Don Gagne committed
480
        qCDebug(LinkManagerLog) << "New auto-connect UDP port added";
Don Gagne's avatar
Don Gagne committed
481 482 483
        UDPConfiguration* udpConfig = new UDPConfiguration(_defaultUPDLinkName);
        udpConfig->setLocalPort(QGC_UDP_LOCAL_PORT);
        udpConfig->setDynamic(true);
484
        _linkConfigurations.append(udpConfig);
Don Gagne's avatar
Don Gagne committed
485
        createConnectedLink(udpConfig);
486
        emit linkConfigurationsChanged();
Don Gagne's avatar
Don Gagne committed
487 488
    }

489
#ifndef __ios__
dogmaphobic's avatar
dogmaphobic committed
490
    QStringList currentPorts;
Don Gagne's avatar
Don Gagne committed
491
    QList<QGCSerialPortInfo> portList = QGCSerialPortInfo::availablePorts();
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 509 510 511

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

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

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

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

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

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

dogmaphobic's avatar
dogmaphobic committed
602 603
    // 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
604 605 606 607
    for (int i=0; i<_autoconnectConfigurations.count(); i++) {
        SerialConfiguration* linkConfig = _autoconnectConfigurations.value<SerialConfiguration*>(i);
        if (linkConfig) {
            if (!currentPorts.contains(linkConfig->portName())) {
608 609 610 611 612 613 614 615 616
                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
617
                }
618
                _confToDelete.append(linkConfig);
dogmaphobic's avatar
dogmaphobic committed
619
            }
Don Gagne's avatar
Don Gagne committed
620 621
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
622 623
        }
    }
Don Gagne's avatar
Don Gagne committed
624

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

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

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

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

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

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

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

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

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

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

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

699 700 701 702 703 704 705 706 707 708 709
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
710
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
711 712
        list += "Bluetooth";
#endif
dogmaphobic's avatar
dogmaphobic committed
713
#ifdef QT_DEBUG
714
        list += "Mock Link";
dogmaphobic's avatar
dogmaphobic committed
715 716
#endif
#ifndef __mobile__
717
        list += "Log Replay";
dogmaphobic's avatar
dogmaphobic committed
718
#endif
dogmaphobic's avatar
dogmaphobic committed
719
        Q_ASSERT(list.size() == (int)LinkConfiguration::TypeLast);
720 721 722 723
    }
    return list;
}

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

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

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

QStringList LinkManager::serialBaudRates(void)
{
#ifdef __ios__
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791

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
792
#ifndef __ios__
793 794
    if((LinkConfiguration::LinkType)type == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
795
#endif
796 797 798 799 800 801
    return LinkConfiguration::createSettings(type, name);
}

LinkConfiguration* LinkManager::startConfigurationEditing(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
dogmaphobic's avatar
dogmaphobic committed
802
#ifndef __ios__
803 804
    if(config->type() == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
805
#endif
806 807 808 809 810 811 812 813 814 815 816 817 818
    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();
819
#ifdef Q_OS_WIN
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
                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
841
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
842 843 844
            case LinkConfiguration::TypeBluetooth: {
                    BluetoothConfiguration* tconfig = dynamic_cast<BluetoothConfiguration*>(config);
                    if(tconfig) {
845
                        config->setName(QString("%1 (Bluetooth Device)").arg(tconfig->device().name));
dogmaphobic's avatar
dogmaphobic committed
846 847 848 849
                    }
                }
                break;
#endif
dogmaphobic's avatar
dogmaphobic committed
850
#ifndef __mobile__
851
            case LinkConfiguration::TypeLogReplay: {
dogmaphobic's avatar
dogmaphobic committed
852 853 854 855
                    LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
                    if(tconfig) {
                        config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
                    }
856 857
                }
                break;
dogmaphobic's avatar
dogmaphobic committed
858
#endif
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
#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();
}
885

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

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

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

    if (_activeLinkCheckList.count() != 0) {
903
        link = _activeLinkCheckList.takeFirst();
Don Gagne's avatar
Don Gagne committed
904 905 906 907 908 909 910 911 912 913
        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;
                }
            }
914 915
        } else {
            link = NULL;
Don Gagne's avatar
Don Gagne committed
916 917 918 919 920 921 922
        }
    }

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

923 924 925
    if (!found && link) {
        // See if we can get an NSH prompt on this link
        bool foundNSHPrompt = false;
926
        link->writeBytesSafe("\r", 1);
927 928 929 930 931 932 933 934 935 936 937
        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
938 939
    }
}
Don Gagne's avatar
Don Gagne committed
940
#endif