UDPLink.cc 8.01 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 <netinet/in.h>
pixhawk's avatar
pixhawk committed
40 41 42 43 44 45 46 47 48 49 50 51

UDPLink::UDPLink(QHostAddress host, quint16 port)
{
    this->host = host;
    this->port = port;
    this->connectState = false;
    this->hosts = new QList<QHostAddress>();
    //this->ports = new QMap<QHostAddress, quint16>();
    this->ports = new QList<quint16>();

    // Set unique ID and add link to the list of links
    this->id = getNextLinkId();
52
    this->name = tr("UDP Link (port:%1)").arg(14550);
pixhawk's avatar
pixhawk committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66
    LinkManager::instance()->add(this);
}

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

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

void UDPLink::setAddress(QString address)
{
pixhawk's avatar
pixhawk committed
75 76 77
    Q_UNUSED(address);
    // FIXME TODO Implement address
    //socket->setLocalAddress(QHostAddress(address));
pixhawk's avatar
pixhawk committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
}

void UDPLink::setPort(quint16 port)
{
    this->port = port;
}


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)

    for (int h = 0; h < hosts->size(); h++)
    {
        QHostAddress currentHost = hosts->at(h);
        quint16 currentPort = ports->at(h);
        //        QList<quint16> currentPorts = ports->values(currentHost);
        //        for (int p = 0; p < currentPorts.size(); p++)
        //        {
        //            quint16 currentPort = currentPorts.at(p);
        //qDebug() << "Sent message to " << currentHost << ":" << currentPort << "at" << __FILE__ << ":" << __LINE__;
        socket->writeDatagram(data, size, currentHost, currentPort);
        //        }
    }


    //if(socket->write(data, size) > 0) {

//    qDebug() << "Transmitted " << size << "bytes:";
//
//    /* Increase write counter */
//    bitsSentTotal += size * 8;
//
//    int i;
//    for (i=0; i<size; i++){
//        unsigned int v=data[i];
//
//        fprintf(stderr,"%02x ", v);
//    }
    //}
}

/**
 * @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
 **/
128
void UDPLink::readBytes()
pixhawk's avatar
pixhawk committed
129
{
130 131
    const qint64 maxLength = 2048;
    char data[maxLength];
pixhawk's avatar
pixhawk committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    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
    if (!hosts->contains(sender))
    {
        hosts->append(sender);
        ports->append(senderPort);
        //        ports->insert(sender, senderPort);
    }
    else
    {
        int index = hosts->indexOf(sender);
        ports->replace(index, senderPort);
    }

}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
qint64 UDPLink::bytesAvailable() {
    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
205 206 207 208 209 210 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 240 241
    //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
//    {
        connectState = socket->bind(host, port);
//    }

    //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
242
    //QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
243
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readBytes()));
pixhawk's avatar
pixhawk committed
244 245

    emit connected(connectState);
246 247 248
    if (connectState)
    {
        emit connected();
249
        connectionStartTime = QGC::groundTimeUsecs()/1000;
250
    }
pixhawk's avatar
pixhawk committed
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 277 278 279 280

    start(HighPriority);
    return connectState;
}

/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
bool UDPLink::isConnected() {
    return connectState;
}

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

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

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

281

pixhawk's avatar
pixhawk committed
282 283 284 285 286 287
qint64 UDPLink::getNominalDataRate() {
    return 54000000; // 54 Mbit
}

qint64 UDPLink::getTotalUpstream() {
    statisticsMutex.lock();
288
    qint64 totalUpstream = bitsSentTotal / ((QGC::groundTimeUsecs()/1000 - connectionStartTime) / 1000);
pixhawk's avatar
pixhawk committed
289
    statisticsMutex.unlock();
290
    return totalUpstream;
pixhawk's avatar
pixhawk committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
}

qint64 UDPLink::getCurrentUpstream() {
    return 0; // TODO
}

qint64 UDPLink::getMaxUpstream() {
    return 0; // TODO
}

qint64 UDPLink::getBitsSent() {
    return bitsSentTotal;
}

qint64 UDPLink::getBitsReceived() {
    return bitsReceivedTotal;
}

qint64 UDPLink::getTotalDownstream() {
    statisticsMutex.lock();
311
    qint64 totalDownstream = bitsReceivedTotal / ((QGC::groundTimeUsecs()/1000 - connectionStartTime) / 1000);
pixhawk's avatar
pixhawk committed
312
    statisticsMutex.unlock();
313
    return totalDownstream;
pixhawk's avatar
pixhawk committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
}

qint64 UDPLink::getCurrentDownstream() {
    return 0; // TODO
}

qint64 UDPLink::getMaxDownstream() {
    return 0; // TODO
}

bool UDPLink::isFullDuplex() {
    return true;
}

int UDPLink::getLinkQuality() {
    /* This feature is not supported with this interface */
    return -1;
}