Blocking Master Example

The Blocking Master example shows how to create a application for a serial interface using QSerialPort's synchronous API in a non-GUI thread.

Screenshot of the Blocking Master example

QSerialPort supports two general programming approaches:

  • The asynchronous (non-blocking) approach. Operations are scheduled and performed when the control returns to Qt's event loop. QSerialPort emits a signal when the operation is finished. For example, QSerialPort::write() returns immediately. When the data is sent to the serial port, QSerialPort emits bytesWritten().
  • The synchronous (blocking) approach. In non-GUI and multithreaded applications, the 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 Terminal 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 unmanagable complexity to your application.

This application is a Master, that demonstrate the work paired with Slave application Blocking Slave Example.

The Master application is initiate the transfer request via serial port to the Slave application and wait for a response from it.

We will start with the MasterThread class, which handles the serial programming code.

class MasterThread : public QThread
{
    Q_OBJECT

public:
    MasterThread(QObject *parent = 0);
    ~MasterThread();

    void transaction(const QString &portName, int waitTimeout, const QString &request);
    void run();

signals:
    void response(const QString &s);
    void error(const QString &s);
    void timeout(const QString &s);

private:
    QString portName;
    QString request;
    int waitTimeout;
    QMutex mutex;
    QWaitCondition cond;
    bool quit;
};

MasterThread is a QThread subclass that provides an API for scheduling requests to Slave, and it has signals for delivering responses and reporting errors. You can call transaction() to startup new master transaction with desired request data and other parameters, and the result is delivered by the response() signal. If any error occurs, the error() or timeout() signals is emitted.

It's important to notice that transaction() is called from the main, GUI thread, but the request data and other parameters will be accessed from MasterThread's thread. Because we will be reading and writing MasterThread's data members from different threads concurrently, we use QMutex to synchronize access.

void MasterThread::transaction(const QString &portName, int waitTimeout, const QString &request)
{
    QMutexLocker locker(&mutex);
    this->portName = portName;
    this->waitTimeout = waitTimeout;
    this->request = request;
    if (!isRunning())
        start();
    else
        cond.wakeOne();
}

The transaction() function stores the serial port name, timeout and request data, and we lock the mutex with QMutexLocker to protect this data. We then start the thread, unless it is already running. We will come back to the QWaitCondition::wakeOne() call later.

void MasterThread::run()
{
    bool currentPortNameChanged = false;

    mutex.lock();
QString currentPortName;
if (currentPortName != portName) {
    currentPortName = portName;
    currentPortNameChanged = true;
}

int currentWaitTimeout = waitTimeout;
QString currentRequest = request;
mutex.unlock();

In the run() function, we start by acquiring the mutex lock, fetching the serial port name, timeout and request data from the member data, and then releasing the lock again. The case that we are protecting ourselves against is that transaction() could be called at the same time as we are fetching this data. QString is reentrant but not thread-safe, and we must also avoid the unlikely risk of reading the serial port name from one request, and timeout or request data of another. And as you might have guessed, MasterThread can only handle one request 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, we check for changed or not the name of serial port for the current transaction. And if the name is changed then re-open and re-configure 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.setBaudRate(QSerialPort::Baud9600)) {
        emit error(tr("Can't set baud rate 9600 baud to port %1, error code %2")
                   .arg(portName).arg(serial.error()));
        return;
    }

    if (!serial.setDataBits(QSerialPort::Data8)) {
        emit error(tr("Can't set 8 data bits to port %1, error code %2")
                   .arg(portName).arg(serial.error()));
        return;
    }

    if (!serial.setParity(QSerialPort::NoParity)) {
        emit error(tr("Can't set no patity to port %1, error code %2")
                   .arg(portName).arg(serial.error()));
        return;
    }

    if (!serial.setStopBits(QSerialPort::OneStop)) {
        emit error(tr("Can't set 1 stop bit to port %1, error code %2")
                   .arg(portName).arg(serial.error()));
        return;
    }

    if (!serial.setFlowControl(QSerialPort::NoFlowControl)) {
        emit error(tr("Can't set no flow control to port %1, error code %2")
                   .arg(portName).arg(serial.error()));
        return;
    }
}

The loop will continue creating request data, write to serial port and wait until all data is transferred.

// write request
QByteArray requestData = currentRequest.toLocal8Bit();
serial.write(requestData);
if (serial.waitForBytesWritten(waitTimeout)) {

Warning: 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 error occurs when transferring data.

} else {
emit timeout(tr("Wait write request timeout %1")
             .arg(QTime::currentTime().toString()));
}

After a successful request, we start wait until response and try read it.

// read response
if (serial.waitForReadyRead(currentWaitTimeout)) {
    QByteArray responseData = serial.readAll();
    while (serial.waitForReadyRead(10))
        responseData += serial.readAll();

    QString response(responseData);
    emit this->response(response);

Warning: 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 receiving data.

} else {
emit timeout(tr("Wait read response timeout %1")
             .arg(QTime::currentTime().toString()));
}

After a successful transaction is emitted response() signal containing the data received from the Slave application:

emit this->response(response);

Next, the thread goes to sleep until the next transaction is appear. On waking, the thread re-reads the new data of members and run loop from the beginning.

mutex.lock();
cond.wait(&mutex);
if (currentPortName != portName) {
    currentPortName = portName;
    currentPortNameChanged = true;
} else {
    currentPortNameChanged = false;
}
currentWaitTimeout = waitTimeout;
currentRequest = request;
mutex.unlock();
}

Files:

See also Terminal Example and Blocking Slave Example.