1 #include <rthw.h> 2 #include <stm32f10x.h> 3 #include <pb_encode.h> 4 #include <pb_decode.h> 5 #include "simple.pb.h" 6 7 int nanopb_test() 8 { 9 /* This is the buffer where we will store our message. */ 10 uint8_t buffer[128]; 11 size_t message_length; 12 bool status; 13 14 /* Encode our message */ 15 { 16 /* Allocate space on the stack to store the message data. 17 * 18 * Nanopb generates simple struct definitions for all the messages. 19 * - check out the contents of simple.pb.h! */ 20 SimpleMessage message = SimpleMessage_init_zero; 21 22 /* Create a stream that will write to our buffer. */ 23 pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); 24 25 /* Fill in the lucky number */ 26 message.lucky_number = 13; 27 28 /* Now we are ready to encode the message! */ 29 status = pb_encode(&stream, SimpleMessage_fields, &message); 30 message_length = stream.bytes_written; 31 32 /* Then just check for any errors.. */ 33 if (!status) 34 { 35 rt_kprintf("Encoding failed: %s\n", PB_GET_ERROR(&stream)); 36 return 1; 37 } 38 } 39 40 /* Now we could transmit the message over network, store it in a file or 41 * wrap it to a pigeon's leg. 42 */ 43 44 /* But because we are lazy, we will just decode it immediately. */ 45 46 { 47 /* Allocate space for the decoded message. */ 48 SimpleMessage message; 49 50 /* Create a stream that reads from the buffer. */ 51 pb_istream_t stream = pb_istream_from_buffer(buffer, message_length); 52 53 /* Now we are ready to decode the message. */ 54 status = pb_decode(&stream, SimpleMessage_fields, &message); 55 56 /* Check for errors... */ 57 if (!status) 58 { 59 rt_kprintf("Decoding failed: %s\n", PB_GET_ERROR(&stream)); 60 return 1; 61 } 62 63 /* Print the data contained in the message. */ 64 rt_kprintf("Your lucky number was %d!\n", message.lucky_number); 65 } 66 67 return 0; 68 } 69 70 #ifdef RT_USING_FINSH 71 #include <finsh.h> 72 FINSH_FUNCTION_EXPORT(nanopb_test, nanopb encode/decode test.) 73 #endif 74