项目场景:
QSerialPort的异常分析
问题描述:
QSerialPort的waitForReadyread()经常接收数据不全或者等待超时
UINT WINAPI RS232::AcceptThread(void*pVoid)
{
RS232* pThis = (RS232*)pVoid;
pThis->AcceptRun();//
return 0;
}
void RS232::AcceptRun()
{
QByteArray rx_buf;
if(m_SerialPort == nullptr)
m_SerialPort = new QSerialPort;
//connect(m_SerialPort,&QSerialPort::readyRead,this,&RS232::SlotAcceptData,Qt::QueuedConnection);
m_ThreadRun = true;
while(m_ThreadRun)
{
if(m_AcceptType == AcceptType_Normal)
{
if(m_SerialPort->waitForReadyRead(2000))
{
qApp->processEvents();
while(true)
{
rx_buf += m_SerialPort->readAll(); //读取串口接收的数据
m_SerialPort->waitForReadyRead(50);
if(rx_buf.endsWith("\r\n")||rx_buf.endsWith("\n"))break;
}
QString rx_buf_tmp = QString::fromLocal8Bit(rx_buf); //转换为中文格式
emit PrintRecevieData(rx_buf_tmp);
IsReceiveData = true;
rx_buf.clear();
}
}
else if(m_AcceptType == AcceptType_Continuous)
{
}
Sleep(50);
}
}
原因分析:
Qt机制的问题
解决方案:
循环里面一直waitForReadyRead()以重置,类要在线程里面new。