Nanopb Protocol Buffers Generator

0.4.9.1 · active · verified Thu Apr 16

Nanopb is a small code-size Protocol Buffers implementation in ANSI C, primarily suitable for microcontrollers and other memory-restricted systems. The Python library component provides the `nanopb_generator.py` script, which compiles `.proto` definition files into C header (`.h`) and source (`.c`) files that can then be used with the Nanopb C runtime. The project is actively maintained, with versions typically released a few times a year, addressing bug fixes and minor improvements, such as the latest 0.4.9.1 release from December 2024.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple Protocol Buffer message and then use the `nanopb_generator.py` script to generate the corresponding C header and source files for use with the Nanopb C runtime. It assumes `nanopb`, `protobuf`, and `grpcio-tools` are already installed.

# 1. Define your Protocol Buffer message in a .proto file (e.g., example.proto):
# message SimpleMessage {
#   required int32 value = 1;
# }

# 2. Run the nanopb generator script:
import subprocess
import os

proto_content = """
syntax = "proto2";

message SimpleMessage {
  required int32 value = 1;
}
"""

with open("example.proto", "w") as f:
    f.write(proto_content)

# Ensure protobuf and grpcio-tools are installed
try:
    import google.protobuf
    print("google.protobuf module found.")
except ImportError:
    print("google.protobuf not found. Please install with: pip install protobuf grpcio-tools")
    exit(1)

# Specify the path to the generator script
# In an installed package, it's usually found via -m
generator_path = "nanopb.generator.nanopb_generator"

print(f"Generating C files from example.proto using {generator_path}...")
try:
    # Using python -m for installed package
    result = subprocess.run(
        ["python", "-m", generator_path, "example.proto"],
        capture_output=True, text=True, check=True
    )
    print("STDOUT:", result.stdout)
    print("STDERR:", result.stderr)
    print("Successfully generated example.pb.h and example.pb.c")

    # Verify output files exist (optional)
    if os.path.exists("example.pb.h") and os.path.exists("example.pb.c"):
        print("Output files example.pb.h and example.pb.c found.")
    else:
        print("Error: Generated files not found.")

except subprocess.CalledProcessError as e:
    print(f"Error during generation: {e}")
    print("STDOUT:", e.stdout)
    print("STDERR:", e.stderr)
    print("Make sure 'protoc' is available in your PATH or installed via grpcio-tools.")
except FileNotFoundError as e:
    print(f"Error: Python or the generator script was not found. {e}")

# Clean up generated files
# os.remove("example.proto")
# if os.path.exists("example.pb.h"): os.remove("example.pb.h")
# if os.path.exists("example.pb.c"): os.remove("example.pb.c")

view raw JSON →