amessage_encode_decode.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <rtthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include "amessage.pb-c.h"
  5. static void protobuf_encode_decode(int argc, char *argv[])
  6. {
  7. void *buf; // Buffer to store serialized data
  8. unsigned msg_len; // Length of serialized data
  9. if (argc != 3)
  10. {
  11. rt_kprintf("Usage: %s a b\n", argv[0]);
  12. return ;
  13. }
  14. // Encode message to buffer
  15. {
  16. rt_kprintf("---- Encoding ---\n");
  17. AMessage encode_msg = AMESSAGE__INIT;
  18. encode_msg.has_a = 1;
  19. encode_msg.a = atoi(argv[1]);
  20. encode_msg.has_b = 1;
  21. encode_msg.b = atoi(argv[2]);
  22. msg_len = amessage__get_packed_size(&encode_msg);
  23. buf = malloc(msg_len);
  24. rt_kprintf("Encoding %d serialized bytes\n", msg_len);
  25. amessage__pack(&encode_msg, buf);
  26. }
  27. // Unpack the message from buffer.
  28. {
  29. rt_kprintf("---- Decoding ---\n");
  30. AMessage* decode_msg;
  31. decode_msg = amessage__unpack(NULL, msg_len, buf);
  32. if (decode_msg == NULL)
  33. {
  34. rt_kprintf("Error unpacking incoming message\n");
  35. return;
  36. }
  37. rt_kprintf("Received: a=%d b=%d \n",decode_msg->a, decode_msg->b); // required field
  38. amessage__free_unpacked(decode_msg, NULL);
  39. }
  40. free(buf);
  41. return;
  42. }
  43. MSH_CMD_EXPORT(protobuf_encode_decode, protobuf-c encode decode test);