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

10

pixhawk's avatar
pixhawk committed
11 12 13 14 15 16 17 18 19 20
/**
 * @file
 *   @brief Brief Description
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QList>
#include <QApplication>
21
#include <QDebug>
22
#include <QSignalSpy>
dogmaphobic's avatar
dogmaphobic committed
23 24

#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
25
#include "QGCSerialPortInfo.h"
dogmaphobic's avatar
dogmaphobic committed
26
#endif
27

28
#include "LinkManager.h"
29
#include "QGCApplication.h"
Don Gagne's avatar
Don Gagne committed
30 31
#include "UDPLink.h"
#include "TCPLink.h"
dogmaphobic's avatar
dogmaphobic committed
32
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
33 34
#include "BluetoothLink.h"
#endif
35

Don Gagne's avatar
Don Gagne committed
36 37 38 39
#ifndef __mobile__
    #include "GPSManager.h"
#endif

Don Gagne's avatar
Don Gagne committed
40
QGC_LOGGING_CATEGORY(LinkManagerLog, "LinkManagerLog")
Don Gagne's avatar
Don Gagne committed
41 42 43 44 45 46 47
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
48
const char* LinkManager::_autoconnectRTKGPSKey =    "AutoconnectRTKGPS";
Don Gagne's avatar
Don Gagne committed
49
const char* LinkManager::_defaultUPDLinkName =      "Default UDP Link";
50

51 52 53 54 55 56 57 58
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

59 60
LinkManager::LinkManager(QGCApplication* app)
    : QGCTool(app)
61 62 63
    , _configUpdateSuspended(false)
    , _configurationsLoaded(false)
    , _connectionsSuspended(false)
64
    , _mavlinkChannelsUsedBitMask(1)    // We never use channel 0 to avoid sequence numbering problems
65
    , _mavlinkProtocol(NULL)
Don Gagne's avatar
Don Gagne committed
66 67 68 69
    , _autoconnectUDP(true)
    , _autoconnectPixhawk(true)
    , _autoconnect3DRRadio(true)
    , _autoconnectPX4Flow(true)
Don Gagne's avatar
Don Gagne committed
70
    , _autoconnectRTKGPS(true)
pixhawk's avatar
pixhawk committed
71
{
Don Gagne's avatar
Don Gagne committed
72 73 74 75 76
    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;
77

Don Gagne's avatar
Don Gagne committed
78 79 80 81 82
    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();
Don Gagne's avatar
Don Gagne committed
83
    _autoconnectRTKGPS =    settings.value(_autoconnectRTKGPSKey, true).toBool();
Don Gagne's avatar
Don Gagne committed
84

Don Gagne's avatar
Don Gagne committed
85
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
86 87 88
    _activeLinkCheckTimer.setInterval(_activeLinkCheckTimeoutMSecs);
    _activeLinkCheckTimer.setSingleShot(false);
    connect(&_activeLinkCheckTimer, &QTimer::timeout, this, &LinkManager::_activeLinkCheck);
Don Gagne's avatar
Don Gagne committed
89
#endif
pixhawk's avatar
pixhawk committed
90 91 92 93
}

LinkManager::~LinkManager()
{
94

pixhawk's avatar
pixhawk committed
95 96
}

97 98 99 100 101 102
void LinkManager::setToolbox(QGCToolbox *toolbox)
{
   QGCTool::setToolbox(toolbox);

   _mavlinkProtocol = _toolbox->mavlinkProtocol();

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

106 107
}

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

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

172
void LinkManager::_addLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
173
{
Don Gagne's avatar
Don Gagne committed
174 175 176 177
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }
178

Don Gagne's avatar
Don Gagne committed
179 180 181
    if (!link) {
        return;
    }
182

Don Gagne's avatar
Don Gagne committed
183
    if (!_links.contains(link)) {
184 185
        bool channelSet = false;

186 187
        // Find a mavlink channel to use for this link
        for (int i=0; i<32; i++) {
188
            if (!(_mavlinkChannelsUsedBitMask & 1 << i)) {
189
                mavlink_reset_channel_status(i);
190 191
                link->_setMavlinkChannel(i);
                _mavlinkChannelsUsedBitMask |= i << i;
192
                channelSet = true;
193 194 195
                break;
            }
        }
196

197 198 199 200
        if (!channelSet) {
            qWarning() << "Ran out of mavlink channels";
        }

Don Gagne's avatar
Don Gagne committed
201
        _links.append(link);
202 203
        emit newLink(link);
    }
204

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

208
    _mavlinkProtocol->resetMetadataForLink(link);
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 221
    // 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
222
        disconnectLink(_links.value<LinkInterface*>(i));
223
    }
pixhawk's avatar
pixhawk committed
224 225 226 227
}

bool LinkManager::connectLink(LinkInterface* link)
{
228
    Q_ASSERT(link);
229

230 231 232 233
    if (_connectionsSuspendedMsg()) {
        return false;
    }

234
    return link->_connect();
pixhawk's avatar
pixhawk committed
235 236
}

Don Gagne's avatar
Don Gagne committed
237
void LinkManager::disconnectLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
238
{
239 240 241
    if (!link || !_links.contains(link)) {
        return;
    }
Don Gagne's avatar
Don Gagne committed
242

Don Gagne's avatar
Don Gagne committed
243 244
    link->_disconnect();
    LinkConfiguration* config = link->getLinkConfiguration();
245 246 247 248
    if (config) {
        if (_autoconnectConfigurations.contains(config)) {
            config->setLink(NULL);
        }
249
    }
Don Gagne's avatar
Don Gagne committed
250
    _deleteLink(link);
251
    if (_autoconnectConfigurations.contains(config)) {
252
        qCDebug(LinkManagerLog) << "Removing disconnected autoconnect config" << config->name();
253 254 255
        _autoconnectConfigurations.removeOne(config);
        delete config;
    }
pixhawk's avatar
pixhawk committed
256 257
}

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

    if (!link) {
        return;
    }
268

269 270
    // Free up the mavlink channel associated with this link
    _mavlinkChannelsUsedBitMask &= ~(1 << link->getMavlinkChannel());
271

Don Gagne's avatar
Don Gagne committed
272 273
    _links.removeOne(link);
    delete link;
274

Don Gagne's avatar
Don Gagne committed
275
    // Emit removal of link
276
    emit linkDeleted(link);
pixhawk's avatar
pixhawk committed
277 278
}

279 280 281 282 283
/// @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) {
284
        qgcApp()->showMessage(QString("Connect not allowed: %1").arg(_connectionsSuspendedReason));
285 286 287 288 289 290 291 292 293 294 295 296
        return true;
    } else {
        return false;
    }
}

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

298 299 300 301 302 303 304 305 306
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

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

308 309 310 311 312 313
void LinkManager::_linkConnectionRemoved(LinkInterface* link)
{
    // Link has been removed from system, disconnect it automatically
    disconnectLink(link);
}

314 315 316 317 318 319 320 321 322
void LinkManager::suspendConfigurationUpdates(bool suspend)
{
    _configUpdateSuspended = suspend;
}

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

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

    if(linksChanged) {
433
        emit linkConfigurationsChanged();
434 435
    }
    // Enable automatic Serial PX4/3DR Radio hunting
436 437 438
    _configurationsLoaded = true;
}

dogmaphobic's avatar
dogmaphobic committed
439
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
440
SerialConfiguration* LinkManager::_autoconnectConfigurationsContainsPort(const QString& portName)
441 442
{
    QString searchPort = portName.trimmed();
Don Gagne's avatar
Don Gagne committed
443 444 445 446 447 448 449

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

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

Don Gagne's avatar
Don Gagne committed
459
void LinkManager::_updateAutoConnectLinks(void)
460
{
Don Gagne's avatar
Don Gagne committed
461
    if (_connectionsSuspended || qgcApp()->runningUnitTests()) {
462 463
        return;
    }
Don Gagne's avatar
Don Gagne committed
464

Don Gagne's avatar
Don Gagne committed
465 466 467 468 469 470 471 472 473
    // 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;
        }
    }
Don Gagne's avatar
Don Gagne committed
474
    if (!foundUDP && _autoconnectUDP) {
Don Gagne's avatar
Don Gagne committed
475
        qCDebug(LinkManagerLog) << "New auto-connect UDP port added";
Don Gagne's avatar
Don Gagne committed
476 477 478
        UDPConfiguration* udpConfig = new UDPConfiguration(_defaultUPDLinkName);
        udpConfig->setLocalPort(QGC_UDP_LOCAL_PORT);
        udpConfig->setDynamic(true);
479
        _linkConfigurations.append(udpConfig);
Don Gagne's avatar
Don Gagne committed
480
        createConnectedLink(udpConfig);
481
        emit linkConfigurationsChanged();
Don Gagne's avatar
Don Gagne committed
482 483
    }

484
#ifndef __ios__
dogmaphobic's avatar
dogmaphobic committed
485
    QStringList currentPorts;
Don Gagne's avatar
Don Gagne committed
486
    QList<QGCSerialPortInfo> portList = QGCSerialPortInfo::availablePorts();
Don Gagne's avatar
Don Gagne committed
487

488
    // Iterate Comm Ports
Don Gagne's avatar
Don Gagne committed
489
    foreach (QGCSerialPortInfo portInfo, portList) {
Don Gagne's avatar
Don Gagne committed
490 491 492 493 494 495 496 497 498
        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
499 500
        // Save port name
        currentPorts << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
501 502 503 504 505 506

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

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

511 512 513 514 515 516 517
            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();
518 519
                _autoconnectWaitList[portInfo.systemLocation()] = 1;
            } else if (++_autoconnectWaitList[portInfo.systemLocation()] * _autoconnectUpdateTimerMSecs > _autoconnectConnectDelayMSecs) {
Don Gagne's avatar
Don Gagne committed
520 521
                SerialConfiguration* pSerialConfig = NULL;

522
                _autoconnectWaitList.remove(portInfo.systemLocation());
523

Don Gagne's avatar
Don Gagne committed
524 525 526
                switch (boardType) {
                case QGCSerialPortInfo::BoardTypePX4FMUV1:
                case QGCSerialPortInfo::BoardTypePX4FMUV2:
527
                case QGCSerialPortInfo::BoardTypePX4FMUV4:
Don Gagne's avatar
Don Gagne committed
528 529
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("Pixhawk on %1").arg(portInfo.portName().trimmed()));
530
                        pSerialConfig->setUsbDirect(true);
Don Gagne's avatar
Don Gagne committed
531
                    }
Don Gagne's avatar
Don Gagne committed
532 533
                    break;
                case QGCSerialPortInfo::BoardTypeAeroCore:
Don Gagne's avatar
Don Gagne committed
534 535
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("AeroCore on %1").arg(portInfo.portName().trimmed()));
536
                        pSerialConfig->setUsbDirect(true);
Don Gagne's avatar
Don Gagne committed
537
                    }
Don Gagne's avatar
Don Gagne committed
538
                    break;
Henry Zhang's avatar
Henry Zhang committed
539 540 541 542 543 544
                case QGCSerialPortInfo::BoardTypeMINDPXFMUV2:
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("MindPX on %1").arg(portInfo.portName().trimmed()));
                        pSerialConfig->setUsbDirect(true);
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
545
                case QGCSerialPortInfo::BoardTypePX4Flow:
Don Gagne's avatar
Don Gagne committed
546 547 548
                    if (_autoconnectPX4Flow) {
                        pSerialConfig = new SerialConfiguration(QString("PX4Flow on %1").arg(portInfo.portName().trimmed()));
                    }
Don Gagne's avatar
Don Gagne committed
549
                    break;
Don Gagne's avatar
Don Gagne committed
550
                case QGCSerialPortInfo::BoardTypeSikRadio:
Don Gagne's avatar
Don Gagne committed
551
                    if (_autoconnect3DRRadio) {
552
                        pSerialConfig = new SerialConfiguration(QString("SiK Radio on %1").arg(portInfo.portName().trimmed()));
Don Gagne's avatar
Don Gagne committed
553 554
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
555 556 557 558 559 560 561 562
#ifndef __mobile__
                case QGCSerialPortInfo::BoardTypeRTKGPS:
                    if (_autoconnectRTKGPS && !_toolbox->gpsManager()->connected()) {
                        qCDebug(LinkManagerLog) << "RTK GPS auto-connected";
                        _toolbox->gpsManager()->connectGPS(portInfo.systemLocation());
                    }
                    break;
#endif
Don Gagne's avatar
Don Gagne committed
563 564
                default:
                    qWarning() << "Internal error";
Don Gagne's avatar
Don Gagne committed
565
                    continue;
dogmaphobic's avatar
dogmaphobic committed
566
                }
Don Gagne's avatar
Don Gagne committed
567

Don Gagne's avatar
Don Gagne committed
568 569
                if (pSerialConfig) {
                    qCDebug(LinkManagerLog) << "New auto-connect port added: " << pSerialConfig->name() << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
570
                    pSerialConfig->setBaud(boardType == QGCSerialPortInfo::BoardTypeSikRadio ? 57600 : 115200);
Don Gagne's avatar
Don Gagne committed
571 572 573
                    pSerialConfig->setDynamic(true);
                    pSerialConfig->setPortName(portInfo.systemLocation());
                    _autoconnectConfigurations.append(pSerialConfig);
Don Gagne's avatar
Don Gagne committed
574
                    createConnectedLink(pSerialConfig);
Don Gagne's avatar
Don Gagne committed
575
                }
dogmaphobic's avatar
dogmaphobic committed
576 577 578
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
579

dogmaphobic's avatar
dogmaphobic committed
580 581
    // 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
582 583 584 585
    for (int i=0; i<_autoconnectConfigurations.count(); i++) {
        SerialConfiguration* linkConfig = _autoconnectConfigurations.value<SerialConfiguration*>(i);
        if (linkConfig) {
            if (!currentPorts.contains(linkConfig->portName())) {
586 587 588 589 590 591 592 593 594
                if (linkConfig->link()) {
                    if (linkConfig->link()->isConnected()) {
                        if (linkConfig->link()->active()) {
                            // 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
595
                }
596
                _confToDelete.append(linkConfig);
dogmaphobic's avatar
dogmaphobic committed
597
            }
Don Gagne's avatar
Don Gagne committed
598 599
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
600 601
        }
    }
Don Gagne's avatar
Don Gagne committed
602

Don Gagne's avatar
Don Gagne committed
603
    // Now remove all configs that are gone
Don Gagne's avatar
Don Gagne committed
604
    foreach (LinkConfiguration* pDeleteConfig, _confToDelete) {
Don Gagne's avatar
Don Gagne committed
605
        qCDebug(LinkManagerLog) << "Removing unused autoconnect config" << pDeleteConfig->name();
Don Gagne's avatar
Don Gagne committed
606
        _autoconnectConfigurations.removeOne(pDeleteConfig);
607 608 609
        if (pDeleteConfig->link()) {
            disconnectLink(pDeleteConfig->link());
        }
Don Gagne's avatar
Don Gagne committed
610
        delete pDeleteConfig;
611
    }
612
#endif // __ios__
613 614
}

Don Gagne's avatar
Don Gagne committed
615 616 617
void LinkManager::shutdown(void)
{
    setConnectionsSuspended("Shutdown");
Don Gagne's avatar
Don Gagne committed
618
    disconnectAll();
Don Gagne's avatar
Don Gagne committed
619 620
}

Don Gagne's avatar
Don Gagne committed
621
bool LinkManager::_setAutoconnectWorker(bool& currentAutoconnect, bool newAutoconnect, const char* autoconnectKey)
Don Gagne's avatar
Don Gagne committed
622
{
Don Gagne's avatar
Don Gagne committed
623
    if (currentAutoconnect != newAutoconnect) {
Don Gagne's avatar
Don Gagne committed
624 625 626
        QSettings settings;

        settings.beginGroup(_settingsGroup);
Don Gagne's avatar
Don Gagne committed
627 628 629 630 631 632 633
        settings.setValue(autoconnectKey, newAutoconnect);
        currentAutoconnect = newAutoconnect;
        return true;
    }

    return false;
}
Don Gagne's avatar
Don Gagne committed
634

Don Gagne's avatar
Don Gagne committed
635 636 637
void LinkManager::setAutoconnectUDP(bool autoconnect)
{
    if (_setAutoconnectWorker(_autoconnectUDP, autoconnect, _autoconnectUDPKey)) {
Don Gagne's avatar
Don Gagne committed
638
        emit autoconnectUDPChanged(autoconnect);
639
    }
Don Gagne's avatar
Don Gagne committed
640 641 642 643
}

void LinkManager::setAutoconnectPixhawk(bool autoconnect)
{
Don Gagne's avatar
Don Gagne committed
644
    if (_setAutoconnectWorker(_autoconnectPixhawk, autoconnect, _autoconnectPixhawkKey)) {
Don Gagne's avatar
Don Gagne committed
645 646 647 648 649 650
        emit autoconnectPixhawkChanged(autoconnect);
    }
}

void LinkManager::setAutoconnect3DRRadio(bool autoconnect)
{
Don Gagne's avatar
Don Gagne committed
651
    if (_setAutoconnectWorker(_autoconnect3DRRadio, autoconnect, _autoconnect3DRRadioKey)) {
Don Gagne's avatar
Don Gagne committed
652 653 654 655 656 657
        emit autoconnect3DRRadioChanged(autoconnect);
    }
}

void LinkManager::setAutoconnectPX4Flow(bool autoconnect)
{
Don Gagne's avatar
Don Gagne committed
658
    if (_setAutoconnectWorker(_autoconnectPX4Flow, autoconnect, _autoconnectPX4FlowKey)) {
Don Gagne's avatar
Don Gagne committed
659 660
        emit autoconnectPX4FlowChanged(autoconnect);
    }
Don Gagne's avatar
Don Gagne committed
661
}
Don Gagne's avatar
Don Gagne committed
662

Don Gagne's avatar
Don Gagne committed
663 664 665 666 667
void LinkManager::setAutoconnectRTKGPS(bool autoconnect)
{
    if (_setAutoconnectWorker(_autoconnectRTKGPS, autoconnect, _autoconnectRTKGPSKey)) {
        emit autoconnectRTKGPSChanged(autoconnect);
    }
668
}
669 670 671 672 673 674 675 676 677 678 679 680

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";
dogmaphobic's avatar
dogmaphobic committed
681
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
682 683
        list += "Bluetooth";
#endif
dogmaphobic's avatar
dogmaphobic committed
684
#ifdef QT_DEBUG
685
        list += "Mock Link";
dogmaphobic's avatar
dogmaphobic committed
686 687
#endif
#ifndef __mobile__
688
        list += "Log Replay";
dogmaphobic's avatar
dogmaphobic committed
689
#endif
dogmaphobic's avatar
dogmaphobic committed
690
        Q_ASSERT(list.size() == (int)LinkConfiguration::TypeLast);
691 692 693 694
    }
    return list;
}

695
void LinkManager::_updateSerialPorts()
696
{
697 698
    _commPortList.clear();
    _commPortDisplayList.clear();
699
#ifndef __ios__
700 701
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
    foreach (const QSerialPortInfo &info, portList)
702
    {
703 704 705
        QString port = info.systemLocation().trimmed();
        _commPortList += port;
        _commPortDisplayList += SerialConfiguration::cleanPortDisplayname(port);
706 707
    }
#endif
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
}

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

QStringList LinkManager::serialPorts(void)
{
    if(!_commPortList.size())
    {
        _updateSerialPorts();
    }
725 726 727 728 729 730 731 732 733 734 735 736
    return _commPortList;
}

QStringList LinkManager::serialBaudRates(void)
{
#ifdef __ios__
    QStringList foo;
    return foo;
#else
    return SerialConfiguration::supportedBaudRates();
#endif
}
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762

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
763
#ifndef __ios__
764 765
    if((LinkConfiguration::LinkType)type == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
766
#endif
767 768 769 770 771 772
    return LinkConfiguration::createSettings(type, name);
}

LinkConfiguration* LinkManager::startConfigurationEditing(LinkConfiguration* config)
{
    Q_ASSERT(config != NULL);
dogmaphobic's avatar
dogmaphobic committed
773
#ifndef __ios__
774 775
    if(config->type() == LinkConfiguration::TypeSerial)
        _updateSerialPorts();
dogmaphobic's avatar
dogmaphobic committed
776
#endif
777 778 779 780 781 782 783 784 785 786 787 788 789
    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();
790
#ifdef Q_OS_WIN
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
                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;
dogmaphobic's avatar
dogmaphobic committed
812
#ifdef QGC_ENABLE_BLUETOOTH
dogmaphobic's avatar
dogmaphobic committed
813 814 815
            case LinkConfiguration::TypeBluetooth: {
                    BluetoothConfiguration* tconfig = dynamic_cast<BluetoothConfiguration*>(config);
                    if(tconfig) {
816
                        config->setName(QString("%1 (Bluetooth Device)").arg(tconfig->device().name));
dogmaphobic's avatar
dogmaphobic committed
817 818 819 820
                    }
                }
                break;
#endif
dogmaphobic's avatar
dogmaphobic committed
821
#ifndef __mobile__
822
            case LinkConfiguration::TypeLogReplay: {
dogmaphobic's avatar
dogmaphobic committed
823 824 825 826
                    LogReplayLinkConfiguration* tconfig = dynamic_cast<LogReplayLinkConfiguration*>(config);
                    if(tconfig) {
                        config->setName(QString("Log Replay %1").arg(tconfig->logFilenameShort()));
                    }
827 828
                }
                break;
dogmaphobic's avatar
dogmaphobic committed
829
#endif
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
#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();
}
856

857 858 859 860
bool LinkManager::isAutoconnectLink(LinkInterface* link)
{
    return _autoconnectConfigurations.contains(link->getLinkConfiguration());
}
dogmaphobic's avatar
dogmaphobic committed
861 862 863 864 865

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

Don Gagne's avatar
Don Gagne committed
867
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
868 869
void LinkManager::_activeLinkCheck(void)
{
870
    SerialLink* link = NULL;
Don Gagne's avatar
Don Gagne committed
871 872 873
    bool found = false;

    if (_activeLinkCheckList.count() != 0) {
874
        link = _activeLinkCheckList.takeFirst();
Don Gagne's avatar
Don Gagne committed
875 876 877 878 879 880 881 882 883 884
        if (_links.contains(link) && link->isConnected()) {
            // 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;
                }
            }
885 886
        } else {
            link = NULL;
Don Gagne's avatar
Don Gagne committed
887 888 889 890 891 892 893
        }
    }

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

894 895 896
    if (!found && link) {
        // See if we can get an NSH prompt on this link
        bool foundNSHPrompt = false;
897
        link->writeBytesSafe("\r", 1);
898 899 900 901 902 903 904 905 906 907 908
        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 ?
                                  QStringLiteral("Please check to make sure you have an SD Card inserted in your Vehicle and try again.") :
                                  QStringLiteral("Your Vehicle is not responding. If this continues shutdown QGroundControl, restart the Vehicle letting it boot completely, then start QGroundControl."));
Don Gagne's avatar
Don Gagne committed
909 910
    }
}
Don Gagne's avatar
Don Gagne committed
911
#endif