semi working

- will create AP "esptest" and http listen on 192.168.4.1:80
 - only motor/nr/value and laser/value are implemented now
This commit is contained in:
FrYakaTKoP
2017-10-08 00:16:50 +02:00
parent 81871b0965
commit 0104ec6874
3 changed files with 154 additions and 364 deletions

View File

@@ -2,142 +2,25 @@
<html> <html>
<head> <head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Esp8266 - FsWebserver</title> <title>Esp8266 laserspiro controller</title>
<link rel="stylesheet" type="text/css" href="style.css"> <link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript"> <script type="text/javascript">
function sendReq(arg)
//var ledGpNames = [5, 4, 13, 12, 14, 16]; // 4 & 5 flipped on my board dirty hack here
function updateLeds(initial, cb)
{ {
var nocache = "&nocache=" + Math.random() *10001; var nocache = "?n=" + Math.random() * 100234;
//var uri = "json.json"; arg = arg + nocache;
var uri = "leds"; var uriDiv = document.getElementById("uriDiv");
uriDiv.innerHTML = arg;
if(!initial) {
uri += "?LED=" + cb.value + "&state=" + (Number(cb.checked)) + nocache;
}
else
{
uri += "?" + nocache;
}
console.log(uri);
var xh = new XMLHttpRequest();
xh.onreadystatechange = function(){
//if (xh.readyState == 4){
//if(xh.status == 200) {
// if (this.responseText != null) {
var res = JSON.parse(xh.responseText);
var ledDiv;
if(initial)
{
var ledInput;
var ledLabel;
var ledBarDiv = document.getElementById("ledBar");
var clearAllMacroBtn = document.createElement("a");
clearAllMacroBtn.setAttribute("class", "ledMacroButton");
clearAllMacroBtn.setAttribute("href", "javascript:handleLedMarco(\"clearAll\")");
clearAllMacroBtn.innerHTML = "Clear All Leds";
}
for (var i = 0; i < res.leds.length; i++) {
var ledPin = res.leds[i][i][0];
var ledState = res.leds[i][i][1];
var ledName = "LED" + ledPin;
if(initial)
{
ledDiv = "";
ledInput = "";
ledLabel = "";
ledDiv = document.createElement("div");
ledDiv.setAttribute("class", "ledDiv");
ledBarDiv.appendChild(ledDiv);
ledInput = document.createElement("input");
ledInput.type = "checkbox";
ledInput.value = (Number(ledPin));
ledInput.setAttribute("id", ledName);
ledInput.setAttribute("name", ledName);
ledInput.setAttribute("onClick", "updateLeds(false, this)");
ledDiv.appendChild(ledInput);
ledLabel = document.createElement("label");
ledLabel.setAttribute("for", ledName);
ledLabel.innerHTML = ledPin;
ledDiv.appendChild(ledLabel);
}
var ledElement = document.getElementsByName(ledName)[0];
if(res.leds[i][i][1] === "1")
{
ledElement.checked = true;
}
else
{
ledElement.checked = false;
}
// }
if(initial)
{
ledBarDiv.appendChild(clearAllMacroBtn);
}
for (var i = 0; i < res.leds.length; i++) {
}
//}
//}
}
};
xh.overrideMimeType("text/json");
//console.log(uri);
xh.open("GET", uri, true);
xh.send(null);
};
function clearAll() {
};
function run(){
if(!running){
running = true;
updateLeds()();
}
}
function dec2bin(dec){
dec = parseInt(dec, 10)
return (dec >>> 0).toString(2);
}
function fillLedBar() {
updateLeds();
}
function handleLedMarco(arg)
{
arg = "/" + arg;
console.log("uri: " + arg );
var xh = new XMLHttpRequest(); var xh = new XMLHttpRequest();
xh.onreadystatechange = function(){ xh.onreadystatechange = function(){
if (xh.readyState == 4){ if (xh.readyState == 4){
if(xh.status == 200) { if(xh.status == 200) {
if (this.responseText != null) { if (this.responseText != null) {
var res = JSON.parse(xh.responseText); var res = JSON.parse(xh.responseText);
for (var i = 0; i < res.leds.length; i++) { var responseDiv = document.getElementById("responseDiv");
var ledName = "LED" + i; responseDiv.innerHTML = JSON.stringify(res, null, 1);
var ledElement = document.getElementsByName(ledName)[0];
if(res.leds[i] === "1")
{
ledElement.checked = true;
}
else
{
ledElement.checked = false;
}
}
} }
console.log("res: " + res);
} }
} }
}; };
@@ -146,20 +29,14 @@
xh.open("GET", arg, true); xh.open("GET", arg, true);
xh.send(null); xh.send(null);
} }
function onBodyLoad(){ </script>
// init LEDbar
updateLeds(true);
// run the loop per default
//run();
}
</script>
</head> </head>
<body id="index" style="margin:0; padding:0;" onload="onBodyLoad()"> <body id="index" style="margin:0; padding:0;">
<div id="Main"> <div id="Main">
<div id="pageTitle"> <div id="pageTitle">
<!-- SVG Glitch from: http://codepen.io/DirkWeber/pen/ArFvk --> <!-- SVG Glitch from: http://codepen.io/DirkWeber/pen/ArFvk -->
<svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="460px" height="85px" viewBox="0 0 460 85"> <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="580px" height="45px" viewBox="0 0 580 45">
<defs> <defs>
<filter id="filter"> <filter id="filter">
<feFlood flood-color="#66bebe" result="black" /> <feFlood flood-color="#66bebe" result="black" />
@@ -235,24 +112,30 @@
</filter> </filter>
</defs> </defs>
<g> <g>
<text id="titleGlitch" style="filter: url(#filter);" x="0" y="45">ESP8266-Arduino</text> <text id="titleGlitch" style="filter: url(#filter);" x="0" y="35">Laserspiro controller</text>
<text id="titleText" x="10" y="75">AP Server Portal</text>
</g> </g>
</svg> </svg>
</div> </div>
<div id="ledControls"> <div id="prototypControls">
<text class="sectionTitle">LED Controls:</text> <text class="sectionDesc">some tests:</text>
<text class="sectionDesc">Click on the LEDs to light em Up! </text> <div id="ledMacroButtonsCont">
<div id="ledBar"></div> <a class="ledMacroButton" href="javascript:sendReq('/motor/1/128')">/motor/1/128</a>
<a class="ledMacroButton" href="javascript:sendReq('/motor/2/3')">/motor/2/3</a>
<text class="sectionDesc">also try a Animation:</text> <a class="ledMacroButton" href="javascript:sendReq('/laser/1/128')">/laser/1/128</a>
<div class="ledMacroButtons"> <a class="ledMacroButton" href="javascript:sendReq('/laser/1/13')">/laser/1/13</a>
<a class="ledMacroButton" href="javascript:handleLedMarco('rider')">Rider</a> <a class="ledMacroButton" href="javascript:sendReq('/laser/1/1')">/laser/1/1</a>
<a class="ledMacroButton" href="javascript:handleLedMarco('flipper')">Flipper</a>
<a class="ledMacroButton" href="javascript:handleLedMarco('clearAll')">stop & ClearAll</a>
</div> </div>
</div> </div>
<div id="prototypControls">
<text class="sectionDesc">last uri:</text>
<div id="uriDiv"></div>
<text class="sectionDesc">last respone:</text>
<br>
<div id="responseDiv">
</div>
<br>
</div>
</div> </div>
</body> </body>
</html> </html>

View File

@@ -5,7 +5,7 @@ body {
align: Center; align: Center;
} }
#Main { #Main {
width: 460px; width: 600px;
margin: 5px 3px 3px 12px; margin: 5px 3px 3px 12px;
} }
@@ -17,7 +17,7 @@ text#titleGlitch {
font-weight: bold; font-weight: bold;
text-shadow: 2px 2px black; text-shadow: 2px 2px black;
font-family: sans-serif; font-family: sans-serif;
font-size: 48px; font-size: 36px;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
} }
@@ -32,7 +32,7 @@ text#titleText {
svg { svg {
border: solid 1px black; border: solid 1px black;
width: 100%; width: 100%;
height: 80px; height: 50px;
display: block; display: block;
position: relative; position: relative;
/*overflow: hidden; */ /*overflow: hidden; */
@@ -41,7 +41,7 @@ svg {
-moz-border-radius: 10px; -moz-border-radius: 10px;
border-radius: 10px; border-radius: 10px;
} }
#ledControls { #prototypControls {
margin-top:3px; margin-top:3px;
padding: 10px; padding: 10px;
border: solid black 1px; border: solid black 1px;
@@ -64,63 +64,16 @@ svg {
float: left; float: left;
clear: left; clear: left;
} }
#ledBar {
float:none;
clear:left;
margin-left: 7px;
padding-top: 10px;
overflow: auto;
}
.ledDiv {
width: 40px;
height: 40px;
background: #add;
margin: 3px 3px;
float:left;
line-height: 30px;
border-radius: 100%;
position: relative;
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
-moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
}
.ledDiv label {
display: block;
width: 30px;
height: 30px;
border-radius: 100px;
text-align: center;
-webkit-transition: all .1s ease; #ledMacroButtonsCont {
-moz-transition: all .1s ease;
-o-transition: all .1s ease;
-ms-transition: all .1s ease;
transition: all .1s ease;
cursor: pointer;
position: absolute;
top: 5px;
left: 5px;
z-index: 1;
background: #663300;
-webkit-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
-moz-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
}
.ledDiv input[type="checkbox"] {
visibility: hidden;
}
.ledDiv input[type=checkbox]:checked + label {
background: #ff9900;
}
.ledMacroButtons {
padding: 18px 5px 15px 5px; padding: 18px 5px 15px 5px;
text-decoration: none; text-decoration: none;
float:none; float:none;
clear:left; clear:left;
} }
.ledMacroButton { .ledMacroButton {
height: 50px; height: 50px;
background: #00989d; background: #00989d;

View File

@@ -30,12 +30,9 @@
#include <ESP8266WebServer.h> #include <ESP8266WebServer.h>
#include <ESP8266mDNS.h> #include <ESP8266mDNS.h>
#include <FS.h> #include <FS.h>
#include <SoftwareSerial.h>
/* SoftwareSerial laserSerial(14, 12, false, 256);
#include <DNSServer.h>
*/
#define DBG_OUTPUT_PORT Serial
const char *ssid = "ESP-test"; const char *ssid = "ESP-test";
const char *password = ""; const char *password = "";
@@ -43,18 +40,7 @@ const char *password = "";
/* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */ /* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */
const char *myHostname = "esp8266"; const char *myHostname = "esp8266";
const char *metaRefreshStr = "<head><meta http-equiv=\"refresh\" content=\"3; url=http://192.168.4.1/index.html\" /></head><body><p>redirecting...</p></body>"; const char *metaRefreshStr = "<head><meta http-equiv=\"refresh\" content=\"3; url=/index.html\" /></head><body><p>redirecting...</p></body>";
/*
// DNS server
const byte DNS_PORT = 53;
DNSServer dnsServer;
*/
// LED Animations
unsigned long previousMillis = 0;
int interval = 100; // ms
/* Soft AP network parameters */ /* Soft AP network parameters */
IPAddress apIP(192, 168, 4, 1); // note: update metaRefreshStr string if ip change! IPAddress apIP(192, 168, 4, 1); // note: update metaRefreshStr string if ip change!
@@ -64,42 +50,42 @@ IPAddress netMsk(255, 255, 255, 0);
ESP8266WebServer server(80); ESP8266WebServer server(80);
//format bytes //format bytes
String formatBytes(size_t bytes){ String formatBytes(size_t bytes) {
if (bytes < 1024){ if (bytes < 1024) {
return String(bytes)+"B"; return String(bytes) + "B";
} else if(bytes < (1024 * 1024)){ } else if (bytes < (1024 * 1024)) {
return String(bytes/1024.0)+"KB"; return String(bytes / 1024.0) + "KB";
} else if(bytes < (1024 * 1024 * 1024)){ } else if (bytes < (1024 * 1024 * 1024)) {
return String(bytes/1024.0/1024.0)+"MB"; return String(bytes / 1024.0 / 1024.0) + "MB";
} else { } else {
return String(bytes/1024.0/1024.0/1024.0)+"GB"; return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
} }
} }
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";
else if(filename.endsWith(".html")) return "text/html"; else if (filename.endsWith(".html")) return "text/html";
else if(filename.endsWith(".css")) return "text/css"; else if (filename.endsWith(".css")) return "text/css";
else if(filename.endsWith(".js")) return "application/javascript"; else if (filename.endsWith(".js")) return "application/javascript";
else if(filename.endsWith(".png")) return "image/png"; else if (filename.endsWith(".png")) return "image/png";
else if(filename.endsWith(".gif")) return "image/gif"; else if (filename.endsWith(".gif")) return "image/gif";
else if(filename.endsWith(".jpg")) return "image/jpeg"; else if (filename.endsWith(".jpg")) return "image/jpeg";
else if(filename.endsWith(".ico")) return "image/x-icon"; else if (filename.endsWith(".ico")) return "image/x-icon";
else if(filename.endsWith(".xml")) return "text/xml"; else if (filename.endsWith(".xml")) return "text/xml";
else if(filename.endsWith(".pdf")) return "application/x-pdf"; else if (filename.endsWith(".pdf")) return "application/x-pdf";
else if(filename.endsWith(".zip")) return "application/x-zip"; else if (filename.endsWith(".zip")) return "application/x-zip";
else if(filename.endsWith(".gz")) return "application/x-gzip"; else if (filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain"; return "text/plain";
} }
bool handleFileRead(String path){ bool handleFileRead(String path) {
DBG_OUTPUT_PORT.println("handleFileRead: " + path); Serial.println("handleFileRead: " + path);
if(path.endsWith("/")) path += "index.html"; if (path.endsWith("/")) path += "index.html";
String contentType = getContentType(path); String contentType = getContentType(path);
String pathWithGz = path + ".gz"; String pathWithGz = path + ".gz";
if(SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)){ if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) {
if(SPIFFS.exists(pathWithGz)) if (SPIFFS.exists(pathWithGz))
path += ".gz"; path += ".gz";
File file = SPIFFS.open(path, "r"); File file = SPIFFS.open(path, "r");
size_t sent = server.streamFile(file, contentType); size_t sent = server.streamFile(file, contentType);
@@ -110,20 +96,23 @@ bool handleFileRead(String path){
} }
void handleFileList() { void handleFileList() {
if(!server.hasArg("dir")) {server.send(500, "text/plain", "BAD ARGS"); return;} if (!server.hasArg("dir")) {
server.send(500, "text/plain", "BAD ARGS");
return;
}
String path = server.arg("dir"); String path = server.arg("dir");
DBG_OUTPUT_PORT.println("handleFileList: " + path); Serial.println("handleFileList: " + path);
Dir dir = SPIFFS.openDir(path); Dir dir = SPIFFS.openDir(path);
path = String(); path = String();
String output = "["; String output = "[";
while(dir.next()){ while (dir.next()) {
File entry = dir.openFile("r"); File entry = dir.openFile("r");
if (output != "[") output += ','; if (output != "[") output += ',';
bool isDir = false; bool isDir = false;
output += "{\"type\":\""; output += "{\"type\":\"";
output += (isDir)?"dir":"file"; output += (isDir) ? "dir" : "file";
output += "\",\"name\":\""; output += "\",\"name\":\"";
output += String(entry.name()).substring(1); output += String(entry.name()).substring(1);
output += "\"}"; output += "\"}";
@@ -134,87 +123,70 @@ void handleFileList() {
server.send(200, "text/json", output); server.send(200, "text/json", output);
} }
// void handleLeds() void handleLaser(String uri)
// {
// if(server.arg("LED") ) {
// int pin = server.arg("LED").toInt();
// bool onOFF = server.arg("state").toInt();
// digitalWrite(pin, onOFF);
// }
// String json = "{ \"leds\": [";
// for (int i = 0; i < sizeof(ledIoNames); i++)
// {
// bool state = digitalRead(ledIoNames[i]);
// json += "{ \"" + String(i) + "\": [";
// json += "\""+String(ledIoNames[i])+"\", ";
// json += "\""+String(state)+"\" ] }";
// if(!(i == sizeof(ledIoNames)-1))
// json += ",";
// }
// json += "] }";
// server.send(200, "text/json", json);
// json = String();
// }
void handleMotor()
{ {
Serial.println("handleMotor"); String laserValue = uri.substring(7);
if(server.arg("motor") ) {
int pin = server.arg("motor").toInt();
bool onOFF = server.arg("state").toInt();
digitalWrite(pin, onOFF);
}
// String json = "{ \"leds\": [";
// for (int i = 0; i < sizeof(ledIoNames); i++)
// {
// bool state = digitalRead(ledIoNames[i]);
// json += "{ \"" + String(i) + "\": [";
// json += "\""+String(ledIoNames[i])+"\", ";
// json += "\""+String(state)+"\" ] }";
// if(!(i == sizeof(ledIoNames)-1))
// json += ",";
// } String msg = "AT SLV ";
// json += "] }"; msg += laserValue;
server.send(200, "text/plain", "blub");
// server.send(200, "text/json", json);
// json = 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 setup(void){ void handleMotor(String uri)
DBG_OUTPUT_PORT.begin(115200); {
DBG_OUTPUT_PORT.print("\n"); String motorNr = uri.substring(7, 8);
DBG_OUTPUT_PORT.setDebugOutput(true); 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 setup(void) {
laserSerial.begin(9600);
Serial.begin(115200);
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();
DBG_OUTPUT_PORT.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());
} }
DBG_OUTPUT_PORT.printf("\n"); Serial.printf("\n");
} }
//WIFI INIT //WIFI INIT
DBG_OUTPUT_PORT.printf("Connecting to %s\n", ssid); Serial.printf("Connecting to %s\n", ssid);
WiFi.mode(WIFI_AP); WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password); WiFi.softAP(ssid, password);
DBG_OUTPUT_PORT.println(""); Serial.println("");
DBG_OUTPUT_PORT.print("Connected! IP address: "); Serial.print("Connected! IP address: ");
DBG_OUTPUT_PORT.println ( WiFi.softAPIP() ); Serial.println ( WiFi.softAPIP() );
/*
//Setup the DNS server redirecting all the domains to the apIP
dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
dnsServer.start(DNS_PORT, "*", apIP);
*/
// Setup MDNS responder // Setup MDNS responder
if (!MDNS.begin(myHostname)) { if (!MDNS.begin(myHostname)) {
@@ -229,9 +201,9 @@ 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("/heap", HTTP_GET, [](){ server.on("/heap", HTTP_GET, []() {
String json = "{"; String json = "{";
json += "\"heap\":"+String(ESP.getFreeHeap()); json += "\"heap\":" + String(ESP.getFreeHeap());
json += "}"; json += "}";
server.send(200, "text/json", json); server.send(200, "text/json", json);
json = String(); json = String();
@@ -242,46 +214,28 @@ void setup(void){
} }
void handleNotFound() { void handleNotFound() {
Serial.println("handleNotFound"); String uri = server.uri();
String uri = server.uri(); Serial.print("unhandled uri:");
Serial.println(uri); Serial.println(uri);
// /motor/1/123 if (uri.substring(0, 7) == "/motor/")
{
if(uri.substring(0,7) == "/motor/") handleMotor(uri);
{ return;
Serial.println("/motor/"); }
int motorNr = uri.substring(7,8).toInt(); if (uri.substring(0, 7) == "/laser/")
int motorValue = uri.substring(9).toInt(); {
Serial.print("motorNr:"); handleLaser(uri);
Serial.println(motorNr); return;
Serial.print("motorValue:"); }
Serial.println(motorValue); if (!handleFileRead(server.uri()))
} {
if(!handleFileRead(server.uri())) server.send(302, "text/html", metaRefreshStr);
{ // server.send(302, "text/plain", "blub");
//server.send(302, "text/html", metaRefreshStr); }
server.send(302, "text/plain", "blub");
}
} }
void loop(void){ void loop(void) {
server.handleClient();
/*
//DNS
dnsServer.processNextRequest();
*/
//HTTP
server.handleClient();
//
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
}
} }