1
0
mirror of https://github.com/s00500/ESPUI.git synced 2024-11-25 03:50:54 +00:00
ESPUI/src/ESPUI.cpp

1451 lines
37 KiB
C++
Raw Normal View History

2020-09-28 08:44:14 +00:00
#include "ESPUI.h"
#include <functional>
#include <ESPAsyncWebServer.h>
#include "dataControlsJS.h"
#include "dataGraphJS.h"
#include "dataIndexHTML.h"
#include "dataNormalizeCSS.h"
#include "dataSliderJS.h"
#include "dataStyleCSS.h"
#include "dataTabbedcontentJS.h"
#include "dataZeptoJS.h"
// ################# LITTLEFS functions
2018-01-14 11:22:26 +00:00
#if defined(ESP32)
void listDir(const char* dirname, uint8_t levels)
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.printf_P(PSTR("Listing directory: %s\n"), dirname);
}
#endif
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
File root = LittleFS.open(dirname);
#else
File root = LITTLEFS.open(dirname);
#endif
#else
File root = LittleFS.open(dirname);
2022-10-13 20:10:20 +00:00
#endif
if (!root)
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("Failed to open directory"));
}
#endif
2018-01-14 11:22:26 +00:00
return;
}
if (!root.isDirectory())
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("Not a directory"));
}
#endif
return;
}
File file = root.openNextFile();
while (file)
{
if (file.isDirectory())
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.print(F(" DIR : "));
Serial.println(file.name());
}
#endif
2018-01-14 11:22:26 +00:00
if (levels)
{
2022-10-13 20:10:20 +00:00
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
listDir(file.path(), levels - 1);
#else
listDir(file.name(), levels - 1);
#endif
}
}
else
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.print(F(" FILE: "));
Serial.print(file.name());
Serial.print(F(" SIZE: "));
Serial.println(file.size());
}
#endif
}
file = root.openNextFile();
}
}
2018-01-14 11:22:26 +00:00
#else
void listDir(const char* dirname, uint8_t levels)
{
2022-10-13 20:10:20 +00:00
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.printf_P(PSTR("Listing directory: %s\n"), dirname);
}
#endif
2022-10-13 20:10:20 +00:00
Dir dir = LittleFS.openDir(dirname);
while (dir.next())
{
2022-10-13 20:10:20 +00:00
if (dir.isDirectory())
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.print(F(" DIR : "));
Serial.println(dir.fileName());
}
#endif
if (levels)
{
File file = dir.openFile("r");
listDir(file.fullName(), levels - 1);
file.close();
}
}
else
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.print(F(" FILE: "));
Serial.print(dir.fileName());
Serial.print(F(" SIZE: "));
Serial.println(dir.fileSize());
}
#endif
}
}
2018-01-14 11:22:26 +00:00
}
#endif
void ESPUIClass::list()
{
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
if (!LittleFS.begin())
#else
if (!LITTLEFS.begin())
#endif
{
Serial.println(F("LITTLEFS Mount Failed"));
return;
}
#else
if (!LittleFS.begin())
{
Serial.println(F("LittleFS Mount Failed"));
return;
}
2022-10-13 20:10:20 +00:00
#endif
listDir("/", 1);
2018-01-14 11:22:26 +00:00
#if defined(ESP32)
2022-10-13 20:10:20 +00:00
Serial.print(F("Total KB: "));
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
Serial.println(LittleFS.totalBytes()/1024);
#else
Serial.println(LITTLEFS.totalBytes()/1024);
#endif
Serial.print(F("Used KB: "));
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
Serial.println(LittleFS.usedBytes()/1024);
#else
Serial.println(LITTLEFS.usedBytes()/1024);
#endif
#else
FSInfo fs_info;
LittleFS.info(fs_info);
2022-10-13 20:10:20 +00:00
Serial.print(F("Total KB: "));
Serial.println(fs_info.totalBytes/1024);
Serial.print(F("Used KB: "));
Serial.println(fs_info.usedBytes/1024);
2018-01-14 11:22:26 +00:00
#endif
}
void deleteFile(const char* path)
{
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
bool exists = LittleFS.exists(path);
#else
bool exists = LITTLEFS.exists(path);
#endif
#else
bool exists = LittleFS.exists(path);
2022-10-13 20:10:20 +00:00
#endif
if (!exists)
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.printf_P(PSTR("File: %s does not exist, not deleting\n"), path);
}
#endif
return;
}
2017-11-29 10:32:07 +00:00
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.printf_P(PSTR("Deleting file: %s\n"), path);
}
#endif
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
bool didRemove = LittleFS.remove(path);
#else
bool didRemove = LITTLEFS.remove(path);
#endif
#else
bool didRemove = LittleFS.remove(path);
2022-10-13 20:10:20 +00:00
#endif
if (didRemove)
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("File deleted"));
}
#endif
}
else
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("Delete failed"));
}
#endif
}
}
void writeFile(const char* path, const char* data)
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.printf_P(PSTR("Writing file: %s\n"), path);
}
#endif
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
File file = LittleFS.open(path, FILE_WRITE);
#else
File file = LITTLEFS.open(path, FILE_WRITE);
#endif
#else
File file = LittleFS.open(path, FILE_WRITE);
2022-10-13 20:10:20 +00:00
#endif
if (!file)
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("Failed to open file for writing"));
}
#endif
return;
}
#if defined(ESP32)
if (file.print(data))
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("File written"));
}
#endif
}
else
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("Write failed"));
}
#endif
}
#else
if (file.print(FPSTR(data)))
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("File written"));
}
#endif
}
else
{
#if defined(DEBUG_ESPUI)
if (ESPUI.verbosity)
{
Serial.println(F("Write failed"));
}
#endif
}
#endif
file.close();
}
// end LITTLEFS functions
2022-10-13 20:10:20 +00:00
void ESPUIClass::prepareFileSystem(bool format)
{
// this function should only be used once
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
Serial.println(F("About to prepare filesystem..."));
}
#endif
2017-12-25 15:39:54 +00:00
#if defined(ESP32)
2022-10-13 20:10:20 +00:00
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
if(!LittleFS.begin(false)) //Test for an already formatted LittleFS by a mount failure
#else
if(!LITTLEFS.begin(false)) //Test for an already formatted LittleFS by a mount failure
#endif
{
2022-10-13 20:10:20 +00:00
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
if(!LittleFS.begin(true)) //Attempt to format LittleFS
#else
if(!LITTLEFS.begin(true)) //Attempt to format LittleFS
#endif
{
#if defined(DEBUG_ESPUI)
2022-10-13 20:10:20 +00:00
if (verbosity)
{
Serial.println(F("LittleFS Format Failed"));
}
#endif
return;
2022-10-13 20:10:20 +00:00
}
}
2022-10-13 20:10:20 +00:00
else if(format)
{
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
LittleFS.format();
#else
LITTLEFS.format();
#endif
#if defined(DEBUG_ESPUI)
if (verbosity)
{
Serial.println(F("LittleFS Formatted"));
}
#endif
}
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
listDir("/", 1);
2022-09-21 19:45:48 +00:00
Serial.println(F("LittleFS Mount ESP32 Done"));
}
#endif
2017-12-25 15:39:54 +00:00
#else
2022-10-13 20:10:20 +00:00
if (!LittleFS.begin()) //Test for an already formatted LittleFS by a mount failure
{
if(LittleFS.format()) //Attempt to format LittleFS
{
#if defined(DEBUG_ESPUI)
if (verbosity)
{
Serial.println(F("LittleFS Formatted"));
}
#endif
}
else
{
#if defined(DEBUG_ESPUI)
if (verbosity)
{
Serial.println(F("LittleFS Mount Failed"));
}
#endif
return;
}
}
else if(format)
{
LittleFS.format();
#if defined(DEBUG_ESPUI)
if (verbosity)
{
Serial.println(F("LittleFS Formatted"));
}
#endif
}
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
2022-10-13 20:10:20 +00:00
listDir("/", 1);
Serial.println(F("LittleFS Mount ESP8266 Done"));
}
#endif
2017-12-25 15:39:54 +00:00
#endif
deleteFile("/index.htm");
deleteFile("/css/style.css");
deleteFile("/css/normalize.css");
deleteFile("/js/zepto.min.js");
deleteFile("/js/controls.js");
deleteFile("/js/slider.js");
deleteFile("/js/graph.js");
deleteFile("/js/tabbedcontent.js");
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
Serial.println(F("Cleanup done"));
}
#endif
// Now write
2022-10-13 20:10:20 +00:00
#ifdef ESP32
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
writeFile("/index.htm", HTML_INDEX);
LittleFS.mkdir("/css");
writeFile("/css/style.css", CSS_STYLE);
writeFile("/css/normalize.css", CSS_NORMALIZE);
LittleFS.mkdir("/js");
writeFile("/js/zepto.min.js", JS_ZEPTO);
writeFile("/js/controls.js", JS_CONTROLS);
writeFile("/js/slider.js", JS_SLIDER);
writeFile("/js/graph.js", JS_GRAPH);
writeFile("/js/tabbedcontent.js", JS_TABBEDCONTENT);
#else
writeFile("/index.htm", HTML_INDEX);
LITTLEFS.mkdir("/css");
writeFile("/css/style.css", CSS_STYLE);
writeFile("/css/normalize.css", CSS_NORMALIZE);
LITTLEFS.mkdir("/js");
writeFile("/js/zepto.min.js", JS_ZEPTO);
writeFile("/js/controls.js", JS_CONTROLS);
writeFile("/js/slider.js", JS_SLIDER);
writeFile("/js/graph.js", JS_GRAPH);
writeFile("/js/tabbedcontent.js", JS_TABBEDCONTENT);
#endif
#else
writeFile("/index.htm", HTML_INDEX);
writeFile("/css/style.css", CSS_STYLE);
writeFile("/css/normalize.css", CSS_NORMALIZE);
writeFile("/js/zepto.min.js", JS_ZEPTO);
writeFile("/js/controls.js", JS_CONTROLS);
writeFile("/js/slider.js", JS_SLIDER);
writeFile("/js/graph.js", JS_GRAPH);
writeFile("/js/tabbedcontent.js", JS_TABBEDCONTENT);
2022-10-13 20:10:20 +00:00
#endif
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
Serial.println(F("Done Initializing filesystem :-)"));
}
#endif
2018-01-14 11:22:26 +00:00
#if defined(ESP32)
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
listDir("/", 1);
}
#endif
2018-01-14 11:22:26 +00:00
#endif
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
LittleFS.end();
#else
LITTLEFS.end();
#endif
#else
LittleFS.end();
2022-10-13 20:10:20 +00:00
#endif
}
2017-10-16 13:00:53 +00:00
// Handle Websockets Communication
2022-09-21 19:45:48 +00:00
void ESPUIClass::onWsEvent(AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len)
{
2022-09-21 19:45:48 +00:00
// Serial.println(String("ESPUIClass::OnWsEvent: type: ") + String(type));
RemoveToBeDeletedControls();
2022-09-21 19:45:48 +00:00
if(WS_EVT_DISCONNECT == type)
{
#if defined(DEBUG_ESPUI)
if (verbosity)
{
Serial.println(F("WS_EVT_DISCONNECT"));
}
#endif
2022-09-21 19:45:48 +00:00
if(MapOfClients.end() != MapOfClients.find(client->id()))
{
2022-09-21 19:45:48 +00:00
// Serial.println("Delete client.");
delete MapOfClients[client->id()];
MapOfClients.erase(client->id());
}
}
2022-09-21 19:45:48 +00:00
else
{
if(MapOfClients.end() == MapOfClients.find(client->id()))
{
2022-09-21 19:45:48 +00:00
// Serial.println("ESPUIClass::OnWsEvent:Create new client.");
MapOfClients[client->id()] = new ESPUIclient(client);
}
2022-09-21 19:45:48 +00:00
MapOfClients[client->id()]->onWsEvent(type, arg, data, len);
2019-03-24 17:10:21 +00:00
}
2022-09-21 19:45:48 +00:00
ClearControlUpdateFlags();
2022-09-21 19:45:48 +00:00
return;
2017-05-18 22:05:32 +00:00
}
2017-10-16 22:10:48 +00:00
uint16_t ESPUIClass::addControl(ControlType type, const char* label)
{
return addControl(type, label, String(""));
}
uint16_t ESPUIClass::addControl(ControlType type, const char* label, const String& value)
{
return addControl(type, label, value, ControlColor::Turquoise);
}
uint16_t ESPUIClass::addControl(ControlType type, const char* label, const String& value, ControlColor color)
{
return addControl(type, label, value, color, Control::noParent);
}
uint16_t ESPUIClass::addControl(ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl)
{
return addControl(type, label, value, color, parentControl, nullptr);
}
uint16_t ESPUIClass::addControl(ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl, void (*callback)(Control*, int))
{
uint16_t id = addControl(type, label, value, color, parentControl, nullptr, nullptr);
// set the original style callback
getControl(id)->callback = callback;
return id;
}
uint16_t ESPUIClass::addControl(ControlType type, const char* label, const String& value, ControlColor color, uint16_t parentControl, void (*callback)(Control*, int, void *), void * UserData)
{
2022-09-21 19:45:48 +00:00
#ifdef ESP32
xSemaphoreTake(ControlsSemaphore, portMAX_DELAY);
#endif // def ESP32
Control* control = new Control(type, label, callback, UserData, value, color, true, parentControl);
2022-09-21 19:45:48 +00:00
if (controls == nullptr)
{
2022-09-21 19:45:48 +00:00
controls = control;
}
else
{
2022-09-21 19:45:48 +00:00
Control* iterator = controls;
while (iterator->next != nullptr)
{
iterator = iterator->next;
}
iterator->next = control;
}
2022-09-21 19:45:48 +00:00
controlCount++;
#ifdef ESP32
xSemaphoreGive(ControlsSemaphore);
#endif // def ESP32
NotifyClients(ClientUpdateType_t::RebuildNeeded);
return control->id;
}
2022-09-21 19:45:48 +00:00
bool ESPUIClass::removeControl(uint16_t id, bool force_rebuild_ui)
{
2022-09-21 19:45:48 +00:00
bool Response = false;
2022-09-21 19:45:48 +00:00
Control* control = getControl(id);
if (control)
2022-06-10 16:44:53 +00:00
{
2022-09-21 19:45:48 +00:00
Response = true;
control->DeleteControl();
controlCount--;
2022-09-21 19:45:48 +00:00
if(force_rebuild_ui)
{
2022-09-21 19:45:48 +00:00
jsonReload();
}
else
{
2022-09-21 19:45:48 +00:00
NotifyClients(ClientUpdateType_t::RebuildNeeded);
}
2022-09-21 19:45:48 +00:00
}
#ifdef DEBUG_ESPUI
else
{
// Serial.println(String("Could not Remove Control ") + String(id));
}
#endif // def DEBUG_ESPUI
return Response;
}
void ESPUIClass::RemoveToBeDeletedControls()
{
#ifdef ESP32
xSemaphoreTake(ControlsSemaphore, portMAX_DELAY);
#endif // def ESP32
Control* PreviousControl = nullptr;
Control* CurrentControl = controls;
while (nullptr != CurrentControl)
{
Control* NextControl = CurrentControl->next;
if (CurrentControl->ToBeDeleted())
{
2022-09-21 19:45:48 +00:00
if (CurrentControl == controls)
{
// this is the root control
controls = NextControl;
}
else
{
PreviousControl->next = NextControl;
}
delete CurrentControl;
CurrentControl = NextControl;
}
else
{
2022-09-21 19:45:48 +00:00
PreviousControl = CurrentControl;
CurrentControl = NextControl;
}
}
2022-09-21 19:45:48 +00:00
#ifdef ESP32
xSemaphoreGive(ControlsSemaphore);
#endif // def ESP32
}
uint16_t ESPUIClass::label(const char* label, ControlColor color, const String& value)
{
return addControl(ControlType::Label, label, value, color);
}
uint16_t ESPUIClass::graph(const char* label, ControlColor color)
{
return addControl(ControlType::Graph, label, "", color);
}
2017-11-13 15:10:56 +00:00
uint16_t ESPUIClass::slider(const char* label, void (*callback)(Control*, int), ControlColor color, int value, int min, int max)
{
uint16_t id = slider(label, nullptr, color, value, min, max, nullptr);
getControl(id)->callback = callback;
return id;
}
uint16_t ESPUIClass::slider(const char* label, void (*callback)(Control*, int, void*), ControlColor color, int value, int min, int max, void* userData)
{
uint16_t sliderId = addControl(ControlType::Slider, label, String(value), color, Control::noParent, callback, userData);
addControl(ControlType::Min, label, String(min), ControlColor::None, sliderId);
addControl(ControlType::Max, label, String(max), ControlColor::None, sliderId);
return sliderId;
}
2017-11-13 16:22:02 +00:00
uint16_t ESPUIClass::button(const char* label, void (*callback)(Control*, int), ControlColor color, const String& value)
{
return addControl(ControlType::Button, label, value, color, Control::noParent, callback);
}
2017-11-13 16:22:02 +00:00
uint16_t ESPUIClass::button(const char* label, void (*callback)(Control*, int, void*), ControlColor color, const String& value, void* UserData)
{
return addControl(ControlType::Button, label, value, color, Control::noParent, callback, UserData);
}
uint16_t ESPUIClass::switcher(const char* label, void (*callback)(Control*, int), ControlColor color, bool startState)
{
return addControl(ControlType::Switcher, label, startState ? "1" : "0", color, Control::noParent, callback);
2017-10-16 13:00:53 +00:00
}
2017-10-19 11:46:47 +00:00
uint16_t ESPUIClass::switcher(const char* label, void (*callback)(Control*, int, void*), ControlColor color, bool startState, void* UserData)
{
return addControl(ControlType::Switcher, label, startState ? "1" : "0", color, Control::noParent, callback, UserData);
}
uint16_t ESPUIClass::pad(const char* label, void (*callback)(Control*, int), ControlColor color)
{
return addControl(ControlType::Pad, label, "", color, Control::noParent, callback);
}
uint16_t ESPUIClass::pad(const char* label, void (*callback)(Control*, int, void*), ControlColor color, void* UserData)
{
return addControl(ControlType::Pad, label, "", color, Control::noParent, callback, UserData);
}
uint16_t ESPUIClass::padWithCenter(const char* label, void (*callback)(Control*, int), ControlColor color)
{
return addControl(ControlType::PadWithCenter, label, "", color, Control::noParent, callback);
}
2017-11-13 15:10:56 +00:00
uint16_t ESPUIClass::padWithCenter(const char* label, void (*callback)(Control*, int, void*), ControlColor color, void* UserData)
{
return addControl(ControlType::PadWithCenter, label, "", color, Control::noParent, callback, UserData);
}
uint16_t ESPUIClass::number(const char* label, void (*callback)(Control*, int), ControlColor color, int number, int min, int max)
{
uint16_t numberId = addControl(ControlType::Number, label, String(number), color, Control::noParent, callback);
addControl(ControlType::Min, label, String(min), ControlColor::None, numberId);
addControl(ControlType::Max, label, String(max), ControlColor::None, numberId);
return numberId;
}
2017-11-13 15:10:56 +00:00
uint16_t ESPUIClass::number(const char* label, void (*callback)(Control*, int, void*), ControlColor color, int number, int min, int max, void* UserData)
{
uint16_t numberId = addControl(ControlType::Number, label, String(number), color, Control::noParent, callback, UserData);
addControl(ControlType::Min, label, String(min), ControlColor::None, numberId);
addControl(ControlType::Max, label, String(max), ControlColor::None, numberId);
return numberId;
}
uint16_t ESPUIClass::gauge(const char* label, ControlColor color, int number, int min, int max)
{
uint16_t numberId = addControl(ControlType::Gauge, label, String(number), color, Control::noParent);
addControl(ControlType::Min, label, String(min), ControlColor::None, numberId);
addControl(ControlType::Max, label, String(max), ControlColor::None, numberId);
return numberId;
2019-03-26 15:22:21 +00:00
}
uint16_t ESPUIClass::separator(const char* label) {
return addControl(ControlType::Separator, label, "", ControlColor::Alizarin, Control::noParent, nullptr);
}
uint16_t ESPUIClass::accelerometer(const char* label, void (*callback)(Control*, int), ControlColor color)
{
return addControl(ControlType::Accel, label, "", color, Control::noParent, callback);
2019-03-26 15:22:21 +00:00
}
uint16_t ESPUIClass::accelerometer(const char* label, void (*callback)(Control*, int, void*), ControlColor color, void* UserData)
{
return addControl(ControlType::Accel, label, "", color, Control::noParent, callback, UserData);
}
uint16_t ESPUIClass::text(const char* label, void (*callback)(Control*, int), ControlColor color, const String& value)
{
return addControl(ControlType::Text, label, value, color, Control::noParent, callback);
2017-10-19 11:46:47 +00:00
}
2017-05-18 22:05:32 +00:00
uint16_t ESPUIClass::text(const char* label, void (*callback)(Control*, int, void*), ControlColor color, const String& value, void* UserData)
{
return addControl(ControlType::Text, label, value, color, Control::noParent, callback, UserData);
}
Control* ESPUIClass::getControl(uint16_t id)
{
2022-09-21 19:45:48 +00:00
#ifdef ESP32
xSemaphoreTake(ControlsSemaphore, portMAX_DELAY);
Control* Response = getControlNoLock(id);
xSemaphoreGive(ControlsSemaphore);
return Response;
#else
return getControlNoLock(id);
#endif // !def ESP32
}
// WARNING: Anytime you walk the chain of controllers, the protection semaphore
// MUST be locked. This function assumes that the semaphore is locked
// at the time it is called. Make sure YOU locked it :)
Control* ESPUIClass::getControlNoLock(uint16_t id)
{
Control* Response = nullptr;
Control* control = controls;
2022-09-21 19:45:48 +00:00
while (nullptr != control)
{
if (control->id == id)
{
2022-09-21 19:45:48 +00:00
if(!control->ToBeDeleted())
{
Response = control;
}
break;
}
control = control->next;
}
2022-09-21 19:45:48 +00:00
return Response;
}
2022-09-21 19:45:48 +00:00
void ESPUIClass::updateControl(Control* control, int)
{
if (!control)
{
return;
}
2022-09-21 19:45:48 +00:00
// tel the control it has been updated
control->HasBeenUpdated();
NotifyClients(ClientUpdateType_t::UpdateNeeded);
2017-10-19 15:30:32 +00:00
}
void ESPUIClass::setPanelStyle(uint16_t id, String style, int clientId)
{
Control* control = getControl(id);
if (control)
{
control->panelStyle = style;
updateControl(control, clientId);
}
}
void ESPUIClass::setElementStyle(uint16_t id, String style, int clientId)
{
Control* control = getControl(id);
if (control)
{
control->elementStyle = style;
updateControl(control, clientId);
}
}
void ESPUIClass::setInputType(uint16_t id, String type, int clientId)
{
Control* control = getControl(id);
if (control)
{
control->inputType = type;
updateControl(control, clientId);
}
}
void ESPUIClass::setPanelWide(uint16_t id, bool wide)
{
Control* control = getControl(id);
if (control)
{
control->wide = wide;
}
}
void ESPUIClass::setEnabled(uint16_t id, bool enabled, int clientId) {
Control* control = getControl(id);
if (control)
{
2022-09-21 19:45:48 +00:00
// Serial.println(String("CreateAllowed: id: ") + String(clientId) + " State: " + String(enabled));
control->enabled = enabled;
updateControl(control, clientId);
}
}
void ESPUIClass::setVertical(uint16_t id, bool vert) {
Control* control = getControl(id);
if (control)
{
control->vertical = vert;
}
}
void ESPUIClass::updateControl(uint16_t id, int clientId)
{
Control* control = getControl(id);
if (!control)
{
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
2022-09-21 19:45:48 +00:00
Serial.printf_P(PSTR("Error: Update Control: There is no control with ID %d\n"), id);
}
#endif
return;
}
2019-03-26 15:22:21 +00:00
updateControl(control, clientId);
}
void ESPUIClass::updateControlValue(Control* control, const String& value, int clientId)
{
if (!control)
{
return;
}
2019-03-24 14:44:27 +00:00
control->value = value;
updateControl(control, clientId);
}
2020-09-14 09:59:35 +00:00
void ESPUIClass::updateControlValue(uint16_t id, const String& value, int clientId)
{
Control* control = getControl(id);
2017-10-19 15:30:32 +00:00
if (!control)
{
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
2022-09-21 19:45:48 +00:00
Serial.printf_P(PSTR("Error: updateControlValue Control: There is no control with ID %d\n"), id);
}
#endif
return;
}
2019-03-26 15:22:21 +00:00
updateControlValue(control, value, clientId);
2017-11-13 15:10:56 +00:00
}
2022-09-21 19:45:48 +00:00
void ESPUIClass::updateControlLabel(uint16_t id, const char * value, int clientId)
{
updateControlLabel(getControl(id), value, clientId);
}
void ESPUIClass::updateControlLabel(Control* control, const char * value, int clientId)
{
if (!control)
{
#if defined(DEBUG_ESPUI)
if (verbosity)
{
Serial.printf_P(PSTR("Error: updateControlLabel Control: There is no control with the requested ID \n"));
}
#endif
return;
}
control->label = value;
updateControl(control, clientId);
}
void ESPUIClass::updateVisibility(uint16_t id, bool visibility, int clientId) {
Control* control = getControl(id);
if(control)
{
control->visible = visibility;
2022-09-21 19:45:48 +00:00
updateControl(control, clientId);
}
}
void ESPUIClass::print(uint16_t id, const String& value)
{
updateControlValue(id, value);
}
void ESPUIClass::updateLabel(uint16_t id, const String& value)
{
updateControlValue(id, value);
}
2022-01-16 14:47:41 +00:00
void ESPUIClass::updateButton(uint16_t id, const String& value) {
updateControlValue(id, value);
}
void ESPUIClass::updateSlider(uint16_t id, int nValue, int clientId)
{
updateControlValue(id, String(nValue), clientId);
}
2017-11-13 15:10:56 +00:00
void ESPUIClass::updateSwitcher(uint16_t id, bool nValue, int clientId)
{
updateControlValue(id, String(nValue ? "1" : "0"), clientId);
}
2017-11-29 10:32:07 +00:00
void ESPUIClass::updateNumber(uint16_t id, int number, int clientId)
{
updateControlValue(id, String(number), clientId);
}
void ESPUIClass::updateText(uint16_t id, const String& text, int clientId)
{
updateControlValue(id, text, clientId);
}
2017-11-13 15:10:56 +00:00
void ESPUIClass::updateSelect(uint16_t id, const String& text, int clientId)
{
updateControlValue(id, text, clientId);
}
void ESPUIClass::updateGauge(uint16_t id, int number, int clientId)
{
updateControlValue(id, String(number), clientId);
}
2019-03-26 15:22:21 +00:00
2022-09-21 19:45:48 +00:00
void ESPUIClass::updateTime(uint16_t id, int clientId)
{
updateControl(id, clientId);
}
2022-11-03 02:31:04 +00:00
void ESPUIClass::clearGraph(uint16_t id, int clientId) {
do // once
{
Control* control = getControl(id);
if (!control)
{
break;
}
DynamicJsonDocument document(jsonUpdateDocumentSize);
JsonObject root = document.to<JsonObject>();
2022-11-05 13:06:13 +00:00
root[F("type")] = (int)ControlType::Graph + UpdateOffset;
2022-11-03 02:31:04 +00:00
root[F("value")] = 0;
root[F("id")] = control->id;
SendJsonDocToWebSocket(document, clientId);
} while(false);
}
void ESPUIClass::addGraphPoint(uint16_t id, int nValue, int clientId)
{
do // once
{
Control* control = getControl(id);
if (!control)
{
break;
}
DynamicJsonDocument document(jsonUpdateDocumentSize);
JsonObject root = document.to<JsonObject>();
root[F("type")] = (int)ControlType::GraphPoint;
root[F("value")] = nValue;
root[F("id")] = control->id;
SendJsonDocToWebSocket(document, clientId);
} while(false);
2022-09-21 19:45:48 +00:00
}
2022-09-21 19:45:48 +00:00
bool ESPUIClass::SendJsonDocToWebSocket(ArduinoJson::DynamicJsonDocument& document, uint16_t clientId)
{
bool Response = false;
2022-09-21 19:45:48 +00:00
if(0 > clientId)
{
2022-09-21 19:45:48 +00:00
if(MapOfClients.end() != MapOfClients.find(clientId))
{
2022-09-21 19:45:48 +00:00
Response = MapOfClients[clientId]->SendJsonDocToWebSocket(document);
}
}
2022-09-21 19:45:48 +00:00
else
{
for(auto CurrentClient : MapOfClients)
2022-09-21 19:45:48 +00:00
{
Response |= CurrentClient.second->SendJsonDocToWebSocket(document);
2022-09-21 19:45:48 +00:00
}
}
2022-01-01 22:04:32 +00:00
2022-09-21 19:45:48 +00:00
return Response;
}
2022-01-01 22:04:32 +00:00
2022-09-21 19:45:48 +00:00
void ESPUIClass::jsonDom(uint16_t, AsyncWebSocketClient*, bool)
{
NotifyClients(ClientUpdateType_t::RebuildNeeded);
2022-01-01 22:04:32 +00:00
}
2022-09-21 19:45:48 +00:00
// Tell all of the clients that they need to ask for an upload of the control data.
void ESPUIClass::NotifyClients(ClientUpdateType_t newState)
{
2022-09-21 19:45:48 +00:00
for (auto& CurrentClient : MapOfClients)
{
2022-09-21 19:45:48 +00:00
CurrentClient.second->NotifyClient(newState);
}
2022-09-21 19:45:48 +00:00
}
2022-09-21 19:45:48 +00:00
void ESPUIClass::ClearControlUpdateFlags()
{
bool CanClearUpdateFlags = true;
2022-01-01 22:04:32 +00:00
2022-09-21 19:45:48 +00:00
for(auto& CurrentClient : MapOfClients)
{
2022-09-21 19:45:48 +00:00
if(!CurrentClient.second->IsSyncronized())
{
2022-09-21 19:45:48 +00:00
CanClearUpdateFlags = false;
break;
}
2022-09-21 19:45:48 +00:00
}
2022-09-21 19:45:48 +00:00
if(CanClearUpdateFlags)
{
Control* control = controls;
while(nullptr != control)
{
2022-09-21 19:45:48 +00:00
control->HasBeenSynchronized();
control = control->next;
}
}
}
void ESPUIClass::jsonReload()
{
2022-09-21 19:45:48 +00:00
for(auto& CurrentClient : MapOfClients)
{
2022-09-21 19:45:48 +00:00
// Serial.println("Requesting Reload");
CurrentClient.second->NotifyClient(ClientUpdateType_t::ReloadNeeded);
}
}
void ESPUIClass::beginSPIFFS(const char* _title, const char* username, const char* password, uint16_t port)
{
// Backwards compatibility wrapper
beginLITTLEFS(_title, username, password, port);
}
void ESPUIClass::beginLITTLEFS(const char* _title, const char* username, const char* password, uint16_t port)
{
ui_title = _title;
2022-09-21 19:45:48 +00:00
basicAuthUsername = username;
basicAuthPassword = password;
if (username == nullptr && password == nullptr)
{
basicAuth = false;
}
else
{
basicAuth = true;
}
server = new AsyncWebServer(port);
ws = new AsyncWebSocket("/ws");
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
bool fsBegin = LittleFS.begin();
#else
bool fsBegin = LITTLEFS.begin();
#endif
#else
bool fsBegin = LittleFS.begin();
2022-10-13 20:10:20 +00:00
#endif
if (!fsBegin)
{
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
Serial.println(F("LITTLEFS Mount Failed, PLEASE CHECK THE README ON HOW TO "
"PREPARE YOUR ESP!!!!!!!"));
}
#endif
return;
}
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
listDir("/", 1);
}
#endif
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
bool indexExists = LittleFS.exists("/index.htm");
#else
bool indexExists = LITTLEFS.exists("/index.htm");
#endif
#else
bool indexExists = LittleFS.exists("/index.htm");
2022-10-13 20:10:20 +00:00
#endif
if (!indexExists)
{
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
Serial.println(F("Please read the README!!!!!!!, Make sure to "
2022-09-21 19:45:48 +00:00
"prepareFileSystem() once in an empty sketch"));
}
#endif
return;
}
2022-09-21 19:45:48 +00:00
ws->onEvent([](AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len)
{
ESPUI.onWsEvent(server, client, type, arg, data, len);
});
server->addHandler(ws);
if (basicAuth)
{
if (WS_AUTHENTICATION)
{
2022-09-21 19:45:48 +00:00
ws->setAuthentication(basicAuthUsername, basicAuthPassword);
}
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
server->serveStatic("/", LittleFS, "/").setDefaultFile("index.htm").setAuthentication(username, password);
#else
server->serveStatic("/", LITTLEFS, "/").setDefaultFile("index.htm").setAuthentication(username, password);
#endif
#else
server->serveStatic("/", LittleFS, "/").setDefaultFile("index.htm").setAuthentication(username, password);
2022-10-13 20:10:20 +00:00
#endif
}
else
{
2022-10-13 20:10:20 +00:00
#if defined(ESP32)
#if (ESP_IDF_VERSION_MAJOR == 4 && ESP_IDF_VERSION_MINOR >= 4) || ESP_IDF_VERSION_MAJOR > 4
server->serveStatic("/", LittleFS, "/").setDefaultFile("index.htm");
#else
server->serveStatic("/", LITTLEFS, "/").setDefaultFile("index.htm");
#endif
#else
server->serveStatic("/", LittleFS, "/").setDefaultFile("index.htm");
2022-10-13 20:10:20 +00:00
#endif
}
// Heap for general Servertest
server->on("/heap", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
request->send(200, "text/plain", String(ESP.getFreeHeap()) + " In LITTLEFS mode");
});
server->onNotFound([this](AsyncWebServerRequest* request) {
if(captivePortal)
{
request->redirect("/");
}
else
{
2022-09-21 19:45:48 +00:00
request->send(404);
}
});
server->begin();
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
Serial.println(F("UI Initialized"));
}
#endif
}
void ESPUIClass::begin(const char* _title, const char* username, const char* password, uint16_t port)
{
basicAuthUsername = username;
basicAuthPassword = password;
if (username != nullptr && password != nullptr)
{
basicAuth = true;
}
else
{
basicAuth = false;
}
ui_title = _title;
server = new AsyncWebServer(port);
ws = new AsyncWebSocket("/ws");
2022-09-21 19:45:48 +00:00
ws->onEvent([](AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len)
{
ESPUI.onWsEvent(server, client, type, arg, data, len);
});
server->addHandler(ws);
if (basicAuth && WS_AUTHENTICATION)
ws->setAuthentication(username, password);
server->on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
AsyncWebServerResponse* response = request->beginResponse_P(200, "text/html", HTML_INDEX);
request->send(response);
});
// Javascript files
server->on("/js/zepto.min.js", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
AsyncWebServerResponse* response
= request->beginResponse_P(200, "application/javascript", JS_ZEPTO_GZIP, sizeof(JS_ZEPTO_GZIP));
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
server->on("/js/controls.js", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
AsyncWebServerResponse* response
= request->beginResponse_P(200, "application/javascript", JS_CONTROLS_GZIP, sizeof(JS_CONTROLS_GZIP));
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
2019-03-24 14:44:27 +00:00
server->on("/js/slider.js", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
AsyncWebServerResponse* response
= request->beginResponse_P(200, "application/javascript", JS_SLIDER_GZIP, sizeof(JS_SLIDER_GZIP));
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
server->on("/js/graph.js", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
AsyncWebServerResponse* response
= request->beginResponse_P(200, "application/javascript", JS_GRAPH_GZIP, sizeof(JS_GRAPH_GZIP));
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
2019-03-24 14:44:27 +00:00
server->on("/js/tabbedcontent.js", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
2019-03-24 17:10:21 +00:00
AsyncWebServerResponse* response = request->beginResponse_P(
200, "application/javascript", JS_TABBEDCONTENT_GZIP, sizeof(JS_TABBEDCONTENT_GZIP));
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
// Stylesheets
server->on("/css/style.css", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
AsyncWebServerResponse* response
= request->beginResponse_P(200, "text/css", CSS_STYLE_GZIP, sizeof(CSS_STYLE_GZIP));
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
server->on("/css/normalize.css", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
AsyncWebServerResponse* response
= request->beginResponse_P(200, "text/css", CSS_NORMALIZE_GZIP, sizeof(CSS_NORMALIZE_GZIP));
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
// Heap for general Servertest
server->on("/heap", HTTP_GET, [](AsyncWebServerRequest* request) {
if (ESPUI.basicAuth && !request->authenticate(ESPUI.basicAuthUsername, ESPUI.basicAuthPassword))
{
return request->requestAuthentication();
}
request->send(200, "text/plain", String(ESP.getFreeHeap()) + " In Memorymode");
});
2017-10-16 13:00:53 +00:00
server->onNotFound([this](AsyncWebServerRequest* request) {
if(captivePortal)
{
request->redirect("/");
}
else
{
2022-09-21 19:45:48 +00:00
request->send(404);
}
});
2017-10-16 13:00:53 +00:00
server->begin();
2017-05-18 22:05:32 +00:00
#if defined(DEBUG_ESPUI)
2022-09-21 19:45:48 +00:00
if (verbosity)
{
Serial.println(F("UI Initialized"));
}
#endif
}
void ESPUIClass::setVerbosity(Verbosity v)
{
2022-09-21 19:45:48 +00:00
verbosity = v;
}
ESPUIClass ESPUI;