PDA

View Full Version : QSerialPort sending data and waiting for response



Bonkers
21st April 2021, 10:03
Hi,

I am working on an application which communicates with an appliance attached to the serial port. The application send commands and waits for the appliance's reply, or until timeout. Currently I am doing the waiting using an instance of QEventLoop, however I read that using QEventLoop leads to subtle bugs. So now I need to redesign my application logic, which currently depends on a method which sends data out of the port and waits for a response of certain length.

What I want to achieve is (pseudocode):

response = connection.sendQuery(query, responseLength, timeout)
if (response.length() == responseLength) {
// valid response
} else {
//invalid response
}


Can you please suggest a strategy for creating that logic?

Thanks

d_stranz
21st April 2021, 15:59
Look at QSerialPort (and the base class QIODevice) which implement a handshake protocol for writing and reading data based on signals and slots. A typical use is to connect a slot to the QSerialPort::readyRead() signal, which will be emitted when the serial port has received data (not necessarily the complete response, just any part of it).

The Qt distribution comes with a large number of QSerialPort examples (https://doc.qt.io/qt-5/qtserialport-examples.html).

There is rarely any need for you to implement your own event loop.