一、 串行通信使用固定数据包格式防止粘包
#include <stdio.h>
#include <string.h>
#define BUFFER_LENGTH 128
#define GB_OK 1
#define GB_NG 0
unsigned char buffer[BUFFER_LENGTH];
int bufferHead;
int bufferTail;
int NextIndex(int index,int length,int offset)
{
index += offset;
if(index >= length)
{
index -= length;
}
return index;
}
int GetPacket(unsigned char *packet,int *pPacketLength)
{
int index = bufferHead;
int nextIndex = NextIndex(index,BUFFER_LENGTH,1);
while(index != bufferTail && nextIndex != bufferTail)
{
if (buffer[index] == 0xfa && buffer[nextIndex] == 0xfb)
{
int bufferLength = bufferTail - index;
if(bufferLength < 0) {bufferLength += BUFFER_LENGTH;}
if(bufferLength < 6){ return GB_NG;}
int dataLength= buffer[NextIndex(index,BUFFER_LENGTH,6)] | (buffer[NextIndex(index,BUFFER_LENGTH,7)] <<8);
if(bufferLength >= 12 + dataLength
&& buffer[NextIndex(index,BUFFER_LENGTH,10 + dataLength)] == 0xfc
&& buffer[NextIndex(index,BUFFER_LENGTH,11 + dataLength)] == 0xfd)
{
*pPacketLength = dataLength+12;
for(int i=0;i<*pPacketLength;i++)
{
packet[i] = buffer[NextIndex(index,BUFFER_LENGTH,i)];
}
bufferHead = NextIndex(index,BUFFER_LENGTH,*pPacketLength);
return GB_OK;
}
}
index = nextIndex;
nextIndex = NextIndex(index,BUFFER_LENGTH,1);
}
return GB_NG;
}
void PrintPacket(unsigned char *packet,int packetLength)
{
for(int i=0;i<packetLength;i++)
{
printf("0x%x ",packet[i]);
}
printf("\n");
}
int main() {
unsigned char packet[128];
int packetLength;
printf("========================================================================================================\n");
printf("测试1\n");
unsigned char buffer1[] = {0xfa,0xfb,0x00,0x00,0x01,0x00,0x01,0x00,0x00,0xcc,0xdd,0xfc,0xfd};
memcpy(buffer,buffer1,sizeof(buffer1)/sizeof(buffer1[0]));
bufferHead = 0;
bufferTail = sizeof(buffer1)/sizeof(buffer1[0]);
int getFlag = GetPacket(packet,&packetLength);
if(getFlag == GB_OK)
{
printf("获取数据包成功\n");
PrintPacket(packet,packetLength);
}else
{
printf("获取数据包失败\n");
}
printf("bufferHead:%d\n",bufferHead);
printf("bufferHead:%d\n",bufferTail);
printf("========================================================================================================\n");
printf("测试2\n");
unsigned char buffer2[] = {0xfa,0xfb,0xfa,0xfb,0x00,0x00,0xff,0x00,0x01,0x00,0x00,0xcc,0xdd,0xfc,0xfd};
memcpy(buffer,buffer2,sizeof(buffer2)/sizeof(buffer2[0]));
bufferHead = 0;
bufferTail = sizeof(buffer2)/sizeof(buffer2[0]);
getFlag = GetPacket(packet,&packetLength);
if(getFlag == GB_OK)
{
printf("获取数据包成功\n");
PrintPacket(packet,packetLength);
}else
{
printf("获取数据包失败\n");
}
printf("bufferHead:%d\n",bufferHead);
printf("bufferHead:%d\n",bufferTail);
return 0;
}
printFloatInfo(-9.25);
return 0;
}