1
0

tofile.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #include <rtthread.h>
  2. #include <ymodem.h>
  3. #include <dfs_posix.h>
  4. #include <stdlib.h>
  5. #include <board.h>
  6. struct custom_ctx
  7. {
  8. struct rym_ctx parent;
  9. int fd;
  10. int flen;
  11. char fpath[256];
  12. };
  13. static enum rym_code _rym_bg(
  14. struct rym_ctx *ctx,
  15. rt_uint8_t *buf,
  16. rt_size_t len)
  17. {
  18. struct custom_ctx *cctx = (struct custom_ctx*)ctx;
  19. cctx->fpath[0] = '/';
  20. /* the buf should be the file name */
  21. strcpy(&(cctx->fpath[1]), (const char*)buf);
  22. cctx->fd = open(cctx->fpath, O_CREAT | O_WRONLY | O_TRUNC, 0);
  23. if (cctx->fd < 0)
  24. {
  25. rt_err_t err = rt_get_errno();
  26. rt_kprintf("error creating file: %d\n", err);
  27. rt_kprintf("abort transmission\n");
  28. return RYM_CODE_CAN;
  29. }
  30. cctx->flen = atoi((const char*)buf+strlen((const char*)buf)+1);
  31. if (cctx->flen == 0)
  32. cctx->flen = -1;
  33. return RYM_CODE_ACK;
  34. }
  35. static enum rym_code _rym_tof(
  36. struct rym_ctx *ctx,
  37. rt_uint8_t *buf,
  38. rt_size_t len)
  39. {
  40. struct custom_ctx *cctx = (struct custom_ctx*)ctx;
  41. RT_ASSERT(cctx->fd >= 0);
  42. if (cctx->flen == -1)
  43. {
  44. write(cctx->fd, buf, len);
  45. }
  46. else
  47. {
  48. int wlen = len > cctx->flen ? cctx->flen : len;
  49. write(cctx->fd, buf, wlen);
  50. cctx->flen -= wlen;
  51. }
  52. return RYM_CODE_ACK;
  53. }
  54. static enum rym_code _rym_end(
  55. struct rym_ctx *ctx,
  56. rt_uint8_t *buf,
  57. rt_size_t len)
  58. {
  59. struct custom_ctx *cctx = (struct custom_ctx*)ctx;
  60. RT_ASSERT(cctx->fd >= 0);
  61. close(cctx->fd);
  62. cctx->fd = -1;
  63. return RYM_CODE_ACK;
  64. }
  65. rt_err_t rym_write_to_file(rt_device_t idev)
  66. {
  67. rt_err_t res;
  68. struct custom_ctx *ctx = rt_malloc(sizeof(*ctx));
  69. RT_ASSERT(idev);
  70. rt_kprintf("entering RYM mode\n");
  71. res = rym_recv_on_device(&ctx->parent, idev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX,
  72. _rym_bg, _rym_tof, _rym_end, 1000);
  73. /* there is no Ymodem traffic on the line so print out info. */
  74. rt_kprintf("leaving RYM mode with code %d\n", res);
  75. rt_kprintf("file %s has been created.\n", ctx->fpath);
  76. rt_free(ctx);
  77. return res;
  78. }
  79. #ifdef RT_USING_FINSH
  80. #include <finsh.h>
  81. rt_err_t ry(char *dname)
  82. {
  83. rt_err_t res;
  84. rt_device_t dev = rt_device_find(dname);
  85. if (!dev)
  86. {
  87. rt_kprintf("could not find device:%s\n", dname);
  88. return -RT_ERROR;
  89. }
  90. res = rym_write_to_file(dev);
  91. return res;
  92. }
  93. FINSH_FUNCTION_EXPORT(ry, receive files by ymodem protocol);
  94. #endif