Backend working

This commit is contained in:
FrYakaTKoP
2017-10-08 22:03:11 +02:00
parent 2e97d83740
commit 924caf8a72
3 changed files with 116 additions and 134 deletions

View File

@@ -1,6 +1,15 @@
# Esp8266-Laser # Esp8266-Laser
Wifi Host for the Arduino-Laser-Spirograph Wifi Host for the Arduino-Laser-Spirograph
#usage:
/motor/{motorNr}/{value}
/laser/{value}
/ssid/{ssidname}
/pwd/{password}
/apmode/1 -> SofAP (default), 0 -> client
/saveconf -> write wificonfig to file
/resetwifi -> reconnect wifi with the new settings (this will work)
#install #install
- install arduino ide (1.8.5) - install arduino ide (1.8.5)
@@ -9,13 +18,17 @@ Wifi Host for the Arduino-Laser-Spirograph
- clone/exctract repo to sketchbook - clone/exctract repo to sketchbook
- install this libary - install this libaries
https://github.com/plerup/espsoftwareserial https://github.com/plerup/espsoftwareserial
https://github.com/bblanchon/ArduinoJson/
- follow this instruction: - follow this instruction:
set wifi parameters in data/config.json before upload
http://esp8266.github.io/Arduino/versions/2.0.0/doc/filesystem.html#uploading-files-to-file-system http://esp8266.github.io/Arduino/versions/2.0.0/doc/filesystem.html#uploading-files-to-file-system
You may also need to: You may also need to:
- get and install driver for nodemcu - get and install driver for nodemcu
https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers

5
data/config.json Normal file
View File

@@ -0,0 +1,5 @@
{
"apMode": 0,
"SSID": "",
"Password": ""
}

View File

@@ -1,30 +1,24 @@
/* /*
https://github.com/0x1d/esp8266-laser https://github.com/0x1d/esp8266-laser
#usage:
/motor/{motorNr}/{value}
/laser/{value}
/ssid/{ssidname}
/pwd/{password}
/wiap/1 -> SofAP, 0 -> client
/saveconf -> will write wificonfig to file
*/ */
#include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
#include <WiFiClient.h> #include <WiFiClient.h>
#include <ESP8266WebServer.h> #include <ESP8266WebServer.h>
#include <ESP8266mDNS.h> #include <ESP8266mDNS.h>
#include <FS.h> #include <FS.h>
#include <SoftwareSerial.h> #include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial laserSerial(14, 12, false, 256); SoftwareSerial laserSerial(14, 12, false, 256);
String ssid2 = "XTZ-72315";
String password2 = "dgzv-6erv-bbbb-bbbb";
String ssid = ""; String ssid = "";
String password = ""; String password = "";
int wifiMode = 0; // 0: client, 1: AP (default) int apMode = 1; // 0: client, 1: AP (default) // will be overwriten
int wifiTimeout = 20000; //ms int apModeRuntime = 0;
int wifiTimeout = 10000; //ms
/* Soft AP network parameters */ /* Soft AP network parameters */
char *ssidAP = "laserAp"; char *ssidAP = "laserAp";
@@ -55,42 +49,6 @@ String formatBytes(size_t bytes) {
} }
} }
boolean writeWifiConfigFile() {
}
void readWifiConfigFile() {
File f = SPIFFS.open("/config.ini", "r");
if (!f) {
Serial.println("config file open failed");
}
Serial.println("Reading wifi config");
String s = f.readStringUntil('\n');
if (s.substring(0, 4) == "mode") {
wifiMode = s.substring(5, 6).toInt();
Serial.print("wifiMode=");
Serial.print(wifiMode);
Serial.println(";");
}
s = f.readStringUntil('\n');
if (s.substring(0, 4) == "ssid") {
ssid = String();
ssid = s.substring(5);
Serial.print("ssid=");
Serial.print(ssid);
Serial.println(";");
}
s = f.readStringUntil('\n');
if (s.substring(0, 3) == "pwd") {
password = String();
password = s.substring(4);
Serial.print("password=");
Serial.print(password);
Serial.println(";");
}
f.close();
}
String getContentType(String filename) { String getContentType(String filename) {
if (server.hasArg("download")) return "application/octet-stream"; if (server.hasArg("download")) return "application/octet-stream";
else if (filename.endsWith(".htm")) return "text/html"; else if (filename.endsWith(".htm")) return "text/html";
@@ -210,37 +168,37 @@ void handlePwd(String uri)
server.send(200, "text/json", json); server.send(200, "text/json", json);
json = String(); json = String();
} }
void handleWiAp(String uri) void handleApmode(String uri)
{ {
wifiMode = uri.substring(6, 7).toInt(); apMode = uri.substring(8, 9).toInt();
String json = "{ \"handledWiAp\":"; apModeRuntime = apMode;
json += "{\"softAp\":\"" + (String)wifiMode + "\"}}"; String json = "{ \"handledApmode\":";
json += "{\"apMode\":\"" + (String)apMode + "\"}}";
server.send(200, "text/json", json); server.send(200, "text/json", json);
json = String(); json = String();
} }
bool saveConfigFile() {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["apMode"] = apMode;
json["SSID"] = ssid;
json["Password"] = password;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("Failed to open config file for writing");
return false;
}
json.printTo(configFile);
return true;
}
void handleSaveConf() { void handleSaveConf() {
boolean success = false; bool success = saveConfigFile();
File f = SPIFFS.open("/config.ini", "w"); if (success)
if (!f) {
Serial.println("config file open failed");
success = false;
}
else
{ {
Serial.println("Writing wifi config"); server.send(200, "text/plain", "saved config to file,<br> reset or /resetwifi to apply settings");
f.print("mode:");
f.println(wifiMode);
f.print("ssid:");
f.println(ssid);
f.print("pwd:");
f.println(password);
f.close();
success = true;
}
if (success == true)
{
server.send(200, "text/plain", "saved config to file, reset to apply");
} }
else else
{ {
@@ -248,22 +206,58 @@ void handleSaveConf() {
} }
} }
boolean readConfigFile() {
Serial.println("Reading config.json");
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
Serial.println("Failed to open config file");
return false;
}
size_t size = configFile.size();
if (size > 1024) {
Serial.println("Config file size is too large");
return false;
}
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
if (!json.success()) {
Serial.println("Failed to parse config file");
return false;
}
apMode = json["apMode"];
apModeRuntime = apMode;
const char* tSsid = json["SSID"];
const char* tPwd = json["Password"];
ssid = tSsid;
password = tPwd;
Serial.print("SSID: ");
Serial.println(ssid);
Serial.print("PW: ");
Serial.println(password);
return true;
}
boolean setupWifi() { boolean setupWifi() {
Serial.print("setupWifi mode="); Serial.print("setupWifi apMode=");
Serial.println(wifiMode); Serial.println(apModeRuntime);
if (wifiMode == 0) if (apModeRuntime == 0)
{ {
Serial.print("Connecting to "); Serial.print("Connecting to ");
Serial.println(ssid); Serial.println(ssid);
WiFi.mode(WIFI_STA); WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password2.c_str()); WiFi.begin(ssid.c_str(), password.c_str());
previousMillis = millis(); previousMillis = millis();
while (WiFi.status() != WL_CONNECTED) { while (WiFi.status() != WL_CONNECTED) {
delay(500); delay(500);
Serial.print("."); Serial.print(".");
Serial.print(WiFi.status());
if (millis() - previousMillis >= wifiTimeout) { if (millis() - previousMillis >= wifiTimeout) {
Serial.println(""); Serial.println("");
Serial.println("connection timedout"); Serial.println("connection timedout");
@@ -276,7 +270,7 @@ boolean setupWifi() {
Serial.println(WiFi.localIP()); Serial.println(WiFi.localIP());
return true; return true;
} }
else if (wifiMode == 1) else
{ {
Serial.printf("Starting SoftAP %s\n", ssidAP); Serial.printf("Starting SoftAP %s\n", ssidAP);
WiFi.mode(WIFI_AP); WiFi.mode(WIFI_AP);
@@ -292,62 +286,30 @@ void setup(void) {
Serial.begin(115200); Serial.begin(115200);
Serial.print("\n"); Serial.print("\n");
SPIFFS.begin(); SPIFFS.begin();
{ // {
Dir dir = SPIFFS.openDir("/"); // Dir dir = SPIFFS.openDir("/");
while (dir.next()) { // while (dir.next()) {
String fileName = dir.fileName(); // String fileName = dir.fileName();
size_t fileSize = dir.fileSize(); // size_t fileSize = dir.fileSize();
Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str()); // Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
} // }
Serial.printf("\n"); // Serial.printf("\n");
} // }
//WIFI INIT //WIFI INIT
WiFi.disconnect(); WiFi.disconnect();
delay(100); delay(100);
readWifiConfigFile(); if (!readConfigFile())
{
Serial.println("reading wifi config failed, start SoftAP");
apModeRuntime = 1;
}
delay(100); delay(100);
delay(100); if (!setupWifi())
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0)
Serial.println("no networks found");
else
{ {
// Serial.print(n); Serial.println("connect failed, start SoftAP");
// Serial.println(" networks found"); apModeRuntime = 1; // fallback to AP mode
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);
if (WiFi.SSID(i) == ssid) {
Serial.println("found ssid");
}
else if (WiFi.SSID(i) == ssid.c_str()) {
Serial.println("found ssid.c_str");
}
else if (WiFi.SSID(i) == ssid2) {
Serial.println("found ssid2");
}
else if (WiFi.SSID(i) == ssid2.c_str()) {
Serial.println("found ssid2.c_str()");
}
}
}
boolean wifiConnected = setupWifi();
if (!wifiConnected)
{
Serial.println("set wifiMode=1");
wifiMode = 1; // fallback to AP mode
setupWifi(); setupWifi();
} }
@@ -364,10 +326,8 @@ void setup(void) {
//SERVER INIT //SERVER INIT
//list directory //list directory
server.on("/listFiles", HTTP_GET, handleFileList); server.on("/listFiles", HTTP_GET, handleFileList);
//server.on("/wwc", HTTP_GET, writeWifiConfigFile);
//server.on("/rwc", HTTP_GET, readWifiConfigFile);
server.on("/saveconf", HTTP_GET, handleSaveConf); server.on("/saveconf", HTTP_GET, handleSaveConf);
server.on("/sw", HTTP_GET, setupWifi); server.on("/resetwifi", HTTP_GET, setupWifi);
server.on("/heap", HTTP_GET, []() { server.on("/heap", HTTP_GET, []() {
String json = "{"; String json = "{";
json += "\"heap\":" + String(ESP.getFreeHeap()); json += "\"heap\":" + String(ESP.getFreeHeap());
@@ -396,7 +356,6 @@ void handleNotFound() {
} }
if (uri.substring(0, 6) == "/ssid/") if (uri.substring(0, 6) == "/ssid/")
{ {
handleSsid(uri); handleSsid(uri);
return; return;
} }
@@ -405,9 +364,14 @@ void handleNotFound() {
handlePwd(uri); handlePwd(uri);
return; return;
} }
if (uri.substring(0, 6) == "/wiap/") if (uri.substring(0, 8) == "/apmode/")
{ {
handleWiAp(uri); handleApmode(uri);
return;
}
if (uri.substring(0,12) == "/config.json")
{
server.send(403, "text/plain", "Forbidden");
return; return;
} }
if (!handleFileRead(server.uri())) if (!handleFileRead(server.uri()))