前言:有时我在写二进制传输协议时,当不使用标准的协议传输时每次项目都要想协议的格式,下面的代码实现了一个标准的二进制协议语法,加密使用异或加密,对除载荷外的字段进行了加密,当然如果你的硬件比较好也可以全部加密。当然你也可以用protobuf,这里使用c语言实现,其他语言可以实现
协议格式
//编程网站查看
// http://www.dooccn.com/c/#id/c85fa97f81596701975d3ae7b9346725
//位数一定要和平台相同
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#define LOCK1 'D'
#define LOCK2 'E'
#define R_CODE 0XF1//异或密码
#define RE_SEND_BUFFER 22
//协议1字节对齐
typedef struct{
u8 MsgHead[2];//头字节
u8 MsgLength;//有效数据长度
u8 MsgClass;//消息类
u16 MsgCrc16;//校验
u8 MsgPayLoad[RE_SEND_BUFFER];//消息载荷
}MsgProtocol_t;
//格式化
typedef struct
{
void (*FmtU8)(u8 d);
void (*FmtU16)(u16 d);
void (*FmtU32)(u32 d);
void (*FmtStr)(char* str);
void (*FmtHex)(u8* Dt,u16 len);
void (*FmtHead)(void);
void (*Fmtend)(void);
void (*FmtCmd)(u16 cmd);
void (*FmtCrc16)(void);
u8* (*GetBuffer)(void);
u16 (*GetLength)(void);
}ProtocolFormat_t;
MsgProtocol_t transferProtocol;
ProtocolFormat_t* Vest_TxRxProtocol = NULL;
static u32 SendProtocolLength = 0;
//CRC16高
const u8 CRC_Array_H[] =
{
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,