ModulosDSP_101.ino 42 KB

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