amessage_encode_to_file.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <rtthread.h>
  2. #include <rtdevice.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <pb_encode.h>
  6. #include <pb_decode.h>
  7. #include "amessage.pb.h"
  8. #include <dfs_posix.h>
  9. static void nanopb_encode_to_file(int argc,char *argv[])
  10. {
  11. /* This is the buffer where we will store our message. */
  12. uint8_t buffer[128];
  13. size_t message_length;
  14. bool status;
  15. /* Encode our message */
  16. {
  17. /* Allocate space on the stack to store the message data.
  18. *
  19. * Nanopb generates simple struct definitions for all the messages.
  20. * - check out the contents of simple.pb.h!
  21. * It is a good idea to always initialize your structures
  22. * so that you do not have garbage data from RAM in there.
  23. */
  24. AMessage amessage = AMessage_init_zero;
  25. /* Create a stream that will write to our buffer. */
  26. pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  27. if (argc != 3)
  28. {
  29. rt_kprintf("usage: amessage aa bb\n");
  30. return;
  31. }
  32. amessage.aa = atoi(argv[1]);
  33. amessage.bb = atoi(argv[2]);
  34. /* Now we are ready to encode the message! */
  35. status = pb_encode(&stream, AMessage_fields, &amessage);
  36. message_length = stream.bytes_written;
  37. /* Then just check for any errors.. */
  38. if (!status)
  39. {
  40. rt_kprintf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
  41. return;
  42. }
  43. rt_kprintf("Writing %d serialized bytes\n", message_length); // See the length of message
  44. int fd = open("/amessage.onnx", O_WRONLY | O_CREAT | O_TRUNC);
  45. if (fd>= 0)
  46. {
  47. write(fd, buffer, message_length);
  48. close(fd);
  49. rt_kprintf("Write done.\n");
  50. }
  51. }
  52. return;
  53. }
  54. MSH_CMD_EXPORT(nanopb_encode_to_file, nanopb encode to file);