Merge pull request #2 from StrangeD0s/load-html-from-sd

load html from sd and implement post requests
This commit is contained in:
StrangeD0s
2024-07-22 00:33:47 +02:00
committed by GitHub
2 changed files with 160 additions and 229 deletions
+148 -216
View File
@@ -31,18 +31,72 @@
developed for the ESP32vn IoT Uni board 2024 developed for the ESP32vn IoT Uni board 2024
*/ */
//-----------------------------------------
// Arduino Web Server using AJAX
// HTML code of webpage is stored on SD card
//-----------------------------------------
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "FS.h" #include "FS.h"
#include "SD.h" #include "SD.h"
#include "SPI.h" #include "SPI.h"
#include <WiFi.h>
#include <IRremote.hpp> #include <IRremote.hpp>
#include "secrets.h" #include "secrets.h"
#include "defines.h" #include "defines.h"
WiFiServer server(80); //------------------------------------------------
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// WiFiServer server(80);
const char *PARAM_MESSAGE = "message";
void notFound(AsyncWebServerRequest *request)
{
request->send(404, "text/plain", "Not found");
}
//------------------------------------------------
//-------------- SD-Card Functions ---------------
void initSDCard()
{
if (!SD.begin())
{
Serial.println("Card Mount Failed");
return;
}
uint8_t cardType = SD.cardType();
if (cardType == CARD_NONE)
{
Serial.println("No SD card attached");
return;
}
Serial.print("SD Card Type: ");
if (cardType == CARD_MMC)
{
Serial.println("MMC");
}
else if (cardType == CARD_SD)
{
Serial.println("SDSC");
}
else if (cardType == CARD_SDHC)
{
Serial.println("SDHC");
}
else
{
Serial.println("UNKNOWN");
}
uint64_t cardSize = SD.cardSize() / (1024 * 1024);
Serial.printf("SD Card Size: %lluMB\n", cardSize);
}
/**** SD-Card Functions ****/
void listDir(fs::FS &fs, const char *dirname, uint8_t levels) void listDir(fs::FS &fs, const char *dirname, uint8_t levels)
{ {
Serial.printf("Listing directory: %s\n", dirname); Serial.printf("Listing directory: %s\n", dirname);
@@ -82,252 +136,130 @@ void listDir(fs::FS &fs, const char *dirname, uint8_t levels)
} }
} }
void readFile(fs::FS &fs, const char *path) //------------------------------------------------
{ //--------------- IR Functions -------------------
Serial.printf("Reading file: %s\n", path);
File file = fs.open(path); void initIR()
if (!file)
{ {
Serial.println("Failed to open file for reading"); IrSender.begin(IR_SEND_PIN, ENABLE_LED_FEEDBACK, USE_DEFAULT_FEEDBACK_LED_PIN); // Specify send pin and enable feedback LED at default feedback LED pin
return; Serial.println();
Serial.print(F("Send IR signals at pin "));
Serial.println(IR_SEND_PIN);
} }
Serial.print("Read from file: ");
while (file.available())
{
Serial.write(file.read());
}
file.close();
}
void testFileIO(fs::FS &fs, const char *path)
{
File file = fs.open(path);
static uint8_t buf[512];
size_t len = 0;
uint32_t start = millis();
uint32_t end = start;
if (file)
{
len = file.size();
size_t flen = len;
start = millis();
while (len)
{
size_t toRead = len;
if (toRead > 512)
{
toRead = 512;
}
file.read(buf, toRead);
len -= toRead;
}
end = millis() - start;
Serial.printf("%u bytes read for %u ms\n", flen, end);
file.close();
}
else
{
Serial.println("Failed to open file for reading");
}
file = fs.open(path, FILE_WRITE);
if (!file)
{
Serial.println("Failed to open file for writing");
return;
}
size_t i;
start = millis();
for (i = 0; i < 2048; i++)
{
file.write(buf, 512);
}
end = millis() - start;
Serial.printf("%u bytes written for %u ms\n", 2048 * 512, end);
file.close();
}
/* ============ IR Functions ============ */
void sendButton(int command) void sendButton(int command)
{ {
Serial.println("sendButton command: ");
Serial.println(command); Serial.println(command);
Serial.flush(); Serial.flush();
IrSender.sendSony(0xF, command, 2, 12); IrSender.sendSony(0xF, command, 2, 12);
} }
/* ============ Setup ============ */ //------------------------------------------------
//------------- Webserver Functions --------------
void initWiFi()
{
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PASSWORD);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
//------------------------------------------------
//-------------------- Setup ---------------------
void setup() void setup()
{ {
Serial.begin(115200); Serial.begin(115200);
initWiFi();
initSDCard();
pinMode(LED_PIN, OUTPUT); // set the LED pin mode pinMode(LED_PIN, OUTPUT); // set the LED pin mode
delay(10); initIR();
/* ============ SD-Card Setup ============ */ server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
if (!SD.begin()) { request->send(SD, "/index.html", "text/html"); });
{
Serial.println("Card Mount Failed");
return;
}
uint8_t cardType = SD.cardType();
if (cardType == CARD_NONE) server.serveStatic("/", SD, "/");
{
Serial.println("No SD card attached");
return;
}
Serial.print("SD Card Type: "); // Send a GET request to <IP>/api/gettextinput?message=<message>
if (cardType == CARD_MMC) server.on("/api/gettextinput", HTTP_GET, [](AsyncWebServerRequest *request)
{ {
Serial.println("MMC"); String message;
} if (request->hasParam("text_input"))
else if (cardType == CARD_SD)
{ {
Serial.println("SDSC"); message = request->getParam("text_input")->value();
} Serial.println(message);
else if (cardType == CARD_SDHC)
{
Serial.println("SDHC");
} }
else else
{ {
Serial.println("UNKNOWN"); message = "No message sent";
} }
request->send(SD, "/index.html", "text/html"); });
uint64_t cardSize = SD.cardSize() / (1024 * 1024); // Send a POST request to <IP>/api/control-led with a form field message set to <message>
Serial.printf("SD Card Size: %lluMB\n", cardSize); server.on("/api/control-led", HTTP_POST, [](AsyncWebServerRequest *request)
listDir(SD, "/", 0);
readFile(SD, "/index.html");
Serial.printf("Total space: %lluMB\n", SD.totalBytes() / (1024 * 1024));
Serial.printf("Used space: %lluMB\n", SD.usedBytes() / (1024 * 1024));
/* ============ IR Setup ============ */
IrSender.begin(IR_SEND_PIN, ENABLE_LED_FEEDBACK, USE_DEFAULT_FEEDBACK_LED_PIN); // Specify send pin and enable feedback LED at default feedback LED pin
Serial.println();
Serial.print(F("Send IR signals at pin "));
Serial.println(IR_SEND_PIN);
/* ============ Webserver Setup ============ */
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(SSID);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{ {
delay(500); String message;
Serial.print("."); if (request->hasParam("led", true)) {
message = request->getParam("led", true)->value();
if (message == "1")
digitalWrite(LED_PIN, HIGH);
if (message == "0")
digitalWrite(LED_PIN, LOW);
} else {
message = "No message sent";
} }
request->send(SD, "/index.html", "text/html"); });
Serial.println(); // Send a POST request to <IP>/api/gettext with a form field message set to <message>
Serial.println("WiFi connected."); server.on("/api/gettext", HTTP_POST, [](AsyncWebServerRequest *request)
Serial.println("IP address: "); {
Serial.println(WiFi.localIP()); String message;
if (request->hasParam("text_box", true)) {
message = request->getParam("text_box", true)->value();
Serial.println(message);
} else {
message = "No message sent";
}
request->send(SD, "/index.html", "text/html"); });
// Send a POST request to <IP>/api/control-deck with a form field message set to <message>
server.on("/api/control-deck", HTTP_POST, [](AsyncWebServerRequest *request)
{
String message;
if (request->hasParam("control", true)) {
message = request->getParam("control", true)->value();
//Serial.print(message);
if (message == "POWER")
sendButton(POWER);
if (message == "PLAY")
sendButton(PLAY);
if (message == "PAUSE")
sendButton(PAUSE);
if (message == "STOP")
sendButton(STOP);
if (message == "PREV")
sendButton(PREV);
if (message == "NEXT")
sendButton(NEXT);
} else {
message = "No message sent";
}
request->send(SD, "/index.html", "text/html"); });
server.onNotFound(notFound);
server.begin(); server.begin();
} }
void loop() void loop()
{ {
WiFiClient client = server.available(); // listen for incoming clients
if (client)
{ // if you get a client,
Serial.println("New Client."); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected())
{ // loop while the client's connected
if (client.available())
{ // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n')
{ // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0)
{
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("Click <a href=\"/H\">here</a> to turn the LED on pin 13 on.<br>Click <a href=\"/L\">here</a> to turn the LED on pin 13 off.<br><a href=\"/power\">power</a><br><a href=\"/play\">play</a><br><a href=\"/pause\">pause</a><br><a href=\"/stop\">stop</a><br><a href=\"/prev\">previous track</a><br><a href=\"/next\">next track</a><br>");
client.print("<form action=\"/api/control-deck\" method=\"post\"><button name=\"control\" type=\"submit\" value=\"play\">play</button></form><br><form action=\"/api/control-deck\" method=\"get\"><input name=\"textinput\" type=\"text\" /><button type=\"submit\">send</button></form><br>");
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
}
else
{ // if you got a newline, then clear currentLine:
currentLine = "";
}
}
else if (c != '\r')
{ // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H"))
{
digitalWrite(LED_PIN, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L"))
{
digitalWrite(LED_PIN, LOW); // GET /L turns the LED off
}
if (currentLine.endsWith("GET /power"))
{
sendButton(POWER);
}
if (currentLine.endsWith("GET /play"))
{
sendButton(PLAY);
}
if (currentLine.endsWith("GET /pause"))
{
sendButton(PAUSE);
}
if (currentLine.endsWith("GET /stop"))
{
sendButton(STOP);
}
if (currentLine.endsWith("GET /prev"))
{
sendButton(PREV);
}
if (currentLine.endsWith("GET /next"))
{
sendButton(NEXT);
}
if (currentLine.endsWith("POST /api/control-deck"))
{
Serial.println("POST");
char c = client.read();
Serial.print(c);
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
} }
+5 -6
View File
@@ -8,7 +8,6 @@
name="viewport" name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no" content="width=device-width, initial-scale=1, shrink-to-fit=no"
/> />
<!-- <link rel="stylesheet" href="style.css" /> -->
<style> <style>
:root { :root {
--main-bg-color: #212121; --main-bg-color: #212121;
@@ -184,26 +183,26 @@
<button <button
name="control" name="control"
type="submit" type="submit"
value="power" value="POWER"
class="smallbutton" class="smallbutton"
> >
power power
</button> </button>
<button name="control" type="submit" value="play" class="smallbutton"> <button name="control" type="submit" value="PLAY" class="smallbutton">
play play
</button> </button>
<button <button
name="control" name="control"
type="submit" type="submit"
value="pause" value="PAUSE"
class="smallbutton" class="smallbutton"
> >
pause pause
</button> </button>
<button name="control" type="submit" value="stop" class="smallbutton"> <button name="control" type="submit" value="STOP" class="smallbutton">
stop stop
</button> </button>
<button name="control" type="submit" value="next" class="smallbutton"> <button name="control" type="submit" value="NEXT" class="smallbutton">
next next
</button> </button>
<button class="roundbutton"></button> <button class="roundbutton"></button>