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

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 519 520 521 522 523 524 525 526 527

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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