SerialLink.cc 23.3 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
    m_stopp(false),
27
    m_reqReset(false)
pixhawk's avatar
pixhawk committed
28
{
29 30
    qDebug() << "create SerialLink " << portname << baudRate << hardwareFlowControl
             << parity << dataBits << stopBits;
pixhawk's avatar
pixhawk committed
31
    // Setup settings
Bill Bonney's avatar
Bill Bonney committed
32
    m_portName = portname.trimmed();
33

34
    if (m_portName == "" && getCurrentPorts().size() > 0)
35
    {
36
        m_portName = m_ports.first().trimmed();
37 38
    }

39 40
    qDebug() << "m_portName " << m_portName;

pixhawk's avatar
pixhawk committed
41
    // Set unique ID and add link to the list of links
Bill Bonney's avatar
Bill Bonney committed
42 43 44
    m_id = getNextLinkId();

    m_baud = baudRate;
45

46 47
    if (hardwareFlowControl)
    {
Bill Bonney's avatar
Bill Bonney committed
48
        m_flowControl = QSerialPort::HardwareControl;
49 50 51
    }
    else
    {
Bill Bonney's avatar
Bill Bonney committed
52
        m_flowControl = QSerialPort::NoFlowControl;
53 54 55
    }
    if (parity)
    {
Bill Bonney's avatar
Bill Bonney committed
56
        m_parity = QSerialPort::EvenParity;
57 58 59
    }
    else
    {
Bill Bonney's avatar
Bill Bonney committed
60
        m_parity = QSerialPort::NoParity;
61
    }
Bill Bonney's avatar
Bill Bonney committed
62 63 64

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

lm's avatar
lm committed
66
    loadSettings();
67
    LinkManager::instance()->add(this);
pixhawk's avatar
pixhawk committed
68
}
69 70 71 72 73
void SerialLink::requestReset()
{
    QMutexLocker locker(&this->m_stoppMutex);
    m_reqReset = true;
}
pixhawk's avatar
pixhawk committed
74 75 76 77

SerialLink::~SerialLink()
{
    disconnect();
Bill Bonney's avatar
Bill Bonney committed
78 79
    if(m_port) delete m_port;
    m_port = NULL;
80 81
}

82
QList<QString> SerialLink::getCurrentPorts()
83
{
84
    m_ports.clear();
85

86
    QList<QSerialPortInfo> portList =  QSerialPortInfo::availablePorts();
87

88 89
    if( portList.count() == 0){
        qDebug() << "No Ports Found" << m_ports;
90 91
    }

92
    foreach (const QSerialPortInfo &info, portList)
93
    {
Bill Bonney's avatar
Bill Bonney committed
94 95 96
//        qDebug() << "PortName    : " << info.portName()
//                 << "Description : " << info.description();
//        qDebug() << "Manufacturer: " << info.manufacturer();
97

98
        m_ports.append(info.portName());
99
    }
Bill Bonney's avatar
Bill Bonney committed
100
    return m_ports;
pixhawk's avatar
pixhawk committed
101 102
}

103 104 105 106 107
void SerialLink::loadSettings()
{
    // Load defaults from settings
    QSettings settings(QGC::COMPANYNAME, QGC::APPNAME);
    settings.sync();
108 109
    if (settings.contains("SERIALLINK_COMM_PORT"))
    {
Bill Bonney's avatar
Bill Bonney committed
110 111 112 113 114 115
        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();
116 117 118 119 120 121 122
    }
}

void SerialLink::writeSettings()
{
    // Store settings
    QSettings settings(QGC::COMPANYNAME, QGC::APPNAME);
123
    settings.setValue("SERIALLINK_COMM_PORT", getPortName());
124 125
    settings.setValue("SERIALLINK_COMM_BAUD", getBaudRateType());
    settings.setValue("SERIALLINK_COMM_PARITY", getParityType());
126 127 128
    settings.setValue("SERIALLINK_COMM_STOPBITS", getStopBits());
    settings.setValue("SERIALLINK_COMM_DATABITS", getDataBits());
    settings.setValue("SERIALLINK_COMM_FLOW_CONTROL", getFlowType());
129 130 131
    settings.sync();
}

pixhawk's avatar
pixhawk committed
132 133 134 135 136

/**
 * @brief Runs the thread
 *
 **/
137 138
void SerialLink::run()
{
pixhawk's avatar
pixhawk committed
139
    // Initialize the connection
140 141 142
    if (!hardwareConnect())
    {
        //Need to error out here.
143
        emit communicationError(getName(),"Error connecting: " + m_port->errorString());
144
        disconnect(); // This tidies up and sends the necessary signals
145
        emit communicationError(tr("Serial Port %1").arg(getPortName()), tr("Cannot read / write data - check physical USB and cable connections."));
146
        return;
147
    }
pixhawk's avatar
pixhawk committed
148 149

    // Qt way to make clear what a while(1) loop does
150 151
    qint64 msecs = QDateTime::currentMSecsSinceEpoch();
    qint64 initialmsecs = QDateTime::currentMSecsSinceEpoch();
152 153 154
    quint64 bytes = 0;
    bool triedreset = false;
    bool triedDTR = false;
155
    qint64 timeout = 5000;
156
    int linkErrorCount = 0;
157

158 159
    forever
    {
160 161
        {
            QMutexLocker locker(&this->m_stoppMutex);
162
            if(m_stopp)
163
            {
164 165 166
                m_stopp = false;
                break; // exit the thread
            }
167

168 169 170 171 172 173 174
            if (m_reqReset)
            {
                m_reqReset = false;
                communicationUpdate(getName(),"Reset requested via DTR signal");
                m_port->setDataTerminalReady(true);
                msleep(250);
                m_port->setDataTerminalReady(false);
175 176
            }
        }
177

178 179 180 181 182 183
        if (isConnected() && (linkErrorCount > 100)) {
            linkErrorCount = 0;
            disconnect();
        }

        if (m_transmitBuffer.count() > 0) {
184 185
            QMutexLocker writeLocker(&m_writeMutex);
            int numWritten = m_port->write(m_transmitBuffer);
186 187 188 189 190 191 192 193
            bool txSuccess = m_port->waitForBytesWritten(1);
            if (!txSuccess || (numWritten != m_transmitBuffer.count()))
            {
                linkErrorCount++;
                qDebug() << "TX Error! wrote" << numWritten << ", asked for " << m_transmitBuffer.count() << "bytes";
            } else {
                linkErrorCount = 0;
            }
194
            m_transmitBuffer =  m_transmitBuffer.remove(0, numWritten);
195 196
        }

197
        bool success = m_port->waitForReadyRead(10);
198

199
        if (success) { // Waits for 1/2 second [TODO][BB] lower to SerialLink::poll_interval?
200 201 202 203 204 205 206 207 208
            QByteArray readData = m_port->readAll();
            while (m_port->waitForReadyRead(10))
                readData += m_port->readAll();
            if (readData.length() > 0) {
                emit bytesReceived(this, readData);
//                qDebug() << "rx of length " << QString::number(readData.length());

                m_bytesRead += readData.length();
                m_bitsReceivedTotal += readData.length() * 8;
209
                linkErrorCount = 0;
210 211
            }
        } else {
212 213
            linkErrorCount++;
            qDebug() << "Wait read response timeout" << QTime::currentTime().toString();
214
        }
215

216
        if (bytes != m_bytesRead) // i.e things are good and data is being read.
217
        {
218
            bytes = m_bytesRead;
219 220 221 222
            msecs = QDateTime::currentMSecsSinceEpoch();
        }
        else
        {
223
            if (QDateTime::currentMSecsSinceEpoch() - msecs > timeout)
224 225 226
            {
                //It's been 10 seconds since the last data came in. Reset and try again
                msecs = QDateTime::currentMSecsSinceEpoch();
227 228 229 230 231 232 233 234 235
                if (msecs - initialmsecs > 25000)
                {
                    //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;
                }
236 237 238
                if (!triedDTR && triedreset)
                {
                    triedDTR = true;
239
                    communicationUpdate(getName(),"No data to receive on COM port. Attempting to reset via DTR signal");
240
                    qDebug() << "No data!!! Attempting reset via DTR.";
241 242 243
                    m_port->setDataTerminalReady(true);
                    msleep(250);
                    m_port->setDataTerminalReady(false);
244 245 246 247
                }
                else if (!triedreset)
                {
                    qDebug() << "No data!!! Attempting reset via reboot command.";
248
                    communicationUpdate(getName(),"No data to receive on COM port. Assuming possible terminal mode, attempting to reset via \"reboot\" command");
249
                    m_port->write("reboot\r\n",8);
250 251 252 253
                    triedreset = true;
                }
                else
                {
254
                    communicationUpdate(getName(),"No data to receive on COM port....");
255 256 257 258
                    qDebug() << "No data!!!";
                }
            }
        }
pixhawk's avatar
pixhawk committed
259
        MG::SLEEP::msleep(SerialLink::poll_interval);
260 261 262 263 264 265 266
    } // 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
267

268 269
        emit disconnected();
        emit connected(false);
270
    }
pixhawk's avatar
pixhawk committed
271 272
}

273 274
void SerialLink::writeBytes(const char* data, qint64 size)
{
Bill Bonney's avatar
Bill Bonney committed
275
    if(m_port && m_port->isOpen()) {
276
//        qDebug() << "writeBytes" << m_portName << "attempting to tx " << size << "bytes.";
pixhawk's avatar
pixhawk committed
277

278
        QByteArray byteArray(data, size);
279 280 281 282
        {
            QMutexLocker writeLocker(&m_writeMutex);
            m_transmitBuffer.append(byteArray);
        }
283

284 285
        // Increase write counter
        m_bitsSentTotal += size * 8;
286

287
        // Extra debug logging
288
//            qDebug() << byteArray->toHex();
289 290 291 292
    } else {
        disconnect();
        // Error occured
        emit communicationError(getName(), tr("Could not send data - link %1 is disconnected!").arg(getName()));
pixhawk's avatar
pixhawk committed
293 294 295 296 297 298 299 300 301
    }
}

/**
 * @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
 **/
302 303
void SerialLink::readBytes()
{
Bill Bonney's avatar
Bill Bonney committed
304 305
    m_dataMutex.lock();
    if(m_port && m_port->isOpen()) {
306 307
        const qint64 maxLength = 2048;
        char data[maxLength];
Bill Bonney's avatar
Bill Bonney committed
308
        qint64 numBytes = m_port->bytesAvailable();
James Goppert's avatar
James Goppert committed
309
        //qDebug() << "numBytes: " << numBytes;
310

311
        if(numBytes > 0) {
pixhawk's avatar
pixhawk committed
312 313 314
            /* Read as much data in buffer as possible without overflow */
            if(maxLength < numBytes) numBytes = maxLength;

Bill Bonney's avatar
Bill Bonney committed
315
            m_port->read(data, numBytes);
pixhawk's avatar
pixhawk committed
316 317 318 319 320 321 322 323 324 325 326
            QByteArray b(data, numBytes);
            emit bytesReceived(this, b);

            //qDebug() << "SerialLink::readBytes()" << std::hex << data;
            //            int i;
            //            for (i=0; i<numBytes; i++){
            //                unsigned int v=data[i];
            //
            //                fprintf(stderr,"%02x ", v);
            //            }
            //            fprintf(stderr,"\n");
Bill Bonney's avatar
Bill Bonney committed
327
            m_bitsReceivedTotal += numBytes * 8;
pixhawk's avatar
pixhawk committed
328 329
        }
    }
Bill Bonney's avatar
Bill Bonney committed
330
    m_dataMutex.unlock();
pixhawk's avatar
pixhawk committed
331 332 333 334 335 336 337 338
}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
339 340
qint64 SerialLink::bytesAvailable()
{
Bill Bonney's avatar
Bill Bonney committed
341 342
    if (m_port) {
        return m_port->bytesAvailable();
343
    } else {
344 345
        return 0;
    }
pixhawk's avatar
pixhawk committed
346 347 348 349 350 351 352
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
353 354
bool SerialLink::disconnect()
{
355 356 357
    qDebug() << "disconnect";
    if (m_port)
        qDebug() << m_port->portName();
Bill Bonney's avatar
Bill Bonney committed
358 359

    if (isRunning())
360
    {
361
        qDebug() << "running so disconnect" << m_port->portName();
362
        {
Bill Bonney's avatar
Bill Bonney committed
363 364
            QMutexLocker locker(&m_stoppMutex);
            m_stopp = true;
365
        }
Bill Bonney's avatar
Bill Bonney committed
366
        wait(); // This will terminate the thread and close the serial port
pixhawk's avatar
pixhawk committed
367

Bill Bonney's avatar
Bill Bonney committed
368
        emit disconnected(); // [TODO] There are signals from QSerialPort we should use
369 370 371
        emit connected(false);
        return true;
    }
pixhawk's avatar
pixhawk committed
372

373 374
    qDebug() << "already disconnected";
    return true;
pixhawk's avatar
pixhawk committed
375 376 377 378 379 380 381 382
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
bool SerialLink::connect()
383
{   
Bill Bonney's avatar
Bill Bonney committed
384 385
    if (isRunning())
        disconnect();
386 387
    {
        QMutexLocker locker(&this->m_stoppMutex);
Bill Bonney's avatar
Bill Bonney committed
388
        m_stopp = false;
389
    }
Bill Bonney's avatar
Bill Bonney committed
390 391

    start(LowPriority);
392
    return true;
pixhawk's avatar
pixhawk committed
393 394 395 396 397 398 399 400 401 402
}

/**
 * @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.
 **/
403 404
bool SerialLink::hardwareConnect()
{
Bill Bonney's avatar
Bill Bonney committed
405 406 407 408 409 410
    if(m_port)
    {
        qDebug() << "SerialLink:" << QString::number((long)this, 16) << "closing port";
        m_port->close();
        delete m_port;
        m_port = NULL;
411
    }
Bill Bonney's avatar
Bill Bonney committed
412 413
    qDebug() << "SerialLink: hardwareConnect to " << m_portName;
    m_port = new QSerialPort(m_portName);
pixhawk's avatar
pixhawk committed
414

Bill Bonney's avatar
Bill Bonney committed
415
    if (m_port == NULL)
416
    {
Bill Bonney's avatar
Bill Bonney committed
417 418
        emit communicationUpdate(getName(),"Error opening port: " + m_port->errorString());
        return false; // couldn't create serial port.
419
    }
Bill Bonney's avatar
Bill Bonney committed
420 421

    QObject::connect(m_port,SIGNAL(aboutToClose()),this,SIGNAL(disconnected()));
422 423
    QObject::connect(m_port, SIGNAL(error(QSerialPort::SerialPortError)),
                     this, SLOT(linkError(QSerialPort::SerialPortError)));
Bill Bonney's avatar
Bill Bonney committed
424 425 426 427 428

//    port->setCommTimeouts(QSerialPort::CtScheme_NonBlockingRead);
    m_connectionStartTime = MG::TIME::getGroundTimeNow();

    if (!m_port->open(QIODevice::ReadWrite))
429
    {
Bill Bonney's avatar
Bill Bonney committed
430 431 432
        emit communicationUpdate(getName(),"Error opening port: " + m_port->errorString());
        m_port->close();
        return false; // couldn't open serial port
433
    }
434

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

Bill Bonney's avatar
Bill Bonney committed
437 438 439 440 441 442
    // 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
443

Bill Bonney's avatar
Bill Bonney committed
444 445
    emit connected();
    emit connected(true);
446

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

450 451
    writeSettings();

Bill Bonney's avatar
Bill Bonney committed
452
    return true; // successful connection
pixhawk's avatar
pixhawk committed
453
}
454

455 456 457 458 459
void SerialLink::linkError(QSerialPort::SerialPortError error)
{
    qDebug() << error;
}

460

pixhawk's avatar
pixhawk committed
461 462 463 464 465
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
466
bool SerialLink::isConnected() const
467
{
Bill Bonney's avatar
Bill Bonney committed
468 469 470

    if (m_port) {
        bool isConnected = m_port->isOpen();
471 472
//        qDebug() << "SerialLink #" << __LINE__ << ":"<<  m_port->portName()
//                 << " isConnected =" << QString::number(isConnected);
Bill Bonney's avatar
Bill Bonney committed
473
        return isConnected;
474
    } else {
475 476
//        qDebug() << "SerialLink #" << __LINE__ << ":" <<  m_portName
//                 << " isConnected = NULL";
lm's avatar
lm committed
477 478
        return false;
    }
pixhawk's avatar
pixhawk committed
479 480
}

481
int SerialLink::getId() const
pixhawk's avatar
pixhawk committed
482
{
Bill Bonney's avatar
Bill Bonney committed
483
    return m_id;
pixhawk's avatar
pixhawk committed
484 485
}

486
QString SerialLink::getName() const
pixhawk's avatar
pixhawk committed
487
{
488
    return m_portName;
pixhawk's avatar
pixhawk committed
489 490
}

491 492 493 494
/**
  * This function maps baud rate constants to numerical equivalents.
  * It relies on the mapping given in qportsettings.h from the QSerialPort library.
  */
495
qint64 SerialLink::getNominalDataRate() const
496
{
Bill Bonney's avatar
Bill Bonney committed
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    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
535 536 537 538
    }
    return dataRate;
}

539 540
qint64 SerialLink::getTotalUpstream()
{
Bill Bonney's avatar
Bill Bonney committed
541 542 543
    m_statisticsMutex.lock();
    return m_bitsSentTotal / ((MG::TIME::getGroundTimeNow() - m_connectionStartTime) / 1000);
    m_statisticsMutex.unlock();
pixhawk's avatar
pixhawk committed
544 545
}

546 547
qint64 SerialLink::getCurrentUpstream()
{
pixhawk's avatar
pixhawk committed
548 549 550
    return 0; // TODO
}

551 552
qint64 SerialLink::getMaxUpstream()
{
pixhawk's avatar
pixhawk committed
553 554 555
    return 0; // TODO
}

556
qint64 SerialLink::getBitsSent() const
557
{
Bill Bonney's avatar
Bill Bonney committed
558
    return m_bitsSentTotal;
pixhawk's avatar
pixhawk committed
559 560
}

561
qint64 SerialLink::getBitsReceived() const
562
{
Bill Bonney's avatar
Bill Bonney committed
563
    return m_bitsReceivedTotal;
pixhawk's avatar
pixhawk committed
564 565
}

566 567
qint64 SerialLink::getTotalDownstream()
{
Bill Bonney's avatar
Bill Bonney committed
568 569 570
    m_statisticsMutex.lock();
    return m_bitsReceivedTotal / ((MG::TIME::getGroundTimeNow() - m_connectionStartTime) / 1000);
    m_statisticsMutex.unlock();
pixhawk's avatar
pixhawk committed
571 572
}

573 574
qint64 SerialLink::getCurrentDownstream()
{
pixhawk's avatar
pixhawk committed
575 576 577
    return 0; // TODO
}

578 579
qint64 SerialLink::getMaxDownstream()
{
pixhawk's avatar
pixhawk committed
580 581 582
    return 0; // TODO
}

583
bool SerialLink::isFullDuplex() const
584
{
pixhawk's avatar
pixhawk committed
585 586 587 588
    /* Serial connections are always half duplex */
    return false;
}

589
int SerialLink::getLinkQuality() const
590
{
pixhawk's avatar
pixhawk committed
591 592 593 594
    /* This feature is not supported with this interface */
    return -1;
}

595
QString SerialLink::getPortName() const
596
{
Bill Bonney's avatar
Bill Bonney committed
597
    return m_portName;
pixhawk's avatar
pixhawk committed
598 599
}

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

602
int SerialLink::getBaudRate() const
603
{
pixhawk's avatar
pixhawk committed
604 605 606
    return getNominalDataRate();
}

607
int SerialLink::getBaudRateType() const
608
{
Bill Bonney's avatar
Bill Bonney committed
609 610 611 612 613 614 615
    int baudRate;
    if (m_port) {
        baudRate = m_port->baudRate();
    } else {
        baudRate = m_baud;
    }
    return baudRate;
pixhawk's avatar
pixhawk committed
616 617
}

618
int SerialLink::getFlowType() const
619
{
Bill Bonney's avatar
Bill Bonney committed
620 621 622 623 624 625 626
    int flowControl;
    if (m_port) {
        flowControl = m_port->flowControl();
    } else {
        flowControl = m_flowControl;
    }
    return flowControl;
pixhawk's avatar
pixhawk committed
627 628
}

629
int SerialLink::getParityType() const
630
{
Bill Bonney's avatar
Bill Bonney committed
631 632 633 634 635 636 637
    int parity;
    if (m_port) {
        parity = m_port->parity();
    } else {
        parity = m_parity;
    }
    return parity;
pixhawk's avatar
pixhawk committed
638 639
}

640
int SerialLink::getDataBitsType() const
641
{
Bill Bonney's avatar
Bill Bonney committed
642 643 644 645 646 647 648
    int dataBits;
    if (m_port) {
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }
    return dataBits;
pixhawk's avatar
pixhawk committed
649 650
}

651
int SerialLink::getStopBitsType() const
652
{
Bill Bonney's avatar
Bill Bonney committed
653 654 655 656 657 658 659
    int stopBits;
    if (m_port) {
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
    return stopBits;
pixhawk's avatar
pixhawk committed
660 661
}

662
int SerialLink::getDataBits() const
663
{
Bill Bonney's avatar
Bill Bonney committed
664 665 666 667 668 669 670 671 672 673
    int ret;
    int dataBits;
    if (m_port) {
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }

    switch (dataBits) {
    case QSerialPort::Data5:
674 675
        ret = 5;
        break;
Bill Bonney's avatar
Bill Bonney committed
676
    case QSerialPort::Data6:
677 678
        ret = 6;
        break;
Bill Bonney's avatar
Bill Bonney committed
679
    case QSerialPort::Data7:
680 681
        ret = 7;
        break;
Bill Bonney's avatar
Bill Bonney committed
682
    case QSerialPort::Data8:
683 684 685
        ret = 8;
        break;
    default:
686
        ret = -1;
687 688 689 690 691
        break;
    }
    return ret;
}

692
int SerialLink::getStopBits() const
693
{
Bill Bonney's avatar
Bill Bonney committed
694 695 696 697 698 699
    int stopBits;
    if (m_port) {
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
700
    int ret = -1;
Bill Bonney's avatar
Bill Bonney committed
701 702
    switch (stopBits) {
    case QSerialPort::OneStop:
703 704
        ret = 1;
        break;
Bill Bonney's avatar
Bill Bonney committed
705
    case QSerialPort::TwoStop:
706 707 708 709 710 711
        ret = 2;
        break;
    default:
        ret = -1;
        break;
    }
712 713 714
    return ret;
}

pixhawk's avatar
pixhawk committed
715 716
bool SerialLink::setPortName(QString portName)
{
Bill Bonney's avatar
Bill Bonney committed
717 718 719 720 721 722
    qDebug() << "current portName " << m_portName;
    qDebug() << "setPortName to " << portName;
    bool accepted = false;
    if ((portName != m_portName)
            && (portName.trimmed().length() > 0)) {
        m_portName = portName.trimmed();
723
//        m_name = tr("serial port ") + portName.trimmed(); // [TODO] Do we need this?
Bill Bonney's avatar
Bill Bonney committed
724 725
        if(m_port)
            m_port->setPortName(portName);
726

727
        emit nameChanged(m_portName); // [TODO] maybe we can eliminate this
728
        emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
729
        return accepted;
pixhawk's avatar
pixhawk committed
730
    }
Bill Bonney's avatar
Bill Bonney committed
731
    return false;
pixhawk's avatar
pixhawk committed
732 733 734 735 736
}


bool SerialLink::setBaudRateType(int rateIndex)
{
Bill Bonney's avatar
Bill Bonney committed
737 738
    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
739
    bool result;
Bill Bonney's avatar
Bill Bonney committed
740 741
    const int minBaud = (int)QSerialPort::Baud1200;
    const int maxBaud = (int)QSerialPort::Baud115200;
742

Bill Bonney's avatar
Bill Bonney committed
743
    if (m_port && (rateIndex >= minBaud && rateIndex <= maxBaud))
744
    {
745 746 747
        result = m_port->setBaudRate(static_cast<QSerialPort::BaudRate>(rateIndex));
        emit updateLink(this);
        return result;
pixhawk's avatar
pixhawk committed
748 749
    }

Bill Bonney's avatar
Bill Bonney committed
750
    return false;
pixhawk's avatar
pixhawk committed
751 752
}

753 754 755 756 757 758 759
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
760 761 762

bool SerialLink::setBaudRate(int rate)
{
Bill Bonney's avatar
Bill Bonney committed
763 764 765 766 767 768
    bool accepted = false;
    if (rate != m_baud) {
        m_baud = rate;
        accepted = true;
        if (m_port)
            accepted = m_port->setBaudRate(rate);
769
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
770
    }
771
    return accepted;
pixhawk's avatar
pixhawk committed
772 773
}

774 775
bool SerialLink::setFlowType(int flow)
{
Bill Bonney's avatar
Bill Bonney committed
776 777 778 779 780 781
    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));
782
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
783 784 785 786
    }
    return accepted;
}

787 788
bool SerialLink::setParityType(int parity)
{
Bill Bonney's avatar
Bill Bonney committed
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    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;
                }
812
            emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
813
        }
pixhawk's avatar
pixhawk committed
814 815 816 817
    }
    return accepted;
}

818

819
bool SerialLink::setDataBits(int dataBits)
820
{
Bill Bonney's avatar
Bill Bonney committed
821 822 823 824 825 826
    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));
827
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
828 829 830 831
    }
    return accepted;
}

832
bool SerialLink::setStopBits(int stopBits)
833
{
Bill Bonney's avatar
Bill Bonney committed
834 835 836 837 838 839 840
    // 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));
841
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
842 843 844
    }
    return accepted;
}
845 846 847 848

bool SerialLink::setDataBitsType(int dataBits)
{
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
849 850
    if (dataBits != m_dataBits) {
        m_dataBits = static_cast<QSerialPort::DataBits>(dataBits);
851
        accepted = true;
Bill Bonney's avatar
Bill Bonney committed
852 853
        if (m_port)
            accepted = m_port->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
854
        emit updateLink(this);
855 856 857 858 859 860 861
    }
    return accepted;
}

bool SerialLink::setStopBitsType(int stopBits)
{
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
862 863
    if (stopBits != m_stopBits) {
        m_stopBits = static_cast<QSerialPort::StopBits>(stopBits);
864
        accepted = true;
Bill Bonney's avatar
Bill Bonney committed
865 866
        if (m_port)
            accepted = m_port->setStopBits(static_cast<QSerialPort::StopBits>(stopBits));
867
        emit updateLink(this);
868 869 870
    }
    return accepted;
}