test_fatfs.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include "ff.h"
  4. #include "esp_partition.h"
  5. #include "wear_levelling.h"
  6. #include "diskio_impl.h"
  7. #include "diskio_wl.h"
  8. #include "catch.hpp"
  9. extern "C" void _spi_flash_init(const char* chip_size, size_t block_size, size_t sector_size, size_t page_size, const char* partition_bin);
  10. TEST_CASE("create volume, open file, write and read back data", "[fatfs]")
  11. {
  12. _spi_flash_init(CONFIG_ESPTOOLPY_FLASHSIZE, CONFIG_WL_SECTOR_SIZE * 16, CONFIG_WL_SECTOR_SIZE, CONFIG_WL_SECTOR_SIZE, "partition_table.bin");
  13. FRESULT fr_result;
  14. BYTE pdrv;
  15. FATFS fs;
  16. FIL file;
  17. UINT bw;
  18. esp_err_t esp_result;
  19. const esp_partition_t *partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, "storage");
  20. // Mount wear-levelled partition
  21. wl_handle_t wl_handle;
  22. esp_result = wl_mount(partition, &wl_handle);
  23. REQUIRE(esp_result == ESP_OK);
  24. // Get a physical drive
  25. esp_result = ff_diskio_get_drive(&pdrv);
  26. REQUIRE(esp_result == ESP_OK);
  27. // Register physical drive as wear-levelled partition
  28. esp_result = ff_diskio_register_wl_partition(pdrv, wl_handle);
  29. // Create FAT volume on the entire disk
  30. DWORD part_list[] = {100, 0, 0, 0};
  31. BYTE work_area[FF_MAX_SS];
  32. fr_result = f_fdisk(pdrv, part_list, work_area);
  33. REQUIRE(fr_result == FR_OK);
  34. fr_result = f_mkfs("", FM_ANY, 0, work_area, sizeof(work_area)); // Use default volume
  35. // Mount the volume
  36. fr_result = f_mount(&fs, "", 0);
  37. REQUIRE(fr_result == FR_OK);
  38. // Open, write and read data
  39. fr_result = f_open(&file, "test.txt", FA_OPEN_ALWAYS | FA_READ | FA_WRITE);
  40. REQUIRE(fr_result == FR_OK);
  41. // Generate data
  42. uint32_t data_size = 100000;
  43. char *data = (char*) malloc(data_size);
  44. char *read = (char*) malloc(data_size);
  45. for(uint32_t i = 0; i < data_size; i += sizeof(i))
  46. {
  47. *((uint32_t*)(data + i)) = i;
  48. }
  49. // Write generated data
  50. fr_result = f_write(&file, data, data_size, &bw);
  51. REQUIRE(fr_result == FR_OK);
  52. REQUIRE(bw == data_size);
  53. // Move to beginning of file
  54. fr_result = f_lseek(&file, 0);
  55. REQUIRE(fr_result == FR_OK);
  56. // Read written data
  57. fr_result = f_read(&file, read, data_size, &bw);
  58. REQUIRE(fr_result == FR_OK);
  59. REQUIRE(bw == data_size);
  60. REQUIRE(memcmp(data, read, data_size) == 0);
  61. // Close file
  62. fr_result = f_close(&file);
  63. REQUIRE(fr_result == FR_OK);
  64. // Unmount default volume
  65. fr_result = f_mount(0, "", 0);
  66. REQUIRE(fr_result == FR_OK);
  67. free(read);
  68. free(data);
  69. }