sd_variant: SD-Bibliothek durch POSIX-Dateizugriff ersetzen, USB-MSC-Lesefehler beheben
Realer Hardwaretest deckte zwei von der Verkabelung unabhaengige Bugs auf: - SD.exists()/SD.open() scheiterten immer mit "File system is not mounted", weil SD.begin() nie aufgerufen wird (sdcard_init()/ sdcard_mount() laufen direkt, um Zugriff auf g_pdrv zu behalten) und die Arduino-SD-Bibliothek dadurch ihren Mountpoint nie kennt. Fix: Nextcloud-Sync, Upload/List/Delete auf plain POSIX-Funktionen (fopen/opendir/...) umgestellt, analog zu flash_variant. - enterUsbExposedState() rief sdcard_unmount() auf, was intern card->status |= STA_NOINIT setzt - dieses Flag blockiert jeden weiteren sd_read_raw()/sd_write_raw()-Aufruf, bis eine volle Kartenneuerkennung ueber einen FAT-Mount laeuft. Da genau diese beiden Funktionen aber fuer den rohen USB-MSC-Zugriff im USB_EXPOSED-Zustand gebraucht werden, blieb das Laufwerk fuer den Host dauerhaft unlesbar (Windows: Dateisystem leer, Laufwerk wird ausgeworfen) - unabhaengig von der SD-Verkabelung. Fix: manuelles f_mount(nullptr,...) + esp_vfs_fat_unregister_path() statt sdcard_unmount(), damit die Karte initialisiert bleibt. Nach dem Fix: Boot-Sektor-Signatur (0x55AA) korrekt lesbar, Nextcloud- Sync/Liste funktionieren, /sync und /release wechseln sauber hin und her. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
970677c69a
commit
bd870ce7a6
2 files changed
+100
-52
No files matched your search
@@ -27,7 +27,33 @@ pio run -e flash_variant --target upload # nur interner Flash, ohne SD-Karte
|
||||
|
||||
Nutzt eine SPI-SD-Karte als Backing Store. Rohe Sektorzugriffe fuer USB MSC
|
||||
laufen ueber die internen `sd_diskio`-Funktionen (`sd_read_raw`/`sd_write_raw`),
|
||||
das Dateisystem fuer den WLAN-Upload ueber die normale `SD`-Bibliothek.
|
||||
das Dateisystem fuer den WLAN-Upload ueber plain POSIX-Funktionen
|
||||
(`fopen`/`opendir`/...) statt ueber die Arduino-`SD`-Bibliothek - siehe
|
||||
Code-Kommentar bei `BASE_PATH` in `main_sd_variant.cpp` fuer die Begruendung
|
||||
(die `SD`-Bibliothek braucht zusaetzlich `SD.begin()`, um ihren eigenen
|
||||
Mountpoint zu kennen, was hier bewusst nicht gemacht wird, da `sdcard_init()`/
|
||||
`sdcard_mount()` direkt aufgerufen werden, um Zugriff auf den rohen
|
||||
Laufwerks-Handle `g_pdrv` zu behalten).
|
||||
|
||||
**Realer Hardwaretest deckte zwei weitere, unabhaengig von der Verkabelung
|
||||
bestehende Bugs auf** (beide behoben):
|
||||
|
||||
1. Die Arduino-`SD`-Bibliothek kannte ihren Mountpoint nie (s.o.), daher
|
||||
scheiterten `SD.exists()`/`SD.open()` in der Nextcloud-Sync und den
|
||||
Upload/List/Delete-Handlern immer mit "File system is not mounted" -
|
||||
unabhaengig vom tatsaechlichen Kartenzustand.
|
||||
2. `enterUsbExposedState()` rief `sdcard_unmount()` auf, was intern
|
||||
`card->status |= STA_NOINIT` setzt. Dieses Flag wird nur durch eine volle
|
||||
Kartenneuerkennung ueber `sdcard_mount()` (also einen FAT-Mount)
|
||||
zurueckgesetzt - `sd_read_raw()`/`sd_write_raw()` (die fuer den rohen
|
||||
USB-MSC-Zugriff im `USB_EXPOSED`-Zustand gebraucht werden) pruefen
|
||||
dieses Flag aber zuerst und schlagen sonst fehl. Ergebnis: der
|
||||
Plasmaschneider/Windows saeh ein Medium, dessen Sektoren sich nicht lesen
|
||||
lassen (Dateisystem leer, Laufwerk wird dauerhaft ausgeworfen) - und zwar
|
||||
bei **jeder** Verkabelung, da der Fehler rein softwareseitig war. Fix:
|
||||
beim Wechsel nach `USB_EXPOSED` nur noch `f_mount(nullptr, ...)` +
|
||||
`esp_vfs_fat_unregister_path()` manuell aufrufen statt `sdcard_unmount()`,
|
||||
damit die Karte fuer rohe Sektorzugriffe initialisiert bleibt.
|
||||
|
||||
**Verkabelung** (auf frische Pins verlegt nach Verdacht auf beschaedigte
|
||||
Loetstellen bei den urspruenglichen Standard-Pins GPIO10-13):
|
||||
|
||||
+73
-51
@@ -20,11 +20,18 @@
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <Preferences.h>
|
||||
#include <SPI.h>
|
||||
#include <SD.h>
|
||||
#include <sd_diskio.h>
|
||||
#include "USB.h"
|
||||
#include "USBMSC.h"
|
||||
|
||||
#include <dirent.h>
|
||||
#include <stdio.h>
|
||||
|
||||
extern "C" {
|
||||
#include "esp_vfs_fat.h"
|
||||
#include "ff.h"
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Konfiguration - vor dem Flashen anpassen!
|
||||
// ---------------------------------------------------------------------
|
||||
@@ -114,6 +121,16 @@ static const int SD_MISO_PIN = 17;
|
||||
static const int SD_MOSI_PIN = 21;
|
||||
static const uint32_t SD_SPI_HZ = 4000000; // konservativ gewaehlt fuer die frisch verloeteten Leitungen
|
||||
|
||||
// Mountpoint, wie er per sdcard_mount() bei der ESP-IDF-VFS-Schicht registriert
|
||||
// wird (esp_vfs_fat_register() innerhalb von sdcard_mount()). Datei-Zugriffe
|
||||
// laufen bewusst ueber die POSIX-Standardfunktionen (fopen/opendir/...) statt
|
||||
// ueber die Arduino-SD-Bibliothek: Letztere braucht zusaetzlich SD.begin(),
|
||||
// um ihren eigenen Mountpoint zu kennen - da dieses Projekt aber direkt
|
||||
// sdcard_init()/sdcard_mount() aufruft (fuer den Zugriff auf g_pdrv), bliebe
|
||||
// SD.exists()/SD.open() sonst immer mit "File system is not mounted"
|
||||
// fehlgeschlagen, unabhaengig vom tatsaechlichen Kartenzustand.
|
||||
static const char *BASE_PATH = "/sd";
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
enum class BridgeState : uint8_t { NETWORK_SYNC, USB_EXPOSED };
|
||||
@@ -206,7 +223,7 @@ static bool enterNetworkSyncState() {
|
||||
flushCache();
|
||||
invalidateCache();
|
||||
MSC.mediaPresent(false);
|
||||
if (!sdcard_mount(g_pdrv, "/sd", 5, false)) {
|
||||
if (!sdcard_mount(g_pdrv, BASE_PATH, 5, false)) {
|
||||
Serial.println("FEHLER: SD-Karte konnte nicht (wieder) gemountet werden");
|
||||
g_fsMounted = false;
|
||||
return false;
|
||||
@@ -218,14 +235,26 @@ static bool enterNetworkSyncState() {
|
||||
|
||||
static bool enterUsbExposedState() {
|
||||
if (g_state == BridgeState::USB_EXPOSED && !g_fsMounted) return true;
|
||||
// sdcard_unmount() nur aufrufen, wenn tatsaechlich ein FAT-Mount aktiv war:
|
||||
// f_mount() beim Unmount eines nie erfolgreich gemounteten Laufwerks
|
||||
// versucht, ein nie angelegtes FreeRTOS-Sync-Objekt zu loeschen
|
||||
// (vQueueDelete auf ungueltigem Handle) - das fuehrt zu einem
|
||||
// Guru-Meditation-Crash (LoadProhibited), reproduzierbar wenn die
|
||||
// SD-Karte beim Booten nicht gemountet werden konnte.
|
||||
// BEWUSST NICHT sdcard_unmount() verwenden: das setzt intern
|
||||
// card->status |= STA_NOINIT (und card->type = CARD_NONE), und dieses
|
||||
// Flag wird NUR durch eine erneute volle Kartenerkennung in
|
||||
// ff_sd_initialize() geloescht - die aber nur ueber sdcard_mount()
|
||||
// (also einen erneuten FAT-Mount) angestossen wird. Da onMscRead/
|
||||
// onMscWrite fuer den rohen USB-MSC-Zugriff sd_read_raw()/sd_write_raw()
|
||||
// aufrufen, die genau dieses Flag zuerst pruefen (ff_sd_read/ff_sd_write:
|
||||
// "if (card->status & STA_NOINIT) return RES_NOTRDY"), wuerde jeder
|
||||
// rohe Sektorzugriff im USB_EXPOSED-Zustand fehlschlagen, sobald einmal
|
||||
// sdcard_unmount() aufgerufen wurde - der Host (Windows/RichAuto) saehe
|
||||
// dann ein Medium, dessen Sektoren sich nicht lesen lassen (genau das
|
||||
// real beobachtete Symptom: Dateisystem leer/nicht lesbar, Laufwerk
|
||||
// wird dauerhaft ausgeworfen). Stattdessen nur die FatFs-/VFS-Ebene
|
||||
// manuell freigeben (wie sdcard_unmount() es tut, ohne die beiden
|
||||
// Karten-Statuszeilen), damit die Karte fuer sd_read_raw()/sd_write_raw()
|
||||
// initialisiert bleibt.
|
||||
if (g_fsMounted) {
|
||||
sdcard_unmount(g_pdrv);
|
||||
char drv[3] = { (char)('0' + g_pdrv), ':', 0 };
|
||||
f_mount(nullptr, drv, 0);
|
||||
esp_vfs_fat_unregister_path(BASE_PATH);
|
||||
g_fsMounted = false;
|
||||
}
|
||||
invalidateCache();
|
||||
@@ -245,7 +274,6 @@ static bool enterUsbExposedState() {
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static String sanitizeFilename(const String &name); // Vorwaertsdeklaration
|
||||
static String baseName(const String &path); // Vorwaertsdeklaration
|
||||
|
||||
// Dekodiert sowohl Prozent-Escapes (%20) als auch die von Nextclouds
|
||||
// PROPFIND-Antwort verwendeten XML-Entities (& < > ' ") -
|
||||
@@ -289,10 +317,9 @@ static bool fetchAndSaveFile(WiFiClientSecure &client, const String &url, const
|
||||
// Download auf den echten Namen umbenennen - sonst wuerde ein WLAN-Abbruch
|
||||
// mitten im Download eine halbe/kaputte Datei unter dem finalen Namen
|
||||
// hinterlassen, die der Plasmaschneider dann faelschlich als gueltig ansieht.
|
||||
String finalPath = "/" + filename;
|
||||
String finalPath = String(BASE_PATH) + "/" + filename;
|
||||
String tmpPath = finalPath + ".part";
|
||||
if (SD.exists(tmpPath)) SD.remove(tmpPath);
|
||||
File out = SD.open(tmpPath, FILE_WRITE);
|
||||
FILE *out = fopen(tmpPath.c_str(), "wb");
|
||||
if (!out) {
|
||||
Serial.printf("Nextcloud: Datei '%s' konnte nicht angelegt werden\n", filename.c_str());
|
||||
http.end();
|
||||
@@ -308,7 +335,7 @@ static bool fetchAndSaveFile(WiFiClientSecure &client, const String &url, const
|
||||
size_t avail = stream->available();
|
||||
if (avail) {
|
||||
int c = stream->readBytes(buf, avail > sizeof(buf) ? sizeof(buf) : avail);
|
||||
out.write(buf, c);
|
||||
fwrite(buf, 1, c, out);
|
||||
if (remaining > 0) remaining -= c;
|
||||
lastData = millis();
|
||||
} else if (millis() - lastData > 10000) {
|
||||
@@ -318,18 +345,18 @@ static bool fetchAndSaveFile(WiFiClientSecure &client, const String &url, const
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
out.close();
|
||||
fclose(out);
|
||||
http.end();
|
||||
|
||||
bool complete = !timedOut && (remaining == 0 || remaining == -1);
|
||||
if (!complete) {
|
||||
Serial.printf("Nextcloud: Download von '%s' unvollstaendig, verwerfe Teildatei\n", filename.c_str());
|
||||
SD.remove(tmpPath);
|
||||
remove(tmpPath.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (SD.exists(finalPath)) SD.remove(finalPath);
|
||||
SD.rename(tmpPath, finalPath);
|
||||
remove(finalPath.c_str()); // vorherige Version ersetzen
|
||||
rename(tmpPath.c_str(), finalPath.c_str());
|
||||
Serial.printf("Nextcloud: '%s' heruntergeladen\n", filename.c_str());
|
||||
return true;
|
||||
}
|
||||
@@ -393,19 +420,17 @@ static bool syncFromNextcloud() {
|
||||
// waehrend der laufenden Verzeichnis-Iteration zu loeschen.
|
||||
String toRemove = "|";
|
||||
{
|
||||
File root = SD.open("/");
|
||||
if (root) {
|
||||
File f = root.openNextFile();
|
||||
while (f) {
|
||||
if (!f.isDirectory()) {
|
||||
String name = baseName(f.name());
|
||||
DIR *dir = opendir(BASE_PATH);
|
||||
if (dir) {
|
||||
struct dirent *entry;
|
||||
while ((entry = readdir(dir)) != nullptr) {
|
||||
if (entry->d_type == DT_DIR) continue;
|
||||
String name = String(entry->d_name);
|
||||
if ((name.endsWith(".tap") || name.endsWith(".TAP")) && expected.indexOf("|" + name + "|") < 0) {
|
||||
toRemove += name + "|";
|
||||
}
|
||||
}
|
||||
f = root.openNextFile();
|
||||
}
|
||||
root.close();
|
||||
closedir(dir);
|
||||
}
|
||||
}
|
||||
int removed = 0;
|
||||
@@ -415,7 +440,8 @@ static bool syncFromNextcloud() {
|
||||
if (bar < 0) break;
|
||||
String name = toRemove.substring(p, bar);
|
||||
p = bar + 1;
|
||||
SD.remove("/" + name);
|
||||
String path = String(BASE_PATH) + "/" + name;
|
||||
remove(path.c_str());
|
||||
removed++;
|
||||
Serial.printf("Nextcloud-Sync: '%s' lokal entfernt (nicht mehr in Nextcloud)\n", name.c_str());
|
||||
}
|
||||
@@ -459,16 +485,11 @@ static String sanitizeFilename(const String &name) {
|
||||
return out;
|
||||
}
|
||||
|
||||
static String baseName(const String &path) {
|
||||
int idx = path.lastIndexOf('/');
|
||||
return idx >= 0 ? path.substring(idx + 1) : path;
|
||||
}
|
||||
|
||||
static String stateToString() {
|
||||
return g_state == BridgeState::NETWORK_SYNC ? "network_sync" : "usb_exposed";
|
||||
}
|
||||
|
||||
static File g_uploadFile;
|
||||
static FILE *g_uploadFile = nullptr;
|
||||
static bool g_uploadAllowed = false;
|
||||
|
||||
static void handleUploadData() {
|
||||
@@ -477,13 +498,12 @@ static void handleUploadData() {
|
||||
if (upload.status == UPLOAD_FILE_START) {
|
||||
g_uploadAllowed = (g_state == BridgeState::NETWORK_SYNC);
|
||||
if (!g_uploadAllowed) return;
|
||||
String path = "/" + sanitizeFilename(upload.filename);
|
||||
if (SD.exists(path)) SD.remove(path);
|
||||
g_uploadFile = SD.open(path, FILE_WRITE);
|
||||
String path = String(BASE_PATH) + "/" + sanitizeFilename(upload.filename);
|
||||
g_uploadFile = fopen(path.c_str(), "wb");
|
||||
} else if (upload.status == UPLOAD_FILE_WRITE) {
|
||||
if (g_uploadAllowed && g_uploadFile) g_uploadFile.write(upload.buf, upload.currentSize);
|
||||
if (g_uploadAllowed && g_uploadFile) fwrite(upload.buf, 1, upload.currentSize, g_uploadFile);
|
||||
} else if (upload.status == UPLOAD_FILE_END || upload.status == UPLOAD_FILE_ABORTED) {
|
||||
if (g_uploadFile) g_uploadFile.close();
|
||||
if (g_uploadFile) { fclose(g_uploadFile); g_uploadFile = nullptr; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,19 +540,22 @@ static void handleStatus() {
|
||||
static void handleList() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (g_state != BridgeState::NETWORK_SYNC) { sendLocked(); return; }
|
||||
File root = SD.open("/");
|
||||
String j = "[";
|
||||
bool first = true;
|
||||
if (root) {
|
||||
File f = root.openNextFile();
|
||||
while (f) {
|
||||
if (!f.isDirectory()) {
|
||||
DIR *dir = opendir(BASE_PATH);
|
||||
if (dir) {
|
||||
struct dirent *entry;
|
||||
while ((entry = readdir(dir)) != nullptr) {
|
||||
if (entry->d_type == DT_DIR) continue;
|
||||
String path = String(BASE_PATH) + "/" + entry->d_name;
|
||||
FILE *f = fopen(path.c_str(), "rb");
|
||||
long size = 0;
|
||||
if (f) { fseek(f, 0, SEEK_END); size = ftell(f); fclose(f); }
|
||||
if (!first) j += ",";
|
||||
first = false;
|
||||
j += "{\"name\":\"" + baseName(f.name()) + "\",\"size\":" + String(f.size()) + "}";
|
||||
}
|
||||
f = root.openNextFile();
|
||||
j += "{\"name\":\"" + String(entry->d_name) + "\",\"size\":" + String(size) + "}";
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
sendJson(200, j + "]");
|
||||
}
|
||||
@@ -541,9 +564,8 @@ static void handleDelete() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (g_state != BridgeState::NETWORK_SYNC) { sendLocked(); return; }
|
||||
if (!server.hasArg("name")) { sendJson(400, "{\"error\":\"missing_name\"}"); return; }
|
||||
String path = "/" + sanitizeFilename(server.arg("name"));
|
||||
if (!SD.exists(path)) { sendJson(404, "{\"error\":\"not_found\"}"); return; }
|
||||
SD.remove(path);
|
||||
String path = String(BASE_PATH) + "/" + sanitizeFilename(server.arg("name"));
|
||||
if (remove(path.c_str()) != 0) { sendJson(404, "{\"error\":\"not_found\"}"); return; }
|
||||
sendJson(200, "{\"ok\":true}");
|
||||
}
|
||||
|
||||
@@ -682,7 +704,7 @@ void setup() {
|
||||
g_pdrv = sdcard_init(SD_CS_PIN, &SPI, SD_SPI_HZ);
|
||||
if (g_pdrv == 0xFF) {
|
||||
Serial.println("FATAL: SD-Karte nicht gefunden - Verkabelung pruefen!");
|
||||
} else if (!sdcard_mount(g_pdrv, "/sd", 5, true /* format_if_empty */)) {
|
||||
} else if (!sdcard_mount(g_pdrv, BASE_PATH, 5, true /* format_if_empty */)) {
|
||||
Serial.println("FATAL: SD-Karte konnte nicht gemountet werden!");
|
||||
} else {
|
||||
g_sectorSize = sdcard_sector_size(g_pdrv);
|
||||
|
||||
Reference in new issue
Block a user