encode.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* This program takes a command line argument and encodes a message in
  2. * one of MsgType1, MsgType2 or MsgType3.
  3. */
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <pb_encode.h>
  8. #include <pb_common.h>
  9. #include "unionproto.pb.h"
  10. /* This function is the core of the union encoding process. It handles
  11. * the top-level pb_field_t array manually, in order to encode a correct
  12. * field tag before the message. The pointer to MsgType_fields array is
  13. * used as an unique identifier for the message type.
  14. */
  15. bool encode_unionmessage(pb_ostream_t *stream, const pb_msgdesc_t *messagetype, void *message)
  16. {
  17. pb_field_iter_t iter;
  18. if (!pb_field_iter_begin(&iter, UnionMessage_fields, message))
  19. return false;
  20. do
  21. {
  22. if (iter.submsg_desc == messagetype)
  23. {
  24. /* This is our field, encode the message using it. */
  25. if (!pb_encode_tag_for_field(stream, &iter))
  26. return false;
  27. return pb_encode_submessage(stream, messagetype, message);
  28. }
  29. } while (pb_field_iter_next(&iter));
  30. /* Didn't find the field for messagetype */
  31. return false;
  32. }
  33. int main(int argc, char **argv)
  34. {
  35. if (argc != 2)
  36. {
  37. fprintf(stderr, "Usage: %s (1|2|3)\n", argv[0]);
  38. return 1;
  39. }
  40. uint8_t buffer[512];
  41. pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  42. bool status = false;
  43. int msgtype = atoi(argv[1]);
  44. if (msgtype == 1)
  45. {
  46. /* Send message of type 1 */
  47. MsgType1 msg = {42};
  48. status = encode_unionmessage(&stream, MsgType1_fields, &msg);
  49. }
  50. else if (msgtype == 2)
  51. {
  52. /* Send message of type 2 */
  53. MsgType2 msg = {true};
  54. status = encode_unionmessage(&stream, MsgType2_fields, &msg);
  55. }
  56. else if (msgtype == 3)
  57. {
  58. /* Send message of type 3 */
  59. MsgType3 msg = {3, 1415};
  60. status = encode_unionmessage(&stream, MsgType3_fields, &msg);
  61. }
  62. else
  63. {
  64. fprintf(stderr, "Unknown message type: %d\n", msgtype);
  65. return 2;
  66. }
  67. if (!status)
  68. {
  69. fprintf(stderr, "Encoding failed!\n");
  70. return 3;
  71. }
  72. else
  73. {
  74. fwrite(buffer, 1, stream.bytes_written, stdout);
  75. return 0; /* Success */
  76. }
  77. }