项目场景:
通过UBUS发送复杂的json字符串,使用blob的接口组包
问题描述
我在网上查了很久,都是讲blob的原理,或者API接口。没有一个demo参考。今天在这边写一个demo 方便大家参考
效果:
{
"ZRVIBRATION-1": [
{
"ts": 1104762309438,
"values": {
"HZ": 2009.000000,
"T": 26.000000
}
}
]
}
解决方案:
代码展示
/* 获取时间戳 ms */
uint64_t Get_time_stam(void)
{
struct timeval time_iot;
gettimeofday(&time_iot, NULL);
return (uint64_t)time_iot.tv_sec * 1000 + (uint64_t)time_iot.tv_usec / 1000;
}
char id[50] = "ZRVIBRATION-1";
int main()
{
char *str;
struct blob_buf data_buf;
memset(&data_buf, 0, sizeof(struct blob_buf));
blob_buf_init(&data_buf, 0);
b = blobmsg_open_array(&data_buf,"ZRVIBRATION-1");
e = blobmsg_open_table(&data_buf,NULL);
blobmsg_add_u64(&data_buf,"ts",Get_time_stam());
c = blobmsg_open_table(&data_buf,"values");
blobmsg_add_double(&data_buf,vibserver.vnamehz,263.2);
blobmsg_add_double(&data_buf,vibserver.vnameT,26);
blobmsg_close_table(&data_buf,c);
blobmsg_close_table(&data_buf,e);
blobmsg_close_array(&data_buf,b);
/* 这一句是个关键,把组建好的blob 转换为字符串,然后打印出来看看 */
str = blobmsg_format_json_indent(data_buf.head, true, 0);
printf("%s\n",str);
free(str);
str = NULL;
}