ModulosDSP_101.ino 27 KB

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