diff options
author | Frederik Gladhorn <frederik.gladhorn@theqtcompany.com> | 2015-02-20 15:55:55 +0100 |
---|---|---|
committer | Frederik Gladhorn <frederik.gladhorn@theqtcompany.com> | 2015-02-25 10:22:53 +0100 |
commit | a325de1910e6627e4d042114d22303cc68fae7a9 (patch) | |
tree | cabf88f9e4e42579e6695ecff5e6ab787f3922ab /src | |
parent | d42d5838b9a4c3cbd6b0e67dabce658ba737eba8 (diff) | |
parent | b84fe7eb3d6d977a347bfbb82da724409b2eda69 (diff) | |
download | qtserialport-a325de1910e6627e4d042114d22303cc68fae7a9.tar.gz |
Merge remote-tracking branch 'origin/5.4' into 5.5
Conflicts:
.qmake.conf
src/serialport/qserialport_unix.cpp
src/serialport/qserialport_unix_p.h
src/serialport/qserialport_win.cpp
src/serialport/qserialport_win_p.h
src/serialport/qserialport_wince.cpp
src/serialport/qserialport_wince_p.h
Change-Id: Ibb917652b132e66fbb90f437bf762c1094911dc0
Diffstat (limited to 'src')
-rw-r--r-- | src/serialport/doc/qtserialport.qdocconf | 2 | ||||
-rw-r--r-- | src/serialport/doc/src/qtserialport-examples.qdoc | 45 | ||||
-rw-r--r-- | src/serialport/qserialport.cpp | 20 | ||||
-rw-r--r-- | src/serialport/qserialport_p.h | 6 | ||||
-rw-r--r-- | src/serialport/qserialport_unix.cpp | 75 | ||||
-rw-r--r-- | src/serialport/qserialport_win.cpp | 24 | ||||
-rw-r--r-- | src/serialport/qserialport_wince.cpp | 31 | ||||
-rw-r--r-- | src/serialport/qserialportinfo.cpp | 2 | ||||
-rw-r--r-- | src/serialport/qserialportinfo.h | 6 | ||||
-rw-r--r-- | src/serialport/qserialportinfo_unix.cpp | 320 | ||||
-rw-r--r-- | src/serialport/qserialportinfo_win.cpp | 12 | ||||
-rw-r--r-- | src/serialport/qserialportinfo_wince.cpp | 12 |
12 files changed, 319 insertions, 236 deletions
diff --git a/src/serialport/doc/qtserialport.qdocconf b/src/serialport/doc/qtserialport.qdocconf index ffc7584..78c1b35 100644 --- a/src/serialport/doc/qtserialport.qdocconf +++ b/src/serialport/doc/qtserialport.qdocconf @@ -36,7 +36,7 @@ excludedirs += ../qt4support examplesinstallpath = serialport -depends += qtcore qtdoc +depends += qtcore qtdoc qtnetwork qmake navigation.landingpage = "Qt Serial Port" navigation.cppclassespage = "Qt Serial Port C++ Classes" diff --git a/src/serialport/doc/src/qtserialport-examples.qdoc b/src/serialport/doc/src/qtserialport-examples.qdoc new file mode 100644 index 0000000..1a04cfa --- /dev/null +++ b/src/serialport/doc/src/qtserialport-examples.qdoc @@ -0,0 +1,45 @@ +/**************************************************************************** +** +** Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com> +** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org> +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: http://www.gnu.org/copyleft/fdl.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \title Qt Serial Port Examples + \group qtserialport-examples + \brief List of serial port examples + + The \l{Qt Serial Port} module provides the following examples for reference + to help understand the API usage. + + \section1 Running the Examples + + To run the examples from \l{Qt Creator Manual}{Qt Creator}, open the \gui + Welcome mode and select the example from \gui Examples. + For more information, visit + \l{Qt Creator: Building and Running an Example}{Building and Running an Example}. + +*/ diff --git a/src/serialport/qserialport.cpp b/src/serialport/qserialport.cpp index dc632f6..cb87689 100644 --- a/src/serialport/qserialport.cpp +++ b/src/serialport/qserialport.cpp @@ -55,8 +55,6 @@ QSerialPortPrivate::QSerialPortPrivate() , stopBits(QSerialPort::OneStop) , flowControl(QSerialPort::NoFlowControl) , policy(QSerialPort::IgnorePolicy) - , dataTerminalReady(false) - , requestToSend(false) #if QT_DEPRECATED_SINCE(5,3) , settingsRestoredOnClose(true) #endif @@ -530,20 +528,16 @@ bool QSerialPort::open(OpenMode mode) if (!d->open(mode)) return false; - QIODevice::open(mode); - if (!d->setBaudRate() || !d->setDataBits(d->dataBits) || !d->setParity(d->parity) || !d->setStopBits(d->stopBits) || !d->setFlowControl(d->flowControl)) { - close(); + d->close(); return false; } - d->dataTerminalReady = isDataTerminalReady(); - d->requestToSend = isRequestToSend(); - + QIODevice::open(mode); return true; } @@ -874,11 +868,10 @@ bool QSerialPort::setDataTerminalReady(bool set) return false; } + const bool dataTerminalReady = isDataTerminalReady(); const bool retval = d->setDataTerminalReady(set); - if (retval && (d->dataTerminalReady != set)) { - d->dataTerminalReady = set; + if (retval && (dataTerminalReady != set)) emit dataTerminalReadyChanged(set); - } return retval; } @@ -922,11 +915,10 @@ bool QSerialPort::setRequestToSend(bool set) return false; } + const bool requestToSend = isRequestToSend(); const bool retval = d->setRequestToSend(set); - if (retval && (d->requestToSend != set)) { - d->requestToSend = set; + if (retval && (requestToSend != set)) emit requestToSendChanged(set); - } return retval; } diff --git a/src/serialport/qserialport_p.h b/src/serialport/qserialport_p.h index ef29678..8ce7a49 100644 --- a/src/serialport/qserialport_p.h +++ b/src/serialport/qserialport_p.h @@ -172,8 +172,6 @@ public: QSerialPort::StopBits stopBits; QSerialPort::FlowControl flowControl; QSerialPort::DataErrorPolicy policy; - bool dataTerminalReady; - bool requestToSend; bool settingsRestoredOnClose; bool isBreakEnabled; @@ -185,7 +183,7 @@ public: bool waitForReadOrWrite(bool *selectForRead, bool *selectForWrite, bool checkRead, bool checkWrite, - int msecs, bool *timedOut); + int msecs); void processIoErrors(bool error); bool notifyRead(); @@ -260,7 +258,7 @@ public: bool waitForReadOrWrite(bool *selectForRead, bool *selectForWrite, bool checkRead, bool checkWrite, - int msecs, bool *timedOut); + int msecs); qint64 readFromPort(char *data, qint64 maxSize); qint64 writeToPort(const char *data, qint64 maxSize); diff --git a/src/serialport/qserialport_unix.cpp b/src/serialport/qserialport_unix.cpp index 04e3e4e..34ef41d 100644 --- a/src/serialport/qserialport_unix.cpp +++ b/src/serialport/qserialport_unix.cpp @@ -212,19 +212,19 @@ void QSerialPortPrivate::close() if (readNotifier) { readNotifier->setEnabled(false); readNotifier->deleteLater(); - readNotifier = 0; + readNotifier = Q_NULLPTR; } if (writeNotifier) { writeNotifier->setEnabled(false); writeNotifier->deleteLater(); - writeNotifier = 0; + writeNotifier = Q_NULLPTR; } if (qt_safe_close(descriptor) == -1) q->setError(decodeSystemError()); - lockFileScopedPointer.reset(0); + lockFileScopedPointer.reset(Q_NULLPTR); descriptor = -1; pendingBytesWritten = 0; @@ -365,19 +365,14 @@ qint64 QSerialPortPrivate::readData(char *data, qint64 maxSize) bool QSerialPortPrivate::waitForReadyRead(int msecs) { - Q_Q(QSerialPort); - QElapsedTimer stopWatch; stopWatch.start(); do { bool readyToRead = false; bool readyToWrite = false; - bool timedOut = false; if (!waitForReadOrWrite(&readyToRead, &readyToWrite, true, !writeBuffer.isEmpty(), - timeoutValue(msecs, stopWatch.elapsed()), &timedOut)) { - if (!timedOut) - q->setError(decodeSystemError()); + timeoutValue(msecs, stopWatch.elapsed()))) { return false; } @@ -392,8 +387,6 @@ bool QSerialPortPrivate::waitForReadyRead(int msecs) bool QSerialPortPrivate::waitForBytesWritten(int msecs) { - Q_Q(QSerialPort); - if (writeBuffer.isEmpty() && pendingBytesWritten <= 0) return false; @@ -403,11 +396,8 @@ bool QSerialPortPrivate::waitForBytesWritten(int msecs) forever { bool readyToRead = false; bool readyToWrite = false; - bool timedOut = false; if (!waitForReadOrWrite(&readyToRead, &readyToWrite, true, !writeBuffer.isEmpty(), - timeoutValue(msecs, stopWatch.elapsed()), &timedOut)) { - if (!timedOut) - q->setError(decodeSystemError()); + timeoutValue(msecs, stopWatch.elapsed()))) { return false; } @@ -562,6 +552,7 @@ bool QSerialPortPrivate::setBaudRate(qint32 baudRate, QSerialPort::Directions di if (error == QSerialPort::NoError) return updateTermios(); + q->setError(error); return false; } @@ -701,17 +692,6 @@ bool QSerialPortPrivate::readNotification() { Q_Q(QSerialPort); - // Prevent recursive calls - if (readPortNotifierCalled) { - if (!readPortNotifierStateSet) { - readPortNotifierStateSet = true; - readPortNotifierState = isReadNotificationEnabled(); - setReadNotificationEnabled(false); - } - } - - readPortNotifierCalled = true; - // Always buffered, read data from the port into the read buffer qint64 newBytes = buffer.size(); qint64 bytesToRead = policy == QSerialPort::IgnorePolicy ? ReadChunkSize : 1; @@ -756,16 +736,6 @@ bool QSerialPortPrivate::readNotification() emittedReadyRead = false; } - if (!hasData) - setReadNotificationEnabled(true); - - // reset the read port notifier state if we reentered inside the - // readyRead() connected slot. - if (readPortNotifierStateSet - && readPortNotifierState != isReadNotificationEnabled()) { - setReadNotificationEnabled(readPortNotifierState); - readPortNotifierStateSet = false; - } return true; } @@ -916,6 +886,26 @@ QSerialPort::SerialPortError QSerialPortPrivate::decodeSystemError(int systemErr error = QSerialPort::ResourceError; break; #endif +#ifdef EINVAL + case EINVAL: + error = QSerialPort::UnsupportedOperationError; + break; +#endif +#ifdef ENOIOCTLCMD + case ENOIOCTLCMD: + error = QSerialPort::UnsupportedOperationError; + break; +#endif +#ifdef ENOTTY + case ENOTTY: + error = QSerialPort::UnsupportedOperationError; + break; +#endif +#ifdef EPERM + case EPERM: + error = QSerialPort::PermissionError; + break; +#endif default: error = QSerialPort::UnknownError; break; @@ -959,13 +949,12 @@ void QSerialPortPrivate::setWriteNotificationEnabled(bool enable) bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectForWrite, bool checkRead, bool checkWrite, - int msecs, bool *timedOut) + int msecs) { Q_Q(QSerialPort); Q_ASSERT(selectForRead); Q_ASSERT(selectForWrite); - Q_ASSERT(timedOut); fd_set fdread; FD_ZERO(&fdread); @@ -981,19 +970,19 @@ bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectFor tv.tv_sec = msecs / 1000; tv.tv_usec = (msecs % 1000) * 1000; - int ret = ::select(descriptor + 1, &fdread, &fdwrite, 0, msecs < 0 ? 0 : &tv); - if (ret < 0) + const int ret = ::select(descriptor + 1, &fdread, &fdwrite, 0, msecs < 0 ? 0 : &tv); + if (ret < 0) { + q->setError(decodeSystemError()); return false; + } if (ret == 0) { - *timedOut = true; q->setError(QSerialPort::TimeoutError); return false; } *selectForRead = FD_ISSET(descriptor, &fdread); *selectForWrite = FD_ISSET(descriptor, &fdwrite); - - return ret; + return true; } qint64 QSerialPortPrivate::readFromPort(char *data, qint64 maxSize) diff --git a/src/serialport/qserialport_win.cpp b/src/serialport/qserialport_win.cpp index fecc944..48db81d 100644 --- a/src/serialport/qserialport_win.cpp +++ b/src/serialport/qserialport_win.cpp @@ -90,7 +90,7 @@ bool QSerialPortPrivate::open(QIODevice::OpenMode mode) desiredAccess |= GENERIC_WRITE; handle = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation.utf16()), - desiredAccess, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); + desiredAccess, 0, Q_NULLPTR, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, Q_NULLPTR); if (handle == INVALID_HANDLE_VALUE) { q->setError(decodeSystemError()); @@ -158,9 +158,9 @@ QSerialPort::PinoutSignals QSerialPortPrivate::pinoutSignals() ret |= QSerialPort::DataCarrierDetectSignal; DWORD bytesReturned = 0; - if (!::DeviceIoControl(handle, IOCTL_SERIAL_GET_DTRRTS, NULL, 0, + if (!::DeviceIoControl(handle, IOCTL_SERIAL_GET_DTRRTS, Q_NULLPTR, 0, &modemStat, sizeof(modemStat), - &bytesReturned, NULL)) { + &bytesReturned, Q_NULLPTR)) { q->setError(decodeSystemError()); return ret; } @@ -208,13 +208,10 @@ bool QSerialPortPrivate::clear(QSerialPort::Directions directions) Q_Q(QSerialPort); DWORD flags = 0; - if (directions & QSerialPort::Input) { + if (directions & QSerialPort::Input) flags |= PURGE_RXABORT | PURGE_RXCLEAR; - readStarted = false; - } if (directions & QSerialPort::Output) { flags |= PURGE_TXABORT | PURGE_TXCLEAR; - writeStarted = false; actualBytesToWrite = 0; } if (!::PurgeComm(handle, flags)) { @@ -226,7 +223,7 @@ bool QSerialPortPrivate::clear(QSerialPort::Directions directions) // PurgeComm can abort of current reading sequence, or a port is in hardware // flow control mode, or a port has a limited read buffer size. if (directions & QSerialPort::Input) - startAsyncRead(); + startAsyncCommunication(); return true; } @@ -475,11 +472,12 @@ bool QSerialPortPrivate::completeAsyncRead(qint64 bytesTransferred) readStarted = false; - // start async read for possible remainder into driver queue if ((bytesTransferred == ReadChunkSize) && (policy == QSerialPort::IgnorePolicy)) return startAsyncRead(); - else // driver queue is emplty, so startup wait comm event + else if (readBufferMaxSize == 0 || readBufferMaxSize > buffer.size()) return startAsyncCommunication(); + else + return true; } bool QSerialPortPrivate::completeAsyncWrite(qint64 bytesTransferred) @@ -536,7 +534,7 @@ bool QSerialPortPrivate::startAsyncRead() } ::ZeroMemory(&readCompletionOverlapped, sizeof(readCompletionOverlapped)); - if (::ReadFile(handle, readChunkBuffer.data(), bytesToRead, NULL, &readCompletionOverlapped)) { + if (::ReadFile(handle, readChunkBuffer.data(), bytesToRead, Q_NULLPTR, &readCompletionOverlapped)) { readStarted = true; return true; } @@ -565,7 +563,7 @@ bool QSerialPortPrivate::_q_startAsyncWrite() const int writeBytes = writeBuffer.nextDataBlockSize(); ::ZeroMemory(&writeCompletionOverlapped, sizeof(writeCompletionOverlapped)); if (!::WriteFile(handle, writeBuffer.readPointer(), - writeBytes, NULL, &writeCompletionOverlapped)) { + writeBytes, Q_NULLPTR, &writeCompletionOverlapped)) { QSerialPort::SerialPortError error = decodeSystemError(); if (error != QSerialPort::NoError) { @@ -665,7 +663,7 @@ void QSerialPortPrivate::handleLineStatusErrors() Q_Q(QSerialPort); DWORD errors = 0; - if (!::ClearCommError(handle, &errors, NULL)) { + if (!::ClearCommError(handle, &errors, Q_NULLPTR)) { q->setError(decodeSystemError()); return; } diff --git a/src/serialport/qserialport_wince.cpp b/src/serialport/qserialport_wince.cpp index 754a574..b8affb6 100644 --- a/src/serialport/qserialport_wince.cpp +++ b/src/serialport/qserialport_wince.cpp @@ -196,7 +196,7 @@ bool QSerialPortPrivate::open(QIODevice::OpenMode mode) } handle = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation.utf16()), - desiredAccess, 0, NULL, OPEN_EXISTING, 0, NULL); + desiredAccess, 0, Q_NULLPTR, OPEN_EXISTING, 0, Q_NULLPTR); if (handle == INVALID_HANDLE_VALUE) { q->setError(decodeSystemError()); @@ -214,7 +214,7 @@ void QSerialPortPrivate::close() { if (eventNotifier) { eventNotifier->deleteLater(); - eventNotifier = 0; + eventNotifier = Q_NULLPTR; } if (settingsRestoredOnClose) { @@ -249,9 +249,9 @@ QSerialPort::PinoutSignals QSerialPortPrivate::pinoutSignals() ret |= QSerialPort::DataCarrierDetectSignal; DWORD bytesReturned = 0; - if (!::DeviceIoControl(handle, IOCTL_SERIAL_GET_DTRRTS, NULL, 0, + if (!::DeviceIoControl(handle, IOCTL_SERIAL_GET_DTRRTS, Q_NULLPTR, 0, &modemStat, sizeof(modemStat), - &bytesReturned, NULL)) { + &bytesReturned, Q_NULLPTR)) { q->setError(decodeSystemError()); return ret; } @@ -345,11 +345,9 @@ bool QSerialPortPrivate::waitForReadyRead(int msec) forever { bool readyToRead = false; bool readyToWrite = false; - bool timedOut = false; if (!waitForReadOrWrite(&readyToRead, &readyToWrite, true, !writeBuffer.isEmpty(), - timeoutValue(msec, stopWatch.elapsed()), - &timedOut)) { + timeoutValue(msec, stopWatch.elapsed()))) { return false; } if (readyToRead) { @@ -373,11 +371,9 @@ bool QSerialPortPrivate::waitForBytesWritten(int msec) forever { bool readyToRead = false; bool readyToWrite = false; - bool timedOut = false; if (!waitForReadOrWrite(&readyToRead, &readyToWrite, true, !writeBuffer.isEmpty(), - timeoutValue(msec, stopWatch.elapsed()), - &timedOut)) { + timeoutValue(msec, stopWatch.elapsed()))) { return false; } if (readyToRead) { @@ -509,7 +505,7 @@ bool QSerialPortPrivate::notifyRead() char *ptr = buffer.reserve(bytesToRead); DWORD readBytes = 0; - BOOL sucessResult = ::ReadFile(handle, ptr, bytesToRead, &readBytes, NULL); + BOOL sucessResult = ::ReadFile(handle, ptr, bytesToRead, &readBytes, Q_NULLPTR); if (!sucessResult) { buffer.chop(bytesToRead); @@ -555,7 +551,7 @@ bool QSerialPortPrivate::notifyWrite() const char *ptr = writeBuffer.readPointer(); DWORD bytesWritten = 0; - if (!::WriteFile(handle, ptr, nextSize, &bytesWritten, NULL)) { + if (!::WriteFile(handle, ptr, nextSize, &bytesWritten, Q_NULLPTR)) { q->setError(QSerialPort::WriteError); return false; } @@ -591,7 +587,7 @@ void QSerialPortPrivate::processIoErrors(bool error) } DWORD errors = 0; - if (!::ClearCommError(handle, &errors, NULL)) { + if (!::ClearCommError(handle, &errors, Q_NULLPTR)) { q->setError(decodeSystemError()); return; } @@ -727,7 +723,7 @@ QSerialPort::SerialPortError QSerialPortPrivate::decodeSystemError(int systemErr bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectForWrite, bool checkRead, bool checkWrite, - int msecs, bool *timedOut) + int msecs) { Q_Q(QSerialPort); @@ -736,15 +732,12 @@ bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectFor // breaker can work out before you call a method WaitCommEvent() // and so it will loop forever! WaitCommEventBreaker breaker(handle, qMax(msecs, 0)); - ::WaitCommEvent(handle, &eventMask, NULL); + ::WaitCommEvent(handle, &eventMask, Q_NULLPTR); breaker.stop(); if (breaker.isWorked()) { - *timedOut = true; q->setError(QSerialPort::TimeoutError); - } - - if (!breaker.isWorked()) { + } else { if (checkRead) { Q_ASSERT(selectForRead); *selectForRead = eventMask & EV_RXCHAR; diff --git a/src/serialport/qserialportinfo.cpp b/src/serialport/qserialportinfo.cpp index 96b76c4..be3eed1 100644 --- a/src/serialport/qserialportinfo.cpp +++ b/src/serialport/qserialportinfo.cpp @@ -72,7 +72,7 @@ QSerialPortInfo::QSerialPortInfo() Constructs a copy of \a other. */ QSerialPortInfo::QSerialPortInfo(const QSerialPortInfo &other) - : d_ptr(other.d_ptr ? new QSerialPortInfoPrivate(*other.d_ptr) : 0) + : d_ptr(other.d_ptr ? new QSerialPortInfoPrivate(*other.d_ptr) : Q_NULLPTR) { } diff --git a/src/serialport/qserialportinfo.h b/src/serialport/qserialportinfo.h index de49e15..9f0352b 100644 --- a/src/serialport/qserialportinfo.h +++ b/src/serialport/qserialportinfo.h @@ -82,9 +82,9 @@ public: private: QSerialPortInfo(const QSerialPortInfoPrivate &dd); - friend QList<QSerialPortInfo> availablePortsByUdev(); - friend QList<QSerialPortInfo> availablePortsBySysfs(); - friend QList<QSerialPortInfo> availablePortsByFiltersOfDevices(); + friend QList<QSerialPortInfo> availablePortsByUdev(bool &ok); + friend QList<QSerialPortInfo> availablePortsBySysfs(bool &ok); + friend QList<QSerialPortInfo> availablePortsByFiltersOfDevices(bool &ok); QScopedPointer<QSerialPortInfoPrivate, QSerialPortInfoPrivateDeleter> d_ptr; }; diff --git a/src/serialport/qserialportinfo_unix.cpp b/src/serialport/qserialportinfo_unix.cpp index 12d7966..83d832b 100644 --- a/src/serialport/qserialportinfo_unix.cpp +++ b/src/serialport/qserialportinfo_unix.cpp @@ -42,6 +42,7 @@ #include <QtCore/qdir.h> #include <QtCore/qscopedpointer.h> +#include <private/qcore_unix_p.h> #include <errno.h> #include <sys/types.h> // kill @@ -93,7 +94,7 @@ static QStringList filteredDeviceFilePaths() return result; } -QList<QSerialPortInfo> availablePortsByFiltersOfDevices() +QList<QSerialPortInfo> availablePortsByFiltersOfDevices(bool &ok) { QList<QSerialPortInfo> serialPortInfoList; @@ -104,15 +105,122 @@ QList<QSerialPortInfo> availablePortsByFiltersOfDevices() serialPortInfoList.append(priv); } + ok = true; return serialPortInfoList; } -QList<QSerialPortInfo> availablePortsBySysfs() +static bool isSerial8250Driver(const QString &driverName) +{ + return (driverName == QStringLiteral("serial8250")); +} + +static bool isValidSerial8250(const QString &systemLocation) +{ +#ifdef Q_OS_LINUX + const mode_t flags = O_RDWR | O_NONBLOCK | O_NOCTTY; + const int fd = qt_safe_open(systemLocation.toLocal8Bit().constData(), flags); + if (fd != -1) { + struct serial_struct serinfo; + const int retval = ::ioctl(fd, TIOCGSERIAL, &serinfo); + qt_safe_close(fd); + if (retval != -1 && serinfo.type != PORT_UNKNOWN) + return true; + } +#else + Q_UNUSED(systemLocation); +#endif + return false; +} + +static bool isRfcommDevice(const QString &portName) +{ + if (!portName.startsWith(QStringLiteral("rfcomm"))) + return false; + + bool ok; + const int portNumber = portName.mid(6).toInt(&ok); + if (!ok || (portNumber < 0) || (portNumber > 255)) + return false; + return true; +} + +static QString ueventProperty(const QDir &targetDir, const QByteArray &pattern) +{ + QFile f(QFileInfo(targetDir, QStringLiteral("uevent")).absoluteFilePath()); + if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) + return QString(); + + const QByteArray content = f.readAll(); + + const int firstbound = content.indexOf(pattern); + if (firstbound == -1) + return QString(); + + const int lastbound = content.indexOf('\n', firstbound); + return QString::fromLatin1( + content.mid(firstbound + pattern.size(), + lastbound - firstbound - pattern.size())) + .simplified(); +} + +static QString deviceName(const QDir &targetDir) +{ + return ueventProperty(targetDir, "DEVNAME="); +} + +static QString deviceDriver(const QDir &targetDir) +{ + const QDir deviceDir(targetDir.absolutePath() + "/device"); + return ueventProperty(deviceDir, "DRIVER="); +} + +static QString deviceProperty(const QString &targetFilePath) +{ + QFile f(targetFilePath); + if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) + return QString(); + return QString::fromLatin1(f.readAll()).simplified(); +} + +static QString deviceDescription(const QDir &targetDir) +{ + return deviceProperty(QFileInfo(targetDir, QStringLiteral("product")).absoluteFilePath()); +} + +static QString deviceManufacturer(const QDir &targetDir) +{ + return deviceProperty(QFileInfo(targetDir, QStringLiteral("manufacturer")).absoluteFilePath()); +} + +static quint16 deviceProductIdentifier(const QDir &targetDir, bool &hasIdentifier) +{ + QString result = deviceProperty(QFileInfo(targetDir, QStringLiteral("idProduct")).absoluteFilePath()); + if (result.isEmpty()) + result = deviceProperty(QFileInfo(targetDir, QStringLiteral("device")).absoluteFilePath()); + return result.toInt(&hasIdentifier, 16); +} + +static quint16 deviceVendorIdentifier(const QDir &targetDir, bool &hasIdentifier) +{ + QString result = deviceProperty(QFileInfo(targetDir, QStringLiteral("idVendor")).absoluteFilePath()); + if (result.isEmpty()) + result = deviceProperty(QFileInfo(targetDir, QStringLiteral("vendor")).absoluteFilePath()); + return result.toInt(&hasIdentifier, 16); +} + +static QString deviceSerialNumber(const QDir &targetDir) +{ + return deviceProperty(QFileInfo(targetDir, QStringLiteral("serial")).absoluteFilePath()); +} + +QList<QSerialPortInfo> availablePortsBySysfs(bool &ok) { QDir ttySysClassDir(QStringLiteral("/sys/class/tty")); - if (!(ttySysClassDir.exists() && ttySysClassDir.isReadable())) + if (!(ttySysClassDir.exists() && ttySysClassDir.isReadable())) { + ok = false; return QList<QSerialPortInfo>(); + } QList<QSerialPortInfo> serialPortInfoList; ttySysClassDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); @@ -120,92 +228,53 @@ QList<QSerialPortInfo> availablePortsBySysfs() if (!fileInfo.isSymLink()) continue; - const QString targetPath = fileInfo.symLinkTarget(); - const int lastIndexOfSlash = targetPath.lastIndexOf(QLatin1Char('/')); - if (lastIndexOfSlash == -1) - continue; + QDir targetDir(fileInfo.symLinkTarget()); QSerialPortInfoPrivate priv; - if (targetPath.contains(QStringLiteral("pnp"))) { - // TODO: Obtain more information -#ifndef Q_OS_ANDROID - } else if (targetPath.contains(QStringLiteral("platform"))) { -#else - } else if (targetPath.contains(QStringLiteral("platform")) && !targetPath.contains(QStringLiteral("ttyUSB")) ) { -#endif - continue; - } else if (targetPath.contains(QStringLiteral("usb"))) { - QDir targetDir(targetPath); - targetDir.setFilter(QDir::Files | QDir::Readable); - targetDir.setNameFilters(QStringList(QStringLiteral("uevent"))); - - do { - const QFileInfoList entryInfoList = targetDir.entryInfoList(); - if (entryInfoList.isEmpty()) - continue; - - QFile uevent(entryInfoList.first().absoluteFilePath()); - if (!uevent.open(QIODevice::ReadOnly | QIODevice::Text)) - continue; - - const QString ueventContent = QString::fromLatin1(uevent.readAll()); - - if (ueventContent.contains(QStringLiteral("DEVTYPE=usb_device")) - && ueventContent.contains(QStringLiteral("DRIVER=usb"))) { - - QFile description(QFileInfo(targetDir, QStringLiteral("product")).absoluteFilePath()); - if (description.open(QIODevice::ReadOnly | QIODevice::Text)) - priv.description = QString::fromLatin1(description.readAll()).simplified(); - - QFile manufacturer(QFileInfo(targetDir, QStringLiteral("manufacturer")).absoluteFilePath()); - if (manufacturer.open(QIODevice::ReadOnly | QIODevice::Text)) - priv.manufacturer = QString::fromLatin1(manufacturer.readAll()).simplified(); - - QFile serialNumber(QFileInfo(targetDir, QStringLiteral("serial")).absoluteFilePath()); - if (serialNumber.open(QIODevice::ReadOnly | QIODevice::Text)) - priv.serialNumber = QString::fromLatin1(serialNumber.readAll()).simplified(); - - QFile vendorIdentifier(QFileInfo(targetDir, QStringLiteral("idVendor")).absoluteFilePath()); - if (vendorIdentifier.open(QIODevice::ReadOnly | QIODevice::Text)) { - priv.vendorIdentifier = QString::fromLatin1(vendorIdentifier.readAll()) - .toInt(&priv.hasVendorIdentifier, 16); - } - - QFile productIdentifier(QFileInfo(targetDir, QStringLiteral("idProduct")).absoluteFilePath()); - if (productIdentifier.open(QIODevice::ReadOnly | QIODevice::Text)) { - priv.productIdentifier = QString::fromLatin1(productIdentifier.readAll()) - .toInt(&priv.hasProductIdentifier, 16); - } - - break; - } - } while (targetDir.cdUp()); - - } else if (targetPath.contains(QStringLiteral("pci"))) { - QDir targetDir(targetPath + QStringLiteral("/device")); - QFile vendorIdentifier(QFileInfo(targetDir, QStringLiteral("vendor")).absoluteFilePath()); - if (vendorIdentifier.open(QIODevice::ReadOnly | QIODevice::Text)) { - priv.vendorIdentifier = QString::fromLatin1(vendorIdentifier.readAll()) - .toInt(&priv.hasVendorIdentifier, 16); - } - QFile productIdentifier(QFileInfo(targetDir, QStringLiteral("device")).absoluteFilePath()); - if (productIdentifier.open(QIODevice::ReadOnly | QIODevice::Text)) { - priv.productIdentifier = QString::fromLatin1(productIdentifier.readAll()) - .toInt(&priv.hasProductIdentifier, 16); - } - // TODO: Obtain more information about the device - } else if (targetPath.contains(QStringLiteral(".serial/tty/tty"))) { - // This condition matches onboard serial port on embedded devices. - // Keep those devices in the list - } else { + + priv.portName = deviceName(targetDir); + if (priv.portName.isEmpty()) continue; + + const QString driverName = deviceDriver(targetDir); + if (driverName.isEmpty()) { + if (!isRfcommDevice(priv.portName)) + continue; } - priv.portName = targetPath.mid(lastIndexOfSlash + 1); priv.device = QSerialPortInfoPrivate::portNameToSystemLocation(priv.portName); + if (isSerial8250Driver(driverName) && !isValidSerial8250(priv.device)) + continue; + + do { + if (priv.description.isEmpty()) + priv.description = deviceDescription(targetDir); + + if (priv.manufacturer.isEmpty()) + priv.manufacturer = deviceManufacturer(targetDir); + + if (priv.serialNumber.isEmpty()) + priv.serialNumber = deviceSerialNumber(targetDir); + + if (!priv.hasVendorIdentifier) + priv.vendorIdentifier = deviceVendorIdentifier(targetDir, priv.hasVendorIdentifier); + + if (!priv.hasProductIdentifier) + priv.productIdentifier = deviceProductIdentifier(targetDir, priv.hasProductIdentifier); + + if (!priv.description.isEmpty() + || !priv.manufacturer.isEmpty() + || !priv.serialNumber.isEmpty() + || priv.hasVendorIdentifier + || priv.hasProductIdentifier) { + break; + } + } while (targetDir.cdUp()); + serialPortInfoList.append(priv); } + ok = true; return serialPortInfoList; } @@ -237,53 +306,55 @@ struct ScopedPointerUdevDeviceDeleter Q_GLOBAL_STATIC(QLibrary, udevLibrary) #endif -static -QString getUdevPropertyValue(struct ::udev_device *dev, const char *name) +static QString deviceProperty(struct ::udev_device *dev, const char *name) { return QString::fromLatin1(::udev_device_get_property_value(dev, name)); } -static -bool checkUdevForSerial8250Driver(struct ::udev_device *dev) +static QString deviceDriver(struct ::udev_device *dev) { - const QString driverName = QString::fromLatin1(::udev_device_get_driver(dev)); - return (driverName == QStringLiteral("serial8250")); + return QString::fromLatin1(::udev_device_get_driver(dev)); } -static -QString getUdevModelName(struct ::udev_device *dev) +static QString deviceDescription(struct ::udev_device *dev) { - return getUdevPropertyValue(dev, "ID_MODEL") - .replace(QLatin1Char('_'), QLatin1Char(' ')); + return deviceProperty(dev, "ID_MODEL").replace(QLatin1Char('_'), QLatin1Char(' ')); } -static -QString getUdevVendorName(struct ::udev_device *dev) +static QString deviceManufacturer(struct ::udev_device *dev) { - return getUdevPropertyValue(dev, "ID_VENDOR") - .replace(QLatin1Char('_'), QLatin1Char(' ')); + return deviceProperty(dev, "ID_VENDOR").replace(QLatin1Char('_'), QLatin1Char(' ')); } -static -quint16 getUdevModelIdentifier(struct ::udev_device *dev, bool &hasIdentifier) +static quint16 deviceProductIdentifier(struct ::udev_device *dev, bool &hasIdentifier) { - return getUdevPropertyValue(dev, "ID_MODEL_ID").toInt(&hasIdentifier, 16); + return deviceProperty(dev, "ID_MODEL_ID").toInt(&hasIdentifier, 16); } -static -quint16 getUdevVendorIdentifier(struct ::udev_device *dev, bool &hasIdentifier) +static quint16 deviceVendorIdentifier(struct ::udev_device *dev, bool &hasIdentifier) { - return getUdevPropertyValue(dev, "ID_VENDOR_ID").toInt(&hasIdentifier, 16); + return deviceProperty(dev, "ID_VENDOR_ID").toInt(&hasIdentifier, 16); } -static -QString getUdevSerialNumber(struct ::udev_device *dev) +static QString deviceSerialNumber(struct ::udev_device *dev) { - return getUdevPropertyValue(dev,"ID_SERIAL_SHORT"); + return deviceProperty(dev,"ID_SERIAL_SHORT"); } -QList<QSerialPortInfo> availablePortsByUdev() +static QString deviceName(struct ::udev_device *dev) { + return QString::fromLatin1(::udev_device_get_sysname(dev)); +} + +static QString deviceLocation(struct ::udev_device *dev) +{ + return QString::fromLatin1(::udev_device_get_devnode(dev)); +} + +QList<QSerialPortInfo> availablePortsByUdev(bool &ok) +{ + ok = false; + #ifndef LINK_LIBUDEV static bool symbolsResolved = resolveSymbols(udevLibrary()); if (!symbolsResolved) @@ -311,6 +382,8 @@ QList<QSerialPortInfo> availablePortsByUdev() udev_list_entry *dev_list_entry; udev_list_entry_foreach(dev_list_entry, devices) { + ok = true; + QScopedPointer<udev_device, ScopedPointerUdevDeviceDeleter> dev(::udev_device_new_from_syspath( udev.data(), ::udev_list_entry_get_name(dev_list_entry))); @@ -320,28 +393,23 @@ QList<QSerialPortInfo> availablePortsByUdev() QSerialPortInfoPrivate priv; - priv.device = QString::fromLatin1(::udev_device_get_devnode(dev.data())); - priv.portName = QString::fromLatin1(::udev_device_get_sysname(dev.data())); + priv.device = deviceLocation(dev.data()); + priv.portName = deviceName(dev.data()); udev_device *parentdev = ::udev_device_get_parent(dev.data()); if (parentdev) { - if (checkUdevForSerial8250Driver(parentdev)) + const QString driverName = deviceDriver(parentdev); + if (isSerial8250Driver(driverName) && !isValidSerial8250(priv.portName)) continue; - priv.description = getUdevModelName(dev.data()); - priv.manufacturer = getUdevVendorName(dev.data()); - priv.serialNumber = getUdevSerialNumber(dev.data()); - priv.vendorIdentifier = getUdevVendorIdentifier(dev.data(), priv.hasVendorIdentifier); - priv.productIdentifier = getUdevModelIdentifier(dev.data(), priv.hasProductIdentifier); + priv.description = deviceDescription(dev.data()); + priv.manufacturer = deviceManufacturer(dev.data()); + priv.serialNumber = deviceSerialNumber(dev.data()); + priv.vendorIdentifier = deviceVendorIdentifier(dev.data(), priv.hasVendorIdentifier); + priv.productIdentifier = deviceProductIdentifier(dev.data(), priv.hasProductIdentifier); } else { - if (priv.portName.startsWith(rfcommDeviceName)) { - bool ok; - int portNumber = priv.portName.mid(rfcommDeviceName.length()).toInt(&ok); - if (!ok || (portNumber < 0) || (portNumber > 255)) - continue; - } else { + if (!isRfcommDevice(priv.portName)) continue; - } } serialPortInfoList.append(priv); @@ -352,17 +420,17 @@ QList<QSerialPortInfo> availablePortsByUdev() QList<QSerialPortInfo> QSerialPortInfo::availablePorts() { - QList<QSerialPortInfo> serialPortInfoList = availablePortsByUdev(); + bool ok; + + QList<QSerialPortInfo> serialPortInfoList = availablePortsByUdev(ok); #ifdef Q_OS_LINUX - if (serialPortInfoList.isEmpty()) - serialPortInfoList = availablePortsBySysfs(); - else - return serialPortInfoList; + if (!ok) + serialPortInfoList = availablePortsBySysfs(ok); #endif - if (serialPortInfoList.isEmpty()) - serialPortInfoList = availablePortsByFiltersOfDevices(); + if (!ok) + serialPortInfoList = availablePortsByFiltersOfDevices(ok); return serialPortInfoList; } diff --git a/src/serialport/qserialportinfo_win.cpp b/src/serialport/qserialportinfo_win.cpp index 7aba45a..df0942f 100644 --- a/src/serialport/qserialportinfo_win.cpp +++ b/src/serialport/qserialportinfo_win.cpp @@ -74,7 +74,7 @@ static QString toStringAndTrimNullCharacter(const QByteArray &buffer) static QStringList portNamesFromHardwareDeviceMap() { - HKEY hKey = 0; + HKEY hKey = Q_NULLPTR; if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS) return QStringList(); @@ -88,7 +88,7 @@ static QStringList portNamesFromHardwareDeviceMap() forever { DWORD requiredValueNameChars = maximumValueNameInChars; const LONG ret = ::RegEnumValue(hKey, index, reinterpret_cast<wchar_t *>(outputValueName.data()), &requiredValueNameChars, - NULL, NULL, reinterpret_cast<unsigned char *>(outputBuffer.data()), &requiredDataBytes); + Q_NULLPTR, Q_NULLPTR, reinterpret_cast<unsigned char *>(outputBuffer.data()), &requiredDataBytes); if (ret == ERROR_MORE_DATA) { outputBuffer.resize(requiredDataBytes); } else if (ret == ERROR_SUCCESS) { @@ -172,7 +172,7 @@ static QString devicePortName(HDEVINFO deviceInfoSet, PSP_DEVINFO_DATA deviceInf DWORD dataType = 0; QByteArray outputBuffer; forever { - const LONG ret = ::RegQueryValueEx(key, reinterpret_cast<const wchar_t *>(portNameKey.utf16()), NULL, &dataType, + const LONG ret = ::RegQueryValueEx(key, reinterpret_cast<const wchar_t *>(portNameKey.utf16()), Q_NULLPTR, &dataType, reinterpret_cast<unsigned char *>(outputBuffer.data()), &bytesRequired); if (ret == ERROR_MORE_DATA) { outputBuffer.resize(bytesRequired); @@ -293,7 +293,7 @@ QList<QSerialPortInfo> QSerialPortInfo::availablePorts() QList<QSerialPortInfo> serialPortInfoList; foreach (const GuidFlagsPair &uniquePair, guidFlagsPairs()) { - const HDEVINFO deviceInfoSet = ::SetupDiGetClassDevs(reinterpret_cast<const GUID *>(&uniquePair.first), NULL, 0, uniquePair.second); + const HDEVINFO deviceInfoSet = ::SetupDiGetClassDevs(reinterpret_cast<const GUID *>(&uniquePair.first), Q_NULLPTR, Q_NULLPTR, uniquePair.second); if (deviceInfoSet == INVALID_HANDLE_VALUE) return serialPortInfoList; @@ -354,7 +354,7 @@ QList<qint32> QSerialPortInfo::standardBaudRates() bool QSerialPortInfo::isBusy() const { const HANDLE handle = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation().utf16()), - GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, Q_NULLPTR); if (handle == INVALID_HANDLE_VALUE) { if (::GetLastError() == ERROR_ACCESS_DENIED) @@ -368,7 +368,7 @@ bool QSerialPortInfo::isBusy() const bool QSerialPortInfo::isValid() const { const HANDLE handle = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation().utf16()), - GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, Q_NULLPTR); if (handle == INVALID_HANDLE_VALUE) { if (::GetLastError() != ERROR_ACCESS_DENIED) diff --git a/src/serialport/qserialportinfo_wince.cpp b/src/serialport/qserialportinfo_wince.cpp index 2b247b9..aa590ba 100644 --- a/src/serialport/qserialportinfo_wince.cpp +++ b/src/serialport/qserialportinfo_wince.cpp @@ -46,7 +46,7 @@ static QString findDescription(HKEY parentKeyHandle, const QString &subKey) const static QString valueName(QStringLiteral("FriendlyName")); QString result; - HKEY hSubKey = 0; + HKEY hSubKey = Q_NULLPTR; LONG res = ::RegOpenKeyEx(parentKeyHandle, reinterpret_cast<const wchar_t *>(subKey.utf16()), 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &hSubKey); @@ -55,12 +55,12 @@ static QString findDescription(HKEY parentKeyHandle, const QString &subKey) DWORD dataType = 0; DWORD dataSize = 0; res = ::RegQueryValueEx(hSubKey, reinterpret_cast<const wchar_t *>(valueName.utf16()), - NULL, &dataType, NULL, &dataSize); + Q_NULLPTR, &dataType, Q_NULLPTR, &dataSize); if (res == ERROR_SUCCESS) { QByteArray data(dataSize, 0); res = ::RegQueryValueEx(hSubKey, reinterpret_cast<const wchar_t *>(valueName.utf16()), - NULL, NULL, + Q_NULLPTR, Q_NULLPTR, reinterpret_cast<unsigned char *>(data.data()), &dataSize); @@ -81,7 +81,7 @@ static QString findDescription(HKEY parentKeyHandle, const QString &subKey) QByteArray data(dataSize, 0); while (::RegEnumKeyEx(hSubKey, index++, reinterpret_cast<wchar_t *>(data.data()), &dataSize, - NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { + Q_NULLPTR, Q_NULLPTR, Q_NULLPTR, Q_NULLPTR) == ERROR_SUCCESS) { result = findDescription(hSubKey, QString::fromUtf16(reinterpret_cast<ushort *>(data.data()), dataSize)); @@ -128,7 +128,7 @@ QList<qint32> QSerialPortInfo::standardBaudRates() bool QSerialPortInfo::isBusy() const { const HANDLE handle = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation().utf16()), - GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + GENERIC_READ | GENERIC_WRITE, 0, Q_NULLPTR, OPEN_EXISTING, 0, Q_NULLPTR); if (handle == INVALID_HANDLE_VALUE) { if (::GetLastError() == ERROR_ACCESS_DENIED) @@ -142,7 +142,7 @@ bool QSerialPortInfo::isBusy() const bool QSerialPortInfo::isValid() const { const HANDLE handle = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation().utf16()), - GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + GENERIC_READ | GENERIC_WRITE, 0, Q_NULLPTR, OPEN_EXISTING, 0, Q_NULLPTR); if (handle == INVALID_HANDLE_VALUE) { if (::GetLastError() != ERROR_ACCESS_DENIED) |