ModulosDSP_101.ino 40 KB

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