TCPLink.cc 6.68 KB
Newer Older
Don Gagne's avatar
Don Gagne committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
/*=====================================================================
 
 QGroundControl Open Source Ground Control Station
 
 (c) 2009 - 2011 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
 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.
 
 QGROUNDCONTROL is distributed in the hope that it will be useful,
 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
 along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
 
 ======================================================================*/

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

#include <QTimer>
#include <QList>
#include <QDebug>
#include <QMutexLocker>
#include <iostream>
#include "TCPLink.h"
#include "LinkManager.h"
#include "QGC.h"
#include <QHostInfo>

Don Gagne's avatar
Don Gagne committed
41 42 43 44 45 46
TCPLink::TCPLink(QHostAddress hostAddress, quint16 socketPort) :
    host(hostAddress),
    port(socketPort),
    socket(NULL),
    socketIsConnected(false)

Don Gagne's avatar
Don Gagne committed
47 48 49 50 51 52
{
    // Set unique ID and add link to the list of links
    this->id = getNextLinkId();
	this->name = tr("TCP Link (port:%1)").arg(this->port);
	emit nameChanged(this->name);
    
Don Gagne's avatar
Don Gagne committed
53
    qDebug() << "TCP Created " << this->name;
Don Gagne's avatar
Don Gagne committed
54 55 56 57 58 59 60 61 62 63 64 65 66
}

TCPLink::~TCPLink()
{
    disconnect();
	this->deleteLater();
}

void TCPLink::run()
{
	exec();
}

Don Gagne's avatar
Don Gagne committed
67 68 69 70 71
void TCPLink::setAddress(const QString &text)
{
    setAddress(QHostAddress(text));
}

Don Gagne's avatar
Don Gagne committed
72 73 74
void TCPLink::setAddress(QHostAddress host)
{
    bool reconnect(false);
Don Gagne's avatar
Don Gagne committed
75
	if (this->isConnected())
Don Gagne's avatar
Don Gagne committed
76 77 78 79 80
	{
		disconnect();
		reconnect = true;
	}
	this->host = host;
Don Gagne's avatar
Don Gagne committed
81
	if (reconnect)
Don Gagne's avatar
Don Gagne committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
	{
		connect();
	}
}

void TCPLink::setPort(int port)
{
	bool reconnect(false);
	if(this->isConnected())
	{
		disconnect();
		reconnect = true;
	}
    this->port = port;
	this->name = tr("TCP Link (port:%1)").arg(this->port);
	emit nameChanged(this->name);
	if(reconnect)
	{
		connect();
	}
}

Don Gagne's avatar
Don Gagne committed
104 105
#ifdef TCPLINK_READWRITE_DEBUG
void TCPLink::writeDebugBytes(const char *data, qint16 size)
Don Gagne's avatar
Don Gagne committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
{
    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);
        }
    }
Don Gagne's avatar
Don Gagne committed
122
    qDebug() << "Sent" << size << "bytes to" << host.toString() << ":" << port << "data:";
Don Gagne's avatar
Don Gagne committed
123 124
    qDebug() << bytes;
    qDebug() << "ASCII:" << ascii;
Don Gagne's avatar
Don Gagne committed
125 126 127 128 129 130 131
}
#endif

void TCPLink::writeBytes(const char* data, qint64 size)
{
#ifdef TCPLINK_READWRITE_DEBUG
    writeDebugBytes(data, size);
Don Gagne's avatar
Don Gagne committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
#endif
    socket->write(data, size);
}

/**
 * @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
 **/
void TCPLink::readBytes()
{
    qint64 byteCount = socket->bytesAvailable();
    
    if (byteCount)
    {
        QByteArray buffer;
        buffer.resize(byteCount);
        
        socket->read(buffer.data(), buffer.size());
        
        emit bytesReceived(this, buffer);
Don Gagne's avatar
Don Gagne committed
154 155 156 157

#ifdef TCPLINK_READWRITE_DEBUG
        writeDebugBytes(buffer.data(), buffer.size());
#endif
Don Gagne's avatar
Don Gagne committed
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
    }
}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
qint64 TCPLink::bytesAvailable()
{
    return socket->bytesAvailable();
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
bool TCPLink::disconnect()
{
	this->quit();
	this->wait();
    
    if (socket)
	{
Don Gagne's avatar
Don Gagne committed
184 185
        socket->disconnect();
        socketIsConnected = false;
Don Gagne's avatar
Don Gagne committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
		delete socket;
		socket = NULL;
	}
    
    return true;
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
bool TCPLink::connect()
{
	if(this->isRunning())
	{
		this->quit();
		this->wait();
	}
    bool connected = this->hardwareConnect();
    start(HighPriority);
    return connected;
}

bool TCPLink::hardwareConnect(void)
{
	socket = new QTcpSocket();
    
    socket->connectToHost(host, port);
    
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readBytes()));
Don Gagne's avatar
Don Gagne committed
217 218 219 220 221 222 223 224
    QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
    
    // Give the socket a second to connect to the other side otherwise error out
    if (!socket->waitForConnected(1000))
    {
        emit communicationError(getName(), "connection failed");
        return false;
    }
Don Gagne's avatar
Don Gagne committed
225
    
Don Gagne's avatar
Don Gagne committed
226
    socketIsConnected = true;
Don Gagne's avatar
Don Gagne committed
227
    connectionStartTime = QGC::groundTimeUsecs()/1000;
Don Gagne's avatar
Don Gagne committed
228 229
    emit connected(true);

Don Gagne's avatar
Don Gagne committed
230 231 232
    return true;
}

Don Gagne's avatar
Don Gagne committed
233
void TCPLink::socketError(QAbstractSocket::SocketError socketError)
Don Gagne's avatar
Don Gagne committed
234
{
Don Gagne's avatar
Don Gagne committed
235
    emit communicationError(getName(), "Error on socket: " + socket->errorString());
Don Gagne's avatar
Don Gagne committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 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 277 278 279 280 281 282 283 284 285 286 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 314 315 316 317 318 319 320 321 322 323 324 325
}

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

int TCPLink::getId() const
{
    return id;
}

QString TCPLink::getName() const
{
    return name;
}

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


qint64 TCPLink::getNominalDataRate() const
{
    return 54000000; // 54 Mbit
}

qint64 TCPLink::getTotalUpstream()
{
    statisticsMutex.lock();
    qint64 totalUpstream = bitsSentTotal / ((QGC::groundTimeUsecs()/1000 - connectionStartTime) / 1000);
    statisticsMutex.unlock();
    return totalUpstream;
}

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

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

qint64 TCPLink::getBitsSent() const
{
    return bitsSentTotal;
}

qint64 TCPLink::getBitsReceived() const
{
    return bitsReceivedTotal;
}

qint64 TCPLink::getTotalDownstream()
{
    statisticsMutex.lock();
    qint64 totalDownstream = bitsReceivedTotal / ((QGC::groundTimeUsecs()/1000 - connectionStartTime) / 1000);
    statisticsMutex.unlock();
    return totalDownstream;
}

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

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

bool TCPLink::isFullDuplex() const
{
    return true;
}

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