UDPLink.cc 11.6 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2
/*=====================================================================

lm's avatar
lm committed
3
QGroundControl Open Source Ground Control Station
pixhawk's avatar
pixhawk committed
4

5
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
pixhawk's avatar
pixhawk committed
6

lm's avatar
lm committed
7
This file is part of the QGROUNDCONTROL project
pixhawk's avatar
pixhawk committed
8

lm's avatar
lm committed
9
    QGROUNDCONTROL is free software: you can redistribute it and/or modify
pixhawk's avatar
pixhawk committed
10 11 12 13
    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
14
    QGROUNDCONTROL is distributed in the hope that it will be useful,
pixhawk's avatar
pixhawk committed
15 16 17 18 19
    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.

    You should have received a copy of the GNU General Public License
lm's avatar
lm committed
20
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
pixhawk's avatar
pixhawk committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34

======================================================================*/

/**
 * @file
 *   @brief Definition of UDP connection (server) for unmanned vehicles
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QTimer>
#include <QList>
#include <QDebug>
#include <QMutexLocker>
35
#include <QNetworkProxy>
pixhawk's avatar
pixhawk committed
36
#include <iostream>
37

pixhawk's avatar
pixhawk committed
38
#include "UDPLink.h"
39
#include "QGC.h"
40
#include <QHostInfo>
pixhawk's avatar
pixhawk committed
41

42 43 44
UDPLink::UDPLink(UDPConfiguration* config)
    : _socket(NULL)
    , _connectState(false)
pixhawk's avatar
pixhawk committed
45
{
46 47 48 49
    Q_ASSERT(config != NULL);
    _config = config;
    _config->setLink(this);

50 51 52
    // We're doing it wrong - because the Qt folks got the API wrong:
    // http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/
    moveToThread(this);
53

pixhawk's avatar
pixhawk committed
54
    // Set unique ID and add link to the list of links
55 56
    _id = getNextLinkId();
    qDebug() << "UDP Created " << _config->name();
pixhawk's avatar
pixhawk committed
57 58 59 60
}

UDPLink::~UDPLink()
{
61 62
    // Disconnect link from configuration
    _config->setLink(NULL);
63
    _disconnect();
Lorenz Meier's avatar
Lorenz Meier committed
64 65 66 67
    // Tell the thread to exit
    quit();
    // Wait for it to exit
    wait();
68
    this->deleteLater();
pixhawk's avatar
pixhawk committed
69 70 71 72 73 74 75 76
}

/**
 * @brief Runs the thread
 *
 **/
void UDPLink::run()
{
77
    _hardwareConnect();
78
    exec();
pixhawk's avatar
pixhawk committed
79 80
}

81
void UDPLink::_restartConnection()
pixhawk's avatar
pixhawk committed
82
{
83 84 85 86 87
    if(this->isConnected())
    {
        _disconnect();
        _connect();
    }
pixhawk's avatar
pixhawk committed
88 89
}

90
QString UDPLink::getName() const
pixhawk's avatar
pixhawk committed
91
{
92
    return _config->name();
93 94 95 96
}

void UDPLink::addHost(const QString& host)
{
97
    _config->addHost(host);
98 99
}

100
void UDPLink::removeHost(const QString& host)
101
{
102
    _config->removeHost(host);
pixhawk's avatar
pixhawk committed
103 104
}

105 106
#define UDPLINK_DEBUG 0

pixhawk's avatar
pixhawk committed
107 108 109
void UDPLink::writeBytes(const char* data, qint64 size)
{
    // Broadcast to all connected systems
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    QString host;
    int port;
    if(_config->firstHost(host, port)) {
        do {
            if(UDPLINK_DEBUG) {
                QString bytes;
                QString ascii;
                for (int i=0; i<size; i++)
                {
                    unsigned char v = data[i];
                    bytes.append(QString().sprintf("%02x ", v));
                    if (data[i] > 31 && data[i] < 127)
                    {
                        ascii.append(data[i]);
                    }
                    else
                    {
                        ascii.append(219);
                    }
                }
                qDebug() << "Sent" << size << "bytes to" << host << ":" << port << "data:";
                qDebug() << bytes;
                qDebug() << "ASCII:" << ascii;
lm's avatar
lm committed
133
            }
134 135 136 137 138 139
            QHostAddress currentHost(host);
            _socket->writeDatagram(data, size, currentHost, (quint16)port);
            // Log the amount and time written out for future data rate calculations.
            QMutexLocker dataRateLocker(&dataRateMutex);
            logDataRateToBuffer(outDataWriteAmounts, outDataWriteTimes, &outDataIndex, size, QDateTime::currentMSecsSinceEpoch());
        } while (_config->nextHost(host, port));
140
    }
pixhawk's avatar
pixhawk committed
141 142 143 144 145
}

/**
 * @brief Read a number of bytes from the interface.
 **/
146
void UDPLink::readBytes()
pixhawk's avatar
pixhawk committed
147
{
148
    while (_socket->hasPendingDatagrams())
149 150
    {
        QByteArray datagram;
151
        datagram.resize(_socket->pendingDatagramSize());
pixhawk's avatar
pixhawk committed
152

153 154
        QHostAddress sender;
        quint16 senderPort;
155
        _socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
pixhawk's avatar
pixhawk committed
156

157 158
        // FIXME TODO Check if this method is better than retrieving the data by individual processes
        emit bytesReceived(this, datagram);
pixhawk's avatar
pixhawk committed
159

160 161 162 163
        // Log this data reception for this timestep
        QMutexLocker dataRateLocker(&dataRateMutex);
        logDataRateToBuffer(inDataWriteAmounts, inDataWriteTimes, &inDataIndex, datagram.length(), QDateTime::currentMSecsSinceEpoch());

164 165 166 167 168 169 170 171 172
//        // Echo data for debugging purposes
//        std::cerr << __FILE__ << __LINE__ << "Received datagram:" << std::endl;
//        int i;
//        for (i=0; i<s; i++)
//        {
//            unsigned int v=data[i];
//            fprintf(stderr,"%02x ", v);
//        }
//        std::cerr << std::endl;
pixhawk's avatar
pixhawk committed
173

174 175 176 177
        // TODO This doesn't validade the sender. Anything sending UDP packets to this port gets
        // added to the list and will start receiving datagrams from here. Even a port scanner
        // would trigger this.
        // Add host to broadcast list if not yet present, or update its port
dogmaphobic's avatar
dogmaphobic committed
178
        _config->addHost(sender.toString(), (int)senderPort);
pixhawk's avatar
pixhawk committed
179 180 181 182 183 184 185 186
    }
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
187
bool UDPLink::_disconnect(void)
pixhawk's avatar
pixhawk committed
188
{
189 190 191 192 193 194
    this->quit();
    this->wait();
    if (_socket) {
        // Make sure delete happen on correct thread
        _socket->deleteLater();
        _socket = NULL;
195
        emit disconnected();
196 197 198 199
    }
    // TODO When would this ever return false?
    _connectState = false;
    return !_connectState;
pixhawk's avatar
pixhawk committed
200 201 202 203 204 205 206
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
207
bool UDPLink::_connect(void)
pixhawk's avatar
pixhawk committed
208
{
209 210 211 212 213 214
    if(this->isRunning())
    {
        this->quit();
        this->wait();
    }
    // TODO When would this ever return false?
215
    bool connected = true;
oberion's avatar
oberion committed
216
    start(HighPriority);
217
    return connected;
oberion's avatar
oberion committed
218 219
}

220
bool UDPLink::_hardwareConnect()
oberion's avatar
oberion committed
221
{
222 223
    QHostAddress host = QHostAddress::Any;
    _socket = new QUdpSocket();
224
    _socket->setProxy(QNetworkProxy::NoProxy);
225 226 227
    _connectState = _socket->bind(host, _config->localPort());
    QObject::connect(_socket, SIGNAL(readyRead()), this, SLOT(readBytes()));
    if (_connectState) {
228 229
        emit connected();
    }
230
    return _connectState;
pixhawk's avatar
pixhawk committed
231 232 233 234 235 236 237
}

/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
238
bool UDPLink::isConnected() const
239
{
240
    return _connectState;
pixhawk's avatar
pixhawk committed
241 242
}

243
int UDPLink::getId() const
pixhawk's avatar
pixhawk committed
244
{
245
    return _id;
pixhawk's avatar
pixhawk committed
246 247
}

248
qint64 UDPLink::getConnectionSpeed() const
pixhawk's avatar
pixhawk committed
249
{
250 251 252 253 254 255
    return 54000000; // 54 Mbit
}

qint64 UDPLink::getCurrentInDataRate() const
{
    return 0;
pixhawk's avatar
pixhawk committed
256 257
}

258
qint64 UDPLink::getCurrentOutDataRate() const
pixhawk's avatar
pixhawk committed
259
{
260
    return 0;
pixhawk's avatar
pixhawk committed
261 262
}

263 264
//--------------------------------------------------------------------------
//-- UDPConfiguration
265

266
UDPConfiguration::UDPConfiguration(const QString& name) : LinkConfiguration(name)
267
{
268
    _localPort = QGC_UDP_LOCAL_PORT;
269 270
}

271
UDPConfiguration::UDPConfiguration(UDPConfiguration* source) : LinkConfiguration(source)
272
{
273 274 275 276 277 278 279 280 281
    _localPort = source->localPort();
    _hosts.clear();
    QString host;
    int port;
    if(source->firstHost(host, port)) {
        do {
            addHost(host, port);
        } while(source->nextHost(host, port));
    }
282 283
}

284
void UDPConfiguration::copyFrom(LinkConfiguration *source)
285
{
286
    LinkConfiguration::copyFrom(source);
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    UDPConfiguration* usource = dynamic_cast<UDPConfiguration*>(source);
    Q_ASSERT(usource != NULL);
    _localPort = usource->localPort();
    QString host;
    int port;
    if(usource->firstHost(host, port)) {
        do {
            addHost(host, port);
        } while(usource->nextHost(host, port));
    }
}

/**
 * @param host Hostname in standard formatt, e.g. localhost:14551 or 192.168.1.1:14551
 */
void UDPConfiguration::addHost(const QString& host)
{
    if (host.contains(":"))
    {
        QHostInfo info = QHostInfo::fromName(host.split(":").first());
        if (info.error() == QHostInfo::NoError)
        {
            // Add host
            QList<QHostAddress> hostAddresses = info.addresses();
            QHostAddress address;
            for (int i = 0; i < hostAddresses.size(); i++)
            {
314 315
                // Exclude all IPv6 addresses
                if (!hostAddresses.at(i).toString().contains(":"))
316 317 318 319
                {
                    address = hostAddresses.at(i);
                }
            }
dogmaphobic's avatar
dogmaphobic committed
320
            _confMutex.lock();
321
            _hosts[address.toString()] = host.split(":").last().toInt();
dogmaphobic's avatar
dogmaphobic committed
322 323
            _confMutex.unlock();
            qDebug() << "UDP:" << "ADDING HOST:" << address.toString() << ":" << host.split(":").last();
324 325 326 327
        }
    }
    else
    {
dogmaphobic's avatar
dogmaphobic committed
328
        addHost(host, (int)_localPort);
329 330 331 332 333
    }
}

void UDPConfiguration::addHost(const QString& host, int port)
{
dogmaphobic's avatar
dogmaphobic committed
334 335 336 337 338 339 340 341 342 343 344 345 346
    QMutexLocker locker(&_confMutex);
    if(_hosts.contains(host)) {
        if(_hosts[host] != port) {
            _hosts[host] = port;
        }
    } else {
        QHostInfo info = QHostInfo::fromName(host);
        if (info.error() == QHostInfo::NoError)
        {
            _hosts[info.addresses().first().toString()] = port;
            qDebug() << "UDP:" << "ADDING HOST:" << info.addresses().first().toString() << ":" << port;
        }
    }
347 348 349 350
}

void UDPConfiguration::removeHost(const QString& host)
{
dogmaphobic's avatar
dogmaphobic committed
351
    QMutexLocker locker(&_confMutex);
352 353 354 355 356 357 358 359 360 361 362 363 364
    QString tHost = host;
    if (tHost.contains(":")) {
        tHost = tHost.split(":").first();
    }
    tHost = tHost.trimmed();
    QMap<QString, int>::iterator i = _hosts.find(tHost);
    if(i != _hosts.end()) {
        _hosts.erase(i);
    }
}

bool UDPConfiguration::firstHost(QString& host, int& port)
{
dogmaphobic's avatar
dogmaphobic committed
365
    _confMutex.lock();
366 367
    _it = _hosts.begin();
    if(_it == _hosts.end()) {
dogmaphobic's avatar
dogmaphobic committed
368
        _confMutex.unlock();
369 370
        return false;
    }
dogmaphobic's avatar
dogmaphobic committed
371
    _confMutex.unlock();
372 373 374 375 376
    return nextHost(host, port);
}

bool UDPConfiguration::nextHost(QString& host, int& port)
{
dogmaphobic's avatar
dogmaphobic committed
377
    QMutexLocker locker(&_confMutex);
378 379 380 381 382 383 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
    if(_it != _hosts.end()) {
        host = _it.key();
        port = _it.value();
        _it++;
        return true;
    }
    return false;
}

void UDPConfiguration::setLocalPort(quint16 port)
{
    _localPort = port;
}

void UDPConfiguration::saveSettings(QSettings& settings, const QString& root)
{
    _confMutex.lock();
    settings.beginGroup(root);
    settings.setValue("port", (int)_localPort);
    settings.setValue("hostCount", _hosts.count());
    int index = 0;
    QMap<QString, int>::const_iterator it = _hosts.begin();
    while(it != _hosts.end()) {
        QString hkey = QString("host%1").arg(index);
        settings.setValue(hkey, it.key());
        QString pkey = QString("port%1").arg(index);
        settings.setValue(pkey, it.value());
        it++;
        index++;
    }
    settings.endGroup();
    _confMutex.unlock();
}

void UDPConfiguration::loadSettings(QSettings& settings, const QString& root)
{
    _confMutex.lock();
    _hosts.clear();
dogmaphobic's avatar
dogmaphobic committed
416 417
    _confMutex.unlock();
    settings.beginGroup(root);
418
    _localPort = (quint16)settings.value("port", QGC_UDP_LOCAL_PORT).toUInt();
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    int hostCount = settings.value("hostCount", 0).toInt();
    for(int i = 0; i < hostCount; i++) {
        QString hkey = QString("host%1").arg(i);
        QString pkey = QString("port%1").arg(i);
        if(settings.contains(hkey) && settings.contains(pkey)) {
            addHost(settings.value(hkey).toString(), settings.value(pkey).toInt());
        }
    }
    settings.endGroup();
}

void UDPConfiguration::updateSettings()
{
    if(_link) {
        UDPLink* ulink = dynamic_cast<UDPLink*>(_link);
        if(ulink) {
            ulink->_restartConnection();
        }
    }
438
}