SerialSimulationLink.cc 12.5 KB
Newer Older
pixhawk's avatar
pixhawk committed
1
/*=====================================================================
2

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

lm's avatar
lm committed
5
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
6

lm's avatar
lm committed
7
This file is part of the QGROUNDCONTROL project
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
    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.
13

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
    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.
18

pixhawk's avatar
pixhawk committed
19
    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/>.
21

pixhawk's avatar
pixhawk committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
======================================================================*/
/**
 * @file
 *   @brief Brief Description
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <SerialSimulationLink.h>
#include <QTime>
#include <QFile>
#include <QDebug>
#include <MG.h>
39
#include "QGC.h"
pixhawk's avatar
pixhawk committed
40 41 42 43 44 45 46 47 48 49 50 51

/**
 * Create a simulated link. This link is connected to an input and output file.
 * The link sends one line at a time at the specified sendrate. The timing of
 * the sendrate is free of drift, which means it is stable on the long run.
 * However, small deviations are mixed in which vary the sendrate slightly
 * in order to simulate disturbances on a real communication link.
 *
 * @param readFile The file with the messages to read (must be in ASCII format, line breaks can be Unix or Windows style)
 * @param writeFile The received messages are written to that file
 * @param sendrate The rate at which the messages are sent (in intervals of milliseconds)
 **/
52 53
SerialSimulationLink::SerialSimulationLink(QFile* readFile, QFile* writeFile, int sendrate)
{
pixhawk's avatar
pixhawk committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    // If a non-empty portname is supplied, the serial simulation link should attempt loopback simulation
    loopBack = NULL;

    /* Comments on the variables can be found in the header file */

    lineBuffer = QByteArray();
    lineBuffer.clear();
    readyBuffer = QByteArray();
    readyBuffer.clear();
    simulationFile = readFile;
    receiveFile = writeFile;
    lastSent = MG::TIME::getGroundTimeNow();

    /* Initialize the pseudo-random number generator */
    srand(QTime::currentTime().msec());
    maxTimeNoise = 0;

    timer = new QTimer(this);
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(readLine()));
    _isConnected = false;
    rate = sendrate;
}

77 78
SerialSimulationLink::~SerialSimulationLink()
{
pixhawk's avatar
pixhawk committed
79 80 81 82 83
    //TODO Check destructor
    fileStream->flush();
    outStream->flush();
}

84 85
void SerialSimulationLink::run()
{
pixhawk's avatar
pixhawk committed
86 87 88 89 90 91 92 93 94 95
    /*
        forever {
                quint64 currentTime = OG::TIME::getGroundTimeNow();
                if(currentTime - lastSent >= rate) {
                        lastSent = currentTime;
                        readLine();
                }

                msleep(rate);
        }*/
96 97 98 99
    forever
    {
        QGC::SLEEP::msleep(5000);
    }
pixhawk's avatar
pixhawk committed
100 101
}

102 103
void SerialSimulationLink::enableLoopBackMode(SerialLink* loop)
{
pixhawk's avatar
pixhawk committed
104 105 106 107 108 109
    // Lock the data
    readyBufferMutex.lock();
    // Disconnect this link
    disconnect();

    // Delete previous loopback link if exists
110 111
    if(loopBack != NULL)
    {
pixhawk's avatar
pixhawk committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
        delete loopBack;
        loopBack = NULL;
    }

    // Set new loopback link
    loopBack = loop;
    // Connect signals
    QObject::connect(loopBack, SIGNAL(connected()), this, SIGNAL(connected()));
    QObject::connect(loopBack, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    QObject::connect(loopBack, SIGNAL(connected(bool)), this, SIGNAL(connected(bool)));
    QObject::connect(loopBack, SIGNAL(bytesReady(LinkInterface*)), this, SIGNAL(bytesReady(LinkInterface*)));
    readyBufferMutex.unlock();

}


128 129
qint64 SerialSimulationLink::bytesAvailable()
{
pixhawk's avatar
pixhawk committed
130 131
    readyBufferMutex.lock();
    qint64 size = 0;
132 133
    if(loopBack == 0)
    {
pixhawk's avatar
pixhawk committed
134
        size = readyBuffer.size();
135 136 137
    }
    else
    {
pixhawk's avatar
pixhawk committed
138 139 140 141 142 143 144
        size = loopBack->bytesAvailable();
    }
    readyBufferMutex.unlock();

    return size;
}

145 146
void SerialSimulationLink::writeBytes(char* data, qint64 length)
{
pixhawk's avatar
pixhawk committed
147
    /* Write bytes to one line */
148 149
    for(qint64 i = 0; i < length; i++)
    {
pixhawk's avatar
pixhawk committed
150 151 152 153 154 155 156
        outStream->operator <<(data[i]);
        outStream->flush();
    }

}


157 158 159 160
void SerialSimulationLink::readBytes()
{
    const qint64 maxLength = 2048;
    char data[maxLength];
pixhawk's avatar
pixhawk committed
161 162
    /* Lock concurrent resource readyBuffer */
    readyBufferMutex.lock();
163 164 165
    if(loopBack == NULL)
    {
        // FIXME Maxlength has no meaning here
pixhawk's avatar
pixhawk committed
166 167 168
        /* copy leftmost maxLength bytes and remove them from buffer */
        qstrncpy(data, readyBuffer.left(maxLength).data(), maxLength);
        readyBuffer.remove(0, maxLength);
169 170 171 172
    }
    else
    {
        //loopBack->readBytes(data, maxLength);
pixhawk's avatar
pixhawk committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    }
    readyBufferMutex.unlock();
}

/**
 * @brief Reads a line at a time of the simulation data file and sends it.
 *
 * The data is read binary, which means that the file doesn't have to contain
 * only ASCII characters. The line break (independent of operating system) is
 * NOT read. The line gets sent as a whole. Because the next line is buffered,
 * the line gets sent instantly when the function is called.
 *
 * @bug The time noise addition is commented out because it adds some delay
 *      which leads to a drift in the timer. This can be fixed by multithreading.
 **/
188 189
void SerialSimulationLink::readLine()
{
pixhawk's avatar
pixhawk committed
190

191 192
    if(_isConnected)
    {
pixhawk's avatar
pixhawk committed
193 194 195 196 197 198 199 200 201 202
        /* The order of operations in this method is arranged to
                 * minimize the impact of slow file read operations on the
                 * message emit timing. The functions should be kept in this order
                 */

        /* (1) Add noise for next iteration (noise is always 0 for maxTimeNoise = 0) */
        addTimeNoise();

        /* (2) Save content of line buffer in readyBuffer (has to be lock for thread safety)*/
        readyBufferMutex.lock();
203 204
        if(loopBack == NULL)
        {
pixhawk's avatar
pixhawk committed
205 206
            readyBuffer.append(lineBuffer);
            //qDebug() << "readLine readyBuffer: " << readyBuffer;
207 208 209
        }
        else
        {
pixhawk's avatar
pixhawk committed
210 211 212 213
            loopBack->writeBytes(lineBuffer.data(), lineBuffer.size());
        }
        readyBufferMutex.unlock();

214 215 216
        if(loopBack == NULL)
        {
            readBytes();
pixhawk's avatar
pixhawk committed
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 242 243 244 245 246 247 248 249 250 251
        }

        /* (4) Read one line and save it in line buffer */
        lineBuffer.clear();

        // Remove whitespaces, tabs and line breaks
        QString readString = fileStream->readLine().trimmed();
        readString.remove(" ");
        readString.remove("\t");
        readString.remove("\n");
        readString.remove("\v");
        readString.remove("\r");
        lineBuffer.append(readString.toAscii());

        //qDebug() << "SerialSimulationLink::readLine()" << readString.size() << readString;

        /* Check if end of file has been reached, start from the beginning if necessary
                 * This has to be done after the last read, otherwise the timer is out of sync */
        if (fileStream->atEnd()) {
            simulationFile->reset();
        }

    }

}

/**
 * Set the maximum time deviation noise. This amount (in milliseconds) is
 * the maximum time offset (+/-) from the specified message send rate.
 *
 * @param milliseconds The maximum time offset (in milliseconds)
 *
 * @bug The current implementation might induce one milliseconds additional
 * 		 discrepancy, this will be fixed by multithreading
 **/
252 253
void SerialSimulationLink::setMaximumTimeNoise(int milliseconds)
{
pixhawk's avatar
pixhawk committed
254 255 256 257 258 259 260 261 262 263
    maxTimeNoise = milliseconds;
}


/**
 * Add or subtract a pseudo random time offset. The maximum time offset is
 * defined by setMaximumTimeNoise().
 *
 * @see setMaximumTimeNoise()
 **/
264 265
void SerialSimulationLink::addTimeNoise()
{
pixhawk's avatar
pixhawk committed
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
    /* Calculate the time deviation */
    if(maxTimeNoise == 0) {
        /* Don't do expensive calculations if no noise is desired */
        timer->setInterval(rate);
    } else {
        /* Calculate random time noise (gauss distribution):
                 *
                 * (1) (2 * rand()) / RAND_MAX: Number between 0 and 2
                 * (induces numerical noise through floating point representation,
                 * ignored here)
                 *
                 * (2) ((2 * rand()) / RAND_MAX) - 1: Number between -1 and 1
                 *
                 * (3) Complete term: Number between -maxTimeNoise and +maxTimeNoise
                 */
        double timeDeviation = (((2 * rand()) / RAND_MAX) - 1) * maxTimeNoise;
        timer->setInterval(static_cast<int>(rate + floor(timeDeviation)));
    }

}

/**
 * Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection
 * couldn't be disconnected.
 **/
bool SerialSimulationLink::disconnect() {

    if(isConnected()) {
        timer->stop();

        fileStream->flush();
        outStream->flush();

        simulationFile->close();
        receiveFile->close();

        _isConnected = false;

        if(loopBack == NULL) {
            emit disconnected();
        } else {
            loopBack->disconnect();
        }

        exit();
    }

    return true;
}

/**
 * Connect the link.
 *
 * @return True if connection has been established, false if connection
 * couldn't be established.
 **/
324 325
bool SerialSimulationLink::connect()
{
pixhawk's avatar
pixhawk committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    /* Open files */
    //@TODO Add check if file can be read
    simulationFile->open(QIODevice::ReadOnly);

    /* Create or replace output file */
    if(receiveFile->exists()) receiveFile->remove(); //TODO Read return value if file has been removed
    receiveFile->open(QIODevice::WriteOnly);

    fileStream = new QTextStream(simulationFile);
    outStream = new QTextStream(receiveFile);

    /* Initialize line buffer */
    lineBuffer.clear();
    lineBuffer.append(fileStream->readLine().toAscii());

    _isConnected = true;

    if(loopBack == NULL) {
        emit connected();
    } else {
        loopBack->connect();
    }

    start(LowPriority);
    timer->start(rate);
    return true;
}

/**
 * Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
359 360
bool SerialSimulationLink::isConnected()
{
pixhawk's avatar
pixhawk committed
361 362 363
    return _isConnected;
}

364 365
qint64 SerialSimulationLink::getNominalDataRate()
{
pixhawk's avatar
pixhawk committed
366 367 368 369
    /* 100 Mbit is reasonable fast and sufficient for all embedded applications */
    return 100000000;
}

370 371
qint64 SerialSimulationLink::getTotalUpstream()
{
pixhawk's avatar
pixhawk committed
372 373 374 375 376
    return 0;
    //TODO Add functionality here
    // @todo Add functionality here
}

377 378
qint64 SerialSimulationLink::getShortTermUpstream()
{
pixhawk's avatar
pixhawk committed
379 380 381
    return 0;
}

382 383
qint64 SerialSimulationLink::getCurrentUpstream()
{
pixhawk's avatar
pixhawk committed
384 385 386
    return 0;
}

387 388
qint64 SerialSimulationLink::getMaxUpstream()
{
pixhawk's avatar
pixhawk committed
389 390 391
    return 0;
}

392 393
qint64 SerialSimulationLink::getBitsSent()
{
pixhawk's avatar
pixhawk committed
394 395 396
    return 0;
}

397 398
qint64 SerialSimulationLink::getBitsReceived()
{
pixhawk's avatar
pixhawk committed
399 400 401
    return 0;
}

402 403
qint64 SerialSimulationLink::getTotalDownstream()
{
pixhawk's avatar
pixhawk committed
404 405 406
    return 0;
}

407 408
qint64 SerialSimulationLink::getShortTermDownstream()
{
pixhawk's avatar
pixhawk committed
409 410 411
    return 0;
}

412 413
qint64 SerialSimulationLink::getCurrentDownstream()
{
pixhawk's avatar
pixhawk committed
414 415 416
    return 0;
}

417 418
qint64 SerialSimulationLink::getMaxDownstream()
{
pixhawk's avatar
pixhawk committed
419 420 421
    return 0;
}

422 423
bool SerialSimulationLink::isFullDuplex()
{
pixhawk's avatar
pixhawk committed
424 425 426 427
    /* Full duplex is no problem when running in pure software, but this is a serial simulation */
    return false;
}

428 429
int SerialSimulationLink::getLinkQuality()
{
pixhawk's avatar
pixhawk committed
430 431 432 433
    /* The Link quality is always perfect when running in software */
    return 100;
}

434 435 436
bool SerialSimulationLink::setPortName(QString portName)
{
    Q_UNUSED(portName);
pixhawk's avatar
pixhawk committed
437 438 439
    return true;
}

440 441 442
bool SerialSimulationLink::setBaudRate(int rate)
{
    Q_UNUSED(rate);
pixhawk's avatar
pixhawk committed
443 444 445
    return true;
}

446 447 448
bool SerialSimulationLink::setFlowType(int type)
{
    Q_UNUSED(type);
pixhawk's avatar
pixhawk committed
449 450 451
    return true;
}

452 453 454
bool SerialSimulationLink::setParityType(int type)
{
    Q_UNUSED(type);
pixhawk's avatar
pixhawk committed
455 456 457
    return true;
}

458 459 460
bool SerialSimulationLink::setDataBitsType(int type)
{
    Q_UNUSED(type);
pixhawk's avatar
pixhawk committed
461 462 463
    return true;
}

464 465 466
bool SerialSimulationLink::setStopBitsType(int type)
{
    Q_UNUSED(type)
pixhawk's avatar
pixhawk committed
467 468 469
    return true;
}

470 471
QString SerialSimulationLink::getPortName()
{
pixhawk's avatar
pixhawk committed
472 473 474
    return tr("simulated/port");
}

475 476
int SerialSimulationLink::getBaudRate()
{
pixhawk's avatar
pixhawk committed
477 478 479
    return 115200;
}

480 481
int SerialSimulationLink::getBaudRateType()
{
pixhawk's avatar
pixhawk committed
482 483 484
    return 19;
}

485 486
int SerialSimulationLink::getFlowType()
{
pixhawk's avatar
pixhawk committed
487 488 489
    return 0;
}

490 491
int SerialSimulationLink::getParityType()
{
pixhawk's avatar
pixhawk committed
492 493 494
    return 0;
}

495 496
int SerialSimulationLink::getDataBitsType()
{
pixhawk's avatar
pixhawk committed
497 498 499
    return 8;
}

500 501
int SerialSimulationLink::getStopBitsType()
{
pixhawk's avatar
pixhawk committed
502 503 504
    return 2;
}

505 506 507
bool SerialSimulationLink::setBaudRateType(int rateIndex)
{
    Q_UNUSED(rateIndex);
pixhawk's avatar
pixhawk committed
508 509
    return true;
}