#include "smartconfig.h" #include #include WebServer server(80); DNSServer dnsServer; Preferences preferences; IPAddress apIP(192, 168, 4, 1); bool should_reboot = false; bool smartconfig_done = false; const char *HTML_FORM = R"rawliteral( Helios Charge Point 配网

配置 WiFi

)rawliteral"; void handleCaptivePortal() { String host = server.hostHeader(); server.sendHeader("Location", String("http://") + apIP.toString(), true); server.send(302, "text/plain", ""); } void handleRoot() { server.send(200, "text/html", HTML_FORM); } void handleSave() { if (server.hasArg("ssid") && server.hasArg("password")) { String ssid = server.arg("ssid"); String password = server.arg("password"); Serial.printf("Received SSID: %s, PASSWORD: %s\n", ssid.c_str(), password.c_str()); // save to NVS preferences.begin("wifi", false); preferences.putString("ssid", ssid); preferences.putString("password", password); preferences.end(); String response = "

配置已保存,设备正在尝试连接网络...

"; server.send(200, "text/html", response); // flag to reboot should_reboot = true; } else { server.send(400, "text/plain", "缺少 SSID 或密码"); } } void startSmartConfig(char *ssid, char *psk) { WiFi.mode(WIFI_AP); WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); WiFi.softAP(ssid, psk); dnsServer.start(53, "*", apIP); server.on("/", handleRoot); server.on("/save", handleSave); server.on("/generate_204", HTTP_GET, handleCaptivePortal); // Android server.on("/ncsi.txt", HTTP_GET, handleCaptivePortal); // Windows server.on("/hotspot-detect.html", HTTP_GET, handleCaptivePortal); // iOS server.onNotFound(handleCaptivePortal); server.begin(); Serial.println("HTTP server started"); } bool connectToSavedWiFi() { preferences.begin("wifi", true); String ssid = preferences.getString("ssid", ""); String password = preferences.getString("password", ""); preferences.end(); if (ssid == "") { Serial.println("No saved WiFi credentials"); return false; } Serial.printf("Connecting to SSID: %s\n", ssid.c_str()); WiFi.mode(WIFI_STA); WiFi.begin(ssid.c_str(), password.c_str()); unsigned long start = millis(); const unsigned long timeout = 15000; // 15 secs while (WiFi.status() != WL_CONNECTED && millis() - start < timeout) { Serial.print("."); delay(500); } if (WiFi.status() == WL_CONNECTED) { Serial.println("\nWiFi connected!"); Serial.printf("IP address: %s\n", WiFi.localIP().toString().c_str()); smartconfig_done = true; return true; } else { Serial.println("\nWiFi connect failed."); return false; } }