SerialConfigurationWindow.cc 19.1 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2
/*=====================================================================

3
QGroundControl Open Source Ground Control Station
pixhawk's avatar
pixhawk committed
4

5
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
pixhawk's avatar
pixhawk committed
6

7
This file is part of the QGROUNDCONTROL project
pixhawk's avatar
pixhawk committed
8

9
    QGROUNDCONTROL is free software: you can redistribute it and/or modify
pixhawk's avatar
pixhawk committed
10 11 12 13
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

14
    QGROUNDCONTROL is distributed in the hope that it will be useful,
pixhawk's avatar
pixhawk committed
15 16 17 18 19
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
20
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
pixhawk's avatar
pixhawk committed
21 22 23 24 25

======================================================================*/

/**
 * @file
lm's avatar
lm committed
26
 *   @brief Implementation of SerialConfigurationWindow
pixhawk's avatar
pixhawk committed
27 28 29 30 31 32 33 34 35
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QDebug>

#include <SerialConfigurationWindow.h>
#include <SerialLinkInterface.h>
#include <QDir>
36
#include <QSettings>
pixhawk's avatar
pixhawk committed
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
#include <QFileInfoList>
#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
90
};
pixhawk's avatar
pixhawk committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

// 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);
111
    if (classesToMatch == NULL) {
pixhawk's avatar
pixhawk committed
112
        printf("IOServiceMatching returned a NULL dictionary.\n");
113
    } else {
pixhawk's avatar
pixhawk committed
114
        /*!
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
          @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.
        */
pixhawk's avatar
pixhawk committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        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);
160
    if (KERN_SUCCESS != kernResult) {
pixhawk's avatar
pixhawk committed
161 162 163 164
        printf("IOServiceGetMatchingServices returned %d\n", kernResult);
        goto exit;
    }

165
exit:
pixhawk's avatar
pixhawk committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    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.

183
    while ((modemService = IOIteratorNext(serialPortIterator)) && !modemFound) {
pixhawk's avatar
pixhawk committed
184 185 186 187 188 189 190
        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,
191 192 193 194
                            CFSTR(kIOCalloutDeviceKey),
                            kCFAllocatorDefault,
                            0);
        if (bsdPathAsCFString) {
pixhawk's avatar
pixhawk committed
195 196 197 198 199 200 201 202 203 204 205
            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);

206
            if (result) {
pixhawk's avatar
pixhawk committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                //printf("Modem found with BSD path: %s", bsdPath);
                modemFound = true;
                kernResult = KERN_SUCCESS;
            }
        }

        printf("\n");

        // Release the io_service_t now that we are done with it.

        (void) IOObjectRelease(modemService);
    }

    return kernResult;
}
#endif

SerialConfigurationWindow::SerialConfigurationWindow(LinkInterface* link, QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags),
225
    userConfigured(false)
pixhawk's avatar
pixhawk committed
226 227 228
{
    SerialLinkInterface* serialLink = dynamic_cast<SerialLinkInterface*>(link);

229
    if(serialLink != 0) {
230
        serialLink->loadSettings();
pixhawk's avatar
pixhawk committed
231 232 233 234
        this->link = serialLink;

        // Setup the user interface according to link type
        ui.setupUi(this);
235 236
        //this->setVisible(false);
        //this->hide();
pixhawk's avatar
pixhawk committed
237 238 239 240 241 242

        // Create action to open this menu
        // Create configuration action for this link
        // Connect the current UAS
        action = new QAction(QIcon(":/images/devices/network-wireless.svg"), "", link);
        setLinkName(link->getName());
243 244 245

        setupPortList();

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        // Set up baud rates
        ui.baudRate->addItem("115200", 115200);

        ui.baudRate->clear();
        ui.baudRate->addItem("50", 50);
        ui.baudRate->addItem("70", 70);
        ui.baudRate->addItem("110", 110);
        ui.baudRate->addItem("134", 134);
        ui.baudRate->addItem("150", 150);
        ui.baudRate->addItem("200", 200);
        ui.baudRate->addItem("300", 300);
        ui.baudRate->addItem("600", 600);
        ui.baudRate->addItem("1200", 1200);
        ui.baudRate->addItem("1800", 1800);
        ui.baudRate->addItem("2400", 2400);
        ui.baudRate->addItem("4800", 4800);
        ui.baudRate->addItem("9600", 9600);
#ifdef Q_OS_WIN
        ui.baudRate->addItem("14400", 14400);
#endif
        ui.baudRate->addItem("19200", 19200);
        ui.baudRate->addItem("34800", 34800);
#ifdef Q_OS_WIN
        ui.baudRate->addItem("56000", 56000);
#endif
        ui.baudRate->addItem("57600", 57600);
#ifdef Q_OS_WIN
        ui.baudRate->addItem("76800", 76800);
#endif
        ui.baudRate->addItem("115200", 115200);
#ifdef Q_OS_WIN
        ui.baudRate->addItem("128000", 128000);
        ui.baudRate->addItem("230400", 230400);
        ui.baudRate->addItem("256000", 256000);
        ui.baudRate->addItem("460800", 460800);
#endif
        ui.baudRate->addItem("921600", 921600);

pixhawk's avatar
pixhawk committed
284 285 286 287 288 289 290 291
        connect(action, SIGNAL(triggered()), this, SLOT(configureCommunication()));

        // Make sure that a change in the link name will be reflected in the UI
        connect(link, SIGNAL(nameChanged(QString)), this, SLOT(setLinkName(QString)));

        // Connect the individual user interface inputs
        connect(ui.portName, SIGNAL(editTextChanged(QString)), this, SLOT(setPortName(QString)));
        connect(ui.portName, SIGNAL(currentIndexChanged(QString)), this, SLOT(setPortName(QString)));
292
        connect(ui.baudRate, SIGNAL(activated(QString)), this->link, SLOT(setBaudRateString(QString)));
pixhawk's avatar
pixhawk committed
293
        connect(ui.flowControlCheckBox, SIGNAL(toggled(bool)), this, SLOT(enableFlowControl(bool)));
lm's avatar
lm committed
294 295 296
        connect(ui.parNone, SIGNAL(toggled(bool)), this, SLOT(setParityNone(bool)));
        connect(ui.parOdd, SIGNAL(toggled(bool)), this, SLOT(setParityOdd(bool)));
        connect(ui.parEven, SIGNAL(toggled(bool)), this, SLOT(setParityEven(bool)));
297 298
        connect(ui.dataBitsSpinBox, SIGNAL(valueChanged(int)), this->link, SLOT(setDataBits(int)));
        connect(ui.stopBitsSpinBox, SIGNAL(valueChanged(int)), this->link, SLOT(setStopBits(int)));
pixhawk's avatar
pixhawk committed
299 300 301 302 303

        //connect(this->link, SIGNAL(connected(bool)), this, SLOT());
        ui.portName->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow);
        ui.baudRate->setSizeAdjustPolicy(QComboBox::AdjustToContentsOnFirstShow);

304
        switch(this->link->getParityType()) {
pixhawk's avatar
pixhawk committed
305 306 307 308 309 310 311 312 313 314 315
        case 0:
            ui.parNone->setChecked(true);
            break;
        case 1:
            ui.parOdd->setChecked(true);
            break;
        case 2:
            ui.parEven->setChecked(true);
            break;
        default:
            // Enforce default: no parity in link
lm's avatar
lm committed
316
            setParityNone(true);
pixhawk's avatar
pixhawk committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
            ui.parNone->setChecked(true);
            break;
        }

        switch(this->link->getFlowType()) {
        case 0:
            ui.flowControlCheckBox->setChecked(false);
            break;
        case 1:
            ui.flowControlCheckBox->setChecked(true);
            break;
        default:
            ui.flowControlCheckBox->setChecked(false);
            enableFlowControl(false);
        }

333
        ui.baudRate->setCurrentIndex(ui.baudRate->findText(QString("%1").arg(this->link->getBaudRate())));
pixhawk's avatar
pixhawk committed
334

335 336
        ui.dataBitsSpinBox->setValue(this->link->getDataBits());
        ui.stopBitsSpinBox->setValue(this->link->getStopBits());
pixhawk's avatar
pixhawk committed
337 338 339 340 341 342 343

        portCheckTimer = new QTimer(this);
        portCheckTimer->setInterval(1000);
        connect(portCheckTimer, SIGNAL(timeout()), this, SLOT(setupPortList()));

        // Display the widget
        this->window()->setWindowTitle(tr("Serial Communication Settings"));
344
        //this->show();
345
    } else {
pixhawk's avatar
pixhawk committed
346 347 348 349 350
        qDebug() << "Link is NOT a serial link, can't open configuration window";

    }
}

351 352
SerialConfigurationWindow::~SerialConfigurationWindow()
{
pixhawk's avatar
pixhawk committed
353 354 355 356 357

}

void SerialConfigurationWindow::showEvent(QShowEvent* event)
{
358 359
    Q_UNUSED(event);
    portCheckTimer->start();
pixhawk's avatar
pixhawk committed
360 361 362 363
}

void SerialConfigurationWindow::hideEvent(QHideEvent* event)
{
364 365
    Q_UNUSED(event);
    portCheckTimer->stop();
pixhawk's avatar
pixhawk committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
}

QAction* SerialConfigurationWindow::getAction()
{
    return action;
}

void SerialConfigurationWindow::configureCommunication()
{
    QString selected = ui.portName->currentText();
    setupPortList();
    ui.portName->setEditText(selected);
    this->show();
}

void SerialConfigurationWindow::setupPortList()
{
    //ui.portName->clear();
    // Get list of existing items


#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);
401 402
        if (fileInfo.fileName().contains(QString("ttyUSB")) || fileInfo.fileName().contains(QString("ttyS"))) {
            if (ui.portName->findText(fileInfo.canonicalFilePath()) == -1) {
pixhawk's avatar
pixhawk committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
                ui.portName->addItem(fileInfo.canonicalFilePath());
                if (!userConfigured) ui.portName->setEditText(fileInfo.canonicalFilePath());
            }
        }
    }
#endif

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

    // Enumerate serial ports
    //int            fileDescriptor;
    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
426 427
    if (bsdPath[0]) {
        if (ui.portName->findText(QString(bsdPath)) == -1) {
pixhawk's avatar
pixhawk committed
428 429 430 431 432 433 434 435 436 437 438 439
            ui.portName->addItem(QString(bsdPath));
            if (!userConfigured) ui.portName->setEditText(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();
440
    for (int i = list.size() - 1; i >= 0; i--) {
pixhawk's avatar
pixhawk committed
441
        QFileInfo fileInfo = list.at(i);
442 443
        if (fileInfo.fileName().contains(QString("ttyUSB")) || fileInfo.fileName().contains(QString("ttyS")) || fileInfo.fileName().contains(QString("tty.usbserial"))) {
            if (ui.portName->findText(fileInfo.canonicalFilePath()) == -1) {
pixhawk's avatar
pixhawk committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457
                ui.portName->addItem(fileInfo.canonicalFilePath());
                if (!userConfigured) ui.portName->setEditText(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
458
    for (int i = ports.size() - 1; i >= 0; i--) {
pixhawk's avatar
pixhawk committed
459 460
        QString portString = QString(ports.at(i).portName.toLocal8Bit().constData()) + " - " + QString(ports.at(i).friendName.toLocal8Bit().constData()).split("(").first();
        // Prepend newly found port to the list
461
        if (ui.portName->findText(portString) == -1) {
pixhawk's avatar
pixhawk committed
462 463 464 465 466 467 468 469 470 471 472 473
            ui.portName->insertItem(0, portString);
            if (!userConfigured) ui.portName->setEditText(portString);
        }
    }

    //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

474 475
    if (this->link) {
        if (this->link->getPortName() != "") {
pixhawk's avatar
pixhawk committed
476 477 478 479 480 481 482
            ui.portName->setEditText(this->link->getPortName());
        }
    }
}

void SerialConfigurationWindow::enableFlowControl(bool flow)
{
483
    if(flow) {
pixhawk's avatar
pixhawk committed
484
        link->setFlowType(1);
485
    } else {
pixhawk's avatar
pixhawk committed
486 487 488 489
        link->setFlowType(0);
    }
}

lm's avatar
lm committed
490
void SerialConfigurationWindow::setParityNone(bool accept)
pixhawk's avatar
pixhawk committed
491
{
lm's avatar
lm committed
492
    if (accept) link->setParityType(0);
pixhawk's avatar
pixhawk committed
493 494
}

lm's avatar
lm committed
495
void SerialConfigurationWindow::setParityOdd(bool accept)
pixhawk's avatar
pixhawk committed
496
{
lm's avatar
lm committed
497
    if (accept) link->setParityType(1);
pixhawk's avatar
pixhawk committed
498 499
}

lm's avatar
lm committed
500
void SerialConfigurationWindow::setParityEven(bool accept)
pixhawk's avatar
pixhawk committed
501
{
lm's avatar
lm committed
502
    if (accept) link->setParityType(2);
pixhawk's avatar
pixhawk committed
503 504 505 506
}

void SerialConfigurationWindow::setPortName(QString port)
{
507
#ifdef Q_OS_WIN
pixhawk's avatar
pixhawk committed
508
    port = port.split("-").first();
509
#endif
pixhawk's avatar
pixhawk committed
510 511
    port = port.remove(" ");

512
    if (this->link->getPortName() != port) {
pixhawk's avatar
pixhawk committed
513 514 515 516 517 518 519
        link->setPortName(port);
    }
    userConfigured = true;
}

void SerialConfigurationWindow::setLinkName(QString name)
{
lm's avatar
lm committed
520 521
    Q_UNUSED(name);
    // FIXME
pixhawk's avatar
pixhawk committed
522 523 524 525 526
    action->setText(tr("Configure ") + link->getName());
    action->setStatusTip(tr("Configure ") + link->getName());
    setWindowTitle(tr("Configuration of ") + link->getName());
}