一、将串口数据接收到循环队列中
串口定义
std::shared_ptr<QSerialPort> m_serialPort;
m_serialPort = std::make_shared<QSerialPort>();
connect(m_serialPort.get(), &QSerialPort::readyRead, this, &CDevProcess::SlotReadDyReadData);
串口数据放入循环队列
void CDevProcess::SlotReadDyReadData()
{
QByteArray recvData = m_serialPort->readAll();
if (recvData.isEmpty())
{
return;
}
CDataArray dataArray;
dataArray.m_data = recvData;
m_dataQueue.EnQueue(dataArray);
}
二、取循环队列数据加入缓存,从缓存中提取每帧数据
在线程中处理数据
void CDevProcess::run()
{
while (m_bRunning)
{
if(m_dataQueue.GetSize() > 0)
{
CDataArray dataArray;
if (m_dataQueue.DeQueue(dataArray))
{
m_RecvData.append(dataArray.m_data);
}
}
for (int i = 0; i < m_RecvData.size(); i++)
{
if (m_RecvData.size() < 4)
{
break;
}
QByteArray byteHead = m_RecvData.mid(i, 2);
QDataStream stream(&byteHead, QIODevice::ReadOnly);
stream.setByteOrder(QDataStream::BigEndian);
uint16_t u16DataHead;
stream >> u16DataHead;
switch (u16DataHead)
{
case 0xAA55:
{
QByteArray byteLen = m_RecvData.mid(i + 2, 2);
QDataStream stream(&byteLen, QIODevice::ReadOnly);
stream.setByteOrder(QDataStream::BigEndian);
uint16_t u16DataLen;
stream >> u16DataLen;
if (u16DataLen != CICD_ADY_DATA::E_MSG_LEN) //长度
{
break;
}
QByteArray sendData = m_RecvData.mid(i, 4 + u16DataLen);
if (sendData.size() != (4 + u16DataLen))
{
break;
}
emit SigRealData(sendData);
m_RecvData.remove(i, 4 + u16DataLen);
}break;
case 0xAA56: //4字节数据头
{
QByteArray byteLen = m_RecvData.mid(i + 2, 2);
QDataStream stream(&byteLen, QIODevice::ReadOnly);
stream.setByteOrder(QDataStream::BigEndian);
uint16_t u16DataLen;
stream >> u16DataLen;
if (u16DataLen != CICD_BDY_DATA::E_MSG_LEN) //长度
{
break;
}
QByteArray sendData = m_RecvData.mid(i, 4 + u16DataLen);
if (sendData.size() != (4 + u16DataLen))
{
break;
}
emit SigRealData(sendData);
m_RecvData.remove(i, 4 + u16DataLen);
}break;
case 0xAA66: //3字节数据头
{
QByteArray byteLen = m_RecvData.mid(i + 2, 1);
QDataStream stream(&byteLen, QIODevice::ReadOnly);
stream.setByteOrder(QDataStream::BigEndian);
uint8_t u8DataLen;
stream >> u8DataLen;
if (u8DataLen != 1)
{
break;
}
QByteArray sendData = m_RecvData.mid(i, 3 + u8DataLen);
if (sendData.size() != (3 + u8DataLen))
{
break;
}
emit SigRealData(sendData);
m_RecvData.remove(i, 3 + u8DataLen);
}break;
default:
break;
}
}
}
}
循环队列链接 C++【循环队列模板】