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

Bill Bonney's avatar
Bill Bonney committed
35
    if (m_portName == "" && getCurrentPorts()->size() > 0)
36
    {
37
        m_portName = m_ports->first().trimmed();   
38 39
    }

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

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

    m_baud = baudRate;
46

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

    m_dataBits = dataBits;
    m_stopBits = stopBits;
pixhawk's avatar
pixhawk committed
66 67

    // Set the port name
68 69 70 71 72 73 74 75 76
//    if (m_portName == "")
//    {
//        m_name = tr("Serial Link ") + QString::number(getId());
//    }
//    else
//    {
//        m_name = portname.trimmed();
//    }

lm's avatar
lm committed
77
    loadSettings();
pixhawk's avatar
pixhawk committed
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 90 91
    if(m_port) delete m_port;
    m_port = NULL;
    if (m_ports) delete m_ports;
    m_ports = NULL;
92 93 94 95
}

QVector<QString>* SerialLink::getCurrentPorts()
{
Bill Bonney's avatar
Bill Bonney committed
96 97 98
    Q_ASSERT_X(m_ports != NULL, "getCurrentPorts", "m_ports is NULL");
    m_ports->clear();
    // Example use QSerialPortInfo
Bill Bonney's avatar
Bill Bonney committed
99
    // [TODO] make this thread safe
Bill Bonney's avatar
Bill Bonney committed
100
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
101
    {
Bill Bonney's avatar
Bill Bonney committed
102 103 104
//        qDebug() << "PortName    : " << info.portName()
//                 << "Description : " << info.description();
//        qDebug() << "Manufacturer: " << info.manufacturer();
105

Bill Bonney's avatar
Bill Bonney committed
106
        m_ports->append(info.portName());
107
    }
Bill Bonney's avatar
Bill Bonney committed
108
    return m_ports;
pixhawk's avatar
pixhawk committed
109 110
}

111 112 113 114 115
void SerialLink::loadSettings()
{
    // Load defaults from settings
    QSettings settings(QGC::COMPANYNAME, QGC::APPNAME);
    settings.sync();
116 117
    if (settings.contains("SERIALLINK_COMM_PORT"))
    {
Bill Bonney's avatar
Bill Bonney committed
118 119 120 121 122 123
        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();
124 125 126 127 128 129 130
    }
}

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

pixhawk's avatar
pixhawk committed
140 141 142 143 144

/**
 * @brief Runs the thread
 *
 **/
145
void SerialLink::run()
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
{
    // Initialize the connection
    if (!hardwareConnect())
    {
        //Need to error out here.
        emit communicationError(getName(),"Error connecting: " + m_port->errorString());
        return;
    }

    // Qt way to make clear what a while(1) loop does
    qint64 msecs = QDateTime::currentMSecsSinceEpoch();
    qint64 initialmsecs = QDateTime::currentMSecsSinceEpoch();
    quint64 bytes = 0;
    bool triedreset = false;
    bool triedDTR = false;
    qint64 timeout = 5000;

    forever
    {
        {
166 167 168 169 170 171
            QMutexLocker locker(&this->m_stoppMutex);
            if(m_stopp)
            {
                m_stopp = false;
                break; // exit the thread
            }
172

173 174 175 176 177 178 179 180
            if (m_reqReset)
            {
                m_reqReset = false;
                communicationUpdate(getName(),"Reset requested via DTR signal");
                m_port->setDataTerminalReady(true);
                msleep(250);
                m_port->setDataTerminalReady(false);
            }
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        }
        bool error = m_port->waitForReadyRead(500);

        if(error) { // Waits for 1/2 second [TODO][BB] lower to SerialLink::poll_interval?
            QByteArray readData = m_port->readAll();
            while (m_port->waitForReadyRead(10))
                readData += m_port->readAll();
            if (readData.length() > 0) {
                emit bytesReceived(this, readData);
//                qDebug() << "rx of length " << QString::number(readData.length());

                m_bytesRead += readData.length();
                m_bitsReceivedTotal += readData.length() * 8;
            }
        } else {
196
//            qDebug() << "readyReadTime #"<< __LINE__;
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

        }

        if (bytes != m_bytesRead) // i.e things are good and data is being read.
        {
            bytes = m_bytesRead;
            msecs = QDateTime::currentMSecsSinceEpoch();
        }
        else
        {
            if (QDateTime::currentMSecsSinceEpoch() - msecs > timeout)
            {
                //It's been 10 seconds since the last data came in. Reset and try again
                msecs = QDateTime::currentMSecsSinceEpoch();
                if (msecs - initialmsecs > 25000)
                {
                    //After initial 25 seconds, timeouts are increased to 30 seconds.
                    //This prevents temporary silences from things like calibration commands
                    //from screwing things up. In all reality, timeouts should be enabled/disabled
                    //for events like that on a case by case basis.
                    //TODO ^^
                    timeout = 30000;
                }
                if (!triedDTR && triedreset)
                {
                    triedDTR = true;
                    communicationUpdate(getName(),"No data to receive on COM port. Attempting to reset via DTR signal");
                    qDebug() << "No data!!! Attempting reset via DTR.";
                    m_port->setDataTerminalReady(true);
                    msleep(250);
                    m_port->setDataTerminalReady(false);
                }
                else if (!triedreset)
                {
                    qDebug() << "No data!!! Attempting reset via reboot command.";
                    communicationUpdate(getName(),"No data to receive on COM port. Assuming possible terminal mode, attempting to reset via \"reboot\" command");
                    m_port->write("reboot\r\n",8);
                    triedreset = true;
                }
                else
                {
                    communicationUpdate(getName(),"No data to receive on COM port....");
                    qDebug() << "No data!!!";
                }
            }
        }
        MG::SLEEP::msleep(SerialLink::poll_interval);
    } // 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;

        emit disconnected();
        emit connected(false);
    }
}
pixhawk's avatar
pixhawk committed
256

257 258
void SerialLink::writeBytes(const char* data, qint64 size)
{
Bill Bonney's avatar
Bill Bonney committed
259
    if(m_port && m_port->isOpen()) {
260
//        qDebug() << "writeBytes" << m_portName << "attempting to tx " << size << "bytes.";
Bill Bonney's avatar
Bill Bonney committed
261
        int b = m_port->write(data, size);
pixhawk's avatar
pixhawk committed
262

263
        if (b > 0) {
Bill Bonney's avatar
Bill Bonney committed
264
            Q_ASSERT_X(b = size, "writeBytes", "failed to write all bytes");
265

266
//            qDebug() << "writeBytes " << m_portName << "tx'd" << b << "bytes:";
pixhawk's avatar
pixhawk committed
267

268
            // Increase write counter
Bill Bonney's avatar
Bill Bonney committed
269 270
            m_bitsSentTotal += size * 8;

271 272 273 274
            // Extra debug logging
//            QByteArray* byteArray = new QByteArray(data,size);
//            qDebug() << byteArray->toHex();
//            delete byteArray;
275

276
        } else {
277 278
            disconnect();
            // Error occured
Bill Bonney's avatar
Bill Bonney committed
279
            emit communicationError(getName(), tr("Could not send data - link %1 is disconnected!").arg(getName()));
280
        }
pixhawk's avatar
pixhawk committed
281 282 283 284 285 286 287 288 289
    }
}

/**
 * @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
 **/
290 291
void SerialLink::readBytes()
{
Bill Bonney's avatar
Bill Bonney committed
292 293
    m_dataMutex.lock();
    if(m_port && m_port->isOpen()) {
294 295
        const qint64 maxLength = 2048;
        char data[maxLength];
Bill Bonney's avatar
Bill Bonney committed
296
        qint64 numBytes = m_port->bytesAvailable();
James Goppert's avatar
James Goppert committed
297
        //qDebug() << "numBytes: " << numBytes;
298

299
        if(numBytes > 0) {
pixhawk's avatar
pixhawk committed
300 301 302
            /* Read as much data in buffer as possible without overflow */
            if(maxLength < numBytes) numBytes = maxLength;

Bill Bonney's avatar
Bill Bonney committed
303
            m_port->read(data, numBytes);
pixhawk's avatar
pixhawk committed
304 305 306 307 308 309 310 311 312 313 314
            QByteArray b(data, numBytes);
            emit bytesReceived(this, b);

            //qDebug() << "SerialLink::readBytes()" << std::hex << data;
            //            int i;
            //            for (i=0; i<numBytes; i++){
            //                unsigned int v=data[i];
            //
            //                fprintf(stderr,"%02x ", v);
            //            }
            //            fprintf(stderr,"\n");
Bill Bonney's avatar
Bill Bonney committed
315
            m_bitsReceivedTotal += numBytes * 8;
pixhawk's avatar
pixhawk committed
316 317
        }
    }
Bill Bonney's avatar
Bill Bonney committed
318
    m_dataMutex.unlock();
pixhawk's avatar
pixhawk committed
319 320 321 322 323 324 325 326
}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
327 328
qint64 SerialLink::bytesAvailable()
{
Bill Bonney's avatar
Bill Bonney committed
329 330
    if (m_port) {
        return m_port->bytesAvailable();
331
    } else {
332 333
        return 0;
    }
pixhawk's avatar
pixhawk committed
334 335 336 337 338 339 340
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
341 342
bool SerialLink::disconnect()
{
343 344 345
    qDebug() << "disconnect";
    if (m_port)
        qDebug() << m_port->portName();
Bill Bonney's avatar
Bill Bonney committed
346 347

    if (isRunning())
348
    {
349
        qDebug() << "running so disconnect" << m_port->portName();
350
        {
Bill Bonney's avatar
Bill Bonney committed
351 352
            QMutexLocker locker(&m_stoppMutex);
            m_stopp = true;
353
        }
Bill Bonney's avatar
Bill Bonney committed
354
        wait(); // This will terminate the thread and close the serial port
pixhawk's avatar
pixhawk committed
355

Bill Bonney's avatar
Bill Bonney committed
356
        emit disconnected(); // [TODO] There are signals from QSerialPort we should use
357
        emit connected(false);
Bill Bonney's avatar
Bill Bonney committed
358
        return true;
359
    }
360 361 362

    qDebug() << "already disconnected";
    return true;
pixhawk's avatar
pixhawk committed
363 364 365 366 367 368 369 370
}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
bool SerialLink::connect()
371
{   
Bill Bonney's avatar
Bill Bonney committed
372 373
    if (isRunning())
        disconnect();
374 375
    {
        QMutexLocker locker(&this->m_stoppMutex);
Bill Bonney's avatar
Bill Bonney committed
376
        m_stopp = false;
377
    }
Bill Bonney's avatar
Bill Bonney committed
378 379

    start(LowPriority);
380
    return true;
pixhawk's avatar
pixhawk committed
381 382 383 384 385 386 387 388 389 390
}

/**
 * @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.
 **/
391 392
bool SerialLink::hardwareConnect()
{
Bill Bonney's avatar
Bill Bonney committed
393 394 395 396 397 398
    if(m_port)
    {
        qDebug() << "SerialLink:" << QString::number((long)this, 16) << "closing port";
        m_port->close();
        delete m_port;
        m_port = NULL;
399
    }
Bill Bonney's avatar
Bill Bonney committed
400 401
    qDebug() << "SerialLink: hardwareConnect to " << m_portName;
    m_port = new QSerialPort(m_portName);
pixhawk's avatar
pixhawk committed
402

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

    QObject::connect(m_port,SIGNAL(aboutToClose()),this,SIGNAL(disconnected()));

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

    if (!m_port->open(QIODevice::ReadWrite))
415
    {
Bill Bonney's avatar
Bill Bonney committed
416 417 418
        emit communicationUpdate(getName(),"Error opening port: " + m_port->errorString());
        m_port->close();
        return false; // couldn't open serial port
419
    }
420

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

Bill Bonney's avatar
Bill Bonney committed
423 424 425 426 427 428
    // 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));
429

Bill Bonney's avatar
Bill Bonney committed
430 431 432 433 434
    emit connected();
    emit connected(true);

    qDebug() << "CONNECTING LINK: " << __FILE__ << __LINE__ << "with settings" << m_port->portName()
             << getBaudRate() << getDataBits() << getParityType() << getStopBits();
435

436 437
    writeSettings();

Bill Bonney's avatar
Bill Bonney committed
438
    return true; // successful connection
pixhawk's avatar
pixhawk committed
439
}
440 441


pixhawk's avatar
pixhawk committed
442 443 444 445 446
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
447 448
bool SerialLink::isConnected()
{
Bill Bonney's avatar
Bill Bonney committed
449 450 451

    if (m_port) {
        bool isConnected = m_port->isOpen();
452 453
//        qDebug() << "SerialLink #" << __LINE__ << ":"<<  m_port->portName()
//                 << " isConnected =" << QString::number(isConnected);
Bill Bonney's avatar
Bill Bonney committed
454
        return isConnected;
455
    } else {
456 457
//        qDebug() << "SerialLink #" << __LINE__ << ":" <<  m_portName
//                 << " isConnected = NULL";
lm's avatar
lm committed
458 459
        return false;
    }
pixhawk's avatar
pixhawk committed
460 461 462 463
}

int SerialLink::getId()
{
Bill Bonney's avatar
Bill Bonney committed
464
    return m_id;
pixhawk's avatar
pixhawk committed
465 466 467 468
}

QString SerialLink::getName()
{
469
    return m_portName;
pixhawk's avatar
pixhawk committed
470 471
}

472 473 474 475
/**
  * This function maps baud rate constants to numerical equivalents.
  * It relies on the mapping given in qportsettings.h from the QSerialPort library.
  */
476 477
qint64 SerialLink::getNominalDataRate()
{
Bill Bonney's avatar
Bill Bonney committed
478 479 480 481 482 483 484 485 486 487 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
    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
516 517 518 519
    }
    return dataRate;
}

520 521
qint64 SerialLink::getTotalUpstream()
{
Bill Bonney's avatar
Bill Bonney committed
522 523 524
    m_statisticsMutex.lock();
    return m_bitsSentTotal / ((MG::TIME::getGroundTimeNow() - m_connectionStartTime) / 1000);
    m_statisticsMutex.unlock();
pixhawk's avatar
pixhawk committed
525 526
}

527 528
qint64 SerialLink::getCurrentUpstream()
{
pixhawk's avatar
pixhawk committed
529 530 531
    return 0; // TODO
}

532 533
qint64 SerialLink::getMaxUpstream()
{
pixhawk's avatar
pixhawk committed
534 535 536
    return 0; // TODO
}

537 538
qint64 SerialLink::getBitsSent()
{
Bill Bonney's avatar
Bill Bonney committed
539
    return m_bitsSentTotal;
pixhawk's avatar
pixhawk committed
540 541
}

542 543
qint64 SerialLink::getBitsReceived()
{
Bill Bonney's avatar
Bill Bonney committed
544
    return m_bitsReceivedTotal;
pixhawk's avatar
pixhawk committed
545 546
}

547 548
qint64 SerialLink::getTotalDownstream()
{
Bill Bonney's avatar
Bill Bonney committed
549 550 551
    m_statisticsMutex.lock();
    return m_bitsReceivedTotal / ((MG::TIME::getGroundTimeNow() - m_connectionStartTime) / 1000);
    m_statisticsMutex.unlock();
pixhawk's avatar
pixhawk committed
552 553
}

554 555
qint64 SerialLink::getCurrentDownstream()
{
pixhawk's avatar
pixhawk committed
556 557 558
    return 0; // TODO
}

559 560
qint64 SerialLink::getMaxDownstream()
{
pixhawk's avatar
pixhawk committed
561 562 563
    return 0; // TODO
}

564 565
bool SerialLink::isFullDuplex()
{
pixhawk's avatar
pixhawk committed
566 567 568 569
    /* Serial connections are always half duplex */
    return false;
}

570 571
int SerialLink::getLinkQuality()
{
pixhawk's avatar
pixhawk committed
572 573 574 575
    /* This feature is not supported with this interface */
    return -1;
}

576 577
QString SerialLink::getPortName()
{
Bill Bonney's avatar
Bill Bonney committed
578
    return m_portName;
pixhawk's avatar
pixhawk committed
579 580
}

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

583 584
int SerialLink::getBaudRate()
{
pixhawk's avatar
pixhawk committed
585 586 587
    return getNominalDataRate();
}

588 589
int SerialLink::getBaudRateType()
{
Bill Bonney's avatar
Bill Bonney committed
590 591 592 593 594 595 596
    int baudRate;
    if (m_port) {
        baudRate = m_port->baudRate();
    } else {
        baudRate = m_baud;
    }
    return baudRate;
pixhawk's avatar
pixhawk committed
597 598
}

599 600
int SerialLink::getFlowType()
{
Bill Bonney's avatar
Bill Bonney committed
601 602 603 604 605 606 607
    int flowControl;
    if (m_port) {
        flowControl = m_port->flowControl();
    } else {
        flowControl = m_flowControl;
    }
    return flowControl;
pixhawk's avatar
pixhawk committed
608 609
}

610 611
int SerialLink::getParityType()
{
Bill Bonney's avatar
Bill Bonney committed
612 613 614 615 616 617 618
    int parity;
    if (m_port) {
        parity = m_port->parity();
    } else {
        parity = m_parity;
    }
    return parity;
pixhawk's avatar
pixhawk committed
619 620
}

621 622
int SerialLink::getDataBitsType()
{
Bill Bonney's avatar
Bill Bonney committed
623 624 625 626 627 628 629
    int dataBits;
    if (m_port) {
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }
    return dataBits;
pixhawk's avatar
pixhawk committed
630 631
}

632 633
int SerialLink::getStopBitsType()
{
Bill Bonney's avatar
Bill Bonney committed
634 635 636 637 638 639 640
    int stopBits;
    if (m_port) {
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
    return stopBits;
pixhawk's avatar
pixhawk committed
641 642
}

643 644
int SerialLink::getDataBits()
{
Bill Bonney's avatar
Bill Bonney committed
645 646 647 648 649 650 651 652 653 654
    int ret;
    int dataBits;
    if (m_port) {
        dataBits = m_port->dataBits();
    } else {
        dataBits = m_dataBits;
    }

    switch (dataBits) {
    case QSerialPort::Data5:
655 656
        ret = 5;
        break;
Bill Bonney's avatar
Bill Bonney committed
657
    case QSerialPort::Data6:
658 659
        ret = 6;
        break;
Bill Bonney's avatar
Bill Bonney committed
660
    case QSerialPort::Data7:
661 662
        ret = 7;
        break;
Bill Bonney's avatar
Bill Bonney committed
663
    case QSerialPort::Data8:
664 665 666
        ret = 8;
        break;
    default:
667
        ret = -1;
668 669 670 671 672 673 674
        break;
    }
    return ret;
}

int SerialLink::getStopBits()
{
Bill Bonney's avatar
Bill Bonney committed
675 676 677 678 679 680
    int stopBits;
    if (m_port) {
        stopBits = m_port->stopBits();
    } else {
        stopBits = m_stopBits;
    }
681
    int ret = -1;
Bill Bonney's avatar
Bill Bonney committed
682 683
    switch (stopBits) {
    case QSerialPort::OneStop:
684 685
        ret = 1;
        break;
Bill Bonney's avatar
Bill Bonney committed
686
    case QSerialPort::TwoStop:
687 688 689 690 691 692
        ret = 2;
        break;
    default:
        ret = -1;
        break;
    }
693 694 695
    return ret;
}

pixhawk's avatar
pixhawk committed
696 697
bool SerialLink::setPortName(QString portName)
{
Bill Bonney's avatar
Bill Bonney committed
698 699 700 701 702 703
    qDebug() << "current portName " << m_portName;
    qDebug() << "setPortName to " << portName;
    bool accepted = false;
    if ((portName != m_portName)
            && (portName.trimmed().length() > 0)) {
        m_portName = portName.trimmed();
704
//        m_name = tr("serial port ") + portName.trimmed(); // [TODO] Do we need this?
Bill Bonney's avatar
Bill Bonney committed
705 706
        if(m_port)
            m_port->setPortName(portName);
707

708
        emit nameChanged(m_portName); // [TODO] maybe we can eliminate this
Bill Bonney's avatar
Bill Bonney committed
709
        return accepted;
pixhawk's avatar
pixhawk committed
710
    }
Bill Bonney's avatar
Bill Bonney committed
711
    return false;
pixhawk's avatar
pixhawk committed
712 713 714 715 716
}


bool SerialLink::setBaudRateType(int rateIndex)
{
Bill Bonney's avatar
Bill Bonney committed
717 718 719 720
    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
    const int minBaud = (int)QSerialPort::Baud1200;
    const int maxBaud = (int)QSerialPort::Baud115200;
721

Bill Bonney's avatar
Bill Bonney committed
722
    if (m_port && (rateIndex >= minBaud && rateIndex <= maxBaud))
723
    {
Bill Bonney's avatar
Bill Bonney committed
724
        return m_port->setBaudRate(static_cast<QSerialPort::BaudRate>(rateIndex));
pixhawk's avatar
pixhawk committed
725 726
    }

Bill Bonney's avatar
Bill Bonney committed
727
    return false;
pixhawk's avatar
pixhawk committed
728 729
}

730 731 732 733 734 735 736
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
737 738 739

bool SerialLink::setBaudRate(int rate)
{
Bill Bonney's avatar
Bill Bonney committed
740 741 742 743 744 745
    bool accepted = false;
    if (rate != m_baud) {
        m_baud = rate;
        accepted = true;
        if (m_port)
            accepted = m_port->setBaudRate(rate);
pixhawk's avatar
pixhawk committed
746
    }
747
    return accepted;
pixhawk's avatar
pixhawk committed
748 749
}

750 751
bool SerialLink::setFlowType(int flow)
{
Bill Bonney's avatar
Bill Bonney committed
752 753 754 755 756 757
    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));
pixhawk's avatar
pixhawk committed
758 759 760 761
    }
    return accepted;
}

762 763
bool SerialLink::setParityType(int parity)
{
Bill Bonney's avatar
Bill Bonney committed
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    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;
                }
        }
pixhawk's avatar
pixhawk committed
788 789 790 791
    }
    return accepted;
}

792

793
bool SerialLink::setDataBits(int dataBits)
794
{
Bill Bonney's avatar
Bill Bonney committed
795 796 797 798 799 800
    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));
pixhawk's avatar
pixhawk committed
801 802 803 804
    }
    return accepted;
}

805
bool SerialLink::setStopBits(int stopBits)
806
{
Bill Bonney's avatar
Bill Bonney committed
807 808 809 810 811 812 813
    // 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));
pixhawk's avatar
pixhawk committed
814 815 816
    }
    return accepted;
}
817 818 819 820

bool SerialLink::setDataBitsType(int dataBits)
{
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
821 822
    if (dataBits != m_dataBits) {
        m_dataBits = static_cast<QSerialPort::DataBits>(dataBits);
823
        accepted = true;
Bill Bonney's avatar
Bill Bonney committed
824 825
        if (m_port)
            accepted = m_port->setDataBits(static_cast<QSerialPort::DataBits>(dataBits));
826 827 828 829 830 831 832
    }
    return accepted;
}

bool SerialLink::setStopBitsType(int stopBits)
{
    bool accepted = false;
Bill Bonney's avatar
Bill Bonney committed
833 834
    if (stopBits != m_stopBits) {
        m_stopBits = static_cast<QSerialPort::StopBits>(stopBits);
835
        accepted = true;
Bill Bonney's avatar
Bill Bonney committed
836 837
        if (m_port)
            accepted = m_port->setStopBits(static_cast<QSerialPort::StopBits>(stopBits));
838 839 840
    }
    return accepted;
}