TLV自定义通信协议的编码和解析

版权声明:转载请附带原博主的网址 https://blog.csdn.net/qq_43260665/article/details/89601831

以下内容均为原创,如有错误,欢迎指正,感激!!!
所有代码都在我的github:
https://github.com/zhanghang1999/Linux/tree/master/TLV
说到通信协议,不得不谈的就是计算机网络中的TCP/IP协议,Linux C提供的网络socketAPI就是基于TCP/IP协议的可靠通信。在计算机网络中,为提高数据传输的可靠性,TCP/IP协议中用到多种对数据的封装和加密来保证接收端收到正确的数据和丢弃错误的数据,而这些"可靠"的接口都是TCP/IP协议隐藏实现直接提供给User的。以往我们见到的数据传输都是基于字符流的(即每个字节由对应的ASCII编码)而现在,我们可以用TLV自定义协议来是实现自己定义"协议"对"字节流(数据流是字节流,即并不是所有字节都是ASCII编码中的一员)"数据的封装和解析。

什么是TLV?

**T(Tag/Type)**所传输数据的类型,自定义,如规定0x01为int类型,则接收端必须使用同样的规定(协议)来解
 析这串数据
**L(Lengh)**    所传输数据的长度(也可以是整帧数据的长度,协议是自定义的,L的定义由协议制定者自己定义
(数据经过协议的封装,最后发送出去的数据串是经过数据链路层的封装形成的最小传输单元--帧))。
**V(Value)**    传输的数据内容。

再用一个例子来加深对此协议的理解:
假设我们现在要发送某地的温度和相对湿度到服务器,温度:0x01,0x02,0x02,0x04(12.24℃)相对湿度0x64(100%)(这里的数据解析由协议制定者来规定)

V:直接传输V(value)如果直接发送。。。。。0x01,0x02,0x02,0x04,0x64。。。
0x01,0x02,0x04,0x04,0x64。。。。。接收方可以解析出温度和湿度,而且会傻傻的一次解析4个字节,如果数据传输
时发生丢失,整帧数据的解析岂不是完全乱了,如果数据传输时发生错误,解析出来一个100℃(笑出声)。。。假
设数据传输完全可靠,如果想再加入一个数据类型如天气,整个传输解析过程要做出大量修改。。。而且数据传输
不可能百分百可靠。	

TLV:加上Tag域同时也要加上Length域,假设Tag(1byte)为数据的类型,假设规定0x01为温度(4byte),0x02为
湿度(1byte),Length(1byte)为整个数据帧的长度,则数据的传输:。。。。**0x01**,0x06,
0x01,0x0,0x02,0x04,**0x02**,0x03,0x64。。。。。。接收端遇到T开始解析,通过数据的Length域来判断解析
的数据的长度,实现对Value的解析,同样,问题仍然没有解决,只是解决了对增加新的数据类型更方便,但是对数
据丢失,变化没有更好的处理,除非数据传输完全可靠。

HTLV:引入H域(Head域)HTLV传输数据,定义H为0xfd,在原来TLV基础上对每个数据包前面加上头Head,接收
方只有遇到Head才开始解析数据,否则丢弃数据,可以很明显的看出,这种方法很好的避免了数据丢失带来的解析
失序,但是不能避免的时当数据包中数据出现0xfd,而此时原数据帧的Head域丢失或者变化,接收端在解析时,会
丢弃变化的Head域,再开始search 0xfd,直到找到Head域才开始解析,而刚好数据域中有一个字节时0xfd,此时数
据将从这开始解析,解析同样会乱套。

HTLVC:引入CRC(Cyclic Redundancy Check)循环冗余检验,形成HTLVC的形式,CRC是一种检错技术,对原
有数据的变化和丢失有很好的检测效果,它的主要工作方式就是对数据的**每一位**(bit而不是byte)进行某种运
算,得出独一无二(相对的独一无二)的FCS(Frame Check Sequence)帧检序列,	将其加在HTLV尾部。CRC
对HTLV的每一位进行计算,得到一个独一无二的数据,并将此数据加在HTLV后面形成数据帧HTLVC,此时接收方
遇到Head域开始对数据进行检测,找到数据的Length域得知数据的长度,再减去CRC的长度,得到数据HTLV,对
数据HTLV进行同样的CRC运算,得到一个CRC值,用此值与源数据包的CRC值进行比较,如果不同,证明数据是
有问题的(HTLVC都可能出错,此时任何一个域出错,都判定此数据出错,则停止解析,继续寻找下一个
Head。。。),如果相同,则证明数据是正确是,并正常解析出Value,**再跳过此帧数据**,继续解析。此外,
CRC技术广泛用于对数据的检测(计算机网络的IP层,数据链路层对数据的封装都会用到CRC校验,为最大可能的
保证数据传输的可靠性),尽管它对数据的计算方式可能不尽相同,但是对同一段数据的解析采用同一种运算的结
果肯定的一样的。

接下来利用socket通信来模拟字节流数据的传输和解析:(在制定协议时,会考虑到大小端字节序的问题,这也同样时自定义协议所要规定的一部分,例如:在socket编程中,采用IPV4来通信时,bind,accept,connect函数对参数struct sockaddr *的要求便是网络字节序(即大端字节序)的family,port,s_addr,倘若此时用小段字节序封装ip,port,和协议族,则server和client端不能通信,这同样时一种协议制定的表现,我制定的协议,如果你不遵守我的协议,你将不能执行下去))
直接先给出CRC算法,对HTLV计算,生成一个两字节的unsigned short:

#include"crc-itu-t.h"
#define MAGIC_CRC           0x1E50
       
const unsigned short crc_itu_t_table[] = {
	0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
	0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
	0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
	0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
	0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
	0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
	0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
	0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
	0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
	0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
	0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
	0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
	0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
	0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
	0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
	0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
	0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
	0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
	0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
	0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
	0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
	0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
	0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
	0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
	0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
	0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
	0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
	0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
	0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
	0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
	0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
	0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
};
static inline unsigned short crc_itu_t_byte(unsigned short crc, const unsigned char data)
{
                return (crc << 8) ^ crc_itu_t_table[((crc >> 8) ^ data) & 0xff];
}

unsigned short crc_itu_t(unsigned short crc, const unsigned char *buffer, unsigned int len)
{
	while (len--)
		crc = crc_itu_t_byte(crc, *buffer++);
	return crc;
}

接下来是对数据的封装函数:(这里我做的比较抽象,分别可以对int,short,double(有规定),unsigned char,char*类型的数据进行解析)

#include<arpa/inet.h>
#include<string.h>
#include<stdio.h>
#include"crc-itu-t.h"
#include"packet.h"
#include"analysis.h"
int create_TLV_msg(unsigned char buf[],int buf_len,int Tag,void *value,int num)
{
    if(!buf||!value||Tag>5||Tag<1||num>=buf_len)
        return num;
    unsigned char  length;
    unsigned short crc,crc_n;
    int            len;
    int            len_s=num;
    if(Tag==TLV_STR)
    {
        char *ptr=(char *)value;
        len=strlen(value);
        length=sizeof(unsigned char)+sizeof(unsigned char)+len+sizeof(unsigned short)+sizeof(unsigned char);//length=H+T+L+V+CRC
        if((buf_len-num-length)<0)//a shortcoming of this function,if the data is too long,this buf will not to accept this data
        {
            return num;
        }
       // printf("%d\n",len);
        buf[num++]=Head;//H
        buf[num++]=Tag;//T
        memcpy(buf+num,&length,sizeof(unsigned char));//L
        num++;
        memcpy(buf+num,ptr,len);//V
        num+=len;
        crc=crc_itu_t(MAGIC_CRC,buf+len_s,num-len_s);
        crc_n=htons(crc);//to big endian
        memcpy(buf+num,&crc_n,sizeof(unsigned short));//C
        return num+=2;
    }
    else if(Tag==TLV_CHR)
    {
        unsigned char *ptr=(unsigned char *)value;
        len=sizeof(unsigned char );
        length=sizeof(unsigned char )+len+sizeof(unsigned short)+sizeof(unsigned char)+sizeof(unsigned char);
        if((buf_len-num-length)<0)
        {
            return num;
        }
        buf[num++]=Head;
        buf[num++]=Tag;
        memcpy(buf+num,&length,sizeof(unsigned char));
        num++;
        memcpy(buf+num,ptr,len);
        num+=len;
        crc=crc_itu_t(MAGIC_CRC,buf+len_s,num-len_s);
        crc_n=htons(crc);
        memcpy(buf+num,&crc_n,sizeof(unsigned short));
        return num+=2;
    }
    else if(Tag==TLV_SHT)
    {
        short val=(htons)(*(short *)value);
        short *ptr=&val;
        len=sizeof(short);
        length=sizeof(unsigned char)+sizeof(unsigned char)+len+sizeof(unsigned short)+sizeof(unsigned char);//length=H+T+L+V+CRC
        if((buf_len-num-length)<0)
        {   
            return num;
        }   
        buf[num++]=Head;//H
        buf[num++]=Tag;//T
        memcpy(buf+num,&length,sizeof(unsigned char));//L
        num++;
        memcpy(buf+num,ptr,len);//V
        num+=len;
        crc=crc_itu_t(MAGIC_CRC,buf+len_s,num-len_s);
        crc_n=htons(crc);//to big endian
        memcpy(buf+num,&crc_n,sizeof(unsigned short));//C
        return num+=2;
    }
    else if(Tag==TLV_INT)
    {
        int val=(htonl)(*(int *)value);
        int *ptr=&val;
        len=sizeof(int);
        length=sizeof(unsigned char)+sizeof(unsigned char)+len+sizeof(unsigned short)+sizeof(unsigned char);//length=H+T+L+V+CRC
        if((buf_len-num-length)<0)
        {
            return num;
        }
        buf[num++]=Head;//H
        buf[num++]=Tag;//T
        memcpy(buf+num,&length,sizeof(unsigned char));//L
        num++;
        memcpy(buf+num,ptr,len);//V
        num+=len;
        crc=crc_itu_t(MAGIC_CRC,buf+len_s,num-len_s);
        crc_n=htons(crc);//to big endian
        memcpy(buf+num,&crc_n,sizeof(unsigned short));//C
        return num+=2;
    }
    else if(Tag==TLV_DOU)
    {
        char ptr=*(double *)value;
        char str=(((int)((*(double *)value)*100))%100);
        len=sizeof(unsigned char )*2;
        length=sizeof(unsigned char)+sizeof(unsigned char)+len+sizeof(unsigned short)+sizeof(unsigned char);//length=H+T+L+V+CRC
        if((buf_len-num-length)<0)
        {
            return num;
        }
        buf[num++]=Head;//H
        buf[num++]=Tag;//T
        memcpy(buf+num,&length,sizeof(unsigned char));//L
        num++;
        memcpy(buf+num,&ptr,sizeof(unsigned char));//V
        num++;
        memcpy(buf+num,&str,sizeof(unsigned char));//V
        num++;
        crc=crc_itu_t(MAGIC_CRC,buf+len_s,num-len_s);
        crc_n=htons(crc);//to big endian(net endian)
        memcpy(buf+num,&crc_n,sizeof(unsigned short));//C
        return num+=2;
    }
}

接下来是对数据的解析:

#include"analysis.h"
#include"crc-itu-t.h"
#include<stdio.h>
#include<string.h>

/* buf:the data's location
 * cmd:the command,1 for byte to short,2 for byte to integer
 */
int byte_to_int(unsigned char *buf,int cmd)
{   //high bytes --------->low bytes
    //for big endian (bytes) to integer or short 
    int val=0;
    int s=0;
    if(!buf)
        return 0;
    if(cmd==1)
    {
        while(s<sizeof(short))
        {
            val+=buf[s++];
            if(s<sizeof(short)) 
                val<<=8;
        }
        return (short)val;
    }
    else if(cmd==2)
    {
        while(s<(sizeof(int)))
        {
            val+=buf[s++];
            if(s<sizeof(int))
            {
                val<<=8;
            }
        }
        return val;
    }
    else if(cmd==3)
    {
        val=buf[s];
        return (unsigned char)val;
    }
}
/* buf:the locaton of the data
 * len:the data's length(for byte)
 * dst:the container of the translated data
 */
void byte_to_string(unsigned char *buf,int len,unsigned char *dst)
{
    if(!buf||len>MAXSIZE||!dst)
        return ;
    memcpy(dst,buf,len);
    dst[len]='\0';
}
/*two bytes to translate,first byte is a integer between -128 to 127,second byte is a decimal between 0  
 * to 1,both have sign*/
double byte_to_double(unsigned char *buf)
{
    double dst;
    if(!buf)
        return 0;
    dst=(char)(*buf)+((double)((char)(*(buf+1))))/100;
    return dst;
}

这里解析实现了对数据帧发送延时的处理,当数据帧发送延时,即某个数据帧只发送了一般,但是还有一部分没发送过来,我们不能直接丢弃这段数据,而是留下来等下一段数据流到来再解析)

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<errno.h>
#include"analysis.h"
#include<unistd.h>
#include"translate.h"
#include"crc-itu-t.h"
int translate(int fd)
{
    if(!fd)
        return -1;
    int bytes=0;
    unsigned char buf_s[MAXSIZE]={'\0'};
    unsigned char buf[MAXSIZE*4]={'\0'};
    int rv=0;
    int i;
    char value_s[MAXSIZE*4]={'\0'};
    int value_i=0;
    double value_d=0.00;
    unsigned short length=0;
    short crc;
    while(1)
    {
        rv=read(fd,buf_s,MAXSIZE);
        if(bytes+rv>MAXSIZE*4)
        {
            printf("This data is to large,we have to throw it\n");
            memset(buf,0,sizeof(buf));
            bytes=0;
            continue;
        }
        if(rv<=0)
        {
            for(i=0;i<bytes;i++)
            {
                printf("0x%02x ",buf[i]);
            }
            printf("Use function read error:%s\n",strerror(errno));
            return -1;
        }
        printf("Read a buffer:%d bytes data\n",rv);
        memcpy(&buf[bytes],buf_s,rv);
        for(i=0;i<bytes+rv;i++)
        {
            if(buf[i]==0xFD)//search head(0xfd) in buffer
            {
                if(rv+bytes-i<6)//find 0xfd in buffer's last five bytes,a complete data packet have at least 6 bytes(1 Head + 1 tag +1 length +2 crc + value(>=1))
                {
                    memset(buf,0,i);
                    memmove(buf,&buf[i],rv+bytes-i);
                    bytes=rv+bytes-i;
                    break;//goto
                }
                if(buf[i+1]==TLV_STR)
                {
                    if(buf[i+2]<6)//a string has at least 6 bytes
                        continue;
                    if(buf[i+2]>(rv+bytes-i))//a string packet can be very big,this packet hasn't tranported completely
                    {
                        memset(buf,0,i);
                        memmove(buf,&buf[i],rv+bytes-i);
                        bytes=rv+bytes-i;
                        break;
                    }
                    length=buf[i+2];
                    crc=crc_itu_t(MAGIC_CRC,&buf[i],length-2);
                    if(((unsigned char *)&crc)[1]==buf[i+length-2]&&((unsigned char *)&crc)[0]==buf[i+length-1])//crc pairing successful
                    {
                        byte_to_string(&buf[i+3],length-5,value_s);
                        printf("Read a string++++:  %s\n",value_s);
                        i+=(length-1);
                        continue;
                    }
                }
                else if(buf[i+1]==TLV_CHR)
                {
                    if(buf[i+2]<6)
                        continue;
                    if(buf[i+2]>(rv+bytes-i))
                    {
                         memset(buf,0,i);
                         memmove(buf,&buf[i],rv+bytes-i);
                         bytes=rv+bytes-i;
                         break;
                    }
                    length=buf[i+2];
                    if(length!=6)
                        continue;
                    crc=crc_itu_t(MAGIC_CRC,&buf[i],length-2);
                    if(((unsigned char *)&crc)[1]==buf[i+length-2]&&((unsigned char *)&crc)[0]==buf[i+length-1])//crc pairing successful
                    { 
                        value_i=byte_to_int(&buf[i+3],3);
                        printf("Read a char++++++:  %d\n",value_i);
                        i+=(length-1);
                        continue; 
                    }
                }
                else if(buf[i+1]==TLV_SHT)
                {
                    if(buf[i+2]<6) 
                        continue; 
                    if(buf[i+2]>(rv+bytes-i))
                    {
                        memset(buf,0,i);
                        memmove(buf,&buf[i],rv+bytes-i);
                        bytes=rv+bytes-i;
                        break;
                    }
                    length=buf[i+2];
                    if(length!=7)
                        continue;
                    crc=crc_itu_t(MAGIC_CRC,&buf[i],length-2);
                    if(((unsigned char *)&crc)[1]==buf[i+length-2]&&((unsigned char *)&crc)[0]==buf[i+length-1])//crc pairing successful
                    {
                        value_i=byte_to_int(&buf[i+3],1);
                        printf("Read a short+++++:  %d\n",value_i);
                        i+=(length-1);
                        continue;
                    }
                }
                else if(buf[i+1]==TLV_INT)
                {
                    if(buf[i+2]<9)
                        continue;
                    if(buf[i+2]>(rv+bytes-i))
                    {
                        memset(buf,0,i);
                        memmove(buf,&buf[i],rv+bytes-i);
                        bytes=rv+bytes-i;
                        break;
                    }
                    length=buf[i+2];
                    if(length!=9)
                        continue;
                    crc=crc_itu_t(MAGIC_CRC,&buf[i],length-2);
                    if(((unsigned char *)&crc)[1]==buf[i+length-2]&&((unsigned char*)&crc)[0]==buf[i+length-1])
                    {
                        value_i=byte_to_int(&buf[i+3],2);
                        printf("read a integer++++:  %d\n",value_i);
                        i+=(length-1);
                        continue;
                    }
                }
                else if(buf[i+1]==TLV_DOU)
                {
                    if(buf[i+2]<7)
                        continue;
                    if(buf[i+2]>(rv+bytes-i))
                    {
                        memset(buf,0,i);
                        memmove(buf,&buf[i],rv+bytes-i);
                        bytes=rv+bytes-i;
                        break;
                    }
                    length=buf[i+2];
                    if(length!=7)
                        continue;
                    crc=crc_itu_t(MAGIC_CRC,&buf[i],length-2);
                    if(((unsigned char *)&crc)[1]==buf[i+length-2]&&((unsigned char *)&crc)[0]==buf[i+length-1])
                    {
                        value_d=byte_to_double(&buf[i+3]);
                        printf("Read a double++++:  %f\n",value_d);
                        i+=(length-1);
                        continue;
                    }
                }
            }     
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43260665/article/details/89601831