protobuf 在单片机系统中的使用

转载:

目前谷歌开发的protobuf库由于运行速度快、体积小、用起来更简单等特点。其协议在通信方面使用越来越广泛。对于在主流开发系统上使用protobuf通信只需将.proto利用protoc生成相应的编码文件,然后调用相关的库与接口就可以方便的使用。但如果需要将protobuf应用在嵌入式领域特别是微型嵌入式领域时,而微型系统无法支持庞大的库文件,通信起来看起来变得不那么容易。

下面就介绍protobuf在微型嵌入式领域的解决方案:nanopb 
源码下载:https://github.com/nanopb/nanopb 
如果不想编译而是想直接使用,请参考下面链接: 
http://koti.kapsi.fi/~jpa/nanopb/download/

使用介绍,这里以nanopb-0.3.3 linux下环境为例: 
1、解压nanopb-0.3.3-linux-x86.tar.gz

$tar vxf nanopb-0.3.3-linux-x86.tar.gz
1
2、进入主目录里面就会有pb_encode、pb_decode、pb_common几个文件,这是几个很重要的文件,用于微型嵌入式开发中对protobuf协议进行编码与解码用的。

3、进入generator-bin目录,里面有protoc可执行文件,可以将proto文件生成微型嵌入式系统用的*pb.c、*pb.h, 这里以项目里面的simple为例: 
$../../generator-bin/protoc –nanopb_out=. simple.proto 
此时就可以将编译后就生成了相关的pb.c与pb.h文件

4、现在就可以使用了,这里可以通过simple里面的Makefile文件发现编译时需要指定相关的protobuf库,只需要指定第二步所说的几个相关文件就可以生成相关的可执行文件。 


5、simple的源码分析 
编码:

     /* Allocate space on the stack to store the message data.
         *
         * Nanopb generates simple struct definitions for all the messages.
         * - check out the contents of simple.pb.h! */
        SimpleMessage message;

        /* Create a stream that will write to our buffer. */
        pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));

        /* Fill in the lucky number */
        message.lucky_number = 13; 

        /* Now we are ready to encode the message! */
        status = pb_encode(&stream, SimpleMessage_fields, &message);
        message_length = stream.bytes_written;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
解码:

 /* Allocate space for the decoded message. */
        SimpleMessage message;

        /* Create a stream that reads from the buffer. */
        pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);

        /* Now we are ready to decode the message. */
        status = pb_decode(&stream, SimpleMessage_fields, &message);
1
2
3
4
5
6
7
8
9

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值