c
复制代码
#include <stdio.h>
#include <string.h>
#define uint8_t unsigned char
#define uint32_t unsigned int
#define uint16_t unsigned short
//根据实际模块来
#define REV_D "+IPD"
#define FUN_PAR_OVERFLOW 0xff
//将数组/指针中为0x00的字段全部变成空格号
void buf_clear_0(uint8_t *data, uint8_t lenth)
{
int i=0;
for(i=0; i<lenth; i++ )
{
if(data[i] == '\0')
{
data[i] = ' ';
}
}
}
//查询字符在字符串位置函数
uint8_t find_char_len(uint8_t *str, uint8_t c,uint16_t len)
{
int i=0;
for(i=0; i<len; i++)
{
if(str[i] == c)
{
return i;
}
}
printf("FUN_PAR_OVERFLOW \r\n");
return FUN_PAR_OVERFLOW;
}
//解析命令数据
/*
cmd :解析的命令,
data:原数据,
rev_data:解析得到的数组
rev_data_len:数组长度
blank_on:json字段是否有空格
str_on:是否是字符串(有双引号就是字符串)
*/
uint8_t decode_cmd_data(uint8_t *cmd, uint8_t * data, uint8_t* rev_data,int rev_data_len, uint8_t blank_on, uint8_t str_on)
{
char * tar_str=NULL;
int cmd_len=0;
char blank_len=2;
uint32_t val;
//如果没有空格
if(blank_on == 1)
{
blank_len++;
}
if(str_on == 1)
{
blank_len++;
}
tar_str = (char *)strstr((char *)data, cmd);
if(tar_str != NULL)
{
tar_str = &tar_str[strlen(cmd) + blank_len];
//字符串
if(str_on == 1)
{
cmd_len = find_char_len((uint8_t *)tar_str,'"',rev_data_len);
if(cmd_len == FUN_PAR_OVERFLOW)
{
return ;
}
memcpy(rev_data,tar_str,cmd_len);
}
else
{
val = atoi(tar_str);
memcpy(rev_data,&val,4);
}
//printf("ok\r\n");
return 1; //成功
}
else
{
printf("err\r\n");
return 0; //失败
}
}
//解析json-解析命令
void decode_cmd(uint8_t *data)
{
uint8_t file_name[50]={0};
uint8_t file_ver[20]={0};
uint8_t file_size[20]={0};
uint8_t file_checksum[64]={0};
uint32_t dat_num=0;
if(strstr(data,"START_UPGRADE"))
{
//printf("have dat\r\n");
//printf("%s\r\n",data);
decode_cmd_data("file_name",data,file_name,sizeof(file_name),1,1);
decode_cmd_data("version",data,file_ver,sizeof(file_ver),1,1);
decode_cmd_data("file_size",data,file_size,sizeof(file_size),1,1);
decode_cmd_data("checksum_check",data,file_checksum,sizeof(file_checksum),1,1);
decode_cmd_data("data_num",data,&dat_num,sizeof(dat_num),0,0);
}
printf("file_name: %s\r\n", file_name);
printf("version: %s\r\n", file_ver);
printf("file_size: %s\r\n", file_size);
printf("checksum_check: %s\r\n", file_checksum);
printf("dat_num:%d\r\n", dat_num);
}
//解析json-初步解析
void decode_json(uint8_t * data)
{
uint8_t *str;
str = strstr(data,REV_D);
if(str != NULL)
{
buf_clear_0(str,15);
decode_cmd(str);
}
}
char buf[] = "+IPD: receive:WBS-MYD-V10-00000001\
{\
\"cmd\": \"START_UPGRADE\",\
\"data\": {\
\"version\": \"1.0\",\
\"file_name\": \"V1.0.0.bin\",\
\"file_size\": \"128537\",\
\"checksum_check\": \"67f3b40ba0cbb7d289a9cf6f3f75e6c319f12bdc82d5c35\",\
\"data_num\":132466\
}\
}";
int main()
{
decode_json(buf);
return 0;
}