ModulosDSP_101.ino 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. // Modulos ADAU DSP WiFi + EEPROM (HTTP uploader + Sigma TCP bridge)
  2. // Build: 260304_13 (YYMMDD_rev)
  3. //
  4. // This is a clean restore to the last known good state (v1.3.0/_04)
  5. // with the chipAddr 0x01 fix applied. The receive loop is the original
  6. // simple byte-at-a-time approach which correctly handled large packets.
  7. //
  8. // Changes vs original:
  9. // - sendReadResponse() corrected to 6-byte SigmaTCP header format
  10. // - sendWriteAck() added after every DSP/EEPROM write
  11. // - chipAddrTo7bit() handles 0x01=DSP, 0x02=EEPROM chip indexes
  12. // - I2C read failure returns zeros instead of dropping connection
  13. // - registerSize derived from ADAU1401 address map
  14. // - DSPWriter::resetSafeload() at start of each TCP session
  15. // - WS2812 NeoPixel on GPIO 21 (Waveshare ESP32-S3 Zero)
  16. //
  17. // Changelog v1.3.0:
  18. // - FIX: sendReadResponse() header corrected to 6-byte SigmaTCP format
  19. // (was 4 bytes; SigmaStudio expects: 0x0B, totalLen_hi, totalLen_lo, status, dataLen_hi, dataLen_lo)
  20. // - ADD: sendWriteAck() — SigmaStudio expects a 4-byte ACK after every write
  21. // (was missing; caused immediate disconnect after first write)
  22. // - FIX: I2C read failure now returns zeros instead of dropping TCP connection
  23. // (SigmaStudio can probe/read a DSP that isn't responding yet without aborting)
  24. // - ADD: Hex dump of first bytes of each received command to Serial for diagnostics
  25. // - ADD: printHex() debug helper
  26. //
  27. // Changelog v1.4.0:
  28. // - FIX: TCP receive loop replaced with client.readBytes() + 3s per-packet timeout
  29. // Previous byte-at-a-time loop timed out mid-transfer on large program blocks
  30. // (e.g. 1490-byte program download) because client.available() returns 0
  31. // between TCP segments even when more data is in flight. Now we block-read
  32. // exactly the bytes needed to complete the current packet, so a large program
  33. // download can span multiple TCP segments without triggering a false idle timeout.
  34. // - FIX: Idle timeout now only applies between commands, not during active receive
  35. //
  36. // Changelog v1.2.0:
  37. // - ADD: WS2812 NeoPixel status LED (Waveshare ESP32-S3 Zero, GPIO 21)
  38. // OFF = idle / no TCP client
  39. // GREEN = DSP write in progress
  40. // BLUE = DSP read in progress
  41. // YELLOW = EEPROM write via TCP
  42. // MAGENTA = HTTP EEPROM upload in progress
  43. // RED flash = error (I2C fail, overflow, bad packet)
  44. //
  45. // Changelog v1.1.0:
  46. // - FIX: Buffer overflow check moved to BEFORE write
  47. // - FIX: chipAddrTo7bit() replaced with explicit lookup table
  48. // - FIX: registerSize now derived from ADAU1401 address range
  49. // - FIX: DSPWriter::resetSafeload() called at TCP session start
  50. // - FIX: Safeload dataLen validated as multiple of 4
  51. // - FIX: totalLen vs dataLen cross-validated on WRITE packets
  52. #include <WiFi.h>
  53. #include <Wire.h>
  54. #include <WebServer.h>
  55. #include <Preferences.h>
  56. #include "DSPWriter.h"
  57. #include <hd44780.h>
  58. #include <hd44780ioClass/hd44780_I2Cexp.h>
  59. #include <Adafruit_NeoPixel.h>
  60. #include "FS.h"
  61. #include <LittleFS.h>
  62. #include <Update.h>
  63. #include <ESPmDNS.h>
  64. //=============================================================
  65. // WiFi / UI
  66. //=============================================================
  67. const char* hostname = "modulos-dsp";
  68. const char* version = "VER: 260304_13";
  69. // Compile-time default credentials — used when NVS has no saved credentials.
  70. // Change these before flashing. If NVS credentials are saved (via the config
  71. // portal) they take priority over these on subsequent boots.
  72. static const char DEFAULT_SSID[] = "alfred";
  73. static const char DEFAULT_PASS[] = "alfred16";
  74. // Runtime WiFi credentials — populated from NVS or defaults at boot
  75. static char s_ssid[64] = "";
  76. static char s_pass[64] = "";
  77. #define I2C_SDA 13
  78. #define I2C_SCL 12
  79. WiFiServer tcpServer(8086);
  80. WebServer httpServer(80);
  81. #include "index_html.h"
  82. #include "ota_html.h"
  83. #include "ap_html.h"
  84. hd44780_I2Cexp lcd;
  85. static bool s_lcdOk = false;
  86. //=============================================================
  87. // NeoPixel status LED (Waveshare ESP32-S3 Zero, GPIO 21)
  88. //=============================================================
  89. #define NEOPIXEL_PIN 21
  90. #define NEOPIXEL_COUNT 1
  91. #define NEOPIXEL_BRIGHT 40
  92. Adafruit_NeoPixel statusLed(NEOPIXEL_COUNT, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
  93. static void ledSet(uint8_t r, uint8_t g, uint8_t b)
  94. {
  95. statusLed.setPixelColor(0, statusLed.Color(r, g, b));
  96. statusLed.show();
  97. }
  98. static void ledOff() { ledSet(0, 0, 0); }
  99. static void ledCyan() { ledSet(0, NEOPIXEL_BRIGHT/2, NEOPIXEL_BRIGHT/2); }
  100. static void ledGreen() { ledSet(0, NEOPIXEL_BRIGHT, 0); }
  101. static void ledBlue() { ledSet(0, 0, NEOPIXEL_BRIGHT); }
  102. static void ledYellow() { ledSet(NEOPIXEL_BRIGHT, NEOPIXEL_BRIGHT, 0); }
  103. static void ledMagenta() { ledSet(NEOPIXEL_BRIGHT, 0, NEOPIXEL_BRIGHT); }
  104. static void ledErrorFlash()
  105. {
  106. for (int i = 0; i < 2; i++) {
  107. ledSet(NEOPIXEL_BRIGHT, 0, 0); delay(80);
  108. ledOff(); delay(80);
  109. }
  110. }
  111. //=============================================================
  112. // TCP protocol buffer
  113. //=============================================================
  114. static uint8_t dataBuffer[50 * 1024];
  115. #define STATE_START 0
  116. #define STATE_READ_CMD 1
  117. #define STATE_WRITE_CMD 2
  118. #define CMD_WRITE 0x09
  119. #define CMD_READ 0x0A
  120. #define TCP_IDLE_TIMEOUT_MS 30000 // drop session if silent for 30 s
  121. constexpr int WRITE_HDR_LEN = 10;
  122. constexpr int READ_HDR_LEN = 8;
  123. struct adauWriteHeader {
  124. uint8_t command;
  125. uint8_t safeload;
  126. uint8_t placement;
  127. uint16_t totalLen;
  128. uint8_t chipAddr;
  129. uint16_t dataLen;
  130. uint16_t address;
  131. };
  132. struct adauReadHeader {
  133. uint8_t command;
  134. uint16_t totalLen;
  135. uint8_t chipAddr;
  136. uint16_t dataLen;
  137. uint16_t address;
  138. };
  139. static adauWriteHeader writeHeader;
  140. static adauReadHeader readHeader;
  141. static constexpr uint8_t DSP_7BIT = DSP_I2C_ADDRESS; // 0x34
  142. static constexpr uint8_t EEPROM_7BIT = EEPROM_I2C_ADDRESS; // 0x50
  143. //=============================================================
  144. // 24C256 EEPROM
  145. //=============================================================
  146. static constexpr uint32_t EEPROM_SIZE_BYTES = 32768;
  147. static constexpr uint16_t EEPROM_PAGE_SIZE = 64;
  148. static constexpr uint8_t I2C_MAX_DATA_PER_TX = 28;
  149. //=============================================================
  150. // CRC32
  151. //=============================================================
  152. static uint32_t crc32_update(uint32_t crc, const uint8_t* data, size_t len)
  153. {
  154. crc = ~crc;
  155. for (size_t i = 0; i < len; i++) {
  156. crc ^= data[i];
  157. for (int b = 0; b < 8; b++) {
  158. uint32_t mask = -(crc & 1u);
  159. crc = (crc >> 1) ^ (0xEDB88320u & mask);
  160. }
  161. }
  162. return ~crc;
  163. }
  164. //=============================================================
  165. // Helpers
  166. //=============================================================
  167. static uint8_t chipAddrTo7bit(uint8_t chipAddr)
  168. {
  169. switch (chipAddr) {
  170. case 0x01: return 0x34; // chip index 1 = DSP
  171. case 0x02: return 0x50; // chip index 2 = EEPROM
  172. case 0x68: return 0x34;
  173. case 0xA0: return 0x50;
  174. case 0x34: return 0x34;
  175. case 0x50: return 0x50;
  176. default:
  177. if (chipAddr > 0x7F) return (uint8_t)(chipAddr >> 1);
  178. return chipAddr;
  179. }
  180. }
  181. static uint8_t registerSizeForAddress(uint16_t address, uint16_t dataLen)
  182. {
  183. if (address == dspRegister::CoreRegister) {
  184. if (dataLen == 2) return CORE_REGISTER_R0_REGSIZE;
  185. if (dataLen == 24) return HARDWARE_CONF_REGSIZE;
  186. return CORE_REGISTER_R0_REGSIZE;
  187. }
  188. if (address >= DSP_PROG_RAM_START && address <= DSP_PROG_RAM_END) return PROGRAM_REGSIZE;
  189. if (address < DSP_PROG_RAM_START) return PARAMETER_REGSIZE;
  190. return HARDWARE_CONF_REGSIZE;
  191. }
  192. static bool i2cAckPoll(uint8_t addr7, uint32_t timeoutMs = 80)
  193. {
  194. uint32_t start = millis();
  195. while ((millis() - start) < timeoutMs) {
  196. Wire.beginTransmission(addr7);
  197. if (Wire.endTransmission() == 0) return true;
  198. delay(1);
  199. }
  200. return false;
  201. }
  202. static bool eepromWritePageChunk(uint16_t memAddr, const uint8_t* data, uint16_t len)
  203. {
  204. Wire.beginTransmission(EEPROM_7BIT);
  205. Wire.write((uint8_t)(memAddr >> 8));
  206. Wire.write((uint8_t)(memAddr & 0xFF));
  207. for (uint16_t i = 0; i < len; i++) Wire.write(data[i]);
  208. if (Wire.endTransmission() != 0) return false;
  209. return i2cAckPoll(EEPROM_7BIT, 120);
  210. }
  211. static bool eepromWriteBlock(uint16_t memAddr, const uint8_t* data, uint16_t len)
  212. {
  213. while (len) {
  214. uint16_t pageOff = memAddr % EEPROM_PAGE_SIZE;
  215. uint16_t spaceInPage = EEPROM_PAGE_SIZE - pageOff;
  216. uint16_t chunk = len;
  217. if (chunk > spaceInPage) chunk = spaceInPage;
  218. if (chunk > I2C_MAX_DATA_PER_TX) chunk = I2C_MAX_DATA_PER_TX;
  219. if (!eepromWritePageChunk(memAddr, data, chunk)) return false;
  220. memAddr += chunk; data += chunk; len -= chunk;
  221. delay(0);
  222. }
  223. return true;
  224. }
  225. static bool eepromReadBlock(uint16_t memAddr, uint8_t* out, uint16_t len)
  226. {
  227. Wire.beginTransmission(EEPROM_7BIT);
  228. Wire.write((uint8_t)(memAddr >> 8));
  229. Wire.write((uint8_t)(memAddr & 0xFF));
  230. if (Wire.endTransmission(false) != 0) return false;
  231. uint16_t got = 0;
  232. while (got < len) {
  233. uint8_t ask = (len - got) > 32 ? 32 : (len - got);
  234. if (Wire.requestFrom((int)EEPROM_7BIT, (int)ask) != ask) return false;
  235. for (uint8_t i = 0; i < ask; i++) out[got++] = Wire.read();
  236. }
  237. return true;
  238. }
  239. static bool dspReadBlock(uint16_t memAddr, uint8_t* out, uint16_t len)
  240. {
  241. Wire.beginTransmission(DSP_7BIT);
  242. Wire.write((uint8_t)(memAddr >> 8));
  243. Wire.write((uint8_t)(memAddr & 0xFF));
  244. if (Wire.endTransmission(false) != 0) return false;
  245. uint16_t got = 0;
  246. while (got < len) {
  247. uint8_t ask = (len - got) > 32 ? 32 : (len - got);
  248. if (Wire.requestFrom((int)DSP_7BIT, (int)ask) != ask) return false;
  249. for (uint8_t i = 0; i < ask; i++) out[got++] = Wire.read();
  250. }
  251. return true;
  252. }
  253. // SigmaTCP read response: 0x0B, totalLen_hi, totalLen_lo, status, dataLen_hi, dataLen_lo, [payload]
  254. static bool sendReadResponse(WiFiClient& client, const uint8_t* data, uint16_t dataLen, bool ok)
  255. {
  256. uint16_t totalLen = 6 + dataLen;
  257. uint8_t hdr[6];
  258. hdr[0] = 0x0B;
  259. hdr[1] = (uint8_t)(totalLen >> 8);
  260. hdr[2] = (uint8_t)(totalLen & 0xFF);
  261. hdr[3] = ok ? 0x00 : 0x01;
  262. hdr[4] = (uint8_t)(dataLen >> 8);
  263. hdr[5] = (uint8_t)(dataLen & 0xFF);
  264. if (client.write(hdr, sizeof(hdr)) != sizeof(hdr)) return false;
  265. if (dataLen > 0) {
  266. if (ok && data) {
  267. if (client.write(data, dataLen) != dataLen) return false;
  268. } else {
  269. // send zeros so SigmaStudio doesn't stall on a failed read
  270. static uint8_t zeros[256];
  271. uint16_t rem = dataLen;
  272. while (rem) {
  273. uint16_t chunk = rem > sizeof(zeros) ? sizeof(zeros) : rem;
  274. if (client.write(zeros, chunk) != chunk) return false;
  275. rem -= chunk;
  276. }
  277. }
  278. }
  279. return true;
  280. }
  281. // SigmaTCP write ack: 0x09, 0x00, 0x04, status
  282. static bool sendWriteAck(WiFiClient& client, bool ok)
  283. {
  284. uint8_t ack[4] = { 0x09, 0x00, 0x04, ok ? (uint8_t)0x00 : (uint8_t)0x01 };
  285. return client.write(ack, sizeof(ack)) == sizeof(ack);
  286. }
  287. static void printHex(const char* label, const uint8_t* buf, uint16_t len, uint16_t maxPrint = 24)
  288. {
  289. Serial.print(label);
  290. uint16_t n = len < maxPrint ? len : maxPrint;
  291. for (uint16_t i = 0; i < n; i++) {
  292. if (buf[i] < 0x10) Serial.print("0");
  293. Serial.print(buf[i], HEX);
  294. Serial.print(" ");
  295. }
  296. if (len > maxPrint) Serial.print("...");
  297. Serial.println();
  298. }
  299. //=============================================================
  300. // NVS credential helpers
  301. //=============================================================
  302. static Preferences s_prefs;
  303. static bool loadWifiCreds()
  304. {
  305. s_prefs.begin("wifi", true);
  306. String ssid = s_prefs.getString("ssid", "");
  307. String pass = s_prefs.getString("pass", "");
  308. s_prefs.end();
  309. if (ssid.length() == 0) return false;
  310. ssid.toCharArray(s_ssid, sizeof(s_ssid));
  311. pass.toCharArray(s_pass, sizeof(s_pass));
  312. return true;
  313. }
  314. static void saveWifiCreds(const String& ssid, const String& pass)
  315. {
  316. s_prefs.begin("wifi", false);
  317. s_prefs.putString("ssid", ssid);
  318. s_prefs.putString("pass", pass);
  319. s_prefs.end();
  320. }
  321. static void clearWifiCreds()
  322. {
  323. s_prefs.begin("wifi", false);
  324. s_prefs.clear();
  325. s_prefs.end();
  326. }
  327. //=============================================================
  328. // SoftAP config portal — runs when no credentials are stored
  329. // or when a previous connection attempt failed.
  330. // Serves a simple HTML form; never returns.
  331. //=============================================================
  332. static void startConfigAP()
  333. {
  334. Serial.println("Starting config AP: ModulosDSP-Setup");
  335. WiFi.mode(WIFI_AP);
  336. WiFi.softAP("ModulosDSP-Setup");
  337. delay(100);
  338. IPAddress apIP = WiFi.softAPIP();
  339. Serial.print("AP IP: "); Serial.println(apIP);
  340. if (s_lcdOk) {
  341. lcd.clear();
  342. lcd.setCursor(0, 0); lcd.print("WiFi Setup Mode");
  343. lcd.setCursor(0, 1); lcd.print("ModulosDSP-Setup");
  344. lcd.setCursor(0, 2); lcd.print(apIP);
  345. }
  346. httpServer.on("/", HTTP_GET, []() {
  347. httpServer.send_P(200, "text/html", AP_HTML);
  348. });
  349. httpServer.on("/save", HTTP_POST, []() {
  350. if (!httpServer.hasArg("ssid") || httpServer.arg("ssid").length() == 0) {
  351. httpServer.send(400, "text/plain", "SSID is required.");
  352. return;
  353. }
  354. String newSsid = httpServer.arg("ssid");
  355. String newPass = httpServer.arg("pass");
  356. saveWifiCreds(newSsid, newPass);
  357. Serial.printf("Credentials saved for SSID: %s\n", newSsid.c_str());
  358. httpServer.send(200, "text/html",
  359. "<html><body style='font-family:sans-serif;max-width:380px;margin:60px auto;padding:0 20px'>"
  360. "<h3>Saved!</h3><p>Connecting to <strong>" + newSsid +
  361. "</strong>&hellip; The device will reboot now.</p></body></html>");
  362. delay(1000);
  363. ESP.restart();
  364. });
  365. httpServer.begin();
  366. Serial.println("Config portal active — waiting for credentials");
  367. while (true) {
  368. httpServer.handleClient();
  369. delay(1);
  370. }
  371. }
  372. static void printWifiInfo()
  373. {
  374. Serial.println();
  375. Serial.println("WiFi connected.");
  376. Serial.print("WiFi IP: "); Serial.println(WiFi.localIP());
  377. Serial.printf("Hostname: http://%s.local/\n", hostname);
  378. Serial.print("MAC: "); Serial.println(WiFi.macAddress());
  379. Serial.println("Modulos AudioDSP");
  380. Serial.println(version);
  381. if (s_lcdOk) {
  382. lcd.setCursor(4, 3);
  383. lcd.print(WiFi.localIP());
  384. }
  385. }
  386. //=============================================================
  387. // HTTP EEPROM uploader state
  388. //=============================================================
  389. static volatile bool uploadActive = false;
  390. static volatile bool uploadVerify = false;
  391. static volatile bool uploadFailed = false;
  392. static volatile uint32_t uploadBytes = 0;
  393. static volatile uint32_t uploadCrc = 0;
  394. //=============================================================
  395. // HTTP handlers
  396. //=============================================================
  397. static String contentTypeFor(const String& path) {
  398. if (path.endsWith(".html")) return "text/html";
  399. if (path.endsWith(".css")) return "text/css";
  400. if (path.endsWith(".js")) return "application/javascript";
  401. if (path.endsWith(".png")) return "image/png";
  402. if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
  403. if (path.endsWith(".webp")) return "image/webp";
  404. if (path.endsWith(".svg")) return "image/svg+xml";
  405. if (path.endsWith(".ico")) return "image/x-icon";
  406. if (path.endsWith(".woff")) return "font/woff";
  407. if (path.endsWith(".woff2"))return "font/woff2";
  408. return "application/octet-stream";
  409. }
  410. static bool streamFromFS(String path) {
  411. if (!LittleFS.exists(path)) {
  412. if (path.startsWith("/")) {
  413. String alt = path.substring(1);
  414. if (LittleFS.exists(alt)) path = alt; else return false;
  415. } else {
  416. String alt = "/" + path;
  417. if (LittleFS.exists(alt)) path = alt; else return false;
  418. }
  419. }
  420. File f = LittleFS.open(path, "r");
  421. if (!f) return false;
  422. httpServer.streamFile(f, contentTypeFor(path));
  423. f.close();
  424. return true;
  425. }
  426. static void handleRoot() {
  427. String html = FPSTR(INDEX_HTML);
  428. html.replace("{{IP}}", WiFi.localIP().toString());
  429. httpServer.send(200, "text/html; charset=utf-8", html);
  430. }
  431. static void handleStatus() {
  432. String s;
  433. s += "uploadActive="; s += (uploadActive ? "1" : "0"); s += "\n";
  434. s += "uploadFailed="; s += (uploadFailed ? "1" : "0"); s += "\n";
  435. s += "uploadBytes="; s += String((uint32_t)uploadBytes); s += "\n";
  436. s += "uploadCRC32=0x"; s += String((uint32_t)uploadCrc, HEX); s += "\n";
  437. httpServer.send(200, "text/plain", s);
  438. }
  439. static void handleUploadDone() {
  440. if (uploadFailed) {
  441. httpServer.send(500, "text/plain", "Upload failed.\nCheck Serial log.\n");
  442. return;
  443. }
  444. String msg = "OK\nBytes written: " + String((uint32_t)uploadBytes) +
  445. "\nCRC32: 0x" + String((uint32_t)uploadCrc, HEX) + "\n";
  446. httpServer.send(200, "text/plain", msg);
  447. }
  448. static void handleUploadStream() {
  449. HTTPUpload& up = httpServer.upload();
  450. if (up.status == UPLOAD_FILE_START) {
  451. uploadActive = true; uploadFailed = false; uploadBytes = 0; uploadCrc = 0;
  452. uploadVerify = httpServer.hasArg("verify");
  453. Serial.println(); Serial.print("HTTP upload start: "); Serial.println(up.filename);
  454. Serial.print("Verify: "); Serial.println(uploadVerify ? "yes" : "no");
  455. Wire.beginTransmission(EEPROM_7BIT);
  456. Serial.print("EEPROM probe err: "); Serial.println(Wire.endTransmission());
  457. }
  458. else if (up.status == UPLOAD_FILE_WRITE) {
  459. if (uploadFailed) return;
  460. if ((uploadBytes + up.currentSize) > EEPROM_SIZE_BYTES) {
  461. Serial.println("Upload too large for 24C256"); uploadFailed = true; return;
  462. }
  463. if (!eepromWriteBlock((uint16_t)uploadBytes, up.buf, (uint16_t)up.currentSize)) {
  464. Serial.println("EEPROM write failed"); uploadFailed = true; return;
  465. }
  466. uploadCrc = crc32_update(uploadCrc, up.buf, up.currentSize);
  467. uploadBytes += up.currentSize;
  468. ledMagenta();
  469. }
  470. else if (up.status == UPLOAD_FILE_END) {
  471. Serial.print("HTTP upload end, bytes="); Serial.println((uint32_t)uploadBytes);
  472. if (uploadVerify && !uploadFailed) {
  473. Serial.println("Verify start (CRC32)...");
  474. uint32_t crc = 0;
  475. static uint8_t tmp[256];
  476. uint32_t remaining = uploadBytes; uint16_t addr = 0;
  477. while (remaining) {
  478. uint16_t n = remaining > sizeof(tmp) ? sizeof(tmp) : (uint16_t)remaining;
  479. if (!eepromReadBlock(addr, tmp, n)) { Serial.println("EEPROM read failed"); uploadFailed = true; break; }
  480. crc = crc32_update(crc, tmp, n);
  481. addr += n; remaining -= n; delay(0);
  482. }
  483. Serial.print("Verify CRC32: 0x"); Serial.println(crc, HEX);
  484. if (!uploadFailed && crc != uploadCrc) { Serial.println("CRC mismatch"); uploadFailed = true; }
  485. }
  486. uploadActive = false; ledOff();
  487. Serial.println(uploadFailed ? "HTTP upload result: FAIL" : "HTTP upload result: OK");
  488. }
  489. else if (up.status == UPLOAD_FILE_ABORTED) {
  490. Serial.println("HTTP upload aborted"); uploadActive = false; uploadFailed = true; ledOff();
  491. }
  492. }
  493. //=============================================================
  494. // HTTP DSP reset handler
  495. //=============================================================
  496. static void handleDspReset() {
  497. Serial.println("DSP soft reset requested");
  498. // Stop DSP execution, brief pause, restart. Program and parameter RAM
  499. // are preserved — this restarts execution without reloading from EEPROM.
  500. uint8_t stop[2] = { 0x00, 0x00 };
  501. uint8_t run[2] = { 0x00, 0x01 };
  502. DSPWriter::writeRegister(dspRegister::CoreRegister, sizeof(stop), stop);
  503. delay(100);
  504. DSPWriter::writeRegister(dspRegister::CoreRegister, sizeof(run), run);
  505. Serial.println("DSP soft reset complete");
  506. httpServer.send(200, "text/plain", "DSP soft reset complete.");
  507. }
  508. //=============================================================
  509. // HTTP DSP status handler GET /dsp_status
  510. //=============================================================
  511. static void handleDspStatus() {
  512. // Core Register (0x081C) — 2 bytes, bit 0 = Run
  513. uint8_t coreRaw[2] = {0, 0};
  514. bool coreOk = dspReadBlock(dspRegister::CoreRegister, coreRaw, 2);
  515. uint16_t coreVal = ((uint16_t)coreRaw[0] << 8) | coreRaw[1];
  516. // GPIO All Register (0x0808) — 1 byte
  517. uint8_t gpio = 0;
  518. bool gpioOk = dspReadBlock(dspRegister::GpioAllRegister, &gpio, 1);
  519. // ADC0–3 (0x0809–0x080C) — 1 byte each, read as a 4-byte burst
  520. uint8_t adc[4] = {0, 0, 0, 0};
  521. bool adcOk = dspReadBlock(dspRegister::Adc0, adc, 4);
  522. bool allOk = coreOk && gpioOk && adcOk;
  523. char buf[200];
  524. snprintf(buf, sizeof(buf),
  525. "{\"ok\":%s,\"running\":%s,"
  526. "\"coreReg\":\"0x%04X\","
  527. "\"gpio\":\"0x%02X\","
  528. "\"adc\":[\"0x%02X\",\"0x%02X\",\"0x%02X\",\"0x%02X\"]}",
  529. allOk ? "true" : "false",
  530. (coreOk && (coreVal & 0x01)) ? "true" : "false",
  531. coreVal, gpio,
  532. adc[0], adc[1], adc[2], adc[3]);
  533. httpServer.send(allOk ? 200 : 500, "application/json", buf);
  534. }
  535. //=============================================================
  536. // HTTP WiFi reset handler POST /wifi_reset
  537. //=============================================================
  538. static void handleWifiReset() {
  539. Serial.println("WiFi credentials cleared — rebooting to AP setup mode");
  540. clearWifiCreds();
  541. httpServer.send(200, "text/plain",
  542. "Credentials cleared. Rebooting into setup mode.\n"
  543. "Connect to 'ModulosDSP-Setup' and open 192.168.4.1.");
  544. delay(500);
  545. ESP.restart();
  546. }
  547. //=============================================================
  548. // HTTP GPIO handlers GET /gpio POST /gpio
  549. //=============================================================
  550. static void handleGpioGet() {
  551. uint8_t gpio = 0;
  552. bool gpioOk = dspReadBlock(dspRegister::GpioAllRegister, &gpio, 1);
  553. uint8_t mpcfg[2] = {0, 0};
  554. bool cfgOk = dspReadBlock(dspRegister::MpCfg0, mpcfg, 2);
  555. bool ok = gpioOk && cfgOk;
  556. char buf[100];
  557. snprintf(buf, sizeof(buf),
  558. "{\"ok\":%s,\"gpio\":%u,\"mpcfg0\":%u,\"mpcfg1\":%u}",
  559. ok ? "true" : "false", gpio, mpcfg[0], mpcfg[1]);
  560. httpServer.send(ok ? 200 : 500, "application/json", buf);
  561. }
  562. static void handleGpioSet() {
  563. if (!httpServer.hasArg("value")) {
  564. httpServer.send(400, "text/plain", "Missing 'value' parameter.");
  565. return;
  566. }
  567. long val = httpServer.arg("value").toInt();
  568. if (val < 0 || val > 255) {
  569. httpServer.send(400, "text/plain", "value must be 0-255.");
  570. return;
  571. }
  572. uint8_t b = (uint8_t)val;
  573. DSPWriter::writeRegister(dspRegister::GpioAllRegister, 1, &b);
  574. Serial.printf("GPIO set: 0x%02X\n", b);
  575. httpServer.send(200, "text/plain", "OK");
  576. }
  577. //=============================================================
  578. // HTTP OTA handlers
  579. //=============================================================
  580. static void handleOtaPage() {
  581. String html = FPSTR(OTA_HTML);
  582. html.replace("{{IP}}", WiFi.localIP().toString());
  583. httpServer.send(200, "text/html; charset=utf-8", html);
  584. }
  585. static void handleOtaDone() {
  586. if (Update.hasError()) {
  587. String err = "OTA failed: " + String(Update.errorString());
  588. Serial.println(err);
  589. httpServer.send(500, "text/plain", err);
  590. } else {
  591. httpServer.send(200, "text/plain", "Firmware updated — rebooting now.");
  592. Serial.println("OTA success — rebooting");
  593. delay(500);
  594. ESP.restart();
  595. }
  596. }
  597. static void handleOtaStream() {
  598. HTTPUpload& up = httpServer.upload();
  599. if (up.status == UPLOAD_FILE_START) {
  600. Serial.printf("OTA start: %s\n", up.filename.c_str());
  601. ledCyan();
  602. if (!Update.begin(UPDATE_SIZE_UNKNOWN)) {
  603. Serial.print("OTA begin failed: ");
  604. Update.printError(Serial);
  605. }
  606. }
  607. else if (up.status == UPLOAD_FILE_WRITE) {
  608. if (Update.write(up.buf, up.currentSize) != up.currentSize) {
  609. Serial.print("OTA write failed: ");
  610. Update.printError(Serial);
  611. ledErrorFlash();
  612. }
  613. }
  614. else if (up.status == UPLOAD_FILE_END) {
  615. if (Update.end(true)) {
  616. Serial.printf("OTA end: %u bytes written\n", up.totalSize);
  617. } else {
  618. Serial.print("OTA end failed: ");
  619. Update.printError(Serial);
  620. ledErrorFlash();
  621. }
  622. ledOff();
  623. }
  624. else if (up.status == UPLOAD_FILE_ABORTED) {
  625. Update.abort();
  626. Serial.println("OTA aborted");
  627. ledOff();
  628. }
  629. }
  630. //=============================================================
  631. // Setup
  632. //=============================================================
  633. void setup() {
  634. Wire.begin(I2C_SDA, I2C_SCL);
  635. Wire.setClock(400000);
  636. statusLed.begin();
  637. statusLed.setBrightness(NEOPIXEL_BRIGHT);
  638. statusLed.show();
  639. s_lcdOk = (lcd.begin(20, 4) == 0);
  640. if (s_lcdOk) {
  641. lcd.display(); lcd.backlight();
  642. lcd.setCursor(2, 0); lcd.print("Modulos AudioDSP"); delay(1000);
  643. lcd.setCursor(5, 1); lcd.print("Booting..."); delay(1000);
  644. } else {
  645. Serial.println("LCD not found - continuing without display");
  646. }
  647. Serial.begin(115200); delay(1500);
  648. Serial.println(); Serial.println("Booting...");
  649. Serial.printf("Reset reason: %d\n", (int)esp_reset_reason());
  650. if (!loadWifiCreds()) {
  651. // NVS empty — fall back to compile-time defaults so an unattended
  652. // device can reach the network without needing the config portal.
  653. strlcpy(s_ssid, DEFAULT_SSID, sizeof(s_ssid));
  654. strlcpy(s_pass, DEFAULT_PASS, sizeof(s_pass));
  655. Serial.println("No NVS credentials — using defaults");
  656. }
  657. Serial.printf("Connecting to %s", s_ssid);
  658. WiFi.mode(WIFI_STA);
  659. WiFi.setAutoReconnect(true);
  660. WiFi.begin(s_ssid, s_pass);
  661. uint32_t t0 = millis();
  662. while (WiFi.status() != WL_CONNECTED && millis() - t0 < 15000) {
  663. delay(500); Serial.print(".");
  664. }
  665. Serial.println();
  666. if (WiFi.status() != WL_CONNECTED) {
  667. Serial.println("WiFi connect failed — entering setup mode");
  668. startConfigAP(); // never returns
  669. }
  670. if (MDNS.begin(hostname)) {
  671. MDNS.addService("http", "tcp", 80);
  672. Serial.printf("mDNS: http://%s.local/\n", hostname);
  673. } else {
  674. Serial.println("mDNS start failed");
  675. }
  676. if (!LittleFS.begin(false)) {
  677. Serial.println("LittleFS mount failed, formatting...");
  678. if (!LittleFS.begin(true)) { Serial.println("LittleFS mount failed even after format"); return; }
  679. }
  680. Serial.println("LittleFS mounted OK");
  681. File root = LittleFS.open("/"); File f = root.openNextFile();
  682. while (f) { Serial.print("LittleFS: "); Serial.println(f.name()); f = root.openNextFile(); }
  683. if (s_lcdOk) { lcd.setCursor(3, 2); lcd.print("File System OK"); delay(1000); }
  684. tcpServer.begin();
  685. httpServer.on("/", HTTP_GET, handleRoot);
  686. httpServer.on("/status", HTTP_GET, handleStatus);
  687. httpServer.on("/upload", HTTP_POST, handleUploadDone, handleUploadStream);
  688. httpServer.on("/ota", HTTP_GET, handleOtaPage);
  689. httpServer.on("/ota_do", HTTP_POST, handleOtaDone, handleOtaStream);
  690. httpServer.on("/dsp_reset", HTTP_POST, handleDspReset);
  691. httpServer.on("/dsp_status", HTTP_GET, handleDspStatus);
  692. httpServer.on("/gpio", HTTP_GET, handleGpioGet);
  693. httpServer.on("/gpio", HTTP_POST, handleGpioSet);
  694. httpServer.on("/wifi_reset", HTTP_POST, handleWifiReset);
  695. httpServer.onNotFound([]() {
  696. String uri = httpServer.uri();
  697. if (streamFromFS(uri)) return;
  698. Serial.print("HTTP 404: "); Serial.println(uri);
  699. httpServer.send(404, "text/plain", "Not found: " + uri);
  700. });
  701. httpServer.begin();
  702. if (s_lcdOk) {
  703. lcd.setCursor(4, 3); lcd.print("System Ready"); delay(1000);
  704. lcd.clear();
  705. lcd.setCursor(2, 0); lcd.print("Modulos AudioDSP");
  706. lcd.setCursor(3, 1); lcd.print(version); delay(500);
  707. }
  708. printWifiInfo();
  709. Serial.print("HTTP uploader: http://"); Serial.print(WiFi.localIP()); Serial.println("/");
  710. }
  711. //=============================================================
  712. // TCP bridge
  713. //=============================================================
  714. //=============================================================
  715. // TCP bridge
  716. //=============================================================
  717. static void handleTcpBridgeClient(WiFiClient& client)
  718. {
  719. Serial.println("TCP new connection");
  720. DSPWriter::resetSafeload();
  721. int writeIndex = 0; // next free slot in dataBuffer
  722. int readIndex = 0; // start of current unprocessed command
  723. int receivedByteCount = 0; // total bytes written into dataBuffer
  724. int currentState = STATE_START;
  725. uint32_t lastActivityMs = millis(); // idle watchdog
  726. while (client.connected()) {
  727. httpServer.handleClient();
  728. delay(0);
  729. // ------------------------------------------------------------------
  730. // STEP 1: Always drain the TCP stack into dataBuffer.
  731. // Do this unconditionally every loop iteration — this is what keeps
  732. // the TCP receive window open. If we only drain when we feel like it,
  733. // the window goes to zero and SigmaStudio stops sending (ZeroWindow).
  734. // ------------------------------------------------------------------
  735. while (client.available()) {
  736. if (writeIndex >= (int)sizeof(dataBuffer)) {
  737. Serial.println("TCP RX overflow");
  738. ledErrorFlash(); client.stop(); return;
  739. }
  740. int b = client.read();
  741. if (b < 0) break;
  742. dataBuffer[writeIndex++] = (uint8_t)b;
  743. receivedByteCount++;
  744. lastActivityMs = millis();
  745. }
  746. // ------------------------------------------------------------------
  747. // STEP 2: Process whatever is in the buffer.
  748. // This is driven purely by buffer contents, not by client.available().
  749. // We loop here processing commands until we run out of buffered data.
  750. // ------------------------------------------------------------------
  751. bool processedSomething = true;
  752. while (processedSomething && client.connected()) {
  753. processedSomething = false;
  754. // --- STATE_START: identify opcode ---
  755. if (currentState == STATE_START) {
  756. if (receivedByteCount <= readIndex) {
  757. // Buffer empty — reset for next command
  758. writeIndex = readIndex = receivedByteCount = 0;
  759. ledOff();
  760. break; // nothing to process, go back to receive loop
  761. }
  762. printHex("TCP RX: ", &dataBuffer[readIndex], (uint16_t)(receivedByteCount - readIndex));
  763. uint8_t op = dataBuffer[readIndex];
  764. if (op == CMD_WRITE) { currentState = STATE_WRITE_CMD; processedSomething = true; }
  765. else if (op == CMD_READ) { currentState = STATE_READ_CMD; processedSomething = true; }
  766. else {
  767. Serial.printf("TCP invalid opcode: 0x%02X\n", op);
  768. ledErrorFlash();
  769. client.stop(); return;
  770. }
  771. }
  772. // --- STATE_WRITE_CMD ---
  773. if (currentState == STATE_WRITE_CMD) {
  774. // Need full header first
  775. if (receivedByteCount < (readIndex + WRITE_HDR_LEN)) break;
  776. writeHeader.safeload = dataBuffer[readIndex + 1];
  777. writeHeader.placement = dataBuffer[readIndex + 2];
  778. writeHeader.totalLen = (uint16_t)((dataBuffer[readIndex + 3] << 8) | dataBuffer[readIndex + 4]);
  779. writeHeader.chipAddr = dataBuffer[readIndex + 5];
  780. writeHeader.dataLen = (uint16_t)((dataBuffer[readIndex + 6] << 8) | dataBuffer[readIndex + 7]);
  781. writeHeader.address = (uint16_t)((dataBuffer[readIndex + 8] << 8) | dataBuffer[readIndex + 9]);
  782. if (writeHeader.totalLen != WRITE_HDR_LEN + writeHeader.dataLen) {
  783. Serial.printf("TCP WRITE bad totalLen: got %u expected %u\n",
  784. writeHeader.totalLen, WRITE_HDR_LEN + writeHeader.dataLen);
  785. ledErrorFlash(); client.stop(); return;
  786. }
  787. // Need full payload — if not here yet, break back to receive loop
  788. if (receivedByteCount < (readIndex + WRITE_HDR_LEN + (int)writeHeader.dataLen)) {
  789. Serial.printf("TCP WRITE buffering: have %d need %d bytes\n",
  790. receivedByteCount - readIndex,
  791. WRITE_HDR_LEN + (int)writeHeader.dataLen);
  792. break;
  793. }
  794. readIndex += WRITE_HDR_LEN;
  795. uint8_t target7 = chipAddrTo7bit(writeHeader.chipAddr);
  796. if (target7 == EEPROM_7BIT) {
  797. ledYellow();
  798. bool ok = eepromWriteBlock(writeHeader.address, &dataBuffer[readIndex], writeHeader.dataLen);
  799. readIndex += writeHeader.dataLen;
  800. sendWriteAck(client, ok);
  801. if (!ok) { Serial.println("TCP EEPROM write failed"); ledErrorFlash(); }
  802. else ledOff();
  803. currentState = STATE_START;
  804. processedSomething = true;
  805. continue;
  806. }
  807. if (target7 != DSP_7BIT) {
  808. Serial.printf("TCP unknown chipAddr: 0x%02X\n", writeHeader.chipAddr);
  809. ledErrorFlash(); client.stop(); return;
  810. }
  811. ledGreen();
  812. uint8_t registerSize = registerSizeForAddress(writeHeader.address, writeHeader.dataLen);
  813. uint16_t regAddress = writeHeader.address;
  814. Serial.printf("TCP WRITE addr=0x%04X len=%u regSz=%u safeload=%u\n",
  815. writeHeader.address, writeHeader.dataLen, registerSize, writeHeader.safeload);
  816. bool writeOk = true;
  817. if (writeHeader.safeload == 1) {
  818. if (writeHeader.dataLen % 4 != 0) {
  819. Serial.printf("TCP safeload dataLen %u not multiple of 4\n", writeHeader.dataLen);
  820. ledErrorFlash(); client.stop(); return;
  821. }
  822. int writeCount = writeHeader.dataLen / 4;
  823. int slri = readIndex;
  824. DSPWriter dspWriter;
  825. while (writeCount > 0) {
  826. uint8_t da[5] = { 0x00, dataBuffer[slri], dataBuffer[slri+1],
  827. dataBuffer[slri+2], dataBuffer[slri+3] };
  828. dspWriter.safeload_writeRegister(regAddress, da, writeCount == 1);
  829. regAddress++; slri += 4; writeCount--; delay(0);
  830. }
  831. } else {
  832. writeOk = DSPWriter::writeRegisterBlock(regAddress, writeHeader.dataLen,
  833. &dataBuffer[readIndex], registerSize);
  834. if (!writeOk) Serial.println("TCP DSP block write failed");
  835. }
  836. readIndex += writeHeader.dataLen;
  837. if (!writeOk) ledErrorFlash(); else ledOff();
  838. sendWriteAck(client, writeOk);
  839. currentState = STATE_START;
  840. processedSomething = true;
  841. continue;
  842. }
  843. // --- STATE_READ_CMD ---
  844. if (currentState == STATE_READ_CMD) {
  845. if (receivedByteCount < (readIndex + READ_HDR_LEN)) break;
  846. readHeader.totalLen = (uint16_t)((dataBuffer[readIndex + 1] << 8) | dataBuffer[readIndex + 2]);
  847. readHeader.chipAddr = dataBuffer[readIndex + 3];
  848. readHeader.dataLen = (uint16_t)((dataBuffer[readIndex + 4] << 8) | dataBuffer[readIndex + 5]);
  849. readHeader.address = (uint16_t)((dataBuffer[readIndex + 6] << 8) | dataBuffer[readIndex + 7]);
  850. readIndex += READ_HDR_LEN;
  851. uint8_t target7 = chipAddrTo7bit(readHeader.chipAddr);
  852. Serial.printf("TCP READ chip=0x%02X addr=0x%04X len=%u\n",
  853. readHeader.chipAddr, readHeader.address, readHeader.dataLen);
  854. if (readHeader.dataLen > 4096) { readHeader.dataLen = 4096; }
  855. static uint8_t readOut[4096];
  856. bool ok = false;
  857. ledBlue();
  858. if (target7 == EEPROM_7BIT) ok = eepromReadBlock(readHeader.address, readOut, readHeader.dataLen);
  859. else if (target7 == DSP_7BIT) ok = dspReadBlock (readHeader.address, readOut, readHeader.dataLen);
  860. else {
  861. Serial.printf("TCP unknown chipAddr (READ): 0x%02X\n", readHeader.chipAddr);
  862. }
  863. if (!ok) Serial.println("TCP READ I2C failed - sending zeros");
  864. if (!sendReadResponse(client, ok ? readOut : nullptr, readHeader.dataLen, ok)) {
  865. Serial.println("TCP READ send failed"); ledErrorFlash(); client.stop(); return;
  866. }
  867. ledOff();
  868. currentState = STATE_START;
  869. processedSomething = true;
  870. continue;
  871. }
  872. } // end process loop
  873. // Idle path — no data waiting, no command in progress.
  874. if (currentState == STATE_START && receivedByteCount == readIndex) {
  875. if (!client.available()) {
  876. if (millis() - lastActivityMs > TCP_IDLE_TIMEOUT_MS) {
  877. Serial.println("TCP idle timeout — closing session");
  878. ledErrorFlash();
  879. break;
  880. }
  881. httpServer.handleClient();
  882. delay(10);
  883. }
  884. }
  885. } // end main while loop
  886. DSPWriter::resetSafeload(); // flush any mid-session safeload before disconnect
  887. client.stop();
  888. Serial.println("TCP disconnected");
  889. ledOff();
  890. }
  891. //=============================================================
  892. // WiFi watchdog
  893. //=============================================================
  894. static uint32_t s_wifiLastCheck = 0;
  895. static bool s_wifiLost = false;
  896. static void maintainWifi()
  897. {
  898. if (millis() - s_wifiLastCheck < 5000) return;
  899. s_wifiLastCheck = millis();
  900. if (WiFi.status() != WL_CONNECTED) {
  901. if (!s_wifiLost) {
  902. Serial.println("WiFi lost");
  903. if (s_lcdOk) { lcd.setCursor(0, 3); lcd.print("WiFi lost... "); }
  904. s_wifiLost = true;
  905. }
  906. WiFi.reconnect();
  907. } else if (s_wifiLost) {
  908. Serial.print("WiFi reconnected, IP: "); Serial.println(WiFi.localIP());
  909. MDNS.begin(hostname);
  910. MDNS.addService("http", "tcp", 80);
  911. tcpServer.begin(); // re-register listening socket with recovered stack
  912. printWifiInfo(); // update LCD with current IP
  913. s_wifiLost = false;
  914. }
  915. }
  916. //=============================================================
  917. // Loop
  918. //=============================================================
  919. void loop() {
  920. maintainWifi();
  921. httpServer.handleClient();
  922. if (uploadActive) { delay(1); return; }
  923. WiFiClient client = tcpServer.available();
  924. if (client) handleTcpBridgeClient(client);
  925. delay(1);
  926. }