2
0

encode_msgid.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Encode a message using msgid field as prefix */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pb_encode.h>
  6. #include "msgid_example.pb.h"
  7. #include "test_helpers.h"
  8. /* This function writes the message id as a prefix to the message, allowing
  9. * the receiving side to identify message type. Here we use uint8_t to store
  10. * it, but e.g. varint or some custom header struct would work just as well.
  11. */
  12. bool write_prefix(pb_ostream_t *stream, int msgid)
  13. {
  14. uint8_t prefix = msgid;
  15. return pb_write(stream, &prefix, 1);
  16. }
  17. /* The main logic will call one of these functions.
  18. * Normally which function you call would be selected based on what message
  19. * you want to send, here it is decided based on command line parameter.
  20. */
  21. bool encode_MyMessage1(pb_ostream_t *stream)
  22. {
  23. MyMessage1 msg = MyMessage1_init_default;
  24. msg.intvalue = 1234;
  25. return write_prefix(stream, MyMessage1_msgid)
  26. && pb_encode(stream, MyMessage1_fields, &msg);
  27. }
  28. bool encode_MyMessage2(pb_ostream_t *stream)
  29. {
  30. MyMessage2 msg = MyMessage2_init_default;
  31. msg.intvalue = 9999;
  32. strcpy(msg.strvalue, "Msg2");
  33. return write_prefix(stream, MyMessage2_msgid)
  34. && pb_encode(stream, MyMessage2_fields, &msg);
  35. }
  36. bool encode_MyMessage3(pb_ostream_t *stream)
  37. {
  38. MyMessage3 msg = MyMessage3_init_default;
  39. msg.boolvalue = true;
  40. return write_prefix(stream, MyMessage3_msgid)
  41. && pb_encode(stream, MyMessage3_fields, &msg);
  42. }
  43. int main(int argc, char **argv)
  44. {
  45. uint8_t buffer[128];
  46. pb_ostream_t stream;
  47. bool status = false;
  48. int option;
  49. if (argc != 2)
  50. {
  51. fprintf(stderr, "Usage: encode_msgid [number]\n");
  52. return 1;
  53. }
  54. option = atoi(argv[1]);
  55. stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  56. if (option == 1)
  57. {
  58. status = encode_MyMessage1(&stream);
  59. }
  60. else if (option == 2)
  61. {
  62. status = encode_MyMessage2(&stream);
  63. }
  64. else if (option == 3)
  65. {
  66. status = encode_MyMessage3(&stream);
  67. }
  68. if (status)
  69. {
  70. SET_BINARY_MODE(stdout);
  71. fwrite(buffer, 1, stream.bytes_written, stdout);
  72. return 0;
  73. }
  74. else
  75. {
  76. fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
  77. return 1;
  78. }
  79. }