simple.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <rthw.h>
  2. #include <stm32f10x.h>
  3. #include <pb_encode.h>
  4. #include <pb_decode.h>
  5. #include "simple.pb.h"
  6. int nanopb_test()
  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. /* Encode our message */
  13. {
  14. /* Allocate space on the stack to store the message data.
  15. *
  16. * Nanopb generates simple struct definitions for all the messages.
  17. * - check out the contents of simple.pb.h! */
  18. SimpleMessage message = SimpleMessage_init_zero;
  19. /* Create a stream that will write to our buffer. */
  20. pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  21. /* Fill in the lucky number */
  22. message.lucky_number = 13;
  23. /* Now we are ready to encode the message! */
  24. status = pb_encode(&stream, SimpleMessage_fields, &message);
  25. message_length = stream.bytes_written;
  26. /* Then just check for any errors.. */
  27. if (!status)
  28. {
  29. rt_kprintf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
  30. return 1;
  31. }
  32. }
  33. /* Now we could transmit the message over network, store it in a file or
  34. * wrap it to a pigeon's leg.
  35. */
  36. /* But because we are lazy, we will just decode it immediately. */
  37. {
  38. /* Allocate space for the decoded message. */
  39. SimpleMessage message;
  40. /* Create a stream that reads from the buffer. */
  41. pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);
  42. /* Now we are ready to decode the message. */
  43. status = pb_decode(&stream, SimpleMessage_fields, &message);
  44. /* Check for errors... */
  45. if (!status)
  46. {
  47. rt_kprintf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
  48. return 1;
  49. }
  50. /* Print the data contained in the message. */
  51. rt_kprintf("Your lucky number was %d!\n", message.lucky_number);
  52. }
  53. return 0;
  54. }
  55. #ifdef RT_USING_FINSH
  56. #include <finsh.h>
  57. FINSH_FUNCTION_EXPORT(nanopb_test, nanopb encode/decode test.)
  58. #endif