LinkManager.cc 14.2 KB
Newer Older
pixhawk's avatar
pixhawk committed
1
/*=====================================================================
lm's avatar
lm committed
2 3 4 5 6 7 8 9

QGroundControl Open Source Ground Control Station

(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

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>
35
#include <QSerialPortInfo>
36

37 38
#include "LinkManager.h"
#include "MainWindow.h"
Don Gagne's avatar
Don Gagne committed
39
#include "QGCMessageBox.h"
40
#include "QGCApplication.h"
41

Don Gagne's avatar
Don Gagne committed
42
IMPLEMENT_QGC_SINGLETON(LinkManager, LinkManager)
43

44

pixhawk's avatar
pixhawk committed
45 46
/**
 * @brief Private singleton constructor
47
 *
pixhawk's avatar
pixhawk committed
48 49
 * This class implements the singleton design pattern and has therefore only a private constructor.
 **/
50 51 52 53 54
LinkManager::LinkManager(QObject* parent)
    : QGCSingleton(parent)
    , _configUpdateSuspended(false)
    , _configurationsLoaded(false)
    , _connectionsSuspended(false)
pixhawk's avatar
pixhawk committed
55
{
56 57
    connect(&_portListTimer, &QTimer::timeout, this, &LinkManager::_updateConfigurationList);
    _portListTimer.start(1000);
pixhawk's avatar
pixhawk committed
58 59 60 61
}

LinkManager::~LinkManager()
{
62 63 64 65 66 67
    // Clear configuration list
    while(_linkConfigurations.count()) {
        LinkConfiguration* pLink = _linkConfigurations.at(0);
        if(pLink) delete pLink;
        _linkConfigurations.removeAt(0);
    }
68
    Q_ASSERT_X(_links.count() == 0, "LinkManager", "LinkManager::_shutdown should have been called previously");
pixhawk's avatar
pixhawk committed
69 70
}

71 72 73 74 75 76 77 78 79 80 81
LinkInterface* LinkManager::createLink(LinkConfiguration* config)
{
    Q_ASSERT(config);
    LinkInterface* pLink = NULL;
    switch(config->type()) {
        case LinkConfiguration::TypeSerial:
            pLink = new SerialLink(dynamic_cast<SerialConfiguration*>(config));
            break;
        case LinkConfiguration::TypeUdp:
            pLink = new UDPLink(dynamic_cast<UDPConfiguration*>(config));
            break;
82
#ifdef UNITTEST_BUILD
83 84 85
        case LinkConfiguration::TypeMock:
            pLink = new MockLink(dynamic_cast<MockConfiguration*>(config));
            break;
86
#endif
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    }
    if(pLink) {
        addLink(pLink);
    }
    return pLink;
}

LinkInterface* LinkManager::createLink(const QString& name)
{
    Q_ASSERT(name.isEmpty() == false);
    for(int i = 0; i < _linkConfigurations.count(); i++) {
        LinkConfiguration* conf = _linkConfigurations.at(i);
        if(conf && conf->name() == name)
            return createLink(conf);
    }
    return NULL;
}

105
void LinkManager::addLink(LinkInterface* link)
pixhawk's avatar
pixhawk committed
106
{
107
    Q_ASSERT(link);
108

109 110
    // Take ownership for delete
    link->_ownedByLinkManager = true;
111

112
    _linkListMutex.lock();
113

114
    if (!_links.contains(link)) {
115
        _links.append(link);
116
        _linkListMutex.unlock();
117
        emit newLink(link);
118
    } else {
119
        _linkListMutex.unlock();
120
    }
121

122 123
    // MainWindow may be around when doing things like running unit tests
    if (MainWindow::instance()) {
124
        connect(link, &LinkInterface::communicationError, qgcApp(), &QGCApplication::criticalMessageBoxOnMainThread);
125
    }
126

127 128 129 130 131
    MAVLinkProtocol* mavlink = MAVLinkProtocol::instance();
    connect(link, &LinkInterface::bytesReceived, mavlink, &MAVLinkProtocol::receiveBytes);
    connect(link, &LinkInterface::connected, mavlink, &MAVLinkProtocol::linkConnected);
    connect(link, &LinkInterface::disconnected, mavlink, &MAVLinkProtocol::linkDisconnected);
    mavlink->resetMetadataForLink(link);
132

133 134
    connect(link, &LinkInterface::connected, this, &LinkManager::_linkConnected);
    connect(link, &LinkInterface::disconnected, this, &LinkManager::_linkDisconnected);
135
}
pixhawk's avatar
pixhawk committed
136 137 138

bool LinkManager::connectAll()
{
139 140 141
    if (_connectionsSuspendedMsg()) {
        return false;
    }
142

143 144
    bool allConnected = true;

145
    _linkListMutex.lock();
146 147 148 149 150
    foreach (LinkInterface* link, _links) {
        Q_ASSERT(link);
        if (!link->_connect()) {
            allConnected = false;
        }
151
    }
152
    _linkListMutex.unlock();
153 154

    return allConnected;
pixhawk's avatar
pixhawk committed
155 156 157 158
}

bool LinkManager::disconnectAll()
{
159 160
    bool allDisconnected = true;

161
    _linkListMutex.lock();
162
    foreach (LinkInterface* link, _links)
Lorenz Meier's avatar
Lorenz Meier committed
163
    {
164
        Q_ASSERT(link);
165
        if (!link->_disconnect()) {
166 167
            allDisconnected = false;
        }
168
    }
169
    _linkListMutex.unlock();
170 171

    return allDisconnected;
pixhawk's avatar
pixhawk committed
172 173 174 175
}

bool LinkManager::connectLink(LinkInterface* link)
{
176
    Q_ASSERT(link);
177

178 179 180 181
    if (_connectionsSuspendedMsg()) {
        return false;
    }

182 183 184 185 186
    if (link->_connect()) {
        return true;
    } else {
        return false;
    }
pixhawk's avatar
pixhawk committed
187 188 189 190
}

bool LinkManager::disconnectLink(LinkInterface* link)
{
191
    Q_ASSERT(link);
192
    if (link->_disconnect()) {
193 194 195 196 197 198 199 200
        // TODO There is no point in disconnecting it if will stay around.
        // This should be turned into a delete link instead. Deleting a link
        // is not yet possible as LinkManager is broken.
        // Disconnect this link from its configuration
        LinkConfiguration* config = link->getLinkConfiguration();
        if(config) {
            config->setLink(NULL);
        }
201 202 203 204
        return true;
    } else {
        return false;
    }
pixhawk's avatar
pixhawk committed
205 206
}

207
void LinkManager::deleteLink(LinkInterface* link)
208
{
209
    Q_ASSERT(link);
210

211
    _linkListMutex.lock();
212

213 214 215 216
    Q_ASSERT(_links.contains(link));
    _links.removeOne(link);
    Q_ASSERT(!_links.contains(link));

217
    _linkListMutex.unlock();
218

Don Gagne's avatar
Don Gagne committed
219
    // Emit removal of link
220
    emit linkDeleted(link);
221

222 223 224
    Q_ASSERT(link->_ownedByLinkManager);
    link->_deletedByLinkManager = true;   // Signal that this is a valid delete
    delete link;
pixhawk's avatar
pixhawk committed
225 226 227 228 229 230 231
}

/**
 *
 */
const QList<LinkInterface*> LinkManager::getLinks()
{
232
    _linkListMutex.lock();
233
    QList<LinkInterface*> ret(_links);
234
    _linkListMutex.unlock();
235
    return ret;
pixhawk's avatar
pixhawk committed
236
}
237

238
const QList<SerialLink *> LinkManager::getSerialLinks()
239
{
240
    _linkListMutex.lock();
241 242
    QList<SerialLink*> s;

243
    foreach (LinkInterface* link, _links)
244
    {
245
        Q_ASSERT(link);
246

247
        SerialLink* serialLink = qobject_cast<SerialLink*>(link);
248

249 250
        if (serialLink)
            s.append(serialLink);
251
    }
252
    _linkListMutex.unlock();
253 254 255

    return s;
}
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

void LinkManager::_shutdown(void)
{
    QList<LinkInterface*> links = _links;
    foreach(LinkInterface* link, links) {
        disconnectLink(link);
        deleteLink(link);
    }
}
285 286 287 288 289 290 291 292 293 294

void LinkManager::_linkConnected(void)
{
    emit linkConnected((LinkInterface*)sender());
}

void LinkManager::_linkDisconnected(void)
{
    emit linkDisconnected((LinkInterface*)sender());
}
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

void LinkManager::addLinkConfiguration(LinkConfiguration* link)
{
    Q_ASSERT(link != NULL);
    //-- If not there already, add it
    int idx = _linkConfigurations.indexOf(link);
    if(idx < 0)
    {
        _linkConfigurations.append(link);
    }
}

void LinkManager::removeLinkConfiguration(LinkConfiguration *link)
{
    Q_ASSERT(link != NULL);
    int idx = _linkConfigurations.indexOf(link);
    if(idx >= 0)
    {
        _linkConfigurations.removeAt(idx);
        delete link;
    }
}

const QList<LinkConfiguration*> LinkManager::getLinkConfigurationList()
{
    return _linkConfigurations;
}

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

void LinkManager::saveLinkConfigurationList()
{
    QSettings settings;
    settings.remove(LinkConfiguration::settingsRoot());
    QString root(LinkConfiguration::settingsRoot());
    settings.setValue(root + "/count", _linkConfigurations.count());
    int index = 0;
    foreach (LinkConfiguration* pLink, _linkConfigurations) {
        Q_ASSERT(pLink != NULL);
        root = LinkConfiguration::settingsRoot();
        root += QString("/Link%1").arg(index++);
        settings.setValue(root + "/name", pLink->name());
        settings.setValue(root + "/type", pLink->type());
        settings.setValue(root + "/preferred", pLink->isPreferred());
        // Have the instance save its own values
        pLink->saveSettings(settings, root);
    }
    emit linkConfigurationChanged();
}

void LinkManager::loadLinkConfigurationList()
{
    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();
                if(type < LinkConfiguration::TypeLast) {
                    if(settings.contains(root + "/name")) {
                        QString name = settings.value(root + "/name").toString();
                        if(!name.isEmpty()) {
                            bool preferred = false;
                            if(settings.contains(root + "/preferred")) {
                                preferred = settings.value(root + "/preferred").toBool();
                            }
                            LinkConfiguration* pLink = NULL;
                            switch(type) {
                                case LinkConfiguration::TypeSerial:
                                    pLink = (LinkConfiguration*)new SerialConfiguration(name);
                                    pLink->setPreferred(preferred);
                                    break;
                                case LinkConfiguration::TypeUdp:
                                    pLink = (LinkConfiguration*)new UDPConfiguration(name);
                                    pLink->setPreferred(preferred);
                                    break;
378
#ifdef UNITTEST_BUILD
379 380 381 382
                                case LinkConfiguration::TypeMock:
                                    pLink = (LinkConfiguration*)new MockConfiguration(name);
                                    pLink->setPreferred(false);
                                    break;
383
#endif
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
                            }
                            if(pLink) {
                                // Have the instance load its own values
                                pLink->loadSettings(settings, root);
                                addLinkConfiguration(pLink);
                            }
                        } 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." ;
            }
        }
        emit linkConfigurationChanged();
    }
    // Enable automatic PX4 hunting
    _configurationsLoaded = true;
}

SerialConfiguration* LinkManager::_findSerialConfiguration(const QString& portName)
{
    QString searchPort = portName.trimmed();
    foreach (LinkConfiguration* pLink, _linkConfigurations) {
        Q_ASSERT(pLink != NULL);
        if(pLink->type() == LinkConfiguration::TypeSerial) {
            SerialConfiguration* pSerial = dynamic_cast<SerialConfiguration*>(pLink);
            if(pSerial->portName() == searchPort) {
                return pSerial;
            }
        }
    }
    return NULL;
}

void LinkManager::_updateConfigurationList(void)
{
    if (_configUpdateSuspended || !_configurationsLoaded) {
        return;
    }
    bool saveList = false;
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
    // Iterate Comm Ports
    foreach (QSerialPortInfo portInfo, portList) {
#if 0
        qDebug() << "-----------------------------------------------------";
        qDebug() << "portName:         " << portInfo.portName();
        qDebug() << "systemLocation:   " << portInfo.systemLocation();
        qDebug() << "description:      " << portInfo.description();
        qDebug() << "manufacturer:     " << portInfo.manufacturer();
        qDebug() << "serialNumber:     " << portInfo.serialNumber();
        qDebug() << "vendorIdentifier: " << portInfo.vendorIdentifier();
#endif
        // Is this a PX4?
        if (portInfo.vendorIdentifier() == 9900) {
            SerialConfiguration* pSerial = _findSerialConfiguration(portInfo.portName());
            if (pSerial) {
                //-- If this port is configured make sure it has the preferred flag set
                if(!pSerial->isPreferred()) {
                    pSerial->setPreferred(true);
                    saveList = true;
                }
            } else {
                // Lets create a new Serial configuration automatically
                pSerial = new SerialConfiguration(QString("Pixhawk on %1").arg(portInfo.portName().trimmed()));
                pSerial->setPreferred(true);
                pSerial->setBaud(115200);
                pSerial->setPortName(portInfo.portName());
                addLinkConfiguration(pSerial);
                saveList = true;
            }
        }
    }
    // Save configuration list, which will also trigger a signal for the UI
    if(saveList) {
        saveLinkConfigurationList();
    }
}