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

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

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

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

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

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

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

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

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

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

Don Gagne's avatar
Don Gagne committed
187
void LinkManager::disconnectAll(bool disconnectAutoconnectLink)
pixhawk's avatar
pixhawk committed
188
{
Don Gagne's avatar
Don Gagne committed
189 190 191
    // 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);
192
    }
pixhawk's avatar
pixhawk committed
193 194 195 196
}

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

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

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

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

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

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

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

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

    if (!link) {
        return;
    }
246

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

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

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

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

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

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

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

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

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

    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
312
        }
313
    }
Don Gagne's avatar
Don Gagne committed
314

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

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

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

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

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

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

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

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

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

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

430 431
    
#ifndef __ios__
dogmaphobic's avatar
dogmaphobic committed
432
    QStringList currentPorts;
Don Gagne's avatar
Don Gagne committed
433
    QList<QGCSerialPortInfo> portList = QGCSerialPortInfo::availablePorts();
Don Gagne's avatar
Don Gagne committed
434

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

        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
457 458 459
            if (!_autoconnectConfigurationsContainsPort(portInfo.systemLocation())) {
                SerialConfiguration* pSerialConfig = NULL;

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

Don Gagne's avatar
Don Gagne committed
487 488 489 490 491 492 493 494 495 496
                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
497 498 499
            }
        }
    }
Don Gagne's avatar
Don Gagne committed
500

dogmaphobic's avatar
dogmaphobic committed
501 502
    // 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
503 504 505 506 507 508
    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
509
            }
Don Gagne's avatar
Don Gagne committed
510 511
        } else {
            qWarning() << "Internal error";
dogmaphobic's avatar
dogmaphobic committed
512 513
        }
    }
Don Gagne's avatar
Don Gagne committed
514 515 516 517 518 519 520 521 522

    // 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;
523
    }
524
#endif // __ios__
525 526
}

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

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

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

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

Don Gagne's avatar
Don Gagne committed
570
bool LinkManager::anyNonAutoconnectActiveLinks(void)
571
{
Don Gagne's avatar
Don Gagne committed
572 573
    // FIXME: Should remove this duplication with anyActiveLinks
    bool found = false;
574
    for (int i=0; i<_links.count(); i++) {
Don Gagne's avatar
Don Gagne committed
575 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
        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);
617
        }
Don Gagne's avatar
Don Gagne committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        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);
640
    }
Don Gagne's avatar
Don Gagne committed
641 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
}

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

683
}