simple.c 2.3 KB

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