--- /dev/null
+#include <stdio.h>
+#include <stdint.h>
+
+#include "esp_vfs_fat.h"
+#include "sdmmc_cmd.h"
+#include "esp_system.h"
+#include "esp_err.h"
+#include "esp_log.h"
+#include "hal/spi_types.h"
+
+#include "sdcardspi.h"
+#include "pins.h"
+
+#define SPI_UNUSED -1
+#define SPI_MAX_TRANSFER_BYTES 4000
+
+/* code largely adapted from ESP-IDF examples: sd_card/sdspi */
+
+/* constants */
+const char *TAG = "sdcardspi";
+/* the sdcard handle itself */
+sdmmc_card_t *sdmmc;
+/* the sd card mount path */
+const char *mntpath = SD_MOUNT_PATH;
+sdmmc_host_t host = SDSPI_HOST_DEFAULT();
+
+
+uint8_t check_valid_swos_fhs(void);
+
+
+uint8_t task_sdcard() {
+ esp_err_t nzec;
+
+ /* set up mount config */
+ esp_vfs_fat_sdmmc_mount_config_t mount_cfg = {
+ .format_if_mount_failed = false,
+ .max_files = SD_MAX_FILE_HANDLES
+ };
+
+ const spi_bus_config_t spi_bus_cfg = {
+ .mosi_io_num = PIN_SD_MOSI,
+ .miso_io_num = PIN_SD_MISO,
+ .sclk_io_num = PIN_SD_SCK,
+ .quadwp_io_num = SPI_UNUSED,
+ .quadhd_io_num = SPI_UNUSED,
+ .max_transfer_sz = SPI_MAX_TRANSFER_BYTES
+ };
+
+ sdspi_device_config_t slot_cfg = SDSPI_DEVICE_CONFIG_DEFAULT();
+ slot_cfg.gpio_cs = PIN_SD_CS;
+ slot_cfg.host_id = host.slot;
+
+ ESP_LOGI(TAG, "Initializing card with mount point: %s", mntpath);
+ if (spi_bus_initialize(host.slot, &spi_bus_cfg,
+ SDSPI_DEFAULT_DMA) != ESP_OK) {
+ ESP_LOGE(TAG, "SPI bus initialization failed!");
+ return 0;
+ }
+
+
+
+ nzec = esp_vfs_fat_sdspi_mount(mntpath, &host, &slot_cfg, &mount_cfg,
+ &sdmmc);
+
+ if (nzec != ESP_OK) {
+ if (nzec == ESP_FAIL) {
+ ESP_LOGE(TAG, "Failed to mount filesystem. Run a disk repair "
+ "tool to correct errors.");
+ } else {
+ ESP_LOGE(TAG, "Failed to initialize SD card (%s).",
+ esp_err_to_name(nzec));
+ }
+ return 0;
+ }
+
+ ESP_LOGI(TAG, "SD FATfs mounted successfully.");
+ sdmmc_card_print_info(stdout, sdmmc);
+
+ if (check_valid_swos_fhs()) {
+ esp_vfs_fat_sdcard_unmount(mntpath, sdmmc);
+ ESP_LOGI(TAG, "Card unmounted since this isn't a valid SWOS system");
+
+ //deinitialize the bus after all devices are removed
+ spi_bus_free(host.slot);
+ }
+ return 1;
+}
+
+
+uint8_t check_valid_swos_fhs() {
+ char txtdata[128];
+ size_t x;
+ FILE *fp = fopen(SD_PATH("README.txt"), "rb");
+
+ if (!fp) {
+ ESP_LOGE(TAG, "The file %s is missing!", SD_PATH("README.txt"));
+ return 1;
+ }
+
+ ESP_LOGI(TAG, "Found README.txt");
+ while ((x = fread(txtdata, sizeof(char), 127, fp))) {
+ txtdata[x + 1] = '\0';
+ printf(txtdata);
+ }
+ fflush(stdout);
+
+ fclose(fp);
+ return 0;
+}
+