目录结构
if (Singleton::getInstance()->m_extSerialPort == NULL)
{
Singleton::getInstance()->m_extSerialPort = new Win_QextSerialPort(ui->comboBox_SerialPort->currentText(),QextSerialBase::EventDriven);
}
else
{
Singleton::getInstance()->m_extSerialPort->close();
}
Singleton::getInstance()->m_extSerialPort->setPortName(ui->comboBox_SerialPort->currentText());
if (Singleton::getInstance()->m_extSerialPort != NULL)
{
if (Singleton::getInstance()->m_extSerialPort->open(QIODevice::ReadWrite))
{
Singleton::getInstance()->m_extSerialPort->setBaudRate(BAUD115200);//波特率设置,设为115200
Singleton::getInstance()->m_extSerialPort->setDataBits(DATA_8);//数据位设置,设为8位
Singleton::getInstance()->m_extSerialPort->setParity(PAR_NONE);//奇偶校验设置,设为无校验
Singleton::getInstance()->m_extSerialPort->setStopBits(STOP_1);//停止位设置,设为1位停止位
Singleton::getInstance()->m_extSerialPort->setFlowControl(FLOW_OFF);//控制流设置,设为无控制流
}
}
char *sendBuffer = (char*)malloc(FrameLengthWithoutData + 3 +2);//定义发送数组
SerialPortProtocol::CodingSerialport(sendBuffer, SystemConfig, Handshaking, Request, 0);//通信帧封装
sendBuffer[FrameLengthWithoutData + 3] = 0x0d;//帧尾添加0d 0a(换行符)
sendBuffer[FrameLengthWithoutData + 3 +1] = 0x0a;//帧尾添加0d 0a(换行符)
Singleton::getInstance()->m_extSerialPort->write(sendBuffer, FrameLengthWithoutData + 3 +2);//发送
备注:帧尾添加换行符,方便下位机界定数据帧结尾
将readyRead信号与自己的串口接收槽函数绑定,即可响应串口读数据事件
connect(Singleton::getInstance()->m_extSerialPort, &Win_QextSerialPort::readyRead, m_receiveSerialportObj, &ReceiveSerialPortThreadObject::receiveRun);
备注:串口读缓冲区一有字符便会触发readyRead信号,为了保证接收数据帧的完整性,接收槽函数可以循环读(将读到的字符暂存在缓冲数组中)直到读到指定长度的字符(或者帧尾字符)
再进行数据帧解码工作,代码如下
if (Singleton::getInstance()->m_extSerialPort->bytesAvailable() >0)
{
char readbuf[MaxDataLen];
int byte_size = Singleton::getInstance()->m_extSerialPort->readLine(readbuf, MaxDataLen);
if (readbuf[byte_size - 2] != 0x0d || readbuf[byte_size - 1] != 0x0a)
{
bool flag = readbuf[byte_size - 2] == 0x0d && readbuf[byte_size - 1] == 0x0a;
while (!flag)
{
if (Singleton::getInstance()->m_extSerialPort->bytesAvailable() > 0)
{
byte_size += Singleton::getInstance()->m_extSerialPort->readLine(readbuf + byte_size, MaxDataLen);
}
flag = readbuf[byte_size - 2] == 0x0d && readbuf[byte_size - 1] == 0x0a;
}
}
if (byte_size >= (FrameLengthWithoutData + 3 + 2))
{
int datalen = byte_size - FrameLengthWithoutData - 2 - 3;
char* data = (char*)malloc(datalen);
memset(data, 0, datalen);
int leve1comm, leve2comm, flag, curfram, totalfram, device;
if (SerialPortProtocol::DecodingSerialport(readbuf, byte_size - 2, data, &leve1comm, &leve2comm, &flag, &datalen, &curfram, &totalfram, &device))
serialcommand(device, curfram, totalfram, leve1comm, leve2comm, flag, QString(data));
//QString mess(data);
//emit message(mess);
delete data;
}
}