How to use nanopb - 10 common examples

To help you get started, we’ve selected a few nanopb examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
for enum in self.enums:
            yield enum.enum_to_string_definition() + '\n'

        # Add checks for numeric limits
        if self.messages:
            largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
            largest_count = largest_msg.count_required_fields()
            if largest_count > 64:
                yield '\n/* Check that missing required fields will be properly detected */\n'
                yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
                yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
                yield '       setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
                yield '#endif\n'

        max_field = FieldMaxSize()
        checks_msgnames = []
        for msg in self.messages:
            checks_msgnames.append(msg.name)
            for field in msg.fields:
                max_field.extend(field.largest_field_value())

        worst = max_field.worst
        worst_field = max_field.worst_field
        checks = max_field.checks

        if worst > 255 or checks:
            yield '\n/* Check that field information fits in pb_field_t */\n'

            if worst > 65535 or checks:
                yield '#if !defined(PB_FIELD_32BIT)\n'
                if worst > 65535:
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
def names_from_type_name(type_name):
    '''Parse Names() from FieldDescriptorProto type_name'''
    if type_name[0] != '.':
        raise NotImplementedError("Lookup of non-absolute type names is not supported")
    return Names(type_name[1:].split('.'))
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
def parse(self):
        self.enums = []
        self.messages = []
        self.extensions = []

        if self.fdesc.package:
            base_name = Names(self.fdesc.package.split('.'))
        else:
            base_name = Names()

        for enum in self.fdesc.enum_type:
            enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
            self.enums.append(Enum(base_name, enum, enum_options))

        for names, message in iterate_messages(self.fdesc, base_name):
            message_options = get_nanopb_suboptions(message, self.file_options, names)

            if message_options.skip_message:
                continue

            self.messages.append(Message(names, message, message_options))
            for enum in message.enum_type:
                enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
                self.enums.append(Enum(names, enum, enum_options))
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
if self.pbtype == 'MESSAGE':
            encsize = None
            if str(self.submsgname) in dependencies:
                submsg = dependencies[str(self.submsgname)]
                encsize = submsg.encoded_size(dependencies)
                if encsize is not None:
                    # Include submessage length prefix
                    encsize += varint_max_size(encsize.upperlimit())

            if encsize is None:
                # Submessage or its size cannot be found.
                # This can occur if submessage is defined in different
                # file, and it or its .options could not be found.
                # Instead of direct numeric value, reference the size that
                # has been #defined in the other file.
                encsize = EncodedSize(self.submsgname + 'size')

                # We will have to make a conservative assumption on the length
                # prefix size, though.
                encsize += 5

        elif self.pbtype in ['ENUM', 'UENUM']:
            if str(self.ctype) in dependencies:
                enumtype = dependencies[str(self.ctype)]
                encsize = enumtype.encoded_size()
            else:
                # Conservative assumption
                encsize = 10

        elif self.enc_size is None:
            raise RuntimeError("Could not determine encoded size for %s.%s"
                               % (self.struct_name, self.name))
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
def parse(self):
        self.enums = []
        self.messages = []
        self.extensions = []

        if self.fdesc.package:
            base_name = Names(self.fdesc.package.split('.'))
        else:
            base_name = Names()

        for enum in self.fdesc.enum_type:
            enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
            self.enums.append(Enum(base_name, enum, enum_options))

        for names, message in iterate_messages(self.fdesc, base_name):
            message_options = get_nanopb_suboptions(message, self.file_options, names)

            if message_options.skip_message:
                continue

            self.messages.append(Message(names, message, message_options))
            for enum in message.enum_type:
                enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
                self.enums.append(Enum(names, enum, enum_options))

        for names, extension in iterate_extensions(self.fdesc, base_name):
            field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
            if field_options.type != nanopb_pb2.FT_IGNORE:
                self.extensions.append(ExtensionField(names, extension, field_options))
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
data = io.open(sys.stdin.fileno(), "rb").read()

    request = plugin_pb2.CodeGeneratorRequest.FromString(data)

    try:
        # Versions of Python prior to 2.7.3 do not support unicode
        # input to shlex.split(). Try to convert to str if possible.
        params = str(request.parameter)
    except UnicodeEncodeError:
        params = request.parameter

    import shlex
    args = shlex.split(params)
    options, dummy = optparser.parse_args(args)

    Globals.verbose_options = options.verbose

    response = plugin_pb2.CodeGeneratorResponse()

    # Google's protoc does not currently indicate the full path of proto files.
    # Instead always add the main file path to the search dirs, that works for
    # the common case.
    import os.path
    options.options_path.append(os.path.dirname(request.file_to_generate[0]))

    # Process any include files first, in order to have them
    # available as dependencies
    other_files = {}
    for fdesc in request.proto_file:
        other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)

    for filename in request.file_to_generate:
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
options, filenames = optparser.parse_args()

    if not filenames:
        optparser.print_help()
        sys.exit(1)

    if options.quiet:
        options.verbose = False

    if options.output_dir and not os.path.exists(options.output_dir):
        optparser.print_help()
        sys.stderr.write("\noutput_dir does not exist: %s\n" % options.output_dir)
        sys.exit(1)


    Globals.verbose_options = options.verbose
    for filename in filenames:
        results = process_file(filename, None, options)

        base_dir = options.output_dir or ''
        to_write = [
            (os.path.join(base_dir, results['headername']), results['headerdata']),
            (os.path.join(base_dir, results['sourcename']), results['sourcedata']),
        ]

        if not options.quiet:
            paths = " and ".join([x[0] for x in to_write])
            sys.stderr.write("Writing to %s\n" % paths)

        for path, data in to_write:
            with open(path, 'w') as f:
                f.write(data)
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
if self.fdesc.package:
            base_name = Names(self.fdesc.package.split('.'))
        else:
            base_name = Names()

        for enum in self.fdesc.enum_type:
            enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
            self.enums.append(Enum(base_name, enum, enum_options))

        for names, message in iterate_messages(self.fdesc, base_name):
            message_options = get_nanopb_suboptions(message, self.file_options, names)

            if message_options.skip_message:
                continue

            self.messages.append(Message(names, message, message_options))
            for enum in message.enum_type:
                enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
                self.enums.append(Enum(names, enum, enum_options))

        for names, extension in iterate_extensions(self.fdesc, base_name):
            field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
            if field_options.type != nanopb_pb2.FT_IGNORE:
                self.extensions.append(ExtensionField(names, extension, field_options))
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
def iterate_extensions(desc, names = Names()):
    '''Recursively find all extensions.
    For each, yield name, FieldDescriptorProto.
    '''
    for extension in desc.extension:
        yield names, extension

    for subname, subdesc in iterate_messages(desc, names):
        for extension in subdesc.extension:
            yield subname, extension
github particle-iot / device-os / nanopb / nanopb / generator / nanopb_generator.py View on Github external
if options.verbose:
                sys.stderr.write('Reading options from ' + optfilename + '\n')
            Globals.separate_options = read_options_file(open(optfilename, "rU"))
            break
    else:
        # If we are given a full filename and it does not exist, give an error.
        # However, don't give error when we automatically look for .options file
        # with the same name as .proto.
        if options.verbose or had_abspath:
            sys.stderr.write('Options file not found: ' + optfilename + '\n')
        Globals.separate_options = []

    Globals.matched_namemasks = set()

    # Parse the file
    file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
    f = ProtoFile(fdesc, file_options)
    f.optfilename = optfilename

    return f