阻塞从属 shows how to create an application for a serial interface using QSerialPort 's synchronous API in a non-GUI thread.
QSerialPort 支持 2 种常规编程方式:
waitFor...()
functions can be called (i.e.
QSerialPort::waitForReadyRead
()) to suspend the calling thread until the operation has completed.
In this example, the synchronous approach is demonstrated. The 终端 example illustrates the asynchronous approach.
The purpose of this example is to demonstrate a pattern that you can use to simplify your serial programming code, without losing responsiveness in your user interface. Use of Qt's blocking serial programming API often leads to simpler code, but because of its blocking behavior, it should only be used in non-GUI threads to prevent the user interface from freezing. But contrary to what many think, using threads with QThread does not necessarily add unmanageable complexity to your application.
This application is a Slave, that demonstrate the work paired with Master application 阻塞主控范例 .
The Slave application is receives the request via serial port from the Master application and send a response to it.
We will start with the SlaveThread class, which handles the serial programming code.
class SlaveThread : public QThread { Q_OBJECT public: explicit SlaveThread(QObject *parent = nullptr); ~SlaveThread(); void startSlave(const QString &portName, int waitTimeout, const QString &response); void run() Q_DECL_OVERRIDE; signals: void request(const QString &s); void error(const QString &s); void timeout(const QString &s); private: QString portName; QString response; int waitTimeout; QMutex mutex; bool quit; };
SlaveThread is a QThread subclass that provides an API for receive requests from Master, and it has signals for delivering responses and reporting errors.
You should be call startSlave() to startup Slave application. This method transfers to the SlaveThread desired parameters for configure and startup the serial interface. When SlaveThread received from Master any request then emitted the request() signal. If any error occurs, the error() or timeout() signals is emitted.
It's important to notice that startSlave() is called from the main, GUI thread, but the response data and other parameters will be accessed from SlaveThread's thread. SlaveThread's data members are read and written from different threads concurrently, so it is advisable to use QMutex to synchronize access.
void SlaveThread::startSlave(const QString &portName, int waitTimeout, const QString &response) { QMutexLocker locker(&mutex); this->portName = portName; this->waitTimeout = waitTimeout; this->response = response; if (!isRunning()) start(); }
The startSlave() function stores the serial port name, timeout and response data, and QMutexLocker locks the mutex to protect these data. We then start the thread, unless it is already running. QWaitCondition::wakeOne () will be discussed later.
void SlaveThread::run() { bool currentPortNameChanged = false; mutex.lock(); QString currentPortName; if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } int currentWaitTimeout = waitTimeout; QString currentRespone = response; mutex.unlock();
In the run() function, start by acquiring the mutex lock, fetch the serial port name, timeout and response data from the member data, and then release the lock again. Under no circumstance should the method
startSlave()
be called simultaneously with a process fetching these data.
QString
is reentrant but not thread-safe, and it is not recommended to read the serial port name from one startup, call and timeout or response data of another. SlaveThread can only handle one startup at a time.
The QSerialPort object we construct on stack into run() function before loop enter:
QSerialPort serial; while (!quit) {
This allows us once to create an object, while running loop, and also means that all the methods of the object will be executed in the context of the run() thread.
In the loop, check whether the name of the serial port for the current startup has changed or not. If it has, re-open and reconfigure the serial port.
if (currentPortNameChanged) { serial.close(); serial.setPortName(currentPortName); if (!serial.open(QIODevice::ReadWrite)) { emit error(tr("Can't open %1, error code %2") .arg(portName).arg(serial.error())); return; } } if (serial.waitForReadyRead(currentWaitTimeout)) {
The loop will continue waiting for request data:
// read request QByteArray requestData = serial.readAll(); while (serial.waitForReadyRead(10)) requestData += serial.readAll();
警告: The method waitForReadyRead() should be used before each read() call for the blocking approach, because it processes all the I/O routines instead of Qt event-loop.
The timeout() signal is emitted if error occurs when reading data.
} else { emit timeout(tr("Wait read request timeout %1") .arg(QTime::currentTime().toString())); }
After a successful read, try to send a response and wait for completion of the transfer:
// write response QByteArray responseData = currentRespone.toLocal8Bit(); serial.write(responseData); if (serial.waitForBytesWritten(waitTimeout)) { QString request(requestData); emit this->request(request);
警告: The method waitForBytesWritten() should be used after each write() call for the blocking approach, because it processes all the I/O routines instead of Qt event-loop.
The timeout() signal is emitted if an error occurs when writing data.
} else { emit timeout(tr("Wait write response timeout %1") .arg(QTime::currentTime().toString())); }
After a successful writing is emitted, request() signal containing the data received from the Master application:
emit this->request(request);
Next, the thread switches to reading the current parameters for the serial interface, because they can already have been updated, and run the loop from the beginning.
mutex.lock(); if (currentPortName != portName) { currentPortName = portName; currentPortNameChanged = true; } else { currentPortNameChanged = false; } currentWaitTimeout = waitTimeout; currentRespone = response; mutex.unlock(); }
要运行范例从 Qt Creator ,打开 欢迎 模式,然后选择范例从 范例 。更多信息,拜访 构建和运行范例 .
文件: