ModulosDSP_101.ino 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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. Wire.beginTransmission(addr7);
  167. Wire.write((uint8_t)(memAddr >> 8));
  168. Wire.write((uint8_t)(memAddr & 0xFF));
  169. if (Wire.endTransmission(false) != 0) return false;
  170. uint16_t got = 0;
  171. while (got < len) {
  172. uint8_t ask = (len - got) > 32 ? 32 : (len - got);
  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. //=============================================================
  320. // HTTP handlers
  321. //=============================================================
  322. static String contentTypeFor(const String& path) {
  323. if (path.endsWith(".html")) return "text/html";
  324. if (path.endsWith(".css")) return "text/css";
  325. if (path.endsWith(".js")) return "application/javascript";
  326. if (path.endsWith(".png")) return "image/png";
  327. if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
  328. if (path.endsWith(".webp")) return "image/webp";
  329. if (path.endsWith(".svg")) return "image/svg+xml";
  330. if (path.endsWith(".ico")) return "image/x-icon";
  331. if (path.endsWith(".woff")) return "font/woff";
  332. if (path.endsWith(".woff2"))return "font/woff2";
  333. return "application/octet-stream";
  334. }
  335. static bool streamFromFS(String path) {
  336. if (!LittleFS.exists(path)) {
  337. if (path.startsWith("/")) {
  338. String alt = path.substring(1);
  339. if (LittleFS.exists(alt)) path = alt; else return false;
  340. } else {
  341. String alt = "/" + path;
  342. if (LittleFS.exists(alt)) path = alt; else return false;
  343. }
  344. }
  345. File f = LittleFS.open(path, "r");
  346. if (!f) return false;
  347. httpServer.streamFile(f, contentTypeFor(path));
  348. f.close();
  349. return true;
  350. }
  351. static void handleRoot() {
  352. String html = FPSTR(INDEX_HTML);
  353. html.replace("{{IP}}", WiFi.localIP().toString());
  354. httpServer.send(200, "text/html; charset=utf-8", html);
  355. }
  356. static void handleUploadDone() {
  357. if (uploadFailed) {
  358. httpServer.send(500, "application/json", "{\"ok\":false}");
  359. return;
  360. }
  361. char buf[80];
  362. snprintf(buf, sizeof(buf),
  363. "{\"ok\":true,\"bytes\":%u,\"crc\":\"0x%08X\",\"verified\":%s}",
  364. (uint32_t)uploadBytes, (uint32_t)uploadCrc,
  365. uploadVerify ? "true" : "false");
  366. httpServer.send(200, "application/json", buf);
  367. }
  368. static void handleUploadStream() {
  369. HTTPUpload& up = httpServer.upload();
  370. if (up.status == UPLOAD_FILE_START) {
  371. uploadActive = true; uploadFailed = false; uploadBytes = 0; uploadCrc = 0;
  372. uploadVerify = httpServer.hasArg("verify");
  373. Serial.println(); Serial.print("HTTP upload start: "); Serial.println(up.filename);
  374. Serial.print("Verify: "); Serial.println(uploadVerify ? "yes" : "no");
  375. Wire.beginTransmission(EEPROM_7BIT);
  376. Serial.print("EEPROM probe err: "); Serial.println(Wire.endTransmission());
  377. }
  378. else if (up.status == UPLOAD_FILE_WRITE) {
  379. if (uploadFailed) return;
  380. if ((uploadBytes + up.currentSize) > EEPROM_SIZE_BYTES) {
  381. Serial.println("Upload too large for 24C256"); uploadFailed = true; return;
  382. }
  383. if (!eepromWriteBlock((uint16_t)uploadBytes, up.buf, (uint16_t)up.currentSize)) {
  384. Serial.println("EEPROM write failed"); uploadFailed = true; return;
  385. }
  386. uploadCrc = esp_rom_crc32_le(uploadCrc, up.buf, up.currentSize);
  387. uploadBytes += up.currentSize;
  388. ledMagenta();
  389. }
  390. else if (up.status == UPLOAD_FILE_END) {
  391. Serial.print("HTTP upload end, bytes="); Serial.println((uint32_t)uploadBytes);
  392. if (uploadVerify && !uploadFailed) {
  393. Serial.println("Verify start (CRC32)...");
  394. uint32_t crc = 0;
  395. static uint8_t tmp[256];
  396. uint32_t remaining = uploadBytes; uint16_t addr = 0;
  397. while (remaining) {
  398. uint16_t n = remaining > sizeof(tmp) ? sizeof(tmp) : (uint16_t)remaining;
  399. if (!i2cReadBlock(EEPROM_7BIT, addr, tmp, n)) { Serial.println("EEPROM read failed"); uploadFailed = true; break; }
  400. crc = esp_rom_crc32_le(crc, tmp, n);
  401. addr += n; remaining -= n; delay(0);
  402. }
  403. Serial.print("Verify CRC32: 0x"); Serial.println(crc, HEX);
  404. if (!uploadFailed && crc != uploadCrc) { Serial.println("CRC mismatch"); uploadFailed = true; }
  405. }
  406. uploadActive = false; ledOff();
  407. Serial.println(uploadFailed ? "HTTP upload result: FAIL" : "HTTP upload result: OK");
  408. }
  409. else if (up.status == UPLOAD_FILE_ABORTED) {
  410. Serial.println("HTTP upload aborted"); uploadActive = false; uploadFailed = true; ledOff();
  411. }
  412. }
  413. //=============================================================
  414. // HTTP DSP reset handler
  415. //=============================================================
  416. static void handleDspReset() {
  417. Serial.println("DSP soft reset requested");
  418. // Stop DSP execution, brief pause, restart. Program and parameter RAM
  419. // are preserved — this restarts execution without reloading from EEPROM.
  420. uint8_t stop[2] = { 0x00, 0x00 };
  421. uint8_t run[2] = { 0x00, 0x01 };
  422. DSPWriter::writeRegister(dspRegister::CoreRegister, sizeof(stop), stop);
  423. delay(100);
  424. DSPWriter::writeRegister(dspRegister::CoreRegister, sizeof(run), run);
  425. Serial.println("DSP soft reset complete");
  426. httpServer.send(200, "text/plain", "DSP soft reset complete.");
  427. }
  428. //=============================================================
  429. // HTTP DSP status handler GET /dsp_status
  430. //=============================================================
  431. static void handleDspStatus() {
  432. // Core Register (0x081C) — 2 bytes, bit 0 = Run
  433. uint8_t coreRaw[2] = {0, 0};
  434. bool coreOk = i2cReadBlock(DSP_7BIT, dspRegister::CoreRegister, coreRaw, 2);
  435. uint16_t coreVal = ((uint16_t)coreRaw[0] << 8) | coreRaw[1];
  436. // GPIO All Register (0x0808) — 1 byte
  437. uint8_t gpio = 0;
  438. bool gpioOk = i2cReadBlock(DSP_7BIT, dspRegister::GpioAllRegister, &gpio, 1);
  439. // ADC0–3 (0x0809–0x080C) — 1 byte each, read as a 4-byte burst
  440. uint8_t adc[4] = {0, 0, 0, 0};
  441. bool adcOk = i2cReadBlock(DSP_7BIT, dspRegister::Adc0, adc, 4);
  442. bool allOk = coreOk && gpioOk && adcOk;
  443. char buf[200];
  444. snprintf(buf, sizeof(buf),
  445. "{\"ok\":%s,\"running\":%s,"
  446. "\"coreReg\":\"0x%04X\","
  447. "\"gpio\":\"0x%02X\","
  448. "\"adc\":[\"0x%02X\",\"0x%02X\",\"0x%02X\",\"0x%02X\"]}",
  449. allOk ? "true" : "false",
  450. (coreOk && (coreVal & 0x01)) ? "true" : "false",
  451. coreVal, gpio,
  452. adc[0], adc[1], adc[2], adc[3]);
  453. httpServer.send(allOk ? 200 : 500, "application/json", buf);
  454. }
  455. //=============================================================
  456. // HTTP parameter tuner GET /params GET /param POST /param
  457. //=============================================================
  458. static void handleParamsPage() {
  459. String html = FPSTR(PARAMS_HTML);
  460. html.replace("{{IP}}", WiFi.localIP().toString());
  461. httpServer.send(200, "text/html; charset=utf-8", html);
  462. }
  463. static void handleParamGet() {
  464. if (!httpServer.hasArg("addr")) {
  465. httpServer.send(400, "text/plain", "Missing 'addr'.");
  466. return;
  467. }
  468. long addr = strtol(httpServer.arg("addr").c_str(), nullptr, 0);
  469. if (addr < 0 || addr > (long)DSP_PARAM_RAM_END) {
  470. httpServer.send(400, "text/plain", "addr must be 0x0000-0x03FF.");
  471. return;
  472. }
  473. uint8_t raw[4] = {0, 0, 0, 0};
  474. bool ok = i2cReadBlock(DSP_7BIT, (uint16_t)addr, raw, 4);
  475. // 5.23 fixed-point → float
  476. int32_t fixed = ((int32_t)raw[0] << 24) | ((int32_t)raw[1] << 16) |
  477. ((int32_t)raw[2] << 8) | (int32_t)raw[3];
  478. float fval = (float)fixed / 8388608.0f;
  479. char buf[128];
  480. snprintf(buf, sizeof(buf),
  481. "{\"ok\":%s,\"addr\":%ld,\"hex\":\"0x%02X%02X%02X%02X\",\"float\":%.7f}",
  482. ok ? "true" : "false", addr,
  483. raw[0], raw[1], raw[2], raw[3], fval);
  484. httpServer.send(ok ? 200 : 500, "application/json", buf);
  485. }
  486. static void handleParamSet() {
  487. if (!httpServer.hasArg("addr") || !httpServer.hasArg("value")) {
  488. httpServer.send(400, "text/plain", "Missing 'addr' or 'value'.");
  489. return;
  490. }
  491. long addr = strtol(httpServer.arg("addr").c_str(), nullptr, 0);
  492. if (addr < 0 || addr > (long)DSP_PARAM_RAM_END) {
  493. httpServer.send(400, "text/plain", "addr must be 0x0000-0x03FF.");
  494. return;
  495. }
  496. String mode = httpServer.arg("mode");
  497. DSPWriter dspWriter;
  498. if (mode == "hex") {
  499. String hexStr = httpServer.arg("value");
  500. if (hexStr.startsWith("0x") || hexStr.startsWith("0X")) hexStr = hexStr.substring(2);
  501. hexStr.replace(" ", "");
  502. hexStr.replace("_", "");
  503. if (hexStr.length() != 8) {
  504. httpServer.send(400, "text/plain", "Hex value must be exactly 8 hex characters.");
  505. return;
  506. }
  507. uint32_t v = strtoul(hexStr.c_str(), nullptr, 16);
  508. uint8_t sl[5] = { 0x00,
  509. (uint8_t)((v >> 24) & 0xFF),
  510. (uint8_t)((v >> 16) & 0xFF),
  511. (uint8_t)((v >> 8) & 0xFF),
  512. (uint8_t)( v & 0xFF) };
  513. dspWriter.safeload_writeRegister((uint16_t)addr, sl, true);
  514. Serial.printf("Param write (hex) addr=0x%04lX val=0x%08X\n", addr, v);
  515. } else {
  516. // Float mode — safeload_writeRegister handles 5.23 conversion internally
  517. float fval = httpServer.arg("value").toFloat();
  518. dspWriter.safeload_writeRegister((uint16_t)addr, fval, true);
  519. Serial.printf("Param write (float) addr=0x%04lX val=%.7f\n", addr, fval);
  520. }
  521. httpServer.send(200, "text/plain", "OK");
  522. }
  523. //=============================================================
  524. // HTTP WiFi reset handler POST /wifi_reset
  525. //=============================================================
  526. static void handleWifiReset() {
  527. Serial.println("WiFi credentials cleared — rebooting to AP setup mode");
  528. clearWifiCreds();
  529. httpServer.send(200, "text/plain",
  530. "Credentials cleared. Rebooting into setup mode.\n"
  531. "Connect to 'ModulosDSP-Setup' and open 192.168.4.1.");
  532. delay(500);
  533. ESP.restart();
  534. }
  535. //=============================================================
  536. // HTTP GPIO handlers GET /gpio POST /gpio
  537. //=============================================================
  538. static void handleGpioGet() {
  539. uint8_t gpio = 0;
  540. bool gpioOk = i2cReadBlock(DSP_7BIT, dspRegister::GpioAllRegister, &gpio, 1);
  541. uint8_t mpcfg[2] = {0, 0};
  542. bool cfgOk = i2cReadBlock(DSP_7BIT, dspRegister::MpCfg0, mpcfg, 2);
  543. bool ok = gpioOk && cfgOk;
  544. char buf[100];
  545. snprintf(buf, sizeof(buf),
  546. "{\"ok\":%s,\"gpio\":%u,\"mpcfg0\":%u,\"mpcfg1\":%u}",
  547. ok ? "true" : "false", gpio, mpcfg[0], mpcfg[1]);
  548. httpServer.send(ok ? 200 : 500, "application/json", buf);
  549. }
  550. static void handleGpioSet() {
  551. if (!httpServer.hasArg("value")) {
  552. httpServer.send(400, "text/plain", "Missing 'value' parameter.");
  553. return;
  554. }
  555. long val = httpServer.arg("value").toInt();
  556. if (val < 0 || val > 255) {
  557. httpServer.send(400, "text/plain", "value must be 0-255.");
  558. return;
  559. }
  560. uint8_t b = (uint8_t)val;
  561. DSPWriter::writeRegister(dspRegister::GpioAllRegister, 1, &b);
  562. Serial.printf("GPIO set: 0x%02X\n", b);
  563. httpServer.send(200, "text/plain", "OK");
  564. }
  565. //=============================================================
  566. // HTTP OTA handlers
  567. //=============================================================
  568. static void handleOtaPage() {
  569. String html = FPSTR(OTA_HTML);
  570. html.replace("{{IP}}", WiFi.localIP().toString());
  571. httpServer.send(200, "text/html; charset=utf-8", html);
  572. }
  573. static void handleOtaDone() {
  574. if (Update.hasError()) {
  575. String err = "OTA failed: " + String(Update.errorString());
  576. Serial.println(err);
  577. httpServer.send(500, "text/plain", err);
  578. } else {
  579. httpServer.send(200, "text/plain", "Firmware updated — rebooting now.");
  580. Serial.println("OTA success — rebooting");
  581. delay(500);
  582. ESP.restart();
  583. }
  584. }
  585. static void handleOtaStream() {
  586. HTTPUpload& up = httpServer.upload();
  587. if (up.status == UPLOAD_FILE_START) {
  588. Serial.printf("OTA start: %s\n", up.filename.c_str());
  589. ledCyan();
  590. if (!Update.begin(UPDATE_SIZE_UNKNOWN)) {
  591. Serial.print("OTA begin failed: ");
  592. Update.printError(Serial);
  593. }
  594. }
  595. else if (up.status == UPLOAD_FILE_WRITE) {
  596. if (Update.write(up.buf, up.currentSize) != up.currentSize) {
  597. Serial.print("OTA write failed: ");
  598. Update.printError(Serial);
  599. ledErrorFlash();
  600. }
  601. }
  602. else if (up.status == UPLOAD_FILE_END) {
  603. if (Update.end(true)) {
  604. Serial.printf("OTA end: %u bytes written\n", up.totalSize);
  605. } else {
  606. Serial.print("OTA end failed: ");
  607. Update.printError(Serial);
  608. ledErrorFlash();
  609. }
  610. ledOff();
  611. }
  612. else if (up.status == UPLOAD_FILE_ABORTED) {
  613. Update.abort();
  614. Serial.println("OTA aborted");
  615. ledOff();
  616. }
  617. }
  618. //=============================================================
  619. // Setup
  620. //=============================================================
  621. void setup() {
  622. Wire.begin(I2C_SDA, I2C_SCL);
  623. Wire.setClock(100000); // PCF8574 backpacks are often 100 kHz only — use safe speed for LCD init
  624. statusLed.begin();
  625. statusLed.setBrightness(NEOPIXEL_BRIGHT);
  626. statusLed.show();
  627. s_lcdOk = (lcd.begin(20, 4) == 0);
  628. Wire.setClock(400000); // restore for DSP / EEPROM
  629. if (s_lcdOk) {
  630. lcd.display(); lcd.backlight();
  631. lcd.setCursor(2, 0); lcd.print("Modulos AudioDSP"); delay(1000);
  632. lcd.setCursor(5, 1); lcd.print("Booting..."); delay(1000);
  633. } else {
  634. Serial.println("LCD not found - continuing without display");
  635. }
  636. Serial.begin(115200); delay(1500);
  637. Serial.println(); Serial.println("Booting...");
  638. Serial.printf("Reset reason: %d\n", (int)esp_reset_reason());
  639. if (!loadWifiCreds()) {
  640. // NVS empty — fall back to compile-time defaults so an unattended
  641. // device can reach the network without needing the config portal.
  642. strlcpy(s_ssid, DEFAULT_SSID, sizeof(s_ssid));
  643. strlcpy(s_pass, DEFAULT_PASS, sizeof(s_pass));
  644. Serial.println("No NVS credentials — using defaults");
  645. }
  646. Serial.printf("Connecting to %s", s_ssid);
  647. WiFi.mode(WIFI_STA);
  648. WiFi.setAutoReconnect(true);
  649. WiFi.begin(s_ssid, s_pass);
  650. uint32_t t0 = millis();
  651. while (WiFi.status() != WL_CONNECTED && millis() - t0 < 15000) {
  652. delay(500); Serial.print(".");
  653. }
  654. Serial.println();
  655. if (WiFi.status() != WL_CONNECTED) {
  656. Serial.println("WiFi connect failed — entering setup mode");
  657. startConfigAP(); // never returns
  658. }
  659. if (MDNS.begin(hostname)) {
  660. MDNS.addService("http", "tcp", 80);
  661. Serial.printf("mDNS: http://%s.local/\n", hostname);
  662. } else {
  663. Serial.println("mDNS start failed");
  664. }
  665. if (!LittleFS.begin(false)) {
  666. Serial.println("LittleFS mount failed, formatting...");
  667. if (!LittleFS.begin(true)) { Serial.println("LittleFS mount failed even after format"); return; }
  668. }
  669. Serial.println("LittleFS mounted OK");
  670. File root = LittleFS.open("/"); File f = root.openNextFile();
  671. while (f) { Serial.print("LittleFS: "); Serial.println(f.name()); f = root.openNextFile(); }
  672. if (s_lcdOk) { lcd.setCursor(3, 2); lcd.print("File System OK"); delay(1000); }
  673. tcpServer.begin();
  674. httpServer.on("/", HTTP_GET, handleRoot);
  675. httpServer.on("/upload", HTTP_POST, handleUploadDone, handleUploadStream);
  676. httpServer.on("/ota", HTTP_GET, handleOtaPage);
  677. httpServer.on("/ota_do", HTTP_POST, handleOtaDone, handleOtaStream);
  678. httpServer.on("/dsp_reset", HTTP_POST, handleDspReset);
  679. httpServer.on("/dsp_status", HTTP_GET, handleDspStatus);
  680. httpServer.on("/gpio", HTTP_GET, handleGpioGet);
  681. httpServer.on("/gpio", HTTP_POST, handleGpioSet);
  682. httpServer.on("/wifi_reset", HTTP_POST, handleWifiReset);
  683. httpServer.on("/params", HTTP_GET, handleParamsPage);
  684. httpServer.on("/param", HTTP_GET, handleParamGet);
  685. httpServer.on("/param", HTTP_POST, handleParamSet);
  686. httpServer.onNotFound([]() {
  687. String uri = httpServer.uri();
  688. if (streamFromFS(uri)) return;
  689. Serial.print("HTTP 404: "); Serial.println(uri);
  690. httpServer.send(404, "text/plain", "Not found: " + uri);
  691. });
  692. httpServer.begin();
  693. if (s_lcdOk) {
  694. lcd.setCursor(4, 3); lcd.print("System Ready"); delay(1000);
  695. lcd.clear();
  696. lcd.setCursor(2, 0); lcd.print("Modulos AudioDSP");
  697. lcd.setCursor(3, 1); lcd.print(version); delay(500);
  698. }
  699. printWifiInfo();
  700. Serial.print("HTTP uploader: http://"); Serial.print(WiFi.localIP()); Serial.println("/");
  701. }
  702. //=============================================================
  703. // TCP bridge
  704. //=============================================================
  705. //=============================================================
  706. // TCP bridge
  707. //=============================================================
  708. static void handleTcpBridgeClient(WiFiClient& client)
  709. {
  710. Serial.println("TCP new connection");
  711. DSPWriter::resetSafeload();
  712. int writeIndex = 0; // next free slot in dataBuffer
  713. int readIndex = 0; // start of current unprocessed command
  714. int receivedByteCount = 0; // total bytes written into dataBuffer
  715. int currentState = STATE_START;
  716. uint32_t lastActivityMs = millis(); // idle watchdog
  717. while (client.connected()) {
  718. httpServer.handleClient();
  719. delay(0);
  720. // ------------------------------------------------------------------
  721. // STEP 1: Always drain the TCP stack into dataBuffer.
  722. // Do this unconditionally every loop iteration — this is what keeps
  723. // the TCP receive window open. If we only drain when we feel like it,
  724. // the window goes to zero and SigmaStudio stops sending (ZeroWindow).
  725. // ------------------------------------------------------------------
  726. int avail = client.available();
  727. if (avail > 0) {
  728. int space = (int)sizeof(dataBuffer) - writeIndex;
  729. if (avail > space) {
  730. Serial.println("TCP RX overflow");
  731. ledErrorFlash(); client.stop(); return;
  732. }
  733. int got = client.read(&dataBuffer[writeIndex], avail);
  734. if (got > 0) {
  735. writeIndex += got;
  736. receivedByteCount += got;
  737. lastActivityMs = millis();
  738. }
  739. }
  740. // ------------------------------------------------------------------
  741. // STEP 2: Process whatever is in the buffer.
  742. // This is driven purely by buffer contents, not by client.available().
  743. // We loop here processing commands until we run out of buffered data.
  744. // ------------------------------------------------------------------
  745. bool processedSomething = true;
  746. while (processedSomething && client.connected()) {
  747. processedSomething = false;
  748. // --- STATE_START: identify opcode ---
  749. if (currentState == STATE_START) {
  750. if (receivedByteCount <= readIndex) {
  751. // Buffer empty — reset for next command
  752. writeIndex = readIndex = receivedByteCount = 0;
  753. ledOff();
  754. break; // nothing to process, go back to receive loop
  755. }
  756. #if TCP_DEBUG
  757. printHex("TCP RX: ", &dataBuffer[readIndex], (uint16_t)(receivedByteCount - readIndex));
  758. #endif
  759. uint8_t op = dataBuffer[readIndex];
  760. if (op == CMD_WRITE) { currentState = STATE_WRITE_CMD; processedSomething = true; }
  761. else if (op == CMD_READ) { currentState = STATE_READ_CMD; processedSomething = true; }
  762. else {
  763. Serial.printf("TCP invalid opcode: 0x%02X\n", op);
  764. ledErrorFlash();
  765. client.stop(); return;
  766. }
  767. }
  768. // --- STATE_WRITE_CMD ---
  769. if (currentState == STATE_WRITE_CMD) {
  770. // Need full header first
  771. if (receivedByteCount < (readIndex + WRITE_HDR_LEN)) break;
  772. writeHeader.safeload = dataBuffer[readIndex + 1];
  773. writeHeader.placement = dataBuffer[readIndex + 2];
  774. writeHeader.totalLen = (uint16_t)((dataBuffer[readIndex + 3] << 8) | dataBuffer[readIndex + 4]);
  775. writeHeader.chipAddr = dataBuffer[readIndex + 5];
  776. writeHeader.dataLen = (uint16_t)((dataBuffer[readIndex + 6] << 8) | dataBuffer[readIndex + 7]);
  777. writeHeader.address = (uint16_t)((dataBuffer[readIndex + 8] << 8) | dataBuffer[readIndex + 9]);
  778. if (writeHeader.totalLen != WRITE_HDR_LEN + writeHeader.dataLen) {
  779. Serial.printf("TCP WRITE bad totalLen: got %u expected %u\n",
  780. writeHeader.totalLen, WRITE_HDR_LEN + writeHeader.dataLen);
  781. ledErrorFlash(); client.stop(); return;
  782. }
  783. // Need full payload — if not here yet, break back to receive loop
  784. if (receivedByteCount < (readIndex + WRITE_HDR_LEN + (int)writeHeader.dataLen)) {
  785. Serial.printf("TCP WRITE buffering: have %d need %d bytes\n",
  786. receivedByteCount - readIndex,
  787. WRITE_HDR_LEN + (int)writeHeader.dataLen);
  788. break;
  789. }
  790. readIndex += WRITE_HDR_LEN;
  791. uint8_t target7 = chipAddrTo7bit(writeHeader.chipAddr);
  792. if (target7 == EEPROM_7BIT) {
  793. ledYellow();
  794. bool ok = eepromWriteBlock(writeHeader.address, &dataBuffer[readIndex], writeHeader.dataLen);
  795. readIndex += writeHeader.dataLen;
  796. sendWriteAck(client, ok);
  797. if (!ok) { Serial.println("TCP EEPROM write failed"); ledErrorFlash(); }
  798. else ledOff();
  799. currentState = STATE_START;
  800. processedSomething = true;
  801. continue;
  802. }
  803. if (target7 != DSP_7BIT) {
  804. Serial.printf("TCP unknown chipAddr: 0x%02X\n", writeHeader.chipAddr);
  805. ledErrorFlash(); client.stop(); return;
  806. }
  807. ledGreen();
  808. uint8_t registerSize = registerSizeForAddress(writeHeader.address, writeHeader.dataLen);
  809. uint16_t regAddress = writeHeader.address;
  810. Serial.printf("TCP WRITE addr=0x%04X len=%u regSz=%u safeload=%u\n",
  811. writeHeader.address, writeHeader.dataLen, registerSize, writeHeader.safeload);
  812. bool writeOk = true;
  813. if (writeHeader.safeload == 1) {
  814. if (writeHeader.dataLen % 4 != 0) {
  815. Serial.printf("TCP safeload dataLen %u not multiple of 4\n", writeHeader.dataLen);
  816. ledErrorFlash(); client.stop(); return;
  817. }
  818. int writeCount = writeHeader.dataLen / 4;
  819. int slri = readIndex;
  820. DSPWriter dspWriter;
  821. while (writeCount > 0) {
  822. uint8_t da[5] = { 0x00, dataBuffer[slri], dataBuffer[slri+1],
  823. dataBuffer[slri+2], dataBuffer[slri+3] };
  824. dspWriter.safeload_writeRegister(regAddress, da, writeCount == 1);
  825. regAddress++; slri += 4; writeCount--; delay(0);
  826. }
  827. } else {
  828. writeOk = DSPWriter::writeRegisterBlock(regAddress, writeHeader.dataLen,
  829. &dataBuffer[readIndex], registerSize);
  830. if (!writeOk) Serial.println("TCP DSP block write failed");
  831. }
  832. readIndex += writeHeader.dataLen;
  833. if (!writeOk) ledErrorFlash(); else ledOff();
  834. sendWriteAck(client, writeOk);
  835. currentState = STATE_START;
  836. processedSomething = true;
  837. continue;
  838. }
  839. // --- STATE_READ_CMD ---
  840. if (currentState == STATE_READ_CMD) {
  841. if (receivedByteCount < (readIndex + READ_HDR_LEN)) break;
  842. readHeader.totalLen = (uint16_t)((dataBuffer[readIndex + 1] << 8) | dataBuffer[readIndex + 2]);
  843. readHeader.chipAddr = dataBuffer[readIndex + 3];
  844. readHeader.dataLen = (uint16_t)((dataBuffer[readIndex + 4] << 8) | dataBuffer[readIndex + 5]);
  845. readHeader.address = (uint16_t)((dataBuffer[readIndex + 6] << 8) | dataBuffer[readIndex + 7]);
  846. readIndex += READ_HDR_LEN;
  847. uint8_t target7 = chipAddrTo7bit(readHeader.chipAddr);
  848. Serial.printf("TCP READ chip=0x%02X addr=0x%04X len=%u\n",
  849. readHeader.chipAddr, readHeader.address, readHeader.dataLen);
  850. if (readHeader.dataLen > 4096) { readHeader.dataLen = 4096; }
  851. static uint8_t readOut[4096];
  852. bool ok = false;
  853. ledBlue();
  854. if (target7 == EEPROM_7BIT) ok = i2cReadBlock(EEPROM_7BIT, readHeader.address, readOut, readHeader.dataLen);
  855. else if (target7 == DSP_7BIT) ok = i2cReadBlock(DSP_7BIT, readHeader.address, readOut, readHeader.dataLen);
  856. else {
  857. Serial.printf("TCP unknown chipAddr (READ): 0x%02X\n", readHeader.chipAddr);
  858. }
  859. if (!ok) Serial.println("TCP READ I2C failed - sending zeros");
  860. if (!sendReadResponse(client, ok ? readOut : nullptr, readHeader.dataLen, ok)) {
  861. Serial.println("TCP READ send failed"); ledErrorFlash(); client.stop(); return;
  862. }
  863. ledOff();
  864. currentState = STATE_START;
  865. processedSomething = true;
  866. continue;
  867. }
  868. } // end process loop
  869. // Idle path — no data waiting, no command in progress.
  870. if (currentState == STATE_START && receivedByteCount == readIndex) {
  871. if (!client.available()) {
  872. if (millis() - lastActivityMs > TCP_IDLE_TIMEOUT_MS) {
  873. Serial.println("TCP idle timeout — closing session");
  874. ledErrorFlash();
  875. break;
  876. }
  877. httpServer.handleClient();
  878. delay(10);
  879. }
  880. }
  881. } // end main while loop
  882. DSPWriter::resetSafeload(); // flush any mid-session safeload before disconnect
  883. client.stop();
  884. Serial.println("TCP disconnected");
  885. ledOff();
  886. }
  887. //=============================================================
  888. // WiFi watchdog
  889. //=============================================================
  890. static uint32_t s_wifiLastCheck = 0;
  891. static bool s_wifiLost = false;
  892. static void maintainWifi()
  893. {
  894. if (millis() - s_wifiLastCheck < 5000) return;
  895. s_wifiLastCheck = millis();
  896. if (WiFi.status() != WL_CONNECTED) {
  897. if (!s_wifiLost) {
  898. Serial.println("WiFi lost");
  899. if (s_lcdOk) { lcd.setCursor(0, 3); lcd.print("WiFi lost... "); }
  900. s_wifiLost = true;
  901. }
  902. WiFi.reconnect();
  903. } else if (s_wifiLost) {
  904. Serial.print("WiFi reconnected, IP: "); Serial.println(WiFi.localIP());
  905. MDNS.begin(hostname);
  906. MDNS.addService("http", "tcp", 80);
  907. tcpServer.begin(); // re-register listening socket with recovered stack
  908. printWifiInfo(); // update LCD with current IP
  909. s_wifiLost = false;
  910. }
  911. }
  912. //=============================================================
  913. // Loop
  914. //=============================================================
  915. void loop() {
  916. maintainWifi();
  917. httpServer.handleClient();
  918. if (uploadActive) { delay(1); return; }
  919. WiFiClient client = tcpServer.available();
  920. if (client) handleTcpBridgeClient(client);
  921. delay(1);
  922. }