test_fatfs.cpp 2.4 KB

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