I want to attach the i value in the <a href= that will add a unique id to each button so that i can use a get or post.
#include <ESP8266WiFi.h>
#include <RTCVars.h>
WiFiServer server(80);
RTCVars state; // create the state object
int reset_counter;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
String header;
const int wwwDelay = 100;
const int networkScanDelay = 2000;
unsigned long wwwPreviousTime = 0;
unsigned long NSDpreviousTime = 0;
void setup() {
Serial.begin (115200);
Serial.println();
state.registerVar( &reset_counter ); // we send a pointer to each of our variables
if (state.loadFromRTC()) { // we load the values from rtc memory back into the registered variables
reset_counter++;
Serial.println("This is reset no. " + (String)reset_counter);
state.saveToRTC(); // since we changed a state relevant variable, we store the new values
} else {
reset_counter = 0;
state.saveToRTC();
}
Serial.println("hello");
server.begin();
if (reset_counter == 0 ) {
APmode();
} else {
stationMode();
}
}
void APmode() {
const String saId = "garbageProject";
WiFi.mode(WIFI_AP);
WiFi.softAP(saId);
}
void stationMode() {
const char* ssid = "*******";
const char* password = "*******";
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - wwwPreviousTime >= wwwDelay) {
www();
wwwPreviousTime = millis();
}
if (currentTime - NSDpreviousTime >= networkScanDelay) {
networkScan();
Serial.print("Number of resets: ");
Serial.println(reset_counter);
NSDpreviousTime = millis();
}
}
void networkScan() {
int i = 0;
int numSSID = WiFi.scanNetworks();
while ( i < numSSID) {
String scannedSSID = (WiFi.SSID(i));
unsigned int SSIDlength = scannedSSID.length();
if (SSIDlength > 10) {
scannedSSID.remove(10);
}
Serial.print(i + 1);
Serial.print(" ");
Serial.print(scannedSSID);
Serial.print("\t Encryption: ");
printEncryptionType(WiFi.encryptionType(i));
if ( i + 1 == numSSID) {
Serial.println();
}
i++;
}
}
void printEncryptionType(int thisType) {
// read the encryption type and print out the name:
switch (thisType) {
case ENC_TYPE_WEP:
Serial.println("WEP");
break;
case ENC_TYPE_TKIP:
Serial.println("WPA");
break;
case ENC_TYPE_CCMP:
Serial.println("WPA2");
break;
case ENC_TYPE_NONE:
Serial.println("None");
break;
case ENC_TYPE_AUTO:
Serial.println("Auto");
break;
}
}
void www() {
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String ssidSelected;
String currentLine = ""; // make a String to hold incoming data from the client
currentTime = millis();
previousTime = currentTime;
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
if (header.indexOf("GET /5/on") >= 0) { //handle the button pressed needs to be changed to generate like the html script does. see line 68.
ssidSelected = "on";
Serial.println("test ");
Serial.print(ssidSelected);
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color:#4095c6; border-radius: 12px; color: white; padding: 16px 40px;transition-duration: 0.4s;}");
client.println(".button:hover{background-color:#AED6F1;}");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP8266 Web Server</h1>");
int i = 0;
String enc;
int numSSID = WiFi.scanNetworks();
while ( i < numSSID) {
String scannedSSID = (WiFi.SSID(i));
unsigned int SSIDlength = scannedSSID.length();
if (SSIDlength > 10) {
scannedSSID.remove(10);
}
char encryption = (WiFi.encryptionType(i));
switch (encryption) {
case ENC_TYPE_WEP:
enc = ("Encryption WEP");
break;
case ENC_TYPE_TKIP:
enc = ("Encryption TKIP");
break;
case ENC_TYPE_CCMP:
enc = ("Encryption WPA2");
break;
case ENC_TYPE_NONE:
enc = ("Encryption none");
break;
}
client.print("<p><a href=\"/5/on\"><button class=\"button\">" + scannedSSID + " " + enc + "</button></a></p>");
i++;
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.flush();
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Fixed it. Thanks for the pointer I'm still learning how to code.
here is the relatively finished product.
#include <ESP8266WiFi.h>
#include <RTCVars.h>
#include <EEPROM.h>
WiFiServer server(80);
RTCVars state; // create the state object
int reset_counter;
int addr_ssid = 0;
int addr_password = 32; // password index
int eepromSize = 512;
const int wwwDelay = 100;
unsigned long wwwPreviousTime = 0;
String ssidSelected;
String WiFiPassword;
String ssid;
String password;
unsigned long previousResetTime = 0;
const int resetTiming = 1000;
unsigned long wwwStatusPreviousTime = 0;
void setup() {
Serial.begin (115200);
Serial.println();
EEPROM.begin(512);
for (int k = addr_ssid; k < addr_ssid + 32; ++k) { //get SSID from memory
ssid += char(EEPROM.read(k));
}
for (int k = addr_password; k < addr_password + 32; ++k) { //get password from memeory
password += char(EEPROM.read(k));
}
Serial.print("this is the value for ssid: ");
Serial.println(ssid);
Serial.print("this is the value for password: ");
Serial.println(password);
//SSID and Password eraser
state.registerVar( &reset_counter); // we send a pointer to each of our variables
if (state.loadFromRTC()) { // we load the values from rtc memory back into the registered variables
reset_counter++;
previousResetTime = millis(); //attached to reset timer below
Serial.println("This is reset no. " + (String)reset_counter);
state.saveToRTC(); // since we changed a state relevant variable, we store the new values
} else {
reset_counter = 0;
state.saveToRTC(); //value passed to reset timer
}
unsigned long currentTime = millis();
if (currentTime - previousResetTime <= resetTiming) { //if the reset button is pressed more than once inside 1 second
for (int i = 0; i < 64; EEPROM.write(i++, 0)); //erase whatever is stored in the 0-64 address range
EEPROM.commit();
}
delay(100);
Serial.println("hello");
server.begin();
int ssidVal = ssid.length();
// int passVal = password.length(); might be useful for somethig else.
if (ssid == 0 ) {
APmode();
} else {
stationMode();
}
}
void APmode() {
const String saId = "garbageProject";
const String pass = "gp123456789";
WiFi.mode(WIFI_AP);
WiFi.softAP( saId, pass);
Serial.println("WiFi access point started.");
}
void stationMode() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - wwwPreviousTime >= wwwDelay) {
www();
wwwPreviousTime = millis();
}
if (currentTime - wwwStatusPreviousTime >= 10000) {
Serial.println("Webserver running");
wwwStatusPreviousTime = millis();
}
}
/********* webserver code provided
Rui Santos
Complete project details at https://randomnerdtutorials.com
*********/
void www() {
// Variable to store the HTTP request
String header;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
currentTime = millis();
previousTime = currentTime;
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
client.println("HTTP/1.1 200 OK"); // and a content-type so the client knows what's coming, then a blank line:
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
String ssidHeader = (header); //redundant veriable for ease of understanding
String passwordWorker = header; //redundant veriable for ease of understanding
int HTTPindex = ssidHeader.indexOf("HTTP");
String scannedSSID;
int numSSID = WiFi.scanNetworks();
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color:#4095c6; border-radius: 12px; color: white; padding: 16px 40px;transition-duration: 0.4s;}");
client.println(".button:hover{background-color:#AED6F1;}");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}</style></head>");
if (HTTPindex == 6) { //if the header has other than intial GET
client.println("<body><h1>ESP8266 Web Server</h1>"); // Web Page Heading
for (int i = 0; i < numSSID; i++) {
String scannedSSID = (WiFi.SSID(i));
client.print("<p><a href='" + scannedSSID + "'><button class=\"button\">" + scannedSSID + "</button></a></p>");
}
}
int passwordIndex = ssidHeader.indexOf("?"); //See if a password was attached to header
if (passwordIndex == -1) { //if there is no password
ssidHeader.remove(0, 5); //remove GET /
unsigned int L = ssidHeader.length(); //get lenght after trimming beginning.
int HTTPindex = ssidHeader.indexOf("HTTP"); //find first instance of HTTP
ssidHeader.remove(HTTPindex - 1, L); //remove from the space before H in HTTP to end of string
ssidSelected = ssidHeader; //whats left of the header is the SSID
Serial.println("");
Serial.print("Write WiFi SSID at address "); Serial.println(addr_ssid);
Serial.print("");
for (int i = 0; i < ssidSelected.length(); ++i) {
EEPROM.write(addr_ssid + i, ssidSelected[i]);
Serial.print(ssidSelected[i]); Serial.print("");
}
}
unsigned int rt = ssidSelected.length(); //if an SSID is set then display password web page
if (rt >= 1) {
client.println("<body><h1>ESP8266 Web erver</h1>");
client.println("<body><h1>WiFi Password</h1>");
client.println("<title>ESP Input Form </title>");
client.println("<form>");
client.println("<input type=\"text\" name=\"WiFiPassword\">");
client.println("<input type=\"submit\"value=\"Submit\">");
client.println("</form><br>");
client.println("</body></html>");
}
if (passwordIndex >= 0) {
int pwIndex = passwordWorker.indexOf("="); //count header string to the first oinstance of =
passwordWorker.remove(0, pwIndex + 1); //remove from beginning of string to and including =
unsigned int L = passwordWorker.length(); //get the current length of the string
int HTTPindex = passwordWorker.indexOf("HTTP"); //find first instance of HTTP
passwordWorker.remove(HTTPindex - 1, L); //remove from the space before H in HTTP to end of string
WiFiPassword = passwordWorker; //whats left in header is the wifi password
Serial.println("");
Serial.print("Write WiFi Password at address ");
Serial.println(addr_password);
Serial.print("");
for (int j = 0; j < WiFiPassword.length(); j++)
{
EEPROM.write(addr_password + j, WiFiPassword[j]);
Serial.print(WiFiPassword[j]); Serial.print("");
}
}
Serial.println("");
if (EEPROM.commit()) {
Serial.println("Data successfully committed");
} else {
Serial.println("ERROR! Data commit failed");
}
client.println("</body></html>"); //The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = " ";
// Close the connection
client.flush();
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
Serial.print("ssid is: ");
Serial.println(ssidSelected);
Serial.print("wifi pass word is: ");
Serial.println(WiFiPassword);
}
}
two hints:
don't use HTTP/1.1 without the http header field "content-length".
if you don't know the length of your payload, use HTTP/1.0
As we know now that you are using an esp8266:
on an esp8266 ... don't build the HTTP on your own. Use the ESP8266HTTPClient, which will make the things easier for your.
See the example ESP8266HTTPClient | BasicHttpclient as start!
Thank you for the hints. I am going to start digging into that. If you want to follow the code here’s the link to GitHub https://github.com/XRC5/apToStationMode
If not I will repost here when I think I’m done.
... in Arduino IDE just looked at Examples/DNSServer/CaptivePortalAdvanced and it does all this crap. Guess I'm done with this project. Good learning experience though.