ModulosDSP_101.ino 37 KB

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