changed http endpoints to more rest like api

This commit is contained in:
fryakatkop
2017-10-26 20:22:30 +02:00
parent 769ec8ef9d
commit 1c9739c5cf
2 changed files with 148 additions and 161 deletions

View File

@@ -1,19 +1,26 @@
# Esp8266-Laser # Esp8266-Laser
Wifi Host for the Arduino-Laser-Spirograph Wifi Host for the Arduino-Laser-Spirograph
HTTP GET endpoints: HTTP endpoints:
/motor/{motorNr}/{value} /spirograph GET returns laser and motor values (0 at startup)
/laser/{value} POST sets new value(s)
/saveconf -> write wificonfig to file laser=1-128 (1:permanent, 2-127 pulse, 128 off)
/resetwifi -> reconnect wifi with the new settings motor1=1-128
/wificonfig -> GET returns wifi settings motor2=1-128
POST sets new wifi settings motor3=1-128
apMode=0: will try to connect to SSID first, 1: will directly start the AP
SSID=ssid
password=password /wificonfig -> GET returns wifi settings
save=true will save config to spiffs POST sets new wifi setting{s}
apply=true will reset wifi and try to connect with new param (buggy atm) apMode=0: will try to connect to SSID first, 1: will directly start the AP
/readvalues -> return laser and motor values (all 0 at startup, ram only) SSID=ssid
password=password
save=true will save config to spiffs, false will only change RAM variable (useful for onetime ap joins)
apply=true will reset wifi and try to connect with new param (buggy atm)
/saveconf -> POST write wificonfig to file (similar to wificonfig->save=true)
/resetwifi -> POST reconnect wifi (similar to wificonfig->apply=true)
/heap -> GET returns free heap of the ESP8266
/files -> GET returns list of files
# Install # Install
- install arduino ide (1.8.5) - install arduino ide (1.8.5)

View File

@@ -1,5 +1,6 @@
/* /*
https://github.com/0x1d/esp8266-laser https://github.com/0x1d/esp8266-laser
0x1d, FrYakaTKoP
*/ */
@@ -16,7 +17,7 @@
*/ */
// Set how long the esp should try to connect to a network before starting it's own AP // Set how long the esp should try to connect to a network before starting it's own AP
int wifiTimeout = 15000; //ms unsigned int wifiTimeout = 15000; //ms
// Hardcoded Soft AP network parameters // Hardcoded Soft AP network parameters
char *ssidAP = "laserAp"; char *ssidAP = "laserAp";
@@ -24,9 +25,9 @@ IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0); IPAddress netMsk(255, 255, 255, 0);
// this is sent to server if invalid request // this is sent to server if invalid request
const char *metaRefreshStr = "<head><meta http-equiv=\"refresh\" content=\"3; url=/index.html\" /></head><body><p>redirecting...</p></body>"; const char *metaRefreshStr = "<head><meta http-equiv=\"refresh\" content=\"2; url=/index.html\" /></head><body><p>redirecting...</p></body>";
/* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */ /* hostname for mDNS. Should work at least on windows. Try http://esplaser.local */
const char *myHostname = "esplaser"; const char *myHostname = "esplaser";
// espsoftwareserial // espsoftwareserial
@@ -43,7 +44,7 @@ String password = "";
int apMode = 1; // default value, will be overwriten with config from file int apMode = 1; // default value, will be overwriten with config from file
int _apMode = 0; // runtime apMode int _apMode = 0; // runtime apMode
// [0] laser[1] m1 [2] m2 [3] m3 // [0] laser, [1] m1, [2] m2, [3] m3
byte lmValues[4] = {0, 0, 0, 0}; byte lmValues[4] = {0, 0, 0, 0};
unsigned long previousMillis = 0; unsigned long previousMillis = 0;
@@ -51,18 +52,20 @@ unsigned long previousMillis = 0;
// Web server // Web server
ESP8266WebServer server(80); ESP8266WebServer server(80);
bool hFileRead(String path) {
//format bytes //Serial.println("handleFileRead: " + path);
String formatBytes(size_t bytes) { if (path.endsWith("/")) path += "index.html";
if (bytes < 1024) { String contentType = getContentType(path);
return String(bytes) + "B"; String pathWithGz = path + ".gz";
} else if (bytes < (1024 * 1024)) { if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) {
return String(bytes / 1024.0) + "KB"; if (SPIFFS.exists(pathWithGz))
} else if (bytes < (1024 * 1024 * 1024)) { path += ".gz";
return String(bytes / 1024.0 / 1024.0) + "MB"; File file = SPIFFS.open(path, "r");
} else { size_t sent = server.streamFile(file, contentType);
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB"; file.close();
return true;
} }
return false;
} }
String getContentType(String filename) { String getContentType(String filename) {
@@ -83,114 +86,83 @@ String getContentType(String filename) {
return "text/plain"; return "text/plain";
} }
bool handleFileRead(String path) { void hFileList() {
Serial.println("handleFileRead: " + path); String responseBuffer = String();
if (path.endsWith("/")) path += "index.html"; StaticJsonBuffer<500> jsonBuffer;
String contentType = getContentType(path); JsonObject& root = jsonBuffer.createObject();
String pathWithGz = path + ".gz"; JsonArray& files = root.createNestedArray("files");
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() { Dir dir = SPIFFS.openDir("/");
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()) { while (dir.next()) {
File entry = dir.openFile("r"); File entry = dir.openFile("r");
if (output != "[") output += ','; files.add(String(entry.name()));
bool isDir = false;
output += "{\"type\":\"";
output += (isDir) ? "dir" : "file";
output += "\",\"name\":\"";
output += String(entry.name()).substring(1);
output += "\"}";
entry.close(); entry.close();
} }
root.prettyPrintTo(responseBuffer);
output += "]"; server.send(200, "text/json", responseBuffer);
server.send(200, "text/json", output); jsonBuffer.clear();
responseBuffer = String();
} }
void handleLaser(String uri) void hReadSpiro()
{ {
String laserValue = uri.substring(7); String responseBuffer = String();
if (laserValue.toInt() > 128) { StaticJsonBuffer<200> jsonBuffer;
lmValues[0] = 128; JsonObject& root = jsonBuffer.createObject();
laserValue = "128"; JsonObject& data = root.createNestedObject("spirograph");
} data["laser"] = (String)lmValues[0];
else data["motor1"] = (String)lmValues[1];
{ data["motor2"] = (String)lmValues[2];
lmValues[0] = laserValue.toInt(); data["motor3"] = (String)lmValues[3];
} root.prettyPrintTo(responseBuffer);
server.send(200, "text/json", responseBuffer);
String msg = "AT SLV "; jsonBuffer.clear();
msg += laserValue; responseBuffer = String();
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) void hWriteSpiro()
{ {
String motorNr = uri.substring(7, 8); String responseBuffer = String();
String motorValue = uri.substring(9); StaticJsonBuffer<200> jsonBuffer;
if (motorValue.toInt() > 128) { JsonObject& root = jsonBuffer.createObject();
lmValues[motorNr.toInt()] = 128; JsonObject& data = root.createNestedObject("wificonfig");
motorValue = "128"; if (server.hasArg("laser") ) {
lmValues[0] = server.arg("laser").toInt();
data["laser"] = (String)lmValues[0];
String msg = "AT SLV ";
msg += (String)lmValues[0];
laserSerial.println(msg);
delay(20);
} }
else if (server.hasArg("motor1") ) {
{ lmValues[1] = server.arg("motor1").toInt();
lmValues[motorNr.toInt()] = motorValue.toInt(); data["motor1"] = (String)lmValues[1];
String msg = "AT SMS 1 ";
msg += (String)lmValues[1];
laserSerial.println(msg);
delay(20);
} }
String msg = "AT SMS "; if (server.hasArg("motor2") ) {
msg += motorNr; lmValues[2] = server.arg("motor2").toInt();
msg += " "; data["motor2"] = (String)lmValues[2];
msg += motorValue; String msg = "AT SMS 2 ";
msg += (String)lmValues[2];
Serial.println("Sent to Laser: " + msg); laserSerial.println(msg);
laserSerial.println(msg); delay(20);
}
String json = "{ \"handledMotor\": "; if (server.hasArg("motor3") ) {
json += "{ \"motor\":\"" + motorNr + "\", "; lmValues[3] = server.arg("motor3").toInt();
json += "\"value\":\"" + motorValue + "\" }}"; data["motor3"] = (String)lmValues[3];
String msg = "AT SMS 3 ";
//server.send(200, "text/plain", "blub"); msg += (String)lmValues[3];
server.send(200, "text/json", json); laserSerial.println(msg);
json = String(); delay(20);
} }
root.prettyPrintTo(responseBuffer);
void handleReadValues() server.send(200, "text/json", responseBuffer);
{ jsonBuffer.clear();
String json = "{ \"handledReadValues\":"; responseBuffer = String();
json += "{\"laser\":\"" + (String)lmValues[0] + "\",";
json += "\"motors\": {\"1\":\"" + (String)lmValues[1] + "\",";
json += "\"2\":\"" + (String)lmValues[2] + "\",";
json += "\"3\":\"" + (String)lmValues[3] + "\"}}}";
server.send(200, "text/json", json);
json = String();
} }
void hReadWifi() void hReadWifi()
@@ -256,8 +228,6 @@ void hWriteWifi()
responseBuffer = String(); responseBuffer = String();
} }
bool saveConfigFile() { bool saveConfigFile() {
StaticJsonBuffer<200> jsonBuffer; StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.createObject(); JsonObject& json = jsonBuffer.createObject();
@@ -267,14 +237,14 @@ bool saveConfigFile() {
File configFile = SPIFFS.open("/wifi.json", "w"); File configFile = SPIFFS.open("/wifi.json", "w");
if (!configFile) { if (!configFile) {
Serial.println("Failed to open config file for writing"); //Serial.println("Failed to open config file for writing");
return false; return false;
} }
json.printTo(configFile); json.printTo(configFile);
return true; return true;
} }
void handleSaveConf() { void hSaveConf() {
bool success = saveConfigFile(); bool success = saveConfigFile();
if (success) if (success)
{ {
@@ -319,12 +289,25 @@ boolean readConfigFile() {
Serial.print("SSID: "); Serial.print("SSID: ");
Serial.println(ssid); Serial.println(ssid);
Serial.print("PW: "); Serial.print("PW: ");
Serial.println(password); Serial.println("***");
//Serial.println(password);
return true; return true;
} }
boolean setupWifi() { void setupWifi()
Serial.print("setupWifi apMode="); {
WiFi.disconnect();
delay(100);
if (!connectWifi())
{
Serial.println("connect failed, start SoftAP");
_apMode = 1; // fallback to AP mode
connectWifi();
}
}
boolean connectWifi() {
Serial.print("connectWifi apMode=");
Serial.println(apMode); Serial.println(apMode);
if (_apMode == 0) if (_apMode == 0)
{ {
@@ -372,14 +355,13 @@ void setup(void) {
// 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\n", fileName.c_str());
// } // }
// Serial.printf("\n"); // Serial.printf("\n");
// } // }
//WIFI INIT
WiFi.disconnect();
delay(100);
if (!readConfigFile()) if (!readConfigFile())
{ {
Serial.println("reading wifi config failed, start SoftAP"); Serial.println("reading wifi config failed, start SoftAP");
@@ -387,12 +369,7 @@ void setup(void) {
} }
delay(100); delay(100);
if (!setupWifi()) setupWifi();
{
Serial.println("connect failed, start SoftAP");
_apMode = 1; // fallback to AP mode
setupWifi();
}
// Setup MDNS responder // Setup MDNS responder
if (!MDNS.begin(myHostname)) { if (!MDNS.begin(myHostname)) {
@@ -406,17 +383,27 @@ void setup(void) {
//SERVER INIT //SERVER INIT
//list directory //list directory
server.on("/listFiles", HTTP_GET, handleFileList); server.on("/files", HTTP_GET, hFileList);
server.on("/saveconf", HTTP_GET, handleSaveConf); server.on("/files", HTTP_POST, []() {
server.on("/resetwifi", HTTP_GET, setupWifi); server.send(400, "text/plain", "400 Bad Request");
});
server.on("/saveconf", HTTP_GET, []() {
server.send(400, "text/plain", "400 Bad Request");
});
server.on("/saveconf", HTTP_POST, hSaveConf);
server.on("/resetwifi", HTTP_GET, []() {
server.send(400, "text/plain", "400 Bad Request");
});
server.on("/resetwifi", HTTP_POST, setupWifi);
server.on("/wificonfig", HTTP_GET, hReadWifi); server.on("/wificonfig", HTTP_GET, hReadWifi);
server.on("/wificonfig", HTTP_POST, hWriteWifi); server.on("/wificonfig", HTTP_POST, hWriteWifi);
// server.on("/wificonfig", HTTP_POST, []() {
// hWriteWifi();
// });
server.on("/readvalues", HTTP_GET, handleReadValues);
server.on("/spirograph", HTTP_GET, hReadSpiro);
server.on("/spirograph", HTTP_POST, hWriteSpiro);
server.on("/heap", HTTP_GET, []() { server.on("/heap", HTTP_GET, []() {
String json = "{"; String json = "{";
json += "\"heap\":" + String(ESP.getFreeHeap()); json += "\"heap\":" + String(ESP.getFreeHeap());
@@ -424,6 +411,9 @@ void setup(void) {
server.send(200, "text/json", json); server.send(200, "text/json", json);
json = String(); json = String();
}); });
server.on("/heap", HTTP_POST, []() {
server.send(400, "text/plain", "400 Bad Request");
});
server.onNotFound(handleNotFound); server.onNotFound(handleNotFound);
server.begin(); server.begin();
Serial.println("HTTP server started"); Serial.println("HTTP server started");
@@ -431,24 +421,14 @@ void setup(void) {
void handleNotFound() { void handleNotFound() {
String uri = server.uri(); String uri = server.uri();
Serial.print("unhandled uri:"); //Serial.print("unhandled uri:");
Serial.println(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, 12) == "/wifi.json") if (uri.substring(0, 12) == "/wifi.json")
{ {
server.send(403, "text/plain", "Forbidden"); server.send(403, "text/plain", "Forbidden");
return; return;
} }
if (!handleFileRead(server.uri())) if (!hFileRead(server.uri()))
{ {
server.send(404, "text/html", metaRefreshStr); server.send(404, "text/html", metaRefreshStr);
// server.send(302, "text/plain", "blub"); // server.send(302, "text/plain", "blub");