Google Protobuf for C 語言 MCU STM32

Google Protobuf for C

site: https://developers.google.com/protocol-buffers/

描述:

Server 將資料結構透過 protobuf 序列化成 bytes 傳送到 MCU,MCU 透過 protobuf 將 bytes 轉回資料結構。

雙方只要先寫好 .proto 檔案,可轉換成兩端程式語言的 code,

開發人員只需專心於資料內容,不用實作各語言間的序列化實作方法。

編譯 Protobuf:

git clone https://github.com/protocolbuffers/protobuf.git

./autogen.sh

./configure

make

make install

編譯 Protobuf-C (C語言才需要):

git clone https://github.com/protobuf-c/protobuf-c.git

./autogen.sh

./configure

make

make install

編寫 .proto, ,data 為任意大小

syntax = “proto3”;
message FOTA {
int32 id=1;
int32 cmd=2;
bytes data=3;
}

ex: Python –>  C語言

產生 Python code

protoc –python_out=./ FOTA.proto

產生: FOTA_pb2.py

支援語言:

–cpp_out=OUT_DIR Generate C++ header and source.
–csharp_out=OUT_DIR Generate C# source file.
–java_out=OUT_DIR Generate Java source file.
–js_out=OUT_DIR Generate JavaScript source.
–objc_out=OUT_DIR Generate Objective C header and source.
–php_out=OUT_DIR Generate PHP source file.
–python_out=OUT_DIR Generate Python source file.
–ruby_out=OUT_DIR Generate Ruby source file.

產生 C code:

protoc-c –c_out=./ FOTA.proto

產生: FOTA.pb-c.c  FOTA.pb-c.h

添加 protobuf-c libary、產生的 code 至 MCU code:

example: MCU 解包  Server 傳來的資料:

FOTA *fota_ptr;
void *buf_rev;
unsigned len_rev;
/*此處省略,收到 server 傳送的 buf_rev */
fota_ptr = fota__unpack(NULL,len_rev,buf_rev);
/*fota_ptr 資料結構已自動生成 */
printf(“id = %d”,fota_ptr->id);

fota__free_unpacked(fota_ptr,NULL);
free(buf_rev);

MCU 傳給 Server:

FOTA fota = FOTA__INIT;

void *buf; //buf to store the serialized data
unsigned len;
void *buf_rev;
unsigned len_rev;
fota.id= 1
fota.cmd = 1;
fota.data.data = (uint8_t *)”hello”;
fota.data.len = 6;

len = fota__get_packed_size(&fota);
buf = malloc(len);
fota__pack(&fota,buf); 
/* 此處將 buf 傳送給 Server */

free(buf);
未經允許不得轉載:GoMCU » Google Protobuf for C 語言 MCU STM32