SerialLink.cc 37.1 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2 3 4 5 6 7 8 9 10 11 12
/*=====================================================================
======================================================================*/
/**
 * @file
 *   @brief Cross-platform support for serial ports
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QTimer>
#include <QDebug>
13
#include <QSettings>
pixhawk's avatar
pixhawk committed
14 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
#ifdef _WIN32
#include "windows.h"
#endif
23 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
#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,
176 177 178
                                                            CFSTR(kIOCalloutDeviceKey),
                                                            kCFAllocatorDefault,
                                                            0);
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        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");
199

200 201 202 203 204 205 206 207 208 209
        // 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
210

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

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

pixhawk's avatar
pixhawk committed
227 228 229
#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
230
    if (this->porthandle.size() > 0 && !this->porthandle.startsWith("\\")) {
pixhawk's avatar
pixhawk committed
231 232 233 234 235 236
        // 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();
237

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    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
257 258

    // Set the port name
259 260
    if (porthandle == "")
    {
261
        name = tr("Serial Link ") + QString::number(getId());
pixhawk's avatar
pixhawk committed
262
    }
263 264 265
    else
    {
        name = portname.trimmed();
pixhawk's avatar
pixhawk committed
266
    }
lm's avatar
lm committed
267
    loadSettings();
pixhawk's avatar
pixhawk committed
268
}
269 270 271 272 273
void SerialLink::requestReset()
{
    QMutexLocker locker(&this->m_stoppMutex);
    m_reqReset = true;
}
pixhawk's avatar
pixhawk committed
274 275 276 277

SerialLink::~SerialLink()
{
    disconnect();
278
    if(port) delete port;
pixhawk's avatar
pixhawk committed
279
    port = NULL;
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
    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);
333
        if (fileInfo.fileName().contains(QString("ttyUSB")) ||
334
                fileInfo.fileName().contains(QString("tty.")) ||
335 336
                fileInfo.fileName().contains(QString("ttyS")) ||
                fileInfo.fileName().contains(QString("ttyACM")))
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        {
            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
353
        this->ports->append(portString);
354 355 356 357 358 359 360 361
    }

    //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
362
    return this->ports;
pixhawk's avatar
pixhawk committed
363 364
}

365 366 367 368 369
void SerialLink::loadSettings()
{
    // Load defaults from settings
    QSettings settings(QGC::COMPANYNAME, QGC::APPNAME);
    settings.sync();
370 371
    if (settings.contains("SERIALLINK_COMM_PORT"))
    {
372
        setPortName(settings.value("SERIALLINK_COMM_PORT").toString());
373 374
        setBaudRateType(settings.value("SERIALLINK_COMM_BAUD").toInt());
        setParityType(settings.value("SERIALLINK_COMM_PARITY").toInt());
375 376 377
        setStopBits(settings.value("SERIALLINK_COMM_STOPBITS").toInt());
        setDataBits(settings.value("SERIALLINK_COMM_DATABITS").toInt());
        setFlowType(settings.value("SERIALLINK_COMM_FLOW_CONTROL").toInt());
378 379 380 381 382 383 384
    }
}

void SerialLink::writeSettings()
{
    // Store settings
    QSettings settings(QGC::COMPANYNAME, QGC::APPNAME);
385
    settings.setValue("SERIALLINK_COMM_PORT", getPortName());
386 387
    settings.setValue("SERIALLINK_COMM_BAUD", getBaudRateType());
    settings.setValue("SERIALLINK_COMM_PARITY", getParityType());
388 389 390
    settings.setValue("SERIALLINK_COMM_STOPBITS", getStopBits());
    settings.setValue("SERIALLINK_COMM_DATABITS", getDataBits());
    settings.setValue("SERIALLINK_COMM_FLOW_CONTROL", getFlowType());
391 392 393
    settings.sync();
}

pixhawk's avatar
pixhawk committed
394 395 396 397 398

/**
 * @brief Runs the thread
 *
 **/
399 400
void SerialLink::run()
{
pixhawk's avatar
pixhawk committed
401
    // Initialize the connection
402 403 404
    if (!hardwareConnect())
    {
        //Need to error out here.
405 406
        emit communicationError(getName(),"Error connecting: " + port->errorString());
        return;
407 408

    }
pixhawk's avatar
pixhawk committed
409 410

    // Qt way to make clear what a while(1) loop does
411
    quint64 msecs = QDateTime::currentMSecsSinceEpoch();
412
    quint64 initialmsecs = QDateTime::currentMSecsSinceEpoch();
413 414 415
    quint64 bytes = 0;
    bool triedreset = false;
    bool triedDTR = false;
416
    int timeout = 5000;
417 418
    forever
    {
419 420 421 422 423 424 425
        {
            QMutexLocker locker(&this->m_stoppMutex);
            if(this->m_stopp)
            {
                this->m_stopp = false;
                break;
            }
426 427 428 429 430 431 432 433
            if (m_reqReset)
            {
                this->m_reqReset = false;
                communicationUpdate(getName(),"Reset requested via DTR signal");
                port->setDtr(true);
                this->msleep(250);
                port->setDtr(false);
            }
434
        }
pixhawk's avatar
pixhawk committed
435 436
        // Check if new bytes have arrived, if yes, emit the notification signal
        checkForBytes();
437 438 439 440 441 442 443
        if (bytes != bytesRead)
        {
            bytes = bytesRead;
            msecs = QDateTime::currentMSecsSinceEpoch();
        }
        else
        {
444
            if (QDateTime::currentMSecsSinceEpoch() - msecs > timeout)
445 446 447
            {
                //It's been 10 seconds since the last data came in. Reset and try again
                msecs = QDateTime::currentMSecsSinceEpoch();
448 449 450 451 452 453 454 455 456
                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;
                }
457 458 459
                if (!triedDTR && triedreset)
                {
                    triedDTR = true;
460
                    communicationUpdate(getName(),"No data to receive on COM port. Attempting to reset via DTR signal");
461 462 463 464 465 466 467 468
                    qDebug() << "No data!!! Attempting reset via DTR.";
                    port->setDtr(true);
                    this->msleep(250);
                    port->setDtr(false);
                }
                else if (!triedreset)
                {
                    qDebug() << "No data!!! Attempting reset via reboot command.";
469
                    communicationUpdate(getName(),"No data to receive on COM port. Assuming possible terminal mode, attempting to reset via \"reboot\" command");
470 471 472 473 474
                    port->write("reboot\r\n",8);
                    triedreset = true;
                }
                else
                {
475
                    communicationUpdate(getName(),"No data to receive on COM port....");
476 477 478 479
                    qDebug() << "No data!!!";
                }
            }
        }
pixhawk's avatar
pixhawk committed
480 481 482 483 484
        /* Serial data isn't arriving that fast normally, this saves the thread
                 * from consuming too much processing time
                 */
        MG::SLEEP::msleep(SerialLink::poll_interval);
    }
485
    if (port) {
oberion's avatar
oberion committed
486 487 488 489 490
        port->flushInBuffer();
        port->flushOutBuffer();
        port->close();
        delete port;
        port = NULL;
491
    }
pixhawk's avatar
pixhawk committed
492 493 494
}


495 496
void SerialLink::checkForBytes()
{
pixhawk's avatar
pixhawk committed
497
    /* Check if bytes are available */
498 499
    if(port && port->isOpen() && port->isWritable())
    {
pixhawk's avatar
pixhawk committed
500 501 502 503
        dataMutex.lock();
        qint64 available = port->bytesAvailable();
        dataMutex.unlock();

504 505
        if(available > 0)
        {
506
            readBytes();
507
            bytesRead += available;
pixhawk's avatar
pixhawk committed
508
        }
509 510 511 512 513 514 515
        else if (available < 0) {
            /* Error, close port */
            port->close();
            emit disconnected();
            emit connected(false);
            emit communicationError(this->getName(), tr("Could not send data - link %1 is disconnected!").arg(this->getName()));
        }
516
    }
517 518 519 520 521
//    else
//    {
//        emit disconnected();
//        emit connected(false);
//    }
pixhawk's avatar
pixhawk committed
522 523 524

}

525 526
void SerialLink::writeBytes(const char* data, qint64 size)
{
527
    if(port && port->isOpen()) {
pixhawk's avatar
pixhawk committed
528 529
        int b = port->write(data, size);

530
        if (b > 0) {
531

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

534 535 536
            // Increase write counter
            bitsSentTotal += size * 8;

537 538 539 540 541 542 543
            //            int i;
            //            for (i=0; i<size; i++)
            //            {
            //                unsigned char v =data[i];
            //                qDebug("%02x ", v);
            //            }
            //            qDebug("\n");
544
        } else {
545 546 547
            disconnect();
            // Error occured
            emit communicationError(this->getName(), tr("Could not send data - link %1 is disconnected!").arg(this->getName()));
548
        }
pixhawk's avatar
pixhawk committed
549 550 551 552 553 554 555 556 557
    }
}

/**
 * @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
 **/
558 559
void SerialLink::readBytes()
{
pixhawk's avatar
pixhawk committed
560
    dataMutex.lock();
561
    if(port && port->isOpen()) {
562 563
        const qint64 maxLength = 2048;
        char data[maxLength];
pixhawk's avatar
pixhawk committed
564
        qint64 numBytes = port->bytesAvailable();
James Goppert's avatar
James Goppert committed
565
        //qDebug() << "numBytes: " << numBytes;
566

567
        if(numBytes > 0) {
pixhawk's avatar
pixhawk committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
            /* 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
 **/
595 596
qint64 SerialLink::bytesAvailable()
{
597
    if (port) {
598
        return port->bytesAvailable();
599
    } else {
600 601
        return 0;
    }
pixhawk's avatar
pixhawk committed
602 603 604 605 606 607 608
}

/**
 * @brief Disconnect the connection.
 *
 * @return True if connection has been disconnected, false if connection couldn't be disconnected.
 **/
609 610
bool SerialLink::disconnect()
{
611 612 613 614 615 616 617 618 619
    if(this->isRunning())
    {
        {
            QMutexLocker locker(&this->m_stoppMutex);
            this->m_stopp = true;
        }
        this->wait();

        //    if (port) {
620 621 622
        //#if !defined _WIN32 || !defined _WIN64
        /* Block the thread until it returns from run() */
        //#endif
623 624 625 626 627 628 629 630
        //        port->flushInBuffer();
        //        port->flushOutBuffer();
        //        port->close();
        //        delete port;
        //        port = NULL;

        //        if(this->isRunning()) this->terminate(); //stop running the thread, restart it upon connect

631 632
        bool closed = true;
        //port->isOpen();
pixhawk's avatar
pixhawk committed
633

634 635
        emit disconnected();
        emit connected(false);
636 637 638
        if (port) {
            port->close();
        }
639
        return closed;
640
    }
oberion's avatar
oberion committed
641
    else {
642 643 644 645
        // not running
        if (port) {
            port->close();
        }
646 647
        return true;
    }
pixhawk's avatar
pixhawk committed
648 649 650 651 652 653 654 655 656 657

}

/**
 * @brief Connect the connection.
 *
 * @return True if connection has been established, false if connection couldn't be established.
 **/
bool SerialLink::connect()
{
658
    if (this->isRunning()) this->disconnect();
659 660 661 662
    {
        QMutexLocker locker(&this->m_stoppMutex);
        this->m_stopp = false;
    }
663
    this->start(LowPriority);
664
    return true;
pixhawk's avatar
pixhawk committed
665 666 667 668 669 670 671 672 673 674
}

/**
 * @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.
 **/
675 676
bool SerialLink::hardwareConnect()
{
677
    if(port) {
678 679 680
        port->close();
        delete port;
    }
681 682 683
    port = new QSerialPort(porthandle, portSettings);
    QObject::connect(port,SIGNAL(aboutToClose()),this,SIGNAL(disconnected()));
    port->setCommTimeouts(QSerialPort::CtScheme_NonBlockingRead);
pixhawk's avatar
pixhawk committed
684 685
    connectionStartTime = MG::TIME::getGroundTimeNow();

686 687 688 689 690 691 692 693
    if (!port->open())
    {
        emit communicationUpdate(getName(),"Error opening port: " + port->errorString());
    }
    else
    {
        emit communicationUpdate(getName(),"Opened port!");
    }
694

pixhawk's avatar
pixhawk committed
695
    bool connectionUp = isConnected();
696
    if(connectionUp) {
pixhawk's avatar
pixhawk committed
697 698 699 700
        emit connected();
        emit connected(true);
    }

701
    //qDebug() << "CONNECTING LINK: " << __FILE__ << __LINE__ << "with settings" << port->portName() << getBaudRate() << getDataBits() << getParityType() << getStopBits();
702 703


704 705
    writeSettings();

pixhawk's avatar
pixhawk committed
706 707
    return connectionUp;
}
708 709


pixhawk's avatar
pixhawk committed
710 711 712 713 714
/**
 * @brief Check if connection is active.
 *
 * @return True if link is connected, false otherwise.
 **/
715 716
bool SerialLink::isConnected()
{
717
    if (port) {
lm's avatar
lm committed
718
        return port->isOpen();
719
    } else {
lm's avatar
lm committed
720 721
        return false;
    }
pixhawk's avatar
pixhawk committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
}

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

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

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


741 742 743 744
/**
  * This function maps baud rate constants to numerical equivalents.
  * It relies on the mapping given in qportsettings.h from the QSerialPort library.
  */
745 746
qint64 SerialLink::getNominalDataRate()
{
pixhawk's avatar
pixhawk committed
747
    qint64 dataRate = 0;
748
    switch (portSettings.baudRate()) {
749

750
    // Baud rates supported only by POSIX systems
751
#if defined(Q_OS_UNIX) || defined(Q_OS_LINUX) || defined(Q_OS_DARWIN)
752
    case QPortSettings::BAUDR_50:
pixhawk's avatar
pixhawk committed
753 754
        dataRate = 50;
        break;
755
    case QPortSettings::BAUDR_75:
pixhawk's avatar
pixhawk committed
756 757
        dataRate = 75;
        break;
758
    case QPortSettings::BAUDR_134:
pixhawk's avatar
pixhawk committed
759 760
        dataRate = 134;
        break;
761
    case QPortSettings::BAUDR_150:
pixhawk's avatar
pixhawk committed
762 763
        dataRate = 150;
        break;
764
    case QPortSettings::BAUDR_200:
pixhawk's avatar
pixhawk committed
765 766
        dataRate = 200;
        break;
767 768 769
    case QPortSettings::BAUDR_1800:
        dataRate = 1800;
        break;
770
#endif
771

772
        // Baud rates supported only by Windows
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
    case QPortSettings::BAUDR_14400:
        dataRate = 14400;
        break;
    case QPortSettings::BAUDR_56000:
        dataRate = 56000;
        break;
    case QPortSettings::BAUDR_128000:
        dataRate = 128000;
        break;
    case QPortSettings::BAUDR_256000:
        dataRate = 256000;
#endif

    case QPortSettings::BAUDR_110:
        dataRate = 110;
        break;
790
    case QPortSettings::BAUDR_300:
pixhawk's avatar
pixhawk committed
791 792
        dataRate = 300;
        break;
793
    case QPortSettings::BAUDR_600:
pixhawk's avatar
pixhawk committed
794 795
        dataRate = 600;
        break;
796
    case QPortSettings::BAUDR_1200:
pixhawk's avatar
pixhawk committed
797 798
        dataRate = 1200;
        break;
799
    case QPortSettings::BAUDR_2400:
pixhawk's avatar
pixhawk committed
800 801
        dataRate = 2400;
        break;
802
    case QPortSettings::BAUDR_4800:
pixhawk's avatar
pixhawk committed
803 804
        dataRate = 4800;
        break;
805
    case QPortSettings::BAUDR_9600:
pixhawk's avatar
pixhawk committed
806 807
        dataRate = 9600;
        break;
808
    case QPortSettings::BAUDR_19200:
pixhawk's avatar
pixhawk committed
809 810
        dataRate = 19200;
        break;
811
    case QPortSettings::BAUDR_38400:
pixhawk's avatar
pixhawk committed
812 813
        dataRate = 38400;
        break;
814
    case QPortSettings::BAUDR_57600:
pixhawk's avatar
pixhawk committed
815 816
        dataRate = 57600;
        break;
817
    case QPortSettings::BAUDR_115200:
pixhawk's avatar
pixhawk committed
818 819
        dataRate = 115200;
        break;
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    case QPortSettings::BAUDR_230400:
        dataRate = 230400;
        break;
    case QPortSettings::BAUDR_460800:
        dataRate = 460800;
        break;
    case QPortSettings::BAUDR_500000:
        dataRate = 500000;
        break;
    case QPortSettings::BAUDR_576000:
        dataRate = 576000;
        break;
    case QPortSettings::BAUDR_921600:
        dataRate = 921600;
        break;
835

836
        // Otherwise do nothing.
837
    case QPortSettings::BAUDR_UNKNOWN:
838
    default:
839
        break;
pixhawk's avatar
pixhawk committed
840 841 842 843
    }
    return dataRate;
}

844 845
qint64 SerialLink::getTotalUpstream()
{
pixhawk's avatar
pixhawk committed
846 847 848 849 850
    statisticsMutex.lock();
    return bitsSentTotal / ((MG::TIME::getGroundTimeNow() - connectionStartTime) / 1000);
    statisticsMutex.unlock();
}

851 852
qint64 SerialLink::getCurrentUpstream()
{
pixhawk's avatar
pixhawk committed
853 854 855
    return 0; // TODO
}

856 857
qint64 SerialLink::getMaxUpstream()
{
pixhawk's avatar
pixhawk committed
858 859 860
    return 0; // TODO
}

861 862
qint64 SerialLink::getBitsSent()
{
pixhawk's avatar
pixhawk committed
863 864 865
    return bitsSentTotal;
}

866 867
qint64 SerialLink::getBitsReceived()
{
pixhawk's avatar
pixhawk committed
868 869 870
    return bitsReceivedTotal;
}

871 872
qint64 SerialLink::getTotalDownstream()
{
pixhawk's avatar
pixhawk committed
873 874 875 876 877
    statisticsMutex.lock();
    return bitsReceivedTotal / ((MG::TIME::getGroundTimeNow() - connectionStartTime) / 1000);
    statisticsMutex.unlock();
}

878 879
qint64 SerialLink::getCurrentDownstream()
{
pixhawk's avatar
pixhawk committed
880 881 882
    return 0; // TODO
}

883 884
qint64 SerialLink::getMaxDownstream()
{
pixhawk's avatar
pixhawk committed
885 886 887
    return 0; // TODO
}

888 889
bool SerialLink::isFullDuplex()
{
pixhawk's avatar
pixhawk committed
890 891 892 893
    /* Serial connections are always half duplex */
    return false;
}

894 895
int SerialLink::getLinkQuality()
{
pixhawk's avatar
pixhawk committed
896 897 898 899
    /* This feature is not supported with this interface */
    return -1;
}

900 901
QString SerialLink::getPortName()
{
pixhawk's avatar
pixhawk committed
902 903 904
    return porthandle;
}

905 906
int SerialLink::getBaudRate()
{
pixhawk's avatar
pixhawk committed
907 908 909
    return getNominalDataRate();
}

910 911
int SerialLink::getBaudRateType()
{
912
    return portSettings.baudRate();
pixhawk's avatar
pixhawk committed
913 914
}

915 916
int SerialLink::getFlowType()
{
917
    return portSettings.flowControl();
pixhawk's avatar
pixhawk committed
918 919
}

920 921
int SerialLink::getParityType()
{
922
    return portSettings.parity();
pixhawk's avatar
pixhawk committed
923 924
}

925 926
int SerialLink::getDataBitsType()
{
927
    return portSettings.dataBits();
pixhawk's avatar
pixhawk committed
928 929
}

930 931
int SerialLink::getStopBitsType()
{
932
    return portSettings.stopBits();
pixhawk's avatar
pixhawk committed
933 934
}

935 936
int SerialLink::getDataBits()
{
937 938 939
    int ret = -1;
    switch (portSettings.dataBits()) {
    case QPortSettings::DB_5:
940 941
        ret = 5;
        break;
942
    case QPortSettings::DB_6:
943 944
        ret = 6;
        break;
945
    case QPortSettings::DB_7:
946 947
        ret = 7;
        break;
948
    case QPortSettings::DB_8:
949 950 951
        ret = 8;
        break;
    default:
952
        ret = -1;
953 954 955 956 957 958 959
        break;
    }
    return ret;
}

int SerialLink::getStopBits()
{
960
    int ret = -1;
961 962 963 964 965 966 967 968 969 970 971
    switch (portSettings.stopBits()) {
    case QPortSettings::STOP_1:
        ret = 1;
        break;
    case QPortSettings::STOP_2:
        ret = 2;
        break;
    default:
        ret = -1;
        break;
    }
972 973 974
    return ret;
}

pixhawk's avatar
pixhawk committed
975 976
bool SerialLink::setPortName(QString portName)
{
977
    if(portName.trimmed().length() > 0) {
pixhawk's avatar
pixhawk committed
978
        bool reconnect = false;
979 980 981
        if (isConnected()) reconnect = true;
        disconnect();

pixhawk's avatar
pixhawk committed
982 983 984 985 986
        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
987
        if (!this->porthandle.startsWith("\\")) {
pixhawk's avatar
pixhawk committed
988 989 990 991
            // Append \\.\ before the port handle. Additional backslashes are used for escaping.
            this->porthandle = "\\\\.\\" + this->porthandle;
        }
#endif
992

pixhawk's avatar
pixhawk committed
993 994
        if(reconnect) connect();
        return true;
995
    } else {
pixhawk's avatar
pixhawk committed
996 997 998 999 1000 1001 1002 1003 1004
        return false;
    }
}


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

1008
    // These minimum and maximum baud rates were based on those enumerated in qportsettings.h.
1009
#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
1010
    const int minBaud = (int)QPortSettings::BAUDR_110;
1011
    const int maxBaud = (int)QPortSettings::BAUDR_921600;
1012
#elif defined(Q_OS_LINUX)
1013 1014
    const int minBaud = (int)QPortSettings::BAUDR_50;
    const int maxBaud = (int)QPortSettings::BAUDR_921600;
1015
#elif defined(Q_OS_UNIX) || defined(Q_OS_DARWIN)
1016
    const int minBaud = (int)QPortSettings::BAUDR_50;
1017
    const int maxBaud = (int)QPortSettings::BAUDR_921600;
1018 1019
#endif

1020
    if (rateIndex >= minBaud && rateIndex <= maxBaud)
1021 1022
    {
        portSettings.setBaudRate((QPortSettings::BaudRate)rateIndex);
pixhawk's avatar
pixhawk committed
1023 1024 1025 1026 1027 1028
    }

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

1029 1030 1031 1032 1033 1034 1035
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
1036 1037 1038 1039 1040

bool SerialLink::setBaudRate(int rate)
{
    bool reconnect = false;
    bool accepted = true; // This is changed if none of the data rates matches
1041
    if(isConnected()) {
pixhawk's avatar
pixhawk committed
1042 1043
        reconnect = true;
    }
1044
    disconnect();
1045

1046
    // This switch-statment relies on the mapping given in qportsettings.h from the QSerialPort library.
1047
    switch (rate) {
1048

1049
    // Baud rates supported only by non-Windows systems
1050
#if defined(Q_OS_UNIX) || defined(Q_OS_LINUX) || defined(Q_OS_DARWIN)
pixhawk's avatar
pixhawk committed
1051
    case 50:
1052
        portSettings.setBaudRate(QPortSettings::BAUDR_50);
pixhawk's avatar
pixhawk committed
1053 1054
        break;
    case 75:
1055
        portSettings.setBaudRate(QPortSettings::BAUDR_75);
pixhawk's avatar
pixhawk committed
1056 1057
        break;
    case 134:
1058
        portSettings.setBaudRate(QPortSettings::BAUDR_134);
pixhawk's avatar
pixhawk committed
1059 1060
        break;
    case 150:
1061
        portSettings.setBaudRate(QPortSettings::BAUDR_150);
pixhawk's avatar
pixhawk committed
1062 1063
        break;
    case 200:
1064
        portSettings.setBaudRate(QPortSettings::BAUDR_200);
pixhawk's avatar
pixhawk committed
1065
        break;
1066 1067 1068 1069 1070
    case 1800:
        portSettings.setBaudRate(QPortSettings::BAUDR_1800);
        break;
#endif

1071
        // Baud rates supported only by windows
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
    case 14400:
        portSettings.setBaudRate(QPortSettings::BAUDR_14400);
        break;
    case 56000:
        portSettings.setBaudRate(QPortSettings::BAUDR_56000);
        break;
    case 128000:
        portSettings.setBaudRate(QPortSettings::BAUDR_128000);
        break;
    case 256000:
        portSettings.setBaudRate(QPortSettings::BAUDR_256000);
        break;
1085
#endif
1086

1087
        // Supported by all OSes:
1088 1089 1090
    case 110:
        portSettings.setBaudRate(QPortSettings::BAUDR_110);
        break;
pixhawk's avatar
pixhawk committed
1091
    case 300:
1092
        portSettings.setBaudRate(QPortSettings::BAUDR_300);
pixhawk's avatar
pixhawk committed
1093 1094
        break;
    case 600:
1095
        portSettings.setBaudRate(QPortSettings::BAUDR_600);
pixhawk's avatar
pixhawk committed
1096 1097
        break;
    case 1200:
1098
        portSettings.setBaudRate(QPortSettings::BAUDR_1200);
pixhawk's avatar
pixhawk committed
1099 1100
        break;
    case 2400:
1101
        portSettings.setBaudRate(QPortSettings::BAUDR_2400);
pixhawk's avatar
pixhawk committed
1102 1103
        break;
    case 4800:
1104
        portSettings.setBaudRate(QPortSettings::BAUDR_4800);
pixhawk's avatar
pixhawk committed
1105 1106
        break;
    case 9600:
1107
        portSettings.setBaudRate(QPortSettings::BAUDR_9600);
pixhawk's avatar
pixhawk committed
1108 1109
        break;
    case 19200:
1110
        portSettings.setBaudRate(QPortSettings::BAUDR_19200);
pixhawk's avatar
pixhawk committed
1111 1112
        break;
    case 38400:
1113
        portSettings.setBaudRate(QPortSettings::BAUDR_38400);
pixhawk's avatar
pixhawk committed
1114 1115
        break;
    case 57600:
1116
        portSettings.setBaudRate(QPortSettings::BAUDR_57600);
pixhawk's avatar
pixhawk committed
1117 1118
        break;
    case 115200:
1119
        portSettings.setBaudRate(QPortSettings::BAUDR_115200);
pixhawk's avatar
pixhawk committed
1120
        break;
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    case 230400:
        portSettings.setBaudRate(QPortSettings::BAUDR_230400);
        break;
    case 460800:
        portSettings.setBaudRate(QPortSettings::BAUDR_460800);
        break;
    case 500000:
        portSettings.setBaudRate(QPortSettings::BAUDR_500000);
        break;
    case 576000:
        portSettings.setBaudRate(QPortSettings::BAUDR_576000);
        break;
    case 921600:
        portSettings.setBaudRate(QPortSettings::BAUDR_921600);
        break;
pixhawk's avatar
pixhawk committed
1136 1137 1138 1139 1140 1141
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }

1142 1143 1144
    if(reconnect) connect();
    return accepted;

pixhawk's avatar
pixhawk committed
1145 1146
}

1147 1148
bool SerialLink::setFlowType(int flow)
{
pixhawk's avatar
pixhawk committed
1149 1150
    bool reconnect = false;
    bool accepted = true;
1151 1152
    if(isConnected()) reconnect = true;
    disconnect();
pixhawk's avatar
pixhawk committed
1153

1154
    switch (flow) {
1155 1156
    case (int)QPortSettings::FLOW_OFF:
        portSettings.setFlowControl(QPortSettings::FLOW_OFF);
pixhawk's avatar
pixhawk committed
1157
        break;
1158 1159
    case (int)QPortSettings::FLOW_HARDWARE:
        portSettings.setFlowControl(QPortSettings::FLOW_HARDWARE);
pixhawk's avatar
pixhawk committed
1160
        break;
1161 1162
    case (int)QPortSettings::FLOW_XONXOFF:
        portSettings.setFlowControl(QPortSettings::FLOW_XONXOFF);
pixhawk's avatar
pixhawk committed
1163 1164 1165 1166 1167 1168
        break;
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }
1169

pixhawk's avatar
pixhawk committed
1170 1171 1172 1173
    if(reconnect) connect();
    return accepted;
}

1174 1175
bool SerialLink::setParityType(int parity)
{
pixhawk's avatar
pixhawk committed
1176 1177
    bool reconnect = false;
    bool accepted = true;
1178 1179
    if (isConnected()) reconnect = true;
    disconnect();
pixhawk's avatar
pixhawk committed
1180

1181
    switch (parity) {
1182 1183
    case (int)QPortSettings::PAR_NONE:
        portSettings.setParity(QPortSettings::PAR_NONE);
pixhawk's avatar
pixhawk committed
1184
        break;
1185 1186
    case (int)QPortSettings::PAR_ODD:
        portSettings.setParity(QPortSettings::PAR_ODD);
pixhawk's avatar
pixhawk committed
1187
        break;
1188 1189
    case (int)QPortSettings::PAR_EVEN:
        portSettings.setParity(QPortSettings::PAR_EVEN);
pixhawk's avatar
pixhawk committed
1190
        break;
1191 1192
    case (int)QPortSettings::PAR_SPACE:
        portSettings.setParity(QPortSettings::PAR_SPACE);
pixhawk's avatar
pixhawk committed
1193 1194 1195 1196 1197 1198 1199
        break;
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }

1200
    if (reconnect) connect();
pixhawk's avatar
pixhawk committed
1201 1202 1203
    return accepted;
}

1204

1205
bool SerialLink::setDataBits(int dataBits)
1206
{
1207
    //qDebug() << "Setting" << dataBits << "data bits";
1208 1209
    bool reconnect = false;
    if (isConnected()) reconnect = true;
pixhawk's avatar
pixhawk committed
1210
    bool accepted = true;
1211
    disconnect();
pixhawk's avatar
pixhawk committed
1212

1213
    switch (dataBits) {
pixhawk's avatar
pixhawk committed
1214
    case 5:
1215
        portSettings.setDataBits(QPortSettings::DB_5);
pixhawk's avatar
pixhawk committed
1216 1217
        break;
    case 6:
1218
        portSettings.setDataBits(QPortSettings::DB_6);
pixhawk's avatar
pixhawk committed
1219 1220
        break;
    case 7:
1221
        portSettings.setDataBits(QPortSettings::DB_7);
pixhawk's avatar
pixhawk committed
1222 1223
        break;
    case 8:
1224
        portSettings.setDataBits(QPortSettings::DB_8);
pixhawk's avatar
pixhawk committed
1225 1226 1227 1228 1229 1230 1231
        break;
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }

1232
    if(reconnect) connect();
pixhawk's avatar
pixhawk committed
1233 1234 1235 1236

    return accepted;
}

1237
bool SerialLink::setStopBits(int stopBits)
1238
{
pixhawk's avatar
pixhawk committed
1239 1240
    bool reconnect = false;
    bool accepted = true;
1241 1242
    if(isConnected()) reconnect = true;
    disconnect();
pixhawk's avatar
pixhawk committed
1243

1244
    switch (stopBits) {
pixhawk's avatar
pixhawk committed
1245
    case 1:
1246
        portSettings.setStopBits(QPortSettings::STOP_1);
pixhawk's avatar
pixhawk committed
1247 1248
        break;
    case 2:
1249
        portSettings.setStopBits(QPortSettings::STOP_2);
pixhawk's avatar
pixhawk committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        break;
    default:
        // If none of the above cases matches, there must be an error
        accepted = false;
        break;
    }

    if(reconnect) connect();
    return accepted;
}
1260 1261 1262 1263 1264 1265

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

1266 1267
    if (isConnected()) reconnect = true;
    disconnect();
1268

1269 1270
    if (dataBits >= (int)QPortSettings::DB_5 && dataBits <= (int)QPortSettings::DB_8) {
        portSettings.setDataBits((QPortSettings::DataBits) dataBits);
1271

1272
        if(reconnect) connect();
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
        accepted = true;
    }

    return accepted;
}

bool SerialLink::setStopBitsType(int stopBits)
{
    bool reconnect = false;
    bool accepted = false;
1283 1284
    if(isConnected()) reconnect = true;
    disconnect();
1285

1286 1287
    if (stopBits >= (int)QPortSettings::STOP_1 && stopBits <= (int)QPortSettings::STOP_2) {
        portSettings.setStopBits((QPortSettings::StopBits) stopBits);
1288

1289
        if(reconnect) connect();
1290 1291 1292 1293 1294 1295
        accepted = true;
    }

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