tftp.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #include "tftp.h"
  2. struct tftp_context bms_tftp;
  3. TFTP_Handler tftp_handler;
  4. FIL tftp_object;
  5. void *bms_tftp_open(const char *fname, const char *mode, INT8U write)
  6. {
  7. INT8U res = FR_OK, err = 0; //, len = 0;
  8. INT8U name[MAX_FILENAME_LEN] = {0}; //, file_head[]="0:";
  9. // len = snprintf((char *)name, MAX_FILENAME_LEN, "0:");
  10. strcpy((char *)name, "0:");
  11. strcat((char *)name, fname);
  12. OSMutexPend(sd_mutex, 0, &err);
  13. if (write)
  14. {
  15. DeleteFile(name);
  16. res = f_open(&tftp_object, (const char *)name, FA_OPEN_ALWAYS | FA_WRITE);
  17. }
  18. else
  19. {
  20. res = f_open(&tftp_object, (const char *)name, FA_OPEN_EXISTING | FA_READ);
  21. }
  22. if (res == FR_OK)
  23. {
  24. tftp_handler.write = write;
  25. tftp_handler.type = 0;
  26. tftp_handler.Open_OK = TRUE;
  27. return &tftp_handler;
  28. }
  29. else
  30. {
  31. OSMutexPost(sd_mutex);
  32. return 0;
  33. }
  34. }
  35. void bms_tftp_close(void *handle)
  36. {
  37. // INT8U res = 0;
  38. if (((TFTP_Handler *)handle)->Open_OK == TRUE)
  39. {
  40. f_close(&tftp_object);
  41. tftp_handler.Open_OK = FALSE;
  42. OSMutexPost(sd_mutex);
  43. }
  44. }
  45. // 入参中bytes固定为512
  46. int bms_tftp_read(void *handle, void *buf, int bytes)
  47. {
  48. INT8U res = 0;
  49. INT32U bys = 0;
  50. if (((TFTP_Handler *)handle)->Open_OK != TRUE)
  51. {
  52. // OSMutexPost(sd_mutex);
  53. return -1;
  54. }
  55. res = f_read(&tftp_object, (INT8U *)buf, bytes, &bys);
  56. if (res == FR_OK)
  57. {
  58. return bys;
  59. }
  60. else
  61. {
  62. // OSMutexPost(sd_mutex);
  63. return -1;
  64. }
  65. }
  66. int bms_tftp_write(void *handle, struct pbuf *p)
  67. {
  68. INT8U res = 0;
  69. INT32U bys = 0;
  70. struct pbuf *q = p;
  71. if (((TFTP_Handler *)handle)->Open_OK != TRUE)
  72. {
  73. // OSMutexPost(sd_mutex);
  74. return -1;
  75. }
  76. while (q != NULL)
  77. {
  78. res = f_write(&tftp_object, q->payload, q->len, &bys);
  79. if (res == FR_OK)
  80. {
  81. q = q->next;
  82. }
  83. else
  84. {
  85. break;
  86. }
  87. }
  88. // res = f_write(&tftp_object, p->payload, p->len, &bys);
  89. if (res == FR_OK)
  90. {
  91. return 0;
  92. }
  93. else
  94. {
  95. // OSMutexPost(sd_mutex);
  96. return -1;
  97. }
  98. }
  99. void tftp_context_init(void)
  100. {
  101. tftp_handler.Open_OK = FALSE;
  102. bms_tftp.close = bms_tftp_close;
  103. bms_tftp.open = bms_tftp_open;
  104. bms_tftp.read = bms_tftp_read;
  105. bms_tftp.write = bms_tftp_write;
  106. tftp_init(&bms_tftp);
  107. }