1
0
mirror of https://github.com/s00500/ESPUI.git synced 2024-11-21 17:40:54 +00:00

Serving static files right

This commit is contained in:
Lukas Bachschwell 2017-10-16 15:00:53 +02:00
parent 75e466c817
commit 90879055df
3 changed files with 120 additions and 156 deletions

View File

@ -3,15 +3,16 @@
#include "HTML_PAGE.h" // Added HTML Index Page
#include "CSS_STYLE.h" // Added Main CSS Style
#include "CSS_NORMALIZE.h" // Added Normalize CSS
#include "JS_JQUERY.h"
#include "JS_ZEPTO.h"
#include <ESPAsyncWebServer.h>
#include <functional>
using namespace std;
using namespace std::placeholders;
/*
// Generate Websockets Script for Webpage
void EasyUIClass::handleSockets(){
void EasyUIClass::handleSockets(AsyncWebServerRequest *request){
String ip;
if(WiFi.localIP().toString() != "0.0.0.0"){
ip = WiFi.localIP().toString();
@ -20,47 +21,64 @@ void EasyUIClass::handleSockets(){
ip = WiFi.softAPIP().toString();
}
String ws;
ws = "var connection = new WebSocket(\"ws://"+ip+":81/\", ['easyui']);";
ws += " var keys = {};";
ws += " connection.onopen = function () {";
ws += " $(\"#connection_status\").toggleClass(\"color-green\");";
ws += " $(\"#connection_status\").text(\"Connected\");";
ws += String(" connection.send(")+"\"{'mode': 'check_tb_status'}\");";
String wsString;
wsString = "var connection = new WebSocket(\"ws://"+ip+":81/\", ['easyui']);";
wsString += " var keys = {};";
wsString += " connection.onopen = function () {";
wsString += " $(\"#connection_status\").toggleClass(\"color-green\");";
wsString += " $(\"#connection_status\").text(\"Connected\");";
wsString += String(" connection.send(")+"\"{'mode': 'check_tb_status'}\");";
for(int i=0; i<tb_index; i++){
ws += String(" $(document).on('click',")+"'#tb"+i+"', function() {";
ws += String(" if($('#tb")+i+"').hasClass(\"button\")){ console.log(\"Button Clicked!\"); connection.send("+"\"{'mode': 'tb_click', 'index': '"+i+"', 'status': 'on'}\""+"); }";
ws += String(" else if($('#tb")+i+"').hasClass(\"button-primary\")){ connection.send("+"\"{'mode': 'tb_click', 'index': '"+i+"', 'status': 'off'}\""+"); } });";
wsString += String(" $(document).on('click',")+"'#tb"+i+"', function() {";
wsString += String(" if($('#tb")+i+"').hasClass(\"button\")){ console.log(\"Button Clicked!\"); connection.send("+"\"{'mode': 'tb_click', 'index': '"+i+"', 'status': 'on'}\""+"); }";
wsString += String(" else if($('#tb")+i+"').hasClass(\"button-primary\")){ connection.send("+"\"{'mode': 'tb_click', 'index': '"+i+"', 'status': 'off'}\""+"); } });";
}
ws += " };";
ws += " connection.onerror = function (error) { $('#connection_status').toggleClass(\"color-red\"); $(\"#connection_status\").text(\"Error / No Connection\"); };";
ws += " connection.onmessage = function (e) {";
ws += " console.log(e.data); ";
ws += " var obj = jQuery.parseJSON(e.data);";
ws += " if(obj.mode === 'create_label'){ $('#row').append(\"<div class='two columns card'><h5>\"+obj.l_title+\"</h5><hr /><h3><span class='label'>\"+obj.l_value+\"</span></h3></div>\");}";
ws += " else if(obj.mode === 'create_tbutton'){ $('#row').append(\"<div class='two columns card'><h5>\"+obj.tb_title+\"</h5><hr/><button id=\"+\"tb\"+obj.index+\"></button></div>\");}";
ws += " else if(obj.mode === 't_button_startup'){ var tb_index = obj.index; for(i=0; i<tb_index; i++){ var tb_index2 = \"tb\"+i; var tb_status = obj[tb_index2]; var tb_index3 = \"#\"+tb_index2; console.log(tb_status); if(tb_status === \"1\"){$(tb_index3).toggleClass('button-primary'); $(tb_index3).text('Turn Off');} else if(tb_status === \"0\"){$(tb_index3).toggleClass('button'); $(tb_index3).text('Turn On');} } }";
ws += " else if(obj.mode === 't_button_click'){ var tb_index = \"tb\"+obj.index; var tb_status = obj[tb_index]; var tb_index3 = \"#\"+tb_index; console.log(tb_status); if(tb_status == \"1\"){ console.log(\"Status Tuned ON\"); $(tb_index3).text('Turn Off'); $(tb_index3).removeClass( \"button\" ).addClass( \"button-primary\" );} else if(tb_status == \"0\"){console.log(\"Status Tuned OFF\"); $(tb_index3).text('Turn On'); $(tb_index3).removeClass( \"button-primary\" ).addClass( \"button\" ); } } };";
server->send(200, "application/javascript", ws);
wsString += " };";
wsString += " connection.onerror = function (error) { $('#connection_status').toggleClass(\"color-red\"); $(\"#connection_status\").text(\"Error / No Connection\"); };";
wsString += " connection.onmessage = function (e) {";
wsString += " console.log(e.data); ";
wsString += " var obj = jQuery.parseJSON(e.data);";
wsString += " if(obj.mode === 'create_label'){ $('#row').append(\"<div class='two columns card'><h5>\"+obj.l_title+\"</h5><hr /><h3><span class='label'>\"+obj.l_value+\"</span></h3></div>\");}";
wsString += " else if(obj.mode === 'create_tbutton'){ $('#row').append(\"<div class='two columns card'><h5>\"+obj.tb_title+\"</h5><hr/><button id=\"+\"tb\"+obj.index+\"></button></div>\");}";
wsString += " else if(obj.mode === 't_button_startup'){ var tb_index = obj.index; for(i=0; i<tb_index; i++){ var tb_index2 = \"tb\"+i; var tb_status = obj[tb_index2]; var tb_index3 = \"#\"+tb_index2; console.log(tb_status); if(tb_status === \"1\"){$(tb_index3).toggleClass('button-primary'); $(tb_index3).text('Turn Off');} else if(tb_status === \"0\"){$(tb_index3).toggleClass('button'); $(tb_index3).text('Turn On');} } }";
wsString += " else if(obj.mode === 't_button_click'){ var tb_index = \"tb\"+obj.index; var tb_status = obj[tb_index]; var tb_index3 = \"#\"+tb_index; console.log(tb_status); if(tb_status == \"1\"){ console.log(\"Status Tuned ON\"); $(tb_index3).text('Turn Off'); $(tb_index3).removeClass( \"button\" ).addClass( \"button-primary\" );} else if(tb_status == \"0\"){console.log(\"Status Tuned OFF\"); $(tb_index3).text('Turn On'); $(tb_index3).removeClass( \"button-primary\" ).addClass( \"button\" ); } } };";
request->send(200, "application/javascript", wsString);
}
// Handle Websockets Communication ( Out of Class)
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {
// Handle Index HTML
void EasyUIClass::handleRoot(AsyncWebServerRequest *request){
String rootString;
//request->setContentLength(CONTENT_LENGTH_UNKNOWN);
rootString += HTML_HEAD1;
rootString += String("<title>")+ui_title+"</title>";
rootString += HTML_HEAD2;
rootString += String("<h4>")+ui_title+" <span id=\"connection_status\" class=\"label\">Offline</span></h4></div><hr />";
rootString += HTML_BODY;
rootString += "<script src=\"/js/zepto.js\"></script>";
rootString += HTML_END;
request->send(200,"text/html", rootString);
//server->client().stop();
}
*/
/*
// Handle Websockets Communication
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
switch(type) {
case WStype_DISCONNECTED:
case WS_EVT_DISCONNECT:
Serial.printf("Disconnected!\n");
break;
case WStype_CONNECTED:
case WS_EVT_CONNECT:
{
Serial.printf("[WSc] Connected to url: %s\n", payload);
//Serial.printf("[WSc] Connected to url: %s\n", payload);
Serial.println("Connected");
EasyUI.handleWebpage();
Serial.println("JSON Data Sent to Client!");
}
break;
case WStype_TEXT:
case WS_EVT_DATA:
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(payload);
JsonObject& root = jsonBuffer.parseObject(data);
String mode = root["mode"];
if(mode == "check_tb_status"){
EasyUI.tbuttonStatus();
@ -70,16 +88,10 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght
String index = root["index"];
EasyUI.tbClick(index, status);
}
// send message to server
// webSocket.sendTXT("message here");
break;
}
}
void EasyUIClass::detectCDN(bool _autoState){
CDN = _autoState;
}
*/
void EasyUIClass::title(const char* _title){
ui_title = _title;
}
@ -90,7 +102,7 @@ void EasyUIClass::label(const char* label_name,const char* label_val){
label_title[l_index] = label_name;
l_index++;
}
/*
// Create Toggle Buttons
void EasyUIClass::toggleButton(uint8_t pin, const char* tbutton_label, int start_state, bool swap_state){
pinMode(pin, OUTPUT);
@ -100,7 +112,19 @@ void EasyUIClass::toggleButton(uint8_t pin, const char* tbutton_label, int star
tbuttontitle[tb_index] = tbutton_label;
tb_index++;
}
*/
// Create a generic Button
void EasyUIClass::button(uint8_t pin, const char* tbutton_label, int start_state, bool swap_state){
//TODO: Implement
pinMode(pin, OUTPUT);
digitalWrite(pin, start_state);
tbutton_swap[tb_index] = swap_state;
tbutton_pinout[tb_index] = pin;
tbuttontitle[tb_index] = tbutton_label;
tb_index++;
}
/*
// Check Toggle Buttons States and Transfer to Webpage
void EasyUIClass::tbuttonStatus(){
String json;
@ -131,82 +155,9 @@ void EasyUIClass::tbuttonStatus(){
root.printTo(json);
webSocket->broadcastTXT(json);
}
*/
// Handle Index HTML
void EasyUIClass::handleRoot(){
bool internet = false;
if(CDN){
HTTPClient http;
http.begin("http://www.google.com/");
int httpCode = http.GET();
if(httpCode > 0) {
internet = true;
}
}
server->setContentLength(CONTENT_LENGTH_UNKNOWN);
server->send(200,"text/html", "");
server->sendContent(HTML_HEAD1);
server->sendContent(String("<title>")+ui_title+"</title>");
server->sendContent(HTML_HEAD2);
server->sendContent(String("<h4>")+ui_title+" <span id=\"connection_status\" class=\"label\">Offline</span></h4></div><hr />");
server->sendContent(HTML_BODY);
if(internet){
server->sendContent("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\"></script>");
}
else{
server->sendContent("<script src=\"/js/jquery.js\"></script>");
}
server->sendContent(HTML_END);
server->client().stop();
}
// Handle Main Style CSS
void EasyUIClass::handleSCSS(){
server->send_P(200, "text/css", CSS_STYLE);
}
// Handle Normalize CSS
void EasyUIClass::handleNCSS(){
server->send_P(200, "text/css", CSS_NORMALIZE);
}
// Handle Jquery
void EasyUIClass::handleJS(){
server->send_P(200, "application/javascript", JS_JQUERY);
}
// Handle Not found Page
void EasyUIClass::handleNotFound() {
String url = "";
String type = "";
url = server->uri();
if (SPIFFS.exists(url)) {
File file = SPIFFS.open(url, "r");
if (url.endsWith(".htm")) type = "text/html";
else if (url.endsWith(".html")) type = "text/html";
else if (url.endsWith(".css")) type = "text/css";
else if (url.endsWith(".js")) type = "application/javascript";
else if (url.endsWith(".png")) type = "image/png";
else if (url.endsWith(".gif")) type = "image/gif";
else if (url.endsWith(".jpg")) type = "image/jpeg";
else if (url.endsWith(".ico")) type = "image/x-icon";
else if (url.endsWith(".xml")) type = "text/xml";
else if (url.endsWith(".pdf")) type = "application/x-pdf";
else if (url.endsWith(".zip")) type = "application/x-zip";
else if (url.endsWith(".gz")) type = "application/x-gzip";
else type = "text/plain";
server->streamFile(file, type);
file.close();
}
else {
server->send(200, "text/html", "<html><h1>404 - You are Lost</h1></html>");
}
}
/*
// Handle Toggle Button Click Response
void EasyUIClass::tbClick(String _index, String _status){
String json;
@ -237,7 +188,8 @@ void EasyUIClass::tbClick(String _index, String _status){
}
}
}
*/
/*
// Convert & Transfer Arduino elements to JSON elements
void EasyUIClass::handleWebpage(){
@ -264,28 +216,49 @@ void EasyUIClass::handleWebpage(){
}
}
*/
void EasyUIClass::begin(){
server.reset(new ESP8266WebServer(80));
webSocket.reset(new WebSocketsServer(81,"","easyui"));
SPIFFS.begin();
server->on("/", std::bind(&EasyUIClass::handleRoot, this));
server->on("/css/normalize.css", std::bind(&EasyUIClass::handleNCSS, this));
server->on("/css/skeleton.css", std::bind(&EasyUIClass::handleSCSS, this));
server->on("/js/jquery.js", std::bind(&EasyUIClass::handleJS, this));
server->on("/js/sockets.js", std::bind(&EasyUIClass::handleSockets, this));
server->onNotFound(std::bind(&EasyUIClass::handleNotFound, this));
server->begin();
webSocket->begin();
webSocket->onEvent(webSocketEvent);
server.reset(new AsyncWebServer(80));
//ws.reset(new AsyncWebSocket("/ws"));
//SPIFFS.begin();
//ws->onEvent(onWsEvent);
//server->addHandler(&ws);
/*
server->on("/", HTTP_GET, [](AsyncWebServerRequest *request){
EasyUI.handleRoot(request);
});
server->on("/js/sockets.js", HTTP_GET, [](AsyncWebServerRequest *request){
EasyUI.handleSockets(request);
});
*/
// Static constant serving =P
server->on("/js/zepto.js", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "application/javascript", JS_ZEPTO);
});
server->on("/css/normalize.css", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/css", CSS_NORMALIZE);
});
server->on("/css/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/css", CSS_STYLE);
});
//Heap for general Servertest
server->on("/heap", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/plain", String(ESP.getFreeHeap()));
});
server->onNotFound([](AsyncWebServerRequest *request){
request->send(404);
});
server->begin();
//webSocket->onEvent(webSocketEvent);
Serial.println("UI Initialized");
}
void EasyUIClass::loop(){
webSocket->loop();
server->handleClient();
}
EasyUIClass EasyUI;

View File

@ -1,26 +1,28 @@
#ifndef EasyUI_h
#define EasyUI_h
#define HARDWARE "esp32"
//ifdef 8266
//#include "Hash.h"
#include "Arduino.h"
#include "stdlib_noniso.h"
#include "FS.h"
#include "ESP8266WiFi.h"
#include "WiFiClient.h"
#include "ESP8266WebServer.h"
#include "ESP8266HTTPClient.h"
#include "ArduinoJson.h"
#include "WebSocketsServer.h"
#include "Hash.h"
//#include "FS.h"
#include "WiFi.h"
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#define HARDWARE "esp8266"
class EasyUIClass{
public:
void begin(); // Begin HTTP Server + WebSocketsServer & Initalize All Elements
void detectCDN(bool _autoState = true); // Detect if Internet Available or Switch to Offline Jquery
void title(const char* _title); // Define Webpage Header Name and title
void toggleButton(uint8_t pin, const char* tbutton_label, int start_state = 0, bool swap_state = false); // Create Toggle Button
void button(uint8_t pin, const char* tbutton_label, int start_state = 0, bool swap_state = false); // Create Toggle Button
void label(const char* label_name, const char* label_val); // Create Label
void loop(); // Do All Loop Work
@ -39,7 +41,7 @@ public:
// const char* variable_type[10]; // un-used feature for now // Stores Label Types, Like 'C' , 'F' or '%' - MAX 10
String webpage; // Coverts Arduino elements to JSON elements
String ws = ""; // Stores Websockets Script
String wsString = ""; // Stores Websockets Script
// Don't Issue the Below functions in your Sketch! - These are Resposible for Webpage functioning.
void tbClick(String _index, String _status);
@ -48,17 +50,12 @@ public:
private:
std::unique_ptr<ESP8266WebServer> server; // Create Unique Instance for Webserver
std::unique_ptr<WebSocketsServer> webSocket; // Create Unique Instance for WebSocketsServer
std::unique_ptr<AsyncWebServer> server; // Create Unique Instance for Webserver
std::unique_ptr<AsyncWebSocket> ws; // Create Unique Instance for WebSocketsServer
bool CDN = false;
void handleRoot(); // Handle Index HTML
void handleNCSS(); // Handle Normalize CSS
void handleSCSS(); // Handle Main Style CSS
void handleJS(); // Handle JQuery
void handleRoot(AsyncWebServerRequest *request); // Handle MainPage
void handleNotFound(); // Handle Page Not-Found
void handleSockets(); // Handle Sockets Script
void handleSockets(AsyncWebServerRequest *request); // Handle Sockets Script
};

File diff suppressed because one or more lines are too long