aboutsummaryrefslogtreecommitdiffstats
path: root/examples/cmake_simple/simple.c
diff options
context:
space:
mode:
authorOliver Lee <oliverzlee@gmail.com>2015-02-13 17:28:27 +0100
committerPetteri Aimonen <jpa@git.mail.kapsi.fi>2015-02-13 18:42:46 +0200
commit7c00b90910d4e14e23e027eb951e6f2a8dcfae29 (patch)
tree07dae73ed586d1a05b5571dc39924d5d7005774a /examples/cmake_simple/simple.c
parent02bd49bc9379e3062a718b1c16d6e2c23ea2f1a0 (diff)
Add simple example built with CMake
Diffstat (limited to 'examples/cmake_simple/simple.c')
-rw-r--r--examples/cmake_simple/simple.c68
1 files changed, 68 insertions, 0 deletions
diff --git a/examples/cmake_simple/simple.c b/examples/cmake_simple/simple.c
new file mode 100644
index 00000000..31272301
--- /dev/null
+++ b/examples/cmake_simple/simple.c
@@ -0,0 +1,68 @@
+#include <stdio.h>
+#include <pb_encode.h>
+#include <pb_decode.h>
+#include "simple.pb.h"
+
+int main()
+{
+ /* This is the buffer where we will store our message. */
+ uint8_t buffer[128];
+ size_t message_length;
+ bool status;
+
+ /* Encode our message */
+ {
+ /* Allocate space on the stack to store the message data.
+ *
+ * Nanopb generates simple struct definitions for all the messages.
+ * - check out the contents of simple.pb.h! */
+ SimpleMessage message;
+
+ /* Create a stream that will write to our buffer. */
+ pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ /* Fill in the lucky number */
+ message.lucky_number = 13;
+
+ /* Now we are ready to encode the message! */
+ status = pb_encode(&stream, SimpleMessage_fields, &message);
+ message_length = stream.bytes_written;
+
+ /* Then just check for any errors.. */
+ if (!status)
+ {
+ printf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ }
+ }
+
+ /* Now we could transmit the message over network, store it in a file or
+ * wrap it to a pigeon's leg.
+ */
+
+ /* But because we are lazy, we will just decode it immediately. */
+
+ {
+ /* Allocate space for the decoded message. */
+ SimpleMessage message;
+
+ /* Create a stream that reads from the buffer. */
+ pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);
+
+ /* Now we are ready to decode the message. */
+ status = pb_decode(&stream, SimpleMessage_fields, &message);
+
+ /* Check for errors... */
+ if (!status)
+ {
+ printf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ }
+
+ /* Print the data contained in the message. */
+ printf("Your lucky number was %d!\n", message.lucky_number);
+ }
+
+ return 0;
+}
+