MOS Source Code
Loading...
Searching...
No Matches
simple.c
Go to the documentation of this file.
1#include <stdio.h>
2#include <pb_encode.h>
3#include <pb_decode.h>
4#include "simple.pb.h"
5
6int main()
7{
8 /* This is the buffer where we will store our message. */
9 uint8_t buffer[128];
10 size_t message_length;
11 bool status;
12
13 /* Encode our message */
14 {
15 /* Allocate space on the stack to store the message data.
16 *
17 * Nanopb generates simple struct definitions for all the messages.
18 * - check out the contents of simple.pb.h!
19 * It is a good idea to always initialize your structures
20 * so that you do not have garbage data from RAM in there.
21 */
22 SimpleMessage message = SimpleMessage_init_zero;
23
24 /* Create a stream that will write to our buffer. */
25 pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
26
27 /* Fill in the lucky number */
28 message.lucky_number = 13;
29 message.unlucky.number = 42;
30
31 /* Now we are ready to encode the message! */
32 status = pb_encode(&stream, SimpleMessage_fields, &message);
33 message_length = stream.bytes_written;
34
35 /* Then just check for any errors.. */
36 if (!status)
37 {
38 printf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
39 return 1;
40 }
41 }
42
43 /* Now we could transmit the message over network, store it in a file or
44 * wrap it to a pigeon's leg.
45 */
46
47 /* But because we are lazy, we will just decode it immediately. */
48
49 {
50 /* Allocate space for the decoded message. */
51 SimpleMessage message = SimpleMessage_init_zero;
52
53 /* Create a stream that reads from the buffer. */
54 pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);
55
56 /* Now we are ready to decode the message. */
57 status = pb_decode(&stream, SimpleMessage_fields, &message);
58
59 /* Check for errors... */
60 if (!status)
61 {
62 printf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
63 return 1;
64 }
65
66 /* Print the data contained in the message. */
67 printf("Your lucky number was %d!\n", message.lucky_number);
68 printf("Your unlucky number was %u!\n", message.unlucky.number);
69 }
70
71 return 0;
72}
73
int main()
Definition simple.c:6
#define PB_GET_ERROR(stream)
Definition pb.h:891
bool pb_decode(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct)
Definition pb_decode.c:1182
pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t msglen)
Definition pb_decode.c:143
pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize)
Definition pb_encode.c:63
bool pb_encode(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct)
Definition pb_encode.c:512
unsigned char uint8_t
Definition pb_syshdr.h:20
static char buffer[2048]
Definition test_printf.c:7