ModulosDSP_101.ino 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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 "DSPWriter.h"
  56. #include <hd44780.h>
  57. #include <hd44780ioClass/hd44780_I2Cexp.h>
  58. #include <Adafruit_NeoPixel.h>
  59. #include "FS.h"
  60. #include <LittleFS.h>
  61. #include <Update.h>
  62. //=============================================================
  63. // WiFi / UI
  64. //=============================================================
  65. const char* ssid = "alfred";
  66. const char* password = "alfred16";
  67. const char* version = "VER: 260304_13";
  68. #define I2C_SDA 13
  69. #define I2C_SCL 12
  70. WiFiServer tcpServer(8086);
  71. WebServer httpServer(80);
  72. #include "index_html.h"
  73. #include "ota_html.h"
  74. hd44780_I2Cexp lcd;
  75. static bool s_lcdOk = false;
  76. //=============================================================
  77. // NeoPixel status LED (Waveshare ESP32-S3 Zero, GPIO 21)
  78. //=============================================================
  79. #define NEOPIXEL_PIN 21
  80. #define NEOPIXEL_COUNT 1
  81. #define NEOPIXEL_BRIGHT 40
  82. Adafruit_NeoPixel statusLed(NEOPIXEL_COUNT, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
  83. static void ledSet(uint8_t r, uint8_t g, uint8_t b)
  84. {
  85. statusLed.setPixelColor(0, statusLed.Color(r, g, b));
  86. statusLed.show();
  87. }
  88. static void ledOff() { ledSet(0, 0, 0); }
  89. static void ledCyan() { ledSet(0, NEOPIXEL_BRIGHT/2, NEOPIXEL_BRIGHT/2); }
  90. static void ledGreen() { ledSet(0, NEOPIXEL_BRIGHT, 0); }
  91. static void ledBlue() { ledSet(0, 0, NEOPIXEL_BRIGHT); }
  92. static void ledYellow() { ledSet(NEOPIXEL_BRIGHT, NEOPIXEL_BRIGHT, 0); }
  93. static void ledMagenta() { ledSet(NEOPIXEL_BRIGHT, 0, NEOPIXEL_BRIGHT); }
  94. static void ledErrorFlash()
  95. {
  96. for (int i = 0; i < 2; i++) {
  97. ledSet(NEOPIXEL_BRIGHT, 0, 0); delay(80);
  98. ledOff(); delay(80);
  99. }
  100. }
  101. //=============================================================
  102. // TCP protocol buffer
  103. //=============================================================
  104. static uint8_t dataBuffer[50 * 1024];
  105. #define STATE_START 0
  106. #define STATE_READ_CMD 1
  107. #define STATE_WRITE_CMD 2
  108. #define CMD_WRITE 0x09
  109. #define CMD_READ 0x0A
  110. constexpr int WRITE_HDR_LEN = 10;
  111. constexpr int READ_HDR_LEN = 8;
  112. struct adauWriteHeader {
  113. uint8_t command;
  114. uint8_t safeload;
  115. uint8_t placement;
  116. uint16_t totalLen;
  117. uint8_t chipAddr;
  118. uint16_t dataLen;
  119. uint16_t address;
  120. };
  121. struct adauReadHeader {
  122. uint8_t command;
  123. uint16_t totalLen;
  124. uint8_t chipAddr;
  125. uint16_t dataLen;
  126. uint16_t address;
  127. };
  128. static adauWriteHeader writeHeader;
  129. static adauReadHeader readHeader;
  130. static constexpr uint8_t DSP_7BIT = DSP_I2C_ADDRESS; // 0x34
  131. static constexpr uint8_t EEPROM_7BIT = EEPROM_I2C_ADDRESS; // 0x50
  132. //=============================================================
  133. // 24C256 EEPROM
  134. //=============================================================
  135. static constexpr uint32_t EEPROM_SIZE_BYTES = 32768;
  136. static constexpr uint16_t EEPROM_PAGE_SIZE = 64;
  137. static constexpr uint8_t I2C_MAX_DATA_PER_TX = 28;
  138. //=============================================================
  139. // CRC32
  140. //=============================================================
  141. static uint32_t crc32_update(uint32_t crc, const uint8_t* data, size_t len)
  142. {
  143. crc = ~crc;
  144. for (size_t i = 0; i < len; i++) {
  145. crc ^= data[i];
  146. for (int b = 0; b < 8; b++) {
  147. uint32_t mask = -(crc & 1u);
  148. crc = (crc >> 1) ^ (0xEDB88320u & mask);
  149. }
  150. }
  151. return ~crc;
  152. }
  153. //=============================================================
  154. // Helpers
  155. //=============================================================
  156. static uint8_t chipAddrTo7bit(uint8_t chipAddr)
  157. {
  158. switch (chipAddr) {
  159. case 0x01: return 0x34; // chip index 1 = DSP
  160. case 0x02: return 0x50; // chip index 2 = EEPROM
  161. case 0x68: return 0x34;
  162. case 0xA0: return 0x50;
  163. case 0x34: return 0x34;
  164. case 0x50: return 0x50;
  165. default:
  166. if (chipAddr > 0x7F) return (uint8_t)(chipAddr >> 1);
  167. return chipAddr;
  168. }
  169. }
  170. static uint8_t registerSizeForAddress(uint16_t address, uint16_t dataLen)
  171. {
  172. if (address == dspRegister::CoreRegister) {
  173. if (dataLen == 2) return CORE_REGISTER_R0_REGSIZE;
  174. if (dataLen == 24) return HARDWARE_CONF_REGSIZE;
  175. return CORE_REGISTER_R0_REGSIZE;
  176. }
  177. if (address >= DSP_PROG_RAM_START && address <= DSP_PROG_RAM_END) return PROGRAM_REGSIZE;
  178. if (address < DSP_PROG_RAM_START) return PARAMETER_REGSIZE;
  179. return HARDWARE_CONF_REGSIZE;
  180. }
  181. static bool i2cAckPoll(uint8_t addr7, uint32_t timeoutMs = 80)
  182. {
  183. uint32_t start = millis();
  184. while ((millis() - start) < timeoutMs) {
  185. Wire.beginTransmission(addr7);
  186. if (Wire.endTransmission() == 0) return true;
  187. delay(1);
  188. }
  189. return false;
  190. }
  191. static bool eepromWritePageChunk(uint16_t memAddr, const uint8_t* data, uint16_t len)
  192. {
  193. Wire.beginTransmission(EEPROM_7BIT);
  194. Wire.write((uint8_t)(memAddr >> 8));
  195. Wire.write((uint8_t)(memAddr & 0xFF));
  196. for (uint16_t i = 0; i < len; i++) Wire.write(data[i]);
  197. if (Wire.endTransmission() != 0) return false;
  198. return i2cAckPoll(EEPROM_7BIT, 120);
  199. }
  200. static bool eepromWriteBlock(uint16_t memAddr, const uint8_t* data, uint16_t len)
  201. {
  202. while (len) {
  203. uint16_t pageOff = memAddr % EEPROM_PAGE_SIZE;
  204. uint16_t spaceInPage = EEPROM_PAGE_SIZE - pageOff;
  205. uint16_t chunk = len;
  206. if (chunk > spaceInPage) chunk = spaceInPage;
  207. if (chunk > I2C_MAX_DATA_PER_TX) chunk = I2C_MAX_DATA_PER_TX;
  208. if (!eepromWritePageChunk(memAddr, data, chunk)) return false;
  209. memAddr += chunk; data += chunk; len -= chunk;
  210. delay(0);
  211. }
  212. return true;
  213. }
  214. static bool eepromReadBlock(uint16_t memAddr, uint8_t* out, uint16_t len)
  215. {
  216. Wire.beginTransmission(EEPROM_7BIT);
  217. Wire.write((uint8_t)(memAddr >> 8));
  218. Wire.write((uint8_t)(memAddr & 0xFF));
  219. if (Wire.endTransmission(false) != 0) return false;
  220. uint16_t got = 0;
  221. while (got < len) {
  222. uint8_t ask = (len - got) > 32 ? 32 : (len - got);
  223. if (Wire.requestFrom((int)EEPROM_7BIT, (int)ask) != ask) return false;
  224. for (uint8_t i = 0; i < ask; i++) out[got++] = Wire.read();
  225. }
  226. return true;
  227. }
  228. static bool dspReadBlock(uint16_t memAddr, uint8_t* out, uint16_t len)
  229. {
  230. Wire.beginTransmission(DSP_7BIT);
  231. Wire.write((uint8_t)(memAddr >> 8));
  232. Wire.write((uint8_t)(memAddr & 0xFF));
  233. if (Wire.endTransmission(false) != 0) return false;
  234. uint16_t got = 0;
  235. while (got < len) {
  236. uint8_t ask = (len - got) > 32 ? 32 : (len - got);
  237. if (Wire.requestFrom((int)DSP_7BIT, (int)ask) != ask) return false;
  238. for (uint8_t i = 0; i < ask; i++) out[got++] = Wire.read();
  239. }
  240. return true;
  241. }
  242. // SigmaTCP read response: 0x0B, totalLen_hi, totalLen_lo, status, dataLen_hi, dataLen_lo, [payload]
  243. static bool sendReadResponse(WiFiClient& client, const uint8_t* data, uint16_t dataLen, bool ok)
  244. {
  245. uint16_t totalLen = 6 + dataLen;
  246. uint8_t hdr[6];
  247. hdr[0] = 0x0B;
  248. hdr[1] = (uint8_t)(totalLen >> 8);
  249. hdr[2] = (uint8_t)(totalLen & 0xFF);
  250. hdr[3] = ok ? 0x00 : 0x01;
  251. hdr[4] = (uint8_t)(dataLen >> 8);
  252. hdr[5] = (uint8_t)(dataLen & 0xFF);
  253. if (client.write(hdr, sizeof(hdr)) != sizeof(hdr)) return false;
  254. if (dataLen > 0) {
  255. if (ok && data) {
  256. if (client.write(data, dataLen) != dataLen) return false;
  257. } else {
  258. // send zeros so SigmaStudio doesn't stall on a failed read
  259. static uint8_t zeros[256];
  260. uint16_t rem = dataLen;
  261. while (rem) {
  262. uint16_t chunk = rem > sizeof(zeros) ? sizeof(zeros) : rem;
  263. if (client.write(zeros, chunk) != chunk) return false;
  264. rem -= chunk;
  265. }
  266. }
  267. }
  268. return true;
  269. }
  270. // SigmaTCP write ack: 0x09, 0x00, 0x04, status
  271. static bool sendWriteAck(WiFiClient& client, bool ok)
  272. {
  273. uint8_t ack[4] = { 0x09, 0x00, 0x04, ok ? (uint8_t)0x00 : (uint8_t)0x01 };
  274. return client.write(ack, sizeof(ack)) == sizeof(ack);
  275. }
  276. static void printHex(const char* label, const uint8_t* buf, uint16_t len, uint16_t maxPrint = 24)
  277. {
  278. Serial.print(label);
  279. uint16_t n = len < maxPrint ? len : maxPrint;
  280. for (uint16_t i = 0; i < n; i++) {
  281. if (buf[i] < 0x10) Serial.print("0");
  282. Serial.print(buf[i], HEX);
  283. Serial.print(" ");
  284. }
  285. if (len > maxPrint) Serial.print("...");
  286. Serial.println();
  287. }
  288. static void printWifiInfo()
  289. {
  290. Serial.println();
  291. Serial.println("WiFi connected.");
  292. Serial.print("WiFi IP: "); Serial.println(WiFi.localIP());
  293. Serial.print("MAC: "); Serial.println(WiFi.macAddress());
  294. Serial.println("Modulos AudioDSP");
  295. Serial.println(version);
  296. if (s_lcdOk) {
  297. lcd.setCursor(4, 3);
  298. lcd.print(WiFi.localIP());
  299. }
  300. }
  301. //=============================================================
  302. // HTTP EEPROM uploader state
  303. //=============================================================
  304. static volatile bool uploadActive = false;
  305. static volatile bool uploadVerify = false;
  306. static volatile bool uploadFailed = false;
  307. static volatile uint32_t uploadBytes = 0;
  308. static volatile uint32_t uploadCrc = 0;
  309. //=============================================================
  310. // HTTP handlers
  311. //=============================================================
  312. static String contentTypeFor(const String& path) {
  313. if (path.endsWith(".html")) return "text/html";
  314. if (path.endsWith(".css")) return "text/css";
  315. if (path.endsWith(".js")) return "application/javascript";
  316. if (path.endsWith(".png")) return "image/png";
  317. if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
  318. if (path.endsWith(".webp")) return "image/webp";
  319. if (path.endsWith(".svg")) return "image/svg+xml";
  320. if (path.endsWith(".ico")) return "image/x-icon";
  321. if (path.endsWith(".woff")) return "font/woff";
  322. if (path.endsWith(".woff2"))return "font/woff2";
  323. return "application/octet-stream";
  324. }
  325. static bool streamFromFS(String path) {
  326. if (!LittleFS.exists(path)) {
  327. if (path.startsWith("/")) {
  328. String alt = path.substring(1);
  329. if (LittleFS.exists(alt)) path = alt; else return false;
  330. } else {
  331. String alt = "/" + path;
  332. if (LittleFS.exists(alt)) path = alt; else return false;
  333. }
  334. }
  335. File f = LittleFS.open(path, "r");
  336. if (!f) return false;
  337. httpServer.streamFile(f, contentTypeFor(path));
  338. f.close();
  339. return true;
  340. }
  341. static void handleRoot() {
  342. String html = FPSTR(INDEX_HTML);
  343. html.replace("{{IP}}", WiFi.localIP().toString());
  344. httpServer.send(200, "text/html; charset=utf-8", html);
  345. }
  346. static void handleStatus() {
  347. String s;
  348. s += "uploadActive="; s += (uploadActive ? "1" : "0"); s += "\n";
  349. s += "uploadFailed="; s += (uploadFailed ? "1" : "0"); s += "\n";
  350. s += "uploadBytes="; s += String((uint32_t)uploadBytes); s += "\n";
  351. s += "uploadCRC32=0x"; s += String((uint32_t)uploadCrc, HEX); s += "\n";
  352. httpServer.send(200, "text/plain", s);
  353. }
  354. static void handleUploadDone() {
  355. if (uploadFailed) {
  356. httpServer.send(500, "text/plain", "Upload failed.\nCheck Serial log.\n");
  357. return;
  358. }
  359. String msg = "OK\nBytes written: " + String((uint32_t)uploadBytes) +
  360. "\nCRC32: 0x" + String((uint32_t)uploadCrc, HEX) + "\n";
  361. httpServer.send(200, "text/plain", msg);
  362. }
  363. static void handleUploadStream() {
  364. HTTPUpload& up = httpServer.upload();
  365. if (up.status == UPLOAD_FILE_START) {
  366. uploadActive = true; uploadFailed = false; uploadBytes = 0; uploadCrc = 0;
  367. uploadVerify = httpServer.hasArg("verify");
  368. Serial.println(); Serial.print("HTTP upload start: "); Serial.println(up.filename);
  369. Serial.print("Verify: "); Serial.println(uploadVerify ? "yes" : "no");
  370. Wire.beginTransmission(EEPROM_7BIT);
  371. Serial.print("EEPROM probe err: "); Serial.println(Wire.endTransmission());
  372. }
  373. else if (up.status == UPLOAD_FILE_WRITE) {
  374. if (uploadFailed) return;
  375. if ((uploadBytes + up.currentSize) > EEPROM_SIZE_BYTES) {
  376. Serial.println("Upload too large for 24C256"); uploadFailed = true; return;
  377. }
  378. if (!eepromWriteBlock((uint16_t)uploadBytes, up.buf, (uint16_t)up.currentSize)) {
  379. Serial.println("EEPROM write failed"); uploadFailed = true; return;
  380. }
  381. uploadCrc = crc32_update(uploadCrc, up.buf, up.currentSize);
  382. uploadBytes += up.currentSize;
  383. ledMagenta();
  384. }
  385. else if (up.status == UPLOAD_FILE_END) {
  386. Serial.print("HTTP upload end, bytes="); Serial.println((uint32_t)uploadBytes);
  387. if (uploadVerify && !uploadFailed) {
  388. Serial.println("Verify start (CRC32)...");
  389. uint32_t crc = 0;
  390. static uint8_t tmp[256];
  391. uint32_t remaining = uploadBytes; uint16_t addr = 0;
  392. while (remaining) {
  393. uint16_t n = remaining > sizeof(tmp) ? sizeof(tmp) : (uint16_t)remaining;
  394. if (!eepromReadBlock(addr, tmp, n)) { Serial.println("EEPROM read failed"); uploadFailed = true; break; }
  395. crc = crc32_update(crc, tmp, n);
  396. addr += n; remaining -= n; delay(0);
  397. }
  398. Serial.print("Verify CRC32: 0x"); Serial.println(crc, HEX);
  399. if (!uploadFailed && crc != uploadCrc) { Serial.println("CRC mismatch"); uploadFailed = true; }
  400. }
  401. uploadActive = false; ledOff();
  402. Serial.println(uploadFailed ? "HTTP upload result: FAIL" : "HTTP upload result: OK");
  403. }
  404. else if (up.status == UPLOAD_FILE_ABORTED) {
  405. Serial.println("HTTP upload aborted"); uploadActive = false; uploadFailed = true; ledOff();
  406. }
  407. }
  408. //=============================================================
  409. // HTTP OTA handlers
  410. //=============================================================
  411. static void handleOtaPage() {
  412. String html = FPSTR(OTA_HTML);
  413. html.replace("{{IP}}", WiFi.localIP().toString());
  414. httpServer.send(200, "text/html; charset=utf-8", html);
  415. }
  416. static void handleOtaDone() {
  417. if (Update.hasError()) {
  418. String err = "OTA failed: " + String(Update.errorString());
  419. Serial.println(err);
  420. httpServer.send(500, "text/plain", err);
  421. } else {
  422. httpServer.send(200, "text/plain", "Firmware updated — rebooting now.");
  423. Serial.println("OTA success — rebooting");
  424. delay(500);
  425. ESP.restart();
  426. }
  427. }
  428. static void handleOtaStream() {
  429. HTTPUpload& up = httpServer.upload();
  430. if (up.status == UPLOAD_FILE_START) {
  431. Serial.printf("OTA start: %s\n", up.filename.c_str());
  432. ledCyan();
  433. if (!Update.begin(UPDATE_SIZE_UNKNOWN)) {
  434. Serial.print("OTA begin failed: ");
  435. Update.printError(Serial);
  436. }
  437. }
  438. else if (up.status == UPLOAD_FILE_WRITE) {
  439. if (Update.write(up.buf, up.currentSize) != up.currentSize) {
  440. Serial.print("OTA write failed: ");
  441. Update.printError(Serial);
  442. ledErrorFlash();
  443. }
  444. }
  445. else if (up.status == UPLOAD_FILE_END) {
  446. if (Update.end(true)) {
  447. Serial.printf("OTA end: %u bytes written\n", up.totalSize);
  448. } else {
  449. Serial.print("OTA end failed: ");
  450. Update.printError(Serial);
  451. ledErrorFlash();
  452. }
  453. ledOff();
  454. }
  455. else if (up.status == UPLOAD_FILE_ABORTED) {
  456. Update.abort();
  457. Serial.println("OTA aborted");
  458. ledOff();
  459. }
  460. }
  461. //=============================================================
  462. // Setup
  463. //=============================================================
  464. void setup() {
  465. Wire.begin(I2C_SDA, I2C_SCL);
  466. Wire.setClock(400000);
  467. statusLed.begin();
  468. statusLed.setBrightness(NEOPIXEL_BRIGHT);
  469. statusLed.show();
  470. s_lcdOk = (lcd.begin(20, 4) == 0);
  471. if (s_lcdOk) {
  472. lcd.display(); lcd.backlight();
  473. lcd.setCursor(2, 0); lcd.print("Modulos AudioDSP"); delay(1000);
  474. lcd.setCursor(5, 1); lcd.print("Booting..."); delay(1000);
  475. } else {
  476. Serial.println("LCD not found - continuing without display");
  477. }
  478. Serial.begin(115200); delay(1500);
  479. Serial.println(); Serial.println("Booting...");
  480. Serial.printf("Reset reason: %d\n", (int)esp_reset_reason());
  481. WiFi.mode(WIFI_STA);
  482. WiFi.setAutoReconnect(true);
  483. WiFi.begin(ssid, password);
  484. while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  485. Serial.println("Connection Failed! Rebooting...");
  486. delay(5000); ESP.restart();
  487. }
  488. if (!LittleFS.begin(false)) {
  489. Serial.println("LittleFS mount failed, formatting...");
  490. if (!LittleFS.begin(true)) { Serial.println("LittleFS mount failed even after format"); return; }
  491. }
  492. Serial.println("LittleFS mounted OK");
  493. File root = LittleFS.open("/"); File f = root.openNextFile();
  494. while (f) { Serial.print("LittleFS: "); Serial.println(f.name()); f = root.openNextFile(); }
  495. if (s_lcdOk) { lcd.setCursor(3, 2); lcd.print("File System OK"); delay(1000); }
  496. tcpServer.begin();
  497. httpServer.on("/", HTTP_GET, handleRoot);
  498. httpServer.on("/status", HTTP_GET, handleStatus);
  499. httpServer.on("/upload", HTTP_POST, handleUploadDone, handleUploadStream);
  500. httpServer.on("/ota", HTTP_GET, handleOtaPage);
  501. httpServer.on("/ota_do", HTTP_POST, handleOtaDone, handleOtaStream);
  502. httpServer.onNotFound([]() {
  503. String uri = httpServer.uri();
  504. if (streamFromFS(uri)) return;
  505. Serial.print("HTTP 404: "); Serial.println(uri);
  506. httpServer.send(404, "text/plain", "Not found: " + uri);
  507. });
  508. httpServer.begin();
  509. if (s_lcdOk) {
  510. lcd.setCursor(4, 3); lcd.print("System Ready"); delay(1000);
  511. lcd.clear();
  512. lcd.setCursor(2, 0); lcd.print("Modulos AudioDSP");
  513. lcd.setCursor(3, 1); lcd.print(version); delay(500);
  514. }
  515. printWifiInfo();
  516. Serial.print("HTTP uploader: http://"); Serial.print(WiFi.localIP()); Serial.println("/");
  517. }
  518. //=============================================================
  519. // TCP bridge
  520. //=============================================================
  521. //=============================================================
  522. // TCP bridge
  523. //=============================================================
  524. static void handleTcpBridgeClient(WiFiClient& client)
  525. {
  526. Serial.println("TCP new connection");
  527. DSPWriter::resetSafeload();
  528. int writeIndex = 0; // next free slot in dataBuffer
  529. int readIndex = 0; // start of current unprocessed command
  530. int receivedByteCount = 0; // total bytes written into dataBuffer
  531. int currentState = STATE_START;
  532. while (client.connected()) {
  533. httpServer.handleClient();
  534. delay(0);
  535. // ------------------------------------------------------------------
  536. // STEP 1: Always drain the TCP stack into dataBuffer.
  537. // Do this unconditionally every loop iteration — this is what keeps
  538. // the TCP receive window open. If we only drain when we feel like it,
  539. // the window goes to zero and SigmaStudio stops sending (ZeroWindow).
  540. // ------------------------------------------------------------------
  541. while (client.available()) {
  542. if (writeIndex >= (int)sizeof(dataBuffer)) {
  543. Serial.println("TCP RX overflow");
  544. ledErrorFlash(); client.stop(); return;
  545. }
  546. int b = client.read();
  547. if (b < 0) break;
  548. dataBuffer[writeIndex++] = (uint8_t)b;
  549. receivedByteCount++;
  550. }
  551. // ------------------------------------------------------------------
  552. // STEP 2: Process whatever is in the buffer.
  553. // This is driven purely by buffer contents, not by client.available().
  554. // We loop here processing commands until we run out of buffered data.
  555. // ------------------------------------------------------------------
  556. bool processedSomething = true;
  557. while (processedSomething && client.connected()) {
  558. processedSomething = false;
  559. // --- STATE_START: identify opcode ---
  560. if (currentState == STATE_START) {
  561. if (receivedByteCount <= readIndex) {
  562. // Buffer empty — reset for next command
  563. writeIndex = readIndex = receivedByteCount = 0;
  564. ledOff();
  565. break; // nothing to process, go back to receive loop
  566. }
  567. printHex("TCP RX: ", &dataBuffer[readIndex], (uint16_t)(receivedByteCount - readIndex));
  568. uint8_t op = dataBuffer[readIndex];
  569. if (op == CMD_WRITE) { currentState = STATE_WRITE_CMD; processedSomething = true; }
  570. else if (op == CMD_READ) { currentState = STATE_READ_CMD; processedSomething = true; }
  571. else {
  572. Serial.printf("TCP invalid opcode: 0x%02X\n", op);
  573. ledErrorFlash();
  574. client.stop(); return;
  575. }
  576. }
  577. // --- STATE_WRITE_CMD ---
  578. if (currentState == STATE_WRITE_CMD) {
  579. // Need full header first
  580. if (receivedByteCount < (readIndex + WRITE_HDR_LEN)) break;
  581. writeHeader.safeload = dataBuffer[readIndex + 1];
  582. writeHeader.placement = dataBuffer[readIndex + 2];
  583. writeHeader.totalLen = (uint16_t)((dataBuffer[readIndex + 3] << 8) | dataBuffer[readIndex + 4]);
  584. writeHeader.chipAddr = dataBuffer[readIndex + 5];
  585. writeHeader.dataLen = (uint16_t)((dataBuffer[readIndex + 6] << 8) | dataBuffer[readIndex + 7]);
  586. writeHeader.address = (uint16_t)((dataBuffer[readIndex + 8] << 8) | dataBuffer[readIndex + 9]);
  587. if (writeHeader.totalLen != WRITE_HDR_LEN + writeHeader.dataLen) {
  588. Serial.printf("TCP WRITE bad totalLen: got %u expected %u\n",
  589. writeHeader.totalLen, WRITE_HDR_LEN + writeHeader.dataLen);
  590. ledErrorFlash(); client.stop(); return;
  591. }
  592. // Need full payload — if not here yet, break back to receive loop
  593. if (receivedByteCount < (readIndex + WRITE_HDR_LEN + (int)writeHeader.dataLen)) {
  594. Serial.printf("TCP WRITE buffering: have %d need %d bytes\n",
  595. receivedByteCount - readIndex,
  596. WRITE_HDR_LEN + (int)writeHeader.dataLen);
  597. break;
  598. }
  599. readIndex += WRITE_HDR_LEN;
  600. uint8_t target7 = chipAddrTo7bit(writeHeader.chipAddr);
  601. if (target7 == EEPROM_7BIT) {
  602. ledYellow();
  603. bool ok = eepromWriteBlock(writeHeader.address, &dataBuffer[readIndex], writeHeader.dataLen);
  604. readIndex += writeHeader.dataLen;
  605. sendWriteAck(client, ok);
  606. if (!ok) { Serial.println("TCP EEPROM write failed"); ledErrorFlash(); }
  607. else ledOff();
  608. currentState = STATE_START;
  609. processedSomething = true;
  610. continue;
  611. }
  612. if (target7 != DSP_7BIT) {
  613. Serial.printf("TCP unknown chipAddr: 0x%02X\n", writeHeader.chipAddr);
  614. ledErrorFlash(); client.stop(); return;
  615. }
  616. ledGreen();
  617. uint8_t registerSize = registerSizeForAddress(writeHeader.address, writeHeader.dataLen);
  618. uint16_t regAddress = writeHeader.address;
  619. Serial.printf("TCP WRITE addr=0x%04X len=%u regSz=%u safeload=%u\n",
  620. writeHeader.address, writeHeader.dataLen, registerSize, writeHeader.safeload);
  621. bool writeOk = true;
  622. if (writeHeader.safeload == 1) {
  623. if (writeHeader.dataLen % 4 != 0) {
  624. Serial.printf("TCP safeload dataLen %u not multiple of 4\n", writeHeader.dataLen);
  625. ledErrorFlash(); client.stop(); return;
  626. }
  627. int writeCount = writeHeader.dataLen / 4;
  628. int slri = readIndex;
  629. DSPWriter dspWriter;
  630. while (writeCount > 0) {
  631. uint8_t da[5] = { 0x00, dataBuffer[slri], dataBuffer[slri+1],
  632. dataBuffer[slri+2], dataBuffer[slri+3] };
  633. dspWriter.safeload_writeRegister(regAddress, da, writeCount == 1);
  634. regAddress++; slri += 4; writeCount--; delay(0);
  635. }
  636. } else {
  637. writeOk = DSPWriter::writeRegisterBlock(regAddress, writeHeader.dataLen,
  638. &dataBuffer[readIndex], registerSize);
  639. if (!writeOk) Serial.println("TCP DSP block write failed");
  640. }
  641. readIndex += writeHeader.dataLen;
  642. if (!writeOk) ledErrorFlash(); else ledOff();
  643. sendWriteAck(client, writeOk);
  644. currentState = STATE_START;
  645. processedSomething = true;
  646. continue;
  647. }
  648. // --- STATE_READ_CMD ---
  649. if (currentState == STATE_READ_CMD) {
  650. if (receivedByteCount < (readIndex + READ_HDR_LEN)) break;
  651. readHeader.totalLen = (uint16_t)((dataBuffer[readIndex + 1] << 8) | dataBuffer[readIndex + 2]);
  652. readHeader.chipAddr = dataBuffer[readIndex + 3];
  653. readHeader.dataLen = (uint16_t)((dataBuffer[readIndex + 4] << 8) | dataBuffer[readIndex + 5]);
  654. readHeader.address = (uint16_t)((dataBuffer[readIndex + 6] << 8) | dataBuffer[readIndex + 7]);
  655. readIndex += READ_HDR_LEN;
  656. uint8_t target7 = chipAddrTo7bit(readHeader.chipAddr);
  657. Serial.printf("TCP READ chip=0x%02X addr=0x%04X len=%u\n",
  658. readHeader.chipAddr, readHeader.address, readHeader.dataLen);
  659. if (readHeader.dataLen > 4096) { readHeader.dataLen = 4096; }
  660. static uint8_t readOut[4096];
  661. bool ok = false;
  662. ledBlue();
  663. if (target7 == EEPROM_7BIT) ok = eepromReadBlock(readHeader.address, readOut, readHeader.dataLen);
  664. else if (target7 == DSP_7BIT) ok = dspReadBlock (readHeader.address, readOut, readHeader.dataLen);
  665. else {
  666. Serial.printf("TCP unknown chipAddr (READ): 0x%02X\n", readHeader.chipAddr);
  667. }
  668. if (!ok) Serial.println("TCP READ I2C failed - sending zeros");
  669. if (!sendReadResponse(client, ok ? readOut : nullptr, readHeader.dataLen, ok)) {
  670. Serial.println("TCP READ send failed"); ledErrorFlash(); client.stop(); return;
  671. }
  672. ledOff();
  673. currentState = STATE_START;
  674. processedSomething = true;
  675. continue;
  676. }
  677. } // end process loop
  678. // No idle timeout — stay connected until SigmaStudio disconnects.
  679. // client.connected() will return false when the TCP connection drops.
  680. if (currentState == STATE_START && receivedByteCount == readIndex) {
  681. if (!client.available()) {
  682. httpServer.handleClient();
  683. delay(10);
  684. }
  685. }
  686. } // end main while loop
  687. DSPWriter::resetSafeload(); // flush any mid-session safeload before disconnect
  688. client.stop();
  689. Serial.println("TCP disconnected");
  690. ledOff();
  691. }
  692. //=============================================================
  693. // WiFi watchdog
  694. //=============================================================
  695. static uint32_t s_wifiLastCheck = 0;
  696. static bool s_wifiLost = false;
  697. static void maintainWifi()
  698. {
  699. if (millis() - s_wifiLastCheck < 5000) return;
  700. s_wifiLastCheck = millis();
  701. if (WiFi.status() != WL_CONNECTED) {
  702. if (!s_wifiLost) {
  703. Serial.println("WiFi lost");
  704. if (s_lcdOk) { lcd.setCursor(0, 3); lcd.print("WiFi lost... "); }
  705. s_wifiLost = true;
  706. }
  707. WiFi.reconnect();
  708. } else if (s_wifiLost) {
  709. Serial.print("WiFi reconnected, IP: "); Serial.println(WiFi.localIP());
  710. tcpServer.begin(); // re-register listening socket with recovered stack
  711. printWifiInfo(); // update LCD with current IP
  712. s_wifiLost = false;
  713. }
  714. }
  715. //=============================================================
  716. // Loop
  717. //=============================================================
  718. void loop() {
  719. maintainWifi();
  720. httpServer.handleClient();
  721. if (uploadActive) { delay(1); return; }
  722. WiFiClient client = tcpServer.available();
  723. if (client) handleTcpBridgeClient(client);
  724. delay(1);
  725. }