LinkManager.cc 30.5 KB
Newer Older
pixhawk's avatar
pixhawk committed
1
/*=====================================================================
lm's avatar
lm committed
2 3 4

QGroundControl Open Source Ground Control Station

5
(c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
lm's avatar
lm committed
6 7 8 9

This file is part of the QGROUNDCONTROL project

    QGROUNDCONTROL is free software: you can redistribute it and/or modify
pixhawk's avatar
pixhawk committed
10 11 12
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
lm's avatar
lm committed
13 14

    QGROUNDCONTROL is distributed in the hope that it will be useful,
pixhawk's avatar
pixhawk committed
15 16 17
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
lm's avatar
lm committed
18

pixhawk's avatar
pixhawk committed
19
    You should have received a copy of the GNU General Public License
lm's avatar
lm committed
20 21
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

pixhawk's avatar
pixhawk committed
22
======================================================================*/
23

pixhawk's avatar
pixhawk committed
24 25 26 27 28 29 30 31 32 33
/**
 * @file
 *   @brief Brief Description
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QList>
#include <QApplication>
34
#include <QDebug>
35
#include <QSignalSpy>
dogmaphobic's avatar
dogmaphobic committed
36 37

#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
38
#include "QGCSerialPortInfo.h"
dogmaphobic's avatar
dogmaphobic committed
39
#endif
40

41
#include "LinkManager.h"
42
#include "QGCApplication.h"
Don Gagne's avatar
Don Gagne committed
43 44
#include "UDPLink.h"
#include "TCPLink.h"
dogmaphobic's avatar
dogmaphobic committed
45
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
46 47
#include "BluetoothLink.h"
#endif
48

Don Gagne's avatar
Don Gagne committed
49
QGC_LOGGING_CATEGORY(LinkManagerLog, "LinkManagerLog")
Don Gagne's avatar
Don Gagne committed
50 51 52 53 54 55 56
QGC_LOGGING_CATEGORY(LinkManagerVerboseLog, "LinkManagerVerboseLog")

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";
Don Gagne's avatar
Don Gagne committed
57
const char* LinkManager::_defaultUPDLinkName =      "Default UDP Link";
58

59 60 61 62 63 64 65 66
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

67 68
LinkManager::LinkManager(QGCApplication* app)
    : QGCTool(app)
69 70 71
    , _configUpdateSuspended(false)
    , _configurationsLoaded(false)
    , _connectionsSuspended(false)
72
    , _mavlinkChannelsUsedBitMask(0)
73
    , _mavlinkProtocol(NULL)
Don Gagne's avatar
Don Gagne committed
74 75 76 77 78
    , _autoconnectUDP(true)
    , _autoconnectPixhawk(true)
    , _autoconnect3DRRadio(true)
    , _autoconnectPX4Flow(true)

pixhawk's avatar
pixhawk committed
79
{
Don Gagne's avatar
Don Gagne committed
80 81 82 83 84
    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;
85

Don Gagne's avatar
Don Gagne committed
86 87 88 89 90
    settings.beginGroup(_settingsGroup);
    _autoconnectUDP =       settings.value(_autoconnectUDPKey, true).toBool();
    _autoconnectPixhawk =   settings.value(_autoconnectPixhawkKey, true).toBool();
    _autoconnect3DRRadio =  settings.value(_autoconnect3DRRadioKey, true).toBool();
    _autoconnectPX4Flow =   settings.value(_autoconnectPX4FlowKey, true).toBool();
Don Gagne's avatar
Don Gagne committed
91 92 93 94

    _activeLinkCheckTimer.setInterval(_activeLinkCheckTimeoutMSecs);
    _activeLinkCheckTimer.setSingleShot(false);
    connect(&_activeLinkCheckTimer, &QTimer::timeout, this, &LinkManager::_activeLinkCheck);
pixhawk's avatar
pixhawk committed
95 96 97 98
}

LinkManager::~LinkManager()
{
99

pixhawk's avatar
pixhawk committed
100 101
}

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

   _mavlinkProtocol = _toolbox->mavlinkProtocol();

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

111 112
}

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

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

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

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

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

191 192
        // Find a mavlink channel to use for this link
        for (int i=0; i<32; i++) {
193
            if (!(_mavlinkChannelsUsedBitMask & 1 << i)) {
194
                mavlink_reset_channel_status(i);
195 196
                link->_setMavlinkChannel(i);
                _mavlinkChannelsUsedBitMask |= i << 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
    connect(link, &LinkInterface::connected,    this, &LinkManager::_linkConnected);
216
    connect(link, &LinkInterface::disconnected, this, &LinkManager::_linkDisconnected);
217
}
pixhawk's avatar
pixhawk committed
218

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

bool LinkManager::connectLink(LinkInterface* link)
{
229
    Q_ASSERT(link);
230

231 232 233 234
    if (_connectionsSuspendedMsg()) {
        return false;
    }

235
    return link->_connect();
pixhawk's avatar
pixhawk committed
236 237
}

Don Gagne's avatar
Don Gagne committed
238
void LinkManager::disconnectLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
239
{
240
    Q_ASSERT(link);
Don Gagne's avatar
Don Gagne committed
241

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

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

    if (!link) {
        return;
    }
267

268 269
    // Free up the mavlink channel associated with this link
    _mavlinkChannelsUsedBitMask &= ~(1 << link->getMavlinkChannel());
270

Don Gagne's avatar
Don Gagne committed
271 272
    _links.removeOne(link);
    delete link;
273

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

278 279 280 281 282
/// @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) {
283
        qgcApp()->showMessage(QString("Connect not allowed: %1").arg(_connectionsSuspendedReason));
284 285 286 287 288 289 290 291 292 293 294 295
        return true;
    } else {
        return false;
    }
}

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

297 298 299 300 301 302 303 304 305
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

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

void LinkManager::suspendConfigurationUpdates(bool suspend)
{
    _configUpdateSuspended = suspend;
}

void LinkManager::saveLinkConfigurationList()
{
    QSettings settings;
    settings.remove(LinkConfiguration::settingsRoot());
316 317
    int trueCount = 0;
    for (int i = 0; i < _linkConfigurations.count(); i++) {
Don Gagne's avatar
Don Gagne committed
318 319 320 321 322
        LinkConfiguration* linkConfig = _linkConfigurations.value<LinkConfiguration*>(i);
        if (linkConfig) {
            if(!linkConfig->isDynamic())
            {
                QString root = LinkConfiguration::settingsRoot();
323
                root += QString("/Link%1").arg(trueCount++);
Don Gagne's avatar
Don Gagne committed
324 325
                settings.setValue(root + "/name", linkConfig->name());
                settings.setValue(root + "/type", linkConfig->type());
326
                settings.setValue(root + "/auto", linkConfig->isAutoConnect());
Don Gagne's avatar
Don Gagne committed
327 328 329 330 331
                // Have the instance save its own values
                linkConfig->saveSettings(settings, root);
            }
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
332
        }
333
    }
dogmaphobic's avatar
dogmaphobic committed
334
    QString root(LinkConfiguration::settingsRoot());
335 336
    settings.setValue(root + "/count", trueCount);
    emit linkConfigurationsChanged();
337 338 339 340
}

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

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

dogmaphobic's avatar
dogmaphobic committed
432
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
433
SerialConfiguration* LinkManager::_autoconnectConfigurationsContainsPort(const QString& portName)
434 435
{
    QString searchPort = portName.trimmed();
Don Gagne's avatar
Don Gagne committed
436 437 438 439 440 441 442

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

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

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

Don Gagne's avatar
Don Gagne committed
458 459 460 461 462 463 464 465 466
    // 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
467
    if (!foundUDP && _autoconnectUDP) {
Don Gagne's avatar
Don Gagne committed
468
        qCDebug(LinkManagerLog) << "New auto-connect UDP port added";
Don Gagne's avatar
Don Gagne committed
469 470 471
        UDPConfiguration* udpConfig = new UDPConfiguration(_defaultUPDLinkName);
        udpConfig->setLocalPort(QGC_UDP_LOCAL_PORT);
        udpConfig->setDynamic(true);
472
        _linkConfigurations.append(udpConfig);
Don Gagne's avatar
Don Gagne committed
473
        createConnectedLink(udpConfig);
474
        emit linkConfigurationsChanged();
Don Gagne's avatar
Don Gagne committed
475 476
    }

477
#ifndef __ios__
dogmaphobic's avatar
dogmaphobic committed
478
    QStringList currentPorts;
Don Gagne's avatar
Don Gagne committed
479
    QList<QGCSerialPortInfo> portList = QGCSerialPortInfo::availablePorts();
Don Gagne's avatar
Don Gagne committed
480

481
    // Iterate Comm Ports
Don Gagne's avatar
Don Gagne committed
482
    foreach (QGCSerialPortInfo portInfo, portList) {
Don Gagne's avatar
Don Gagne committed
483 484 485 486 487 488 489 490 491
        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
492 493
        // Save port name
        currentPorts << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
494 495 496 497 498 499

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

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

504 505 506 507 508 509 510
            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();
511 512
                _autoconnectWaitList[portInfo.systemLocation()] = 1;
            } else if (++_autoconnectWaitList[portInfo.systemLocation()] * _autoconnectUpdateTimerMSecs > _autoconnectConnectDelayMSecs) {
Don Gagne's avatar
Don Gagne committed
513 514
                SerialConfiguration* pSerialConfig = NULL;

515
                _autoconnectWaitList.remove(portInfo.systemLocation());
516

Don Gagne's avatar
Don Gagne committed
517 518 519
                switch (boardType) {
                case QGCSerialPortInfo::BoardTypePX4FMUV1:
                case QGCSerialPortInfo::BoardTypePX4FMUV2:
520
                case QGCSerialPortInfo::BoardTypePX4FMUV4:
Don Gagne's avatar
Don Gagne committed
521 522
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("Pixhawk on %1").arg(portInfo.portName().trimmed()));
523
                        pSerialConfig->setUsbDirect(true);
Don Gagne's avatar
Don Gagne committed
524
                    }
Don Gagne's avatar
Don Gagne committed
525 526
                    break;
                case QGCSerialPortInfo::BoardTypeAeroCore:
Don Gagne's avatar
Don Gagne committed
527 528
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("AeroCore on %1").arg(portInfo.portName().trimmed()));
529
                        pSerialConfig->setUsbDirect(true);
Don Gagne's avatar
Don Gagne committed
530
                    }
Don Gagne's avatar
Don Gagne committed
531 532
                    break;
                case QGCSerialPortInfo::BoardTypePX4Flow:
Don Gagne's avatar
Don Gagne committed
533 534 535
                    if (_autoconnectPX4Flow) {
                        pSerialConfig = new SerialConfiguration(QString("PX4Flow on %1").arg(portInfo.portName().trimmed()));
                    }
Don Gagne's avatar
Don Gagne committed
536 537
                    break;
                case QGCSerialPortInfo::BoardType3drRadio:
Don Gagne's avatar
Don Gagne committed
538 539 540 541
                    if (_autoconnect3DRRadio) {
                        pSerialConfig = new SerialConfiguration(QString("3DR Radio on %1").arg(portInfo.portName().trimmed()));
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
542 543
                default:
                    qWarning() << "Internal error";
Don Gagne's avatar
Don Gagne committed
544
                    continue;
dogmaphobic's avatar
dogmaphobic committed
545
                }
Don Gagne's avatar
Don Gagne committed
546

Don Gagne's avatar
Don Gagne committed
547 548 549 550 551 552
                if (pSerialConfig) {
                    qCDebug(LinkManagerLog) << "New auto-connect port added: " << pSerialConfig->name() << portInfo.systemLocation();
                    pSerialConfig->setBaud(boardType == QGCSerialPortInfo::BoardType3drRadio ? 57600 : 115200);
                    pSerialConfig->setDynamic(true);
                    pSerialConfig->setPortName(portInfo.systemLocation());
                    _autoconnectConfigurations.append(pSerialConfig);
Don Gagne's avatar
Don Gagne committed
553
                    createConnectedLink(pSerialConfig);
Don Gagne's avatar
Don Gagne committed
554
                }
dogmaphobic's avatar
dogmaphobic committed
555 556 557
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
558

dogmaphobic's avatar
dogmaphobic committed
559 560
    // 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
561 562 563 564
    for (int i=0; i<_autoconnectConfigurations.count(); i++) {
        SerialConfiguration* linkConfig = _autoconnectConfigurations.value<SerialConfiguration*>(i);
        if (linkConfig) {
            if (!currentPorts.contains(linkConfig->portName())) {
565 566 567 568 569 570 571 572 573
                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
574
                }
575
                _confToDelete.append(linkConfig);
dogmaphobic's avatar
dogmaphobic committed
576
            }
Don Gagne's avatar
Don Gagne committed
577 578
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
579 580
        }
    }
Don Gagne's avatar
Don Gagne committed
581

Don Gagne's avatar
Don Gagne committed
582
    // Now remove all configs that are gone
Don Gagne's avatar
Don Gagne committed
583
    foreach (LinkConfiguration* pDeleteConfig, _confToDelete) {
Don Gagne's avatar
Don Gagne committed
584
        qCDebug(LinkManagerLog) << "Removing unused autoconnect config" << pDeleteConfig->name();
Don Gagne's avatar
Don Gagne committed
585
        _autoconnectConfigurations.removeOne(pDeleteConfig);
586 587 588
        if (pDeleteConfig->link()) {
            disconnectLink(pDeleteConfig->link());
        }
Don Gagne's avatar
Don Gagne committed
589
        delete pDeleteConfig;
590
    }
591
#endif // __ios__
592 593
}

Don Gagne's avatar
Don Gagne committed
594 595 596
void LinkManager::shutdown(void)
{
    setConnectionsSuspended("Shutdown");
Don Gagne's avatar
Don Gagne committed
597
    disconnectAll();
Don Gagne's avatar
Don Gagne committed
598 599 600 601 602 603 604 605 606 607 608 609
}

void LinkManager::setAutoconnectUDP(bool autoconnect)
{
    if (_autoconnectUDP != autoconnect) {
        QSettings settings;

        settings.beginGroup(_settingsGroup);
        settings.setValue(_autoconnectUDPKey, autoconnect);

        _autoconnectUDP = autoconnect;
        emit autoconnectUDPChanged(autoconnect);
610
    }
Don Gagne's avatar
Don Gagne committed
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
}

void LinkManager::setAutoconnectPixhawk(bool autoconnect)
{
    if (_autoconnectPixhawk != autoconnect) {
        QSettings settings;

        settings.beginGroup(_settingsGroup);
        settings.setValue(_autoconnectPixhawkKey, autoconnect);

        _autoconnectPixhawk = autoconnect;
        emit autoconnectPixhawkChanged(autoconnect);
    }

}

void LinkManager::setAutoconnect3DRRadio(bool autoconnect)
{
    if (_autoconnect3DRRadio != autoconnect) {
        QSettings settings;

        settings.beginGroup(_settingsGroup);
        settings.setValue(_autoconnect3DRRadioKey, autoconnect);

        _autoconnect3DRRadio = autoconnect;
        emit autoconnect3DRRadioChanged(autoconnect);
    }

}

void LinkManager::setAutoconnectPX4Flow(bool autoconnect)
{
    if (_autoconnectPX4Flow != autoconnect) {
        QSettings settings;

        settings.beginGroup(_settingsGroup);
        settings.setValue(_autoconnectPX4FlowKey, autoconnect);

        _autoconnectPX4Flow = autoconnect;
        emit autoconnectPX4FlowChanged(autoconnect);
    }

653
}
654 655 656 657 658 659 660 661 662 663 664 665

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
666
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
667 668
        list += "Bluetooth";
#endif
dogmaphobic's avatar
dogmaphobic committed
669
#ifdef QT_DEBUG
670
        list += "Mock Link";
dogmaphobic's avatar
dogmaphobic committed
671 672
#endif
#ifndef __mobile__
673
        list += "Log Replay";
dogmaphobic's avatar
dogmaphobic committed
674
#endif
dogmaphobic's avatar
dogmaphobic committed
675
        Q_ASSERT(list.size() == (int)LinkConfiguration::TypeLast);
676 677 678 679
    }
    return list;
}

680
void LinkManager::_updateSerialPorts()
681
{
682 683
    _commPortList.clear();
    _commPortDisplayList.clear();
684
#ifndef __ios__
685 686
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
    foreach (const QSerialPortInfo &info, portList)
687
    {
688 689 690
        QString port = info.systemLocation().trimmed();
        _commPortList += port;
        _commPortDisplayList += SerialConfiguration::cleanPortDisplayname(port);
691 692
    }
#endif
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
}

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

QStringList LinkManager::serialPorts(void)
{
    if(!_commPortList.size())
    {
        _updateSerialPorts();
    }
710 711 712 713 714 715 716 717 718 719 720 721
    return _commPortList;
}

QStringList LinkManager::serialBaudRates(void)
{
#ifdef __ios__
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747

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
748
#ifndef __ios__
749 750
    if((LinkConfiguration::LinkType)type == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
751
#endif
752 753 754 755 756 757
    return LinkConfiguration::createSettings(type, name);
}

LinkConfiguration* LinkManager::startConfigurationEditing(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
dogmaphobic's avatar
dogmaphobic committed
758
#ifndef __ios__
759 760
    if(config->type() == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
761
#endif
762 763 764 765 766 767 768 769 770 771 772 773 774
    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();
775
#ifdef Q_OS_WIN
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
                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
797
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
798 799 800
            case LinkConfiguration::TypeBluetooth: {
                    BluetoothConfiguration* tconfig = dynamic_cast<BluetoothConfiguration*>(config);
                    if(tconfig) {
801
                        config->setName(QString("%1 (Bluetooth Device)").arg(tconfig->device().name));
dogmaphobic's avatar
dogmaphobic committed
802 803 804 805
                    }
                }
                break;
#endif
dogmaphobic's avatar
dogmaphobic committed
806
#ifndef __mobile__
807
            case LinkConfiguration::TypeLogReplay: {
dogmaphobic's avatar
dogmaphobic committed
808 809 810 811
                    LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
                    if(tconfig) {
                        config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
                    }
812 813
                }
                break;
dogmaphobic's avatar
dogmaphobic committed
814
#endif
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
#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();
}
841

842 843 844 845
bool LinkManager::isAutoconnectLink(LinkInterface* link)
{
    return _autoconnectConfigurations.contains(link->getLinkConfiguration());
}
dogmaphobic's avatar
dogmaphobic committed
846 847 848 849 850

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

void LinkManager::_activeLinkCheck(void)
{
854
    SerialLink* link = NULL;
Don Gagne's avatar
Don Gagne committed
855 856 857
    bool found = false;

    if (_activeLinkCheckList.count() != 0) {
858
        link = _activeLinkCheckList.takeFirst();
Don Gagne's avatar
Don Gagne committed
859 860 861 862 863 864 865 866 867 868
        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;
                }
            }
869 870
        } else {
            link = NULL;
Don Gagne's avatar
Don Gagne committed
871 872 873 874 875 876 877
        }
    }

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

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    if (!found && link) {
        // See if we can get an NSH prompt on this link
        bool foundNSHPrompt = false;
        link->writeBytes("\r", 1);
        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
893 894
    }
}