90 lines
2.6 KiB
C++
90 lines
2.6 KiB
C++
#include "SdCard.hpp"
|
|
#include "esp_log.h"
|
|
#include "esp_vfs_fat.h"
|
|
#include "sdmmc_cmd.h"
|
|
#include "driver/sdmmc_host.h"
|
|
#include <sys/stat.h>
|
|
|
|
static const char* TAG = "SdCard";
|
|
|
|
// ESP32-P4 Waveshare Board SDMMC Pins
|
|
#define SDMMC_CLK_GPIO 43
|
|
#define SDMMC_CMD_GPIO 44
|
|
#define SDMMC_D0_GPIO 39
|
|
#define SDMMC_D1_GPIO 40
|
|
#define SDMMC_D2_GPIO 41
|
|
#define SDMMC_D3_GPIO 42
|
|
|
|
SdCard& SdCard::instance() {
|
|
static SdCard inst;
|
|
return inst;
|
|
}
|
|
|
|
bool SdCard::init() {
|
|
if (mounted_) {
|
|
ESP_LOGW(TAG, "SD card already mounted");
|
|
return true;
|
|
}
|
|
|
|
ESP_LOGI(TAG, "Initializing SD card");
|
|
|
|
// Configure SDMMC host
|
|
sdmmc_host_t host = SDMMC_HOST_DEFAULT();
|
|
host.max_freq_khz = SDMMC_FREQ_HIGHSPEED;
|
|
|
|
// Configure SDMMC slot with GPIO pins
|
|
sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
|
|
slot_config.clk = static_cast<gpio_num_t>(SDMMC_CLK_GPIO);
|
|
slot_config.cmd = static_cast<gpio_num_t>(SDMMC_CMD_GPIO);
|
|
slot_config.d0 = static_cast<gpio_num_t>(SDMMC_D0_GPIO);
|
|
slot_config.d1 = static_cast<gpio_num_t>(SDMMC_D1_GPIO);
|
|
slot_config.d2 = static_cast<gpio_num_t>(SDMMC_D2_GPIO);
|
|
slot_config.d3 = static_cast<gpio_num_t>(SDMMC_D3_GPIO);
|
|
slot_config.width = 4; // 4-bit mode
|
|
slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
|
|
|
|
// Mount FAT filesystem
|
|
esp_vfs_fat_sdmmc_mount_config_t mount_config = {
|
|
.format_if_mount_failed = true,
|
|
.max_files = 5,
|
|
.allocation_unit_size = 16 * 1024
|
|
};
|
|
|
|
sdmmc_card_t* card;
|
|
esp_err_t ret = esp_vfs_fat_sdmmc_mount(MOUNT_POINT, &host, &slot_config, &mount_config, &card);
|
|
|
|
if (ret != ESP_OK) {
|
|
if (ret == ESP_FAIL) {
|
|
ESP_LOGE(TAG, "Failed to mount filesystem. If you want the card to be formatted, set format_if_mount_failed = true.");
|
|
} else {
|
|
ESP_LOGE(TAG, "Failed to initialize the card (%s). Make sure SD card lines have pull-up resistors.", esp_err_to_name(ret));
|
|
}
|
|
return false;
|
|
}
|
|
|
|
mounted_ = true;
|
|
|
|
// Print card info
|
|
sdmmc_card_print_info(stdout, card);
|
|
ESP_LOGI(TAG, "SD card mounted at %s", MOUNT_POINT);
|
|
|
|
// Create directories if they don't exist
|
|
struct stat st;
|
|
const char* dirs[] = {
|
|
"/sdcard/webseite",
|
|
"/sdcard/images"
|
|
};
|
|
|
|
for (const char* dir : dirs) {
|
|
if (stat(dir, &st) != 0) {
|
|
if (mkdir(dir, 0755) == 0) {
|
|
ESP_LOGI(TAG, "Created directory: %s", dir);
|
|
} else {
|
|
ESP_LOGW(TAG, "Failed to create directory: %s", dir);
|
|
}
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|