NanoPB:如何在 C 中处理可选字段

另请参阅:C++ 版本:如何在 C++ 中处理可选字段

NanoPB 是一个面向嵌入式系统的代码体积优化的 Protocol Buffers 实现。本文介绍如何在 C 中使用 NanoPB 处理可选字段。

Proto 定义

首先,创建一个包含可选字段的 .proto 文件:

optional.proto
syntax = "proto3";

package example;

message OptionalMessage {
  optional uint32 id = 1;
  optional string name = 2;
  optional float temperature = 3;
  bool active = 4;  // 常规(非可选)字段
}

生成 NanoPB 代码

使用 .options 文件指定字符串缓冲区大小,然后生成 NanoPB 代码:

创建 optional.options

optional.options
example.OptionalMessage.name max_size:64

然后生成:

generate_nanopb_optional.sh
protoc --nanopb_out=. optional.proto

这将生成 optional.pb.hoptional.pb.c

C 示例

下面是一个处理可选字段的完整 C 示例:

optional_example.c
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    // 编码消息的缓冲区
    uint8_t buffer[256];
    size_t message_length;
    
    // --- 编码 ---
    example_OptionalMessage message = example_OptionalMessage_init_zero;
    
    // 设置可选字段
    message.id = 42;
    message.has_id = true;  // 重要:设置 has_* 标志
    
    strncpy(message.name, "Sensor1", sizeof(message.name) - 1);
    message.has_name = true;  // 重要:设置 has_* 标志
    
    message.temperature = 23.5f;
    message.has_temperature = true;  // 重要:设置 has_* 标志
    
    // 常规字段(不需要 has_* 标志)
    message.active = true;
    
    // 创建编码流
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    // 编码消息
    if (!pb_encode(&ostream, example_OptionalMessage_fields, &message)) {
        printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
        return 1;
    }
    
    message_length = ostream.bytes_written;
    printf("Encoded %zu bytes\n", message_length);
    
    // 打印编码数据的十六进制转储
    printf("Encoded data: ");
    for (size_t i = 0; i < message_length; i++) {
        printf("%02x ", buffer[i]);
    }
    printf("\n");
    
    // --- 解码 ---
    example_OptionalMessage decoded = example_OptionalMessage_init_zero;
    
    // 创建解码流
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    // 解码消息
    if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    // 打印解码后的值
    printf("Decoded values:\n");
    if (decoded.has_id) {
        printf("  id: %u\n", (unsigned int)decoded.id);
    } else {
        printf("  id: (not set)\n");
    }
    
    if (decoded.has_name) {
        printf("  name: %s\n", decoded.name);
    } else {
        printf("  name: (not set)\n");
    }
    
    if (decoded.has_temperature) {
        printf("  temperature: %f\n", decoded.temperature);
    } else {
        printf("  temperature: (not set)\n");
    }
    
    printf("  active: %s\n", decoded.active ? "true" : "false");
    
    return 0;
}

编译命令

使用 nanopb 编译该示例。NanoPB 通常通过将源文件直接包含到你的项目来使用:

compile_optional_example.sh
gcc -o optional_example optional_example.c optional.pb.c pb_common.c pb_encode.c pb_decode.c -I.

**注意:**NanoPB 源文件(pb_common.c、pb_encode.c、pb_decode.c)需要直接与你的项目一起编译。你可以从 NanoPB GitHub 仓库 获取这些文件。

Python 测试脚本

为了验证编码,你可以使用 Python 的 protobuf 库:

test_optional.py
import optional_pb2

# 读取二进制数据
with open('encoded.bin', 'rb') as f:
    data = f.read()

# 解码
msg = optional_pb2.OptionalMessage()
msg.ParseFromString(data)

print("Python decoded values:")
print(f"  id: {msg.id if msg.HasField('id') else '(not set)'}")
print(f"  name: {msg.name if msg.HasField('name') else '(not set)'}")
print(f"  temperature: {msg.temperature if msg.HasField('temperature') else '(not set)'}")
print(f"  active: {msg.active}")

首先,编译 Python protobuf 定义:

compile_python_optional.sh
protoc --python_out=. optional.proto

然后修改 C 示例,将编码后的数据保存到文件:

save_encoded_optional.c
// 编码后,添加以下代码:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);

缺少可选字段的示例

下面是一个某些可选字段未设置的示例:

optional_partial_example.c
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    uint8_t buffer[256];
    size_t message_length;
    
    // --- 编码 ---
    example_OptionalMessage message = example_OptionalMessage_init_zero;
    
    // 只设置部分可选字段
    message.id = 42;
    message.has_id = true;
    
    // name 和 temperature 未设置(has_* 标志保持为 false)
    
    // 常规字段总是设置
    message.active = true;
    
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    if (!pb_encode(&ostream, example_OptionalMessage_fields, &message)) {
        printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
        return 1;
    }
    
    message_length = ostream.bytes_written;
    printf("Encoded %zu bytes (partial)\n", message_length);
    
    // --- 解码 ---
    example_OptionalMessage decoded = example_OptionalMessage_init_zero;
    
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    printf("Decoded values:\n");
    printf("  id: %s\n", decoded.has_id ? "set" : "not set");
    printf("  name: %s\n", decoded.has_name ? "set" : "not set");
    printf("  temperature: %s\n", decoded.has_temperature ? "set" : "not set");
    printf("  active: %s\n", decoded.active ? "true" : "false");
    
    return 0;
}

要点

何时使用可选字段

预期输出(完整示例)

optional_full_expected_output.txt
Encoded 19 bytes
Encoded data: 08 2a 12 07 53 65 6e 73 6f 72 31 1d 00 00 bc 41 30 01 
Decoded values:
  id: 42
  name: Sensor1
  temperature: 23.500000
  active: true

预期输出(部分示例)

optional_partial_expected_output.txt
Encoded 4 bytes (partial)
Encoded data: 08 2a 30 01 
Decoded values:
  id: set
  name: not set
  temperature: not set
  active: true

注意部分编码如何变得更小(4 字节对比 19 字节),因为可选字段被省略了。

更多 NanoPB 文章


Check out similar posts by category: Embedded, C/C++, Protocol Buffers