tinance2-doorbot/include/mainwebserver.h
2023-06-13 21:11:23 +02:00

95 lines
2.8 KiB
C++

#ifndef mainwebserver_h
#define mainwebserver_h
#include "Arduino.h"
#include "stdlib_noniso.h"
#include "WiFi.h"
#include "AsyncTCP.h"
#include "Update.h"
#include "esp_int_wdt.h"
#include "esp_task_wdt.h"
#include "ESPAsyncWebServer.h"
#include "SPIFFS.h"
#include "hardware.h"
class MainWebServerClass{
public:
void begin(AsyncWebServer *server, const char* username = "", const char* password = ""){
_server = server;
if(strlen(username) > 0){
_authRequired = true;
_username = username;
_password = password;
}else{
_authRequired = false;
_username = "";
_password = "";
}
_server->on("/test/identity", HTTP_GET, [&](AsyncWebServerRequest *request){
if(_authRequired){
if(!request->authenticate(_username.c_str(), _password.c_str())){
return request->requestAuthentication();
}
}
request->send(200, "application/json");
});
_server->on("/", HTTP_GET, [&](AsyncWebServerRequest *request){
if(_authRequired){
if(!request->authenticate(_username.c_str(), _password.c_str())){
return request->requestAuthentication();
}
}
request->send(SPIFFS, "/index.html", String(), false, processor);
});
_server->onNotFound([&](AsyncWebServerRequest *request){
request->send(200, "application/json", "{\"msg\":\"The content you are looking for was not found\"}");
});
}
// deprecated, keeping for backward compatibility
void loop() {
}
private:
AsyncWebServer *_server;
String _username = "";
String _password = "";
bool _authRequired = false;
static String outputState(int output){
if(digitalRead(output)){
return "checked";
}
else {
return "";
}
}
// Replaces placeholder with button section in your web page
static String processor(const String& var){
//Serial.println(var);
if(var == "BUTTONPLACEHOLDER"){
String buttons = "";
#ifdef RELAY1
buttons += "<h4>Output - Relay 1 </h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"relay1\" " + MainWebServerClass::outputState(RELAY1_PIN) + "><span class=\"slider\"></span></label>";
#endif
return buttons;
}
return String();
}
};
MainWebServerClass MainWebServer;
#endif