92 lines
2.3 KiB
Plaintext
92 lines
2.3 KiB
Plaintext
#include <WiFi.h>
|
|
#include <WebServer.h>
|
|
#include <EEPROM.h>
|
|
|
|
const char* ap_ssid = "ESP32_Config";
|
|
const char* ap_password = "12345678";
|
|
|
|
WebServer server(80);
|
|
|
|
String ssid = "";
|
|
String password = "";
|
|
String static_ip = "";
|
|
String hostname = "";
|
|
|
|
void setup() {
|
|
Serial.begin(115200);
|
|
EEPROM.begin(512);
|
|
|
|
// Load saved settings
|
|
loadSettings();
|
|
|
|
// If settings are not set, enter AP mode
|
|
if (ssid == "" || password == "") {
|
|
WiFi.softAP(ap_ssid, ap_password);
|
|
Serial.println("AP Mode: Connect to the network and configure settings.");
|
|
server.on("/", handleRoot);
|
|
server.on("/save", handleSave);
|
|
server.begin();
|
|
} else {
|
|
// Connect to WiFi in client mode
|
|
WiFi.mode(WIFI_STA);
|
|
WiFi.config(IPAddress(static_ip.c_str()), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0));
|
|
WiFi.begin(ssid.c_str(), password.c_str());
|
|
WiFi.setHostname(hostname.c_str());
|
|
|
|
while (WiFi.status() != WL_CONNECTED) {
|
|
delay(1000);
|
|
Serial.println("Connecting to WiFi...");
|
|
}
|
|
|
|
Serial.println("Connected to WiFi");
|
|
Serial.print("IP Address: ");
|
|
Serial.println(WiFi.localIP());
|
|
Serial.print("MAC Address: ");
|
|
Serial.println(WiFi.macAddress());
|
|
}
|
|
}
|
|
|
|
void loop() {
|
|
if (WiFi.getMode() == WIFI_AP) {
|
|
server.handleClient();
|
|
}
|
|
}
|
|
|
|
void handleRoot() {
|
|
String html = "<form action='/save' method='POST'>";
|
|
html += "SSID: <input type='text' name='ssid'><br>";
|
|
html += "Password: <input type='text' name='password'><br>";
|
|
html += "Static IP: <input type='text' name='static_ip'><br>";
|
|
html += "Hostname: <input type='text' name='hostname'><br>";
|
|
html += "<input type='submit' value='Save'>";
|
|
html += "</form>";
|
|
server.send(200, "text/html", html);
|
|
}
|
|
|
|
void handleSave() {
|
|
ssid = server.arg("ssid");
|
|
password = server.arg("password");
|
|
static_ip = server.arg("static_ip");
|
|
hostname = server.arg("hostname");
|
|
|
|
saveSettings();
|
|
|
|
server.send(200, "text/html", "Settings saved. Rebooting...");
|
|
delay(2000);
|
|
ESP.restart();
|
|
}
|
|
|
|
void saveSettings() {
|
|
EEPROM.writeString(0, ssid);
|
|
EEPROM.writeString(32, password);
|
|
EEPROM.writeString(64, static_ip);
|
|
EEPROM.writeString(96, hostname);
|
|
EEPROM.commit();
|
|
}
|
|
|
|
void loadSettings() {
|
|
ssid = EEPROM.readString(0);
|
|
password = EEPROM.readString(32);
|
|
static_ip = EEPROM.readString(64);
|
|
hostname = EEPROM.readString(96);
|
|
} |