Загрузить параметры подключения к wi-fi с файла
- Войдите на сайт для отправки комментариев
Пт, 08/11/2019 - 17:41
Добрый день! Есть желание создать возможность сохранить настройки подключения в файл, потом при запуску esp их считать. В перспективе будет создана веб страница для редактирования этих данных. Ну возникла проблема, данные считать удалось, ну что-то не хочет подключать. Если параметры прописать в переменных, все отлично подключает. Где я накосячил? Спасибо!
#include "FS.h"
#include <ESP8266WiFi.h>
void setup() {
Serial.begin(115200);
// always use this to "mount" the filesystem
bool result = SPIFFS.begin();
Serial.println("SPIFFS opened: " + result);
// this opens the file "f.txt" in read-mode
File f = SPIFFS.open("/wi-fi.txt", "r");
if (!f) {
Serial.println("File doesn't exist yet. Creating it");
// open the file in write mode
File f = SPIFFS.open("/wi-fi.txt", "w");
if (!f) {
Serial.println("file creation failed");
}
// now write two lines in key/value style with end-of-line characters
f.println("router_it");
f.println("0472454294");
} else {
// we could open the file
String ssid = "";
String pass = "";
while(f.available()) {
//Lets read line by line from the file
String line = f.readStringUntil('\n');
Serial.println(line);
if(ssid == "")
ssid = line;
else
pass = line;
}
//задать вручную, все работает
//ssid = "router_it";
//pass = "0472454294";
// We start by connecting to a WiFi network
Serial.print("Connecting to :");
Serial.println(ssid);
Serial.println(pass);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
f.close();
}
void loop() {
// nothing to do for now, this is just a simple test
}
При запуску:
router_it
0472454294
Connecting to :router_it
0472454294
....................................
сдаётся мне, что ssid = "router_it\r\n", а pass = "0472454294\r\n"
так, зараз попробуем сделать substring
https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/trim/
А не, сорри, вроде этот трим только пробелы удаляет, \r\n оставляет. привык я к trim()-у на высокоуровневых языках, более продвинутому :)
Спасибо! trim() пробывал, не помогло, нужно убрать переход.
Вот рабочая заготовка, когда сделаю веб страничку выложу готовый шаблон.
#include "FS.h" #include <ESP8266WiFi.h> void setup() { Serial.begin(115200); // always use this to "mount" the filesystem bool result = SPIFFS.begin(); Serial.println("SPIFFS opened: " + result); // this opens the file "f.txt" in read-mode File f = SPIFFS.open("/wi-fi.txt", "r"); if (!f) { Serial.println("File doesn't exist yet. Creating it"); // open the file in write mode File f = SPIFFS.open("/wi-fi.txt", "w"); if (!f) { Serial.println("file creation failed"); } // now write two lines in key/value style with end-of-line characters f.println("router_it"); f.println("0472454294"); } else { // we could open the file String ssid = ""; String pass = ""; while(f.available()) { //Lets read line by line from the file String line = f.readStringUntil('\n'); Serial.println(line); if(ssid == "") ssid = line.substring(0,line.length()-1); else pass = line.substring(0,line.length()-1); } // We start by connecting to a WiFi network Serial.print("Connecting to :"); Serial.println(ssid); Serial.println(pass); WiFi.mode(WIFI_STA); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } f.close(); } void loop() { // nothing to do for now, this is just a simple test }При запуску:
Ну, в конце пароля \r то уберите. Что он там делает?
Вот готовый вариант с возможности изменять настройки подключения.
Если в течении 50 сек. не удалось подключится к сети, запускаем точку доступа для настройки, при первом запуске тоже.
Как то так.
#include "FS.h" #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> String ssid = ""; String pass = ""; String html_header = "<html>\ <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\ <head>\ <title>ESP8266 Settings</title>\ <style>\ body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\ </style>\ </head>"; ESP8266WebServer server(80); void setup() { Serial.begin(115200); // always use this to "mount" the filesystem bool result = SPIFFS.begin(); Serial.println("SPIFFS opened: " + result); // this opens the file "f.txt" in read-mode File f = SPIFFS.open("/wi-fi.txt", "r"); if (!f) { start_server();//запускаем настройку подключения } else { while(f.available()) { //Lets read line by line from the file String line = f.readStringUntil('\n'); Serial.println(line); if(ssid == "") ssid = line.substring(0,line.length()-1); else pass = line.substring(0,line.length()-1); } // We start by connecting to a WiFi network Serial.print("Connecting to :"); Serial.println(ssid); Serial.println(pass); WiFi.mode(WIFI_STA); WiFi.begin(ssid, pass); byte stop_connect = 0; while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); stop_connect++; if(stop_connect>100)//что-то не так, запускаем настройку подключения { Serial.println(".no connect"); start_server(); break; } } Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } f.close(); } void loop() { // nothing to do for now, this is just a simple test server.handleClient(); } void handleRoot() { String str = ""; str += html_header; str += "<body>\ <form method=\"POST\" action=\"ok\">\ <input name=\"ssid\"> WIFI Net</br>\ <input name=\"pswd\"> Password</br></br>\ <input type=SUBMIT value=\"Save settings\">\ </form>\ </body>\ </html>"; server.send ( 200, "text/html", str ); } void handleOk(){ String ssid_ap; String pass_ap; String str = ""; str += html_header; str += "<body>"; ssid_ap = server.arg(0); pass_ap = server.arg(1); if(ssid_ap != ""){ Serial.println("File doesn't exist yet. Creating it"); // open the file in write mode File f = SPIFFS.open("/wi-fi.txt", "w"); if (!f) { Serial.println("file creation failed"); } // now write two lines in key/value style with end-of-line characters f.println(ssid_ap); f.println(pass_ap); f.close(); str +="Configuration saved in FLASH</br>\ Changes applied after reboot</p></br></br>\ <a href=\"/\">Return</a> to settings page</br>"; } else { str += "No WIFI Net</br>\ <a href=\"/\">Return</a> to settings page</br>"; } str += "</body></html>"; server.send ( 200, "text/html", str ); } void start_server() { const char *ssid_ap = "ESPap"; WiFi.mode(WIFI_AP); Serial.print("Configuring access point..."); /* You can remove the password parameter if you want the AP to be open. */ WiFi.softAP(ssid_ap); delay(2000); Serial.println("done"); IPAddress myIP = WiFi.softAPIP(); Serial.print("AP IP address: "); Serial.println(myIP); server.on("/", handleRoot); server.on("/ok", handleOk); server.begin(); Serial.println("HTTP server started"); }