您的位置:首页 > 其它

protobuf基于微型嵌入式系统的应用

2015-05-16 21:44 549 查看
智能家居、物联网越来越火热,也是当前的热门应用开发,因此可以预见未来越来越多的微型嵌入式硬件会接入互联网中,因此硬件与服务器的通信就变得越来越重要。

目前谷歌开发的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


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 */

9b1e
message.lucky_number = 13;

/* Now we are ready to encode the message! */
status = pb_encode(&stream, SimpleMessage_fields, &message);
message_length = stream.bytes_written;


解码:

/* 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);


上面的说明很清楚,这里就不在说明。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐