Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dns #7

Merged
merged 4 commits into from
Oct 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 77 additions & 44 deletions lib/ConfigManager/ConfigManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,16 @@ const char *apPassword = "opencmm1sensor";
const char *ssidKey = "wifi_ssid";
const char *passwordKey = "wifi_password";

boolean scanCompleted = false;
String scanResults = "";

IPAddress local_ip(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

const char *htmlHeader = "<!DOCTYPE html><html><header><meta charset='utf-8' /><title>OpenCMM WiFI Settings</title><style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}</style></header><body>";
const char *htmlFooter = "</body></html>";

void checkWifiInfo()
{
preferences.begin("credentials", false);
Expand Down Expand Up @@ -46,7 +52,6 @@ void startAPServer()
server.on("/", HTTP_GET, handleRoot);
server.on("/connect", HTTP_GET, handleConnect);
server.on("/config", HTTP_POST, handleConfig);

server.begin();
}

Expand All @@ -64,65 +69,56 @@ void connectToWiFi()
// Attempt to connect to Wi-Fi
WiFi.begin(ssid.c_str(), password.c_str());
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED)
{

int i = 0;
while (WiFi.status() != WL_CONNECTED && i++ < 5) {
delay(1000);
Serial.print('.');
}
} else {
Serial.println("No Wi-Fi credentials found.");
}

if (WiFi.status() == WL_CONNECTED) {
Serial.println("Successfully connected to WiFi.");
Serial.println(WiFi.localIP());
}
else
{
Serial.println("No Wi-Fi credentials found.");
} else {
Serial.println("Could not connect to WiFi.");
startAPServer();
}
}

void handleRoot()
{
String html = "<!DOCTYPE html><html><body>";
int n = WiFi.scanNetworks();
Serial.println("Scan done");

if (n == 0)
{
Serial.println("no networks found");
html += "<h2>No Wi-Fi Networks Found</h2>";
html += "<p>Refresh the page to scan again.</p>";
}
else
{
Serial.print(n);
Serial.println(" networks found");
delay(10);
html += "<p>Select SSID</p>";

for (int i = 0; i < n; i++)
{
html += "<p><a href='/connect?ssid=" + WiFi.SSID(i) + "'>" + WiFi.SSID(i) + "</a></p>";
}
String html = htmlHeader;
if (scanCompleted) {
html += scanResults;
scanResults = ""; // Clear the results
scanCompleted = false;
} else {
html += "<h2>Scanning for Wi-Fi Networks...</h2>";
html += "<h2>周辺のWifiの情報を取得しています...</h2>";
}
html += "</body></html>";

Serial.println("");
WiFi.scanDelete();
html += htmlFooter;

Serial.println("Sending Wi-Fi scan results");
server.send(200, "text/html", html);
}

void handleConnect()
{
String ssid = server.arg("ssid");
Serial.println("ssid: " + ssid);
String html = "<!DOCTYPE html><html><body>";
String html = htmlHeader;
html += "<h2>Enter Wi-Fi Credentials</h2>";
html += "<h2>Wi-Fiのパスワードを入力してください</h2>";
html += "<p>SSID: " + ssid + "</p>";
html += "<form method='post' action='/config'>";
html += "<input type='hidden' name='ssid' value='" + ssid + "'>";
html += "Password: <input type='password' name='password'><br>";
html += "<input type='submit' value='Submit'>";
html += "<input type='submit' value='Submit' style='margin-top: 20px;'>";
html += "</form>";
html += "</body></html>";
html += htmlFooter;
server.send(200, "text/html", html);
}

Expand All @@ -131,23 +127,31 @@ void handleConfig()
String ssid = server.arg("ssid");
String password = server.arg("password");

saveWiFiCredentials(ssid, password);
// Send message to client
String message = htmlHeader;
message += "<h2>Connecting to Wi-Fi...</h2>";
message += "<h2>Wi-Fiに接続しています...</h2>";
message += htmlFooter;
server.send(200, "text/html", message);

// Switch to Station mode and connect to the user's Wi-Fi network
WiFi.softAPdisconnect();
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED)
{
int i = 0;
while (WiFi.status() != WL_CONNECTED && i++ < 5) {
delay(1000);
Serial.println("Connecting to WiFi...");
}

Serial.println("Connected to the WiFi network");
server.close();

// Redirect to a success page or any other action you want
server.sendHeader("Location", "/");
server.send(302, "text/plain", "credentials saved");
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Failed to connect to WiFi.");
startAPServer();
return;
} else {
saveWiFiCredentials(ssid, password);
Serial.println("Connected to the WiFi network");
server.close();
}
}

void saveWiFiCredentials(String ssid, String password)
Expand All @@ -168,4 +172,33 @@ bool isIntervalValid(int interval)
bool isThresholdValid(int threshold)
{
return threshold >= 1 && threshold <= 20000;
}

void scanNetworks() {
int n = WiFi.scanNetworks();
Serial.println("n: " + String(n));
if (n <= 0) {
scanResults += "<h2>No Wi-Fi Networks found</h2>";
scanResults += "<h2>Wi-Fiが見つかりませんでした</h2>";
} else {
scanResults += "<h2>Select Wi-Fi Network</h2>";
scanResults += "<h2>Wi-Fiを選択してください</h2>";
for (int i = 0; i < n; i++) {
scanResults += "<p><a href='/connect?ssid=" + WiFi.SSID(i) + "'>" + WiFi.SSID(i) + "</a></p>";
}
}
WiFi.scanDelete();
scanCompleted = true;
}

bool checkIfScanCompleted() {
return scanCompleted;
}

void resetWifiCredentialsWithWs() {
preferences.begin("credentials", false);
preferences.clear();
// disconnect from Wi-Fi
WiFi.disconnect(true);
startAPServer();
}
5 changes: 4 additions & 1 deletion lib/ConfigManager/ConfigManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ void handleConfig();
void handleConnect();
void connectToWiFi();
bool isIntervalValid(int interval);
bool isThresholdValid(int threshold);
bool isThresholdValid(int threshold);
void scanNetworks();
bool checkIfScanCompleted();
void resetWifiCredentialsWithWs();
16 changes: 11 additions & 5 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <WebSocketsServer.h>
#include <ConfigManager.h>
#include <Sensor.h>
#include <ESPmDNS.h>
#include <ArduinoJson.h>

void ledBlink();
Expand All @@ -11,6 +12,7 @@ const int touchPin = 4; // GPIO4 as the touch-sensitive pin
int sensorData = 0;
int interval = 1000; // 1 second
int threshold = 100;
const char* hostname = "opencmm";

WebSocketsServer webSocket(81);

Expand Down Expand Up @@ -67,6 +69,9 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length)
switchSensor(false);
delay(1000);
esp_deep_sleep_start();
} else if (strcmp(command, "resetWifi") == 0) {
Serial.println("Resetting Wi-Fi credentials");
resetWifiCredentialsWithWs();
}
}

Expand All @@ -89,7 +94,7 @@ void setup()
{
Serial.begin(115200);
checkWifiInfo();

MDNS.begin(hostname);
setupSensor();

touchAttachInterrupt(touchPin, touchCallback, 40); // Attach touch interrupt
Expand Down Expand Up @@ -124,11 +129,12 @@ void loop()
webSocket.broadcastTXT(dataStr.c_str(), dataStr.length());
delay(interval);
}
}
else
{
} else {
runServer();
delay(1000);
if (!checkIfScanCompleted()) {
scanNetworks();
}
}
}

Expand All @@ -138,4 +144,4 @@ void ledBlink()
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
}
}