From aa2b923ef44b5b3bafd878f62d506293cbbbe826 Mon Sep 17 00:00:00 2001 From: vdeconinck Date: Sun, 10 May 2020 10:37:21 +0200 Subject: [PATCH 1/6] New Graph Example --- .../ESP8266WebServer/examples/Graph/Graph.ino | 314 +++++++++++ .../examples/Graph/data/index.htm | 527 ++++++++++++++++++ .../ESP8266WebServer/examples/Graph/readme.md | 48 ++ 3 files changed, 889 insertions(+) create mode 100644 libraries/ESP8266WebServer/examples/Graph/Graph.ino create mode 100644 libraries/ESP8266WebServer/examples/Graph/data/index.htm create mode 100644 libraries/ESP8266WebServer/examples/Graph/readme.md diff --git a/libraries/ESP8266WebServer/examples/Graph/Graph.ino b/libraries/ESP8266WebServer/examples/Graph/Graph.ino new file mode 100644 index 0000000000..850981d762 --- /dev/null +++ b/libraries/ESP8266WebServer/examples/Graph/Graph.ino @@ -0,0 +1,314 @@ +/* + Graph - A web-based Graph display of ESP8266 data + + This file is part of the ESP8266WebServer library for Arduino environment. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + See readme.md for more information. +*/ + +//////////////////////////////// + +// Select the FileSystem by uncommenting one of the lines below + +//#define USE_SPIFFS +#define USE_LITTLEFS +//#define USE_SDFS + +//////////////////////////////// + +#include +#include +#include +#include +#include + +#if defined USE_SPIFFS +#include +FS* fileSystem = &SPIFFS; +SPIFFSConfig fileSystemConfig = SPIFFSConfig(); +#elif defined USE_LITTLEFS +#include +FS* fileSystem = &LittleFS; +LittleFSConfig fileSystemConfig = LittleFSConfig(); +#elif defined USE_SDFS +#include +FS* fileSystem = &SDFS; +SDFSConfig fileSystemConfig = SDFSConfig(); +// fileSystemConfig.setCSPin(chipSelectPin); +#else +#error Please select a filesystem first by uncommenting one of the "#define USE_xxx" lines at the beginning of the sketch. +#endif + + +#define DBG_OUTPUT_PORT Serial + +#ifndef STASSID +#define STASSID "your-ssid" +#define STAPSK "your-password" +#endif + +// Indicate which digital I/Os should be displayed on the chart. +// From GPIO16 to GPIO0, a '1' means the corresponding GPIO will be shown +// Note: SD GPIOs are hidden by default: +#define DEFAULT_GPIO_MASK 0b11111000000111111 + +unsigned int gpioMask = DEFAULT_GPIO_MASK; + +const char* ssid = STASSID; +const char* password = STAPSK; +const char* host = "graph"; + +ESP8266WebServer server(80); + +static const char TEXT_PLAIN[] PROGMEM = "text/plain"; +static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; +static const char FILE_NOT_FOUND[] PROGMEM = "FileNotFound"; + +//////////////////////////////// +// Utils to return HTTP codes + +void replyOK() { + server.send(200, FPSTR(TEXT_PLAIN), ""); +} + +void replyOKWithMsg(String msg) { + server.send(200, FPSTR(TEXT_PLAIN), msg); +} + +void replyNotFound(String msg) { + server.send(404, FPSTR(TEXT_PLAIN), msg); +} + +void replyBadRequest(String msg) { + DBG_OUTPUT_PORT.println(msg); + server.send(400, FPSTR(TEXT_PLAIN), msg + "\r\n"); +} + +void replyServerError(String msg) { + DBG_OUTPUT_PORT.println(msg); + server.send(500, FPSTR(TEXT_PLAIN), msg + "\r\n"); +} + +//////////////////////////////// +// Request handlers + +/* + Read the given file from the filesystem and stream it back to the client +*/ +bool handleFileRead(String path) { + DBG_OUTPUT_PORT.println(String("handleFileRead: ") + path); + + if (path.endsWith("/")) { + path += "index.htm"; + } + + String contentType = mime::getContentType(path); + + if (!fileSystem->exists(path)) { + // File not found, try gzip version + path = path + ".gz"; + } + if (fileSystem->exists(path)) { + File file = fileSystem->open(path, "r"); + if (server.streamFile(file, contentType) != file.size()) { + DBG_OUTPUT_PORT.println("Sent less data than expected!"); + } + file.close(); + return true; + } + + return false; +} + + +/* + The "Not Found" handler catches all URI not explicitely declared in code + First try to find and return the requested file from the filesystem, + and if it fails, return a 404 page with debug information +*/ +void handleNotFound() { + String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks + + if (handleFileRead(uri)) { + return; + } + + // Dump debug data + String message; + message.reserve(100); + message = F("Error: File not found\n\nURI: "); + message += uri; + message += F("\nMethod: "); + message += (server.method() == HTTP_GET) ? "GET" : "POST"; + message += F("\nArguments: "); + message += server.args(); + message += '\n'; + for (uint8_t i = 0; i < server.args(); i++) { + message += F(" NAME:"); + message += server.argName(i); + message += F("\n VALUE:"); + message += server.arg(i); + message += '\n'; + } + message += "path="; + message += server.arg("path"); + message += '\n'; + DBG_OUTPUT_PORT.print(message); + + return replyNotFound(message); +} + +void setup(void) { + //////////////////////////////// + // SERIAL INIT + DBG_OUTPUT_PORT.begin(115200); + DBG_OUTPUT_PORT.setDebugOutput(true); + DBG_OUTPUT_PORT.print('\n'); + + //////////////////////////////// + // FILESYSTEM INIT + + fileSystemConfig.setAutoFormat(false); + fileSystem->setConfig(fileSystemConfig); + boolean fsOK = fileSystem->begin(); + DBG_OUTPUT_PORT.println(fsOK ? F("Filesystem initialized.") : F("Filesystem init failed!")); + + //////////////////////////////// + // PIN INIT + pinMode(4 , INPUT); + pinMode(12, OUTPUT); + pinMode(13, OUTPUT); + pinMode(15, OUTPUT); + + //////////////////////////////// + // WI-FI INIT + DBG_OUTPUT_PORT.printf("Connecting to %s\n", ssid); + WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + // Wait for connection + while (WiFi.status() != WL_CONNECTED) { + delay(500); + DBG_OUTPUT_PORT.print("."); + } + DBG_OUTPUT_PORT.println(""); + DBG_OUTPUT_PORT.print(F("Connected! IP address: ")); + DBG_OUTPUT_PORT.println(WiFi.localIP()); + + //////////////////////////////// + // MDNS INIT + if (MDNS.begin(host)) { + MDNS.addService("http", "tcp", 80); + DBG_OUTPUT_PORT.print(F("Open http://")); + DBG_OUTPUT_PORT.print(host); + DBG_OUTPUT_PORT.println(F(".local to open the graph page")); + } + + //////////////////////////////// + // WEB SERVER INIT + + //get heap status, analog input value and all GPIO statuses in one json call + server.on("/espData", HTTP_GET, []() { + String json; + json.reserve(88); + json = "{\"time\":"; + json += millis(); + json += ", \"heap\":"; + json += ESP.getFreeHeap(); + json += ", \"analog\":"; + json += analogRead(A0); + json += ", \"gpioMask\":"; + json += gpioMask; + json += ", \"gpioData\":"; + json += (uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16)); + json += "}"; + server.send(200, "text/json", json); + }); + + // Default handler for all URIs not defined above + // Use it to read files from filesystem + server.onNotFound(handleNotFound); + + + // Start server + server.begin(); + DBG_OUTPUT_PORT.println("HTTP server started"); + + DBG_OUTPUT_PORT.println("Please pull GPIO4 low (e.g. press button) to switch output mode:"); + DBG_OUTPUT_PORT.println(" 0 (OFF): outputs are off and hidden from chart"); + DBG_OUTPUT_PORT.println(" 1 (AUTO): outputs are rotated automatically every second"); + DBG_OUTPUT_PORT.println(" 2 (MANUAL): outputs can be toggled from the web page"); + +} + +int rgbMode = 1; // 0=off - 1=auto - 2=manual +int rgbValue = 0; +long lastChangeTime = 0; +boolean modeChangeRequested = false; + +void loop(void) { + server.handleClient(); + MDNS.update(); + + if (digitalRead(4) == 0) { + // button pressed + modeChangeRequested = true; + } + + // see if one second has passed since last change + long now = millis(); + if (now - lastChangeTime > 1000) { + // see if a mode change was requested + if (modeChangeRequested) { + // increment mode (reset after 2) + rgbMode++; + if (rgbMode > 2) rgbMode = 0; + + modeChangeRequested = false; + } + + // act according to mode + switch (rgbMode) { + case 0: // off + gpioMask = 0b10100000000111111; // GPIOs 12-13-15 are hidden + // output 0 + digitalWrite(12, 0); + digitalWrite(13, 0); + digitalWrite(15, 0); + break; + + case 1: // auto + gpioMask = DEFAULT_GPIO_MASK; + // increment value (reset after 7) + rgbValue++; + if (rgbValue > 7) rgbValue = 0; + + // output values + digitalWrite(12, rgbValue & 0b001); + digitalWrite(13, rgbValue & 0b010); + digitalWrite(15, rgbValue & 0b100); + break; + + case 2: // manual + gpioMask = DEFAULT_GPIO_MASK; + // don't change values + break; + } + + // update last change time + lastChangeTime = now; + } +} diff --git a/libraries/ESP8266WebServer/examples/Graph/data/index.htm b/libraries/ESP8266WebServer/examples/Graph/data/index.htm new file mode 100644 index 0000000000..38bcba5e41 --- /dev/null +++ b/libraries/ESP8266WebServer/examples/Graph/data/index.htm @@ -0,0 +1,527 @@ + + + + + + + + + + +
+ Max number of samples:  + + . Sampling period:  + +  ms  + + + +
+
+
+
+
+
+ + \ No newline at end of file diff --git a/libraries/ESP8266WebServer/examples/Graph/readme.md b/libraries/ESP8266WebServer/examples/Graph/readme.md new file mode 100644 index 0000000000..8bfe09255d --- /dev/null +++ b/libraries/ESP8266WebServer/examples/Graph/readme.md @@ -0,0 +1,48 @@ +# Graph readme + +## What is this sketch about ? +This example consists of a web page that displays misc ESP8266 information, namely values of GPIOs, ADC measurement and free heap +using http requests and a html/javascript frontend. +A similar functionality used to be hidden in previous versions of the FSBrowser example. + +## How to use it ? +1. Uncomment one of the `#define USE_xxx` directives in the sketch to select the ESP filesystem to store the index.htm file on +2. Provide the credentials of your WiFi network (search for `STASSID`) +3. Compile and upload the sketch to your ESP8266 device +4. For normal use, copy the contents of the `data` folder to the filesystem. To do so: +- for SDFS, copy that contents (not the data folder itself, just its contents) to the root of a FAT/FAT32-formated SD card connected to the SPI port of the ESP8266 +- for SPIFFS or LittleFS, please follow the instructions at https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html#uploading-files-to-file-system +5. Once the data and sketch have been uploaded, access the page by pointing your browser to http://graph.local + +## What does it demonstrate ? +1. Use of the ESP8266WebServer library to return files from the ESP filesystem +2. Use of the ESP8266WebServer library to return a dynamic JSON document +3. Querying the state of ESP I/Os as well as free heap +4. Ajax calls to a JSON API of the ESP from a webpage +5. Rendering of "real-time" data in a webpage + +## Usage +- the page should start showing samples right away +- the sampling period (interval between requests to the ESP) can be selected. If the system cannot keep up with the rhythm, the interval will get longer (and the period input field will turn red to indicate it). Note that the X-axis is the time since ESP bootup, in milliseconds. +- the maximum number of samples can be selected. Warning: this uses up browser memory and power, so a large number might increase the sampling period. +- sampling can be paused or restarted, and graph can be cleared during pause +- the list of GPIOs to be displayed can be customized from Arduino code by changing the gpioMask value included in the json document +- in that list, some GPIOs can be temporarily hidden by clicking on their labels on top +- analog and heap graphs can be zoomed in using the mouse wheel. A click resets the zoom level + +## Options +This sample is "fully compatible" with the FSBrowser sample. In other words, if you copy the `espData` handler over from this sketch to the FSBrowser example sketch, and upload the index.htm page to its filesystem, you will be able to use both the FSBrowser and the graph page at the same time. + +## Dependency +The html page requires the [Chart.js](https://www.chartjs.org/) (v2.9.3 at the time of writing) library, which is loaded from a CDN, as well as its [zoom plugin](https://github.com/chartjs/chartjs-plugin-zoom/blob/master/README.md) (v0.7.7) and [hammer.js](http://hammerjs.github.io/) (v2.0.8) for gesture capture. +Consequently, internet access from your web browser is required for this app to work as-is. +If your browser has no web access (e.g. if you are connected to the ESP8266 as an access-point), you can download those three files locally and upload them along with the index.htm page, and uncomment the block at the top of the index.htm page + +## Notes +- The code in the loop is just to demonstrate that the app is working by toggling a few I/Os. +However, values have been particularly chosen to be meaningful for the [Witty Cloud](https://gregwareblog.wordpress.com/2016/01/10/esp-witty/) board, rotating colors of the RGB led. +When placed close to a reflecting area, the light sensor (LDR) of the board also shows an analog image of the RGB led power. +The button rotates mode between "RGB rotate", "RGB stop", "RGB off" (and corresponding GPIOs disappearing from the graph), . +- If you use SDFS, if your card's CS pin is not connected to the default pin (4), uncomment the `fileSystemConfig.setCSPin(chipSelectPin);` line and specify the GPIO the CS pin is connected to +- `index.htm` is the default index returned if your URL does not end with a filename (works on subfolders as well) + From 6f0538c529fd51ee5f1dff7d28cb18b560b2aff2 Mon Sep 17 00:00:00 2001 From: vdeconinck Date: Tue, 12 May 2020 02:42:55 +0200 Subject: [PATCH 2/6] (restyled) --- .../ESP8266WebServer/examples/Graph/Graph.ino | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/libraries/ESP8266WebServer/examples/Graph/Graph.ino b/libraries/ESP8266WebServer/examples/Graph/Graph.ino index 850981d762..41e4180979 100644 --- a/libraries/ESP8266WebServer/examples/Graph/Graph.ino +++ b/libraries/ESP8266WebServer/examples/Graph/Graph.ino @@ -62,7 +62,7 @@ SDFSConfig fileSystemConfig = SDFSConfig(); #endif // Indicate which digital I/Os should be displayed on the chart. -// From GPIO16 to GPIO0, a '1' means the corresponding GPIO will be shown +// From GPIO16 to GPIO0, a '1' means the corresponding GPIO will be shown // Note: SD GPIOs are hidden by default: #define DEFAULT_GPIO_MASK 0b11111000000111111 @@ -189,11 +189,11 @@ void setup(void) { //////////////////////////////// // PIN INIT - pinMode(4 , INPUT); + pinMode(4, INPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); pinMode(15, OUTPUT); - + //////////////////////////////// // WI-FI INIT DBG_OUTPUT_PORT.printf("Connecting to %s\n", ssid); @@ -246,7 +246,7 @@ void setup(void) { // Start server server.begin(); DBG_OUTPUT_PORT.println("HTTP server started"); - + DBG_OUTPUT_PORT.println("Please pull GPIO4 low (e.g. press button) to switch output mode:"); DBG_OUTPUT_PORT.println(" 0 (OFF): outputs are off and hidden from chart"); DBG_OUTPUT_PORT.println(" 1 (AUTO): outputs are rotated automatically every second"); @@ -274,15 +274,17 @@ void loop(void) { // see if a mode change was requested if (modeChangeRequested) { // increment mode (reset after 2) - rgbMode++; - if (rgbMode > 2) rgbMode = 0; - + rgbMode++; + if (rgbMode > 2) { + rgbMode = 0; + } + modeChangeRequested = false; } // act according to mode switch (rgbMode) { - case 0: // off + case 0: // off gpioMask = 0b10100000000111111; // GPIOs 12-13-15 are hidden // output 0 digitalWrite(12, 0); @@ -293,22 +295,24 @@ void loop(void) { case 1: // auto gpioMask = DEFAULT_GPIO_MASK; // increment value (reset after 7) - rgbValue++; - if (rgbValue > 7) rgbValue = 0; - + rgbValue++; + if (rgbValue > 7) { + rgbValue = 0; + } + // output values digitalWrite(12, rgbValue & 0b001); digitalWrite(13, rgbValue & 0b010); digitalWrite(15, rgbValue & 0b100); break; - + case 2: // manual gpioMask = DEFAULT_GPIO_MASK; // don't change values break; } - + // update last change time - lastChangeTime = now; + lastChangeTime = now; } } From f4d35c313396cc97af641e00cad6554e196c04f2 Mon Sep 17 00:00:00 2001 From: vdeconinck Date: Tue, 19 May 2020 22:49:07 +0200 Subject: [PATCH 3/6] Now using isFlashInterfacePin() no define default GPIO mask. --- .../ESP8266WebServer/examples/Graph/Graph.ino | 36 +++++++++++++------ 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/libraries/ESP8266WebServer/examples/Graph/Graph.ino b/libraries/ESP8266WebServer/examples/Graph/Graph.ino index 41e4180979..89eb57e9b0 100644 --- a/libraries/ESP8266WebServer/examples/Graph/Graph.ino +++ b/libraries/ESP8266WebServer/examples/Graph/Graph.ino @@ -63,10 +63,8 @@ SDFSConfig fileSystemConfig = SDFSConfig(); // Indicate which digital I/Os should be displayed on the chart. // From GPIO16 to GPIO0, a '1' means the corresponding GPIO will be shown -// Note: SD GPIOs are hidden by default: -#define DEFAULT_GPIO_MASK 0b11111000000111111 - -unsigned int gpioMask = DEFAULT_GPIO_MASK; +// e.g. 0b11111000000111111 +unsigned int gpioMask; const char* ssid = STASSID; const char* password = STAPSK; @@ -254,6 +252,17 @@ void setup(void) { } +// Return default GPIO mask, that is all I/Os except SD card ones +unsigned int defaultMask() { + unsigned int mask = 0b11111111111111111; + for (auto pin=0; pin <= 16; pin++) { + if (isFlashInterfacePin(pin)) { + mask &= ~(1<