UDPLink.cc 9.22 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

lm's avatar
lm committed
5
(c) 2009, 2010 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 43 44 45 46 47 48

UDPLink::UDPLink(QHostAddress host, quint16 port)
{
    this->host = host;
    this->port = port;
    this->connectState = false;
    // Set unique ID and add link to the list of links
    this->id = getNextLinkId();
49
    this->name = tr("UDP Link (port:%1)").arg(14550);
pixhawk's avatar
pixhawk committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63
    LinkManager::instance()->add(this);
}

UDPLink::~UDPLink()
{
    disconnect();
}

/**
 * @brief Runs the thread
 *
 **/
void UDPLink::run()
{
lm's avatar
lm committed
64 65 66 67 68
//    forever
//    {
//        QGC::SLEEP::msleep(5000);
//    }
    exec();
pixhawk's avatar
pixhawk committed
69 70 71 72
}

void UDPLink::setAddress(QString address)
{
pixhawk's avatar
pixhawk committed
73
    Q_UNUSED(address);
pixhawk's avatar
pixhawk committed
74 75
}

76
void UDPLink::setPort(int port)
pixhawk's avatar
pixhawk committed
77 78
{
    this->port = port;
79 80 81 82 83 84 85 86 87
    disconnect();
    connect();
}

/**
 * @param host Hostname in standard formatting, e.g. localhost:14551 or 192.168.1.1:14551
 */
void UDPLink::addHost(const QString& host)
{
88
    qDebug() << "UDP:" << "ADDING HOST:" << host;
89
    if (host.contains(":")) {
90 91
        qDebug() << "HOST: " << host.split(":").first();
        QHostInfo info = QHostInfo::fromName(host.split(":").first());
92
        // Add host
93 94
        QList<QHostAddress> hostAddresses = info.addresses();
        QHostAddress address;
95
        for (int i = 0; i < hostAddresses.size(); i++) {
96
            // Exclude loopback IPv4 and all IPv6 addresses
97
            if (!hostAddresses.at(i).toString().contains(":")) {
98 99 100 101 102
                address = hostAddresses.at(i);
            }
        }
        hosts.append(address);
        qDebug() << "Address:" << address.toString();
103
        // Set port according to user input
104
        ports.append(host.split(":").last().toInt());
105
    } else {
106
        QHostInfo info = QHostInfo::fromName(host);
107
        // Add host
108
        hosts.append(info.addresses().first());
109
        // Set port according to default (this port)
110 111 112 113 114 115 116 117 118 119 120 121
        ports.append(port);
    }
}

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();
122
    for (int i = 0; i < hostAddresses.size(); i++) {
123
        // Exclude loopback IPv4 and all IPv6 addresses
124
        if (!hostAddresses.at(i).toString().contains(":")) {
125 126 127
            address = hostAddresses.at(i);
        }
    }
128 129
    for (int i = 0; i < hosts.count(); ++i) {
        if (hosts.at(i) == address) {
130 131 132
            hosts.removeAt(i);
            ports.removeAt(i);
        }
133
    }
pixhawk's avatar
pixhawk committed
134 135 136 137 138 139 140 141 142
}


void UDPLink::writeBytes(const char* data, qint64 size)
{
    // Broadcast to all connected systems
    //QList<QHostAddress>::iterator h;
    // for (h = hosts->begin(); h != hosts->end(); ++h)

143

144
    for (int h = 0; h < hosts.size(); h++) {
145 146
        QHostAddress currentHost = hosts.at(h);
        quint16 currentPort = ports.at(h);
pixhawk's avatar
pixhawk committed
147

148
        qDebug() << "WRITING TO" << currentHost.toIPv4Address() << currentPort;
149
        for (int i=0; i<size; i++) {
150 151 152
            unsigned char v =data[i];
            qDebug("%02x ", v);
        }
153
        qDebug() <<"Sent to " << currentHost.toString() << ":" << currentPort;
pixhawk's avatar
pixhawk committed
154

155 156
        socket->writeDatagram(data, size, currentHost, currentPort);
    }
pixhawk's avatar
pixhawk committed
157 158 159 160 161 162 163 164
}

/**
 * @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
 **/
165
void UDPLink::readBytes()
pixhawk's avatar
pixhawk committed
166
{
167 168
    const qint64 maxLength = 2048;
    char data[maxLength];
pixhawk's avatar
pixhawk committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    QHostAddress sender;
    quint16 senderPort;

    unsigned int s = socket->pendingDatagramSize();
    if (s > maxLength) std::cerr << __FILE__ << __LINE__ << " UDP datagram overflow, allowed to read less bytes than datagram size" << std::endl;
    socket->readDatagram(data, maxLength, &sender, &senderPort);

    // FIXME TODO Check if this method is better than retrieving the data by individual processes
    QByteArray b(data, s);
    emit bytesReceived(this, b);

//    // 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;


    // Add host to broadcast list if not yet present
192
    if (!hosts.contains(sender)) {
193 194
        hosts.append(sender);
        ports.append(senderPort);
pixhawk's avatar
pixhawk committed
195
        //        ports->insert(sender, senderPort);
196
    } else {
197 198
        int index = hosts.indexOf(sender);
        ports.replace(index, senderPort);
pixhawk's avatar
pixhawk committed
199 200 201 202 203 204 205 206 207 208
    }

}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
209 210
qint64 UDPLink::bytesAvailable()
{
pixhawk's avatar
pixhawk committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    return socket->pendingDatagramSize();
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
bool UDPLink::disconnect()
{
    delete socket;
    socket = NULL;

    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()
{
    socket = new QUdpSocket(this);

pixhawk's avatar
pixhawk committed
240 241 242 243 244 245 246 247 248
    //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
//    {
249
    connectState = socket->bind(host, port);
pixhawk's avatar
pixhawk committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
//    }

    //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
277
    //QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
278
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readBytes()));
pixhawk's avatar
pixhawk committed
279 280

    emit connected(connectState);
281
    if (connectState) {
282
        emit connected();
283
        connectionStartTime = QGC::groundTimeUsecs()/1000;
284
    }
pixhawk's avatar
pixhawk committed
285 286 287 288 289 290 291 292 293 294

    start(HighPriority);
    return connectState;
}

/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
295 296
bool UDPLink::isConnected()
{
pixhawk's avatar
pixhawk committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    return connectState;
}

int UDPLink::getId()
{
    return id;
}

QString UDPLink::getName()
{
    return name;
}

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

316

317 318
qint64 UDPLink::getNominalDataRate()
{
pixhawk's avatar
pixhawk committed
319 320 321
    return 54000000; // 54 Mbit
}

322 323
qint64 UDPLink::getTotalUpstream()
{
pixhawk's avatar
pixhawk committed
324
    statisticsMutex.lock();
325
    qint64 totalUpstream = bitsSentTotal / ((QGC::groundTimeUsecs()/1000 - connectionStartTime) / 1000);
pixhawk's avatar
pixhawk committed
326
    statisticsMutex.unlock();
327
    return totalUpstream;
pixhawk's avatar
pixhawk committed
328 329
}

330 331
qint64 UDPLink::getCurrentUpstream()
{
pixhawk's avatar
pixhawk committed
332 333 334
    return 0; // TODO
}

335 336
qint64 UDPLink::getMaxUpstream()
{
pixhawk's avatar
pixhawk committed
337 338 339
    return 0; // TODO
}

340 341
qint64 UDPLink::getBitsSent()
{
pixhawk's avatar
pixhawk committed
342 343 344
    return bitsSentTotal;
}

345 346
qint64 UDPLink::getBitsReceived()
{
pixhawk's avatar
pixhawk committed
347 348 349
    return bitsReceivedTotal;
}

350 351
qint64 UDPLink::getTotalDownstream()
{
pixhawk's avatar
pixhawk committed
352
    statisticsMutex.lock();
353
    qint64 totalDownstream = bitsReceivedTotal / ((QGC::groundTimeUsecs()/1000 - connectionStartTime) / 1000);
pixhawk's avatar
pixhawk committed
354
    statisticsMutex.unlock();
355
    return totalDownstream;
pixhawk's avatar
pixhawk committed
356 357
}

358 359
qint64 UDPLink::getCurrentDownstream()
{
pixhawk's avatar
pixhawk committed
360 361 362
    return 0; // TODO
}

363 364
qint64 UDPLink::getMaxDownstream()
{
pixhawk's avatar
pixhawk committed
365 366 367
    return 0; // TODO
}

368 369
bool UDPLink::isFullDuplex()
{
pixhawk's avatar
pixhawk committed
370 371 372
    return true;
}

373 374
int UDPLink::getLinkQuality()
{
pixhawk's avatar
pixhawk committed
375 376 377
    /* This feature is not supported with this interface */
    return -1;
}