OctoCube/src/netman.h

270 lines
8.8 KiB
C
Raw Normal View History

2024-11-05 11:18:36 +00:00
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <Adafruit_SSD1306.h>
#include <LittleFS.h>
#include <DNSServer.h>
#include <map>
// Constants for the HTML pages and config file
2024-11-05 12:05:31 +00:00
static const String beginHtml = "<!DOCTYPE html><html lang='en'><head><title>SmartCube Configure</title><style>body{font-family:Arial,sans-serif;background-color:#f4f4f9;color:#333;display:flex;align-items:center;justify-content:center;height:100vh;margin:0}.container{width:300px;padding:20px;background:#fff;border-radius:10px;box-shadow:0 4px 8px rgba(0,0,0,0.2)}h2{margin-top:0;text-align:center;color:#0073e6}label{display:block;margin-bottom:5px;font-weight:bold}input[type='text'],input[type='password']{width:100%;padding:8px;margin-bottom:15px;border:1px solid #ccc;border-radius:4px}button{width:100%;padding:10px;background-color:#0073e6;color:white;border:none;border-radius:4px;cursor:pointer;font-size:16px}button:hover{background-color:#005bb5}table{width:100%;margin-top:20px}td{padding:5px;text-align:left}</style></head><body><div class='container'><h2>Configure AP</h2><table><tbody><tr><td><label for='ssid'>SSID</label></td><td><input id='ssid' type='text' placeholder='Enter SSID'/></td></tr><tr><td><label for='pass'>Password</label></td><td><input id='pass' type='password' placeholder='Enter Password'/></td></tr><tr><td colspan='2'><button onclick=\"location.href = '/add?ssid=' + encodeURIComponent(document.getElementById('ssid').value) + '&pass=' + encodeURIComponent(document.getElementById('pass').value);\">Add Network</button></td></tr></tbody></table><br/><table><tbody>";
2024-11-05 11:18:36 +00:00
static const String endHtml = "</tbody></table></body></html>";
static const String configFile = "/netman";
// Timeout for WiFi connection attempts
static const unsigned long connectionTimeout = 15000; // 15 seconds
struct netman {
public:
netman(Adafruit_SSD1306& display);
netman(String ssid, String pass, bool hidden, Adafruit_SSD1306& display);
bool start();
void reset();
void addSsid(String ssid, String password);
void removeSsid(String ssid, String password);
private:
Adafruit_SSD1306& display;
std::unique_ptr<ESP8266WebServer> server;
std::map<String, String> _ssids;
String _ssid, _pass;
bool _hidden;
void init(String ssid, String pass, bool hidden);
bool tryConnectToSsid(const char* ssid, const char* pass);
bool tryConnect();
void createAP();
bool redirectToIp();
void readConfig();
void writeConfig();
void handleRoot();
void handleAdd();
void handleRemove();
};
// Initialization
void netman::init(String ssid, String pass, bool hidden) {
// Ensure password meets minimum length
if (pass != "" && pass.length() < 8) {
2024-11-05 11:54:36 +00:00
display.clearDisplay();
display.setCursor(0, 0);
display.println("Password too short");
display.display();
pass = "8characters";
2024-11-05 11:18:36 +00:00
}
// Set default SSID if none provided
2024-11-05 11:54:36 +00:00
_ssid = ssid.isEmpty() ? "SmartCube_" + String(ESP.getChipId()) : ssid;
2024-11-05 11:18:36 +00:00
_pass = pass;
_hidden = hidden;
// Initialize LittleFS with error handling
if (!LittleFS.begin()) {
2024-11-05 11:54:36 +00:00
display.clearDisplay();
display.setCursor(0, 0);
display.println("FS init failed");
display.display();
2024-11-05 11:18:36 +00:00
}
}
// Constructors
netman::netman(Adafruit_SSD1306& display) : display(display) {
init("", "", false);
}
netman::netman(String ssid, String pass, bool hidden, Adafruit_SSD1306& display) : display(display) {
init(ssid, pass, hidden);
}
// Attempt to start and connect or create AP
bool netman::start() {
if (_pass == "8characters") {
2024-11-05 11:54:36 +00:00
display.clearDisplay();
display.setCursor(0, 0);
display.println("Using default pass:");
display.println("8characters");
display.display();
2024-11-05 11:18:36 +00:00
}
return tryConnect() || (createAP(), false);
}
// Attempt connection to each saved SSID in order
bool netman::tryConnect() {
readConfig();
2024-11-05 11:54:36 +00:00
display.clearDisplay();
display.setCursor(0, 0);
display.println("Connecting to wifi");
display.display();
2024-11-05 11:18:36 +00:00
for (auto const& item : _ssids) {
if (tryConnectToSsid(item.first.c_str(), item.second.c_str())) {
return true;
}
}
return false;
}
2024-11-05 12:13:32 +00:00
// Attempt to connect to a specific SSID with timeout, dot animation, and IP display
2024-11-05 11:18:36 +00:00
bool netman::tryConnectToSsid(const char* ssid, const char* pass) {
WiFi.begin(ssid, pass);
unsigned long start = millis();
2024-11-05 12:13:32 +00:00
2024-11-05 12:05:31 +00:00
// Clear display and set initial message
display.clearDisplay();
display.setCursor(0, 0);
display.println("Connecting to SSID:");
display.println(String(ssid));
display.display();
int dotCount = 0;
2024-11-05 11:18:36 +00:00
while (millis() - start < connectionTimeout) {
delay(500);
2024-11-05 12:05:31 +00:00
// Check WiFi connection status
2024-11-05 11:18:36 +00:00
if (WiFi.status() == WL_CONNECTED) {
2024-11-05 12:13:32 +00:00
// Success message with IP address
2024-11-05 12:05:31 +00:00
display.clearDisplay();
display.setCursor(0, 0);
2024-11-05 11:18:36 +00:00
display.println("Connected!");
2024-11-05 12:13:32 +00:00
display.setCursor(0, 10);
display.print("IP: ");
display.println(WiFi.localIP());
2024-11-05 12:05:31 +00:00
display.display();
2024-11-05 11:18:36 +00:00
return true;
}
2024-11-05 12:05:31 +00:00
// Animate by adding dots up to three, then reset
display.setCursor(0, 20);
for (int i = 0; i < dotCount; i++) {
display.print(".");
}
display.display();
2024-11-05 12:13:32 +00:00
dotCount = (dotCount + 1);
2024-11-05 11:18:36 +00:00
}
2024-11-05 12:05:31 +00:00
// Connection failed
display.clearDisplay();
display.setCursor(0, 0);
2024-11-05 11:18:36 +00:00
display.println("Connection failed.");
2024-11-05 12:05:31 +00:00
display.display();
2024-11-05 11:18:36 +00:00
WiFi.disconnect();
return false;
}
// Setup Access Point with DNS and HTTP server
void netman::createAP() {
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_AP);
WiFi.softAP(_ssid.c_str(), _pass.c_str(), 1, _hidden);
2024-11-05 11:54:36 +00:00
display.clearDisplay();
display.setCursor(0, 0);
display.println("AccessPoint created");
display.println("SSID:");
display.println(_ssid.c_str());
display.println("IP:");
display.println(WiFi.softAPIP().toString());
display.display();
2024-11-05 11:18:36 +00:00
server.reset(new ESP8266WebServer(80));
DNSServer dnsServer;
dnsServer.start(53, "*", WiFi.softAPIP());
server->on("/", std::bind(&netman::handleRoot, this));
server->on("/add", std::bind(&netman::handleAdd, this));
server->on("/remove", std::bind(&netman::handleRemove, this));
server->begin();
while (true) {
dnsServer.processNextRequest();
server->handleClient();
delay(10);
}
}
// Redirect to AP IP if not accessed directly
bool netman::redirectToIp() {
if (server->hostHeader() == WiFi.softAPIP().toString()) {
return false;
}
server->sendHeader("Location", "http://" + WiFi.softAPIP().toString(), true);
server->send(302, "text/plain", "");
server->client().stop();
return true;
}
// Add SSID to config and save
void netman::addSsid(String ssid, String password) {
_ssids[ssid] = password;
writeConfig();
}
// Remove SSID from config
void netman::removeSsid(String ssid, String password) {
if (_ssids.count(ssid) && _ssids[ssid] == password) {
_ssids.erase(ssid);
writeConfig();
}
}
// Handle file-based config loading
void netman::readConfig() {
_ssids.clear();
File file = LittleFS.open(configFile, "r");
if (!file) {
2024-11-05 11:54:36 +00:00
display.clearDisplay();
display.setCursor(0, 0);
display.println("Config not found");
display.display();
2024-11-05 11:18:36 +00:00
return;
}
while (file.available()) {
String ssid = file.readStringUntil('\n');
ssid.trim();
String pass = file.readStringUntil('\n');
pass.trim();
_ssids[ssid] = pass;
}
file.close();
}
// Handle file-based config saving
void netman::writeConfig() {
File file = LittleFS.open(configFile, "w");
for (const auto& item : _ssids) {
file.println(item.first);
file.println(item.second);
}
file.close();
}
// Reset configuration
void netman::reset() {
LittleFS.remove(configFile);
_ssids.clear();
}
// Web handlers for adding/removing SSIDs
void netman::handleRoot() {
if (redirectToIp()) return;
String result = beginHtml;
for (const auto& item : _ssids) {
result += "<tr><td><button onclick=\"location.href='/remove?ssid=' + escape('" + item.first + "') + '&pass=' + escape('" + item.second + "') \">&times;</button></td><td>" + item.first + "</td><td>-</td><td>" + item.second + "</td></tr>";
}
result += endHtml;
server->send(200, "text/html", result);
}
void netman::handleAdd() {
server->send(200, "text/html", "The ESP will now reboot.");
addSsid(server->arg("ssid"), server->arg("pass"));
delay(500);
ESP.restart();
}
void netman::handleRemove() {
removeSsid(server->arg("ssid"), server->arg("pass"));
handleRoot();
}