M5-router-2/router+portal.ino

84 lines
2.4 KiB
C++

#include <M5StickCPlus.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
const char *homeSSID = "Home";
const char *homePassword = "Smart@2018";
const char *apSSID = "M5";
const char *apPassword = "123456789";
const char *server = "notify.sadqi.eu.org";
const int port = 80;
AsyncWebServer server(80);
// Hardcoded list of connection codes
const char *validConnectionCodes[] = {"code1", "code2", "code3"};
bool isValidCode(const String &code) {
for (const char *validCode : validConnectionCodes) {
if (code.equals(validCode)) {
return true;
}
}
return false;
}
void connectToHomeWiFi() {
M5.Lcd.println("Connecting to Home WiFi...");
WiFi.begin(homeSSID, homePassword);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(1000);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
M5.Lcd.println("\nConnected to Home WiFi");
} else {
M5.Lcd.println("\nFailed to connect to Home WiFi. Creating Access Point.");
setupAccessPoint();
}
}
void setupAccessPoint() {
M5.Lcd.println("Setting up Access Point...");
WiFi.softAP(apSSID, apPassword);
M5.Lcd.println("Access Point created");
// Set up the captive portal
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
if (request->hasParam("code")) {
String enteredCode = request->getParam("code")->value();
if (isValidCode(enteredCode)) {
request->send(200, "text/html", "<html><body><h1>Connected to Internet!</h1></body></html>");
// Implement the logic to allow internet access for the user here
// E.g., you might use WiFi.begin() with the user's WiFi credentials
} else {
request->send(200, "text/html", "<html><body><h1>Invalid Connection Code</h1></body></html>");
}
} else {
request->send(200, "text/html", "<html><body><h1>Enter Connection Code:</h1><form><input type='text' name='code' placeholder='Connection Code'><br><br><button type='submit'>Connect</button></form></body></html>");
}
});
server.begin();
}
void setup() {
M5.begin();
Serial.begin(115200);
M5.Lcd.println("Booting...");
// Connect to Home WiFi
connectToHomeWiFi();
}
void loop() {
// Your main loop logic goes here
delay(5000); // Wait for 5 seconds before repeating the loop
}