NanoPB: Umgang mit optionalen Feldern in C

Siehe auch: C++-Version: Umgang mit optionalen Feldern in C++

NanoPB ist eine auf Codegröße optimierte Protocol-Buffers-Implementierung für Embedded-Systeme. Dieser Beitrag zeigt, wie man mit optionalen Feldern in C mit NanoPB umgeht.

Proto-Definition

Erstellen Sie zunächst eine .proto-Datei mit optionalen Feldern:

optional.proto
syntax = "proto3";

package example;

message OptionalMessage {
  optional uint32 id = 1;
  optional string name = 2;
  optional float temperature = 3;
  bool active = 4;  // Regular (non-optional) field
}

NanoPB-Code generieren

Generieren Sie den NanoPB-Code mit einer .options-Datei, um String-Puffergrößen festzulegen:

Erstellen Sie optional.options:

optional.options
example.OptionalMessage.name max_size:64

Dann generieren:

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

Dadurch werden optional.pb.h und optional.pb.c generiert.

C-Beispiel

Hier ist ein vollständiges C-Beispiel, das optionale Felder behandelt:

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() {
    // Buffer for encoded message
    uint8_t buffer[256];
    size_t message_length;
    
    // --- ENCODING ---
    example_OptionalMessage message = example_OptionalMessage_init_zero;
    
    // Set optional fields
    message.id = 42;
    message.has_id = true;  // Important: set has_* flag
    
    strncpy(message.name, "Sensor1", sizeof(message.name) - 1);
    message.has_name = true;  // Important: set has_* flag
    
    message.temperature = 23.5f;
    message.has_temperature = true;  // Important: set has_* flag
    
    // Regular field (no has_* flag needed)
    message.active = true;
    
    // Create stream for encoding
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    // Encode the message
    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);
    
    // Print hex dump of encoded data
    printf("Encoded data: ");
    for (size_t i = 0; i < message_length; i++) {
        printf("%02x ", buffer[i]);
    }
    printf("\n");
    
    // --- DECODING ---
    example_OptionalMessage decoded = example_OptionalMessage_init_zero;
    
    // Create stream for decoding
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    // Decode the message
    if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    // Print decoded values
    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;
}

Kompilierbefehl

Kompilieren Sie das Beispiel mit NanoPB. NanoPB wird typischerweise verwendet, indem die Quelldateien direkt in Ihr Projekt eingebunden werden:

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

Hinweis: NanoPB-Quelldateien (pb_common.c, pb_encode.c, pb_decode.c) müssen direkt mit Ihrem Projekt kompiliert werden. Sie können diese aus dem NanoPB GitHub-Repository beziehen.

Python-Testskript

Um die Kodierung zu überprüfen, können Sie die Python-Protobuf-Bibliothek verwenden:

test_optional.py
import optional_pb2

# Read the binary data
with open('encoded.bin', 'rb') as f:
    data = f.read()

# Decode
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}")

Kompilieren Sie zunächst die Python-Protobuf-Definitionen:

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

Modifizieren Sie dann das C-Beispiel, um die kodierten Daten in einer Datei zu speichern:

save_encoded_optional.c
// After encoding, add this:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);

Beispiel mit fehlenden optionalen Feldern

Hier ist ein Beispiel, bei dem einige optionale Felder nicht gesetzt sind:

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;
    
    // --- ENCODING ---
    example_OptionalMessage message = example_OptionalMessage_init_zero;
    
    // Only set some optional fields
    message.id = 42;
    message.has_id = true;
    
    // name and temperature not set (has_* flags remain false)
    
    // Regular field always set
    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);
    
    // --- DECODING ---
    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;
}

Wesentliche Punkte

Wann optionale Felder verwendet werden sollten

Erwartete Ausgabe (vollständiges Beispiel)

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

Erwartete Ausgabe (partielles Beispiel)

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

Beachten Sie, wie die partielle Kodierung viel kleiner ist (4 Bytes gegenüber 19 Bytes), da optionale Felder weggelassen werden.

Weitere NanoPB-Beiträge


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