QSerialPort readLine() extremely slow compared to readAll()

后端 未结 1 1959
清歌不尽
清歌不尽 2020-12-09 22:12

The data I\'m reading from a serialport (in Qt, using QtSerialPort/QSerialPort) is separated by the newline \'\\n\' and return \'\\r\' characters, which is the way I intend

相关标签:
1条回答
  • 2020-12-09 23:03

    This is a common error. The readData is called only once per a chunk of data, not necessarily once per line.

    You need to keep reading lines as long as data is available. It is also a bad design to have serial line reading 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's 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 error was to implement readData as shown below. Such code reads only one line no matter how many lines are available to be read. It'll appear "slow" since on each invocation there's more and more accumulated data that's left behind unread. Eventually it'll run out of heap.

    void readData() {
      // WRONG!
      if (m_port.canReadLine()) processLine(m_port.readLine());
    }
    
    0 讨论(0)
提交回复
热议问题