3

im trying to use nanopb, according to the example: https://github.com/nanopb/nanopb/blob/master/examples/simple/simple.c

the buffer size is initialized to 128:

uint8_t buffer[128];

my question is how do i know (in advance) this 128-length buffer is enough to transmit my message? how to decide a proper(enough but not waste too much due to over-large) size of buffer before initial (or coding) it?

looks like a noob question :) , but thx for your quick suggestion.

furynerd
  • 109
  • 1
  • 8
  • do i need just do some simple calculations? e.g. https://github.com/nanopb/nanopb/blob/master/examples/simple/simple.proto the msg is defined by `int32`, so payload `int32 <= 4 bytes` , with maybe some header/keywords/MagicWords of nanopb decoding, saying 16 bytes, so `4+16 = 20bytes` is ok? – furynerd Sep 27 '21 at 08:36

1 Answers1

2

When possible, nanopb adds a define in the generated .pb.h file that has the maximum encoded size of a message. In the file examples/simple/simple.pb.h you'll find:

/* Maximum encoded size of messages (where known) */
#define SimpleMessage_size                       11

And could specify uint8_t buffer[SimpleMessage_size];.

This define will be available only if all repeated and string fields have been specified (nanopb).max_count and (nanopb).max_size options.

For many practical purposes, you can pick a buffer size that you estimate will be large enough, and handle error conditions. It is also possible to use pb_get_encoded_size() to calculate the encoded size and dynamically allocate storage, but in general that is not a great solution in embedded applications. When total system memory size is limited, it is often better to have a constant sized buffer that you can test with, instead of having the available amount of dynamic memory vary at the runtime.

jpa
  • 10,351
  • 1
  • 28
  • 45