SerialLink.cc 32.5 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 15 16
#include <QMutexLocker>
#include "SerialLink.h"
#include "LinkManager.h"
17
#include "QGC.h"
pixhawk's avatar
pixhawk committed
18
#include <MG.h>
19
#include <iostream>
pixhawk's avatar
pixhawk committed
20 21 22 23
#ifdef _WIN32
#include "windows.h"
#endif

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
#ifdef _WIN32
#include <qextserialenumerator.h>
#endif
#if defined (__APPLE__) && defined (__MACH__)
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <paths.h>
#include <termios.h>
#include <sysexits.h>
#include <sys/param.h>
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>
#include <AvailabilityMacros.h>

#ifdef __MWERKS__
#define __CF_USE_FRAMEWORK_INCLUDES__
#endif


#include <CoreFoundation/CoreFoundation.h>

#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3)
#include <IOKit/serial/ioss.h>
#endif
#include <IOKit/IOBSD.h>

// Apple internal modems default to local echo being on. If your modem has local echo disabled,
// undefine the following macro.
#define LOCAL_ECHO

#define kATCommandString  "AT\r"

#ifdef LOCAL_ECHO
#define kOKResponseString  "AT\r\r\nOK\r\n"
#else
#define kOKResponseString  "\r\nOK\r\n"
#endif
#endif


// Some helper functions for serial port enumeration
#if defined (__APPLE__) && defined (__MACH__)

enum {
    kNumRetries = 3
};

// Function prototypes
static kern_return_t FindModems(io_iterator_t *matchingServices);
static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char *bsdPath, CFIndex maxPathSize);

// Returns an iterator across all known modems. Caller is responsible for
// releasing the iterator when iteration is complete.
static kern_return_t FindModems(io_iterator_t *matchingServices)
{
    kern_return_t      kernResult;
    CFMutableDictionaryRef  classesToMatch;

    /*! @function IOServiceMatching
    @abstract Create a matching dictionary that specifies an IOService class match.
    @discussion A very common matching criteria for IOService is based on its class. IOServiceMatching will create a matching dictionary that specifies any IOService of a class, or its subclasses. The class is specified by C-string name.
    @param name The class name, as a const C-string. Class matching is successful on IOService's of this class or any subclass.
    @result The matching dictionary created, is returned on success, or zero on failure. The dictionary is commonly passed to IOServiceGetMatchingServices or IOServiceAddNotification which will consume a reference, otherwise it should be released with CFRelease by the caller. */

    // Serial devices are instances of class IOSerialBSDClient
    classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
    if (classesToMatch == NULL) {
        printf("IOServiceMatching returned a NULL dictionary.\n");
    } else {
        /*!
          @function CFDictionarySetValue
          Sets the value of the key in the dictionary.
          @param theDict The dictionary to which the value is to be set. If this
            parameter is not a valid mutable CFDictionary, the behavior is
            undefined. If the dictionary is a fixed-capacity dictionary and
            it is full before this operation, and the key does not exist in
            the dictionary, the behavior is undefined.
          @param key The key of the value to set into the dictionary. If a key
            which matches this key is already present in the dictionary, only
            the value is changed ("add if absent, replace if present"). If
            no key matches the given key, the key-value pair is added to the
            dictionary. If added, the key is retained by the dictionary,
            using the retain callback provided
            when the dictionary was created. If the key is not of the sort
            expected by the key retain callback, the behavior is undefined.
          @param value The value to add to or replace into the dictionary. The value
            is retained by the dictionary using the retain callback provided
            when the dictionary was created, and the previous value if any is
            released. If the value is not of the sort expected by the
            retain or release callbacks, the behavior is undefined.
        */
        CFDictionarySetValue(classesToMatch,
                             CFSTR(kIOSerialBSDTypeKey),
                             CFSTR(kIOSerialBSDModemType));

        // Each serial device object has a property with key
        // kIOSerialBSDTypeKey and a value that is one of kIOSerialBSDAllTypes,
        // kIOSerialBSDModemType, or kIOSerialBSDRS232Type. You can experiment with the
        // matching by changing the last parameter in the above call to CFDictionarySetValue.

        // As shipped, this sample is only interested in modems,
        // so add this property to the CFDictionary we're matching on.
        // This will find devices that advertise themselves as modems,
        // such as built-in and USB modems. However, this match won't find serial modems.
    }

    /*! @function IOServiceGetMatchingServices
        @abstract Look up registered IOService objects that match a matching dictionary.
        @discussion This is the preferred method of finding IOService objects currently registered by IOKit. IOServiceAddNotification can also supply this information and install a notification of new IOServices. The matching information used in the matching dictionary may vary depending on the class of service being looked up.
        @param masterPort The master port obtained from IOMasterPort().
        @param matching A CF dictionary containing matching information, of which one reference is consumed by this function. IOKitLib can contruct matching dictionaries for common criteria with helper functions such as IOServiceMatching, IOOpenFirmwarePathMatching.
        @param existing An iterator handle is returned on success, and should be released by the caller when the iteration is finished.
        @result A kern_return_t error code. */

    kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, matchingServices);
    if (KERN_SUCCESS != kernResult) {
        printf("IOServiceGetMatchingServices returned %d\n", kernResult);
        goto exit;
    }

exit:
    return kernResult;
}

/** Given an iterator across a set of modems, return the BSD path to the first one.
 *  If no modems are found the path name is set to an empty string.
 */
static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char *bsdPath, CFIndex maxPathSize)
{
    io_object_t    modemService;
    kern_return_t  kernResult = KERN_FAILURE;
    Boolean      modemFound = false;

    // Initialize the returned path
    *bsdPath = '\0';

    // Iterate across all modems found. In this example, we bail after finding the first modem.

    while ((modemService = IOIteratorNext(serialPortIterator)) && !modemFound) {
        CFTypeRef  bsdPathAsCFString;

        // Get the callout device's path (/dev/cu.xxxxx). The callout device should almost always be
        // used: the dialin device (/dev/tty.xxxxx) would be used when monitoring a serial port for
        // incoming calls, e.g. a fax listener.

        bsdPathAsCFString = IORegistryEntryCreateCFProperty(modemService,
                            CFSTR(kIOCalloutDeviceKey),
                            kCFAllocatorDefault,
                            0);
        if (bsdPathAsCFString) {
            Boolean result;

            // Convert the path from a CFString to a C (NUL-terminated) string for use
            // with the POSIX open() call.

            result = CFStringGetCString((CFStringRef)bsdPathAsCFString,
                                        bsdPath,
                                        maxPathSize,
                                        kCFStringEncodingUTF8);
            CFRelease(bsdPathAsCFString);

            if (result) {
                //printf("Modem found with BSD path: %s", bsdPath);
                modemFound = true;
                kernResult = KERN_SUCCESS;
            }
        }

        printf("\n");
200

201 202 203 204 205 206 207 208 209 210
        // Release the io_service_t now that we are done with it.

        (void) IOObjectRelease(modemService);
    }

    return kernResult;
}
#endif

using namespace TNX;
pixhawk's avatar
pixhawk committed
211

212 213
SerialLink::SerialLink(QString portname, int baudRate, bool hardwareFlowControl, bool parity,
                       int dataBits, int stopBits) :
214 215 216
    port(NULL),
    ports(new QVector<QString>()),
          m_stopp(false)
pixhawk's avatar
pixhawk committed
217 218 219
{
    // Setup settings
    this->porthandle = portname.trimmed();
220 221 222 223 224 225

    if (this->porthandle == "" && getCurrentPorts()->size() > 0)
    {
        this->porthandle = getCurrentPorts()->first().trimmed();
    }

pixhawk's avatar
pixhawk committed
226 227 228
#ifdef _WIN32
    // Port names above 20 need the network path format - if the port name is not already in this format
    // catch this special case
229
    if (this->porthandle.size() > 0 && !this->porthandle.startsWith("\\")) {
pixhawk's avatar
pixhawk committed
230 231 232 233 234 235
        // Append \\.\ before the port handle. Additional backslashes are used for escaping.
        this->porthandle = "\\\\.\\" + this->porthandle;
    }
#endif
    // Set unique ID and add link to the list of links
    this->id = getNextLinkId();
236

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    setBaudRate(baudRate);
    if (hardwareFlowControl)
    {
        portSettings.setFlowControl(QPortSettings::FLOW_HARDWARE);
    }
    else
    {
        portSettings.setFlowControl(QPortSettings::FLOW_OFF);
    }
    if (parity)
    {
        portSettings.setParity(QPortSettings::PAR_EVEN);
    }
    else
    {
        portSettings.setParity(QPortSettings::PAR_NONE);
    }
    setDataBits(dataBits);
    setStopBits(stopBits);
pixhawk's avatar
pixhawk committed
256 257

    // Set the port name
258 259
    if (porthandle == "")
    {
260
        name = tr("Serial Link ") + QString::number(getId());
pixhawk's avatar
pixhawk committed
261
    }
262 263 264
    else
    {
        name = portname.trimmed();
pixhawk's avatar
pixhawk committed
265
    }
lm's avatar
lm committed
266
    loadSettings();
pixhawk's avatar
pixhawk committed
267 268 269 270 271
}

SerialLink::~SerialLink()
{
    disconnect();
272
    if(port) delete port;
pixhawk's avatar
pixhawk committed
273
    port = NULL;
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    if (ports) delete ports;
    ports = NULL;
}

QVector<QString>* SerialLink::getCurrentPorts()
{
    ports->clear();
#ifdef __linux

    // TODO Linux has no standard way of enumerating serial ports
    // However the device files are only present when the physical
    // device is connected, therefore listing the files should be
    // sufficient.

    QString devdir = "/dev";
    QDir dir(devdir);
    dir.setFilter(QDir::System);

    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);
        if (fileInfo.fileName().contains(QString("ttyUSB")) || fileInfo.fileName().contains(QString("ttyS")) || fileInfo.fileName().contains(QString("ttyACM")))
        {
            ports->append(fileInfo.canonicalFilePath());
        }
    }
#endif

#if defined (__APPLE__) && defined (__MACH__)

    // Enumerate serial ports
    kern_return_t    kernResult; // on PowerPC this is an int (4 bytes)
    io_iterator_t    serialPortIterator;
    char        bsdPath[MAXPATHLEN];
    kernResult = FindModems(&serialPortIterator);
    kernResult = GetModemPath(serialPortIterator, bsdPath, sizeof(bsdPath));
    IOObjectRelease(serialPortIterator);    // Release the iterator.

    // Add found modems
    if (bsdPath[0])
    {
        ports->append(QString(bsdPath));
    }

    // Add USB serial port adapters
    // TODO Strangely usb serial port adapters are not enumerated, even when connected
    QString devdir = "/dev";
    QDir dir(devdir);
    dir.setFilter(QDir::System);

    QFileInfoList list = dir.entryInfoList();
    for (int i = list.size() - 1; i >= 0; i--) {
        QFileInfo fileInfo = list.at(i);
        if (fileInfo.fileName().contains(QString("ttyUSB")) || fileInfo.fileName().contains(QString("ttyS")) || fileInfo.fileName().contains(QString("tty.usbserial")) || fileInfo.fileName().contains(QString("ttyACM")))
        {
            ports->append(fileInfo.canonicalFilePath());
        }
    }
#endif

#ifdef _WIN32
    // Get the ports available on this system
    QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();

    // Add the ports in reverse order, because we prepend them to the list
    for (int i = ports.size() - 1; i >= 0; i--)
    {
        QextPortInfo portInfo = ports.at(i);
        QString portString = QString(portInfo.portName.toLocal8Bit().constData()) + " - " + QString(ports.at(i).friendName.toLocal8Bit().constData()).split("(").first();
        // Prepend newly found port to the list
oberion's avatar
oberion committed
344
        this->ports->append(portString);
345 346 347 348 349 350 351 352
    }

    //printf("port name: %s\n", ports.at(i).portName.toLocal8Bit().constData());
    //printf("friendly name: %s\n", ports.at(i).friendName.toLocal8Bit().constData());
    //printf("physical name: %s\n", ports.at(i).physName.toLocal8Bit().constData());
    //printf("enumerator name: %s\n", ports.at(i).enumName.toLocal8Bit().constData());
    //printf("===================================\n\n");
#endif
oberion's avatar
oberion committed
353
    return this->ports;
pixhawk's avatar
pixhawk committed
354 355
}

356 357 358 359 360
void SerialLink::loadSettings()
{
    // Load defaults from settings
    QSettings settings(QGC::COMPANYNAME, QGC::APPNAME);
    settings.sync();
361 362
    if (settings.contains("SERIALLINK_COMM_PORT"))
    {
363
        if (porthandle == "") setPortName(settings.value("SERIALLINK_COMM_PORT").toString());
364 365
        setBaudRateType(settings.value("SERIALLINK_COMM_BAUD").toInt());
        setParityType(settings.value("SERIALLINK_COMM_PARITY").toInt());
366 367 368
        setStopBits(settings.value("SERIALLINK_COMM_STOPBITS").toInt());
        setDataBits(settings.value("SERIALLINK_COMM_DATABITS").toInt());
        setFlowType(settings.value("SERIALLINK_COMM_FLOW_CONTROL").toInt());
369 370 371 372 373 374 375 376 377 378
    }
}

void SerialLink::writeSettings()
{
    // Store settings
    QSettings settings(QGC::COMPANYNAME, QGC::APPNAME);
    settings.setValue("SERIALLINK_COMM_PORT", this->porthandle);
    settings.setValue("SERIALLINK_COMM_BAUD", getBaudRateType());
    settings.setValue("SERIALLINK_COMM_PARITY", getParityType());
379 380 381
    settings.setValue("SERIALLINK_COMM_STOPBITS", getStopBits());
    settings.setValue("SERIALLINK_COMM_DATABITS", getDataBits());
    settings.setValue("SERIALLINK_COMM_FLOW_CONTROL", getFlowType());
382 383 384
    settings.sync();
}

pixhawk's avatar
pixhawk committed
385 386 387 388 389

/**
 * @brief Runs the thread
 *
 **/
390 391
void SerialLink::run()
{
pixhawk's avatar
pixhawk committed
392 393 394 395
    // Initialize the connection
    hardwareConnect();

    // Qt way to make clear what a while(1) loop does
396 397
    forever
    {
oberion's avatar
oberion committed
398 399 400 401 402 403 404 405
		{
			QMutexLocker locker(&this->m_stoppMutex);
			if(this->m_stopp)
			{
				this->m_stopp = false;
				break;
			}
		}
pixhawk's avatar
pixhawk committed
406 407 408 409 410 411 412
        // Check if new bytes have arrived, if yes, emit the notification signal
        checkForBytes();
        /* Serial data isn't arriving that fast normally, this saves the thread
                 * from consuming too much processing time
                 */
        MG::SLEEP::msleep(SerialLink::poll_interval);
    }
oberion's avatar
oberion committed
413 414 415 416 417 418 419
	if (port) {
        port->flushInBuffer();
        port->flushOutBuffer();
        port->close();
        delete port;
        port = NULL;
	}
pixhawk's avatar
pixhawk committed
420 421 422
}


423 424
void SerialLink::checkForBytes()
{
pixhawk's avatar
pixhawk committed
425
    /* Check if bytes are available */
426 427
    if(port && port->isOpen() && port->isWritable())
    {
pixhawk's avatar
pixhawk committed
428 429 430 431
        dataMutex.lock();
        qint64 available = port->bytesAvailable();
        dataMutex.unlock();

432 433
        if(available > 0)
        {
434
            readBytes();
pixhawk's avatar
pixhawk committed
435
        }
436 437 438
    }
    else
    {
pixhawk's avatar
pixhawk committed
439
        emit disconnected();
440
        emit connected(false);
pixhawk's avatar
pixhawk committed
441 442 443 444
    }

}

445 446
void SerialLink::writeBytes(const char* data, qint64 size)
{
447
    if(port && port->isOpen()) {
pixhawk's avatar
pixhawk committed
448 449
        int b = port->write(data, size);

450
        if (b > 0) {
451

452
//            qDebug() << "Serial link " << this->getName() << "transmitted" << b << "bytes:";
pixhawk's avatar
pixhawk committed
453

454 455 456
            // Increase write counter
            bitsSentTotal += size * 8;

457 458 459 460 461 462 463
//            int i;
//            for (i=0; i<size; i++)
//            {
//                unsigned char v =data[i];
//                qDebug("%02x ", v);
//            }
//            qDebug("\n");
464
        } else {
465 466 467
            disconnect();
            // Error occured
            emit communicationError(this->getName(), tr("Could not send data - link %1 is disconnected!").arg(this->getName()));
468
        }
pixhawk's avatar
pixhawk committed
469 470 471 472 473 474 475 476 477
    }
}

/**
 * @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
 **/
478 479
void SerialLink::readBytes()
{
pixhawk's avatar
pixhawk committed
480
    dataMutex.lock();
481
    if(port && port->isOpen()) {
482 483
        const qint64 maxLength = 2048;
        char data[maxLength];
pixhawk's avatar
pixhawk committed
484
        qint64 numBytes = port->bytesAvailable();
James Goppert's avatar
James Goppert committed
485
        //qDebug() << "numBytes: " << numBytes;
486

487
        if(numBytes > 0) {
pixhawk's avatar
pixhawk 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
            /* Read as much data in buffer as possible without overflow */
            if(maxLength < numBytes) numBytes = maxLength;

            port->read(data, numBytes);
            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");
            bitsReceivedTotal += numBytes * 8;
        }
    }
    dataMutex.unlock();
}


/**
 * @brief Get the number of bytes to read.
 *
 * @return The number of bytes to read
 **/
515 516
qint64 SerialLink::bytesAvailable()
{
517
    if (port) {
518
        return port->bytesAvailable();
519
    } else {
520 521
        return 0;
    }
pixhawk's avatar
pixhawk committed
522 523 524 525 526 527 528
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
529 530
bool SerialLink::disconnect()
{
oberion's avatar
oberion committed
531 532 533 534 535 536 537 538 539
	if(this->isRunning())
	{
		{
			QMutexLocker locker(&this->m_stoppMutex);
			this->m_stopp = true;
		}
		this->wait();
	
//    if (port) {
540 541 542
        //#if !defined _WIN32 || !defined _WIN64
        /* Block the thread until it returns from run() */
        //#endif
oberion's avatar
oberion committed
543 544 545 546 547
//        port->flushInBuffer();
//        port->flushOutBuffer();
//        port->close();
//        delete port;
//        port = NULL;
pixhawk's avatar
pixhawk committed
548

oberion's avatar
oberion committed
549 550
//        if(this->isRunning()) this->terminate(); //stop running the thread, restart it upon connect
		
551 552
        bool closed = true;
        //port->isOpen();
pixhawk's avatar
pixhawk committed
553

554 555
        emit disconnected();
        emit connected(false);
556
        return closed;
oberion's avatar
oberion committed
557 558
	}
    else {
559 560 561
        // No port, so we're disconnected
        return true;
    }
pixhawk's avatar
pixhawk committed
562 563 564 565 566 567 568 569 570 571

}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
bool SerialLink::connect()
{
572
    if (this->isRunning()) this->disconnect();
oberion's avatar
oberion committed
573 574 575 576
	{
		QMutexLocker locker(&this->m_stoppMutex);
		this->m_stopp = false;
	}
577
    this->start(LowPriority);
578
    return true;
pixhawk's avatar
pixhawk committed
579 580 581 582 583 584 585 586 587 588
}

/**
 * @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.
 **/
589 590
bool SerialLink::hardwareConnect()
{
591
    if(port) {
592 593 594
        port->close();
        delete port;
    }
595 596 597
    port = new QSerialPort(porthandle, portSettings);
    QObject::connect(port,SIGNAL(aboutToClose()),this,SIGNAL(disconnected()));
    port->setCommTimeouts(QSerialPort::CtScheme_NonBlockingRead);
pixhawk's avatar
pixhawk committed
598 599
    connectionStartTime = MG::TIME::getGroundTimeNow();

600 601
    port->open();

pixhawk's avatar
pixhawk committed
602
    bool connectionUp = isConnected();
603
    if(connectionUp) {
pixhawk's avatar
pixhawk committed
604 605 606 607
        emit connected();
        emit connected(true);
    }

608
    //qDebug() << "CONNECTING LINK: " << __FILE__ << __LINE__ << "with settings" << port->portName() << getBaudRate() << getDataBits() << getParityType() << getStopBits();
609 610


611 612
    writeSettings();

pixhawk's avatar
pixhawk committed
613 614
    return connectionUp;
}
615 616


pixhawk's avatar
pixhawk committed
617 618 619 620 621
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
622 623
bool SerialLink::isConnected()
{
624
    if (port) {
lm's avatar
lm committed
625
        return port->isOpen();
626
    } else {
lm's avatar
lm committed
627 628
        return false;
    }
pixhawk's avatar
pixhawk committed
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
}

int SerialLink::getId()
{
    return id;
}

QString SerialLink::getName()
{
    return name;
}

void SerialLink::setName(QString name)
{
    this->name = name;
    emit nameChanged(this->name);
}


648 649
qint64 SerialLink::getNominalDataRate()
{
pixhawk's avatar
pixhawk committed
650
    qint64 dataRate = 0;
651
    switch (portSettings.baudRate()) {
652
#ifndef Q_OS_WIN
653
    case QPortSettings::BAUDR_50:
pixhawk's avatar
pixhawk committed
654 655
        dataRate = 50;
        break;
656
    case QPortSettings::BAUDR_75:
pixhawk's avatar
pixhawk committed
657 658
        dataRate = 75;
        break;
659
    case QPortSettings::BAUDR_110:
pixhawk's avatar
pixhawk committed
660 661
        dataRate = 110;
        break;
662
    case QPortSettings::BAUDR_134:
pixhawk's avatar
pixhawk committed
663 664
        dataRate = 134;
        break;
665
    case QPortSettings::BAUDR_150:
pixhawk's avatar
pixhawk committed
666 667
        dataRate = 150;
        break;
668
    case QPortSettings::BAUDR_200:
pixhawk's avatar
pixhawk committed
669 670
        dataRate = 200;
        break;
671
#endif
672
    case QPortSettings::BAUDR_300:
pixhawk's avatar
pixhawk committed
673 674
        dataRate = 300;
        break;
675
    case QPortSettings::BAUDR_600:
pixhawk's avatar
pixhawk committed
676 677
        dataRate = 600;
        break;
678
    case QPortSettings::BAUDR_1200:
pixhawk's avatar
pixhawk committed
679 680
        dataRate = 1200;
        break;
681
#ifndef Q_OS_WIN
682
    case QPortSettings::BAUDR_1800:
pixhawk's avatar
pixhawk committed
683 684
        dataRate = 1800;
        break;
685
#endif
686
    case QPortSettings::BAUDR_2400:
pixhawk's avatar
pixhawk committed
687 688
        dataRate = 2400;
        break;
689
    case QPortSettings::BAUDR_4800:
pixhawk's avatar
pixhawk committed
690 691
        dataRate = 4800;
        break;
692
    case QPortSettings::BAUDR_9600:
pixhawk's avatar
pixhawk committed
693 694
        dataRate = 9600;
        break;
695 696
#ifdef Q_OS_WIN
    case QPortSettings::BAUDR_14400:
pixhawk's avatar
pixhawk committed
697 698
        dataRate = 14400;
        break;
699 700
#endif
    case QPortSettings::BAUDR_19200:
pixhawk's avatar
pixhawk committed
701 702
        dataRate = 19200;
        break;
703
    case QPortSettings::BAUDR_38400:
pixhawk's avatar
pixhawk committed
704 705
        dataRate = 38400;
        break;
706 707
#ifdef Q_OS_WIN
    case QPortSettings::BAUDR_56000:
pixhawk's avatar
pixhawk committed
708 709
        dataRate = 56000;
        break;
710 711
#endif
    case QPortSettings::BAUDR_57600:
pixhawk's avatar
pixhawk committed
712 713
        dataRate = 57600;
        break;
714
#ifdef Q_OS_WIN_XXXX // FIXME
715
    case QPortSettings::BAUDR_76800:
pixhawk's avatar
pixhawk committed
716 717
        dataRate = 76800;
        break;
718 719
#endif
    case QPortSettings::BAUDR_115200:
pixhawk's avatar
pixhawk committed
720 721
        dataRate = 115200;
        break;
722 723 724
#ifdef Q_OS_WIN
        // Windows-specific high-end baudrates
    case QPortSettings::BAUDR_128000:
pixhawk's avatar
pixhawk committed
725 726
        dataRate = 128000;
        break;
727
    case QPortSettings::BAUDR_256000:
pixhawk's avatar
pixhawk committed
728
        dataRate = 256000;
729
    case QPortSettings::BAUDR_230400:
730
        dataRate = 230400;
731
    case QPortSettings::BAUDR_460800:
732
        dataRate = 460800;
733 734 735
#endif
        // All-OS high-speed
    case QPortSettings::BAUDR_921600:
736
        dataRate = 921600;
pixhawk's avatar
pixhawk committed
737
        break;
738 739 740 741
    case QPortSettings::BAUDR_UNKNOWN:
        default:
        // Do nothing
        break;
pixhawk's avatar
pixhawk committed
742 743 744 745
    }
    return dataRate;
}

746 747
qint64 SerialLink::getTotalUpstream()
{
pixhawk's avatar
pixhawk committed
748 749 750 751 752
    statisticsMutex.lock();
    return bitsSentTotal / ((MG::TIME::getGroundTimeNow() - connectionStartTime) / 1000);
    statisticsMutex.unlock();
}

753 754
qint64 SerialLink::getCurrentUpstream()
{
pixhawk's avatar
pixhawk committed
755 756 757
    return 0; // TODO
}

758 759
qint64 SerialLink::getMaxUpstream()
{
pixhawk's avatar
pixhawk committed
760 761 762
    return 0; // TODO
}

763 764
qint64 SerialLink::getBitsSent()
{
pixhawk's avatar
pixhawk committed
765 766 767
    return bitsSentTotal;
}

768 769
qint64 SerialLink::getBitsReceived()
{
pixhawk's avatar
pixhawk committed
770 771 772
    return bitsReceivedTotal;
}

773 774
qint64 SerialLink::getTotalDownstream()
{
pixhawk's avatar
pixhawk committed
775 776 777 778 779
    statisticsMutex.lock();
    return bitsReceivedTotal / ((MG::TIME::getGroundTimeNow() - connectionStartTime) / 1000);
    statisticsMutex.unlock();
}

780 781
qint64 SerialLink::getCurrentDownstream()
{
pixhawk's avatar
pixhawk committed
782 783 784
    return 0; // TODO
}

785 786
qint64 SerialLink::getMaxDownstream()
{
pixhawk's avatar
pixhawk committed
787 788 789
    return 0; // TODO
}

790 791
bool SerialLink::isFullDuplex()
{
pixhawk's avatar
pixhawk committed
792 793 794 795
    /* Serial connections are always half duplex */
    return false;
}

796 797
int SerialLink::getLinkQuality()
{
pixhawk's avatar
pixhawk committed
798 799 800 801
    /* This feature is not supported with this interface */
    return -1;
}

802 803
QString SerialLink::getPortName()
{
pixhawk's avatar
pixhawk committed
804 805 806
    return porthandle;
}

807 808
int SerialLink::getBaudRate()
{
pixhawk's avatar
pixhawk committed
809 810 811
    return getNominalDataRate();
}

812 813
int SerialLink::getBaudRateType()
{
814
    return portSettings.baudRate();
pixhawk's avatar
pixhawk committed
815 816
}

817 818
int SerialLink::getFlowType()
{
819
    return portSettings.flowControl();
pixhawk's avatar
pixhawk committed
820 821
}

822 823
int SerialLink::getParityType()
{
824
    return portSettings.parity();
pixhawk's avatar
pixhawk committed
825 826
}

827 828
int SerialLink::getDataBitsType()
{
829
    return portSettings.dataBits();
pixhawk's avatar
pixhawk committed
830 831
}

832 833
int SerialLink::getStopBitsType()
{
834
    return portSettings.stopBits();
pixhawk's avatar
pixhawk committed
835 836
}

837 838
int SerialLink::getDataBits()
{
839 840 841
    int ret = -1;
    switch (portSettings.dataBits()) {
    case QPortSettings::DB_5:
842 843
        ret = 5;
        break;
844
    case QPortSettings::DB_6:
845 846
        ret = 6;
        break;
847
    case QPortSettings::DB_7:
848 849
        ret = 7;
        break;
850
    case QPortSettings::DB_8:
851 852 853
        ret = 8;
        break;
    default:
854
        ret = -1;
855 856 857 858 859 860 861
        break;
    }
    return ret;
}

int SerialLink::getStopBits()
{
862 863 864 865 866 867 868 869 870 871 872 873
    int ret = -1;
        switch (portSettings.stopBits()) {
        case QPortSettings::STOP_1:
            ret = 1;
            break;
        case QPortSettings::STOP_2:
            ret = 2;
            break;
        default:
            ret = -1;
            break;
        }
874 875 876
    return ret;
}

pixhawk's avatar
pixhawk committed
877 878
bool SerialLink::setPortName(QString portName)
{
879
    if(portName.trimmed().length() > 0) {
pixhawk's avatar
pixhawk committed
880
        bool reconnect = false;
881 882 883
        if (isConnected()) reconnect = true;
        disconnect();

pixhawk's avatar
pixhawk committed
884 885 886 887 888
        this->porthandle = portName.trimmed();
        setName(tr("serial port ") + portName.trimmed());
#ifdef _WIN32
        // Port names above 20 need the network path format - if the port name is not already in this format
        // catch this special case
889
        if (!this->porthandle.startsWith("\\")) {
pixhawk's avatar
pixhawk committed
890 891 892 893
            // Append \\.\ before the port handle. Additional backslashes are used for escaping.
            this->porthandle = "\\\\.\\" + this->porthandle;
        }
#endif
894

pixhawk's avatar
pixhawk committed
895 896
        if(reconnect) connect();
        return true;
897
    } else {
pixhawk's avatar
pixhawk committed
898 899 900 901 902 903 904 905 906
        return false;
    }
}


bool SerialLink::setBaudRateType(int rateIndex)
{
    bool reconnect = false;
    bool accepted = true; // This is changed if none of the data rates matches
907 908 909
    if(isConnected()) reconnect = true;
    disconnect();

910 911 912 913 914 915 916
#ifdef Q_OS_WIN
	const int minBaud = (int)QPortSettings::BAUDR_14400;
#else
	const int minBaud = (int)QPortSettings::BAUDR_50;
#endif

    if (rateIndex >= minBaud && rateIndex <= (int)QPortSettings::BAUDR_921600)
917 918
    {
        portSettings.setBaudRate((QPortSettings::BaudRate)rateIndex);
pixhawk's avatar
pixhawk committed
919 920 921 922 923 924
    }

    if(reconnect) connect();
    return accepted;
}

925 926 927 928 929 930 931
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
932 933 934

bool SerialLink::setBaudRate(int rate)
{
935
    //qDebug() << "BAUD RATE:" << rate;
936

pixhawk's avatar
pixhawk committed
937 938
    bool reconnect = false;
    bool accepted = true; // This is changed if none of the data rates matches
939
    if(isConnected()) {
pixhawk's avatar
pixhawk committed
940 941
        reconnect = true;
    }
942
    disconnect();
pixhawk's avatar
pixhawk committed
943

944
    switch (rate) {
945 946

#ifndef Q_OS_WIN
pixhawk's avatar
pixhawk committed
947
    case 50:
948
        portSettings.setBaudRate(QPortSettings::BAUDR_50);
pixhawk's avatar
pixhawk committed
949 950
        break;
    case 75:
951
        portSettings.setBaudRate(QPortSettings::BAUDR_75);
pixhawk's avatar
pixhawk committed
952 953
        break;
    case 110:
954
        portSettings.setBaudRate(QPortSettings::BAUDR_110);
pixhawk's avatar
pixhawk committed
955 956
        break;
    case 134:
957
        portSettings.setBaudRate(QPortSettings::BAUDR_134);
pixhawk's avatar
pixhawk committed
958 959
        break;
    case 150:
960
        portSettings.setBaudRate(QPortSettings::BAUDR_150);
pixhawk's avatar
pixhawk committed
961 962
        break;
    case 200:
963
        portSettings.setBaudRate(QPortSettings::BAUDR_200);
pixhawk's avatar
pixhawk committed
964
        break;
965
#endif
pixhawk's avatar
pixhawk committed
966
    case 300:
967
        portSettings.setBaudRate(QPortSettings::BAUDR_300);
pixhawk's avatar
pixhawk committed
968 969
        break;
    case 600:
970
        portSettings.setBaudRate(QPortSettings::BAUDR_600);
pixhawk's avatar
pixhawk committed
971 972
        break;
    case 1200:
973
        portSettings.setBaudRate(QPortSettings::BAUDR_1200);
pixhawk's avatar
pixhawk committed
974
        break;
975
#ifndef Q_OS_WIN
pixhawk's avatar
pixhawk committed
976
    case 1800:
977
        portSettings.setBaudRate(QPortSettings::BAUDR_1800);
pixhawk's avatar
pixhawk committed
978
        break;
979
#endif
pixhawk's avatar
pixhawk committed
980
    case 2400:
981
        portSettings.setBaudRate(QPortSettings::BAUDR_2400);
pixhawk's avatar
pixhawk committed
982 983
        break;
    case 4800:
984
        portSettings.setBaudRate(QPortSettings::BAUDR_4800);
pixhawk's avatar
pixhawk committed
985 986
        break;
    case 9600:
987
        portSettings.setBaudRate(QPortSettings::BAUDR_9600);
pixhawk's avatar
pixhawk committed
988
        break;
989
#ifdef Q_OS_WIN
pixhawk's avatar
pixhawk committed
990
    case 14400:
991
        portSettings.setBaudRate(QPortSettings::BAUDR_14400);
pixhawk's avatar
pixhawk committed
992
        break;
993
#endif
pixhawk's avatar
pixhawk committed
994
    case 19200:
995
        portSettings.setBaudRate(QPortSettings::BAUDR_19200);
pixhawk's avatar
pixhawk committed
996 997
        break;
    case 38400:
998
        portSettings.setBaudRate(QPortSettings::BAUDR_38400);
pixhawk's avatar
pixhawk committed
999
        break;
1000
#ifdef Q_OS_WIN
pixhawk's avatar
pixhawk committed
1001
    case 56000:
1002
        portSettings.setBaudRate(QPortSettings::BAUDR_56000);
pixhawk's avatar
pixhawk committed
1003
        break;
1004
#endif
pixhawk's avatar
pixhawk committed
1005
    case 57600:
1006
        portSettings.setBaudRate(QPortSettings::BAUDR_57600);
pixhawk's avatar
pixhawk committed
1007
        break;
1008
#ifdef Q_OS_WIN_XXXX // FIXME CHECK THIS
pixhawk's avatar
pixhawk committed
1009
    case 76800:
1010
        portSettings.setBaudRate(QPortSettings::BAUDR_76800);
pixhawk's avatar
pixhawk committed
1011
        break;
1012
#endif
pixhawk's avatar
pixhawk committed
1013
    case 115200:
1014
        portSettings.setBaudRate(QPortSettings::BAUDR_115200);
pixhawk's avatar
pixhawk committed
1015
        break;
1016
#ifdef Q_OS_WIN
pixhawk's avatar
pixhawk committed
1017
    case 128000:
1018
        portSettings.setBaudRate(QPortSettings::BAUDR_128000);
pixhawk's avatar
pixhawk committed
1019
        break;
1020
    case 230400:
1021
        portSettings.setBaudRate(QPortSettings::BAUDR_230400);
1022
        break;
pixhawk's avatar
pixhawk committed
1023
    case 256000:
1024
        portSettings.setBaudRate(QPortSettings::BAUDR_256000);
pixhawk's avatar
pixhawk committed
1025
        break;
1026
    case 460800:
1027
        portSettings.setBaudRate(QPortSettings::BAUDR_460800);
1028
        break;
1029
#endif
1030
    case 921600:
1031
        portSettings.setBaudRate(QPortSettings::BAUDR_921600);
1032
        break;
pixhawk's avatar
pixhawk committed
1033 1034 1035 1036 1037 1038
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }

1039 1040 1041
    if(reconnect) connect();
    return accepted;

pixhawk's avatar
pixhawk committed
1042 1043
}

1044 1045
bool SerialLink::setFlowType(int flow)
{
pixhawk's avatar
pixhawk committed
1046 1047
    bool reconnect = false;
    bool accepted = true;
1048 1049
    if(isConnected()) reconnect = true;
    disconnect();
pixhawk's avatar
pixhawk committed
1050

1051
    switch (flow) {
1052 1053
    case (int)QPortSettings::FLOW_OFF:
        portSettings.setFlowControl(QPortSettings::FLOW_OFF);
pixhawk's avatar
pixhawk committed
1054
        break;
1055 1056
    case (int)QPortSettings::FLOW_HARDWARE:
        portSettings.setFlowControl(QPortSettings::FLOW_HARDWARE);
pixhawk's avatar
pixhawk committed
1057
        break;
1058 1059
    case (int)QPortSettings::FLOW_XONXOFF:
        portSettings.setFlowControl(QPortSettings::FLOW_XONXOFF);
pixhawk's avatar
pixhawk committed
1060 1061 1062 1063 1064 1065
        break;
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }
1066

pixhawk's avatar
pixhawk committed
1067 1068 1069 1070
    if(reconnect) connect();
    return accepted;
}

1071 1072
bool SerialLink::setParityType(int parity)
{
pixhawk's avatar
pixhawk committed
1073 1074
    bool reconnect = false;
    bool accepted = true;
1075 1076
    if (isConnected()) reconnect = true;
    disconnect();
pixhawk's avatar
pixhawk committed
1077

1078
    switch (parity) {
1079 1080
    case (int)QPortSettings::PAR_NONE:
        portSettings.setParity(QPortSettings::PAR_NONE);
pixhawk's avatar
pixhawk committed
1081
        break;
1082 1083
    case (int)QPortSettings::PAR_ODD:
        portSettings.setParity(QPortSettings::PAR_ODD);
pixhawk's avatar
pixhawk committed
1084
        break;
1085 1086
    case (int)QPortSettings::PAR_EVEN:
        portSettings.setParity(QPortSettings::PAR_EVEN);
pixhawk's avatar
pixhawk committed
1087
        break;
1088 1089
    case (int)QPortSettings::PAR_SPACE:
        portSettings.setParity(QPortSettings::PAR_SPACE);
pixhawk's avatar
pixhawk committed
1090 1091 1092 1093 1094 1095 1096
        break;
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }

1097
    if (reconnect) connect();
pixhawk's avatar
pixhawk committed
1098 1099 1100
    return accepted;
}

1101

1102
bool SerialLink::setDataBits(int dataBits)
1103
{
1104
    //qDebug() << "Setting" << dataBits << "data bits";
1105 1106
    bool reconnect = false;
    if (isConnected()) reconnect = true;
pixhawk's avatar
pixhawk committed
1107
    bool accepted = true;
1108
    disconnect();
pixhawk's avatar
pixhawk committed
1109

1110
    switch (dataBits) {
pixhawk's avatar
pixhawk committed
1111
    case 5:
1112
        portSettings.setDataBits(QPortSettings::DB_5);
pixhawk's avatar
pixhawk committed
1113 1114
        break;
    case 6:
1115
        portSettings.setDataBits(QPortSettings::DB_6);
pixhawk's avatar
pixhawk committed
1116 1117
        break;
    case 7:
1118
        portSettings.setDataBits(QPortSettings::DB_7);
pixhawk's avatar
pixhawk committed
1119 1120
        break;
    case 8:
1121
        portSettings.setDataBits(QPortSettings::DB_8);
pixhawk's avatar
pixhawk committed
1122 1123 1124 1125 1126 1127 1128
        break;
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }

1129
    if(reconnect) connect();
pixhawk's avatar
pixhawk committed
1130 1131 1132 1133

    return accepted;
}

1134
bool SerialLink::setStopBits(int stopBits)
1135
{
pixhawk's avatar
pixhawk committed
1136 1137
    bool reconnect = false;
    bool accepted = true;
1138 1139
    if(isConnected()) reconnect = true;
    disconnect();
pixhawk's avatar
pixhawk committed
1140

1141
    switch (stopBits) {
pixhawk's avatar
pixhawk committed
1142
    case 1:
1143
        portSettings.setStopBits(QPortSettings::STOP_1);
pixhawk's avatar
pixhawk committed
1144 1145
        break;
    case 2:
1146
        portSettings.setStopBits(QPortSettings::STOP_2);
pixhawk's avatar
pixhawk committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
        break;
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }

    if(reconnect) connect();
    return accepted;
}
1157 1158 1159 1160 1161 1162

bool SerialLink::setDataBitsType(int dataBits)
{
    bool reconnect = false;
    bool accepted = false;

1163 1164
    if (isConnected()) reconnect = true;
    disconnect();
1165

1166 1167
    if (dataBits >= (int)QPortSettings::DB_5 && dataBits <= (int)QPortSettings::DB_8) {
        portSettings.setDataBits((QPortSettings::DataBits) dataBits);
1168

1169
        if(reconnect) connect();
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        accepted = true;
    }

    return accepted;
}

bool SerialLink::setStopBitsType(int stopBits)
{
    bool reconnect = false;
    bool accepted = false;
1180 1181
    if(isConnected()) reconnect = true;
    disconnect();
1182

1183 1184
    if (stopBits >= (int)QPortSettings::STOP_1 && stopBits <= (int)QPortSettings::STOP_2) {
        portSettings.setStopBits((QPortSettings::StopBits) stopBits);
1185

1186
        if(reconnect) connect();
1187 1188 1189 1190 1191 1192
        accepted = true;
    }

    if(reconnect) connect();
    return accepted;
}