Updated the Readme.md files in this fork (used Mark Text editor)

Cookie auth with Xtea encrypting, see SmartSwitch.ino example
Tested on ESP8266 and ESP32 with better built-in LED handling 
Minor updates and improvements of js / html packed files.
This commit is contained in:
lorol
2020-05-27 11:51:06 -04:00
parent 44b27dc61f
commit 10a23dfcc7
16 changed files with 381 additions and 112 deletions

114
README.md
View File

@@ -1,4 +1,20 @@
# In this fork
SPIFFSEditor improvements
Added [extras](https://github.com/lorol/ESPAsyncWebServer/tree/master/extras) folder with (Win) tools for re-packing, allow editing, updating and compressing html to binary arrays, embedded to source
Added a [SmartSwitch](https://github.com/lorol/ESPAsyncWebServer/tree/master/examples/SmartSwitch) example to test code features
Applied the memory optimizations from [sascha432](https://github.com/sascha432/ESPAsyncWebServer) fork
Cookie Authentication including on Websocket part, based on [ayushsharma82](https://github.com/me-no-dev/ESPAsyncWebServer/pull/684) PR, new functions added:
- For Websocket: ```void handleHandshake(AwsHandshakeHandler handler) ```
- For EventSource: ```void authorizeConnect(ArAuthorizeConnectHandler cb)```
# ESPAsyncWebServer
[![Build Status](https://travis-ci.org/me-no-dev/ESPAsyncWebServer.svg?branch=master)](https://travis-ci.org/me-no-dev/ESPAsyncWebServer) ![](https://github.com/me-no-dev/ESPAsyncWebServer/workflows/ESP%20Async%20Web%20Server%20CI/badge.svg) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/395dd42cfc674e6ca2e326af3af80ffc)](https://www.codacy.com/manual/me-no-dev/ESPAsyncWebServer?utm_source=github.com&utm_medium=referral&utm_content=me-no-dev/ESPAsyncWebServer&utm_campaign=Badge_Grade)
For help and support [![Join the chat at https://gitter.im/me-no-dev/ESPAsyncWebServer](https://badges.gitter.im/me-no-dev/ESPAsyncWebServer.svg)](https://gitter.im/me-no-dev/ESPAsyncWebServer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
@@ -12,6 +28,7 @@ For ESP32 it requires [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) to work
To use this library you might need to have the latest git versions of [ESP32](https://github.com/espressif/arduino-esp32) Arduino Core
## Table of contents
- [ESPAsyncWebServer](#espasyncwebserver)
- [Table of contents](#table-of-contents)
- [Installation](#installation)
@@ -102,7 +119,7 @@ To use this library you might need to have the latest git versions of [ESP32](ht
3. Update dev/platform to staging version:
- [Instruction for Espressif 8266](http://docs.platformio.org/en/latest/platforms/espressif8266.html#using-arduino-framework-with-staging-version)
- [Instruction for Espressif 32](http://docs.platformio.org/en/latest/platforms/espressif32.html#using-arduino-framework-with-staging-version)
4. Add "ESP Async WebServer" to project using [Project Configuration File `platformio.ini`](http://docs.platformio.org/page/projectconf.html) and [lib_deps](http://docs.platformio.org/page/projectconf/section_env_library.html#lib-deps) option:
4. Add "ESP Async WebServer" to project using [Project Configuration File `platformio.ini`](http://docs.platformio.org/page/projectconf.html) and [lib_deps](http://docs.platformio.org/page/projectconf/section_env_library.html#lib-deps) option:
```ini
[env:myboard]
@@ -116,9 +133,11 @@ lib_deps = ESP Async WebServer
# or using GIT Url (the latest development version)
lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
```
5. Happy coding with PlatformIO!
5. Happy coding with PlatformIO!
## Why should you care
- Using asynchronous network means that you can handle more than one connection at the same time
- You are called once the request is ready and parsed
- When you send the response, you are immediately ready to handle other connections
@@ -134,6 +153,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
- Simple template processing engine to handle templates
## Important things to remember
- This is fully asynchronous server and as such does not run on the loop thread.
- You can not use yield or delay or any function that uses them inside the callbacks
- The server is smart enough to know when to close the connection and free resources
@@ -142,6 +162,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
## Principles of operation
### The Async Web server
- Listens for connections
- Wraps the new clients into ```Request```
- Keeps track of clients and cleans memory
@@ -149,6 +170,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
- Manages ```Handlers``` and attaches them to Requests
### Request Life Cycle
- TCP connection is received by the server
- The connection is wrapped inside ```Request``` object
- When the request head is received (type, url, get params, http version and host),
@@ -161,6 +183,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
- When the ```Response``` is sent, the client is closed and freed from the memory
### Rewrites and how do they work
- The ```Rewrites``` are used to rewrite the request url and/or inject get parameters for a specific request url path.
- All ```Rewrites``` are evaluated on the request in the order they have been added to the server.
- The ```Rewrite``` will change the request url only if the request url (excluding get parameters) is fully match
@@ -172,6 +195,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
- The ```Rewrite``` can specify a target url with optional get parameters, e.g. ```/to-url?with=params```
### Handlers and how do they work
- The ```Handlers``` are used for executing specific actions to particular requests
- One ```Handler``` instance can be attached to any request and lives together with the server
- Setting a ```Filter``` to the ```Handler``` enables to control when to apply the handler, decision can be based on
@@ -189,6 +213,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
- The first ```Handler``` that can handle the request is selected, not further ```Filter``` and ```canHandle``` are called.
### Responses and how do they work
- The ```Response``` objects are used to send the response data back to the client
- The ```Response``` object lives with the ```Request``` and is freed on end or disconnect
- Different techniques are used depending on the response type to send the data in packets
@@ -198,6 +223,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
- Many different options exist for the user to make responding a background task
### Template processing
- ESPAsyncWebserver contains simple template processing engine.
- Template processing can be added to most response types.
- Currently it supports only replacing template placeholders with actual values. No conditional processing, cycles, etc.
@@ -207,6 +233,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
- Since it's impossible to know the actual response size after template processing step in advance (and, therefore, to include it in response headers), the response becomes [chunked](#chunked-response).
## Libraries and projects that use AsyncWebServer
- [WebSocketToSerial](https://github.com/hallard/WebSocketToSerial) - Debug serial devices through the web browser
- [Sattrack](https://github.com/Hopperpop/Sattrack) - Track the ISS with ESP8266
- [ESP Radio](https://github.com/Edzelf/Esp-radio) - Icecast radio based on ESP8266 and VS1053
@@ -218,6 +245,7 @@ lib_deps = https://github.com/me-no-dev/ESPAsyncWebServer.git
## Request Variables
### Common Variables
```cpp
request->version(); // uint8_t: 0 = HTTP/1.0, 1 = HTTP/1.1
request->method(); // enum: HTTP_GET, HTTP_POST, HTTP_DELETE, HTTP_PUT, HTTP_PATCH, HTTP_HEAD, HTTP_OPTIONS
@@ -229,6 +257,7 @@ request->multipart(); // bool: True if the request has content type "mult
```
### Headers
```cpp
//List all collected headers
int headers = request->headers();
@@ -258,6 +287,7 @@ if(request->hasHeader("MyHeader")){
```
### GET, POST and FILE parameters
```cpp
//List all parameters
int params = request->params();
@@ -296,6 +326,7 @@ if(request->hasArg("download"))
```
### FILE Upload handling
```cpp
void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
if(!index){
@@ -311,6 +342,7 @@ void handleUpload(AsyncWebServerRequest *request, String filename, size_t index,
```
### Body data handling
```cpp
void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
if(!index){
@@ -324,10 +356,13 @@ void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_
}
}
```
If needed, the `_tempObject` field on the request can be used to store a pointer to temporary data (e.g. from the body) associated with the request. If assigned, the pointer will automatically be freed along with the request.
### JSON body handling with ArduinoJson
Endpoints which consume JSON can use a special handler to get ready to use JSON data in the request callback:
```cpp
#include "AsyncJson.h"
#include "ArduinoJson.h"
@@ -340,7 +375,9 @@ server.addHandler(handler);
```
## Responses
### Redirect to another URL
```cpp
//to local url
request->redirect("/login");
@@ -350,11 +387,13 @@ request->redirect("http://esp8266.com");
```
### Basic response with HTTP Code
```cpp
request->send(404); //Sends 404 File Not Found
```
### Basic response with HTTP Code and extra headers
```cpp
AsyncWebServerResponse *response = request->beginResponse(404); //Sends 404 File Not Found
response->addHeader("Server","ESP Async Web Server");
@@ -362,11 +401,13 @@ request->send(response);
```
### Basic response with string content
```cpp
request->send(200, "text/plain", "Hello World!");
```
### Basic response with string content and extra headers
```cpp
AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "Hello World!");
response->addHeader("Server","ESP Async Web Server");
@@ -374,12 +415,14 @@ request->send(response);
```
### Send large webpage from PROGMEM
```cpp
const char index_html[] PROGMEM = "..."; // large char array, tested with 14k
request->send_P(200, "text/html", index_html);
```
### Send large webpage from PROGMEM and extra headers
```cpp
const char index_html[] PROGMEM = "..."; // large char array, tested with 14k
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html);
@@ -388,6 +431,7 @@ request->send(response);
```
### Send large webpage from PROGMEM containing templates
```cpp
String processor(const String& var)
{
@@ -403,6 +447,7 @@ request->send_P(200, "text/html", index_html, processor);
```
### Send large webpage from PROGMEM containing templates and extra headers
```cpp
String processor(const String& var)
{
@@ -420,8 +465,8 @@ request->send(response);
```
### Send binary content from PROGMEM
```cpp
```cpp
//File: favicon.ico.gz, Size: 726
#define favicon_ico_gz_len 726
const uint8_t favicon_ico_gz[] PROGMEM = {
@@ -479,12 +524,14 @@ request->send(response);
```
### Respond with content coming from a Stream
```cpp
//read 12 bytes from Serial and send them as Content Type text/plain
request->send(Serial, "text/plain", 12);
```
### Respond with content coming from a Stream and extra headers
```cpp
//read 12 bytes from Serial and send them as Content Type text/plain
AsyncWebServerResponse *response = request->beginResponse(Serial, "text/plain", 12);
@@ -493,6 +540,7 @@ request->send(response);
```
### Respond with content coming from a Stream containing templates
```cpp
String processor(const String& var)
{
@@ -508,6 +556,7 @@ request->send(Serial, "text/plain", 12, processor);
```
### Respond with content coming from a Stream containing templates and extra headers
```cpp
String processor(const String& var)
{
@@ -525,6 +574,7 @@ request->send(response);
```
### Respond with content coming from a File
```cpp
//Send index.htm with default content type
request->send(SPIFFS, "/index.htm");
@@ -537,6 +587,7 @@ request->send(SPIFFS, "/index.htm", String(), true);
```
### Respond with content coming from a File and extra headers
```cpp
//Send index.htm with default content type
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/index.htm");
@@ -552,14 +603,17 @@ request->send(response);
```
### Respond with content coming from a File containing templates
Internally uses [Chunked Response](#chunked-response).
Index.htm contents:
```
%HELLO_FROM_TEMPLATE%
```
Somewhere in source files:
```cpp
String processor(const String& var)
{
@@ -575,6 +629,7 @@ request->send(SPIFFS, "/index.htm", String(), false, processor);
```
### Respond with content using a callback
```cpp
//send 128 bytes as plain text
request->send("text/plain", 128, [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
@@ -588,6 +643,7 @@ request->send("text/plain", 128, [](uint8_t *buffer, size_t maxLen, size_t index
```
### Respond with content using a callback and extra headers
```cpp
//send 128 bytes as plain text
AsyncWebServerResponse *response = request->beginResponse("text/plain", 128, [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
@@ -603,6 +659,7 @@ request->send(response);
```
### Respond with content using a callback containing templates
```cpp
String processor(const String& var)
{
@@ -625,6 +682,7 @@ request->send("text/plain", 128, [](uint8_t *buffer, size_t maxLen, size_t index
```
### Respond with content using a callback containing templates and extra headers
```cpp
String processor(const String& var)
{
@@ -649,7 +707,9 @@ request->send(response);
```
### Chunked Response
Used when content length is unknown. Works best if the client supports HTTP/1.1
```cpp
AsyncWebServerResponse *response = request->beginChunkedResponse("text/plain", [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
//Write up to "maxLen" bytes into "buffer" and return the amount written.
@@ -663,7 +723,9 @@ request->send(response);
```
### Chunked Response containing templates
Used when content length is unknown. Works best if the client supports HTTP/1.1
```cpp
String processor(const String& var)
{
@@ -686,6 +748,7 @@ request->send(response);
```
### Print to response
```cpp
AsyncResponseStream *response = request->beginResponseStream("text/html");
response->addHeader("Server","ESP Async Web Server");
@@ -736,7 +799,9 @@ request->send(response);
```
### ArduinoJson Basic Response
This way of sending Json is great for when the result is below 4KB
```cpp
#include "AsyncJson.h"
#include "ArduinoJson.h"
@@ -752,11 +817,13 @@ request->send(response);
```
### ArduinoJson Advanced Response
This response can handle really large Json objects (tested to 40KB)
There isn't any noticeable speed decrease for small results with the method above
Since ArduinoJson does not allow reading parts of the string, the whole Json has to
be passed every time a chunks needs to be sent, which shows speed decrease proportional
to the resulting json packets
```cpp
#include "AsyncJson.h"
#include "ArduinoJson.h"
@@ -772,6 +839,7 @@ request->send(response);
```
## Serving static files
In addition to serving files from SPIFFS as described above, the server provide a dedicated handler that optimize the
performance of serving files from SPIFFS - ```AsyncStaticWebHandler```. Use ```server.serveStatic()``` function to
initialize and add a new instance of ```AsyncStaticWebHandler``` to the server.
@@ -780,13 +848,16 @@ handler that can handle the request.
Notice that you can chain setter functions to setup the handler, or keep a pointer to change it at a later time.
### Serving specific file by name
```cpp
// Serve the file "/www/page.htm" when request url is "/page.htm"
server.serveStatic("/page.htm", SPIFFS, "/www/page.htm");
```
### Serving files in directory
To serve files in a directory, the path to the files should specify a directory in SPIFFS and ends with "/".
```cpp
// Serve files in directory "/www/" when request url starts with "/"
// Request to the root or none existing files will try to server the defualt
@@ -807,8 +878,10 @@ server
```
### Specifying Cache-Control header
It is possible to specify Cache-Control header value to reduce the number of calls to the server once the client loaded
the files. For more information on Cache-Control values see [Cache-Control](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9)
```cpp
// Cache responses for 10 minutes (600 seconds)
server.serveStatic("/", SPIFFS, "/www/").setCacheControl("max-age=600");
@@ -823,8 +896,10 @@ handler->setCacheControl("max-age=30");
```
### Specifying Date-Modified header
It is possible to specify Date-Modified header to enable the server to return Not-Modified (304) response for requests
with "If-Modified-Since" header with the same value, instead of responding with the actual file content.
```cpp
// Update the date modified string every time files are updated
server.serveStatic("/", SPIFFS, "/www/").setLastModified("Mon, 20 Jun 2016 14:00:00 GMT");
@@ -843,8 +918,10 @@ handler->setLastModified(date_modified);
```
### Specifying Template Processor callback
It is possible to specify template processor for static files. For information on template processor see
[Respond with content coming from a File containing templates](#respond-with-content-coming-from-a-file-containing-templates).
```cpp
String processor(const String& var)
{
@@ -859,6 +936,7 @@ server.serveStatic("/", SPIFFS, "/www/").setTemplateProcessor(processor);
```
## Param Rewrite With Matching
It is possible to rewrite the request url with parameter matchg. Here is an example with one parameter:
Rewrite for example "/radio/{frequence}" -> "/radio?f={frequence}"
@@ -911,20 +989,24 @@ Usage:
```
## Using filters
Filters can be set to `Rewrite` or `Handler` in order to control when to apply the rewrite and consider the handler.
A filter is a callback function that evaluates the request and return a boolean `true` to include the item
or `false` to exclude it.
Two filter callback are provided for convince:
* `ON_STA_FILTER` - return true when requests are made to the STA (station mode) interface.
* `ON_AP_FILTER` - return true when requests are made to the AP (access point) interface.
### Serve different site files in AP mode
```cpp
server.serveStatic("/", SPIFFS, "/www/").setFilter(ON_STA_FILTER);
server.serveStatic("/", SPIFFS, "/ap/").setFilter(ON_AP_FILTER);
```
### Rewrite to different index on AP
```cpp
// Serve the file "/www/index-ap.htm" in AP, and the file "/www/index.htm" on STA
server.rewrite("/", "index.htm");
@@ -933,6 +1015,7 @@ server.serveStatic("/", SPIFFS, "/www/");
```
### Serving different hosts
```cpp
// Filter callback using request host
bool filterOnHost1(AsyncWebServerRequest *request) { return request->host() == "host1"; }
@@ -943,6 +1026,7 @@ server.serveStatic("/", SPIFFS, "/www/");
```
### Determine interface inside callbacks
```cpp
String RedirectUrl = "http://";
if (ON_STA_FILTER(request)) {
@@ -955,11 +1039,13 @@ server.serveStatic("/", SPIFFS, "/www/");
```
## Bad Responses
Some responses are implemented, but you should not use them, because they do not conform to HTTP.
The following example will lead to unclean close of the connection and more time wasted
than providing the length of the content
### Respond with content using a callback without content length to HTTP/1.0 clients
```cpp
//This is used as fallback for chunked responses to HTTP/1.0 Clients
request->send("text/plain", 0, [](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
@@ -971,12 +1057,13 @@ request->send("text/plain", 0, [](uint8_t *buffer, size_t maxLen, size_t index)
```
## Async WebSocket Plugin
The server includes a web socket plugin which lets you define different WebSocket locations to connect to
without starting another listening service or using different port
### Async WebSocket Event
```cpp
```cpp
void onEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
if(type == WS_EVT_CONNECT){
//client connected
@@ -1046,10 +1133,8 @@ void onEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventTyp
```
### Methods for sending data to a socket client
```cpp
//Server methods
AsyncWebSocket ws("/ws");
//printf to a client
@@ -1104,6 +1189,7 @@ client->binary(flash_binary, 4);
```
### Direct access to web socket message buffer
When sending a web socket message using the above methods a buffer is created. Under certain circumstances you might want to manipulate or populate this buffer directly from your application, for example to prevent unnecessary duplications of the data. This example below shows how to create a buffer and print data to it from an ArduinoJson object then send it.
```cpp
@@ -1130,6 +1216,7 @@ void sendDataWs(AsyncWebSocketClient * client)
```
### Limiting the number of web socket clients
Browsers sometimes do not correctly close the websocket connection, even when the close() function is called in javascript. This will eventually exhaust the web server's resources and will cause the server to crash. Periodically calling the cleanClients() function from the main loop() function limits the number of clients by closing the oldest client when the maximum number of clients has been exceeded. This can called be every cycle, however, if you wish to use less power, then calling as infrequently as once per second is sufficient.
```cpp
@@ -1138,12 +1225,13 @@ void loop(){
}
```
## Async Event Source Plugin
The server includes EventSource (Server-Sent Events) plugin which can be used to send short text events to the browser.
Difference between EventSource and WebSockets is that EventSource is single direction, text-only protocol.
### Setup Event Source on the server
```cpp
AsyncWebServer server(80);
AsyncEventSource events("/events");
@@ -1173,6 +1261,7 @@ void loop(){
```
### Setup Event Source in the browser
```javascript
if (!!window.EventSource) {
var source = new EventSource('/events');
@@ -1198,6 +1287,7 @@ if (!!window.EventSource) {
```
## Scanning for available WiFi Networks
```cpp
//First request will return 0 results unless you start scan from somewhere else (loop/setup)
//Do not request more often than 3-5 seconds
@@ -1233,6 +1323,7 @@ server.on("/scan", HTTP_GET, [](AsyncWebServerRequest *request){
Server goes through handlers in same order as they were added. You can't simple add handler with same path to override them.
To remove handler:
```arduino
// save callback for particular URL path
auto handler = server.on("/some/path", [](AsyncWebServerRequest *request){
@@ -1256,6 +1347,7 @@ server.reset();
```
## Setting up the server
```cpp
#include "ESPAsyncTCP.h"
#include "ESPAsyncWebServer.h"
@@ -1456,7 +1548,6 @@ Example of OTA code
ws.closeAll();
});
```
### Adding Default Headers
@@ -1496,11 +1587,11 @@ For example we want a `sensorId` parameter in a route rule to match only a integ
String sensorId = request->pathArg(0);
});
```
*NOTE*: All regex patterns starts with `^` and ends with `$`
To enable the `Path variable` support, you have to define the buildflag `-DASYNCWEBSERVER_REGEX`.
For Arduino IDE create/update `platform.local.txt`:
`Windows`: C:\Users\(username)\AppData\Local\Arduino15\packages\\`{espxxxx}`\hardware\\`espxxxx`\\`{version}`\platform.local.txt
@@ -1508,14 +1599,17 @@ For Arduino IDE create/update `platform.local.txt`:
`Linux`: ~/.arduino15/packages/`{espxxxx}`/hardware/`{espxxxx}`/`{version}`/platform.local.txt
Add/Update the following line:
```
compiler.cpp.extra_flags=-DASYNCWEBSERVER_REGEX
```
For platformio modify `platformio.ini`:
```ini
[env:myboard]
build_flags =
-DASYNCWEBSERVER_REGEX
```
*NOTE*: By enabling `ASYNCWEBSERVER_REGEX`, `<regex>` will be included. This will add an 100k to your binary.

View File

@@ -1,12 +1,12 @@
This application:
D2 = 4; // DHT DATA I/O
D3 = 0; // BUTTON - most modules have it populated on PCB
D4 = 2; // LED (RELAY) - most modules have it populated on PCB
D3 = 0; // BUTTON - most modules have it populated on PCB
D4 = 2; // LED (RELAY) - most modules have it populated, on ESP32 is with reversed logic levels
Pinout ESP12 (8266)
D GPIO In Out Notes
D GPIO In Out Notes
D0 16 no interrupt no PWM or I2C support HIGH at boot used to wake up from deep sleep
D1 5 OK OK often used as SCL (I2C)
@@ -23,16 +23,16 @@ A0 ADC0 Analog Input
Pinout ESP32
IO In Out Notes
IO In Out Notes
0 PU OK pulled-up input, outputs PWM signal at boot
1 TX OK debug output at boot
1 TX OK debug output at boot
2 OK OK connected to on-board LED
3 OK RX pin HIGH at boot
3 OK RX HIGH at boot
4 OK OK
5 OK OK outputs PWM signal at boot
6-11 x x connected to the integrated SPI flash
6-11 x x connected to the integrated SPI flash
12 OK OK boot fail if pulled high
13 OK OK

View File

@@ -1,19 +1,35 @@
![](1.PNG) ![](2.PNG)
##
![](3.PNG) ![](4.PNG)
<img title="" src="1.PNG" alt="" width="137"> <img title="" src="2.PNG" alt="" width="138"> <img title="" src="3.PNG" alt="" width="150"> <img title="" src="4.PNG" alt="" width="150">
## SmartSwitch
* Remote Temperature Control application with schedule (example car block heater or battery charger)
* Based on ESP_AsyncFSBrowser example with ACE editor
* Wide browser compatibility, no extra server-side needed
* HTTP server and WebSocket, single port
* Standalone, no JS dependencies for the browser from Internet (I hope), ace editor included
* Added ESPAsyncWiFiManager
* Real Time (NTP) w/ Time Zones
* Memorized settings to EEPROM
* Multiple clients can be connected at same time, they see each other' requests
* Base Authentication of the editor, static content, WS
* Or Cookie Authentication including WS part, need lib src changes taken from https://github.com/me-no-dev/ESPAsyncWebServer/pull/684
* Default credentials <b>smart:switch</b>
* Use latest ESP8266 ESP32 cores from GitHub
* Remote Temperature Control application with schedule
(example: car block heater or car battery charger for winter)
* Based on [ESP_AsyncFSBrowser](https://github.com/lorol/ESPAsyncWebServer/tree/master/examples/ESP_AsyncFSBrowser) example that uses embedded ACE editor
* Wide browser compatibility, no extra server-side needed
* HTTP server and WebSocket on same port
* Standalone, no JS dependencies for the browser from Internet
* [Ace Editor](https://github.com/ajaxorg/ace) embedded to source but also - editable, upgradeable see [extras folder](https://github.com/lorol/ESPAsyncWebServer/tree/master/extras)
* Added [ESPAsyncWiFiManager](https://github.com/alanswx/ESPAsyncWiFiManager) and fallback AP mode after timeout
* Real Time (NTP) w/ Time Zones. Sync from browser time if in AP mode
* Memorized settings to EEPROM
* Multiple clients can be connected at same time, they see each other' requests
* Authentication variants including [Cookie-based](https://github.com/me-no-dev/ESPAsyncWebServer/pull/684) idea
* Used [this Xtea implementation](https://github.com/franksmicro/Arduino/tree/master/libraries/Xtea) for getting a fancier Cookie token
* Default credentials **smart : switch** or only **switch** as password
* OTA included
* Use the latest ESP8266 ESP32 cores from GitHub

View File

@@ -17,20 +17,23 @@ Use latest ESP core lib (from Github)
//#define DEL_WFM // delete Wifi credentials stored
//(use once then comment and flash again), also HTTP /erase-wifi can do the same live
// AUTH COOKIE uses only the password, Base uses both
// AUTH COOKIE uses only the password and unsigned long MY_SECRET_NUMBER
#define http_username "smart"
#define http_password "switch"
#define MY_SECRET_NUMBER 0xA217B02F
//See https://github.com/me-no-dev/ESPAsyncWebServer/pull/684
//SSWI or other 4 chars
#define USE_AUTH_COOKIE
// 1 year age, path helps Safari to unset
#define MY_COOKIE_FULL "LLKQ=3; Max-Age=31536000; Path=/;"
#define MY_COOKIE_DEL "LLKQ=; Max-Age=-1; Path=/;"
#define MY_COOKIE "LLKQ=3"
#define MY_COOKIE_DEL "SSWI=;Max-Age=-1;Path=/;"
#define MY_COOKIE_PREF "SSWI="
#define MY_COOKIE_SUFF ";Max-Age=31536000;Path=/;"
#ifndef USE_AUTH_COOKIE
#define USE_AUTH_STAT //Base Auth for stat, /commands and SPIFFSEditor
//#define USE_AUTH_WS //Base Auth also for WS, not very supported
//#define USE_AUTH_WS //Base Auth also for WS, not very supported
#endif
#include <ArduinoOTA.h>
@@ -54,6 +57,11 @@ Use latest ESP core lib (from Github)
#include <Ticker.h>
#include <DHT.h>
#ifdef USE_AUTH_COOKIE
#include <stdint.h>
#include "Xtea.h"
#endif
#define RTC_UTC_TEST 1577836800 // Some Date
#define MYTZ PSTR("EST5EDT,M3.2.0,M11.1.0")
@@ -70,12 +78,13 @@ Use latest ESP core lib (from Github)
#define DHTTYPE DHT22 // DHT 11 // DHT 22, AM2302, AM2321 // DHT 21, AM2301
#define DHTPIN 4 //D2
#define DHT_T_CORR -0.5 //Temperature offset compensation of the sensor (can be -)
#define DHT_H_CORR 1.5 //Humidity offset compensation of the sensor
#define DHT_T_CORR -0.3 //Temperature offset compensation of the sensor (can be -)
#define DHT_H_CORR -2.2 //Humidity offset compensation of the sensor
// SKETCH BEGIN MAIN DECLARATIONS
DHT dht(DHTPIN, DHTTYPE);
// SKETCH BEGIN MAIN DECLARATIONS
Ticker tim;
AsyncWebServer server(80); //single port - easy for forwarding
AsyncWebSocket ws("/ws");
@@ -96,7 +105,8 @@ AsyncWebSocket ws("/ws");
const char* ssid = "MYROUTERSSD";
const char* password = "MYROUTERPASSWD";
#endif
const char* hostName = "smartsw32";
const char* hostName = "smartsw";
// RTC
static timeval tv;
@@ -222,7 +232,7 @@ void updateDHT(){
float h1 = dht.readHumidity();
float t1 = dht.readTemperature(); //Celsius or dht.readTemperature(true) for Fahrenheit
if (isnan(h1) || isnan(t1)) {
Serial.print(F("Failed to read from DHT sensor!"));
Serial.println(F("Failed to read from DHT sensor!"));
} else {
h = h1 + DHT_H_CORR;
t = t1 + DHT_T_CORR;
@@ -241,8 +251,13 @@ void checkPhysicalButton()
if (btnState != LOW) { // btnState is used to avoid sequential toggles
ledState = !ledState;
digitalWrite(ledPin, ledState);
if (ledState == LED_OFF) ws.textAll("led,ledoff");
else ws.textAll("led,ledon");
if (ledState == LED_OFF) {
ws.textAll("led,ledoff");
Serial.println(F("LED-OFF"));
} else {
ws.textAll("led,ledon");
Serial.println(F("LED-ON"));
}
}
btnState = LOW;
} else {
@@ -267,12 +282,41 @@ void mytimer() {
}
#ifdef USE_AUTH_COOKIE
unsigned long key[4] = {0x01F20304,0x05060708,0x090a0b0c,0x0d0e0f00};
Xtea x(key);
void encip(String &mtk, unsigned long token){
unsigned long res[2] = {random(0xFFFFFFFF),token};
x.encrypt(res);
char buf1[18];
sprintf(buf1, "%08X_%08X",res[0],res[1]); //8 bytes for encryping the IP cookie
mtk = (String)buf1;
}
unsigned long decip(const char *pch){
unsigned long res[2] = {0,0};
res[0] = strtoul(pch, NULL, 16);
res[1] = strtoul(&pch[9], NULL, 16);
x.decrypt(res);
return res[1];
}
bool myHandshake(AsyncWebServerRequest *request){ // false will 401
bool rslt = false;
if (request->hasHeader("Cookie")){
String cookie = request->header("Cookie");
if (cookie.indexOf(MY_COOKIE) != -1) return true;
else return false;
} else return false;
Serial.println(cookie);
uint8_t pos = cookie.indexOf(MY_COOKIE_PREF);
if (pos != -1){
unsigned long ix = decip(cookie.substring(pos+5, pos+22).c_str());
Serial.printf("Ask:%08X Got:%08X\n", MY_SECRET_NUMBER, ix);
if (MY_SECRET_NUMBER == ix)
rslt=true;
} else rslt=false;
} else rslt=false;
Serial.printf(rslt ? "C-YES\n" : "C-NO\n");
return rslt;
}
#endif
@@ -323,7 +367,6 @@ void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventT
}
digitalWrite(ledPin, ledState); // apply change
} else if(data[0] == 'T') { // timeset
if (len > 11) {
data[3] = data[6] = data[9] = data[12] = 0; // cut strings
@@ -444,7 +487,8 @@ void setup(){
}
#endif
Serial.print(F("*CONNECTED*\n"));
Serial.print(F("*CONNECTED* OWN IP:"));
Serial.println(WiFi.localIP());
//DHT
dht.begin();
@@ -492,25 +536,41 @@ void setup(){
server.addHandler(new SPIFFSEditor(SPIFFS, http_username,http_password));
#elif defined(USE_AUTH_COOKIE)
server.addHandler(new SPIFFSEditor(SPIFFS)).setFilter(myHandshake);
#else
server.addHandler(new SPIFFSEditor(SPIFFS));
#endif
#elif defined(ESP8266)
#ifdef USE_AUTH_STAT
server.addHandler(new SPIFFSEditor(http_username,http_password));
#elif defined(USE_AUTH_COOKIE)
server.addHandler(new SPIFFSEditor()).setFilter(myHandshake);
#else
server.addHandler(new SPIFFSEditor());
#endif
#endif
#ifdef USE_AUTH_COOKIE
server.on("/lg2n", HTTP_POST, [](AsyncWebServerRequest *request){ // cookie test
if((request->hasParam("pa2w",true) && (String(request->getParam("pa2w",true)->value().c_str()) == String(http_password)))||(request->hasParam("lg0f",true))){
AsyncWebServerResponse *response = request->beginResponse(301);
server.on("/lg2n", HTTP_POST, [](AsyncWebServerRequest *request){
String ckx;
encip(ckx, MY_SECRET_NUMBER);
AsyncWebServerResponse *response;
if(request->hasParam("lg0f",true)){
response = request->beginResponse(200, "text/html;charset=utf-8", "<h1>Logged Out! <a href='/'>Back</a></h1>");
response->addHeader("Cache-Control", "no-cache");
response->addHeader("Set-Cookie", MY_COOKIE_DEL);
} else if(request->hasParam("pa2w",true) && (String(request->getParam("pa2w",true)->value().c_str()) == String(http_password))){
response = request->beginResponse(301);
response->addHeader("Location", "/");
response->addHeader("Cache-Control", "no-cache");
if(request->hasParam("lg0f",true)) response->addHeader("Set-Cookie", MY_COOKIE_DEL);
else response->addHeader("Set-Cookie", MY_COOKIE_FULL);
request->send(response);
} else request->send(200, "text/plain","Wrong Password!");
response->addHeader("Set-Cookie", MY_COOKIE_PREF + ckx + MY_COOKIE_SUFF);
} else response = request->beginResponse(200, "text/html;charset=utf-8", "<h1>Wrong password! <a href='/'>Back</a></h1>");
request->send(response);
});
#endif
@@ -520,7 +580,14 @@ void setup(){
#ifdef USE_AUTH_STAT
if(!request->authenticate(http_username, http_password)) return request->requestAuthentication();
#endif
#ifdef ESP32
request->send(200, "text/plain", String(ESP.getMinFreeHeap()) + ':' + String(ESP.getFreeHeap()) + ':'+ String(ESP.getHeapSize()));
#else
request->send(200, "text/plain", String(ESP.getFreeHeap()));
#endif
#ifdef USE_AUTH COOKIE
}).setFilter(myHandshake);
#else
@@ -584,7 +651,7 @@ void setup(){
#ifdef USE_AUTH_COOKIE
server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm").setFilter(myHandshake);
server.serveStatic("/", SPIFFS, "/login/").setDefaultFile("index.htm").setFilter(!myHandshake);
server.serveStatic("/", SPIFFS, "/login/").setDefaultFile("index.htm");
#else
#ifdef USE_AUTH_STAT
server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm").setAuthentication(http_username,http_password);

View File

@@ -0,0 +1,48 @@
/*
Xtea.cpp - Xtea encryption/decryption
Written by Frank Kienast in November, 2010
https://github.com/franksmicro/Arduino/tree/master/libraries/Xtea
*/
#include <stdint.h>
#include "Xtea.h"
#define NUM_ROUNDS 32
Xtea::Xtea(unsigned long key[4])
{
_key[0] = key[0];
_key[1] = key[1];
_key[2] = key[2];
_key[3] = key[3];
}
void Xtea::encrypt(unsigned long v[2])
{
unsigned int i;
unsigned long v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9;
for (i=0; i < NUM_ROUNDS; i++)
{
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + _key[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + _key[(sum>>11) & 3]);
}
v[0]=v0; v[1]=v1;
}
void Xtea::decrypt(unsigned long v[2])
{
unsigned int i;
uint32_t v0=v[0], v1=v[1], delta=0x9E3779B9, sum=delta*NUM_ROUNDS;
for (i=0; i < NUM_ROUNDS; i++)
{
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + _key[(sum>>11) & 3]);
sum -= delta;
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + _key[sum & 3]);
}
v[0]=v0; v[1]=v1;
}

View File

@@ -0,0 +1,20 @@
/*
Xtea.h - Crypto library
Written by Frank Kienast in November, 2010
https://github.com/franksmicro/Arduino/tree/master/libraries/Xtea
*/
#ifndef Xtea_h
#define Xtea_h
class Xtea
{
public:
Xtea(unsigned long key[4]);
void encrypt(unsigned long data[2]);
void decrypt(unsigned long data[2]);
private:
unsigned long _key[4];
};
#endif

View File

@@ -1,5 +1,4 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
@@ -115,13 +114,13 @@
}
.clk {
font-size: 54px;
font-size: 52px;
color: #444;
cursor: pointer
}
.clk2 {
font-size: 32px;
font-size: 24px;
color: #444
}
@@ -329,7 +328,7 @@
<div id="g2" class="gauge"></div>
<div id="C" class="clk" onclick="getBtime();"></div>
<div id="C2" class="clk2"></div>
<p><a href="/login">Logoff</a></p>
<input type="button" id="O" value="Logout" onclick="buttonOClick();" />
</div>
<script src="app.min.js"></script>
@@ -378,10 +377,10 @@
}, {
color: "#32a852",
lo: 0,
hi: 25
hi: 35
}, {
color: "#ff4d4d",
lo: 25,
lo: 35,
hi: 50
}],
formatNumber: true
@@ -531,7 +530,7 @@
message: 'Timer REQ'
});
}
};
}
function button2Click(e) {
if (connection.readyState === WebSocket.OPEN) {
@@ -540,32 +539,40 @@
message: 'Temp. REQ'
});
}
};
}
function buttonEClick() {
var murl = '/edit';
if (document.location.host.length < 5) murl = 'http://' + MYCORS + '/edit'; //CORS
successNotification({
message: 'Editor'
});
successNotification({message: 'Editor'});
window.open(murl, '_blank');
};
}
function buttonOClick() {
// If base auth
var murl = document.location.href.replace("http://", "http://" + new Date().getTime() + "@");
// If cookie auth
murl += 'login';
if (document.location.host.length < 5) murl = 'http://' + MYCORS + '/login'; //CORS
warningNotification({ message: 'Logout'});
window.open(murl, '_self');
}
function checkboxClick(e) {
if (connection.readyState === WebSocket.OPEN) {
if (e.checked) connection.send('L1');
else connection.send('L0');
}
};
}
function ent1Click() {
document.getElementById("input-temperature").className = "blinking";
};
}
function ent2Click() {
document.getElementById("input-popup-stop").className = "blinking";
document.getElementById("input-popup-start").className = "blinking";
};
}
function handleClick(e) {
if (e.value == 'Z0' ) auto = true;

View File

@@ -8,13 +8,29 @@
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
</head>
<body style="background-color:#bbb;font-family:arial;"><center>
<body style="background-color:#bbb;font-family:arial;">
<center>
<br><br>
<h4>Password</h4>
<h4>Login - Logout</h4>
<form action="/lg2n" method="post">
<input type="password" name="pa2w"><br><br>
<input type="checkbox" name="lg0f"><label for="lg0f">Logoff</label><br><br>
<input type="password" id="pwd" name="pa2w" placeholder="Enter the password"><br><br>
<input type="checkbox" id="lof" name="lg0f" onclick="hidep()"><label for="lg0f">Logout</label><br><br>
<input type="submit" value="Submit">
</form></center>
</form>
<br><a href='/'>Back</a>
</center>
<script>
function hidep() {
var checkBox = document.getElementById("lof");
var text = document.getElementById("pwd");
if (checkBox.checked == true){
text.style.display = "none";
} else {
text.style.display = "inline";
}
}
</script>
</body>
</html>

28
extras/README.md Normal file
View File

@@ -0,0 +1,28 @@
### Extras
Additions to facilitate code modifications (for MS Win, similar can be done on Linux)
**ehg.c (ehg.exe):** Tool to generate C-code array from file' bytes
Based on [bin2array](https://github.com/TheLivingOne/bin2array/) PROGMEM keyword can optionally be added.
**rehg.c (rehg.exe):** Tool to reverse C-code array generated by **ehg.exe** back to a file
Based on [c2bin](https://github.com/birkett/cbintools/tree/master/c2bin)
First 4 lines of source are ignored, then parses the 0xHH - formated bytes
until a } is found on separate new line.
### Tools
[TCC : Tiny C Compiler](https://bellard.org/tcc/) for **ehg** and **rehg** compiling on MS Win
[7-Zip](https://www.7-zip.org) Install 7z and use the included gzip as command line tool
[Node.js](https://nodejs.org) Install Node with default settings, then run:
``` npm install html-minifier-terser -g, npm install -g github-files-fetcher ```
### Batch files provided
**do.bat:** Generates **edit.htm.gz.h** file
**undo.bat:** Reverts **edit.htm** from C array header to file (still minified!)
**update_ace.bat:** Updates **acefull.js.gz** file from latest GitHub Ace sources

View File

@@ -1,27 +0,0 @@
ehg.c (ehg.exe): Tool to generate C-code array from file' bytes
Based on https://github.com/TheLivingOne/bin2array/ and compiled with TynyCC
PROGMEM word can optionally be added.
rehg.c (rehg.exe): Tool to reverse C-code array generated by ehg.exe back to a file
Based on https://github.com/birkett/cbintools/tree/master/c2bin and compiled with TynyCC
First 4x lines of source are ignored, then parses the 0x00, formated bytes
until a } is found on separate new line.
Tools used (on Win 10):
https://www.7-zip.org (install 7z and use gzip - command line)
https://nodejs.org
(install node and npm install html-minifier-terser -g, npm install -g github-files-fetcher)
https://www.npmjs.com/package/html-minifier-terser
https://www.npmjs.com/package/github-files-fetcher
Optional:
https://bellard.org/tcc/ (TynyCC, ehg.c and rehg.c to executable)
Provided batch files (MS Win)
do.bat: Generates edit.htm.gz.h
undo.bat: Reverts edit.htm from C array header to file (still minified!)
update_ace.bat: Updates acefull.js.gz from latest Github sources

View File

@@ -2,7 +2,7 @@
//File: edit.htm.gz, Size: 4408
#define edit_htm_gz_len 4408
const uint8_t edit_htm_gz[] PROGMEM = {
0x1F,0x8B,0x08,0x08,0x42,0x13,0xB7,0x5E,0x02,0x00,0x65,0x64,0x69,0x74,0x2E,0x68,0x74,0x6D,0x00,0xB5,
0x1F,0x8B,0x08,0x08,0x1B,0x89,0xCE,0x5E,0x02,0x00,0x65,0x64,0x69,0x74,0x2E,0x68,0x74,0x6D,0x00,0xB5,
0x1A,0x0B,0x5B,0xDB,0x36,0xF0,0xAF,0x18,0x6F,0x63,0xF6,0xE2,0x38,0x0E,0xA5,0xAC,0x73,0x30,0x2C,0x50,
0x56,0xFA,0x02,0x4A,0x42,0x3B,0xCA,0xD8,0x3E,0xC5,0x56,0x62,0x15,0x5B,0xF6,0x2C,0x99,0x40,0xB3,0xFC,
0xF7,0x9D,0x24,0x3F,0x43,0xE8,0x1E,0xDF,0xD6,0x6E,0x8D,0xA4,0xD3,0x9D,0xEE,0x4E,0xF7,0x54,0xB2,0xBB,