amessage_encode_decode.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <rtthread.h>
  2. #include <rtdevice.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <pb_encode.h>
  6. #include <pb_decode.h>
  7. #include "amessage.pb.h"
  8. static void nanopb_encode_decode(int argc,char *argv[])
  9. {
  10. /* This is the buffer where we will store our message. */
  11. uint8_t buffer[128];
  12. size_t message_length;
  13. bool status;
  14. /* Encode our message */
  15. {
  16. /* Allocate space on the stack to store the message data.
  17. *
  18. * Nanopb generates simple struct definitions for all the messages.
  19. * - check out the contents of simple.pb.h!
  20. * It is a good idea to always initialize your structures
  21. * so that you do not have garbage data from RAM in there.
  22. */
  23. AMessage amessage = AMessage_init_zero;
  24. /* Create a stream that will write to our buffer. */
  25. pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  26. if (argc != 3)
  27. {
  28. rt_kprintf("usage: amessage aa bb\n");
  29. return;
  30. }
  31. amessage.aa = atoi(argv[1]);
  32. amessage.bb = atoi(argv[2]);
  33. /* Now we are ready to encode the message! */
  34. status = pb_encode(&stream, AMessage_fields, &amessage);
  35. message_length = stream.bytes_written;
  36. /* Then just check for any errors.. */
  37. if (!status)
  38. {
  39. rt_kprintf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
  40. return;
  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. /* But because we are lazy, we will just decode it immediately. */
  47. {
  48. /* Allocate space for the decoded message. */
  49. AMessage amessage = AMessage_init_zero;
  50. /* Create a stream that reads from the buffer. */
  51. pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);
  52. /* Now we are ready to decode the message. */
  53. status = pb_decode(&stream, AMessage_fields, &amessage);
  54. /* Check for errors... */
  55. if (!status)
  56. {
  57. rt_kprintf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
  58. return ;
  59. }
  60. /* Print the data contained in the message. */
  61. rt_kprintf("amessage.aa = %d\n", (int)amessage.aa);
  62. rt_kprintf("amessage.bb = %d\n", (int)amessage.bb);
  63. }
  64. return;
  65. }
  66. MSH_CMD_EXPORT(nanopb_encode_decode, nanopb encode test);