SerialLink.cc 24.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>
15 16
#include <QSerialPort>
#include <QSerialPortInfo>
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
    type(""),
    m_is_cdc(true),
28
    m_stopp(false),
29
    m_reqReset(false)
pixhawk's avatar
pixhawk committed
30
{
31 32 33 34
    // 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);

35 36
    // Get the name of the current port in use.
    m_portName = portname.trimmed();
37
    if (m_portName == "" && getCurrentPorts().size() > 0)
38
    {
39
        m_portName = m_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 74

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

75
    LinkManager::instance()->add(this);
76
    qDebug() << "link added to link manager";
pixhawk's avatar
pixhawk committed
77
}
78

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

SerialLink::~SerialLink()
{
    disconnect();
Bill Bonney's avatar
Bill Bonney committed
88 89
    if(m_port) delete m_port;
    m_port = NULL;
Lorenz Meier's avatar
Lorenz Meier committed
90 91 92 93 94

    // Tell the thread to exit
    quit();
    // Wait for it to exit
    wait();
95 96
}

97
QList<QString> SerialLink::getCurrentPorts()
98
{
99
    m_ports.clear();
100

101 102
    QList<QSerialPortInfo> portList =  QSerialPortInfo::availablePorts();
    foreach (const QSerialPortInfo &info, portList)
103
    {
104
        m_ports.append(info.portName());
105
    }
106

Bill Bonney's avatar
Bill Bonney committed
107
    return m_ports;
pixhawk's avatar
pixhawk committed
108 109
}

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
bool SerialLink::isBootloader()
{
    QList<QSerialPortInfo> portList =  QSerialPortInfo::availablePorts();

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

    foreach (const QSerialPortInfo &info, portList)
    {
//        qDebug() << "PortName    : " << info.portName()
//                 << "Description : " << info.description();
//        qDebug() << "Manufacturer: " << info.manufacturer();

       if (info.portName().trimmed() == this->m_portName.trimmed() &&
               (info.description().toLower().contains("bootloader") ||
                info.description().toLower().contains("px4 bl"))) {
           qDebug() << "BOOTLOADER FOUND";
           return true;
       }
    }

    // Not found
    return false;
}

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

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

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

167
void SerialLink::checkIfCDC()
168
{
169 170 171 172 173 174 175 176 177 178 179 180
    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";
181
        m_is_cdc = false;
182 183 184 185 186
        qDebug() << "Attempting connection to an APM, with description:" << description;
    }
    else if (description.toLower().contains("px4"))
    {
        type = "px4";
187
        m_is_cdc = true;
188 189 190 191 192
        qDebug() << "Attempting connection to a PX4 unit with description:" << description;
    }
    else
    {
        type = "other";
193
        m_is_cdc = false;
194 195
        qDebug() << "Attempting connection to something unknown with description:" << description;
    }
196 197 198 199 200 201 202 203 204 205
}


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

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

218 219
    qint64 msecs = QDateTime::currentMSecsSinceEpoch();
    qint64 initialmsecs = QDateTime::currentMSecsSinceEpoch();
220
    quint64 bytes = 0;
221
    qint64 timeout = 5000;
222
    int linkErrorCount = 0;
223

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

234
        // If there are too many errors on this link, disconnect.
235 236
        if (isConnected() && (linkErrorCount > 100)) {
            qDebug() << "linkErrorCount too high: re-connecting!";
237
            linkErrorCount = 0;
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
            emit communicationUpdate(getName(), tr("Reconnecting on too many link errors"));

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

                emit disconnected();
                emit connected(false);
            }

            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;
            }

263 264
        }

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

                // Since we were successful, reset out error counter.
277 278
                linkErrorCount = 0;
            }
279 280 281 282 283 284 285

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

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

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

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

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

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

344 345
        emit disconnected();
        emit connected(false);
346
    }
pixhawk's avatar
pixhawk committed
347 348
}

349 350
void SerialLink::writeBytes(const char* data, qint64 size)
{
Bill Bonney's avatar
Bill Bonney committed
351
    if(m_port && m_port->isOpen()) {
pixhawk's avatar
pixhawk committed
352

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

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

377
        if(numBytes > 0) {
pixhawk's avatar
pixhawk committed
378 379 380
            /* Read as much data in buffer as possible without overflow */
            if(maxLength < numBytes) numBytes = maxLength;

Bill Bonney's avatar
Bill Bonney committed
381
            m_port->read(data, numBytes);
pixhawk's avatar
pixhawk committed
382 383 384
            QByteArray b(data, numBytes);
            emit bytesReceived(this, b);
        }
385
        m_dataMutex.unlock();
pixhawk's avatar
pixhawk committed
386 387 388 389 390 391 392 393 394
    }
}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
395 396
qint64 SerialLink::bytesAvailable()
{
Bill Bonney's avatar
Bill Bonney committed
397 398
    if (m_port) {
        return m_port->bytesAvailable();
399
    } else {
400 401
        return 0;
    }
pixhawk's avatar
pixhawk committed
402 403 404 405 406 407 408
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
409 410
bool SerialLink::disconnect()
{
Bill Bonney's avatar
Bill Bonney committed
411
    if (isRunning())
412 413
    {
        {
Bill Bonney's avatar
Bill Bonney committed
414 415
            QMutexLocker locker(&m_stoppMutex);
            m_stopp = true;
416
        }
Bill Bonney's avatar
Bill Bonney committed
417
        wait(); // This will terminate the thread and close the serial port
pixhawk's avatar
pixhawk committed
418

419 420
        return true;
    }
pixhawk's avatar
pixhawk committed
421

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

424 425
    qDebug() << "already disconnected";
    return true;
pixhawk's avatar
pixhawk committed
426 427 428 429 430 431 432 433
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
bool SerialLink::connect()
434
{   
435
    qDebug() << "CONNECT CALLED";
Bill Bonney's avatar
Bill Bonney committed
436 437
    if (isRunning())
        disconnect();
438 439
    {
        QMutexLocker locker(&this->m_stoppMutex);
Bill Bonney's avatar
Bill Bonney committed
440
        m_stopp = false;
441
    }
Bill Bonney's avatar
Bill Bonney committed
442

443
    start(HighPriority);
444
    return true;
pixhawk's avatar
pixhawk committed
445 446 447 448 449 450 451 452 453 454
}

/**
 * @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.
 **/
455
bool SerialLink::hardwareConnect(QString &type)
456
{
457
    if (m_port) {
Bill Bonney's avatar
Bill Bonney committed
458 459
        qDebug() << "SerialLink:" << QString::number((long)this, 16) << "closing port";
        m_port->close();
460
        QGC::SLEEP::usleep(50000);
Bill Bonney's avatar
Bill Bonney committed
461 462
        delete m_port;
        m_port = NULL;
463
    }
pixhawk's avatar
pixhawk committed
464

465
    qDebug() << "SerialLink: hardwareConnect to " << m_portName;
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

    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;
        }
    }

488
    m_port = new QSerialPort(m_portName);
Lorenz Meier's avatar
Lorenz Meier committed
489
    m_port->moveToThread(this);
490 491 492

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

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

499
    checkIfCDC();
pixhawk's avatar
pixhawk committed
500

501 502 503 504 505 506 507 508
    //    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
    }

509 510 511 512 513 514 515 516 517 518 519
    // 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));
    }

520 521
    emit communicationUpdate(getName(),"Opened port!");

Bill Bonney's avatar
Bill Bonney committed
522 523
    emit connected();
    emit connected(true);
524

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

528 529
    writeSettings();

Bill Bonney's avatar
Bill Bonney committed
530
    return true; // successful connection
pixhawk's avatar
pixhawk committed
531
}
532

533
void SerialLink::linkError(QSerialPort::SerialPortError error)
534
{
535
    if (error != QSerialPort::NoError) {
536 537 538 539 540
        // 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;
541
    }
542 543
}

544

pixhawk's avatar
pixhawk committed
545 546 547 548 549
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
550
bool SerialLink::isConnected() const
551
{
Bill Bonney's avatar
Bill Bonney committed
552 553 554

    if (m_port) {
        bool isConnected = m_port->isOpen();
555 556
//        qDebug() << "SerialLink #" << __LINE__ << ":"<<  m_port->portName()
//                 << " isConnected =" << QString::number(isConnected);
Bill Bonney's avatar
Bill Bonney committed
557
        return isConnected;
558
    } else {
559 560
//        qDebug() << "SerialLink #" << __LINE__ << ":" <<  m_portName
//                 << " isConnected = NULL";
lm's avatar
lm committed
561 562
        return false;
    }
pixhawk's avatar
pixhawk committed
563 564
}

565
int SerialLink::getId() const
pixhawk's avatar
pixhawk committed
566
{
Bill Bonney's avatar
Bill Bonney committed
567
    return m_id;
pixhawk's avatar
pixhawk committed
568 569
}

570
QString SerialLink::getName() const
pixhawk's avatar
pixhawk committed
571
{
572
    return m_portName;
pixhawk's avatar
pixhawk committed
573 574
}

575 576 577 578
/**
  * This function maps baud rate constants to numerical equivalents.
  * It relies on the mapping given in qportsettings.h from the QSerialPort library.
  */
579
qint64 SerialLink::getConnectionSpeed() const
580
{
Bill Bonney's avatar
Bill Bonney committed
581
    int baudRate;
582
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
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
        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
618 619 620 621
    }
    return dataRate;
}

622
QString SerialLink::getPortName() const
623
{
Bill Bonney's avatar
Bill Bonney committed
624
    return m_portName;
pixhawk's avatar
pixhawk committed
625 626
}

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

629
int SerialLink::getBaudRate() const
630
{
631
    return getConnectionSpeed();
pixhawk's avatar
pixhawk committed
632 633
}

634
int SerialLink::getBaudRateType() const
635
{
Bill Bonney's avatar
Bill Bonney committed
636
    int baudRate;
637
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
638 639 640 641 642
        baudRate = m_port->baudRate();
    } else {
        baudRate = m_baud;
    }
    return baudRate;
pixhawk's avatar
pixhawk committed
643 644
}

645
int SerialLink::getFlowType() const
646
{
647

Bill Bonney's avatar
Bill Bonney committed
648
    int flowControl;
649
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
650 651 652 653 654
        flowControl = m_port->flowControl();
    } else {
        flowControl = m_flowControl;
    }
    return flowControl;
pixhawk's avatar
pixhawk committed
655 656
}

657
int SerialLink::getParityType() const
658
{
659

Bill Bonney's avatar
Bill Bonney committed
660
    int parity;
661
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
662 663 664 665 666
        parity = m_port->parity();
    } else {
        parity = m_parity;
    }
    return parity;
pixhawk's avatar
pixhawk committed
667 668
}

669
int SerialLink::getDataBitsType() const
670
{
671

Bill Bonney's avatar
Bill Bonney committed
672
    int dataBits;
673
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
674 675 676 677 678
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }
    return dataBits;
pixhawk's avatar
pixhawk committed
679 680
}

681
int SerialLink::getStopBitsType() const
682
{
683

Bill Bonney's avatar
Bill Bonney committed
684
    int stopBits;
685
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
686 687 688 689 690
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
    return stopBits;
pixhawk's avatar
pixhawk committed
691 692
}

693
int SerialLink::getDataBits() const
694
{
695

Bill Bonney's avatar
Bill Bonney committed
696 697
    int ret;
    int dataBits;
698
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
699 700 701 702 703 704 705
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }

    switch (dataBits) {
    case QSerialPort::Data5:
706 707
        ret = 5;
        break;
Bill Bonney's avatar
Bill Bonney committed
708
    case QSerialPort::Data6:
709 710
        ret = 6;
        break;
Bill Bonney's avatar
Bill Bonney committed
711
    case QSerialPort::Data7:
712 713
        ret = 7;
        break;
Bill Bonney's avatar
Bill Bonney committed
714
    case QSerialPort::Data8:
715 716 717
        ret = 8;
        break;
    default:
718
        ret = -1;
719 720 721 722 723
        break;
    }
    return ret;
}

724
int SerialLink::getStopBits() const
725
{
726

Bill Bonney's avatar
Bill Bonney committed
727
    int stopBits;
728
    if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
729 730 731 732
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
733
    int ret = -1;
Bill Bonney's avatar
Bill Bonney committed
734 735
    switch (stopBits) {
    case QSerialPort::OneStop:
736 737
        ret = 1;
        break;
Bill Bonney's avatar
Bill Bonney committed
738
    case QSerialPort::TwoStop:
739 740 741 742 743 744
        ret = 2;
        break;
    default:
        ret = -1;
        break;
    }
745 746 747
    return ret;
}

pixhawk's avatar
pixhawk committed
748 749
bool SerialLink::setPortName(QString portName)
{
Bill Bonney's avatar
Bill Bonney committed
750 751
    qDebug() << "current portName " << m_portName;
    qDebug() << "setPortName to " << portName;
752
    bool accepted = true;
Bill Bonney's avatar
Bill Bonney committed
753 754 755
    if ((portName != m_portName)
            && (portName.trimmed().length() > 0)) {
        m_portName = portName.trimmed();
756 757 758

        checkIfCDC();

Bill Bonney's avatar
Bill Bonney committed
759 760
        if(m_port)
            m_port->setPortName(portName);
761

762
        emit nameChanged(m_portName); // [TODO] maybe we can eliminate this
763
        emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
764
        return accepted;
pixhawk's avatar
pixhawk committed
765
    }
Bill Bonney's avatar
Bill Bonney committed
766
    return false;
pixhawk's avatar
pixhawk committed
767 768 769 770 771
}


bool SerialLink::setBaudRateType(int rateIndex)
{
772

773
  // These minimum and maximum baud rates were based on those enumerated in <QSerialPort>
774
    bool result;
Bill Bonney's avatar
Bill Bonney committed
775 776
    const int minBaud = (int)QSerialPort::Baud1200;
    const int maxBaud = (int)QSerialPort::Baud115200;
777

778
    if ((rateIndex >= minBaud && rateIndex <= maxBaud))
779
    {
780 781 782 783 784 785 786 787 788 789
        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
790 791
    }

792
    return result;
pixhawk's avatar
pixhawk committed
793 794
}

795 796 797 798 799 800 801
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
802 803 804

bool SerialLink::setBaudRate(int rate)
{
805

Bill Bonney's avatar
Bill Bonney committed
806 807 808 809
    bool accepted = false;
    if (rate != m_baud) {
        m_baud = rate;
        accepted = true;
810
        if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
811
            accepted = m_port->setBaudRate(rate);
812
        }
813
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
814
    }
815
    return accepted;
pixhawk's avatar
pixhawk committed
816 817
}

818 819
bool SerialLink::setFlowType(int flow)
{
820

Bill Bonney's avatar
Bill Bonney committed
821 822 823 824
    bool accepted = false;
    if (flow != m_flowControl) {
        m_flowControl = static_cast<QSerialPort::FlowControl>(flow);
        accepted = true;
825
        if (m_port && !m_is_cdc)
Bill Bonney's avatar
Bill Bonney committed
826
            accepted = m_port->setFlowControl(static_cast<QSerialPort::FlowControl>(flow));
827
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
828 829 830 831
    }
    return accepted;
}

832 833
bool SerialLink::setParityType(int parity)
{
834

Bill Bonney's avatar
Bill Bonney committed
835 836 837 838
    bool accepted = false;
    if (parity != m_parity) {
        m_parity = static_cast<QSerialPort::Parity>(parity);
        accepted = true;
839
        if (m_port && !m_is_cdc) {
Bill Bonney's avatar
Bill Bonney committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
            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;
                }
858
            emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
859
        }
pixhawk's avatar
pixhawk committed
860 861 862 863
    }
    return accepted;
}

864

865
bool SerialLink::setDataBits(int dataBits)
866
{
867 868

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

880
bool SerialLink::setStopBits(int stopBits)
881
{
882

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

bool SerialLink::setDataBitsType(int dataBits)
{
897

898
    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;
902
        if (m_port && !m_is_cdc)
Bill Bonney's avatar
Bill Bonney committed
903
            accepted = m_port->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
904
        emit updateLink(this);
905 906 907 908 909 910
    }
    return accepted;
}

bool SerialLink::setStopBitsType(int stopBits)
{
911

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