simple.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <rtthread.h>
  2. #include <rtdevice.h>
  3. #include <stdio.h>
  4. #include <pb_encode.h>
  5. #include <pb_decode.h>
  6. #include "simple.pb.h"
  7. static void nanopb_simple(int argc,char *argv[])
  8. {
  9. /* This is the buffer where we will store our message. */
  10. uint8_t buffer[128];
  11. size_t message_length;
  12. bool status;
  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. /* Create a stream that will write to our buffer. */
  24. pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  25. /* Fill in the lucky number */
  26. message.lucky_number = 13;
  27. /* Now we are ready to encode the message! */
  28. status = pb_encode(&stream, SimpleMessage_fields, &message);
  29. message_length = stream.bytes_written;
  30. /* Then just check for any errors.. */
  31. if (!status)
  32. {
  33. rt_kprintf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
  34. return ;
  35. }
  36. rt_kprintf("Successfully encoded\n");
  37. }
  38. /* Now we could transmit the message over network, store it in a file or
  39. * wrap it to a pigeon's leg.
  40. */
  41. /* But because we are lazy, we will just decode it immediately. */
  42. {
  43. /* Allocate space for the decoded message. */
  44. SimpleMessage message = SimpleMessage_init_zero;
  45. /* Create a stream that reads from the buffer. */
  46. pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);
  47. /* Now we are ready to decode the message. */
  48. status = pb_decode(&stream, SimpleMessage_fields, &message);
  49. /* Check for errors... */
  50. if (!status)
  51. {
  52. rt_kprintf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
  53. return;
  54. }
  55. /* Print the data contained in the message. */
  56. rt_kprintf("Your lucky number was %d!\n", (int)message.lucky_number);
  57. }
  58. return;
  59. }
  60. MSH_CMD_EXPORT(nanopb_simple, nanopb test);