SerialLink.cc 22.4 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 31
    // Get the name of the current port in use.
    m_portName = portname.trimmed();
32
    if (m_portName == "" && getCurrentPorts().size() > 0)
33
    {
34
        m_portName = m_ports.first().trimmed();
35 36
    }

pixhawk's avatar
pixhawk committed
37
    // Set unique ID and add link to the list of links
Bill Bonney's avatar
Bill Bonney committed
38 39 40
    m_id = getNextLinkId();

    m_baud = baudRate;
41

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

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

lm's avatar
lm committed
62
    loadSettings();
Lorenz Meier's avatar
Lorenz Meier committed
63 64 65 66 67

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

68
    LinkManager::instance()->add(this);
pixhawk's avatar
pixhawk committed
69
}
70

71 72 73 74 75
void SerialLink::requestReset()
{
    QMutexLocker locker(&this->m_stoppMutex);
    m_reqReset = true;
}
pixhawk's avatar
pixhawk committed
76 77 78 79

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

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

88
    QList<QSerialPortInfo> portList =  QSerialPortInfo::availablePorts();
89

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

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

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

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

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

pixhawk's avatar
pixhawk committed
134 135 136 137 138

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

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

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

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

176
        // If there are too many errors on this link, disconnect.
Lorenz Meier's avatar
Lorenz Meier committed
177
        if (isConnected() && (linkErrorCount > 1000)) {
178
            qDebug() << "linkErrorCount too high: disconnecting!";
179
            linkErrorCount = 0;
180
            emit communicationUpdate(getName(), tr("Disconnecting on too many link errors"));
181 182 183
            disconnect();
        }

184
        // Write all our buffered data out the serial port.
185
        if (m_transmitBuffer.count() > 0) {
186
            m_writeMutex.lock();
187
            int numWritten = m_port->write(m_transmitBuffer);
188
            bool txSuccess = m_port->waitForBytesWritten(5);
189
            if (!txSuccess || (numWritten != m_transmitBuffer.count())) {
190 191
                linkErrorCount++;
                qDebug() << "TX Error! wrote" << numWritten << ", asked for " << m_transmitBuffer.count() << "bytes";
192 193
            }
            else {
194 195

                // Since we were successful, reset out error counter.
196 197
                linkErrorCount = 0;
            }
198 199 200 201 202 203 204

            // 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.
205 206
            QMutexLocker dataRateLocker(&dataRateMutex);
            logDataRateToBuffer(outDataWriteAmounts, outDataWriteTimes, &outDataIndex, numWritten, QDateTime::currentMSecsSinceEpoch());
207 208
        }

209 210
        //wait n msecs for data to be ready
        //[TODO][BB] lower to SerialLink::poll_interval?
211
        m_dataMutex.lock();
212
        bool success = m_port->waitForReadyRead(10);
213

214
        if (success) {
215 216 217
            QByteArray readData = m_port->readAll();
            while (m_port->waitForReadyRead(10))
                readData += m_port->readAll();
218
            m_dataMutex.unlock();
219 220 221
            if (readData.length() > 0) {
                emit bytesReceived(this, readData);

222
                // Log this data reception for this timestep
223 224
                QMutexLocker dataRateLocker(&dataRateMutex);
                logDataRateToBuffer(inDataWriteAmounts, inDataWriteTimes, &inDataIndex, readData.length(), QDateTime::currentMSecsSinceEpoch());
225 226

                // Track the total amount of data read.
227
                m_bytesRead += readData.length();
228
                linkErrorCount = 0;
229
            }
230 231
        }
        else {
232
            m_dataMutex.unlock();
233
            linkErrorCount++;
234
        }
235

236
        if (bytes != m_bytesRead) { // i.e things are good and data is being read.
237
            bytes = m_bytesRead;
238 239
            msecs = QDateTime::currentMSecsSinceEpoch();
        }
240 241
        else {
            if (QDateTime::currentMSecsSinceEpoch() - msecs > timeout) {
242 243
                //It's been 10 seconds since the last data came in. Reset and try again
                msecs = QDateTime::currentMSecsSinceEpoch();
244
                if (msecs - initialmsecs > 25000) {
245 246 247 248 249 250 251
                    //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;
                }
252
                if (!triedDTR && triedreset) {
253
                    triedDTR = true;
254
                    emit communicationUpdate(getName(),"No data to receive on COM port. Attempting to reset via DTR signal");
255
                    qDebug() << "No data!!! Attempting reset via DTR.";
256 257 258
                    m_port->setDataTerminalReady(true);
                    msleep(250);
                    m_port->setDataTerminalReady(false);
259
                }
260
                else if (!triedreset) {
261
                    qDebug() << "No data!!! Attempting reset via reboot command.";
262
                    emit communicationUpdate(getName(),"No data to receive on COM port. Assuming possible terminal mode, attempting to reset via \"reboot\" command");
263
                    m_port->write("reboot\r\n",8);
264 265
                    triedreset = true;
                }
266 267
                else {
                    emit communicationUpdate(getName(),"No data to receive on COM port....");
268 269 270 271
                    qDebug() << "No data!!!";
                }
            }
        }
pixhawk's avatar
pixhawk committed
272
        MG::SLEEP::msleep(SerialLink::poll_interval);
273 274 275 276 277 278 279
    } // 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
280

281 282
        emit disconnected();
        emit connected(false);
283
    }
pixhawk's avatar
pixhawk committed
284 285
}

286 287
void SerialLink::writeBytes(const char* data, qint64 size)
{
Bill Bonney's avatar
Bill Bonney committed
288
    if(m_port && m_port->isOpen()) {
pixhawk's avatar
pixhawk committed
289

290
        QByteArray byteArray(data, size);
291 292 293
        m_writeMutex.lock();
        m_transmitBuffer.append(byteArray);
        m_writeMutex.unlock();
294 295 296 297
    } else {
        disconnect();
        // Error occured
        emit communicationError(getName(), tr("Could not send data - link %1 is disconnected!").arg(getName()));
pixhawk's avatar
pixhawk committed
298 299 300 301 302 303 304 305 306
    }
}

/**
 * @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
 **/
307 308
void SerialLink::readBytes()
{
Bill Bonney's avatar
Bill Bonney committed
309
    if(m_port && m_port->isOpen()) {
310 311
        const qint64 maxLength = 2048;
        char data[maxLength];
312
        m_dataMutex.lock();
Bill Bonney's avatar
Bill Bonney committed
313
        qint64 numBytes = m_port->bytesAvailable();
314

315
        if(numBytes > 0) {
pixhawk's avatar
pixhawk committed
316 317 318
            /* Read as much data in buffer as possible without overflow */
            if(maxLength < numBytes) numBytes = maxLength;

Bill Bonney's avatar
Bill Bonney committed
319
            m_port->read(data, numBytes);
pixhawk's avatar
pixhawk committed
320 321 322
            QByteArray b(data, numBytes);
            emit bytesReceived(this, b);
        }
323
        m_dataMutex.unlock();
pixhawk's avatar
pixhawk committed
324 325 326 327 328 329 330 331 332
    }
}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
333 334
qint64 SerialLink::bytesAvailable()
{
Bill Bonney's avatar
Bill Bonney committed
335 336
    if (m_port) {
        return m_port->bytesAvailable();
337
    } else {
338 339
        return 0;
    }
pixhawk's avatar
pixhawk committed
340 341 342 343 344 345 346
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
347 348
bool SerialLink::disconnect()
{
349 350 351
    qDebug() << "disconnect";
    if (m_port)
        qDebug() << m_port->portName();
Bill Bonney's avatar
Bill Bonney committed
352 353

    if (isRunning())
354
    {
355
        qDebug() << "running so disconnect" << m_port->portName();
356
        {
Bill Bonney's avatar
Bill Bonney committed
357 358
            QMutexLocker locker(&m_stoppMutex);
            m_stopp = true;
359
        }
Bill Bonney's avatar
Bill Bonney committed
360
        wait(); // This will terminate the thread and close the serial port
pixhawk's avatar
pixhawk committed
361

Bill Bonney's avatar
Bill Bonney committed
362
        emit disconnected(); // [TODO] There are signals from QSerialPort we should use
363 364 365
        emit connected(false);
        return true;
    }
pixhawk's avatar
pixhawk committed
366

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

369 370
    qDebug() << "already disconnected";
    return true;
pixhawk's avatar
pixhawk committed
371 372 373 374 375 376 377 378
}

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

    start(LowPriority);
388
    return true;
pixhawk's avatar
pixhawk committed
389 390 391 392 393 394 395 396 397 398
}

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

410
    if (m_port == NULL) {
Bill Bonney's avatar
Bill Bonney committed
411 412
        emit communicationUpdate(getName(),"Error opening port: " + m_port->errorString());
        return false; // couldn't create serial port.
413
    }
Bill Bonney's avatar
Bill Bonney committed
414 415

    QObject::connect(m_port,SIGNAL(aboutToClose()),this,SIGNAL(disconnected()));
416
    QObject::connect(m_port, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(linkError(QSerialPort::SerialPortError)));
Bill Bonney's avatar
Bill Bonney committed
417 418 419

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

420
    if (!m_port->open(QIODevice::ReadWrite)) {
Bill Bonney's avatar
Bill Bonney committed
421 422 423
        emit communicationUpdate(getName(),"Error opening port: " + m_port->errorString());
        m_port->close();
        return false; // couldn't open serial port
424
    }
425

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

Bill Bonney's avatar
Bill Bonney committed
428 429 430 431 432 433
    // 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
434

Bill Bonney's avatar
Bill Bonney committed
435 436
    emit connected();
    emit connected(true);
437

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

441 442
    writeSettings();

Bill Bonney's avatar
Bill Bonney committed
443
    return true; // successful connection
pixhawk's avatar
pixhawk committed
444
}
445

446
void SerialLink::linkError(QSerialPort::SerialPortError error)
447 448 449 450
{
    qDebug() << error;
}

451

pixhawk's avatar
pixhawk committed
452 453 454 455 456
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
457
bool SerialLink::isConnected() const
458
{
Bill Bonney's avatar
Bill Bonney committed
459 460 461

    if (m_port) {
        bool isConnected = m_port->isOpen();
462 463
//        qDebug() << "SerialLink #" << __LINE__ << ":"<<  m_port->portName()
//                 << " isConnected =" << QString::number(isConnected);
Bill Bonney's avatar
Bill Bonney committed
464
        return isConnected;
465
    } else {
466 467
//        qDebug() << "SerialLink #" << __LINE__ << ":" <<  m_portName
//                 << " isConnected = NULL";
lm's avatar
lm committed
468 469
        return false;
    }
pixhawk's avatar
pixhawk committed
470 471
}

472
int SerialLink::getId() const
pixhawk's avatar
pixhawk committed
473
{
Bill Bonney's avatar
Bill Bonney committed
474
    return m_id;
pixhawk's avatar
pixhawk committed
475 476
}

477
QString SerialLink::getName() const
pixhawk's avatar
pixhawk committed
478
{
479
    return m_portName;
pixhawk's avatar
pixhawk committed
480 481
}

482 483 484 485
/**
  * This function maps baud rate constants to numerical equivalents.
  * It relies on the mapping given in qportsettings.h from the QSerialPort library.
  */
486
qint64 SerialLink::getConnectionSpeed() const
487
{
Bill Bonney's avatar
Bill Bonney committed
488 489 490 491 492 493 494 495 496 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
    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
526 527 528 529
    }
    return dataRate;
}

530
QString SerialLink::getPortName() const
531
{
Bill Bonney's avatar
Bill Bonney committed
532
    return m_portName;
pixhawk's avatar
pixhawk committed
533 534
}

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

537
int SerialLink::getBaudRate() const
538
{
539
    return getConnectionSpeed();
pixhawk's avatar
pixhawk committed
540 541
}

542
int SerialLink::getBaudRateType() const
543
{
Bill Bonney's avatar
Bill Bonney committed
544 545 546 547 548 549 550
    int baudRate;
    if (m_port) {
        baudRate = m_port->baudRate();
    } else {
        baudRate = m_baud;
    }
    return baudRate;
pixhawk's avatar
pixhawk committed
551 552
}

553
int SerialLink::getFlowType() const
554
{
Bill Bonney's avatar
Bill Bonney committed
555 556 557 558 559 560 561
    int flowControl;
    if (m_port) {
        flowControl = m_port->flowControl();
    } else {
        flowControl = m_flowControl;
    }
    return flowControl;
pixhawk's avatar
pixhawk committed
562 563
}

564
int SerialLink::getParityType() const
565
{
Bill Bonney's avatar
Bill Bonney committed
566 567 568 569 570 571 572
    int parity;
    if (m_port) {
        parity = m_port->parity();
    } else {
        parity = m_parity;
    }
    return parity;
pixhawk's avatar
pixhawk committed
573 574
}

575
int SerialLink::getDataBitsType() const
576
{
Bill Bonney's avatar
Bill Bonney committed
577 578 579 580 581 582 583
    int dataBits;
    if (m_port) {
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }
    return dataBits;
pixhawk's avatar
pixhawk committed
584 585
}

586
int SerialLink::getStopBitsType() const
587
{
Bill Bonney's avatar
Bill Bonney committed
588 589 590 591 592 593 594
    int stopBits;
    if (m_port) {
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
    return stopBits;
pixhawk's avatar
pixhawk committed
595 596
}

597
int SerialLink::getDataBits() const
598
{
Bill Bonney's avatar
Bill Bonney committed
599 600 601 602 603 604 605 606 607 608
    int ret;
    int dataBits;
    if (m_port) {
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }

    switch (dataBits) {
    case QSerialPort::Data5:
609 610
        ret = 5;
        break;
Bill Bonney's avatar
Bill Bonney committed
611
    case QSerialPort::Data6:
612 613
        ret = 6;
        break;
Bill Bonney's avatar
Bill Bonney committed
614
    case QSerialPort::Data7:
615 616
        ret = 7;
        break;
Bill Bonney's avatar
Bill Bonney committed
617
    case QSerialPort::Data8:
618 619 620
        ret = 8;
        break;
    default:
621
        ret = -1;
622 623 624 625 626
        break;
    }
    return ret;
}

627
int SerialLink::getStopBits() const
628
{
Bill Bonney's avatar
Bill Bonney committed
629 630 631 632 633 634
    int stopBits;
    if (m_port) {
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
635
    int ret = -1;
Bill Bonney's avatar
Bill Bonney committed
636 637
    switch (stopBits) {
    case QSerialPort::OneStop:
638 639
        ret = 1;
        break;
Bill Bonney's avatar
Bill Bonney committed
640
    case QSerialPort::TwoStop:
641 642 643 644 645 646
        ret = 2;
        break;
    default:
        ret = -1;
        break;
    }
647 648 649
    return ret;
}

pixhawk's avatar
pixhawk committed
650 651
bool SerialLink::setPortName(QString portName)
{
Bill Bonney's avatar
Bill Bonney committed
652 653 654 655 656 657 658 659
    qDebug() << "current portName " << m_portName;
    qDebug() << "setPortName to " << portName;
    bool accepted = false;
    if ((portName != m_portName)
            && (portName.trimmed().length() > 0)) {
        m_portName = portName.trimmed();
        if(m_port)
            m_port->setPortName(portName);
660

661
        emit nameChanged(m_portName); // [TODO] maybe we can eliminate this
662
        emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
663
        return accepted;
pixhawk's avatar
pixhawk committed
664
    }
Bill Bonney's avatar
Bill Bonney committed
665
    return false;
pixhawk's avatar
pixhawk committed
666 667 668 669 670
}


bool SerialLink::setBaudRateType(int rateIndex)
{
Bill Bonney's avatar
Bill Bonney committed
671 672
    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
673
    bool result;
Bill Bonney's avatar
Bill Bonney committed
674 675
    const int minBaud = (int)QSerialPort::Baud1200;
    const int maxBaud = (int)QSerialPort::Baud115200;
676

Bill Bonney's avatar
Bill Bonney committed
677
    if (m_port && (rateIndex >= minBaud && rateIndex <= maxBaud))
678
    {
679 680 681
        result = m_port->setBaudRate(static_cast<QSerialPort::BaudRate>(rateIndex));
        emit updateLink(this);
        return result;
pixhawk's avatar
pixhawk committed
682 683
    }

Bill Bonney's avatar
Bill Bonney committed
684
    return false;
pixhawk's avatar
pixhawk committed
685 686
}

687 688 689 690 691 692 693
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
694 695 696

bool SerialLink::setBaudRate(int rate)
{
Bill Bonney's avatar
Bill Bonney committed
697 698 699 700 701 702
    bool accepted = false;
    if (rate != m_baud) {
        m_baud = rate;
        accepted = true;
        if (m_port)
            accepted = m_port->setBaudRate(rate);
703
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
704
    }
705
    return accepted;
pixhawk's avatar
pixhawk committed
706 707
}

708 709
bool SerialLink::setFlowType(int flow)
{
Bill Bonney's avatar
Bill Bonney committed
710 711 712 713 714 715
    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));
716
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
717 718 719 720
    }
    return accepted;
}

721 722
bool SerialLink::setParityType(int parity)
{
Bill Bonney's avatar
Bill Bonney committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
    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;
                }
746
            emit updateLink(this);
Bill Bonney's avatar
Bill Bonney committed
747
        }
pixhawk's avatar
pixhawk committed
748 749 750 751
    }
    return accepted;
}

752

753
bool SerialLink::setDataBits(int dataBits)
754
{
Bill Bonney's avatar
Bill Bonney committed
755 756 757 758 759 760
    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));
761
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
762 763 764 765
    }
    return accepted;
}

766
bool SerialLink::setStopBits(int stopBits)
767
{
Bill Bonney's avatar
Bill Bonney committed
768 769 770 771 772 773 774
    // 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));
775
        emit updateLink(this);
pixhawk's avatar
pixhawk committed
776 777 778
    }
    return accepted;
}
779 780 781 782

bool SerialLink::setDataBitsType(int dataBits)
{
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
783 784
    if (dataBits != m_dataBits) {
        m_dataBits = static_cast<QSerialPort::DataBits>(dataBits);
785
        accepted = true;
Bill Bonney's avatar
Bill Bonney committed
786 787
        if (m_port)
            accepted = m_port->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
788
        emit updateLink(this);
789 790 791 792 793 794 795
    }
    return accepted;
}

bool SerialLink::setStopBitsType(int stopBits)
{
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
796 797
    if (stopBits != m_stopBits) {
        m_stopBits = static_cast<QSerialPort::StopBits>(stopBits);
798
        accepted = true;
Bill Bonney's avatar
Bill Bonney committed
799 800
        if (m_port)
            accepted = m_port->setStopBits(static_cast<QSerialPort::StopBits>(stopBits));
801
        emit updateLink(this);
802 803 804
    }
    return accepted;
}