LinkManager.cc 35.4 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
lm's avatar
lm committed
9

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"
dogmaphobic's avatar
dogmaphobic committed
24
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
25 26
#include "BluetoothLink.h"
#endif
27

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

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

Don Gagne's avatar
Don Gagne committed
36
const char* LinkManager::_defaultUPDLinkName =       "UDP Link (AutoConnect)";
37

38 39 40 41 42 43 44 45
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

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

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

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

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

87
    connect(_mavlinkProtocol, &MAVLinkProtocol::messageReceived, this, &LinkManager::_mavlinkMessageReceived);
88

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

92 93
}

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

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

111 112
    LinkInterface* pLink = NULL;
    switch(config->type()) {
Gus Grubba's avatar
Gus Grubba committed
113
#ifndef NO_SERIAL_LINK
DonLakeFlyer's avatar
DonLakeFlyer committed
114 115 116 117
    case LinkConfiguration::TypeSerial:
    {
        SerialConfiguration* serialConfig = dynamic_cast<SerialConfiguration*>(config.data());
        if (serialConfig) {
118
            pLink = new SerialLink(config, isPX4Flow);
DonLakeFlyer's avatar
DonLakeFlyer committed
119 120 121 122
            if (serialConfig->usbDirect()) {
                _activeLinkCheckList.append((SerialLink*)pLink);
                if (!_activeLinkCheckTimer.isActive()) {
                    _activeLinkCheckTimer.start();
Don Gagne's avatar
Don Gagne committed
123 124 125
                }
            }
        }
DonLakeFlyer's avatar
DonLakeFlyer committed
126
    }
Don Gagne's avatar
Don Gagne committed
127
        break;
DonLakeFlyer's avatar
DonLakeFlyer committed
128 129
#else
    Q_UNUSED(isPX4Flow)
dogmaphobic's avatar
dogmaphobic committed
130
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
131 132 133 134 135 136
    case LinkConfiguration::TypeUdp:
        pLink = new UDPLink(config);
        break;
    case LinkConfiguration::TypeTcp:
        pLink = new TCPLink(config);
        break;
dogmaphobic's avatar
dogmaphobic committed
137
#ifdef QGC_ENABLE_BLUETOOTH
DonLakeFlyer's avatar
DonLakeFlyer committed
138 139 140
    case LinkConfiguration::TypeBluetooth:
        pLink = new BluetoothLink(config);
        break;
dogmaphobic's avatar
dogmaphobic committed
141
#endif
dogmaphobic's avatar
dogmaphobic committed
142
#ifndef __mobile__
DonLakeFlyer's avatar
DonLakeFlyer committed
143 144 145
    case LinkConfiguration::TypeLogReplay:
        pLink = new LogReplayLink(config);
        break;
dogmaphobic's avatar
dogmaphobic committed
146
#endif
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 154
    case LinkConfiguration::TypeLast:
    default:
        break;
155
    }
156 157

    if (pLink) {
158 159
        _addLink(pLink);
        connectLink(pLink);
160
    }
161

162 163 164
    return pLink;
}

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

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

Don Gagne's avatar
Don Gagne committed
187 188 189
    if (!link) {
        return;
    }
190

191
    if (!containsLink(link)) {
192 193 194 195
        int mavlinkChannel = _reserveMavlinkChannel();
        if (mavlinkChannel != 0) {
            link->_setMavlinkChannel(mavlinkChannel);
        } else {
196
            qWarning() << "Ran out of mavlink channels";
197
            return;
198 199
        }

200
        _sharedLinks.append(SharedLinkInterfacePointer(link));
201 202
        emit newLink(link);
    }
203

Don Gagne's avatar
Don Gagne committed
204 205
    connect(link, &LinkInterface::communicationError,   _app,               &QGCApplication::criticalMessageBoxOnMainThread);
    connect(link, &LinkInterface::bytesReceived,        _mavlinkProtocol,   &MAVLinkProtocol::receiveBytes);
206

207
    _mavlinkProtocol->resetMetadataForLink(link);
208
    _mavlinkProtocol->setVersion(_mavlinkProtocol->getCurrentVersion());
209

210 211 212 213 214 215
    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);
216
}
pixhawk's avatar
pixhawk committed
217

Don Gagne's avatar
Don Gagne committed
218
void LinkManager::disconnectAll(void)
pixhawk's avatar
pixhawk committed
219
{
Don Gagne's avatar
Don Gagne committed
220
    // Walk list in reverse order to preserve indices during delete
221 222
    for (int i=_sharedLinks.count()-1; i>=0; i--) {
        disconnectLink(_sharedLinks[i].data());
223
    }
pixhawk's avatar
pixhawk committed
224 225 226 227
}

bool LinkManager::connectLink(LinkInterface* link)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
228 229 230 231 232 233 234
    if (link) {
        if (_connectionsSuspendedMsg()) {
            return false;
        }
        return link->_connect();
    } else {
        qWarning() << "Internal error";
235 236
        return false;
    }
pixhawk's avatar
pixhawk committed
237 238
}

Don Gagne's avatar
Don Gagne committed
239
void LinkManager::disconnectLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
240
{
241
    if (!link || !containsLink(link)) {
242 243
        return;
    }
Don Gagne's avatar
Don Gagne committed
244

Don Gagne's avatar
Don Gagne committed
245
    link->_disconnect();
246

Don Gagne's avatar
Don Gagne committed
247
    LinkConfiguration* config = link->getLinkConfiguration();
248 249 250 251 252
    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;
253
        }
254
    }
255

Don Gagne's avatar
Don Gagne committed
256
    _deleteLink(link);
pixhawk's avatar
pixhawk committed
257 258
}

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

    if (!link) {
        return;
    }
269

270
    // Free up the mavlink channel associated with this link
271
    _freeMavlinkChannel(link->mavlinkChannel());
272

273 274 275 276 277 278
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            _sharedLinks.removeAt(i);
            break;
        }
    }
279

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

284 285 286 287 288 289 290 291 292 293 294 295
SharedLinkInterfacePointer LinkManager::sharedLinkInterfacePointerForLink(LinkInterface* link)
{
    for (int i=0; i<_sharedLinks.count(); i++) {
        if (_sharedLinks[i].data() == link) {
            return _sharedLinks[i];
        }
    }

    qWarning() << "LinkManager::sharedLinkInterfaceForLink returning NULL";
    return SharedLinkInterfacePointer(NULL);
}

296 297 298 299 300
/// @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) {
301
        qgcApp()->showMessage(tr("Connect not allowed: %1").arg(_connectionsSuspendedReason));
302 303 304 305 306 307 308 309 310 311 312
        return true;
    } else {
        return false;
    }
}

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

314 315 316 317 318 319 320 321 322
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

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

324 325 326 327 328 329
void LinkManager::_linkConnectionRemoved(LinkInterface* link)
{
    // Link has been removed from system, disconnect it automatically
    disconnectLink(link);
}

330 331 332 333 334 335 336 337 338
void LinkManager::suspendConfigurationUpdates(bool suspend)
{
    _configUpdateSuspended = suspend;
}

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

void LinkManager::loadLinkConfigurationList()
{
364
    bool linksChanged = false;
365 366 367 368 369 370 371 372 373 374
    QSettings settings;
    // Is the group even there?
    if(settings.contains(LinkConfiguration::settingsRoot() + "/count")) {
        // Find out how many configurations we have
        int count = settings.value(LinkConfiguration::settingsRoot() + "/count").toInt();
        for(int i = 0; i < count; i++) {
            QString root(LinkConfiguration::settingsRoot());
            root += QString("/Link%1").arg(i);
            if(settings.contains(root + "/type")) {
                int type = settings.value(root + "/type").toInt();
375
                if((LinkConfiguration::LinkType)type < LinkConfiguration::TypeLast) {
376 377 378 379
                    if(settings.contains(root + "/name")) {
                        QString name = settings.value(root + "/name").toString();
                        if(!name.isEmpty()) {
                            LinkConfiguration* pLink = NULL;
380
                            bool autoConnect = settings.value(root + "/auto").toBool();
381
                            bool highLatency = settings.value(root + "/high_latency").toBool();
382
                            switch((LinkConfiguration::LinkType)type) {
Gus Grubba's avatar
Gus Grubba committed
383
#ifndef NO_SERIAL_LINK
DonLakeFlyer's avatar
DonLakeFlyer committed
384 385 386
                            case LinkConfiguration::TypeSerial:
                                pLink = (LinkConfiguration*)new SerialConfiguration(name);
                                break;
dogmaphobic's avatar
dogmaphobic committed
387
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
388 389 390 391 392 393
                            case LinkConfiguration::TypeUdp:
                                pLink = (LinkConfiguration*)new UDPConfiguration(name);
                                break;
                            case LinkConfiguration::TypeTcp:
                                pLink = (LinkConfiguration*)new TCPConfiguration(name);
                                break;
dogmaphobic's avatar
dogmaphobic committed
394
#ifdef QGC_ENABLE_BLUETOOTH
DonLakeFlyer's avatar
DonLakeFlyer committed
395 396 397
                            case LinkConfiguration::TypeBluetooth:
                                pLink = (LinkConfiguration*)new BluetoothConfiguration(name);
                                break;
dogmaphobic's avatar
dogmaphobic committed
398
#endif
dogmaphobic's avatar
dogmaphobic committed
399
#ifndef __mobile__
DonLakeFlyer's avatar
DonLakeFlyer committed
400 401 402
                            case LinkConfiguration::TypeLogReplay:
                                pLink = (LinkConfiguration*)new LogReplayLinkConfiguration(name);
                                break;
dogmaphobic's avatar
dogmaphobic committed
403
#endif
404
#ifdef QT_DEBUG
DonLakeFlyer's avatar
DonLakeFlyer committed
405 406 407
                            case LinkConfiguration::TypeMock:
                                pLink = (LinkConfiguration*)new MockConfiguration(name);
                                break;
408
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
409 410 411
                            default:
                            case LinkConfiguration::TypeLast:
                                break;
412 413
                            }
                            if(pLink) {
414 415
                                //-- Have the instance load its own values
                                pLink->setAutoConnect(autoConnect);
416
                                pLink->setHighLatency(highLatency);
417
                                pLink->loadSettings(settings, root);
418
                                addConfiguration(pLink);
419
                                linksChanged = true;
420 421
                            }
                        } else {
422
                            qWarning() << "Link Configuration" << root << "has an empty name." ;
423 424
                        }
                    } else {
425
                        qWarning() << "Link Configuration" << root << "has no name." ;
426 427
                    }
                } else {
428
                    qWarning() << "Link Configuration" << root << "an invalid type: " << type;
429 430
                }
            } else {
431
                qWarning() << "Link Configuration" << root << "has no type." ;
432 433 434
            }
        }
    }
435 436

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

Gus Grubba's avatar
Gus Grubba committed
443
#ifndef NO_SERIAL_LINK
Don Gagne's avatar
Don Gagne committed
444
SerialConfiguration* LinkManager::_autoconnectConfigurationsContainsPort(const QString& portName)
445 446
{
    QString searchPort = portName.trimmed();
Don Gagne's avatar
Don Gagne committed
447

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

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

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

Don Gagne's avatar
Don Gagne committed
469 470
    // Re-add UDP if we need to
    bool foundUDP = false;
471 472
    for (int i=0; i<_sharedLinks.count(); i++) {
        LinkConfiguration* linkConfig = _sharedLinks[i]->getLinkConfiguration();
Don Gagne's avatar
Don Gagne committed
473 474 475 476 477
        if (linkConfig->type() == LinkConfiguration::TypeUdp && linkConfig->name() == _defaultUPDLinkName) {
            foundUDP = true;
            break;
        }
    }
478
    if (!foundUDP && _autoConnectSettings->autoConnectUDP()->rawValue().toBool()) {
Don Gagne's avatar
Don Gagne committed
479
        qCDebug(LinkManagerLog) << "New auto-connect UDP port added";
480
        // Default UDPConfiguration is set up for autoconnect
Don Gagne's avatar
Don Gagne committed
481
        UDPConfiguration* udpConfig = new UDPConfiguration(_defaultUPDLinkName);
DonLakeFlyer's avatar
DonLakeFlyer committed
482
        udpConfig->setDynamic(true);
483 484
        SharedLinkConfigurationPointer config = addConfiguration(udpConfig);
        createConnectedLink(config);
485
        emit linkConfigurationsChanged();
Don Gagne's avatar
Don Gagne committed
486 487
    }

Gus Grubba's avatar
Gus Grubba committed
488
#ifndef NO_SERIAL_LINK
dogmaphobic's avatar
dogmaphobic committed
489
    QStringList currentPorts;
490 491 492 493 494 495
    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.
496
    if (!_sharedAutoconnectConfigurations.count()) {
497 498
        portList = QGCSerialPortInfo::availablePorts();
    }
499 500
#else
    portList = QGCSerialPortInfo::availablePorts();
501
#endif
Don Gagne's avatar
Don Gagne committed
502

503
    // Iterate Comm Ports
504
    for (QGCSerialPortInfo portInfo: portList) {
Don Gagne's avatar
Don Gagne committed
505 506 507 508 509 510 511 512 513
        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
514 515
        // Save port name
        currentPorts << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
516

517 518
        QGCSerialPortInfo::BoardType_t boardType;
        QString boardName;
Don Gagne's avatar
Don Gagne committed
519

520
#ifndef NO_SERIAL_LINK
521
#ifndef __mobile__
522 523 524 525 526 527 528 529 530 531 532 533
        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();
                newPort->setBaudRate(_nmeaBaud);
                qCDebug(LinkManagerLog) << "Configuring nmea baudrate" << _nmeaBaud;

                // This will stop polling old device if previously set
                _toolbox->qgcPositionManager()->setNmeaSourceDevice(newPort);
534

535 536 537 538 539 540 541 542 543 544
                if (_nmeaPort) {
                    delete _nmeaPort;
                }
                _nmeaPort = newPort;

            } else if (_autoConnectSettings->autoConnectNmeaBaud()->cookedValue().toUInt() != _nmeaBaud) {
                _nmeaBaud = _autoConnectSettings->autoConnectNmeaBaud()->cookedValue().toUInt();
                _nmeaPort->setBaudRate(_nmeaBaud);
                qCDebug(LinkManagerLog) << "Configuring nmea baudrate" << _nmeaBaud;
            }
545
        } else
546
#endif
547 548
#endif
        if (portInfo.getBoardInfo(boardType, boardName)) {
Don Gagne's avatar
Don Gagne committed
549 550
            if (portInfo.isBootloader()) {
                // Don't connect to bootloader
551
                qCDebug(LinkManagerLog) << "Waiting for bootloader to finish" << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
552 553
                continue;
            }
554

555
            if (_autoconnectConfigurationsContainsPort(portInfo.systemLocation()) || _autoConnectRTKPort == portInfo.systemLocation()) {
556 557 558 559 560 561
                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();
562 563
                _autoconnectWaitList[portInfo.systemLocation()] = 1;
            } else if (++_autoconnectWaitList[portInfo.systemLocation()] * _autoconnectUpdateTimerMSecs > _autoconnectConnectDelayMSecs) {
Don Gagne's avatar
Don Gagne committed
564 565
                SerialConfiguration* pSerialConfig = NULL;

566
                _autoconnectWaitList.remove(portInfo.systemLocation());
567

Don Gagne's avatar
Don Gagne committed
568
                switch (boardType) {
569
                case QGCSerialPortInfo::BoardTypePixhawk:
570
                    if (_autoConnectSettings->autoConnectPixhawk()->rawValue().toBool()) {
571
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
572 573 574
                        pSerialConfig->setUsbDirect(true);
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
575
                case QGCSerialPortInfo::BoardTypePX4Flow:
576
                    if (_autoConnectSettings->autoConnectPX4Flow()->rawValue().toBool()) {
577
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
Don Gagne's avatar
Don Gagne committed
578
                    }
Don Gagne's avatar
Don Gagne committed
579
                    break;
580
                case QGCSerialPortInfo::BoardTypeSiKRadio:
581
                    if (_autoConnectSettings->autoConnectSiKRadio()->rawValue().toBool()) {
582
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
Don Gagne's avatar
Don Gagne committed
583 584
                    }
                    break;
585
                case QGCSerialPortInfo::BoardTypeOpenPilot:
586
                    if (_autoConnectSettings->autoConnectLibrePilot()->rawValue().toBool()) {
587
                        pSerialConfig = new SerialConfiguration(tr("%1 on %2 (AutoConnect)").arg(boardName).arg(portInfo.portName().trimmed()));
588 589
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
590 591
#ifndef __mobile__
                case QGCSerialPortInfo::BoardTypeRTKGPS:
592
                    if (_autoConnectSettings->autoConnectRTKGPS()->rawValue().toBool() && !_toolbox->gpsManager()->connected()) {
593 594
                        qCDebug(LinkManagerLog) << "RTK GPS auto-connected" << portInfo.portName().trimmed();
                        _autoConnectRTKPort = portInfo.systemLocation();
595
                        _toolbox->gpsManager()->connectGPS(portInfo.systemLocation(), boardName);
Don Gagne's avatar
Don Gagne committed
596 597 598
                    }
                    break;
#endif
Don Gagne's avatar
Don Gagne committed
599 600
                default:
                    qWarning() << "Internal error";
Don Gagne's avatar
Don Gagne committed
601
                    continue;
dogmaphobic's avatar
dogmaphobic committed
602
                }
Don Gagne's avatar
Don Gagne committed
603

Don Gagne's avatar
Don Gagne committed
604 605
                if (pSerialConfig) {
                    qCDebug(LinkManagerLog) << "New auto-connect port added: " << pSerialConfig->name() << portInfo.systemLocation();
606
                    pSerialConfig->setBaud(boardType == QGCSerialPortInfo::BoardTypeSiKRadio ? 57600 : 115200);
Don Gagne's avatar
Don Gagne committed
607 608
                    pSerialConfig->setDynamic(true);
                    pSerialConfig->setPortName(portInfo.systemLocation());
609
                    _sharedAutoconnectConfigurations.append(SharedLinkConfigurationPointer(pSerialConfig));
610
                    createConnectedLink(_sharedAutoconnectConfigurations.last(), boardType == QGCSerialPortInfo::BoardTypePX4Flow);
Don Gagne's avatar
Don Gagne committed
611
                }
dogmaphobic's avatar
dogmaphobic committed
612 613 614
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
615

616 617 618 619 620 621 622
#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
    // bug after we connect the first serial port we stop probing for additional ports. The means we must rely on
    // 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
623 624
    // Now we go through the current configuration list and make sure any dynamic config has gone away
    QList<LinkConfiguration*>  _confToDelete;
625 626 627 628 629 630 631
    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()) {
632 633 634 635 636 637
                            // 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
638
                }
639
                _confToDelete.append(serialConfig);
dogmaphobic's avatar
dogmaphobic committed
640
            }
Don Gagne's avatar
Don Gagne committed
641 642
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
643 644
        }
    }
Don Gagne's avatar
Don Gagne committed
645

Don Gagne's avatar
Don Gagne committed
646
    // Now remove all configs that are gone
647
    for (LinkConfiguration* pDeleteConfig: _confToDelete) {
Don Gagne's avatar
Don Gagne committed
648
        qCDebug(LinkManagerLog) << "Removing unused autoconnect config" << pDeleteConfig->name();
Don Gagne's avatar
Don Gagne committed
649 650 651
        if (pDeleteConfig->link()) {
            disconnectLink(pDeleteConfig->link());
        }
652 653 654 655 656 657
        for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
            if (_sharedAutoconnectConfigurations[i].data() == pDeleteConfig) {
                _sharedAutoconnectConfigurations.removeAt(i);
                break;
            }
        }
658
    }
659 660

    // Check for RTK GPS connection gone
661
#if !defined(__mobile__)
662 663 664 665 666
    if (!_autoConnectRTKPort.isEmpty() && !currentPorts.contains(_autoConnectRTKPort)) {
        qCDebug(LinkManagerLog) << "RTK GPS disconnected" << _autoConnectRTKPort;
        _toolbox->gpsManager()->disconnectGPS();
        _autoConnectRTKPort.clear();
    }
667
#endif
668

669
#endif
Gus Grubba's avatar
Gus Grubba committed
670
#endif // NO_SERIAL_LINK
671 672
}

Don Gagne's avatar
Don Gagne committed
673 674
void LinkManager::shutdown(void)
{
675
    setConnectionsSuspended(tr("Shutdown"));
Don Gagne's avatar
Don Gagne committed
676
    disconnectAll();
Don Gagne's avatar
Don Gagne committed
677 678
}

679 680 681 682 683 684
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
685
#ifndef NO_SERIAL_LINK
686 687 688 689
        list += "Serial";
#endif
        list += "UDP";
        list += "TCP";
dogmaphobic's avatar
dogmaphobic committed
690
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
691 692
        list += "Bluetooth";
#endif
dogmaphobic's avatar
dogmaphobic committed
693
#ifdef QT_DEBUG
694
        list += "Mock Link";
dogmaphobic's avatar
dogmaphobic committed
695 696
#endif
#ifndef __mobile__
697
        list += "Log Replay";
dogmaphobic's avatar
dogmaphobic committed
698
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
699 700 701
        if (list.size() != (int)LinkConfiguration::TypeLast) {
            qWarning() << "Internal error";
        }
702 703 704 705
    }
    return list;
}

706
void LinkManager::_updateSerialPorts()
707
{
708 709
    _commPortList.clear();
    _commPortDisplayList.clear();
Gus Grubba's avatar
Gus Grubba committed
710
#ifndef NO_SERIAL_LINK
711
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
712
    for (const QSerialPortInfo &info: portList)
713
    {
714 715 716
        QString port = info.systemLocation().trimmed();
        _commPortList += port;
        _commPortDisplayList += SerialConfiguration::cleanPortDisplayname(port);
717 718
    }
#endif
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
}

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

QStringList LinkManager::serialPorts(void)
{
    if(!_commPortList.size())
    {
        _updateSerialPorts();
    }
736 737 738 739 740
    return _commPortList;
}

QStringList LinkManager::serialBaudRates(void)
{
Gus Grubba's avatar
Gus Grubba committed
741
#ifdef NO_SERIAL_LINK
742 743 744 745 746 747
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
748 749 750

bool LinkManager::endConfigurationEditing(LinkConfiguration* config, LinkConfiguration* editedConfig)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
751 752 753 754 755 756 757 758 759 760 761
    if (config && editedConfig) {
        _fixUnnamed(editedConfig);
        config->copyFrom(editedConfig);
        saveLinkConfigurationList();
        // Tell link about changes (if any)
        config->updateSettings();
        // Discard temporary duplicate
        delete editedConfig;
    } else {
        qWarning() << "Internal error";
    }
762 763 764 765 766
    return true;
}

bool LinkManager::endCreateConfiguration(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
767 768 769 770 771 772 773
    if (config) {
        _fixUnnamed(config);
        addConfiguration(config);
        saveLinkConfigurationList();
    } else {
        qWarning() << "Internal error";
    }
774 775 776 777 778
    return true;
}

LinkConfiguration* LinkManager::createConfiguration(int type, const QString& name)
{
Gus Grubba's avatar
Gus Grubba committed
779
#ifndef NO_SERIAL_LINK
780 781
    if((LinkConfiguration::LinkType)type == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
782
#endif
783 784 785 786 787
    return LinkConfiguration::createSettings(type, name);
}

LinkConfiguration* LinkManager::startConfigurationEditing(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
788
    if (config) {
Gus Grubba's avatar
Gus Grubba committed
789
#ifndef NO_SERIAL_LINK
DonLakeFlyer's avatar
DonLakeFlyer committed
790 791
        if(config->type() == LinkConfiguration::TypeSerial)
            _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
792
#endif
DonLakeFlyer's avatar
DonLakeFlyer committed
793 794 795 796 797
        return LinkConfiguration::duplicateSettings(config);
    } else {
        qWarning() << "Internal error";
        return NULL;
    }
798 799 800 801 802
}


void LinkManager::_fixUnnamed(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
803 804 805 806
    if (config) {
        //-- Check for "Unnamed"
        if (config->name() == "Unnamed") {
            switch(config->type()) {
Gus Grubba's avatar
Gus Grubba committed
807
#ifndef NO_SERIAL_LINK
808 809
            case LinkConfiguration::TypeSerial: {
                QString tname = dynamic_cast<SerialConfiguration*>(config)->portName();
810
#ifdef Q_OS_WIN
811 812 813 814 815 816 817
                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
818
            }
819 820 821
#endif
            case LinkConfiguration::TypeUdp:
                config->setName(
DonLakeFlyer's avatar
DonLakeFlyer committed
822
                            QString("UDP Link on Port %1").arg(dynamic_cast<UDPConfiguration*>(config)->localPort()));
823 824
                break;
            case LinkConfiguration::TypeTcp: {
DonLakeFlyer's avatar
DonLakeFlyer committed
825 826 827 828
                TCPConfiguration* tconfig = dynamic_cast<TCPConfiguration*>(config);
                if(tconfig) {
                    config->setName(
                                QString("TCP Link %1:%2").arg(tconfig->address().toString()).arg((int)tconfig->port()));
829
                }
DonLakeFlyer's avatar
DonLakeFlyer committed
830
            }
831
                break;
dogmaphobic's avatar
dogmaphobic committed
832
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
833
            case LinkConfiguration::TypeBluetooth: {
DonLakeFlyer's avatar
DonLakeFlyer committed
834 835 836
                BluetoothConfiguration* tconfig = dynamic_cast<BluetoothConfiguration*>(config);
                if(tconfig) {
                    config->setName(QString("%1 (Bluetooth Device)").arg(tconfig->device().name));
dogmaphobic's avatar
dogmaphobic committed
837
                }
DonLakeFlyer's avatar
DonLakeFlyer committed
838
            }
dogmaphobic's avatar
dogmaphobic committed
839 840
                break;
#endif
dogmaphobic's avatar
dogmaphobic committed
841
#ifndef __mobile__
842
            case LinkConfiguration::TypeLogReplay: {
DonLakeFlyer's avatar
DonLakeFlyer committed
843 844 845
                LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
                if(tconfig) {
                    config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
846
                }
DonLakeFlyer's avatar
DonLakeFlyer committed
847
            }
848
                break;
dogmaphobic's avatar
dogmaphobic committed
849
#endif
850 851 852
#ifdef QT_DEBUG
            case LinkConfiguration::TypeMock:
                config->setName(
DonLakeFlyer's avatar
DonLakeFlyer committed
853
                            QString("Mock Link"));
854 855 856 857 858
                break;
#endif
            case LinkConfiguration::TypeLast:
            default:
                break;
DonLakeFlyer's avatar
DonLakeFlyer committed
859
            }
860
        }
DonLakeFlyer's avatar
DonLakeFlyer committed
861 862
    } else {
        qWarning() << "Internal error";
863 864 865 866 867
    }
}

void LinkManager::removeConfiguration(LinkConfiguration* config)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
868 869 870 871 872
    if (config) {
        LinkInterface* iface = config->link();
        if(iface) {
            disconnectLink(iface);
        }
873

DonLakeFlyer's avatar
DonLakeFlyer committed
874 875 876 877 878
        _removeConfiguration(config);
        saveLinkConfigurationList();
    } else {
        qWarning() << "Internal error";
    }
879
}
880

881 882
bool LinkManager::isAutoconnectLink(LinkInterface* link)
{
883 884 885 886 887 888
    for (int i=0; i<_sharedAutoconnectConfigurations.count(); i++) {
        if (_sharedAutoconnectConfigurations[i].data() == link->getLinkConfiguration()) {
            return true;
        }
    }
    return false;
889
}
dogmaphobic's avatar
dogmaphobic committed
890 891 892 893 894

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

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

    if (_activeLinkCheckList.count() != 0) {
903
        link = _activeLinkCheckList.takeFirst();
904
        if (containsLink(link) && link->isConnected()) {
Don Gagne's avatar
Don Gagne committed
905 906 907 908 909 910 911 912 913
            // Make sure there is a vehicle on the link
            QmlObjectListModel* vehicles = _toolbox->multiVehicleManager()->vehicles();
            for (int i=0; i<vehicles->count(); i++) {
                Vehicle* vehicle = qobject_cast<Vehicle*>(vehicles->get(i));
                if (vehicle->containsLink(link)) {
                    found = true;
                    break;
                }
            }
914 915
        } else {
            link = NULL;
Don Gagne's avatar
Don Gagne committed
916 917 918 919 920 921 922
        }
    }

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

923 924 925
    if (!found && link) {
        // See if we can get an NSH prompt on this link
        bool foundNSHPrompt = false;
926
        link->writeBytesSafe("\r", 1);
927 928 929 930 931 932 933 934 935
        QSignalSpy spy(link, SIGNAL(bytesReceived(LinkInterface*, QByteArray)));
        if (spy.wait(100)) {
            QList<QVariant> arguments = spy.takeFirst();
            if (arguments[1].value<QByteArray>().contains("nsh>")) {
                foundNSHPrompt = true;
            }
        }

        qgcApp()->showMessage(foundNSHPrompt ?
936 937
                                  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
938 939
    }
}
Don Gagne's avatar
Don Gagne committed
940
#endif
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

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;
}
983 984 985 986 987 988 989 990 991 992 993

void LinkManager::startAutoConnectedLinks(void)
{
    SharedLinkConfigurationPointer conf;

    for(int i = 0; i < _sharedConfigurations.count(); i++) {
        conf = _sharedConfigurations[i];
        if (conf->isAutoConnect())
            createConnectedLink(conf);
    }
}
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

int LinkManager::_reserveMavlinkChannel(void)
{
    // Find a mavlink channel to use for this link, Channel 0 is reserved for internal use.
    for (int mavlinkChannel=1; mavlinkChannel<32; mavlinkChannel++) {
        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);
}
1016

1017 1018
void LinkManager::_mavlinkMessageReceived(LinkInterface* link, mavlink_message_t message) {
    link->startMavlinkMessagesTimer(message.sysid);
1019
}