编辑代码

#include <stdio.h>
#include <stdint.h>

// 检测数据头
int Check_Data_Header(uint8_t *data, int data_len)
{
    int i=-1;
    // 只有数据长度大于3,进行数据头检测
    for ( i = 0; i < data_len - 3; i++)
    {
        if (data[i] == 0x40 && data[i + 1] == 0x40 && data[i + 2] == 0x63)
        {
            // 如果检测到数据头,返回数据索引
            return i;
        }
    }
    return -1;
}

// 检测数据尾
int Check_Data_Tail(uint8_t *data, int data_len)
{
    int i = -1;
    // 只有数据长度大于3,进行数据尾检测
    for (i = 0; i < data_len ; i++)
    {
        
        if (data[i-2] == 0x1A && data[i -1] == 0x0D && data[i] == 0x0A)
        {
            // 如果检测到数据头,返回数据索引
            return i;
        }
    }
    return -1;
}




int main () 
{
    uint8_t Protocol_Buf[40]; // 完整的一条协议数据

    // uint8_t TCP_Recv_Buf[]={0x45,0x32, 0x40, 0x40, 0x63, 0x05, 0x00, 0x72, 0x2c, 0x33, 0x31,
    //                         0x56, 0x84, 0xd0, 0x1a, 0x0d, 0x0a,0x56, 0x35};
    uint8_t TCP_Recv_Buf[]={0x40, 0x40, 0x63, 0x05, 0x00, 0x72, 0x2c, 0x33, 0x31,
                            0x56, 0x84, 0xd0, 0x1a, 0x0d, 0x0a};
int data_len = sizeof(TCP_Recv_Buf);
// 2 16  16-2+1
    // 检测数据头
    int header_index = Check_Data_Header(TCP_Recv_Buf, data_len);
    if (header_index >= 0)
    {
        printf("检测到数据头\n");
        int tail_index = Check_Data_Tail(TCP_Recv_Buf, data_len);
        if (tail_index >= 0)
        {
            printf("检测到数据尾\n");

            int protocol_len =tail_index-header_index+1;

            //将完整的一条数据复制到Protocol_Buf
            memcpy(Protocol_Buf, TCP_Recv_Buf+header_index,protocol_len);

            for(int i=0;i<protocol_len;i++)
            {
                printf("%02x ",Protocol_Buf[i]);
            }
uint16_t crc =  Protocol_Buf[protocol_len - 5] | (Protocol_Buf[protocol_len - 4] << 8);

        printf("\nprotocol_len=%d\n",protocol_len);
        printf("%02x \n",Protocol_Buf[protocol_len-5]);
                printf("crc:%04x \n",crc);

        // uint16_t crc=
            // // 解析协议数据
            // Analyze_Protocol_Data(TCP_Recv_Buf, protocol_len);

            // // 移除已处理的数据
            // memmove(TCP_Recv_Buf, TCP_Recv_Buf + header_index + protocol_len, TCP_Recv_Buf_Len - (header_index + protocol_len));
            // TCP_Recv_Buf_Len -= (header_index + protocol_len);
        }
        
    }
    
    return 0;
}