ESP32 writeStringEEPROM adds unwanted nembers when I use the letter '&' - arduino

I am trying to use this code:
https://github.com/jatocode/WifiConnect/blob/master/WifiConnect/WifiConnect.ino with my ESP32.
The problem is that my wifi network name is "y&t" and when I am trying to use it the progrem saves to the EEPROM "y&26t" insted, with other networks names in my area it dosn't have a problem.
I will be greatful if somebady knows how to solve this problem.

Thanks to #Juraj I solved the problem.
I used in this code a decoder from here: https://circuits4you.com/2019/03/21/esp8266-url-encode-decode-example/
/*
Configuration AP example
The example shows a very simple Configuration Access Point.
created in August 2019
by Juraj Andrassy https://github.com/jandrassy
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <Arduino.h>
// #include <String.h>
String urldecode(String str);
unsigned char h2int(char c);
void setup() {
Serial.begin(115200);
delay(500);
// WiFi.disconnect(); // forget the persistent connection to test the Configuration AP
WiFi.persistent(true);
// waiting for connection to remembered Wifi network
Serial.println("Waiting for connection to WiFi");
WiFi.begin(); // use SSID and password stored by SDK
WiFi.waitForConnectResult();
if (WiFi.status() != WL_CONNECTED) {
Serial.println();
Serial.println("Could not connect to WiFi. Starting configuration AP...");
configAP();
} else {
Serial.println("WiFi connected");
}
}
void loop() {
}
void configAP() {
WiFiServer configWebServer(80);
WiFi.mode(WIFI_AP_STA); // starts the default AP (factory default or setup as persistent)
Serial.print("Connect your computer to the WiFi network ");
// Serial.print(WiFi.softAP());
Serial.println();
IPAddress ip = WiFi.softAPIP();
Serial.print("and enter http://");
Serial.print(ip);
Serial.println(" in a Web browser");
configWebServer.begin();
while (true) {
WiFiClient client = configWebServer.available();
if (client) {
char line[64];
int l = client.readBytesUntil('\n', line, sizeof(line));
line[l] = 0;
client.find((char*) "\r\n\r\n");
if (strncmp_P(line, PSTR("POST"), strlen("POST")) == 0) {
l = client.readBytes(line, sizeof(line));
line[l] = 0;
// parse the parameters sent by the html form
const char* delims = "=&";
strtok(line, delims);
const char* ssid = strtok(NULL, delims);
strtok(NULL, delims);
const char* pass = strtok(NULL, delims);
// decoding the ssid and the password for ASCII characters
String ssidS = String(ssid);
String ssidSdecode= urldecode(ssidS);
ssid=const_cast<char*>(ssidSdecode.c_str());
String passS = String(pass);
String passSdecode= urldecode(passS);
pass=const_cast<char*>(passSdecode.c_str());
// send a response before attemting to connect to the WiFi network
// because it will reset the SoftAP and disconnect the client station
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Connection: close"));
client.println(F("Refresh: 10")); // send a request after 10 seconds
client.println();
client.println(F("<html><body><h3>Configuration AP</h3><br>connecting...</body></html>"));
client.stop();
Serial.println();
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
WiFi.waitForConnectResult();
// configuration continues with the next request
} else {
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Connection: close"));
client.println();
client.println(F("<html><body><h3>Configuration AP</h3><br>"));
int status = WiFi.status();
if (status == WL_CONNECTED) {
client.println(F("Connection successful. Ending AP."));
} else {
client.println(F("<form action='/' method='POST'>WiFi connection failed. Enter valid parameters, please.<br><br>"));
client.println(F("SSID:<br><input type='text' name='i'><br>"));
client.println(F("Password:<br><input type='password' name='p'><br><br>"));
client.println(F("<input type='submit' value='Submit'></form>"));
}
client.println(F("</body></html>"));
client.stop();
if (status == WL_CONNECTED) {
delay(1000); // to let the SDK finish the communication
Serial.println("Connection successful. Ending AP.");
configWebServer.stop();
WiFi.mode(WIFI_STA);
}
}
}
}
}
String urldecode(String str) {
String encodedString="";
char c;
char code0;
char code1;
for (int i =0; i < str.length(); i++) {
c=str.charAt(i);
if (c == '+') {
encodedString+=' ';
} else if (c == '%') {
i++;
code0=str.charAt(i);
i++;
code1=str.charAt(i);
c = (h2int(code0) << 4) | h2int(code1);
encodedString+=c;
} else {
encodedString+=c;
}
yield();
}
return encodedString;
}
unsigned char h2int(char c) {
if (c >= '0' && c <='9') {
return((unsigned char)c - '0');
}
if (c >= 'a' && c <='f') {
return((unsigned char)c - 'a' + 10);
}
if (c >= 'A' && c <='F') {
return((unsigned char)c - 'A' + 10);
}
return(0);
}

Related

ESP8266 Wifi configuration

I had a Node MCU module as shown in the photo.
My nodemcu
I had this tutorial from this link:Tutorial link
I had a problem with WIFI Configuring which from the code I had online it should be working with the browser 192.168.4.1 as shown as below. But with my LoLin NodeMCU V3 I cant reach to the browser page and always show the connection has timed out. Can I know is it my NodeMCU module problem?
p.s.
The wifi connection work well with hardcoding but not WIFI configuration)
The Module i found there is slightly different from normal Nodemcu with a yellow component on it.
I used ARDUINO IDE to compile and upload.
proper result with the browser for wifi configuration
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
//Variables
int i = 0;
int statusCode;
const char* ssid = "Default_SSID";
const char* passphrase = "Default_Password";
String st;
String content;
//Function Decalration
bool testWifi(void);
void launchWeb(void);
void setupAP(void);
//Establishing Local server at port 80 whenever required
ESP8266WebServer server(80);
void setup()
{
Serial.begin(115200); //Initialising if(DEBUG)Serial Monitor
Serial.println();
Serial.println("Disconnecting current wifi connection");
WiFi.disconnect();
EEPROM.begin(512); //Initialasing EEPROM
delay(10);
pinMode(LED_BUILTIN, OUTPUT);
Serial.println();
Serial.println();
Serial.println("Startup");
//---------------------------------------- Read eeprom for ssid and pass
Serial.println("Reading EEPROM ssid");
String esid;
for (int i = 0; i < 32; ++i)
{
esid += char(EEPROM.read(i));
}
Serial.println();
Serial.print("SSID: ");
Serial.println(esid);
Serial.println("Reading EEPROM pass");
String epass = "";
for (int i = 32; i < 96; ++i)
{
epass += char(EEPROM.read(i));
}
Serial.print("PASS: ");
Serial.println(epass);
WiFi.begin(esid.c_str(), epass.c_str());
if (testWifi())
{
Serial.println("Succesfully Connected!!!");
return;
}
else
{
Serial.println("Turning the HotSpot On");
launchWeb();
setupAP();// Setup HotSpot
}
Serial.println();
Serial.println("Waiting.");
while ((WiFi.status() != WL_CONNECTED))
{
Serial.print(".");
delay(100);
server.handleClient();
}
}
void loop() {
if ((WiFi.status() == WL_CONNECTED))
{
for (int i = 0; i < 10; i++)
{
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}
}
else
{
}
}
//----------------------------------------------- Fuctions used for WiFi credentials saving and connecting to it which you do not need to change
bool testWifi(void)
{
int c = 0;
Serial.println("Waiting for Wifi to connect");
while ( c < 20 ) {
if (WiFi.status() == WL_CONNECTED)
{
return true;
}
delay(500);
Serial.print("*");
c++;
}
Serial.println("");
Serial.println("Connect timed out, opening AP");
return false;
}
void launchWeb()
{
Serial.println("");
if (WiFi.status() == WL_CONNECTED)
Serial.println("WiFi connected");
Serial.print("Local IP: ");
Serial.println(WiFi.localIP());
Serial.print("SoftAP IP: ");
Serial.println(WiFi.softAPIP());
createWebServer();
// Start the server
server.begin();
Serial.println("Server started");
}
void setupAP(void)
{
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0)
Serial.println("no networks found");
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
delay(10);
}
}
Serial.println("");
st = "<ol>";
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
st += "<li>";
st += WiFi.SSID(i);
st += " (";
st += WiFi.RSSI(i);
st += ")";
st += (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*";
st += "</li>";
}
st += "</ol>";
delay(100);
WiFi.softAP("ElectronicsInnovation", "");
Serial.println("Initializing_softap_for_wifi credentials_modification");
launchWeb();
Serial.println("over");
}
void createWebServer()
{
{
server.on("/", []() {
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
content = "<!DOCTYPE HTML>\r\n<html>Welcome to Wifi Credentials Update page";
content += "<form action=\"/scan\" method=\"POST\"><input type=\"submit\" value=\"scan\"></form>";
content += ipStr;
content += "<p>";
content += st;
content += "</p><form method='get' action='setting'><label>SSID: </label><input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
content += "</html>";
server.send(200, "text/html", content);
});
server.on("/scan", []() {
//setupAP();
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
content = "<!DOCTYPE HTML>\r\n<html>go back";
server.send(200, "text/html", content);
});
server.on("/setting", []() {
String qsid = server.arg("ssid");
String qpass = server.arg("pass");
if (qsid.length() > 0 && qpass.length() > 0) {
Serial.println("clearing eeprom");
for (int i = 0; i < 96; ++i) {
EEPROM.write(i, 0);
}
Serial.println(qsid);
Serial.println("");
Serial.println(qpass);
Serial.println("");
Serial.println("writing eeprom ssid:");
for (int i = 0; i < qsid.length(); ++i)
{
EEPROM.write(i, qsid[i]);
Serial.print("Wrote: ");
Serial.println(qsid[i]);
}
Serial.println("writing eeprom pass:");
for (int i = 0; i < qpass.length(); ++i)
{
EEPROM.write(32 + i, qpass[i]);
Serial.print("Wrote: ");
Serial.println(qpass[i]);
}
EEPROM.commit();
content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
statusCode = 200;
ESP.reset();
} else {
content = "{\"Error\":\"404 not found\"}";
statusCode = 404;
Serial.println("Sending 404");
}
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(statusCode, "application/json", content);
});
}
}
I had tried several times with the code provided online but same results came out with the browser couldnt work.
Be sure to first connect to AP ElectronnicsInnovation and type "http://192.168.4.1" in browser address.
(https - by default - don't works).
I try your code on esp8266 and it works fine.

ESP8266 HTTP client connection falis

This demo code is working fine but mine does not.
It returns "HTTPC_ERROR_CONNECTION_REFUSED" (my debug work suggests that it fails to create a TCP connection)
The example code uses WiFiMulti but that is not the issue.
What am I missing ?
Please kindly assist.
Working Example:
/**
* BasicHTTPClient.ino
*
* Created on: 24.05.2015
*
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial
ESP8266WiFiMulti WiFiMulti;
void setup() {
USE_SERIAL.begin(115200);
// USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFi.mode(WIFI_STA);
WiFiMulti.addAP("SSID", "PASSWORD");
}
void loop() {
// wait for WiFi connection
if((WiFiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
USE_SERIAL.print("[HTTP] begin...\n");
// configure traged server and url
//http.begin("https://192.168.1.12/test.html", "7a 9c f4 db 40 d3 62 5a 6e 21 bc 5c cc 66 c8 3e a1 45 59 38"); //HTTPS
http.begin("http://192.168.1.12/test.html"); //HTTP
USE_SERIAL.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(10000);
}
My code:
#include <string>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
//EEPROM
#include <EEPROM.h>
//Serial
#include <SoftwareSerial.h> // We need this even if we're not using a SoftwareSerial object
#include <SerialCommand.h>
//Timer
#include <Ticker.h>
//***************************************************
#include "generalDeclerations.h"
#include "serialSetup.h"
#include "EEPROMAnything.h"
#include "ioControl.h"
#include "webServer.h"
//***************************************************
void setup() {
Serial.begin(115200);
EEPROM.begin(100);
initIO();
checkFD(); //Factory default ?
initSerialSetup(); //Initelize serial setup interface
bootPause(); //give the user a chance to interupt using the serial interface
//***************************** Starting the flow from here
// loadEEPROM();
initConnection();
initWebServer();
ledControl(HB_LED_PIN, 0.5);
regData.attach(REG_DATA_INTERVAL, regData2DB);
}
void loop() {
webServer.handleClient();
SCmd.readSerial(); // We don't do much, just process serial commands
// collectData();
// regData();
if ( (wifiMode == WIFI_AP) && (millis() - apTimeStamp > WIFI_RETRY_TIME_MILI_SECONDS)) {
initConnection();
apTimeStamp = millis();
}
}
void regData2DB() {
if (wifiMode != WIFI_STA) {
Serial.println("no internet connection");
return;
}
if (WiFi.status() != WL_CONNECTED ) return;
// http.begin(msg); //HTTP
http.begin("http://google.com"); //HTTP
int httpCode = http.GET();
Serial.println(httpCode);
// http.returnError(httpCode);
// httpCode will be negative on error
if (httpCode > 0) {
Serial.print("got respond");
// HTTP header has been send and Server response header has been handled
// file found at server
if (httpCode == HTTP_CODE_OK) {
Serial.println("and it is a GOOD one !");
String payload = http.getString();
if (http.getString() == "ok") {
Serial.println(counter_in);
Serial.println(counter_out);
counter_in = 0;
counter_out = 0;
}
}
} else {
Serial.println("and it is a BAD one !");
Serial.println(counter_in);
Serial.println(counter_out);
// ledControl(WIFI_LED_PIN, 0.1); //need to return the toggle rate once ok
}
http.end();
}
void initConnection() {
loadEEPROM();
WiFi.disconnect(true); //disconect from any activity ==> Fresh Start
delay(3000);
if (strcmp(eeprom.ssid, "") == 0) {
//No SSID stored.. init as access point
Serial.println("No SSID found in eeprom Starting AP mode:");
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_SSID, AP_PASS);
delay(5000);
Serial.print(WiFi.softAPIP());
apTimeStamp = millis();
wifiMode = WIFI_AP;
ledControl(WIFI_LED_PIN, 0.5);
} else {
Serial.print("Found SSID and PASS in eeprom, trying STA connect to: "); Serial.print(eeprom.ssid); Serial.print(" | "); Serial.println(eeprom.pass);
WiFi.mode(WIFI_STA);
WiFi.begin(eeprom.ssid, eeprom.pass);
delay(6000);
int i = 0;
while (WiFi.status() != WL_CONNECTED) {
Serial.print("Failed ==>");
if (i > 3) {
Serial.println("Starting AP mode:");
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_SSID, AP_PASS);
apTimeStamp = millis();
wifiMode = WIFI_AP;
ledControl(WIFI_LED_PIN, 0.5);
return;
}
else {
Serial.println("Retrying..");
WiFi.mode(WIFI_STA);
WiFi.begin(eeprom.ssid, eeprom.pass);
delay(5000);
}
i++;
}
wifiMode = WIFI_STA;
Serial.print("Connected as STA:");
Serial.println(WiFi.localIP());
WiFi.setAutoReconnect(true);
ledControl(WIFI_LED_PIN, HIGH);
}
}
SOLVED.
I was calling the regData2DB() function by using timer...
When I called the regData2DB() function from main loop by using:
if ( (millis() - regDataTimeStamp) > DB_UPDATE_INTERVAL_MS) {
regData2DB();
regDataTimeStamp = millis();
}
It started to work.
No Idea what happened but it seems to be stable.. moving on :-)

ESP8266 Using wifimanager with onSoftAPModeProbeRequestReceived

I would like to use https://github.com/tzapu/WiFiManager in conjunction with onSoftAPModeProbeRequestReceived. The end goal is to config the wifi with WifiMaager then "switch over" and send probe request information via the wifi.
I get this to work without wifi manager using the following
#include <ESP8266httpUpdate.h>
#include <ESP8266WiFi.h>
#include <esp8266httpclient.h>
#include <stdio.h>
const char* ssid = "someap"; // The SSID (name) of the Wi-Fi
network you want to connect to
const char* password = ""; // The password of the Wi-Fi network
int status = WL_IDLE_STATUS;
String macAddr = "";
WiFiEventHandler probeRequestPrintHandler;
WiFiEventHandler probeRequestBlinkHandler;
bool blinkFlag;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("Starting");
WiFi.persistent(false);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password);
probeRequestPrintHandler =
WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint);
probeRequestBlinkHandler =
WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestBlink);
while ( status != 3)
{
Serial.print("Attempting to connect to network, SSID: ");
Serial.println(ssid);
status = WiFi.status();
WiFi.begin(ssid, password);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(WiFi.localIP());
}
void onProbeRequestPrint(const WiFiEventSoftAPModeProbeRequestReceived& evt)
{
if (macAddr != macToString(evt.mac))
{
macAddr = macToString(evt.mac);
Serial.print("Probe request from: ");
Serial.print(macToString(evt.mac));
Serial.print(" RSSI: ");
Serial.println(evt.rssi);
}
}
void onProbeRequestBlink(const WiFiEventSoftAPModeProbeRequestReceived&) {
blinkFlag = true;
}
void loop() {
if (blinkFlag) {
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://requestbin.fullcontact.com/110f1ss6a1?test=true");
//Specify request destination
int httpCode = http.GET();
Serial.println(httpCode);
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
}
http.end(); //Close connection
macAddr="";
blinkFlag = false;
digitalWrite(LED_BUILTIN, LOW);
delay(100);
digitalWrite(LED_BUILTIN, HIGH);
status = 0;
}
delay(1000);
}
String macToString(const unsigned char* mac) {
char buf[20];
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(buf);
}
When the connection is established we rely on WiFiEventHandler probeRequestPrintHandler; and WiFiEventHandler probeRequestBlinkHandler; This does work and does collect the mac address, how ever it can not connect to the AP. Do I need to close the current wifi mode open the connection then close it?
Seems all I needed to do is add WiFi.begin(); before void loop()

ESP8266 EEPROM or FLASH Error: Succesfully connecting to Wifi with false credentials

I am building a small sensor based on the ESP8266. For setting up wifi I host a small webserver, where the user can enter the credentials.
In the setup routine I load the credentials and try to connect to wifi. If the connection fails, the esp creates an AP and the user can enter new credentials.
I got some strange behaviour. Because when I remove the credentials, the esp nevertheless connects successfully to the wifi. But the 'serial.print()' don't show any credentials.
Maybe its a problem with the EEPROM or FLASH I have no idea. I could reproduce this behaviour on several ESPs.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
ESP8266WebServer server(80);
const char *soft_ap_ssid = "Connect Sensor to MCU";
const char *soft_ap_password = "MySensor";
char ssid[32] = "";
char password[32] = "";
bool wifi_status;
void setup()
{
Serial.begin(115200);
Serial.println();
delay(10);
load_credentials();
wifi_status = setup_wifi(5);
if (!wifi_status)
{
setup_soft_ap();
setup_server();
}
}
void loop()
{
if (!wifi_status)
{
server.handleClient();
}
else
{
Serial.println("Doing Sensor stuff");
delay(2000);
// Remove exsting credentials
for( int i = 0; i < sizeof(ssid); i++ ){
ssid[i] = (char)0;
password[i] = (char)0;
}
save_credentials();
}
}
/*
############## Gernerische Code ########### TODO LIB
*/
bool setup_wifi(int timeout)
{
int timeout_ctr = 0;
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password); //Connect to the WiFi network
while ((WiFi.status() != WL_CONNECTED) && (timeout_ctr < timeout))
{
delay(500);
Serial.println("...");
timeout_ctr++;
}
if (WiFi.status())
{
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //Print the local IP
}
else
{
Serial.println("Connection to MCU failed, setting up AP.");
}
return (WiFi.status() == WL_CONNECTED);
}
void setup_soft_ap()
{
Serial.println();
Serial.println("Creating WiFi AP...");
WiFi.softAP(soft_ap_ssid, soft_ap_password);
Serial.print("AP \"");
Serial.print(soft_ap_ssid);
Serial.println("\" is online.");
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
Serial.println();
}
void setup_server()
{
server.on("/", handle_root); //Associate the landingpage function to the path
server.on("/submit", handle_submit); //Associate the handler function to the path
server.begin(); //Start the server
Serial.println("Server listening");
}
void handle_root()
{
const char *landingpage = "<html><head> <title>ESP8266 Demo</title> <style></style></head><body> <h1>Sensor einrichten</h1> <p> Eingabe der Wifi Daten </p><form action='/submit' method='post'> <input type='text' name='ssid' placeholder='Wifi SSID'> <input type='text' name='pw' placeholder='Wifi Password'> <input type='submit' value='Submit'> </form></body></html>";
server.send(200, "text/html", landingpage);
}
void handle_submit()
{
if (server.args() > 0)
{
Serial.println("POST:");
Serial.println(server.arg("ssid"));
Serial.println(server.arg("pw"));
server.arg("ssid").toCharArray(ssid, sizeof(ssid) - 1);
server.arg("pw").toCharArray(password, sizeof(password) - 1);
Serial.println("credentials:");
Serial.println(ssid);
Serial.println(password);
save_credentials();
}
server.sendHeader("Location", String("/"), true);
server.send(302, "text/plain", "");
}
void load_credentials()
{
EEPROM.begin(512);
EEPROM.get(0, ssid);
EEPROM.get(0 + sizeof(ssid), password);
char ok[2 + 1];
EEPROM.get(0 + sizeof(ssid) + sizeof(password), ok);
EEPROM.end();
if (String(ok) != String("OK"))
{
ssid[0] = 0;
password[0] = 0;
}
Serial.println("Recovered credentials:");
Serial.println(ssid);
Serial.println(password);
}
/** Store WLAN credentials to EEPROM */
void save_credentials()
{
EEPROM.begin(512);
EEPROM.put(0, ssid);
EEPROM.put(0 + sizeof(ssid), password);
char ok[2 + 1] = "OK";
EEPROM.put(0 + sizeof(ssid) + sizeof(password), ok);
EEPROM.commit();
EEPROM.end();
}
By default, the ESP8266 Arduino SDK saves its wifi configuration in flash memory.
This is documented but not called out clearly.
You'll need to call Wifi.persistent() to get the ESP to not save the credentials. This doesn't seem to be called out clearly in a lot of ESP Arduino Core writeups that I've seen.
Try this:
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.persistent(false);
WiFi.begin(ssid, password); //Connect to the WiFi network
while ((WiFi.status() != WL_CONNECTED) && (timeout_ctr < timeout))
You'll probably want to write a bad set of credentials to flash before you update your code to tell the SDK to stop saving them, otherwise I think it will keep using the last saved set. The alternative is to wipe the sector of flash on your ESP where the credentials are stored, which is a lot more work.
There's some documentation on WiFi.persistent() here - which appears to be incorrect - I believe this call operates the way I described (passing false just doesn't store the credentials at all).
If your project is going to be restarting frequently (like going in and out of deep sleep often) I'd definitely use WiFi.persistent(false) to avoid wear on the flash.

Validating the return of an HTTP GET request with arduino IDE and nodemcu-esp-12e

Using the Arduino IDE with the Nodemcu-esp12e module, I created a program which makes an HTTP GET request.
However, I do not know how it would be the right way to deal with the return of this consultation.
I am validating the return with the 'indexOf' function to find out if the return is false/off or true/on.
This is the correct way to validate the return?
Any suggestions for how to improve this code?
#include <ESP8266WiFi.h>
const char* ssid = "mywifiid";
const char* password = "mypassword";
IPAddress host(192,168,0,11);
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
//
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
//
Serial.print("connecting to ");
Serial.println(host);
//
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
else{
Serial.println("connection success");
}
//
String get = "http://localhost/Test/GetStatusSensor?idsensor=2";
Serial.println(get);
//
client.print("GET " + get + "\r\nHTTP/1.1\r\nHost: localhost\Test\r\nConnection: keep-alive\r\n\r\n");
//
while(client.available()){
String line = client.readStringUntil('\r');
//
int iret= line.indexOf('on');
//
Serial.print(line);
Serial.println(String(iret));
//
if (iret> 0) {
//
Serial.println("On");
}
else {
Serial.println("Off");
}
}
//
Serial.println();
Serial.println("closing connection");
delay(20000); // 20 sec
}
My suggestion is to use JSON to switch to more structured way of comm. You can define custom data names and types and easily cover them. Take a look it at :
https://github.com/bblanchon/ArduinoJson
Here some JSON example from the HTTPClient example :
DynamicJsonBuffer jsonBuffer(BUFFER_SIZE);
JsonObject& root = jsonBuffer.parseObject(client);
if (!root.success()) {
Serial.println("JSON parsing failed!");
return false;
}
// Here were copy the strings we're interested in
strcpy(userData->name, root["name"]);
strcpy(userData->company, root["company"]["name"]);

Resources