qt 记录一个qt串口获取指定格式加密报文的一个函数
1 在字符数据传输时候,设置一个足够的缓冲区尽可能用strcpy函数拷贝,用new申请,可能有bug
2 项目开发需要串口收发数据,但是数据本身开头有乱码,结尾目前还没发现,但是为了保险起见,加上结尾的截断不多于
具体接收代码如下
void ToolInterface::receivedMsg() { info.append(tool->m_serialPort->readAll()); qDebug()<<"interface,,,,,received info 01:"<<info.toHex()<<endl; //经过观察发现开头不是79,但是中间有79//因此要截取数据了 if(!info.isEmpty()) { int len = info.count();//计算长度 //这种写法太费了,但是可以完成任务 // while (1) { // if(info.at(0)==0x79)break; // else info.remove(0,1); // qDebug()<<"interface,,,,,received info:"<<info.toHex()<<endl; // if(info.length()<=0)break; // } //推荐第二种 int tem = info.indexOf(0x79); qDebug()<<"info.indexOf(0x79):"<<tem<<endl; tem>=1?info.remove(0,tem):tem<0?info.clear():""; } qDebug()<<"interface,,,,,received info 02:"<<info.toHex()<<endl; if(!info.isEmpty()) { int len = info.count();//计算长度 //经过观察发现开头不是79,但是中间有79//因此要截取数据了 if(len>=3) { if(info.at(0) == 0x79) { int packetLen = (unsigned char)info.at(2); packetLen<<=8; packetLen+=(unsigned char)info.at(1); // qDebug()<<"receive==================================1"<<len<<packetLen<<endl; // qDebug()<<"debug:"<<info.toHex()<<endl; if(len >= packetLen) { //qDebug()<<"receive==================================2"<<packetLen<<endl; if(info.at(packetLen-1) == 0x37) { len>packetLen? info.remove(packetLen,len-packetLen):"";//数据太长就截断 emit sigReceivedMsg(QString(info.toHex())); qDebug()<<"get sigReceivedMsg(QString(info.toHex())):"<<QString(info.toHex())<<endl; info.clear(); } else { info.clear(); } } } else { info.clear(); } } // else if(len>1024*2) // { // info.clear(); // qDebug() << "data full!" <<endl; // } } }