Initial commit: ESP32-S3 USB-Stick-Bridge fuer Plasmaschneider
This commit is contained in:
commit
0567f4ec41
7 files changed
+1831
No files matched your search
@@ -0,0 +1,713 @@
|
||||
// Springers Plasma Software - USB-Stick-Bridge (ESP32-S3), Flash-Variante
|
||||
//
|
||||
// Wie main_sd_variant.cpp, aber ohne SD-Karte: Backing Store ist die
|
||||
// dedizierte Flash-Partition "storage" (siehe partitions.csv), verwaltet
|
||||
// per ESP-IDF Wear-Levelling-Bibliothek.
|
||||
//
|
||||
// WICHTIG: FAT-Dateisystem-Mount (fuer WLAN-Schreibzugriff) und roher
|
||||
// Wear-Levelling-Sektorzugriff (fuer USB-MSC) duerfen NIEMALS gleichzeitig
|
||||
// aktiv sein - sonst laufen die internen Caches auseinander und die
|
||||
// Partition korrumpiert. Es ist daher zu jedem Zeitpunkt hoechstens ein
|
||||
// wl_mount() auf dieser Partition aktiv:
|
||||
// NETWORK_SYNC : esp_vfs_fat_spiflash_mount() aktiv (FAT+WL kombiniert),
|
||||
// WLAN-Upload moeglich, USB-Stick fuer den Plasmaschneider
|
||||
// unsichtbar (kein Medium).
|
||||
// USB_EXPOSED : FAT-Mount ausgehaengt, stattdessen roher wl_mount() fuer
|
||||
// die MSC-Callbacks aktiv. WLAN-Uploads -> HTTP 423.
|
||||
//
|
||||
// BEKANNTER RISIKOPUNKT: Die Wear-Levelling-Sektorgroesse ist in diesem
|
||||
// arduino-esp32-Core fest auf 4096 Byte einkompiliert (CONFIG_WL_SECTOR_SIZE),
|
||||
// nicht auf 512 Byte umstellbar ohne den Core aus dem Quellcode neu zu
|
||||
// bauen. Falls der RichAuto-Controller nur 512-Byte-Sektoren akzeptiert,
|
||||
// muss auf main_sd_variant.cpp (SD-Karte) zurueckgefallen werden.
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <WebServer.h>
|
||||
#include <HTTPClient.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <Preferences.h>
|
||||
#include "USB.h"
|
||||
#include "USBMSC.h"
|
||||
|
||||
extern "C" {
|
||||
#include "esp_partition.h"
|
||||
#include "esp_vfs_fat.h"
|
||||
#include "wear_levelling.h"
|
||||
}
|
||||
|
||||
#include <dirent.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Konfiguration - vor dem Flashen anpassen!
|
||||
// ---------------------------------------------------------------------
|
||||
// Bekannte WLANs je nach moeglichem Aufstellungsort des Plasmaschneiders.
|
||||
// Die Firmware probiert beim Boot jedes davon der Reihe nach per WiFi.begin()
|
||||
// (kein Scan-basierter Abgleich - erwies sich als unzuverlaessiger als
|
||||
// direktes Verbinden). Zusaetzlich bleibt der Konfigurations-Hotspot als
|
||||
// Fallback fuer einen komplett neuen, hier noch nicht hinterlegten Standort
|
||||
// aktiv.
|
||||
struct WifiCredential { const char *ssid; const char *password; };
|
||||
static const WifiCredential KNOWN_WIFI_NETWORKS[] = {
|
||||
{ "Leonardo da WiFi", "44290812080358610465" },
|
||||
{ "FRITZ!Box 7490 (UI)", "66015959757493719529" },
|
||||
{ "Raederknecht", "34487670821857484552" },
|
||||
};
|
||||
static const size_t KNOWN_WIFI_NETWORKS_COUNT = sizeof(KNOWN_WIFI_NETWORKS) / sizeof(KNOWN_WIFI_NETWORKS[0]);
|
||||
|
||||
const char *AP_SSID = "PlasmaBridge-Setup";
|
||||
const char *AUTH_TOKEN = "CHANGE_ME"; // z.B. mit `openssl rand -hex 32` erzeugen
|
||||
static const uint32_t WIFI_CONNECT_TIMEOUT_MS = 12000; // pro Netzwerk
|
||||
|
||||
// Nextcloud-WebDAV-Ordner, aus dem beim Boot (und per POST /nextcloud/sync)
|
||||
// neue .tap-Dateien automatisch abgeholt werden, bevor der Stick fuer den
|
||||
// Plasmaschneider sichtbar wird. Nur ueber die oeffentliche HTTPS-Domain
|
||||
// erreichbar (Reverse Proxy) - Zugangsdaten daher fest hier eingetragen.
|
||||
const char *NEXTCLOUD_HOST = "nextcloud.dominicspringer.de";
|
||||
const char *NEXTCLOUD_USER = "Plasma";
|
||||
const char *NEXTCLOUD_APP_PASSWORD = "Springer3888"; // besser: echtes App-Passwort statt Account-Passwort verwenden
|
||||
const char *NEXTCLOUD_FOLDER = "/Plasmadatein"; // WebDAV-Pfad relativ zum Benutzer-Root
|
||||
|
||||
// ISRG Root X1 (Let's Encrypt Root-CA, gueltig bis 2035) - noetig, damit
|
||||
// WiFiClientSecure das Zertifikat des Reverse Proxy validieren kann.
|
||||
static const char *LETSENCRYPT_ROOT_CA = R"EOF(
|
||||
-----BEGIN CERTIFICATE-----
|
||||
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
|
||||
-----END CERTIFICATE-----
|
||||
)EOF";
|
||||
|
||||
static const char *PARTITION_LABEL = "storage"; // muss zu partitions.csv passen
|
||||
static const char *BASE_PATH = "/storage";
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
enum class BridgeState : uint8_t { NETWORK_SYNC, USB_EXPOSED };
|
||||
static volatile BridgeState g_state = BridgeState::NETWORK_SYNC;
|
||||
|
||||
static const esp_partition_t *g_partition = nullptr;
|
||||
static wl_handle_t g_wlHandle = WL_INVALID_HANDLE;
|
||||
static uint32_t g_sectorSize = 4096;
|
||||
static uint32_t g_sectorCount = 0;
|
||||
|
||||
WebServer server(80);
|
||||
USBMSC MSC;
|
||||
|
||||
// Ein-Sektor-Cache: rohes Schreiben auf NOR-Flash erfordert vorheriges
|
||||
// Loeschen des gesamten (4096-Byte-)Sektors. MSC-Schreibzugriffe koennen in
|
||||
// mehreren kleineren Chunks auf denselben Sektor eintreffen, deshalb wird
|
||||
// hier erst gelesen/gepuffert und der Sektor als Ganzes zurueckgeschrieben.
|
||||
static uint8_t g_cacheBuf[4096];
|
||||
static uint32_t g_cacheLba = 0xFFFFFFFF;
|
||||
static bool g_cacheDirty = false;
|
||||
|
||||
static void flushCache() {
|
||||
if (g_cacheDirty && g_cacheLba != 0xFFFFFFFF && g_wlHandle != WL_INVALID_HANDLE) {
|
||||
size_t addr = (size_t)g_cacheLba * g_sectorSize;
|
||||
if (wl_erase_range(g_wlHandle, addr, g_sectorSize) == ESP_OK) {
|
||||
wl_write(g_wlHandle, addr, g_cacheBuf, g_sectorSize);
|
||||
}
|
||||
}
|
||||
g_cacheDirty = false;
|
||||
}
|
||||
|
||||
static void invalidateCache() {
|
||||
g_cacheLba = 0xFFFFFFFF;
|
||||
g_cacheDirty = false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// USB-MSC-Callbacks
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static int32_t onMscRead(uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize) {
|
||||
if (g_state != BridgeState::USB_EXPOSED || g_wlHandle == WL_INVALID_HANDLE) return -1;
|
||||
// Absicherung gegen ungueltige offset/bufsize-Kombinationen (sollten von
|
||||
// TinyUSB nie ausserhalb eines Sektors liegen, aber g_cacheBuf ist ein
|
||||
// Fixed-Size-Puffer - defensiv trotzdem pruefen statt dem Host zu vertrauen.
|
||||
if ((uint64_t)offset + bufsize > g_sectorSize) return -1;
|
||||
if (g_cacheDirty && lba == g_cacheLba) {
|
||||
memcpy(buffer, g_cacheBuf + offset, bufsize);
|
||||
return bufsize;
|
||||
}
|
||||
size_t addr = (size_t)lba * g_sectorSize + offset;
|
||||
if (wl_read(g_wlHandle, addr, buffer, bufsize) != ESP_OK) return -1;
|
||||
return bufsize;
|
||||
}
|
||||
|
||||
static int32_t onMscWrite(uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize) {
|
||||
if (g_state != BridgeState::USB_EXPOSED || g_wlHandle == WL_INVALID_HANDLE) return -1;
|
||||
if ((uint64_t)offset + bufsize > g_sectorSize) return -1;
|
||||
if (lba != g_cacheLba) {
|
||||
flushCache();
|
||||
size_t addr = (size_t)lba * g_sectorSize;
|
||||
if (wl_read(g_wlHandle, addr, g_cacheBuf, g_sectorSize) != ESP_OK) return -1;
|
||||
g_cacheLba = lba;
|
||||
}
|
||||
memcpy(g_cacheBuf + offset, buffer, bufsize);
|
||||
g_cacheDirty = true;
|
||||
return bufsize;
|
||||
}
|
||||
|
||||
static bool onMscStartStop(uint8_t power_condition, bool start, bool load_eject) {
|
||||
if (load_eject && !start) flushCache();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Zustandswechsel
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static bool enterNetworkSyncState() {
|
||||
// Zusaetzlich g_wlHandle pruefen: falls ein vorheriger Wechsel fehlgeschlagen
|
||||
// ist, wuerde der reine g_state-Vergleich einen erneuten Mount-Versuch
|
||||
// faelschlich uebergehen und den Stick dauerhaft in einem kaputten
|
||||
// Zwischenzustand belassen (weder Netzwerk- noch USB-Zugriff moeglich).
|
||||
if (g_state == BridgeState::NETWORK_SYNC && g_wlHandle != WL_INVALID_HANDLE) return true;
|
||||
MSC.mediaPresent(false);
|
||||
if (g_wlHandle != WL_INVALID_HANDLE) {
|
||||
wl_unmount(g_wlHandle);
|
||||
g_wlHandle = WL_INVALID_HANDLE;
|
||||
}
|
||||
invalidateCache();
|
||||
esp_vfs_fat_mount_config_t mount_config = {};
|
||||
mount_config.format_if_mount_failed = true;
|
||||
mount_config.max_files = 5;
|
||||
mount_config.allocation_unit_size = 0;
|
||||
esp_err_t err = esp_vfs_fat_spiflash_mount(BASE_PATH, PARTITION_LABEL, &mount_config, &g_wlHandle);
|
||||
if (err != ESP_OK) {
|
||||
Serial.printf("FEHLER: FAT-Mount fehlgeschlagen (%d)\n", (int)err);
|
||||
g_wlHandle = WL_INVALID_HANDLE;
|
||||
return false;
|
||||
}
|
||||
g_state = BridgeState::NETWORK_SYNC;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool enterUsbExposedState() {
|
||||
if (g_state == BridgeState::USB_EXPOSED && g_wlHandle != WL_INVALID_HANDLE) return true;
|
||||
esp_vfs_fat_spiflash_unmount(BASE_PATH, g_wlHandle);
|
||||
g_wlHandle = WL_INVALID_HANDLE;
|
||||
invalidateCache();
|
||||
esp_err_t err = wl_mount(g_partition, &g_wlHandle);
|
||||
if (err != ESP_OK) {
|
||||
Serial.printf("FEHLER: Roh-Mount fehlgeschlagen (%d)\n", (int)err);
|
||||
g_wlHandle = WL_INVALID_HANDLE;
|
||||
return false;
|
||||
}
|
||||
g_state = BridgeState::USB_EXPOSED;
|
||||
MSC.mediaPresent(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Nextcloud-Sync: holt .tap-Dateien aus einem WebDAV-Ordner und legt sie
|
||||
// lokal ab. Laeuft nur, waehrend das Dateisystem gemountet ist
|
||||
// (NETWORK_SYNC) - wird im setup() vor dem Wechsel nach USB_EXPOSED
|
||||
// aufgerufen, sowie manuell per POST /nextcloud/sync.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static String sanitizeFilename(const String &name); // Vorwaertsdeklaration
|
||||
|
||||
// Dekodiert sowohl Prozent-Escapes (%20) als auch die von Nextclouds
|
||||
// PROPFIND-Antwort verwendeten XML-Entities (& < > ' ") -
|
||||
// ohne Letzteres wuerden Dateinamen mit diesen Zeichen falsch uebernommen.
|
||||
static String urlDecode(const String &in) {
|
||||
String out;
|
||||
for (size_t i = 0; i < in.length(); i++) {
|
||||
char c = in[i];
|
||||
if (c == '%' && i + 2 < in.length()) {
|
||||
char hex[3] = { in[i + 1], in[i + 2], 0 };
|
||||
out += (char)strtol(hex, nullptr, 16);
|
||||
i += 2;
|
||||
} else if (c == '+') {
|
||||
out += ' ';
|
||||
} else if (c == '&') {
|
||||
if (in.startsWith("&", i)) { out += '&'; i += 4; }
|
||||
else if (in.startsWith("<", i)) { out += '<'; i += 3; }
|
||||
else if (in.startsWith(">", i)) { out += '>'; i += 3; }
|
||||
else if (in.startsWith("'", i)){ out += '\''; i += 5; }
|
||||
else if (in.startsWith(""", i)){ out += '"'; i += 5; }
|
||||
else out += c;
|
||||
} else {
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static bool fetchAndSaveFile(WiFiClientSecure &client, const String &url, const String &filename) {
|
||||
HTTPClient http;
|
||||
if (!http.begin(client, url)) return false;
|
||||
http.setAuthorization(NEXTCLOUD_USER, NEXTCLOUD_APP_PASSWORD);
|
||||
int code = http.GET();
|
||||
if (code != HTTP_CODE_OK) {
|
||||
Serial.printf("Nextcloud: Download von '%s' fehlgeschlagen (HTTP %d)\n", filename.c_str(), code);
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Erst in eine temporaere Datei schreiben und nur bei vollstaendigem
|
||||
// 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 = String(BASE_PATH) + "/" + filename;
|
||||
String tmpPath = finalPath + ".part";
|
||||
FILE *out = fopen(tmpPath.c_str(), "wb");
|
||||
if (!out) {
|
||||
Serial.printf("Nextcloud: Datei '%s' konnte nicht angelegt werden\n", filename.c_str());
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
|
||||
WiFiClient *stream = http.getStreamPtr();
|
||||
int remaining = http.getSize();
|
||||
uint8_t buf[1024];
|
||||
unsigned long lastData = millis();
|
||||
bool timedOut = false;
|
||||
while (http.connected() && (remaining > 0 || remaining == -1)) {
|
||||
size_t avail = stream->available();
|
||||
if (avail) {
|
||||
int c = stream->readBytes(buf, avail > sizeof(buf) ? sizeof(buf) : avail);
|
||||
fwrite(buf, 1, c, out);
|
||||
if (remaining > 0) remaining -= c;
|
||||
lastData = millis();
|
||||
} else if (millis() - lastData > 10000) {
|
||||
timedOut = true;
|
||||
break; // 10s ohne Daten -> Verbindung aufgeben
|
||||
} else {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
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());
|
||||
remove(tmpPath.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
static bool syncFromNextcloud() {
|
||||
WiFiClientSecure client;
|
||||
client.setCACert(LETSENCRYPT_ROOT_CA);
|
||||
|
||||
String folderUrl = String("https://") + NEXTCLOUD_HOST + "/remote.php/dav/files/" + NEXTCLOUD_USER + NEXTCLOUD_FOLDER + "/";
|
||||
|
||||
HTTPClient http;
|
||||
if (!http.begin(client, folderUrl)) {
|
||||
Serial.println("Nextcloud: PROPFIND begin() fehlgeschlagen");
|
||||
return false;
|
||||
}
|
||||
http.setAuthorization(NEXTCLOUD_USER, NEXTCLOUD_APP_PASSWORD);
|
||||
http.addHeader("Depth", "1");
|
||||
int code = http.sendRequest("PROPFIND", "");
|
||||
if (code != 207 && code != 200) {
|
||||
Serial.printf("Nextcloud: PROPFIND fehlgeschlagen (HTTP %d)\n", code);
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
String xml = http.getString();
|
||||
http.end();
|
||||
|
||||
int pos = 0;
|
||||
int candidates = 0;
|
||||
int downloaded = 0;
|
||||
// Liste aller aktuell in Nextcloud vorhandenen Dateinamen (mit "|" umrahmt,
|
||||
// damit ein Teilstring-Vergleich keine falschen Treffer liefert) - fuer den
|
||||
// Spiegel-Abgleich weiter unten.
|
||||
String expected = "|";
|
||||
while (true) {
|
||||
int start = xml.indexOf("<d:href>", pos);
|
||||
if (start < 0) break;
|
||||
start += 8;
|
||||
int end = xml.indexOf("</d:href>", start);
|
||||
if (end < 0) break;
|
||||
String href = xml.substring(start, end);
|
||||
pos = end + 9;
|
||||
|
||||
if (!href.endsWith(".tap") && !href.endsWith(".TAP")) continue;
|
||||
candidates++;
|
||||
int slash = href.lastIndexOf('/');
|
||||
String encodedName = slash >= 0 ? href.substring(slash + 1) : href;
|
||||
String filename = sanitizeFilename(urlDecode(encodedName));
|
||||
expected += filename + "|";
|
||||
|
||||
String fileUrl = "https://" + String(NEXTCLOUD_HOST) + href;
|
||||
if (fetchAndSaveFile(client, fileUrl, filename)) downloaded++;
|
||||
}
|
||||
Serial.printf("Nextcloud-Sync: %d/%d Datei(en) aktualisiert\n", downloaded, candidates);
|
||||
|
||||
// Spiegel-Sync: lokale .tap-Dateien loeschen, die nicht mehr in Nextcloud
|
||||
// liegen. Echte Verbindungs-/Auth-Fehler wurden oben beim PROPFIND schon
|
||||
// per fruehem return abgefangen - eine erfolgreiche Antwort (207/200) mit
|
||||
// null Treffern bedeutet also zuverlaessig "Ordner ist leer", nicht
|
||||
// "Verbindung war kurz weg".
|
||||
int removed = 0;
|
||||
{
|
||||
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")) continue;
|
||||
if (expected.indexOf("|" + name + "|") < 0) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
}
|
||||
if (removed > 0) Serial.printf("Nextcloud-Sync: %d Datei(en) entfernt\n", removed);
|
||||
|
||||
// Nur dann als Fehlschlag melden, wenn Dateien gefunden wurden, aber keine
|
||||
// einzige davon heruntergeladen werden konnte (z.B. Zugangsdaten falsch).
|
||||
return candidates == 0 || downloaded > 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// HTTP-API
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static bool checkAuth() {
|
||||
String expected = String("Bearer ") + AUTH_TOKEN;
|
||||
String got = server.header("Authorization");
|
||||
if (got.length() != expected.length()) return false;
|
||||
uint8_t diff = 0;
|
||||
for (size_t i = 0; i < expected.length(); i++) diff |= (uint8_t)(got[i] ^ expected[i]);
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
static void sendJson(int code, const String &json) {
|
||||
server.send(code, "application/json", json);
|
||||
}
|
||||
|
||||
static void sendUnauthorized() { sendJson(401, "{\"error\":\"unauthorized\"}"); }
|
||||
|
||||
static void sendLocked() {
|
||||
sendJson(423, "{\"error\":\"stick_exposed_to_cutter\"}");
|
||||
}
|
||||
|
||||
static String sanitizeFilename(const String &name) {
|
||||
String out;
|
||||
for (size_t i = 0; i < name.length(); i++) {
|
||||
char c = name[i];
|
||||
if (isalnum((unsigned char)c) || c == '_' || c == '.' || c == '-') out += c;
|
||||
}
|
||||
if (out.length() == 0) out = "upload.tap";
|
||||
return out;
|
||||
}
|
||||
|
||||
static String stateToString() {
|
||||
return g_state == BridgeState::NETWORK_SYNC ? "network_sync" : "usb_exposed";
|
||||
}
|
||||
|
||||
static FILE *g_uploadFile = nullptr;
|
||||
static bool g_uploadAllowed = false;
|
||||
|
||||
static void handleUploadData() {
|
||||
if (!checkAuth()) return;
|
||||
HTTPUpload &upload = server.upload();
|
||||
if (upload.status == UPLOAD_FILE_START) {
|
||||
g_uploadAllowed = (g_state == BridgeState::NETWORK_SYNC);
|
||||
if (!g_uploadAllowed) return;
|
||||
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) fwrite(upload.buf, 1, upload.currentSize, g_uploadFile);
|
||||
} else if (upload.status == UPLOAD_FILE_END || upload.status == UPLOAD_FILE_ABORTED) {
|
||||
if (g_uploadFile) { fclose(g_uploadFile); g_uploadFile = nullptr; }
|
||||
}
|
||||
}
|
||||
|
||||
static void handleUploadComplete() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (!g_uploadAllowed) { sendLocked(); return; }
|
||||
sendJson(200, "{\"ok\":true}");
|
||||
}
|
||||
|
||||
static void handleSync() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (!enterUsbExposedState()) { sendJson(500, "{\"error\":\"sync_failed\"}"); return; }
|
||||
sendJson(200, "{\"state\":\"" + stateToString() + "\"}");
|
||||
}
|
||||
|
||||
static void handleRelease() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (!enterNetworkSyncState()) { sendJson(500, "{\"error\":\"release_failed\"}"); return; }
|
||||
sendJson(200, "{\"state\":\"" + stateToString() + "\"}");
|
||||
}
|
||||
|
||||
static void handleStatus() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
String j = "{";
|
||||
j += "\"state\":\"" + stateToString() + "\",";
|
||||
j += "\"wifi_connected\":" + String(WiFi.status() == WL_CONNECTED ? "true" : "false") + ",";
|
||||
j += "\"ip\":\"" + WiFi.localIP().toString() + "\",";
|
||||
j += "\"sector_size\":" + String(g_sectorSize) + ",";
|
||||
j += "\"sector_count\":" + String(g_sectorCount);
|
||||
j += "}";
|
||||
sendJson(200, j);
|
||||
}
|
||||
|
||||
static void handleList() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (g_state != BridgeState::NETWORK_SYNC) { sendLocked(); return; }
|
||||
String j = "[";
|
||||
bool first = true;
|
||||
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\":\"" + String(entry->d_name) + "\",\"size\":" + String(size) + "}";
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
sendJson(200, j + "]");
|
||||
}
|
||||
|
||||
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 = String(BASE_PATH) + "/" + sanitizeFilename(server.arg("name"));
|
||||
if (remove(path.c_str()) != 0) { sendJson(404, "{\"error\":\"not_found\"}"); return; }
|
||||
sendJson(200, "{\"ok\":true}");
|
||||
}
|
||||
|
||||
static void handleNotFound() {
|
||||
sendJson(404, "{\"error\":\"not_found\"}");
|
||||
}
|
||||
|
||||
static void handleWifiReset() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
Preferences prefs;
|
||||
prefs.begin("wifi", false);
|
||||
prefs.clear();
|
||||
prefs.end();
|
||||
sendJson(200, "{\"ok\":true,\"message\":\"Neustart in Konfigurations-Hotspot\"}");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
static void handleNextcloudSync() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
bool wasExposed = (g_state == BridgeState::USB_EXPOSED);
|
||||
bool readyForSync = !wasExposed || enterNetworkSyncState();
|
||||
bool ok = readyForSync && syncFromNextcloud();
|
||||
// Sichtbaren Zustand in jedem Fall wiederherstellen versuchen, auch wenn
|
||||
// der Sync fehlgeschlagen ist - der Stick soll fuer den Cutter nicht
|
||||
// unnoetig unsichtbar bleiben.
|
||||
if (wasExposed) enterUsbExposedState();
|
||||
sendJson(ok ? 200 : 500, String("{\"ok\":") + (ok ? "true" : "false") + "}");
|
||||
}
|
||||
|
||||
static void setupHttpServer() {
|
||||
static const char *headerKeys[] = {"Authorization"};
|
||||
server.collectHeaders(headerKeys, 1);
|
||||
server.on("/upload", HTTP_POST, handleUploadComplete, handleUploadData);
|
||||
server.on("/sync", HTTP_POST, handleSync);
|
||||
server.on("/release", HTTP_POST, handleRelease);
|
||||
server.on("/status", HTTP_GET, handleStatus);
|
||||
server.on("/list", HTTP_GET, handleList);
|
||||
server.on("/delete", HTTP_POST, handleDelete);
|
||||
server.on("/wifi/reset", HTTP_POST, handleWifiReset);
|
||||
server.on("/nextcloud/sync", HTTP_POST, handleNextcloudSync);
|
||||
server.onNotFound(handleNotFound);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// WLAN-Konfiguration: Zugangsdaten werden in NVS (Preferences) persistiert
|
||||
// und zur Laufzeit ueber einen Konfigurations-Hotspot eingegeben, statt sie
|
||||
// im Quellcode zu hinterlegen.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static bool tryConnectWifi(const char *ssid, const char *pass) {
|
||||
Serial.printf("Verbinde mit WLAN '%s'", ssid);
|
||||
WiFi.begin(ssid, pass);
|
||||
uint32_t start = millis();
|
||||
while (WiFi.status() != WL_CONNECTED && millis() - start < WIFI_CONNECT_TIMEOUT_MS) {
|
||||
delay(300);
|
||||
Serial.print(".");
|
||||
}
|
||||
Serial.println();
|
||||
return WiFi.status() == WL_CONNECTED;
|
||||
}
|
||||
|
||||
static bool connectToStoredWifi() {
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
for (size_t i = 0; i < KNOWN_WIFI_NETWORKS_COUNT; i++) {
|
||||
if (tryConnectWifi(KNOWN_WIFI_NETWORKS[i].ssid, KNOWN_WIFI_NETWORKS[i].password)) return true;
|
||||
}
|
||||
|
||||
// Zusaetzlich das zuletzt ueber den Konfigurations-Hotspot eingegebene Netzwerk
|
||||
Preferences prefs;
|
||||
prefs.begin("wifi", true /* read-only */);
|
||||
String savedSsid = prefs.getString("ssid", "");
|
||||
String savedPass = prefs.getString("pass", "");
|
||||
prefs.end();
|
||||
if (savedSsid.length() > 0 && tryConnectWifi(savedSsid.c_str(), savedPass.c_str())) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static void handleConfigRoot() {
|
||||
server.send(200, "text/html",
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\">"
|
||||
"<title>Plasma-Bridge WLAN-Setup</title></head><body>"
|
||||
"<h2>Plasma-Bridge WLAN-Konfiguration</h2>"
|
||||
"<form method=\"POST\" action=\"/wifi-config\">"
|
||||
"SSID:<br><input name=\"ssid\" required><br><br>"
|
||||
"Passwort:<br><input name=\"password\" type=\"password\"><br><br>"
|
||||
"<input type=\"submit\" value=\"Speichern und neu starten\">"
|
||||
"</form></body></html>");
|
||||
}
|
||||
|
||||
static void handleConfigSave() {
|
||||
String ssid = server.arg("ssid");
|
||||
String pass = server.arg("password");
|
||||
if (ssid.length() == 0) {
|
||||
server.send(400, "text/html", "<p>SSID darf nicht leer sein. <a href=\"/\">Zurueck</a></p>");
|
||||
return;
|
||||
}
|
||||
Preferences prefs;
|
||||
prefs.begin("wifi", false);
|
||||
prefs.putString("ssid", ssid);
|
||||
prefs.putString("pass", pass);
|
||||
prefs.end();
|
||||
server.send(200, "text/html", "<p>Gespeichert. Das Geraet startet neu und verbindet sich mit dem WLAN.</p>");
|
||||
delay(1500);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
// Blockiert dauerhaft (kehrt nie zurueck) - beendet sich per ESP.restart()
|
||||
// sobald gueltige Zugangsdaten gespeichert wurden.
|
||||
static void runConfigPortal() {
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.softAP(AP_SSID); // offenes WLAN, kein Passwort
|
||||
Serial.print("Kein WLAN konfiguriert/erreichbar - Hotspot gestartet: ");
|
||||
Serial.println(AP_SSID);
|
||||
Serial.print("Verbinde dich damit und rufe http://");
|
||||
Serial.print(WiFi.softAPIP());
|
||||
Serial.println("/ auf, um die Zugangsdaten einzugeben.");
|
||||
|
||||
server.on("/", HTTP_GET, handleConfigRoot);
|
||||
server.on("/wifi-config", HTTP_POST, handleConfigSave);
|
||||
server.onNotFound(handleConfigRoot);
|
||||
server.begin();
|
||||
|
||||
while (true) {
|
||||
server.handleClient();
|
||||
delay(2);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
g_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, PARTITION_LABEL);
|
||||
if (!g_partition) {
|
||||
Serial.println("FATAL: Partition 'storage' nicht gefunden - partitions.csv korrekt geflasht?");
|
||||
} else {
|
||||
// Sektorgeometrie einmalig ermitteln (kurzer roher Mount, sofort wieder frei)
|
||||
wl_handle_t probeHandle = WL_INVALID_HANDLE;
|
||||
if (wl_mount(g_partition, &probeHandle) == ESP_OK) {
|
||||
g_sectorSize = wl_sector_size(probeHandle);
|
||||
g_sectorCount = wl_size(probeHandle) / g_sectorSize;
|
||||
wl_unmount(probeHandle);
|
||||
}
|
||||
if (g_sectorSize == 0 || g_sectorSize > sizeof(g_cacheBuf)) {
|
||||
Serial.printf("FATAL: unerwartete Sektorgroesse %u\n", g_sectorSize);
|
||||
}
|
||||
|
||||
esp_vfs_fat_mount_config_t mount_config = {};
|
||||
mount_config.format_if_mount_failed = true;
|
||||
mount_config.max_files = 5;
|
||||
mount_config.allocation_unit_size = 0;
|
||||
esp_err_t err = esp_vfs_fat_spiflash_mount(BASE_PATH, PARTITION_LABEL, &mount_config, &g_wlHandle);
|
||||
if (err == ESP_OK) {
|
||||
g_state = BridgeState::NETWORK_SYNC;
|
||||
} else {
|
||||
Serial.printf("FATAL: FAT-Mount fehlgeschlagen (%d)\n", (int)err);
|
||||
}
|
||||
}
|
||||
|
||||
MSC.vendorID("Springer");
|
||||
MSC.productID("PlasmaBridge");
|
||||
MSC.productRevision("1.0");
|
||||
MSC.onRead(onMscRead);
|
||||
MSC.onWrite(onMscWrite);
|
||||
MSC.onStartStop(onMscStartStop);
|
||||
MSC.mediaPresent(false); // Start im NETWORK_SYNC-Zustand: fuer den Cutter unsichtbar
|
||||
MSC.begin(g_sectorCount, g_sectorSize);
|
||||
USB.begin();
|
||||
|
||||
if (!connectToStoredWifi()) {
|
||||
runConfigPortal(); // kehrt nie zurueck
|
||||
}
|
||||
Serial.print("IP-Adresse: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
// Frische Dateien von Nextcloud holen, bevor der Stick fuer den
|
||||
// Plasmaschneider sichtbar wird (typischerweise bei jedem Einschalten,
|
||||
// da der ESP32 ueber den USB/OTG-Port vom Cutter mitversorgt wird).
|
||||
syncFromNextcloud();
|
||||
enterUsbExposedState();
|
||||
|
||||
setupHttpServer();
|
||||
server.begin();
|
||||
Serial.println("HTTP-Server gestartet");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
server.handleClient();
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
// Springers Plasma Software - USB-Stick-Bridge (ESP32-S3), SD-Karten-Variante
|
||||
//
|
||||
// Ein ESP32-S3 haengt dauerhaft am nativen USB-Port ("USB"/OTG) eines
|
||||
// RichAuto-DSP-Plasmaschneiders und gibt sich dort als USB-Massenspeicher
|
||||
// (USB MSC) aus. Backing Store ist eine SPI-SD-Karte. Ueber WLAN kann per
|
||||
// HTTP jederzeit eine neue .TAP-Datei hochgeladen werden.
|
||||
//
|
||||
// Zwei sich gegenseitig ausschliessende Zustaende:
|
||||
// NETWORK_SYNC : SD-Karte als Dateisystem gemountet, WLAN-Upload moeglich,
|
||||
// USB-Stick fuer den Plasmaschneider unsichtbar (kein Medium).
|
||||
// USB_EXPOSED : Dateisystem ausgehaengt, Stick sichtbar, WLAN-Uploads
|
||||
// werden mit HTTP 423 abgelehnt.
|
||||
// HTTP POST /sync -> wechselt nach USB_EXPOSED (Stick wird sichtbar)
|
||||
// HTTP POST /release -> wechselt nach NETWORK_SYNC (Stick verschwindet, WLAN frei)
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <WebServer.h>
|
||||
#include <HTTPClient.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <Preferences.h>
|
||||
#include <SPI.h>
|
||||
#include <SD.h>
|
||||
#include <sd_diskio.h>
|
||||
#include "USB.h"
|
||||
#include "USBMSC.h"
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Konfiguration - vor dem Flashen anpassen!
|
||||
// ---------------------------------------------------------------------
|
||||
// Bekannte WLANs je nach moeglichem Aufstellungsort des Plasmaschneiders.
|
||||
// Die Firmware probiert beim Boot jedes davon der Reihe nach per WiFi.begin()
|
||||
// (kein Scan-basierter Abgleich - erwies sich als unzuverlaessiger als
|
||||
// direktes Verbinden). Zusaetzlich bleibt der Konfigurations-Hotspot als
|
||||
// Fallback fuer einen komplett neuen, hier noch nicht hinterlegten Standort
|
||||
// aktiv.
|
||||
struct WifiCredential { const char *ssid; const char *password; };
|
||||
static const WifiCredential KNOWN_WIFI_NETWORKS[] = {
|
||||
{ "Leonardo da WiFi", "44290812080358610465" },
|
||||
{ "FRITZ!Box 7490 (UI)", "66015959757493719529" },
|
||||
{ "Raederknecht", "34487670821857484552" },
|
||||
};
|
||||
static const size_t KNOWN_WIFI_NETWORKS_COUNT = sizeof(KNOWN_WIFI_NETWORKS) / sizeof(KNOWN_WIFI_NETWORKS[0]);
|
||||
|
||||
const char *AP_SSID = "PlasmaBridge-Setup";
|
||||
const char *AUTH_TOKEN = "CHANGE_ME"; // z.B. mit `openssl rand -hex 32` erzeugen
|
||||
static const uint32_t WIFI_CONNECT_TIMEOUT_MS = 12000; // pro Netzwerk
|
||||
|
||||
// Nextcloud-WebDAV-Ordner, aus dem beim Boot (und per POST /nextcloud/sync)
|
||||
// neue .tap-Dateien automatisch abgeholt werden, bevor der Stick fuer den
|
||||
// Plasmaschneider sichtbar wird. Nur ueber die oeffentliche HTTPS-Domain
|
||||
// erreichbar (Reverse Proxy) - Zugangsdaten daher fest hier eingetragen.
|
||||
const char *NEXTCLOUD_HOST = "nextcloud.dominicspringer.de";
|
||||
const char *NEXTCLOUD_USER = "Plasma";
|
||||
const char *NEXTCLOUD_APP_PASSWORD = "Springer3888"; // besser: echtes App-Passwort statt Account-Passwort verwenden
|
||||
const char *NEXTCLOUD_FOLDER = "/Plasmadatein"; // WebDAV-Pfad relativ zum Benutzer-Root
|
||||
|
||||
// ISRG Root X1 (Let's Encrypt Root-CA, gueltig bis 2035) - noetig, damit
|
||||
// WiFiClientSecure das Zertifikat des Reverse Proxy validieren kann.
|
||||
static const char *LETSENCRYPT_ROOT_CA = R"EOF(
|
||||
-----BEGIN CERTIFICATE-----
|
||||
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
|
||||
-----END CERTIFICATE-----
|
||||
)EOF";
|
||||
|
||||
// SPI-Pins fuer das SD-Kartenmodul. Entsprechen den Standard-SPI-Pins des
|
||||
// Freenove ESP32-S3 WROOM Boards (SS=10, SCK=12, MISO=13, MOSI=11).
|
||||
// Bei abweichender Verkabelung hier anpassen (siehe README.md).
|
||||
static const int SD_CS_PIN = 10;
|
||||
static const uint32_t SD_SPI_HZ = 20000000;
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
enum class BridgeState : uint8_t { NETWORK_SYNC, USB_EXPOSED };
|
||||
static volatile BridgeState g_state = BridgeState::NETWORK_SYNC;
|
||||
// Verfolgt den tatsaechlichen Mount-Zustand unabhaengig von g_state, damit ein
|
||||
// fehlgeschlagener Zustandswechsel (z.B. sdcard_mount() schlaegt fehl) beim
|
||||
// naechsten Versuch nicht durch den g_state-Schnellausstieg uebersprungen wird.
|
||||
static bool g_fsMounted = false;
|
||||
|
||||
static uint8_t g_pdrv = 0xFF;
|
||||
static uint32_t g_sectorSize = 512;
|
||||
static uint32_t g_sectorCount = 0;
|
||||
|
||||
WebServer server(80);
|
||||
USBMSC MSC;
|
||||
|
||||
// Ein-Sektor-Cache: SD-Karten liefern/erwarten immer volle 512-Byte-Sektoren,
|
||||
// waehrend MSC-Callbacks in mehreren Teil-Chunks fuer denselben Sektor
|
||||
// aufgerufen werden koennen. Deshalb erst den Sektor lesen, aendern,
|
||||
// gesammelt zurueckschreiben.
|
||||
static uint8_t g_cacheBuf[512];
|
||||
static uint32_t g_cacheLba = 0xFFFFFFFF;
|
||||
static bool g_cacheDirty = false;
|
||||
|
||||
static void flushCache() {
|
||||
if (g_cacheDirty && g_cacheLba != 0xFFFFFFFF && g_pdrv != 0xFF) {
|
||||
sd_write_raw(g_pdrv, g_cacheBuf, g_cacheLba);
|
||||
}
|
||||
g_cacheDirty = false;
|
||||
}
|
||||
|
||||
static void invalidateCache() {
|
||||
g_cacheLba = 0xFFFFFFFF;
|
||||
g_cacheDirty = false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// USB-MSC-Callbacks
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static int32_t onMscRead(uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize) {
|
||||
if (g_state != BridgeState::USB_EXPOSED || g_pdrv == 0xFF) return -1;
|
||||
if (g_cacheDirty && lba == g_cacheLba) {
|
||||
memcpy(buffer, g_cacheBuf + offset, bufsize);
|
||||
return bufsize;
|
||||
}
|
||||
uint8_t sector[512];
|
||||
if (!sd_read_raw(g_pdrv, sector, lba)) return -1;
|
||||
memcpy(buffer, sector + offset, bufsize);
|
||||
return bufsize;
|
||||
}
|
||||
|
||||
static int32_t onMscWrite(uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize) {
|
||||
if (g_state != BridgeState::USB_EXPOSED || g_pdrv == 0xFF) return -1;
|
||||
if (lba != g_cacheLba) {
|
||||
flushCache();
|
||||
if (!sd_read_raw(g_pdrv, g_cacheBuf, lba)) return -1;
|
||||
g_cacheLba = lba;
|
||||
}
|
||||
memcpy(g_cacheBuf + offset, buffer, bufsize);
|
||||
g_cacheDirty = true;
|
||||
return bufsize;
|
||||
}
|
||||
|
||||
static bool onMscStartStop(uint8_t power_condition, bool start, bool load_eject) {
|
||||
if (load_eject && !start) flushCache();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Zustandswechsel
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static bool enterNetworkSyncState() {
|
||||
if (g_state == BridgeState::NETWORK_SYNC && g_fsMounted) return true;
|
||||
flushCache();
|
||||
invalidateCache();
|
||||
MSC.mediaPresent(false);
|
||||
if (!sdcard_mount(g_pdrv, "/sd", 5, false)) {
|
||||
Serial.println("FEHLER: SD-Karte konnte nicht (wieder) gemountet werden");
|
||||
g_fsMounted = false;
|
||||
return false;
|
||||
}
|
||||
g_fsMounted = true;
|
||||
g_state = BridgeState::NETWORK_SYNC;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool enterUsbExposedState() {
|
||||
if (g_state == BridgeState::USB_EXPOSED && !g_fsMounted) return true;
|
||||
sdcard_unmount(g_pdrv);
|
||||
g_fsMounted = false;
|
||||
invalidateCache();
|
||||
g_state = BridgeState::USB_EXPOSED;
|
||||
MSC.mediaPresent(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Nextcloud-Sync: holt .tap-Dateien aus einem WebDAV-Ordner und legt sie
|
||||
// lokal ab. Laeuft nur, waehrend das Dateisystem gemountet ist
|
||||
// (NETWORK_SYNC) - wird im setup() vor dem Wechsel nach USB_EXPOSED
|
||||
// aufgerufen, sowie manuell per POST /nextcloud/sync.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static String sanitizeFilename(const String &name); // Vorwaertsdeklaration
|
||||
|
||||
// Dekodiert sowohl Prozent-Escapes (%20) als auch die von Nextclouds
|
||||
// PROPFIND-Antwort verwendeten XML-Entities (& < > ' ") -
|
||||
// ohne Letzteres wuerden Dateinamen mit diesen Zeichen falsch uebernommen.
|
||||
static String urlDecode(const String &in) {
|
||||
String out;
|
||||
for (size_t i = 0; i < in.length(); i++) {
|
||||
char c = in[i];
|
||||
if (c == '%' && i + 2 < in.length()) {
|
||||
char hex[3] = { in[i + 1], in[i + 2], 0 };
|
||||
out += (char)strtol(hex, nullptr, 16);
|
||||
i += 2;
|
||||
} else if (c == '+') {
|
||||
out += ' ';
|
||||
} else if (c == '&') {
|
||||
if (in.startsWith("&", i)) { out += '&'; i += 4; }
|
||||
else if (in.startsWith("<", i)) { out += '<'; i += 3; }
|
||||
else if (in.startsWith(">", i)) { out += '>'; i += 3; }
|
||||
else if (in.startsWith("'", i)){ out += '\''; i += 5; }
|
||||
else if (in.startsWith(""", i)){ out += '"'; i += 5; }
|
||||
else out += c;
|
||||
} else {
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static bool fetchAndSaveFile(WiFiClientSecure &client, const String &url, const String &filename) {
|
||||
HTTPClient http;
|
||||
if (!http.begin(client, url)) return false;
|
||||
http.setAuthorization(NEXTCLOUD_USER, NEXTCLOUD_APP_PASSWORD);
|
||||
int code = http.GET();
|
||||
if (code != HTTP_CODE_OK) {
|
||||
Serial.printf("Nextcloud: Download von '%s' fehlgeschlagen (HTTP %d)\n", filename.c_str(), code);
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
|
||||
String path = "/" + filename;
|
||||
if (SD.exists(path)) SD.remove(path);
|
||||
File out = SD.open(path, FILE_WRITE);
|
||||
if (!out) {
|
||||
Serial.printf("Nextcloud: Datei '%s' konnte nicht angelegt werden\n", filename.c_str());
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
|
||||
WiFiClient *stream = http.getStreamPtr();
|
||||
int remaining = http.getSize();
|
||||
uint8_t buf[1024];
|
||||
unsigned long lastData = millis();
|
||||
while (http.connected() && (remaining > 0 || remaining == -1)) {
|
||||
size_t avail = stream->available();
|
||||
if (avail) {
|
||||
int c = stream->readBytes(buf, avail > sizeof(buf) ? sizeof(buf) : avail);
|
||||
out.write(buf, c);
|
||||
if (remaining > 0) remaining -= c;
|
||||
lastData = millis();
|
||||
} else if (millis() - lastData > 10000) {
|
||||
break; // 10s ohne Daten -> Verbindung aufgeben
|
||||
} else {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
out.close();
|
||||
http.end();
|
||||
Serial.printf("Nextcloud: '%s' heruntergeladen\n", filename.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool syncFromNextcloud() {
|
||||
WiFiClientSecure client;
|
||||
client.setCACert(LETSENCRYPT_ROOT_CA);
|
||||
|
||||
String folderUrl = String("https://") + NEXTCLOUD_HOST + "/remote.php/dav/files/" + NEXTCLOUD_USER + NEXTCLOUD_FOLDER + "/";
|
||||
|
||||
HTTPClient http;
|
||||
if (!http.begin(client, folderUrl)) {
|
||||
Serial.println("Nextcloud: PROPFIND begin() fehlgeschlagen");
|
||||
return false;
|
||||
}
|
||||
http.setAuthorization(NEXTCLOUD_USER, NEXTCLOUD_APP_PASSWORD);
|
||||
http.addHeader("Depth", "1");
|
||||
int code = http.sendRequest("PROPFIND", "");
|
||||
if (code != 207 && code != 200) {
|
||||
Serial.printf("Nextcloud: PROPFIND fehlgeschlagen (HTTP %d)\n", code);
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
String xml = http.getString();
|
||||
http.end();
|
||||
|
||||
int pos = 0;
|
||||
int candidates = 0;
|
||||
int downloaded = 0;
|
||||
while (true) {
|
||||
int start = xml.indexOf("<d:href>", pos);
|
||||
if (start < 0) break;
|
||||
start += 8;
|
||||
int end = xml.indexOf("</d:href>", start);
|
||||
if (end < 0) break;
|
||||
String href = xml.substring(start, end);
|
||||
pos = end + 9;
|
||||
|
||||
if (!href.endsWith(".tap") && !href.endsWith(".TAP")) continue;
|
||||
candidates++;
|
||||
int slash = href.lastIndexOf('/');
|
||||
String encodedName = slash >= 0 ? href.substring(slash + 1) : href;
|
||||
String filename = sanitizeFilename(urlDecode(encodedName));
|
||||
|
||||
String fileUrl = "https://" + String(NEXTCLOUD_HOST) + href;
|
||||
if (fetchAndSaveFile(client, fileUrl, filename)) downloaded++;
|
||||
}
|
||||
Serial.printf("Nextcloud-Sync: %d/%d Datei(en) aktualisiert\n", downloaded, candidates);
|
||||
// Nur dann als Fehlschlag melden, wenn Dateien gefunden wurden, aber keine
|
||||
// einzige davon heruntergeladen werden konnte (z.B. Zugangsdaten falsch).
|
||||
return candidates == 0 || downloaded > 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// HTTP-API
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static bool checkAuth() {
|
||||
String expected = String("Bearer ") + AUTH_TOKEN;
|
||||
String got = server.header("Authorization");
|
||||
if (got.length() != expected.length()) return false;
|
||||
uint8_t diff = 0;
|
||||
for (size_t i = 0; i < expected.length(); i++) diff |= (uint8_t)(got[i] ^ expected[i]);
|
||||
return diff == 0;
|
||||
}
|
||||
|
||||
static void sendJson(int code, const String &json) {
|
||||
server.send(code, "application/json", json);
|
||||
}
|
||||
|
||||
static void sendUnauthorized() { sendJson(401, "{\"error\":\"unauthorized\"}"); }
|
||||
|
||||
static void sendLocked() {
|
||||
sendJson(423, "{\"error\":\"stick_exposed_to_cutter\"}");
|
||||
}
|
||||
|
||||
static String sanitizeFilename(const String &name) {
|
||||
String out;
|
||||
for (size_t i = 0; i < name.length(); i++) {
|
||||
char c = name[i];
|
||||
if (isalnum((unsigned char)c) || c == '_' || c == '.' || c == '-') out += c;
|
||||
}
|
||||
if (out.length() == 0) out = "upload.tap";
|
||||
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 bool g_uploadAllowed = false;
|
||||
|
||||
static void handleUploadData() {
|
||||
if (!checkAuth()) return;
|
||||
HTTPUpload &upload = server.upload();
|
||||
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);
|
||||
} else if (upload.status == UPLOAD_FILE_WRITE) {
|
||||
if (g_uploadAllowed && g_uploadFile) g_uploadFile.write(upload.buf, upload.currentSize);
|
||||
} else if (upload.status == UPLOAD_FILE_END || upload.status == UPLOAD_FILE_ABORTED) {
|
||||
if (g_uploadFile) g_uploadFile.close();
|
||||
}
|
||||
}
|
||||
|
||||
static void handleUploadComplete() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (!g_uploadAllowed) { sendLocked(); return; }
|
||||
sendJson(200, "{\"ok\":true}");
|
||||
}
|
||||
|
||||
static void handleSync() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (!enterUsbExposedState()) { sendJson(500, "{\"error\":\"sync_failed\"}"); return; }
|
||||
sendJson(200, "{\"state\":\"" + stateToString() + "\"}");
|
||||
}
|
||||
|
||||
static void handleRelease() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
if (!enterNetworkSyncState()) { sendJson(500, "{\"error\":\"release_failed\"}"); return; }
|
||||
sendJson(200, "{\"state\":\"" + stateToString() + "\"}");
|
||||
}
|
||||
|
||||
static void handleStatus() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
String j = "{";
|
||||
j += "\"state\":\"" + stateToString() + "\",";
|
||||
j += "\"wifi_connected\":" + String(WiFi.status() == WL_CONNECTED ? "true" : "false") + ",";
|
||||
j += "\"ip\":\"" + WiFi.localIP().toString() + "\",";
|
||||
j += "\"sector_size\":" + String(g_sectorSize) + ",";
|
||||
j += "\"sector_count\":" + String(g_sectorCount);
|
||||
j += "}";
|
||||
sendJson(200, j);
|
||||
}
|
||||
|
||||
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()) {
|
||||
if (!first) j += ",";
|
||||
first = false;
|
||||
j += "{\"name\":\"" + baseName(f.name()) + "\",\"size\":" + String(f.size()) + "}";
|
||||
}
|
||||
f = root.openNextFile();
|
||||
}
|
||||
}
|
||||
sendJson(200, j + "]");
|
||||
}
|
||||
|
||||
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);
|
||||
sendJson(200, "{\"ok\":true}");
|
||||
}
|
||||
|
||||
static void handleNotFound() {
|
||||
sendJson(404, "{\"error\":\"not_found\"}");
|
||||
}
|
||||
|
||||
static void handleWifiReset() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
Preferences prefs;
|
||||
prefs.begin("wifi", false);
|
||||
prefs.clear();
|
||||
prefs.end();
|
||||
sendJson(200, "{\"ok\":true,\"message\":\"Neustart in Konfigurations-Hotspot\"}");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
static void handleNextcloudSync() {
|
||||
if (!checkAuth()) { sendUnauthorized(); return; }
|
||||
bool wasExposed = (g_state == BridgeState::USB_EXPOSED);
|
||||
bool readyForSync = !wasExposed || enterNetworkSyncState();
|
||||
bool ok = readyForSync && syncFromNextcloud();
|
||||
// Sichtbaren Zustand in jedem Fall wiederherstellen versuchen, auch wenn
|
||||
// der Sync fehlgeschlagen ist - der Stick soll fuer den Cutter nicht
|
||||
// unnoetig unsichtbar bleiben.
|
||||
if (wasExposed) enterUsbExposedState();
|
||||
sendJson(ok ? 200 : 500, String("{\"ok\":") + (ok ? "true" : "false") + "}");
|
||||
}
|
||||
|
||||
static void setupHttpServer() {
|
||||
static const char *headerKeys[] = {"Authorization"};
|
||||
server.collectHeaders(headerKeys, 1);
|
||||
server.on("/upload", HTTP_POST, handleUploadComplete, handleUploadData);
|
||||
server.on("/sync", HTTP_POST, handleSync);
|
||||
server.on("/release", HTTP_POST, handleRelease);
|
||||
server.on("/status", HTTP_GET, handleStatus);
|
||||
server.on("/list", HTTP_GET, handleList);
|
||||
server.on("/delete", HTTP_POST, handleDelete);
|
||||
server.on("/wifi/reset", HTTP_POST, handleWifiReset);
|
||||
server.on("/nextcloud/sync", HTTP_POST, handleNextcloudSync);
|
||||
server.onNotFound(handleNotFound);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// WLAN-Konfiguration: Zugangsdaten werden in NVS (Preferences) persistiert
|
||||
// und zur Laufzeit ueber einen Konfigurations-Hotspot eingegeben, statt sie
|
||||
// im Quellcode zu hinterlegen.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
static bool tryConnectWifi(const char *ssid, const char *pass) {
|
||||
Serial.printf("Verbinde mit WLAN '%s'", ssid);
|
||||
WiFi.begin(ssid, pass);
|
||||
uint32_t start = millis();
|
||||
while (WiFi.status() != WL_CONNECTED && millis() - start < WIFI_CONNECT_TIMEOUT_MS) {
|
||||
delay(300);
|
||||
Serial.print(".");
|
||||
}
|
||||
Serial.println();
|
||||
return WiFi.status() == WL_CONNECTED;
|
||||
}
|
||||
|
||||
static bool connectToStoredWifi() {
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
for (size_t i = 0; i < KNOWN_WIFI_NETWORKS_COUNT; i++) {
|
||||
if (tryConnectWifi(KNOWN_WIFI_NETWORKS[i].ssid, KNOWN_WIFI_NETWORKS[i].password)) return true;
|
||||
}
|
||||
|
||||
// Zusaetzlich das zuletzt ueber den Konfigurations-Hotspot eingegebene Netzwerk
|
||||
Preferences prefs;
|
||||
prefs.begin("wifi", true /* read-only */);
|
||||
String savedSsid = prefs.getString("ssid", "");
|
||||
String savedPass = prefs.getString("pass", "");
|
||||
prefs.end();
|
||||
if (savedSsid.length() > 0 && tryConnectWifi(savedSsid.c_str(), savedPass.c_str())) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static void handleConfigRoot() {
|
||||
server.send(200, "text/html",
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\">"
|
||||
"<title>Plasma-Bridge WLAN-Setup</title></head><body>"
|
||||
"<h2>Plasma-Bridge WLAN-Konfiguration</h2>"
|
||||
"<form method=\"POST\" action=\"/wifi-config\">"
|
||||
"SSID:<br><input name=\"ssid\" required><br><br>"
|
||||
"Passwort:<br><input name=\"password\" type=\"password\"><br><br>"
|
||||
"<input type=\"submit\" value=\"Speichern und neu starten\">"
|
||||
"</form></body></html>");
|
||||
}
|
||||
|
||||
static void handleConfigSave() {
|
||||
String ssid = server.arg("ssid");
|
||||
String pass = server.arg("password");
|
||||
if (ssid.length() == 0) {
|
||||
server.send(400, "text/html", "<p>SSID darf nicht leer sein. <a href=\"/\">Zurueck</a></p>");
|
||||
return;
|
||||
}
|
||||
Preferences prefs;
|
||||
prefs.begin("wifi", false);
|
||||
prefs.putString("ssid", ssid);
|
||||
prefs.putString("pass", pass);
|
||||
prefs.end();
|
||||
server.send(200, "text/html", "<p>Gespeichert. Das Geraet startet neu und verbindet sich mit dem WLAN.</p>");
|
||||
delay(1500);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
// Blockiert dauerhaft (kehrt nie zurueck) - beendet sich per ESP.restart()
|
||||
// sobald gueltige Zugangsdaten gespeichert wurden.
|
||||
static void runConfigPortal() {
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.softAP(AP_SSID); // offenes WLAN, kein Passwort
|
||||
Serial.print("Kein WLAN konfiguriert/erreichbar - Hotspot gestartet: ");
|
||||
Serial.println(AP_SSID);
|
||||
Serial.print("Verbinde dich damit und rufe http://");
|
||||
Serial.print(WiFi.softAPIP());
|
||||
Serial.println("/ auf, um die Zugangsdaten einzugeben.");
|
||||
|
||||
server.on("/", HTTP_GET, handleConfigRoot);
|
||||
server.on("/wifi-config", HTTP_POST, handleConfigSave);
|
||||
server.onNotFound(handleConfigRoot);
|
||||
server.begin();
|
||||
|
||||
while (true) {
|
||||
server.handleClient();
|
||||
delay(2);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
SPI.begin(); // Standard-SPI-Pins des Boards: SCK=12, MISO=13, MOSI=11
|
||||
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 */)) {
|
||||
Serial.println("FATAL: SD-Karte konnte nicht gemountet werden!");
|
||||
} else {
|
||||
g_sectorSize = sdcard_sector_size(g_pdrv);
|
||||
g_sectorCount = sdcard_num_sectors(g_pdrv);
|
||||
g_state = BridgeState::NETWORK_SYNC;
|
||||
g_fsMounted = true;
|
||||
if (g_sectorSize != sizeof(g_cacheBuf)) {
|
||||
Serial.printf("WARNUNG: unerwartete Sektorgroesse %u (Cache ist auf 512 ausgelegt)\n", g_sectorSize);
|
||||
}
|
||||
}
|
||||
|
||||
MSC.vendorID("Springer");
|
||||
MSC.productID("PlasmaBridge");
|
||||
MSC.productRevision("1.0");
|
||||
MSC.onRead(onMscRead);
|
||||
MSC.onWrite(onMscWrite);
|
||||
MSC.onStartStop(onMscStartStop);
|
||||
MSC.mediaPresent(false); // Start im NETWORK_SYNC-Zustand: fuer den Cutter unsichtbar
|
||||
MSC.begin(g_sectorCount, g_sectorSize);
|
||||
USB.begin();
|
||||
|
||||
if (!connectToStoredWifi()) {
|
||||
runConfigPortal(); // kehrt nie zurueck
|
||||
}
|
||||
Serial.print("IP-Adresse: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
// Frische Dateien von Nextcloud holen, bevor der Stick fuer den
|
||||
// Plasmaschneider sichtbar wird (typischerweise bei jedem Einschalten,
|
||||
// da der ESP32 ueber den USB/OTG-Port vom Cutter mitversorgt wird).
|
||||
syncFromNextcloud();
|
||||
enterUsbExposedState();
|
||||
|
||||
setupHttpServer();
|
||||
server.begin();
|
||||
Serial.println("HTTP-Server gestartet");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
server.handleClient();
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Minimaler USB-MSC-Test (RAM-Disk, offizielles arduino-esp32-Beispiel,
|
||||
// fast unveraendert uebernommen aus USB/examples/USBMSC/USBMSC.ino).
|
||||
//
|
||||
// Zweck: isolieren, ob das native USB auf diesem Board grundsaetzlich
|
||||
// funktioniert - ganz ohne WLAN/Nextcloud/Wear-Levelling. Zeigt zusaetzlich
|
||||
// USB-Verbindungsereignisse (PLUGGED/UNPLUGGED/SUSPEND/RESUME) auf der
|
||||
// seriellen Konsole an.
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "USB.h"
|
||||
#include "USBMSC.h"
|
||||
|
||||
#define HWSerial Serial
|
||||
USBCDC USBSerial;
|
||||
|
||||
USBMSC MSC;
|
||||
|
||||
#define FAT_U8(v) ((v) & 0xFF)
|
||||
#define FAT_U16(v) FAT_U8(v), FAT_U8((v) >> 8)
|
||||
#define FAT_U32(v) FAT_U8(v), FAT_U8((v) >> 8), FAT_U8((v) >> 16), FAT_U8((v) >> 24)
|
||||
#define FAT_MS2B(s,ms) FAT_U8(((((s) & 0x1) * 1000) + (ms)) / 10)
|
||||
#define FAT_HMS2B(h,m,s) FAT_U8(((s) >> 1)|(((m) & 0x7) << 5)), FAT_U8((((m) >> 3) & 0x7)|((h) << 3))
|
||||
#define FAT_YMD2B(y,m,d) FAT_U8(((d) & 0x1F)|(((m) & 0x7) << 5)), FAT_U8((((m) >> 3) & 0x1)|((((y) - 1980) & 0x7F) << 1))
|
||||
#define FAT_TBL2B(l,h) FAT_U8(l), FAT_U8(((l >> 8) & 0xF) | ((h << 4) & 0xF0)), FAT_U8(h >> 4)
|
||||
|
||||
#define README_CONTENTS "USB-MSC Testlaufwerk fuer Springers Plasma Software.\r\n"
|
||||
|
||||
static const uint32_t DISK_SECTOR_COUNT = 2 * 8; // 8KB - kleinste von Windows akzeptierte Groesse
|
||||
static const uint16_t DISK_SECTOR_SIZE = 512;
|
||||
static const uint16_t DISC_SECTORS_PER_TABLE = 1;
|
||||
|
||||
static uint8_t msc_disk[DISK_SECTOR_COUNT][DISK_SECTOR_SIZE] =
|
||||
{
|
||||
//------------- Block0: Boot Sector -------------//
|
||||
{
|
||||
0xEB, 0x3C, 0x90,
|
||||
'M' , 'S' , 'D' , 'O' , 'S' , '5' , '.' , '0' ,
|
||||
FAT_U16(DISK_SECTOR_SIZE),
|
||||
FAT_U8(1),
|
||||
FAT_U16(1),
|
||||
FAT_U8(1),
|
||||
FAT_U16(16),
|
||||
FAT_U16(DISK_SECTOR_COUNT),
|
||||
0xF8,
|
||||
FAT_U16(DISC_SECTORS_PER_TABLE),
|
||||
FAT_U16(1),
|
||||
FAT_U16(1),
|
||||
FAT_U32(0),
|
||||
FAT_U32(0),
|
||||
0x00,
|
||||
0x00,
|
||||
0x29,
|
||||
FAT_U32(0x1234),
|
||||
'P' , 'L' , 'A' , 'S' , 'M' , 'A' , ' ' , ' ' , 'M' , 'S' , 'C' ,
|
||||
'F' , 'A' , 'T' , '1' , '2' , ' ' , ' ' , ' ' ,
|
||||
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
|
||||
0x55, 0xAA
|
||||
},
|
||||
|
||||
//------------- Block1: FAT12 Table -------------//
|
||||
{
|
||||
FAT_TBL2B(0xFF8, 0xFFF), FAT_TBL2B(0xFFF, 0x000)
|
||||
},
|
||||
|
||||
//------------- Block2: Root Directory -------------//
|
||||
{
|
||||
'P' , 'L' , 'A' , 'S' , 'M' , 'A' , ' ' , ' ' ,
|
||||
'M' , 'S' , 'C' ,
|
||||
0x08,
|
||||
0x00,
|
||||
FAT_MS2B(0,0),
|
||||
FAT_HMS2B(0,0,0),
|
||||
FAT_YMD2B(0,0,0),
|
||||
FAT_YMD2B(0,0,0),
|
||||
FAT_U16(0),
|
||||
FAT_HMS2B(13,42,30),
|
||||
FAT_YMD2B(2018,11,5),
|
||||
FAT_U16(0),
|
||||
FAT_U32(0),
|
||||
|
||||
'R' , 'E' , 'A' , 'D' , 'M' , 'E' , ' ' , ' ' ,
|
||||
'T' , 'X' , 'T' ,
|
||||
0x20,
|
||||
0x00,
|
||||
FAT_MS2B(1,980),
|
||||
FAT_HMS2B(13,42,36),
|
||||
FAT_YMD2B(2018,11,5),
|
||||
FAT_YMD2B(2020,11,5),
|
||||
FAT_U16(0),
|
||||
FAT_HMS2B(13,44,16),
|
||||
FAT_YMD2B(2019,11,5),
|
||||
FAT_U16(2),
|
||||
FAT_U32(sizeof(README_CONTENTS) - 1)
|
||||
},
|
||||
|
||||
//------------- Block3: Readme Content -------------//
|
||||
README_CONTENTS
|
||||
};
|
||||
|
||||
static int32_t onWrite(uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize){
|
||||
HWSerial.printf("MSC WRITE: lba: %u, offset: %u, bufsize: %u\n", lba, offset, bufsize);
|
||||
memcpy(msc_disk[lba] + offset, buffer, bufsize);
|
||||
return bufsize;
|
||||
}
|
||||
|
||||
static int32_t onRead(uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize){
|
||||
HWSerial.printf("MSC READ: lba: %u, offset: %u, bufsize: %u\n", lba, offset, bufsize);
|
||||
memcpy(buffer, msc_disk[lba] + offset, bufsize);
|
||||
return bufsize;
|
||||
}
|
||||
|
||||
static bool onStartStop(uint8_t power_condition, bool start, bool load_eject){
|
||||
HWSerial.printf("MSC START/STOP: power: %u, start: %u, eject: %u\n", power_condition, start, load_eject);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void usbEventCallback(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data){
|
||||
if(event_base == ARDUINO_USB_EVENTS){
|
||||
arduino_usb_event_data_t * data = (arduino_usb_event_data_t*)event_data;
|
||||
switch (event_id){
|
||||
case ARDUINO_USB_STARTED_EVENT:
|
||||
HWSerial.println("USB PLUGGED");
|
||||
break;
|
||||
case ARDUINO_USB_STOPPED_EVENT:
|
||||
HWSerial.println("USB UNPLUGGED");
|
||||
break;
|
||||
case ARDUINO_USB_SUSPEND_EVENT:
|
||||
HWSerial.printf("USB SUSPENDED: remote_wakeup_en: %u\n", data->suspend.remote_wakeup_en);
|
||||
break;
|
||||
case ARDUINO_USB_RESUME_EVENT:
|
||||
HWSerial.println("USB RESUMED");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
HWSerial.begin(115200);
|
||||
HWSerial.setDebugOutput(true);
|
||||
|
||||
USB.onEvent(usbEventCallback);
|
||||
MSC.vendorID("Springer");
|
||||
MSC.productID("MSCTest");
|
||||
MSC.productRevision("1.0");
|
||||
MSC.onStartStop(onStartStop);
|
||||
MSC.onRead(onRead);
|
||||
MSC.onWrite(onWrite);
|
||||
MSC.mediaPresent(true);
|
||||
MSC.begin(DISK_SECTOR_COUNT, DISK_SECTOR_SIZE);
|
||||
USBSerial.begin();
|
||||
USB.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
||||
Reference in new issue
Block a user