首页 > 代码库 > 【嵌入式程序设计】——消息编解码nanopb
【嵌入式程序设计】——消息编解码nanopb
nanopb最方便的还是在linux下生成C源码文件,编辑好所需要的消息数据结构,通过.proto文件生成C语言代码
To use the nanopb library, you need to do two things:
- Compile your .proto files for nanopb, using protoc.
- Include pb_encode.c, pb_decode.c and pb_common.c in your project.
The easiest way to get started is to study the project in "examples/simple". It contains a Makefile, which should work directly under most Linux systems. However, for any other kind of build system, see the manual steps in README.txt in that folder.
https://github.com/zhoudd1/nanopb
simple.c
message SimpleMessage { required int32 lucky_number = 1;}
#include <stdio.h>#include <pb_encode.h>#include <pb_decode.h>#include "simple.pb.h"int main(){ /* This is the buffer where we will store our message. */ uint8_t buffer[128]; size_t message_length; bool status; /* Encode our message */ { /* 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! * It is a good idea to always initialize your structures * so that you do not have garbage data from RAM in there. */ SimpleMessage message = SimpleMessage_init_zero; /* 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; /* Then just check for any errors.. */ if (!status) { printf("Encoding failed: %s\n", PB_GET_ERROR(&stream)); return 1; } } /* Now we could transmit the message over network, store it in a file or * wrap it to a pigeon‘s leg. */ /* But because we are lazy, we will just decode it immediately. */ { /* Allocate space for the decoded message. */ SimpleMessage message = SimpleMessage_init_zero; /* 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); /* Check for errors... */ if (!status) { printf("Decoding failed: %s\n", PB_GET_ERROR(&stream)); return 1; } /* Print the data contained in the message. */ printf("Your lucky number was %d!\n", message.lucky_number); } return 0;}
【嵌入式程序设计】——消息编解码nanopb
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。