LinkManager.cc 38.8 KB
Newer Older
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8
 *
 * 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"
24
#include "LogReplayLink.h"
dogmaphobic's avatar
dogmaphobic committed
25
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
26 27
#include "BluetoothLink.h"
#endif
28

Don Gagne's avatar
Don Gagne committed
29
#ifndef __mobile__
DonLakeFlyer's avatar
DonLakeFlyer committed
30
#include "GPSManager.h"
31
#include "PositionManager.h"
Don Gagne's avatar
Don Gagne committed
32 33
#endif

34 35 36 37
#ifdef QT_DEBUG
#include "MockLink.h"
#endif

Don Gagne's avatar
Don Gagne committed
38
QGC_LOGGING_CATEGORY(LinkManagerLog, "LinkManagerLog")
Don Gagne's avatar
Don Gagne committed
39 40
QGC_LOGGING_CATEGORY(LinkManagerVerboseLog, "LinkManagerVerboseLog")

41
const char* LinkManager::_defaultUDPLinkName =       "UDP Link (AutoConnect)";
42
const char* LinkManager::_mavlinkForwardingLinkName =       "MAVLink Forwarding Link";
43

44 45 46 47 48 49 50 51
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

52 53
LinkManager::LinkManager(QGCApplication* app, QGCToolbox* toolbox)
    : QGCTool(app, toolbox)
54 55 56
    , _configUpdateSuspended(false)
    , _configurationsLoaded(false)
    , _connectionsSuspended(false)
57
    , _mavlinkChannelsUsedBitMask(1)    // We never use channel 0 to avoid sequence numbering problems
58 59
    , _autoConnectSettings(nullptr)
    , _mavlinkProtocol(nullptr)
60
#ifndef __mobile__
61
#ifndef NO_SERIAL_LINK
62
    , _nmeaPort(nullptr)
63
#endif
64
#endif
pixhawk's avatar
pixhawk committed
65
{
Don Gagne's avatar
Don Gagne committed
66 67 68 69
    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
70
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
71 72 73
    _activeLinkCheckTimer.setInterval(_activeLinkCheckTimeoutMSecs);
    _activeLinkCheckTimer.setSingleShot(false);
    connect(&_activeLinkCheckTimer, &QTimer::timeout, this, &LinkManager::_activeLinkCheck);
Don Gagne's avatar
Don Gagne committed
74
#endif
pixhawk's avatar
pixhawk committed
75 76 77 78
}

LinkManager::~LinkManager()
{
79
#ifndef __mobile__
80
#ifndef NO_SERIAL_LINK
81
    delete _nmeaPort;
82
#endif
83
#endif
pixhawk's avatar
pixhawk committed
84 85
}

86 87
void LinkManager::setToolbox(QGCToolbox *toolbox)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
88
    QGCTool::setToolbox(toolbox);
89

DonLakeFlyer's avatar
DonLakeFlyer committed
90 91
    _autoConnectSettings = toolbox->settingsManager()->autoConnectSettings();
    _mavlinkProtocol = _toolbox->mavlinkProtocol();
92

93
    connect(_mavlinkProtocol, &MAVLinkProtocol::messageReceived, this, &LinkManager::_mavlinkMessageReceived);
94

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

98 99
}

Don Gagne's avatar
Don Gagne committed
100 101 102 103 104 105 106 107 108 109
// 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);
    }
}

110
LinkInterface* LinkManager::createConnectedLink(SharedLinkConfigurationPointer& config, bool isPX4Flow)
111
{
112
    if (!config) {
113 114
        qWarning() << "LinkManager::createConnectedLink called with nullptr config";
        return nullptr;
115 116
    }

117
    LinkInterface* pLink = nullptr;
118
    switch(config->type()) {
Gus Grubba's avatar
Gus Grubba committed
119
#ifndef NO_SERIAL_LINK
DonLakeFlyer's avatar
DonLakeFlyer committed
120 121
    case LinkConfiguration::TypeSerial:
    {
122
        auto* serialConfig = qobject_cast<SerialConfiguration*>(config.data());
DonLakeFlyer's avatar
DonLakeFlyer committed
123
        if (serialConfig) {
124
            pLink = new SerialLink(config, isPX4Flow);
DonLakeFlyer's avatar
DonLakeFlyer committed
125
            if (serialConfig->usbDirect()) {
126
                _activeLinkCheckList.append(qobject_cast<SerialLink*>(pLink));
DonLakeFlyer's avatar
DonLakeFlyer committed
127 128
                if (!_activeLinkCheckTimer.isActive()) {
                    _activeLinkCheckTimer.start();
Don Gagne's avatar
Don Gagne committed
129 130 131
                }
            }
        }
DonLakeFlyer's avatar
DonLakeFlyer committed
132
    }
Don Gagne's avatar
Don Gagne committed
133
        break;
DonLakeFlyer's avatar
DonLakeFlyer committed
134 135
#else
    Q_UNUSED(isPX4Flow)
dogmaphobic's avatar
dogmaphobic committed
136
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
137 138 139 140 141 142
    case LinkConfiguration::TypeUdp:
        pLink = new UDPLink(config);
        break;
    case LinkConfiguration::TypeTcp:
        pLink = new TCPLink(config);
        break;
dogmaphobic's avatar
dogmaphobic committed
143
#ifdef QGC_ENABLE_BLUETOOTH
DonLakeFlyer's avatar
DonLakeFlyer committed
144 145 146
    case LinkConfiguration::TypeBluetooth:
        pLink = new BluetoothLink(config);
        break;
dogmaphobic's avatar
dogmaphobic committed
147
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
148 149 150
    case LinkConfiguration::TypeLogReplay:
        pLink = new LogReplayLink(config);
        break;
151
#ifdef QT_DEBUG
DonLakeFlyer's avatar
DonLakeFlyer committed
152 153 154
    case LinkConfiguration::TypeMock:
        pLink = new MockLink(config);
        break;
155
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
156 157
    case LinkConfiguration::TypeLast:
        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
{
DonLakeFlyer's avatar
DonLakeFlyer committed
168 169 170 171 172 173 174 175 176
    if (name.isEmpty()) {
        qWarning() << "Internal error";
    } else {
        for(int i = 0; i < _sharedConfigurations.count(); i++) {
            SharedLinkConfigurationPointer& conf = _sharedConfigurations[i];
            if (conf->name() == name) {
                return createConnectedLink(conf);
            }
        }
177
    }
178
    return nullptr;
179 180
}

181 182 183 184 185 186 187 188 189 190 191 192 193
SharedLinkInterfacePointer LinkManager::mavlinkForwardingLink()
{
    for (int i = 0; i < _sharedLinks.count(); i++) {
        LinkConfiguration* linkConfig = _sharedLinks[i]->getLinkConfiguration();
        if (linkConfig->type() == LinkConfiguration::TypeUdp && linkConfig->name() == _mavlinkForwardingLinkName) {
            SharedLinkInterfacePointer& link = _sharedLinks[i];
            return link;
        }
    }

    return nullptr;
}

194
void LinkManager::_addLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
195
{
Don Gagne's avatar
Don Gagne committed
196
    if (thread() != QThread::currentThread()) {
197
        qWarning() << "_addLink called from incorrect thread";
Don Gagne's avatar
Don Gagne committed
198 199
        return;
    }
200

Don Gagne's avatar
Don Gagne committed
201 202 203
    if (!link) {
        return;
    }
204

205
    if (!containsLink(link)) {
206 207 208 209
        int mavlinkChannel = _reserveMavlinkChannel();
        if (mavlinkChannel != 0) {
            link->_setMavlinkChannel(mavlinkChannel);
        } else {
210
            qWarning() << "Ran out of mavlink channels";
211
            return;
212 213
        }

214
        _sharedLinks.append(SharedLinkInterfacePointer(link));
215 216
        emit newLink(link);
    }
217

Don Gagne's avatar
Don Gagne committed
218 219
    connect(link, &LinkInterface::communicationError,   _app,               &QGCApplication::criticalMessageBoxOnMainThread);
    connect(link, &LinkInterface::bytesReceived,        _mavlinkProtocol,   &MAVLinkProtocol::receiveBytes);
220
    connect(link, &LinkInterface::bytesSent,            _mavlinkProtocol,   &MAVLinkProtocol::logSentBytes);
221

222
    _mavlinkProtocol->resetMetadataForLink(link);
223
    _mavlinkProtocol->setVersion(_mavlinkProtocol->getCurrentVersion());
224

225 226 227 228 229 230
    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);
231
}
pixhawk's avatar
pixhawk committed
232

Don Gagne's avatar
Don Gagne committed
233
void LinkManager::disconnectAll(void)
pixhawk's avatar
pixhawk committed
234
{
Don Gagne's avatar
Don Gagne committed
235
    // Walk list in reverse order to preserve indices during delete
236 237
    for (int i=_sharedLinks.count()-1; i>=0; i--) {
        disconnectLink(_sharedLinks[i].data());
238
    }
pixhawk's avatar
pixhawk committed
239 240 241 242
}

bool LinkManager::connectLink(LinkInterface* link)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
243 244 245 246 247 248 249
    if (link) {
        if (_connectionsSuspendedMsg()) {
            return false;
        }
        return link->_connect();
    } else {
        qWarning() << "Internal error";
250 251
        return false;
    }
pixhawk's avatar
pixhawk committed
252 253
}

Don Gagne's avatar
Don Gagne committed
254
void LinkManager::disconnectLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
255
{
256
    if (!link || !containsLink(link)) {
257 258
        return;
    }
Don Gagne's avatar
Don Gagne committed
259

Don Gagne's avatar
Don Gagne committed
260
    link->_disconnect();
261

Don Gagne's avatar
Don Gagne committed
262
    LinkConfiguration* config = link->getLinkConfiguration();
263 264 265 266 267
    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;
268
        }
269
    }
270

Don Gagne's avatar
Don Gagne committed
271
    _deleteLink(link);
pixhawk's avatar
pixhawk committed
272 273
}

274
void LinkManager::_deleteLink(LinkInterface* link)
275
{
Don Gagne's avatar
Don Gagne committed
276 277 278 279 280 281 282 283
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }

    if (!link) {
        return;
    }
284

285
    // Free up the mavlink channel associated with this link
286
    _freeMavlinkChannel(link->mavlinkChannel());
287

288 289 290 291 292 293
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            _sharedLinks.removeAt(i);
            break;
        }
    }
294

Don Gagne's avatar
Don Gagne committed
295
    // Emit removal of link
296
    emit linkDeleted(link);
pixhawk's avatar
pixhawk committed
297 298
}

299 300 301 302 303 304 305 306
SharedLinkInterfacePointer LinkManager::sharedLinkInterfacePointerForLink(LinkInterface* link)
{
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            return _sharedLinks[i];
        }
    }

307 308
    qWarning() << "LinkManager::sharedLinkInterfaceForLink returning nullptr";
    return SharedLinkInterfacePointer(nullptr);
309 310
}

311 312 313 314 315
/// @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) {
316
        qgcApp()->showAppMessage(tr("Connect not allowed: %1").arg(_connectionsSuspendedReason));
317 318 319 320 321 322 323 324 325 326 327
        return true;
    } else {
        return false;
    }
}

void LinkManager::setConnectionsSuspended(QString reason)
{
    _connectionsSuspended = true;
    _connectionsSuspendedReason = reason;
}
328

329 330 331 332 333 334 335 336 337
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

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

339 340 341 342 343 344
void LinkManager::_linkConnectionRemoved(LinkInterface* link)
{
    // Link has been removed from system, disconnect it automatically
    disconnectLink(link);
}

345 346 347 348 349 350 351 352 353
void LinkManager::suspendConfigurationUpdates(bool suspend)
{
    _configUpdateSuspended = suspend;
}

void LinkManager::saveLinkConfigurationList()
{
    QSettings settings;
    settings.remove(LinkConfiguration::settingsRoot());
354
    int trueCount = 0;
355 356
    for (int i = 0; i < _sharedConfigurations.count(); i++) {
        SharedLinkConfigurationPointer linkConfig = _sharedConfigurations[i];
Don Gagne's avatar
Don Gagne committed
357
        if (linkConfig) {
358
            if (!linkConfig->isDynamic()) {
Don Gagne's avatar
Don Gagne committed
359
                QString root = LinkConfiguration::settingsRoot();
360
                root += QString("/Link%1").arg(trueCount++);
Don Gagne's avatar
Don Gagne committed
361 362
                settings.setValue(root + "/name", linkConfig->name());
                settings.setValue(root + "/type", linkConfig->type());
363
                settings.setValue(root + "/auto", linkConfig->isAutoConnect());
364
                settings.setValue(root + "/high_latency", linkConfig->isHighLatency());
Don Gagne's avatar
Don Gagne committed
365 366 367 368
                // Have the instance save its own values
                linkConfig->saveSettings(settings, root);
            }
        } else {
369
            qWarning() << "Internal error for link configuration in LinkManager";
dogmaphobic's avatar
dogmaphobic committed
370
        }
371
    }
dogmaphobic's avatar
dogmaphobic committed
372
    QString root(LinkConfiguration::settingsRoot());
373 374
    settings.setValue(root + "/count", trueCount);
    emit linkConfigurationsChanged();
375 376 377 378
}

void LinkManager::loadLinkConfigurationList()
{
379
    bool linksChanged = false;
380 381 382 383 384 385 386 387 388
    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")) {
389 390
                LinkConfiguration::LinkType type = static_cast<LinkConfiguration::LinkType>(settings.value(root + "/type").toInt());
                if(type < LinkConfiguration::TypeLast) {
391 392 393
                    if(settings.contains(root + "/name")) {
                        QString name = settings.value(root + "/name").toString();
                        if(!name.isEmpty()) {
394
                            LinkConfiguration* pLink = nullptr;
395
                            bool autoConnect = settings.value(root + "/auto").toBool();
396
                            bool highLatency = settings.value(root + "/high_latency").toBool();
397

398
                            switch(type) {
Gus Grubba's avatar
Gus Grubba committed
399
#ifndef NO_SERIAL_LINK
DonLakeFlyer's avatar
DonLakeFlyer committed
400
                            case LinkConfiguration::TypeSerial:
401
                                pLink = new SerialConfiguration(name);
DonLakeFlyer's avatar
DonLakeFlyer committed
402
                                break;
dogmaphobic's avatar
dogmaphobic committed
403
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
404
                            case LinkConfiguration::TypeUdp:
405
                                pLink = new UDPConfiguration(name);
DonLakeFlyer's avatar
DonLakeFlyer committed
406 407
                                break;
                            case LinkConfiguration::TypeTcp:
408
                                pLink = new TCPConfiguration(name);
DonLakeFlyer's avatar
DonLakeFlyer committed
409
                                break;
dogmaphobic's avatar
dogmaphobic committed
410
#ifdef QGC_ENABLE_BLUETOOTH
DonLakeFlyer's avatar
DonLakeFlyer committed
411
                            case LinkConfiguration::TypeBluetooth:
412
                                pLink = new BluetoothConfiguration(name);
DonLakeFlyer's avatar
DonLakeFlyer committed
413
                                break;
dogmaphobic's avatar
dogmaphobic committed
414
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
415
                            case LinkConfiguration::TypeLogReplay:
416
                                pLink = new LogReplayLinkConfiguration(name);
DonLakeFlyer's avatar
DonLakeFlyer committed
417
                                break;
418
#ifdef QT_DEBUG
DonLakeFlyer's avatar
DonLakeFlyer committed
419
                            case LinkConfiguration::TypeMock:
420
                                pLink = new MockConfiguration(name);
421
                                break;
422
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
423 424
                            case LinkConfiguration::TypeLast:
                                break;
425 426
                            }
                            if(pLink) {
427 428
                                //-- Have the instance load its own values
                                pLink->setAutoConnect(autoConnect);
429
                                pLink->setHighLatency(highLatency);
430
                                pLink->loadSettings(settings, root);
431
                                addConfiguration(pLink);
432
                                linksChanged = true;
433 434
                            }
                        } else {
435
                            qWarning() << "Link Configuration" << root << "has an empty name." ;
436 437
                        }
                    } else {
438
                        qWarning() << "Link Configuration" << root << "has no name." ;
439 440
                    }
                } else {
441
                    qWarning() << "Link Configuration" << root << "an invalid type: " << type;
442 443
                }
            } else {
444
                qWarning() << "Link Configuration" << root << "has no type." ;
445 446 447
            }
        }
    }
448 449

    if(linksChanged) {
450
        emit linkConfigurationsChanged();
451 452
    }
    // Enable automatic Serial PX4/3DR Radio hunting
453 454 455
    _configurationsLoaded = true;
}

Gus Grubba's avatar
Gus Grubba committed
456
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
457
SerialConfiguration* LinkManager::_autoconnectConfigurationsContainsPort(const QString& portName)
458 459
{
    QString searchPort = portName.trimmed();
Don Gagne's avatar
Don Gagne committed
460

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

464 465 466
        if (serialConfig) {
            if (serialConfig->portName() == searchPort) {
                return serialConfig;
467
            }
Don Gagne's avatar
Don Gagne committed
468 469
        } else {
            qWarning() << "Internal error";
470 471
        }
    }
472
    return nullptr;
473
}
dogmaphobic's avatar
dogmaphobic committed
474
#endif
475

Don Gagne's avatar
Don Gagne committed
476
void LinkManager::_updateAutoConnectLinks(void)
477
{
Don Gagne's avatar
Don Gagne committed
478
    if (_connectionsSuspended || qgcApp()->runningUnitTests()) {
479 480
        return;
    }
Don Gagne's avatar
Don Gagne committed
481 482
    // Re-add UDP if we need to
    bool foundUDP = false;
483
    for (int i = 0; i < _sharedLinks.count(); i++) {
484
        LinkConfiguration* linkConfig = _sharedLinks[i]->getLinkConfiguration();
485
        if (linkConfig->type() == LinkConfiguration::TypeUdp && linkConfig->name() == _defaultUDPLinkName) {
Don Gagne's avatar
Don Gagne committed
486 487 488 489
            foundUDP = true;
            break;
        }
    }
490
    if (!foundUDP && _autoConnectSettings->autoConnectUDP()->rawValue().toBool()) {
Don Gagne's avatar
Don Gagne committed
491
        qCDebug(LinkManagerLog) << "New auto-connect UDP port added";
492
        //-- Default UDPConfiguration is set up for autoconnect
493
        UDPConfiguration* udpConfig = new UDPConfiguration(_defaultUDPLinkName);
DonLakeFlyer's avatar
DonLakeFlyer committed
494
        udpConfig->setDynamic(true);
495 496
        SharedLinkConfigurationPointer config = addConfiguration(udpConfig);
        createConnectedLink(config);
497
        emit linkConfigurationsChanged();
Don Gagne's avatar
Don Gagne committed
498
    }
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518

    // Connect MAVLink forwarding if it is enabled
    bool foundMAVLinkForwardingLink = false;
    for (int i = 0; i < _sharedLinks.count(); i++) {
        LinkConfiguration* linkConfig = _sharedLinks[i]->getLinkConfiguration();
        if (linkConfig->type() == LinkConfiguration::TypeUdp && linkConfig->name() == _mavlinkForwardingLinkName) {
            foundMAVLinkForwardingLink = true;
            // TODO: should we check if the host/port matches the mavlinkForwardHostName setting and update if it does not match?
            break;
        }
    }

    // Create the link if necessary
    bool forwardingEnabled = _toolbox->settingsManager()->appSettings()->forwardMavlink()->rawValue().toBool();
    if (!foundMAVLinkForwardingLink && forwardingEnabled) {

        qCDebug(LinkManagerLog) << "New MAVLink forwarding port added";

        UDPConfiguration* udpConfig = new UDPConfiguration(_mavlinkForwardingLinkName);
        udpConfig->setDynamic(true);
519
        udpConfig->setTransmitOnly(true);
520 521 522 523 524 525 526 527 528

        QString hostName = _toolbox->settingsManager()->appSettings()->forwardMavlinkHostName()->rawValue().toString();
        udpConfig->addHost(hostName);

        SharedLinkConfigurationPointer config = addConfiguration(udpConfig);
        createConnectedLink(config);
        emit linkConfigurationsChanged();
    }

529
#ifndef __mobile__
530
#ifndef NO_SERIAL_LINK
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    // check to see if nmea gps is configured for UDP input, if so, set it up to connect
    if (_autoConnectSettings->autoConnectNmeaPort()->cookedValueString() == "UDP Port") {
        if (_nmeaSocket.localPort() != _autoConnectSettings->nmeaUdpPort()->rawValue().toUInt()
                || _nmeaSocket.state() != UdpIODevice::BoundState) {
            qCDebug(LinkManagerLog) << "Changing port for UDP NMEA stream";
            _nmeaSocket.close();
            _nmeaSocket.bind(QHostAddress::AnyIPv4, _autoConnectSettings->nmeaUdpPort()->rawValue().toUInt());
            _toolbox->qgcPositionManager()->setNmeaSourceDevice(&_nmeaSocket);
        }
        //close serial port
        if (_nmeaPort) {
            _nmeaPort->close();
            delete _nmeaPort;
            _nmeaPort = nullptr;
            _nmeaDeviceName = "";
        }
    } else {
        _nmeaSocket.close();
    }
#endif
551
#endif
Don Gagne's avatar
Don Gagne committed
552

Gus Grubba's avatar
Gus Grubba committed
553
#ifndef NO_SERIAL_LINK
dogmaphobic's avatar
dogmaphobic committed
554
    QStringList currentPorts;
555 556 557 558 559
    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.
560
    if (!_sharedAutoconnectConfigurations.count()) {
561 562
        portList = QGCSerialPortInfo::availablePorts();
    }
563 564
#else
    portList = QGCSerialPortInfo::availablePorts();
565
#endif
Don Gagne's avatar
Don Gagne committed
566

567
    // Iterate Comm Ports
568
    for (const QGCSerialPortInfo& portInfo: portList) {
Don Gagne's avatar
Don Gagne committed
569 570 571 572 573 574 575 576 577
        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
578 579
        // Save port name
        currentPorts << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
580

581 582
        QGCSerialPortInfo::BoardType_t boardType;
        QString boardName;
Don Gagne's avatar
Don Gagne committed
583

584
#ifndef NO_SERIAL_LINK
585
#ifndef __mobile__
586
        // check to see if nmea gps is configured for current Serial port, if so, set it up to connect
587 588 589 590 591 592
        if (portInfo.systemLocation().trimmed() == _autoConnectSettings->autoConnectNmeaPort()->cookedValueString()) {
            if (portInfo.systemLocation().trimmed() != _nmeaDeviceName) {
                _nmeaDeviceName = portInfo.systemLocation().trimmed();
                qCDebug(LinkManagerLog) << "Configuring nmea port" << _nmeaDeviceName;
                QSerialPort* newPort = new QSerialPort(portInfo);
                _nmeaBaud = _autoConnectSettings->autoConnectNmeaBaud()->cookedValue().toUInt();
593
                newPort->setBaudRate(static_cast<qint32>(_nmeaBaud));
594 595 596 597 598 599 600 601 602
                qCDebug(LinkManagerLog) << "Configuring nmea baudrate" << _nmeaBaud;
                // This will stop polling old device if previously set
                _toolbox->qgcPositionManager()->setNmeaSourceDevice(newPort);
                if (_nmeaPort) {
                    delete _nmeaPort;
                }
                _nmeaPort = newPort;
            } else if (_autoConnectSettings->autoConnectNmeaBaud()->cookedValue().toUInt() != _nmeaBaud) {
                _nmeaBaud = _autoConnectSettings->autoConnectNmeaBaud()->cookedValue().toUInt();
603
                _nmeaPort->setBaudRate(static_cast<qint32>(_nmeaBaud));
604 605
                qCDebug(LinkManagerLog) << "Configuring nmea baudrate" << _nmeaBaud;
            }
606
        } else
607
#endif
608 609
#endif
        if (portInfo.getBoardInfo(boardType, boardName)) {
Don Gagne's avatar
Don Gagne committed
610 611
            if (portInfo.isBootloader()) {
                // Don't connect to bootloader
612
                qCDebug(LinkManagerLog) << "Waiting for bootloader to finish" << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
613 614
                continue;
            }
615
            if (_autoconnectConfigurationsContainsPort(portInfo.systemLocation()) || _autoConnectRTKPort == portInfo.systemLocation()) {
616 617 618 619 620 621
                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();
622 623
                _autoconnectWaitList[portInfo.systemLocation()] = 1;
            } else if (++_autoconnectWaitList[portInfo.systemLocation()] * _autoconnectUpdateTimerMSecs > _autoconnectConnectDelayMSecs) {
624
                SerialConfiguration* pSerialConfig = nullptr;
625
                _autoconnectWaitList.remove(portInfo.systemLocation());
Don Gagne's avatar
Don Gagne committed
626
                switch (boardType) {
627
                case QGCSerialPortInfo::BoardTypePixhawk:
628
                    if (_autoConnectSettings->autoConnectPixhawk()->rawValue().toBool()) {
629
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
630 631 632
                        pSerialConfig->setUsbDirect(true);
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
633
                case QGCSerialPortInfo::BoardTypePX4Flow:
634
                    if (_autoConnectSettings->autoConnectPX4Flow()->rawValue().toBool()) {
635
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
Don Gagne's avatar
Don Gagne committed
636
                    }
Don Gagne's avatar
Don Gagne committed
637
                    break;
638
                case QGCSerialPortInfo::BoardTypeSiKRadio:
639
                    if (_autoConnectSettings->autoConnectSiKRadio()->rawValue().toBool()) {
640
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
Don Gagne's avatar
Don Gagne committed
641 642
                    }
                    break;
643
                case QGCSerialPortInfo::BoardTypeOpenPilot:
644
                    if (_autoConnectSettings->autoConnectLibrePilot()->rawValue().toBool()) {
645
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
646 647
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
648 649
#ifndef __mobile__
                case QGCSerialPortInfo::BoardTypeRTKGPS:
650
                    if (_autoConnectSettings->autoConnectRTKGPS()->rawValue().toBool() && !_toolbox->gpsManager()->connected()) {
651 652
                        qCDebug(LinkManagerLog) << "RTK GPS auto-connected" << portInfo.portName().trimmed();
                        _autoConnectRTKPort = portInfo.systemLocation();
653
                        _toolbox->gpsManager()->connectGPS(portInfo.systemLocation(), boardName);
Don Gagne's avatar
Don Gagne committed
654 655 656
                    }
                    break;
#endif
Don Gagne's avatar
Don Gagne committed
657 658
                default:
                    qWarning() << "Internal error";
Don Gagne's avatar
Don Gagne committed
659
                    continue;
dogmaphobic's avatar
dogmaphobic committed
660
                }
Don Gagne's avatar
Don Gagne committed
661 662
                if (pSerialConfig) {
                    qCDebug(LinkManagerLog) << "New auto-connect port added: " << pSerialConfig->name() << portInfo.systemLocation();
663
                    pSerialConfig->setBaud(boardType == QGCSerialPortInfo::BoardTypeSiKRadio ? 57600 : 115200);
Don Gagne's avatar
Don Gagne committed
664 665
                    pSerialConfig->setDynamic(true);
                    pSerialConfig->setPortName(portInfo.systemLocation());
666
                    _sharedAutoconnectConfigurations.append(SharedLinkConfigurationPointer(pSerialConfig));
667
                    createConnectedLink(_sharedAutoconnectConfigurations.last(), boardType == QGCSerialPortInfo::BoardTypePX4Flow);
Don Gagne's avatar
Don Gagne committed
668
                }
dogmaphobic's avatar
dogmaphobic committed
669 670 671
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
672

673 674 675
#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
676
    // bug after we connect the first serial port we stop probing for additional ports. That means we must rely on
677 678 679
    // 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
680 681
    // Now we go through the current configuration list and make sure any dynamic config has gone away
    QList<LinkConfiguration*>  _confToDelete;
682 683 684 685 686 687 688
    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()) {
689 690 691 692 693 694
                            // 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
695
                }
696
                _confToDelete.append(serialConfig);
dogmaphobic's avatar
dogmaphobic committed
697
            }
Don Gagne's avatar
Don Gagne committed
698 699
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
700 701
        }
    }
Don Gagne's avatar
Don Gagne committed
702

Don Gagne's avatar
Don Gagne committed
703
    // Now remove all configs that are gone
704
    for (LinkConfiguration* pDeleteConfig: _confToDelete) {
Don Gagne's avatar
Don Gagne committed
705
        qCDebug(LinkManagerLog) << "Removing unused autoconnect config" << pDeleteConfig->name();
Don Gagne's avatar
Don Gagne committed
706 707 708
        if (pDeleteConfig->link()) {
            disconnectLink(pDeleteConfig->link());
        }
709 710 711 712 713 714
        for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
            if (_sharedAutoconnectConfigurations[i].data() == pDeleteConfig) {
                _sharedAutoconnectConfigurations.removeAt(i);
                break;
            }
        }
715
    }
716 717

    // Check for RTK GPS connection gone
718
#if !defined(__mobile__)
719 720 721 722 723
    if (!_autoConnectRTKPort.isEmpty() && !currentPorts.contains(_autoConnectRTKPort)) {
        qCDebug(LinkManagerLog) << "RTK GPS disconnected" << _autoConnectRTKPort;
        _toolbox->gpsManager()->disconnectGPS();
        _autoConnectRTKPort.clear();
    }
724
#endif
725

726
#endif
Gus Grubba's avatar
Gus Grubba committed
727
#endif // NO_SERIAL_LINK
728 729
}

Don Gagne's avatar
Don Gagne committed
730 731
void LinkManager::shutdown(void)
{
732
    setConnectionsSuspended(tr("Shutdown"));
Don Gagne's avatar
Don Gagne committed
733
    disconnectAll();
Don Gagne's avatar
Don Gagne committed
734 735
}

736 737 738 739 740 741
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
742
#ifndef NO_SERIAL_LINK
743 744 745 746
        list += tr("Serial");
#endif
        list += tr("UDP");
        list += tr("TCP");
dogmaphobic's avatar
dogmaphobic committed
747
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
748 749
        list += "Bluetooth";
#endif
dogmaphobic's avatar
dogmaphobic committed
750
#ifdef QT_DEBUG
751
        list += tr("Mock Link");
dogmaphobic's avatar
dogmaphobic committed
752 753
#endif
#ifndef __mobile__
754
        list += tr("Log Replay");
dogmaphobic's avatar
dogmaphobic committed
755
#endif
756
        if (list.size() != static_cast<int>(LinkConfiguration::TypeLast)) {
DonLakeFlyer's avatar
DonLakeFlyer committed
757 758
            qWarning() << "Internal error";
        }
759 760 761 762
    }
    return list;
}

763
void LinkManager::_updateSerialPorts()
764
{
765 766
    _commPortList.clear();
    _commPortDisplayList.clear();
Gus Grubba's avatar
Gus Grubba committed
767
#ifndef NO_SERIAL_LINK
768
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
769
    for (const QSerialPortInfo &info: portList)
770
    {
771 772 773
        QString port = info.systemLocation().trimmed();
        _commPortList += port;
        _commPortDisplayList += SerialConfiguration::cleanPortDisplayname(port);
774 775
    }
#endif
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
}

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

QStringList LinkManager::serialPorts(void)
{
    if(!_commPortList.size())
    {
        _updateSerialPorts();
    }
793 794 795 796 797
    return _commPortList;
}

QStringList LinkManager::serialBaudRates(void)
{
Gus Grubba's avatar
Gus Grubba committed
798
#ifdef NO_SERIAL_LINK
799 800 801 802 803 804
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
805 806 807

bool LinkManager::endConfigurationEditing(LinkConfiguration* config, LinkConfiguration* editedConfig)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
808 809 810 811 812 813
    if (config && editedConfig) {
        _fixUnnamed(editedConfig);
        config->copyFrom(editedConfig);
        saveLinkConfigurationList();
        // Tell link about changes (if any)
        config->updateSettings();
814
        emit config->nameChanged(config->name());
DonLakeFlyer's avatar
DonLakeFlyer committed
815 816 817 818 819
        // Discard temporary duplicate
        delete editedConfig;
    } else {
        qWarning() << "Internal error";
    }
820 821 822 823 824
    return true;
}

bool LinkManager::endCreateConfiguration(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
825 826 827 828 829 830 831
    if (config) {
        _fixUnnamed(config);
        addConfiguration(config);
        saveLinkConfigurationList();
    } else {
        qWarning() << "Internal error";
    }
832 833 834 835 836
    return true;
}

LinkConfiguration* LinkManager::createConfiguration(int type, const QString& name)
{
Gus Grubba's avatar
Gus Grubba committed
837
#ifndef NO_SERIAL_LINK
838
    if(static_cast<LinkConfiguration::LinkType>(type) == LinkConfiguration::TypeSerial)
839
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
840
#endif
841 842 843 844 845
    return LinkConfiguration::createSettings(type, name);
}

LinkConfiguration* LinkManager::startConfigurationEditing(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
846
    if (config) {
Gus Grubba's avatar
Gus Grubba committed
847
#ifndef NO_SERIAL_LINK
DonLakeFlyer's avatar
DonLakeFlyer committed
848 849
        if(config->type() == LinkConfiguration::TypeSerial)
            _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
850
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
851 852 853
        return LinkConfiguration::duplicateSettings(config);
    } else {
        qWarning() << "Internal error";
854
        return nullptr;
DonLakeFlyer's avatar
DonLakeFlyer committed
855
    }
856 857 858 859
}

void LinkManager::_fixUnnamed(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
860 861 862 863
    if (config) {
        //-- Check for "Unnamed"
        if (config->name() == "Unnamed") {
            switch(config->type()) {
Gus Grubba's avatar
Gus Grubba committed
864
#ifndef NO_SERIAL_LINK
865 866
            case LinkConfiguration::TypeSerial: {
                QString tname = dynamic_cast<SerialConfiguration*>(config)->portName();
867
#ifdef Q_OS_WIN
868 869 870 871 872 873 874
                tname.replace("\\\\.\\", "");
#else
                tname.replace("/dev/cu.", "");
                tname.replace("/dev/", "");
#endif
                config->setName(QString("Serial Device on %1").arg(tname));
                break;
DonLakeFlyer's avatar
DonLakeFlyer committed
875
            }
876 877 878
#endif
            case LinkConfiguration::TypeUdp:
                config->setName(
879
                    QString("UDP Link on Port %1").arg(dynamic_cast<UDPConfiguration*>(config)->localPort()));
880 881
                break;
            case LinkConfiguration::TypeTcp: {
DonLakeFlyer's avatar
DonLakeFlyer committed
882 883 884
                TCPConfiguration* tconfig = dynamic_cast<TCPConfiguration*>(config);
                if(tconfig) {
                    config->setName(
885
                        QString("TCP Link %1:%2").arg(tconfig->address().toString()).arg(static_cast<int>(tconfig->port())));
886
                }
DonLakeFlyer's avatar
DonLakeFlyer committed
887
            }
888
                break;
dogmaphobic's avatar
dogmaphobic committed
889
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
890
            case LinkConfiguration::TypeBluetooth: {
DonLakeFlyer's avatar
DonLakeFlyer committed
891 892 893
                BluetoothConfiguration* tconfig = dynamic_cast<BluetoothConfiguration*>(config);
                if(tconfig) {
                    config->setName(QString("%1 (Bluetooth Device)").arg(tconfig->device().name));
dogmaphobic's avatar
dogmaphobic committed
894
                }
DonLakeFlyer's avatar
DonLakeFlyer committed
895
            }
dogmaphobic's avatar
dogmaphobic committed
896 897
                break;
#endif
898
            case LinkConfiguration::TypeLogReplay: {
DonLakeFlyer's avatar
DonLakeFlyer committed
899 900 901
                LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
                if(tconfig) {
                    config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
902
                }
DonLakeFlyer's avatar
DonLakeFlyer committed
903
            }
904 905 906
                break;
#ifdef QT_DEBUG
            case LinkConfiguration::TypeMock:
907
                config->setName(QString("Mock Link"));
908 909 910 911
                break;
#endif
            case LinkConfiguration::TypeLast:
                break;
DonLakeFlyer's avatar
DonLakeFlyer committed
912
            }
913
        }
DonLakeFlyer's avatar
DonLakeFlyer committed
914 915
    } else {
        qWarning() << "Internal error";
916 917 918 919 920
    }
}

void LinkManager::removeConfiguration(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
921 922 923 924 925
    if (config) {
        LinkInterface* iface = config->link();
        if(iface) {
            disconnectLink(iface);
        }
926

DonLakeFlyer's avatar
DonLakeFlyer committed
927 928 929 930 931
        _removeConfiguration(config);
        saveLinkConfigurationList();
    } else {
        qWarning() << "Internal error";
    }
932
}
933

934 935
bool LinkManager::isAutoconnectLink(LinkInterface* link)
{
936 937 938 939 940 941
    for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
        if (_sharedAutoconnectConfigurations[i].data() == link->getLinkConfiguration()) {
            return true;
        }
    }
    return false;
942
}
dogmaphobic's avatar
dogmaphobic committed
943 944 945 946 947

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

Gus Grubba's avatar
Gus Grubba committed
949
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
950 951
void LinkManager::_activeLinkCheck(void)
{
952
    SerialLink* link = nullptr;
Don Gagne's avatar
Don Gagne committed
953 954
    bool found = false;
    if (_activeLinkCheckList.count() != 0) {
955
        link = _activeLinkCheckList.takeFirst();
956
        if (containsLink(link) && link->isConnected()) {
Don Gagne's avatar
Don Gagne committed
957 958 959 960 961 962 963 964 965
            // 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;
                }
            }
966
        } else {
967
            link = nullptr;
Don Gagne's avatar
Don Gagne committed
968 969 970 971 972
        }
    }
    if (_activeLinkCheckList.count() == 0) {
        _activeLinkCheckTimer.stop();
    }
973 974 975
    if (!found && link) {
        // See if we can get an NSH prompt on this link
        bool foundNSHPrompt = false;
976
        link->writeBytesThreadSafe("\r", 1);
977 978 979
        QSignalSpy spy(link, SIGNAL(bytesReceived(LinkInterface*, QByteArray)));
        if (spy.wait(100)) {
            QList<QVariant> arguments = spy.takeFirst();
980
            if (arguments[1].toByteArray().contains("nsh>")) {
981 982 983
                foundNSHPrompt = true;
            }
        }
984
        qgcApp()->showAppMessage(
985 986 987
            foundNSHPrompt ?
                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
988 989
    }
}
Don Gagne's avatar
Don Gagne committed
990
#endif
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

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;
}
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

void LinkManager::startAutoConnectedLinks(void)
{
    SharedLinkConfigurationPointer conf;
    for(int i = 0; i < _sharedConfigurations.count(); i++) {
        conf = _sharedConfigurations[i];
        if (conf->isAutoConnect())
            createConnectedLink(conf);
    }
}
1039 1040 1041 1042

int LinkManager::_reserveMavlinkChannel(void)
{
    // Find a mavlink channel to use for this link, Channel 0 is reserved for internal use.
1043
    for (uint8_t mavlinkChannel = 1; mavlinkChannel < MAVLINK_COMM_NUM_BUFFERS; mavlinkChannel++) {
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
        if (!(_mavlinkChannelsUsedBitMask & 1 << mavlinkChannel)) {
            mavlink_reset_channel_status(mavlinkChannel);
            // Start the channel on Mav 1 protocol
            mavlink_status_t* mavlinkStatus = mavlink_get_channel_status(mavlinkChannel);
            mavlinkStatus->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1;
            _mavlinkChannelsUsedBitMask |= 1 << mavlinkChannel;
            return mavlinkChannel;
        }
    }
    return 0;   // All channels reserved
}

void LinkManager::_freeMavlinkChannel(int channel)
{
    _mavlinkChannelsUsedBitMask &= ~(1 << channel);
}
1060

1061 1062
void LinkManager::_mavlinkMessageReceived(LinkInterface* link, mavlink_message_t message) {
    link->startMavlinkMessagesTimer(message.sysid);
1063
}
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073

LogReplayLink* LinkManager::startLogReplay(const QString& logFile)
{
    LogReplayLinkConfiguration* linkConfig = new LogReplayLinkConfiguration(tr("Log Replay"));
    linkConfig->setLogFilename(logFile);
    linkConfig->setName(linkConfig->logFilenameShort());

    SharedLinkConfigurationPointer sharedConfig = addConfiguration(linkConfig);
    return qobject_cast<LogReplayLink*>(createConnectedLink(sharedConfig));
}