当前位置:   article > 正文

protocol buffer协议的两种常用框架protobuf和nanopb

nanopb

目录

目录

什么是protocol buffer

1.protobuf

1.1安装

 1.2使用

2.nanopb(支持c语言)

2.1解压压缩包

2.2使用nanopb

3.3python解析nanopb生成的二进制数据


什么是protocol buffer

百度百科解释如下
  protocolbuffer(以下简称PB)是google 的一种数据交换的格式,它独立于语言,独立于平台。google 提供了多种语言的实现:java、c#、c++、go 和 python,每一种实现都包含了相应语言的编译器以及库文件。
由于它是一种二进制的格式,比使用 xml 进行数据交换快许多。可以把它用于分布式应用之间的数据通信或者异构环境下的数据交换。
作为一种效率和兼容性都很优秀的二进制数据传输格式,可以用于诸如网络传输、配置文件、数据存储等诸多领域。

PB和json,xml比较:
一条消息数据,用protobuf序列化后的大小是json的10分之一,xml格式的20分之一,是二进制序列化的10分之一,总体看来PB的优势还是很明显的。
简单说来PB的主要优点就是:简单,快。缺点:可读性差

PB协议处理常用的两种框架protobuf和nanopb进行介绍

1.protobuf

protobuf是PB协议使用较广的一个框架,支持C++,JAVA,Python,Ruby,Go,PHP等多种语言,具体如下:

1.1安装

(1)protobuf源码git地址
https://gitcode.net/mirrors/google/protobuf?utm_source=csdn_github_accelerator
(2)protobuf各发行版本地址
https://github.com/protocolbuffers/protobuf/tags
例如下载protobuf-all-3.6.1.tar.gz


tar -zxvf protobuf-all-3.6.1.tar.gz
cd protobuf-3.6.1 
检测安装环境和生成Makefile
./configure --prefix=/home/tiger/protobuf-3.6.1/protobuf 

编译和安装
make && make install


安装完成后在目录/home/tiger/protobuf-3.6.1/protobuf下可以看到三个文件夹:


bin:存放protoc可执行程序
include:调用protobuf所需头文件
lib:调用protobuf所需库文件
查看protoc版本:
cd bin
./protoc --version

 

 1.2使用

参考文章:

java中使用protobuf总结

python中读写Protobuf总结

python中protobuf和json互相转换应用

2.nanopb(支持c语言)

protobuf支持多种语言,但是却不支持纯C语言,而且protobuf的使用笨重,在一些内存紧张的嵌入式设备上不能使用,nanopb是谷歌协议缓冲数据格式的一个纯C实现。它的目标是32位微控制器,但也适用于其他嵌入式系统的严格(< 10kB ROM,< 1kB RAM)内存限制。
源码下载地址如下:
https://jpa.kapsi.fi/nanopb/download/

2.1解压压缩包

此处以版本0.3.9.4为例子进行说明
tar -zxvf nanopb-0.3.9.4-linux-x86.tar.gz 

2.2使用nanopb

cd nanopb-0.3.9.4-linux-x86
如下7个文件是nanopb用来处理protocol buffer协议的核心文件

  1. pb_common.c
  2. pb_common.h
  3. pb_decode.c
  4. pb_decode.h
  5. pb_encode.c
  6. pb_encode.h
  7. pb.h

定义协议:

metric.proto

syntax = "proto3";

package com.union.fun;

option optimize_for = LITE_RUNTIME;

enum MetricStatus {

UNKNOWN = 0;

IDLE = 1;

BUSY = 2;

}

message Metric {

string name = 1;// [nanopb.max_length = 40];

string type = 2;

float value = 3;

repeated string tags = 4;// [(nanopb).max_length = 40, (nanopb).max_count = 5];

int32 id = 5;

repeated string remarks = 6;

MetricStatus status = 7;

bytes version = 8;

}

metric.options

com.union.fun.Metric.name max_length:40 
com.union.fun.Metric.tags max_size:40 max_count:5

生成实现文件:
生成器根据metric.proto生成对应的实现文件和头文件metric.pb.h 和 metric.pb.c

/home/tiger/nanopb-0.3.9.4-linux-x86/generator-bin/protoc  --nanopb_out=. metric.proto

查看各个字段名称

/home/tiger/nanopb-0.3.9.4-linux-x86/generator-bin/protoc  --nanopb_out=-v:. metric.proto

C++方式如下:

/home/tiger/nanopb-0.3.9.4-linux-x86/generator-bin/protoc  --cpp_out=./ metric.proto

1)string类型使用注意
在nanopb中,string类型在生成c语言文件的时候,会有两种结构,一种是指定了最大长度的,一种是没有指定最大长度.指定了最大长度的string,会生成char[] 数组类型,
没有指定最大长度的,会生成pb_callback_t类型.具体的可以参照nanopb文档(https://jpa.kapsi.fi/nanopb/docs/concepts.html#compiling-proto-files-for-nanopb)


2).proto中optimize_for的参数
option optimize_for = LITE_RUNTIME;
optimize_for是文件级别的选项,Protocol Buffer定义三种优化级别SPEED/CODE_SIZE/LITE_RUNTIME。缺省情况下是SPEED。
SPEED: 表示生成的代码运行效率高,但是由此生成的代码编译后会占用更多的空间。
CODE_SIZE: 和SPEED恰恰相反,代码运行效率较低,但是由此生成的代码编译后会占用更少的空间,通常用于资源有限的平台,如Mobile。
LITE_RUNTIME: 生成的代码执行效率高,同时生成代码编译后的所占用的空间也是非常少。这是以牺牲Protocol Buffer提供的反射功能为代价的。因此我们在C++中链接Protocol Buffer库时仅需链接libprotobuf-lite,而非libprotobuf。
在Java中仅需包含protobuf-java-2.4.1-lite.jar,而非protobuf-java-2.4.1.jar。
注:对于LITE_MESSAGE选项而言,其生成的代码均将继承自MessageLite,而非Message。

3)pb_callback_t结构

pb_callback_t 是一个结构体,有两个成员变量,一个是回调函数指针,这个回调函数是一个union,在编码的时候,需要赋值encode函数,解码的时候赋值decode,如果不赋值,则该属性值会忽略.
另外一个变量是arg,这是一个指针,会在回调函数中作为最后一个参数传递给回调函数.
typedef struct pb_callback_s pb_callback_t;
struct pb_callback_s {
#ifdef PB_OLD_CALLBACK_STYLE
    /* Deprecated since nanopb-0.2.1 */
    union {
        bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void *arg);
        bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, const void *arg);
    } funcs;
#else
    /* New function signature, which allows modifying arg contents in callback. */
    union {
        bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void **arg);
        bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, void * const *arg);
    } funcs;
#endif    
    
    /* Free arg for use by callback */
    void *arg;
};

struct _pb_ostream_t
{
   bool (*callback)(pb_ostream_t *stream, const uint8_t *buf, size_t count);
   void *state;
   size_t max_size;
   size_t bytes_written;
};

struct _pb_istream_t
{
   bool (*callback)(pb_istream_t *stream, uint8_t *buf, size_t count);
   void *state;
   size_t bytes_left;
};

调用举例:

项目结构:

 main.c

  1. #include "metric.pb.h"
  2. #include "nanopb_tools.h"
  3. #define DATA_BUFFER_SIZE 1024
  4. bool write_string_list(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  5. {
  6. char *str = *arg;
  7. if (!pb_encode_tag_for_field(stream, field))
  8. return false;
  9. printf("write_string_list %s\n", str);
  10. return pb_encode_string(stream, (uint8_t*)str, strlen(str));
  11. }
  12. //打包
  13. static int pack_data(uint8_t *buffer)
  14. {
  15. com_union_fun_Metric metric = com_union_fun_Metric_init_zero;
  16. memset(buffer, 0, DATA_BUFFER_SIZE);
  17. char name[41];
  18. pb_callback_t type;
  19. float value;
  20. pb_size_t tags_count;
  21. char tags[5][40];
  22. int32_t id;
  23. pb_callback_t remarks;
  24. com_union_fun_MetricStatus status;
  25. pb_callback_t version;
  26. strcpy(metric.name, "liudehua");
  27. metric.type.funcs.encode = write_string;
  28. metric.type.arg = &"welcome to using nanopb";
  29. metric.value = 99.01;
  30. metric.tags_count = 5;
  31. for (int i = 0; i < 5; i++) {
  32. sprintf(metric.tags[i], "%d ok", i);
  33. }
  34. metric.id = 110;
  35. //metric.remarks.funcs.encode = &write_string_list;
  36. //metric.remarks.arg = &"hello hello hello hello hello";
  37. metric.status = com_union_fun_MetricStatus_BUSY;
  38. metric.version.funcs.encode = &nanopb_encode_map_bytes;
  39. char strVersion[128] = {0};
  40. strcpy(strVersion, "V1.0.0.1");
  41. struct pb_bytes_array byteData;
  42. byteData.size = strlen(strVersion);
  43. byteData.bytes = (uint8_t*)strVersion;
  44. metric.version.arg = &byteData;
  45. pb_ostream_t enc_stream;
  46. enc_stream = pb_ostream_from_buffer(buffer, DATA_BUFFER_SIZE);
  47. if (!pb_encode(&enc_stream, com_union_fun_Metric_fields, &metric))
  48. {
  49. printf("pb_encode error in %s [%s]\n", __func__, PB_GET_ERROR(&enc_stream));
  50. return -1;
  51. }
  52. return enc_stream.bytes_written;
  53. }
  54. //解包
  55. static int unpack_data(const uint8_t *buffer, size_t len)
  56. {
  57. com_union_fun_Metric metric;
  58. metric.type.funcs.decode = read_ints;
  59. char tmp[128] = {0};
  60. metric.type.arg = &tmp;
  61. metric.version.funcs.decode = nanopb_decode_map_bytes;
  62. metric.version.arg = NULL;
  63. pb_istream_t dec_stream;
  64. dec_stream = pb_istream_from_buffer(buffer, len);
  65. if (!pb_decode(&dec_stream, com_union_fun_Metric_fields, &metric))
  66. {
  67. printf("pb_decodeerror in %s [%s]\n", __func__, PB_GET_ERROR(&dec_stream));
  68. return -1;
  69. }
  70. for (int i = 0; i < 5; i++) {
  71. printf("unpack_data: %d %s %s %f %s %d %s\n",
  72. metric.id, metric.name, tmp, metric.value, metric.tags[i], metric.status, (char*)metric.version.arg);
  73. }
  74. nanopb_release_map_bytes(&metric.version);
  75. return 0;
  76. }
  77. int main(int argc,char *argv[])
  78. {
  79. uint8_t buffer[DATA_BUFFER_SIZE];
  80. int lenght = pack_data(buffer);
  81. if(lenght < 0) {
  82. printf("pack_data fail \n");
  83. return -1;
  84. }
  85. printf("pack_data len: %d\n", lenght);
  86. unpack_data(buffer, lenght);
  87. return 0;
  88. }

metric.pb.h

  1. /* Automatically generated nanopb header */
  2. /* Generated by nanopb-0.3.9.4 at Mon Mar 13 20:12:37 2023. */
  3. #ifndef PB_COM_UNION_FUN_METRIC_PB_H_INCLUDED
  4. #define PB_COM_UNION_FUN_METRIC_PB_H_INCLUDED
  5. #include <pb.h>
  6. /* @@protoc_insertion_point(includes) */
  7. #if PB_PROTO_HEADER_VERSION != 30
  8. #error Regenerate this file with the current version of nanopb generator.
  9. #endif
  10. #ifdef __cplusplus
  11. extern "C" {
  12. #endif
  13. /* Enum definitions */
  14. typedef enum _com_union_fun_MetricStatus {
  15. com_union_fun_MetricStatus_UNKNOWN = 0,
  16. com_union_fun_MetricStatus_IDLE = 1,
  17. com_union_fun_MetricStatus_BUSY = 2
  18. } com_union_fun_MetricStatus;
  19. #define _com_union_fun_MetricStatus_MIN com_union_fun_MetricStatus_UNKNOWN
  20. #define _com_union_fun_MetricStatus_MAX com_union_fun_MetricStatus_BUSY
  21. #define _com_union_fun_MetricStatus_ARRAYSIZE ((com_union_fun_MetricStatus)(com_union_fun_MetricStatus_BUSY+1))
  22. /* Struct definitions */
  23. typedef struct _com_union_fun_Metric {
  24. char name[41];
  25. pb_callback_t type;
  26. float value;
  27. pb_size_t tags_count;
  28. char tags[5][40];
  29. int32_t id;
  30. pb_callback_t remarks;
  31. com_union_fun_MetricStatus status;
  32. pb_callback_t version;
  33. /* @@protoc_insertion_point(struct:com_union_fun_Metric) */
  34. } com_union_fun_Metric;
  35. /* Default values for struct fields */
  36. /* Initializer values for message structs */
  37. #define com_union_fun_Metric_init_default {"", {{NULL}, NULL}, 0, 0, {"", "", "", "", ""}, 0, {{NULL}, NULL}, _com_union_fun_MetricStatus_MIN, {{NULL}, NULL}}
  38. #define com_union_fun_Metric_init_zero {"", {{NULL}, NULL}, 0, 0, {"", "", "", "", ""}, 0, {{NULL}, NULL}, _com_union_fun_MetricStatus_MIN, {{NULL}, NULL}}
  39. /* Field tags (for use in manual encoding/decoding) */
  40. #define com_union_fun_Metric_name_tag 1
  41. #define com_union_fun_Metric_type_tag 2
  42. #define com_union_fun_Metric_value_tag 3
  43. #define com_union_fun_Metric_tags_tag 4
  44. #define com_union_fun_Metric_id_tag 5
  45. #define com_union_fun_Metric_remarks_tag 6
  46. #define com_union_fun_Metric_status_tag 7
  47. #define com_union_fun_Metric_version_tag 8
  48. /* Struct field encoding specification for nanopb */
  49. extern const pb_field_t com_union_fun_Metric_fields[9];
  50. /* Maximum encoded size of messages (where known) */
  51. /* com_union_fun_Metric_size depends on runtime parameters */
  52. /* Message IDs (where set with "msgid" option) */
  53. #ifdef PB_MSGID
  54. #define METRIC_MESSAGES \
  55. #endif
  56. #ifdef __cplusplus
  57. } /* extern "C" */
  58. #endif
  59. /* @@protoc_insertion_point(eof) */
  60. #endif

metric.pb.c

  1. /* Automatically generated nanopb constant definitions */
  2. /* Generated by nanopb-0.3.9.4 at Mon Mar 13 20:12:37 2023. */
  3. #include "metric.pb.h"
  4. /* @@protoc_insertion_point(includes) */
  5. #if PB_PROTO_HEADER_VERSION != 30
  6. #error Regenerate this file with the current version of nanopb generator.
  7. #endif
  8. const pb_field_t com_union_fun_Metric_fields[9] = {
  9. PB_FIELD( 1, STRING , SINGULAR, STATIC , FIRST, com_union_fun_Metric, name, name, 0),
  10. PB_FIELD( 2, STRING , SINGULAR, CALLBACK, OTHER, com_union_fun_Metric, type, name, 0),
  11. PB_FIELD( 3, FLOAT , SINGULAR, STATIC , OTHER, com_union_fun_Metric, value, type, 0),
  12. PB_FIELD( 4, STRING , REPEATED, STATIC , OTHER, com_union_fun_Metric, tags, value, 0),
  13. PB_FIELD( 5, INT32 , SINGULAR, STATIC , OTHER, com_union_fun_Metric, id, tags, 0),
  14. PB_FIELD( 6, STRING , REPEATED, CALLBACK, OTHER, com_union_fun_Metric, remarks, id, 0),
  15. PB_FIELD( 7, UENUM , SINGULAR, STATIC , OTHER, com_union_fun_Metric, status, remarks, 0),
  16. PB_FIELD( 8, BYTES , SINGULAR, CALLBACK, OTHER, com_union_fun_Metric, version, status, 0),
  17. PB_LAST_FIELD
  18. };
  19. /* @@protoc_insertion_point(eof) */

nanopb_tools.h

  1. #ifndef _NANOPB_TOOL_H_
  2. #define _NANOPB_TOOL_H_
  3. #include "pb.h"
  4. #include "pb_encode.h"
  5. #include "pb_decode.h"
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. struct pb_bytes_array {
  10. int size;
  11. uint8_t* bytes;
  12. };
  13. bool write_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg);
  14. bool read_ints(pb_istream_t *stream, const pb_field_t *field, void **arg);
  15. /**
  16. * nanopb库解析bytes类型
  17. *
  18. * @param [in] stream nanop:b输入数据流
  19. * @param [in] field proto对象属性域数组
  20. * @param [in] arg callback回调的参数(外部传入NULL即可,内存动态申请内存)
  21. *
  22. * @return 是否解析成功
  23. * @note: nanopb在解析不定长对象时需要指定解析的回调函数,为了方便,解析string类型,封装该方法
  24. *
  25. */
  26. bool nanopb_decode_map_bytes(pb_istream_t *stream, const pb_field_t *field, void **arg);
  27. //
  28. bool nanopb_decode_map_string(pb_istream_t *stream, const pb_field_t *field, void **arg);
  29. /**
  30. * nanopb库构造string 类型buffer
  31. *
  32. * @param [in] stream nanop:b输入数据流
  33. * @param [in] field proto对象属性域数组
  34. * @param [in] arg callback回调的参数(外部传入)
  35. *
  36. * @return 是否解析成功
  37. * @note: nanopb在解析不定长对象时需要指定解析的回调函数,为了方便,解析string类型,封装该方法
  38. *
  39. */
  40. bool nanopb_encode_map_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg);
  41. bool nanopb_encode_map_bytes(pb_ostream_t *stream, const pb_field_t *field, void * const *arg);
  42. /**
  43. * nanopb库释放callback申请的heap内存
  44. *
  45. * @param [in] pCallBack 指向callback申请内存的指针
  46. *
  47. * @return N/A
  48. * @note:
  49. *
  50. */
  51. void nanopb_release_map_string(pb_callback_t* pCallBack);
  52. /**
  53. * nanopb库释放callback申请的heap内存
  54. *
  55. * @param [in] pCallBack 指向callback申请内存的指针
  56. *
  57. * @return N/A
  58. * @note:
  59. *
  60. */
  61. void nanopb_release_map_bytes(pb_callback_t* pCallBack);
  62. /**
  63. * nanopb库设置string类型
  64. *
  65. * @param [in] pCallBack string的callback
  66. * @param [in] pSrcChar 源字符串
  67. * @return N/A
  68. * @note: nanopb的字符串类型赋值封装接口,内部会申请内存
  69. *
  70. */
  71. void nanopb_map_set_string(pb_callback_t* pCallBack, const char* pSrcChar);
  72. #endif

nanopb_tools.c

  1. #include "nanopb_tools.h"
  2. bool write_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  3. {
  4. char *str = *arg;
  5. if (!pb_encode_tag_for_field(stream, field))
  6. return false;
  7. // printf("11111111111111111\n");
  8. return pb_encode_string(stream, (uint8_t*)str, strlen(str));
  9. }
  10. bool read_ints(pb_istream_t *stream, const pb_field_t *field, void **arg)
  11. {
  12. int i=0;
  13. char* tmp = *arg;
  14. while (stream->bytes_left)
  15. {
  16. uint64_t value;
  17. if (!pb_decode_varint(stream, &value))
  18. return false;
  19. *(tmp+i)=value;
  20. i++;
  21. // printf("222222222222222222\n");
  22. }
  23. return true;
  24. }
  25. /**
  26. * nanopb库解析bytes类型
  27. *
  28. * @param [in] stream nanop:b输入数据流
  29. * @param [in] field proto对象属性域数组
  30. * @param [in] arg callback回调的参数(外部传入NULL即可,内存动态申请内存)
  31. *
  32. * @return 是否解析成功
  33. * @note: nanopb在解析不定长对象时需要指定解析的回调函数,为了方便,解析string类型,封装该方法
  34. *
  35. */
  36. bool nanopb_decode_map_bytes(pb_istream_t *stream, const pb_field_t *field, void **arg)
  37. {
  38. #if 1
  39. if (*arg != NULL)
  40. {
  41. free(*arg);
  42. *arg = NULL;
  43. }
  44. #else
  45. if (*arg != NULL)
  46. {
  47. pb_bytes_array* pBytes = (pb_bytes_array*)*arg;
  48. if (pBytes->bytes)
  49. {
  50. free(pBytes->bytes);
  51. pBytes->bytes = NULL;
  52. }
  53. pBytes->size = 0;
  54. delete[] pBytes;
  55. *arg = NULL;
  56. }
  57. #endif
  58. #if 1
  59. size_t alloc_size = 0;
  60. bool status = false;
  61. size_t size = stream->bytes_left;
  62. /* Space for null terminator */
  63. alloc_size = size + 1;
  64. if (alloc_size < size) {
  65. PB_RETURN_ERROR(stream, "size too large");
  66. }
  67. char* pData = (char*)malloc(alloc_size);
  68. if (!pData) {
  69. return false;
  70. }
  71. memset(pData, 0, alloc_size);
  72. status = pb_read(stream, (uint8_t*)pData, size);
  73. *((uint8_t*)pData + size) = 0;
  74. *arg = pData;
  75. #else
  76. pb_bytes_array* pDest = new pb_bytes_array;
  77. if (!pDest)
  78. return V_FALSE;
  79. bool status;
  80. size_t alloc_size = stream->bytes_left;
  81. pDest->bytes = (uint8_t*)malloc(alloc_size);
  82. if (!pDest->bytes)
  83. {
  84. delete pDest;
  85. return V_TRUE;
  86. }
  87. pDest->size = alloc_size;
  88. memset(pDest->bytes, 0, alloc_size);
  89. status = pb_read(stream, (uint8_t*)pDest->bytes, pDest->size);
  90. *arg = pDest;
  91. #endif
  92. return status;
  93. }
  94. //
  95. bool nanopb_decode_map_string(pb_istream_t *stream, const pb_field_t *field, void **arg)
  96. {
  97. if ( *arg != NULL )
  98. {
  99. free(*arg);
  100. *arg = NULL;
  101. }
  102. size_t alloc_size;
  103. bool status;
  104. //if (!pb_decode_varint32(stream, &size))
  105. // return false;
  106. size_t size = stream->bytes_left;
  107. /* Space for null terminator */
  108. alloc_size = size + 1;
  109. if (alloc_size < size)
  110. PB_RETURN_ERROR(stream, "size too large");
  111. char* pData = (char*)malloc( alloc_size );
  112. if ( !pData )
  113. return false;
  114. memset(pData, 0, alloc_size);
  115. status = pb_read(stream, (uint8_t*)pData, size);
  116. *((uint8_t*)pData + size) = 0;
  117. *arg = pData;
  118. return status;
  119. }
  120. /**
  121. * nanopb库构造string 类型buffer
  122. *
  123. * @param [in] stream nanop:b输入数据流
  124. * @param [in] field proto对象属性域数组
  125. * @param [in] arg callback回调的参数(外部传入)
  126. *
  127. * @return 是否解析成功
  128. * @note: nanopb在解析不定长对象时需要指定解析的回调函数,为了方便,解析string类型,封装该方法
  129. *
  130. */
  131. bool nanopb_encode_map_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  132. {
  133. if ( !stream || !field )
  134. return false;
  135. int nLen = 0;
  136. if ( *arg )
  137. {
  138. nLen = strlen((const char *)*arg);
  139. }
  140. return pb_encode_tag_for_field(stream, field) &&
  141. pb_encode_string(stream, (const uint8_t *)*arg, nLen);
  142. }
  143. bool nanopb_encode_map_bytes(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  144. {
  145. if (!stream || !field)
  146. return false;
  147. const struct pb_bytes_array *bytes = (const struct pb_bytes_array*)*arg;
  148. if (bytes == NULL)
  149. {
  150. printf("nanopb_encode_map_bytes 1\n");
  151. /* Threat null pointer as an empty bytes field */
  152. return pb_encode_string(stream, NULL, 0);
  153. }
  154. printf("nanopb_encode_map_bytes 2\n");
  155. return pb_encode_tag_for_field(stream, field) &&
  156. pb_encode_string(stream, (const uint8_t *)bytes->bytes, bytes->size);
  157. }
  158. /**
  159. * nanopb库释放callback申请的heap内存
  160. *
  161. * @param [in] pCallBack 指向callback申请内存的指针
  162. *
  163. * @return N/A
  164. * @note:
  165. *
  166. */
  167. void nanopb_release_map_string(pb_callback_t* pCallBack)
  168. {
  169. if ( !pCallBack || !pCallBack->arg )
  170. return;
  171. char* pData = (char*)pCallBack->arg;
  172. if ( pData )
  173. {
  174. free(pData);
  175. pCallBack->arg = NULL;
  176. }
  177. }
  178. /**
  179. * nanopb库释放callback申请的heap内存
  180. *
  181. * @param [in] pCallBack 指向callback申请内存的指针
  182. *
  183. * @return N/A
  184. * @note:
  185. *
  186. */
  187. void nanopb_release_map_bytes(pb_callback_t* pCallBack)
  188. {
  189. if ( !pCallBack || !pCallBack->arg )
  190. return;
  191. #if 1
  192. char* pData = (char*)pCallBack->arg;
  193. if (pData)
  194. {
  195. free(pData);
  196. pCallBack->arg = NULL;
  197. }
  198. #else
  199. pb_bytes_array* pBytes = (pb_bytes_array*)pCallBack->arg;
  200. if (pBytes->bytes)
  201. {
  202. free(pBytes->bytes);
  203. pBytes->bytes = V_NULL;
  204. }
  205. pBytes->size = 0;
  206. delete pBytes;
  207. pCallBack->arg = V_NULL;
  208. #endif
  209. }
  210. /**
  211. * nanopb库设置string类型
  212. *
  213. * @param [in] pCallBack string的callback
  214. * @param [in] pSrcChar 源字符串
  215. * @return N/A
  216. * @note: nanopb的字符串类型赋值封装接口,内部会申请内存
  217. *
  218. */
  219. void nanopb_map_set_string(pb_callback_t* pCallBack, const char* pSrcChar)
  220. {
  221. if(!pCallBack || !pSrcChar)
  222. return;
  223. int nLen = strlen(pSrcChar);
  224. pCallBack->arg = malloc(nLen+1);
  225. memset( pCallBack->arg, 0, nLen+1 );
  226. if ( pCallBack->arg )
  227. {
  228. memcpy(pCallBack->arg, pSrcChar, nLen);
  229. }
  230. }

编译:

gcc -I . main.c metric.pb.c pb_common.c pb_decode.c  pb_encode.c nanopb_tools.c

执行:

./a.out

运行结果:

源码下载

3.3python解析nanopb生成的二进制数据

  1. #include "metric.pb.h"
  2. #include "nanopb_tools.h"
  3. #define DATA_BUFFER_SIZE 1024
  4. bool write_string_list(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
  5. {
  6. char *str = *arg;
  7. if (!pb_encode_tag_for_field(stream, field))
  8. return false;
  9. printf("write_string_list %s\n", str);
  10. return pb_encode_string(stream, (uint8_t*)str, strlen(str));
  11. }
  12. //打包
  13. static int pack_data(uint8_t *buffer)
  14. {
  15. com_union_fun_Metric metric = com_union_fun_Metric_init_zero;
  16. memset(buffer, 0, DATA_BUFFER_SIZE);
  17. char name[41];
  18. pb_callback_t type;
  19. float value;
  20. pb_size_t tags_count;
  21. char tags[5][40];
  22. int32_t id;
  23. pb_callback_t remarks;
  24. com_union_fun_MetricStatus status;
  25. pb_callback_t version;
  26. strcpy(metric.name, "liudehua");
  27. metric.type.funcs.encode = write_string;
  28. metric.type.arg = &"welcome to using nanopb";
  29. metric.value = 99.01;
  30. metric.tags_count = 5;
  31. for (int i = 0; i < 5; i++) {
  32. sprintf(metric.tags[i], "%d ok", i);
  33. }
  34. metric.id = 110;
  35. //metric.remarks.funcs.encode = &write_string_list;
  36. //metric.remarks.arg = &"hello hello hello hello hello";
  37. metric.status = com_union_fun_MetricStatus_BUSY;
  38. metric.version.funcs.encode = &nanopb_encode_map_bytes;
  39. char strVersion[128] = {0};
  40. strcpy(strVersion, "V1.0.0.1");
  41. struct pb_bytes_array byteData;
  42. byteData.size = strlen(strVersion);
  43. byteData.bytes = (uint8_t*)strVersion;
  44. metric.version.arg = &byteData;
  45. pb_ostream_t enc_stream;
  46. enc_stream = pb_ostream_from_buffer(buffer, DATA_BUFFER_SIZE);
  47. if (!pb_encode(&enc_stream, com_union_fun_Metric_fields, &metric))
  48. {
  49. printf("pb_encode error in %s [%s]\n", __func__, PB_GET_ERROR(&enc_stream));
  50. return -1;
  51. }
  52. return enc_stream.bytes_written;
  53. }
  54. //解包
  55. static int unpack_data(const uint8_t *buffer, size_t len)
  56. {
  57. com_union_fun_Metric metric;
  58. metric.type.funcs.decode = read_ints;
  59. char tmp[128] = {0};
  60. metric.type.arg = &tmp;
  61. metric.version.funcs.decode = nanopb_decode_map_bytes;
  62. metric.version.arg = NULL;
  63. pb_istream_t dec_stream;
  64. dec_stream = pb_istream_from_buffer(buffer, len);
  65. if (!pb_decode(&dec_stream, com_union_fun_Metric_fields, &metric))
  66. {
  67. printf("pb_decodeerror in %s [%s]\n", __func__, PB_GET_ERROR(&dec_stream));
  68. return -1;
  69. }
  70. for (int i = 0; i < 5; i++) {
  71. printf("unpack_data: %d %s %s %f %s %d %s\n",
  72. metric.id, metric.name, tmp, metric.value, metric.tags[i], metric.status, (char*)metric.version.arg);
  73. }
  74. nanopb_release_map_bytes(&metric.version);
  75. return 0;
  76. }
  77. int main(int argc,char *argv[])
  78. {
  79. uint8_t buffer[DATA_BUFFER_SIZE];
  80. int lenght = pack_data(buffer);
  81. if(lenght < 0) {
  82. printf("pack_data fail \n");
  83. return -1;
  84. }
  85. FILE* fp = fopen("metric.bin", "wb");
  86. fwrite(buffer, sizeof(uint8_t), lenght, fp);
  87. fwrite(buffer, sizeof(uint8_t), lenght, fp);
  88. fwrite(buffer, sizeof(uint8_t), lenght, fp);
  89. fclose(fp);
  90. fp = NULL;
  91. printf("pack_data len: %d\n", lenght);
  92. unpack_data(buffer, lenght);
  93. return 0;
  94. }

运行结果如下:

从运行结果可以看出每个对象84字节 , 将3个nanopb生成的PB对象存放在metric.bin

利用Python解析读取

/home/tiger/protobuf-3.6.1/protobuf/bin/protoc -I=/home/tiger/nanopb  --python_out=/home/tiger/nanopb  metric.proto

test_nanopb.py

  1. """
  2. This is the main module.
  3. """
  4. #coding=utf-8
  5. import sys
  6. import os
  7. import argparse
  8. import metric_pb2
  9. '''
  10. /home/tiger/protobuf-3.6.1/protobuf/bin/protoc -I=/home/tiger/nanopb --python_out=/home/tiger/nanopb metric.proto
  11. python3 test_nanopb.py -f=metric.bin
  12. '''
  13. def main(pbfile):
  14. print("main start ...", pbfile)
  15. index = 0
  16. with open(pbfile, 'rb') as f:
  17. buf = f.read()
  18. while index < len(buf):
  19. data = buf[index : index+84]
  20. index += 84
  21. #print(data)
  22. read_metric = metric_pb2.Metric()
  23. read_metric.ParseFromString(data)
  24. print(read_metric)
  25. print("================")
  26. if __name__ == "__main__":
  27. #print(sys.argv)
  28. parser = argparse.ArgumentParser()
  29. parser.add_argument(
  30. '-f', '--file', dest='pbfile', type=str, default="anpVehicleData.log",
  31. help='input pb file'
  32. )
  33. parser.add_argument(
  34. '-s', '--start', dest='startpos', default=123, required=False,
  35. help='input start postion'
  36. )
  37. parser.add_argument(
  38. '-e', '--end', dest='endpos', default=456, required=False,
  39. help='input end postion'
  40. )
  41. args = parser.parse_args()
  42. pbfile = args.pbfile
  43. startpos = args.startpos
  44. endpos = args.endpos
  45. print("pbfile:", pbfile)
  46. print("startpos:", startpos)
  47. print("endpos:", endpos)
  48. main(pbfile)

执行Python脚本:python3 test_nanopb.py -f=metric.bin

可以看到三个PB对象被成功解析出来 

说明:另一种支持c语言的框架是protobuf-c,此处不再说明

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/763444
推荐阅读
相关标签
  

闽ICP备14008679号