Example of Google Protocol Buffers Serialize and Deserialize with ESP-IDF.
In MQTT for IoT devices, JSON is used as the serialization format of the message.
However, for low-performance hardware, JSON parsing in C is a heavy load.
So when I was looking for a good serialized format that could be implemented in C, I found protobuf.
ESP-IDF includes this Google Protocol Buffers library.
You can use Protocol Buffers components as standard.
But there is no example code in ESP-IDF.
I ported from this.
esp-idf v4.4/v5.x.
git clone https://github.com/nopnop2002/esp-idf-protocol-buffer
cd esp-idf-protocol-buffer
idf.py flash monitor
- Serialize
I (328) MAIN: Writing 4 serialized bytes
I (338) MAIN: 0x3ffaff78 08 0a 10 02 |....|
- DeSerialize
I (338) MAIN: deserialize: a=10
I (348) MAIN: deserialize: b=2
$ sudo apt install protobuf-c-compiler libprotobuf-c-dev
$ protoc-c --version
protobuf-c 1.3.3
libprotoc 3.6.1
$ cat amessage.proto
syntax = "proto2";
message AMessage {
required int32 a=1;
optional int32 b=2;
}
protoc-c generates header files and source code.
$ protoc-c --c_out=. amessage.proto
$ ls amessage.*
amessage.pb-c.c amessage.pb-c.h amessage.proto
$ cp amessage.pb-c.* /your_project/main/
#include "amessage.pb-c.h"
set(component_srcs main.c amessage.pb-c.c)
proto3 is not supported.
An error occurs while building the firmware.
../main/main.c:23:12: error: 'AMessage' {aka 'struct _AMessage'} has no member named 'has_b'
23 | msg.has_b = 1;
| ^
../main/main.c:41:17: error: 'AMessage' {aka 'struct _AMessage'} has no member named 'has_b'
41 | if (msg2->has_b) // handle optional field