SerialLink.cc 26.2 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2 3 4 5 6 7 8 9 10 11 12
/*=====================================================================
======================================================================*/
/**
 * @file
 *   @brief Cross-platform support for serial ports
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QTimer>
#include <QDebug>
13
#include <QSettings>
pixhawk's avatar
pixhawk committed
14
#include <QMutexLocker>
Bill Bonney's avatar
Bill Bonney committed
15 16
#include <qserialport.h>
#include <qserialportinfo.h>
pixhawk's avatar
pixhawk committed
17 18
#include "SerialLink.h"
#include "LinkManager.h"
19
#include "QGC.h"
pixhawk's avatar
pixhawk committed
20 21
#include <MG.h>

22 23
SerialLink::SerialLink(QString portname, int baudRate, bool hardwareFlowControl, bool parity,
                       int dataBits, int stopBits) :
Bill Bonney's avatar
Bill Bonney committed
24 25
    m_bytesRead(0),
    m_port(NULL),
26 27
    inDataIndex(0),
    outDataIndex(0),
28
    m_stopp(false),
29
    m_reqReset(false)
pixhawk's avatar
pixhawk committed
30
{
31 32 33 34 35 36 37 38
    // Initialize our arrays manually, cause C++<03 is dumb.
    for (int i = 0; i < buffer_size; ++i)
    {
        inDataWriteAmounts[i] = 0;
        inDataWriteTimes[i] = 0;
        outDataWriteAmounts[i] = 0;
        outDataWriteTimes[i] = 0;
    }
39

40 41
    // Get the name of the current port in use.
    m_portName = portname.trimmed();
42
    if (m_portName == "" && getCurrentPorts().size() > 0)
43
    {
44
        m_portName = m_ports.first().trimmed();
45 46
    }

pixhawk's avatar
pixhawk committed
47
    // Set unique ID and add link to the list of links
Bill Bonney's avatar
Bill Bonney committed
48 49 50
    m_id = getNextLinkId();

    m_baud = baudRate;
51

52 53
    if (hardwareFlowControl)
    {
Bill Bonney's avatar
Bill Bonney committed
54
        m_flowControl = QSerialPort::HardwareControl;
55 56 57
    }
    else
    {
Bill Bonney's avatar
Bill Bonney committed
58
        m_flowControl = QSerialPort::NoFlowControl;
59 60 61
    }
    if (parity)
    {
Bill Bonney's avatar
Bill Bonney committed
62
        m_parity = QSerialPort::EvenParity;
63 64 65
    }
    else
    {
Bill Bonney's avatar
Bill Bonney committed
66
        m_parity = QSerialPort::NoParity;
67
    }
Bill Bonney's avatar
Bill Bonney committed
68 69 70

    m_dataBits = dataBits;
    m_stopBits = stopBits;
pixhawk's avatar
pixhawk committed
71

lm's avatar
lm committed
72
    loadSettings();
Lorenz Meier's avatar
Lorenz Meier committed
73 74 75 76 77

    qDebug() << "create SerialLink " << portname << baudRate << hardwareFlowControl
             << parity << dataBits << stopBits;
    qDebug() << "m_portName " << m_portName;

78
    LinkManager::instance()->add(this);
pixhawk's avatar
pixhawk committed
79
}
80

81 82 83 84 85
void SerialLink::requestReset()
{
    QMutexLocker locker(&this->m_stoppMutex);
    m_reqReset = true;
}
pixhawk's avatar
pixhawk committed
86 87 88 89

SerialLink::~SerialLink()
{
    disconnect();
Bill Bonney's avatar
Bill Bonney committed
90 91
    if(m_port) delete m_port;
    m_port = NULL;
92 93
}

94
QList<QString> SerialLink::getCurrentPorts()
95
{
96
    m_ports.clear();
97

98
    QList<QSerialPortInfo> portList =  QSerialPortInfo::availablePorts();
99

100 101
    if( portList.count() == 0){
        qDebug() << "No Ports Found" << m_ports;
102 103
    }

104
    foreach (const QSerialPortInfo &info, portList)
105
    {
Bill Bonney's avatar
Bill Bonney committed
106 107 108
//        qDebug() << "PortName    : " << info.portName()
//                 << "Description : " << info.description();
//        qDebug() << "Manufacturer: " << info.manufacturer();
109

110
        m_ports.append(info.portName());
111
    }
Bill Bonney's avatar
Bill Bonney committed
112
    return m_ports;
pixhawk's avatar
pixhawk committed
113 114
}

115 116 117
void SerialLink::loadSettings()
{
    // Load defaults from settings
118
    QSettings settings(QGC::ORG_NAME, QGC::APPNAME);
119
    settings.sync();
120 121
    if (settings.contains("SERIALLINK_COMM_PORT"))
    {
Bill Bonney's avatar
Bill Bonney committed
122 123 124 125 126 127
        m_portName = settings.value("SERIALLINK_COMM_PORT").toString();
        m_baud = settings.value("SERIALLINK_COMM_BAUD").toInt();
        m_parity = settings.value("SERIALLINK_COMM_PARITY").toInt();
        m_stopBits = settings.value("SERIALLINK_COMM_STOPBITS").toInt();
        m_dataBits = settings.value("SERIALLINK_COMM_DATABITS").toInt();
        m_flowControl = settings.value("SERIALLINK_COMM_FLOW_CONTROL").toInt();
128 129 130 131 132 133
    }
}

void SerialLink::writeSettings()
{
    // Store settings
134
    QSettings settings(QGC::ORG_NAME, QGC::APPNAME);
135
    settings.setValue("SERIALLINK_COMM_PORT", getPortName());
136 137
    settings.setValue("SERIALLINK_COMM_BAUD", getBaudRateType());
    settings.setValue("SERIALLINK_COMM_PARITY", getParityType());
138 139 140
    settings.setValue("SERIALLINK_COMM_STOPBITS", getStopBits());
    settings.setValue("SERIALLINK_COMM_DATABITS", getDataBits());
    settings.setValue("SERIALLINK_COMM_FLOW_CONTROL", getFlowType());
141 142 143
    settings.sync();
}

pixhawk's avatar
pixhawk committed
144 145 146 147 148

/**
 * @brief Runs the thread
 *
 **/
149 150
void SerialLink::run()
{
pixhawk's avatar
pixhawk committed
151
    // Initialize the connection
152
    if (!hardwareConnect()) {
153
        //Need to error out here.
154
        emit communicationError(getName(),"Error connecting: " + m_port->errorString());
155
        disconnect(); // This tidies up and sends the necessary signals
156
        emit communicationError(tr("Serial Port %1").arg(getPortName()), tr("Cannot read / write data - check physical USB and cable connections."));
157
        return;
158
    }
pixhawk's avatar
pixhawk committed
159 160

    // Qt way to make clear what a while(1) loop does
161 162
    qint64 msecs = QDateTime::currentMSecsSinceEpoch();
    qint64 initialmsecs = QDateTime::currentMSecsSinceEpoch();
163 164 165
    quint64 bytes = 0;
    bool triedreset = false;
    bool triedDTR = false;
166
    qint64 timeout = 5000;
167
    int linkErrorCount = 0;
168

169
    forever {
170
        {
171
            QMutexLocker locker(&this->m_stoppMutex);
172 173 174 175
            if(m_stopp) {
                m_stopp = false;
                break; // exit the thread
            }
176

177 178 179 180 181 182 183
            if (m_reqReset) {
                m_reqReset = false;
                emit communicationUpdate(getName(),"Reset requested via DTR signal");
                m_port->setDataTerminalReady(true);
                msleep(250);
                m_port->setDataTerminalReady(false);
            }
184
        }
185

186
        // If there are too many errors on this link, disconnect.
Lorenz Meier's avatar
Lorenz Meier committed
187
        if (isConnected() && (linkErrorCount > 1000)) {
188
            qDebug() << "linkErrorCount too high: disconnecting!";
189
            linkErrorCount = 0;
190
            emit communicationUpdate(getName(), tr("Disconnecting on too many link errors"));
191 192 193
            disconnect();
        }

194
        // Write all our buffered data out the serial port.
195
        if (m_transmitBuffer.count() > 0) {
196
            m_writeMutex.lock();
197
            int numWritten = m_port->write(m_transmitBuffer);
198
            bool txSuccess = m_port->waitForBytesWritten(5);
199
            if (!txSuccess || (numWritten != m_transmitBuffer.count())) {
200 201
                linkErrorCount++;
                qDebug() << "TX Error! wrote" << numWritten << ", asked for " << m_transmitBuffer.count() << "bytes";
202 203
            }
            else {
204 205

                // Since we were successful, reset out error counter.
206 207
                linkErrorCount = 0;
            }
208 209 210 211 212 213 214 215 216

            // Now that we transmit all of the data in the transmit buffer, flush it.
            m_transmitBuffer = m_transmitBuffer.remove(0, numWritten);
            m_writeMutex.unlock();

            // Log this written data for this timestep. If this value ends up being 0 due to
            // write() failing, that's what we want as well.
            QMutexLocker statsLocker(&m_statisticsMutex);
            WriteDataStatsBuffer(outDataWriteAmounts, outDataWriteTimes, &outDataIndex, numWritten, QDateTime::currentMSecsSinceEpoch());
217 218
        }

219 220
        //wait n msecs for data to be ready
        //[TODO][BB] lower to SerialLink::poll_interval?
221
        m_dataMutex.lock();
222
        bool success = m_port->waitForReadyRead(10);
223

224
        if (success) {
225 226 227
            QByteArray readData = m_port->readAll();
            while (m_port->waitForReadyRead(10))
                readData += m_port->readAll();
228
            m_dataMutex.unlock();
229 230 231
            if (readData.length() > 0) {
                emit bytesReceived(this, readData);

232 233 234 235 236
                // Log this data reception for this timestep
                QMutexLocker statsLocker(&m_statisticsMutex);
                WriteDataStatsBuffer(inDataWriteAmounts, inDataWriteTimes, &inDataIndex, readData.length(), QDateTime::currentMSecsSinceEpoch());

                // Track the total amount of data read.
237
                m_bytesRead += readData.length();
238
                linkErrorCount = 0;
239
            }
240 241
        }
        else {
242
            m_dataMutex.unlock();
243
            linkErrorCount++;
244
        }
245

246
        if (bytes != m_bytesRead) { // i.e things are good and data is being read.
247
            bytes = m_bytesRead;
248 249
            msecs = QDateTime::currentMSecsSinceEpoch();
        }
250 251
        else {
            if (QDateTime::currentMSecsSinceEpoch() - msecs > timeout) {
252 253
                //It's been 10 seconds since the last data came in. Reset and try again
                msecs = QDateTime::currentMSecsSinceEpoch();
254
                if (msecs - initialmsecs > 25000) {
255 256 257 258 259 260 261
                    //After initial 25 seconds, timeouts are increased to 30 seconds.
                    //This prevents temporary silences from things like calibration commands
                    //from screwing things up. In all reality, timeouts should be enabled/disabled
                    //for events like that on a case by case basis.
                    //TODO ^^
                    timeout = 30000;
                }
262
                if (!triedDTR && triedreset) {
263
                    triedDTR = true;
264
                    emit communicationUpdate(getName(),"No data to receive on COM port. Attempting to reset via DTR signal");
265
                    qDebug() << "No data!!! Attempting reset via DTR.";
266 267 268
                    m_port->setDataTerminalReady(true);
                    msleep(250);
                    m_port->setDataTerminalReady(false);
269
                }
270
                else if (!triedreset) {
271
                    qDebug() << "No data!!! Attempting reset via reboot command.";
272
                    emit communicationUpdate(getName(),"No data to receive on COM port. Assuming possible terminal mode, attempting to reset via \"reboot\" command");
273
                    m_port->write("reboot\r\n",8);
274 275
                    triedreset = true;
                }
276 277
                else {
                    emit communicationUpdate(getName(),"No data to receive on COM port....");
278 279 280 281
                    qDebug() << "No data!!!";
                }
            }
        }
pixhawk's avatar
pixhawk committed
282
        MG::SLEEP::msleep(SerialLink::poll_interval);
283 284 285 286 287 288 289
    } // end of forever
    
    if (m_port) { // [TODO][BB] Not sure we need to close the port here
        qDebug() << "Closing Port #"<< __LINE__ << m_port->portName();
        m_port->close();
        delete m_port;
        m_port = NULL;
pixhawk's avatar
pixhawk committed
290

291 292
        emit disconnected();
        emit connected(false);
293
    }
pixhawk's avatar
pixhawk committed
294 295
}

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
void SerialLink::WriteDataStatsBuffer(quint64 *bytesBuffer, qint64 *timeBuffer, int *writeIndex, quint64 bytes, qint64 time)
{
    int i = *writeIndex;

    // Now write into the buffer, if there's no room, we just overwrite the first data point.
    bytesBuffer[i] = bytes;
    timeBuffer[i] = time;

    // Increment and wrap the write index
    ++i;
    if (i == buffer_size)
    {
        i = 0;
    }
    *writeIndex = i;
}

313 314
void SerialLink::writeBytes(const char* data, qint64 size)
{
Bill Bonney's avatar
Bill Bonney committed
315
    if(m_port && m_port->isOpen()) {
pixhawk's avatar
pixhawk committed
316

317
        QByteArray byteArray(data, size);
318 319 320
        m_writeMutex.lock();
        m_transmitBuffer.append(byteArray);
        m_writeMutex.unlock();
321 322 323 324
    } else {
        disconnect();
        // Error occured
        emit communicationError(getName(), tr("Could not send data - link %1 is disconnected!").arg(getName()));
pixhawk's avatar
pixhawk committed
325 326 327 328 329 330 331 332 333
    }
}

/**
 * @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
 **/
334 335
void SerialLink::readBytes()
{
Bill Bonney's avatar
Bill Bonney committed
336
    if(m_port && m_port->isOpen()) {
337 338
        const qint64 maxLength = 2048;
        char data[maxLength];
339
        m_dataMutex.lock();
Bill Bonney's avatar
Bill Bonney committed
340
        qint64 numBytes = m_port->bytesAvailable();
341

342
        if(numBytes > 0) {
pixhawk's avatar
pixhawk committed
343 344 345
            /* Read as much data in buffer as possible without overflow */
            if(maxLength < numBytes) numBytes = maxLength;

Bill Bonney's avatar
Bill Bonney committed
346
            m_port->read(data, numBytes);
pixhawk's avatar
pixhawk committed
347 348 349
            QByteArray b(data, numBytes);
            emit bytesReceived(this, b);
        }
350
        m_dataMutex.unlock();
pixhawk's avatar
pixhawk committed
351 352 353 354 355 356 357 358 359
    }
}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
360 361
qint64 SerialLink::bytesAvailable()
{
Bill Bonney's avatar
Bill Bonney committed
362 363
    if (m_port) {
        return m_port->bytesAvailable();
364
    } else {
365 366
        return 0;
    }
pixhawk's avatar
pixhawk committed
367 368 369 370 371 372 373
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
374 375
bool SerialLink::disconnect()
{
376 377 378
    qDebug() << "disconnect";
    if (m_port)
        qDebug() << m_port->portName();
Bill Bonney's avatar
Bill Bonney committed
379 380

    if (isRunning())
381
    {
382
        qDebug() << "running so disconnect" << m_port->portName();
383
        {
Bill Bonney's avatar
Bill Bonney committed
384 385
            QMutexLocker locker(&m_stoppMutex);
            m_stopp = true;
386
        }
Bill Bonney's avatar
Bill Bonney committed
387
        wait(); // This will terminate the thread and close the serial port
pixhawk's avatar
pixhawk committed
388

Bill Bonney's avatar
Bill Bonney committed
389
        emit disconnected(); // [TODO] There are signals from QSerialPort we should use
390 391 392
        emit connected(false);
        return true;
    }
pixhawk's avatar
pixhawk committed
393

394 395
    m_transmitBuffer.clear(); //clear the output buffer to avoid sending garbage at next connect

396 397
    qDebug() << "already disconnected";
    return true;
pixhawk's avatar
pixhawk committed
398 399 400 401 402 403 404 405
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
bool SerialLink::connect()
406
{   
Bill Bonney's avatar
Bill Bonney committed
407 408
    if (isRunning())
        disconnect();
409 410
    {
        QMutexLocker locker(&this->m_stoppMutex);
Bill Bonney's avatar
Bill Bonney committed
411
        m_stopp = false;
412
    }
Bill Bonney's avatar
Bill Bonney committed
413 414

    start(LowPriority);
415
    return true;
pixhawk's avatar
pixhawk committed
416 417 418 419 420 421 422 423 424 425
}

/**
 * @brief This function is called indirectly by the connect() call.
 *
 * The connect() function starts the thread and indirectly calls this method.
 *
 * @return True if the connection could be established, false otherwise
 * @see connect() For the right function to establish the connection.
 **/
426 427
bool SerialLink::hardwareConnect()
{
428
    if(m_port) {
Bill Bonney's avatar
Bill Bonney committed
429 430 431 432
        qDebug() << "SerialLink:" << QString::number((long)this, 16) << "closing port";
        m_port->close();
        delete m_port;
        m_port = NULL;
433
    }
Bill Bonney's avatar
Bill Bonney committed
434 435
    qDebug() << "SerialLink: hardwareConnect to " << m_portName;
    m_port = new QSerialPort(m_portName);
pixhawk's avatar
pixhawk committed
436

437
    if (m_port == NULL) {
Bill Bonney's avatar
Bill Bonney committed
438 439
        emit communicationUpdate(getName(),"Error opening port: " + m_port->errorString());
        return false; // couldn't create serial port.
440
    }
Bill Bonney's avatar
Bill Bonney committed
441 442

    QObject::connect(m_port,SIGNAL(aboutToClose()),this,SIGNAL(disconnected()));
443 444
    QObject::connect(m_port, SIGNAL(error(SerialLinkPortError_t)),
                     this, SLOT(linkError(SerialLinkPortError_t)));
Bill Bonney's avatar
Bill Bonney committed
445 446 447

//    port->setCommTimeouts(QSerialPort::CtScheme_NonBlockingRead);

448
    if (!m_port->open(QIODevice::ReadWrite)) {
Bill Bonney's avatar
Bill Bonney committed
449 450 451
        emit communicationUpdate(getName(),"Error opening port: " + m_port->errorString());
        m_port->close();
        return false; // couldn't open serial port
452
    }
453

Bill Bonney's avatar
Bill Bonney committed
454
    emit communicationUpdate(getName(),"Opened port!");
pixhawk's avatar
pixhawk committed
455

Bill Bonney's avatar
Bill Bonney committed
456 457 458 459 460 461
    // Need to configure the port
    m_port->setBaudRate(m_baud);
    m_port->setDataBits(static_cast<QSerialPort::DataBits>(m_dataBits));
    m_port->setFlowControl(static_cast<QSerialPort::FlowControl>(m_flowControl));
    m_port->setStopBits(static_cast<QSerialPort::StopBits>(m_stopBits));
    m_port->setParity(static_cast<QSerialPort::Parity>(m_parity));
pixhawk's avatar
pixhawk committed
462

Bill Bonney's avatar
Bill Bonney committed
463 464
    emit connected();
    emit connected(true);
465

Bill Bonney's avatar
Bill Bonney committed
466 467
    qDebug() << "CONNECTING LINK: " << __FILE__ << __LINE__ << "with settings" << m_port->portName()
             << getBaudRate() << getDataBits() << getParityType() << getStopBits();
468

469 470
    writeSettings();

Bill Bonney's avatar
Bill Bonney committed
471
    return true; // successful connection
pixhawk's avatar
pixhawk committed
472
}
473

474
void SerialLink::linkError(SerialLinkPortError_t error)
475 476 477 478
{
    qDebug() << error;
}

479

pixhawk's avatar
pixhawk committed
480 481 482 483 484
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
485
bool SerialLink::isConnected() const
486
{
Bill Bonney's avatar
Bill Bonney committed
487 488 489

    if (m_port) {
        bool isConnected = m_port->isOpen();
490 491
//        qDebug() << "SerialLink #" << __LINE__ << ":"<<  m_port->portName()
//                 << " isConnected =" << QString::number(isConnected);
Bill Bonney's avatar
Bill Bonney committed
492
        return isConnected;
493
    } else {
494 495
//        qDebug() << "SerialLink #" << __LINE__ << ":" <<  m_portName
//                 << " isConnected = NULL";
lm's avatar
lm committed
496 497
        return false;
    }
pixhawk's avatar
pixhawk committed
498 499
}

500
int SerialLink::getId() const
pixhawk's avatar
pixhawk committed
501
{
Bill Bonney's avatar
Bill Bonney committed
502
    return m_id;
pixhawk's avatar
pixhawk committed
503 504
}

505
QString SerialLink::getName() const
pixhawk's avatar
pixhawk committed
506
{
507
    return m_portName;
pixhawk's avatar
pixhawk committed
508 509
}

510 511 512 513
/**
  * This function maps baud rate constants to numerical equivalents.
  * It relies on the mapping given in qportsettings.h from the QSerialPort library.
  */
514
qint64 SerialLink::getConnectionSpeed() const
515
{
Bill Bonney's avatar
Bill Bonney committed
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    int baudRate;
    if (m_port) {
        baudRate = m_port->baudRate();
    } else {
        baudRate = m_baud;
    }
    qint64 dataRate;
    switch (baudRate)
    {
        case QSerialPort::Baud1200:
            dataRate = 1200;
            break;
        case QSerialPort::Baud2400:
            dataRate = 2400;
            break;
        case QSerialPort::Baud4800:
            dataRate = 4800;
            break;
        case QSerialPort::Baud9600:
            dataRate = 9600;
            break;
        case QSerialPort::Baud19200:
            dataRate = 19200;
            break;
        case QSerialPort::Baud38400:
            dataRate = 38400;
            break;
        case QSerialPort::Baud57600:
            dataRate = 57600;
            break;
        case QSerialPort::Baud115200:
            dataRate = 115200;
            break;
            // Otherwise do nothing.
        case QSerialPort::UnknownBaud:
        default:
            dataRate = -1;
            break;
pixhawk's avatar
pixhawk committed
554 555 556 557
    }
    return dataRate;
}

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
qint64 SerialLink::getCurrentOutDataRate() const
{
    const qint64 now = QDateTime::currentMSecsSinceEpoch();

    // Limit the time we calculate to the recent past
    const qint64 cutoff = now - stats_timespan;

    // Grab the mutex for working with the stats variables
    QMutexLocker statsLocker(&m_statisticsMutex);

    // Now iterate through the buffer of all received data packets adding up all values
    // within now and our cutof.
    int index = outDataIndex;
    qint64 totalBytes = 0;
    qint64 totalTime = 0;
    qint64 lastTime = 0;
    int size = buffer_size;
    while (size-- > 0)
    {
        // If this data is within our cutoff time, include it in our calculations.
        // This also accounts for when the buffer is empty and filled with 0-times.
        if (outDataWriteTimes[index] > cutoff && lastTime > 0) {
            // Track the total time, using the previous time as our timeperiod.
            totalTime += outDataWriteTimes[index] - lastTime;
            totalBytes += outDataWriteAmounts[index];
        }

        // Track the last time sample for doing timespan calculations
        lastTime = outDataWriteTimes[index];

        // Increment and wrap the index if necessary.
        if (++index == buffer_size)
        {
            index = 0;
        }
    }

    // Return the final calculated value in bits / s, converted from bytes/ms.
    qint64 dataRate = (totalTime != 0)?(qint64)((float)totalBytes * 8.0f / ((float)totalTime / 1000.0f)):0;

    // Finally return our calculated data rate.
    return dataRate;
}

qint64 SerialLink::getCurrentInDataRate() const
{
    const qint64 now = QDateTime::currentMSecsSinceEpoch();

    // Limit the time we calculate to the recent past
    const qint64 cutoff = now - stats_timespan;

    // Grab the mutex for working with the stats variables
    QMutexLocker statsLocker(&m_statisticsMutex);

    // Now iterate through the buffer of all received data packets adding up all values
    // within now and our cutof.
    int index = inDataIndex;
    qint64 totalBytes = 0;
    qint64 totalTime = 0;
    qint64 lastTime = 0;
    int size = buffer_size;
    while (size-- > 0)
    {
        // If this data is within our cutoff time, include it in our calculations.
        // This also accounts for when the buffer is empty and filled with 0-times.
        if (inDataWriteTimes[index] > cutoff && lastTime > 0) {
            // Track the total time, using the previous time as our timeperiod.
            totalTime += inDataWriteTimes[index] - lastTime;
            totalBytes += inDataWriteAmounts[index];
        }

        // Track the last time sample for doing timespan calculations
        lastTime = inDataWriteTimes[index];

        // Increment and wrap the index if necessary.
        if (++index == buffer_size)
        {
            index = 0;
        }
    }

    // Return the final calculated value in bits / s, converted from bytes/ms.
    qint64 dataRate = (totalTime != 0)?(qint64)((float)totalBytes * 8.0f / ((float)totalTime / 1000.0f)):0;

    // Finally return our calculated data rate.
    return dataRate;
}

646
QString SerialLink::getPortName() const
647
{
Bill Bonney's avatar
Bill Bonney committed
648
    return m_portName;
pixhawk's avatar
pixhawk committed
649 650
}

Bill Bonney's avatar
Bill Bonney committed
651 652
// We should replace the accessors below with one to get the QSerialPort

653
int SerialLink::getBaudRate() const
654
{
655
    return getConnectionSpeed();
pixhawk's avatar
pixhawk committed
656 657
}

658
int SerialLink::getBaudRateType() const
659
{
Bill Bonney's avatar
Bill Bonney committed
660 661 662 663 664 665 666
    int baudRate;
    if (m_port) {
        baudRate = m_port->baudRate();
    } else {
        baudRate = m_baud;
    }
    return baudRate;
pixhawk's avatar
pixhawk committed
667 668
}

669
int SerialLink::getFlowType() const
670
{
Bill Bonney's avatar
Bill Bonney committed
671 672 673 674 675 676 677
    int flowControl;
    if (m_port) {
        flowControl = m_port->flowControl();
    } else {
        flowControl = m_flowControl;
    }
    return flowControl;
pixhawk's avatar
pixhawk committed
678 679
}

680
int SerialLink::getParityType() const
681
{
Bill Bonney's avatar
Bill Bonney committed
682 683 684 685 686 687 688
    int parity;
    if (m_port) {
        parity = m_port->parity();
    } else {
        parity = m_parity;
    }
    return parity;
pixhawk's avatar
pixhawk committed
689 690
}

691
int SerialLink::getDataBitsType() const
692
{
Bill Bonney's avatar
Bill Bonney committed
693 694 695 696 697 698 699
    int dataBits;
    if (m_port) {
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }
    return dataBits;
pixhawk's avatar
pixhawk committed
700 701
}

702
int SerialLink::getStopBitsType() const
703
{
Bill Bonney's avatar
Bill Bonney committed
704 705 706 707 708 709 710
    int stopBits;
    if (m_port) {
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
    return stopBits;
pixhawk's avatar
pixhawk committed
711 712
}

713
int SerialLink::getDataBits() const
714
{
Bill Bonney's avatar
Bill Bonney committed
715 716 717 718 719 720 721 722 723 724
    int ret;
    int dataBits;
    if (m_port) {
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }

    switch (dataBits) {
    case QSerialPort::Data5:
725 726
        ret = 5;
        break;
Bill Bonney's avatar
Bill Bonney committed
727
    case QSerialPort::Data6:
728 729
        ret = 6;
        break;
Bill Bonney's avatar
Bill Bonney committed
730
    case QSerialPort::Data7:
731 732
        ret = 7;
        break;
Bill Bonney's avatar
Bill Bonney committed
733
    case QSerialPort::Data8:
734 735 736
        ret = 8;
        break;
    default:
737
        ret = -1;
738 739 740 741 742
        break;
    }
    return ret;
}

743
int SerialLink::getStopBits() const
744
{
Bill Bonney's avatar
Bill Bonney committed
745 746 747 748 749 750
    int stopBits;
    if (m_port) {
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
751
    int ret = -1;
Bill Bonney's avatar
Bill Bonney committed
752 753
    switch (stopBits) {
    case QSerialPort::OneStop:
754 755
        ret = 1;
        break;
Bill Bonney's avatar
Bill Bonney committed
756
    case QSerialPort::TwoStop:
757 758 759 760 761 762
        ret = 2;
        break;
    default:
        ret = -1;
        break;
    }
763 764 765
    return ret;
}

pixhawk's avatar
pixhawk committed
766 767
bool SerialLink::setPortName(QString portName)
{
Bill Bonney's avatar
Bill Bonney committed
768 769 770 771 772 773 774 775
    qDebug() << "current portName " << m_portName;
    qDebug() << "setPortName to " << portName;
    bool accepted = false;
    if ((portName != m_portName)
            && (portName.trimmed().length() > 0)) {
        m_portName = portName.trimmed();
        if(m_port)
            m_port->setPortName(portName);
776

777
        emit nameChanged(m_portName); // [TODO] maybe we can eliminate this
778
        emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
779
        return accepted;
pixhawk's avatar
pixhawk committed
780
    }
Bill Bonney's avatar
Bill Bonney committed
781
    return false;
pixhawk's avatar
pixhawk committed
782 783 784 785 786
}


bool SerialLink::setBaudRateType(int rateIndex)
{
Bill Bonney's avatar
Bill Bonney committed
787 788
    Q_ASSERT_X(m_port != NULL, "setBaudRateType", "m_port is NULL");
    // These minimum and maximum baud rates were based on those enumerated in qserialport.h
789
    bool result;
Bill Bonney's avatar
Bill Bonney committed
790 791
    const int minBaud = (int)QSerialPort::Baud1200;
    const int maxBaud = (int)QSerialPort::Baud115200;
792

Bill Bonney's avatar
Bill Bonney committed
793
    if (m_port && (rateIndex >= minBaud && rateIndex <= maxBaud))
794
    {
795 796 797
        result = m_port->setBaudRate(static_cast<QSerialPort::BaudRate>(rateIndex));
        emit updateLink(this);
        return result;
pixhawk's avatar
pixhawk committed
798 799
    }

Bill Bonney's avatar
Bill Bonney committed
800
    return false;
pixhawk's avatar
pixhawk committed
801 802
}

803 804 805 806 807 808 809
bool SerialLink::setBaudRateString(const QString& rate)
{
    bool ok;
    int intrate = rate.toInt(&ok);
    if (!ok) return false;
    return setBaudRate(intrate);
}
pixhawk's avatar
pixhawk committed
810 811 812

bool SerialLink::setBaudRate(int rate)
{
Bill Bonney's avatar
Bill Bonney committed
813 814 815 816 817 818
    bool accepted = false;
    if (rate != m_baud) {
        m_baud = rate;
        accepted = true;
        if (m_port)
            accepted = m_port->setBaudRate(rate);
819
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
820
    }
821
    return accepted;
pixhawk's avatar
pixhawk committed
822 823
}

824 825
bool SerialLink::setFlowType(int flow)
{
Bill Bonney's avatar
Bill Bonney committed
826 827 828 829 830 831
    bool accepted = false;
    if (flow != m_flowControl) {
        m_flowControl = static_cast<QSerialPort::FlowControl>(flow);
        accepted = true;
        if (m_port)
            accepted = m_port->setFlowControl(static_cast<QSerialPort::FlowControl>(flow));
832
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
833 834 835 836
    }
    return accepted;
}

837 838
bool SerialLink::setParityType(int parity)
{
Bill Bonney's avatar
Bill Bonney committed
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    bool accepted = false;
    if (parity != m_parity) {
        m_parity = static_cast<QSerialPort::Parity>(parity);
        accepted = true;
        if (m_port) {
            switch (parity) {
                case QSerialPort::NoParity:
                accepted = m_port->setParity(QSerialPort::NoParity);
                break;
                case 1: // Odd Parity setting for backwards compatibilty
                    accepted = m_port->setParity(QSerialPort::OddParity);
                    break;
                case QSerialPort::EvenParity:
                    accepted = m_port->setParity(QSerialPort::EvenParity);
                    break;
                case QSerialPort::OddParity:
                    accepted = m_port->setParity(QSerialPort::OddParity);
                    break;
                default:
                    // If none of the above cases matches, there must be an error
                    accepted = false;
                    break;
                }
862
            emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
863
        }
pixhawk's avatar
pixhawk committed
864 865 866 867
    }
    return accepted;
}

868

869
bool SerialLink::setDataBits(int dataBits)
870
{
Bill Bonney's avatar
Bill Bonney committed
871 872 873 874 875 876
    bool accepted = false;
    if (dataBits != m_dataBits) {
        m_dataBits = static_cast<QSerialPort::DataBits>(dataBits);
        accepted = true;
        if (m_port)
            accepted = m_port->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
877
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
878 879 880 881
    }
    return accepted;
}

882
bool SerialLink::setStopBits(int stopBits)
883
{
Bill Bonney's avatar
Bill Bonney committed
884 885 886 887 888 889 890
    // Note 3 is OneAndAHalf stopbits.
    bool accepted = false;
    if (stopBits != m_stopBits) {
        m_stopBits = static_cast<QSerialPort::StopBits>(stopBits);
        accepted = true;
        if (m_port)
            accepted = m_port->setStopBits(static_cast<QSerialPort::StopBits>(stopBits));
891
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
892 893 894
    }
    return accepted;
}
895 896 897 898

bool SerialLink::setDataBitsType(int dataBits)
{
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
899 900
    if (dataBits != m_dataBits) {
        m_dataBits = static_cast<QSerialPort::DataBits>(dataBits);
901
        accepted = true;
Bill Bonney's avatar
Bill Bonney committed
902 903
        if (m_port)
            accepted = m_port->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
904
        emit updateLink(this);
905 906 907 908 909 910 911
    }
    return accepted;
}

bool SerialLink::setStopBitsType(int stopBits)
{
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
912 913
    if (stopBits != m_stopBits) {
        m_stopBits = static_cast<QSerialPort::StopBits>(stopBits);
914
        accepted = true;
Bill Bonney's avatar
Bill Bonney committed
915 916
        if (m_port)
            accepted = m_port->setStopBits(static_cast<QSerialPort::StopBits>(stopBits));
917
        emit updateLink(this);
918 919 920
    }
    return accepted;
}