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

Don Gagne's avatar
Don Gagne committed
34
QGC_LOGGING_CATEGORY(LinkManagerLog, "LinkManagerLog")
Don Gagne's avatar
Don Gagne committed
35 36
QGC_LOGGING_CATEGORY(LinkManagerVerboseLog, "LinkManagerVerboseLog")

37
const char* LinkManager::_defaultUDPLinkName =       "UDP Link (AutoConnect)";
38
const char* LinkManager::_mavlinkForwardingLinkName =       "MAVLink Forwarding Link";
39

40 41 42 43 44 45 46 47
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

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

LinkManager::~LinkManager()
{
75
#ifndef __mobile__
76
#ifndef NO_SERIAL_LINK
77
    delete _nmeaPort;
78
#endif
79
#endif
pixhawk's avatar
pixhawk committed
80 81
}

82 83
void LinkManager::setToolbox(QGCToolbox *toolbox)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
84
    QGCTool::setToolbox(toolbox);
85

DonLakeFlyer's avatar
DonLakeFlyer committed
86 87
    _autoConnectSettings = toolbox->settingsManager()->autoConnectSettings();
    _mavlinkProtocol = _toolbox->mavlinkProtocol();
88

89
    connect(_mavlinkProtocol, &MAVLinkProtocol::messageReceived, this, &LinkManager::_mavlinkMessageReceived);
90

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

94 95
}

Don Gagne's avatar
Don Gagne committed
96 97 98 99 100 101 102 103 104 105
// 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);
    }
}

106
LinkInterface* LinkManager::createConnectedLink(SharedLinkConfigurationPointer& config, bool isPX4Flow)
107
{
108
    if (!config) {
109 110
        qWarning() << "LinkManager::createConnectedLink called with nullptr config";
        return nullptr;
111 112
    }

113
    LinkInterface* pLink = nullptr;
114
    switch(config->type()) {
Gus Grubba's avatar
Gus Grubba committed
115
#ifndef NO_SERIAL_LINK
DonLakeFlyer's avatar
DonLakeFlyer committed
116 117
    case LinkConfiguration::TypeSerial:
    {
118
        auto* serialConfig = qobject_cast<SerialConfiguration*>(config.data());
DonLakeFlyer's avatar
DonLakeFlyer committed
119
        if (serialConfig) {
120
            pLink = new SerialLink(config, isPX4Flow);
DonLakeFlyer's avatar
DonLakeFlyer committed
121
            if (serialConfig->usbDirect()) {
122
                _activeLinkCheckList.append(qobject_cast<SerialLink*>(pLink));
DonLakeFlyer's avatar
DonLakeFlyer committed
123 124
                if (!_activeLinkCheckTimer.isActive()) {
                    _activeLinkCheckTimer.start();
Don Gagne's avatar
Don Gagne committed
125 126 127
                }
            }
        }
DonLakeFlyer's avatar
DonLakeFlyer committed
128
    }
Don Gagne's avatar
Don Gagne committed
129
        break;
DonLakeFlyer's avatar
DonLakeFlyer committed
130 131
#else
    Q_UNUSED(isPX4Flow)
dogmaphobic's avatar
dogmaphobic committed
132
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
133 134 135 136 137 138
    case LinkConfiguration::TypeUdp:
        pLink = new UDPLink(config);
        break;
    case LinkConfiguration::TypeTcp:
        pLink = new TCPLink(config);
        break;
dogmaphobic's avatar
dogmaphobic committed
139
#ifdef QGC_ENABLE_BLUETOOTH
DonLakeFlyer's avatar
DonLakeFlyer committed
140 141 142
    case LinkConfiguration::TypeBluetooth:
        pLink = new BluetoothLink(config);
        break;
dogmaphobic's avatar
dogmaphobic committed
143
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
144 145 146
    case LinkConfiguration::TypeLogReplay:
        pLink = new LogReplayLink(config);
        break;
147
#ifdef QT_DEBUG
DonLakeFlyer's avatar
DonLakeFlyer committed
148 149 150
    case LinkConfiguration::TypeMock:
        pLink = new MockLink(config);
        break;
151
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
152 153
    case LinkConfiguration::TypeLast:
        break;
154
    }
155
    if (pLink) {
156 157
        _addLink(pLink);
        connectLink(pLink);
158 159 160 161
    }
    return pLink;
}

Don Gagne's avatar
Don Gagne committed
162
LinkInterface* LinkManager::createConnectedLink(const QString& name)
163
{
DonLakeFlyer's avatar
DonLakeFlyer committed
164 165 166 167 168 169 170 171 172
    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);
            }
        }
173
    }
174
    return nullptr;
175 176
}

177 178 179 180 181 182 183 184 185 186 187 188 189
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;
}

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

Don Gagne's avatar
Don Gagne committed
197 198 199
    if (!link) {
        return;
    }
200

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

210
        _sharedLinks.append(SharedLinkInterfacePointer(link));
211 212
        emit newLink(link);
    }
213

Don Gagne's avatar
Don Gagne committed
214 215
    connect(link, &LinkInterface::communicationError,   _app,               &QGCApplication::criticalMessageBoxOnMainThread);
    connect(link, &LinkInterface::bytesReceived,        _mavlinkProtocol,   &MAVLinkProtocol::receiveBytes);
216
    connect(link, &LinkInterface::bytesSent,            _mavlinkProtocol,   &MAVLinkProtocol::logSentBytes);
217

218
    _mavlinkProtocol->resetMetadataForLink(link);
219
    _mavlinkProtocol->setVersion(_mavlinkProtocol->getCurrentVersion());
220

221 222 223 224 225 226
    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);
227
}
pixhawk's avatar
pixhawk committed
228

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

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

Don Gagne's avatar
Don Gagne committed
250
void LinkManager::disconnectLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
251
{
252
    if (!link || !containsLink(link)) {
253 254
        return;
    }
Don Gagne's avatar
Don Gagne committed
255

Don Gagne's avatar
Don Gagne committed
256
    link->_disconnect();
257

Don Gagne's avatar
Don Gagne committed
258
    LinkConfiguration* config = link->getLinkConfiguration();
259 260 261 262 263
    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;
264
        }
265
    }
266

Don Gagne's avatar
Don Gagne committed
267
    _deleteLink(link);
pixhawk's avatar
pixhawk committed
268 269
}

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

    if (!link) {
        return;
    }
280

281
    // Free up the mavlink channel associated with this link
282
    _freeMavlinkChannel(link->mavlinkChannel());
283

284 285 286 287 288 289
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            _sharedLinks.removeAt(i);
            break;
        }
    }
290

Don Gagne's avatar
Don Gagne committed
291
    // Emit removal of link
292
    emit linkDeleted(link);
pixhawk's avatar
pixhawk committed
293 294
}

295 296 297 298 299 300 301 302
SharedLinkInterfacePointer LinkManager::sharedLinkInterfacePointerForLink(LinkInterface* link)
{
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            return _sharedLinks[i];
        }
    }

303 304
    qWarning() << "LinkManager::sharedLinkInterfaceForLink returning nullptr";
    return SharedLinkInterfacePointer(nullptr);
305 306
}

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

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

325 326 327 328 329 330 331 332 333
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

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

335 336 337 338 339 340
void LinkManager::_linkConnectionRemoved(LinkInterface* link)
{
    // Link has been removed from system, disconnect it automatically
    disconnectLink(link);
}

341 342 343 344 345 346 347 348 349
void LinkManager::suspendConfigurationUpdates(bool suspend)
{
    _configUpdateSuspended = suspend;
}

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

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

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

    if(linksChanged) {
446
        emit linkConfigurationsChanged();
447 448
    }
    // Enable automatic Serial PX4/3DR Radio hunting
449 450 451
    _configurationsLoaded = true;
}

Gus Grubba's avatar
Gus Grubba committed
452
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
453
SerialConfiguration* LinkManager::_autoconnectConfigurationsContainsPort(const QString& portName)
454 455
{
    QString searchPort = portName.trimmed();
Don Gagne's avatar
Don Gagne committed
456

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

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

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

    // 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);
515
        udpConfig->setTransmitOnly(true);
516 517 518 519 520 521 522 523 524

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

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

525
#ifndef __mobile__
526
#ifndef NO_SERIAL_LINK
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    // 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
547
#endif
Don Gagne's avatar
Don Gagne committed
548

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

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

577 578
        QGCSerialPortInfo::BoardType_t boardType;
        QString boardName;
Don Gagne's avatar
Don Gagne committed
579

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

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

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

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

722
#endif
Gus Grubba's avatar
Gus Grubba committed
723
#endif // NO_SERIAL_LINK
724 725
}

Don Gagne's avatar
Don Gagne committed
726 727
void LinkManager::shutdown(void)
{
728
    setConnectionsSuspended(tr("Shutdown"));
Don Gagne's avatar
Don Gagne committed
729
    disconnectAll();
Don Gagne's avatar
Don Gagne committed
730 731
}

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

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

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

QStringList LinkManager::serialPorts(void)
{
    if(!_commPortList.size())
    {
        _updateSerialPorts();
    }
789 790 791 792 793
    return _commPortList;
}

QStringList LinkManager::serialBaudRates(void)
{
Gus Grubba's avatar
Gus Grubba committed
794
#ifdef NO_SERIAL_LINK
795 796 797 798 799 800
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
801 802 803

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

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

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

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

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

void LinkManager::removeConfiguration(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
917 918 919 920 921
    if (config) {
        LinkInterface* iface = config->link();
        if(iface) {
            disconnectLink(iface);
        }
922

DonLakeFlyer's avatar
DonLakeFlyer committed
923 924 925 926 927
        _removeConfiguration(config);
        saveLinkConfigurationList();
    } else {
        qWarning() << "Internal error";
    }
928
}
929

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

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

Gus Grubba's avatar
Gus Grubba committed
945
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
946 947
void LinkManager::_activeLinkCheck(void)
{
948
    SerialLink* link = nullptr;
Don Gagne's avatar
Don Gagne committed
949 950
    bool found = false;
    if (_activeLinkCheckList.count() != 0) {
951
        link = _activeLinkCheckList.takeFirst();
952
        if (containsLink(link) && link->isConnected()) {
Don Gagne's avatar
Don Gagne committed
953 954 955 956 957 958 959 960 961
            // 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;
                }
            }
962
        } else {
963
            link = nullptr;
Don Gagne's avatar
Don Gagne committed
964 965 966 967 968
        }
    }
    if (_activeLinkCheckList.count() == 0) {
        _activeLinkCheckTimer.stop();
    }
969 970 971
    if (!found && link) {
        // See if we can get an NSH prompt on this link
        bool foundNSHPrompt = false;
972
        link->writeBytesThreadSafe("\r", 1);
973 974 975
        QSignalSpy spy(link, SIGNAL(bytesReceived(LinkInterface*, QByteArray)));
        if (spy.wait(100)) {
            QList<QVariant> arguments = spy.takeFirst();
976
            if (arguments[1].toByteArray().contains("nsh>")) {
977 978 979
                foundNSHPrompt = true;
            }
        }
980
        qgcApp()->showAppMessage(
981 982 983
            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
984 985
    }
}
Don Gagne's avatar
Don Gagne committed
986
#endif
987 988 989 990 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

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;
}
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

void LinkManager::startAutoConnectedLinks(void)
{
    SharedLinkConfigurationPointer conf;
    for(int i = 0; i < _sharedConfigurations.count(); i++) {
        conf = _sharedConfigurations[i];
        if (conf->isAutoConnect())
            createConnectedLink(conf);
    }
}
1035 1036 1037 1038

int LinkManager::_reserveMavlinkChannel(void)
{
    // Find a mavlink channel to use for this link, Channel 0 is reserved for internal use.
1039
    for (uint8_t mavlinkChannel = 1; mavlinkChannel < MAVLINK_COMM_NUM_BUFFERS; mavlinkChannel++) {
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
        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);
}
1056

1057 1058
void LinkManager::_mavlinkMessageReceived(LinkInterface* link, mavlink_message_t message) {
    link->startMavlinkMessagesTimer(message.sysid);
1059
}
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

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));
}