QSerialPort readLine () is extremely slow compared to readAll ()

The data that I read from the serial port (in Qt, using QtSerialPort / QSerialPort) is separated by the newline characters '\ n' and return '\ r', which I am going to look at it for analysis, the line length can be very strong, but very Easily extract data from each row format.

//signal/slot connection on readyRead() is as follows: connect(serial, SIGNAL(readyRead()), this, SLOT(readData())); 

where readData () is defined as:

 void MainWindow::readData() { //As mentioned below, which I will reiterate, I have already tried the addition of // canReadLine(): if (serial->canReadLine()){ QByteArray data = serial->readLine(); //QByteArray allData = serial->readAll(); parseSerialBytes(data); //console->putData(data); //console->putData(alldata); } } 

However, the QIODevice::readLine() function is extremely slow and explicitly blocks receiving data at full frequency compared to QIODevice :: readAll ()

Can someone explain how to use the readLine() function correctly, so I don't have to go through readAll() in QByteArray to parse each line? I used the Qt Widgets β€œTerminal” example to create this asynchronous serialport read function.

Thanks in advance - this seems to be a common problem that I have not seen here yet.

+6
source share
1 answer

This is a common mistake. readData is called only once per piece of data , not necessarily once per line .

You need to continue reading rows until data is available. This is also a poor design for reading lines in a widget class. Move it to a separate object.

 class Receiver : public QObject { Q_OBJECT QSerialPort m_port; QByteArray m_buffer; void processLine(const QByteArray & line) { ... } Q_SLOT void readData() { // IMPORTANT: That a *while*, not an *if*! while (m_port.canReadLine()) processLine(m_port.readLine()); } public: Receiver(QObject * receiver = 0) : QObject(parent) { connect(&m_port, &QIODevice::readyRead, this, &Receiver::readData); ... } } 

Your mistake was to implement readData as shown below. Such code reads only one line, regardless of how many lines are available for reading. It will seem β€œslow” because with each call, more and more data is accumulated that remains unread. In the end, he will run out of heaps.

 void readData() { // WRONG! if (m_port.canReadLine()) processLine(m_port.readLine()); } 
+5
source

Source: https://habr.com/ru/post/972271/


All Articles