decode_msgid.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /* Decode a message using msgid prefix to identify message type */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <pb_decode.h>
  5. #include "msgid_example.pb.h"
  6. #include "test_helpers.h"
  7. /* This function reads the prefix written by sending side. */
  8. bool read_prefix(pb_istream_t *stream, int *msgid)
  9. {
  10. uint8_t prefix = 0;
  11. if (!pb_read(stream, &prefix, 1))
  12. return false;
  13. *msgid = prefix;
  14. return true;
  15. }
  16. /* Main function will call one of these functions based on the prefix */
  17. bool handle_MyMessage1(pb_istream_t *stream)
  18. {
  19. MyMessage1 msg = MyMessage1_init_default;
  20. if (!pb_decode(stream, MyMessage1_fields, &msg))
  21. return false;
  22. printf("Got MyMessage1: intvalue = %d\n", (int)msg.intvalue);
  23. return true;
  24. }
  25. bool handle_MyMessage2(pb_istream_t *stream)
  26. {
  27. MyMessage2 msg = MyMessage2_init_default;
  28. if (!pb_decode(stream, MyMessage2_fields, &msg))
  29. return false;
  30. printf("Got MyMessage2: intvalue = %d, strvalue = %s\n",
  31. (int)msg.intvalue, msg.strvalue);
  32. return true;
  33. }
  34. bool handle_MyMessage3(pb_istream_t *stream)
  35. {
  36. MyMessage3 msg = MyMessage3_init_default;
  37. if (!pb_decode(stream, MyMessage3_fields, &msg))
  38. return false;
  39. printf("Got MyMessage3: boolvalue = %d\n", (int)msg.boolvalue);
  40. return true;
  41. }
  42. int main(int argc, char **argv)
  43. {
  44. uint8_t buffer[128];
  45. pb_istream_t stream;
  46. size_t count;
  47. bool status = false;
  48. int prefix;
  49. /* Read the data into buffer */
  50. SET_BINARY_MODE(stdin);
  51. count = fread(buffer, 1, sizeof(buffer), stdin);
  52. if (!feof(stdin))
  53. {
  54. printf("Message does not fit in buffer\n");
  55. return 1;
  56. }
  57. stream = pb_istream_from_buffer(buffer, count);
  58. if (!read_prefix(&stream, &prefix))
  59. {
  60. printf("Failed to read prefix: %s\n", PB_GET_ERROR(&stream));
  61. return 1;
  62. }
  63. /* Call message handler based on prefix.
  64. * We could write the switch cases manually, comparing against
  65. * the MyMessageX_msgid defines. However, this uses the automatically
  66. * generated X-macro construct to make the switch case.
  67. */
  68. switch (prefix)
  69. {
  70. #define PB_MSG(id,len,name) case id: status = handle_ ## name(&stream); break;
  71. MSGID_EXAMPLE_MESSAGES
  72. #undef PB_MSG
  73. default: printf("Unknown prefix: %d\n", prefix); return 1;
  74. }
  75. if (!status)
  76. {
  77. printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
  78. return 1;
  79. } else {
  80. return 0;
  81. }
  82. }