/* ESP32-CAM Spy Car v2 - MAIN BOARD (WiFi + Camera + Motor Driver + Flash LED) + Arduino Nano link (Relay, Radar, Ultrasonic, IR sensor Nano te ache) v2 FIX: - Radar shudhu button chaple ON hobe (scan korbe), default OFF - Radar data/HUD camera video er upore overlay (radar ON thakle radar, sob somoy HUD reading) - Web server jam hoy na: radar poll e in-flight guard, halka JSON (String use kora hoyni) - Motor failsafe 1000ms + heartbeat 200ms (deri hole o motor bondho hobe na) - Nano status race fix (button chaple ager status ulte dey na) - UART RX buffer 1024 byte - Flash LED: OFF / ON / BLINK (Light button chaple ghure ghure) - Pichoner lal LED (GPIO33) = loop alive indicator. Blink korle code cholche, blink bondho = hang - WiFi TX power kom kora (brownout kom hobe) Nano link (hardware UART, 9600 baud): ESP32 U0T (GPIO1) --------------------> Nano RX0 ESP32 U0R (GPIO3) <--[1k]--+--[2k]--GND Nano TX1 (voltage divider, 5V -> 3.3V) GND ---- GND NOTE: UART0 Nano er sathe use hocche, tai Serial Monitor/debug kaj korbe na. ESP32 code upload korar somoy U0T/U0R er wire duita khule rakho. Board : AI Thinker ESP32-CAM (Arduino IDE: "AI Thinker ESP32-CAM") Kibhabe use korbe: 1) Power on korar por phone er WiFi e "SpyCar" khojo, password: 12345678 2) Connect hoye browser e kholo: http://192.168.4.1 3) Router WiFi select/likho + password dao -> Connect 4) Page e IP ar URL dekhabe. Phone ke router WiFi te connect kore oi IP/URL kholo 5) WiFi bodlate chaile controller page er "WiFi Reset" button chaapo (Mobile data off rakho) */ #include "esp_camera.h" #include "esp_http_server.h" #include "esp_timer.h" #include #include #include #include "soc/soc.h" #include "soc/rtc_cntl_reg.h" // UART0 (GPIO1/GPIO3) Nano er sathe link hishebe use hocche. // Tai debug "Serial" ke dummy kore dewa hoyeche (Serial.print/println kono kaj korbe na). static HardwareSerial& NanoLink = Serial; struct NullSerial { void begin(unsigned long) {} template size_t print(T) { return 0; } template size_t println(T) { return 0; } size_t println() { return 0; } int printf(const char*, ...) { return 0; } }; static NullSerial SerialNull; #define Serial SerialNull // ================== FIX SWITCHES ================== // 1 = brownout reset bondho (shudhu temporary test er jonno; asol fix hocche power/capacitor) #define DISABLE_BROWNOUT 0 // Nano na pele car forward e jabe kina (1 = jabe na, safer) #define BLOCK_FWD_IF_NANO_LOST 1 #define NANO_TIMEOUT_MS 1500 // Command na ashle koto ms por motor stop (web heartbeat 200ms) #define MOTOR_FAILSAFE_MS 1000 // WiFi TX power: kom korle current peak kome, brownout kome (range ektu kome) #define WIFI_TX_POWER WIFI_POWER_15dBm // ================== WIFI SETTINGS ================== // Setup hotspot (WiFi set korar jonno) const char* AP_SSID = "SpyCar"; const char* AP_PASS = "12345678"; // mDNS hostname: http://spycar.local const char* MDNS_NAME = "spycar"; const unsigned long WIFI_BOOT_TIMEOUT_MS = 20000; // boot e saved WiFi te connect howar somoy const unsigned long CONNECT_TIMEOUT_MS = 20000; // setup page theke connect howar somoy const unsigned long AP_KEEP_MS = 300000; // WiFi connect hower por hotspot koto khon cholbe (5 min) const unsigned long WIFI_LOST_TO_AP_MS = 60000; // router haraye 60s por abar hotspot on const unsigned long AP_RETRY_MS = 60000; // hotspot on thakle saved WiFi te abar try // ================== PINS ================== #define IN1 12 // Left motor #define IN2 13 #define IN3 15 // Right motor #define IN4 14 #define FLASH_LED 4 // shada boro flash LED #define STATUS_LED 33 // pichoner choto lal LED (active LOW) // ---- Nano UART link (UART0) ---- // ESP32 U0T (GPIO1) -> Nano RX0 ; Nano TX1 -> divider -> ESP32 U0R (GPIO3) #define NANO_BAUD 9600 // ================== CAMERA PINS (AI Thinker) ================== #define PWDN_GPIO_NUM 32 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 0 #define SIOD_GPIO_NUM 26 #define SIOC_GPIO_NUM 27 #define Y9_GPIO_NUM 35 #define Y8_GPIO_NUM 34 #define Y7_GPIO_NUM 39 #define Y6_GPIO_NUM 36 #define Y5_GPIO_NUM 21 #define Y4_GPIO_NUM 19 #define Y3_GPIO_NUM 18 #define Y2_GPIO_NUM 5 #define VSYNC_GPIO_NUM 25 #define HREF_GPIO_NUM 23 #define PCLK_GPIO_NUM 22 // ================== STATE ================== enum Dir { D_STOP, D_FORWARD, D_BACK, D_LEFT, D_RIGHT }; volatile Dir currentDir = D_STOP; volatile unsigned long lastCmdTime = 0; volatile uint8_t flashMode = 0; // 0 = off, 1 = on, 2 = blink // ---- Nano theke ashe ---- #define RADAR_STEP 5 #define RADAR_POINTS 37 // 0..180 deg, 5 deg step volatile bool nanoObstacle = false; // IR ba ultrasonic samne obstacle dekhche volatile int nanoDist = 0; // samner distance (cm), 0 = echo nai volatile bool nanoIR = false; volatile bool relayOn = false; volatile bool radarOn = false; volatile int radarAngle = 90; volatile unsigned long lastNanoMsg = 0; // 0 = kokhono Nano er signal pai nai volatile unsigned long radarCmdAt = 0; // button chapar somoy (Nano status race fix) volatile unsigned long relayCmdAt = 0; int16_t radarDist[RADAR_POINTS]; // 0 = echo nai / bahire httpd_handle_t control_httpd = NULL; httpd_handle_t stream_httpd = NULL; // ---- WiFi manager state ---- Preferences prefs; String savedSsid = ""; String savedPass = ""; bool apActive = false; // setup hotspot on ache kina bool mdnsStarted = false; enum ConnState { CS_IDLE, CS_CONNECTING, CS_OK, CS_FAIL }; volatile ConnState connState = CS_IDLE; volatile bool connectRequested = false; String reqSsid = ""; String reqPass = ""; unsigned long connStart = 0; volatile unsigned long apOffAt = 0; // 0 = hotspot off schedule nei volatile unsigned long restartAt = 0; // 0 = restart schedule nei #define PART_BOUNDARY "123456789000000000000987654321" // ================= VIDEO QUALITY PRESET ================= // 1 = QQVGA 160x120 (sobcheye halka, quality kom) // 2 = QVGA 320x240 (RECOMMENDED: quality valo + smooth) // 3 = VGA 640x480 (sobcheye valo quality, kintu strong router WiFi lagbe, lag hote pare) #define VIDEO_PRESET 1 #if VIDEO_PRESET == 1 #define CAM_FRAME_SIZE FRAMESIZE_QQVGA #define CAM_JPEG_QUALITY 20 // jototuku choto number, toto valo quality #define STREAM_MIN_INTERVAL_MS 70 // ~14 FPS #define STREAM_MAX_FRAME_BYTES 16000 #elif VIDEO_PRESET == 2 #define CAM_FRAME_SIZE FRAMESIZE_QVGA #define CAM_JPEG_QUALITY 12 #define STREAM_MIN_INTERVAL_MS 90 // ~11 FPS #define STREAM_MAX_FRAME_BYTES 30000 #else #define CAM_FRAME_SIZE FRAMESIZE_VGA #define CAM_JPEG_QUALITY 12 #define STREAM_MIN_INTERVAL_MS 140 // ~7 FPS #define STREAM_MAX_FRAME_BYTES 70000 #endif static const char* STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY; static const char* STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n"; static const char* STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n"; // ================== CONTROL PAGE ================== static const char INDEX_HTML[] PROGMEM = R"rawliteral( Spy Car

🕵️ Spy Car

Live Video
Connecting...
⚠ OBSTACLE! Forward blocked
Connecting...
Network: Checking...
IP: Checking...
)rawliteral"; // ================== WIFI SETUP PAGE ================== static const char SETUP_HTML[] PROGMEM = R"rawliteral( SpyCar WiFi Setup

📶 SpyCar WiFi Setup

Loading...
)rawliteral"; // ================== WIFI HELPERS ================== String jsonEsc(const String& s) { String o; for (unsigned int i = 0; i < s.length(); i++) { char c = s[i]; if (c == '"' || c == '\\') { o += '\\'; o += c; } else if ((uint8_t)c >= 0x20) o += c; } return o; } String urlDecode(const char* s) { String o; while (*s) { if (*s == '+') { o += ' '; } else if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { char h[3] = { s[1], s[2], 0 }; o += (char)strtol(h, NULL, 16); s += 2; } else { o += *s; } s++; } return o; } void applyWiFiTuning() { WiFi.setSleep(false); // video/control latency komanor jonno WiFi.setTxPower(WIFI_TX_POWER); } void loadWiFi() { prefs.begin("spycar", true); savedSsid = prefs.getString("ssid", ""); savedPass = prefs.getString("pass", ""); prefs.end(); } void saveWiFi(const String& s, const String& p) { prefs.begin("spycar", false); prefs.putString("ssid", s); prefs.putString("pass", p); prefs.end(); savedSsid = s; savedPass = p; } void clearWiFi() { prefs.begin("spycar", false); prefs.remove("ssid"); prefs.remove("pass"); prefs.end(); savedSsid = ""; savedPass = ""; } void startAP() { WiFi.mode(WIFI_AP_STA); // AP + STA ek shathe, jate scan/connect korar somoy hotspot thake applyWiFiTuning(); WiFi.disconnect(false); // background e bar bar router khujbe na (retry loop e kora hobe) bool ok = WiFi.softAP(AP_SSID, AP_PASS, 1, 0, 4); apActive = ok; if (ok) { Serial.println("Setup hotspot ready!"); Serial.print("SSID: "); Serial.println(AP_SSID); Serial.print("Password: "); Serial.println(AP_PASS); Serial.print("Portal: http://"); Serial.println(WiFi.softAPIP()); } else { Serial.println("Setup hotspot start failed!"); } } void stopAP() { WiFi.softAPdisconnect(true); WiFi.mode(WIFI_STA); applyWiFiTuning(); apActive = false; Serial.println("Setup hotspot off."); } void startMDNS() { MDNS.end(); mdnsStarted = false; if (MDNS.begin(MDNS_NAME)) { MDNS.addService("http", "tcp", 80); mdnsStarted = true; Serial.print("mDNS ready: http://"); Serial.print(MDNS_NAME); Serial.println(".local"); } else { Serial.println("mDNS start failed."); } } // ================== NANO LINK ================== bool nanoLost() { return lastNanoMsg == 0 || (millis() - lastNanoMsg) > NANO_TIMEOUT_MS; } void nanoSend(const char* cmd) { NanoLink.print(cmd); NanoLink.print('\n'); } // Nano theke ashe: S,,,,, ar R,, void nanoHandleLine(char* l) { if (l[0] == 'S' && l[1] == ',') { int o, d, ir, rl, rd; if (sscanf(l + 2, "%d,%d,%d,%d,%d", &o, &d, &ir, &rl, &rd) == 5) { nanoObstacle = (o != 0); nanoDist = d; nanoIR = (ir != 0); unsigned long t = millis(); // button chapar por 1.5s purano status ignore (UI ulte jay na) if (relayCmdAt == 0 || t - relayCmdAt > 1500) relayOn = (rl != 0); if (radarCmdAt == 0 || t - radarCmdAt > 1500) radarOn = (rd != 0); lastNanoMsg = t; } } else if (l[0] == 'R' && l[1] == ',') { int a, d; if (sscanf(l + 2, "%d,%d", &a, &d) == 2 && a >= 0 && a <= 180) { radarDist[a / RADAR_STEP] = (int16_t)d; radarAngle = a; lastNanoMsg = millis(); } } } void nanoPoll() { static char buf[48]; static uint8_t n = 0; while (NanoLink.available()) { char c = (char)NanoLink.read(); if (c == '\n' || c == '\r') { if (n) { buf[n] = 0; nanoHandleLine(buf); n = 0; } } else if (n < sizeof(buf) - 1) { buf[n++] = c; } else { n = 0; // line onek boro, bad } } } void setRelay(bool on) { if (nanoLost()) return; nanoSend(on ? "RL,1" : "RL,0"); relayOn = on; relayCmdAt = millis(); if (relayCmdAt == 0) relayCmdAt = 1; } void setRadar(bool on) { if (nanoLost()) return; for (int i = 0; i < RADAR_POINTS; i++) radarDist[i] = 0; // purano point muche dao nanoSend(on ? "RD,1" : "RD,0"); radarOn = on; radarCmdAt = millis(); if (radarCmdAt == 0) radarCmdAt = 1; } // ================== MOTOR CONTROL ================== // Forward er jonno: Nano obstacle dekhle ba Nano er signal na pele block bool obstacleDetected() { if (nanoLost()) return BLOCK_FWD_IF_NANO_LOST; return nanoObstacle; } void stopMotors() { digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); currentDir = D_STOP; } // return false hole forward block hoyeche bool drive(Dir d) { switch (d) { case D_FORWARD: if (obstacleDetected()) { stopMotors(); return false; } digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); break; case D_BACK: digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); break; case D_LEFT: // pivot left digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); break; case D_RIGHT: // pivot right digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH); break; default: stopMotors(); return true; } currentDir = d; return true; } const char* dirName(Dir d) { switch (d) { case D_FORWARD: return "forward"; case D_BACK: return "back"; case D_LEFT: return "left"; case D_RIGHT: return "right"; default: return "stop"; } } // ================== HTTP HANDLERS ================== static esp_err_t sendJson(httpd_req_t* req, const String& body) { httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, body.c_str(), body.length()); } // "/" : hotspot on thakle setup page, na hole controller static esp_err_t index_handler(httpd_req_t* req) { httpd_resp_set_type(req, "text/html; charset=utf-8"); if (apActive) return httpd_resp_send(req, SETUP_HTML, HTTPD_RESP_USE_STRLEN); return httpd_resp_send(req, INDEX_HTML, HTTPD_RESP_USE_STRLEN); } static esp_err_t control_handler(httpd_req_t* req) { httpd_resp_set_type(req, "text/html; charset=utf-8"); return httpd_resp_send(req, INDEX_HTML, HTTPD_RESP_USE_STRLEN); } static esp_err_t setup_handler(httpd_req_t* req) { httpd_resp_set_type(req, "text/html; charset=utf-8"); return httpd_resp_send(req, SETUP_HTML, HTTPD_RESP_USE_STRLEN); } // WiFi scan (async, httpd block korbe na) static esp_err_t scan_handler(httpd_req_t* req) { char query[16]; char val[4]; bool start = false; if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK && httpd_query_key_value(query, "start", val, sizeof(val)) == ESP_OK) { start = true; } int n = WiFi.scanComplete(); if (start && n != WIFI_SCAN_RUNNING) { WiFi.scanDelete(); n = WiFi.scanNetworks(true); // async scan shuru if (n == WIFI_SCAN_FAILED) return sendJson(req, "{\"scanning\":false,\"list\":[]}"); return sendJson(req, "{\"scanning\":true}"); } if (n == WIFI_SCAN_RUNNING) return sendJson(req, "{\"scanning\":true}"); if (n < 0) return sendJson(req, "{\"scanning\":false,\"list\":[]}"); String out = "{\"scanning\":false,\"list\":["; bool first = true; for (int i = 0; i < n && i < 20; i++) { String s = WiFi.SSID(i); if (s.length() == 0) continue; if (!first) out += ","; first = false; out += "{\"s\":\"" + jsonEsc(s) + "\",\"r\":" + String(WiFi.RSSI(i)) + ",\"l\":" + (WiFi.encryptionType(i) == WIFI_AUTH_OPEN ? "0" : "1") + "}"; } out += "]}"; WiFi.scanDelete(); return sendJson(req, out); } // WiFi connect request (/connect?ssid=..&pass=..) static esp_err_t connect_handler(httpd_req_t* req) { char query[400]; char sEnc[128]; char pEnc[200]; sEnc[0] = 0; pEnc[0] = 0; if (httpd_req_get_url_query_str(req, query, sizeof(query)) != ESP_OK || httpd_query_key_value(query, "ssid", sEnc, sizeof(sEnc)) != ESP_OK) { return sendJson(req, "{\"ok\":false}"); } if (httpd_query_key_value(query, "pass", pEnc, sizeof(pEnc)) != ESP_OK) pEnc[0] = 0; String s = urlDecode(sEnc); String p = urlDecode(pEnc); if (s.length() == 0 || s.length() > 32 || p.length() > 63) { return sendJson(req, "{\"ok\":false}"); } reqSsid = s; reqPass = p; connState = CS_CONNECTING; // status page e sathe sathe "connecting" dekhabe connectRequested = true; // asol connect loop() e hobe return sendJson(req, "{\"ok\":true}"); } // Setup page er status (state + IP + URL) static esp_err_t wifistatus_handler(httpd_req_t* req) { bool sta = (WiFi.status() == WL_CONNECTED); const char* st = (connState == CS_CONNECTING) ? "connecting" : (connState == CS_FAIL) ? "fail" : sta ? "ok" : "idle"; String out = "{\"state\":\"" + String(st) + "\""; out += ",\"ssid\":\"" + (sta ? jsonEsc(WiFi.SSID()) : String("")) + "\""; out += ",\"ip\":\"" + (sta ? WiFi.localIP().toString() : String("")) + "\""; out += ",\"url\":\"http://" + String(MDNS_NAME) + ".local\""; out += ",\"apip\":\"" + WiFi.softAPIP().toString() + "\"}"; return sendJson(req, out); } // Setup hotspot off (shudhu router connected thakle) static esp_err_t apoff_handler(httpd_req_t* req) { if (apActive && WiFi.status() == WL_CONNECTED) { apOffAt = millis() + 1500; if (apOffAt == 0) apOffAt = 1; return sendJson(req, "{\"ok\":true}"); } return sendJson(req, "{\"ok\":false}"); } // Saved WiFi muche restart static esp_err_t resetwifi_handler(httpd_req_t* req) { clearWiFi(); restartAt = millis() + 1500; if (restartAt == 0) restartAt = 1; return sendJson(req, "{\"ok\":true}"); } static esp_err_t action_handler(httpd_req_t* req) { char query[64]; char val[16]; bool ok = true; if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK && httpd_query_key_value(query, "go", val, sizeof(val)) == ESP_OK) { lastCmdTime = millis(); if (!strcmp(val, "forward")) ok = drive(D_FORWARD); else if (!strcmp(val, "back")) ok = drive(D_BACK); else if (!strcmp(val, "left")) ok = drive(D_LEFT); else if (!strcmp(val, "right")) ok = drive(D_RIGHT); else stopMotors(); } httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, ok ? "{\"ok\":true}" : "{\"ok\":false,\"blocked\":true}", HTTPD_RESP_USE_STRLEN); } static esp_err_t status_handler(httpd_req_t* req) { char buf[400]; bool sta = (WiFi.status() == WL_CONNECTED); String ip = sta ? WiFi.localIP().toString() : WiFi.softAPIP().toString(); int rssi = sta ? WiFi.RSSI() : 0; bool nano = !nanoLost(); snprintf(buf, sizeof(buf), "{\"dir\":\"%s\",\"obstacle\":%s,\"dist\":%d,\"ir\":%s,\"nano\":%s,\"relay\":%s,\"radar\":%s," "\"sta\":%s,\"ap\":%s,\"ip\":\"%s\",\"rssi\":%d,\"url\":\"http://%s.local\"}", dirName(currentDir), (nano && nanoObstacle) ? "true" : "false", (int)nanoDist, nanoIR ? "true" : "false", nano ? "true" : "false", relayOn ? "true" : "false", radarOn ? "true" : "false", sta ? "true" : "false", apActive ? "true" : "false", ip.c_str(), rssi, MDNS_NAME); httpd_resp_set_type(req, "application/json"); return httpd_resp_send(req, buf, HTTPD_RESP_USE_STRLEN); } // /led?on=0 (off) | 1 (on) | 2 (blink) static esp_err_t led_handler(httpd_req_t* req) { char query[32], val[8]; if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK && httpd_query_key_value(query, "on", val, sizeof(val)) == ESP_OK) { int m = val[0] - '0'; if (m < 0 || m > 2) m = 0; flashMode = (uint8_t)m; if (m == 0) digitalWrite(FLASH_LED, LOW); else if (m == 1) digitalWrite(FLASH_LED, HIGH); // m == 2 : loop() blink korbe } return httpd_resp_send(req, "OK", HTTPD_RESP_USE_STRLEN); } static esp_err_t relay_handler(httpd_req_t* req) { char query[32], val[8]; if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK && httpd_query_key_value(query, "on", val, sizeof(val)) == ESP_OK) { setRelay(val[0] == '1'); } char out[48]; snprintf(out, sizeof(out), "{\"relay\":%s,\"nano\":%s}", relayOn ? "true" : "false", nanoLost() ? "false" : "true"); return sendJson(req, String(out)); } static esp_err_t radar_handler(httpd_req_t* req) { char query[32], val[8]; if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK && httpd_query_key_value(query, "on", val, sizeof(val)) == ESP_OK) { setRadar(val[0] == '1'); } char out[48]; snprintf(out, sizeof(out), "{\"radar\":%s,\"nano\":%s}", radarOn ? "true" : "false", nanoLost() ? "false" : "true"); return sendJson(req, String(out)); } // Radar + reading (halka JSON, String use kora hoyni, heap fragment hoy na) static esp_err_t radardata_handler(httpd_req_t* req) { char buf[360]; int n = snprintf(buf, sizeof(buf), "{\"a\":%d,\"f\":%d,\"o\":%d,\"i\":%d,\"n\":%d,\"d\":[", (int)radarAngle, (int)nanoDist, nanoObstacle ? 1 : 0, nanoIR ? 1 : 0, nanoLost() ? 0 : 1); for (int i = 0; i < RADAR_POINTS; i++) { if (n >= (int)sizeof(buf) - 12) break; n += snprintf(buf + n, sizeof(buf) - n, i ? ",%d" : "%d", (int)radarDist[i]); } n += snprintf(buf + n, sizeof(buf) - n, "]}"); httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, buf, n); } static esp_err_t capture_handler(httpd_req_t* req) { camera_fb_t* fb = esp_camera_fb_get(); if (!fb) { httpd_resp_send_500(req); return ESP_FAIL; } httpd_resp_set_type(req, "image/jpeg"); httpd_resp_set_hdr(req, "Content-Disposition", "attachment; filename=spycar.jpg"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); esp_err_t res = httpd_resp_send(req, (const char*)fb->buf, fb->len); esp_camera_fb_return(fb); return res; } static esp_err_t stream_handler(httpd_req_t* req) { camera_fb_t* fb = NULL; esp_err_t res = ESP_OK; char part_buf[64]; res = httpd_resp_set_type(req, STREAM_CONTENT_TYPE); if (res != ESP_OK) return res; httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); httpd_resp_set_hdr(req, "Cache-Control", "no-cache, no-store, must-revalidate"); httpd_resp_set_hdr(req, "Pragma", "no-cache"); httpd_resp_set_hdr(req, "Connection", "keep-alive"); unsigned long lastFrame = 0; while (true) { if (millis() - lastFrame < STREAM_MIN_INTERVAL_MS) { delay(2); continue; } lastFrame = millis(); fb = esp_camera_fb_get(); if (!fb) { delay(10); continue; } if (fb->len > STREAM_MAX_FRAME_BYTES) { esp_camera_fb_return(fb); fb = NULL; continue; } size_t hlen = snprintf(part_buf, sizeof(part_buf), STREAM_PART, fb->len); res = httpd_resp_send_chunk(req, STREAM_BOUNDARY, strlen(STREAM_BOUNDARY)); if (res == ESP_OK) res = httpd_resp_send_chunk(req, part_buf, hlen); if (res == ESP_OK) res = httpd_resp_send_chunk(req, (const char*)fb->buf, fb->len); esp_camera_fb_return(fb); fb = NULL; if (res != ESP_OK) break; } return res; } void startServers() { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); config.server_port = 80; config.core_id = 0; // control server Core 0 e config.stack_size = 8192; // String/JSON handler er jonno beshi stack config.max_uri_handlers = 16; config.max_open_sockets = 4; config.lru_purge_enable = true; // purano connection auto bondho config.recv_wait_timeout = 5; config.send_wait_timeout = 5; httpd_uri_t index_uri = { "/", HTTP_GET, index_handler, NULL }; httpd_uri_t control_uri = { "/control", HTTP_GET, control_handler, NULL }; httpd_uri_t setup_uri = { "/setup", HTTP_GET, setup_handler, NULL }; httpd_uri_t scan_uri = { "/scan", HTTP_GET, scan_handler, NULL }; httpd_uri_t connect_uri = { "/connect", HTTP_GET, connect_handler, NULL }; httpd_uri_t wifistatus_uri = { "/wifistatus", HTTP_GET, wifistatus_handler, NULL }; httpd_uri_t apoff_uri = { "/apoff", HTTP_GET, apoff_handler, NULL }; httpd_uri_t resetwifi_uri = { "/resetwifi", HTTP_GET, resetwifi_handler, NULL }; httpd_uri_t action_uri = { "/action", HTTP_GET, action_handler, NULL }; httpd_uri_t status_uri = { "/status", HTTP_GET, status_handler, NULL }; httpd_uri_t led_uri = { "/led", HTTP_GET, led_handler, NULL }; httpd_uri_t relay_uri = { "/relay", HTTP_GET, relay_handler, NULL }; httpd_uri_t radar_uri = { "/radar", HTTP_GET, radar_handler, NULL }; httpd_uri_t radardata_uri = { "/radardata", HTTP_GET, radardata_handler, NULL }; httpd_uri_t capture_uri = { "/capture", HTTP_GET, capture_handler, NULL }; if (httpd_start(&control_httpd, &config) == ESP_OK) { httpd_register_uri_handler(control_httpd, &index_uri); httpd_register_uri_handler(control_httpd, &control_uri); httpd_register_uri_handler(control_httpd, &setup_uri); httpd_register_uri_handler(control_httpd, &scan_uri); httpd_register_uri_handler(control_httpd, &connect_uri); httpd_register_uri_handler(control_httpd, &wifistatus_uri); httpd_register_uri_handler(control_httpd, &apoff_uri); httpd_register_uri_handler(control_httpd, &resetwifi_uri); httpd_register_uri_handler(control_httpd, &action_uri); httpd_register_uri_handler(control_httpd, &status_uri); httpd_register_uri_handler(control_httpd, &led_uri); httpd_register_uri_handler(control_httpd, &relay_uri); httpd_register_uri_handler(control_httpd, &radar_uri); httpd_register_uri_handler(control_httpd, &radardata_uri); httpd_register_uri_handler(control_httpd, &capture_uri); } // Stream alada port (81) o alada core (1) e, jate control command block na hoy config.server_port = 81; config.ctrl_port += 1; config.core_id = 1; config.max_open_sockets = 3; // stream reconnect + control httpd_uri_t stream_uri = { "/stream", HTTP_GET, stream_handler, NULL }; if (httpd_start(&stream_httpd, &config) == ESP_OK) { httpd_register_uri_handler(stream_httpd, &stream_uri); } } // ================== SETUP ================== bool initCamera() { camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.pixel_format = PIXFORMAT_JPEG; // Video quality (upore VIDEO_PRESET diye bodlano jay) config.frame_size = CAM_FRAME_SIZE; config.jpeg_quality = CAM_JPEG_QUALITY; config.grab_mode = CAMERA_GRAB_LATEST; if (psramFound()) { config.fb_count = 2; config.fb_location = CAMERA_FB_IN_PSRAM; } else { config.fb_count = 1; config.fb_location = CAMERA_FB_IN_DRAM; } esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init failed: 0x%x\n", err); return false; } return true; } void setup() { #if DISABLE_BROWNOUT WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); #endif // Sobar age motor pin gulo LOW kore dao pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); pinMode(FLASH_LED, OUTPUT); pinMode(STATUS_LED, OUTPUT); stopMotors(); digitalWrite(FLASH_LED, LOW); digitalWrite(STATUS_LED, HIGH); // lal LED off (active LOW) // Boot e flash LED 3 bar blink (LED/pin thik ache kina test) for (int i = 0; i < 3; i++) { digitalWrite(FLASH_LED, HIGH); delay(80); digitalWrite(FLASH_LED, LOW); delay(150); } Serial.begin(115200); delay(300); // power stable hoar somoy dao // Nano er sathe UART (RX buffer boro, jate radar data haray na) NanoLink.setRxBufferSize(1024); NanoLink.begin(NANO_BAUD); if (!initCamera()) { Serial.println("Camera error! Check ribbon cable / power."); } delay(300); // ---- Saved WiFi thakle age oi WiFi te try, na hole / fail hole setup hotspot ---- loadWiFi(); if (savedSsid.length() > 0) { WiFi.mode(WIFI_STA); applyWiFiTuning(); Serial.println(); Serial.print("Connecting to saved WiFi: "); Serial.println(savedSsid); WiFi.begin(savedSsid.c_str(), savedPass.c_str()); unsigned long wifiStart = millis(); while (WiFi.status() != WL_CONNECTED && millis() - wifiStart < WIFI_BOOT_TIMEOUT_MS) { // WiFi khujar somoy lal LED fast blink digitalWrite(STATUS_LED, (millis() / 150) % 2 ? HIGH : LOW); delay(50); } digitalWrite(STATUS_LED, HIGH); Serial.println(); } else { Serial.println("Kono saved WiFi nei."); } if (WiFi.status() == WL_CONNECTED) { Serial.println("WiFi connected!"); Serial.print("ESP32-CAM IP: http://"); Serial.println(WiFi.localIP()); Serial.print("Video stream: http://"); Serial.print(WiFi.localIP()); Serial.println(":81/stream"); } else { Serial.println("Router WiFi pawa jay nai -> setup hotspot start..."); startAP(); } startServers(); } // ================== LOOP ================== void loop() { // 0) Nano theke data poro nanoPoll(); // 1) Obstacle safety: forward cholte thakle obstacle ashle (ba Nano na thakle) stop if (currentDir == D_FORWARD && obstacleDetected()) { stopMotors(); } // 2) Failsafe: command na ashle stop (web heartbeat 200ms er shathe match kore) if (currentDir != D_STOP && millis() - lastCmdTime > MOTOR_FAILSAFE_MS) { stopMotors(); } // 3) Restart request (WiFi Reset) if (restartAt && (long)(millis() - restartAt) >= 0) { Serial.println("Restarting..."); delay(100); ESP.restart(); } // 3b) Flash LED blink mode if (flashMode == 2) { digitalWrite(FLASH_LED, (millis() / 300) % 2 ? HIGH : LOW); } // ================= WiFi manager ================= static bool wasConnected = false; static unsigned long lostSince = 0; static unsigned long lastRetry = 0; static unsigned long lastReconnect = 0; bool now = (WiFi.status() == WL_CONNECTED); // 3c) Pichoner lal LED = loop alive indicator // router connected: 100ms jhilik 2 sec e ekbar | hotspot/no WiFi: fast blink // LED blink bondho hoye gele bujhbe code hang / reset hocche { unsigned long t = millis(); bool on = now ? ((t % 2000) < 100) : ((t % 500) < 250); digitalWrite(STATUS_LED, on ? LOW : HIGH); } // 4) Connect / disconnect event if (now != wasConnected) { wasConnected = now; if (now) { Serial.print("WiFi connected. IP: http://"); Serial.println(WiFi.localIP()); startMDNS(); if (connState == CS_FAIL) connState = CS_IDLE; // auto-connect hole (setup page theke noy) hotspot schedule kore off if (apActive && apOffAt == 0 && connState != CS_CONNECTING) { apOffAt = millis() + (WiFi.softAPgetStationNum() ? AP_KEEP_MS : 10000UL); } } else { lostSince = millis(); Serial.println("WiFi lost."); } } // 5) Setup page theke ashe connect request if (connectRequested) { connectRequested = false; connStart = millis(); Serial.print("Connecting to: "); Serial.println(reqSsid); WiFi.disconnect(false); delay(100); WiFi.begin(reqSsid.c_str(), reqPass.c_str()); } if (connState == CS_CONNECTING) { if (now && WiFi.SSID() == reqSsid) { saveWiFi(reqSsid, reqPass); // success -> save connState = CS_OK; apOffAt = millis() + AP_KEEP_MS; // phone e IP/URL dekhar jonno hotspot kichu khon thakbe Serial.println("WiFi saved."); } else if (millis() - connStart > CONNECT_TIMEOUT_MS) { connState = CS_FAIL; WiFi.disconnect(false); Serial.println("WiFi connect failed."); } } // 6) Setup hotspot off if (apOffAt && (long)(millis() - apOffAt) >= 0) { apOffAt = 0; if (now && apActive) stopAP(); } // 7) Hotspot on thakle + keu connected na thakle saved WiFi te abar try if (apActive && !now && connState != CS_CONNECTING && savedSsid.length() > 0 && WiFi.softAPgetStationNum() == 0 && millis() - lastRetry > AP_RETRY_MS) { lastRetry = millis(); WiFi.begin(savedSsid.c_str(), savedPass.c_str()); } // 8) Router mode e disconnect hole reconnect; onek khon na pele hotspot on if (!apActive && !now) { if (millis() - lastReconnect >= 5000) { lastReconnect = millis(); WiFi.reconnect(); } if (millis() - lostSince > WIFI_LOST_TO_AP_MS) { Serial.println("Router onek khon pawa jachche na -> setup hotspot on."); startAP(); } } delay(2); }