C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – readyRead()在Qt中如何工作?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我在这个网站上的第一个问题!

我在从COM端口读取数据时遇到一些麻烦,我从另一个COM端口发送完整的消息,当我用Qt接收它时,它总是被切成多个子消息.

@H_673_9@void serialPortReader::init() { connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(readData())); } void serialPortReader::readData() { // m_serialPort->waitForReadyRead(200); QByteArray byteArray = m_serialPort->readAll(); qDebug() << byteArray; if(byteArray.startsWith(SOF) && byteArray.endsWith(EOF_LS) && byteArray.size() >= MIN_SIZE_DATA) { decodeData(byteArray.constData()); } else { qDebug() << "LIB SWCom : Unvalid trame !"; } }

发送的消息长度为25或27字节,如果我使用Putty或Hyperterminal来读取它们,我没有遇到麻烦.
另外如果我使用2个模拟串口COM进行通信,我没有这个问题……
它只发生在Qt读取系统和2个物理COM端口……

我认为在准确发出readyRead信号时我没有得到…

我很困惑,提前谢谢你的帮助!

解决方法

documentation实际上非常清楚:

这意味着它并没有真正保证可以读取多少数据,只是有些数据可用.

如果您希望读取的数据多于一次性输入的数据,则可以选择超时值和/或readyRead.这取决于你想要达到的目标.

请参阅我之前为此操作编写的command line async reader example

@H_673_9@#include "serialportreader.h" #include <QCoreApplication> QT_USE_NAMESPACE serialPortReader::serialPortReader(QserialPort *serialPort,QObject *parent) : QObject(parent),m_serialPort(serialPort),m_standardOutput(stdout) { connect(m_serialPort,SLOT(handleReadyRead())); connect(m_serialPort,SIGNAL(error(QserialPort::serialPortError)),SLOT(handleError(QserialPort::serialPortError))); connect(&m_timer,SIGNAL(timeout()),SLOT(handleTimeout())); m_timer.start(5000); } serialPortReader::~serialPortReader() { } void serialPortReader::handleReadyRead() { m_readData.append(m_serialPort->readAll()); if (!m_timer.isActive()) m_timer.start(5000); } void serialPortReader::handleTimeout() { if (m_readData.isEmpty()) { m_standardOutput << QObject::tr("No data was currently available for reading from port %1").arg(m_serialPort->portName()) << endl; } else { m_standardOutput << QObject::tr("Data successfully received from port %1").arg(m_serialPort->portName()) << endl; m_standardOutput << m_readData << endl; } QCoreApplication::quit(); } void serialPortReader::handleError(QserialPort::serialPortError serialPortError) { if (serialPortError == QserialPort::readError) { m_standardOutput << QObject::tr("An I/O error occurred while reading the data from port %1,error: %2").arg(m_serialPort->portName()).arg(m_serialPort->errorString()) << endl; QCoreApplication::exit(1); } }

在这种情况下,命令行阅读器示例将获取一次性传递的任何数据,但不保证长度或任何内容.

此外,请注意您的评论背后的同步api与您询问的异步API一起没有多大意义.我指的是m_serialPort-> waitForReadyRead(200);在这里.

大佬总结

以上是大佬教程为你收集整理的c – readyRead()在Qt中如何工作?全部内容,希望文章能够帮你解决c – readyRead()在Qt中如何工作?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。