Files
esp8266-laser/esp8266-laser.ino
FrYakaTKoP a7de25a117 added wificonfig
/ssid/ssidname,
 /pwd/password,
 /wiap/0/ -> client /1/ -> SoftAP,
 /saveconf -> write config to file

* write to file worked ssid and pw gets saved but fails to connect may timeout 10s to short?
2017-10-08 03:59:08 +02:00

381 lines
10 KiB
C++

/*
modified by fryakatkop nov2015
FSWebServer - Example WebServer with SPIFFS backend for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the ESP8266WebServer library for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
upload the contents of the data folder with MkSPIFFS Tool ("ESP8266 Sketch Data Upload" in Tools menu in Arduino IDE)
or you can upload the contents of a folder if you CD in that folder and run the following command:
for file in `ls -A1`; do curl -F "file=@$PWD/$file" esp8266fs.local/edit; done
access the sample web page at http://esp8266fs.local *edit* dns will catch all request and response with 302
edit the page by going to http://esp8266fs.local/edit
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <FS.h>
#include <SoftwareSerial.h>
SoftwareSerial laserSerial(14, 12, false, 256);
char ssid[50] = "tojoin";
char password[50] = "";
int wifiMode = 0; // 0: client, 1: AP (default)
int wifiTimeout = 10000; //ms
/* Soft AP network parameters */
char *ssidAP = "ESP-test";
IPAddress apIP(192, 168, 4, 1); // note: update metaRefreshStr string if ip change!
IPAddress netMsk(255, 255, 255, 0);
/* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */
const char *myHostname = "esplaser";
const char *metaRefreshStr = "<head><meta http-equiv=\"refresh\" content=\"3; url=/index.html\" /></head><body><p>redirecting...</p></body>";
unsigned long previousMillis = 0;
// Web server
ESP8266WebServer server(80);
//format bytes
String formatBytes(size_t bytes) {
if (bytes < 1024) {
return String(bytes) + "B";
} else if (bytes < (1024 * 1024)) {
return String(bytes / 1024.0) + "KB";
} else if (bytes < (1024 * 1024 * 1024)) {
return String(bytes / 1024.0 / 1024.0) + "MB";
} else {
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
}
}
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") {
s.substring(5, 6).toInt();
}
s = f.readStringUntil('\n');
if (s.substring(0, 4) == "ssid") {
s.substring(5).toCharArray(ssid, 50);
}
s = f.readStringUntil('\n');
if (s.substring(0, 3) == "pwd") {
s.substring(5).toCharArray(password, 50);
}
f.close();
}
String getContentType(String filename) {
if (server.hasArg("download")) return "application/octet-stream";
else if (filename.endsWith(".htm")) return "text/html";
else if (filename.endsWith(".html")) return "text/html";
else if (filename.endsWith(".ini")) return "text/plain";
else if (filename.endsWith(".css")) return "text/css";
else if (filename.endsWith(".js")) return "application/javascript";
else if (filename.endsWith(".png")) return "image/png";
else if (filename.endsWith(".gif")) return "image/gif";
else if (filename.endsWith(".jpg")) return "image/jpeg";
else if (filename.endsWith(".ico")) return "image/x-icon";
else if (filename.endsWith(".xml")) return "text/xml";
else if (filename.endsWith(".pdf")) return "application/x-pdf";
else if (filename.endsWith(".zip")) return "application/x-zip";
else if (filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain";
}
bool handleFileRead(String path) {
Serial.println("handleFileRead: " + path);
if (path.endsWith("/")) path += "index.html";
String contentType = getContentType(path);
String pathWithGz = path + ".gz";
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) {
if (SPIFFS.exists(pathWithGz))
path += ".gz";
File file = SPIFFS.open(path, "r");
size_t sent = server.streamFile(file, contentType);
file.close();
return true;
}
return false;
}
void handleFileList() {
if (!server.hasArg("dir")) {
server.send(500, "text/plain", "BAD ARGS");
return;
}
String path = server.arg("dir");
Serial.println("handleFileList: " + path);
Dir dir = SPIFFS.openDir(path);
path = String();
String output = "[";
while (dir.next()) {
File entry = dir.openFile("r");
if (output != "[") output += ',';
bool isDir = false;
output += "{\"type\":\"";
output += (isDir) ? "dir" : "file";
output += "\",\"name\":\"";
output += String(entry.name()).substring(1);
output += "\"}";
entry.close();
}
output += "]";
server.send(200, "text/json", output);
}
void handleLaser(String uri)
{
String laserValue = uri.substring(7);
String msg = "AT SLV ";
msg += laserValue;
Serial.println("Sent to Laser: " + msg);
laserSerial.println(msg);
String json = "{ \"handledLaser\":";
json += "{\"value\":\"" + laserValue + "\"}}";
//server.send(200, "text/plain", "blub");
server.send(200, "text/json", json);
json = String();
}
void handleMotor(String uri)
{
String motorNr = uri.substring(7, 8);
String motorValue = uri.substring(9);
String msg = "AT SMS ";
msg += motorNr;
msg += " ";
msg += motorValue;
Serial.println("Sent to Laser: " + msg);
laserSerial.println(msg);
String json = "{ \"handledMotor\": ";
json += "{ \"motor\":\"" + motorNr + "\", ";
json += "\"value\":\"" + motorValue + "\" }}";
//server.send(200, "text/plain", "blub");
server.send(200, "text/json", json);
json = String();
}
void handleSsid(String uri)
{
uri.substring(6).toCharArray(ssid, 50);
String json = "{ \"handledSsid\":";
json += "{\"ssid\":\"" + (String)ssid + "\"}}";
server.send(200, "text/json", json);
json = String();
}
void handlePwd(String uri)
{
uri.substring(5).toCharArray(password, 50);
String json = "{ \"handledPwd\":";
json += "{\"password\":\"" + (String)password + "\"}}";
server.send(200, "text/json", json);
json = String();
}
void handleWiAp(String uri)
{
wifiMode = uri.substring(6, 7).toInt();
String json = "{ \"handledWiAp\":";
json += "{\"softAp\":\"" + (String)wifiMode + "\"}}";
server.send(200, "text/json", json);
json = String();
}
void handleSaveConf() {
boolean success = false;
File f = SPIFFS.open("/config.ini", "w");
if (!f) {
Serial.println("config file open failed");
success = false;
}
else
{
Serial.println("Writing wifi config");
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
{
server.send(500, "text/plain", "error saving file");
}
}
boolean setupWifi() {
// Serial.print("setupWifi");
// Serial.println(wifiMode);
if (wifiMode == 0)
{
Serial.printf("Try connecting to %s\n", ssid);
WiFi.begin(ssid, password);
previousMillis = millis();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if (millis() - previousMillis >= wifiTimeout) {
Serial.println("connection timedout");
return false;
}
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
return true;
}
else if (wifiMode == 1)
{
Serial.printf("Starting SoftAP %s\n", ssidAP);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssidAP);
Serial.println("");
Serial.print("SoftAP started! IP address: ");
Serial.println ( WiFi.softAPIP() );
return true;
}
}
void setup(void) {
laserSerial.begin(9600);
Serial.begin(115200);
Serial.print("\n");
SPIFFS.begin();
{
Dir dir = SPIFFS.openDir("/");
while (dir.next()) {
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
}
Serial.printf("\n");
}
//WIFI INIT
readWifiConfigFile();
boolean wifiConnected = setupWifi();
if (!wifiConnected)
{
wifiMode = 1; // fallback to AP mode
setupWifi();
}
// Setup MDNS responder
if (!MDNS.begin(myHostname)) {
Serial.println("Error setting up MDNS responder!");
} else {
Serial.println("mDNS responder started");
// Add service to MDNS-SD
MDNS.addService("http", "tcp", 80);
}
//SERVER INIT
//list directory
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("/heap", HTTP_GET, []() {
String json = "{";
json += "\"heap\":" + String(ESP.getFreeHeap());
json += "}";
server.send(200, "text/json", json);
json = String();
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void handleNotFound() {
String uri = server.uri();
Serial.print("unhandled uri:");
Serial.println(uri);
if (uri.substring(0, 7) == "/motor/")
{
handleMotor(uri);
return;
}
if (uri.substring(0, 7) == "/laser/")
{
handleLaser(uri);
return;
}
if (uri.substring(0, 6) == "/ssid/")
{
handleSsid(uri);
return;
}
if (uri.substring(0, 5) == "/pwd/")
{
handlePwd(uri);
return;
}
if (uri.substring(0, 6) == "/wiap/")
{
handleWiAp(uri);
return;
}
if (!handleFileRead(server.uri()))
{
server.send(302, "text/html", metaRefreshStr);
// server.send(302, "text/plain", "blub");
}
}
void loop(void) {
server.handleClient();
}