打包数据可以根据此模式进行修改自己需要的,解包下一篇文章介绍
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define DEBUG printf("%d %s\n",__LINE__,__func__)
typedef unsigned char UCHAR;
typedef unsigned int UINT;
typedef unsigned short UINT16;
/*向平台发送的数据报侦头*/
static UCHAR DDC_head[] =
{
0xA5, 0xA6//帧头
};
/*向平台发送的数据包功能吗*/
static UCHAR CMD_head[] =
{
0x05 //功能码
};
/*向平台发送的数据包校验*/
static UCHAR Crc_end[] =
{
0xFF //数据校验值
};
/*向硬件设备发送的数据报侦头*/
static UCHAR DEV_head[] =
{
0x0A, 0x0B//帧头
};
/*向硬件设备发送的数据包功能吗*/
static UCHAR CMD_DEV[] =
{
0x05 //功能码
};
/*向硬件设备发送的数据包校验*/
static UCHAR Crc_DEV[] =
{
0xFF //数据校验值
};
/*数值型数据转换为字符型*/
int itoc(UINT16 num, UCHAR data[], UINT type)
{
if (data == NULL)
{
return -1;
}
DEBUG;
switch(type)
{
case 4:
data[3] = (UCHAR)((num&0xFF000000)>>24);
case 3:
data[2] = (UCHAR)((num&0xFF0000)>>16);
case 2:
data[1] = (UCHAR)((num&0xFF00)>>8);
case 1:
data[0] = (UCHAR)(num&0xFF);
break;
default:
break;
}
return 0;
}
/***********3.5 DDC上传传感器数据报文*****************/
int pack_ddc(UCHAR *msgall, UCHAR *ddmsg) //参数传输数据ddmsg,打包后的报文:
{
if(msgall == NULL)
return 0;
if(ddmsg == NULL)
return 0;
UINT16 num =(int)( strlen(ddmsg) + 2);
memset(msgall, 0, 4+sizeof(DDC_head)+sizeof(ddmsg));
memcpy(msgall, DDC_head, sizeof(DDC_head)); //报头
UCHAR data[4] = {0};
itoc(num, data, 2);
memcpy(msgall+sizeof(DDC_head), data, 2); //数据长度
memcpy(msgall+sizeof(DDC_head)+2, CMD_head, sizeof(CMD_head)); //功能码
memcpy(msgall+sizeof(DDC_head)+2+sizeof(CMD_head), ddmsg, strlen(ddmsg)); //数据
memcpy(msgall+sizeof(DDC_head)+2+sizeof(CMD_head)+strlen(ddmsg), Crc_end, sizeof(Crc_end));//校验码
return 1;
}
/********************向硬件设备发送信息报文***********************/
int pack_dev(UCHAR * msgall,UCHAR *iD,UCHAR *mes) //参数设备id ,要发送的数据mes,打包数据存储在pack—mes里面
{
if(msgall == NULL)
return 0;
if(mes == NULL)
return 0;
UINT16 num =(int)( strlen(mes) );
UCHAR data[4] = {0};
itoc(num, data, 2);
memset(msgall,0,strlen(mes)+6);
memcpy(msgall, DEV_head, sizeof(DEV_head)); //报头
memcpy(msgall+sizeof(DEV_head),iD, 1); //设备ID
memcpy(msgall+sizeof(DEV_head)+1,CMD_DEV,sizeof(CMD_DEV)); //功能码
memcpy(msgall+sizeof(DEV_head)+1+sizeof(CMD_DEV),data,2); //数据长度
memcpy(msgall+sizeof(DEV_head)+1+sizeof(CMD_DEV)+2,mes,strlen(mes)); //数据段
memcpy(msgall+sizeof(DEV_head)+1+sizeof(CMD_DEV)+2+strlen(mes),Crc_DEV,sizeof(Crc_DEV)); //校验位
return 1;
}
/******** 测试打包情况 ****************/
int main()
{
static UCHAR message[] ={0x12}; //
UCHAR ID[] = {0X01};
UCHAR msgall[1024];
memset(msgall,0,1024);
pack_dev(msgall,ID,message);
//pack_ddc(msgall,message);
int i;
for(i = 0; i<30;i++)
{
printf("%.2x",msgall[i]);
}
printf("\n");
return 0;
}