knob_os/src/hal/Storage.cpp

61 lines
1.9 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "Storage.h"
#include "../core/Log.h"
#include "../config/BoardPins.h"
#include <SD_MMC.h>
#include <mutex>
namespace hal {
static SemaphoreHandle_t _mtx = nullptr;
static bool _ready = false;
bool storageBegin() {
if (!_mtx) _mtx = xSemaphoreCreateRecursiveMutex();
SD_MMC.setPins(PIN_SD_CLK, PIN_SD_CMD, PIN_SD_D0, PIN_SD_D1, PIN_SD_D2, PIN_SD_D3);
// 1-bit 模式在部分卡上更稳;这里用 4-bit,失败再回落
if (!SD_MMC.begin("/sdcard", false, false, 20000)) {
LOG("HAL", "SD 4-bit mount failed, retry 1-bit");
SD_MMC.end();
if (!SD_MMC.begin("/sdcard", true, false, 20000)) {
LOG("HAL", "SD mount failed (no card?)");
_ready = false;
return false;
}
}
_ready = true;
LOG("HAL", "SD mounted: %llu MB total, %llu MB used",
SD_MMC.totalBytes() / (1024ULL * 1024ULL),
SD_MMC.usedBytes() / (1024ULL * 1024ULL));
return true;
}
bool storageReady() { return _ready; }
uint64_t storageTotalBytes() { return _ready ? SD_MMC.totalBytes() : 0; }
uint64_t storageUsedBytes() { return _ready ? SD_MMC.usedBytes() : 0; }
void storageLock() { if (_mtx) xSemaphoreTakeRecursive(_mtx, portMAX_DELAY); }
void storageUnlock() { if (_mtx) xSemaphoreGiveRecursive(_mtx); }
std::vector<String> listDir(const String& dirPath) {
std::vector<String> out;
if (!_ready) return out;
StorageLock guard;
File dir = SD_MMC.open(dirPath);
if (!dir || !dir.isDirectory()) return out;
File f = dir.openNextFile();
while (f) {
String name = f.name();
int slash = name.lastIndexOf('/');
if (slash >= 0) name = name.substring(slash + 1);
if (!name.startsWith(".")) out.push_back(name); // 过滤 macOS 的 ._ 垃圾文件
f.close();
f = dir.openNextFile();
}
dir.close();
return out;
}
} // namespace hal