diff options
28 files changed, 762 insertions, 439 deletions
diff --git a/.qmake.conf b/.qmake.conf index e28797d..42a8dd9 100644 --- a/.qmake.conf +++ b/.qmake.conf @@ -1,3 +1,3 @@ load(qt_build_config) -MODULE_VERSION = 5.4.0 +MODULE_VERSION = 5.4.1 diff --git a/examples/serialport/enumerator/main.cpp b/examples/serialport/enumerator/main.cpp index 007e918..40bc67a 100644 --- a/examples/serialport/enumerator/main.cpp +++ b/examples/serialport/enumerator/main.cpp @@ -36,6 +36,7 @@ #include <QWidget> #include <QVBoxLayout> #include <QLabel> +#include <QScrollArea> #include <QtSerialPort/QSerialPortInfo> QT_USE_NAMESPACE @@ -44,8 +45,6 @@ int main(int argc, char *argv[]) { QApplication a(argc, argv); - QWidget w; - w.setWindowTitle(QObject::tr("Info about all available serial ports.")); QVBoxLayout *layout = new QVBoxLayout; foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { @@ -62,8 +61,13 @@ int main(int argc, char *argv[]) layout->addWidget(label); } - w.setLayout(layout); - w.show(); + QWidget *workPage = new QWidget; + workPage->setLayout(layout); + + QScrollArea area; + area.setWindowTitle(QObject::tr("Info about all available serial ports.")); + area.setWidget(workPage); + area.show(); return a.exec(); } diff --git a/examples/serialport/terminal/mainwindow.cpp b/examples/serialport/terminal/mainwindow.cpp index f9967cc..2cb52a1 100644 --- a/examples/serialport/terminal/mainwindow.cpp +++ b/examples/serialport/terminal/mainwindow.cpp @@ -109,7 +109,8 @@ void MainWindow::openSerialPort() //! [5] void MainWindow::closeSerialPort() { - serial->close(); + if (serial->isOpen()) + serial->close(); console->setEnabled(false); ui->actionConnect->setEnabled(true); ui->actionDisconnect->setEnabled(false); diff --git a/examples/serialport/terminal/settingsdialog.cpp b/examples/serialport/terminal/settingsdialog.cpp index 494cf89..7df3c35 100644 --- a/examples/serialport/terminal/settingsdialog.cpp +++ b/examples/serialport/terminal/settingsdialog.cpp @@ -41,6 +41,8 @@ QT_USE_NAMESPACE +static const char blankString[] = QT_TRANSLATE_NOOP("SettingsDialog", "N/A"); + SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SettingsDialog) @@ -57,6 +59,8 @@ SettingsDialog::SettingsDialog(QWidget *parent) : this, SLOT(showPortInfo(int))); connect(ui->baudRateBox, SIGNAL(currentIndexChanged(int)), this, SLOT(checkCustomBaudRatePolicy(int))); + connect(ui->serialPortInfoListBox, SIGNAL(currentIndexChanged(int)), + this, SLOT(checkCustomDevicePathPolicy(int))); fillPortsParameters(); fillPortsInfo(); @@ -76,15 +80,16 @@ SettingsDialog::Settings SettingsDialog::settings() const void SettingsDialog::showPortInfo(int idx) { - if (idx != -1) { - QStringList list = ui->serialPortInfoListBox->itemData(idx).toStringList(); - ui->descriptionLabel->setText(tr("Description: %1").arg(list.at(1))); - ui->manufacturerLabel->setText(tr("Manufacturer: %1").arg(list.at(2))); - ui->serialNumberLabel->setText(tr("Serial number: %1").arg(list.at(3))); - ui->locationLabel->setText(tr("Location: %1").arg(list.at(4))); - ui->vidLabel->setText(tr("Vendor Identifier: %1").arg(list.at(5))); - ui->pidLabel->setText(tr("Product Identifier: %1").arg(list.at(6))); - } + if (idx == -1) + return; + + QStringList list = ui->serialPortInfoListBox->itemData(idx).toStringList(); + ui->descriptionLabel->setText(tr("Description: %1").arg(list.count() > 1 ? list.at(1) : tr(blankString))); + ui->manufacturerLabel->setText(tr("Manufacturer: %1").arg(list.count() > 2 ? list.at(2) : tr(blankString))); + ui->serialNumberLabel->setText(tr("Serial number: %1").arg(list.count() > 3 ? list.at(3) : tr(blankString))); + ui->locationLabel->setText(tr("Location: %1").arg(list.count() > 4 ? list.at(4) : tr(blankString))); + ui->vidLabel->setText(tr("Vendor Identifier: %1").arg(list.count() > 5 ? list.at(5) : tr(blankString))); + ui->pidLabel->setText(tr("Product Identifier: %1").arg(list.count() > 6 ? list.at(6) : tr(blankString))); } void SettingsDialog::apply() @@ -104,13 +109,21 @@ void SettingsDialog::checkCustomBaudRatePolicy(int idx) } } +void SettingsDialog::checkCustomDevicePathPolicy(int idx) +{ + bool isCustomPath = !ui->serialPortInfoListBox->itemData(idx).isValid(); + ui->serialPortInfoListBox->setEditable(isCustomPath); + if (isCustomPath) + ui->serialPortInfoListBox->clearEditText(); +} + void SettingsDialog::fillPortsParameters() { ui->baudRateBox->addItem(QStringLiteral("9600"), QSerialPort::Baud9600); ui->baudRateBox->addItem(QStringLiteral("19200"), QSerialPort::Baud19200); ui->baudRateBox->addItem(QStringLiteral("38400"), QSerialPort::Baud38400); ui->baudRateBox->addItem(QStringLiteral("115200"), QSerialPort::Baud115200); - ui->baudRateBox->addItem(QStringLiteral("Custom")); + ui->baudRateBox->addItem(tr("Custom")); ui->dataBitsBox->addItem(QStringLiteral("5"), QSerialPort::Data5); ui->dataBitsBox->addItem(QStringLiteral("6"), QSerialPort::Data6); @@ -118,27 +131,26 @@ void SettingsDialog::fillPortsParameters() ui->dataBitsBox->addItem(QStringLiteral("8"), QSerialPort::Data8); ui->dataBitsBox->setCurrentIndex(3); - ui->parityBox->addItem(QStringLiteral("None"), QSerialPort::NoParity); - ui->parityBox->addItem(QStringLiteral("Even"), QSerialPort::EvenParity); - ui->parityBox->addItem(QStringLiteral("Odd"), QSerialPort::OddParity); - ui->parityBox->addItem(QStringLiteral("Mark"), QSerialPort::MarkParity); - ui->parityBox->addItem(QStringLiteral("Space"), QSerialPort::SpaceParity); + ui->parityBox->addItem(tr("None"), QSerialPort::NoParity); + ui->parityBox->addItem(tr("Even"), QSerialPort::EvenParity); + ui->parityBox->addItem(tr("Odd"), QSerialPort::OddParity); + ui->parityBox->addItem(tr("Mark"), QSerialPort::MarkParity); + ui->parityBox->addItem(tr("Space"), QSerialPort::SpaceParity); ui->stopBitsBox->addItem(QStringLiteral("1"), QSerialPort::OneStop); #ifdef Q_OS_WIN - ui->stopBitsBox->addItem(QStringLiteral("1.5"), QSerialPort::OneAndHalfStop); + ui->stopBitsBox->addItem(tr("1.5"), QSerialPort::OneAndHalfStop); #endif ui->stopBitsBox->addItem(QStringLiteral("2"), QSerialPort::TwoStop); - ui->flowControlBox->addItem(QStringLiteral("None"), QSerialPort::NoFlowControl); - ui->flowControlBox->addItem(QStringLiteral("RTS/CTS"), QSerialPort::HardwareControl); - ui->flowControlBox->addItem(QStringLiteral("XON/XOFF"), QSerialPort::SoftwareControl); + ui->flowControlBox->addItem(tr("None"), QSerialPort::NoFlowControl); + ui->flowControlBox->addItem(tr("RTS/CTS"), QSerialPort::HardwareControl); + ui->flowControlBox->addItem(tr("XON/XOFF"), QSerialPort::SoftwareControl); } void SettingsDialog::fillPortsInfo() { ui->serialPortInfoListBox->clear(); - static const QString blankString = QObject::tr("N/A"); QString description; QString manufacturer; QString serialNumber; @@ -157,6 +169,8 @@ void SettingsDialog::fillPortsInfo() ui->serialPortInfoListBox->addItem(list.first(), list); } + + ui->serialPortInfoListBox->addItem(tr("Custom")); } void SettingsDialog::updateSettings() diff --git a/examples/serialport/terminal/settingsdialog.h b/examples/serialport/terminal/settingsdialog.h index 774ea67..d6c9d5e 100644 --- a/examples/serialport/terminal/settingsdialog.h +++ b/examples/serialport/terminal/settingsdialog.h @@ -79,6 +79,7 @@ private slots: void showPortInfo(int idx); void apply(); void checkCustomBaudRatePolicy(int idx); + void checkCustomDevicePathPolicy(int idx); private: void fillPortsParameters(); diff --git a/src/serialport/qserialport.cpp b/src/serialport/qserialport.cpp index 82bcde3..0e60036 100644 --- a/src/serialport/qserialport.cpp +++ b/src/serialport/qserialport.cpp @@ -36,6 +36,7 @@ #include "qserialport.h" #include "qserialportinfo.h" +#include "qserialportinfo_p.h" #ifdef Q_OS_WINCE #include "qserialport_wince_p.h" @@ -69,8 +70,6 @@ QSerialPortPrivateData::QSerialPortPrivateData(QSerialPort *q) , stopBits(QSerialPort::OneStop) , flowControl(QSerialPort::NoFlowControl) , policy(QSerialPort::IgnorePolicy) - , dataTerminalReady(false) - , requestToSend(false) #if QT_DEPRECATED_SINCE(5,3) , settingsRestoredOnClose(true) #endif @@ -435,7 +434,7 @@ QSerialPort::~QSerialPort() void QSerialPort::setPortName(const QString &name) { Q_D(QSerialPort); - d->systemLocation = QSerialPortPrivate::portNameToSystemLocation(name); + d->systemLocation = QSerialPortInfoPrivate::portNameToSystemLocation(name); } /*! @@ -446,7 +445,7 @@ void QSerialPort::setPortName(const QString &name) void QSerialPort::setPort(const QSerialPortInfo &serialPortInfo) { Q_D(QSerialPort); - d->systemLocation = QSerialPortPrivate::portNameToSystemLocation(serialPortInfo.systemLocation()); + d->systemLocation = serialPortInfo.systemLocation(); } /*! @@ -460,7 +459,7 @@ void QSerialPort::setPort(const QSerialPortInfo &serialPortInfo) \li Brief Description \row \li Windows - \li Removes the prefix "\\\\.\\" from the system location + \li Removes the prefix "\\\\.\\" or "//./" from the system location and returns the remainder of the string. \row \li Windows CE @@ -471,16 +470,9 @@ void QSerialPort::setPort(const QSerialPortInfo &serialPortInfo) \li Returns the system location as it is, as it is equivalent to the port name. \row - \li GNU/Linux + \li Unix, BSD \li Removes the prefix "/dev/" from the system location and returns the remainder of the string. - \row - \li Mac OSX - \li Removes the prefix "/dev/cu." and "/dev/tty." from the - system location and returns the remainder of the string. - \row - \li Other *nix - \li The same as for GNU/Linux. \endtable \sa setPort(), QSerialPortInfo::portName() @@ -488,7 +480,7 @@ void QSerialPort::setPort(const QSerialPortInfo &serialPortInfo) QString QSerialPort::portName() const { Q_D(const QSerialPort); - return QSerialPortPrivate::portNameFromSystemLocation(d->systemLocation); + return QSerialPortInfoPrivate::portNameFromSystemLocation(d->systemLocation); } /*! @@ -527,20 +519,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; } @@ -871,11 +859,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; } @@ -919,11 +906,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.h b/src/serialport/qserialport.h index a8f9a05..fa681ad 100644 --- a/src/serialport/qserialport.h +++ b/src/serialport/qserialport.h @@ -273,7 +273,7 @@ private: Q_DISABLE_COPY(QSerialPort) -#if defined (Q_OS_WIN32) || defined(Q_OS_WIN64) +#if defined (Q_OS_WIN32) Q_PRIVATE_SLOT(d_func(), bool _q_completeAsyncCommunication()) Q_PRIVATE_SLOT(d_func(), bool _q_completeAsyncRead()) Q_PRIVATE_SLOT(d_func(), bool _q_completeAsyncWrite()) diff --git a/src/serialport/qserialport_p.h b/src/serialport/qserialport_p.h index 6f39260..578d8a9 100644 --- a/src/serialport/qserialport_p.h +++ b/src/serialport/qserialport_p.h @@ -75,8 +75,6 @@ public: QSerialPort::StopBits stopBits; QSerialPort::FlowControl flowControl; QSerialPort::DataErrorPolicy policy; - bool dataTerminalReady; - bool requestToSend; bool settingsRestoredOnClose; QSerialPort * const q_ptr; }; diff --git a/src/serialport/qserialport_unix.cpp b/src/serialport/qserialport_unix.cpp index eb71e86..648b6fc 100644 --- a/src/serialport/qserialport_unix.cpp +++ b/src/serialport/qserialport_unix.cpp @@ -34,6 +34,7 @@ ****************************************************************************/ #include "qserialport_unix_p.h" +#include "qserialportinfo_p.h" #include <errno.h> #include <sys/time.h> @@ -147,8 +148,8 @@ private: QSerialPortPrivate::QSerialPortPrivate(QSerialPort *q) : QSerialPortPrivateData(q) , descriptor(-1) - , readNotifier(0) - , writeNotifier(0) + , readNotifier(Q_NULLPTR) + , writeNotifier(Q_NULLPTR) , readPortNotifierCalled(false) , readPortNotifierState(false) , readPortNotifierStateSet(false) @@ -163,7 +164,7 @@ bool QSerialPortPrivate::open(QIODevice::OpenMode mode) { Q_Q(QSerialPort); - QString lockFilePath = serialPortLockFilePath(portNameFromSystemLocation(systemLocation)); + QString lockFilePath = serialPortLockFilePath(QSerialPortInfoPrivate::portNameFromSystemLocation(systemLocation)); bool isLockFileEmpty = lockFilePath.isEmpty(); if (isLockFileEmpty) { qWarning("Failed to create a lock file for opening the device"); @@ -226,19 +227,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; @@ -379,20 +380,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; } @@ -407,23 +402,17 @@ bool QSerialPortPrivate::waitForReadyRead(int msecs) bool QSerialPortPrivate::waitForBytesWritten(int msecs) { - Q_Q(QSerialPort); - if (writeBuffer.isEmpty() && pendingBytesWritten <= 0) return false; QElapsedTimer stopWatch; - stopWatch.start(); 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; } @@ -578,6 +567,7 @@ bool QSerialPortPrivate::setBaudRate(qint32 baudRate, QSerialPort::Directions di if (error == QSerialPort::NoError) return updateTermios(); + q->setError(error); return false; } @@ -930,6 +920,26 @@ QSerialPort::SerialPortError QSerialPortPrivate::decodeSystemError() const 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; @@ -973,13 +983,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); @@ -995,19 +1004,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) @@ -1158,38 +1167,6 @@ qint64 QSerialPortPrivate::readPerChar(char *data, qint64 maxSize) return ret; } -#ifdef Q_OS_MAC -static const QString defaultFilePathPrefix = QStringLiteral("/dev/cu."); -static const QString unusedFilePathPrefix = QStringLiteral("/dev/tty."); -#else -static const QString defaultFilePathPrefix = QStringLiteral("/dev/"); -#endif - -QString QSerialPortPrivate::portNameToSystemLocation(const QString &port) -{ - QString ret = port; - -#ifdef Q_OS_MAC - ret.remove(unusedFilePathPrefix); -#endif - - if (!ret.contains(defaultFilePathPrefix)) - ret.prepend(defaultFilePathPrefix); - return ret; -} - -QString QSerialPortPrivate::portNameFromSystemLocation(const QString &location) -{ - QString ret = location; - -#ifdef Q_OS_MAC - ret.remove(unusedFilePathPrefix); -#endif - - ret.remove(defaultFilePathPrefix); - return ret; -} - typedef QMap<qint32, qint32> BaudRateMap; // The OS specific defines can be found in termios.h diff --git a/src/serialport/qserialport_unix_p.h b/src/serialport/qserialport_unix_p.h index 1cc767d..5ec6653 100644 --- a/src/serialport/qserialport_unix_p.h +++ b/src/serialport/qserialport_unix_p.h @@ -82,6 +82,7 @@ struct serial_struct { }; #define ASYNC_SPD_CUST 0x0030 #define ASYNC_SPD_MASK 0x1030 +#define PORT_UNKNOWN 0 #endif QT_BEGIN_NAMESPACE @@ -131,9 +132,6 @@ public: qint64 bytesToWrite() const; qint64 writeData(const char *data, qint64 maxSize); - static QString portNameToSystemLocation(const QString &port); - static QString portNameFromSystemLocation(const QString &location); - static qint32 baudRateFromSetting(qint32 setting); static qint32 settingFromBaudRate(qint32 baudRate); @@ -177,7 +175,7 @@ private: 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_win.cpp b/src/serialport/qserialport_win.cpp index 64ca00e..0e9f187 100644 --- a/src/serialport/qserialport_win.cpp +++ b/src/serialport/qserialport_win.cpp @@ -94,13 +94,13 @@ QSerialPortPrivate::QSerialPortPrivate(QSerialPort *q) , communicationNotifier(new QWinEventNotifier(q)) , readCompletionNotifier(new QWinEventNotifier(q)) , writeCompletionNotifier(new QWinEventNotifier(q)) - , startAsyncWriteTimer(0) + , startAsyncWriteTimer(Q_NULLPTR) , originalEventMask(0) , triggeredEventMask(0) , actualBytesToWrite(0) { ::ZeroMemory(&communicationOverlapped, sizeof(communicationOverlapped)); - communicationOverlapped.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + communicationOverlapped.hEvent = ::CreateEvent(Q_NULLPTR, FALSE, FALSE, Q_NULLPTR); if (!communicationOverlapped.hEvent) q->setError(decodeSystemError()); else { @@ -109,7 +109,7 @@ QSerialPortPrivate::QSerialPortPrivate(QSerialPort *q) } ::ZeroMemory(&readCompletionOverlapped, sizeof(readCompletionOverlapped)); - readCompletionOverlapped.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + readCompletionOverlapped.hEvent = ::CreateEvent(Q_NULLPTR, FALSE, FALSE, Q_NULLPTR); if (!readCompletionOverlapped.hEvent) q->setError(decodeSystemError()); else { @@ -118,7 +118,7 @@ QSerialPortPrivate::QSerialPortPrivate(QSerialPort *q) } ::ZeroMemory(&writeCompletionOverlapped, sizeof(writeCompletionOverlapped)); - writeCompletionOverlapped.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + writeCompletionOverlapped.hEvent = ::CreateEvent(Q_NULLPTR, FALSE, FALSE, Q_NULLPTR); if (!writeCompletionOverlapped.hEvent) q->setError(decodeSystemError()); else { @@ -127,6 +127,16 @@ QSerialPortPrivate::QSerialPortPrivate(QSerialPort *q) } } +QSerialPortPrivate::~QSerialPortPrivate() +{ + if (communicationOverlapped.hEvent) + CloseHandle(communicationOverlapped.hEvent); + if (readCompletionOverlapped.hEvent) + CloseHandle(readCompletionOverlapped.hEvent); + if (writeCompletionOverlapped.hEvent) + CloseHandle(writeCompletionOverlapped.hEvent); +} + bool QSerialPortPrivate::open(QIODevice::OpenMode mode) { Q_Q(QSerialPort); @@ -142,7 +152,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()); @@ -213,9 +223,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; } @@ -328,27 +338,19 @@ qint64 QSerialPortPrivate::readData(char *data, qint64 maxSize) bool QSerialPortPrivate::waitForReadyRead(int msecs) { - Q_Q(QSerialPort); - - QElapsedTimer stopWatch; - stopWatch.start(); - if (!writeStarted && !_q_startAsyncWrite()) return false; const qint64 initialReadBufferSize = readBuffer.size(); qint64 currentReadBufferSize = initialReadBufferSize; - do { - bool timedOut = false; - HANDLE triggeredEvent = 0; + QElapsedTimer stopWatch; + stopWatch.start(); - if (!waitAnyEvent(timeoutValue(msecs, stopWatch.elapsed()), &timedOut, &triggeredEvent) || !triggeredEvent) { - // This is occur timeout or another error - if (!timedOut) - q->setError(decodeSystemError()); + do { + HANDLE triggeredEvent = Q_NULLPTR; + if (!waitAnyEvent(timeoutValue(msecs, stopWatch.elapsed()), &triggeredEvent) || !triggeredEvent) return false; - } if (triggeredEvent == communicationOverlapped.hEvent) { if (!_q_completeAsyncCommunication()) @@ -379,26 +381,19 @@ bool QSerialPortPrivate::waitForReadyRead(int msecs) bool QSerialPortPrivate::waitForBytesWritten(int msecs) { - Q_Q(QSerialPort); - if (writeBuffer.isEmpty()) return false; - QElapsedTimer stopWatch; - stopWatch.start(); - if (!writeStarted && !_q_startAsyncWrite()) return false; - forever { - bool timedOut = false; - HANDLE triggeredEvent = 0; + QElapsedTimer stopWatch; + stopWatch.start(); - if (!waitAnyEvent(timeoutValue(msecs, stopWatch.elapsed()), &timedOut, &triggeredEvent) || !triggeredEvent) { - if (!timedOut) - q->setError(decodeSystemError()); + forever { + HANDLE triggeredEvent = Q_NULLPTR; + if (!waitAnyEvent(timeoutValue(msecs, stopWatch.elapsed()), &triggeredEvent) || !triggeredEvent) return false; - } if (triggeredEvent == communicationOverlapped.hEvent) { if (!_q_completeAsyncCommunication()) @@ -518,7 +513,7 @@ bool QSerialPortPrivate::setDataErrorPolicy(QSerialPort::DataErrorPolicy policy) bool QSerialPortPrivate::_q_completeAsyncCommunication() { - if (handleOverlappedResult(0, communicationOverlapped) == qint64(-1)) + if (overlappedResult(communicationOverlapped) == qint64(-1)) return false; if (EV_ERR & triggeredEventMask) handleLineStatusErrors(); @@ -528,7 +523,7 @@ bool QSerialPortPrivate::_q_completeAsyncCommunication() bool QSerialPortPrivate::_q_completeAsyncRead() { - const qint64 bytesTransferred = handleOverlappedResult(QSerialPort::Input, readCompletionOverlapped); + const qint64 bytesTransferred = overlappedResult(readCompletionOverlapped); if (bytesTransferred == qint64(-1)) { readStarted = false; return false; @@ -553,7 +548,7 @@ bool QSerialPortPrivate::_q_completeAsyncWrite() Q_Q(QSerialPort); if (writeStarted) { - const qint64 bytesTransferred = handleOverlappedResult(QSerialPort::Output, writeCompletionOverlapped); + const qint64 bytesTransferred = overlappedResult(writeCompletionOverlapped); if (bytesTransferred == qint64(-1)) { writeStarted = false; return false; @@ -603,7 +598,7 @@ bool QSerialPortPrivate::startAsyncRead() } initializeOverlappedStructure(readCompletionOverlapped); - if (::ReadFile(handle, readChunkBuffer.data(), bytesToRead, NULL, &readCompletionOverlapped)) { + if (::ReadFile(handle, readChunkBuffer.data(), bytesToRead, Q_NULLPTR, &readCompletionOverlapped)) { readStarted = true; return true; } @@ -634,7 +629,7 @@ bool QSerialPortPrivate::_q_startAsyncWrite() const int writeBytes = writeBuffer.nextDataBlockSize(); if (!::WriteFile(handle, writeBuffer.readPointer(), writeBytes, - NULL, &writeCompletionOverlapped)) { + Q_NULLPTR, &writeCompletionOverlapped)) { QSerialPort::SerialPortError error = decodeSystemError(); if (error != QSerialPort::NoError) { @@ -714,7 +709,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; } @@ -809,7 +804,7 @@ bool QSerialPortPrivate::updateCommTimeouts() return true; } -qint64 QSerialPortPrivate::handleOverlappedResult(int direction, OVERLAPPED &overlapped) +qint64 QSerialPortPrivate::overlappedResult(OVERLAPPED &overlapped) { Q_Q(QSerialPort); @@ -819,9 +814,9 @@ qint64 QSerialPortPrivate::handleOverlappedResult(int direction, OVERLAPPED &ove if (error == QSerialPort::NoError) return qint64(0); if (error != QSerialPort::ResourceError) { - if (direction == QSerialPort::Input) + if (&overlapped == &readCompletionOverlapped) q->setError(QSerialPort::ReadError); - else if (direction == QSerialPort::Output) + else if (&overlapped == &writeCompletionOverlapped) q->setError(QSerialPort::WriteError); else q->setError(error); @@ -872,12 +867,10 @@ QSerialPort::SerialPortError QSerialPortPrivate::decodeSystemError() const return error; } -bool QSerialPortPrivate::waitAnyEvent(int msecs, bool *timedOut, HANDLE *triggeredEvent) +bool QSerialPortPrivate::waitAnyEvent(int msecs, HANDLE *triggeredEvent) { Q_Q(QSerialPort); - Q_ASSERT(timedOut); - QVector<HANDLE> handles = QVector<HANDLE>() << communicationOverlapped.hEvent << readCompletionOverlapped.hEvent @@ -888,36 +881,18 @@ bool QSerialPortPrivate::waitAnyEvent(int msecs, bool *timedOut, HANDLE *trigger FALSE, // wait any event msecs == -1 ? INFINITE : msecs); if (waitResult == WAIT_TIMEOUT) { - *timedOut = true; q->setError(QSerialPort::TimeoutError, qt_error_string(WAIT_TIMEOUT)); return false; } - - if (waitResult >= DWORD(WAIT_OBJECT_0 + handles.count())) + if (waitResult >= DWORD(WAIT_OBJECT_0 + handles.count())) { + q->setError(decodeSystemError()); return false; + } *triggeredEvent = handles.at(waitResult - WAIT_OBJECT_0); return true; } -static const QString defaultPathPrefix = QStringLiteral("\\\\.\\"); - -QString QSerialPortPrivate::portNameToSystemLocation(const QString &port) -{ - QString ret = port; - if (!ret.contains(defaultPathPrefix)) - ret.prepend(defaultPathPrefix); - return ret; -} - -QString QSerialPortPrivate::portNameFromSystemLocation(const QString &location) -{ - QString ret = location; - if (ret.contains(defaultPathPrefix)) - ret.remove(defaultPathPrefix); - return ret; -} - // This table contains standard values of baud rates that // are defined in MSDN and/or in Win SDK file winbase.h diff --git a/src/serialport/qserialport_win_p.h b/src/serialport/qserialport_win_p.h index 6b009fe..b4097ff 100644 --- a/src/serialport/qserialport_win_p.h +++ b/src/serialport/qserialport_win_p.h @@ -63,6 +63,7 @@ class QSerialPortPrivate : public QSerialPortPrivateData public: QSerialPortPrivate(QSerialPort *q); + ~QSerialPortPrivate(); bool open(QIODevice::OpenMode mode); void close(); @@ -108,9 +109,6 @@ public: qint64 bytesToWrite() const; qint64 writeData(const char *data, qint64 maxSize); - static QString portNameToSystemLocation(const QString &port); - static QString portNameFromSystemLocation(const QString &location); - static qint32 baudRateFromSetting(qint32 setting); static qint32 settingFromBaudRate(qint32 baudRate); @@ -141,9 +139,9 @@ private: bool initialize(QIODevice::OpenMode mode); bool updateDcb(); bool updateCommTimeouts(); - qint64 handleOverlappedResult(int direction, OVERLAPPED &overlapped); + qint64 overlappedResult(OVERLAPPED &overlapped); - bool waitAnyEvent(int msecs, bool *timedOut, HANDLE *triggeredEvent); + bool waitAnyEvent(int msecs, HANDLE *triggeredEvent); }; diff --git a/src/serialport/qserialport_wince.cpp b/src/serialport/qserialport_wince.cpp index a9c80b2..99cc603 100644 --- a/src/serialport/qserialport_wince.cpp +++ b/src/serialport/qserialport_wince.cpp @@ -183,7 +183,7 @@ QSerialPortPrivate::QSerialPortPrivate(QSerialPort *q) : QSerialPortPrivateData(q) , handle(INVALID_HANDLE_VALUE) , parityErrorOccurred(false) - , eventNotifier(0) + , eventNotifier(Q_NULLPTR) { } @@ -204,7 +204,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()); @@ -222,7 +222,7 @@ void QSerialPortPrivate::close() { if (eventNotifier) { eventNotifier->deleteLater(); - eventNotifier = 0; + eventNotifier = Q_NULLPTR; } if (settingsRestoredOnClose) { @@ -257,9 +257,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; } @@ -348,17 +348,14 @@ bool QSerialPortPrivate::waitForReadyRead(int msec) return true; QElapsedTimer stopWatch; - stopWatch.start(); 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) { @@ -377,17 +374,14 @@ bool QSerialPortPrivate::waitForBytesWritten(int msec) return false; QElapsedTimer stopWatch; - stopWatch.start(); 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) { @@ -519,7 +513,7 @@ bool QSerialPortPrivate::notifyRead() char *ptr = readBuffer.reserve(bytesToRead); DWORD readBytes = 0; - BOOL sucessResult = ::ReadFile(handle, ptr, bytesToRead, &readBytes, NULL); + BOOL sucessResult = ::ReadFile(handle, ptr, bytesToRead, &readBytes, Q_NULLPTR); if (!sucessResult) { readBuffer.truncate(bytesToRead); @@ -565,7 +559,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; } @@ -601,7 +595,7 @@ void QSerialPortPrivate::processIoErrors(bool error) } DWORD errors = 0; - if (!::ClearCommError(handle, &errors, NULL)) { + if (!::ClearCommError(handle, &errors, Q_NULLPTR)) { q->setError(decodeSystemError()); return; } @@ -735,7 +729,7 @@ QSerialPort::SerialPortError QSerialPortPrivate::decodeSystemError() const bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectForWrite, bool checkRead, bool checkWrite, - int msecs, bool *timedOut) + int msecs) { Q_Q(QSerialPort); @@ -744,15 +738,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; @@ -768,22 +759,6 @@ bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectFor return false; } -QString QSerialPortPrivate::portNameToSystemLocation(const QString &port) -{ - QString ret = port; - if (!ret.contains(QLatin1Char(':'))) - ret.append(QLatin1Char(':')); - return ret; -} - -QString QSerialPortPrivate::portNameFromSystemLocation(const QString &location) -{ - QString ret = location; - if (ret.contains(QLatin1Char(':'))) - ret.remove(QLatin1Char(':')); - return ret; -} - static const QList<qint32> standardBaudRatePairList() { diff --git a/src/serialport/qserialport_wince_p.h b/src/serialport/qserialport_wince_p.h index dedd4b1..57977f1 100644 --- a/src/serialport/qserialport_wince_p.h +++ b/src/serialport/qserialport_wince_p.h @@ -99,9 +99,6 @@ public: qint64 bytesToWrite() const; qint64 writeData(const char *data, qint64 maxSize); - static QString portNameToSystemLocation(const QString &port); - static QString portNameFromSystemLocation(const QString &location); - static qint32 baudRateFromSetting(qint32 setting); static qint32 settingFromBaudRate(qint32 baudRate); @@ -124,7 +121,7 @@ private: bool waitForReadOrWrite(bool *selectForRead, bool *selectForWrite, bool checkRead, bool checkWrite, - int msecs, bool *timedOut); + int msecs); }; diff --git a/src/serialport/qserialportinfo.cpp b/src/serialport/qserialportinfo.cpp index 23a4d1c..26b275d 100644 --- a/src/serialport/qserialportinfo.cpp +++ b/src/serialport/qserialportinfo.cpp @@ -65,7 +65,6 @@ QT_BEGIN_NAMESPACE \sa isNull() */ QSerialPortInfo::QSerialPortInfo() - : d_ptr(new QSerialPortInfoPrivate) { } @@ -73,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) { } @@ -81,7 +80,6 @@ QSerialPortInfo::QSerialPortInfo(const QSerialPortInfo &other) Constructs a QSerialPortInfo object from serial \a port. */ QSerialPortInfo::QSerialPortInfo(const QSerialPort &port) - : d_ptr(new QSerialPortInfoPrivate) { foreach (const QSerialPortInfo &serialPortInfo, availablePorts()) { if (port.portName() == serialPortInfo.portName()) { @@ -99,7 +97,6 @@ QSerialPortInfo::QSerialPortInfo(const QSerialPort &port) instance for that port. */ QSerialPortInfo::QSerialPortInfo(const QString &name) - : d_ptr(new QSerialPortInfoPrivate) { foreach (const QSerialPortInfo &serialPortInfo, availablePorts()) { if (name == serialPortInfo.portName()) { @@ -109,6 +106,11 @@ QSerialPortInfo::QSerialPortInfo(const QString &name) } } +QSerialPortInfo::QSerialPortInfo(const QSerialPortInfoPrivate &dd) + : d_ptr(new QSerialPortInfoPrivate(dd)) +{ +} + /*! Destroys the QSerialPortInfo object. References to the values in the object become invalid. diff --git a/src/serialport/qserialportinfo.h b/src/serialport/qserialportinfo.h index 262e54d..714708d 100644 --- a/src/serialport/qserialportinfo.h +++ b/src/serialport/qserialportinfo.h @@ -81,9 +81,10 @@ public: static QList<QSerialPortInfo> availablePorts(); private: - friend QList<QSerialPortInfo> availablePortsByUdev(); - friend QList<QSerialPortInfo> availablePortsBySysfs(); - friend QList<QSerialPortInfo> availablePortsByFiltersOfDevices(); + QSerialPortInfo(const QSerialPortInfoPrivate &dd); + 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_mac.cpp b/src/serialport/qserialportinfo_mac.cpp index d400d68..54abe21 100644 --- a/src/serialport/qserialportinfo_mac.cpp +++ b/src/serialport/qserialportinfo_mac.cpp @@ -78,15 +78,15 @@ static quint16 searchShortIntProperty(io_registry_entry_t ioRegistryEntry, return value; } -static bool isCompleteInfo(const QSerialPortInfo &portInfo) +static bool isCompleteInfo(const QSerialPortInfoPrivate &priv) { - return !portInfo.portName().isEmpty() - && !portInfo.systemLocation().isEmpty() - && !portInfo.manufacturer().isEmpty() - && !portInfo.description().isEmpty() - && !portInfo.serialNumber().isEmpty() - && portInfo.hasProductIdentifier() - && portInfo.hasVendorIdentifier(); + return !priv.portName.isEmpty() + && !priv.device.isEmpty() + && !priv.manufacturer.isEmpty() + && !priv.description.isEmpty() + && !priv.serialNumber.isEmpty() + && priv.hasProductIdentifier + && priv.hasVendorIdentifier; } static QString devicePortName(io_registry_entry_t ioRegistryEntry) @@ -160,37 +160,37 @@ QList<QSerialPortInfo> QSerialPortInfo::availablePorts() if (!serialPortService) break; - QSerialPortInfo serialPortInfo; + QSerialPortInfoPrivate priv; forever { - if (serialPortInfo.portName().isEmpty()) - serialPortInfo.d_ptr->portName = devicePortName(serialPortService); + if (priv.portName.isEmpty()) + priv.portName = devicePortName(serialPortService); - if (serialPortInfo.systemLocation().isEmpty()) - serialPortInfo.d_ptr->device = deviceSystemLocation(serialPortService); + if (priv.device.isEmpty()) + priv.device = deviceSystemLocation(serialPortService); - if (serialPortInfo.description().isEmpty()) - serialPortInfo.d_ptr->description = deviceDescription(serialPortService); + if (priv.description.isEmpty()) + priv.description = deviceDescription(serialPortService); - if (serialPortInfo.manufacturer().isEmpty()) - serialPortInfo.d_ptr->manufacturer = deviceManufacturer(serialPortService); + if (priv.manufacturer.isEmpty()) + priv.manufacturer = deviceManufacturer(serialPortService); - if (serialPortInfo.serialNumber().isEmpty()) - serialPortInfo.d_ptr->serialNumber = deviceSerialNumber(serialPortService); + if (priv.serialNumber.isEmpty()) + priv.serialNumber = deviceSerialNumber(serialPortService); - if (!serialPortInfo.hasVendorIdentifier()) { - serialPortInfo.d_ptr->vendorIdentifier = + if (!priv.hasVendorIdentifier) { + priv.vendorIdentifier = deviceVendorIdentifier(serialPortService, - serialPortInfo.d_ptr->hasVendorIdentifier); + priv.hasVendorIdentifier); } - if (!serialPortInfo.hasProductIdentifier()) { - serialPortInfo.d_ptr->productIdentifier = + if (!priv.hasProductIdentifier) { + priv.productIdentifier = deviceProductIdentifier(serialPortService, - serialPortInfo.d_ptr->hasProductIdentifier); + priv.hasProductIdentifier); } - if (isCompleteInfo(serialPortInfo)) { + if (isCompleteInfo(priv)) { ::IOObjectRelease(serialPortService); break; } @@ -200,7 +200,7 @@ QList<QSerialPortInfo> QSerialPortInfo::availablePorts() break; } - serialPortInfoList.append(serialPortInfo); + serialPortInfoList.append(priv); } ::IOObjectRelease(serialPortIterator); @@ -242,4 +242,18 @@ bool QSerialPortInfo::isValid() const return f.exists(); } +QString QSerialPortInfoPrivate::portNameToSystemLocation(const QString &source) +{ + return (source.startsWith(QLatin1Char('/')) + || source.startsWith(QStringLiteral("./")) + || source.startsWith(QStringLiteral("../"))) + ? source : (QStringLiteral("/dev/") + source); +} + +QString QSerialPortInfoPrivate::portNameFromSystemLocation(const QString &source) +{ + return source.startsWith(QStringLiteral("/dev/")) + ? source.mid(5) : source; +} + QT_END_NAMESPACE diff --git a/src/serialport/qserialportinfo_p.h b/src/serialport/qserialportinfo_p.h index 6ab4117..c9f1086 100644 --- a/src/serialport/qserialportinfo_p.h +++ b/src/serialport/qserialportinfo_p.h @@ -51,7 +51,7 @@ QT_BEGIN_NAMESPACE -class QSerialPortInfoPrivate +class Q_AUTOTEST_EXPORT QSerialPortInfoPrivate { public: QSerialPortInfoPrivate() @@ -59,9 +59,15 @@ public: , productIdentifier(0) , hasVendorIdentifier(false) , hasProductIdentifier(false) - {} + { + } + + ~QSerialPortInfoPrivate() + { + } - ~QSerialPortInfoPrivate() {} + static QString portNameToSystemLocation(const QString &source); + static QString portNameFromSystemLocation(const QString &source); QString portName; QString device; diff --git a/src/serialport/qserialportinfo_unix.cpp b/src/serialport/qserialportinfo_unix.cpp index 4479e97..07587ec 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,26 +94,133 @@ static QStringList filteredDeviceFilePaths() return result; } -QList<QSerialPortInfo> availablePortsByFiltersOfDevices() +QList<QSerialPortInfo> availablePortsByFiltersOfDevices(bool &ok) { QList<QSerialPortInfo> serialPortInfoList; foreach (const QString &deviceFilePath, filteredDeviceFilePaths()) { - QSerialPortInfo serialPortInfo; - serialPortInfo.d_ptr->device = deviceFilePath; - serialPortInfo.d_ptr->portName = QSerialPortPrivate::portNameFromSystemLocation(deviceFilePath); - serialPortInfoList.append(serialPortInfo); + QSerialPortInfoPrivate priv; + priv.device = deviceFilePath; + priv.portName = QSerialPortInfoPrivate::portNameFromSystemLocation(deviceFilePath); + 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) + QDir targetDir(fileInfo.symLinkTarget()); + + QSerialPortInfoPrivate priv; + + priv.portName = deviceName(targetDir); + if (priv.portName.isEmpty()) continue; - QSerialPortInfo serialPortInfo; - 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 + const QString driverName = deviceDriver(targetDir); + if (driverName.isEmpty()) { + if (!isRfcommDevice(priv.portName)) + continue; + } + + priv.device = QSerialPortInfoPrivate::portNameToSystemLocation(priv.portName); + if (isSerial8250Driver(driverName) && !isValidSerial8250(priv.device)) 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)) - serialPortInfo.d_ptr->description = QString::fromLatin1(description.readAll()).simplified(); - - QFile manufacturer(QFileInfo(targetDir, QStringLiteral("manufacturer")).absoluteFilePath()); - if (manufacturer.open(QIODevice::ReadOnly | QIODevice::Text)) - serialPortInfo.d_ptr->manufacturer = QString::fromLatin1(manufacturer.readAll()).simplified(); - - QFile serialNumber(QFileInfo(targetDir, QStringLiteral("serial")).absoluteFilePath()); - if (serialNumber.open(QIODevice::ReadOnly | QIODevice::Text)) - serialPortInfo.d_ptr->serialNumber = QString::fromLatin1(serialNumber.readAll()).simplified(); - - QFile vendorIdentifier(QFileInfo(targetDir, QStringLiteral("idVendor")).absoluteFilePath()); - if (vendorIdentifier.open(QIODevice::ReadOnly | QIODevice::Text)) { - serialPortInfo.d_ptr->vendorIdentifier = QString::fromLatin1(vendorIdentifier.readAll()) - .toInt(&serialPortInfo.d_ptr->hasVendorIdentifier, 16); - } - - QFile productIdentifier(QFileInfo(targetDir, QStringLiteral("idProduct")).absoluteFilePath()); - if (productIdentifier.open(QIODevice::ReadOnly | QIODevice::Text)) { - serialPortInfo.d_ptr->productIdentifier = QString::fromLatin1(productIdentifier.readAll()) - .toInt(&serialPortInfo.d_ptr->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)) { - serialPortInfo.d_ptr->vendorIdentifier = QString::fromLatin1(vendorIdentifier.readAll()) - .toInt(&serialPortInfo.d_ptr->hasVendorIdentifier, 16); - } - QFile productIdentifier(QFileInfo(targetDir, QStringLiteral("device")).absoluteFilePath()); - if (productIdentifier.open(QIODevice::ReadOnly | QIODevice::Text)) { - serialPortInfo.d_ptr->productIdentifier = QString::fromLatin1(productIdentifier.readAll()) - .toInt(&serialPortInfo.d_ptr->hasProductIdentifier, 16); + + 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; } - // 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 { - continue; - } + } while (targetDir.cdUp()); - serialPortInfo.d_ptr->portName = targetPath.mid(lastIndexOfSlash + 1); - serialPortInfo.d_ptr->device = QSerialPortPrivate::portNameToSystemLocation(serialPortInfo.d_ptr->portName); - serialPortInfoList.append(serialPortInfo); + 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 deviceDescription(struct ::udev_device *dev) +{ + return deviceProperty(dev, "ID_MODEL").replace(QLatin1Char('_'), QLatin1Char(' ')); +} + +static QString deviceManufacturer(struct ::udev_device *dev) +{ + return deviceProperty(dev, "ID_VENDOR").replace(QLatin1Char('_'), QLatin1Char(' ')); } -static -QString getUdevModelName(struct ::udev_device *dev) +static quint16 deviceProductIdentifier(struct ::udev_device *dev, bool &hasIdentifier) { - return getUdevPropertyValue(dev, "ID_MODEL") - .replace(QLatin1Char('_'), QLatin1Char(' ')); + return deviceProperty(dev, "ID_MODEL_ID").toInt(&hasIdentifier, 16); } -static -QString getUdevVendorName(struct ::udev_device *dev) +static quint16 deviceVendorIdentifier(struct ::udev_device *dev, bool &hasIdentifier) { - return getUdevPropertyValue(dev, "ID_VENDOR") - .replace(QLatin1Char('_'), QLatin1Char(' ')); + return deviceProperty(dev, "ID_VENDOR_ID").toInt(&hasIdentifier, 16); } -static -quint16 getUdevModelIdentifier(struct ::udev_device *dev, bool &hasIdentifier) +static QString deviceSerialNumber(struct ::udev_device *dev) { - return getUdevPropertyValue(dev, "ID_MODEL_ID").toInt(&hasIdentifier, 16); + return deviceProperty(dev,"ID_SERIAL_SHORT"); } -static -quint16 getUdevVendorIdentifier(struct ::udev_device *dev, bool &hasIdentifier) +static QString deviceName(struct ::udev_device *dev) { - return getUdevPropertyValue(dev, "ID_VENDOR_ID").toInt(&hasIdentifier, 16); + return QString::fromLatin1(::udev_device_get_sysname(dev)); } -static -QString getUdevSerialNumber(struct ::udev_device *dev) +static QString deviceLocation(struct ::udev_device *dev) { - return getUdevPropertyValue(dev,"ID_SERIAL_SHORT"); + return QString::fromLatin1(::udev_device_get_devnode(dev)); } -QList<QSerialPortInfo> availablePortsByUdev() +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))); @@ -318,33 +391,28 @@ QList<QSerialPortInfo> availablePortsByUdev() if (!dev) return serialPortInfoList; - QSerialPortInfo serialPortInfo; + QSerialPortInfoPrivate priv; - serialPortInfo.d_ptr->device = QString::fromLatin1(::udev_device_get_devnode(dev.data())); - serialPortInfo.d_ptr->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; - serialPortInfo.d_ptr->description = getUdevModelName(dev.data()); - serialPortInfo.d_ptr->manufacturer = getUdevVendorName(dev.data()); - serialPortInfo.d_ptr->serialNumber = getUdevSerialNumber(dev.data()); - serialPortInfo.d_ptr->vendorIdentifier = getUdevVendorIdentifier(dev.data(), serialPortInfo.d_ptr->hasVendorIdentifier); - serialPortInfo.d_ptr->productIdentifier = getUdevModelIdentifier(dev.data(), serialPortInfo.d_ptr->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 (serialPortInfo.d_ptr->portName.startsWith(rfcommDeviceName)) { - bool ok; - int portNumber = serialPortInfo.d_ptr->portName.mid(rfcommDeviceName.length()).toInt(&ok); - if (!ok || (portNumber < 0) || (portNumber > 255)) - continue; - } else { + if (!isRfcommDevice(priv.portName)) continue; - } } - serialPortInfoList.append(serialPortInfo); + serialPortInfoList.append(priv); } return serialPortInfoList; @@ -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; } @@ -401,4 +469,18 @@ bool QSerialPortInfo::isValid() const return f.exists(); } +QString QSerialPortInfoPrivate::portNameToSystemLocation(const QString &source) +{ + return (source.startsWith(QLatin1Char('/')) + || source.startsWith(QStringLiteral("./")) + || source.startsWith(QStringLiteral("../"))) + ? source : (QStringLiteral("/dev/") + source); +} + +QString QSerialPortInfoPrivate::portNameFromSystemLocation(const QString &source) +{ + return source.startsWith(QStringLiteral("/dev/")) + ? source.mid(5) : source; +} + QT_END_NAMESPACE diff --git a/src/serialport/qserialportinfo_win.cpp b/src/serialport/qserialportinfo_win.cpp index 0958617..493c4d0 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; @@ -312,23 +312,23 @@ QList<QSerialPortInfo> QSerialPortInfo::availablePorts() continue; } - QSerialPortInfo serialPortInfo; + QSerialPortInfoPrivate priv; - serialPortInfo.d_ptr->portName = portName; - serialPortInfo.d_ptr->device = QSerialPortPrivate::portNameToSystemLocation(portName); - serialPortInfo.d_ptr->description = deviceDescription(deviceInfoSet, &deviceInfoData); - serialPortInfo.d_ptr->manufacturer = deviceManufacturer(deviceInfoSet, &deviceInfoData); + priv.portName = portName; + priv.device = QSerialPortInfoPrivate::portNameToSystemLocation(portName); + priv.description = deviceDescription(deviceInfoSet, &deviceInfoData); + priv.manufacturer = deviceManufacturer(deviceInfoSet, &deviceInfoData); const QString instanceIdentifier = deviceInstanceIdentifier(deviceInfoData.DevInst); - serialPortInfo.d_ptr->serialNumber = + priv.serialNumber = deviceSerialNumber(instanceIdentifier, deviceInfoData.DevInst); - serialPortInfo.d_ptr->vendorIdentifier = - deviceVendorIdentifier(instanceIdentifier, serialPortInfo.d_ptr->hasVendorIdentifier); - serialPortInfo.d_ptr->productIdentifier = - deviceProductIdentifier(instanceIdentifier, serialPortInfo.d_ptr->hasProductIdentifier); + priv.vendorIdentifier = + deviceVendorIdentifier(instanceIdentifier, priv.hasVendorIdentifier); + priv.productIdentifier = + deviceProductIdentifier(instanceIdentifier, priv.hasProductIdentifier); - serialPortInfoList.append(serialPortInfo); + serialPortInfoList.append(priv); } ::SetupDiDestroyDeviceInfoList(deviceInfoSet); } @@ -336,10 +336,10 @@ QList<QSerialPortInfo> QSerialPortInfo::availablePorts() foreach (const QString &portName, portNamesFromHardwareDeviceMap()) { if (std::find_if(serialPortInfoList.begin(), serialPortInfoList.end(), SerialPortNameEqualFunctor(portName)) == serialPortInfoList.end()) { - QSerialPortInfo serialPortInfo; - serialPortInfo.d_ptr->portName = portName; - serialPortInfo.d_ptr->device = QSerialPortPrivate::portNameToSystemLocation(portName); - serialPortInfoList.append(serialPortInfo); + QSerialPortInfoPrivate priv; + priv.portName = portName; + priv.device = QSerialPortInfoPrivate::portNameToSystemLocation(portName); + serialPortInfoList.append(priv); } } @@ -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) @@ -379,4 +379,17 @@ bool QSerialPortInfo::isValid() const return true; } +QString QSerialPortInfoPrivate::portNameToSystemLocation(const QString &source) +{ + return source.startsWith(QStringLiteral("COM")) + ? (QStringLiteral("\\\\.\\") + source) : source; +} + +QString QSerialPortInfoPrivate::portNameFromSystemLocation(const QString &source) +{ + return (source.startsWith(QStringLiteral("\\\\.\\")) + || source.startsWith(QStringLiteral("//./"))) + ? source.mid(4) : source; +} + QT_END_NAMESPACE diff --git a/src/serialport/qserialportinfo_wince.cpp b/src/serialport/qserialportinfo_wince.cpp index 15d2cf7..78439c9 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)); @@ -105,13 +105,13 @@ QList<QSerialPortInfo> QSerialPortInfo::availablePorts() &di); if (hSearch != INVALID_HANDLE_VALUE) { do { - QSerialPortInfo serialPortInfo; - serialPortInfo.d_ptr->device = QString::fromWCharArray(di.szLegacyName); - serialPortInfo.d_ptr->portName = QSerialPortPrivate::portNameFromSystemLocation(serialPortInfo.d_ptr->device); - serialPortInfo.d_ptr->description = findDescription(HKEY_LOCAL_MACHINE, - QString::fromWCharArray(di.szDeviceKey)); + QSerialPortInfoPrivate priv; + priv.device = QString::fromWCharArray(di.szLegacyName); + priv.portName = QSerialPortInfoPrivate::portNameFromSystemLocation(priv.device); + priv.description = findDescription(HKEY_LOCAL_MACHINE, + QString::fromWCharArray(di.szDeviceKey)); - serialPortInfoList.append(serialPortInfo); + serialPortInfoList.append(priv); } while (::FindNextDevice(hSearch, &di)); ::FindClose(hSearch); @@ -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) @@ -153,4 +153,16 @@ bool QSerialPortInfo::isValid() const return true; } +QString QSerialPortInfoPrivate::portNameToSystemLocation(const QString &source) +{ + return source.endsWith(QLatin1Char(':')) + ? source : (source + QLatin1Char(':')); +} + +QString QSerialPortInfoPrivate::portNameFromSystemLocation(const QString &source) +{ + return source.endsWith(QLatin1Char(':')) + ? source.mid(0, source.size() - 1) : source; +} + QT_END_NAMESPACE diff --git a/src/serialport/qt4support/include/private/qcore_unix_p.h b/src/serialport/qt4support/include/private/qcore_unix_p.h index 6a7fb72..640525a 100644 --- a/src/serialport/qt4support/include/private/qcore_unix_p.h +++ b/src/serialport/qt4support/include/private/qcore_unix_p.h @@ -72,7 +72,7 @@ static inline int qt_safe_open(const char *pathname, int flags, mode_t mode = 07 #ifdef O_CLOEXEC flags |= O_CLOEXEC; #endif - register int fd; + int fd; EINTR_LOOP(fd, QT_OPEN(pathname, flags, mode)); // unknown flags are ignored, so we have no way of verifying if @@ -104,7 +104,7 @@ static inline qint64 qt_safe_write(int fd, const void *data, qint64 len) static inline int qt_safe_close(int fd) { - register int ret; + int ret; EINTR_LOOP(ret, QT_CLOSE(fd)); return ret; } diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro index 14963a2..2fa03f0 100644 --- a/tests/auto/auto.pro +++ b/tests/auto/auto.pro @@ -1,2 +1,5 @@ TEMPLATE = subdirs -SUBDIRS += qserialport cmake +SUBDIRS += qserialport qserialportinfo qserialportinfoprivate cmake + +!contains(QT_CONFIG, private_tests): SUBDIRS -= \ + qserialportinfoprivate diff --git a/tests/auto/qserialport/tst_qserialport.cpp b/tests/auto/qserialport/tst_qserialport.cpp index 357cef8..b05d7d0 100644 --- a/tests/auto/qserialport/tst_qserialport.cpp +++ b/tests/auto/qserialport/tst_qserialport.cpp @@ -164,10 +164,24 @@ void tst_QSerialPort::initTestCase() m_senderPortName = QString::fromLocal8Bit(qgetenv("QTEST_SERIALPORT_SENDER")); m_receiverPortName = QString::fromLocal8Bit(qgetenv("QTEST_SERIALPORT_RECEIVER")); if (m_senderPortName.isEmpty() || m_receiverPortName.isEmpty()) { + static const char message[] = + "Test doesn't work because the names of serial ports aren't found in env.\n" + "Please set environment variables:\n" + " QTEST_SERIALPORT_SENDER to name of output serial port\n" + " QTEST_SERIALPORT_RECEIVER to name of input serial port\n" + "Specify short names of port" +#if defined(Q_OS_UNIX) + ", like: ttyS0\n"; +#elif defined(Q_OS_WIN32) + ", like: COM1\n"; +#else + "\n"; +#endif + #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) - QSKIP("Test doesn't work because the names of serial ports aren't found in env."); + QSKIP(message); #else - QSKIP("Test doesn't work because the names of serial ports aren't set found env.", SkipAll); + QSKIP(message, SkipAll); #endif } else { m_availablePortNames << m_senderPortName << m_receiverPortName; diff --git a/tests/auto/qserialportinfo/qserialportinfo.pro b/tests/auto/qserialportinfo/qserialportinfo.pro new file mode 100644 index 0000000..b3e49bd --- /dev/null +++ b/tests/auto/qserialportinfo/qserialportinfo.pro @@ -0,0 +1,11 @@ +QT = core testlib +TARGET = tst_qserialportinfo +#CONFIG += testcase + +greaterThan(QT_MAJOR_VERSION, 4) { + QT += serialport +} else { + include($$QTSERIALPORT_PROJECT_ROOT/src/serialport/qt4support/serialport.prf) +} + +SOURCES = tst_qserialportinfo.cpp diff --git a/tests/auto/qserialportinfo/tst_qserialportinfo.cpp b/tests/auto/qserialportinfo/tst_qserialportinfo.cpp new file mode 100644 index 0000000..e421aa4 --- /dev/null +++ b/tests/auto/qserialportinfo/tst_qserialportinfo.cpp @@ -0,0 +1,127 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Denis Shienkov <denis.shienkov@gmail.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtSerialPort module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> +#include <QtSerialPort/QSerialPort> +#include <QtSerialPort/QSerialPortInfo> + +class tst_QSerialPortInfo : public QObject +{ + Q_OBJECT +public: + explicit tst_QSerialPortInfo(); + +private slots: + void initTestCase(); + + void constructors(); + void assignment(); + +private: + QString m_senderPortName; + QString m_receiverPortName; + QStringList m_availablePortNames; +}; + +tst_QSerialPortInfo::tst_QSerialPortInfo() +{ +} + +void tst_QSerialPortInfo::initTestCase() +{ + m_senderPortName = QString::fromLocal8Bit(qgetenv("QTEST_SERIALPORT_SENDER")); + m_receiverPortName = QString::fromLocal8Bit(qgetenv("QTEST_SERIALPORT_RECEIVER")); + if (m_senderPortName.isEmpty() || m_receiverPortName.isEmpty()) { + static const char message[] = + "Test doesn't work because the names of serial ports aren't found in env.\n" + "Please set environment variables:\n" + " QTEST_SERIALPORT_SENDER to name of output serial port\n" + " QTEST_SERIALPORT_RECEIVER to name of input serial port\n" + "Specify short names of port" +#if defined(Q_OS_UNIX) + ", like 'ttyS0'\n"; +#elif defined(Q_OS_WIN32) + ", like 'COM1'\n"; +#else + "\n"; +#endif +#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) + QSKIP(message); +#else + QSKIP(message, SkipAll); +#endif + } else { + m_availablePortNames << m_senderPortName << m_receiverPortName; + } +} + +void tst_QSerialPortInfo::constructors() +{ + QSerialPortInfo empty; + QVERIFY(empty.isNull()); + QSerialPortInfo empty2(QLatin1String("ABCD")); + QVERIFY(empty2.isNull()); + QSerialPortInfo empty3(empty); + QVERIFY(empty3.isNull()); + + QSerialPortInfo exist(m_senderPortName); + QVERIFY(!exist.isNull()); + QSerialPortInfo exist2(exist); + QVERIFY(!exist2.isNull()); +} + +void tst_QSerialPortInfo::assignment() +{ + QSerialPortInfo empty; + QVERIFY(empty.isNull()); + QSerialPortInfo empty2; + empty2 = empty; + QVERIFY(empty2.isNull()); + + QSerialPortInfo exist(m_senderPortName); + QVERIFY(!exist.isNull()); + QSerialPortInfo exist2; + exist2 = exist; + QVERIFY(!exist2.isNull()); +} + +QTEST_MAIN(tst_QSerialPortInfo) +#include "tst_qserialportinfo.moc" diff --git a/tests/auto/qserialportinfoprivate/qserialportinfoprivate.pro b/tests/auto/qserialportinfoprivate/qserialportinfoprivate.pro new file mode 100644 index 0000000..f479a29 --- /dev/null +++ b/tests/auto/qserialportinfoprivate/qserialportinfoprivate.pro @@ -0,0 +1,4 @@ +QT = core testlib serialport-private +TARGET = tst_qserialportinfoprivate +#CONFIG += testcase +SOURCES = tst_qserialportinfoprivate.cpp diff --git a/tests/auto/qserialportinfoprivate/tst_qserialportinfoprivate.cpp b/tests/auto/qserialportinfoprivate/tst_qserialportinfoprivate.cpp new file mode 100644 index 0000000..cfd2d85 --- /dev/null +++ b/tests/auto/qserialportinfoprivate/tst_qserialportinfoprivate.cpp @@ -0,0 +1,110 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Denis Shienkov <denis.shienkov@gmail.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtSerialPort module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <private/qserialportinfo_p.h> + +class tst_QSerialPortInfoPrivate : public QObject +{ + Q_OBJECT +public: + explicit tst_QSerialPortInfoPrivate(); + +private slots: + void canonical_data(); + void canonical(); +}; + +tst_QSerialPortInfoPrivate::tst_QSerialPortInfoPrivate() +{ +} + +void tst_QSerialPortInfoPrivate::canonical_data() +{ + QTest::addColumn<QString>("source"); + QTest::addColumn<QString>("name"); + QTest::addColumn<QString>("location"); + +#if defined (Q_OS_WINCE) + QTest::newRow("Test1") << "COM1" << "COM1" << "COM1:"; + QTest::newRow("Test2") << "COM1:" << "COM1" << "COM1:"; +#elif defined (Q_OS_WIN32) + QTest::newRow("Test1") << "COM1" << "COM1" << "\\\\.\\COM1"; + QTest::newRow("Test2") << "\\\\.\\COM1" << "COM1" << "\\\\.\\COM1"; + QTest::newRow("Test3") << "//./COM1" << "COM1" << "//./COM1"; +#elif defined (Q_OS_OSX) + QTest::newRow("Test1") << "ttyS0" << "ttyS0" << "/dev/ttyS0"; + QTest::newRow("Test2") << "cu.serial1" << "cu.serial1" << "/dev/cu.serial1"; + QTest::newRow("Test3") << "tty.serial1" << "tty.serial1" << "/dev/tty.serial1"; + QTest::newRow("Test4") << "/dev/ttyS0" << "ttyS0" << "/dev/ttyS0"; + QTest::newRow("Test5") << "/dev/tty.serial1" << "tty.serial1" << "/dev/tty.serial1"; + QTest::newRow("Test6") << "/dev/cu.serial1" << "cu.serial1" << "/dev/cu.serial1"; + QTest::newRow("Test7") << "/dev/serial/ttyS0" << "serial/ttyS0" << "/dev/serial/ttyS0"; + QTest::newRow("Test8") << "/home/ttyS0" << "/home/ttyS0" << "/home/ttyS0"; + QTest::newRow("Test9") << "/home/serial/ttyS0" << "/home/serial/ttyS0" << "/home/serial/ttyS0"; + QTest::newRow("Test10") << "serial/ttyS0" << "serial/ttyS0" << "/dev/serial/ttyS0"; + QTest::newRow("Test11") << "./ttyS0" << "./ttyS0" << "./ttyS0"; + QTest::newRow("Test12") << "../ttyS0" << "../ttyS0" << "../ttyS0"; +#elif defined (Q_OS_UNIX) + QTest::newRow("Test1") << "ttyS0" << "ttyS0" << "/dev/ttyS0"; + QTest::newRow("Test2") << "/dev/ttyS0" << "ttyS0" << "/dev/ttyS0"; + QTest::newRow("Test3") << "/dev/serial/ttyS0" << "serial/ttyS0" << "/dev/serial/ttyS0"; + QTest::newRow("Test4") << "/home/ttyS0" << "/home/ttyS0" << "/home/ttyS0"; + QTest::newRow("Test5") << "/home/serial/ttyS0" << "/home/serial/ttyS0" << "/home/serial/ttyS0"; + QTest::newRow("Test6") << "serial/ttyS0" << "serial/ttyS0" << "/dev/serial/ttyS0"; + QTest::newRow("Test7") << "./ttyS0" << "./ttyS0" << "./ttyS0"; + QTest::newRow("Test8") << "../ttyS0" << "../ttyS0" << "../ttyS0"; +#endif +} + +void tst_QSerialPortInfoPrivate::canonical() +{ + QFETCH(QString, source); + QFETCH(QString, name); + QFETCH(QString, location); + + QCOMPARE(QSerialPortInfoPrivate::portNameFromSystemLocation(source), name); + QCOMPARE(QSerialPortInfoPrivate::portNameToSystemLocation(source), location); +} + +QTEST_MAIN(tst_QSerialPortInfoPrivate) +#include "tst_qserialportinfoprivate.moc" |