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

QGroundControl Open Source Ground Control Station

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

This file is part of the QGROUNDCONTROL project

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

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

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

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

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

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

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

40 41
#include "LinkManager.h"
#include "MainWindow.h"
Don Gagne's avatar
Don Gagne committed
42
#include "QGCMessageBox.h"
43
#include "QGCApplication.h"
44
#include "QGCApplication.h"
Don Gagne's avatar
Don Gagne committed
45 46
#include "UDPLink.h"
#include "TCPLink.h"
47
#ifdef __mobile__
dogmaphobic's avatar
dogmaphobic committed
48 49
#include "BluetoothLink.h"
#endif
50

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

const char* LinkManager::_settingsGroup =           "LinkManager";
const char* LinkManager::_autoconnectUDPKey =       "AutoconnectUDP";
const char* LinkManager::_autoconnectPixhawkKey =   "AutoconnectPixhawk";
const char* LinkManager::_autoconnect3DRRadioKey =  "Autoconnect3DRRadio";
const char* LinkManager::_autoconnectPX4FlowKey =   "AutoconnectPX4Flow";
Don Gagne's avatar
Don Gagne committed
59
const char* LinkManager::_defaultUPDLinkName =      "Default UDP Link";
60

61 62 63 64 65 66 67 68
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

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

pixhawk's avatar
pixhawk committed
81
{
Don Gagne's avatar
Don Gagne committed
82 83 84 85 86
    qmlRegisterUncreatableType<LinkManager>         ("QGroundControl", 1, 0, "LinkManager",         "Reference only");
    qmlRegisterUncreatableType<LinkConfiguration>   ("QGroundControl", 1, 0, "LinkConfiguration",   "Reference only");
    qmlRegisterUncreatableType<LinkInterface>       ("QGroundControl", 1, 0, "LinkInterface",       "Reference only");

    QSettings settings;
87

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

LinkManager::~LinkManager()
{
Don Gagne's avatar
Don Gagne committed
97 98
    if (anyActiveLinks()) {
        qWarning() << "Why are there still active links?";
99
    }
pixhawk's avatar
pixhawk committed
100 101
}

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

   _mavlinkProtocol = _toolbox->mavlinkProtocol();
Don Gagne's avatar
Don Gagne committed
107
   connect(_mavlinkProtocol, &MAVLinkProtocol::vehicleHeartbeatInfo, this, &LinkManager::_vehicleHeartbeatInfo);
108

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

112 113
}

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

Don Gagne's avatar
Don Gagne committed
156
LinkInterface* LinkManager::createConnectedLink(const QString& name)
157 158 159
{
    Q_ASSERT(name.isEmpty() == false);
    for(int i = 0; i < _linkConfigurations.count(); i++) {
Don Gagne's avatar
Don Gagne committed
160
        LinkConfiguration* conf = _linkConfigurations.value<LinkConfiguration*>(i);
161
        if(conf && conf->name() == name)
Don Gagne's avatar
Don Gagne committed
162
            return createConnectedLink(conf);
163 164 165 166
    }
    return NULL;
}

167
void LinkManager::_addLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
168
{
Don Gagne's avatar
Don Gagne committed
169 170 171 172
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }
173

Don Gagne's avatar
Don Gagne committed
174 175 176
    if (!link) {
        return;
    }
177

Don Gagne's avatar
Don Gagne committed
178
    if (!_links.contains(link)) {
179 180 181
        // Find a mavlink channel to use for this link
        for (int i=0; i<32; i++) {
            if (!(_mavlinkChannelsUsedBitMask && 1 << i)) {
182
                mavlink_reset_channel_status(i);
183 184 185 186 187
                link->_setMavlinkChannel(i);
                _mavlinkChannelsUsedBitMask |= i << i;
                break;
            }
        }
188

Don Gagne's avatar
Don Gagne committed
189
        _links.append(link);
190 191
        emit newLink(link);
    }
192

193 194
    // MainWindow may be around when doing things like running unit tests
    if (MainWindow::instance()) {
195
        connect(link, &LinkInterface::communicationError, _app, &QGCApplication::criticalMessageBoxOnMainThread);
196
    }
197

198 199 200 201
    connect(link, &LinkInterface::bytesReceived,    _mavlinkProtocol, &MAVLinkProtocol::receiveBytes);
    connect(link, &LinkInterface::connected,        _mavlinkProtocol, &MAVLinkProtocol::linkConnected);
    connect(link, &LinkInterface::disconnected,     _mavlinkProtocol, &MAVLinkProtocol::linkDisconnected);
    _mavlinkProtocol->resetMetadataForLink(link);
202

203
    connect(link, &LinkInterface::connected,    this, &LinkManager::_linkConnected);
204
    connect(link, &LinkInterface::disconnected, this, &LinkManager::_linkDisconnected);
205
}
pixhawk's avatar
pixhawk committed
206

Don Gagne's avatar
Don Gagne committed
207
void LinkManager::disconnectAll(void)
pixhawk's avatar
pixhawk committed
208
{
Don Gagne's avatar
Don Gagne committed
209 210
    // Walk list in reverse order to preserve indices during delete
    for (int i=_links.count()-1; i>=0; i--) {
Don Gagne's avatar
Don Gagne committed
211
        disconnectLink(_links.value<LinkInterface*>(i));
212
    }
pixhawk's avatar
pixhawk committed
213 214 215 216
}

bool LinkManager::connectLink(LinkInterface* link)
{
217
    Q_ASSERT(link);
218

219 220 221 222
    if (_connectionsSuspendedMsg()) {
        return false;
    }

Don Gagne's avatar
Don Gagne committed
223 224
    bool previousAnyConnectedLinks = anyConnectedLinks();

225
    if (link->_connect()) {
Don Gagne's avatar
Don Gagne committed
226 227 228
        if (!previousAnyConnectedLinks) {
            emit anyConnectedLinksChanged(true);
        }
229 230 231 232
        return true;
    } else {
        return false;
    }
pixhawk's avatar
pixhawk committed
233 234
}

Don Gagne's avatar
Don Gagne committed
235
void LinkManager::disconnectLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
236
{
237
    Q_ASSERT(link);
Don Gagne's avatar
Don Gagne committed
238

Don Gagne's avatar
Don Gagne committed
239 240
    link->_disconnect();
    LinkConfiguration* config = link->getLinkConfiguration();
241 242 243 244
    if (config) {
        if (_autoconnectConfigurations.contains(config)) {
            config->setLink(NULL);
        }
245
    }
Don Gagne's avatar
Don Gagne committed
246
    _deleteLink(link);
247 248 249 250
    if (_autoconnectConfigurations.contains(config)) {
        _autoconnectConfigurations.removeOne(config);
        delete config;
    }
pixhawk's avatar
pixhawk committed
251 252
}

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

    if (!link) {
        return;
    }
263

264 265
    // Free up the mavlink channel associated with this link
    _mavlinkChannelsUsedBitMask &= ~(1 << link->getMavlinkChannel());
266

Don Gagne's avatar
Don Gagne committed
267 268
    _links.removeOne(link);
    delete link;
269

Don Gagne's avatar
Don Gagne committed
270
    // Emit removal of link
271
    emit linkDeleted(link);
pixhawk's avatar
pixhawk committed
272 273
}

274 275 276 277 278
/// @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) {
Don Gagne's avatar
Don Gagne committed
279 280
        QGCMessageBox::information(tr("Connect not allowed"),
                                   tr("Connect not allowed: %1").arg(_connectionsSuspendedReason));
281 282 283 284 285 286 287 288 289 290 291 292
        return true;
    } else {
        return false;
    }
}

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

294 295 296 297 298 299 300 301 302
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

void LinkManager::_linkDisconnected(void)
{
    emit linkDisconnected((LinkInterface*)sender());
}
303 304 305 306 307 308 309 310 311 312

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

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

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

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

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

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

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

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

Don Gagne's avatar
Don Gagne committed
455 456 457 458 459 460 461 462 463 464
    // Re-add UDP if we need to
    bool foundUDP = false;
    for (int i=0; i<_links.count(); i++) {
        LinkConfiguration* linkConfig = _links.value<LinkInterface*>(i)->getLinkConfiguration();
        if (linkConfig->type() == LinkConfiguration::TypeUdp && linkConfig->name() == _defaultUPDLinkName) {
            foundUDP = true;
            break;
        }
    }
    if (!foundUDP) {
Don Gagne's avatar
Don Gagne committed
465
        qCDebug(LinkManagerLog) << "New auto-connect UDP port added";
Don Gagne's avatar
Don Gagne committed
466 467 468
        UDPConfiguration* udpConfig = new UDPConfiguration(_defaultUPDLinkName);
        udpConfig->setLocalPort(QGC_UDP_LOCAL_PORT);
        udpConfig->setDynamic(true);
469
        _linkConfigurations.append(udpConfig);
Don Gagne's avatar
Don Gagne committed
470
        createConnectedLink(udpConfig);
471
        emit linkConfigurationsChanged();
Don Gagne's avatar
Don Gagne committed
472 473
    }

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

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

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

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

501 502 503 504 505 506 507
            if (_autoconnectConfigurationsContainsPort(portInfo.systemLocation())) {
                qCDebug(LinkManagerVerboseLog) << "Skipping existing autoconnect" << portInfo.systemLocation();
            } else if (!_autoconnectWaitList.contains(portInfo.systemLocation())) {
                // We don't connect to the port the first time we see it. The ability to correctly detect whether we
                // are in the bootloader is flaky from a cross-platform standpoint. So by putting it on a wait list
                // and only connect on the second pass we leave enough time for the board to boot up.
                qCDebug(LinkManagerLog) << "Waiting for next autoconnect pass" << portInfo.systemLocation();
508 509
                _autoconnectWaitList[portInfo.systemLocation()] = 1;
            } else if (++_autoconnectWaitList[portInfo.systemLocation()] * _autoconnectUpdateTimerMSecs > _autoconnectConnectDelayMSecs) {
Don Gagne's avatar
Don Gagne committed
510 511
                SerialConfiguration* pSerialConfig = NULL;

512
                _autoconnectWaitList.remove(portInfo.systemLocation());
513

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

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

dogmaphobic's avatar
dogmaphobic committed
554 555
    // Now we go through the current configuration list and make sure any dynamic config has gone away
    QList<LinkConfiguration*>  _confToDelete;
Don Gagne's avatar
Don Gagne committed
556 557 558 559
    for (int i=0; i<_autoconnectConfigurations.count(); i++) {
        SerialConfiguration* linkConfig = _autoconnectConfigurations.value<SerialConfiguration*>(i);
        if (linkConfig) {
            if (!currentPorts.contains(linkConfig->portName())) {
Don Gagne's avatar
Don Gagne committed
560 561 562 563 564 565 566
                // We don't remove links which are still connected even though at this point the cable may
                // have been pulled. This is due to the fact that whether a serial port goes away from the
                // list when the cable is pulled is OS dependant. By not disconnecting in this case, we keep
                // things working the same across all OS.
                if (!linkConfig->link() || !linkConfig->link()->isConnected()) {
                    _confToDelete.append(linkConfig);
                }
dogmaphobic's avatar
dogmaphobic committed
567
            }
Don Gagne's avatar
Don Gagne committed
568 569
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
570 571
        }
    }
Don Gagne's avatar
Don Gagne committed
572

Don Gagne's avatar
Don Gagne committed
573
    // Now remove all configs that are gone
Don Gagne's avatar
Don Gagne committed
574
    foreach (LinkConfiguration* pDeleteConfig, _confToDelete) {
Don Gagne's avatar
Don Gagne committed
575
        qCDebug(LinkManagerLog) << "Removing unused autoconnect config" << pDeleteConfig->name();
Don Gagne's avatar
Don Gagne committed
576 577
        _autoconnectConfigurations.removeOne(pDeleteConfig);
        delete pDeleteConfig;
578
    }
579
#endif // __ios__
580 581
}

Don Gagne's avatar
Don Gagne committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
bool LinkManager::anyConnectedLinks(void)
{
    bool found = false;
    for (int i=0; i<_links.count(); i++) {
        LinkInterface* link = _links.value<LinkInterface*>(i);

        if (link && link->isConnected()) {
            found = true;
            break;
        }
    }
    return found;
}

bool LinkManager::anyActiveLinks(void)
597 598
{
    bool found = false;
Don Gagne's avatar
Don Gagne committed
599 600 601 602
    for (int i=0; i<_links.count(); i++) {
        LinkInterface* link = _links.value<LinkInterface*>(i);

        if (link && link->active()) {
603 604 605 606 607 608 609
            found = true;
            break;
        }
    }
    return found;
}

Don Gagne's avatar
Don Gagne committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
void LinkManager::_vehicleHeartbeatInfo(LinkInterface* link, int vehicleId, int vehicleMavlinkVersion, int vehicleFirmwareType, int vehicleType)
{
    if (!link->active() && !_ignoreVehicleIds.contains(vehicleId)) {
        qCDebug(LinkManagerLog) << "New heartbeat on link:vehicleId:vehicleMavlinkVersion:vehicleFirmwareType:vehicleType "
                                << link->getName()
                                << vehicleId
                                << vehicleMavlinkVersion
                                << vehicleFirmwareType
                                << vehicleType;

        if (vehicleId == _mavlinkProtocol->getSystemId()) {
            _app->showToolBarMessage(QString("Warning: A vehicle is using the same system id as QGroundControl: %1").arg(vehicleId));
        }

        QSettings settings;
        bool mavlinkVersionCheck = settings.value("VERSION_CHECK_ENABLED", true).toBool();
        if (mavlinkVersionCheck && vehicleMavlinkVersion != MAVLINK_VERSION) {
            _ignoreVehicleIds += vehicleId;
            _app->showToolBarMessage(QString("The MAVLink protocol version on vehicle #%1 and QGroundControl differ! "
                                                 "It is unsafe to use different MAVLink versions. "
                                                 "QGroundControl therefore refuses to connect to vehicle #%1, which sends MAVLink version %2 (QGroundControl uses version %3).").arg(vehicleId).arg(vehicleMavlinkVersion).arg(MAVLINK_VERSION));
            return;
        }

        bool previousAnyActiveLinks = anyActiveLinks();

        link->setActive(true);
        emit linkActive(link, vehicleId, vehicleFirmwareType, vehicleType);

        if (!previousAnyActiveLinks) {
            emit anyActiveLinksChanged(true);
641
        }
Don Gagne's avatar
Don Gagne committed
642 643 644 645 646 647
    }
}

void LinkManager::shutdown(void)
{
    setConnectionsSuspended("Shutdown");
Don Gagne's avatar
Don Gagne committed
648
    disconnectAll();
Don Gagne's avatar
Don Gagne committed
649 650 651 652 653 654 655 656 657 658 659 660
}

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

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

        _autoconnectUDP = autoconnect;
        emit autoconnectUDPChanged(autoconnect);
661
    }
Don Gagne's avatar
Don Gagne committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
}

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

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

        _autoconnectPixhawk = autoconnect;
        emit autoconnectPixhawkChanged(autoconnect);
    }

}

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

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

        _autoconnect3DRRadio = autoconnect;
        emit autoconnect3DRRadioChanged(autoconnect);
    }

}

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

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

        _autoconnectPX4Flow = autoconnect;
        emit autoconnectPX4FlowChanged(autoconnect);
    }

704
}
705 706 707 708 709 710 711 712 713 714 715 716

QStringList LinkManager::linkTypeStrings(void) const
{
    //-- Must follow same order as enum LinkType in LinkConfiguration.h
    static QStringList list;
    if(!list.size())
    {
#ifndef __ios__
        list += "Serial";
#endif
        list += "UDP";
        list += "TCP";
717
#ifdef __mobile__
dogmaphobic's avatar
dogmaphobic committed
718 719
        list += "Bluetooth";
#endif
dogmaphobic's avatar
dogmaphobic committed
720
#ifdef QT_DEBUG
721
        list += "Mock Link";
dogmaphobic's avatar
dogmaphobic committed
722 723
#endif
#ifndef __mobile__
724
        list += "Log Replay";
dogmaphobic's avatar
dogmaphobic committed
725
#endif
dogmaphobic's avatar
dogmaphobic committed
726
        Q_ASSERT(list.size() == (int)LinkConfiguration::TypeLast);
727 728 729 730
    }
    return list;
}

731
void LinkManager::_updateSerialPorts()
732
{
733 734
    _commPortList.clear();
    _commPortDisplayList.clear();
735
#ifndef __ios__
736 737
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
    foreach (const QSerialPortInfo &info, portList)
738
    {
739 740 741
        QString port = info.systemLocation().trimmed();
        _commPortList += port;
        _commPortDisplayList += SerialConfiguration::cleanPortDisplayname(port);
742 743
    }
#endif
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
}

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

QStringList LinkManager::serialPorts(void)
{
    if(!_commPortList.size())
    {
        _updateSerialPorts();
    }
761 762 763 764 765 766 767 768 769 770 771 772
    return _commPortList;
}

QStringList LinkManager::serialBaudRates(void)
{
#ifdef __ios__
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798

bool LinkManager::endConfigurationEditing(LinkConfiguration* config, LinkConfiguration* editedConfig)
{
    Q_ASSERT(config != NULL);
    Q_ASSERT(editedConfig != NULL);
    _fixUnnamed(editedConfig);
    config->copyFrom(editedConfig);
    saveLinkConfigurationList();
    // Tell link about changes (if any)
    config->updateSettings();
    // Discard temporary duplicate
    delete editedConfig;
    return true;
}

bool LinkManager::endCreateConfiguration(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
    _fixUnnamed(config);
    _linkConfigurations.append(config);
    saveLinkConfigurationList();
    return true;
}

LinkConfiguration* LinkManager::createConfiguration(int type, const QString& name)
{
dogmaphobic's avatar
dogmaphobic committed
799
#ifndef __ios__
800 801
    if((LinkConfiguration::LinkType)type == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
802
#endif
803 804 805 806 807 808
    return LinkConfiguration::createSettings(type, name);
}

LinkConfiguration* LinkManager::startConfigurationEditing(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
dogmaphobic's avatar
dogmaphobic committed
809
#ifndef __ios__
810 811
    if(config->type() == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
812
#endif
813 814 815 816 817 818 819 820 821 822 823 824 825
    return LinkConfiguration::duplicateSettings(config);
}


void LinkManager::_fixUnnamed(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
    //-- Check for "Unnamed"
    if (config->name() == "Unnamed") {
        switch(config->type()) {
#ifndef __ios__
            case LinkConfiguration::TypeSerial: {
                QString tname = dynamic_cast<SerialConfiguration*>(config)->portName();
826
#ifdef Q_OS_WIN
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
                tname.replace("\\\\.\\", "");
#else
                tname.replace("/dev/cu.", "");
                tname.replace("/dev/", "");
#endif
                config->setName(QString("Serial Device on %1").arg(tname));
                break;
                }
#endif
            case LinkConfiguration::TypeUdp:
                config->setName(
                    QString("UDP Link on Port %1").arg(dynamic_cast<UDPConfiguration*>(config)->localPort()));
                break;
            case LinkConfiguration::TypeTcp: {
                    TCPConfiguration* tconfig = dynamic_cast<TCPConfiguration*>(config);
                    if(tconfig) {
                        config->setName(
                            QString("TCP Link %1:%2").arg(tconfig->address().toString()).arg((int)tconfig->port()));
                    }
                }
                break;
848
#ifdef __mobile__
dogmaphobic's avatar
dogmaphobic committed
849 850 851
            case LinkConfiguration::TypeBluetooth: {
                    BluetoothConfiguration* tconfig = dynamic_cast<BluetoothConfiguration*>(config);
                    if(tconfig) {
852
                        config->setName(QString("%1 (Bluetooth Device)").arg(tconfig->device().name));
dogmaphobic's avatar
dogmaphobic committed
853 854 855 856
                    }
                }
                break;
#endif
dogmaphobic's avatar
dogmaphobic committed
857
#ifndef __mobile__
858
            case LinkConfiguration::TypeLogReplay: {
dogmaphobic's avatar
dogmaphobic committed
859 860 861 862
                    LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
                    if(tconfig) {
                        config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
                    }
863 864
                }
                break;
dogmaphobic's avatar
dogmaphobic committed
865
#endif
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
#ifdef QT_DEBUG
            case LinkConfiguration::TypeMock:
                config->setName(
                    QString("Mock Link"));
                break;
#endif
            case LinkConfiguration::TypeLast:
            default:
                break;
        }
    }
}

void LinkManager::removeConfiguration(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
    LinkInterface* iface = config->link();
    if(iface) {
        disconnectLink(iface);
    }
    // Remove configuration
    _linkConfigurations.removeOne(config);
    delete config;
    // Save list
    saveLinkConfigurationList();
}
892

893 894 895 896
bool LinkManager::isAutoconnectLink(LinkInterface* link)
{
    return _autoconnectConfigurations.contains(link->getLinkConfiguration());
}