user_fatfs.c 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #include "at32f403a_407.h"
  2. #include "user_fatfs.h"
  3. #include "common_config.h"
  4. #include "common.h"
  5. #include "FreeRTOS.h"
  6. #include "task.h"
  7. #include "semphr.h"
  8. #include "spi_flash.h"
  9. #include <string.h>
  10. #include <stdlib.h>
  11. #ifdef PRINTF_STDLIB
  12. #include <stdio.h>
  13. #endif
  14. #ifdef PRINTF_CUSTOM
  15. #include "tinystdio.h"
  16. #endif
  17. #define MAX_DRV_NUM 2 // Текущее число поддерживаемых дисков
  18. SemaphoreHandle_t spiFlashMutex;
  19. FIL update_file; // Файл прошивки
  20. FATFS *disks[MAX_DRV_NUM];
  21. static unsigned long writePtr[MAX_DRV_NUM] = {0, 0}; // Указатель на позицию для записи в файл
  22. static uint32_t strCount = 0; // Число строк в файле
  23. static uint32_t pageCount = 0; // Число страниц в файле
  24. char file_path[32];
  25. static bool fSecDrvEn = false; // Флаг присутствия второстепенного диска
  26. static bool fPrimDrvEn = false; // Флаг присутствия основного диска
  27. static bool fatfs_init = false;
  28. //
  29. bool InitFS(BYTE drv)
  30. {
  31. FRESULT res;
  32. FATFS *disk;
  33. DWORD free;
  34. uint32_t space;
  35. spiFlashMutex = xSemaphoreCreateMutex();
  36. snprintf(file_path, sizeof(file_path), "%u:", drv);
  37. disk = pvPortMalloc(sizeof(FATFS));
  38. if (disk == NULL) {
  39. printf("DRIVE %u: malloc error\n\r", drv);
  40. fatfs_init = true;
  41. return false;
  42. }
  43. // Монтировать диск
  44. res = f_mount(disk, "", 1);
  45. // Создать файловую систему
  46. if (res != FR_OK) {
  47. res = f_mkfs(file_path,0,0);
  48. }
  49. f_getfree("/", &free, &disk);
  50. space = free * disk->ssize;
  51. if (space == 0) {
  52. f_mkfs(file_path,0,0);
  53. f_getfree("/", &free, &disk);
  54. space = free * disk->ssize;
  55. }
  56. res = f_chdir(file_path);
  57. if (res == FR_NO_FILESYSTEM)
  58. {
  59. printf("DRIVE %u: no filesystem found\n\r", drv);
  60. switch(drv)
  61. {
  62. case SPI_FLASH:
  63. spi_flash_erase_sector(0,0);
  64. spi_flash_erase_sector(1,0);
  65. spi_flash_erase_sector(2,0);
  66. spi_flash_erase_sector(3,0);
  67. break;
  68. }
  69. f_mkfs(file_path,0,0);
  70. if (f_chdir(file_path) != FR_OK) {
  71. printf("DRIVE %u: filesystem error\n\r", drv);
  72. vPortFree(disk);
  73. fatfs_init = true;
  74. return false;
  75. }
  76. else {
  77. printf("DRIVE %u: filesystem created successfully\n\r", drv);
  78. }
  79. }
  80. else if (res == FR_NOT_READY) {
  81. printf("DRIVE %u: not ready\n\r", drv);
  82. printf("DRIVE %u: File system is not initialized. Error!\n\r", drv);
  83. vPortFree(disk);
  84. fatfs_init = true;
  85. return false;
  86. }
  87. else if(res == FR_OK)
  88. {
  89. // Проверка файла лога
  90. res = f_open(&update_file, LOG_NAME, FA_READ);
  91. if (res != FR_OK) {
  92. res = f_open(&update_file, LOG_NAME, FA_WRITE | FA_CREATE_NEW);
  93. if (res != FR_OK) {
  94. f_close(&update_file);
  95. printf("DRIVE %u: File system is not initialized. Error!\n\r", drv);
  96. fatfs_init = true;
  97. return false;
  98. }
  99. }
  100. f_close(&update_file);
  101. }
  102. printf("DRIVE %u: filesystem initialized successfully\n\r", drv);
  103. fatfs_init = true;
  104. return true;
  105. }
  106. /**
  107. * @brief Возвращает число файлов в папке
  108. * @param *path имя папки в виде "/LOG"
  109. * @retval
  110. */
  111. uint32_t GetFilesCount(char *path)
  112. {
  113. FRESULT res;
  114. FILINFO fno;
  115. DIR dir;
  116. char *fn;
  117. uint32_t fileCount;
  118. res = f_opendir(&dir, path);
  119. if (res != FR_OK)
  120. return 0; // Не удалось открыть директорию
  121. for (;;)
  122. {
  123. res = f_readdir(&dir, &fno); // Чтение объекта директории
  124. // Останов цикла при ошибке или при достижении конца списка директории
  125. if (res != FR_OK || fno.fname[0] == 0)
  126. return fileCount;
  127. if (fno.fname[0] == '.')
  128. continue; // Игнорирование элемента 'точка'
  129. fn = fno.fname;
  130. if (!(fno.fattrib & AM_DIR))
  131. { // Это директория
  132. fileCount++;
  133. DBG printf("%s\r\n",fn);
  134. }
  135. else
  136. {
  137. DBG printf("%s/%s\r\n", path, fn);
  138. }
  139. }
  140. }
  141. /* Get fs file raw data */
  142. uint32_t GetFileData(BYTE drv, char *file_name, unsigned long ptr, char *str, uint32_t size)
  143. {
  144. unsigned long readPtr;
  145. FRESULT res;
  146. uint32_t count = 0;
  147. res = f_open(&update_file, file_name, FA_WRITE);
  148. if (res != FR_OK) {
  149. f_close(&update_file);
  150. return 0;
  151. }
  152. readPtr = ptr;
  153. res = f_lseek(&update_file, readPtr);
  154. if (res != FR_OK) {
  155. f_close(&update_file);
  156. return 0;
  157. }
  158. res = f_read(&update_file, str, size, (UINT *)&count);
  159. if (res != FR_OK) {
  160. f_close(&update_file);
  161. return 0;
  162. }
  163. f_close(&update_file);
  164. return count;
  165. }
  166. /* Put fs file raw data */
  167. uint32_t PutFileData(BYTE drv, char *file_name, unsigned long ptr, char *str, uint32_t size, bool truncate)
  168. {
  169. FRESULT res;
  170. uint32_t count = 0;
  171. if (xSemaphoreTake(spiFlashMutex, 2000) != pdTRUE)
  172. return 0;
  173. res = f_open(&update_file, file_name, FA_WRITE);
  174. if (res != FR_OK) {
  175. f_close(&update_file);
  176. xSemaphoreGive(spiFlashMutex);
  177. return 0;
  178. }
  179. if( ptr == 1 ){
  180. res = f_lseek(&update_file, 0);
  181. }
  182. else{
  183. res = f_lseek(&update_file, update_file.fsize);
  184. }
  185. if (res != FR_OK) {
  186. f_close(&update_file);
  187. xSemaphoreGive(spiFlashMutex);
  188. return 0;
  189. }
  190. res = f_write(&update_file, str, size, (UINT *)&count);
  191. if (res != FR_OK) {
  192. f_close(&update_file);
  193. xSemaphoreGive(spiFlashMutex);
  194. return 0;
  195. }
  196. if (truncate) {
  197. res = f_truncate(&update_file);
  198. if (res != FR_OK) {
  199. xSemaphoreGive(spiFlashMutex);
  200. }
  201. }
  202. f_close(&update_file);
  203. xSemaphoreGive(spiFlashMutex);
  204. return count;
  205. }
  206. //
  207. void EraseFlash()
  208. {
  209. if (xSemaphoreTake(spiFlashMutex, 10000) != pdTRUE)
  210. return;
  211. spi_flash_erase_sector(0,0);
  212. spi_flash_erase_sector(1,0);
  213. spi_flash_erase_sector(2,0);
  214. spi_flash_erase_sector(3,0);
  215. xSemaphoreGive(spiFlashMutex);
  216. }
  217. //
  218. void flash_check_space(FATFS *fs)
  219. {
  220. DWORD fre_clust, fre_sect;
  221. // Получение информации о томе и количество свободных кластеров
  222. f_getfree(0, &fre_clust, &fs);
  223. fre_sect = fre_clust * fs->csize;
  224. //availableSpace = fre_sect/2;
  225. }
  226. //
  227. bool fatfs_isinit(void)
  228. {
  229. return fatfs_init;
  230. }