SerialLink.cc 24.1 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>
15 16
#include <QSerialPort>
#include <QSerialPortInfo>
pixhawk's avatar
pixhawk committed
17
#include "SerialLink.h"
18
#include "QGC.h"
pixhawk's avatar
pixhawk committed
19 20
#include <MG.h>

21 22
SerialLink::SerialLink(QString portname, int baudRate, bool hardwareFlowControl, bool parity,
                       int dataBits, int stopBits) :
Bill Bonney's avatar
Bill Bonney committed
23
    m_bytesRead(0),
24
    m_port(Q_NULLPTR),
25 26
    type(""),
    m_is_cdc(true),
27
    m_stopp(false),
28
    m_reqReset(false)
pixhawk's avatar
pixhawk committed
29
{
30 31 32 33
    // We're doing it wrong - because the Qt folks got the API wrong:
    // http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/
    moveToThread(this);

34 35
    // Get the name of the current port in use.
    m_portName = portname.trimmed();
36 37
    QList<QString> ports = getCurrentPorts();
    if (m_portName == "" && ports.size() > 0)
38
    {
39
        m_portName = ports.first().trimmed();
40 41
    }

42 43
    checkIfCDC();

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

    m_baud = baudRate;
48

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

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

lm's avatar
lm committed
69
    loadSettings();
Lorenz Meier's avatar
Lorenz Meier committed
70 71 72 73

    qDebug() << "create SerialLink " << portname << baudRate << hardwareFlowControl
             << parity << dataBits << stopBits;
    qDebug() << "m_portName " << m_portName;
pixhawk's avatar
pixhawk committed
74
}
75

76 77 78 79 80
void SerialLink::requestReset()
{
    QMutexLocker locker(&this->m_stoppMutex);
    m_reqReset = true;
}
pixhawk's avatar
pixhawk committed
81 82 83

SerialLink::~SerialLink()
{
84
    _disconnect();
Bill Bonney's avatar
Bill Bonney committed
85 86
    if(m_port) delete m_port;
    m_port = NULL;
Lorenz Meier's avatar
Lorenz Meier committed
87 88 89 90 91

    // Tell the thread to exit
    quit();
    // Wait for it to exit
    wait();
92 93
}

94
QList<QString> SerialLink::getCurrentPorts()
95
{
96
    QList<QString> ports;
97

98 99
    QList<QSerialPortInfo> portList =  QSerialPortInfo::availablePorts();
    foreach (const QSerialPortInfo &info, portList)
100
    {
101
        ports.append(info.portName());
102
    }
103

104
    return ports;
pixhawk's avatar
pixhawk committed
105 106
}

107 108 109 110 111 112 113 114 115 116
bool SerialLink::isBootloader()
{
    QList<QSerialPortInfo> portList =  QSerialPortInfo::availablePorts();

    if( portList.count() == 0){
        return false;
    }

    foreach (const QSerialPortInfo &info, portList)
    {
117
        // XXX debug statements will be removed once we have 100% stable link reports
118 119 120 121 122 123
//        qDebug() << "PortName    : " << info.portName()
//                 << "Description : " << info.description();
//        qDebug() << "Manufacturer: " << info.manufacturer();

       if (info.portName().trimmed() == this->m_portName.trimmed() &&
               (info.description().toLower().contains("bootloader") ||
124 125 126
                info.description().toLower().contains("px4 bl") ||
                info.description().toLower().contains("px4 fmu v1.6"))) {
//           qDebug() << "BOOTLOADER FOUND";
127 128 129 130 131 132 133 134
           return true;
       }
    }

    // Not found
    return false;
}

135 136 137
void SerialLink::loadSettings()
{
    // Load defaults from settings
138
    QSettings settings;
139 140
    if (settings.contains("SERIALLINK_COMM_PORT"))
    {
Bill Bonney's avatar
Bill Bonney committed
141
        m_portName = settings.value("SERIALLINK_COMM_PORT").toString();
142 143
        checkIfCDC();

Bill Bonney's avatar
Bill Bonney committed
144 145 146 147 148
        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();
149 150 151 152 153 154
    }
}

void SerialLink::writeSettings()
{
    // Store settings
155
    QSettings settings;
156
    settings.setValue("SERIALLINK_COMM_PORT", getPortName());
157 158
    settings.setValue("SERIALLINK_COMM_BAUD", getBaudRateType());
    settings.setValue("SERIALLINK_COMM_PARITY", getParityType());
159 160 161
    settings.setValue("SERIALLINK_COMM_STOPBITS", getStopBits());
    settings.setValue("SERIALLINK_COMM_DATABITS", getDataBits());
    settings.setValue("SERIALLINK_COMM_FLOW_CONTROL", getFlowType());
162 163
}

164
void SerialLink::checkIfCDC()
165
{
166 167 168 169 170 171 172 173 174 175 176 177
    QString description = "X";
    foreach (QSerialPortInfo info,QSerialPortInfo::availablePorts())
    {
        if (m_portName == info.portName())
        {
            description = info.description();
            break;
        }
    }
    if (description.toLower().contains("mega") && description.contains("2560"))
    {
        type = "apm";
178
        m_is_cdc = false;
179 180 181 182 183
        qDebug() << "Attempting connection to an APM, with description:" << description;
    }
    else if (description.toLower().contains("px4"))
    {
        type = "px4";
184
        m_is_cdc = true;
185 186 187 188 189
        qDebug() << "Attempting connection to a PX4 unit with description:" << description;
    }
    else
    {
        type = "other";
190
        m_is_cdc = false;
191 192
        qDebug() << "Attempting connection to something unknown with description:" << description;
    }
193 194 195 196 197 198 199 200 201 202
}


/**
 * @brief Runs the thread
 *
 **/
void SerialLink::run()
{
    checkIfCDC();
203

pixhawk's avatar
pixhawk committed
204
    // Initialize the connection
205
    if (!hardwareConnect(type)) {
206
        //Need to error out here.
207 208 209 210 211
        QString err("Could not create port.");
        if (m_port) {
            err = m_port->errorString();
        }
        emit communicationError(getName(),"Error connecting: " + err);
212
        return;
213
    }
pixhawk's avatar
pixhawk committed
214

215 216
    qint64 msecs = QDateTime::currentMSecsSinceEpoch();
    qint64 initialmsecs = QDateTime::currentMSecsSinceEpoch();
217
    quint64 bytes = 0;
218
    qint64 timeout = 5000;
219
    int linkErrorCount = 0;
220

221
    // Qt way to make clear what a while(1) loop does
222
    forever {
223
        {
224
            QMutexLocker locker(&this->m_stoppMutex);
225
            if (m_stopp) {
226 227 228
                m_stopp = false;
                break; // exit the thread
            }
229
        }
230

231
        // If there are too many errors on this link, disconnect.
232
        if (isConnected() && (linkErrorCount > 150)) {
233
            qDebug() << "linkErrorCount too high: re-connecting!";
234
            linkErrorCount = 0;
235
            emit communicationUpdate(getName(), tr("Link timeout, not receiving any data, attempting reconnect"));
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

            if (m_port) {
                m_port->close();
                delete m_port;
                m_port = NULL;

                emit disconnected();
            }

            QGC::SLEEP::msleep(500);

            unsigned tries = 0;
            const unsigned tries_max = 15;
            while (!hardwareConnect(type) && tries < tries_max) {
                tries++;
                QGC::SLEEP::msleep(500);
            }

            // Give up
            if (tries == tries_max) {
                break;
            }

259 260
        }

261
        // Write all our buffered data out the serial port.
262
        if (m_transmitBuffer.count() > 0) {
263
            m_writeMutex.lock();
264
            int numWritten = m_port->write(m_transmitBuffer);
265 266
            bool txSuccess = m_port->flush();
            txSuccess |= m_port->waitForBytesWritten(10);
267
            if (!txSuccess || (numWritten != m_transmitBuffer.count())) {
268
                linkErrorCount++;
269
                qDebug() << "TX Error! written:" << txSuccess << "wrote" << numWritten << ", asked for " << m_transmitBuffer.count() << "bytes";
270 271
            }
            else {
272 273

                // Since we were successful, reset out error counter.
274 275
                linkErrorCount = 0;
            }
276 277 278 279 280 281 282

            // 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.
283 284
            QMutexLocker dataRateLocker(&dataRateMutex);
            logDataRateToBuffer(outDataWriteAmounts, outDataWriteTimes, &outDataIndex, numWritten, QDateTime::currentMSecsSinceEpoch());
285 286
        }

287 288
        //wait n msecs for data to be ready
        //[TODO][BB] lower to SerialLink::poll_interval?
289
        m_dataMutex.lock();
290
        bool success = m_port->waitForReadyRead(20);
291

292
        if (success) {
293 294 295
            QByteArray readData = m_port->readAll();
            while (m_port->waitForReadyRead(10))
                readData += m_port->readAll();
296
            m_dataMutex.unlock();
297 298 299
            if (readData.length() > 0) {
                emit bytesReceived(this, readData);

300
                // Log this data reception for this timestep
301 302
                QMutexLocker dataRateLocker(&dataRateMutex);
                logDataRateToBuffer(inDataWriteAmounts, inDataWriteTimes, &inDataIndex, readData.length(), QDateTime::currentMSecsSinceEpoch());
303 304

                // Track the total amount of data read.
305
                m_bytesRead += readData.length();
306
                linkErrorCount = 0;
307
            }
308 309
        }
        else {
310
            m_dataMutex.unlock();
311
            linkErrorCount++;
312
        }
313

314
        if (bytes != m_bytesRead) { // i.e things are good and data is being read.
315
            bytes = m_bytesRead;
316 317
            msecs = QDateTime::currentMSecsSinceEpoch();
        }
318 319
        else {
            if (QDateTime::currentMSecsSinceEpoch() - msecs > timeout) {
320 321
                //It's been 10 seconds since the last data came in. Reset and try again
                msecs = QDateTime::currentMSecsSinceEpoch();
322
                if (msecs - initialmsecs > 25000) {
323 324 325 326 327 328 329
                    //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;
                }
330 331
            }
        }
332
        QGC::SLEEP::msleep(SerialLink::poll_interval);
333 334
    } // end of forever
    
335
    if (m_port) {
336 337 338 339
        qDebug() << "Closing Port #"<< __LINE__ << m_port->portName();
        m_port->close();
        delete m_port;
        m_port = NULL;
pixhawk's avatar
pixhawk committed
340

341
        emit disconnected();
342
    }
pixhawk's avatar
pixhawk committed
343 344
}

345 346
void SerialLink::writeBytes(const char* data, qint64 size)
{
Bill Bonney's avatar
Bill Bonney committed
347
    if(m_port && m_port->isOpen()) {
pixhawk's avatar
pixhawk committed
348

349
        QByteArray byteArray(data, size);
350 351 352
        m_writeMutex.lock();
        m_transmitBuffer.append(byteArray);
        m_writeMutex.unlock();
353 354 355
    } else {
        // Error occured
        emit communicationError(getName(), tr("Could not send data - link %1 is disconnected!").arg(getName()));
pixhawk's avatar
pixhawk committed
356 357 358 359 360 361 362 363 364
    }
}

/**
 * @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
 **/
365 366
void SerialLink::readBytes()
{
Bill Bonney's avatar
Bill Bonney committed
367
    if(m_port && m_port->isOpen()) {
368 369
        const qint64 maxLength = 2048;
        char data[maxLength];
370
        m_dataMutex.lock();
Bill Bonney's avatar
Bill Bonney committed
371
        qint64 numBytes = m_port->bytesAvailable();
372

373
        if(numBytes > 0) {
pixhawk's avatar
pixhawk committed
374 375 376
            /* Read as much data in buffer as possible without overflow */
            if(maxLength < numBytes) numBytes = maxLength;

Bill Bonney's avatar
Bill Bonney committed
377
            m_port->read(data, numBytes);
pixhawk's avatar
pixhawk committed
378 379 380
            QByteArray b(data, numBytes);
            emit bytesReceived(this, b);
        }
381
        m_dataMutex.unlock();
pixhawk's avatar
pixhawk committed
382 383 384 385 386 387 388 389
    }
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
390
bool SerialLink::_disconnect(void)
391
{
Bill Bonney's avatar
Bill Bonney committed
392
    if (isRunning())
393 394
    {
        {
Bill Bonney's avatar
Bill Bonney committed
395 396
            QMutexLocker locker(&m_stoppMutex);
            m_stopp = true;
397
        }
Bill Bonney's avatar
Bill Bonney committed
398
        wait(); // This will terminate the thread and close the serial port
pixhawk's avatar
pixhawk committed
399

400 401
        return true;
    }
pixhawk's avatar
pixhawk committed
402

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

405 406
    qDebug() << "already disconnected";
    return true;
pixhawk's avatar
pixhawk committed
407 408 409 410 411 412 413
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
414
bool SerialLink::_connect(void)
415
{   
416
    qDebug() << "CONNECT CALLED";
Bill Bonney's avatar
Bill Bonney committed
417
    if (isRunning())
418
        _disconnect();
419 420
    {
        QMutexLocker locker(&this->m_stoppMutex);
Bill Bonney's avatar
Bill Bonney committed
421
        m_stopp = false;
422
    }
Bill Bonney's avatar
Bill Bonney committed
423

424
    start(HighPriority);
425
    return true;
pixhawk's avatar
pixhawk committed
426 427 428
}

/**
429
 * @brief This function is called indirectly by the _connect() call.
pixhawk's avatar
pixhawk committed
430
 *
431
 * The _connect() function starts the thread and indirectly calls this method.
pixhawk's avatar
pixhawk committed
432 433
 *
 * @return True if the connection could be established, false otherwise
434
 * @see _connect() For the right function to establish the connection.
pixhawk's avatar
pixhawk committed
435
 **/
436
bool SerialLink::hardwareConnect(QString &type)
437
{
438
    if (m_port) {
Bill Bonney's avatar
Bill Bonney committed
439 440
        qDebug() << "SerialLink:" << QString::number((long)this, 16) << "closing port";
        m_port->close();
441
        QGC::SLEEP::usleep(50000);
Bill Bonney's avatar
Bill Bonney committed
442 443
        delete m_port;
        m_port = NULL;
444
    }
pixhawk's avatar
pixhawk committed
445

446
    qDebug() << "SerialLink: hardwareConnect to " << m_portName;
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

    if (isBootloader()) {
        qDebug() << "Not connecting to a bootloader, waiting for 2nd chance";

        const unsigned retry_limit = 12;
        unsigned retries;

        for (retries = 0; retries < retry_limit; retries++) {
            if (!isBootloader()) {
                break;
            }
            QGC::SLEEP::msleep(500);
        }

        // Check limit
        if (retries == retry_limit) {

            // bail out
            return false;
        }
    }

469
    m_port = new QSerialPort(m_portName);
Lorenz Meier's avatar
Lorenz Meier committed
470
    m_port->moveToThread(this);
471 472 473

    if (!m_port) {
        emit communicationUpdate(getName(),"Error opening port: " + m_portName);
Bill Bonney's avatar
Bill Bonney committed
474
        return false; // couldn't create serial port.
475
    }
Bill Bonney's avatar
Bill Bonney committed
476 477

    QObject::connect(m_port,SIGNAL(aboutToClose()),this,SIGNAL(disconnected()));
478
    QObject::connect(m_port, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(linkError(QSerialPort::SerialPortError)));
Bill Bonney's avatar
Bill Bonney committed
479

480
    checkIfCDC();
pixhawk's avatar
pixhawk committed
481

482 483 484 485 486 487 488 489
    //    port->setCommTimeouts(QSerialPort::CtScheme_NonBlockingRead);

    if (!m_port->open(QIODevice::ReadWrite)) {
        emit communicationUpdate(getName(),"Error opening port: " + m_port->errorString());
        m_port->close();
        return false; // couldn't open serial port
    }

490 491 492 493 494 495 496 497 498 499 500
    // Need to configure the port
    // NOTE: THE PORT NEEDS TO BE OPEN!
    if (!m_is_cdc) {
        qDebug() << "Configuring 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));
    }

501 502
    emit communicationUpdate(getName(),"Opened port!");

Bill Bonney's avatar
Bill Bonney committed
503
    emit connected();
504

505
    qDebug() << "CONNECTING LINK: " << __FILE__ << __LINE__ << "type:" << type << "with settings" << m_port->portName()
Bill Bonney's avatar
Bill Bonney committed
506
             << getBaudRate() << getDataBits() << getParityType() << getStopBits();
507

508 509
    writeSettings();

Bill Bonney's avatar
Bill Bonney committed
510
    return true; // successful connection
pixhawk's avatar
pixhawk committed
511
}
512

513
void SerialLink::linkError(QSerialPort::SerialPortError error)
514
{
515
    if (error != QSerialPort::NoError) {
516 517 518 519 520
        // You can use the following qDebug output as needed during development. Make sure to comment it back out
        // when you are done. The reason for this is that this signal is very noisy. For example if you try to
        // connect to a PixHawk before it is ready to accept the connection it will output a continuous stream
        // of errors until the Pixhawk responds.
        //qDebug() << "SerialLink::linkError" << error;
521
    }
522 523
}

524

pixhawk's avatar
pixhawk committed
525 526 527 528 529
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
530
bool SerialLink::isConnected() const
531
{
Bill Bonney's avatar
Bill Bonney committed
532 533 534

    if (m_port) {
        bool isConnected = m_port->isOpen();
535 536
//        qDebug() << "SerialLink #" << __LINE__ << ":"<<  m_port->portName()
//                 << " isConnected =" << QString::number(isConnected);
Bill Bonney's avatar
Bill Bonney committed
537
        return isConnected;
538
    } else {
539 540
//        qDebug() << "SerialLink #" << __LINE__ << ":" <<  m_portName
//                 << " isConnected = NULL";
lm's avatar
lm committed
541 542
        return false;
    }
pixhawk's avatar
pixhawk committed
543 544
}

545
int SerialLink::getId() const
pixhawk's avatar
pixhawk committed
546
{
Bill Bonney's avatar
Bill Bonney committed
547
    return m_id;
pixhawk's avatar
pixhawk committed
548 549
}

550
QString SerialLink::getName() const
pixhawk's avatar
pixhawk committed
551
{
552
    return m_portName;
pixhawk's avatar
pixhawk committed
553 554
}

555 556 557 558
/**
  * This function maps baud rate constants to numerical equivalents.
  * It relies on the mapping given in qportsettings.h from the QSerialPort library.
  */
559
qint64 SerialLink::getConnectionSpeed() const
560
{
Bill Bonney's avatar
Bill Bonney committed
561
    int baudRate;
562
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
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
        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.
        default:
            dataRate = -1;
            break;
pixhawk's avatar
pixhawk committed
598 599 600 601
    }
    return dataRate;
}

602
QString SerialLink::getPortName() const
603
{
Bill Bonney's avatar
Bill Bonney committed
604
    return m_portName;
pixhawk's avatar
pixhawk committed
605 606
}

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

609
int SerialLink::getBaudRate() const
610
{
611
    return getConnectionSpeed();
pixhawk's avatar
pixhawk committed
612 613
}

614
int SerialLink::getBaudRateType() const
615
{
Bill Bonney's avatar
Bill Bonney committed
616
    int baudRate;
617
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
618 619 620 621 622
        baudRate = m_port->baudRate();
    } else {
        baudRate = m_baud;
    }
    return baudRate;
pixhawk's avatar
pixhawk committed
623 624
}

625
int SerialLink::getFlowType() const
626
{
627

Bill Bonney's avatar
Bill Bonney committed
628
    int flowControl;
629
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
630 631 632 633 634
        flowControl = m_port->flowControl();
    } else {
        flowControl = m_flowControl;
    }
    return flowControl;
pixhawk's avatar
pixhawk committed
635 636
}

637
int SerialLink::getParityType() const
638
{
639

Bill Bonney's avatar
Bill Bonney committed
640
    int parity;
641
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
642 643 644 645 646
        parity = m_port->parity();
    } else {
        parity = m_parity;
    }
    return parity;
pixhawk's avatar
pixhawk committed
647 648
}

649
int SerialLink::getDataBitsType() const
650
{
651

Bill Bonney's avatar
Bill Bonney committed
652
    int dataBits;
653
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
654 655 656 657 658
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }
    return dataBits;
pixhawk's avatar
pixhawk committed
659 660
}

661
int SerialLink::getStopBitsType() const
662
{
663

Bill Bonney's avatar
Bill Bonney committed
664
    int stopBits;
665
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
666 667 668 669 670
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
    return stopBits;
pixhawk's avatar
pixhawk committed
671 672
}

673
int SerialLink::getDataBits() const
674
{
675

Bill Bonney's avatar
Bill Bonney committed
676 677
    int ret;
    int dataBits;
678
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
679 680 681 682 683 684 685
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }

    switch (dataBits) {
    case QSerialPort::Data5:
686 687
        ret = 5;
        break;
Bill Bonney's avatar
Bill Bonney committed
688
    case QSerialPort::Data6:
689 690
        ret = 6;
        break;
Bill Bonney's avatar
Bill Bonney committed
691
    case QSerialPort::Data7:
692 693
        ret = 7;
        break;
Bill Bonney's avatar
Bill Bonney committed
694
    case QSerialPort::Data8:
695 696 697
        ret = 8;
        break;
    default:
698
        ret = -1;
699 700 701 702 703
        break;
    }
    return ret;
}

704
int SerialLink::getStopBits() const
705
{
706

Bill Bonney's avatar
Bill Bonney committed
707
    int stopBits;
708
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
709 710 711 712
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
713
    int ret = -1;
Bill Bonney's avatar
Bill Bonney committed
714 715
    switch (stopBits) {
    case QSerialPort::OneStop:
716 717
        ret = 1;
        break;
Bill Bonney's avatar
Bill Bonney committed
718
    case QSerialPort::TwoStop:
719 720 721 722 723 724
        ret = 2;
        break;
    default:
        ret = -1;
        break;
    }
725 726 727
    return ret;
}

pixhawk's avatar
pixhawk committed
728 729
bool SerialLink::setPortName(QString portName)
{
Bill Bonney's avatar
Bill Bonney committed
730 731
    qDebug() << "current portName " << m_portName;
    qDebug() << "setPortName to " << portName;
732
    bool accepted = true;
Bill Bonney's avatar
Bill Bonney committed
733 734 735
    if ((portName != m_portName)
            && (portName.trimmed().length() > 0)) {
        m_portName = portName.trimmed();
736 737 738

        checkIfCDC();

Bill Bonney's avatar
Bill Bonney committed
739 740
        if(m_port)
            m_port->setPortName(portName);
741

742
        emit nameChanged(m_portName); // [TODO] maybe we can eliminate this
743
        emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
744
        return accepted;
pixhawk's avatar
pixhawk committed
745
    }
Bill Bonney's avatar
Bill Bonney committed
746
    return false;
pixhawk's avatar
pixhawk committed
747 748 749 750 751
}


bool SerialLink::setBaudRateType(int rateIndex)
{
752

753
  // These minimum and maximum baud rates were based on those enumerated in <QSerialPort>
754
    bool result;
Bill Bonney's avatar
Bill Bonney committed
755 756
    const int minBaud = (int)QSerialPort::Baud1200;
    const int maxBaud = (int)QSerialPort::Baud115200;
757

758
    if ((rateIndex >= minBaud && rateIndex <= maxBaud))
759
    {
760 761 762 763 764 765 766 767 768 769
        if (!m_is_cdc && m_port)
        {
            result = m_port->setBaudRate(static_cast<QSerialPort::BaudRate>(rateIndex));
            emit updateLink(this);
        } else {
            m_baud = (int)rateIndex;
            result = true;
        }
    } else {
        result = false;
pixhawk's avatar
pixhawk committed
770 771
    }

772
    return result;
pixhawk's avatar
pixhawk committed
773 774
}

775 776 777 778 779 780 781
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
782 783 784

bool SerialLink::setBaudRate(int rate)
{
785

Bill Bonney's avatar
Bill Bonney committed
786 787 788 789
    bool accepted = false;
    if (rate != m_baud) {
        m_baud = rate;
        accepted = true;
790
        if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
791
            accepted = m_port->setBaudRate(rate);
792
        }
793
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
794
    }
795
    return accepted;
pixhawk's avatar
pixhawk committed
796 797
}

798 799
bool SerialLink::setFlowType(int flow)
{
800

Bill Bonney's avatar
Bill Bonney committed
801 802 803 804
    bool accepted = false;
    if (flow != m_flowControl) {
        m_flowControl = static_cast<QSerialPort::FlowControl>(flow);
        accepted = true;
805
        if (m_port && !m_is_cdc)
Bill Bonney's avatar
Bill Bonney committed
806
            accepted = m_port->setFlowControl(static_cast<QSerialPort::FlowControl>(flow));
807
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
808 809 810 811
    }
    return accepted;
}

812 813
bool SerialLink::setParityType(int parity)
{
814

Bill Bonney's avatar
Bill Bonney committed
815 816 817 818
    bool accepted = false;
    if (parity != m_parity) {
        m_parity = static_cast<QSerialPort::Parity>(parity);
        accepted = true;
819
        if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
            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;
                }
838
            emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
839
        }
pixhawk's avatar
pixhawk committed
840 841 842 843
    }
    return accepted;
}

844

845
bool SerialLink::setDataBits(int dataBits)
846
{
847 848

    qDebug("SET DATA BITS");
Bill Bonney's avatar
Bill Bonney committed
849 850 851 852
    bool accepted = false;
    if (dataBits != m_dataBits) {
        m_dataBits = static_cast<QSerialPort::DataBits>(dataBits);
        accepted = true;
853
        if (m_port && !m_is_cdc)
Bill Bonney's avatar
Bill Bonney committed
854
            accepted = m_port->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
855
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
856 857 858 859
    }
    return accepted;
}

860
bool SerialLink::setStopBits(int stopBits)
861
{
862

Bill Bonney's avatar
Bill Bonney committed
863 864 865 866 867
    // Note 3 is OneAndAHalf stopbits.
    bool accepted = false;
    if (stopBits != m_stopBits) {
        m_stopBits = static_cast<QSerialPort::StopBits>(stopBits);
        accepted = true;
868
        if (m_port && !m_is_cdc)
Bill Bonney's avatar
Bill Bonney committed
869
            accepted = m_port->setStopBits(static_cast<QSerialPort::StopBits>(stopBits));
870
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
871 872 873
    }
    return accepted;
}
874 875 876

bool SerialLink::setDataBitsType(int dataBits)
{
877

878
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
879 880
    if (dataBits != m_dataBits) {
        m_dataBits = static_cast<QSerialPort::DataBits>(dataBits);
881
        accepted = true;
882
        if (m_port && !m_is_cdc)
Bill Bonney's avatar
Bill Bonney committed
883
            accepted = m_port->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
884
        emit updateLink(this);
885 886 887 888 889 890
    }
    return accepted;
}

bool SerialLink::setStopBitsType(int stopBits)
{
891

892
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
893 894
    if (stopBits != m_stopBits) {
        m_stopBits = static_cast<QSerialPort::StopBits>(stopBits);
895
        accepted = true;
896
        if (m_port && !m_is_cdc)
Bill Bonney's avatar
Bill Bonney committed
897
            accepted = m_port->setStopBits(static_cast<QSerialPort::StopBits>(stopBits));
898
        emit updateLink(this);
899 900 901
    }
    return accepted;
}