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

Don Gagne's avatar
Don Gagne committed
48
QGC_LOGGING_CATEGORY(LinkManagerLog, "LinkManagerLog")
Don Gagne's avatar
Don Gagne committed
49 50 51 52 53 54 55
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";
56

57 58
LinkManager::LinkManager(QGCApplication* app)
    : QGCTool(app)
59 60 61
    , _configUpdateSuspended(false)
    , _configurationsLoaded(false)
    , _connectionsSuspended(false)
62
    , _mavlinkChannelsUsedBitMask(0)
63
    , _mavlinkProtocol(NULL)
Don Gagne's avatar
Don Gagne committed
64 65 66 67 68 69
    , _autoconnectUDPConfig(NULL)
    , _autoconnectUDP(true)
    , _autoconnectPixhawk(true)
    , _autoconnect3DRRadio(true)
    , _autoconnectPX4Flow(true)

pixhawk's avatar
pixhawk committed
70
{
Don Gagne's avatar
Don Gagne committed
71 72 73 74 75
    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;
76

Don Gagne's avatar
Don Gagne committed
77 78 79 80 81
    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
82 83 84 85
}

LinkManager::~LinkManager()
{
Don Gagne's avatar
Don Gagne committed
86 87
    if (anyActiveLinks()) {
        qWarning() << "Why are there still active links?";
88
    }
pixhawk's avatar
pixhawk committed
89 90
}

91 92 93 94 95
void LinkManager::setToolbox(QGCToolbox *toolbox)
{
   QGCTool::setToolbox(toolbox);

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

#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
99
    connect(&_portListTimer, &QTimer::timeout, this, &LinkManager::_updateAutoConnectLinks);
100 101 102 103
    _portListTimer.start(1000);
#endif
}

Don Gagne's avatar
Don Gagne committed
104
LinkInterface* LinkManager::createConnectedLink(LinkConfiguration* config, bool autoconnectLink)
105 106 107 108
{
    Q_ASSERT(config);
    LinkInterface* pLink = NULL;
    switch(config->type()) {
dogmaphobic's avatar
dogmaphobic committed
109
#ifndef __ios__
110 111 112
        case LinkConfiguration::TypeSerial:
            pLink = new SerialLink(dynamic_cast<SerialConfiguration*>(config));
            break;
dogmaphobic's avatar
dogmaphobic committed
113
#endif
114 115 116
        case LinkConfiguration::TypeUdp:
            pLink = new UDPLink(dynamic_cast<UDPConfiguration*>(config));
            break;
117 118 119
        case LinkConfiguration::TypeTcp:
            pLink = new TCPLink(dynamic_cast<TCPConfiguration*>(config));
            break;
Don Gagne's avatar
Don Gagne committed
120 121 122
        case LinkConfiguration::TypeLogReplay:
            pLink = new LogReplayLink(dynamic_cast<LogReplayLinkConfiguration*>(config));
            break;
123
#ifdef QT_DEBUG
124 125 126
        case LinkConfiguration::TypeMock:
            pLink = new MockLink(dynamic_cast<MockConfiguration*>(config));
            break;
127
#endif
128 129
    }
    if(pLink) {
Don Gagne's avatar
Don Gagne committed
130
        pLink->setAutoconnect(autoconnectLink);
131 132
        _addLink(pLink);
        connectLink(pLink);
133 134 135 136
    }
    return pLink;
}

Don Gagne's avatar
Don Gagne committed
137
LinkInterface* LinkManager::createConnectedLink(const QString& name, bool autoconnectLink)
138 139 140
{
    Q_ASSERT(name.isEmpty() == false);
    for(int i = 0; i < _linkConfigurations.count(); i++) {
Don Gagne's avatar
Don Gagne committed
141
        LinkConfiguration* conf = _linkConfigurations.value<LinkConfiguration*>(i);
142
        if(conf && conf->name() == name)
Don Gagne's avatar
Don Gagne committed
143
            return createConnectedLink(conf, autoconnectLink);
144 145 146 147
    }
    return NULL;
}

148
void LinkManager::_addLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
149
{
Don Gagne's avatar
Don Gagne committed
150 151 152 153
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }
154

Don Gagne's avatar
Don Gagne committed
155 156 157
    if (!link) {
        return;
    }
158

Don Gagne's avatar
Don Gagne committed
159
    if (!_links.contains(link)) {
160 161 162
        // Find a mavlink channel to use for this link
        for (int i=0; i<32; i++) {
            if (!(_mavlinkChannelsUsedBitMask && 1 << i)) {
163
                mavlink_reset_channel_status(i);
164 165 166 167 168 169
                link->_setMavlinkChannel(i);
                _mavlinkChannelsUsedBitMask |= i << i;
                break;
            }
        }
        
Don Gagne's avatar
Don Gagne committed
170
        _links.append(link);
171 172
        emit newLink(link);
    }
173

174 175
    // MainWindow may be around when doing things like running unit tests
    if (MainWindow::instance()) {
176
        connect(link, &LinkInterface::communicationError, _app, &QGCApplication::criticalMessageBoxOnMainThread);
177
    }
178

179 180 181 182
    connect(link, &LinkInterface::bytesReceived,    _mavlinkProtocol, &MAVLinkProtocol::receiveBytes);
    connect(link, &LinkInterface::connected,        _mavlinkProtocol, &MAVLinkProtocol::linkConnected);
    connect(link, &LinkInterface::disconnected,     _mavlinkProtocol, &MAVLinkProtocol::linkDisconnected);
    _mavlinkProtocol->resetMetadataForLink(link);
183

184
    connect(link, &LinkInterface::connected,    this, &LinkManager::_linkConnected);
185
    connect(link, &LinkInterface::disconnected, this, &LinkManager::_linkDisconnected);
186
}
pixhawk's avatar
pixhawk committed
187

Don Gagne's avatar
Don Gagne committed
188
void LinkManager::disconnectAll(bool disconnectAutoconnectLink)
pixhawk's avatar
pixhawk committed
189
{
Don Gagne's avatar
Don Gagne committed
190 191 192
    // Walk list in reverse order to preserve indices during delete
    for (int i=_links.count()-1; i>=0; i--) {
        disconnectLink(_links.value<LinkInterface*>(i), disconnectAutoconnectLink);
193
    }
pixhawk's avatar
pixhawk committed
194 195 196 197
}

bool LinkManager::connectLink(LinkInterface* link)
{
198
    Q_ASSERT(link);
199

200 201 202 203
    if (_connectionsSuspendedMsg()) {
        return false;
    }

Don Gagne's avatar
Don Gagne committed
204 205 206
    bool previousAnyConnectedLinks = anyConnectedLinks();
    bool previousAnyNonAutoconnectConnectedLinks = anyNonAutoconnectConnectedLinks();

207
    if (link->_connect()) {
Don Gagne's avatar
Don Gagne committed
208 209 210 211 212 213
        if (!previousAnyConnectedLinks) {
            emit anyConnectedLinksChanged(true);
        }
        if (!previousAnyNonAutoconnectConnectedLinks && anyNonAutoconnectConnectedLinks()) {
            emit anyNonAutoconnectConnectedLinksChanged(true);
        }
214 215 216 217
        return true;
    } else {
        return false;
    }
pixhawk's avatar
pixhawk committed
218 219
}

Don Gagne's avatar
Don Gagne committed
220
bool LinkManager::disconnectLink(LinkInterface* link, bool disconnectAutoconnectLink)
pixhawk's avatar
pixhawk committed
221
{
222
    Q_ASSERT(link);
Don Gagne's avatar
Don Gagne committed
223 224 225

    if (disconnectAutoconnectLink || !link->autoconnect()) {
        link->_disconnect();
226 227 228 229
        LinkConfiguration* config = link->getLinkConfiguration();
        if(config) {
            config->setLink(NULL);
        }
230
        _deleteLink(link);
231 232
        return true;
    }
Don Gagne's avatar
Don Gagne committed
233 234

    return false;
pixhawk's avatar
pixhawk committed
235 236
}

237
void LinkManager::_deleteLink(LinkInterface* link)
238
{
Don Gagne's avatar
Don Gagne committed
239 240 241 242 243 244 245 246
    if (thread() != QThread::currentThread()) {
        qWarning() << "_deleteLink called from incorrect thread";
        return;
    }

    if (!link) {
        return;
    }
247

248 249
    // Free up the mavlink channel associated with this link
    _mavlinkChannelsUsedBitMask &= ~(1 << link->getMavlinkChannel());
250

Don Gagne's avatar
Don Gagne committed
251 252
    _links.removeOne(link);
    delete link;
253

Don Gagne's avatar
Don Gagne committed
254
    // Emit removal of link
255
    emit linkDeleted(link);
pixhawk's avatar
pixhawk committed
256 257
}

258 259 260 261 262
/// @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
263 264
        QGCMessageBox::information(tr("Connect not allowed"),
                                   tr("Connect not allowed: %1").arg(_connectionsSuspendedReason));
265 266 267 268 269 270 271 272 273 274 275 276
        return true;
    } else {
        return false;
    }
}

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

278 279 280 281 282 283 284 285 286
void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

void LinkManager::_linkDisconnected(void)
{
    emit linkDisconnected((LinkInterface*)sender());
}
287 288 289 290 291 292 293 294 295 296

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

void LinkManager::saveLinkConfigurationList()
{
    QSettings settings;
    settings.remove(LinkConfiguration::settingsRoot());
Don Gagne's avatar
Don Gagne committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

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

        if (linkConfig) {
            if(!linkConfig->isDynamic())
            {
                QString root = LinkConfiguration::settingsRoot();
                root += QString("/Link%1").arg(i);
                settings.setValue(root + "/name", linkConfig->name());
                settings.setValue(root + "/type", linkConfig->type());
                // Have the instance save its own values
                linkConfig->saveSettings(settings, root);
            }
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
313
        }
314
    }
Don Gagne's avatar
Don Gagne committed
315

dogmaphobic's avatar
dogmaphobic committed
316
    QString root(LinkConfiguration::settingsRoot());
Don Gagne's avatar
Don Gagne committed
317
    settings.setValue(root + "/count", _linkConfigurations.count());
318 319 320 321 322
    emit linkConfigurationChanged();
}

void LinkManager::loadLinkConfigurationList()
{
323
    bool linksChanged = false;
324
    QSettings settings;
Don Gagne's avatar
Don Gagne committed
325

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    // 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();
                if(type < LinkConfiguration::TypeLast) {
                    if(settings.contains(root + "/name")) {
                        QString name = settings.value(root + "/name").toString();
                        if(!name.isEmpty()) {
                            LinkConfiguration* pLink = NULL;
                            switch(type) {
dogmaphobic's avatar
dogmaphobic committed
341
#ifndef __ios__
342 343 344
                                case LinkConfiguration::TypeSerial:
                                    pLink = (LinkConfiguration*)new SerialConfiguration(name);
                                    break;
dogmaphobic's avatar
dogmaphobic committed
345
#endif
346 347 348
                                case LinkConfiguration::TypeUdp:
                                    pLink = (LinkConfiguration*)new UDPConfiguration(name);
                                    break;
349 350 351
                                case LinkConfiguration::TypeTcp:
                                    pLink = (LinkConfiguration*)new TCPConfiguration(name);
                                    break;
Don Gagne's avatar
Don Gagne committed
352 353 354
                                case LinkConfiguration::TypeLogReplay:
                                    pLink = (LinkConfiguration*)new LogReplayLinkConfiguration(name);
                                    break;
355
#ifdef QT_DEBUG
356 357 358
                                case LinkConfiguration::TypeMock:
                                    pLink = (LinkConfiguration*)new MockConfiguration(name);
                                    break;
359
#endif
360 361 362 363
                            }
                            if(pLink) {
                                // Have the instance load its own values
                                pLink->loadSettings(settings, root);
Don Gagne's avatar
Don Gagne committed
364
                                _linkConfigurations.append(pLink);
365
                                linksChanged = true;
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
                            }
                        } else {
                            qWarning() << "Link Configuration " << root << " has an empty name." ;
                        }
                    } else {
                        qWarning() << "Link Configuration " << root << " has no name." ;
                    }
                } else {
                    qWarning() << "Link Configuration " << root << " an invalid type: " << type;
                }
            } else {
                qWarning() << "Link Configuration " << root << " has no type." ;
            }
        }
    }
381 382 383
    
    // Debug buids always add MockLink automatically
#ifdef QT_DEBUG
384
    MockConfiguration* pMock = new MockConfiguration("Mock Link PX4");
385
    pMock->setDynamic(true);
Don Gagne's avatar
Don Gagne committed
386
    _linkConfigurations.append(pMock);
387
    linksChanged = true;
388
#endif
389 390 391 392

    if(linksChanged) {
        emit linkConfigurationChanged();
    }
Don Gagne's avatar
Don Gagne committed
393

394
    // Enable automatic Serial PX4/3DR Radio hunting
395 396 397
    _configurationsLoaded = true;
}

dogmaphobic's avatar
dogmaphobic committed
398
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
399
SerialConfiguration* LinkManager::_autoconnectConfigurationsContainsPort(const QString& portName)
400 401
{
    QString searchPort = portName.trimmed();
Don Gagne's avatar
Don Gagne committed
402 403 404 405 406 407 408

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

        if (linkConfig) {
            if (linkConfig->portName() == searchPort) {
                return linkConfig;
409
            }
Don Gagne's avatar
Don Gagne committed
410 411
        } else {
            qWarning() << "Internal error";
412 413 414 415
        }
    }
    return NULL;
}
dogmaphobic's avatar
dogmaphobic committed
416
#endif
417

dogmaphobic's avatar
dogmaphobic committed
418
#ifndef __ios__
Don Gagne's avatar
Don Gagne committed
419
void LinkManager::_updateAutoConnectLinks(void)
420
{
Don Gagne's avatar
Don Gagne committed
421
    if (_connectionsSuspended || qgcApp()->runningUnitTests()) {
422 423
        return;
    }
Don Gagne's avatar
Don Gagne committed
424 425 426 427 428 429 430 431 432

    if (_autoconnectUDP && !_autoconnectUDPConfig) {
        _autoconnectUDPConfig = new UDPConfiguration("Default UDP Link");
        _autoconnectUDPConfig->setLocalPort(QGC_UDP_LOCAL_PORT);
        _autoconnectUDPConfig->setDynamic(true);
        createConnectedLink(_autoconnectUDPConfig, true /* persistenLink */);
    }


dogmaphobic's avatar
dogmaphobic committed
433
    QStringList currentPorts;
Don Gagne's avatar
Don Gagne committed
434
    QList<QGCSerialPortInfo> portList = QGCSerialPortInfo::availablePorts();
Don Gagne's avatar
Don Gagne committed
435

436
    // Iterate Comm Ports
Don Gagne's avatar
Don Gagne committed
437
    foreach (QGCSerialPortInfo portInfo, portList) {
Don Gagne's avatar
Don Gagne committed
438 439 440 441 442 443 444 445 446
        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
447 448
        // Save port name
        currentPorts << portInfo.systemLocation();
Don Gagne's avatar
Don Gagne committed
449 450 451 452 453 454 455 456 457

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

        if (boardType != QGCSerialPortInfo::BoardTypeUnknown) {
            if (portInfo.isBootloader()) {
                // Don't connect to bootloader
                continue;
            }
            
Don Gagne's avatar
Don Gagne committed
458 459 460
            if (!_autoconnectConfigurationsContainsPort(portInfo.systemLocation())) {
                SerialConfiguration* pSerialConfig = NULL;

Don Gagne's avatar
Don Gagne committed
461 462 463
                switch (boardType) {
                case QGCSerialPortInfo::BoardTypePX4FMUV1:
                case QGCSerialPortInfo::BoardTypePX4FMUV2:
Don Gagne's avatar
Don Gagne committed
464 465 466
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("Pixhawk on %1").arg(portInfo.portName().trimmed()));
                    }
Don Gagne's avatar
Don Gagne committed
467 468
                    break;
                case QGCSerialPortInfo::BoardTypeAeroCore:
Don Gagne's avatar
Don Gagne committed
469 470 471
                    if (_autoconnectPixhawk) {
                        pSerialConfig = new SerialConfiguration(QString("AeroCore on %1").arg(portInfo.portName().trimmed()));
                    }
Don Gagne's avatar
Don Gagne committed
472 473
                    break;
                case QGCSerialPortInfo::BoardTypePX4Flow:
Don Gagne's avatar
Don Gagne committed
474 475 476
                    if (_autoconnectPX4Flow) {
                        pSerialConfig = new SerialConfiguration(QString("PX4Flow on %1").arg(portInfo.portName().trimmed()));
                    }
Don Gagne's avatar
Don Gagne committed
477 478
                    break;
                case QGCSerialPortInfo::BoardType3drRadio:
Don Gagne's avatar
Don Gagne committed
479 480 481 482
                    if (_autoconnect3DRRadio) {
                        pSerialConfig = new SerialConfiguration(QString("3DR Radio on %1").arg(portInfo.portName().trimmed()));
                    }
                    break;
Don Gagne's avatar
Don Gagne committed
483 484
                default:
                    qWarning() << "Internal error";
Don Gagne's avatar
Don Gagne committed
485
                    continue;
dogmaphobic's avatar
dogmaphobic committed
486
                }
Don Gagne's avatar
Don Gagne committed
487

Don Gagne's avatar
Don Gagne committed
488 489 490 491 492 493 494 495 496 497
                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);

                    createConnectedLink(pSerialConfig, true /* persistenLink */);
                }
dogmaphobic's avatar
dogmaphobic committed
498 499 500
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
501

dogmaphobic's avatar
dogmaphobic committed
502 503
    // 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
504 505 506 507 508 509
    for (int i=0; i<_autoconnectConfigurations.count(); i++) {
        SerialConfiguration* linkConfig = _autoconnectConfigurations.value<SerialConfiguration*>(i);

        if (linkConfig) {
            if (!currentPorts.contains(linkConfig->portName())) {
                _confToDelete.append(linkConfig);
dogmaphobic's avatar
dogmaphobic committed
510
            }
Don Gagne's avatar
Don Gagne committed
511 512
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
513 514
        }
    }
Don Gagne's avatar
Don Gagne committed
515 516 517 518 519 520 521 522 523

    // Now disconnect/remove all links that are gone
    foreach (LinkConfiguration* pDeleteConfig, _confToDelete) {
        LinkInterface* link = pDeleteConfig->link();
        if (link) {
            disconnectLink(link, true /* disconnectAutoconnectLink */);
        }
        _autoconnectConfigurations.removeOne(pDeleteConfig);
        delete pDeleteConfig;
524 525
    }
}
dogmaphobic's avatar
dogmaphobic committed
526
#endif
527

Don Gagne's avatar
Don Gagne committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
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::anyNonAutoconnectConnectedLinks(void)
543
{
Don Gagne's avatar
Don Gagne committed
544
    // FIXME: Should remove this duplication with anyConnectedLinks
545
    bool found = false;
Don Gagne's avatar
Don Gagne committed
546 547 548 549
    for (int i=0; i<_links.count(); i++) {
        LinkInterface* link = _links.value<LinkInterface*>(i);

        if (link && !link->autoconnect() && link->isConnected()) {
550 551 552 553 554 555 556
            found = true;
            break;
        }
    }
    return found;
}

Don Gagne's avatar
Don Gagne committed
557
bool LinkManager::anyActiveLinks(void)
558 559
{
    bool found = false;
Don Gagne's avatar
Don Gagne committed
560 561 562 563
    for (int i=0; i<_links.count(); i++) {
        LinkInterface* link = _links.value<LinkInterface*>(i);

        if (link && link->active()) {
564 565 566 567 568 569 570
            found = true;
            break;
        }
    }
    return found;
}

Don Gagne's avatar
Don Gagne committed
571
bool LinkManager::anyNonAutoconnectActiveLinks(void)
572
{
Don Gagne's avatar
Don Gagne committed
573 574
    // FIXME: Should remove this duplication with anyActiveLinks
    bool found = false;
575
    for (int i=0; i<_links.count(); i++) {
Don Gagne's avatar
Don Gagne committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
        LinkInterface* link = _links.value<LinkInterface*>(i);

        if (link && !link->autoconnect() && link->active()) {
            found = true;
            break;
        }
    }
    return found;
}

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();
        bool previousAnyNonAutoconnectActiveLinks = anyNonAutoconnectActiveLinks();

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

        if (!previousAnyActiveLinks) {
            emit anyActiveLinksChanged(true);
618
        }
Don Gagne's avatar
Don Gagne committed
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
        if (!previousAnyNonAutoconnectActiveLinks && anyNonAutoconnectActiveLinks()) {
            emit anyNonAutoconnectActiveLinksChanged(true);
        }
    }
}

void LinkManager::shutdown(void)
{
    setConnectionsSuspended("Shutdown");
    disconnectAll(true /* disconnectAutoconnectLink */);
}

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

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

        _autoconnectUDP = autoconnect;
        emit autoconnectUDPChanged(autoconnect);
641
    }
Don Gagne's avatar
Don Gagne committed
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
}

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

684
}