ModulosDSP_101.ino 37 KB

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