UDPLink.cc 10.3 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 - 2011 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 35 36 37

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

/**
 * @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>
#include <iostream>
#include "UDPLink.h"
#include "LinkManager.h"
38
#include "QGC.h"
39
#include <QHostInfo>
40
//#include <netinet/in.h>
pixhawk's avatar
pixhawk committed
41 42

UDPLink::UDPLink(QHostAddress host, quint16 port)
oberion's avatar
oberion committed
43
	: socket(NULL)
pixhawk's avatar
pixhawk committed
44 45 46 47 48 49
{
    this->host = host;
    this->port = port;
    this->connectState = false;
    // Set unique ID and add link to the list of links
    this->id = getNextLinkId();
oberion's avatar
oberion committed
50 51 52
	this->name = tr("UDP Link (port:%1)").arg(this->port);
	emit nameChanged(this->name);
    // LinkManager::instance()->add(this);
pixhawk's avatar
pixhawk committed
53 54 55 56 57
}

UDPLink::~UDPLink()
{
    disconnect();
oberion's avatar
oberion committed
58
	this->deleteLater();
pixhawk's avatar
pixhawk committed
59 60 61 62 63 64 65 66
}

/**
 * @brief Runs the thread
 *
 **/
void UDPLink::run()
{
oberion's avatar
oberion committed
67
	exec();
pixhawk's avatar
pixhawk committed
68 69
}

oberion's avatar
oberion committed
70
void UDPLink::setAddress(QHostAddress host)
pixhawk's avatar
pixhawk committed
71
{
oberion's avatar
oberion committed
72 73 74 75 76 77 78 79 80 81 82
    bool reconnect(false);
	if(this->isConnected())
	{
		disconnect();
		reconnect = true;
	}
	this->host = host;
	if(reconnect)
	{
		connect();
	}
pixhawk's avatar
pixhawk committed
83 84
}

85
void UDPLink::setPort(int port)
pixhawk's avatar
pixhawk committed
86
{
oberion's avatar
oberion committed
87 88 89 90 91 92
	bool reconnect(false);
	if(this->isConnected())
	{
		disconnect();
		reconnect = true;
	}
pixhawk's avatar
pixhawk committed
93
    this->port = port;
oberion's avatar
oberion committed
94 95 96 97 98 99
	this->name = tr("UDP Link (port:%1)").arg(this->port);
	emit nameChanged(this->name);
	if(reconnect)
	{
		connect();
	}
100 101 102 103 104 105 106
}

/**
 * @param host Hostname in standard formatting, e.g. localhost:14551 or 192.168.1.1:14551
 */
void UDPLink::addHost(const QString& host)
{
107
    //qDebug() << "UDP:" << "ADDING HOST:" << host;
108 109
    if (host.contains(":"))
    {
110
        //qDebug() << "HOST: " << host.split(":").first();
111
        QHostInfo info = QHostInfo::fromName(host.split(":").first());
lm's avatar
lm committed
112
        if (info.error() == QHostInfo::NoError)
113
        {
lm's avatar
lm committed
114 115 116 117
            // Add host
            QList<QHostAddress> hostAddresses = info.addresses();
            QHostAddress address;
            for (int i = 0; i < hostAddresses.size(); i++)
118
            {
lm's avatar
lm committed
119 120 121 122 123
                // Exclude loopback IPv4 and all IPv6 addresses
                if (!hostAddresses.at(i).toString().contains(":"))
                {
                    address = hostAddresses.at(i);
                }
124
            }
lm's avatar
lm committed
125
            hosts.append(address);
126
            //qDebug() << "Address:" << address.toString();
lm's avatar
lm committed
127 128
            // Set port according to user input
            ports.append(host.split(":").last().toInt());
129
        }
130 131 132
    }
    else
    {
133
        QHostInfo info = QHostInfo::fromName(host);
lm's avatar
lm committed
134 135 136 137 138 139 140
        if (info.error() == QHostInfo::NoError)
        {
            // Add host
            hosts.append(info.addresses().first());
            // Set port according to default (this port)
            ports.append(port);
        }
141 142 143 144 145 146 147 148 149 150 151
    }
}

void UDPLink::removeHost(const QString& hostname)
{
    QString host = hostname;
    if (host.contains(":")) host = host.split(":").first();
    host = host.trimmed();
    QHostInfo info = QHostInfo::fromName(host);
    QHostAddress address;
    QList<QHostAddress> hostAddresses = info.addresses();
152 153
    for (int i = 0; i < hostAddresses.size(); i++)
    {
154
        // Exclude loopback IPv4 and all IPv6 addresses
155 156
        if (!hostAddresses.at(i).toString().contains(":"))
        {
157 158 159
            address = hostAddresses.at(i);
        }
    }
160 161 162 163
    for (int i = 0; i < hosts.count(); ++i)
    {
        if (hosts.at(i) == address)
        {
164 165 166
            hosts.removeAt(i);
            ports.removeAt(i);
        }
167
    }
pixhawk's avatar
pixhawk committed
168 169 170 171 172
}

void UDPLink::writeBytes(const char* data, qint64 size)
{
    // Broadcast to all connected systems
lm's avatar
lm committed
173 174
    for (int h = 0; h < hosts.size(); h++)
    {
175 176
        QHostAddress currentHost = hosts.at(h);
        quint16 currentPort = ports.at(h);
lm's avatar
lm committed
177 178
//#define UDPLINK_DEBUG
#ifdef UDPLINK_DEBUG
lm's avatar
lm committed
179 180
        QString bytes;
        QString ascii;
181 182
        for (int i=0; i<size; i++)
        {
lm's avatar
lm committed
183 184
            unsigned char v = data[i];
            bytes.append(QString().sprintf("%02x ", v));
lm's avatar
lm committed
185 186 187 188 189 190 191 192
            if (data[i] > 31 && data[i] < 127)
            {
                ascii.append(data[i]);
            }
            else
            {
                ascii.append(219);
            }
193
        }
lm's avatar
lm committed
194 195 196
        qDebug() << "Sent" << size << "bytes to" << currentHost.toString() << ":" << currentPort << "data:";
        qDebug() << bytes;
        qDebug() << "ASCII:" << ascii;
lm's avatar
lm committed
197
#endif
198 199
        socket->writeDatagram(data, size, currentHost, currentPort);
    }
pixhawk's avatar
pixhawk committed
200 201 202 203 204 205 206 207
}

/**
 * @brief Read a number of bytes from the interface.
 *
 * @param data Pointer to the data byte array to write the bytes to
 * @param maxLength The maximum number of bytes to write
 **/
208
void UDPLink::readBytes()
pixhawk's avatar
pixhawk committed
209
{
210 211 212 213
    while (socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
pixhawk's avatar
pixhawk committed
214

215 216 217
        QHostAddress sender;
        quint16 senderPort;
        socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
pixhawk's avatar
pixhawk committed
218

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

222 223 224 225 226 227 228 229 230
//        // 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
231 232


233 234 235 236 237 238 239 240 241 242 243 244
        // Add host to broadcast list if not yet present
        if (!hosts.contains(sender))
        {
            hosts.append(sender);
            ports.append(senderPort);
            //        ports->insert(sender, senderPort);
        }
        else
        {
            int index = hosts.indexOf(sender);
            ports.replace(index, senderPort);
        }
pixhawk's avatar
pixhawk committed
245 246 247 248 249 250 251 252 253
    }
}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
254 255
qint64 UDPLink::bytesAvailable()
{
pixhawk's avatar
pixhawk committed
256 257 258 259 260 261 262 263 264 265
    return socket->pendingDatagramSize();
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
bool UDPLink::disconnect()
{
oberion's avatar
oberion committed
266 267 268
	this->quit();
	this->wait();

269
        if(socket)
oberion's avatar
oberion committed
270 271 272 273
	{
		delete socket;
		socket = NULL;
	}
pixhawk's avatar
pixhawk committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

    connectState = false;

    emit disconnected();
    emit connected(false);
    return !connectState;
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
bool UDPLink::connect()
{
oberion's avatar
oberion committed
289 290 291 292 293
	if(this->isRunning())
	{
		this->quit();
		this->wait();
	}
294
    bool connected = this->hardwareConnect();
oberion's avatar
oberion committed
295
    start(HighPriority);
296
    return connected;
oberion's avatar
oberion committed
297 298 299 300 301
}

bool UDPLink::hardwareConnect(void)
{
	socket = new QUdpSocket();
pixhawk's avatar
pixhawk committed
302

pixhawk's avatar
pixhawk committed
303 304 305 306 307 308 309 310 311
    //Check if we are using a multicast-address
//    bool multicast = false;
//    if (host.isInSubnet(QHostAddress("224.0.0.0"),4))
//    {
//        multicast = true;
//        connectState = socket->bind(port, QUdpSocket::ShareAddress);
//    }
//    else
//    {
312
    connectState = socket->bind(host, port);
pixhawk's avatar
pixhawk committed
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
//    }

    //Provides Multicast functionality to UdpSocket
    /* not working yet
    if (multicast)
    {
        int sendingFd = socket->socketDescriptor();

        if (sendingFd != -1)
        {
            // set up destination address
            struct sockaddr_in sendAddr;
            memset(&sendAddr,0,sizeof(sendAddr));
            sendAddr.sin_family=AF_INET;
            sendAddr.sin_addr.s_addr=inet_addr(HELLO_GROUP);
            sendAddr.sin_port=htons(port);

            // set TTL
            unsigned int ttl = 1; // restricted to the same subnet
            if (setsockopt(sendingFd, IPPROTO_IP, IP_MULTICAST_TTL, (unsigned int*)&ttl, sizeof(ttl) ) < 0)
            {
                std::cout << "TTL failed\n";
            }
        }
    }
    */

pixhawk's avatar
pixhawk committed
340
    //QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
341
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readBytes()));
pixhawk's avatar
pixhawk committed
342 343

    emit connected(connectState);
344
    if (connectState) {
345
        emit connected();
346
        connectionStartTime = QGC::groundTimeUsecs()/1000;
347
    }
oberion's avatar
oberion committed
348
	return connectState;
pixhawk's avatar
pixhawk committed
349 350
}

oberion's avatar
oberion committed
351

pixhawk's avatar
pixhawk committed
352 353 354 355 356
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
357
bool UDPLink::isConnected() const
358
{
pixhawk's avatar
pixhawk committed
359 360 361
    return connectState;
}

362
int UDPLink::getId() const
pixhawk's avatar
pixhawk committed
363 364 365 366
{
    return id;
}

367
QString UDPLink::getName() const
pixhawk's avatar
pixhawk committed
368 369 370 371 372 373 374 375 376 377
{
    return name;
}

void UDPLink::setName(QString name)
{
    this->name = name;
    emit nameChanged(this->name);
}

378

379
qint64 UDPLink::getNominalDataRate() const
380
{
pixhawk's avatar
pixhawk committed
381 382 383
    return 54000000; // 54 Mbit
}

384 385
qint64 UDPLink::getTotalUpstream()
{
pixhawk's avatar
pixhawk committed
386
    statisticsMutex.lock();
387
    qint64 totalUpstream = bitsSentTotal / ((QGC::groundTimeUsecs()/1000 - connectionStartTime) / 1000);
pixhawk's avatar
pixhawk committed
388
    statisticsMutex.unlock();
389
    return totalUpstream;
pixhawk's avatar
pixhawk committed
390 391
}

392 393
qint64 UDPLink::getCurrentUpstream()
{
pixhawk's avatar
pixhawk committed
394 395 396
    return 0; // TODO
}

397 398
qint64 UDPLink::getMaxUpstream()
{
pixhawk's avatar
pixhawk committed
399 400 401
    return 0; // TODO
}

402
qint64 UDPLink::getBitsSent() const
403
{
pixhawk's avatar
pixhawk committed
404 405 406
    return bitsSentTotal;
}

407
qint64 UDPLink::getBitsReceived() const
408
{
pixhawk's avatar
pixhawk committed
409 410 411
    return bitsReceivedTotal;
}

412 413
qint64 UDPLink::getTotalDownstream()
{
pixhawk's avatar
pixhawk committed
414
    statisticsMutex.lock();
415
    qint64 totalDownstream = bitsReceivedTotal / ((QGC::groundTimeUsecs()/1000 - connectionStartTime) / 1000);
pixhawk's avatar
pixhawk committed
416
    statisticsMutex.unlock();
417
    return totalDownstream;
pixhawk's avatar
pixhawk committed
418 419
}

420 421
qint64 UDPLink::getCurrentDownstream()
{
pixhawk's avatar
pixhawk committed
422 423 424
    return 0; // TODO
}

425 426
qint64 UDPLink::getMaxDownstream()
{
pixhawk's avatar
pixhawk committed
427 428 429
    return 0; // TODO
}

430
bool UDPLink::isFullDuplex() const
431
{
pixhawk's avatar
pixhawk committed
432 433 434
    return true;
}

435
int UDPLink::getLinkQuality() const
436
{
pixhawk's avatar
pixhawk committed
437 438 439
    /* This feature is not supported with this interface */
    return -1;
}