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