93aae8b0e4f660279b630e10a4cbb83a35db2757
[apps/agl-service-can-low-level.git] / docs / reference.rst
1 =====================
2 Nanopb: API reference
3 =====================
4
5 .. include :: menu.rst
6
7 .. contents ::
8
9 Compilation options
10 ===================
11 The following options can be specified using -D switch given to the C compiler:
12
13 ============================  ================================================================================================
14 __BIG_ENDIAN__                 Set this if your platform stores integers and floats in big-endian format.
15                                Mixed-endian systems (different layout for ints and floats) are currently not supported.
16 NANOPB_INTERNALS               Set this to expose the field encoder functions that are hidden since nanopb-0.1.3.
17 PB_MAX_REQUIRED_FIELDS         Maximum number of required fields to check for presence. Default value is 64. Increases stack
18                                usage 1 byte per every 8 fields. Compiler warning will tell if you need this.
19 PB_FIELD_16BIT                 Add support for tag numbers > 255 and fields larger than 255 bytes or 255 array entries.
20                                Increases code size 3 bytes per each field. Compiler error will tell if you need this.
21 PB_FIELD_32BIT                 Add support for tag numbers > 65535 and fields larger than 65535 bytes or 65535 array entries.
22                                Increases code size 9 bytes per each field. Compiler error will tell if you need this.
23 PB_NO_ERRMSG                   Disables the support for error messages; only error information is the true/false return value.
24                                Decreases the code size by a few hundred bytes.
25 PB_BUFFER_ONLY                 Disables the support for custom streams. Only supports encoding to memory buffers.
26                                Speeds up execution and decreases code size slightly.
27 ============================  ================================================================================================
28
29 The PB_MAX_REQUIRED_FIELDS, PB_FIELD_16BIT and PB_FIELD_32BIT settings allow raising some datatype limits to suit larger messages.
30 Their need is recognized automatically by C-preprocessor #if-directives in the generated .pb.h files. The default setting is to use
31 the smallest datatypes (least resources used).
32
33 pb.h
34 ====
35
36 pb_type_t
37 ---------
38 Defines the encoder/decoder behaviour that should be used for a field. ::
39
40     typedef uint8_t pb_type_t;
41
42 The low-order nibble of the enumeration values defines the function that can be used for encoding and decoding the field data:
43
44 ==================== ===== ================================================
45 LTYPE identifier     Value Storage format
46 ==================== ===== ================================================
47 PB_LTYPE_VARINT      0x00  Integer.
48 PB_LTYPE_SVARINT     0x01  Integer, zigzag encoded.
49 PB_LTYPE_FIXED32     0x02  32-bit integer or floating point.
50 PB_LTYPE_FIXED64     0x03  64-bit integer or floating point.
51 PB_LTYPE_BYTES       0x04  Structure with *size_t* field and byte array.
52 PB_LTYPE_STRING      0x05  Null-terminated string.
53 PB_LTYPE_SUBMESSAGE  0x06  Submessage structure.
54 ==================== ===== ================================================
55
56 The bits 4-5 define whether the field is required, optional or repeated:
57
58 ==================== ===== ================================================
59 HTYPE identifier     Value Field handling
60 ==================== ===== ================================================
61 PB_HTYPE_REQUIRED    0x00  Verify that field exists in decoded message.
62 PB_HTYPE_OPTIONAL    0x10  Use separate *has_<field>* boolean to specify
63                            whether the field is present.
64                            (Unless it is a callback)
65 PB_HTYPE_REPEATED    0x20  A repeated field with preallocated array.
66                            Separate *<field>_count* for number of items.
67                            (Unless it is a callback)
68 ==================== ===== ================================================
69
70 The bits 6-7 define the how the storage for the field is allocated:
71
72 ==================== ===== ================================================
73 ATYPE identifier     Value Allocation method
74 ==================== ===== ================================================
75 PB_ATYPE_STATIC      0x00  Statically allocated storage in the structure.
76 PB_ATYPE_CALLBACK    0x40  A field with dynamic storage size. Struct field
77                            actually contains a pointer to a callback
78                            function.
79 ==================== ===== ================================================
80
81
82 pb_field_t
83 ----------
84 Describes a single structure field with memory position in relation to others. The descriptions are usually autogenerated. ::
85
86     typedef struct _pb_field_t pb_field_t;
87     struct _pb_field_t {
88         uint8_t tag;
89         pb_type_t type;
90         uint8_t data_offset;
91         int8_t size_offset;
92         uint8_t data_size;
93         uint8_t array_size;
94         const void *ptr;
95     } pb_packed;
96
97 :tag:           Tag number of the field or 0 to terminate a list of fields.
98 :type:          LTYPE, HTYPE and ATYPE of the field.
99 :data_offset:   Offset of field data, relative to the end of the previous field.
100 :size_offset:   Offset of *bool* flag for optional fields or *size_t* count for arrays, relative to field data.
101 :data_size:     Size of a single data entry, in bytes. For PB_LTYPE_BYTES, the size of the byte array inside the containing structure. For PB_HTYPE_CALLBACK, size of the C data type if known.
102 :array_size:    Maximum number of entries in an array, if it is an array type.
103 :ptr:           Pointer to default value for optional fields, or to submessage description for PB_LTYPE_SUBMESSAGE.
104
105 The *uint8_t* datatypes limit the maximum size of a single item to 255 bytes and arrays to 255 items. Compiler will give error if the values are too large. The types can be changed to larger ones by defining *PB_FIELD_16BIT*.
106
107 pb_bytes_array_t
108 ----------------
109 An byte array with a field for storing the length::
110
111     typedef struct {
112         size_t size;
113         uint8_t bytes[1];
114     } pb_bytes_array_t;
115
116 In an actual array, the length of *bytes* may be different.
117
118 pb_callback_t
119 -------------
120 Part of a message structure, for fields with type PB_HTYPE_CALLBACK::
121
122     typedef struct _pb_callback_t pb_callback_t;
123     struct _pb_callback_t {
124         union {
125             bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void *arg);
126             bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, const void *arg);
127         } funcs;
128         
129         void *arg;
130     };
131
132 The *arg* is passed to the callback when calling. It can be used to store any information that the callback might need.
133
134 When calling `pb_encode`_, *funcs.encode* is used, and similarly when calling `pb_decode`_, *funcs.decode* is used. The function pointers are stored in the same memory location but are of incompatible types. You can set the function pointer to NULL to skip the field.
135
136 pb_wire_type_t
137 --------------
138 Protocol Buffers wire types. These are used with `pb_encode_tag`_. ::
139
140     typedef enum {
141         PB_WT_VARINT = 0,
142         PB_WT_64BIT  = 1,
143         PB_WT_STRING = 2,
144         PB_WT_32BIT  = 5
145     } pb_wire_type_t;
146
147 pb_encode.h
148 ===========
149
150 pb_ostream_from_buffer
151 ----------------------
152 Constructs an output stream for writing into a memory buffer. This is just a helper function, it doesn't do anything you couldn't do yourself in a callback function. It uses an internal callback that stores the pointer in stream *state* field. ::
153
154     pb_ostream_t pb_ostream_from_buffer(uint8_t *buf, size_t bufsize);
155
156 :buf:           Memory buffer to write into.
157 :bufsize:       Maximum number of bytes to write.
158 :returns:       An output stream.
159
160 After writing, you can check *stream.bytes_written* to find out how much valid data there is in the buffer.
161
162 pb_write
163 --------
164 Writes data to an output stream. Always use this function, instead of trying to call stream callback manually. ::
165
166     bool pb_write(pb_ostream_t *stream, const uint8_t *buf, size_t count);
167
168 :stream:        Output stream to write to.
169 :buf:           Pointer to buffer with the data to be written.
170 :count:         Number of bytes to write.
171 :returns:       True on success, false if maximum length is exceeded or an IO error happens.
172
173 If an error happens, *bytes_written* is not incremented. Depending on the callback used, calling pb_write again after it has failed once may be dangerous. Nanopb itself never does this, instead it returns the error to user application. The builtin pb_ostream_from_buffer is safe to call again after failed write.
174
175 pb_encode
176 ---------
177 Encodes the contents of a structure as a protocol buffers message and writes it to output stream. ::
178
179     bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
180
181 :stream:        Output stream to write to.
182 :fields:        A field description array, usually autogenerated.
183 :src_struct:    Pointer to the data that will be serialized.
184 :returns:       True on success, false on IO error, on detectable errors in field description, or if a field encoder returns false.
185
186 Normally pb_encode simply walks through the fields description array and serializes each field in turn. However, submessages must be serialized twice: first to calculate their size and then to actually write them to output. This causes some constraints for callback fields, which must return the same data on every call.
187
188 .. sidebar:: Encoding fields manually
189
190     The functions with names *pb_encode_\** are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, `pb_encode`_ will call your callback function, which in turn will call *pb_encode_\** functions repeatedly to write out values.
191
192     The tag of a field must be encoded separately with `pb_encode_tag_for_field`_. After that, you can call exactly one of the content-writing functions to encode the payload of the field. For repeated fields, you can repeat this process multiple times.
193
194     Writing packed arrays is a little bit more involved: you need to use `pb_encode_tag` and specify `PB_WT_STRING` as the wire type. Then you need to know exactly how much data you are going to write, and use `pb_encode_varint`_ to write out the number of bytes before writing the actual data. Substreams can be used to determine the number of bytes beforehand; see `pb_encode_submessage`_ source code for an example.
195
196 pb_encode_tag
197 -------------
198 Starts a field in the Protocol Buffers binary format: encodes the field number and the wire type of the data. ::
199
200     bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, int field_number);
201
202 :stream:        Output stream to write to. 1-5 bytes will be written.
203 :wiretype:      PB_WT_VARINT, PB_WT_64BIT, PB_WT_STRING or PB_WT_32BIT
204 :field_number:  Identifier for the field, defined in the .proto file. You can get it from field->tag.
205 :returns:       True on success, false on IO error.
206
207 pb_encode_tag_for_field
208 -----------------------
209 Same as `pb_encode_tag`_, except takes the parameters from a *pb_field_t* structure. ::
210
211     bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field);
212
213 :stream:        Output stream to write to. 1-5 bytes will be written.
214 :field:         Field description structure. Usually autogenerated.
215 :returns:       True on success, false on IO error or unknown field type.
216
217 This function only considers the LTYPE of the field. You can use it from your field callbacks, because the source generator writes correct LTYPE also for callback type fields.
218
219 Wire type mapping is as follows:
220
221 ========================= ============
222 LTYPEs                    Wire type
223 ========================= ============
224 VARINT, SVARINT           PB_WT_VARINT
225 FIXED64                   PB_WT_64BIT  
226 STRING, BYTES, SUBMESSAGE PB_WT_STRING 
227 FIXED32                   PB_WT_32BIT
228 ========================= ============
229
230 pb_encode_varint
231 ----------------
232 Encodes a signed or unsigned integer in the varint_ format. Works for fields of type `bool`, `enum`, `int32`, `int64`, `uint32` and `uint64`::
233
234     bool pb_encode_varint(pb_ostream_t *stream, uint64_t value);
235
236 :stream:        Output stream to write to. 1-10 bytes will be written.
237 :value:         Value to encode. Just cast e.g. int32_t directly to uint64_t.
238 :returns:       True on success, false on IO error.
239
240 .. _varint: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
241
242 pb_encode_svarint
243 -----------------
244 Encodes a signed integer in the 'zig-zagged' format. Works for fields of type `sint32` and `sint64`::
245
246     bool pb_encode_svarint(pb_ostream_t *stream, int64_t value);
247
248 (parameters are the same as for `pb_encode_varint`_
249
250 pb_encode_string
251 ----------------
252 Writes the length of a string as varint and then contents of the string. Works for fields of type `bytes` and `string`::
253
254     bool pb_encode_string(pb_ostream_t *stream, const uint8_t *buffer, size_t size);
255
256 :stream:        Output stream to write to.
257 :buffer:        Pointer to string data.
258 :size:          Number of bytes in the string. Pass `strlen(s)` for strings.
259 :returns:       True on success, false on IO error.
260
261 pb_encode_fixed32
262 -----------------
263 Writes 4 bytes to stream and swaps bytes on big-endian architectures. Works for fields of type `fixed32`, `sfixed32` and `float`::
264
265     bool pb_encode_fixed32(pb_ostream_t *stream, const void *value);
266
267 :stream:    Output stream to write to.
268 :value:     Pointer to a 4-bytes large C variable, for example `uint32_t foo;`.
269 :returns:   True on success, false on IO error.
270
271 pb_encode_fixed64
272 -----------------
273 Writes 8 bytes to stream and swaps bytes on big-endian architecture. Works for fields of type `fixed64`, `sfixed64` and `double`::
274
275     bool pb_encode_fixed64(pb_ostream_t *stream, const void *value);
276
277 :stream:    Output stream to write to.
278 :value:     Pointer to a 8-bytes large C variable, for example `uint64_t foo;`.
279 :returns:   True on success, false on IO error.
280
281 pb_encode_submessage
282 --------------------
283 Encodes a submessage field, including the size header for it. Works for fields of any message type::
284
285     bool pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
286
287 :stream:        Output stream to write to.
288 :fields:        Pointer to the autogenerated field description array for the submessage type, e.g. `MyMessage_fields`.
289 :src:           Pointer to the structure where submessage data is.
290 :returns:       True on success, false on IO errors, pb_encode errors or if submessage size changes between calls.
291
292 In Protocol Buffers format, the submessage size must be written before the submessage contents. Therefore, this function has to encode the submessage twice in order to know the size beforehand.
293
294 If the submessage contains callback fields, the callback function might misbehave and write out a different amount of data on the second call. This situation is recognized and *false* is returned, but garbage will be written to the output before the problem is detected.
295
296 pb_decode.h
297 ===========
298
299 pb_istream_from_buffer
300 ----------------------
301 Helper function for creating an input stream that reads data from a memory buffer. ::
302
303     pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize);
304
305 :buf:           Pointer to byte array to read from.
306 :bufsize:       Size of the byte array.
307 :returns:       An input stream ready to use.
308
309 pb_read
310 -------
311 Read data from input stream. Always use this function, don't try to call the stream callback directly. ::
312
313     bool pb_read(pb_istream_t *stream, uint8_t *buf, size_t count);
314
315 :stream:        Input stream to read from.
316 :buf:           Buffer to store the data to, or NULL to just read data without storing it anywhere.
317 :count:         Number of bytes to read.
318 :returns:       True on success, false if *stream->bytes_left* is less than *count* or if an IO error occurs.
319
320 End of file is signalled by *stream->bytes_left* being zero after pb_read returns false.
321
322 pb_decode
323 ---------
324 Read and decode all fields of a structure. Reads until EOF on input stream. ::
325
326     bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
327
328 :stream:        Input stream to read from.
329 :fields:        A field description array. Usually autogenerated.
330 :dest_struct:   Pointer to structure where data will be stored.
331 :returns:       True on success, false on IO error, on detectable errors in field description, if a field encoder returns false or if a required field is missing.
332
333 In Protocol Buffers binary format, EOF is only allowed between fields. If it happens anywhere else, pb_decode will return *false*. If pb_decode returns false, you cannot trust any of the data in the structure.
334
335 In addition to EOF, the pb_decode implementation supports terminating a message with a 0 byte. This is compatible with the official Protocol Buffers because 0 is never a valid field tag.
336
337 For optional fields, this function applies the default value and sets *has_<field>* to false if the field is not present.
338
339 pb_decode_noinit
340 ----------------
341 Same as `pb_decode`_, except does not apply the default values to fields. ::
342
343     bool pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
344
345 (parameters are the same as for `pb_decode`_.)
346
347 The destination structure should be filled with zeros before calling this function. Doing a *memset* manually can be slightly faster than using `pb_decode`_ if you don't need any default values.
348
349 pb_skip_varint
350 --------------
351 Skip a varint_ encoded integer without decoding it. ::
352
353     bool pb_skip_varint(pb_istream_t *stream);
354
355 :stream:        Input stream to read from. Will read 1 byte at a time until the MSB is clear.
356 :returns:       True on success, false on IO error.
357
358 pb_skip_string
359 --------------
360 Skip a varint-length-prefixed string. This means skipping a value with wire type PB_WT_STRING. ::
361
362     bool pb_skip_string(pb_istream_t *stream);
363
364 :stream:        Input stream to read from.
365 :returns:       True on success, false on IO error or length exceeding uint32_t.
366
367 pb_decode_tag
368 -------------
369 Decode the tag that comes before field in the protobuf encoding::
370
371     bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, int *tag, bool *eof);
372
373 :stream:        Input stream to read from.
374 :wire_type:     Pointer to variable where to store the wire type of the field.
375 :tag:           Pointer to variable where to store the tag of the field.
376 :eof:           Pointer to variable where to store end-of-file status.
377 :returns:       True on success, false on error or EOF.
378
379 When the message (stream) ends, this function will return false and set *eof* to true. On other
380 errors, *eof* will be set to false.
381
382 pb_skip_field
383 -------------
384 Remove the data for a field from the stream, without actually decoding it::
385
386     bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type);
387
388 :stream:        Input stream to read from.
389 :wire_type:     Type of field to skip.
390 :returns:       True on success, false on IO error.
391
392 .. sidebar:: Decoding fields manually
393     
394     The functions with names beginning with *pb_decode_* are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, `pb_decode`_ will call your callback function repeatedly, which can then store the values into e.g. filesystem in the order received in.
395
396     For decoding numeric (including enumerated and boolean) values, use `pb_decode_varint`_, `pb_decode_svarint`_, `pb_decode_fixed32`_ and `pb_decode_fixed64`_. They take a pointer to a 32- or 64-bit C variable, which you may then cast to smaller datatype for storage.
397
398     For decoding strings and bytes fields, the length has already been decoded. You can therefore check the total length in *stream->bytes_left* and read the data using `pb_read`_.
399
400     Finally, for decoding submessages in a callback, simply use `pb_decode`_ and pass it the *SubMessage_fields* descriptor array.
401
402 pb_decode_varint
403 ----------------
404 Read and decode a varint_ encoded integer. ::
405
406     bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest);
407
408 :stream:        Input stream to read from. 1-10 bytes will be read.
409 :dest:          Storage for the decoded integer. Value is undefined on error.
410 :returns:       True on success, false if value exceeds uint64_t range or an IO error happens.
411
412 pb_decode_svarint
413 -----------------
414 Similar to `pb_decode_varint`_, except that it performs zigzag-decoding on the value. This corresponds to the Protocol Buffers *sint32* and *sint64* datatypes. ::
415
416     bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest);
417
418 (parameters are the same as `pb_decode_varint`_)
419
420 pb_decode_fixed32
421 -----------------
422 Decode a *fixed32*, *sfixed32* or *float* value. ::
423
424     bool pb_decode_fixed32(pb_istream_t *stream, void *dest);
425
426 :stream:        Input stream to read from. 4 bytes will be read.
427 :dest:          Pointer to destination *int32_t*, *uint32_t* or *float*.
428 :returns:       True on success, false on IO errors.
429
430 This function reads 4 bytes from the input stream.
431 On big endian architectures, it then reverses the order of the bytes.
432 Finally, it writes the bytes to *dest*.
433
434 pb_decode_fixed64
435 -----------------
436 Decode a *fixed64*, *sfixed64* or *double* value. ::
437
438     bool pb_dec_fixed(pb_istream_t *stream, const pb_field_t *field, void *dest);
439
440 :stream:        Input stream to read from. 8 bytes will be read.
441 :field:         Not used.
442 :dest:          Pointer to destination *int64_t*, *uint64_t* or *double*.
443 :returns:       True on success, false on IO errors.
444
445 Same as `pb_decode_fixed32`_, except this reads 8 bytes.
446
447 pb_make_string_substream
448 ------------------------
449 Decode the length for a field with wire type *PB_WT_STRING* and create a substream for reading the data. ::
450
451     bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream);
452
453 :stream:        Original input stream to read the length and data from.
454 :substream:     New substream that has limited length. Filled in by the function.
455 :returns:       True on success, false if reading the length fails.
456
457 This function uses `pb_decode_varint`_ to read an integer from the stream. This is interpreted as a number of bytes, and the substream is set up so that its `bytes_left` is initially the same as the length, and its callback function and state the same as the parent stream.
458
459 pb_close_string_substream
460 -------------------------
461 Close the substream created with `pb_make_string_substream`_. ::
462
463     void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream);
464
465 :stream:        Original input stream to read the length and data from.
466 :substream:     Substream to close
467
468 This function copies back the state from the substream to the parent stream.
469 It must be called after done with the substream.